/
asterisell.php
2003 lines (1659 loc) · 65.9 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
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2009-2019 Massimo Zaniboni <massimo.zaniboni@asterisell.com>
////////////////////////////////////
// INIT ENVIRONMENT AND CALL MAIN //
////////////////////////////////////
//
// Manage Debug Mode and other activation flags.
//
/**
* Set usually to false.
* Set to true in case of run-time errors that must be intercepted.
*/
$debugMode = false;
/**
* @param string $script
* @param string $line
* @param string $message
*/
function assert_callback($script, $line, $message)
{
echo 'You have a design error in your script ', $script, ': line ' . $line;
echo 'message: ' . $message;
exit(1);
}
assert_options(ASSERT_ACTIVE, true);
assert_options(ASSERT_BAIL, true);
assert_options(ASSERT_WARNING, true);
assert_options(ASSERT_QUIET_EVAL, false);
assert_options(ASSERT_CALLBACK, 'assert_callback');
require_once(dirname(__FILE__) . '/config/ProjectConfiguration.class.php');
if ($debugMode == true || ($argc > 1 && trim($argv[1]) === "debug")) {
if ($debugMode) {
echo "\nWARNING: debug mode activate.";
}
$configuration = ProjectConfiguration::getApplicationConfiguration('asterisell', 'dev', true);
} else {
$configuration = ProjectConfiguration::getApplicationConfiguration('asterisell', 'prod', false);
}
sfContext::createInstance($configuration);
// An external job must set explicitely the culture, because it isn't running
// inside a request.
$i18nDir = dirname(getAsterisellCompleteRootDirectory()) . '/admin/apps/asterisell/i18n';
$culture = trim(sfConfig::get('app_culture'));
$I18N = sfContext::getInstance()->getI18N();
$i18nConversions = array($i18nDir);
$I18N->setMessageSource($i18nConversions, $culture);
$I18N->setCulture($culture);
$databaseManager = new sfDatabaseManager($configuration);
$databaseManager->loadConfiguration();
/**
* Special file where read user input.
*/
$input_line = fopen('php://stdin', 'r');
$exitCode = main($argc, $argv);
exit($exitCode);
/**
* @return void
*/
function displayUsage()
{
$str = <<<HELP
Installation/development operations
-----------------------------------
php asterisell.php activate
Clear cache, set directories, and other common and safe management operations.
php asterisell.php activate users [db-root-user] [db-root-password]
Create again the MySQL users for accessing the application.
NOTE: if a new name is used, then old users had to be deleted manually.
php asterisell.php make-derived-files
Internal command.
php asterisell.php silently-activate
Internal command.
php asterisell.php install
Initial install with empty database.
php asterisell.php install-demo
To call after "install" command for installing demo data.
php asterisell.php install-views-and-procedures
Install views, procedures, and calls rating procedures, without deleting data. Useful in case of restore from an instance with errors, or for updating of the code.
php asterisell.php run [upgrade-jobs|db-upgrade-jobs]
Execute only upgrading jobs. Called from the administrator.
php asterisell.php data admin <some-password>
Add an "admin" user, with the specified password.
php asterisell.php data unbilled YY-MM-DD hh:mm:ss
All CDRS befor this calldate are considered as already billed.
php asterisell.php data merge-telephone-prefixes
Add new telephone prefixes to the telephone prefix table, reading them from "scripts/world_prefix_table.csv".
php asterisell.php dev remove-model <SomeModelClassName>
Remove from lib directory, the occurrences of the model.
php asterisell.php dev update-customizations
Update the description of rate formats, and other settings that are likely to be changed during development.
php asterisell.php dev support-user <password>
Create or modify an admin support user, with login "support", and the specified password.
php asterisell.php dev test-import-cdrs [SOME-FILE-NAME].manual-importing__v1__[SOME-FORMAT]__[SOME-VERSION]
php asterisell.php dev test-import-cdrs [SOME-FILE-NAME].[YYYY-MM-DD].manual-importing__v1__[SOME-FORMAT]__[SOME-VERSION]
Simulate (without writing to the DB) the importing of CDRS from an UTF8 file, in the specified SOME-FORMAT__SOME-VERSION.
Show result in a file with the same name of input-file, and suffix ".out"
php asterisell.php debug stress-rerating [MAX-DAYS-IN-THE-PAST] [HOURS]
Rerate starting from the specified days in the past, simulating new CDRS every specified hours, using random time-frames, and checking for errors in grouped cached CDRS.
php asterisell.php debug test <test-class> <test-method>
Called from regression test code for executing certain regression tests.
php asterisell.php debug some-code-test
Start some demo code, useful during development.
php asterisell.php debug regression-test <db-root-user> <db-root-password>
Execute unit tests on code.
php asterisell.php debug signal-critical-problem-in-the-code
Signal in the problem table, a critical problem in the code.
php asterisell.php run scheduled-jobs
Start job processor in silent mode, usually called from cron daemon.
php asterisell.php data update-cached-cdrs
Recalculate all daily totals, of the table ar_cached_cdrs, according the new content of ar_cdr.
Used only during development or maintenance, if some unusual operations corrupt the content of the table.
php asterisell.php debug send-test-email
Send a test email to the email address configured in Web UI Params.
Maintenance operations
----------------------
php asterisell.php cron [enable|disable|disable-for-upgrade]
Enable or disable the cron job processor: the application can be used for viewing old data, but not process new data
php asterisell.php app [enable|disable]
Disable application access for normal users, saying that the application is under maintenance.
php asterisell.php dev list-jobs
List scheduled jobs with related development notes.
php asterisell.php cron force-execution-of-all-jobs
At next job execution also postponed (maintenance) jobs will be executed.
php asterisell.php run jobs
Start job processor. Called from the administrator.
php asterisell.php debug jobs
Start job processor reporting problems on the command line and in the log/asterisell_dev.log file, and executing the rating engine in debug/test mode.
This mode is a lot slower, but it can detect more errors in the code.
php asterisell.php debug rerate [yyyy-mm-dd]
Schedule a rerate event. The CDRs will be rated at next execution of jobs.
If none calldate is specified, then all not yet billed CDRS are scheduled for rerate.
php asterisell.php debug rate [yyyy-mm-dd]
Rate immediately the CDRs from the specified calldate.
php asterisell.php debug debug-rate [yyyy-mm-dd]
Rate immediately the CDRs from the specified calldate, generating debug info.
NOTE: more accurate info is generated, but it is slower than normal rating.
php asterisell.php debug reset-rerate-event
Reset the scheduled rerate events.
Data operations
---------------
php asterisell.php data backup
Create a file with the dump of the database.
php asterisell.php data config-backup
Make a compact backup of the database, excluding CDRs data.
php asterisell.php data restore
Restore the application data, according the content of "data_files/messages/backup" directory.
This is the suggested way for restoring data.
After the execution of this command the content of the backup directory will be overwritten with new data.
php asterisell.php data export-organizations <file-name>
Export organizations to file-name.
php asterisell.php data import-organizations <file-name> [new]
Import organizations from an YAML file.
Specify "new" for considering all data as new data, also if the part-id is specified.
php asterisell.php data complete-reseller-export-code <reseller-code>
Given the code of a reseller, complete the export-code field of the children extensions, with the first value in extensions codes. Only extensions with an empty value are affected.
This is a sane default value, that can be used for extensions to export to resellers, in case a batch initialization is needed. These values can be specified individually also in the user interface.
php asterisell.php data delete-organization <id>
Given the id of an organization (the unique identifier in a URL like "view/id/123"), delete from the database. Useful in case of infinite loops in definition of an organization, and other bad configurations.
php asterisell.php data export-cdrs [cdr-provider-code] [cdr-format] [yyyy-mm-[dd]]
Without params, list the available cdr-provider-codes and cdr-format.
Use YYYY-MM for exporting all the CDRs of a month, and YYYY-MM-DD for exporting all the CDRs of a day.
php asterisels.php data export-rated-cdrs [yyyy-mm-dd]
Export rated CDRS in CSV format useful for reconciliation.
HELP;
echo $str;
showMaintananceMode();
}
////////////////////
// DATABASE TESTS //
////////////////////
/**
* @return bool TRUE if there is a safe connection to the database
*/
function isSafeReadConnection()
{
try {
$connection = Propel::getConnection();
$query = 'SELECT id FROM ar_cdr LIMIT 1';
$stm = $connection->prepare($query);
$stm->execute();
while ($stm->fetchColumn()) {
}
$stm->closeCursor();
return TRUE;
} catch (Exception $e) {
return FALSE;
}
}
/////////////////////
// DELETE DATABASE //
/////////////////////
/**
* @param PDO $c
* @param string $t
* @return void
*/
function myDelete($c, $t)
{
$query = "DELETE FROM $t";
$stmt = $c->prepare($query);
$stmt->execute();
}
////////////////////////////////////
// APPLICATION MANAGEMENT SECTION //
////////////////////////////////////
/**
* @param string $password
* @return void
*/
function addRootUser($password)
{
$defaultParamsId = ConfigureDefaultParamsAndSettings::getOrCreateDefaultParams();
$user = ArUserPeer::getRootUser();
if (!is_null($user)) {
$party = $user->getArParty();
if (!is_null($party)) {
$party->delete();
}
$user->delete();
}
$p = new ArParty();
$p->setName('admin');
$p->setIsActive(true);
$p->save();
$w = new ArUser();
$w->setLogin("admin");
$w->setClearPassword($password);
$w->setIsEnabled(true);
$w->setIsRootAdmin(true);
$w->setArParty($p);
$w->save();
// NOTE: additional roles and permissions to root user are added after permissions and roles
// are created.
echo "\nCreated \"admin\" user with password \"$password\".\n";
}
/**
* 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);
}
}
}
/**
* @param string $comment
* @param string $cmd
*/
function myExecute($comment, $cmd)
{
echo "\n$comment";
echo "\nexecute> $cmd\n";
system($cmd, $result);
}
/**
* @return void
*/
function explicitContinue()
{
global $input_line;
echo "\nPress Enter to continue...";
echo "\n";
trim(fgets($input_line, 1024));
}
/**
* Create an user.
* @param string $rootUser
* @param string $rootPassword
* @param string $database
* @param string $user
* @param string $password
* @param bool $isAdmin true if the created user is an admin user of the application,
* false if it is a normal customer.
*/
function createMySQLUser($rootUser, $rootPassword, $database, $user, $password, $isAdmin)
{
myExecute("Create database user '$user'", "mysql -u $rootUser --password=$rootPassword mysql -e \"CREATE USER IF NOT EXISTS $user@localhost IDENTIFIED BY '$password';\" ");
myExecute("Change $user password in case the user was already existing ", "mysql -u $rootUser --password=$rootPassword mysql -e \"ALTER USER $user@localhost IDENTIFIED BY '$password';\"");
if ($isAdmin) {
myExecute("Grant Access", "mysql -u $rootUser --password=$rootPassword mysql -e \"GRANT ALL ON $database.* TO $user@localhost;\"");
myExecute("Grant Load File Access", "mysql -u $rootUser --password=$rootPassword mysql -e \"GRANT FILE ON *.* TO $user@localhost;\"");
} else {
myExecute("Grant Access", "mysql -u $rootUser --password=$rootPassword mysql -e \"GRANT SELECT ON $database.* TO $user@localhost;\"");
myExecute("Grant Access", "mysql -u $rootUser --password=$rootPassword mysql -e \"GRANT SELECT, UPDATE ON $database.ar_report_to_read TO $user@localhost;\"");
myExecute("Grant Access", "mysql -u $rootUser --password=$rootPassword mysql -e \"GRANT INSERT ON $database.ar_user_change_password_request TO $user@localhost;\"");
myExecute("Grant Access", "mysql -u $rootUser --password=$rootPassword mysql -e \"REVOKE SELECT ON $database.ar_user_change_password_request FROM $user@localhost;\"");
}
}
/**
* @param string|null $rootUser
* @param string|null $rootPassword
* @return void
*/
function makeInstallCreateDatabase($rootUser = null, $rootPassword = null)
{
global $input_line;
list($database, $user, $password) = getDatabaseNameUserAndPassword(true);
$isInteractive = (is_null($rootUser) || is_null($rootPassword));
if ($isInteractive) {
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", "mysql -u$rootUser --password=$rootPassword -e 'CREATE DATABASE $database DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_bin;'");
myExecute("Init '$database' schema", "mysql -u $rootUser --password=$rootPassword $database < data/sql/lib.model.schema.sql");
makeInstallCreateUsers($rootUser, $rootPassword);
}
/**
* Create admin and customer users.
* @param string|null $rootUser
* @param string|null $rootPassword
* @return void
*/
function makeInstallCreateUsers($rootUser = null, $rootPassword = null)
{
global $input_line;
list($database, $user, $password) = getDatabaseNameUserAndPassword(true);
$isInteractive = (is_null($rootUser) || is_null($rootPassword));
if ($isInteractive) {
echo "\nEnter the name of MySQL administrator user, or another MySQL user that can create new users: ";
$rootUser = trim(fgets($input_line, 1024));
echo "\nEnter the MySQL password of the administrator user $rootUser: ";
$rootPassword = trim(fgets($input_line, 1024));
}
createMySQLUser($rootUser, $rootPassword, $database, $user, $password, true);
list($customerDatabase, $customerUser, $customerPassword) = getDatabaseNameUserAndPassword(false);
createMySQLUser($rootUser, $rootPassword, $customerDatabase, $customerUser, $customerPassword, false);
if ($isInteractive) {
explicitContinue();
}
makeActivate($isInteractive);
}
/**
* @param bool $isInteractive
* @param bool $onlyConfig
* @return string|null the created file, null if no file were created
*/
function makeDatabaseBackup($isInteractive = true, $onlyConfig = false)
{
global $input_line;
list($database, $user, $password) = getDatabaseNameUserAndPassword();
$onlyConfigTables = BackupConfigurations::getConfigurationTablesToIgnoreInOnlyConfigExport();
$options = ' ';
if ($onlyConfig) {
foreach ($onlyConfigTables as $t) {
$options .= " --ignore-table=$database.$t ";
}
}
$fileName = '/var/tmp/';
if ($onlyConfig) {
$fileName .= 'backup-only-config-' . date('Y-m-d_H-i-s') . '.sql';
} else {
$fileName .= 'backup-' . date('Y-m-d_H-i-s') . '.sql';
}
$fileName .= '.gz';
$cmd = "mysqldump -u $user --password=$password $database --no-tablespaces --single-transaction $options | gzip > $fileName";
$restoreCmd = "pv $fileName | gunzip | mysql -uroot -p" . $password . " " . $database;
if ($isInteractive) {
echo "\nThe database can be backuped using the command\n\n > $cmd";
echo "\nand restored using the command\n\n > $restoreCmd \n\n";
}
$r = system($cmd);
if ($r === FALSE) {
if ($isInteractive) {
echo "\nError during execution of command";
}
return null;
} else {
return $fileName;
}
}
/**
* @param bool $askPermission true for asking permission before restore
* @return true|string true if the restore is performed, false if it is aborted, and the error message in case of problems during restore.
*/
function makeDatabaseRestore($askPermission)
{
global $input_line;
$makeRestore = FALSE;
if ($askPermission) {
echo "\nIf you confirm, all the content of the *current database will be lost*, and replaced with the data in backup database directory. Are you sure? [yes/NO]\n";
$next_line = trim(fgets($input_line, 1024));
if ($next_line === "yes" || $next_line === "YES") {
$makeRestore = TRUE;
}
} else {
$makeRestore = TRUE;
}
if ($makeRestore) {
list($database, $user, $password) = getDatabaseNameUserAndPassword();
// Drop database, and install an empty copy.
echo "\n\nStart with an empty database.\n\n";
manageCommand_install(false, true);
echo "\n\nLoad configurations.\n\n";
$confRestore = new BackupConfigurations();
$errorMsg = $confRestore->restoreFromBackup();
if (!is_null($errorMsg)) {
return $errorMsg;
}
echo "\n\nLoad reports.\n\n";
$reportRestore = new BackupReports();
$errorMsg = $reportRestore->restoreFromBackup();
if (!is_null($errorMsg)) {
return $errorMsg;
}
echo "\n\nLoad Source CDRs.\n\n";
$cdrsRestore = new BackupSourceCDRS();
$errorMsg = $cdrsRestore->restoreFromBackup();
if (!is_null($errorMsg)) {
return $errorMsg;
}
echo "\n\nLoad CDRs.\n\n";
$cdrsRestore = new BackupCDRS();
$errorMsg = $cdrsRestore->restoreFromBackup();
if (!is_null($errorMsg)) {
return $errorMsg;
}
echo "\n\nUpdate ar_cached_cdrs and ar_cached_errors tables.\n\n";
if (!RateEngineService::executeUpdateAllCachedCDRS()) {
return "Error during updating of ar_cached_cdrs and ar_cached_errors table";
}
return true;
} else {
return false;
}
}
/**
* @param string $user
* @param bool $isAdmin
*/
function makeActivateDirs($user, $isAdmin)
{
if ($isAdmin) {
$preCmd = "cd " . getAsterisellCompleteAdminDirectory();
} else {
$preCmd = "cd " . getAsterisellCompleteUserDirectory();
}
$cmd = $preCmd . ' && chown -R ' . $user . ':' . $user . ' . ';
myExecute("Fix ownerships", $cmd);
$webWritableDirs = array(
'cache/',
'log/',
'web/',
'web/uploads/assets/'
);
$makeDirCmd = $preCmd . ' && mkdir -p ';
$chmodCmd = $preCmd . ' && chmod -R --silent ug+rwx,o-rwx ';
foreach ($webWritableDirs as $d) {
$makeDirCmd .= " $d ";
$chmodCmd .= " $d ";
}
myExecute("Create web-server working directories", $makeDirCmd);
myExecute("COPYRIGHT", $preCmd . ' && chmod --silent g+r COPYRIGHT');
if (!$isAdmin) {
executeSymfonyCC($isAdmin);
}
myExecute("Fix Permissions for web-server writable directories", $chmodCmd);
myExecute("Fix Permissions for web-server readable directories", "$preCmd && chmod -R --silent g+rx,g-w,u+rwx,o-rwx ext_libs/ apps/ lib/ config/ data/ symfony symfony.php");
myExecute("Fix Permissions for web-server not accessible directories", "$preCmd && chmod -R --silent u+rwx,go-rwx scripts/ updates/ data_files/ fabric_data/ development_tools/ symfony-patch/ README.md LICENSE asterisell.php");
// In EPEL the nginx user changed from "apache" to "nginx". So update it, if it is needed
myExecute("Fix nginx directories", "chown --silent :$user /var/lib/php/session /var/lib/php/wsdlcache /var/lib/dav");
}
/**
* In case of admin, filter only the conversion strings starting with "__".
* For customers copy the file.
* @param bool $isAdmin
* @param string $inFileName
* @param string $outFileName
*/
function convert_i18n_messages($isAdmin, $inFileName, $outFileName)
{
if ($isAdmin) {
$fp = fopen($inFileName, "r") or die("cannot open file $inFileName");
$str = fread($fp, filesize($inFileName));
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error parsing $inFileName");
$root = $xml->documentElement;
$toRemove = array();
$children = $root->firstChild->getElementsByTagName('source');
foreach ($children as $child) {
/**
* @var DOMElement $child
*/
$value = $child->textContent;
if ($value[0] == '_' && $value[1] == '_') {
// Node is valid
} else {
// Remove node in a later step otherwise iteration is broken...
$toRemove[] = $child->parentNode;
}
}
foreach ($toRemove as $child) {
/**
* @var DOMElement $child
*/
$root->firstChild->firstChild->removeChild($child);
}
$xml->save($outFileName) or die("cannot write file $outFileName");
fclose($fp);
} else {
myExecute('i18n support', 'cp -f ' . $inFileName . ' ' . $outFileName);
}
}
/**
* Signal as already imported some CSV file.
* @param string $csvFileName
* @return null if it is all ok, the error message otherwise
*/
function theseRemoteFilesAreAlreadyProcessed($csvFileName)
{
$conn = Propel::getConnection();
$handle = fopen($csvFileName, 'r');
if ($handle === FALSE) {
return "$csvFileName does not exists";
}
$nrOfCol = 2;
$ln = 0;
while (($data = fgetcsv($handle, 64000, ',', "\"", "\"")) !== FALSE) {
$ln++;
$nr = count($data);
if ($nr != $nrOfCol) {
return "at line $ln of $csvFileName there are $nr columns instead of expected $nrOfCol (" . print_r($data, TRUE) . ")";
} else {
$providerName = $data[0];
$remoteFileName = $data[1];
$stmt = $conn->prepare('SELECT id FROM ar_cdr_provider WHERE internal_name = ?');
$stmt->execute(array($providerName));
$providerId = null;
while (($rs = $stmt->fetch(PDO::FETCH_NUM)) !== false) {
$providerId = $rs[0];
}
$stmt->closeCursor();
if (is_null($providerId)) {
return "unknown provider $providerName at line $ln of $csvFileName";
}
$now = fromUnixTimestampToMySQLTimestamp(strtotime('+0 days'));
$stmt = $conn->prepare('INSERT INTO ar_remote_file SET ar_cdr_provider_id = ?, name = ?, receiving_date = ?');
$stmt->execute(array($providerId, $remoteFileName, $now));
$stmt->closeCursor();
echo "\n Virtually imported from $providerName : $remoteFileName";
}
}
return null;
}
/**
* @param bool $isInteractive
* @param bool $changePermissions
* @param bool $writeToDatabase
* @return void
*/
function makeActivate($isInteractive = true, $changePermissions = false, $writeToDatabase = true)
{
global $input_line;
makeDerivedFiles();
if ($writeToDatabase) {
$job = CustomCDRServices::getInstance()->getRateFormatsJob();
$job->process();
}
$user = getInstanceConfigValue('web_server_user');
makeActivateDirs($user, true);
if ($writeToDatabase) {
echo "\nWrite settings in table ar_global_permissions";
FieldsToShow::exportToGlobalSettingsTable();
}
//
// Manage the user instance
//
$toExclude = array(
'/cache/'
, '/log/'
, '/asterisell.php'
, '/config/databases.yml'
, '/data_files/'
, '/rating_tools/'
, '/doc/'
, '/fabric_data/'
, '/scripts/'
, '/symfony-patch/'
, '/updates/');
$toExclude_rsync = '';
foreach ($toExclude as $d) {
$toExclude_rsync .= " --exclude='$d' ";
}
myExecute("Update user instance", "rsync -ar --delete " . getAsterisellCompleteAdminDirectory() . "/ " . getAsterisellCompleteUserDirectory() . " " . $toExclude_rsync);
// NOTE: I'm using the final "/" for not copying the admin directory inside source
// Manage translation files, producing a version for admin and another for customer.
$destDir = '/apps/asterisell/i18n';
myExecute("i18n support", "mkdir " . getAsterisellCompleteUserDirectory() . $destDir);
myExecute("i18n support", "mkdir " . getAsterisellCompleteAdminDirectory() . $destDir);
$dir = getAsterisellCompleteAdminDirectory() . '/scripts/installation/i18n';
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
if (isSuffixOf('.xml', $filename)) {
$inFileName = $dir . '/' . $filename;
$outFileName1 = getAsterisellCompleteAdminDirectory() . $destDir . '/' . $filename;
$outFileName2 = getAsterisellCompleteUserDirectory() . $destDir . '/' . $filename;
convert_i18n_messages(true, $inFileName, $outFileName1);
convert_i18n_messages(false, $inFileName, $outFileName2);
}
}
closedir($dh);
myExecute("Publish manual", "ln -s " . getAsterisellCompleteAdminDirectory() . "/doc/manual/out " . getAsterisellCompleteAdminDirectory() . "/web/manual");
// NOTE: I'm using the final "/" for not copying the admin directory inside source
makeActivateDirs($user, false);
}
/**
* Do not require a database connection, and derive only files.
*/
function makeDerivedFiles()
{
myExecute("Create default directories", "mkdir -p cache ; mkdir -p log ; mkdir -p web/generated_graphs ; mkdir -p data_files/rsync_with_remote_servers ; mkdir -p data_files/messages/archive ; mkdir -p data_files/messages/backup ; mkdir -p data_files/messages/input ; mkdir -p data_files/messages/output ; mkdir -p data_files/messages/params ; mkdir -p data_files/messages/tmp ; mkdir -p updates ; mkdir -p web/uploads/assets");
$buildVersion = '';
CustomCDRServices::getInstance()->calledFromMakeActivate();
executeSymfonyCC();
myExecute("Regenerate modules depending from the new cache values.", "cd module_templates && php generate.php");
echo "\n";
}
/**
* Clear symfony cache.
*
* @param bool $isAdmin
* @return void
*/
function executeSymfonyCC($isAdmin = true)
{
// NOTE: I'm executing 'cc' instead of 'cache:clear' because it seems more complete
if ($isAdmin) {
$preCmd = 'cd ' . getAsterisellCompleteAdminDirectory() . ' && ';
} else {
$preCmd = 'cd ' . getAsterisellCompleteUserDirectory() . ' && ';
}
myExecute("Clear symfony cache, in order to enable new settings.", "$preCmd ./symfony cc");
}
function deleteLockTableExceptJobProcessor()
{
$conn = Propel::getConnection();
$stmt = $conn->prepare("DELETE FROM ar_lock WHERE NOT name = ?");
$stmt->execute(array(JobQueueProcessor::MUTEX_FILE_NAME));
}
///////////////////////
// SYSTEM MANAGEMENT //
///////////////////////
/**
* 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.
*
* @param bool $silent true for not showing messages
* @param bool $isDebugMode
* @return void
*/
function runJobProcessorQueue($silent, $isDebugMode)
{
$webDir = getAsterisellCompleteAdminDirectory() . DIRECTORY_SEPARATOR . 'web';
if (!$silent) {
echo "\nStarted Job Processor.";
}
// Execute the jobs immediately.
FixedJobProcessor::setWaitForScheduledRerate(false);
$processor = new JobQueueProcessor();
$r = $processor->process(!$silent, $isDebugMode);
if (!$silent) {
if (is_null($r)) {
echo "\nWARNING: Jobs were not processed, because lock can not be acquired.";
} else {
echo "\nJobs were executed.";
}
}
}
/**
* Wait some time, for free cron job, otherwise exit with error code.
*
* @param bool $silent
* @param bool $waitForLock true for waiting some time, until the lock is released
* @return JobQueueProcessor the processor with the lock.
*/
function waitCronJob($silent = false, $waitForLock = true)
{
$waitSeconds = 5;
$processor = new JobQueueProcessor();
$continue = TRUE;
if ($waitForLock) {
$retryCount = 20;
} else {
$retryCount = 1;
}
while ($continue) {
if ($retryCount <= 0) {
if (!$silent) {
echo "\nBAD: there are still running Jobs. The process can not continue.";
echo "\nYou could try with command `php asterisell.php app unlock-halted-jobs`\n";
}
exit(1);
}
$retryCount--;
$r = $processor->lock();
if ($r == TRUE) {
if (!$silent) {
echo "\nOk: there are no running Jobs, and other Jobs will be locked.\n";
}
$continue = FALSE;
} else {
if (!$silent) {
echo "\nWaiting: there are running Jobs. I will sleep for $waitSeconds seconds, and try other $retryCount times.\n";
}
sleep($waitSeconds);
}
}
return $processor;
}
/**
* NOTE: it is not mandatory
*
* @param JobQueueProcessor $processor
* @return void
*/
function unlockCronJob(JobQueueProcessor $processor)
{
$processor->unlock();
}
/**
* @return void
*/
function showMaintananceMode()
{
if (AsterisellUser::isCronLockedForMaintanance()) {
echo "\nWARNING:";
echo "\n Up to date all cron jobs are locked, because the application is in maintanance mode.";
echo "\n You can enable it again with command `php asterisell.php cron enable`";
echo "\n";
}
if (AsterisellUser::isAppLockedForMaintanance()) {
echo "\nWARNING:";
echo "\n Up to date Asterisell Web application can be accessed only from administrators, because it is in maintanance mode.";
echo "\n You can enable Asterisell again with command `php asterisell.php app enable`";
echo "\n";
}
}
///////////////
// UTILITIES //
///////////////
/**
* @param string $srcDir
* @param string $destDir
* @param string $readmeFile
*/
function moveCSVFiles($srcDir, $destDir, $readmeFile)
{
if (file_exists($destDir)) {
if (is_dir($destDir)) {
if (is_writable($destDir)) {
if ($handle = opendir($srcDir)) {
while (false !== ($file = readdir($handle))) {
if (is_file($srcDir . '/' . $file) && $file !== $readmeFile) {
$s = rename($srcDir . '/' . $file, $destDir . '/' . $file);
if ($s == FALSE) {
echo "\n!!!!!!!! error moving $file";
}
}
}
closedir($handle);
} else {
echo "$srcDir could not be opened.\n";
}
} else {
echo "\n$destDir is not writable!\n";
}
} else {
echo "\n$destDir is not a directory!\n";
}
} else {
echo "\n$destDir does not exist\n";
}
}
//////////////////////
// MAIN ENTRY POINT //
//////////////////////
/**
* @param int $argc
* @param array $argv
* @return int exit code
*/
function main($argc, $argv)