forked from fearless359/simpleinvoices
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
649 lines (581 loc) · 24 KB
/
index.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
<?php /** @noinspection PhpUndefinedFieldInspection */
use Inc\Claz\Biller;
use Inc\Claz\CheckPermission;
use Inc\Claz\Config;
use Inc\Claz\Customer;
use Inc\Claz\Install;
use Inc\Claz\Invoice;
use Inc\Claz\Funcs;
use Inc\Claz\Log;
use Inc\Claz\PdoDbException;
use Inc\Claz\Product;
use Inc\Claz\Setup;
use Inc\Claz\SiAcl;
use Inc\Claz\SiError;
use Inc\Claz\SqlPatchManager;
use Inc\Claz\Util;
/*
* Script: index.php
* Main controller file for SimpleInvoices
* License:
* GPL v3 or above
*/
// **********************************************************
// The include configs and requirements stuff section - START
// **********************************************************
$lclPath = get_include_path() .
PATH_SEPARATOR . "./library/" .
PATH_SEPARATOR . "./include/";
if (set_include_path($lclPath) === false) {
echo "<h1>Unable to set include path. Request terminated.</h1>";
exit();
}
require_once 'vendor/autoload.php';
Util::allowDirectAccess();
$module = isset($_GET['module']) ? Util::filenameEscape($_GET['module']) : "";
$view = isset($_GET['view']) ? Util::filenameEscape($_GET['view']) : "";
$action = isset($_GET['case']) ? Util::filenameEscape($_GET['case']) : "";
$apiRequest = $module == 'api';
require_once 'config/define.php';
session_name(SESSION_NAME);
session_start();
/***********************************************************************
* Make sure the public and tmp directories exist and are writeable.
***********************************************************************/
if (!file_exists('./public')) {
mkdir('./public');
} elseif (!is_writable('./public')) {
SiError::out('notWritable', 'directory', './public');
}
if (!file_exists('./tmp')) {
mkdir('./tmp');
} elseif (!is_writable('./tmp')) {
SiError::out('notWritable', 'directory', './tmp');
}
if (!file_exists('./tmp/database_backups')) {
mkdir('./tmp/database_backups');
} elseif (!is_writable('tmp/database_backups')) {
SiError::out('notWritable', 'file', './tmp/database_backups');
}
if (!file_exists('./tmp/cache')) {
mkdir('./tmp/cache');
} elseif (!is_writable('tmp/cache')) {
SiError::out('notWritable', 'file', './tmp/cache');
}
if (!file_exists('./tmp/template_c')) {
mkdir('./tmp/template_c');
} elseif (!is_writable('tmp/template_c')) {
SiError::out('notWritable', 'file', './tmp/template_c');
}
if (!file_exists('./tmp/log')) {
mkdir('./tmp/log');
} elseif (!is_writable('tmp/log')) {
SiError::out('notWritable', 'directory', './tmp/log');
}
if (!file_exists('./tmp/pdf_tmp')) {
mkdir('./tmp/pdf_tmp');
} elseif (!is_writable('tmp/pdf_tmp')) {
SiError::out('notWritable', 'directory', './tmp/pdf_tmp');
}
try {
$setup = new Setup(CONFIG_SECTION, empty($module));
$config = $setup->getConfigIni();
$pdoDb = $setup->getPdoDb();
$pdoDbAdmin = $setup->getPdoDbAdmin();
} catch (Exception $exp) {
// Error already reported so simply exit.
exit();
}
// globals set in the init.php logic
$databaseBuilt = false;
$databasePopulated = false;
// It's possible that we are in the initial install mode. If so, set
// a flag, so we won't terminate on an "Unknown database" error later.
$databaseBuilt = $pdoDbAdmin->checkTableExists('biller');
$timeout = 0;
if ($apiRequest) {
if (!$databaseBuilt) {
exit("Database not built. Can't run batch job.");
}
} elseif ($databaseBuilt) {
// If session_timeout is defined in the database, use it. If not
// set it to the 60-minute default.
try {
$pdoDbAdmin->addSimpleWhere('name', 'session_timeout');
$pdoDbAdmin->setSelectList('value');
$rows = $pdoDbAdmin->request('SELECT', 'system_defaults');
$timeout = empty($rows) ? 0 : intval($rows[0]['value']);
Log::out("index.php - session_timeout loaded[$timeout]");
} catch (PdoDbException $pde) {
$timeout = 0;
}
}
// Force api request timeout to 60 seconds.
if ($apiRequest || $timeout <= 0) {
$timeout = 60;
}
Util::sessionTimeout($timeout);
// Will be set in the following init.php call to extensions that are enabled.
$extNames = [];
$helpImagePath = "images/";
// formatter:off
include_once "include/init.php";
global $unappliedPatches,
$earlyExit,
$extNames,
$LANG,
$patchCount,
$path,
$PATTERNS,
$PLACEHOLDERS,
$siUrl,
$smarty,
$smartyOutput;
// formatter:on
Log::out("index.php - After init.php - module[$module] view[$view] " .
"patchCount[$patchCount] unappliedPatches[$unappliedPatches]");
foreach ($extNames as $extName) {
if (file_exists("extensions/$extName/include/init.php")) {
/** @noinspection PhpIncludeInspection */
$extInitFile = "extensions/$extName/include/init.php";
Log::out("index.php - extInitFile[$extInitFile]");
require_once $extInitFile;
}
}
Log::out("index.php - After processing init.php for extensions");
// **********************************************************
// The include configs and requirements stuff section - END
// **********************************************************
$smarty->assign("LANG", $LANG);
$smarty->assign("PATTERNS", $PATTERNS);
$smarty->assign("PLACEHOLDERS", $PLACEHOLDERS);
$smarty->assign("config", $config);
$smarty->assign("configFile", Config::CUSTOM_CONFIG_FILE);
$smarty->assign("enabled", [$LANG['disabled'], $LANG['enabled']]);
$smarty->assign("ext_names", $extNames);
$smarty->assign("helpImagePath", $helpImagePath);
$smarty->assign("module", $module);
$smarty->assign("siUrl", $siUrl);
$smarty->assign("view", $view);
// Menu - hide or show menu
if (!isset($menu)) {
$menu = true;
}
// Check for any unapplied SQL patches
Log::out("index.php - module[$module] view[$view] " .
"databaseBuilt[$databaseBuilt] databasePopulated[$databasePopulated]");
if ($module == "options" && $view == "database_sqlpatches") {
SqlPatchManager::donePatchesMessage();
} else {
// Check that database structure has been built and populated.
$applyDbPatches = true;
if (!$databaseBuilt) {
$module = "install";
$view == "structure" ? $view = "structure" : $view = "index";
$applyDbPatches = false; // do installer
} elseif (!$databasePopulated) {
// If no patches have been applied, then assume loading database content from scratch.
if ($patchCount == 0) {
$module = "install";
$view == "essential" ? $view = "essential" : $view = "structure";
$applyDbPatches = false; // do installer
}
} elseif ($module == 'install' && $view == 'sample_data') {
$applyDbPatches = false;
}
Log::out("index.php - applyDbPatches[$applyDbPatches]");
// See if we need to verify patches have been loaded.
if ($applyDbPatches) {
Log::out("index.php - authenticationEnabled[{$config['authenticationEnabled']}] ".
"\$_SESSION['id'][{$_SESSION['id']}]");
// If default user or an active session exists, proceed with check.
if ($config['authenticationEnabled'] == DISABLED || isset($_SESSION['id'])) {
// Check if there are patches to process
if ($unappliedPatches > 0 ) {
$module = "options";
$view = "database_sqlpatches";
Log::out("index.php - Unapplied patches found - action[$action]");
if ($action == "run") {
SqlPatchManager::runPatches();
} else {
SqlPatchManager::listPatches();
}
$menu = false;
} else {
Log::out("index.php - all patches applied - module[$module] view[$view]");
// All patches have been applied. Now check to see if the database has been set up.
// It is considered setup when there is at least one biller, one customer and one product.
// If it has not been set up, allow the user to add a biller, customer, product or to
// modify the setting options.
$noInvoices = Invoice::count() == 0;
if (!empty($module)) {
$stillDoingSetup = false;
if (($view != 'create' || $module != 'billers' && $module != 'customers' && $module != 'products') &&
($module != 'system_defaults' || $view != 'manage' && $view != 'edit' && $view != 'save')) {
if ($noInvoices) {
$stillDoingSetup = true;
if (Biller::count() > 0 && Customer::count() > 0 && Product::count() > 0) {
// Biller, Customer and Product set up but no invoices. Check to
// see if this is the first time we've encountered this. If it is
// the first time, then set $stillDoingSetup to true.
$stillDoingSetup = Install::setComplete();
}
}
}
} else {
$stillDoingSetup = true;
}
Log::out("index.php - stillDoingSetup[$stillDoingSetup]");
if ($stillDoingSetup) {
try {
if ($noInvoices) {
$module = "index";
$view = "index";
} else {
Invoice::updateAging();
$module = "invoices";
$view = "manage";
}
} catch (PdoDbException $pde) {
error_log("index.php: Unable to get Invoice count to set default module and view. Error: " . $pde->getMessage());
exit("Unable to set install complete flag. See error log for additional information.");
}
}
}
}
}
}
Log::out("index.php - module[" . ($module ?? "") . "] view[" . ($view ?? "") . "] action[" . ($action ?? "") .
"] id[" . ($_GET['id'] ?? "") . "] menu[$menu]");
$smarty->assign('menu', $menu);
if (!CheckPermission::isAllowed($module, $view)) {
$role = SiAcl::getSessionRole();
Log::out("index.php - CheckPermission::isAllowed('$module', '$view') returned false for role[$role].");
$module = "errorPages";
$view = "401";
}
// This logic is for the default_invoice where the invoice "template" (aka record)
// is used to make the new invoice.
if ($module == "invoices" && strstr($view, "template")) {
// Get the default module path php if there aren't any for enabled extensions.
$myPath = Util::getCustomPath("invoices/template", 'module');
Log::out("index.php - default invoice template path[$myPath]");
if (!empty($myPath)) {
/** @noinspection PhpIncludeInspection */
include_once $myPath;
}
exit();
}
Log::out("index.php - After invoices/template");
// Check for "api" module or a "xml" or "ajax" "page request" (aka view)
if ($apiRequest || strstr($view, "xml") || preg_match("/.*[Aa]jax/", $view)) {
$extensionXml = 0;
foreach ($extNames as $extName) {
if (file_exists("extensions/$extName/modules/$module/$view.php")) {
/** @noinspection PhpIncludeInspection */
include "extensions/$extName/modules/$module/$view.php";
$extensionXml++;
}
}
// Load default if none found for enabled extensions.
$myPath = Util::getCustomPath("$module/$view", 'module');
if ($extensionXml == 0 && isset($myPath)) {
/** @noinspection PhpIncludeInspection */
include $myPath;
}
exit(0);
}
Log::out("index.php - After api/xml or ajax");
// **********************************************************
// Prep the page - load the header stuff - START
// **********************************************************
$extensionJqueryFiles = "";
foreach ($extNames as $extName) {
$path = "extensions/$extName/include/js/$extName.jquery.ext.js";
if (file_exists($path)) {
$extensionJqueryFiles .= "<script src='$path'></script>";
}
}
$smarty->assign("extension_jquery_files", $extensionJqueryFiles);
Log::out("index.php - After extension_jquery_files");
// Load any hooks that are defined for extensions
foreach ($extNames as $extName) {
if (file_exists("extensions/$extName/templates/default/hooks.tpl")) {
$smarty->$smartyOutput("extensions/$extName/templates/default/hooks.tpl");
}
}
// Load standard hooks file. Note that any module hooks loaded will not be
// impacted by loading this file.
$smarty->$smartyOutput("custom/hooks.tpl");
Log::out("index.php - After custom/hooks.tpl");
if (!in_array($module . "_" . $view, $earlyExit)) {
$extensionHeader = 0;
foreach ($extNames as $extName) {
$phpFile = "extensions/$extName/templates/default/header.tpl";
if (file_exists("extensions/$extName/templates/default/header.tpl")) {
$smarty->$smartyOutput("extensions/$extName/templates/default/header.tpl");
$extensionHeader++;
}
}
if ($extensionHeader == 0) {
$myPath = Util::getCustomPath('header');
if (isset($myPath)) {
$smarty->$smartyOutput($myPath);
}
}
}
Log::out("index.php - After header.tpl");
// **********************************************************
// Prep the page - load the header stuff - END
// **********************************************************
// **********************************************************
// Include php file for the requested page section - START
// **********************************************************
// See https://simpleinvoices.group/howto page extension topic.
$extensionPhpInsertFiles = [];
$performExtensionPhpInsertions = $module == 'system_defaults' && $view == 'edit';
$extensionPhpFile = 0;
foreach ($extNames as $extName) {
$phpFile = "extensions/$extName/modules/$module/$view.php";
if (file_exists($phpFile)) {
Log::out("index.php - extension module exists - phpFile[$phpFile]");
// If $performExtensionPhpInsertions is true, then the extension php
// file content is to be included in the standard php file. Otherwise,
// the file is a replacement for the standard php file.
if ($performExtensionPhpInsertions) {
// @formatter:off
$vals = [
"file" => $phpFile,
"module" => $module,
"view" => $view
];
$extensionPhpInsertFiles[$extName] = $vals;
// @formatter:on
} else {
/** @noinspection PhpIncludeInspection */
include $phpFile;
$extensionPhpFile++;
}
}
}
Log::out("index.php - After extension_php_insert_files, etc.");
// Determine reports template path for an extension or standard path.
if ($module == "reports" && ($view == "export" || $view == "email")) {
$path = '';
foreach ($extNames as $extName) {
$phpFile = "extensions/$extName/templates/default/reports/$view.php";
if (file_exists($phpFile)) {
$path = "extensions/$extName/templates/default/reports";
}
}
if (empty($path)) {
$path = 'templates/default/reports/';
}
$smarty->assign('path', $path);
Log::out("index.php - reports export/email path[$path]");
}
if ($extensionPhpFile == 0) {
$myPath = Util::getCustomPath("$module/$view", 'module');
if (isset($myPath)) {
Log::out("index.php - my_path[$myPath]");
/** @noinspection PhpIncludeInspection */
include $myPath;
}
}
// **********************************************************
// Include php file for the requested page section - END
// **********************************************************
if ($module == "export" || $view == "export") {
Log::out("index.php - path[$path] Before export exit");
exit(0);
}
Log::out("index.php - After export/export exit");
// **********************************************************
// Post load javascript files - START
// NOTE: This is loaded after the .php file so that it can
// use script load for the .php file.
// **********************************************************
foreach ($extNames as $extName) {
if (file_exists("extensions/$extName/include/js/$extName.post_load.jquery.ext.js.tpl")) {
$smarty->$smartyOutput("extensions/$extName/include/js/$extName.post_load.jquery.ext.js.tpl");
}
}
// NOTE: Don't load the default file if we are processing an authentication "auth" request.
// if ($extensionPostLoadJquery == 0 && $module != 'auth') {
if ($module != 'auth' && !($module == 'payments' && $view == 'print')) {
$smarty->$smartyOutput("include/js/post_load.jquery.ext.js.tpl");
}
Log::out("index.php - post_load. menu[$menu]");
// **********************************************************
// Post load javascript files - END
// **********************************************************
// **********************************************************
// Main: Custom menu - START
// **********************************************************
if ($menu) {
// If no matching section is found, the file will NOT be inserted.
$myPath = Util::getCustomPath('menu');
if (isset($myPath)) {
Log::out("index.php - menu my_path[$myPath]");
try {
$menuTpl = $smarty->fetch($myPath);
} catch (Exception $exp) {
exit("Unable to fetch menu path. Error: " . $exp->getMessage());
}
$lines = [];
$sections = [];
Funcs::menuSections($menuTpl, $lines, $sections);
$menuTpl = Funcs::mergeMenuSections($extNames, $lines, $sections);
echo $menuTpl;
}
}
Log::out("index.php - After menuTpl processed");
// **********************************************************
// Main: Custom menu - END
// **********************************************************
// **********************************************************
// Main: Custom layout - START
// **********************************************************
if (!in_array($module . "_" . $view, $earlyExit)) {
$extensionMain = 0;
foreach ($extNames as $extName) {
if (file_exists("extensions/$extName/templates/default/main.tpl")) {
$smarty->$smartyOutput("extensions/$extName/templates/default/main.tpl");
$extensionMain++;
}
}
if ($extensionMain == "0") {
$myPath = Util::getCustomPath('main');
if (isset($myPath)) {
$smarty->$smartyOutput($myPath);
}
}
}
Log::out("index.php - After main.tpl");
// **********************************************************
// Main: Custom layout - END
// **********************************************************
// **********************************************************
// Smarty template load - START
// **********************************************************
$extensionTemplates = 0;
$myTplPath = '';
$path = '';
$realPath = '';
// For extensions with a report, this logic allows them to be inserted into the
// report menu (index.tpl) without having to replicate the content of that
// file. There two ways to insert content; either as a new menu section or as
// an appendage to an existing section. There are examples of each of these.
// Refer to the "expense" extension report index.tpl file for insertion of
// a new menu section. Note the "data-section" with the "BEFORE" entry. This
// tells the program to insert the menu before the menu section with the
// "$LANG.xxxxx" value that appears following the "BEFORE" statement. To
// append to an existing menu section, refer to the report index.tpl file
// for the "past_due_report" extension. Note the "data-section" attribute
// in the "<span ...>" tag. This tells the program to insert the report
// menu item at the end of the section with "$LANG.xxxxx" value assigned
// to the attribute.
$extensionInsertionFiles = [];
$performExtensionInsertions =
$module == 'reports' && $view == 'index' ||
$module == 'system_defaults' && $view == 'manage';
Log::out("index.php - performExtensionInsertions[$performExtensionInsertions]");
Log::out("index.php - extNames: " .print_r($extNames, true));
foreach ($extNames as $extName) {
if ($extName == "core") {
continue;
}
$tplFile = "extensions/$extName/templates/default/$module/$view.tpl";
Log::out("index.php - extension tplFile[$tplFile]");
if (file_exists($tplFile)) {
// If $performExtensionInsertions is true, the $path and
// $extensionTemplates are not set/incremented intentionally.
// The logic runs through the normal report template logic
// with the index.tpl files for each one of the extensions
// reports will be loaded for the section it goes in.
if ($performExtensionInsertions) {
$content = file_get_contents($tplFile);
$type = "";
if (($pos = strpos($content, 'data-section="')) === false) {
$section = $smarty->tpl_vars['LANG']->value['other'];
} else {
$pos += 14;
$str = substr($content, $pos);
$exp = "^BEFORE \{\$LANG\.";
if (preg_match($exp, $str)) {
$pos += 14;
$type = "BEFORE ";
} else {
$pos += 7;
}
$end = strpos($content, '}', $pos);
$len = $end - $pos;
$langElement = substr($content, $pos, $len);
$section = $smarty->tpl_vars['LANG']->value[$langElement];
}
// @formatter:off
$vals = [
"file" => $tplFile,
"module" => $module,
"section" => $type . $section
];
$extensionInsertionFiles[] = $vals;
// @formatter:on
} else {
$path = "extensions/$extName/templates/default/$module/";
$realPath = "templates/default/$module/";
$myTplPath = $tplFile;
$extensionTemplates++;
Log::out("index.php - extension path[$path] realPath[$realPath] myTplPath[$myTplPath]");
}
}
}
// TODO: if more than one extension has a template for the requested file, that's trouble :-(
// This won't happen to the standard menu.tpl and system_defaults menu.tpl given
// changes implemented in this file for them. Similar changes should be implemented for
// other templates as needed.
if ($extensionTemplates == 0) {
$myTplPath = Util::getCustomPath("$module/$view");
if (isset($myTplPath)) {
$path = dirname($myTplPath) . '/';
$realPath = $path;
$extensionTemplates++;
}
}
Log::out("index.php - final path[$path] realPath[$realPath] myTplPath[$myTplPath]");
$smarty->assign("extension_insertion_files", $extensionInsertionFiles);
$smarty->assign("perform_extension_insertions", $performExtensionInsertions);
// If this is not an extension, $path and $realPath are the same. If it is an extension,
// $path is relative to the extension and $realPath is relative to the standard library path.
$smarty->assign("path", $path);
$smarty->assign("realPath", $realPath);
Log::out("index.php - path[$path] my_tpl_path[$myTplPath] realPath[$realPath]");
if (!empty($myTplPath)) {
$smarty->$smartyOutput($myTplPath);
}
// If no smarty template - add message
if ($extensionTemplates == 0) {
error_log("NO TEMPLATE!!! for module[$module] view[$view]");
}
// **********************************************************
// Smarty template load - END
// **********************************************************
// **********************************************************
// Footer - START
// **********************************************************
if (!in_array($module . "_" . $view, $earlyExit)) {
$extensionFooter = 0;
foreach ($extNames as $extName) {
if (file_exists("extensions/$extName/templates/default/footer.tpl")) {
$smarty->$smartyOutput("extensions/$extName/templates/default/footer.tpl");
$extensionFooter++;
}
}
if ($extensionFooter == 0) {
$smarty->$smartyOutput(Util::getCustomPath('footer'));
}
}
Log::out("index.php - At END\n\n");
// **********************************************************
// Footer - END
// **********************************************************