From 2227493a543e5a0bfaf0e0b8363065b91f53bb4d Mon Sep 17 00:00:00 2001 From: Kilian Saffran Date: Fri, 12 Mar 2021 09:31:40 +0100 Subject: [PATCH] v20210311 --- app/{static => }/css/fonts/appicons.eot | Bin app/{static => }/css/fonts/appicons.svg | 0 app/{static => }/css/fonts/appicons.ttf | Bin app/{static => }/css/fonts/appicons.woff | Bin app/{static => }/css/icons.css | 0 app/{static => }/css/theme.css | 0 app/data/reports/pot/content.html.mustache | 35 + app/data/reports/pot/footer.html.mustache | 47 + app/data/reports/pot/header.html.mustache | 20 + app/db.cgi | 394 - app/db.php | 54 +- app/{static => }/img/POT-logo.png | Bin app/{static => }/img/bg1.jpg | Bin app/{static => }/img/chrome.png | Bin app/{static => }/img/chrome.svg | 0 app/{static => }/img/edge.png | Bin app/{static => }/img/edge.svg | 0 .../img/favicon/android-icon-144x144.png | Bin .../img/favicon/android-icon-192x192.png | Bin .../img/favicon/android-icon-36x36.png | Bin .../img/favicon/android-icon-48x48.png | Bin .../img/favicon/android-icon-512x512.png | Bin .../img/favicon/android-icon-72x72.png | Bin .../img/favicon/android-icon-96x96.png | Bin .../img/favicon/apple-icon-114x114.png | Bin .../img/favicon/apple-icon-120x120.png | Bin .../img/favicon/apple-icon-144x144.png | Bin .../img/favicon/apple-icon-152x152.png | Bin .../img/favicon/apple-icon-180x180.png | Bin .../img/favicon/apple-icon-57x57.png | Bin .../img/favicon/apple-icon-60x60.png | Bin .../img/favicon/apple-icon-72x72.png | Bin .../img/favicon/apple-icon-76x76.png | Bin .../img/favicon/apple-icon-precomposed.png | Bin app/{static => }/img/favicon/apple-icon.png | Bin .../img/favicon/browserconfig.xml | 0 .../img/favicon/favicon-16x16.png | Bin .../img/favicon/favicon-32x32.png | Bin .../img/favicon/favicon-96x96.png | Bin app/{static => }/img/favicon/favicon.ico | Bin app/{static => }/img/favicon/manifest.json | 0 .../img/favicon/ms-icon-144x144.png | Bin .../img/favicon/ms-icon-150x150.png | Bin .../img/favicon/ms-icon-310x310.png | Bin .../img/favicon/ms-icon-70x70.png | Bin app/{static => }/img/firefox.svg | 0 app/{static => }/img/logo_512.png | Bin app/{static => }/img/logo_512_xx.png | Bin app/{static => }/img/opera.svg | 0 app/{static => }/img/potbg.jpg | Bin app/{static => }/img/poticon512.png | Bin app/{static => }/img/potlogowhite.svg | 0 app/{static => }/img/pottop.png | Bin app/{static => }/img/safari.png | Bin app/{static => }/img/safari.svg | 0 .../img/splashscreens/ipad_splash.png | Bin .../img/splashscreens/ipadpro1_splash.png | Bin .../img/splashscreens/ipadpro2_splash.png | Bin .../img/splashscreens/ipadpro3_splash.png | Bin .../img/splashscreens/iphone5_splash.png | Bin .../img/splashscreens/iphone6_splash.png | Bin .../img/splashscreens/iphoneplus_splash.png | Bin .../img/splashscreens/iphonex_splash.png | Bin .../img/splashscreens/iphonexr_splash.png | Bin .../img/splashscreens/iphonexsmax_splash.png | Bin app/{static => }/img/toplogo.png | Bin app/index.cgi | 160 - app/{static => }/js/app.js | 200 +- app/{static => }/js/dataform.js | 0 app/{static => }/js/report.js | 4 +- app/{static => }/js/request.js | 0 app/{static => }/js/sw.js | 40 +- app/{static => }/js/timecalc.js | 0 app/lib/POT/Period.php | 17 +- app/lib/POT/{Report.nousephp => Report.php} | 533 +- app/lib/POT/Staff.php | 53 +- app/lib/POT/TimeTracker.php | 8 +- app/lib/config.php | 14 +- app/lib/database.php | 5 +- app/lib/helpers.php | 14 + app/lib/session.php | 21 +- app/report.cgi | 102 - app/report.php | 97 +- app/synctimetrack.cgi | 69 - app/tmpl/browser.html | 6 +- app/tmpl/index.html | 84 +- app/tmpl/login.html | 52 +- app/tmpl/module/admin/index.html | 8 +- app/tmpl/module/index.html | 28 +- app/tmpl/module/index/index.js | 4 +- app/tmpl/module/periods/reportperiod.js | 132 +- app/tmpl/module/staff/dlg_staffcontract.html | 4 +- app/tmpl/module/staff/staff.js | 3 +- app/tmpl/module/timeclock.html | 9 + app/tmpl/module/vacancydays/vacancydays.html | 29 + app/tmpl/module/vacancydays/vacancydays.js | 68 + .../vendors/flatpickr/flatpickr.css | 0 .../vendors/flatpickr/flatpickr.js | 64 +- .../vendors/flatpickr/flatpickr.min.css | 0 .../vendors/flatpickr/flatpickr.min.js | 0 app/{static => }/vendors/flatpickr/ie.css | 0 app/{static => }/vendors/flatpickr/index.d.ts | 0 .../vendors/flatpickr/l10n/de.d.ts | 0 app/{static => }/vendors/flatpickr/l10n/de.js | 0 .../vendors/flatpickr/l10n/default.d.ts | 0 .../vendors/flatpickr/l10n/default.js | 0 .../vendors/flatpickr/l10n/fr.d.ts | 0 app/{static => }/vendors/flatpickr/l10n/fr.js | 0 .../vendors/flatpickr/l10n/index.d.ts | 0 .../vendors/flatpickr/l10n/index.js | 48 +- .../plugins/confirmDate/confirmDate.css | 0 .../plugins/confirmDate/confirmDate.d.ts | 0 .../plugins/confirmDate/confirmDate.js | 48 +- .../plugins/labelPlugin/labelPlugin.d.ts | 0 .../plugins/labelPlugin/labelPlugin.js | 0 .../flatpickr/plugins/minMaxTimePlugin.d.ts | 0 .../flatpickr/plugins/minMaxTimePlugin.js | 0 .../flatpickr/plugins/momentPlugin.d.ts | 0 .../vendors/flatpickr/plugins/momentPlugin.js | 0 .../flatpickr/plugins/monthSelect/index.d.ts | 0 .../flatpickr/plugins/monthSelect/index.js | 48 +- .../flatpickr/plugins/monthSelect/style.css | 0 .../plugins/monthSelect/tests.spec.d.ts | 0 .../flatpickr/plugins/rangePlugin.d.ts | 0 .../vendors/flatpickr/plugins/rangePlugin.js | 42 +- .../flatpickr/plugins/scrollPlugin.d.ts | 0 .../vendors/flatpickr/plugins/scrollPlugin.js | 0 .../plugins/weekSelect/weekSelect.d.ts | 0 .../plugins/weekSelect/weekSelect.js | 0 .../vendors/flatpickr/themes/airbnb.css | 0 .../vendors/flatpickr/types/globals.d.ts | 0 .../vendors/flatpickr/types/instance.d.ts | 0 .../vendors/flatpickr/types/locale.d.ts | 0 .../vendors/flatpickr/types/options.d.ts | 0 .../vendors/flatpickr/typings.d.ts | 0 .../vendors/flatpickr/utils/dates.d.ts | 0 .../vendors/flatpickr/utils/dom.d.ts | 0 .../vendors/flatpickr/utils/formatting.d.ts | 0 .../vendors/flatpickr/utils/index.d.ts | 0 .../vendors/flatpickr/utils/polyfills.d.ts | 0 app/{static => }/vendors/moment/locales.js | 0 .../vendors/moment/locales.min.js | 0 .../vendors/moment/locales.min.js.map | 0 .../vendors/moment/moment-with-locales.js | 0 .../vendors/moment/moment-with-locales.min.js | 0 .../moment/moment-with-locales.min.js.map | 0 app/{static => }/vendors/moment/moment.js | 0 app/{static => }/vendors/moment/moment.min.js | 0 .../vendors/moment/moment.min.js.map | 0 .../vendors/slimselect/slimselect.css | 0 .../vendors/slimselect/slimselect.min.css | 0 .../vendors/slimselect/slimselect.min.js | 0 .../slimselect/slimselect.min.orig.css | 0 .../vendors/slimselect/slimselect.min.xx.js | 0 .../vendors/slimselect/slimselect.scss | 0 .../vendors/slimselect/slimselect.xx.js | 0 .../vendors/suneditor/css/suneditor.min.css | 0 .../vendors/suneditor/suneditor.min.js | 0 .../vendors/tabulator/css/tabulator.css | 0 .../vendors/tabulator/css/tabulator.min.css | 0 .../tabulator/css/tabulator.min.css.map | 0 .../vendors/tabulator/css/tabulator_site.css | 0 .../tabulator/css/tabulator_site.min.css | 0 .../tabulator/css/tabulator_site.min.css.map | 0 .../tabulator/css/tabulator_site.min.orig.css | 0 .../vendors/tabulator/js/modules/accessor.js | 0 .../tabulator/js/modules/accessor.min.js | 0 .../vendors/tabulator/js/modules/ajax.js | 0 .../vendors/tabulator/js/modules/ajax.min.js | 0 .../js/modules/calculation_colums.js | 0 .../js/modules/calculation_colums.min.js | 0 .../vendors/tabulator/js/modules/clipboard.js | 0 .../tabulator/js/modules/clipboard.min.js | 0 .../vendors/tabulator/js/modules/data_tree.js | 0 .../tabulator/js/modules/data_tree.min.js | 0 .../vendors/tabulator/js/modules/download.js | 0 .../tabulator/js/modules/download.min.js | 0 .../vendors/tabulator/js/modules/edit.js | 0 .../vendors/tabulator/js/modules/edit.min.js | 0 .../vendors/tabulator/js/modules/export.js | 0 .../tabulator/js/modules/export.min.js | 0 .../vendors/tabulator/js/modules/filter.js | 0 .../tabulator/js/modules/filter.min.js | 0 .../vendors/tabulator/js/modules/format.js | 0 .../tabulator/js/modules/format.min.js | 0 .../tabulator/js/modules/frozen_columns.js | 0 .../js/modules/frozen_columns.min.js | 0 .../tabulator/js/modules/frozen_rows.js | 0 .../tabulator/js/modules/frozen_rows.min.js | 0 .../tabulator/js/modules/group_rows.js | 0 .../tabulator/js/modules/group_rows.min.js | 0 .../vendors/tabulator/js/modules/history.js | 0 .../tabulator/js/modules/history.min.js | 0 .../tabulator/js/modules/html_table_import.js | 0 .../js/modules/html_table_import.min.js | 0 .../tabulator/js/modules/keybindings.js | 0 .../tabulator/js/modules/keybindings.min.js | 0 .../vendors/tabulator/js/modules/menu.js | 0 .../vendors/tabulator/js/modules/menu.min.js | 0 .../tabulator/js/modules/moveable_columns.js | 0 .../js/modules/moveable_columns.min.js | 0 .../tabulator/js/modules/moveable_rows.js | 0 .../tabulator/js/modules/moveable_rows.min.js | 0 .../vendors/tabulator/js/modules/mutator.js | 0 .../tabulator/js/modules/mutator.min.js | 0 .../vendors/tabulator/js/modules/page.js | 0 .../vendors/tabulator/js/modules/page.min.js | 0 .../tabulator/js/modules/persistence.js | 0 .../tabulator/js/modules/persistence.min.js | 0 .../vendors/tabulator/js/modules/print.js | 0 .../vendors/tabulator/js/modules/print.min.js | 0 .../tabulator/js/modules/reactive_data.js | 0 .../tabulator/js/modules/reactive_data.min.js | 0 .../tabulator/js/modules/resize_columns.js | 0 .../js/modules/resize_columns.min.js | 0 .../tabulator/js/modules/resize_rows.js | 0 .../tabulator/js/modules/resize_rows.min.js | 0 .../tabulator/js/modules/resize_table.js | 0 .../tabulator/js/modules/resize_table.min.js | 0 .../tabulator/js/modules/responsive_layout.js | 0 .../js/modules/responsive_layout.min.js | 0 .../tabulator/js/modules/select_row.js | 0 .../tabulator/js/modules/select_row.min.js | 0 .../vendors/tabulator/js/modules/sort.js | 0 .../vendors/tabulator/js/modules/sort.min.js | 0 .../vendors/tabulator/js/modules/validate.js | 0 .../tabulator/js/modules/validate.min.js | 0 .../vendors/tabulator/js/tabulator.js | 0 .../vendors/tabulator/js/tabulator.min.js | 0 .../tabulator/js/tabulator.min.orig.js | 0 .../vendors/tabulator/js/tabulator_core.js | 0 .../tabulator/js/tabulator_core.min.js | 0 appdata/POT.json | 1 - .../live/potlu2_db.alicehartmann.pg.data.sql | 2561 +++++ .../live/potlu2_db.alicehartmann.pg.full.sql | 3163 ++++++ .../potlu2_db.alicehartmann.pg.schema.sql | 624 ++ dev/db/live/potlu2_db.barto.pg.data.sql | 4 +- dev/db/live/potlu2_db.barto.pg.full.sql | 4 +- dev/db/live/potlu2_db.barto.pg.schema.sql | 4 +- ...potlu2_db.brasserie_du_theatre.pg.data.sql | 1624 +-- ...potlu2_db.brasserie_du_theatre.pg.full.sql | 1700 ++-- ...tlu2_db.brasserie_du_theatre.pg.schema.sql | 80 +- dev/db/live/potlu2_db.demo.pg.data.sql | 8782 ++++++++-------- dev/db/live/potlu2_db.demo.pg.full.sql | 8858 +++++++++-------- dev/db/live/potlu2_db.demo.pg.schema.sql | 80 +- dev/db/live/potlu2_db.demo50.pg.data.sql | 5473 +++++----- dev/db/live/potlu2_db.demo50.pg.full.sql | 5549 ++++++----- dev/db/live/potlu2_db.demo50.pg.schema.sql | 80 +- dev/db/live/potlu2_db.demoold.pg.data.sql | 4 +- dev/db/live/potlu2_db.demoold.pg.full.sql | 4 +- dev/db/live/potlu2_db.demoold.pg.schema.sql | 4 +- dev/db/live/potlu2_db.elch.pg.data.sql | 4105 ++++---- dev/db/live/potlu2_db.elch.pg.full.sql | 4181 ++++---- dev/db/live/potlu2_db.elch.pg.schema.sql | 80 +- dev/db/live/potlu2_db.etude_dbe.pg.data.sql | 413 +- dev/db/live/potlu2_db.etude_dbe.pg.full.sql | 489 +- dev/db/live/potlu2_db.etude_dbe.pg.schema.sql | 80 +- dev/db/live/potlu2_db.kraeltgen.pg.data.sql | 6857 +++++++++++++ dev/db/live/potlu2_db.kraeltgen.pg.full.sql | 7459 ++++++++++++++ dev/db/live/potlu2_db.kraeltgen.pg.schema.sql | 624 ++ dev/db/live/potlu2_db.lousdiner.pg.data.sql | 944 ++ dev/db/live/potlu2_db.lousdiner.pg.full.sql | 1487 +++ dev/db/live/potlu2_db.lousdiner.pg.schema.sql | 565 ++ dev/db/live/potlu2_db.portanova.pg.data.sql | 6441 ++++++------ dev/db/live/potlu2_db.portanova.pg.full.sql | 6517 ++++++------ dev/db/live/potlu2_db.portanova.pg.schema.sql | 80 +- dev/db/live/potlu2_db.public.pg.data.sql | 115 +- dev/db/live/potlu2_db.public.pg.full.sql | 121 +- dev/db/live/potlu2_db.public.pg.schema.sql | 10 +- dev/db/tmp/schemas.csv | 13 + website/api/.htaccess | 8 - website/api/sendemail.cgi | 100 - website/api/tmp/.htaccess | 5 - website/api/tools/.htaccess | 5 - website/api/tools/sendEmail | 2235 ----- 275 files changed, 53843 insertions(+), 30254 deletions(-) rename app/{static => }/css/fonts/appicons.eot (100%) rename app/{static => }/css/fonts/appicons.svg (100%) rename app/{static => }/css/fonts/appicons.ttf (100%) rename app/{static => }/css/fonts/appicons.woff (100%) rename app/{static => }/css/icons.css (100%) rename app/{static => }/css/theme.css (100%) create mode 100644 app/data/reports/pot/content.html.mustache create mode 100644 app/data/reports/pot/footer.html.mustache create mode 100644 app/data/reports/pot/header.html.mustache delete mode 100644 app/db.cgi rename app/{static => }/img/POT-logo.png (100%) rename app/{static => }/img/bg1.jpg (100%) rename app/{static => }/img/chrome.png (100%) rename app/{static => }/img/chrome.svg (100%) rename app/{static => }/img/edge.png (100%) rename app/{static => }/img/edge.svg (100%) rename app/{static => }/img/favicon/android-icon-144x144.png (100%) rename app/{static => }/img/favicon/android-icon-192x192.png (100%) rename app/{static => }/img/favicon/android-icon-36x36.png (100%) rename app/{static => }/img/favicon/android-icon-48x48.png (100%) rename app/{static => }/img/favicon/android-icon-512x512.png (100%) rename app/{static => }/img/favicon/android-icon-72x72.png (100%) rename app/{static => }/img/favicon/android-icon-96x96.png (100%) rename app/{static => }/img/favicon/apple-icon-114x114.png (100%) rename app/{static => }/img/favicon/apple-icon-120x120.png (100%) rename app/{static => }/img/favicon/apple-icon-144x144.png (100%) rename app/{static => }/img/favicon/apple-icon-152x152.png (100%) rename app/{static => }/img/favicon/apple-icon-180x180.png (100%) rename app/{static => }/img/favicon/apple-icon-57x57.png (100%) rename app/{static => }/img/favicon/apple-icon-60x60.png (100%) rename app/{static => }/img/favicon/apple-icon-72x72.png (100%) rename app/{static => }/img/favicon/apple-icon-76x76.png (100%) rename app/{static => }/img/favicon/apple-icon-precomposed.png (100%) rename app/{static => }/img/favicon/apple-icon.png (100%) rename app/{static => }/img/favicon/browserconfig.xml (100%) rename app/{static => }/img/favicon/favicon-16x16.png (100%) rename app/{static => }/img/favicon/favicon-32x32.png (100%) rename app/{static => }/img/favicon/favicon-96x96.png (100%) rename app/{static => }/img/favicon/favicon.ico (100%) rename app/{static => }/img/favicon/manifest.json (100%) rename app/{static => }/img/favicon/ms-icon-144x144.png (100%) rename app/{static => }/img/favicon/ms-icon-150x150.png (100%) rename app/{static => }/img/favicon/ms-icon-310x310.png (100%) rename app/{static => }/img/favicon/ms-icon-70x70.png (100%) rename app/{static => }/img/firefox.svg (100%) rename app/{static => }/img/logo_512.png (100%) rename app/{static => }/img/logo_512_xx.png (100%) rename app/{static => }/img/opera.svg (100%) rename app/{static => }/img/potbg.jpg (100%) rename app/{static => }/img/poticon512.png (100%) rename app/{static => }/img/potlogowhite.svg (100%) rename app/{static => }/img/pottop.png (100%) rename app/{static => }/img/safari.png (100%) rename app/{static => }/img/safari.svg (100%) rename app/{static => }/img/splashscreens/ipad_splash.png (100%) rename app/{static => }/img/splashscreens/ipadpro1_splash.png (100%) rename app/{static => }/img/splashscreens/ipadpro2_splash.png (100%) rename app/{static => }/img/splashscreens/ipadpro3_splash.png (100%) rename app/{static => }/img/splashscreens/iphone5_splash.png (100%) rename app/{static => }/img/splashscreens/iphone6_splash.png (100%) rename app/{static => }/img/splashscreens/iphoneplus_splash.png (100%) rename app/{static => }/img/splashscreens/iphonex_splash.png (100%) rename app/{static => }/img/splashscreens/iphonexr_splash.png (100%) rename app/{static => }/img/splashscreens/iphonexsmax_splash.png (100%) rename app/{static => }/img/toplogo.png (100%) delete mode 100644 app/index.cgi rename app/{static => }/js/app.js (97%) rename app/{static => }/js/dataform.js (100%) rename app/{static => }/js/report.js (73%) rename app/{static => }/js/request.js (100%) rename app/{static => }/js/sw.js (94%) rename app/{static => }/js/timecalc.js (100%) rename app/lib/POT/{Report.nousephp => Report.php} (53%) create mode 100644 app/lib/helpers.php delete mode 100644 app/report.cgi delete mode 100644 app/synctimetrack.cgi create mode 100644 app/tmpl/module/timeclock.html create mode 100644 app/tmpl/module/vacancydays/vacancydays.html create mode 100644 app/tmpl/module/vacancydays/vacancydays.js rename app/{static => }/vendors/flatpickr/flatpickr.css (100%) rename app/{static => }/vendors/flatpickr/flatpickr.js (99%) rename app/{static => }/vendors/flatpickr/flatpickr.min.css (100%) rename app/{static => }/vendors/flatpickr/flatpickr.min.js (100%) rename app/{static => }/vendors/flatpickr/ie.css (100%) rename app/{static => }/vendors/flatpickr/index.d.ts (100%) rename app/{static => }/vendors/flatpickr/l10n/de.d.ts (100%) rename app/{static => }/vendors/flatpickr/l10n/de.js (100%) rename app/{static => }/vendors/flatpickr/l10n/default.d.ts (100%) rename app/{static => }/vendors/flatpickr/l10n/default.js (100%) rename app/{static => }/vendors/flatpickr/l10n/fr.d.ts (100%) rename app/{static => }/vendors/flatpickr/l10n/fr.js (100%) rename app/{static => }/vendors/flatpickr/l10n/index.d.ts (100%) rename app/{static => }/vendors/flatpickr/l10n/index.js (99%) rename app/{static => }/vendors/flatpickr/plugins/confirmDate/confirmDate.css (100%) rename app/{static => }/vendors/flatpickr/plugins/confirmDate/confirmDate.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/confirmDate/confirmDate.js (99%) rename app/{static => }/vendors/flatpickr/plugins/labelPlugin/labelPlugin.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/labelPlugin/labelPlugin.js (100%) rename app/{static => }/vendors/flatpickr/plugins/minMaxTimePlugin.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/minMaxTimePlugin.js (100%) rename app/{static => }/vendors/flatpickr/plugins/momentPlugin.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/momentPlugin.js (100%) rename app/{static => }/vendors/flatpickr/plugins/monthSelect/index.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/monthSelect/index.js (99%) rename app/{static => }/vendors/flatpickr/plugins/monthSelect/style.css (100%) rename app/{static => }/vendors/flatpickr/plugins/monthSelect/tests.spec.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/rangePlugin.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/rangePlugin.js (99%) rename app/{static => }/vendors/flatpickr/plugins/scrollPlugin.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/scrollPlugin.js (100%) rename app/{static => }/vendors/flatpickr/plugins/weekSelect/weekSelect.d.ts (100%) rename app/{static => }/vendors/flatpickr/plugins/weekSelect/weekSelect.js (100%) rename app/{static => }/vendors/flatpickr/themes/airbnb.css (100%) rename app/{static => }/vendors/flatpickr/types/globals.d.ts (100%) rename app/{static => }/vendors/flatpickr/types/instance.d.ts (100%) rename app/{static => }/vendors/flatpickr/types/locale.d.ts (100%) rename app/{static => }/vendors/flatpickr/types/options.d.ts (100%) rename app/{static => }/vendors/flatpickr/typings.d.ts (100%) rename app/{static => }/vendors/flatpickr/utils/dates.d.ts (100%) rename app/{static => }/vendors/flatpickr/utils/dom.d.ts (100%) rename app/{static => }/vendors/flatpickr/utils/formatting.d.ts (100%) rename app/{static => }/vendors/flatpickr/utils/index.d.ts (100%) rename app/{static => }/vendors/flatpickr/utils/polyfills.d.ts (100%) rename app/{static => }/vendors/moment/locales.js (100%) rename app/{static => }/vendors/moment/locales.min.js (100%) rename app/{static => }/vendors/moment/locales.min.js.map (100%) rename app/{static => }/vendors/moment/moment-with-locales.js (100%) rename app/{static => }/vendors/moment/moment-with-locales.min.js (100%) rename app/{static => }/vendors/moment/moment-with-locales.min.js.map (100%) rename app/{static => }/vendors/moment/moment.js (100%) rename app/{static => }/vendors/moment/moment.min.js (100%) rename app/{static => }/vendors/moment/moment.min.js.map (100%) rename app/{static => }/vendors/slimselect/slimselect.css (100%) rename app/{static => }/vendors/slimselect/slimselect.min.css (100%) rename app/{static => }/vendors/slimselect/slimselect.min.js (100%) rename app/{static => }/vendors/slimselect/slimselect.min.orig.css (100%) rename app/{static => }/vendors/slimselect/slimselect.min.xx.js (100%) rename app/{static => }/vendors/slimselect/slimselect.scss (100%) rename app/{static => }/vendors/slimselect/slimselect.xx.js (100%) rename app/{static => }/vendors/suneditor/css/suneditor.min.css (100%) rename app/{static => }/vendors/suneditor/suneditor.min.js (100%) rename app/{static => }/vendors/tabulator/css/tabulator.css (100%) rename app/{static => }/vendors/tabulator/css/tabulator.min.css (100%) rename app/{static => }/vendors/tabulator/css/tabulator.min.css.map (100%) rename app/{static => }/vendors/tabulator/css/tabulator_site.css (100%) rename app/{static => }/vendors/tabulator/css/tabulator_site.min.css (100%) rename app/{static => }/vendors/tabulator/css/tabulator_site.min.css.map (100%) rename app/{static => }/vendors/tabulator/css/tabulator_site.min.orig.css (100%) rename app/{static => }/vendors/tabulator/js/modules/accessor.js (100%) rename app/{static => }/vendors/tabulator/js/modules/accessor.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/ajax.js (100%) rename app/{static => }/vendors/tabulator/js/modules/ajax.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/calculation_colums.js (100%) rename app/{static => }/vendors/tabulator/js/modules/calculation_colums.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/clipboard.js (100%) rename app/{static => }/vendors/tabulator/js/modules/clipboard.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/data_tree.js (100%) rename app/{static => }/vendors/tabulator/js/modules/data_tree.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/download.js (100%) rename app/{static => }/vendors/tabulator/js/modules/download.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/edit.js (100%) rename app/{static => }/vendors/tabulator/js/modules/edit.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/export.js (100%) rename app/{static => }/vendors/tabulator/js/modules/export.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/filter.js (100%) rename app/{static => }/vendors/tabulator/js/modules/filter.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/format.js (100%) rename app/{static => }/vendors/tabulator/js/modules/format.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/frozen_columns.js (100%) rename app/{static => }/vendors/tabulator/js/modules/frozen_columns.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/frozen_rows.js (100%) rename app/{static => }/vendors/tabulator/js/modules/frozen_rows.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/group_rows.js (100%) rename app/{static => }/vendors/tabulator/js/modules/group_rows.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/history.js (100%) rename app/{static => }/vendors/tabulator/js/modules/history.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/html_table_import.js (100%) rename app/{static => }/vendors/tabulator/js/modules/html_table_import.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/keybindings.js (100%) rename app/{static => }/vendors/tabulator/js/modules/keybindings.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/menu.js (100%) rename app/{static => }/vendors/tabulator/js/modules/menu.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/moveable_columns.js (100%) rename app/{static => }/vendors/tabulator/js/modules/moveable_columns.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/moveable_rows.js (100%) rename app/{static => }/vendors/tabulator/js/modules/moveable_rows.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/mutator.js (100%) rename app/{static => }/vendors/tabulator/js/modules/mutator.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/page.js (100%) rename app/{static => }/vendors/tabulator/js/modules/page.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/persistence.js (100%) rename app/{static => }/vendors/tabulator/js/modules/persistence.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/print.js (100%) rename app/{static => }/vendors/tabulator/js/modules/print.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/reactive_data.js (100%) rename app/{static => }/vendors/tabulator/js/modules/reactive_data.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/resize_columns.js (100%) rename app/{static => }/vendors/tabulator/js/modules/resize_columns.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/resize_rows.js (100%) rename app/{static => }/vendors/tabulator/js/modules/resize_rows.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/resize_table.js (100%) rename app/{static => }/vendors/tabulator/js/modules/resize_table.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/responsive_layout.js (100%) rename app/{static => }/vendors/tabulator/js/modules/responsive_layout.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/select_row.js (100%) rename app/{static => }/vendors/tabulator/js/modules/select_row.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/sort.js (100%) rename app/{static => }/vendors/tabulator/js/modules/sort.min.js (100%) rename app/{static => }/vendors/tabulator/js/modules/validate.js (100%) rename app/{static => }/vendors/tabulator/js/modules/validate.min.js (100%) rename app/{static => }/vendors/tabulator/js/tabulator.js (100%) rename app/{static => }/vendors/tabulator/js/tabulator.min.js (100%) rename app/{static => }/vendors/tabulator/js/tabulator.min.orig.js (100%) rename app/{static => }/vendors/tabulator/js/tabulator_core.js (100%) rename app/{static => }/vendors/tabulator/js/tabulator_core.min.js (100%) delete mode 100644 appdata/POT.json create mode 100644 dev/db/live/potlu2_db.alicehartmann.pg.data.sql create mode 100644 dev/db/live/potlu2_db.alicehartmann.pg.full.sql create mode 100644 dev/db/live/potlu2_db.alicehartmann.pg.schema.sql create mode 100644 dev/db/live/potlu2_db.kraeltgen.pg.data.sql create mode 100644 dev/db/live/potlu2_db.kraeltgen.pg.full.sql create mode 100644 dev/db/live/potlu2_db.kraeltgen.pg.schema.sql create mode 100644 dev/db/live/potlu2_db.lousdiner.pg.data.sql create mode 100644 dev/db/live/potlu2_db.lousdiner.pg.full.sql create mode 100644 dev/db/live/potlu2_db.lousdiner.pg.schema.sql create mode 100644 dev/db/tmp/schemas.csv delete mode 100644 website/api/.htaccess delete mode 100644 website/api/sendemail.cgi delete mode 100644 website/api/tmp/.htaccess delete mode 100644 website/api/tools/.htaccess delete mode 100644 website/api/tools/sendEmail diff --git a/app/static/css/fonts/appicons.eot b/app/css/fonts/appicons.eot similarity index 100% rename from app/static/css/fonts/appicons.eot rename to app/css/fonts/appicons.eot diff --git a/app/static/css/fonts/appicons.svg b/app/css/fonts/appicons.svg similarity index 100% rename from app/static/css/fonts/appicons.svg rename to app/css/fonts/appicons.svg diff --git a/app/static/css/fonts/appicons.ttf b/app/css/fonts/appicons.ttf similarity index 100% rename from app/static/css/fonts/appicons.ttf rename to app/css/fonts/appicons.ttf diff --git a/app/static/css/fonts/appicons.woff b/app/css/fonts/appicons.woff similarity index 100% rename from app/static/css/fonts/appicons.woff rename to app/css/fonts/appicons.woff diff --git a/app/static/css/icons.css b/app/css/icons.css similarity index 100% rename from app/static/css/icons.css rename to app/css/icons.css diff --git a/app/static/css/theme.css b/app/css/theme.css similarity index 100% rename from app/static/css/theme.css rename to app/css/theme.css diff --git a/app/data/reports/pot/content.html.mustache b/app/data/reports/pot/content.html.mustache new file mode 100644 index 00000000..b9704714 --- /dev/null +++ b/app/data/reports/pot/content.html.mustache @@ -0,0 +1,35 @@ + + + + PDF - Rapport - Période de Référence + + + + + + diff --git a/app/data/reports/pot/footer.html.mustache b/app/data/reports/pot/footer.html.mustache new file mode 100644 index 00000000..ff0f0e0e --- /dev/null +++ b/app/data/reports/pot/footer.html.mustache @@ -0,0 +1,47 @@ + + + + + + + + + + + + +
 
+
Congé: + {{#vleg}} + {{vleg.legend}}) {{vleg.vacancyname}} + {{/vleg}} +
+
Récupération: + $rleg =$this->dbh->queryarray(); + foreach ($rleg as $r){ + $outdata .= $rleg[$r]["legend"].") ".$rleg[$r]["vacancyname"]." "; + } + $outdata .= "
+ Page / +
+ \ No newline at end of file diff --git a/app/data/reports/pot/header.html.mustache b/app/data/reports/pot/header.html.mustache new file mode 100644 index 00000000..32e23591 --- /dev/null +++ b/app/data/reports/pot/header.html.mustache @@ -0,0 +1,20 @@ + + + + + + + + + + +
+

{{ reportheading }}

+

+
+ {{company}} {{socialtype}}
+ {{address}}
+ {{zip}} {{city}}

+
+
+ \ No newline at end of file diff --git a/app/db.cgi b/app/db.cgi deleted file mode 100644 index 950c69b5..00000000 --- a/app/db.cgi +++ /dev/null @@ -1,394 +0,0 @@ -#!/usr/local/bin/perl -use strict; -use lib ('./lib/perl5'); -use lib ('./lib'); -use CGI; -use CGI::Cookie; -# use CGI::Carp qw/fatalsToBrowser/; -use File::Basename; -use JSON::PP; -use Data::Dumper; -use Digest::SHA qw(sha256_hex); -use POT::Period; -use POT::Company; -use POT::Staff; -use POT::Workplan; -use POT::Worktime; -use POT::User; -use POT::TimeTracker; -use dksconfig qw/$sitecfg/; -use dksdb; - -use session; - -my $cgi = new CGI(); -my $scriptpath = $cgi->url(-absolute => 1); -my $p = (); - -my $html->{result} = (); -my $db = dksdb->new({dsn => $sitecfg->{dsn},dbuser => $sitecfg->{dbuser},dbpassword => $sitecfg->{dbpassword}}); -$p->{sid} = $cgi->cookie($sitecfg->{cookiename}); - -my $se = session->new({db => $db}); -my $sess = $se->getsession($p->{sid}); -print $cgi->header(-type=>"application/json", -charset => "utf-8"); -if ($sess == undef){ - $html->{error} = "No Authorisation"; - print JSON::PP::encode_json($html); - exit(0); -} - - -if (($cgi->request_method() eq "GET") || ($cgi->request_method() eq "POST")){ - - my @params = $cgi->param(); - - foreach my $pp (@params){ - $p->{$pp} = $cgi->param($pp); - } - if (exists($p->{"POSTDATA"})){ - my $pdj = (); - if ($p->{"POSTDATA"} =~ /^\{.*\}$/ ){ - $pdj = JSON::PP::decode_json($p->{"POSTDATA"}); - } - - foreach my $k (keys(%{$pdj})){ - $p->{$k} = $pdj->{$k}; - } - } - #$html->{params} = $p; - if (exists($p->{get})){ - my @retdata = (); - my $hres; - my $schema = "public"; - if (exists($p->{schemata})){ - $schema = $db->securetext($p->{schemata}); - } - if ($p->{get} =~ /periods$|periodweeksums$|perioddays$|perioddata$|staffperiods$|staffperiodsgrouped$|staffperiodsplitted$|defaultdaylimits$|lastperioddates$/){ - my $period = POT::Period->new({db => $db}); - if ($p->{get} eq 'periods'){ - $hres = $period->getPeriods($schema); - } elsif ($p->{get} eq 'periodweeksums'){ - $hres = $period->getPeriodWeekSums($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{date_start}),$db->securetext($p->{date_end}),$db->securetext($p->{id_period})); - } elsif ($p->{get} eq 'perioddays'){ - $hres = $period->getPeriodDays($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{date_start}),$db->securetext($p->{date_end})); - } elsif ($p->{get} eq 'staffperiods'){ - if ($sess->{usergroup} eq "teamleader"){ - $hres = $period->getStaffPeriods($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),$sess->{staffgroups},"0"); - } else { - $hres = $period->getStaffPeriods($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),undef,"0"); - } - } elsif ($p->{get} eq 'staffperiodsgrouped'){ - if ($sess->{usergroup} eq "teamleader"){ - $hres = $period->getStaffPeriods($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),$sess->{staffgroups},"1"); - } else { - $hres = $period->getStaffPeriods($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),undef,"1"); - } - } elsif ($p->{get} eq 'staffperiodsplitted'){ - if ($sess->{usergroup} eq "teamleader"){ - $hres = $period->getStaffPeriodSplitted($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),$sess->{staffgroups},"1"); - } else { - $hres = $period->getStaffPeriodSplitted($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),undef,"1"); - } - } - elsif ($p->{get} eq "defaultdaylimits"){ - $hres = $period->getDefaultDayLimits($schema); - } - elsif ($p->{get} eq "lastperioddates"){ - $hres = $period->getLastPeriodDates($schema); - } - } elsif ($p->{get} =~ /company$|companiesdata$|staffgroups$|staffgroup$|sectors$|allschemalist$|companysize$|vacancydays$|gvacancytypes$|sectordata$/){ - my $cp = POT::Company->new({db => $db}); - if ($p->{get} eq 'companiesdata'){ - $hres = $cp->getCompaniesData(); - } elsif ($p->{get} eq 'company'){ - $hres = $cp->getCompany($schema); - } elsif ($p->{get} eq 'staffgroups'){ - $hres = $cp->getStaffGroups($schema); - } elsif ($p->{get} eq 'staffgroup'){ - $hres = $cp->getStaffGroup($schema,$db->securetext($p->{id})); - } elsif ($p->{get} eq 'sectors'){ - $hres = $cp->getSectors(); - } elsif ($p->{get} eq 'sectordata'){ - $hres = $cp->getSectorData($schema); - }elsif ($p->{get} eq 'companysize'){ - $hres = $cp->getCompanySize(); - }elsif ($p->{get} eq 'allschemalist'){ - $hres = $cp->getAllSchemata(); - }elsif ($p->{get} eq 'vacancydays'){ - $hres = $cp->getVacancyDays($schema); - }elsif ($p->{get} eq 'gvacancytypes'){ - $hres = $cp->getVacancyTypes($schema); - } - } elsif ($p->{get} =~ /workplanlist$|workplan$|workplandayslist$|workplanday$/){ - my $wp = POT::Workplan->new({db => $db}); - if ($p->{get} eq 'workplanlist'){ - $hres = $wp->getWorkplans($schema); - } elsif ($p->{get} eq 'workplandayslist'){ - $hres = $wp->getWorkplanDays($schema,$db->securetext($p->{id_workplan})); - } elsif ($p->{get} eq 'workplan'){ - $hres = $wp->getWorkplan($schema,$db->securetext($p->{id})); - } elsif ($p->{get} eq 'workplanday'){ - $hres = $wp->getWorkplanDay($schema,$db->securetext($p->{id})); - } - } elsif ($p->{get} =~ /worktimeslist$|worktime$|vacancytypes$|recuperationtypes$/){ - my $wk = POT::Worktime->new({db => $db}); - if ($p->{get} eq 'worktimeslist'){ - $hres = $wk->getWorktimes($schema); - } elsif ($p->{get} eq 'worktime'){ - $hres = $wk->getWorktime($schema,$db->securetext($p->{id})); - } elsif ($p->{get} eq 'vacancytypes'){ - $hres = $wk->getVacancyTypes($schema); - }elsif ($p->{get} eq 'recuperationtypes'){ - $hres = $wk->getRecuperationTypes($schema); - } - } elsif ($p->{get} =~ /staffcontractdates$|staffcontract$|stafflist$|staff$|getStaffVacancy$|getStaffVacancyYears$/){ - my $st = POT::Staff->new({db => $db}); - if ($p->{get} eq 'staffcontractdates'){ - $hres = $st->getStaffContractDates($schema,$db->securetext($p->{id_staff})); - } elsif ($p->{get} eq 'staffcontract'){ - $hres = $st->getStaffContract($schema,$db->securetext($p->{id})); - } elsif ($p->{get} eq 'staff'){ - $hres = $st->getStaff($schema,$db->securetext($p->{id})); - } elsif($p->{get} eq 'getStaffVacancyYears'){ - $hres = $st->getStaffVacancyYears($schema,$db->securetext($p->{id})); - } elsif($p->{get} eq 'getStaffVacancy'){ - $hres = $st->getStaffVacancy($schema,$db->securetext($p->{id})); - }elsif ($p->{get} eq 'stafflist'){ - if ($sess->{usergroup} eq "teamleader"){ - $hres = $st->getStaffList($schema,$sess->{staffgroups}); - } else { - $hres = $st->getStaffList($schema,undef); - } - - } - - } elsif ($p->{get} =~ /gettrackday$|emptytrackdataset$|getTimeTrackerList$/){ - my $st = POT::TimeTracker->new({db => $db}); - if ($p->{get} eq 'gettrackday'){ - $hres = $st->getTrackDay($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{daydate})); - } elsif ($p->{get} eq 'emptytrackdataset'){ - $hres = $st->getEmptyTrackDataSet($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{daydate})); - } elsif ($p->{get} eq 'getTimeTrackerList'){ - $hres = $st->getTimeTrackerList($schema); - } - } elsif ($p->{get} =~ /userschemaaccess$|termsstatus$|userlist$|user$|usergrouplist$/){ - my $us = POT::User->new({db => $db}); - if ($p->{get} eq 'userschemaaccess'){ - if ($sess->{usergroup} eq 'admin'){ - $hres = $us->getAllSchemata(); - } else { - $hres = $us->getUserSchemata($sess->{id}); - } - }elsif($p->{get} =~ "termsstatus"){ - $hres = $us->getTermsStatus($sess->{id}); - }elsif ($p->{get} eq 'userlist'){ - if ($sess->{usergroup} eq 'admin'){ - $hres = $us->getUserList($db->securetext($p->{schemata}),undef); - } else { - my $ugroups = ["teamleader","manager"]; - $hres = $us->getUserList($db->securetext($p->{schemata}),$ugroups); - } - }elsif ($p->{get} eq 'user'){ - $hres = $us->getUser($db->securetext($p->{id})); - }elsif ($p->{get} eq 'usergrouplist'){ - $hres = $us->getUserGroupList(); - } - } - - if ($p->{get} !~ /periodweeksums$|staffperiodsgrouped$|company$|workplan$|workplanday$|worktime$|staffcontract$|staff$|staffgroup$|defaultdaylimits$|termsstatus$|user$|lastperioddates$/ ){ - foreach my $r (sort {$a <=> $b} keys(%{$hres})){ - push(@retdata,$hres->{$r}); - } - - $html->{result}->{sqldata} = \@retdata; - } else { - $html->{result}->{data} = $hres; - } - - } - elsif ($p->{fn} eq "setnewpassword"){ - #my $vcode = $se->randomstring(6); - #$vcode = lc($vcode); - #$db->exec("UPDATE users set vcode='".$vcode."' where id=".$sess->{id}.";"); - my $sql = "select id,userpassword,surname,prename from users where username='".$db->securetext($p->{email})."';"; - my $ex = $db->querysorted($sql); - my $data; - if (keys(%{$ex}) > 0){ - my $newpwd = $se->randomstring(12); - my $pwd = sha256_hex($newpwd); - $db->exec("UPDATE users SET userpassword = '".$pwd."' WHERE id='".$ex->{0}->{id}."';"); - $data->{password} = $newpwd; - $data->{username} = $db->securetext($p->{email}); - #$data->{name} = $ex->{0}->{prename}." ".$ex->{0}->{surname}; - #my $eml = sendemail->new(); - #$mret = $eml->sendemail('user_forgotpasswd',$p->{email},$data); - } - $html->{result}->{data} = $data; - } elsif ($p->{fn} eq "genpwd"){ - my $newpwd = $se->randomstring(12); - $html->{result}->{data}->{password} = $newpwd; - } elsif ($p->{fn} eq "savenewpwd"){ - if (length($db->securetext($p->{pwd})) > 9){ - my $pwd = sha256_hex($db->securetext($p->{pwd})); - $db->exec("UPDATE public.users SET userpassword = '".$pwd."' WHERE id='".$db->securetext($p->{iduser})."';"); - } - $html->{result}->{data} = "OK"; - } - elsif (exists($p->{save})){ - my $schema = "public"; - if (exists($p->{schemata})){ - $schema = $db->securetext($p->{schemata}); - } - if ($p->{save} eq "field"){ - my $val = "null"; - - if ($p->{value} ne ""){ - $val = "'".$db->securetext($p->{value})."'"; - } - my $usql = "UPDATE ".$schema.".".$db->securetext($p->{table})." SET ".$db->securetext($p->{column})."=".$val." WHERE id='".$db->securetext($p->{id})."';"; - $html->{result} = $db->exec($usql); - } - } - elsif (exists($p->{fn}) && ($p->{fn} eq "saveform")){ - delete $p->{fn}; - delete $p->{sid}; - my $retid=undef; - my $type = "upd"; - my $table = $p->{table}; - delete $p->{table}; - - my $schema = "public"; - if (exists($p->{schemata})){$schema = $db->securetext($p->{schemata});} - foreach my $px (keys(%{$p})){ - if (($px =~ /\_id$/) && ($p->{$px} eq "")){$type = "ins";delete $p->{$px};} - if ($px !~ /$table/){delete $p->{$px};} - } - my @sql = (); - if ($type eq "ins"){@sql = $db->create_ddl_insert($schema,$p);} - else { @sql = $db->create_ddl_update($schema,$p);} - #$html->{sql} = \@sql; - if (scalar(@sql) > 0){ - $retid= $db->exec($sql[0]); - } - $html->{result} = $retid->{0}; - } - elsif (exists($p->{fn})){ - my $schema = "public"; - if (exists($p->{schemata})){ - $schema = $db->securetext($p->{schemata}); - } - # print STDERR $p->{fn}."\n"; - if ($p->{fn} eq "setsessiondata"){ - my $sid = $sess->{idsession}; - my $res = $se->setsessiondata($sid,$p->{params}); - $html->{result}->{sessiondata} = $res; - } - - if ($p->{fn} =~ /getfreeschema$|installschema$|del_company$|del_staffgroup$|set_staffgroup$/){ - my $cp = POT::Company->new({db => $db}); - # print STDERR $p->{fn}.": Company\n"; - if ($p->{fn} eq "installschema"){ - my $linkid = $cp->InstallCompanySchema($db->securetext($p->{schemaname}),$db->securetext($p->{datasetname}),$db->securetext($p->{sector}),$db->securetext($p->{periodtype}),$db->securetext($p->{reportperiodunit}),$db->securetext($p->{reportperiodlength}),$db->securetext($p->{payedpauses})); - $html->{result}->{link} = $linkid; - }elsif ($p->{fn} eq "getfreeschema"){ - $html->{result}->{newschema} = $cp->checkFreeSchema($db->securetext($p->{datasetname})); - }elsif ($p->{fn} eq "del_company"){ - $html->{result} = $cp->deleteCompany($db->securetext($p->{id})); - }elsif ($p->{fn} eq "del_staffgroup"){ - $html->{result} = $cp->deleteStaffGroup($schema,$db->securetext($p->{id})); - }elsif ($p->{fn} = "set_staffgroup"){ - $html->{result} = $cp->setStaffGroup($schema,$db->securetext($p->{id_staffgroup}),$db->securetext($p->{groupname})); - } - } elsif ($p->{fn} =~ /del_staff$|del_staffcontract$|add_staff$|setstaffcontractdays$/) { - # print STDERR $p->{fn}.": Staff\n"; - my $st = POT::Staff->new({db => $db}); - if ($p->{fn} eq "del_staff"){ - $html->{result} = $st->deleteStaff($schema,$db->securetext($p->{id})); - } elsif ($p->{fn} eq "del_staffcontract"){ - $html->{result} = $st->deleteStaffContract($schema,$db->securetext($p->{id})); - } elsif ($p->{fn} eq "add_staff"){ - $html->{result} = $st->addStaff($schema,$db->securetext($p->{surname}),$db->securetext($p->{prename}),$db->securetext($p->{startdate}),$db->securetext($p->{enddate}),$db->securetext($p->{weekhours}),$db->securetext($p->{weekdays}),$db->securetext($p->{id_staffgroup})); - } elsif ($p->{fn} = "setstaffcontractdays"){ - $html->{result} = $st->setStaffContractDays($schema,$db->securetext($p->{id_staff})); - } - } elsif ($p->{fn} =~ /clone_staffperiodweekdayhours$|clean_staffperiodday$|replace_staffperiodweekdayhours$|update_staff_in_period$|getworktimelimits$|refresh_periods$|add_reportperiod$|save_payedhours$|^invalidate_period$|^validate_period$/) { - # print STDERR $p->{fn}.": Period\n"; - my $pd= POT::Period->new({db => $db}); - - if ($p->{fn} eq "clone_staffperiodweekdayhours"){ - $html->{result} = $pd->clonePeriodDay($schema,,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),$db->securetext($p->{copyid}),$db->securetext($p->{pasteids})); - } elsif ($p->{fn} eq "clean_staffperiodday"){ - $html->{result} = $pd->cleanPeriodDays($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),$db->securetext($p->{ids})); - } elsif ($p->{fn} eq "replace_staffperiodweekdayhours"){ - $html->{result} = $pd->replaceDayWorkplan($schema,$db->securetext($p->{id_staff}),$db->securetext($p->{id_period}),$db->securetext($p->{id_workplan}),$db->securetext($p->{keepvac}),$db->securetext($p->{keeprec}),$db->securetext($p->{replaceids})); - } elsif ($p->{fn} eq "update_staff_in_period"){ - $html->{result} = $pd->updateStaffPeriod($schema,$db->securetext($p->{id_period}),$db->securetext($p->{id_staff})); - } elsif ($p->{fn} eq "getworktimelimits"){ - $html->{result} = $pd->getPeriodDayLimits($schema,$db->securetext($p->{daydate}),$db->securetext($p->{id_staff})); - } elsif ($p->{fn} eq "refresh_periods"){ - $html->{result} = $pd->refreshPeriods($schema); - } elsif ($p->{fn} eq "add_reportperiod"){ - $html->{result} = $pd->addPeriod($schema); - } elsif ($p->{fn} eq "save_payedhours"){ - $html->{result} = $pd->savePayedHours($schema,$db->securetext($p->{id_period}),$db->securetext($p->{id_staff}),$db->securetext($p->{hourstotransfer}),$db->securetext($p->{hourstotransfercalc}),$db->securetext($p->{payedhours40}),$db->securetext($p->{payedhours40calc}),$db->securetext($p->{payedhours0})); - }elsif ($p->{fn} eq "validate_period"){ - $html->{result} = $pd->validatePeriod($schema,$db->securetext($p->{id_period}),$db->securetext($p->{id_staff}),$db->securetext($p->{hourstotransfer}),$db->securetext($p->{hourstotransfercalc}),$db->securetext($p->{payedhours40}),$db->securetext($p->{payedhours40calc}),$db->securetext($p->{payedhours0})); - } - elsif ($p->{fn} eq "invalidate_period"){ - $html->{result} = $pd->invalidatePeriod($schema,$db->securetext($p->{id_period}),$db->securetext($p->{id_staff})); - } - } elsif ($p->{fn} =~ /add_workplan$|del_workplan$|duplicate_workplan$|workplan_replaceday$|workplan_saveday$/) { - my $wp = POT::Workplan->new({db => $db}); - # print STDERR $p->{fn}.": Workplan\n"; - if ($p->{fn} eq "add_workplan"){ - $html->{result} = $wp->addWorkplan($schema,$db->securetext($p->{name})); - } elsif ($p->{fn} eq "del_workplan"){ - $html->{result} = $wp->deleteWorkplan($schema,$db->securetext($p->{id})); - } elsif ($p->{fn} eq "duplicate_workplan"){ - $html->{result} = $wp->duplicateWorkplan($schema,$db->securetext($p->{id})); - } elsif ($p->{fn} eq "workplan_replaceday"){ - $html->{result} = $wp->replaceWorkplanDay($schema,$db->securetext($p->{copyid}),$db->securetext($p->{pasteid})); - } elsif ($p->{fn} eq "workplan_saveday"){ - #print STDERR Dumper($p->{workplanday}); - $html->{result} = $wp->saveWorkplanDay($schema,$p->{workplanday},$db->securetext($p->{id})); - } - } elsif ($p->{fn} =~ /del_worktimes$/) { - # print STDERR $p->{fn}.": Worktime\n"; - my $wk = POT::Worktime->new({db => $db}); - if ($p->{fn} eq "del_worktimes"){ - $html->{result} = $wk->deleteWorktime($schema,$db->securetext($p->{id})); - } - } elsif ($p->{fn} =~ /del_user$|add_user$|useracceptedterms$|validatelogin$|changelanguage$/) { - # print STDERR $p->{fn}.": User\n"; - my $us = POT::User->new({db => $db}); - if ($p->{fn} eq "del_user"){ - if ($sess->{id} ne $p->{id}){ - $html->{result} = $us->deleteUser($db->securetext($p->{id})); - } - } elsif ($p->{fn} eq "add_user"){ - $html->{result} = $us->addUser($p); - } elsif( $p->{fn} eq "useracceptedterms"){ - $html->{result} = $us->SetAcceptedTerms($sess->{id}); - } elsif($p->{fn} eq "validatelogin"){ - - $html->{result} = $us->ValidateLogin($db->securetext($p->{username}),$sess->{id}); - } elsif($p->{fn} eq "changelanguage"){ - - $html->{result} = $us->ChangeLanguage($db->securetext($p->{lang}),$sess->{id}); - } - - } elsif ($p->{fn} =~ /savetrackdatasets$/){ - my $tt = POT::TimeTracker->new({db => $db}); - # print STDERR $p->{fn}.": TimeTracker\n"; - if ($p->{fn} eq "savetrackdatasets"){ - $html->{result} = $tt->saveTrackDataSets($schema,$p->{daydate},$p->{id_staff},$p->{timetrackdata}); - } - } - # else{ - # print STDERR "fn:".$p->{fn}." not found\n"; - # } - } -} -$db->disconnect(); -print JSON::PP::encode_json($html); diff --git a/app/db.php b/app/db.php index da630577..ad0db476 100644 --- a/app/db.php +++ b/app/db.php @@ -5,6 +5,7 @@ foreach ($mainclasses as $key => $value) { if ((is_file("lib/".$value) && strpos($value,'.') !== 0) && substr_compare($value, ".php", -strlen(".php")) === 0){ + //error_log("lib/".$value); require("lib/".$value); } } @@ -12,7 +13,7 @@ foreach ($moduleclasses as $key => $value) { if ((is_file("lib/POT/".$value) && strpos($value,'.') !== 0) && substr_compare($value, ".php", -strlen(".php")) === 0){ - error_log($value); + //error_log("lib/POT/".$value); require("lib/POT/".$value); } } @@ -146,13 +147,13 @@ } } elseif (preg_match('/gettrackday$|emptytrackdataset$|getTimeTrackerList$/',$p["get"])){ - $st = TimeTracker($db,$cfg); + $tt = new TimeTracker($db,$cfg); if ($p["get"] == 'gettrackday'){ - $hres = $st->getTrackDay($schema,$db->securetext($p["id_staff"]),$db->securetext($p["daydate"])); + $hres = $tt->getTrackDay($schema,$db->securetext($p["id_staff"]),$db->securetext($p["daydate"])); } elseif ($p["get"] == 'emptytrackdataset'){ - $hres = $st->getEmptyTrackDataSet($schema,$db->securetext($p["id_staff"]),$db->securetext($p["daydate"])); + $hres = $tt->getEmptyTrackDataSet($schema,$db->securetext($p["id_staff"]),$db->securetext($p["daydate"])); } elseif ($p["get"] == 'getTimeTrackerList'){ - $hres = $st->getTimeTrackerList($schema); + $hres = $tt->getTimeTrackerList($schema); } } elseif (preg_match('/userschemaaccess$|termsstatus$|userlist$|user$|usergrouplist$/',$p["get"])){ $us = new User($db,$cfg); @@ -241,22 +242,38 @@ unset($p["table"]); $schema = "public"; - if (isset($p["schemata"])){$schema = $db->securetext($p["schemata"]);} - foreach ($p as $px){ - if (str_ends_with($px,'_id') && ($p[$px] == "")) { - $type="ins"; - unset($p[$px]); - } - if (!strpos($px,$table)){unset($p[$px]);} + $ident = array(); + $data = array(); + if (isset($p["schemata"])){ + $schema = $db->securetext($p["schemata"]); + unset($p["schemata"]); + } + + foreach ($p as $k => $v){ + if (strstr($k,$table)){ + if (startsWith($k,"ident_")){ + $col = substr($k,6 + strlen($table) + 1); + $ident[$col] = $v; + } else { + $col = substr($k,strlen($table) + 1); + $data[$col] = $v; + } + if (endsWith($k,'_id') && ($v == "")) { + $type="ins"; + } + } } - $sql = array(); - if ($type == "ins"){$sql = $db->create_ddl_insert($schema,$p);} - else { $sql = $db->create_ddl_update($schema,$p);} + error_log("ident:".print_r($ident,true)); + error_log("DATA:".print_r($data,true)); + //$sql = array(); + if (count($data) > 0){ + if ($type == "ins"){$sql = $db->createInsertDDL($schema,$table,$data);} + else { $sql = $db->createUpdateDDL($schema,$table,$ident,$data);} + error_log("save_form: ".$sql); #$html["sql"] = \@sql; - if (count($sql) > 0){ - $retid= $db->exec($sql[0]); + $retid= $db->exec($sql); + $html["result"] = $retid["0"]; } - $html["result"] = $retid["0"]; } elseif (isset($p["fn"])){ $schema = "public"; @@ -266,6 +283,7 @@ # print STDERR $p["fn"]."\n"; if ($p["fn"] == "setsessiondata"){ $sid = $sess["idsession"]; + error_log(print_r($p["params"],true)); $res = $se->setsessiondata($sid,$p["params"]); $html["result"]["sessiondata"] = $res; } diff --git a/app/static/img/POT-logo.png b/app/img/POT-logo.png similarity index 100% rename from app/static/img/POT-logo.png rename to app/img/POT-logo.png diff --git a/app/static/img/bg1.jpg b/app/img/bg1.jpg similarity index 100% rename from app/static/img/bg1.jpg rename to app/img/bg1.jpg diff --git a/app/static/img/chrome.png b/app/img/chrome.png similarity index 100% rename from app/static/img/chrome.png rename to app/img/chrome.png diff --git a/app/static/img/chrome.svg b/app/img/chrome.svg similarity index 100% rename from app/static/img/chrome.svg rename to app/img/chrome.svg diff --git a/app/static/img/edge.png b/app/img/edge.png similarity index 100% rename from app/static/img/edge.png rename to app/img/edge.png diff --git a/app/static/img/edge.svg b/app/img/edge.svg similarity index 100% rename from app/static/img/edge.svg rename to app/img/edge.svg diff --git a/app/static/img/favicon/android-icon-144x144.png b/app/img/favicon/android-icon-144x144.png similarity index 100% rename from app/static/img/favicon/android-icon-144x144.png rename to app/img/favicon/android-icon-144x144.png diff --git a/app/static/img/favicon/android-icon-192x192.png b/app/img/favicon/android-icon-192x192.png similarity index 100% rename from app/static/img/favicon/android-icon-192x192.png rename to app/img/favicon/android-icon-192x192.png diff --git a/app/static/img/favicon/android-icon-36x36.png b/app/img/favicon/android-icon-36x36.png similarity index 100% rename from app/static/img/favicon/android-icon-36x36.png rename to app/img/favicon/android-icon-36x36.png diff --git a/app/static/img/favicon/android-icon-48x48.png b/app/img/favicon/android-icon-48x48.png similarity index 100% rename from app/static/img/favicon/android-icon-48x48.png rename to app/img/favicon/android-icon-48x48.png diff --git a/app/static/img/favicon/android-icon-512x512.png b/app/img/favicon/android-icon-512x512.png similarity index 100% rename from app/static/img/favicon/android-icon-512x512.png rename to app/img/favicon/android-icon-512x512.png diff --git a/app/static/img/favicon/android-icon-72x72.png b/app/img/favicon/android-icon-72x72.png similarity index 100% rename from app/static/img/favicon/android-icon-72x72.png rename to app/img/favicon/android-icon-72x72.png diff --git a/app/static/img/favicon/android-icon-96x96.png b/app/img/favicon/android-icon-96x96.png similarity index 100% rename from app/static/img/favicon/android-icon-96x96.png rename to app/img/favicon/android-icon-96x96.png diff --git a/app/static/img/favicon/apple-icon-114x114.png b/app/img/favicon/apple-icon-114x114.png similarity index 100% rename from app/static/img/favicon/apple-icon-114x114.png rename to app/img/favicon/apple-icon-114x114.png diff --git a/app/static/img/favicon/apple-icon-120x120.png b/app/img/favicon/apple-icon-120x120.png similarity index 100% rename from app/static/img/favicon/apple-icon-120x120.png rename to app/img/favicon/apple-icon-120x120.png diff --git a/app/static/img/favicon/apple-icon-144x144.png b/app/img/favicon/apple-icon-144x144.png similarity index 100% rename from app/static/img/favicon/apple-icon-144x144.png rename to app/img/favicon/apple-icon-144x144.png diff --git a/app/static/img/favicon/apple-icon-152x152.png b/app/img/favicon/apple-icon-152x152.png similarity index 100% rename from app/static/img/favicon/apple-icon-152x152.png rename to app/img/favicon/apple-icon-152x152.png diff --git a/app/static/img/favicon/apple-icon-180x180.png b/app/img/favicon/apple-icon-180x180.png similarity index 100% rename from app/static/img/favicon/apple-icon-180x180.png rename to app/img/favicon/apple-icon-180x180.png diff --git a/app/static/img/favicon/apple-icon-57x57.png b/app/img/favicon/apple-icon-57x57.png similarity index 100% rename from app/static/img/favicon/apple-icon-57x57.png rename to app/img/favicon/apple-icon-57x57.png diff --git a/app/static/img/favicon/apple-icon-60x60.png b/app/img/favicon/apple-icon-60x60.png similarity index 100% rename from app/static/img/favicon/apple-icon-60x60.png rename to app/img/favicon/apple-icon-60x60.png diff --git a/app/static/img/favicon/apple-icon-72x72.png b/app/img/favicon/apple-icon-72x72.png similarity index 100% rename from app/static/img/favicon/apple-icon-72x72.png rename to app/img/favicon/apple-icon-72x72.png diff --git a/app/static/img/favicon/apple-icon-76x76.png b/app/img/favicon/apple-icon-76x76.png similarity index 100% rename from app/static/img/favicon/apple-icon-76x76.png rename to app/img/favicon/apple-icon-76x76.png diff --git a/app/static/img/favicon/apple-icon-precomposed.png b/app/img/favicon/apple-icon-precomposed.png similarity index 100% rename from app/static/img/favicon/apple-icon-precomposed.png rename to app/img/favicon/apple-icon-precomposed.png diff --git a/app/static/img/favicon/apple-icon.png b/app/img/favicon/apple-icon.png similarity index 100% rename from app/static/img/favicon/apple-icon.png rename to app/img/favicon/apple-icon.png diff --git a/app/static/img/favicon/browserconfig.xml b/app/img/favicon/browserconfig.xml similarity index 100% rename from app/static/img/favicon/browserconfig.xml rename to app/img/favicon/browserconfig.xml diff --git a/app/static/img/favicon/favicon-16x16.png b/app/img/favicon/favicon-16x16.png similarity index 100% rename from app/static/img/favicon/favicon-16x16.png rename to app/img/favicon/favicon-16x16.png diff --git a/app/static/img/favicon/favicon-32x32.png b/app/img/favicon/favicon-32x32.png similarity index 100% rename from app/static/img/favicon/favicon-32x32.png rename to app/img/favicon/favicon-32x32.png diff --git a/app/static/img/favicon/favicon-96x96.png b/app/img/favicon/favicon-96x96.png similarity index 100% rename from app/static/img/favicon/favicon-96x96.png rename to app/img/favicon/favicon-96x96.png diff --git a/app/static/img/favicon/favicon.ico b/app/img/favicon/favicon.ico similarity index 100% rename from app/static/img/favicon/favicon.ico rename to app/img/favicon/favicon.ico diff --git a/app/static/img/favicon/manifest.json b/app/img/favicon/manifest.json similarity index 100% rename from app/static/img/favicon/manifest.json rename to app/img/favicon/manifest.json diff --git a/app/static/img/favicon/ms-icon-144x144.png b/app/img/favicon/ms-icon-144x144.png similarity index 100% rename from app/static/img/favicon/ms-icon-144x144.png rename to app/img/favicon/ms-icon-144x144.png diff --git a/app/static/img/favicon/ms-icon-150x150.png b/app/img/favicon/ms-icon-150x150.png similarity index 100% rename from app/static/img/favicon/ms-icon-150x150.png rename to app/img/favicon/ms-icon-150x150.png diff --git a/app/static/img/favicon/ms-icon-310x310.png b/app/img/favicon/ms-icon-310x310.png similarity index 100% rename from app/static/img/favicon/ms-icon-310x310.png rename to app/img/favicon/ms-icon-310x310.png diff --git a/app/static/img/favicon/ms-icon-70x70.png b/app/img/favicon/ms-icon-70x70.png similarity index 100% rename from app/static/img/favicon/ms-icon-70x70.png rename to app/img/favicon/ms-icon-70x70.png diff --git a/app/static/img/firefox.svg b/app/img/firefox.svg similarity index 100% rename from app/static/img/firefox.svg rename to app/img/firefox.svg diff --git a/app/static/img/logo_512.png b/app/img/logo_512.png similarity index 100% rename from app/static/img/logo_512.png rename to app/img/logo_512.png diff --git a/app/static/img/logo_512_xx.png b/app/img/logo_512_xx.png similarity index 100% rename from app/static/img/logo_512_xx.png rename to app/img/logo_512_xx.png diff --git a/app/static/img/opera.svg b/app/img/opera.svg similarity index 100% rename from app/static/img/opera.svg rename to app/img/opera.svg diff --git a/app/static/img/potbg.jpg b/app/img/potbg.jpg similarity index 100% rename from app/static/img/potbg.jpg rename to app/img/potbg.jpg diff --git a/app/static/img/poticon512.png b/app/img/poticon512.png similarity index 100% rename from app/static/img/poticon512.png rename to app/img/poticon512.png diff --git a/app/static/img/potlogowhite.svg b/app/img/potlogowhite.svg similarity index 100% rename from app/static/img/potlogowhite.svg rename to app/img/potlogowhite.svg diff --git a/app/static/img/pottop.png b/app/img/pottop.png similarity index 100% rename from app/static/img/pottop.png rename to app/img/pottop.png diff --git a/app/static/img/safari.png b/app/img/safari.png similarity index 100% rename from app/static/img/safari.png rename to app/img/safari.png diff --git a/app/static/img/safari.svg b/app/img/safari.svg similarity index 100% rename from app/static/img/safari.svg rename to app/img/safari.svg diff --git a/app/static/img/splashscreens/ipad_splash.png b/app/img/splashscreens/ipad_splash.png similarity index 100% rename from app/static/img/splashscreens/ipad_splash.png rename to app/img/splashscreens/ipad_splash.png diff --git a/app/static/img/splashscreens/ipadpro1_splash.png b/app/img/splashscreens/ipadpro1_splash.png similarity index 100% rename from app/static/img/splashscreens/ipadpro1_splash.png rename to app/img/splashscreens/ipadpro1_splash.png diff --git a/app/static/img/splashscreens/ipadpro2_splash.png b/app/img/splashscreens/ipadpro2_splash.png similarity index 100% rename from app/static/img/splashscreens/ipadpro2_splash.png rename to app/img/splashscreens/ipadpro2_splash.png diff --git a/app/static/img/splashscreens/ipadpro3_splash.png b/app/img/splashscreens/ipadpro3_splash.png similarity index 100% rename from app/static/img/splashscreens/ipadpro3_splash.png rename to app/img/splashscreens/ipadpro3_splash.png diff --git a/app/static/img/splashscreens/iphone5_splash.png b/app/img/splashscreens/iphone5_splash.png similarity index 100% rename from app/static/img/splashscreens/iphone5_splash.png rename to app/img/splashscreens/iphone5_splash.png diff --git a/app/static/img/splashscreens/iphone6_splash.png b/app/img/splashscreens/iphone6_splash.png similarity index 100% rename from app/static/img/splashscreens/iphone6_splash.png rename to app/img/splashscreens/iphone6_splash.png diff --git a/app/static/img/splashscreens/iphoneplus_splash.png b/app/img/splashscreens/iphoneplus_splash.png similarity index 100% rename from app/static/img/splashscreens/iphoneplus_splash.png rename to app/img/splashscreens/iphoneplus_splash.png diff --git a/app/static/img/splashscreens/iphonex_splash.png b/app/img/splashscreens/iphonex_splash.png similarity index 100% rename from app/static/img/splashscreens/iphonex_splash.png rename to app/img/splashscreens/iphonex_splash.png diff --git a/app/static/img/splashscreens/iphonexr_splash.png b/app/img/splashscreens/iphonexr_splash.png similarity index 100% rename from app/static/img/splashscreens/iphonexr_splash.png rename to app/img/splashscreens/iphonexr_splash.png diff --git a/app/static/img/splashscreens/iphonexsmax_splash.png b/app/img/splashscreens/iphonexsmax_splash.png similarity index 100% rename from app/static/img/splashscreens/iphonexsmax_splash.png rename to app/img/splashscreens/iphonexsmax_splash.png diff --git a/app/static/img/toplogo.png b/app/img/toplogo.png similarity index 100% rename from app/static/img/toplogo.png rename to app/img/toplogo.png diff --git a/app/index.cgi b/app/index.cgi deleted file mode 100644 index d61c72e8..00000000 --- a/app/index.cgi +++ /dev/null @@ -1,160 +0,0 @@ -#!/usr/local/bin/perl - -use strict; -use lib ('./lib/perl5'); -use lib ('./lib'); -use File::Basename qw/dirname basename/; -use Template; -# use Template::Constants qw( :debug ); -use CGI; -#use CGI::Carp qw(fatalsToBrowser); -use CGI::Cookie; -use Data::Dumper; -use JSON::PP; - -use dksconfig qw/$sitecfg/; -use session; -use dksdb; -my $skl = "index.tt"; -my $cgi = new CGI(); -my $p=(); -my $cookie; -my $db = dksdb->new({dsn => $sitecfg->{dsn},dbuser => $sitecfg->{dbuser},dbpassword => $sitecfg->{dbpassword}}); -my $vars = $sitecfg; -my $sess = (); -my $se = session->new({db => $db}); -$vars->{isapp} = "0"; -$vars->{ua} = $ENV{HTTP_USER_AGENT}; -if ($vars->{ua} =~ /^POT/){ - $vars->{isapp} = "1"; -# print "Location: https://www.plandutravail.lu\n\n"; -# exit(0); -} -$vars->{realpath} = $cgi->url({-absolute=>1}); -$vars->{filepath} = substr($cgi->url({-absolute=>1}),length($vars->{basepath})+1); -$vars->{baseurl} = $cgi->url({-base=>1}).'/'.$vars->{basepath}; -$vars->{siteurl} = $cgi->url({-base=>1}); -#$vars->{mode} = $vars->{siteurl}; -if ($vars->{siteurl} ne "https://app.plandutravail.lu"){ - $vars->{mode} = $vars->{siteurl}; -} - - -if ($vars->{filepath} ne ""){ - $vars->{suffix} = substr($vars->{filepath},rindex($vars->{filepath},'.')); - $vars->{page} = $vars->{filepath}; - $vars->{page} =~ s/html$/tt/; -} -$vars->{abspath} = ""; - - -$p->{sid} = $cgi->cookie($vars->{cookiename}); -#print STDERR "cookie: ".$vars->{cookiename}." : ".$p->{sid}."\n--\n"; -if ($cgi->request_method() eq "GET"){ - my @params = $cgi->param(); - foreach my $pp (@params){ - $p->{$pp} = $cgi->param($pp); - } -} - -if (($cgi->request_method() eq "POST") || ($cgi->request_method() eq "GET")){ - - my @params = $cgi->param(); - foreach my $pp (@params){ - $p->{$pp} = $cgi->param($pp); - } - $vars->{hasposts} = $p; - if (exists($p->{'btnlogin'})){ - my $ret = $se->checklogin($p->{login},$p->{password}); - - if ($ret->{sid} ne ""){ - $p->{sid} = $ret->{sid}; - - $cookie = CGI::Cookie->new(-name=>$vars->{cookiename},-value=>$p->{sid},-httponly => 1, -expires => '+6M', - '-max-age' => '+6M'); - - }else { - $vars->{message} = $ret->{message}; - $vars->{messagetype} = $ret->{messagetype}; - $vars->{page} = "message.tt"; - } - } - - if (exists($p->{'btnforgotpassword'})){ - my $ret = $se->passwordforgotten($p->{email}); - $vars->{message} = $ret->{message}; - $vars->{messagetype} = $ret->{messagetype}; - $vars->{page} = "message.tt"; - } - - - if (exists($p->{logout})){ - $se->deletesession($p->{sid}); - $p->{sid} = ""; - $cookie = CGI::Cookie->new(-name=>$vars->{cookiename},-value=>"",-httponly => 1); - } -} -if ($p->{sid} ne ""){ - $sess = $se->getsession($p->{sid}); - #print STDERR "after sessioncheck:".Dumper($sess); - if ($sess == undef){ - $p->{sid} = ""; - $skl = "login.tt"; - } elsif ($vars->{page} eq "login.tt"){ - $vars->{page} = 'index.tt'; - } -} else { - $skl = "login.tt"; -} -if ($skl == "login.tt"){ - if ((lc($vars->{ua}) =~ /trident/) || (lc($vars->{ua}) =~ /msie/)){ - $skl = "browser.tt"; - } -} - -$vars->{session} = $sess; -my $ctype = 'text/html'; -if ($vars->{suffix} eq ".js"){ - $vars->{ctype}= "application/javascript"; - $skl = "file.tt"; -} elsif ($vars->{suffix} eq ".css"){ - $vars->{ctype} = "text/css"; - $skl = "file.tt"; -} -print $cgi->header(-type=>$ctype, -charset=>"utf-8", -cookie => $cookie); - -$vars->{session} = $sess; - -$vars->{abspath} = ""; -if ($vars->{page} =~ /\//){ - my @spl = split(/\//,$vars->{page}); - foreach (my $i = 1; $i< scalar(@spl); $i++){ - $vars->{abspath} .= "../"; - } -} -# } -$vars->{page} = 'module/'.$vars->{page}; -$vars->{pagename} = basename($vars->{page}); -$vars->{pagename} =~ s/\.tt$//; - -if ($sess->{id}){ - $vars->{cmpcfg} = $se->getCompanyConfig($sess->{sessiondata}->{schemata}); -} -$vars->{params}= $p; -if ($sess->{lang} eq ""){ - $sess->{lang} = "fr"; -} -$vars->{lang} = $sess->{lang}; - -$vars->{skl} = $skl; - -$vars->{ua} = $ENV{HTTP_USER_AGENT}; -$vars->{remote_addr} = $ENV{REMOTE_ADDR}; -my $template = Template->new({INCLUDE_PATH => [$sitecfg->{tmplpath}]}); -$template->process($skl,$vars) || die "Template process failed: ", $template->error(), "\n"; -$db->disconnect(); -# if ($vars->{page} =~ /\.tt/){ -# print '
'.Dumper($vars)."
";
-# } 
-
-
diff --git a/app/static/js/app.js b/app/js/app.js
similarity index 97%
rename from app/static/js/app.js
rename to app/js/app.js
index a3e98746..d872e9db 100644
--- a/app/static/js/app.js
+++ b/app/js/app.js
@@ -1,100 +1,100 @@
-let app = {
-    loadpage: function(modulepage, modulename) {
-      location.href=modulepage;
-    },
-    logout: function() {
-      postData(location.href, { "logout": "1" }).then (data => { location.href = 'login.html';});
-    },
-    reloadpage() { },
-    changedataset: function(){},
-    getCurrentSchemata: function(){
-      return schemata;
-    },
-    changedataset: function(){
-      let csel = document.getElementById("current_schemata").value;
-      schemata =  csel;
-      postData("db.php",{"fn":"setsessiondata","params":{"schemata":csel}}).then(data => {
-        document.getElementById("current_schemata").dataset.selected = csel;
-      });
-    },
-    setschemata(data){
-    },
-    reload_page: function() {
-      location.href = location.href;
-    },
-    viewpanel: function(pnlname){
-      let panels = document.getElementsByClassName("panel");
-      let toolbars = document.getElementsByClassName("paneltoolbar");
-      currentview = pnlname;
-      for (let p=0;p console.log("service worker registered"))
-      .catch(err => console.log("service worker not registered", err))
-  })
-}
+let app = {
+    loadpage: function(modulepage, modulename) {
+      location.href=modulepage;
+    },
+    logout: function() {
+      postData(location.href, { "logout": "1" }).then (data => { location.href = 'login.html';});
+    },
+    reloadpage() { },
+    changedataset: function(){},
+    getCurrentSchemata: function(){
+      return schemata;
+    },
+    changedataset: function(){
+      let csel = document.getElementById("current_schemata").value;
+      schemata =  csel;
+      postData("db.php",{"fn":"setsessiondata","params":{"schemata":csel}}).then(data => {
+        document.getElementById("current_schemata").dataset.selected = csel;
+      });
+    },
+    setschemata(data){
+    },
+    reload_page: function() {
+      location.href = location.href;
+    },
+    viewpanel: function(pnlname){
+      let panels = document.getElementsByClassName("panel");
+      let toolbars = document.getElementsByClassName("paneltoolbar");
+      currentview = pnlname;
+      for (let p=0;p console.log("service worker registered"))
+      .catch(err => console.log("service worker not registered", err))
+  })
+}
diff --git a/app/static/js/dataform.js b/app/js/dataform.js
similarity index 100%
rename from app/static/js/dataform.js
rename to app/js/dataform.js
diff --git a/app/static/js/report.js b/app/js/report.js
similarity index 73%
rename from app/static/js/report.js
rename to app/js/report.js
index 97733df7..08abf969 100644
--- a/app/static/js/report.js
+++ b/app/js/report.js
@@ -1,13 +1,13 @@
 var report ={
   generate: function(repname,filename,data){
     showdataloaddlg("Création PDF encours","Attendez s.v.p.");//closedataloaddlg();
-    postData("report.cgi",{"generate":repname,"file": filename + ".pdf","data":data}).then(data => {closedataloaddlg();;report.openreport(data.result)}).catch(e => {closedataloaddlg();});
+    postData("report.php",{"generate":repname,"file": filename + ".pdf","data":data}).then(data => {closedataloaddlg();;report.openreport(data.result)}).catch(e => {closedataloaddlg();});
     return false;
   },
   openreport(data){
     
     if (data && data.file){
-      window.open(api + "report.cgi?open=" + encodeURIComponent(data.file));
+      window.open(api + "report.php?open=" + encodeURIComponent(data.file));
     }
   }
 }
\ No newline at end of file
diff --git a/app/static/js/request.js b/app/js/request.js
similarity index 100%
rename from app/static/js/request.js
rename to app/js/request.js
diff --git a/app/static/js/sw.js b/app/js/sw.js
similarity index 94%
rename from app/static/js/sw.js
rename to app/js/sw.js
index 0a364eac..e3e5d96b 100644
--- a/app/static/js/sw.js
+++ b/app/js/sw.js
@@ -1,21 +1,21 @@
-const staticpot = "pot"
-const assets = [
-  "/",
-  "/index.html"
-]
-
-self.addEventListener("install", installEvent => {
-  installEvent.waitUntil(
-    caches.open(staticpot).then(cache => {
-      cache.addAll(assets)
-    })
-  )
-})
-
-self.addEventListener("fetch", fetchEvent => {
-  fetchEvent.respondWith(
-    caches.match(fetchEvent.request).then(res => {
-      return res || fetch(fetchEvent.request)
-    })
-  )
+const staticpot = "pot"
+const assets = [
+  "/",
+  "/index.html"
+]
+
+self.addEventListener("install", installEvent => {
+  installEvent.waitUntil(
+    caches.open(staticpot).then(cache => {
+      cache.addAll(assets)
+    })
+  )
+})
+
+self.addEventListener("fetch", fetchEvent => {
+  fetchEvent.respondWith(
+    caches.match(fetchEvent.request).then(res => {
+      return res || fetch(fetchEvent.request)
+    })
+  )
 })
\ No newline at end of file
diff --git a/app/static/js/timecalc.js b/app/js/timecalc.js
similarity index 100%
rename from app/static/js/timecalc.js
rename to app/js/timecalc.js
diff --git a/app/lib/POT/Period.php b/app/lib/POT/Period.php
index 86bb1b88..8d66ebda 100644
--- a/app/lib/POT/Period.php
+++ b/app/lib/POT/Period.php
@@ -66,8 +66,7 @@ function getStaffPeriodSplitted($schema,$id_staff,$id_period,$id_groups){
   if (isset($id_groups)){
     $wgroups .= " and sgr.id in ('".join("','",$id_groups)."') ";
   }
-  $sql = "select
-  st.prename,st.surname, coalesce(st.prename,'') || ' ' || coalesce(st.surname,'') as staffname,
+  $sql = "select st.prename,st.surname, coalesce(st.prename,'') || ' ' || coalesce(st.surname,'') as staffname,
   srp.id as id_staffreportperiod,
   pd.id_staff,
   psplit.id_reportperiod as id_reportperiod,
@@ -354,7 +353,7 @@ function updatePeriodDaySums($schema,$dayids){
   if (is_array($dayids)){
     $dayselect = "'".join("','",$dayids)."'";
   }else {
-    if (str_starts_with(strtolower($dayids),'select')){
+    if (startsWith(strtolower($dayids),'select')){
       $dayselect=$dayids;
     } else {
       $dayselect = "'".$dayids."'";
@@ -559,18 +558,18 @@ where sc.id_staff='".$id_staff."' order by startdate,enddate;";
   $defdays[$kl]["enddate"] = $dlim["lastday"];
   $delete = array();
   foreach ($defdays as $dd){
-      $cthsql = "select '".$defdays[$dd]["weekhours"]."'::interval/".$defdays[$dd]["weekdays"]." as wdcontracthours" ;
+      $cthsql = "select '".$dd["weekhours"]."'::interval/".$dd["weekdays"]." as wdcontracthours" ;
       if($cp["reportperiodunit"] == 'month'){
-        $cthsql = "select round(cast(((extract(epoch from (current_date + '".$defdays[$dd]["weekhours"]."'::interval)::timestamp) - extract(epoch from current_date::timestamp))/3600.0)/".$defdays[$dd]["weekdays"]." as numeric) ,2) * '01:00:00'::interval as wdcontracthours";
+        $cthsql = "select round(cast(((extract(epoch from (current_date + '".$dd["weekhours"]."'::interval)::timestamp) - extract(epoch from current_date::timestamp))/3600.0)/".$dd["weekdays"]." as numeric) ,2) * '01:00:00'::interval as wdcontracthours";
       } 
     $cth = $this->dbh->query($cthsql);
     $inssql = "insert into ".$schema.".staffreportperioddays (daydate,id_staff,payedpause,wdcontracthours)
 SELECT date_trunc('day', dd)::date as daydate,'".$id_staff."' as id_staff, ".(($cp["payedpauses"] == "1")?"true":"null")." as payedpause, 
- '".$cth->{ wdcontracthours}."' as  wdcontracthours  
-FROM generate_series( '".$defdays[$dd]["startdate"]."'::timestamp,'".$defdays[$dd]["enddate"]."'::timestamp,'1 day'::interval) dd on conflict on constraint uniq_staffworplan_staffday 
-do update set wdcontracthours = '".$cth->{ wdcontracthours}."';";;
+ '".$cth["wdcontracthours"]."' as  wdcontracthours  
+FROM generate_series( '".$dd["startdate"]."'::timestamp,'".$dd["enddate"]."'::timestamp,'1 day'::interval) dd on conflict on constraint uniq_staffworplan_staffday 
+do update set wdcontracthours = '".$cth["wdcontracthours"]."';";
     $this->dbh->exec($inssql);
-    push (@delete," daydate not between date('".$defdays[$dd]["startdate"]."') and date('".$defdays[$dd]["enddate"]."')");
+    array_push($delete," daydate not between date('".$dd["startdate"]."') and date('".$dd["enddate"]."')");
     
   }
   ////VERIFY no more nessessary data 
diff --git a/app/lib/POT/Report.nousephp b/app/lib/POT/Report.php
similarity index 53%
rename from app/lib/POT/Report.nousephp
rename to app/lib/POT/Report.php
index 12245858..4f07e09c 100644
--- a/app/lib/POT/Report.nousephp
+++ b/app/lib/POT/Report.php
@@ -1,194 +1,174 @@
-package POT::Report;
+{db} = $p->{db};
-    $self->{tmp} =$p->{tmp};
-    $self->{pdf}->{app} = dirname($ENV{SCRIPT_FILENAME})."/tools/bin/wkhtmltopdf";
-    $self->{report}->{pot} = {top=>"20mm",bottom =>"15mm",left=>"5mm",right=>"5mm",size=>"A4",orientation=>"Landscape",encoding=>"ISO-8859-1"};
-    return $self;
-}
+class Report{
+  private $dbh;
+  private $cfg;
+  private $legend = array();
+  private $report = array("pot" => array("top"=>"20mm","bottom" =>"15mm","left"=>"5mm","right"=>"5mm","size"=>"A4","orientation"=>"Landscape","encoding"=>"ISO-8859-1"));
+  public function __construct($dblink,$cfg){
+    $this->dbh = $dblink;
+    $this->cfg = $cfg;
+  }
+  public function __destruct(){
+    $this->conn = null;
+  }
 
-sub createReport(){
-  my $self = shift;
-  my $schema = shift;
-  my $template = shift;
-  my $archive =  shift;
-  my $data = shift;
-  my $resReports = ();  
-  if ($template eq "pot"){
-    my $repsql = "select srp.id_staff,srp.id_reportperiod,'pot_' || to_char(rp.startdate,'YYYYMMDD') || '-' || to_char(rp.enddate,'YYYYMMDD') || '_' || coalesce(surname || '_','')  || coalesce(prename,'') || '.pdf' as fname 
+  public function  createReport($schema,$template,$archive,$data){
+  $resReports = array();  
+  if ($template =="pot"){
+    $repsql = "select srp.id_staff,srp.id_reportperiod,'pot_' || to_char(rp.startdate,'YYYYMMDD') || '-' || to_char(rp.enddate,'YYYYMMDD') || '_' || coalesce(surname || '_','')  || coalesce(prename,'') || '.pdf' as fname 
 from ".$schema.".staffreportperiod srp 
 join ".$schema.".reportperiod rp on (srp.id_reportperiod=rp.id)
 join ".$schema.".staff st on (st.id=srp.id_staff)";
-    my @wh = ();
-    if (scalar(@{$data->{id_staff}}) > 0){
-      push (@wh,"srp.id_staff in ('".join("','",@{$data->{id_staff}})."')");
+    $wh = array();
+    if (count($data["id_staff"]) > 0){
+      array_push ($wh,"srp.id_staff in ('".join("','",data["id_staff"])."')");
     }
-    if (scalar(@{$data->{id_period}}) > 0){
-      push (@wh,"srp.id_reportperiod in ('".join("','",@{$data->{id_period}})."')");
+    if (count($data["id_period"]) > 0){
+      array_push ($wh,"srp.id_reportperiod in ('".join("','",$data["id_period"])."')");
     }
-    if (scalar(@wh) >  0){
-      $repsql .= join(' AND ',@wh);
+    if (count($wh) >  0){
+      $repsql .= implode(' AND ',$wh);
     }
-    my $repdata = $self->{db}->querysorted($repsql);
+    $repdata =$this->dbh->queryarray($repsql);
     
-    foreach my $r (keys(%{$repdata})){
-      my $resfile = $self->createPDF($schema,$template,$repdata->{$r}->{fname},{"id_staff" => $repdata->{$r}->{id_staff},"id_period" => $repdata->{$r}->{id_reportperiod}});
-      push(@{$resReports},$resfile);
+    foreach ($repdata as $r){
+      $resfile = $this->createPDF($schema,$template,$repdata[$r]["fname"],array("id_staff" => $repdata[$r]["id_staff"],"id_period" => $repdata[$r]["id_reportperiod"]));
+      array_push($resReports,$resfile);
     }
-  } elsif ($template eq "tracker"){
+  } elseif ($template =="tracker"){
 
   }
   return $resReports;
 }
 
-sub createPDF(){
-  my $self = shift;
-  my $schema = shift;
-  my $template = shift;
-  my $pdfname  = shift;
-  my $data = shift;
-  my $time = time();
-  my $tmpfile = $template.$time.$$; 
-  my $r = undef;
-  if ($template eq "pot"){
-    $self->printPOTContent($schema,$self->{tmp}.'/'.$tmpfile.".html",$data->{id_staff},$data->{id_period});
-    $self->printPOTHeader($schema,$self->{tmp}.'/'.$tmpfile.".header.html");
-    $self->printPOTFooter($schema,$self->{tmp}.'/'.$tmpfile.".footer.html");
+  public function  createPDF($schema,$template,$pdfname,$data){
+
+  $time = time();
+  $tmpfile = $template.$time; 
+  $r = null;
+  if ($template =="pot"){
+    $this->printPOTContent($schema,$this->cfg["tmppath"].$tmpfile.".html",$data["id_staff"],$data["id_period"]);
+    $this->printPOTHeader($schema,$this->cfg["tmppath"].$tmpfile.".header.html");
+    $this->printPOTFooter($schema,$this->cfg["tmppath"].$tmpfile.".footer.html");
   }
   
   
   
-  #dircopy($self->{tmplpath}.'/'.$template,$self->{tmp}.'/'.$template);
-  if ((-e $self->{tmp}.'/'.$tmpfile.'.html')){
-    my $cmd = '"'.$self->{pdf}->{app}.'"';
-    if ($self->{pdf}->{$template}->{bottom}){ $cmd .= " -B ".$self->{pdf}->{$template}->{bottom}; }
-    if ($self->{pdf}->{$template}->{left}){ $cmd .= " -L ".$self->{pdf}->{$template}->{left}; }
-    if ($self->{pdf}->{$template}->{right}){ $cmd .= " -R ".$self->{pdf}->{$template}->{right}; }
-    if ($self->{pdf}->{$template}->{top}){ $cmd .= " -T ".$self->{pdf}->{$template}->{top}; }
-    if ($self->{pdf}->{$template}->{orientation}){ $cmd .= " -O ".$self->{pdf}->{$template}->{orientation}; }
-    if ($self->{pdf}->{$template}->{size}){ $cmd .= " -s ".$self->{pdf}->{$template}->{size}; }
-    if ($self->{pdf}->{$template}->{encoding}){ $cmd .= " --encoding '".$self->{pdf}->{$template}->{encoding}."'"; }
-    if (-e $self->{tmp}.'/'.$tmpfile.'.header.html'){
-      $cmd .= ' --header-html "'.$self->{tmp}.'/'.$tmpfile.'.header.html"';
+  #dircopy($self->{tmplpath}.'/'.$template,$this->cfg["tmppath"].'/'.$template);
+  if (file_exists($this->cfg["tmppath"].$tmpfile.'.html')){
+    $cmd = '"'.$this->cfg["toolspath"]."/bin/wkhtmltopdf".'"';
+    if ($this->report[$template]["bottom"]){ $cmd .= " -B ".$this->report[$template]["bottom"]; }
+    if ($this->report[$template]["left"]){ $cmd .= " -L ".$this->report[$template]["left"]; }
+    if ($this->report[$template]["right"]){ $cmd .= " -R ".$this->report[$template]["right"]; }
+    if ($this->report[$template]["top"]){ $cmd .= " -T ".$this->report[$template]["top"]; }
+    if ($this->report[$template]["orientation"]){ $cmd .= " -O ".$this->report[$template]["orientation"]; }
+    if ($this->report[$template]["size"]){ $cmd .= " -s ".$this->report[$template]["size"]; }
+    if ($this->report[$template]["encoding"]){ $cmd .= " --encoding '".$this->report[$template]["encoding"]."'"; }
+    if (file_exists($this->cfg["tmppath"].'/'.$tmpfile.'.header.html')){
+      $cmd .= ' --header-html "'.$this->cfg["tmppath"].$tmpfile.'.header.html"';
     }
-    if (-e $self->{tmp}.'/'.$tmpfile.'.footer.html'){
-      $cmd .= ' --footer-html "'.$self->{tmp}.'/'.$tmpfile.'.footer.html"';
+    if (file_exists($this->cfg["tmppath"].'/'.$tmpfile.'.footer.html')){
+      $cmd .= ' --footer-html "'.$this->cfg["tmppath"].$tmpfile.'.footer.html"';
     }
-    $cmd .= ' "'.$self->{tmp}.'/'.$tmpfile.'.html"';
+    $cmd .= ' "'.$this->cfg["tmppath"].'/'.$tmpfile.'.html"';
     $cmd .= ' "'.$pdfname.'"';
+    error_log($cmd);
     #print STDERR $cmd."\n";
     $r = system($cmd);
   }
-  if (-e $pdfname){
-    unlink($self->{tmp}.'/'.$tmpfile.'.html');
-    unlink($self->{tmp}.'/'.$tmpfile.'.header.html');
-    unlink($self->{tmp}.'/'.$tmpfile.'.footer.html');
+  if (file_exists($pdfname)){
+    unlink($this->cfg["tmppath"].'/'.$tmpfile.'.html');
+    unlink($this->cfg["tmppath"].'/'.$tmpfile.'.header.html');
+    unlink($this->cfg["tmppath"].'/'.$tmpfile.'.footer.html');
     return $pdfname;
   }
   return "";
 }
 
-sub createpdf(){
-  my $self = shift;
-  my $schema = shift;
-  my $template = shift;
-  my $output = shift;
-  my $inputdata = shift;
-  my $r = -1;
-  my $pdfreports->{pot}= {top=>"20mm",bottom =>"15mm",left=>"5mm",right=>"5mm",size=>"A4",orientation=>"Landscape",encoding=>"ISO-8859-1"};
-  $self->printContent($schema,$self->{tmp}.'/'.$template.$$.".html",$inputdata);
-  $self->printHeader($schema,$self->{tmp}.'/'.$template.$$.".header.html");
-  $self->printFooter($schema,$self->{tmp}.'/'.$template.$$.".footer.html");
-  #dircopy($self->{tmplpath}.'/'.$template,$self->{tmp}.'/'.$template);
-  if ((-e $self->{tmp}.'/'.$template.$$.'.html')){
-    my $cmd = '"'.$self->{pdf}->{app}.'"';
-    if ($pdfreports->{$template}->{bottom}){ $cmd .= " -B ".$pdfreports->{$template}->{bottom}; }
-    if ($pdfreports->{$template}->{left}){ $cmd .= " -L ".$pdfreports->{$template}->{left}; }
-    if ($pdfreports->{$template}->{right}){ $cmd .= " -R ".$pdfreports->{$template}->{right}; }
-    if ($pdfreports->{$template}->{top}){ $cmd .= " -T ".$pdfreports->{$template}->{top}; }
-    if ($pdfreports->{$template}->{orientation}){ $cmd .= " -O ".$pdfreports->{$template}->{orientation}; }
-    if ($pdfreports->{$template}->{size}){ $cmd .= " -s ".$pdfreports->{$template}->{size}; }
-    if ($pdfreports->{$template}->{encoding}){ $cmd .= " --encoding '".$pdfreports->{$template}->{encoding}."'"; }
-    if (-e $self->{tmp}.'/'.$template.$$.'.header.html'){
-      $cmd .= ' --header-html "'.$self->{tmp}.'/'.$template.$$.'.header.html"';
-    }
-    if (-e $self->{tmp}.'/'.$template.$$.'.footer.html'){
-      $cmd .= ' --footer-html "'.$self->{tmp}.'/'.$template.$$.'.footer.html"';
-    }
-    $cmd .= ' "'.$self->{tmp}.'/'.$template.$$.'.html"';
-    $cmd .= ' "'.$output.'"';
-    #print STDERR $cmd."\n";
-    $r = system($cmd);
-  }
-  if (-e $output){
-    #unlink($self->{tmp}.'/'.$template.$$.'.html');
-    unlink($self->{tmp}.'/'.$template.$$.'.header.html');
-    unlink($self->{tmp}.'/'.$template.$$.'.footer.html');
-    return ($r,$output);
-  }
-  return ($r,undef);
-}
+//   public function  createpdf($schema,$template,$output,$inputdata){
+  
+//   $r = -1;
+//   $pdfreports->{pot}= {top=>"20mm",bottom =>"15mm",left=>"5mm",right=>"5mm",size=>"A4",orientation=>"Landscape",encoding=>"ISO-8859-1"};
+//   $self->printContent($schema,$this->cfg["tmppath"].'/'.$template.$$.".html",$inputdata);
+//   $self->printHeader($schema,$this->cfg["tmppath"].'/'.$template.$$.".header.html");
+//   $self->printFooter($schema,$this->cfg["tmppath"].'/'.$template.$$.".footer.html");
+//   #dircopy($self->{tmplpath}.'/'.$template,$this->cfg["tmppath"].'/'.$template);
+//   if ((-e $this->cfg["tmppath"].'/'.$template.$$.'.html')){
+//     $cmd = '"'.$self->{pdf}->{app}.'"';
+//     if ($pdfreports->{$template}->{bottom}){ $cmd .= " -B ".$pdfreports->{$template}->{bottom}; }
+//     if ($pdfreports->{$template}->{left}){ $cmd .= " -L ".$pdfreports->{$template}->{left}; }
+//     if ($pdfreports->{$template}->{right}){ $cmd .= " -R ".$pdfreports->{$template}->{right}; }
+//     if ($pdfreports->{$template}->{top}){ $cmd .= " -T ".$pdfreports->{$template}->{top}; }
+//     if ($pdfreports->{$template}->{orientation}){ $cmd .= " -O ".$pdfreports->{$template}->{orientation}; }
+//     if ($pdfreports->{$template}->{size}){ $cmd .= " -s ".$pdfreports->{$template}->{size}; }
+//     if ($pdfreports->{$template}->{encoding}){ $cmd .= " --encoding '".$pdfreports->{$template}->{encoding}."'"; }
+//     if (-e $this->cfg["tmppath"].'/'.$template.$$.'.header.html'){
+//       $cmd .= ' --header-html "'.$this->cfg["tmppath"].'/'.$template.$$.'.header.html"';
+//     }
+//     if (-e $this->cfg["tmppath"].'/'.$template.$$.'.footer.html'){
+//       $cmd .= ' --footer-html "'.$this->cfg["tmppath"].'/'.$template.$$.'.footer.html"';
+//     }
+//     $cmd .= ' "'.$this->cfg["tmppath"].'/'.$template.$$.'.html"';
+//     $cmd .= ' "'.$output.'"';
+//     #print STDERR $cmd."\n";
+//     $r = system($cmd);
+//   }
+//   if (-e $output){
+//     #unlink($this->cfg["tmppath"].'/'.$template.$$.'.html');
+//     unlink($this->cfg["tmppath"].'/'.$template.$$.'.header.html');
+//     unlink($this->cfg["tmppath"].'/'.$template.$$.'.footer.html');
+//     return ($r,$output);
+//   }
+//   return ($r,undef);
+// }
+
+  public function  printPOTHeader($schema,$outfile){
 
-sub printPOTHeader(){
-  my $self = shift;
-  my $schema = shift;
-  my $outfile = shift;
-  my $cmp= $self->{db}->query_unenc("select * from public.companies where schemata='".$schema."';");
-  open(HD,">".$outfile);
-  print HD "
+  $cmp=$this->dbh->query("select * from public.companies where schemata='".$schema."';");
+  //Registre des heures prestées":"Plan d'Organisation du Travail")."
+  $outdata = "
   
   
   
   
-

".(($cmp->{periodtypes} eq "<15")?"Registre des heures prestées":"Plan d'Organisation du Travail")."

+

".(($cmp["periodtypes"] =="<15")?"Registre des heures prestées":"Plan d'Organisation du Travail")."

- ".$cmp->{company}." ".$cmp->{socialtype}."
- ".$cmp->{address}."
- ".$cmp->{zip}." ".$cmp->{city}."

+ ".$cmp["company"]." ".$cmp["socialtype"]."
+ ".$cmp["address"]."
+ ".$cmp["zip"]." ".$cmp["city"]."

"; - close(HD); + return 1; } -sub printPOTFooter(){ - my $self = shift; - my $schema = shift; - my $outfile = shift; - open(FT,">".$outfile); - print FT " + public function printPOTFooter($schema,$outfile){ + $vleg = "SELECT vacancyname,legend FROM ".$schema.".vacancytypes WHERE isworktime=true order by legend;"; + $vrec = "SELECT vacancyname,legend FROM ".$schema.".vacancytypes WHERE isworktime<>true order by legend;"; + $outdata= " - + + $outdata .= "
 
"; - print FT "
Congé: "; - my $vleg = $self->{db}->querysorted("SELECT vacancyname,legend FROM ".$schema.".vacancytypes WHERE isworktime=true order by legend;"); - foreach my $v (sort {$a <=> $b} keys(%{$vleg})){ - print FT $vleg->{$v}->{legend}.") ".$vleg->{$v}->{vacancyname}." "; + $outdata .= "
Congé: "; + $vleg =$this->dbh->queryarray("SELECT vacancyname,legend FROM ".$schema.".vacancytypes WHERE isworktime=true order by legend;"); + foreach ($vleg as $v){ + $outdata .= $v["legend"].") ".$v["vacancyname"]." "; } - print FT "
"; - print FT '
Récupération: '; - my $rleg = $self->{db}->querysorted("SELECT vacancyname,legend FROM ".$schema.".vacancytypes WHERE isworktime<>true order by legend;"); - foreach my $r (sort {$a <=> $b} keys(%{$rleg})){ - print FT $rleg->{$r}->{legend}.") ".$rleg->{$r}->{vacancyname}." "; + $outdata .= "
"; + $outdata .= '
Récupération: '; + $rleg =$this->dbh->queryarray("SELECT vacancyname,legend FROM ".$schema.".vacancytypes WHERE isworktime<>true order by legend;"); + foreach ($rleg as $r){ + $outdata .= $r["legend"].") ".$r["vacancyname"]." "; } - print FT "
Page /
"; - close(FT); + file_put_contents($outfile,$outdata); return 1; } -sub printPOTContent(){ - my $self = shift; - my $schema = shift; - my $outfile = shift; - my $id_staff = shift; - my $id_period = shift; - $self->{legend}->{vacancy} = $self->{db}->querybykey("id","SELECT id,legend FROM ".$schema.".vacancytypes WHERE isworktime=true order by legend;"); - $self->{legend}->{recup} = $self->{db}->querybykey("id","SELECT id,legend FROM ".$schema.".vacancytypes WHERE isworktime<>true order by legend;"); - open(CT,">".$outfile); - print CT " + public function printPOTContent($schema,$outfile,$id_staff,$id_period){ + + $legend["vacancy"] =$this->dbh->querybykey("id","SELECT id,legend FROM ".$schema.".vacancytypes WHERE isworktime=true order by legend;"); + $legend["recup"] =$this->dbh->querybykey("id","SELECT id,legend FROM ".$schema.".vacancytypes WHERE isworktime<>true order by legend;"); + + $outdata .= " @@ -269,7 +245,7 @@ sub printPOTContent(){ "; - my $sql = "select rp.id,rp.startdate,rp.enddate,st.prename,st.surname,st.staffnumber,st.matricule,to_char(rp.startdate,'DD.MM.YYYY') as dspstartdate,to_char(rp.enddate,'DD.MM.YYYY') as dspenddate, srp.id_staff, + $sql = "select rp.id,rp.startdate,rp.enddate,st.prename,st.surname,st.staffnumber,st.matricule,to_char(rp.startdate,'DD.MM.YYYY') as dspstartdate,to_char(rp.enddate,'DD.MM.YYYY') as dspenddate, srp.id_staff, to_char(srp.contracthours, 'HH24:MI'::text) AS contracthours, to_char(srp.workhours, 'HH24:MI'::text) AS workhours, to_char(srp.vacancyhours, 'HH24:MI'::text) AS vacancyhours, @@ -288,28 +264,26 @@ sub printPOTContent(){ join ".$schema.".staff st on (srp.id_staff=st.id) where st.isdeleted is null and id_staff='".$id_staff."' and srp.id_reportperiod='".$id_period."' order by rp.startdate,rp.enddate,st.surname,st.prename;"; - my $rpdata = $self->{db}->querysorted($sql); - my $rpmax = keys(%{$rpdata})-1; - foreach my $rd (sort {$a <=> $b} keys(%{$rpdata})){ - print CT $self->ReportPage($schema,$rpdata->{$rd}); + $rpdata =$this->dbh->queryarray($sql); + $rpmax = count($rpdata)-1; + foreach ($rpdata as $rd){ + $outdata .= $self->ReportPage($schema,$rpdata[$rd]); if ($rd != $rpmax){ - print CT "
"; + $outdata .= "
"; } } - print CT ""; - close(CT); + $outdata .= ""; + file_put_contents($outfile,$outdata); return 1; } -sub ReportPage(){ - my $self = shift; - my $schema = shift; - my $data = shift; - my $perioddata = $self->getPeriodDays($schema,$data->{id_staff},$data->{startdate},$data->{enddate}); - my $weeksums = $self->getPeriodWeekSums($schema,$data->{id_staff},$data->{startdate},$data->{enddate}); - my $tblheader = " + public function ReportPage($schema,$data){ + + $perioddata = $this->getPeriodDays($schema,$data["id_staff"],$data["startdate"],$data["enddate"]); + $weeksums = $this->getPeriodWeekSums($schema,$data["id_staff"],$data["startdate"],$data["enddate"]); + $tblheader = "
- + @@ -323,16 +297,16 @@ sub ReportPage(){ "; - my $txtpage = $tblheader; - #my $pdays = $self->getPeriodDays($schema,$data->{startdate},$data->{enddate}); - my $wdk = 0; - my $lastpw = -1; - my $numweeks = keys(%{$weeksums}); - my $cntr = 0; + $txtpage = $tblheader; + #$pdays = $self->getPeriodDays($schema,$data["startdate"],$data["enddate"]); + $wdk = 0; + $lastpw = -1; + $numweeks = count($weeksums); + $cntr = 0; - foreach my $pw (sort {$a <=> $b} keys(%{$perioddata})){ - my @wd = split(',',','.$perioddata->{$pw}->{weekdates}); - #print STDERR "CWEEKDAY:".$perioddata->{$pw}->{daydate}."=>".$wd[$wdk]."\n"; + foreach ($perioddata as $pw){ + $wd = explode(',',','.$perioddata[$pw]["weekdates"]); + #print STDERR "CWEEKDAY:".$perioddata[$pw]["daydate"]."=>".$wd[$wdk]."\n"; if ($wdk == 0 ){ if ($cntr > 6){ $txtpage .= "
"; @@ -340,10 +314,10 @@ sub ReportPage(){ $cntr = 0; } $cntr++; - my @dspwd = split(',',$perioddata->{$pw}->{dspweekdates}); + $dspwd = explode(',',$perioddata[$pw]["dspweekdates"]); $txtpage .=" - + @@ -355,28 +329,28 @@ sub ReportPage(){ "; $wdk = 1; } - #print STDERR "CWEEKDAY:".$perioddata->{$pw}->{daydate}."=>".$wd[$wdk]."\n"; - while (($perioddata->{$pw}->{daydate} ne $wd[$wdk]) && $wdk le "7"){ + #print STDERR "CWEEKDAY:".$perioddata[$pw]["daydate"]."=>".$wd[$wdk]."\n"; + while (($perioddata[$pw]["daydate"] != $wd[$wdk]) && $wdk <= "7"){ if ($wdk == 0){$wdk++; next; } - if (($perioddata->{$pw}->{daydate} gt $data->{startdate}) || ($perioddata->{$pw}->{daydate} lt $data->{enddate})){ + if (($perioddata[$pw]["daydate"] >= $data["startdate"]) || ($perioddata[$pw]["daydate"] <= $data["enddate"])){ $txtpage .=""; } $wdk++; } - #print STDERR "CWEEKDAY2:".$perioddata->{$pw}->{daydate}."=>".$wd[$wdk]."\n"; - if ($wdk le "7"){ + #print STDERR "CWEEKDAY2:".$perioddata[$pw]["daydate"]."=>".$wd[$wdk]."\n"; + if ($wdk <= "7"){ - if ($perioddata->{$pw}->{dayhours} ne ""){ + if ($perioddata[$pw]["dayhours"] != ""){ $txtpage .= ""; } else { - #print STDERR "ELSE:".$perioddata->{$pw}->{dayhours}."\n"; + #print STDERR "ELSE:".$perioddata[$pw]["dayhours"]."\n"; $txtpage .= ""; } } $wdk++; $lastpw = $pw; - #print STDERR "Weekday:".$wdk."<=".$perioddata->{$pw}->{daydate}."\n"; - if ($wdk gt "7"){ + #print STDERR "Weekday:".$wdk."<=".$perioddata[$pw]["daydate"]."\n"; + if ($wdk >= "7"){ $txtpage .= " @@ -431,36 +405,36 @@ sub ReportPage(){ } } #print STDERR "WDK: ".$wdk."\n"; - if ($wdk gt "0"){ - while ($wdk le "7"){ + if ($wdk >= "0"){ + while ($wdk <= "7"){ $txtpage .=""; $wdk++; } - if ($wdk gt "7"){ + if ($wdk >= "7"){ $txtpage .= " @@ -471,27 +445,27 @@ sub ReportPage(){ $txtpage .= "
".$data->{dspstartdate}." - ".$data->{dspenddate}."".(($data->{staffnumber} ne "")?"".$data->{staffnumber}."":"")." ".$data->{surname}." ".$data->{prename}." ".(($data->{matricule} ne "")?"(".$data->{matricule}.")":"")."
".$data["dspstartdate"]." - ".$data["dspenddate"]."".(($data["staffnumber"] != "")?"".$data["staffnumber"]."":"")." ".$data["surname"]." ".$data["prename"]." ".(($data["matricule"] != "")?"(".$data["matricule"].")":"")."
Lundi
".$dspwd[0]." ".$dspwd[1]." ".$dspwd[2]." 
- +
".$perioddata->{$pw}->{dspworkdata}."
".$perioddata[$pw]["dspworkdata"]."
-
".(($perioddata->{$pw}->{dsppausedata})?$perioddata->{$pw}->{dsppausedata}:" ")."
+
".(($perioddata[$pw]["dsppausedata"])?$perioddata[$pw]["dsppausedata"]:" ")."
@@ -384,45 +358,45 @@ sub ReportPage(){
- ".(($perioddata->{$pw}->{dayhours})?"
".$perioddata->{$pw}->{dayhours}."
":" ")." + ".(($perioddata[$pw]["dayhours"])?"
".$perioddata[$pw]["dayhours"]."
":" ")."
- ".(($perioddata->{$pw}->{vacancyhours})?"
".$perioddata->{$pw}->{vacancyhours}." ".$self->{legend}->{vacancy}->{$perioddata->{$pw}->{id_vacancytype}}->{legend}.")
":" ")." + ".(($perioddata[$pw]["vacancyhours"])?"
".$perioddata[$pw]["vacancyhours"]." ".$self->{legend}->{vacancy}->{$perioddata[$pw]["id_vacancytype"]}->{legend}.")
":" ")."
- ".(($perioddata->{$pw}->{recuperationhours})?"
".$perioddata->{$pw}->{recuperationhours}." ".$self->{legend}->{recup}->{$perioddata->{$pw}->{id_recuperationtype}}->{legend}.")
":" ")." + ".(($perioddata[$pw]["recuperationhours"])?"
".$perioddata[$pw]["recuperationhours"]." ".$self->{legend}->{recup}->{$perioddata[$pw]["id_recuperationtype"]}->{legend}.")
":" ")."
jour de repos
"; - my $ws = $perioddata->{$pw}->{weekstart}; - if (exists($weeksums->{$ws})){ + $ws = $perioddata[$pw]["weekstart"]; + if (isset($weeksums[$ws])){ $txtpage .= "
-
".$weeksums->{$ws}->{totalhours}."
+
".$weeksums[$ws]["totalhours"]."
"; - #
".(($weeksums->{$ws}->{diffhours} eq "00:00")?"":$weeksums->{$ws}->{diffhours})."
+ #
".(($weeksums->{$ws}->{diffhours} =="00:00")?"":$weeksums->{$ws}->{diffhours})."
} $txtpage .= "
  # # # # # - #
".(($weeksums->{$ws}->{diffhours} eq "00:00")?"":$weeksums->{$ws}->{diffhours})."
+ #
".(($weeksums->{$ws}->{diffhours} =="00:00")?"":$weeksums->{$ws}->{diffhours})."
} $txtpage .= "
"; - my $ws = $perioddata->{$lastpw}->{weekstart}; - if (exists($weeksums->{$ws})){ + $ws = $perioddata[$lastpw]["weekstart"]; + if (isset($weeksums[$ws])){ $txtpage .= "
-
".$weeksums->{$ws}->{totalhours}."
+
".$weeksums[$ws]["totalhours"]."
"; #
- #
".(($weeksums->{$ws}->{recperationhours} eq "00:00")?"":$weeksums->{$ws}->{recperationhours})."
+ #
".(($weeksums->{$ws}->{recperationhours} =="00:00")?"":$weeksums->{$ws}->{recperationhours})."
#
- #
".(($weeksums->{$ws}->{vacancyhours} eq "00:00")?"":$weeksums->{$ws}->{vacancyhours})."
+ #
".(($weeksums->{$ws}->{vacancyhours} =="00:00")?"":$weeksums->{$ws}->{vacancyhours})."
#
"; - # my $spt = $data->{sums}; + # $spt = $data["sums"]; $txtpage .= " - + - + - + - + - + - + - + - + - +
Résumée période de référence: ".$data->{dspstartdate}." - ".$data->{dspenddate}."
Résumée période de référence: ".$data["dspstartdate"]." - ".$data["dspenddate"]."
heures contractuelles:
heures travaillées:
".$data->{contracthours}."
".$data->{workhours}."
".$data["contracthours"]."
".$data["workhours"]."
congé maladie:
congé:
congé except.:
".(($data->{vacancyill} ne '')?$data->{vacancyill} :"00:00")."
".(($data->{vacancynormal} ne '')?$data->{vacancynormal} :"00:00")."
".(($data->{vacancyextra} ne '')?$data->{vacancyextra} :"00:00")."
".(($data["vacancyill"] != '')?$data["vacancyill"] :"00:00")."
".(($data["vacancynormal"] != '')?$data["vacancynormal"] :"00:00")."
".(($data["vacancyextra"] != '')?$data["vacancyextra"] :"00:00")."
heures
récupérées:
".$data->{recuperationhours}."
 
".$data["recuperationhours"]."
 
durée travail
réel prestée:
".$data->{totalhours}."".$data["totalhours"]." moyenne durée
travail réel:
".$data->{avgtotalweekhours}."".$data["avgtotalweekhours"]." décompte reporté:
heures payées:
".(($data->{transferedhourscalc} ne '')?$data->{transferedhourscalc}:"00:00")."
".(($data->{payedhours} ne '')?$data->{payedhours}:"00:00")."
".(($data["transferedhourscalc"] != '')?$data["transferedhourscalc"]:"00:00")."
".(($data["payedhours"] != '')?$data["payedhours"]:"00:00")."
décompte
fin POT:
".$data->{hoursdiff}."".$data["hoursdiff"]." congé suppl. +44h:
congé suppl. dimache travaillé:
".(($data->{suppvacancy44hours} ne '')?$data->{suppvacancy44hours}:" ")."
".(($data->{suppvacancysunwork} ne '')?$data->{suppvacancysunwork}:" ")."
".(($data["suppvacancy44hours"] != '')?$data["suppvacancy44hours"]:" ")."
".(($data["suppvacancysunwork"] != '')?$data["suppvacancysunwork"]:" ")."
"; @@ -499,14 +473,8 @@ sub ReportPage(){ return $txtpage; } -sub getPeriodDays(){ - my $self = shift; - my $schema = shift; - my $id_staff = shift; - my $date_start = shift; - my $date_end = shift; - - my $sql = "SELECT pd.id,pd.daydate,pd.id_vacancytype,pd.id_recuperationtype, + public function getPeriodDays($schema,$id_staff,$date_start,$date_end){ + $sql = "SELECT pd.id,pd.daydate,pd.id_vacancytype,pd.id_recuperationtype, date(date_trunc('week',pd.daydate)) as weekstart, date_part('isoyear',pd.daydate) || '-' || lpad(date_part('week',pd.daydate)::text, 2, '0') AS dspweekshort, to_char(CASE WHEN pd.vacancyhours::interval = '00:00:00'::interval THEN NULL ELSE pd.vacancyhours END::interval, 'HH24:MI') AS vacancyhours, @@ -521,46 +489,40 @@ sub getPeriodDays(){ WHERE pd.daydate between date('".$date_start."') and date('".$date_end."') ORDER BY pd.id_staff, pd.daydate;"; #print STDERR $sql."\n"; - my $ret = $self->{db}->querysorted($sql); - return $ret; -} -sub getPeriodDates(){ - my $self = shift; - my $date_start = shift; - my $date_end = shift; - my $sql = "SELECT date_trunc('day', dd)::date as daydate FROM generate_series( '".$date_start."'::timestamp,'".$date_end."'::timestamp,'1 day'::interval) dd"; - my $ret = $self->{db}->querybykey('daydate',$sql); -} + return $this->dbh->queryarray($sql); + } + + public function getPeriodDates($date_start,$date_end){ + $sql = "SELECT date_trunc('day', dd)::date as daydate FROM generate_series( '".$date_start."'::timestamp,'".$date_end."'::timestamp,'1 day'::interval) dd"; + return $this->dbh->querybykey('daydate',$sql); + + } + + public function getPeriodWeekSums($schem,$id_staff,$date_start,$date_end){ -sub getPeriodWeekSums(){ - my $self = shift; - my $schema = shift; - my $id_staff = shift; - my $date_start = shift; - my $date_end = shift; - my $sql = "select ws.weekstart,ws.weekend,ws.calweek,ws.calyear, ws.id_staff - ,to_char(ws.vacancyhours,'HH24:MI') as vacancyhours - ,to_char(ws.recuperationhours,'HH24:MI') as recuperationhours - ,to_char(ws.totalhours,'HH24:MI') as totalhours - ,case when cd.contractworkdays < cd.cmpcontractdays then to_char(cd.contractworkdays*'08:00:00'::interval,'HH24:MI') else to_char(cd.contracthours,'HH24:MI') end as contracthours - ,to_char(AVG(ws.totalhours) over (order by ws.weekstart),'HH24:MI') as avgtotalhours - ,case when cd.contractworkdays < cd.cmpcontractdays then '00:00' else - case when position('-' in to_char(ws.totalhours-cd.contracthours ,'HH24:MI')) > 0 then '-' || replace(to_char(ws.totalhours-cd.contracthours ,'HH24:MI'),'-','') else to_char(ws.totalhours-cd.contracthours ,'HH24:MI') end end as diffhours - ,cd.contractworkdays - ,cd.cmpcontractdays - ,cd.cmpweekhours - ,to_char(ws.workhours::interval,'HH24:MI') as workhours - ,case when cd.contractworkdays < cd.cmpcontractdays then + $sql = "select ws.weekstart,ws.weekend,ws.calweek,ws.calyear, ws.id_staff + ,to_char(ws.vacancyhours,'HH24:MI') as vacancyhours + ,to_char(ws.recuperationhours,'HH24:MI') as recuperationhours + ,to_char(ws.totalhours,'HH24:MI') as totalhours + ,case when cd.contractworkdays < cd.cmpcontractdays then to_char(cd.contractworkdays*'08:00:00'::interval,'HH24:MI') else to_char(cd.contracthours,'HH24:MI') end as contracthours + ,to_char(AVG(ws.totalhours) over (order by ws.weekstart),'HH24:MI') as avgtotalhours + ,case when cd.contractworkdays < cd.cmpcontractdays then '00:00' else + case when position('-' in to_char(ws.totalhours-cd.contracthours ,'HH24:MI')) > 0 then '-' || replace(to_char(ws.totalhours-cd.contracthours ,'HH24:MI'),'-','') else to_char(ws.totalhours-cd.contracthours ,'HH24:MI') end end as diffhours + ,cd.contractworkdays + ,cd.cmpcontractdays + ,cd.cmpweekhours + ,to_char(ws.workhours::interval,'HH24:MI') as workhours + ,case when cd.contractworkdays < cd.cmpcontractdays then to_char(case when cd.cmpweekhours < '40:00:00'::interval then cd.contracthours * 1.15 * cd.contractworkdays else (cd.contractworkdays*'08:00:00'::interval) + (cd.contractworkdays* case when maxdata.maxweekhours > '48:00:00' then '01:16:50'::interval else '00:50:00'::interval end) end,'HH24:MI') else - to_char(case when cd.contracthours < '40:00:00'::interval then cd.contracthours * 1.15 else maxdata.maxweekhours end,'HH24:MI') - end as maxweekhours - ,case when cd.contractworkdays < cd.cmpcontractdays then to_char(cd.contractworkdays*'08:00:00'::interval,'HH24:MI') else + to_char(case when cd.contracthours < '40:00:00'::interval then cd.contracthours * 1.15 else maxdata.maxweekhours end,'HH24:MI') + end as maxweekhours + ,case when cd.contractworkdays < cd.cmpcontractdays then to_char(cd.contractworkdays*'08:00:00'::interval,'HH24:MI') else to_char(case when cd.contracthours < '40:00:00'::interval then cd.contracthours else maxdata.defaultweekhours end,'HH24:MI') - end as defaultweekhours - from ( - SELECT weekstart,weekend,calweek,calyear, id_staff, + end as defaultweekhours + from ( + SELECT weekstart,weekend,calweek,calyear, id_staff, sum(CASE WHEN srpd.workhours IS NULL THEN '00:00:00'::interval ELSE srpd.workhours::interval END) AS workhours, sum(CASE WHEN srpd.vacancyhours IS NULL THEN '00:00:00'::interval ELSE srpd.vacancyhours::interval END) AS vacancyhours, sum(CASE WHEN srpd.recuperationhours IS NULL THEN '00:00:00'::interval ELSE srpd.recuperationhours::interval END) AS recuperationhours, @@ -575,32 +537,33 @@ sub getPeriodWeekSums(){ ) srpd GROUP BY srpd.weekstart,srpd.weekend,srpd.calweek,srpd.calyear,srpd.id_staff ORDER BY weekstart) ws left join ( select date(date_trunc('week',pd.daydate)) as weekstart,pd.id_staff,max(sc.weekdays) as cmpcontractdays,max(sc.weekhours) as cmpweekhours, - case when count(pd.daydate) < avg(sc.weekdays) then count(pd.daydate) else avg(sc.weekdays) end as contractworkdays, - case when count(pd.daydate) < avg(sc.weekdays) then avg(sc.weekhours/ sc.weekdays) * count(pd.daydate) else avg(sc.weekhours/ sc.weekdays) * avg(sc.weekdays) end as contracthours ,sum(case when coalesce(pd.workhours,'00:00:00'::time) > '00:00:00'::time then 1 else 0 end) as realworkdays - from ( select id_staff,weekdays ,weekhours, - case when startdate> date('".$date_start."') then startdate else date('".$date_start."') end as staffperiodstart, - case when enddate is null or enddate > date('".$date_end."') then date('".$date_end."') - else enddate end as staffperiodend from ".$schema.".staffcontract where id_staff='".$id_staff."' - and startdate < date('".$date_end."') - ) sc - join ".$schema.".staffreportperioddays pd on (pd.id_staff=sc.id_staff and pd.daydate between sc.staffperiodstart and sc.staffperiodend) - group by date(date_trunc('week',pd.daydate)),pd.id_staff + case when count(pd.daydate) < avg(sc.weekdays) then count(pd.daydate) else avg(sc.weekdays) end as contractworkdays, + case when count(pd.daydate) < avg(sc.weekdays) then avg(sc.weekhours/ sc.weekdays) * count(pd.daydate) else avg(sc.weekhours/ sc.weekdays) * avg(sc.weekdays) end as contracthours ,sum(case when coalesce(pd.workhours,'00:00:00'::time) > '00:00:00'::time then 1 else 0 end) as realworkdays + from ( select id_staff,weekdays ,weekhours, + case when startdate> date('".$date_start."') then startdate else date('".$date_start."') end as staffperiodstart, + case when enddate is null or enddate > date('".$date_end."') then date('".$date_end."') + else enddate end as staffperiodend from ".$schema.".staffcontract where id_staff='".$id_staff."' + and startdate < date('".$date_end."') + ) sc + join ".$schema.".staffreportperioddays pd on (pd.id_staff=sc.id_staff and pd.daydate between sc.staffperiodstart and sc.staffperiodend) + group by date(date_trunc('week',pd.daydate)),pd.id_staff ) cd on ws.id_staff = cd.id_staff and ws.weekstart=cd.weekstart - left join ( - select id_staff,weekstart,max(defaultweekhours) as defaultweekhours,max(maxweekhours) as maxweekhours from ( - select lpd.id_staff,date(date_trunc('week',lpd.daydate)) as weekstart,lpd.daydate, - case when wk.defaultweekhours is null then wkdef.defaultweekhours else wk.defaultweekhours end as defaultweekhours , - case when wk.maxweekhours is null then wkdef.maxweekhours else wk.maxweekhours end as maxweekhours - from ".$schema.".staffreportperioddays lpd - left join ".$schema.".worktimes wk on (lpd.daydate between wk.startdate and wk.enddate) - cross join (select * from ".$schema.".worktimes where isdefault=true) wkdef - where id_staff='".$id_staff."' and lpd.daydate between date('".$date_start."') and date('".$date_end."') - order by lpd.daydate ) mh group by id_staff,weekstart - ) maxdata on ws.id_staff = maxdata.id_staff and ws.weekstart=maxdata.weekstart"; - #print STDERR "\n======WEEK SUMS=$date_start-$date_end======\n".$sql."\n=====\n"; - my $ret = $self->{db}->querybykey('weekstart',$sql); + left join ( + select id_staff,weekstart,max(defaultweekhours) as defaultweekhours,max(maxweekhours) as maxweekhours from ( + select lpd.id_staff,date(date_trunc('week',lpd.daydate)) as weekstart,lpd.daydate, + case when wk.defaultweekhours is null then wkdef.defaultweekhours else wk.defaultweekhours end as defaultweekhours , + case when wk.maxweekhours is null then wkdef.maxweekhours else wk.maxweekhours end as maxweekhours + from ".$schema.".staffreportperioddays lpd + left join ".$schema.".worktimes wk on (lpd.daydate between wk.startdate and wk.enddate) + cross join (select * from ".$schema.".worktimes where isdefault=true) wkdef + where id_staff='".$id_staff."' and lpd.daydate between date('".$date_start."') and date('".$date_end."') + order by lpd.daydate ) mh group by id_staff,weekstart + ) maxdata on ws.id_staff = maxdata.id_staff and ws.weekstart=maxdata.weekstart"; + //print STDERR "\n======WEEK SUMS=$date_start-$date_end======\n".$sql."\n=====\n"; + //$ret = + return $this->dbh->querybykey('weekstart',$sql); + } - return $ret; } -1; \ No newline at end of file +?> \ No newline at end of file diff --git a/app/lib/POT/Staff.php b/app/lib/POT/Staff.php index c0513d4c..01e17081 100644 --- a/app/lib/POT/Staff.php +++ b/app/lib/POT/Staff.php @@ -12,7 +12,7 @@ class Staff{ } -function addStaff($schema ,$surname ,$prename ,$startdate ,$enddate ,$weekhours ,$weekdays ,$id_group){ + public function addStaff($schema ,$surname ,$prename ,$startdate ,$enddate ,$weekhours ,$weekdays ,$id_group){ //$wk = $this->dbh->query("select id from ".$schema.".workplans where isdefault = true;"); $sg = $this->dbh->query("select id from ".$schema.".staffgroups where isdefault = true"); $st = $this->dbh->query("insert into ".$schema.".staff (prename,surname,id_staffgroup) values (".$this->dbh->value($prename).",".$this->dbh->value($surname).",".$this->dbh->value($id_group).") returning id"); @@ -24,11 +24,11 @@ function addStaff($schema ,$surname ,$prename ,$startdate ,$enddate ,$weekhours return $st["id"]; } -function saveStaff($schema ,$data){ +public function saveStaff($schema ,$data){ } -function deleteStaffContract($schema ,$id){ +public function deleteStaffContract($schema ,$id){ $staff = $this->dbh->query("select id_staff from ".$schema.".staffcontract where id='".$id."';"); $this->dbh->exec("delete from ".$schema.".staffcontract where id='".$id."'"); $this->setStaffContractDays($schema,$staff["id_staff"]); @@ -36,20 +36,20 @@ function deleteStaffContract($schema ,$id){ return 1; } -function deleteStaff($schema ,$id){ +public function deleteStaff($schema ,$id){ $this->dbh->exec("update ".$schema.".staff set isdeleted = true where id='".$id."';"); //TODO: syncStaffToPointeuse return 1; } -function saveStaffContract($schema ,$data ){ +public function saveStaffContract($schema ,$data ){ //TODO: update $this->setStaffContractDays($schema,$data["staffcontract_id_staff"]); //TODO: syncStaffToPointeuse return 1; } -function setStaffContractDays($schema ,$id_staff){ +public function setStaffContractDays($schema ,$id_staff){ //print STDERR "START Staff::setStaffContractDays()\n"; $periodssql = "select id,startdate,enddate from ".$schema.".reportperiod where @@ -57,12 +57,14 @@ startdate >= date((select min(startdate) from ".$schema.".staffcontract where id or date((select min(startdate) from ".$schema.".staffcontract where id_staff='".$id_staff."')) between startdate and enddate;"; $perioddata = $this->dbh->queryarray($periodssql); // print STDERR Dumper($perioddata)."\n"; - $period = new Period($this->dbh,$this->$cfg); + $period = new Period($this->dbh,$this->cfg); foreach ($perioddata as $pp){ + error_log(print_r($perioddata,true)); + error_log(print_r($pp,true)); $this->dbh->exec("INSERT INTO ".$schema.".staffreportperiod (id_reportperiod, id_staff) - VALUES ('".$perioddata[$pp]["id"]."','".$id_staff."') on conflict on constraint uniq_staffreportperiod_cal do nothing;"); - $period->setStaffPeriodDays($schema,$perioddata[$pp]["id"],$id_staff); + VALUES ('".$pp["id"]."','".$id_staff."') on conflict on constraint uniq_staffreportperiod_cal do nothing;"); + $period->setStaffPeriodDays($schema,$pp["id"],$id_staff); } $cpsql = "select reportperiodunit,reportperiodlength from public.companies where schemata='".$schema."'"; $rprol = $this->dbh->query($cpsql); @@ -74,15 +76,15 @@ case when sc.enddate is null or sc.enddate > rp.enddate then rp.enddate else sc. sc.weekhours,sc.weekdays from ".$schema.".staffcontract sc cross join ".$schema.".reportperiod rp where sc.id_staff='".$id_staff."' -) scx where startdate < enddate and id='".$perioddata[$pp]["id"]."' order by startdate,enddate;"; +) scx where startdate < enddate and id='".$pp["id"]."' order by startdate,enddate;"; // $ctsql = "select * from ( // select case when startdate < date('".$perioddata[$pp]["startdate"]."') then date('".$perioddata[$pp]["startdate"]."') else startdate end as startdate , // case when enddate is null or enddate > date('".$perioddata[$pp]["enddate"]."') then date('".$perioddata[$pp]["enddate"]."') else enddate end as enddate, // weekhours,weekdays from portanova.staffcontract where id_staff='".$id_staff."' // ) sc where date('".$perioddata[$pp]["startdate"]."') between startdate and enddate and date('".$perioddata[$pp]["enddate"]."') between startdate and enddate order by startdate,enddate;"; //check for startwork in this period - $isstartingperiod = $this->dbh->queryarray("select startdate from ".$schema.".staffcontract where id_staff='".$id_staff."' and startdate between date(date('".$perioddata[$pp]["startdate"]."') + interval '1 day') and date('".$perioddata[$pp]["enddate"]."')"); - $isendingperiod = $this->dbh->queryarray("select enddate from ".$schema.".staffcontract where id_staff='".$id_staff."' and enddate between date('".$perioddata[$pp]["startdate"]."') and date(date('".$perioddata[$pp]["enddate"]."') + interval '1 day')"); + $isstartingperiod = $this->dbh->queryarray("select startdate from ".$schema.".staffcontract where id_staff='".$id_staff."' and startdate between date(date('".$pp["startdate"]."') + interval '1 day') and date('".$pp["enddate"]."')"); + $isendingperiod = $this->dbh->queryarray("select enddate from ".$schema.".staffcontract where id_staff='".$id_staff."' and enddate between date('".$pp["startdate"]."') and date(date('".$pp["enddate"]."') + interval '1 day')"); $ctdata = $this->dbh->queryarray($ctsql); foreach ($ctdata as $c){ $daysql = ""; @@ -96,13 +98,13 @@ where sc.id_staff='".$id_staff."' $chsql = "select sum(maxdays) as maxdays,sum(contracthours - ('00:00:'|| extract(second from contracthours))::interval ) as itmcontracthours from ( select sum(maxdays) as maxdays,sum(maxdays) * (round(cast(((extract(epoch from (current_date + weekhours::interval)::timestamp) - extract(epoch from current_date::timestamp))/3600.0) /weekdays as numeric) ,2)+0.00) * '01:00:00'::interval as contracthours from ( select case when count(daydate) > weekdays then weekdays else count(daydate)-count(sundays) end as maxdays, calweek,count(daydate) as cntdays,count(sundays) as sundays,weekdays,weekhours from ( - --select calweek,count(daydate) as cntdays,count(sundays) as sundays from ( + select id_staff,date(date_trunc('week',daydate)) as calweek,daydate,case when date_part('isodow',daydate)::int4=7 then 1 else null end as sundays from ".$schema.".staffreportperioddays - where id_staff='".$id_staff."' and daydate between date('".$perioddata[$pp]["startdate"]."') and date('".$perioddata[$pp]["enddate"]."') + where id_staff='".$id_staff."' and daydate between date('".$pp["startdate"]."') and date('".$pp["enddate"]."') ) wgr left join ( - select date(date_trunc('week',startdate)) as weekstartdate,startdate,case when enddate is null then date('".$perioddata[$pp]["enddate"]."') else enddate end as enddate,case when enddate is null then date(date_trunc('week',date('".$perioddata[$pp]["enddate"]."')) + interval '6 days') else enddate end as weekenddate,weekdays,weekhours from ".$schema.".staffcontract where id_staff='".$id_staff."' + select date(date_trunc('week',startdate)) as weekstartdate,startdate,case when enddate is null then date('".$pp["enddate"]."') else enddate end as enddate,case when enddate is null then date(date_trunc('week',date('".$pp["enddate"]."')) + interval '6 days') else enddate end as weekenddate,weekdays,weekhours from ".$schema.".staffcontract where id_staff='".$id_staff."' ) sc on (wgr.calweek between sc.weekstartdate and sc.weekenddate ) where wgr.daydate between sc.startdate and sc.enddate group by sc.weekhours,sc.weekdays,calweek ) rnddays group by weekhours,weekdays) xx"; //OLD @@ -122,9 +124,9 @@ left join ( // print STDERR "CONTRACT:".$chsql."\n========\n"; $checkhours = $this->dbh->query($chsql); - $usql = "update ".$schema.".staffreportperiod set maxdays=".(($checkhours["maxdays"] != "")?$checkhours["maxdays"]:'null').",contracthours=".(($checkhours["itmcontracthours"] != "")?"'".$checkhours["itmcontracthours"]."'":'null')." where id_staff='".$id_staff."' and id_reportperiod='".$perioddata[$pp]["id"]."';" ; + $usql = "update ".$schema.".staffreportperiod set maxdays=".(($checkhours["maxdays"] != "")?$checkhours["maxdays"]:'null').",contracthours=".(($checkhours["itmcontracthours"] != "")?"'".$checkhours["itmcontracthours"]."'":'null')." where id_staff='".$id_staff."' and id_reportperiod='".$pp["id"]."';" ; $this->dbh->exec($usql); - $period->updateStaffPeriod($schema,$perioddata[$pp]["id"],$id_staff); + $period->updateStaffPeriod($schema,$pp["id"],$id_staff); } @@ -136,15 +138,15 @@ left join ( // print STDERR "END Staff::setStaffContractDays()\n"; } -function getStaffContractDates($schema ,$id_staff){ +public function getStaffContractDates($schema ,$id_staff){ return $this->dbh->queryarray("SELECT id,id as id_staffcontract,id_staff,startdate,enddate,weekdays,to_char(weekhours, 'HH24:MI'::text) AS weekhours from ".$schema.".staffcontract where id_staff='".$id_staff."' order by startdate,enddate;"); } -function getStaffContract($schema ,$id){ +public function getStaffContract($schema ,$id){ return $this->dbh->query("SELECT id,id as id_staffcontract,id_staff,startdate,enddate,weekdays,to_char(weekhours, 'HH24:MI'::text) AS weekhours from ".$schema.".staffcontract where id='".$id."';"); } -function getStaffList($schema ,$id_groups){ +public function getStaffList($schema ,$id_groups){ $wgroups = ""; //print STDERR "groups:".Dumper($id_groups)."\n"; @@ -160,17 +162,17 @@ where st.isdeleted is null ".$wgroups." order by groupname,surname,prename;"; return $this->dbh->queryarray($sql); } -function getStaff($schema ,$id_staff){ +public function getStaff($schema ,$id_staff){ $sql = "select * from ".$schema.".staff where id='".$id_staff."' and isdeleted is null;"; return $this->dbh->query($sql); } -function getStaffVacancyYears($schema ,$id_staff){ +public function getStaffVacancyYears($schema ,$id_staff){ $sql = "select id,id_staff,vacyear,to_char(vachours,'HH24:MI') as vachours from ".$schema.".staffvacancyyear where id_staff='".$id_staff."' order by vacyear;"; return $this->dbh->queryarray($sql); } -function getStaffVacancy($schema ,$id_staff){ +public function getStaffVacancy($schema ,$id_staff){ $sql = "select to_char(daydate,'YYYY') as vacyear,daydate, to_char(vacancyhours::interval,'HH24:MI') as vacancyhours, @@ -180,5 +182,10 @@ $sql = "select to_char(daydate,'YYYY') as vacyear,daydate, from ".$schema.".staffreportperioddays where (vacancyhours is not null or vacillhours is not null or vacextrahours is not null) and id_staff='".$id_staff."' order by daydate;"; return $this->dbh->queryarray($sql); } + + + } + + ?> \ No newline at end of file diff --git a/app/lib/POT/TimeTracker.php b/app/lib/POT/TimeTracker.php index 9f175159..9ca5df47 100644 --- a/app/lib/POT/TimeTracker.php +++ b/app/lib/POT/TimeTracker.php @@ -11,7 +11,7 @@ class TimeTracker{ $this->conn = null; } - function getTrackDay($schema,$idstaff,$daydate){ + public function getTrackDay($schema,$idstaff,$daydate){ $sql = "select id,id_staff,daydate,to_char(stamp_in,'HH24:MI') as stamp_in,to_char(stamp_out,'HH24:MI') as stamp_out, case when stamp_in is null or stamp_out is null then '00:00' else to_char(stamp_out-stamp_in,'HH24:MI') end as total from ".$schema.".timetracker where daydate=date('".$daydate."') and id_staff='".$idstaff."' order by stamp_in,stamp_out;"; @@ -23,11 +23,11 @@ from ".$schema.".timetracker where daydate=date('".$daydate."') and id_staff='". return $res; } - function getEmptyTrackDataSet($schema,$idstaff,$daydate){ +public function getEmptyTrackDataSet($schema,$idstaff,$daydate){ return $this->dbh->queryarray("select public.getuuid() as id, '".$idstaff."' as id_staff,date('".$daydate."') as daydate,'00:00' as stamp_in,'00:00' as stamp_out, '00:00' as total"); } - function saveTrackDataSets($schema,$daydate,$idstaff,$trackdata){ +public function saveTrackDataSets($schema,$daydate,$idstaff,$trackdata){ //print STDERR Dumper($trackdata); $ttids = array(); @@ -55,7 +55,7 @@ from ".$schema.".timetracker where daydate=date('".$daydate."') and id_staff='". // function ImportTimeTrackProSysPDF(){ // } - function getTimeTrackerList($schema){ + public function getTimeTrackerList($schema){ $sql = "select id,trackername from ".$schema.".timetrackerconfig order by trackername"; return $this->dbh->queryarray($sql); } diff --git a/app/lib/config.php b/app/lib/config.php index b9b27359..c28b81da 100644 --- a/app/lib/config.php +++ b/app/lib/config.php @@ -1,18 +1,16 @@ '1.3.6', + "appversion" => '1.3.7', "basepath" => substr(dirname($_SERVER["SCRIPT_FILENAME"]),strlen($_SERVER["DOCUMENT_ROOT"])).'/', "cookie" => "potlu", "templatepath" => "tmpl/", "webdocroot" => $_SERVER["DOCUMENT_ROOT"].'/'.substr(dirname($_SERVER["SCRIPT_FILENAME"]),strlen($_SERVER["DOCUMENT_ROOT"])).'/', "liveurl" => "https://app.plandutravail.lu", - "cache" => "data/cache", + "cache" => "data/cache/", //"webmediapath" => $_SERVER["DOCUMENT_ROOT"].'/mobile/media/', //"sitedata" => "data/", //"adminmediapath" => $_SERVER["DOCUMENT_ROOT"]..'/media/', - "datapath" => "/home/dks/mirror/invoicejournal/dks2", + "datapath" => "data/output/", "db"=> array( "type" => "pgsql", #"dbfile" => "/home/dks/mirror/invoicejournal/dks/dks.sqlite" @@ -22,11 +20,11 @@ "user" => 'potlu2_user', "password" => 'dMY8xGB6cBLzrDGE', ), - "tmppath" => "/home/dks/mirror/invoicejournal/dks2/tmp", + "tmppath" => "data/tmp/", "lang" => "de", - "toolspath" => "/home/dks/public_html/invoicejournal/tools", + "toolspath" => "tools", "version" => date("YmdHis"), "minify" => "", ); - + ?> \ No newline at end of file diff --git a/app/lib/database.php b/app/lib/database.php index bff9e5aa..5d1f756e 100644 --- a/app/lib/database.php +++ b/app/lib/database.php @@ -2,7 +2,7 @@ class database { private $conn; private $dbconf; - private $debug=1; + private $debug=0; public function __construct($pdbconf){ $this->dbconf = $pdbconf; try { @@ -124,6 +124,9 @@ class database { return $inssql; } + + + public function newuuid(){ $nid = $this->query("SELECT lower(hex( randomblob(4)) || '-' || hex( randomblob(2)) || '-' || hex( randomblob(2)) || '-' || hex( randomblob(2)) || '-' || hex(randomblob(6))) as id;"); return $nid["id"]; diff --git a/app/lib/helpers.php b/app/lib/helpers.php new file mode 100644 index 00000000..8ecd95ce --- /dev/null +++ b/app/lib/helpers.php @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/app/lib/session.php b/app/lib/session.php index f1c18cdc..d2b01ed6 100644 --- a/app/lib/session.php +++ b/app/lib/session.php @@ -14,9 +14,10 @@ class session { where se.id= '".$this->dbh->securetext($sid)."' and se.remote_addr= '".$_SERVER["REMOTE_ADDR"]."' and se.user_agent ='".$_SERVER["HTTP_USER_AGENT"]."' and us.isblocked is null group by se.id,us.id,ugrp.id;"); } - if (count($this->session) == 0){ - return null; - } + error_log("session:".print_r($this->session,true)); + // if (count($this->session) == 0){ + // return null; + // } return $this->session; } @@ -46,15 +47,17 @@ class session { } public function setsessiondata($idsession,$params){ - + error_log(print_r($params,true)); $sdata = $this->dbh->query("select sessiondata from public.sessions where id='".$idsession."'"); - $sdata["sessiondata"]= json_decode($sdata->{sessiondata}); + $nxdata = json_decode($sdata["sessiondata"]); + error_log(print_r($nxdata,true)); + //$sdata->sessiondata= $sdata->sessiondata); # print STDERR Dumper($sdata); - foreach ($params as $ss){ - $sdata["sessiondata"][$ss] = $params[$ss]; + foreach ($params as $ss => $val){ + $nxdata->$ss = $val; } - $this->dbh->exec("update public.sessions set sessiondata='".json_encode($sdata["sessiondata"])."' where id='".$idsession."'"); - return $sdata["sessiondata"]; + $this->dbh->exec("update public.sessions set sessiondata='".json_encode($nxdata)."' where id='".$idsession."'"); + return $sdata; } public function deletesession($sid){ diff --git a/app/report.cgi b/app/report.cgi deleted file mode 100644 index 6ae4b560..00000000 --- a/app/report.cgi +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/local/bin/perl -use strict; -use lib ('./lib/perl5'); -use lib ('./lib'); -use CGI; -use CGI::Cookie; -use Encode; -#use CGI::Carp qw/fatalsToBrowser/; -use File::Basename; -use JSON::PP; -use MIME::Type::FileName; -use Data::Dumper; -use File::Path qw(make_path); -use dksconfig qw/$sitecfg/; -use dksdb; -use session; -use POT::Report; -#use pdfreport; - -my $cgi = new CGI(); -my $scriptpath = $cgi->url(-absolute => 1); -my $p = (); -my @params = $cgi->param(); -foreach my $pe (@params){ - $p->{$pe} = $cgi->param($pe); -} -if (exists($p->{"POSTDATA"})){ - my $pdj = (); - if ($p->{"POSTDATA"} =~ /^\{.*\}$/ ){ - $pdj = JSON::PP::decode_json($p->{"POSTDATA"}); - } - - foreach my $k (keys(%{$pdj})){ - $p->{$k} = $pdj->{$k}; - } - } -my $db = dksdb->new({dsn => $sitecfg->{dsn},dbuser => $sitecfg->{dbuser},dbpassword => $sitecfg->{dbpassword}}); -my $html->{result} = (); -$p->{sid} = $cgi->cookie($sitecfg->{cookiename}); -my $se = session->new({db => $db}); -my $sess = $se->getsession($p->{sid}); - -if ($sess == undef){ - print $cgi->header(-type=>"application/json", -charset => "utf-8"); - $html->{error} = "No Authorisation"; - $html->{params} = $p; - $html->{session} = $sess; - print JSON::PP::encode_json($html); - exit(0); -} - -if (($cgi->request_method() eq "GET") || ($cgi->request_method() eq "POST")){ - - if (exists($p->{generate})){ - print $cgi->header(-type=>"application/json", -charset => "utf-8"); - my $data = (); - if (ref($p->{data}) ne "HASH"){ - $data = JSON::PP::decode_json($p->{data}); - }else { - $data = $p->{data}; - } - my $schemata = "public"; - if (exists($data->{schemata})){ - $schemata = $data->{schemata}; - } - my $tmppath = $sitecfg->{docroot}.'/'.$sitecfg->{datapath}.'tmp/'; - my $output = $sitecfg->{docroot}.'/'.$sitecfg->{datapath}.'output/'.$schemata."/"; - if (! -d $tmppath) { make_path($tmppath);} - if (! -d $output) { make_path($output);} - if (! -d $output.$p->{generate}){make_path($output.$p->{generate});} - my $rep = POT::Report->new({db => $db,tmp => $tmppath}); - my ($result,$file) = $rep->createpdf($schemata,$p->{generate},$output.dirname($p->{generate}).'/'.'/'.$p->{file},$data); - $html->{result}->{file} = (($file)?$schemata.'/'.substr($file,length($output)):""); - } - elsif (exists($p->{open})){ - my $file = $sitecfg->{docroot}.'/'.$sitecfg->{datapath}.'output/'.$p->{open}; - if (-e $file){ - my $mimetype = MIME::Type::FileName::guess ($file); - my @stat = stat($file); - print $cgi->header( - -type => $mimetype, - -target => basename($p->{open}) - #-attachment => basename($p->{open}) - ); - open(DLD,$file); - binmode(DLD); - local $/ = \1024; - while (){ - print $_; - } - close(DLD); - exit(0); - } - else { - print $cgi->header(-type=>"application/json", -charset => "utf-8"); - $html->{result}->{file} = $file; - } - } else { - print $cgi->header(-type=>"application/json", -charset => "utf-8"); - } -} -print JSON::PP::encode_json($html); diff --git a/app/report.php b/app/report.php index a75d0694..a6850224 100644 --- a/app/report.php +++ b/app/report.php @@ -1,5 +1,5 @@ $value) @@ -16,24 +16,81 @@ require("lib/POT/".$value); } } + $vars = array(); $vars["sid"] = ""; - if (isset($_COOKIE[$cfg["cookie"]])){ - $vars["sid"] = $_COOKIE[$cfg["cookie"]]; +if (isset($_COOKIE[$cfg["cookie"]])){ + $vars["sid"] = $_COOKIE[$cfg["cookie"]]; +} +error_log("SID:".$vars["sid"] ); +$db = new database($cfg["db"]); +$se = new session($db); + +$html = array("result" => ""); +if ($vars["sid"] != ""){ + $vars["session"] = $se->getSession($vars["sid"]); + $sess = $vars["session"]; +} else { + error_log("No Session!"); + $html["error"] = " No Authorization"; + header('Content-Type: application/json'); + echo json_encode($html); + exit(0); } - $db = new database($cfg["db"]); - $sess = new session($db); - $vars = array(); - $html = array(); - if (isset($_COOKIE[$cfg["cookie"]])){ - $vars["sid"] = $_COOKIE[$cfg["cookie"]]; - } - if (isset($vars["sid"]) && ($vars["sid"] != "")){ - $vars["session"] = $sess->getSession($vars["sid"]); - } else { - error_log("No Session!"); - } - // $vars["session"] = array(); - // if ($vars["sid"] != ""){ - // $vars["session"] = $sess->getSession($vars["sid"]); - // } -?> \ No newline at end of file +$p = json_decode(file_get_contents('php://input'), true); +error_log("params:".print_r($p,true)); +if (isset($p["generate"])){ + $data = $p["data"]; + $schemata = "public"; + if (isset($data["schemata"])){ + $schemata = $data["schemata"]; + } + $tmppath = $cfg["tmppath"]; + $output = $cfg["datapath"].$schemata."/"; + if (!file_exists($tmppath)) { mkdir($tmppath);} + if (!file_exists($output)) { mkdir($output);} + if (!file_exists($output.$p["generate"])){mkdir($output.$p["generate"]);} + $rep = new Report($db,$cfg); + $file = $rep->createpdf($schemata,$p["generate"],$output.dirname($p["generate"].'/'.'/'.$p["file"]),$data); + $html["result"]["file"] = (($file)?$schemata.'/'.substr($file,strlen($output)):""); +} +elseif (isset($p["open"])){ + +} +header("Content-Type: application/json; charset=utf-8"); +echo json_encode($html); + /* + + if (exists($p->{generate})){ + + } + elsif (exists($p->{open})){ + my $file = $sitecfg->{docroot}.'/'.$sitecfg->{datapath}.'output/'.$p->{open}; + if (-e $file){ + my $mimetype = MIME::Type::FileName::guess ($file); + my @stat = stat($file); + print $cgi->header( + -type => $mimetype, + -target => basename($p->{open}) + #-attachment => basename($p->{open}) + ); + open(DLD,$file); + binmode(DLD); + local $/ = \1024; + while (){ + print $_; + } + close(DLD); + exit(0); + } + else { + print $cgi->header(-type=>"application/json", -charset => "utf-8"); + $html->{result}->{file} = $file; + } + } else { + print $cgi->header(-type=>"application/json", -charset => "utf-8"); + } +} +print JSON::PP::encode_json($html); + +*/ +?> diff --git a/app/synctimetrack.cgi b/app/synctimetrack.cgi deleted file mode 100644 index fa2b11a8..00000000 --- a/app/synctimetrack.cgi +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/local/bin/perl -use strict; -use lib ('./lib/perl5'); -use lib ('./lib'); -use CGI; -use CGI::Cookie; -# use CGI::Carp qw/fatalsToBrowser/; -use File::Basename; -use JSON::PP; -use Data::Dumper; -use POT::TimeTrackSync; -use dksconfig qw/$sitecfg/; -use dksdb; - -use session; - -my $cgi = new CGI(); -my $scriptpath = $cgi->url(-absolute => 1); -my $p = (); - -my $html->{result} = (); -my $db = dksdb->new({dsn => $sitecfg->{dsn},dbuser => $sitecfg->{dbuser},dbpassword => $sitecfg->{dbpassword}}); -$p->{sid} = $cgi->cookie($sitecfg->{cookiename}); - -my $se = session->new({db => $db}); -my $sess = $se->getsession($p->{sid}); -print $cgi->header(-type=>"application/json", -charset => "utf-8"); -if ($sess == undef){ - $html->{error} = "No Authorisation"; - print JSON::PP::encode_json($html); - exit(0); -} -if (($cgi->request_method() eq "GET") || ($cgi->request_method() eq "POST")){ - - my @params = $cgi->param(); - - foreach my $pp (@params){ - $p->{$pp} = $cgi->param($pp); - } - if (exists($p->{"POSTDATA"})){ - my $pdj = (); - if ($p->{"POSTDATA"} =~ /^\{.*\}$/ ){ - $pdj = JSON::PP::decode_json($p->{"POSTDATA"}); - } - - foreach my $k (keys(%{$pdj})){ - $p->{$k} = $pdj->{$k}; - } - } - - my @retdata = (); - my $hres; - my $schema = "public"; - if (exists($p->{schemata})){ - $schema = $db->securetext($p->{schemata}); - } - if ($p->{get} =~ /getusers$|getpotdata$/){ - my $tts = POT::TimeTrackSync->new({db => $db}); - if ($p->{get} eq 'getusers'){ - $hres = $tts->GetUsers($schema); - } - if ($p->{get} eq 'getpotdata'){ - $hres = $tts->GetPotData($schema,$p->{id_staff}); - } - $html->{result}->{$p->{get}} = $hres; - } -} -$db->disconnect(); -print JSON::PP::encode_json($html); diff --git a/app/tmpl/browser.html b/app/tmpl/browser.html index a50e34a0..3f502445 100644 --- a/app/tmpl/browser.html +++ b/app/tmpl/browser.html @@ -21,11 +21,11 @@ - + - -
'; - $bodydata .= 'Entreprise: '.$p->{company}.'
'; - $bodydata .= 'Nom: '.$p->{surname}.' '.$p->{prename}.'
'; - $bodydata .= 'Position: '.$p->{position}.'
'; - $bodydata .= 'E-mail: '.$p->{email}.'
'; - $bodydata .= 'Téléphone: '.$p->{phone}.'
'; - $bodydata .= 'Message:

'.$p->{message}.'
'; - $bodydata .= '
'; - $html->{result} = &sendemail($sitecfg->{mailuser},$sitecfg->{subject},$bodydata); -} -print $cgi->header(-type=>"application/json", -charset=>"utf-8"); -print JSON::PP::encode_json($html); -exit(0); - -sub sendemail(){ - my $email = shift; - my $subject = shift; - my $bodydata = shift; - - my $bodyfile = $basepath.'/tmp/'.$$.'.mail'; - open (BF,">".$bodyfile); - print BF $bodydata; - close(BF); - my $binsemail = $basepath.'/tools/sendEmail'; - #print STDERR "Mailpath:".$basepath.'/tools/sendEmail'."\n"; - if (! -e $binsemail){ - return 256; - } - my $cmd= 'perl "'.$binsemail.'" -f '.$sitecfg->{mailfrom}.' '; - $cmd .= ' -s "'.$sitecfg->{mailserver}.':'.$sitecfg->{mailport}.'" -xu "'.$sitecfg->{mailuser}.'" -xp "'.$sitecfg->{mailpassword}.'" -q '; - $cmd .= '-o tls=auto '; - $cmd .= '-t "'.$email.'" '; - $cmd .= '-u "'.$subject.'" '; - $cmd .= '-o message-content-type=html '; - $cmd .= '-o message-charset=ISO-8859-1 '; - $cmd .= '-o message-file='.$bodyfile.' '; - #print STDERR "\n--\n".$cmd."\n--\n"; - # if ($attach != undef){ - # $cmd .= ' -a'; - - # foreach my $a (@{$attach}){ - # $cmd .= ' ".$a." '; - # } - # } - my $send = system($cmd); - unlink($bodyfile); - return $send; - -} \ No newline at end of file diff --git a/website/api/tmp/.htaccess b/website/api/tmp/.htaccess deleted file mode 100644 index 908fc527..00000000 --- a/website/api/tmp/.htaccess +++ /dev/null @@ -1,5 +0,0 @@ -#RewriteEngine On -#RewriteBase / -#RewriteCond %{HTTP_COOKIE} !potlu= [NC] -#RewriteRule .* "%{REQUEST_SCHEME}://%{HTTP_HOST}/backoffice/login.html" [L] -Require all denied \ No newline at end of file diff --git a/website/api/tools/.htaccess b/website/api/tools/.htaccess deleted file mode 100644 index 908fc527..00000000 --- a/website/api/tools/.htaccess +++ /dev/null @@ -1,5 +0,0 @@ -#RewriteEngine On -#RewriteBase / -#RewriteCond %{HTTP_COOKIE} !potlu= [NC] -#RewriteRule .* "%{REQUEST_SCHEME}://%{HTTP_HOST}/backoffice/login.html" [L] -Require all denied \ No newline at end of file diff --git a/website/api/tools/sendEmail b/website/api/tools/sendEmail deleted file mode 100644 index c639439c..00000000 --- a/website/api/tools/sendEmail +++ /dev/null @@ -1,2235 +0,0 @@ -#!/usr/bin/perl -w -############################################################################## -## sendEmail -## Written by: Brandon Zehm -## -## License: -## sendEmail (hereafter referred to as "program") 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 -## 2 of the License, or (at your option) any later version. -## When redistributing modified versions of this source code it is recommended -## that that this disclaimer and the above coder's names are included in the -## modified code. -## -## Disclaimer: -## This program is provided with no warranty of any kind, either expressed or -## implied. It is the responsibility of the user (you) to fully research and -## comprehend the usage of this program. As with any tool, it can be misused, -## either intentionally (you're a vandal) or unintentionally (you're a moron). -## THE AUTHOR(S) IS(ARE) NOT RESPONSIBLE FOR ANYTHING YOU DO WITH THIS PROGRAM -## or anything that happens because of your use (or misuse) of this program, -## including but not limited to anything you, your lawyers, or anyone else -## can dream up. And now, a relevant quote directly from the GPL: -## -## NO WARRANTY -## -## 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -## FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -## OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -## PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -## OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -## MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -## TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -## PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -## REPAIR OR CORRECTION. -## -############################################################################## -use strict; -use IO::Socket; - - -######################## -## Global Variables ## -######################## - -my %conf = ( - ## General - "programName" => $0, ## The name of this program - "version" => '1.56', ## The version of this program - "authorName" => 'Brandon Zehm', ## Author's Name - "authorEmail" => 'caspian@dotconf.net', ## Author's Email Address - "timezone" => '+0000', ## We always use +0000 for the time zone - "hostname" => 'changeme', ## Used in printmsg() for all output (is updated later in the script). - "debug" => 0, ## Default debug level - "error" => '', ## Error messages will often be stored here - - ## Logging - "stdout" => 1, - "logging" => 0, ## If this is true the printmsg function prints to the log file - "logFile" => '', ## If this is specified (form the command line via -l) this file will be used for logging. - - ## Network - "server" => 'localhost', ## Default SMTP server - "port" => 25, ## Default port - "bindaddr" => '', ## Default local bind address - "alarm" => '', ## Default timeout for connects and reads, this gets set from $opt{'timeout'} - "tls_client" => 0, ## If TLS is supported by the client (us) - "tls_server" => 0, ## If TLS is supported by the remote SMTP server - - ## Email - "delimiter" => "----MIME delimiter for sendEmail-" ## MIME Delimiter - . rand(1000000), ## Add some randomness to the delimiter - "Message-ID" => rand(1000000) . "-sendEmail", ## Message-ID for email header - -); - - -## This hash stores the options passed on the command line via the -o option. -my %opt = ( - ## Addressing - "reply-to" => '', ## Reply-To field - - ## Message - "message-file" => '', ## File to read message body from - "message-header" => '', ## Additional email header line(s) - "message-format" => 'normal', ## If "raw" is specified the message is sent unmodified - "message-charset" => 'iso-8859-1', ## Message character-set - "message-content-type" => 'auto', ## auto, text, html or an actual string to put into the content-type header. - - ## Network - "timeout" => 60, ## Default timeout for connects and reads, this is copied to $conf{'alarm'} later. - "fqdn" => 'changeme', ## FQDN of this machine, used during SMTP communication (is updated later in the script). - - ## eSMTP - "username" => '', ## Username used in SMTP Auth - "password" => '', ## Password used in SMTP Auth - "tls" => 'auto', ## Enable or disable TLS support. Options: auto, yes, no - -); - -## More variables used later in the program -my $SERVER; -my $CRLF = "\015\012"; -my $subject = ''; -my $header = ''; -my $message = ''; -my $from = ''; -my @to = (); -my @cc = (); -my @bcc = (); -my @attachments = (); -my @attachments_names = (); - -## For printing colors to the console -my ${colorRed} = "\033[31;1m"; -my ${colorGreen} = "\033[32;1m"; -my ${colorCyan} = "\033[36;1m"; -my ${colorWhite} = "\033[37;1m"; -my ${colorNormal} = "\033[m"; -my ${colorBold} = "\033[1m"; -my ${colorNoBold} = "\033[0m"; - -## Don't use shell escape codes on Windows systems -if ($^O =~ /win/i) { - ${colorRed} = ${colorGreen} = ${colorCyan} = ${colorWhite} = ${colorNormal} = ${colorBold} = ${colorNoBold} = ""; -} - -## Load IO::Socket::SSL if it's available -eval { require IO::Socket::SSL; }; -if ($@) { $conf{'tls_client'} = 0; } -else { $conf{'tls_client'} = 1; } - - - - - - -############################# -## ## -## FUNCTIONS ## -## ## -############################# - - - - - -############################################################################################### -## Function: initialize () -## -## Does all the script startup jibberish. -## -############################################################################################### -sub initialize { - - ## Set STDOUT to flush immediatly after each print - $| = 1; - - ## Intercept signals - $SIG{'QUIT'} = sub { quit("EXITING: Received SIG$_[0]", 1); }; - $SIG{'INT'} = sub { quit("EXITING: Received SIG$_[0]", 1); }; - $SIG{'KILL'} = sub { quit("EXITING: Received SIG$_[0]", 1); }; - $SIG{'TERM'} = sub { quit("EXITING: Received SIG$_[0]", 1); }; - - ## ALARM and HUP signals are not supported in Win32 - unless ($^O =~ /win/i) { - $SIG{'HUP'} = sub { quit("EXITING: Received SIG$_[0]", 1); }; - $SIG{'ALRM'} = sub { quit("EXITING: Received SIG$_[0]", 1); }; - } - - ## Fixup $conf{'programName'} - $conf{'programName'} =~ s/(.)*[\/,\\]//; - $0 = $conf{'programName'} . " " . join(" ", @ARGV); - - ## Fixup $conf{'hostname'} and $opt{'fqdn'} - if ($opt{'fqdn'} eq 'changeme') { $opt{'fqdn'} = get_hostname(1); } - if ($conf{'hostname'} eq 'changeme') { $conf{'hostname'} = $opt{'fqdn'}; $conf{'hostname'} =~ s/\..*//; } - - return(1); -} - - - - - - - - - - - - - - - -############################################################################################### -## Function: processCommandLine () -## -## Processes command line storing important data in global vars (usually %conf) -## -############################################################################################### -sub processCommandLine { - - - ############################ - ## Process command line ## - ############################ - - my @ARGS = @ARGV; ## This is so later we can re-parse the command line args later if we need to - my $numargv = @ARGS; - help() unless ($numargv); - my $counter = 0; - - for ($counter = 0; $counter < $numargv; $counter++) { - - if ($ARGS[$counter] =~ /^-h$/i) { ## Help ## - help(); - } - - elsif ($ARGS[$counter] eq "") { ## Ignore null arguments - ## Do nothing - } - - elsif ($ARGS[$counter] =~ /^--help/) { ## Topical Help ## - $counter++; - if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - helpTopic($ARGS[$counter]); - } - else { - help(); - } - } - - elsif ($ARGS[$counter] =~ /^-o$/i) { ## Options specified with -o ## - $counter++; - ## Loop through each option passed after the -o - while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - - if ($ARGS[$counter] !~ /(\S+)=(\S.*)/) { - printmsg("WARNING => Name/Value pair [$ARGS[$counter]] is not properly formatted", 0); - printmsg("WARNING => Arguments proceeding -o should be in the form of \"name=value\"", 0); - } - else { - if (exists($opt{$1})) { - if ($1 eq 'message-header') { - $opt{$1} .= $2 . $CRLF; - } - else { - $opt{$1} = $2; - } - printmsg("DEBUG => Assigned \$opt{} key/value: $1 => $2", 3); - } - else { - printmsg("WARNING => Name/Value pair [$ARGS[$counter]] will be ignored: unknown key [$1]", 0); - printmsg("HINT => Try the --help option to find valid command line arguments", 1); - } - } - $counter++; - } $counter--; - } - - elsif ($ARGS[$counter] =~ /^-f$/) { ## From ## - $counter++; - if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { $from = $ARGS[$counter]; } - else { printmsg("WARNING => The argument after -f was not an email address!", 0); $counter--; } - } - - elsif ($ARGS[$counter] =~ /^-t$/) { ## To ## - $counter++; - while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) { - if ($ARGS[$counter] =~ /[;,]/) { - push (@to, split(/[;,]/, $ARGS[$counter])); - } - else { - push (@to,$ARGS[$counter]); - } - $counter++; - } $counter--; - } - - elsif ($ARGS[$counter] =~ /^-cc$/) { ## Cc ## - $counter++; - while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) { - if ($ARGS[$counter] =~ /[;,]/) { - push (@cc, split(/[;,]/, $ARGS[$counter])); - } - else { - push (@cc,$ARGS[$counter]); - } - $counter++; - } $counter--; - } - - elsif ($ARGS[$counter] =~ /^-bcc$/) { ## Bcc ## - $counter++; - while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) { - if ($ARGS[$counter] =~ /[;,]/) { - push (@bcc, split(/[;,]/, $ARGS[$counter])); - } - else { - push (@bcc,$ARGS[$counter]); - } - $counter++; - } $counter--; - } - - elsif ($ARGS[$counter] =~ /^-m$/) { ## Message ## - $counter++; - $message = ""; - while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - if ($message) { $message .= " "; } - $message .= $ARGS[$counter]; - $counter++; - } $counter--; - - ## Replace '\n' with $CRLF. - ## This allows newlines with messages sent on the command line - $message =~ s/\\n/$CRLF/g; - } - - elsif ($ARGS[$counter] =~ /^-u$/) { ## Subject ## - $counter++; - $subject = ""; - while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - if ($subject) { $subject .= " "; } - $subject .= $ARGS[$counter]; - $counter++; - } $counter--; - } - - elsif ($ARGS[$counter] =~ /^-s$/) { ## Server ## - $counter++; - if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - $conf{'server'} = $ARGS[$counter]; - if ($conf{'server'} =~ /:/) { ## Port ## - ($conf{'server'},$conf{'port'}) = split(":",$conf{'server'}); - } - } - else { printmsg("WARNING - The argument after -s was not the server!", 0); $counter--; } - } - - elsif ($ARGS[$counter] =~ /^-b$/) { ## Bind Address ## - $counter++; - if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - $conf{'bindaddr'} = $ARGS[$counter]; - } - else { printmsg("WARNING - The argument after -b was not the bindaddr!", 0); $counter--; } - } - - elsif ($ARGS[$counter] =~ /^-a$/) { ## Attachments ## - $counter++; - while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) { - push (@attachments,$ARGS[$counter]); - $counter++; - } $counter--; - } - - elsif ($ARGS[$counter] =~ /^-xu$/) { ## AuthSMTP Username ## - $counter++; - if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - $opt{'username'} = $ARGS[$counter]; - } - else { - printmsg("WARNING => The argument after -xu was not valid username!", 0); - $counter--; - } - } - - elsif ($ARGS[$counter] =~ /^-xp$/) { ## AuthSMTP Password ## - $counter++; - if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { - $opt{'password'} = $ARGS[$counter]; - } - else { - printmsg("WARNING => The argument after -xp was not valid password!", 0); - $counter--; - } - } - - elsif ($ARGS[$counter] =~ /^-l$/) { ## Logging ## - $counter++; - $conf{'logging'} = 1; - if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { $conf{'logFile'} = $ARGS[$counter]; } - else { printmsg("WARNING - The argument after -l was not the log file!", 0); $counter--; } - } - - elsif ($ARGS[$counter] =~ s/^-v+//i) { ## Verbosity ## - my $tmp = (length($&) - 1); - $conf{'debug'} += $tmp; - } - - elsif ($ARGS[$counter] =~ /^-q$/) { ## Quiet ## - $conf{'stdout'} = 0; - } - - else { - printmsg("Error: \"$ARGS[$counter]\" is not a recognized option!", 0); - help(); - } - - } - - - - - - - - - ################################################### - ## Verify required variables are set correctly ## - ################################################### - - ## Make sure we have something in $conf{hostname} and $opt{fqdn} - if ($opt{'fqdn'} =~ /\./) { - $conf{'hostname'} = $opt{'fqdn'}; - $conf{'hostname'} =~ s/\..*//; - } - - if (!$conf{'server'}) { $conf{'server'} = 'localhost'; } - if (!$conf{'port'}) { $conf{'port'} = 25; } - if (!$from) { - quit("ERROR => You must specify a 'from' field! Try --help.", 1); - } - if ( ((scalar(@to)) + (scalar(@cc)) + (scalar(@bcc))) <= 0) { - quit("ERROR => You must specify at least one recipient via -t, -cc, or -bcc", 1); - } - - ## Make sure email addresses look OK. - foreach my $addr (@to, @cc, @bcc, $from, $opt{'reply-to'}) { - if ($addr) { - if (!returnAddressParts($addr)) { - printmsg("ERROR => Can't use improperly formatted email address: $addr", 0); - printmsg("HINT => Try viewing the extended help on addressing with \"--help addressing\"", 1); - quit("", 1); - } - } - } - - ## Make sure all attachments exist. - foreach my $file (@attachments) { - if ( (! -f $file) or (! -r $file) ) { - printmsg("ERROR => The attachment [$file] doesn't exist!", 0); - printmsg("HINT => Try specifying the full path to the file or reading extended help with \"--help message\"", 1); - quit("", 1); - } - } - - if ($conf{'logging'} and (!$conf{'logFile'})) { - quit("ERROR => You used -l to enable logging but didn't specify a log file!", 1); - } - - if ( $opt{'username'} ) { - if (!$opt{'password'}) { - ## Prompt for a password since one wasn't specified with the -xp option. - $SIG{'ALRM'} = sub { quit("ERROR => Timeout waiting for password inpupt", 1); }; - alarm(60) if ($^O !~ /win/i); ## alarm() doesn't work in win32 - print "Password: "; - $opt{'password'} = ; chomp $opt{'password'}; - if (!$opt{'password'}) { - quit("ERROR => A username for SMTP authentication was specified, but no password!", 1); - } - } - } - - ## Validate the TLS setting - $opt{'tls'} = lc($opt{'tls'}); - if ($opt{'tls'} !~ /^(auto|yes|no)$/) { - quit("ERROR => Invalid TLS setting ($opt{'tls'}). Must be one of auto, yes, or no.", 1); - } - - ## If TLS is set to "yes", make sure sendEmail loaded the libraries needed. - if ($opt{'tls'} eq 'yes' and $conf{'tls_client'} == 0) { - quit("ERROR => No TLS support! SendEmail can't load required libraries. (try installing Net::SSLeay and IO::Socket::SSL)", 1); - } - - ## Return 0 errors - return(0); -} - - - - - - - - - - - - - - - - -## getline($socketRef) -sub getline { - my ($socketRef) = @_; - local ($/) = "\r\n"; - return $$socketRef->getline; -} - - - - -## Receive a (multiline?) SMTP response from ($socketRef) -sub getResponse { - my ($socketRef) = @_; - my ($tmp, $reply); - local ($/) = "\r\n"; - return undef unless defined($tmp = getline($socketRef)); - return("getResponse() socket is not open") unless ($$socketRef->opened); - ## Keep reading lines if it's a multi-line response - while ($tmp =~ /^\d{3}-/o) { - $reply .= $tmp; - return undef unless defined($tmp = getline($socketRef)); - } - $reply .= $tmp; - $reply =~ s/\r?\n$//o; - return $reply; -} - - - - -############################################################################################### -## Function: SMTPchat ( [string $command] ) -## -## Description: Sends $command to the SMTP server (on SERVER) and awaits a successful -## reply form the server. If the server returns an error, or does not reply -## within $conf{'alarm'} seconds an error is generated. -## NOTE: $command is optional, if no command is specified then nothing will -## be sent to the server, but a valid response is still required from the server. -## -## Input: [$command] A (optional) valid SMTP command (ex. "HELO") -## -## -## Output: Returns zero on success, or non-zero on error. -## Error messages will be stored in $conf{'error'} -## A copy of the last SMTP response is stored in the global variable -## $conf{'SMTPchat_response'} -## -## -## Example: SMTPchat ("HELO mail.isp.net"); -############################################################################################### -sub SMTPchat { - my ($command) = @_; - - printmsg("INFO => Sending: \t$command", 1) if ($command); - - ## Send our command - print $SERVER "$command$CRLF" if ($command); - - ## Read a response from the server - $SIG{'ALRM'} = sub { $conf{'error'} = "alarm"; $SERVER->close(); }; - alarm($conf{'alarm'}) if ($^O !~ /win/i); ## alarm() doesn't work in win32; - my $result = $conf{'SMTPchat_response'} = getResponse(\$SERVER); - alarm(0) if ($^O !~ /win/i); ## alarm() doesn't work in win32; - - ## Generate an alert if we timed out - if ($conf{'error'} eq "alarm") { - $conf{'error'} = "ERROR => Timeout while reading from $conf{'server'}:$conf{'port'} There was no response after $conf{'alarm'} seconds."; - return(1); - } - - ## Make sure the server actually responded - if (!$result) { - $conf{'error'} = "ERROR => $conf{'server'}:$conf{'port'} returned a zero byte response to our query."; - return(2); - } - - ## Validate the response - if (evalSMTPresponse($result)) { - ## conf{'error'} will already be set here - return(2); - } - - ## Print the success messsage - printmsg($conf{'error'}, 1); - - ## Return Success - return(0); -} - - - - - - - - - - - - -############################################################################################### -## Function: evalSMTPresponse (string $message ) -## -## Description: Searches $message for either an SMTP success or error code, and returns -## 0 on success, and the actual error code on error. -## -## -## Input: $message Data received from a SMTP server (ex. "220 -## -## -## Output: Returns zero on success, or non-zero on error. -## Error messages will be stored in $conf{'error'} -## -## -## Example: SMTPchat ("HELO mail.isp.net"); -############################################################################################### -sub evalSMTPresponse { - my ($message) = @_; - - ## Validate input - if (!$message) { - $conf{'error'} = "ERROR => No message was passed to evalSMTPresponse(). What happened?"; - return(1) - } - - printmsg("DEBUG => evalSMTPresponse() - Checking for SMTP success or error status in the message: $message ", 3); - - ## Look for a SMTP success code - if ($message =~ /^([23]\d\d)/) { - printmsg("DEBUG => evalSMTPresponse() - Found SMTP success code: $1", 2); - $conf{'error'} = "SUCCESS => Received: \t$message"; - return(0); - } - - ## Look for a SMTP error code - if ($message =~ /^([45]\d\d)/) { - printmsg("DEBUG => evalSMTPresponse() - Found SMTP error code: $1", 2); - $conf{'error'} = "ERROR => Received: \t$message"; - return($1); - } - - ## If no SMTP codes were found return an error of 1 - $conf{'error'} = "ERROR => Received a message with no success or error code. The message received was: $message"; - return(2); - -} - - - - - - - - - - -######################################################### -# SUB: &return_month(0,1,etc) -# returns the name of the month that corrosponds -# with the number. returns 0 on error. -######################################################### -sub return_month { - my $x = $_[0]; - if ($x == 0) { return 'Jan'; } - if ($x == 1) { return 'Feb'; } - if ($x == 2) { return 'Mar'; } - if ($x == 3) { return 'Apr'; } - if ($x == 4) { return 'May'; } - if ($x == 5) { return 'Jun'; } - if ($x == 6) { return 'Jul'; } - if ($x == 7) { return 'Aug'; } - if ($x == 8) { return 'Sep'; } - if ($x == 9) { return 'Oct'; } - if ($x == 10) { return 'Nov'; } - if ($x == 11) { return 'Dec'; } - return (0); -} - - - - - - - - - - - - - - - - -######################################################### -# SUB: &return_day(0,1,etc) -# returns the name of the day that corrosponds -# with the number. returns 0 on error. -######################################################### -sub return_day { - my $x = $_[0]; - if ($x == 0) { return 'Sun'; } - if ($x == 1) { return 'Mon'; } - if ($x == 2) { return 'Tue'; } - if ($x == 3) { return 'Wed'; } - if ($x == 4) { return 'Thu'; } - if ($x == 5) { return 'Fri'; } - if ($x == 6) { return 'Sat'; } - return (0); -} - - - - - - - - - - - - - - - - -############################################################################################### -## Function: returnAddressParts(string $address) -## -## Description: Returns a two element array containing the "Name" and "Address" parts of -## an email address. -## -## Example: "Brandon Zehm " -## would return: ("Brandon Zehm", "caspian@dotconf.net"); -## -## "caspian@dotconf.net" -## would return: ("caspian@dotconf.net", "caspian@dotconf.net") -############################################################################################### -sub returnAddressParts { - my $input = $_[0]; - my $name = ""; - my $address = ""; - - ## Make sure to fail if it looks totally invalid - if ($input !~ /(\S+\@\S+)/) { - $conf{'error'} = "ERROR => The address [$input] doesn't look like a valid email address, ignoring it"; - return(undef()); - } - - ## Check 1, should find addresses like: "Brandon Zehm " - elsif ($input =~ /^\s*(\S(.*\S)?)\s*<(\S+\@\S+)>/o) { - ($name, $address) = ($1, $3); - } - - ## Otherwise if that failed, just get the address: - elsif ($input =~ /<(\S+\@\S+)>/o) { - $name = $address = $1; - } - - ## Or maybe it was formatted this way: caspian@dotconf.net - elsif ($input =~ /(\S+\@\S+)/o) { - $name = $address = $1; - } - - ## Something stupid happened, just return an error. - unless ($name and $address) { - printmsg("ERROR => Couldn't parse the address: $input", 0); - printmsg("HINT => If you think this should work, consider reporting this as a bug to $conf{'authorEmail'}", 1); - return(undef()); - } - - ## Make sure there aren't invalid characters in the address, and return it. - my $ctrl = '\000-\037'; - my $nonASCII = '\x80-\xff'; - if ($address =~ /[<> ,;:"'\[\]\\$ctrl$nonASCII]/) { - printmsg("WARNING => The address [$address] seems to contain invalid characters: continuing anyway", 0); - } - return($name, $address); -} - - - - - - - - - - - - - - - - -############################################################################################### -## Function: base64_encode(string $data, bool $chunk) -## -## Description: Returns $data as a base64 encoded string. -## If $chunk is true, the encoded data is returned in 76 character long lines -## with the final \CR\LF removed. -## -## Note: This is only used from the smtp auth section of code. -## At some point it would be nice to merge the code that encodes attachments and this. -############################################################################################### -sub base64_encode { - my $data = $_[0]; - my $chunk = $_[1]; - my $tmp = ''; - my $base64 = ''; - my $CRLF = "\r\n"; - - ################################### - ## Convert binary data to base64 ## - ################################### - while ($data =~ s/(.{45})//s) { ## Get 45 bytes from the binary string - $tmp = substr(pack('u', $&), 1); ## Convert the binary to uuencoded text - chop($tmp); - $tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64 - $base64 .= $tmp; - } - - ########################## - ## Encode the leftovers ## - ########################## - my $padding = ""; - if ( ($data) and (length($data) > 0) ) { - $padding = (3 - length($data) % 3) % 3; ## Set flag if binary data isn't divisible by 3 - $tmp = substr(pack('u', $data), 1); ## Convert the binary to uuencoded text - chop($tmp); - $tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64 - $base64 .= $tmp; - } - - ############################ - ## Fix padding at the end ## - ############################ - $data = ''; - $base64 =~ s/.{$padding}$/'=' x $padding/e if $padding; ## Fix the end padding if flag (from above) is set - if ($chunk) { - while ($base64 =~ s/(.{1,76})//s) { ## Put $CRLF after each 76 characters - $data .= "$1$CRLF"; - } - } - else { - $data = $base64; - } - - ## Remove any trailing CRLF's - $data =~ s/(\r|\n)*$//s; - return($data); -} - - - - - - - - - -######################################################### -# SUB: send_attachment("/path/filename") -# Sends the mime headers and base64 encoded file -# to the email server. -######################################################### -sub send_attachment { - my ($filename) = @_; ## Get filename passed - my (@fields, $y, $filename_name, $encoding, ## Local variables - @attachlines, $content_type); - my $bin = 1; - - @fields = split(/\/|\\/, $filename); ## Get the actual filename without the path - $filename_name = pop(@fields); - push @attachments_names, $filename_name; ## FIXME: This is only used later for putting in the log file - - ########################## - ## Autodetect Mime Type ## - ########################## - - @fields = split(/\./, $filename_name); - $encoding = $fields[$#fields]; - - if ($encoding =~ /txt|text|log|conf|^c$|cpp|^h$|inc|m3u/i) { $content_type = 'text/plain'; } - elsif ($encoding =~ /html|htm|shtml|shtm|asp|php|cfm/i) { $content_type = 'text/html'; } - elsif ($encoding =~ /sh$/i) { $content_type = 'application/x-sh'; } - elsif ($encoding =~ /tcl/i) { $content_type = 'application/x-tcl'; } - elsif ($encoding =~ /pl$/i) { $content_type = 'application/x-perl'; } - elsif ($encoding =~ /js$/i) { $content_type = 'application/x-javascript'; } - elsif ($encoding =~ /man/i) { $content_type = 'application/x-troff-man'; } - elsif ($encoding =~ /gif/i) { $content_type = 'image/gif'; } - elsif ($encoding =~ /jpg|jpeg|jpe|jfif|pjpeg|pjp/i) { $content_type = 'image/jpeg'; } - elsif ($encoding =~ /tif|tiff/i) { $content_type = 'image/tiff'; } - elsif ($encoding =~ /xpm/i) { $content_type = 'image/x-xpixmap'; } - elsif ($encoding =~ /bmp/i) { $content_type = 'image/x-MS-bmp'; } - elsif ($encoding =~ /pcd/i) { $content_type = 'image/x-photo-cd'; } - elsif ($encoding =~ /png/i) { $content_type = 'image/png'; } - elsif ($encoding =~ /aif|aiff/i) { $content_type = 'audio/x-aiff'; } - elsif ($encoding =~ /wav/i) { $content_type = 'audio/x-wav'; } - elsif ($encoding =~ /mp2|mp3|mpa/i) { $content_type = 'audio/x-mpeg'; } - elsif ($encoding =~ /ra$|ram/i) { $content_type = 'audio/x-pn-realaudio'; } - elsif ($encoding =~ /mpeg|mpg/i) { $content_type = 'video/mpeg'; } - elsif ($encoding =~ /mov|qt$/i) { $content_type = 'video/quicktime'; } - elsif ($encoding =~ /avi/i) { $content_type = 'video/x-msvideo'; } - elsif ($encoding =~ /zip/i) { $content_type = 'application/x-zip-compressed'; } - elsif ($encoding =~ /tar/i) { $content_type = 'application/x-tar'; } - elsif ($encoding =~ /jar/i) { $content_type = 'application/java-archive'; } - elsif ($encoding =~ /exe|bin/i) { $content_type = 'application/octet-stream'; } - elsif ($encoding =~ /ppt|pot|ppa|pps|pwz/i) { $content_type = 'application/vnd.ms-powerpoint'; } - elsif ($encoding =~ /mdb|mda|mde/i) { $content_type = 'application/vnd.ms-access'; } - elsif ($encoding =~ /xls|xlt|xlm|xld|xla|xlc|xlw|xll/i) { $content_type = 'application/vnd.ms-excel'; } - elsif ($encoding =~ /doc|dot/i) { $content_type = 'application/msword'; } - elsif ($encoding =~ /rtf/i) { $content_type = 'application/rtf'; } - elsif ($encoding =~ /pdf/i) { $content_type = 'application/pdf'; } - elsif ($encoding =~ /tex/i) { $content_type = 'application/x-tex'; } - elsif ($encoding =~ /latex/i) { $content_type = 'application/x-latex'; } - elsif ($encoding =~ /vcf/i) { $content_type = 'application/x-vcard'; } - else { $content_type = 'application/octet-stream'; } - - - ############################ - ## Process the attachment ## - ############################ - - ##################################### - ## Generate and print MIME headers ## - ##################################### - - $y = "$CRLF--$conf{'delimiter'}$CRLF"; - $y .= "Content-Type: $content_type;$CRLF"; - $y .= " name=\"$filename_name\"$CRLF"; - $y .= "Content-Transfer-Encoding: base64$CRLF"; - $y .= "Content-Disposition: attachment; filename=\"$filename_name\"$CRLF"; - $y .= "$CRLF"; - print $SERVER $y; - - - ########################################################### - ## Convert the file to base64 and print it to the server ## - ########################################################### - - open (FILETOATTACH, $filename) || do { - printmsg("ERROR => Opening the file [$filename] for attachment failed with the error: $!", 0); - return(1); - }; - binmode(FILETOATTACH); ## Hack to make Win32 work - - my $res = ""; - my $tmp = ""; - my $base64 = ""; - while () { ## Read a line from the (binary) file - $res .= $_; - - ################################### - ## Convert binary data to base64 ## - ################################### - while ($res =~ s/(.{45})//s) { ## Get 45 bytes from the binary string - $tmp = substr(pack('u', $&), 1); ## Convert the binary to uuencoded text - chop($tmp); - $tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64 - $base64 .= $tmp; - } - - ################################ - ## Print chunks to the server ## - ################################ - while ($base64 =~ s/(.{76})//s) { - print $SERVER "$1$CRLF"; - } - - } - - ################################### - ## Encode and send the leftovers ## - ################################### - my $padding = ""; - if ( ($res) and (length($res) >= 1) ) { - $padding = (3 - length($res) % 3) % 3; ## Set flag if binary data isn't divisible by 3 - $res = substr(pack('u', $res), 1); ## Convert the binary to uuencoded text - chop($res); - $res =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64 - } - - ############################ - ## Fix padding at the end ## - ############################ - $res = $base64 . $res; ## Get left overs from above - $res =~ s/.{$padding}$/'=' x $padding/e if $padding; ## Fix the end padding if flag (from above) is set - if ($res) { - while ($res =~ s/(.{1,76})//s) { ## Send it to the email server. - print $SERVER "$1$CRLF"; - } - } - - close (FILETOATTACH) || do { - printmsg("ERROR - Closing the filehandle for file [$filename] failed with the error: $!", 0); - return(2); - }; - - ## Return 0 errors - return(0); - -} - - - - - - - - - -############################################################################################### -## Function: $string = get_hostname (boot $fqdn) -## -## Description: Tries really hard to returns the short (or FQDN) hostname of the current -## system. Uses techniques and code from the Sys-Hostname module. -## -## Input: $fqdn A true value (1) will cause this function to return a FQDN hostname -## rather than a short hostname. -## -## Output: Returns a string -############################################################################################### -sub get_hostname { - ## Assign incoming parameters to variables - my ( $fqdn ) = @_; - my $hostname = ""; - - ## STEP 1: Get short hostname - - ## Load Sys::Hostname if it's available - eval { require Sys::Hostname; }; - unless ($@) { - $hostname = Sys::Hostname::hostname(); - } - - ## If that didn't get us a hostname, try a few other things - else { - ## Windows systems - if ($^O !~ /win/i) { - if ($ENV{'COMPUTERNAME'}) { $hostname = $ENV{'COMPUTERNAME'}; } - if (!$hostname) { $hostname = gethostbyname('localhost'); } - if (!$hostname) { chomp($hostname = `hostname 2> NUL`) }; - } - - ## Unix systems - else { - local $ENV{PATH} = '/usr/bin:/bin:/usr/sbin:/sbin'; ## Paranoia - - ## Try the environment first (Help! What other variables could/should I be checking here?) - if ($ENV{'HOSTNAME'}) { $hostname = $ENV{'HOSTNAME'}; } - - ## Try the hostname command - eval { local $SIG{__DIE__}; local $SIG{CHLD}; $hostname = `hostname 2>/dev/null`; chomp($hostname); } || - - ## Try POSIX::uname(), which strictly can't be expected to be correct - eval { local $SIG{__DIE__}; require POSIX; $hostname = (POSIX::uname())[1]; } || - - ## Try the uname command - eval { local $SIG{__DIE__}; $hostname = `uname -n 2>/dev/null`; chomp($hostname); }; - - } - - ## If we can't find anything else, return "" - if (!$hostname) { - print "WARNING => No hostname could be determined, please specify one with -o fqdn=FQDN option!\n"; - return("unknown"); - } - } - - ## Return the short hostname - unless ($fqdn) { - $hostname =~ s/\..*//; - return(lc($hostname)); - } - - ## STEP 2: Determine the FQDN - - ## First, if we already have one return it. - if ($hostname =~ /\w\.\w/) { return(lc($hostname)); } - - ## Next try using - eval { $fqdn = (gethostbyname($hostname))[0]; }; - if ($fqdn) { return(lc($fqdn)); } - return(lc($hostname)); -} - - - - - - - - -############################################################################################### -## Function: printmsg (string $message, int $level) -## -## Description: Handles all messages - printing them to the screen only if the messages -## $level is >= the global debug level. If $conf{'logFile'} is defined it -## will also log the message to that file. -## -## Input: $message A message to be printed, logged, etc. -## $level The debug level of the message. If -## not defined 0 will be assumed. 0 is -## considered a normal message, 1 and -## higher is considered a debug message. -## -## Output: Prints to STDOUT -## -## Assumptions: $conf{'hostname'} should be the name of the computer we're running on. -## $conf{'stdout'} should be set to 1 if you want to print to stdout -## $conf{'logFile'} should be a full path to a log file if you want that -## $conf{'debug'} should be an integer between 0 and 10. -## -## Example: printmsg("WARNING: We believe in generic error messages... NOT!", 0); -############################################################################################### -sub printmsg { - ## Assign incoming parameters to variables - my ( $message, $level ) = @_; - - ## Make sure input is sane - $level = 0 if (!defined($level)); - $message =~ s/\s+$//sgo; - $message =~ s/\r?\n/, /sgo; - - ## Continue only if the debug level of the program is >= message debug level. - if ($conf{'debug'} >= $level) { - - ## Get the date in the format: Dec 3 11:14:04 - my ($sec, $min, $hour, $mday, $mon) = localtime(); - $mon = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[$mon]; - my $date = sprintf("%s %02d %02d:%02d:%02d", $mon, $mday, $hour, $min, $sec); - - ## Print to STDOUT always if debugging is enabled, or if conf{stdout} is true. - if ( ($conf{'debug'} >= 1) or ($conf{'stdout'} == 1) ) { - print "$date $conf{'hostname'} $conf{'programName'}\[$$\]: $message\n"; - } - - ## Print to the log file if $conf{'logging'} is true - if ($conf{'logFile'}) { - if (openLogFile($conf{'logFile'})) { $conf{'logFile'} = ""; printmsg("ERROR => Opening the file [$conf{'logFile'}] for appending returned the error: $!", 1); } - print LOGFILE "$date $conf{'hostname'} $conf{'programName'}\[$$\]: $message\n"; - } - - } - - ## Return 0 errors - return(0); -} - - - - - - - - - - - - -############################################################################################### -## FUNCTION: -## openLogFile ( $filename ) -## -## -## DESCRIPTION: -## Opens the file $filename and attaches it to the filehandle "LOGFILE". Returns 0 on success -## and non-zero on failure. Error codes are listed below, and the error message gets set in -## global variable $!. -## -## -## Example: -## openFile ("/var/log/sendEmail.log"); -## -############################################################################################### -sub openLogFile { - ## Get the incoming filename - my $filename = $_[0]; - - ## Make sure our file exists, and if the file doesn't exist then create it - if ( ! -f $filename ) { - print STDERR "NOTICE: The log file [$filename] does not exist. Creating it now with mode [0600].\n" if ($conf{'stdout'}); - open (LOGFILE, ">>$filename"); - close LOGFILE; - chmod (0600, $filename); - } - - ## Now open the file and attach it to a filehandle - open (LOGFILE,">>$filename") or return (1); - - ## Put the file into non-buffering mode - select LOGFILE; - $| = 1; - select STDOUT; - - ## Return success - return(0); -} - - - - - - - - -############################################################################################### -## Function: read_file (string $filename) -## -## Description: Reads the contents of a file and returns a two part array: -## ($status, $file-contents) -## $status is 0 on success, non-zero on error. -## -## Example: ($status, $file) = read_file("/etc/passwd"); -############################################################################################### -sub read_file { - my ( $filename ) = @_; - - ## If the value specified is a file, load the file's contents - if ( (-e $filename and -r $filename) ) { - my $FILE; - if(!open($FILE, ' ' . $filename)) { - return((1, "")); - } - my $file = ''; - while (<$FILE>) { - $file .= $_; - } - ## Strip an ending \r\n - $file =~ s/\r?\n$//os; - } - return((1, "")); -} - - - - - - - - - -############################################################################################### -## Function: quit (string $message, int $errorLevel) -## -## Description: Exits the program, optionally printing $message. It -## returns an exit error level of $errorLevel to the -## system (0 means no errors, and is assumed if empty.) -## -## Example: quit("Exiting program normally", 0); -############################################################################################### -sub quit { - my ( $message, $errorLevel ) = @_; - $errorLevel = 0 if (!defined($errorLevel)); - - ## Print exit message - if ($message) { - printmsg($message, 0); - } - - ## Exit - exit($errorLevel); -} - - - - - - - - - - - - -############################################################################################### -## Function: help () -## -## Description: For all those newbies ;) -## Prints a help message and exits the program. -## -############################################################################################### -sub help { -exit(1) if (!$conf{'stdout'}); -print <${colorNoBold} - -Synopsis: $conf{'programName'} -f ADDRESS [options] - - ${colorRed}Required:${colorNormal} - -f ADDRESS from (sender) email address - * At least one recipient required via -t, -cc, or -bcc - * Message body required via -m, STDIN, or -o message-file=FILE - - ${colorGreen}Common:${colorNormal} - -t ADDRESS [ADDR ...] to email address(es) - -u SUBJECT message subject - -m MESSAGE message body - -s SERVER[:PORT] smtp mail relay, default is $conf{'server'}:$conf{'port'} - - ${colorGreen}Optional:${colorNormal} - -a FILE [FILE ...] file attachment(s) - -cc ADDRESS [ADDR ...] cc email address(es) - -bcc ADDRESS [ADDR ...] bcc email address(es) - -xu USERNAME username for SMTP authentication - -xp PASSWORD password for SMTP authentication - - ${colorGreen}Paranormal:${colorNormal} - -b BINDADDR[:PORT] local host bind address - -l LOGFILE log to the specified file - -v verbosity, use multiple times for greater effect - -q be quiet (i.e. no STDOUT output) - -o NAME=VALUE advanced options, for details try: --help misc - -o message-content-type= - -o message-file=FILE -o message-format=raw - -o message-header=HEADER -o message-charset=CHARSET - -o reply-to=ADDRESS -o timeout=SECONDS - -o username=USERNAME -o password=PASSWORD - -o tls= -o fqdn=FQDN - - - ${colorGreen}Help:${colorNormal} - --help the helpful overview you're reading now - --help addressing explain addressing and related options - --help message explain message body input and related options - --help networking explain -s, -b, etc - --help output explain logging and other output options - --help misc explain -o options, TLS, SMTP auth, and more - -EOM -exit(1); -} - - - - - - - - - -############################################################################################### -## Function: helpTopic ($topic) -## -## Description: For all those newbies ;) -## Prints a help message and exits the program. -## -############################################################################################### -sub helpTopic { - exit(1) if (!$conf{'stdout'}); - my ($topic) = @_; - - CASE: { - - - - -## ADDRESSING - ($topic eq 'addressing') && do { - print <" - Just Address: "john.doe\@gmail.com" - -The "Full Name" method is useful if you want a name, rather than a plain -email address, to be displayed in the recipient's From, To, or Cc fields -when they view the message. - - -${colorGreen}Multiple Recipients${colorNormal} -The -t, -cc, and -bcc options each accept multiple addresses. They may be -specified by separating them by either a white space, comma, or semi-colon -separated list. You may also specify the -t, -cc, and -bcc options multiple -times, each occurance will append the new recipients to the respective list. - -Examples: -(I used "-t" in these examples, but it can be "-cc" or "-bcc" as well) - - * Space separated list: - -t jane.doe\@yahoo.com "John Doe " - - * Semi-colon separated list: - -t "jane.doe\@yahoo.com; John Doe " - - * Comma separated list: - -t "jane.doe\@yahoo.com, John Doe " - - * Multiple -t, -cc, or -bcc options: - -t "jane.doe\@yahoo.com" -t "John Doe " - - -EOM - last CASE; - }; - - - - - - -## MESSAGE - ($topic eq 'message') && do { - print < - -o message-header=EMAIL HEADER - -o message-charset=CHARSET - -o message-format=raw - --u SUBJECT - This option allows you to specify the subject for your email message. - It is not required (anymore) that the subject be quoted, although it - is recommended. The subject will be read until an argument starting - with a hyphen (-) is found. - Examples: - -u "Contact information while on vacation" - -u New Microsoft vulnerability discovered - --m MESSAGE - This option is one of three methods that allow you to specify the message - body for your email. The message may be specified on the command line - with this -m option, read from a file with the -o message-file=FILE - option, or read from STDIN if neither of these options are present. - - It is not required (anymore) that the message be quoted, although it is - recommended. The message will be read until an argument starting with a - hyphen (-) is found. - Examples: - -m "See you in South Beach, Hawaii. -Todd" - -m Please ensure that you upgrade your systems right away - - Multi-line message bodies may be specified with the -m option by putting - a "\\n" into the message. Example: - -m "This is line 1.\\nAnd this is line 2." - - HTML messages are supported, simply begin your message with "" and - sendEmail will properly label the mime header so MUAs properly render - the message. It is currently not possible without "-o message-format=raw" - to send a message with both text and html parts with sendEmail. - --o message-file=FILE - This option is one of three methods that allow you to specify the message - body for your email. To use this option simply specify a text file - containing the body of your email message. Examples: - -o message-file=/root/message.txt - -o message-file="C:\\Program Files\\output.txt" - --o message-content-type= - This option allows you to specify the content-type of the email. If your - email message is an html message but is being displayed as a text message - just add "-o message-content-type=html" to the command line to force it - to display as an html message. This actually just changes the Content-Type: - header. Advanced users will be happy to know that if you specify anything - other than the three options listed above it will use that as the vaule - for the Content-Type header. - --o message-header=EMAIL HEADER - This option allows you to specify additional email headers to be included. - To add more than one message header simply use this option on the command - line more than once. If you specify a message header that sendEmail would - normally generate the one you specified will be used in it's place. - Do not use this unless you know what you are doing! - Example: - To scare a Microsoft Outlook user you may want to try this: - -o message-header="X-Message-Flag: Message contains illegal content" - Example: - To request a read-receipt try this: - -o message-header="Disposition-Notification-To: " - Example: - To set the message priority try this: - -o message-header="X-Priority: 1" - Priority reference: 1=highest, 2=high, 3=normal, 4=low, 5=lowest - --o message-charset=CHARSET - This option allows you to specify the character-set for the message body. - The default is iso-8859-1. - --o message-format=raw - This option instructs sendEmail to assume the message (specified with -m, - read from STDIN, or read from the file specified in -o message-file=FILE) - is already a *complete* email message. SendEmail will not generate any - headers and will transmit the message as-is to the remote SMTP server. - Due to the nature of this option the following command line options will - be ignored when this one is used: - -u SUBJECT - -o message-header=EMAIL HEADER - -o message-charset=CHARSET - -a ATTACHMENT - - -${colorGreen}The Message Body${colorNormal} -The email message body may be specified in one of three ways: - 1) Via the -m MESSAGE command line option. - Example: - -m "This is the message body" - - 2) By putting the message body in a file and using the -o message-file=FILE - command line option. - Example: - -o message-file=/root/message.txt - - 3) By piping the message body to sendEmail when nither of the above command - line options were specified. - Example: - grep "ERROR" /var/log/messages | sendEmail -t you\@domain.com ... - -If the message body begins with "" then the message will be treated as -an HTML message and the MIME headers will be written so that a HTML capable -email client will display the message in it's HTML form. -Any of the above methods may be used with the -o message-format=raw option -to deliver an already complete email message. - - -EOM - last CASE; - }; - - - - - - -## MISC - ($topic eq 'misc') && do { - print < - -o timeout=SECONDS - -o fqdn=FQDN - --a ATTACHMENT [ATTACHMENT ...] - This option allows you to attach any number of files to your email message. - To specify more than one attachment, simply separate each filename with a - space. Example: -a file1.txt file2.txt file3.txt - --xu USERNAME - Alias for -o username=USERNAME - --xp PASSWORD - Alias for -o password=PASSWORD - --o username=USERNAME (synonym for -xu) - These options allow specification of a username to be used with SMTP - servers that require authentication. If a username is specified but a - password is not, you will be prompted to enter one at runtime. - --o password=PASSWORD (synonym for -xp) - These options allow specification of a password to be used with SMTP - servers that require authentication. If a username is specified but a - password is not, you will be prompted to enter one at runtime. - --o tls= - This option allows you to specify if TLS (SSL for SMTP) should be enabled - or disabled. The default, auto, will use TLS automatically if your perl - installation has the IO::Socket::SSL and Net::SSLeay modules available, - and if the remote SMTP server supports TLS. To require TLS for message - delivery set this to yes. To disable TLS support set this to no. A debug - level of one or higher will reveal details about the status of TLS. - --o timeout=SECONDS - This option sets the timeout value in seconds used for all network reads, - writes, and a few other things. - --o fqdn=FQDN - This option sets the Fully Qualified Domain Name used during the initial - SMTP greeting. Normally this is automatically detected, but in case you - need to manually set it for some reason or get a warning about detection - failing, you can use this to override the default. - - -EOM - last CASE; - }; - - - - - - -## NETWORKING - ($topic eq 'networking') && do { - print < - -o timeout=SECONDS - --s SERVER[:PORT] - This option allows you to specify the SMTP server sendEmail should - connect to to deliver your email message to. If this option is not - specified sendEmail will try to connect to localhost:25 to deliver - the message. THIS IS MOST LIKELY NOT WHAT YOU WANT, AND WILL LIKELY - FAIL unless you have a email server (commonly known as an MTA) running - on your computer! - Typically you will need to specify your company or ISP's email server. - For example, if you use CableOne you will need to specify: - -s mail.cableone.net - If you have your own email server running on port 300 you would - probably use an option like this: - -s myserver.mydomain.com:300 - If you're a GMail user try: - -s smtp.gmail.com:587 -xu me\@gmail.com -xp PASSWD - --b BINDADDR[:PORT] - This option allows you to specify the local IP address (and optional - tcp port number) for sendEmail to bind to when connecting to the remote - SMTP server. This useful for people who need to send an email from a - specific network interface or source address and are running sendEmail on - a firewall or other host with several network interfaces. - --o tls= - This option allows you to specify if TLS (SSL for SMTP) should be enabled - or disabled. The default, auto, will use TLS automatically if your perl - installation has the IO::Socket::SSL and Net::SSLeay modules available, - and if the remote SMTP server supports TLS. To require TLS for message - delivery set this to yes. To disable TLS support set this to no. A debug - level of one or higher will reveal details about the status of TLS. - --o timeout=SECONDS - This option sets the timeout value in seconds used for all network reads, - writes, and a few other things. - - -EOM - last CASE; - }; - - - - - - -## OUTPUT - ($topic eq 'output') && do { - print < The help topic specified is not valid!", 1); - }; - -exit(1); -} - - - - - - - - - - - - - - - - - - - - - - -############################# -## ## -## MAIN PROGRAM ## -## ## -############################# - - -## Initialize -initialize(); - -## Process Command Line -processCommandLine(); -$conf{'alarm'} = $opt{'timeout'}; - -## Abort program after $conf{'alarm'} seconds to avoid infinite hangs -alarm($conf{'alarm'}) if ($^O !~ /win/i); ## alarm() doesn't work in win32 - - - - -################################################### -## Read $message from STDIN if -m was not used ## -################################################### - -if (!($message)) { - ## Read message body from a file specified with -o message-file= - if ($opt{'message-file'}) { - if (! -e $opt{'message-file'}) { - printmsg("ERROR => Message body file specified [$opt{'message-file'}] does not exist!", 0); - printmsg("HINT => 1) check spelling of your file; 2) fully qualify the path; 3) doubble quote it", 1); - quit("", 1); - } - if (! -r $opt{'message-file'}) { - printmsg("ERROR => Message body file specified can not be read due to restricted permissions!", 0); - printmsg("HINT => Check permissions on file specified to ensure it can be read", 1); - quit("", 1); - } - if (!open(MFILE, "< " . $opt{'message-file'})) { - printmsg("ERROR => Error opening message body file [$opt{'message-file'}]: $!", 0); - quit("", 1); - } - while () { - $message .= $_; - } - close(MFILE); - } - - ## Read message body from STDIN - else { - alarm($conf{'alarm'}) if ($^O !~ /win/i); ## alarm() doesn't work in win32 - if ($conf{'stdout'}) { - print "Reading message body from STDIN because the '-m' option was not used.\n"; - print "If you are manually typing in a message:\n"; - print " - First line must be received within $conf{'alarm'} seconds.\n" if ($^O !~ /win/i); - print " - End manual input with a CTRL-D on its own line.\n\n" if ($^O !~ /win/i); - print " - End manual input with a CTRL-Z on its own line.\n\n" if ($^O =~ /win/i); - } - while () { ## Read STDIN into $message - $message .= $_; - alarm(0) if ($^O !~ /win/i); ## Disable the alarm since at least one line was received - } - printmsg("Message input complete.", 0); - } -} - -## Replace bare LF's with CRLF's (\012 should always have \015 with it) -$message =~ s/(\015)?(\012|$)/\015\012/g; - -## Replace bare CR's with CRLF's (\015 should always have \012 with it) -$message =~ s/(\015)(\012|$)?/\015\012/g; - -## Check message for bare periods and encode them -$message =~ s/(^|$CRLF)(\.{1})($CRLF|$)/$1.$2$3/g; - -## Get the current date for the email header -my ($sec,$min,$hour,$mday,$mon,$year,$day) = gmtime(); -$year += 1900; $mon = return_month($mon); $day = return_day($day); -my $date = sprintf("%s, %s %s %d %.2d:%.2d:%.2d %s",$day, $mday, $mon, $year, $hour, $min, $sec, $conf{'timezone'}); - - - - -################################## -## Connect to the SMTP server ## -################################## -printmsg("DEBUG => Connecting to $conf{'server'}:$conf{'port'}", 1); -$SIG{'ALRM'} = sub { - printmsg("ERROR => Timeout while connecting to $conf{'server'}:$conf{'port'} There was no response after $conf{'alarm'} seconds.", 0); - printmsg("HINT => Try specifying a different mail relay with the -s option.", 1); - quit("", 1); -}; -alarm($conf{'alarm'}) if ($^O !~ /win/i); ## alarm() doesn't work in win32; -$SERVER = IO::Socket::INET->new( PeerAddr => $conf{'server'}, - PeerPort => $conf{'port'}, - LocalAddr => $conf{'bindaddr'}, - Proto => 'tcp', - Autoflush => 1, - timeout => $conf{'alarm'}, -); -alarm(0) if ($^O !~ /win/i); ## alarm() doesn't work in win32; - -## Make sure we got connected -if ( (!$SERVER) or (!$SERVER->opened()) ) { - printmsg("ERROR => Connection attempt to $conf{'server'}:$conf{'port'} failed: $@", 0); - printmsg("HINT => Try specifying a different mail relay with the -s option.", 1); - quit("", 1); -} - -## Save our IP address for later -$conf{'ip'} = $SERVER->sockhost(); -printmsg("DEBUG => My IP address is: $conf{'ip'}", 1); - - - - - - - -######################### -## Do the SMTP Dance ## -######################### - -## Read initial greeting to make sure we're talking to a live SMTP server -if (SMTPchat()) { quit($conf{'error'}, 1); } - -## We're about to use $opt{'fqdn'}, make sure it isn't empty -if (!$opt{'fqdn'}) { - ## Ok, that means we couldn't get a hostname, how about using the IP address for the HELO instead - $opt{'fqdn'} = "[" . $conf{'ip'} . "]"; -} - -## EHLO -if (SMTPchat('EHLO ' . $opt{'fqdn'})) { - printmsg($conf{'error'}, 0); - printmsg("NOTICE => EHLO command failed, attempting HELO instead"); - if (SMTPchat('HELO ' . $opt{'fqdn'})) { quit($conf{'error'}, 1); } - if ( $opt{'username'} and $opt{'password'} ) { - printmsg("WARNING => The mail server does not support SMTP authentication!", 0); - } -} -else { - - ## Determin if the server supports TLS - if ($conf{'SMTPchat_response'} =~ /STARTTLS/) { - $conf{'tls_server'} = 1; - printmsg("DEBUG => The remote SMTP server supports TLS :)", 2); - } - else { - $conf{'tls_server'} = 0; - printmsg("DEBUG => The remote SMTP server does NOT support TLS :(", 2); - } - - ## Start TLS if possible - if ($conf{'tls_server'} == 1 and $conf{'tls_client'} == 1 and $opt{'tls'} =~ /^(yes|auto)$/) { - printmsg("DEBUG => Starting TLS", 2); - if (SMTPchat('STARTTLS')) { quit($conf{'error'}, 1); } - if (! IO::Socket::SSL->start_SSL($SERVER, SSL_version => 'SSLv23:!SSLv3:!SSLv2', , SSL_verify_mode => 0)) { - quit("ERROR => TLS setup failed: " . IO::Socket::SSL::errstr(), 1); - } - printmsg("DEBUG => TLS: Using cipher: ". $SERVER->get_cipher(), 3); - printmsg("DEBUG => TLS session initialized :)", 1); - - ## Restart our SMTP session - if (SMTPchat('EHLO ' . $opt{'fqdn'})) { quit($conf{'error'}, 1); } - } - elsif ($opt{'tls'} eq 'yes' and $conf{'tls_server'} == 0) { - quit("ERROR => TLS not possible! Remote SMTP server, $conf{'server'}, does not support it.", 1); - } - - - ## Do SMTP Auth if required - if ( $opt{'username'} and $opt{'password'} ) { - if ($conf{'SMTPchat_response'} !~ /AUTH\s/) { - printmsg("NOTICE => Authentication not supported by the remote SMTP server!", 0); - } - else { - my $auth_succeeded = 0; - my $mutual_method = 0; - - # ## SASL CRAM-MD5 authentication method - # if ($conf{'SMTPchat_response'} =~ /\bCRAM-MD5\b/i) { - # printmsg("DEBUG => SMTP-AUTH: Using CRAM-MD5 authentication method", 1); - # if (SMTPchat('AUTH CRAM-MD5')) { quit($conf{'error'}, 1); } - # - # ## FIXME!! - # - # printmsg("DEBUG => User authentication was successful", 1); - # } - - ## SASL LOGIN authentication method - if ($auth_succeeded == 0 and $conf{'SMTPchat_response'} =~ /\bLOGIN\b/i) { - $mutual_method = 1; - printmsg("DEBUG => SMTP-AUTH: Using LOGIN authentication method", 1); - if (!SMTPchat('AUTH LOGIN')) { - if (!SMTPchat(base64_encode($opt{'username'}))) { - if (!SMTPchat(base64_encode($opt{'password'}))) { - $auth_succeeded = 1; - printmsg("DEBUG => User authentication was successful (Method: LOGIN)", 1); - } - } - } - if ($auth_succeeded == 0) { - printmsg("DEBUG => SMTP-AUTH: LOGIN authenticaion failed.", 1); - } - } - - ## SASL PLAIN authentication method - if ($auth_succeeded == 0 and $conf{'SMTPchat_response'} =~ /\bPLAIN\b/i) { - $mutual_method = 1; - printmsg("DEBUG => SMTP-AUTH: Using PLAIN authentication method", 1); - if (SMTPchat('AUTH PLAIN ' . base64_encode("$opt{'username'}\0$opt{'username'}\0$opt{'password'}"))) { - printmsg("DEBUG => SMTP-AUTH: PLAIN authenticaion failed.", 1); - } - else { - $auth_succeeded = 1; - printmsg("DEBUG => User authentication was successful (Method: PLAIN)", 1); - } - } - - ## If none of the authentication methods supported by sendEmail were supported by the server, let the user know - if ($mutual_method == 0) { - printmsg("WARNING => SMTP-AUTH: No mutually supported authentication methods available", 0); - } - - ## If we didn't get authenticated, log an error message and exit - if ($auth_succeeded == 0) { - quit("ERROR => ERROR => SMTP-AUTH: Authentication to $conf{'server'}:$conf{'port'} failed.", 1); - } - } - } -} - -## MAIL FROM -if (SMTPchat('MAIL FROM:<' .(returnAddressParts($from))[1]. '>')) { quit($conf{'error'}, 1); } - -## RCPT TO -my $oneRcptAccepted = 0; -foreach my $rcpt (@to, @cc, @bcc) { - my ($name, $address) = returnAddressParts($rcpt); - if (SMTPchat('RCPT TO:<' . $address . '>')) { - printmsg("WARNING => The recipient <$address> was rejected by the mail server, error follows:", 0); - $conf{'error'} =~ s/^ERROR/WARNING/o; - printmsg($conf{'error'}, 0); - } - elsif ($oneRcptAccepted == 0) { - $oneRcptAccepted = 1; - } -} -## If no recipients were accepted we need to exit with an error. -if ($oneRcptAccepted == 0) { - quit("ERROR => Exiting. No recipients were accepted for delivery by the mail server.", 1); -} - -## DATA -if (SMTPchat('DATA')) { quit($conf{'error'}, 1); } - - -############################### -## Build and send the body ## -############################### -printmsg("INFO => Sending message body",1); - -## If the message-format is raw just send the message as-is. -if ($opt{'message-format'} =~ /^raw$/i) { - print $SERVER $message; -} - -## If the message-format isn't raw, then build and send the message, -else { - - ## Message-ID: - if ($opt{'message-header'} !~ /^Message-ID:/iom) { - $header .= 'Message-ID: <' . $conf{'Message-ID'} . '@' . $conf{'hostname'} . '>' . $CRLF; - } - - ## From: "Name" (the pointless test below is just to keep scoping correct) - if ($from and $opt{'message-header'} !~ /^From:/iom) { - my ($name, $address) = returnAddressParts($from); - $header .= 'From: "' . $name . '" <' . $address . '>' . $CRLF; - } - - ## Reply-To: - if ($opt{'reply-to'} and $opt{'message-header'} !~ /^Reply-To:/iom) { - my ($name, $address) = returnAddressParts($opt{'reply-to'}); - $header .= 'Reply-To: "' . $name . '" <' . $address . '>' . $CRLF; - } - - ## To: "Name" - if ($opt{'message-header'} =~ /^To:/iom) { - ## The user put the To: header in via -o message-header - dont do anything - } - elsif (scalar(@to) > 0) { - $header .= "To:"; - for (my $a = 0; $a < scalar(@to); $a++) { - my $msg = ""; - - my ($name, $address) = returnAddressParts($to[$a]); - $msg = " \"$name\" <$address>"; - - ## If we're not on the last address add a comma to the end of the line. - if (($a + 1) != scalar(@to)) { - $msg .= ","; - } - - $header .= $msg . $CRLF; - } - } - ## We always want a To: line so if the only recipients were bcc'd they don't see who it was sent to - else { - $header .= "To: \"Undisclosed Recipients\" <>$CRLF"; - } - - if (scalar(@cc) > 0 and $opt{'message-header'} !~ /^Cc:/iom) { - $header .= "Cc:"; - for (my $a = 0; $a < scalar(@cc); $a++) { - my $msg = ""; - - my ($name, $address) = returnAddressParts($cc[$a]); - $msg = " \"$name\" <$address>"; - - ## If we're not on the last address add a comma to the end of the line. - if (($a + 1) != scalar(@cc)) { - $msg .= ","; - } - - $header .= $msg . $CRLF; - } - } - - if ($opt{'message-header'} !~ /^Subject:/iom) { - $header .= 'Subject: ' . $subject . $CRLF; ## Subject - } - if ($opt{'message-header'} !~ /^Date:/iom) { - $header .= 'Date: ' . $date . $CRLF; ## Date - } - if ($opt{'message-header'} !~ /^X-Mailer:/iom) { - $header .= 'X-Mailer: sendEmail-'.$conf{'version'}.$CRLF; ## X-Mailer - } - ## I wonder if I should put this in by default? - # if ($opt{'message-header'} !~ /^X-Originating-IP:/iom) { - # $header .= 'X-Originating-IP: ['.$conf{'ip'}.']'.$CRLF; ## X-Originating-IP - # } - - ## Encode all messages with MIME. - if ($opt{'message-header'} !~ /^MIME-Version:/iom) { - $header .= "MIME-Version: 1.0$CRLF"; - } - if ($opt{'message-header'} !~ /^Content-Type:/iom) { - my $content_type = 'multipart/mixed'; - if (scalar(@attachments) == 0) { $content_type = 'multipart/related'; } - $header .= "Content-Type: $content_type; boundary=\"$conf{'delimiter'}\"$CRLF"; - } - - ## Send additional message header line(s) if specified - if ($opt{'message-header'}) { - $header .= $opt{'message-header'}; - } - - ## Send the message header to the server - print $SERVER $header . $CRLF; - - ## Start sending the message body to the server - print $SERVER "This is a multi-part message in MIME format. To properly display this message you need a MIME-Version 1.0 compliant Email program.$CRLF"; - print $SERVER "$CRLF"; - - - ## Send message body - print $SERVER "--$conf{'delimiter'}$CRLF"; - ## Send a message content-type header: - ## If the message contains HTML... - if ($opt{'message-content-type'} eq 'html' or ($opt{'message-content-type'} eq 'auto' and $message =~ /^\s*( 0) { - ## Disable the alarm so people on modems can send big attachments - alarm(0) if ($^O !~ /win/i); ## alarm() doesn't work in win32 - - ## Send the attachments - foreach my $filename (@attachments) { - ## This is check 2, we already checked this above, but just in case... - if ( ! -f $filename ) { - printmsg("ERROR => The file [$filename] doesn't exist! Email will be sent, but without that attachment.", 0); - } - elsif ( ! -r $filename ) { - printmsg("ERROR => Couldn't open the file [$filename] for reading: $! Email will be sent, but without that attachment.", 0); - } - else { - printmsg("DEBUG => Sending the attachment [$filename]", 1); - send_attachment($filename); - } - } - } - - - ## End the mime encoded message - print $SERVER "$CRLF--$conf{'delimiter'}--$CRLF"; -} - - -## Tell the server we are done sending the email -print $SERVER "$CRLF.$CRLF"; -if (SMTPchat()) { quit($conf{'error'}, 1); } - - - -#################### -# We are done!!! # -#################### - -## Disconnect from the server (don't SMTPchat(), it breaks when using TLS) -print $SERVER "QUIT$CRLF"; -close $SERVER; - - - - - - -####################################### -## Generate exit message/log entry ## -####################################### - -if ($conf{'debug'} or $conf{'logging'}) { - printmsg("Generating a detailed exit message", 3); - - ## Put the message together - my $output = "Email was sent successfully! From: <" . (returnAddressParts($from))[1] . "> "; - - if (scalar(@to) > 0) { - $output .= "To: "; - for ($a = 0; $a < scalar(@to); $a++) { - $output .= "<" . (returnAddressParts($to[$a]))[1] . "> "; - } - } - if (scalar(@cc) > 0) { - $output .= "Cc: "; - for ($a = 0; $a < scalar(@cc); $a++) { - $output .= "<" . (returnAddressParts($cc[$a]))[1] . "> "; - } - } - if (scalar(@bcc) > 0) { - $output .= "Bcc: "; - for ($a = 0; $a < scalar(@bcc); $a++) { - $output .= "<" . (returnAddressParts($bcc[$a]))[1] . "> "; - } - } - $output .= "Subject: [$subject] " if ($subject); - if (scalar(@attachments_names) > 0) { - $output .= "Attachment(s): "; - foreach(@attachments_names) { - $output .= "[$_] "; - } - } - $output .= "Server: [$conf{'server'}:$conf{'port'}]"; - - -###################### -# Exit the program # -###################### - - ## Print / Log the detailed message - quit($output, 0); -} -else { - ## Or the standard message - quit("Email was sent successfully!", 0); -} - -- 2.39.5