This repository has been archived by the owner on Nov 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
asterisell.php
2843 lines (2472 loc) · 93.8 KB
/
asterisell.php
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
/* $LICENSE 2011, 2012:
*
* Copyright (C) 2011, 2012 Massimo Zaniboni <massimo.zaniboni@profitoss.com>
*
* This file is part of Asterisell.
*
* Asterisell is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* Asterisell 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 Asterisell. If not, see <http://www.gnu.org/licenses/>.
* $
*/
////////////////////////////////////
// INIT ENVIRONMENT AND CALL MAIN //
////////////////////////////////////
define('SF_ROOT_DIR', realpath(dirname(__FILE__)));
define('SF_APP', 'asterisell');
define('SF_ENVIRONMENT', 'prod');
define('SF_DEBUG', false);
require_once(SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php');
sfLoader::loadHelpers(array('I18N', 'Debug', 'Asterisell'));
sfContext::getInstance();
define('WEB_DIR', SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'web');
/**
* Special file where read user input.
*/
$input_line = fopen('php://stdin', 'r');
main($argc, $argv);
//////////////////////
// DATABASE UPGRADE //
//////////////////////
/**
* Apply upgrade commands only if they are not already applied.
*
* @param $findNewCommands TRUE for applying only not already applied commands
* @param $applyCommands TRUE for applying commands to SQL database
* @param $storeCommands TRUE for storing in upgrade table the commands
* @return TRUE if there were commands working on the CDR table
*/
function upgradeDatabase($findNewCommands, $applyCommands, $storeCommands)
{
global $input_line;
// commands to apply
$r = array();
$i = 1;
$cdrCommandIndexes = array();
// NOTE: the order and the key of the array is very important because it is used also as a key for recognizing
// already executed commands. You should only add commands to this list.
//
$r[$i++] = "alter table ar_params modify column vat_tax_perc integer(20) not null default 0;";
$r[$i++] = "alter table ar_params add `logo_image_in_invoices` VARCHAR(120);";
$r[$i++] = "alter table ar_params add `invoice_notes` VARCHAR(2048);";
$r[$i++] = "alter table ar_params add `invoice_payment_terms` VARCHAR(2048);";
$r[$i++] = "alter table ar_params add `current_invoice_nr` INTEGER(11) default 1 NOT NULL;";
$r[$i++] = "alter table ar_params drop column`pdf_call_report`;";
$r[$i++] = "alter table ar_invoice add `pdf_call_report` LONGBLOB;";
$r[$i++] = "alter table ar_invoice_creation add `ar_params_id` INTEGER;";
$r[$i++] = "ALTER TABLE ar_invoice_creation ADD (KEY `ar_invoice_creation_FI_1` (`ar_params_id`), CONSTRAINT `ar_invoice_creation_FK_1` FOREIGN KEY (`ar_params_id`) REFERENCES `ar_params` (`id`));";
$r[$i++] = "ALTER TABLE ar_invoice ADD `info_or_ads_image1` VARCHAR(1024);";
$r[$i++] = "ALTER TABLE ar_invoice ADD `info_or_ads_image2` VARCHAR(1024);";
$r[$i++] = "ALTER TABLE ar_invoice_creation ADD `info_or_ads_image1` VARCHAR(1024);";
$r[$i++] = "ALTER TABLE ar_invoice_creation ADD `info_or_ads_image2` VARCHAR(1024);";
$r[$i++] = "ALTER TABLE ar_params ADD `logo_html_color` VARCHAR(12);";
$r[$i++] = "CREATE TABLE `ar_payment` (`id` int(11) NOT NULL AUTO_INCREMENT, `ar_party_id` int(11) DEFAULT NULL, `date` date DEFAULT NULL, `invoice_nr` varchar(20) DEFAULT NULL, `payment_method` varchar(1024) DEFAULT NULL, `payment_references` varchar(1024) DEFAULT NULL, `amount` int(20) NOT NULL DEFAULT 0, `note` text, PRIMARY KEY (`id`), KEY `ar_payment_date_index` (`date`), KEY `ar_payment_invoice_nr_index` (`invoice_nr`), KEY `ar_payment_amount_index` (`amount`), KEY `ar_payment_FI_1` (`ar_party_id`), CONSTRAINT `ar_payment_FK_1` FOREIGN KEY (`ar_party_id`) REFERENCES `ar_party` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$r[$i++] = "ALTER TABLE ar_invoice ADD `total_bundle_without_tax` int(20) DEFAULT 0;";
$r[$i++] = "ALTER TABLE ar_invoice ADD `total_calls_without_tax` int(20) DEFAULT 0;";
$r[$i++] = "CREATE TABLE `ar_rate_incremental_info` (`id` int(11) NOT NULL AUTO_INCREMENT, `ar_party_id` int(11) DEFAULT NULL, `ar_rate_id` int(11) DEFAULT NULL, `period` varchar(1024) DEFAULT NULL, `last_processed_cdr_date` datetime DEFAULT NULL, `last_processed_cdr_id` int(20) DEFAULT NULL, `bundle_rate` longtext, PRIMARY KEY (`id`), KEY `ar_rate_incremental_info_period_index` (`period`(767)), KEY `ar_rate_incremental_info_FI_1` (`ar_party_id`), KEY `ar_rate_incremental_info_FI_2` (`ar_rate_id`), CONSTRAINT `ar_rate_incremental_info_FK_1` FOREIGN KEY (`ar_party_id`) REFERENCES `ar_party` (`id`), CONSTRAINT `ar_rate_incremental_info_FK_2` FOREIGN KEY (`ar_rate_id`) REFERENCES `ar_rate` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$r[$i++] = "ALTER TABLE ar_asterisk_account ADD `is_active` int(11) NOT NULL DEFAULT 1;";
$r[$i++] = "ALTER TABLE ar_invoice ADD `ar_params_id` int(11) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `payment_days` int(20) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `reconnection_fee` VARCHAR(50) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `info_telephone_number` varchar(512) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `late_payment_fee` VARCHAR(50) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `etf_bbs` varchar(512) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `etf_acc_no` varchar(512) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `account_department` varchar(512) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `direct_debit_payment_email` varchar(512) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params ADD `direct_debit_payment_telephone_number` varchar(512) DEFAULT NULL;";
$r[$i++] = "CREATE TABLE `ar_lock`(`id` INTEGER NOT NULL AUTO_INCREMENT, `name` CHAR(255) NOT NULL, `time` DATETIME, `info` VARCHAR(1024), PRIMARY KEY (`id`), KEY `ar_lock_name_index`(`name`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;";
$r[$i++] = "ALTER TABLE ar_params ADD `login_urn` VARCHAR(512) DEFAULT NULL;";
$r[$i++] = "ALTER TABLE `ar_asterisk_account` ADD `ar_rate_category_id` INTEGER;";
$r[$i++] = "ALTER TABLE `ar_office` ADD `ar_rate_category_id` INTEGER;";
$r[$i++] = "ALTER TABLE `ar_party` ADD `is_reseller` INTEGER default 0 NOT NULL;";
$r[$i++] = "ALTER TABLE `ar_party` ADD `reseller_code` VARCHAR(80);";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` ADD `source_cost` INTEGER(20) default null, ADD `is_exported` INTEGER default 0 NOT NULL, ADD `source_data_type` VARCHAR(1024), ADD `source_data` VARCHAR(10000), CHANGE COLUMN `source_id` `source_id` VARCHAR(255) DEFAULT NULL, ADD KEY `cdr_is_exported_index`(`is_exported`), ADD INDEX account_and_calldate_index(ar_asterisk_account_id, calldate), DROP KEY `cdr_source_id_index`, ADD KEY `cdr_source_id_index`(`source_id`);";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_channel_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_income_ar_rate_id_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_income_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_cost_ar_rate_id_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_vendor_id_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_cost_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_cached_internal_telephone_number_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_cached_external_telephone_number_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_external_telephone_number_with_applied_portability_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE `cdr` DROP KEY `cdr_cached_masked_external_telephone_number_index`;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE cdr MODIFY COLUMN clid VARCHAR(255) NOT NULL, MODIFY COLUMN src VARCHAR(255) NOT NULL, MODIFY COLUMN dst VARCHAR(255) NOT NULL, MODIFY COLUMN dcontext VARCHAR(255) NOT NULL, MODIFY COLUMN channel VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN dstchannel VARCHAR(255) NOT NULL, MODIFY COLUMN lastapp VARCHAR(255) NOT NULL, MODIFY COLUMN lastdata VARCHAR(255) NOT NULL, MODIFY COLUMN disposition VARCHAR(255) NOT NULL, MODIFY COLUMN accountcode VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN uniqueid VARCHAR(255) DEFAULT '' NOT NULL, MODIFY COLUMN cached_internal_telephone_number VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN cached_external_telephone_number VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN external_telephone_number_with_applied_portability VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN cached_masked_external_telephone_number VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN source_data_type VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN source_data VARCHAR(8000) NULL DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_number_portability MODIFY COLUMN telephone_number VARCHAR(255) NOT NULL, MODIFY COLUMN ported_telephone_number VARCHAR(255) NOT NULL;";
$r[$i++] = "ALTER TABLE ar_asterisk_account MODIFY COLUMN name VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN account_code VARCHAR(255) NOT NULL;";
$r[$i++] = "ALTER TABLE ar_office MODIFY COLUMN name VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN description VARCHAR(255) NULL DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_party MODIFY COLUMN external_crm_code VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN vat VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_address VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_city VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_zipcode VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_state_province VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_country VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN email VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN phone VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN phone2 VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN fax VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN reseller_code VARCHAR(255) NULL DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_params MODIFY COLUMN name VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN service_name VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN service_provider_website VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN service_provider_email VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN logo_image VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN slogan VARCHAR(1024) NULL DEFAULT NULL, MODIFY COLUMN logo_image_in_invoices VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN user_message VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN external_crm_code VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN vat VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_address VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_website VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_city VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_zipcode VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_state_province VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_country VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_email VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_phone VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN phone2 VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN legal_fax VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN invoice_notes VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN sender_name_on_invoicing_emails VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN invoicing_email_address VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN accountant_email_address VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN smtp_username VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN smtp_password VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN smtp_encryption VARCHAR(255) NULL DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_rate_category MODIFY COLUMN name VARCHAR(255) NULL DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_telephone_prefix MODIFY COLUMN prefix VARCHAR(255) NOT NULL, MODIFY COLUMN name VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN geographic_location VARCHAR(255) NULL DEFAULT NULL, MODIFY COLUMN operator_type VARCHAR(255) NULL DEFAULT NULL;";
$r[$i++] = "ALTER TABLE ar_problem MODIFY COLUMN duplication_key VARCHAR(255) NOT NULL;";
$r[$i++] = "ALTER TABLE ar_lock MODIFY COLUMN info VARCHAR(255) NULL DEFAULT NULL;";
$r[$i++] = "CREATE TABLE ar_database_version (id INTEGER AUTO_INCREMENT NOT NULL, version VARCHAR(255) NULL DEFAULT NULL, installation_date DATETIME NULL DEFAULT NULL, PRIMARY KEY (id)) ENGINE=InnoDB;";
$cdrCommandIndexes[$i] = TRUE;
$r[$i++] = "ALTER TABLE cdr MODIFY COLUMN `source_id` VARCHAR(1024), MODIFY COLUMN `source_data` TEXT;";
$r[$i++] = "ALTER TABLE ar_invoice ADD `displayed_online` INTEGER;";
$secondRunIndex = $i;
$r[$i++] = "UPDATE ar_invoice SET displayed_online = 1 WHERE already_sent = 1;";
$r[$i++] = "CREATE TABLE `ar_asterisk_account_range` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `ar_office_id` INTEGER, `system_prefix` VARCHAR(255), `system_suffix` VARCHAR(255), `system_start_range` INTEGER(10) NOT NULL, `system_end_range` INTEGER(10) NOT NULL, `system_leading_zero` INTEGER(3) NOT NULL, `is_delete` INTEGER default 0 NOT NULL, `is_physical_delete` INTEGER default 0 NOT NULL, `user_prefix` VARCHAR(255), `user_suffix` VARCHAR(255), `user_start_range` INTEGER(10) NOT NULL, `generate_range_for_users` INTEGER default 1 NOT NULL, `user_leading_zero` INTEGER(3) NOT NULL, `user_note` TEXT, PRIMARY KEY (`id`), INDEX `ar_asterisk_account_range_FI_1` (`ar_office_id`), CONSTRAINT `ar_asterisk_account_range_FK_1` FOREIGN KEY (`ar_office_id`) REFERENCES `ar_office` (`id`))Engine=InnoDB;";
$r[$i++] = "ALTER TABLE `ar_asterisk_account_range` MODIFY COLUMN system_start_range VARCHAR(18) NOT NULL, MODIFY COLUMN system_end_range VARCHAR(18) NOT NULL, MODIFY COLUMN `system_leading_zero` INTEGER(4) NOT NULL, MODIFY COLUMN `user_start_range` VARCHAR(18) NOT NULL, MODIFY COLUMN `generate_range_for_users` INTEGER default 1 NOT NULL, MODIFY COLUMN `user_leading_zero` INTEGER(4) NOT NULL, MODIFY COLUMN `user_note` VARCHAR(6048);";
$r[$i++] = "CREATE TABLE `ar_document` (`id` INTEGER NOT NULL AUTO_INCREMENT, `ar_party_id` INTEGER, `document_name` VARCHAR(128), `document_date` DATE, `document` LONGBLOB, `file_name` VARCHAR(128), `mime_type` VARCHAR(256), `already_opened` INTEGER default 0 NOT NULL, PRIMARY KEY (`id`), INDEX `ar_document_FI_1` (`ar_party_id`), CONSTRAINT `ar_document_FK_1` FOREIGN KEY (`ar_party_id`) REFERENCES `ar_party` (`id`) )Engine=InnoDB;";
$r[$i++] = "ALTER TABLE ar_telephone_prefix ADD COLUMN never_mask_number INTEGER default 0 NOT NULL;";
// END OF UPGRADES //
/////////////////////
$totCommands = $i;
// recent installation, with already upgrade table, but with a bug in notification process
$firstRun = isUpgradeFromVeryOldVersion();
$secondRun = isUpgradeFromOldVersion();
$supressWarnings = $firstRun || $secondRun;
// Upgrade the database
$time1 = time();
$cdrTableModified = FALSE;
$connection = Propel::getConnection();
$countCommands = 0;
foreach ($r as $key => $cmd) {
$cmd_alreadyApplied = FALSE;
$cmd_apply = $applyCommands;
$cmd_testForModifiedCDR = FALSE;
if ($findNewCommands) {
$found = FALSE;
if ($secondRun && $key < $secondRunIndex) {
// all commands before this are already applied
$found = TRUE;
} else {
$c = new Criteria();
$c->add(ArDatabaseVersionPeer::VERSION, $key);
$upg = ArDatabaseVersionPeer::doSelectOne($c);
$found = !is_null($upg);
}
if ($found) {
$cmd_alreadyApplied = TRUE;
$cmd_apply = FALSE;
} else {
$cmd_alreadyApplied = FALSE;
$cmd_testForModifiedCDR = TRUE;
}
} else {
// all commands are (at least virtually) applied so test it
$cmd_testForModifiedCDR = TRUE;
}
if ($cmd_testForModifiedCDR) {
if (array_key_exists($key, $cdrCommandIndexes)) {
$cdrTableModified = TRUE;
}
}
$cmd_store = $storeCommands;
if ($cmd_apply) {
$countCommands++;
echo "\n$key:\n$cmd";
try {
$stm = $connection->prepareStatement($cmd);
$stm->executeUpdate();
echo "\nSUCCESS\n";
} catch (Exception $e) {
$cmd_store = FALSE;
if ($supressWarnings) {
echo "\nERROR: this is the first upgrade using the new method, and the initial commands can generate some errors because they were already applied to the database. In this case this is not a problem.";
} else {
echo "\nERROR: if you execute upgrade again, this command will be retried again. ";
}
echo "\nThe error message is: " . $e->getMessage() . "\n";
explicitContinue();
}
}
if ($cmd_store) {
markUpgradeCommand($key);
}
}
// Show stats
$time2 = time();
if ($applyCommands) {
echo "\n\nUpgrading started at " . date("r", $time1) . " and completed at " . date("r", $time2) . "\nDuring this time the dabase was locked.\nApplied $countCommands upgrade commands.";
}
return $cdrTableModified;
}
function markUpgradeCommand($key)
{
global $input_line;
$c = new Criteria();
$c->add(ArDatabaseVersionPeer::VERSION, $key);
$rs = ArDatabaseVersionPeer::doSelectOne($c);
if (is_null($rs)) {
$upg = new ArDatabaseVersion();
$upg->setVersion($key);
$upg->setInstallationDate(time());
$upg->save();
} else {
// command already inserted
}
}
/**
* @return TRUE if it an upgrade from a previous version without the upgrade table
*/
function isUpgradeFromVeryOldVersion()
{
global $input_line;
$connection = Propel::getConnection();
$query = 'SELECT id FROM ar_database_version LIMIT 1';
$stm = $connection->createStatement();
try {
$rs = $stm->executeQuery($query);
while ($rs->next()) {
// there is the ar_database_version table and it contain some data,
// so it is not the first upgrade.
return FALSE;
}
// there is the table, but it does not contain data, so it is the first upgrade
return TRUE;
} catch (Exception $e) {
// there is no ar_database_table
return TRUE;
}
}
/**
* @return TRUE if there is the upgrade table, but it is empty.
* This situation never occur in last version of upgrade procedure because all commands are signaled
* as applied, but it occurs in case of older versions.
*/
function isUpgradeFromOldVersion()
{
global $input_line;
$connection = Propel::getConnection();
$query = 'SELECT id FROM ar_database_version LIMIT 1';
$stm = $connection->createStatement();
try {
$rs = $stm->executeQuery($query);
while ($rs->next()) {
// there is the ar_database_version table and it contain some data,
// so it is not the first upgrade.
return FALSE;
}
// there is the table, but it does not contain data, so it is the first upgrade
return TRUE;
} catch (Exception $e) {
// there is no ar_database_table, so this is a very old version
return FALSE;
}
}
/**
* @return TRUE if there is a safe connection to the database
*/
function isSafeReadConnection()
{
global $input_line;
try {
$connection = Propel::getConnection();
$query = 'SELECT id FROM cdr LIMIT 1';
$stm = $connection->createStatement();
$rs = $stm->executeQuery($query);
while ($rs->next()) {
}
return TRUE;
} catch (Exception $e) {
return FALSE;
}
}
/**
* @return TRUE if the database user can alter the database
*/
function isSafeAlterConnection()
{
global $input_line;
try {
$connection = Propel::getConnection();
$stm = $connection->createStatement();
$s1 = "CREATE TABLE IF NOT EXISTS ar_check_upgrade_script (id INTEGER(1)) ENGINE=InnoDB;";
$s2 = "ALTER TABLE ar_check_upgrade_script MODIFY COLUMN id INTEGER(5);";
$s3 = "ALTER TABLE ar_check_upgrade_script MODIFY COLUMN id INTEGER(4);";
$stm = $connection->prepareStatement($s1);
$stm->executeUpdate();
$stm = $connection->prepareStatement($s2);
$stm->executeUpdate();
$stm = $connection->prepareStatement($s3);
$stm->executeUpdate();
return TRUE;
} catch (Exception $e) {
return FALSE;
}
}
////////////////////////////////////
// APPLICATION MANAGEMENT SECTION //
////////////////////////////////////
/**
* Exit if the user does not confirm.
*
* @return void
*/
function explicitConfirmForDeletion($isInteractive = TRUE)
{
global $input_line;
if ($isInteractive) {
list($database, $user, $password) = getDatabaseNameUserAndPassword();
echo "\nWARNING: all data in database '$database' will be deleted. Are you sure? [y/N]";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "y" || $next_line === "Y") {
} else {
echo "\nStop execution: database was not modified.\n";
exit(1);
}
}
}
function myExecute($comment, $cmd)
{
global $input_line;
echo "\n$comment";
echo "\nexecute> $cmd\n";
system($cmd, $result);
}
function explicitContinue()
{
global $input_line;
echo "\nPress Enter to continue...";
echo "\n";
$next_line = trim(fgets($input_line, 1024));
}
function makeInstallCreateDatabase()
{
global $input_line;
list($database, $user, $password) = getDatabaseNameUserAndPassword();
echo "\nConfirm you want create database '$database', user '$user', with password '$password', as specified in file 'configure/databases.yms' [y/N]";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "y" || $next_line === "Y") {
} else {
echo "\nStop execution: database data was not confirmed.\n";
exit(1);
}
echo "\nEnter the name of MySQL administrator user, or another MySQL user that can create new databases: ";
$rootUser = trim(fgets($input_line, 1024));
echo "\nEnter the MySQL password of the administrator user $rootUser: ";
$rootPassword = trim(fgets($input_line, 1024));
myExecute("Drop '$database' database", "mysqladmin -u $rootUser --password=$rootPassword drop --force $database");
myExecute("Create '$database' database", "mysqladmin -u $rootUser --password=$rootPassword create $database");
myExecute("Drop database user '$user'", "mysql -u $rootUser --password=$rootPassword mysql -e \"DROP USER $user@localhost;\" ");
myExecute("Create database user '$user'", "mysql -u $rootUser --password=$rootPassword mysql -e \"CREATE USER $user@localhost IDENTIFIED BY '$password';\" ");
myExecute("Grant Access", "mysql -u $rootUser --password=$rootPassword mysql -e 'GRANT ALL ON $database.* TO $user@localhost;'");
myExecute("Init '$database' database", "mysql -u $rootUser --password=$rootPassword $database < data/sql/lib.model.schema.sql");
explicitContinue();
makeActivate();
}
function makeInstallData()
{
global $input_line;
// this in the first installation of the database, so all upgrades are already applied, and mark them according
// this simplify other pass of uprade.
upgradeDatabase(FALSE, FALSE, TRUE, TRUE);
makeActivate();
$password = 'root';
$paramsId = initWithDemoData(3000);
addRootUser($password, $paramsId);
echo "\nLoaded some demo data. user: $password - password: $password \n";
}
function makeDatabaseBackup($isInteractive = TRUE)
{
global $input_line;
list($database, $user, $password) = getDatabaseNameUserAndPassword();
$fileName = 'backup-' . date('Y-m-d_H-i-s') . '.sql';
$cmd = "mysqldump -u $user --password=$password $database --single-transaction > $fileName";
$makeBackup = TRUE;
if ($isInteractive) {
echo "\nThe database can be backuped using the command\n > $cmd";
echo "\nCould I perform first a backup of the current database, without locking it? [Y/n]";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "n" || $next_line === "N") {
$makeBackup = FALSE;
}
}
if ($makeBackup) {
myExecute("Make backup", $cmd);
}
echo "\nDone";
}
/**
* Manage in a complete way the application upgrade procedure.
*
* @return the suggestion about next commands
*/
function makeAppUpgrade()
{
global $input_line;
echo "\nLock the application access to users, so code can be upgraded safely.";
MyUser::lockCronForMaintanance();
MyUser::lockAppForMaintanance();
$cmd = sfConfig::get('app_git_upgrade_command');
echo "\nConfirm the execution of `$cmd` for upgrading the source code? [y/N]";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "y" || $next_line === "Y") {
$continue = TRUE;
}
if ($continue) {
myExecute("Update source code", $cmd);
return "\nResolve conflicts in source code. Then `git commit -a`. Then `php asterisell.php data upgrade`\n";
} else {
return "";
}
}
/**
* Manage in a complete way the data upgrade procedure.
*
* @return void
*/
function makeDataUpgrade()
{
global $input_line;
// Advise if the CDR table is involved
$continue = FALSE;
if (isUpgradeFromVeryOldVersion() || upgradeDatabase(TRUE, FALSE, FALSE, FALSE)) {
echo "\nWARNING: The CDR table must be upgraded!";
echo "\n";
echo "\nThis is a slow operation, and during upgrading the CDR table will be locked, and it can not be written.";
echo "\nIn case of CDR table with 1 milion of records, this operation can require also 1-2 hours.";
echo "\nIf CALLS are inserted dynamically in the table from the VoIP server, then during upgrading process ";
echo "\nthey will be lost, and they must be retrieved from VoIP server log files.";
echo "\n ";
echo "\nThis command will display the starting and ending time, when the CDR table were locked.";
echo "\n ";
echo "\nContinue upgrading? [y/N]";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "y" || $next_line === "Y") {
$continue = TRUE;
}
} else {
echo "\nThis upgrading does not involve the CDR table, so there is no dangerous locking, or interruption of service.";
echo "\n ";
echo "\nContinue upgrading? [y/N]";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "y" || $next_line === "Y") {
$continue = TRUE;
} else {
echo "\nWARNING: Upgrading procedure STOPPED.\n";
}
}
if ($continue) {
makeDatabaseBackup(TRUE);
if (isUpgradeFromVeryOldVersion()) {
// note: it does not store anything, because maybe there is no the safe upgrade table yet
upgradeDatabase(FALSE, TRUE, FALSE);
// then store all the commands, without applying them.
upgradeDatabase(FALSE, FALSE, TRUE);
} else {
upgradeDatabase(TRUE, TRUE, TRUE);
}
makeActivate();
}
}
function makeActivate()
{
global $input_line;
myExecute("Create default directories", "mkdir -p cache");
myExecute("Create default directories", "mkdir -p log");
myExecute("Create default directories", "mkdir -p web/generated_graphs");
// Create VERSION file
$fh = fopen("VERSION-TYPE", "r");
$f1 = fgets($fh);
fclose($fh);
$fh = fopen("VERSION-NR", "r");
$f2 = fgets($fh);
fclose($fh);
$fh = fopen("VERSION", "w");
$version = "asterisell-$f1-$f2";
fwrite($fh, $version);
fclose($fh);
// Assign the user group
$user = sfConfig::get('app_web_server_user');
$cmd = 'chown -R :' . $user . ' . ';
echo "\nFix files ownership with command `$cmd`, assuming you are running as super user? [y/N] ";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "y" || $next_line === "Y") {
myExecute("Fix ownerships", $cmd);
explicitContinue();
}
executeSymfonyCC();
myExecute("Fix Permissions", "./symfony fix-perms");
myExecute("Fix Web Server Permissions", "chmod -R ug+rwx web/");
myExecute("Fix Permissions", "chmod -R ug+rx ext_libs/ apps/ scripts/");
myExecute("Remove old lock files", "rm -f web/*.lock");
myExecute("Regenerate modules depending from the new cache values.", "cd module_templates; php generate.php");
executeSymfonyCC();
echo "\n\nGenerated VERSION $version";
echo "\n";
}
/**
* Clear symfony cache.
*/
function executeSymfonyCC()
{
myExecute("Clear symfony cache, in order to enable new settings.", "./symfony cc");
}
/**
* @return list(database name, user, password)
*/
function getDatabaseNameUserAndPassword()
{
global $input_line;
$value = sfYaml::load(file_get_contents(SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'databases.yml'));
$r = $value['all']['propel']['param'];
return array($r['database'], $r['username'], $r['password']);
}
///////////////////////////////////////////////
// ADD INITIAL AND DEMO DATA TO THE DATABASE //
///////////////////////////////////////////////
/**
* Execute the JobProcessorQueue.
*
* Delete also LOCK files.
* This is needed because during installation these files
* have rights different from the lock files created
* from the web server during normal/production execution.
*/
function runJobProcessorQueue()
{
global $input_line;
$webDir = realpath(WEB_DIR);
$culture = sfConfig::get('app_culture');
$I18N = sfContext::getInstance()->getI18N();
$I18N->setMessageSourceDir(SF_ROOT_DIR . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'i18n', $culture);
$I18N->setCulture($culture);
echo "\nStarted Job Processor.";
$processor = new JobQueueProcessor();
$r = $processor->process($webDir);
foreach (glob($webDir . DIRECTORY_SEPARATOR . '*.lock') as $filename) {
unlink($filename);
}
if (is_null($r)) {
echo "\nWARNING: Jobs were not processed, because lock can not be acquired. You should manually lanch job processor.";
} else {
echo "\nJobs were executed.";
}
}
function myDelete($c, $t)
{
$query = "DELETE FROM $t";
$s = $c->executeUpdate($query);
}
function deleteAllData()
{
global $input_line;
echo "Deleting all data inside database.\n";
// Delete all data from database, except upgrade table
//
$connection = Propel::getConnection();
myDelete($connection, "ar_document");
myDelete($connection, "ar_job_queue");
myDelete($connection, "ar_asterisk_account_range");
myDelete($connection, "ar_invoice_creation");
myDelete($connection, "ar_invoice");
myDelete($connection, "ar_problem");
myDelete($connection, "cdr");
myDelete($connection, "ar_rate_incremental_info");
myDelete($connection, "ar_rate");
myDelete($connection, "ar_web_account");
myDelete($connection, "ar_asterisk_account");
myDelete($connection, "ar_office");
myDelete($connection, "ar_party");
myDelete($connection, "ar_telephone_prefix");
myDelete($connection, "ar_rate_category");
myDelete($connection, "ar_params");
}
/**
* Create a date in the past.
*
* Note: seconds are setted according time()
* so two invocation of the function using
* the same number of $days do not return
* the same result.
*/
function pastDays($days)
{
$t = time() - ($days * 24 * 60 * 60);
return $t;
}
function nextDays($days)
{
return pastDays(0 - $days);
}
function createPrefix($pType, $pPlace, $pPrefix)
{
$r = new ArTelephonePrefix();
$r->setPrefix($pPrefix);
$r->setName(null);
$r->setGeographicLocation($pPlace);
$r->setOperatorType($pType);
$r->save();
}
function mergeCompletePrefix($prefix, $nation, $type, $operator)
{
$c = new Criteria();
$c->add(ArTelephonePrefixPeer::PREFIX, $prefix);
$r = ArTelephonePrefixPeer::doSelectOne($c);
$msg = "";
if (is_null($r)) {
$msg .= "Create new entry ";
createCompletePrefix($prefix, $nation, $type, $operator);
} else {
$msg .= "Update entry ";
$r->setPrefix($prefix);
$r->setName($operator);
$r->setGeographicLocation($nation);
$r->setOperatorType($type);
$r->save();
}
$msg .= "\"$prefix\", \"$nation\", \"$type\", \"$operator\"";
echo $msg . "\n";
}
function createCompletePrefix($prefix, $nation, $type, $operator)
{
$r = new ArTelephonePrefix();
$r->setPrefix($prefix);
$r->setName($operator);
$r->setGeographicLocation($nation);
$r->setOperatorType($type);
$r->save();
}
function loadPrefixes($filename, $merge)
{
$nrOfColInLine = 5;
$handle = fopen($filename, 'r');
if ($handle == false) {
echo "Error opening file \"$filename\"";
exit(2);
}
echo "\nImport Telephone Prefixes: ";
$ln = 0;
while (($data = fgetcsv($handle, 5000, ",")) !== false) {
$ln++;
if ($ln % 250 == 0) {
echo "#";
}
$prefix = trim($data[0]);
$nation = trim($data[1]);
$type = trim($data[2]);
$operator = trim($data[3]);
if ($merge) {
mergeCompletePrefix($prefix, $nation, $type, $operator);
} else {
createCompletePrefix($prefix, $nation, $type, $operator);
}
}
}
function addNewTelephonePrefixes()
{
loadPrefixes("scripts/world_prefix_table.csv", TRUE);
}
/**
* @return $defaultParamsId created
*/
function createDefaultParams()
{
global $input_line;
$c = new Criteria();
$c->add(ArParamsPeer::IS_DEFAULT, TRUE);
$params = ArParamsPeer::doSelectOne($c);
if (is_null($params)) {
$params = new ArParams();
$params->setIsDefault(TRUE);
$params->setName("Default");
$params->setIsDefault(TRUE);
$params->setServiceName("Asterisell");
$params->setServiceProviderWebsite("http://voipinfo.example.com");
$params->setLegalWebsite("http://www.example.com");
$params->setServiceProviderEmail("info@example.com");
$params->setLogoImage("asterisell.png");
$params->setLogoImageInInvoices("asterisell.jpeg");
$params->setSlogan("open source web application for rating, showing to customers, and billing Asterisk VoIP calls.");
$params->setFooter("<center>For info contact:<a href=\"mailto:info@example.com\">info@example.com</a></center>");
$params->setUserMessage("");
$params->setVatTaxPercAsPhpDecimal("20");
$params->setLegalName("ACME Example VoIP Corporation");
$params->setVat("WRLD12345678909876");
$params->setLegalAddress("Street By Example");
$params->setLegalCity("Soliera");
$params->setLegalZipcode("41019");
$params->setLegalStateProvince("Modena");
$params->setLegalCountry("Italy");
$params->setLegalEmail("acme@example.com");
$params->setLegalPhone("+0 000-0000");
$params->setSenderNameOnInvoicingEmails("ACME Corporation");
$params->setInvoicingEmailAddress("sales@acme.example.com");
$params->setSmtpHost("");
$params->setSmtpPort("");
$params->setSmtpUsername("");
$params->setSmtpPassword("");
$params->setSmtpEncryption("");
$params->setSmtpReconnectAfterNrOfMessages("");
$params->setSmtpSecondsOfPauseAfterReconnection(0);
$params->save();
}
return $params->getId();
}
/**
* Return a list($defaultParamsId, $normalCategoryId, $discountedCategoryId, $defaultVendorId)
*/
function initWithDefaultData()
{
try {
deleteAllData();
// Create dates starting from current time.
// This allows to create more "user friendly"
// demo-data.
//
$past = pastDays(365 * 2);
// Create default params
//
echo "\nCreating default Params";
$defaultParamsId = createDefaultParams();
echo "\nCreating Categories and Parties";
$r = new ArRateCategory();
$r->setName("Normal");
$r->save();
$normalCategoryId = $r->getId();
$r = new ArRateCategory();
$r->setName("Discounted");
$r->save();
$discountedCategoryId = $r->getId();
$r = new ArParty();
$r->setCustomerOrVendor("V");
$r->setName("Default Vendor");
$r->setExternalCrmCode("");
$r->setArRateCategoryId(null);
$r->setArParamsId($defaultParamsId);
$r->save();
$defaultVendorId = $r->getId();
echo "\nCreating Rates";
// ANSWERED --> outgoing
//
$rm = new PhpCDRProcessing();
$rm->dstChannel = "";
$rm->disposition = "ANSWERED";
$rm->amaflags = 0;
$rm->destinationType = DestinationType::outgoing;
$r = new ArRate();
$r->setDestinationType(DestinationType::unprocessed);
$r->setArRateCategoryId(null);
$r->setArPartyId(null);
$r->setStartTime($past);
$r->setEndTime(null);
$r->setIsException(false);
$r->setPhpClassSerialization(serialize($rm));
$r->save();
$rm = new PhpCDRProcessing();
$rm->dstChannel = "";
$rm->disposition = "ANSWERED";
$rm->amaflags = 3;
$rm->destinationType = DestinationType::outgoing;
$r = new ArRate();
$r->setDestinationType(DestinationType::unprocessed);
$r->setArRateCategoryId(null);
$r->setArPartyId(null);
$r->setStartTime($past);
$r->setEndTime(null);
$r->setIsException(false);
$r->setPhpClassSerialization(serialize($rm));
$r->save();
// NO ANSWERED --> IGNORED
//
$rm = new PhpCDRProcessing();
$rm->dstChannel = "";
$rm->disposition = "NO ANSWERED";
$rm->amaflags = 5;
$rm->destinationType = DestinationType::ignored;
$r = new ArRate();
$r->setDestinationType(DestinationType::unprocessed);
$r->setArRateCategoryId(null);
$r->setArPartyId(null);
$r->setStartTime($past);
$r->setEndTime(null);
$r->setIsException(false);
$r->setPhpClassSerialization(serialize($rm));
$r->save();
// NO ANSWER --> IGNORED
//
$rm = new PhpCDRProcessing();
$rm->dstChannel = "";
$rm->disposition = "NO ANSWER";
$rm->amaflags = 5;
$rm->destinationType = DestinationType::ignored;
$r = new ArRate();
$r->setDestinationType(DestinationType::unprocessed);
$r->setArRateCategoryId(null);
$r->setArPartyId(null);
$r->setStartTime($past);
$r->setEndTime(null);
$r->setIsException(false);
$r->setPhpClassSerialization(serialize($rm));
$r->save();
// BUSY --> IGNORED
//
$rm = new PhpCDRProcessing();
$rm->dstChannel = "";