forked from emaijala/MLInvoice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlfuncs.php
More file actions
executable file
·2303 lines (2179 loc) · 73.1 KB
/
sqlfuncs.php
File metadata and controls
executable file
·2303 lines (2179 loc) · 73.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Database functions
*
* PHP version 5
*
* Copyright (C) 2004-2008 Samu Reinikainen
* Copyright (C) 2010-2019 Ere Maijala
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category MLInvoice
* @package MLInvoice\Base
* @author Ere Maijala <ere@labs.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://labs.fi/mlinvoice.eng.php
*/
require_once 'config.php';
$dblink = null;
/**
* Initialize database connection
*
* @return void
*/
function initDbConnection()
{
global $dblink;
// Connect to database server
$dblink = mysqli_connect(_DB_SERVER_, _DB_USERNAME_, _DB_PASSWORD_);
if (mysqli_connect_errno()) {
die('Could not connect to database: ' . mysqli_connect_error());
}
// Select database
mysqli_select_db($dblink, _DB_NAME_) or
die('Could not select database: ' . mysqli_error($dblink));
if (_CHARSET_ == 'UTF-8') {
dbQueryCheck('SET NAMES \'utf8\'');
}
dbQueryCheck('SET AUTOCOMMIT=1');
}
/**
* Parse a search string
*
* @param string $searchTerms Search terms
* @param string $field Field
* @param string $operator Operator
* @param string $term Extracted term
* @param string $boolean Any boolean operator
*
* @return bool Whether the extraction succeeded
*/
function extractSearchTerm(&$searchTerms, &$field, &$operator, &$term, &$boolean)
{
if (true
&& !preg_match(
'/^([\w\.\_]+)\s*(=|!=|<=?|>=?|LIKE)\s*(.+)/',
$searchTerms,
$matches
)
) {
if (!preg_match('/^([\w\.\_]+)\s+(IN)\s+(.+)/', $searchTerms, $matches)) {
return false;
}
}
$field = $matches[1];
$operator = $matches[2];
$rest = $matches[3];
$term = '';
$inQuotes = false;
$inParenthesis = 0;
$escaped = false;
while ($rest != '') {
$ch = substr($rest, 0, 1);
$rest = substr($rest, 1);
if ($escaped) {
$escaped = false;
$term .= $ch;
continue;
}
if ($ch == '\\') {
$escaped = true;
continue;
}
if ($ch == "'") {
$inQuotes = !$inQuotes;
continue;
}
if ($ch == '(') {
++$inParenthesis;
} elseif ($ch == ')') {
if (--$inParenthesis < 0) {
die('Unbalanced parenthesis');
}
}
if ($ch == ' ' && !$inQuotes && $inParenthesis == 0) {
break;
}
$term .= $ch;
}
if ($inParenthesis > 0) {
die('Unbalanced parenthesis');
}
if (substr($rest, 0, 4) == 'AND ') {
$boolean = ' AND ';
$searchTerms = substr($rest, 4);
} elseif (substr($rest, 0, 3) == 'OR ') {
$boolean = ' OR ';
$searchTerms = substr($rest, 3);
} else {
$boolean = '';
$searchTerms = '';
}
return $term != '';
}
/**
* Create a 'where' clause
*
* @param array $astrSearchFields Search fields
* @param string $strSearchTerms Search terms
* @param array $arrQueryParams Query parameters
* @param bool $leftAnchored Whether the search is anchored or in the middle
*
* @return string
*/
function createWhereClause($astrSearchFields, $strSearchTerms, &$arrQueryParams,
$leftAnchored = false
) {
$astrTerms = explode(' ', $strSearchTerms);
$strWhereClause = '(';
$termPrefix = $leftAnchored ? '' : '%';
for ($i = 0; $i < count($astrTerms); $i ++) {
if ($i > 0) {
$termPrefix = '%';
}
if ($astrTerms[$i]) {
$strWhereClause .= '(';
for ($j = 0; $j < count($astrSearchFields); $j ++) {
if ($astrSearchFields[$j]['type'] == 'TEXT') {
$strWhereClause .= $astrSearchFields[$j]['name'] . ' LIKE ? OR ';
$arrQueryParams[] = $termPrefix . $astrTerms[$i] . '%';
} elseif ($astrSearchFields[$j]['type'] == 'INT'
&& preg_match('/^([0-9]+)$/', $astrTerms[$i])
) {
$strWhereClause .= $astrSearchFields[$j]['name'] . ' = ?'
. ' OR ';
$arrQueryParams[] = $astrTerms[$i];
} elseif ($astrSearchFields[$j]['type'] == 'CURRENCY') {
$strWhereClause .= 'CAST(' . $astrSearchFields[$j]['name'] . ' AS CHAR) LIKE ? OR ';
$arrQueryParams[] = $termPrefix . $astrTerms[$i] . '%';
} elseif ($astrSearchFields[$j]['type'] == 'PRIMARY'
&& preg_match('/^([0-9]+)$/', $intID)
) {
$strWhereClause = 'WHERE ' . $astrSearchFields[$j]['name']
. ' = ? ';
$arrQueryParams = [$intID];
unset($astrSearchFields);
break 2;
}
}
$strWhereClause = substr($strWhereClause, 0, -3) . ') AND ';
}
}
$strWhereClause = substr($strWhereClause, 0, -4) . ')';
return $strWhereClause;
}
/**
* Update product stock balance for an invoice row
*
* @param int $invoiceRowId Invoice row ID
* @param int $productId Product ID
* @param int $count Count of items
*
* @return void
*/
function updateProductStockBalance($invoiceRowId, $productId, $count)
{
// Get old product stock balance
$oldProductId = false;
$oldCount = 0;
if (!empty($invoiceRowId)) {
// Fetch old product id
$rows = dbParamQuery(
'SELECT product_id, pcs from {prefix}invoice_row WHERE id=?'
. ' AND deleted=0',
[$invoiceRowId],
'exception'
);
if ($rows) {
$oldProductId = $rows[0]['product_id'];
$oldCount = $rows[0]['pcs'];
}
}
if ($oldProductId) {
// Add old balance to old product
dbParamQuery(
'UPDATE {prefix}product SET stock_balance=IFNULL(stock_balance, 0)+?'
. ' WHERE id=?',
[$oldCount, $oldProductId],
'exception'
);
}
if (!empty($productId)) {
// Deduct from new product
dbParamQuery(
'UPDATE {prefix}product SET stock_balance=IFNULL(stock_balance, 0)-?'
. ' WHERE id=?',
[
$count,
$productId
],
'exception'
);
}
}
/**
* Get payment days for a company
*
* @param int $companyId Company ID
*
* @return int
*/
function getPaymentDays($companyId)
{
if (!empty($companyId)) {
$rows = dbParamQuery(
'SELECT payment_days FROM {prefix}company WHERE id = ?',
[$companyId]
);
if (!empty($rows[0]['payment_days'])) {
return $rows[0]['payment_days'];
}
}
return getSetting('invoice_payment_days');
}
/**
* Check if an invoice record in an offer
*
* @param int $invoiceId Invoice ID
*
* @return bool
*/
function isOffer($invoiceId)
{
$rows = dbParamQuery(
'SELECT id FROM {prefix}invoice_state WHERE invoice_offer=1 AND id IN ('
. 'SELECT state_id FROM {prefix}invoice WHERE id=?)',
[$invoiceId]
);
return $rows ? true : false;
}
/**
* Check if an invoice record is open
*
* @param int $invoiceId Invoice ID
*
* @return bool
*/
function isInvoiceOpen($invoiceId)
{
$rows = dbParamQuery(
'SELECT id FROM {prefix}invoice_state WHERE invoice_open=1 AND id IN ('
. 'SELECT state_id FROM {prefix}invoice WHERE id=?)',
[$invoiceId]
);
return $rows ? true : false;
}
/**
* Check if an invoice row belongs to an offer
*
* @param int $invoiceRowId Invoice row ID
*
* @return bool
*/
function isRowOfOffer($invoiceRowId)
{
$rows = dbParamQuery(
'SELECT id FROM {prefix}invoice_state WHERE invoice_offer=1 AND id IN ('
. 'SELECT state_id FROM {prefix}invoice i'
. ' INNER JOIN {prefix}invoice_row ir ON i.id = ir.invoice_id'
. ' WHERE ir.id=?)',
[$invoiceRowId]
);
return $rows ? true : false;
}
/**
* Get the initial state for offers
*
* @return int
*/
function getInitialOfferState()
{
$res = dbQueryCheck(
'SELECT id FROM {prefix}invoice_state'
. ' WHERE invoice_open=1 AND invoice_offer=1 AND invoice_offer_sent=0'
. ' ORDER BY order_no'
);
$result = dbFetchValue($res) ?: 1;
return $result;
}
/**
* Get tags for a record
*
* @param string $type Record type (company, contact)
* @param int $id Record ID
*
* @return string Comma-separated list of tags
*/
function getTags($type, $id)
{
$tags = [];
$rows = dbParamQuery(
<<<EOT
SELECT tag FROM {prefix}${type}_tag WHERE id IN (
SELECT tag_id FROM {prefix}${type}_tag_link WHERE ${type}_id=?
)
EOT
,
[$id]
);
foreach ($rows as $tagRow) {
$tags[] = $tagRow['tag'];
}
return implode(',', $tags);
}
/**
* Save tags for a record
*
* @param string $type Record type (company, contact)
* @param int $id Record ID
* @param string $tags Comma-separated list of tags
*
* @return void
*/
function saveTags($type, $id, $tags)
{
global $dblink;
// Delete tag links
dbParamQuery(
"DELETE FROM {prefix}${type}_tag_link WHERE ${type}_id=?",
[$id],
'exception'
);
if ($tags) {
// Save tags
foreach (explode(',', $tags) as $tag) {
$tag = trim($tag);
$rows = dbParamQuery(
"SELECT id FROM {prefix}${type}_tag WHERE tag=?",
[$tag]
);
$tagId = $rows ? $rows[0]['id'] : null;
if (null === $tagId) {
dbParamQuery(
"INSERT INTO {prefix}${type}_tag (tag) VALUES (?)",
[$tag],
'exception'
);
$tagId = mysqli_insert_id($dblink);
}
dbParamQuery(
"INSERT INTO {prefix}${type}_tag_link (tag_id, ${type}_id)"
. ' VALUES (?, ?)',
[$tagId, $id],
'exception'
);
}
}
// Delete any orphaned tags
dbParamQuery(
<<<EOT
DELETE FROM {prefix}${type}_tag WHERE id NOT IN
(SELECT tag_id FROM {prefix}${type}_tag_link)
EOT
,
[],
'exception'
);
}
/**
* Get a default value
*
* @param int $id Record ID
* @param bool $full Whether to return full record or just the value
*
* @return mixed String, array if $full or null
*/
function getDefaultValue($id, $full = false)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}default_value WHERE id=?',
[$id]
);
if (!$rows) {
return null;
}
return $full ? $rows[0] : $rows[0]['content'];
}
/**
* Get an invoice
*
* @param int $id Invoice ID
*
* @return array
*/
function getInvoice($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}invoice WHERE id=?',
[$id]
);
return $rows ? $rows[0] : [];
}
/**
* Update invoice's print date
*
* @param int $id Invoice ID
*
* @return void
*/
function updateInvoicePrintDate($id)
{
dbParamQuery(
'UPDATE {prefix}invoice SET print_date=? where id=?',
[
date('Ymd'),
$id
]
);
}
/**
* Verify that the given invoice has invoice number and reference number for printing
* as required in the settings
*
* @param array $id Invoice ID
*
* @return void
*/
function verifyInvoiceDataForPrinting($id)
{
if (isOffer($id)) {
return;
}
$needInvNo = getSetting('invoice_add_number');
$needRefNo = getSetting('invoice_add_reference_number');
if (!$needInvNo && !$needRefNo) {
return;
}
dbQueryCheck(
'LOCK TABLES {prefix}invoice WRITE, {prefix}settings READ'
. ', {prefix}company READ'
);
$rows = dbParamQuery(
'SELECT invoice_no, ref_number, base_id, company_id, invoice_date,'
. "interval_type FROM {prefix}invoice WHERE id=?",
[$id]
);
$data = isset($rows[0]) ? $rows[0] : null;
if (($needInvNo && empty($data['invoice_no']))
|| ($needRefNo && empty($data['ref_number']))
) {
$defaults = getInvoiceDefaults(
$id, $data['base_id'], $data['company_id'],
dateConvDBDate2Date($data['invoice_date']), $data['interval_type'],
$data['invoice_no']
);
$sql = "UPDATE {prefix}invoice SET";
$updateStrings = [];
$params = [];
if ($needInvNo && empty($data['invoice_no'])) {
$updateStrings[] = 'invoice_no=?';
$params[] = $defaults['invoice_no'];
}
if ($needRefNo && empty($data['ref_number'])) {
$updateStrings[] = 'ref_number=?';
$params[] = $defaults['ref_no'];
}
$sql .= ' ' . implode(', ', $updateStrings) . ' WHERE id=?';
$params[] = $id;
dbParamQuery($sql, $params);
}
dbQueryCheck('UNLOCK TABLES');
}
/**
* Get a base
*
* @param int $id Base ID
*
* @return array
*/
function getBase($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}base WHERE id=?',
[$id]
);
return $rows ? $rows[0] : [];
}
/**
* Get send API config
*
* @param int $baseId Base ID
* @param string $apiId API name
*
* @return array
*/
function getSendApiConfig($baseId, $apiId)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}send_api_config WHERE base_id=? AND id=?',
[$baseId, $apiId]
);
return $rows ? $rows[0] : [];
}
/**
* Get send API configs for base
*
* @param int $id Base ID
*
* @return array
*/
function getSendApiConfigs($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}send_api_config WHERE base_id=?',
[$id]
);
return $rows;
}
/**
* Get a print template
*
* @param int $id Template ID
*
* @return array
*/
function getPrintTemplate($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}print_template WHERE id=?',
[$id]
);
return $rows ? $rows[0] : [];
}
/**
* Get a product
*
* @param int $productId Product ID
*
* @return array
*/
function getProduct($productId)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}product WHERE id=?',
[$productId]
);
return $rows ? $rows[0] : [];
}
/**
* Get a company
*
* @param int $id Company ID
*
* @return array
*/
function getCompany($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}company WHERE id=?',
[$id]
);
return $rows ? $rows[0] : [];
}
/**
* Get company specific price settings
*
* @param int $companyId Company ID
*
* @return array
*/
function getCustomPriceSettings($companyId)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}custom_price WHERE company_id=?',
[$companyId]
);
if ($rows) {
$result = $rows[0];
$result['valid'] = empty($result['valid_until'])
|| $result['valid_until'] >= date('Ymd');
return $result;
}
return [];
}
/**
* Set company specific price settings
*
* @param int $companyId Company ID
* @param float $discount Discount percentage
* @param float $multiplier Price multiplier
* @param int $validUntil Valid until date
*
* @return void
*/
function setCustomPriceSettings($companyId, $discount, $multiplier, $validUntil)
{
$settings = getCustomPriceSettings($companyId);
if ($settings) {
dbParamQuery(
'UPDATE {prefix}custom_price SET discount=?, multiplier=?'
. ', valid_until=? WHERE id=?',
[$discount, $multiplier, $validUntil, $settings['id']]
);
} else {
dbParamQuery(
'INSERT INTO {prefix}custom_price (company_id, discount, multiplier'
. ', valid_until) VALUES (?, ?, ?, ?)',
[$companyId, $discount, $multiplier, $validUntil]
);
}
}
/**
* Delete company specific price settings
*
* @param int $companyId Company ID
*
* @return void
*/
function deleteCustomPriceSettings($companyId)
{
dbParamQuery(
'DELETE FROM {prefix}custom_price WHERE company_id=?', [$companyId]
);
}
/**
* Get company specific price for a product
*
* @param int $companyId Company ID
* @param int $productId Product ID
*
* @return array
*/
function getCustomPrice($companyId, $productId)
{
$rows = dbParamQuery(
<<<EOT
SELECT * FROM {prefix}custom_price_map WHERE product_id=? AND custom_price_id IN (
SELECT id FROM {prefix}custom_price WHERE company_id=?
)
EOT
,
[$productId, $companyId]
);
return $rows ? $rows[0] : [];
}
/**
* Set company specific product price
*
* @param int $companyId Company ID
* @param int $productId Product ID
* @param float $unitPrice Unit price
*
* @return void
*/
function setCustomPrice($companyId, $productId, $unitPrice)
{
dbQueryCheck('BEGIN');
try {
$customPrices = getCustomPriceSettings($companyId);
if (!$customPrices) {
die('No custom prices defined for the company');
}
dbParamQuery(
<<<EOT
DELETE FROM {prefix}custom_price_map WHERE product_id=? AND custom_price_id=?
EOT
,
[$productId, $customPrices['id']]
);
dbParamQuery(
<<<EOT
INSERT INTO {prefix}custom_price_map (custom_price_id, product_id, unit_price)
VALUES (?, ?, ?)
EOT
,
[$customPrices['id'], $productId, $unitPrice]
);
} catch (Exception $e) {
dbQueryCheck('ROLLBACK');
throw $e;
}
dbQueryCheck('COMMIT');
}
/**
* Delete company specific product price
*
* @param int $companyId Company ID
* @param int $productId Product ID
*
* @return void
*/
function deleteCustomPrice($companyId, $productId)
{
$customPrices = getCustomPriceSettings($companyId);
if (!$customPrices) {
return;
}
dbParamQuery(
<<<EOT
DELETE FROM {prefix}custom_price_map WHERE product_id=? AND custom_price_id=?
EOT
,
[$productId, $customPrices['id']]
);
}
/**
* Get user by id
*
* @param string $id User id
*
* @return mixed array or null
*/
function getUserById($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}users WHERE id=?',
[$id]
);
return $rows ? $rows[0] : null;
}
/**
* Get user by login name or email
*
* @param string $userId User login name or email address
*
* @return mixed array or null
*/
function getUserByLoginId($userId)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}users WHERE login=? OR email=?',
[$userId, $userId]
);
return $rows ? $rows[0] : null;
}
/**
* Get user by token
*
* @param string $token User token
*
* @return mixed array or null
*/
function getUserByToken($token)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}users WHERE token=?',
[$token]
);
return $rows ? $rows[0] : null;
}
/**
* Update user's token
*
* @param int $id User id
*
* @return string
*/
function updateUserToken($id)
{
$user = getUserById($id);
if (!$user) {
throw new Exception('User not found');
}
$token = sha1($user['id'] . $user['login'] . $user['passwd'] . rand())
. str_pad(substr((string)time(), 0, 10), 10, '0', STR_PAD_LEFT);
dbParamQuery(
'UPDATE {prefix}users SET token=? WHERE id=?',
[$token, $id]
);
return $token;
}
/**
* Update user
*
* @param int $id User id
* @param array $data User data
*
* @return void
*/
function updateUser($id, $data)
{
$fields = [];
$params = [];
foreach ($data as $key => $value) {
$fields[] = "$key = ?";
$params[] = $value;
}
$params[] = $id;
dbParamQuery(
'UPDATE {prefix}users SET ' . implode(', ', $fields) . ' WHERE id=?',
$params
);
}
/**
* Update user's password
*
* @param int $id User id
* @param string $password New password
*
* @return void
*/
function updateUserPassword($id, $password)
{
$user = getUserById($id);
if (!$user) {
throw new Exception('User not found');
}
dbParamQuery(
'UPDATE {prefix}users SET passwd=? WHERE id=?',
[password_hash($password, PASSWORD_DEFAULT), $id]
);
}
/**
* Get the maximum invoice number with the given arguments
*
* @param int $invoiceId Invoice ID
* @param int $baseId Base ID
* @param bool $perYear Whether to use year-based invoice numbering
*
* @return int
*/
function getMaxInvoiceNumber($invoiceId, $baseId, $perYear)
{
if ($baseId !== null) {
$sql = 'SELECT max(cast(invoice_no as unsigned integer)) as maxnum'
. ' FROM {prefix}invoice WHERE deleted=0 AND id!=? AND base_id=?';
$params = [
$invoiceId,
$baseId
];
} else {
$sql = 'SELECT max(cast(invoice_no as unsigned integer)) as maxnum'
. ' FROM {prefix}invoice WHERE deleted=0 AND id!=?';
$params = [$invoiceId];
}
if ($perYear) {
$sql .= ' AND invoice_date >= ' . date('Y') . '0101';
}
$rows = dbParamQuery($sql, $params);
return $rows[0]['maxnum'];
}
/**
* Get an invoice type
*
* @param int $id Invoice type ID
*
* @return array
*/
function getInvoiceType($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}invoice_type WHERE id=?',
[$id]
);
return $rows ? $rows[0] : [];
}
/**
* Get an attachment
*
* @param int $id Attachment ID
*
* @return array
*/
function getAttachment($id)
{
$rows = dbParamQuery(
'SELECT * FROM {prefix}attachment WHERE id=?',
[$id]
);
return $rows ? $rows[0] : [];
}
/**
* Get attachments
*
* @return array
*/
function getAttachments()
{
$rows = dbParamQuery(
'SELECT id, name, description, date, filename, filesize, mimetype FROM {prefix}attachment'
);
return $rows ? $rows : [];
}
/**
* Get attachment count for invoice
*
* @param int $id Invoice ID
*
* @return int
*/
function getInvoiceAttachmentCount($id)
{
$rows = dbParamQuery(
'SELECT count(*) as cnt FROM {prefix}invoice_attachment WHERE invoice_id=?',
[$id]
);
return $rows[0]['cnt'];
}
/**
* Get attachments for invoice
*
* @param int $id Invoice ID
* @param bool $sendable Whether to return only sendable attachments
*
* @return int
*/
function getInvoiceAttachments($id, $sendable)
{
$sendable = $sendable ? ' AND send=1' : '';
$rows = dbParamQuery(
<<<EOT
SELECT id, name, description, date, filename, filesize, mimetype
FROM {prefix}invoice_attachment
WHERE invoice_id=?$sendable
ORDER BY order_no, id
EOT
,
[$id]
);
return $rows ? $rows : [];
}
/**
* Get an invoice attachment
*
* @param int $id Invoice attachment ID
*
* @return array