From 56a986c0baef30016f11335741509099da957558 Mon Sep 17 00:00:00 2001 From: geos_one Date: Wed, 6 Aug 2025 18:11:51 +0200 Subject: [PATCH] New upstream version 0.6.27 --- .gitignore | 41 - AUTHORS | 4 +- ChangeLog | 18 + Makefile.in | 159 +- README | 10 - README.md | 67 + THANKS | 2 + aclocal.m4 | 54 + autoconf-macros/.gitignore | 1 + autoconf-macros/CHANGELOG.md | 7 + autoconf-macros/LICENSE | 264 + autoconf-macros/LICENSE.md | 264 + autoconf-macros/README.md | 199 + autoconf-macros/add_group_user | 164 + autoconf-macros/ax_nagios_get_distrib | 160 + autoconf-macros/ax_nagios_get_files | 131 + autoconf-macros/ax_nagios_get_init | 200 + autoconf-macros/ax_nagios_get_os | 101 + autoconf-macros/ax_nagios_get_paths | 783 + ci/.gitignore | 6 + ci/maketar.sh | 117 + ci/mockbuild.sh | 44 + ci/pnp4nagios.spec | 498 + ci/pnp4nagios.spec.in | 498 + configure | 12529 +++++++++------- configure.ac | 1016 +- contrib/.gitignore | 4 + .../logwatch/conf/logfiles/pnp4nagios.conf.in | 25 + .../logwatch/conf/services/pnp4nagios.conf | 21 + .../logwatch/scripts/services/pnp4nagios.in | 71 + contrib/fedora/npcd.service | 17 + contrib/fedora/npcd.sysconfig | 5 + contrib/fedora/pnp4nagios-README.fedora | 89 + contrib/fedora/pnp4nagios-npcd.sysvinit | 103 + contrib/fedora/pnp4nagios.logrotate.conf.in | 7 + contrib/pnp4nagios.spec | 128 - contrib/ssi/status-header.ssi.in | 4 +- helpers/wiki2html.sh | 2 +- include/.gitignore | 2 + include/config.h.in | 32 +- include/stamp-h.in | 1 + lib/.gitignore | 1 + lib/Makefile.in | 564 +- lib/kohana/system/config/cache.php | 14 +- lib/kohana/system/config/cache_memcache.php | 20 +- lib/kohana/system/config/cache_sqlite.php | 8 +- lib/kohana/system/config/cache_xcache.php | 6 +- lib/kohana/system/config/captcha.php | 24 +- lib/kohana/system/config/cookie.php | 10 +- lib/kohana/system/config/credit_cards.php | 106 +- lib/kohana/system/config/database.php | 44 +- lib/kohana/system/config/email.php | 8 +- lib/kohana/system/config/encryption.php | 12 +- lib/kohana/system/config/http.php | 34 +- lib/kohana/system/config/image.php | 8 +- lib/kohana/system/config/inflector.php | 104 +- lib/kohana/system/config/locale.php | 8 +- lib/kohana/system/config/mimes.php | 426 +- lib/kohana/system/config/pagination.php | 18 +- lib/kohana/system/config/profiler.php | 8 +- lib/kohana/system/config/routes.php | 6 +- lib/kohana/system/config/session.php | 10 +- lib/kohana/system/config/sql_types.php | 48 +- lib/kohana/system/config/upload.php | 12 +- lib/kohana/system/config/user_agents.php | 178 +- lib/kohana/system/config/view.php | 22 +- lib/kohana/system/controllers/captcha.php | 29 +- lib/kohana/system/controllers/template.php | 74 +- lib/kohana/system/core/Benchmark.php | 203 +- lib/kohana/system/core/Bootstrap.php | 29 +- lib/kohana/system/core/Event.php | 384 +- lib/kohana/system/core/Kohana.php | 3335 ++-- lib/kohana/system/core/Security.php | 138 + lib/kohana/system/core/utf8.php | 1354 +- lib/kohana/system/core/utf8/from_unicode.php | 97 +- lib/kohana/system/core/utf8/ltrim.php | 24 +- lib/kohana/system/core/utf8/ord.php | 114 +- lib/kohana/system/core/utf8/rtrim.php | 24 +- lib/kohana/system/core/utf8/str_ireplace.php | 94 +- lib/kohana/system/core/utf8/str_pad.php | 69 +- lib/kohana/system/core/utf8/str_split.php | 35 +- lib/kohana/system/core/utf8/strcasecmp.php | 19 +- lib/kohana/system/core/utf8/strcspn.php | 37 +- lib/kohana/system/core/utf8/stristr.php | 31 +- lib/kohana/system/core/utf8/strlen.php | 22 +- lib/kohana/system/core/utf8/strpos.php | 35 +- lib/kohana/system/core/utf8/strrev.php | 17 +- lib/kohana/system/core/utf8/strrpos.php | 35 +- lib/kohana/system/core/utf8/strspn.php | 37 +- lib/kohana/system/core/utf8/strtolower.php | 136 +- lib/kohana/system/core/utf8/strtoupper.php | 136 +- lib/kohana/system/core/utf8/substr.php | 114 +- .../system/core/utf8/substr_replace.php | 25 +- lib/kohana/system/core/utf8/to_unicode.php | 225 +- .../core/utf8/transliterate_to_ascii.php | 122 +- lib/kohana/system/core/utf8/trim.php | 17 +- lib/kohana/system/core/utf8/ucfirst.php | 17 +- lib/kohana/system/core/utf8/ucwords.php | 32 +- lib/kohana/system/helpers/arr.php | 510 +- lib/kohana/system/helpers/cookie.php | 137 +- lib/kohana/system/helpers/date.php | 785 +- lib/kohana/system/helpers/download.php | 158 +- lib/kohana/system/helpers/email.php | 284 +- lib/kohana/system/helpers/expires.php | 177 +- lib/kohana/system/helpers/feed.php | 186 +- lib/kohana/system/helpers/file.php | 291 +- lib/kohana/system/helpers/form.php | 903 +- lib/kohana/system/helpers/format.php | 106 +- lib/kohana/system/helpers/html.php | 748 +- lib/kohana/system/helpers/inflector.php | 309 +- lib/kohana/system/helpers/num.php | 40 +- lib/kohana/system/helpers/remote.php | 95 +- lib/kohana/system/helpers/request.php | 390 +- lib/kohana/system/helpers/security.php | 78 +- lib/kohana/system/helpers/text.php | 682 +- lib/kohana/system/helpers/upload.php | 273 +- lib/kohana/system/helpers/url.php | 407 +- lib/kohana/system/helpers/valid.php | 575 +- lib/kohana/system/i18n/de_DE/cache.php | 18 +- lib/kohana/system/i18n/de_DE/calendar.php | 108 +- lib/kohana/system/i18n/de_DE/captcha.php | 61 +- lib/kohana/system/i18n/de_DE/core.php | 62 +- lib/kohana/system/i18n/de_DE/database.php | 28 +- lib/kohana/system/i18n/de_DE/encrypt.php | 12 +- lib/kohana/system/i18n/de_DE/errors.php | 34 +- lib/kohana/system/i18n/de_DE/event.php | 10 +- lib/kohana/system/i18n/de_DE/image.php | 58 +- lib/kohana/system/i18n/de_DE/orm.php | 8 +- lib/kohana/system/i18n/de_DE/pagination.php | 26 +- lib/kohana/system/i18n/de_DE/profiler.php | 26 +- lib/kohana/system/i18n/de_DE/session.php | 10 +- lib/kohana/system/i18n/de_DE/swift.php | 10 +- lib/kohana/system/i18n/de_DE/upload.php | 10 +- lib/kohana/system/i18n/de_DE/validation.php | 72 +- lib/kohana/system/i18n/en_US/cache.php | 16 +- lib/kohana/system/i18n/en_US/calendar.php | 106 +- lib/kohana/system/i18n/en_US/captcha.php | 56 +- lib/kohana/system/i18n/en_US/core.php | 58 +- lib/kohana/system/i18n/en_US/database.php | 26 +- lib/kohana/system/i18n/en_US/encrypt.php | 10 +- lib/kohana/system/i18n/en_US/errors.php | 26 +- lib/kohana/system/i18n/en_US/event.php | 8 +- lib/kohana/system/i18n/en_US/image.php | 58 +- lib/kohana/system/i18n/en_US/orm.php | 6 +- lib/kohana/system/i18n/en_US/pagination.php | 24 +- lib/kohana/system/i18n/en_US/profiler.php | 24 +- lib/kohana/system/i18n/en_US/session.php | 8 +- lib/kohana/system/i18n/en_US/swift.php | 8 +- lib/kohana/system/i18n/en_US/upload.php | 8 +- lib/kohana/system/i18n/en_US/validation.php | 70 +- lib/kohana/system/i18n/es_ES/cache.php | 16 +- lib/kohana/system/i18n/es_ES/calendar.php | 106 +- lib/kohana/system/i18n/es_ES/captcha.php | 59 +- lib/kohana/system/i18n/es_ES/core.php | 58 +- lib/kohana/system/i18n/es_ES/database.php | 26 +- lib/kohana/system/i18n/es_ES/encrypt.php | 10 +- lib/kohana/system/i18n/es_ES/errors.php | 32 +- lib/kohana/system/i18n/es_ES/event.php | 8 +- lib/kohana/system/i18n/es_ES/image.php | 54 +- lib/kohana/system/i18n/es_ES/orm.php | 4 +- lib/kohana/system/i18n/es_ES/pagination.php | 24 +- lib/kohana/system/i18n/es_ES/profiler.php | 24 +- lib/kohana/system/i18n/es_ES/session.php | 9 +- lib/kohana/system/i18n/es_ES/swift.php | 8 +- lib/kohana/system/i18n/es_ES/upload.php | 8 +- lib/kohana/system/i18n/es_ES/validation.php | 72 +- lib/kohana/system/i18n/fr_FR/cache.php | 10 +- lib/kohana/system/i18n/fr_FR/calendar.php | 108 +- lib/kohana/system/i18n/fr_FR/captcha.php | 60 +- lib/kohana/system/i18n/fr_FR/core.php | 60 +- lib/kohana/system/i18n/fr_FR/database.php | 26 +- lib/kohana/system/i18n/fr_FR/encrypt.php | 14 +- lib/kohana/system/i18n/fr_FR/errors.php | 34 +- lib/kohana/system/i18n/fr_FR/event.php | 10 +- lib/kohana/system/i18n/fr_FR/image.php | 60 +- lib/kohana/system/i18n/fr_FR/orm.php | 8 +- lib/kohana/system/i18n/fr_FR/pagination.php | 26 +- lib/kohana/system/i18n/fr_FR/profiler.php | 28 +- lib/kohana/system/i18n/fr_FR/session.php | 9 +- lib/kohana/system/i18n/fr_FR/swift.php | 8 +- lib/kohana/system/i18n/fr_FR/upload.php | 6 +- lib/kohana/system/i18n/fr_FR/validation.php | 72 +- lib/kohana/system/i18n/it_IT/cache.php | 18 +- lib/kohana/system/i18n/it_IT/calendar.php | 108 +- lib/kohana/system/i18n/it_IT/captcha.php | 58 +- lib/kohana/system/i18n/it_IT/core.php | 62 +- lib/kohana/system/i18n/it_IT/database.php | 28 +- lib/kohana/system/i18n/it_IT/encrypt.php | 12 +- lib/kohana/system/i18n/it_IT/errors.php | 36 +- lib/kohana/system/i18n/it_IT/event.php | 10 +- lib/kohana/system/i18n/it_IT/image.php | 56 +- lib/kohana/system/i18n/it_IT/orm.php | 6 +- lib/kohana/system/i18n/it_IT/pagination.php | 26 +- lib/kohana/system/i18n/it_IT/profiler.php | 26 +- lib/kohana/system/i18n/it_IT/session.php | 10 +- lib/kohana/system/i18n/it_IT/swift.php | 10 +- lib/kohana/system/i18n/it_IT/upload.php | 8 +- lib/kohana/system/i18n/it_IT/validation.php | 72 +- lib/kohana/system/i18n/nl_NL/cache.php | 18 +- lib/kohana/system/i18n/nl_NL/calendar.php | 108 +- lib/kohana/system/i18n/nl_NL/captcha.php | 58 +- lib/kohana/system/i18n/nl_NL/core.php | 62 +- lib/kohana/system/i18n/nl_NL/database.php | 28 +- lib/kohana/system/i18n/nl_NL/encrypt.php | 12 +- lib/kohana/system/i18n/nl_NL/errors.php | 36 +- lib/kohana/system/i18n/nl_NL/event.php | 10 +- lib/kohana/system/i18n/nl_NL/image.php | 47 +- lib/kohana/system/i18n/nl_NL/orm.php | 8 +- lib/kohana/system/i18n/nl_NL/pagination.php | 26 +- lib/kohana/system/i18n/nl_NL/profiler.php | 26 +- lib/kohana/system/i18n/nl_NL/session.php | 12 +- lib/kohana/system/i18n/nl_NL/swift.php | 10 +- lib/kohana/system/i18n/nl_NL/upload.php | 10 +- lib/kohana/system/i18n/nl_NL/validation.php | 70 +- lib/kohana/system/i18n/ru_RU/cache.php | 16 +- lib/kohana/system/i18n/ru_RU/calendar.php | 106 +- lib/kohana/system/i18n/ru_RU/captcha.php | 54 +- lib/kohana/system/i18n/ru_RU/core.php | 60 +- lib/kohana/system/i18n/ru_RU/database.php | 26 +- lib/kohana/system/i18n/ru_RU/encrypt.php | 12 +- lib/kohana/system/i18n/ru_RU/errors.php | 33 +- lib/kohana/system/i18n/ru_RU/event.php | 10 +- lib/kohana/system/i18n/ru_RU/image.php | 46 +- lib/kohana/system/i18n/ru_RU/orm.php | 6 +- lib/kohana/system/i18n/ru_RU/pagination.php | 26 +- lib/kohana/system/i18n/ru_RU/profiler.php | 26 +- lib/kohana/system/i18n/ru_RU/session.php | 8 +- lib/kohana/system/i18n/ru_RU/swift.php | 8 +- lib/kohana/system/i18n/ru_RU/upload.php | 42 +- lib/kohana/system/i18n/ru_RU/validation.php | 68 +- lib/kohana/system/libraries/Cache.php | 335 +- lib/kohana/system/libraries/Calendar.php | 589 +- .../system/libraries/Calendar_Event.php | 505 +- lib/kohana/system/libraries/Captcha.php | 459 +- lib/kohana/system/libraries/Controller.php | 137 +- lib/kohana/system/libraries/Database.php | 2769 ++-- .../system/libraries/Database_Expression.php | 35 +- lib/kohana/system/libraries/Encrypt.php | 253 +- .../system/libraries/Event_Observer.php | 114 +- lib/kohana/system/libraries/Event_Subject.php | 107 +- lib/kohana/system/libraries/Image.php | 851 +- lib/kohana/system/libraries/Input.php | 784 +- lib/kohana/system/libraries/Model.php | 47 +- lib/kohana/system/libraries/ORM.php | 2680 ++-- lib/kohana/system/libraries/ORM_Iterator.php | 375 +- lib/kohana/system/libraries/ORM_Tree.php | 113 +- lib/kohana/system/libraries/ORM_Versioned.php | 215 +- lib/kohana/system/libraries/Pagination.php | 394 +- lib/kohana/system/libraries/Profiler.php | 437 +- .../system/libraries/Profiler_Table.php | 113 +- lib/kohana/system/libraries/Router.php | 463 +- lib/kohana/system/libraries/Session.php | 885 +- lib/kohana/system/libraries/Tagcloud.php | 203 +- lib/kohana/system/libraries/URI.php | 477 +- lib/kohana/system/libraries/Validation.php | 1539 +- lib/kohana/system/libraries/View.php | 520 +- lib/kohana/system/libraries/drivers/Cache.php | 60 +- .../system/libraries/drivers/Cache/Apc.php | 97 +- .../libraries/drivers/Cache/Eaccelerator.php | 99 +- .../system/libraries/drivers/Cache/File.php | 424 +- .../libraries/drivers/Cache/Memcache.php | 288 +- .../system/libraries/drivers/Cache/Sqlite.php | 408 +- .../system/libraries/drivers/Cache/Xcache.php | 183 +- .../system/libraries/drivers/Captcha.php | 387 +- .../libraries/drivers/Captcha/Alpha.php | 151 +- .../libraries/drivers/Captcha/Basic.php | 127 +- .../libraries/drivers/Captcha/Black.php | 138 +- .../system/libraries/drivers/Captcha/Math.php | 97 +- .../libraries/drivers/Captcha/Riddle.php | 72 +- .../system/libraries/drivers/Captcha/Word.php | 58 +- .../system/libraries/drivers/Database.php | 1080 +- .../libraries/drivers/Database/Mssql.php | 722 +- .../libraries/drivers/Database/Mysql.php | 761 +- .../libraries/drivers/Database/Mysqli.php | 550 +- .../libraries/drivers/Database/Pdosqlite.php | 759 +- .../libraries/drivers/Database/Pgsql.php | 807 +- lib/kohana/system/libraries/drivers/Image.php | 242 +- .../system/libraries/drivers/Image/GD.php | 602 +- .../drivers/Image/GraphicsMagick.php | 341 +- .../libraries/drivers/Image/ImageMagick.php | 343 +- .../system/libraries/drivers/Session.php | 116 +- .../libraries/drivers/Session/Cache.php | 146 +- .../libraries/drivers/Session/Cookie.php | 117 +- .../libraries/drivers/Session/Database.php | 244 +- lib/kohana/system/views/kohana/template.php | 44 +- lib/kohana/system/views/kohana_calendar.php | 36 +- .../system/views/kohana_error_disabled.php | 4 +- lib/kohana/system/views/kohana_error_page.php | 10 +- lib/kohana/system/views/kohana_profiler.php | 37 +- .../system/views/kohana_profiler_table.php | 38 +- .../system/views/pagination/classic.php | 43 +- lib/kohana/system/views/pagination/digg.php | 118 +- .../system/views/pagination/extended.php | 36 +- lib/kohana/system/views/pagination/punbb.php | 45 +- man/.gitignore | 2 + man/Makefile.in | 4 +- man/npcd.8.in | 4 +- pnp4nagios.fc.in | 10 + pnp4nagios.te | 28 + sample-config/.gitignore | 18 + sample-config/Makefile.in | 150 +- sample-config/README_config.md.in | 130 + sample-config/SetLogLevels.in | 68 + .../check_all_local_disks.cfg-sample | 0 .../check_commands/check_nrpe.cfg-sample | 0 .../check_commands/check_nwstat.cfg-sample | 0 .../apache.pnp4nagios.conf.in} | 20 +- .../{pnp => config_samples}/config.php.in | 94 +- sample-config/config_samples/config_local.php | 5 + .../lighttpd.pnp4nagios.conf.in | 6 +- .../nagios.cfg.in} | 2 +- .../nginx.pnp4nagios.conf.in | 4 +- .../npcd.cfg.in} | 8 +- sample-config/config_samples/pnp-bulk.cfg.in | 30 + sample-config/config_samples/pnp-npcd.cfg.in | 28 + sample-config/config_samples/pnp-sync.cfg.in | 31 + .../process_perfdata.cfg.in} | 33 +- .../rra.cfg-sample => config_samples/rra.cfg} | 0 sample-config/config_samples/templates.cfg | 224 + sample-config/config_tools/NagiosCfgMod.pl.in | 169 + sample-config/config_tools/TemplateMod.pl.in | 140 + .../config_tools/verify_pnp_config.in | 510 +- sample-config/misccommands.cfg-sample.in | 44 - .../background-A4.pdf} | Bin .../{pnp => pages}/background-letter.pdf | Bin .../{pnp => }/pages/web_traffic.cfg-sample | 0 sample-config/{pnp => }/pnp4nagios_release.in | 4 +- scripts/.gitignore | 13 + scripts/Makefile.in | 72 +- scripts/check_pnp_rrds.pl.in | 15 +- scripts/config4rpm_path.sh | 62 + scripts/newbsd.npcd.in | 32 + scripts/npcd.openrc.in | 61 + scripts/npcd.service.in | 16 + scripts/npcd.upstart.in | 21 + scripts/pnp_gearman_worker.service.in | 16 + scripts/process_perfdata.pl.in | 377 +- scripts/rc.npcd.in | 8 +- scripts/rc.pnp_gearman_worker.in | 4 +- scripts/rrd_convert.pl.in | 10 +- scripts/rrd_modify.pl.in | 4 +- share/.gitignore | 3 + share/Makefile.in | 17 +- share/pnp/application/config/config.php | 129 +- share/pnp/application/config/locale.php | 19 +- share/pnp/application/config/routes.php | 8 +- share/pnp/application/config/session.php | 24 +- share/pnp/application/controllers/ajax.php | 201 +- share/pnp/application/controllers/color.php | 20 +- share/pnp/application/controllers/debug.php | 63 +- share/pnp/application/controllers/docs.php | 110 +- share/pnp/application/controllers/graph.php | 155 +- share/pnp/application/controllers/image.php | 62 +- share/pnp/application/controllers/json.php | 56 +- share/pnp/application/controllers/mobile.php | 53 +- share/pnp/application/controllers/page.php | 113 +- share/pnp/application/controllers/pdf.php | 247 +- share/pnp/application/controllers/popup.php | 27 +- share/pnp/application/controllers/special.php | 32 +- share/pnp/application/controllers/start.php | 16 +- share/pnp/application/controllers/system.php | 340 +- share/pnp/application/controllers/xml.php | 27 +- share/pnp/application/controllers/xport.php | 63 +- share/pnp/application/controllers/zoom.php | 45 +- share/pnp/application/helpers/nagios.php | 109 +- share/pnp/application/helpers/pnp.php | 137 +- share/pnp/application/helpers/rrd.php | 751 +- share/pnp/application/i18n/de_DE/common.php | 111 +- share/pnp/application/i18n/de_DE/error.php | 89 +- share/pnp/application/i18n/en_US/common.php | 111 +- share/pnp/application/i18n/en_US/error.php | 89 +- share/pnp/application/i18n/es_ES/common.php | 109 +- share/pnp/application/i18n/es_ES/error.php | 90 +- share/pnp/application/i18n/fr_FR/common.php | 111 +- share/pnp/application/i18n/fr_FR/error.php | 90 +- share/pnp/application/i18n/ru_RU/common.php | 111 +- share/pnp/application/i18n/ru_RU/error.php | 90 +- share/pnp/application/lib/json.php | 806 - share/pnp/application/lib/jsonwrapper.php | 6 - .../pnp/application/lib/jsonwrapper_inner.php | 23 - share/pnp/application/models/auth.php | 229 +- .../pnp/application/models/auth_multisite.php | 101 +- share/pnp/application/models/config.php | 60 +- share/pnp/application/models/data.php | 1436 +- share/pnp/application/models/rrdtool.php | 292 +- share/pnp/application/models/system.php | 21 +- share/pnp/application/vendor/fpdf/fpdf.php | 23 +- share/pnp/application/vendor/fpdf/fpdi.php | 6 +- .../vendor/fpdf/fpdi_pdf_parser.php | 3 + .../vendor/fpdf/makefont/makefont.php | 5 +- share/pnp/application/views/basket_box.php | 33 +- share/pnp/application/views/color.php | 42 +- share/pnp/application/views/color_box.php | 14 +- share/pnp/application/views/debug.php | 66 +- share/pnp/application/views/docs.php | 28 +- share/pnp/application/views/docs_box.php | 18 +- share/pnp/application/views/graph.php | 104 +- share/pnp/application/views/graph_content.php | 179 +- .../views/graph_content_special.php | 67 +- share/pnp/application/views/graph_tiny.php | 30 +- share/pnp/application/views/header.php | 2 +- share/pnp/application/views/host_box.php | 6 +- share/pnp/application/views/icon_box.php | 59 +- .../application/views/kohana_error_page.php | 44 +- share/pnp/application/views/logo_box.php | 4 +- share/pnp/application/views/mobile.php | 70 +- share/pnp/application/views/mobile_about.php | 6 + share/pnp/application/views/mobile_graph.php | 42 +- .../views/mobile_graph_special.php | 32 +- share/pnp/application/views/mobile_home.php | 16 +- share/pnp/application/views/mobile_host.php | 34 +- .../pnp/application/views/mobile_overview.php | 14 +- share/pnp/application/views/mobile_pages.php | 6 +- share/pnp/application/views/mobile_search.php | 8 +- .../pnp/application/views/mobile_special.php | 4 +- share/pnp/application/views/multisite_box.php | 12 +- share/pnp/application/views/page.php | 84 +- share/pnp/application/views/pages_box.php | 41 +- share/pnp/application/views/popup.php | 10 +- share/pnp/application/views/search_box.php | 12 +- share/pnp/application/views/service_box.php | 45 +- .../views/special_templates_box.php | 34 +- share/pnp/application/views/status_box.php | 30 +- share/pnp/application/views/template.php | 170 +- share/pnp/application/views/timerange_box.php | 28 +- .../application/views/timerange_select.php | 60 +- .../application/views/widget_graph.sample.php | 7 +- .../application/views/widget_menu.sample.php | 7 +- share/pnp/application/views/zoom.php | 155 +- share/pnp/application/views/zoom_header.php | 2 +- share/pnp/documents/de_DE/about.html | 14 +- share/pnp/documents/de_DE/advanced.html | 6 +- share/pnp/documents/de_DE/config.html | 2 +- share/pnp/documents/de_DE/doc_complete.html | 882 +- share/pnp/documents/de_DE/dwnld.html | 531 +- share/pnp/documents/de_DE/mobile.html | 2 +- share/pnp/documents/de_DE/modes.html | 2 +- share/pnp/documents/de_DE/new-features.html | 8 +- share/pnp/documents/de_DE/rrdcached.html | 2 +- share/pnp/documents/de_DE/start.html | 2 +- share/pnp/documents/de_DE/tpl.html | 2 +- share/pnp/documents/de_DE/tpl_custom.html | 6 +- share/pnp/documents/de_DE/tpl_helper.html | 14 +- share/pnp/documents/de_DE/tpl_special.html | 6 +- share/pnp/documents/de_DE/upgrade.html | 2 +- .../documents/de_DE/verify_pnp_config.html | 6 +- share/pnp/documents/de_DE/webfe.html | 2 +- share/pnp/documents/en_US/about.html | 36 +- share/pnp/documents/en_US/advanced.html | 8 +- share/pnp/documents/en_US/config.html | 8 +- share/pnp/documents/en_US/doc_complete.html | 485 +- share/pnp/documents/en_US/dwnld.html | 56 +- share/pnp/documents/en_US/install.html | 4 +- share/pnp/documents/en_US/mobile.html | 2 +- share/pnp/documents/en_US/modes.html | 2 +- share/pnp/documents/en_US/new-features.html | 10 +- share/pnp/documents/en_US/npcd.html | 4 +- share/pnp/documents/en_US/rrdcached.html | 12 +- share/pnp/documents/en_US/start.html | 4 +- share/pnp/documents/en_US/tpl.html | 6 +- share/pnp/documents/en_US/tpl_custom.html | 6 +- share/pnp/documents/en_US/tpl_helper.html | 24 +- share/pnp/documents/en_US/tpl_special.html | 6 +- share/pnp/documents/en_US/upgrade.html | 2 +- .../documents/en_US/verify_pnp_config.html | 10 +- share/pnp/documents/en_US/webfe.html | 31 +- share/pnp/documents/templates/alerter.html | 48 + .../templates/check_apachestatus.html | 49 + share/pnp/documents/templates/check_cpu.html | 60 + share/pnp/documents/templates/check_http.html | 62 + .../templates/check_mk-cpu.loads.html | 72 + .../pnp/documents/templates/check_mk-df.html | 83 + .../check_oracle_health_tablespace-usage.html | 49 + .../documents/templates/check_wlsagent.html | 90 + share/pnp/documents/templates/gradient1.html | 74 + share/pnp/documents/templates/integer.html | 31 + share/pnp/documents/templates/start.html | 25 + share/pnp/documents/templates/ticker.html | 50 + share/pnp/index.php.in | 72 +- share/pnp/install.ignore.not | 11 + share/pnp/install.php.in | 186 +- share/pnp/media/images/pnp.png | Bin 265 -> 269 bytes share/pnp/templates.dist/arrayfix.php | 11 + share/pnp/templates.dist/check-host-alive.php | 53 +- .../pnp/templates.dist/check_apachestatus.php | 157 +- .../check_apachestatus_auto.php | 96 +- .../check_dell_bladechassis.php | 165 +- share/pnp/templates.dist/check_disk.php | 111 +- share/pnp/templates.dist/check_dns.php | 9 +- share/pnp/templates.dist/check_esx3.php | 100 +- share/pnp/templates.dist/check_fping.php | 24 +- share/pnp/templates.dist/check_gearman.php | 52 +- .../templates.dist/check_hp_bladechassis.php | 29 +- share/pnp/templates.dist/check_hpasm.php | 37 +- share/pnp/templates.dist/check_http.php | 17 +- share/pnp/templates.dist/check_icmp.php | 53 +- .../check_iftraffic_counter.php | 6 +- .../templates.dist/check_iftraffic_pct.php | 4 +- .../check_jmx4perl_connector_errors.php | 14 +- .../check_jmx4perl_connector_nr_requests.php | 16 +- .../check_jmx4perl_connector_proc_time.php | 14 +- .../check_jmx4perl_connector_received.php | 18 +- .../check_jmx4perl_connector_sent.php | 18 +- .../check_jmx4perl_connector_threads.php | 18 +- .../check_jmx4perl_memory_gc_count.php | 20 +- .../check_jmx4perl_memory_gc_time.php | 14 +- .../check_jmx4perl_memory_heap.php | 16 +- .../check_jmx4perl_thread_count.php | 20 +- .../check_jmx4perl_thread_increase.php | 16 +- share/pnp/templates.dist/check_load.php | 5 +- share/pnp/templates.dist/check_local_disk.php | 66 +- share/pnp/templates.dist/check_local_load.php | 28 +- .../pnp/templates.dist/check_messpc_temp.php | 9 +- .../pnp/templates.dist/check_mssql_health.php | 738 +- share/pnp/templates.dist/check_multi.php | 22 +- .../templates.dist/check_multi_nagiostats.php | 34 +- .../pnp/templates.dist/check_mysql_health.php | 384 +- share/pnp/templates.dist/check_nt_cpu.php | 12 +- share/pnp/templates.dist/check_nt_disk.php | 15 +- share/pnp/templates.dist/check_nt_mem.php | 17 +- share/pnp/templates.dist/check_ntp_time.php | 13 +- .../pnp/templates.dist/check_nwstat_CONNS.php | 7 +- .../pnp/templates.dist/check_nwstat_LOAD.php | 7 +- .../pnp/templates.dist/check_nwstat_LOAD1.php | 36 +- .../templates.dist/check_nwstat_LOAD15.php | 36 +- .../pnp/templates.dist/check_nwstat_LOAD5.php | 36 +- .../templates.dist/check_nwstat_ofiles.php | 9 +- share/pnp/templates.dist/check_openmanage.php | 754 +- .../check_oracle_connection-time.php | 10 +- .../templates.dist/check_oracle_health.php | 40 +- .../check_oracle_health_connection-time.php | 10 +- ...oracle_health_pga-in-memory-sort-ratio.php | 9 +- .../check_oracle_health_redo-io-traffic.php | 9 +- .../check_oracle_health_switch-interval.php | 10 +- .../check_oracle_health_tablespace-usage.php | 24 +- share/pnp/templates.dist/check_ping.php | 36 +- share/pnp/templates.dist/check_ping_tick.php | 36 +- share/pnp/templates.dist/check_pnp_rrds.php | 3 +- share/pnp/templates.dist/check_smtp.php | 16 +- .../templates.dist/check_snmp_int-bits.php | 7 +- .../templates.dist/check_snmp_int-full.php | 41 + share/pnp/templates.dist/check_snmp_int.php | 7 +- share/pnp/templates.dist/check_swap.php | 21 +- share/pnp/templates.dist/check_tcp.php | 16 +- share/pnp/templates.dist/check_users.php | 10 +- share/pnp/templates.dist/default.php | 157 +- share/pnp/templates.dist/icinga.php | 130 +- share/pnp/templates.dist/integer.php | 40 +- share/pnp/templates.dist/nagiostats.php | 64 +- share/pnp/templates.dist/pnp-runtime.php | 30 +- share/pnp/templates.dist/response.php | 10 +- .../advanced_loop.php-sample | 26 +- share/pnp/templates.special/loop.php-sample | 23 +- share/pnp/templates.special/static.php-sample | 21 +- src/.gitignore | 7 + src/Makefile.in | 13 +- src/{config.c => config.c.in} | 14 +- src/npcd.c | 8 +- src/{npcdmod.c => npcdmod.c.in} | 12 +- src/pnpsender.c | 2 +- src/utils.c | 2 +- subst.in | 36 +- summary.in | 23 +- 563 files changed, 45811 insertions(+), 35282 deletions(-) delete mode 100644 .gitignore mode change 100644 => 100755 Makefile.in delete mode 100644 README create mode 100644 README.md create mode 100755 aclocal.m4 create mode 100644 autoconf-macros/.gitignore create mode 100644 autoconf-macros/CHANGELOG.md create mode 100644 autoconf-macros/LICENSE create mode 100644 autoconf-macros/LICENSE.md create mode 100644 autoconf-macros/README.md create mode 100755 autoconf-macros/add_group_user create mode 100644 autoconf-macros/ax_nagios_get_distrib create mode 100644 autoconf-macros/ax_nagios_get_files create mode 100644 autoconf-macros/ax_nagios_get_init create mode 100644 autoconf-macros/ax_nagios_get_os create mode 100644 autoconf-macros/ax_nagios_get_paths create mode 100644 ci/.gitignore create mode 100755 ci/maketar.sh create mode 100755 ci/mockbuild.sh create mode 100755 ci/pnp4nagios.spec create mode 100755 ci/pnp4nagios.spec.in mode change 100644 => 100755 configure.ac create mode 100644 contrib/.gitignore create mode 100644 contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf.in create mode 100644 contrib/fedora/logwatch/conf/services/pnp4nagios.conf create mode 100644 contrib/fedora/logwatch/scripts/services/pnp4nagios.in create mode 100644 contrib/fedora/npcd.service create mode 100644 contrib/fedora/npcd.sysconfig create mode 100644 contrib/fedora/pnp4nagios-README.fedora create mode 100644 contrib/fedora/pnp4nagios-npcd.sysvinit create mode 100644 contrib/fedora/pnp4nagios.logrotate.conf.in delete mode 100644 contrib/pnp4nagios.spec create mode 100644 include/.gitignore create mode 100644 include/stamp-h.in create mode 100644 lib/.gitignore create mode 100644 lib/kohana/system/core/Security.php create mode 100644 man/.gitignore create mode 100644 pnp4nagios.fc.in create mode 100644 pnp4nagios.te create mode 100644 sample-config/.gitignore create mode 100644 sample-config/README_config.md.in create mode 100755 sample-config/SetLogLevels.in rename sample-config/{pnp => }/check_commands/check_all_local_disks.cfg-sample (100%) rename sample-config/{pnp => }/check_commands/check_nrpe.cfg-sample (100%) rename sample-config/{pnp => }/check_commands/check_nwstat.cfg-sample (100%) rename sample-config/{httpd.conf.in => config_samples/apache.pnp4nagios.conf.in} (64%) rename sample-config/{pnp => config_samples}/config.php.in (77%) create mode 100644 sample-config/config_samples/config_local.php rename sample-config/{ => config_samples}/lighttpd.pnp4nagios.conf.in (69%) rename sample-config/{nagios.cfg-sample.in => config_samples/nagios.cfg.in} (95%) rename sample-config/{ => config_samples}/nginx.pnp4nagios.conf.in (92%) rename sample-config/{pnp/npcd.cfg-sample.in => config_samples/npcd.cfg.in} (97%) create mode 100644 sample-config/config_samples/pnp-bulk.cfg.in create mode 100644 sample-config/config_samples/pnp-npcd.cfg.in create mode 100644 sample-config/config_samples/pnp-sync.cfg.in rename sample-config/{pnp/process_perfdata.cfg-sample.in => config_samples/process_perfdata.cfg.in} (77%) rename sample-config/{pnp/rra.cfg-sample => config_samples/rra.cfg} (100%) create mode 100644 sample-config/config_samples/templates.cfg create mode 100755 sample-config/config_tools/NagiosCfgMod.pl.in create mode 100755 sample-config/config_tools/TemplateMod.pl.in rename scripts/verify_pnp_config_v2.pl => sample-config/config_tools/verify_pnp_config.in (66%) delete mode 100644 sample-config/misccommands.cfg-sample.in rename sample-config/{pnp/background.pdf => pages/background-A4.pdf} (100%) rename sample-config/{pnp => pages}/background-letter.pdf (100%) rename sample-config/{pnp => }/pages/web_traffic.cfg-sample (100%) rename sample-config/{pnp => }/pnp4nagios_release.in (58%) create mode 100644 scripts/.gitignore create mode 100755 scripts/config4rpm_path.sh create mode 100644 scripts/newbsd.npcd.in create mode 100644 scripts/npcd.openrc.in create mode 100644 scripts/npcd.service.in create mode 100644 scripts/npcd.upstart.in create mode 100644 scripts/pnp_gearman_worker.service.in create mode 100644 share/.gitignore delete mode 100644 share/pnp/application/lib/json.php delete mode 100644 share/pnp/application/lib/jsonwrapper.php delete mode 100644 share/pnp/application/lib/jsonwrapper_inner.php mode change 120000 => 100644 share/pnp/documents/de_DE/dwnld.html create mode 100644 share/pnp/documents/templates/alerter.html create mode 100644 share/pnp/documents/templates/check_apachestatus.html create mode 100644 share/pnp/documents/templates/check_cpu.html create mode 100644 share/pnp/documents/templates/check_http.html create mode 100644 share/pnp/documents/templates/check_mk-cpu.loads.html create mode 100644 share/pnp/documents/templates/check_mk-df.html create mode 100644 share/pnp/documents/templates/check_oracle_health_tablespace-usage.html create mode 100644 share/pnp/documents/templates/check_wlsagent.html create mode 100644 share/pnp/documents/templates/gradient1.html create mode 100644 share/pnp/documents/templates/integer.html create mode 100644 share/pnp/documents/templates/start.html create mode 100644 share/pnp/documents/templates/ticker.html create mode 100644 share/pnp/install.ignore.not create mode 100644 share/pnp/templates.dist/arrayfix.php mode change 120000 => 100644 share/pnp/templates.dist/check-host-alive.php mode change 120000 => 100644 share/pnp/templates.dist/check_icmp.php mode change 120000 => 100644 share/pnp/templates.dist/check_local_disk.php mode change 120000 => 100644 share/pnp/templates.dist/check_local_load.php mode change 120000 => 100644 share/pnp/templates.dist/check_nwstat_LOAD1.php mode change 120000 => 100644 share/pnp/templates.dist/check_nwstat_LOAD15.php mode change 120000 => 100644 share/pnp/templates.dist/check_nwstat_LOAD5.php mode change 120000 => 100644 share/pnp/templates.dist/check_smtp.php create mode 100644 share/pnp/templates.dist/check_snmp_int-full.php mode change 120000 => 100644 share/pnp/templates.dist/check_tcp.php create mode 100644 src/.gitignore rename src/{config.c => config.c.in} (97%) rename src/{npcdmod.c => npcdmod.c.in} (97%) diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 187f456..0000000 --- a/.gitignore +++ /dev/null @@ -1,41 +0,0 @@ -autom4te.cache -subst -summary -*Makefile -config.log -config.status -scripts/rc.npcd -scripts/rc.pnp_gearman_worker -scripts/check_pnp_rrds.pl -scripts/process_perfdata.pl -scripts/rrd_modify.pl -src/*.o -src/npcd -include/config.h -*~ - -sample-config/pnp/config.php -sample-config/pnp/pnp4nagios_release -sample-config/pnp/process_perfdata.cfg-sample -sample-config/pnp/npcd.cfg-sample -sample-config/misccommands.cfg-sample -sample-config/nagios.cfg-sample - -share/pnp/application/config/config.php -share/pnp/index.php -share/pnp/install.php -sample-config/httpd.conf -share/pnp/application/logs/* -contrib/ssi/status-header.ssi -helpers/w2h.pl -scripts/verify_pnp_config.pl -sample-config/lighttpd.pnp4nagios.conf -sample-config/nginx.pnp4nagios.conf -share/pnp/media/js/basket.js -scripts/rrd_convert.pl -scripts/rrd_converter.pl - -man/npcd.8 - -*.swp -*.swo diff --git a/AUTHORS b/AUTHORS index 56e9fde..fb44f71 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1,3 +1,3 @@ Authors: -Jörg Linge pitchfork@pnp4nagios.org -Hendrik Bäcker andurin@process-zero.de +Jörg Linge +Hendrik Bäcker diff --git a/ChangeLog b/ChangeLog index 6fb2687..36a3d97 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,4 +1,22 @@ +**pnp-0.6.27-4 09/12/2023** + * update URLs and related text + * clean up autoconf stuff + * add scripts/config4rpm_path.sh to test existing rpm installation (tjyang) + +**pnp-0.6.27 08/18/2023** + * many php 8.2 fixes to remove 'deprecated' errors: + pre-defining class variables (instead of dynamic), + explicitly re-creating arrays as needed + converting utf8_encode to mbstring + +**pnp-0.6.26-2 09/18/2022 + * various php8 fixes + * rrdtools needs env XDG_CACHE_HOME for fontconfig + * fix so that 'bucket' display works + * fix so that pdf generation works + **pnp-0.6.?? ??/??/2017** + * Bugfix: Fix for CVE-2017-16834 **pnp-0.6.26 08/21/2017** * Bugfix: Use complete option arguments for compatibility with rrdtool 1.6.0 (sbraz) diff --git a/Makefile.in b/Makefile.in old mode 100644 new mode 100755 index 5ac4d8e..775efb2 --- a/Makefile.in +++ b/Makefile.in @@ -1,11 +1,13 @@ ############################### # Makefile for PNP # -# Last Modified: 12-10-2006 +# Last Modified: 11-13-2023 ############################### +VERSION=@PACKAGE_VERSION@ # Source code directories +srcdir=@srcdir@ SRC_BASE=@srcdir@/src SRC_SHARE=@srcdir@/share SRC_LIB=@srcdir@/lib @@ -22,48 +24,81 @@ LDFLAGS=@LDFLAGS@ @LIBS@ prefix=@prefix@ exec_prefix=@exec_prefix@ LOGDIR=@localstatedir@ -CFGDIR=@sysconfdir@ BINDIR=@bindir@ LIBEXECDIR=@libexecdir@ -LIBDIR=@libdir@ KOHANA=@KOHANA@ CGIDIR=@sbindir@ INSTALL=@INSTALL@ INSTALL_OPTS=@INSTALL_OPTS@ +HTTP_INSTALL_OPTS=@HTTP_INSTALL_OPTS@ DATAROOTDIR=@datarootdir@ +NAGIOS_VERSION=@NAGIOS_VER@ +CACHE_DIR=@CACHE_DIR@ + +SELINUX=@SELINUX@ +SELINUX_DEVELDIR=@SELINUX_DEVELDIR@ CP=@CP@ PERL=@PERL@ +.PHONY: clean rpm dist distclean devclean + none: @echo "Please supply a command line argument (i.e. 'make all'). Other targets are:" - @echo " clean" - @echo " install install-init install-config install-processperfdata install-html fullinstall" - @echo " install-plugins" + @echo " clean distclean dist" + @echo " install install-init install-selinux fullinstall" all: - cd $(SRC_BASE) && $(MAKE) - cd $(SRC_SHARE) && $(MAKE) - cd $(SRC_SCRIPTS) && $(MAKE) + cd $(SRC_BASE) && $(MAKE) $@ + cd $(SRC_SHARE) && $(MAKE) $@ + cd $(SRC_SCRIPTS) && $(MAKE) $@ + cd $(SRC_CONFIG) && $(MAKE) $@ chmod a+r $(SRC_CONTRIB)/ssi/status-header.ssi @echo "" @echo "*** Compile finished ***" @echo "" @echo " make install" - @echo " - This installs the main program and HTML files" + @echo " - This installs directories, binaries and php files" + @echo "" + @echo " make install-selinux" + @echo " - This installs the selinux setup (if you are using selinux)" + @echo "" @echo "" @echo " make fullinstall" - @echo " - This installs the main program, runlevel scripts, config and HTML files" + @echo " - install everything " @echo "" @echo "Enjoy." @echo "" +# this section from autoconf doc suggestions +# reautoconf if config changed +configure: configure.ac + autoconf + +# autoheader might not change config.h.in, so touch a stamp file. +include/config.h.in: include/stamp-h.in ; +include/stamp-h.in: configure.ac + autoheader + date -Is > 'include/stamp-h.in' + +include/config.h: include/stamp-h ; +include/stamp-h: include/config.h.in config.status + ./config.status + +Makefile: Makefile.in config.status + ./config.status + +config.status: configure + ./config.status --recheck + + scripts: - cd $(SRC_SCRIPTS) && $(MAKE) + cd $(SRC_SCRIPTS) && $(MAKE) $@ share: - cd $(SRC_SHARE) && $(MAKE) + cd $(SRC_SHARE) && $(MAKE) $@ + clean: cd $(SRC_BASE) && $(MAKE) $@ @@ -75,6 +110,8 @@ clean: -rm -f *.cfg core -rm -f *~ *.*~ */*~ */*.*~ -rm -f config.log config.status config.cache +@SE@ rm -f pnp4nagios.fc +@SE@ rm -f pnp4nagios.if pnp4nagios.pp* tmp distclean: cd $(SRC_BASE) && $(MAKE) $@ @@ -89,56 +126,16 @@ distclean: rm -f Makefile include/stamp-h1 include/config.h config.status config.log rm -f subst summary rm -f $(SRC_CONTRIB)/ssi/status-header.ssi + rm -f $(SRC_CONTRIB)/fedora/pnp4nagios.logrotate.conf + rm -f $(SRC_CONTRIB)/fedora/logwatch/conf/logfiles/pnp4nagios.conf +@SE@ rm -f pnp4nagios.fc pnp4nagios.if pnp4nagios.pp* tmp devclean: distclean -install-html: - cd $(SRC_SHARE) && $(MAKE) install - -install-base: - cd $(SRC_BASE) && $(MAKE) install - -install-man: - cd $(SRC_MAN) && $(MAKE) install - -install-processperfdata: - cd $(SRC_SCRIPTS) && $(MAKE) install install-init: cd $(SRC_SCRIPTS) && $(MAKE) $@ -install-config: - cd $(SRC_CONFIG) && $(MAKE) $@ - - @echo "" - @echo "*** PNP4Nagios sample config files installed ***" - @echo "" - @echo "Please run 'make install-init' if you want to use" - @echo "BULK Mode with NPCD" - @echo "" - @echo "" - @echo "" - -install-webconf: - cd $(SRC_CONFIG) && $(MAKE) $@ - - - @echo "" - @echo "*** Apache config file installed ***" - @echo "" - @echo "Restart your apache webserver to activete your changes." - @echo "" - @echo "Please run 'make install-config' to install sample" - @echo "configuration files" - @echo "" - @echo "Please run 'make install-init' if you want to use" - @echo "BULK Mode with NPCD" - @echo "" - @echo "" - @echo "" - -install-plugins: - cd $(SRC_SCRIPTS) && $(MAKE) $@ install: cd $(SRC_BASE) && $(MAKE) $@ @@ -147,37 +144,63 @@ install: if [ x$(KOHANA) = xyes ]; then \ cd $(SRC_LIB) && $(MAKE) $@; \ fi - cd $(SRC_SCRIPTS) && $(MAKE) $@ cd $(SRC_CONFIG) && $(MAKE) $@ - + $(INSTALL) $(HTTP_INSTALL_OPTS) -d $(DESTDIR)$(CACHE_DIR) @echo "" @echo "*** Main program, Scripts and HTML files installed ***" @echo "" - @echo "Please run 'make install-webconf' to install the" - @echo "web configuration file" - @echo "" - @echo "Please run 'make install-config' to install sample" - @echo "configuration files" - @echo "" - @echo "Please run 'make install-init' if you want to use" - @echo "BULK Mode with NPCD" - @echo "" @echo "" @echo "" +# Nagios might have some pnp4nagios selinux entries +# so mask out duplicates. + +install-selinux: +@SE@ -rm nagios.pp +@SE@ -semodule -E nagios 2>/dev/null >/dev/null +@SE@ if [ -e nagios.pp ] ; then \ +@SE@ semodule_unpackage nagios.pp nagios.mod nagios.fc ; \ +@SE@ for pnpdir in /etc/pnp4nagios /var/log/pnp4nagios /var/lib/pnp4nagios /usr/lib/pnp4nagios ; \ +@SE@ do \ +@SE@ if grep -q "^$pnpdir" nagios.fc ; \ +@SE@ then \ +@SE@ sed -i "\\|^$pnpdir|s/^/#/" pnp4nagios.fc ; \ +@SE@ fi \ +@SE@ done \ +@SE@ fi +@SE@ $(MAKE) -f $(SELINUX_DEVELDIR)/Makefile load +@SE@ fixfiles restore @datadir@ @pkgsysconfdir@ +@SE@ fixfiles restore @PERFDATA_DIR@ @logdir@ +@SE@ fixfiles restore @PERFDATA_SPOOL_DIR@ @piddir@ + + install-unstripped: cd $(SRC_BASE) && $(MAKE) $@ cd $(SRC_SHARE) && $(MAKE) $@ cd $(SRC_SCRIPTS) && $(MAKE) $@ $(MAKE) install-basic -fullinstall: install install-webconf install-config install-init +fullinstall: + $(MAKE) install + $(MAKE) install-selinux $(PERL) summary fullinstall @echo "" @echo "*** Main program, Scripts and HTML files installed ***" + @echo "Config files in: @pkgsysconfdir@ might need updating." + @echo "" @echo "" @echo "Enjoy." @echo "" + +dist: + ci/maketar.sh $(VERSION) + mv ci/pnp4nagios*.tgz . + mv ci/pnp4nagios*.zip . + + + + + diff --git a/README b/README deleted file mode 100644 index 72010fd..0000000 --- a/README +++ /dev/null @@ -1,10 +0,0 @@ -######################### -# # -# README # -# # -######################### - -See our online documentation at: - -http://pnp4nagios.sourceforge.net or: -http://docs.pnp4nagios.org/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..aa1a318 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# PNP4Nagios + +The new/current place for the pnp4nagios organization is + https://github.com/pnp4nagios +With this *particular* version residing in + https://github.com/pnp4nagios/pnp4nagios + + +This is a fork of [@lingej's original pnp4nagios package](https://github.com/lingej/pnp4nagios). + +As a long-time user of `pnpnagios`, I am trying to give the project a +good home as we work to further develop and enhance this project. Please +contact me if you would like to help. + +The original source was retired on commit 5e09f538373ac4310a13355746bb3d3a10eb7bef +(Version pnp-0.6.?? ??/??/2017 on 2022/Jan/16). Many thanks to Joerg Linge and his +awesome contributors for what we have, now! + + +## Getting Started + +For now, I'm advocating installing from source (**my** source), as we move +forward into further developing this project. + +Instructions can be found in +[this gist](https://gist.github.com/russellvt/051fa43592778a41e53cb423b791bab6). + + +## Documentation + +The old site for documentation at https://docs.pnp4nagios.org is no longer +up; the replacement is https://github.com/pnp4nagios/docs +It's possible that there are still some references to the old site scattered +here and there. + + +## About Me + +I am a long time Nagios/Icinga/Monitoring/Devops Professional. I've been +"the toolsguy" long from "devops" was even a "new" term. + + + +## build RPM from git + +The spec file is in the "ci" subdirectory. Install git-build-rpm (it's on +github, surprise!) and, as an example: + +HERE=(main directory of this git package; where this README.md file is located) +cd $HERE +autoconf # builds 'configure' +./configure # builds 'ci/pnp4nagios.spec' +git build-rpm --rpm-dir /home/local/lane/rpmbuild --spec ci/pnp4nagios.spec --dist .fc35 + +The --rpm-dir option is to keep the .srpm file from the build (it will be +in your usual SRPMS subdirectory in your rpmbuild tree), the +--dist option is to avoid the longwinded "-%{version}-%{release}%{timestamp}.%{dist}..." package name. The rpms will get copied from the rpmbuild tree to +$HERE. + +You can also just get the source code, do a +autoconf +./configure +then +make all +etc....but some of us (me) prefers to have a software package, to organize +software installation/update/removal. + diff --git a/THANKS b/THANKS index 94b9a83..44ad6c7 100644 --- a/THANKS +++ b/THANKS @@ -2,6 +2,8 @@ # PNP Thanks # ########################################### +Russell M. Van Tassell - Taking over from 0.6.26+CVE-2017-16384 + Olivier PLATHEY - For providing FPDF Sven Nierlein - For providing mod_gearman Michal Wojciechowski - For providing imgAreaSelect diff --git a/aclocal.m4 b/aclocal.m4 new file mode 100755 index 0000000..9ffb0c4 --- /dev/null +++ b/aclocal.m4 @@ -0,0 +1,54 @@ +# AM_CONDITIONAL -*- Autoconf -*- + +# Copyright (C) 1997-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# AM_CONDITIONAL(NAME, SHELL-CONDITION) +# ------------------------------------- +# Define a conditional. +AC_DEFUN([AM_CONDITIONAL], +[AC_PREREQ([2.52])dnl + m4_if([$1], [TRUE], [AC_FATAL([$0: invalid condition: $1])], + [$1], [FALSE], [AC_FATAL([$0: invalid condition: $1])])dnl +AC_SUBST([$1_TRUE])dnl +AC_SUBST([$1_FALSE])dnl +_AM_SUBST_NOTMAKE([$1_TRUE])dnl +_AM_SUBST_NOTMAKE([$1_FALSE])dnl +m4_define([_AM_COND_VALUE_$1], [$2])dnl +if $2; then + $1_TRUE= + $1_FALSE='#' +else + $1_TRUE='#' + $1_FALSE= +fi +AC_CONFIG_COMMANDS_PRE( +[if test -z "${$1_TRUE}" && test -z "${$1_FALSE}"; then + AC_MSG_ERROR([[conditional "$1" was never defined. +Usually this means the macro was only invoked conditionally.]]) +fi])]) +# Copyright (C) 2006-2021 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_SUBST_NOTMAKE(VARIABLE) +# --------------------------- +# Prevent Automake from outputting VARIABLE = @VARIABLE@ in Makefile.in. +# This macro is traced by Automake. +AC_DEFUN([_AM_SUBST_NOTMAKE]) + +# AM_SUBST_NOTMAKE(VARIABLE) +# -------------------------- +# Public sister of _AM_SUBST_NOTMAKE. +AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) + +m4_include([autoconf-macros/ax_nagios_get_os]) +m4_include([autoconf-macros/ax_nagios_get_distrib]) +m4_include([autoconf-macros/ax_nagios_get_init]) +m4_include([autoconf-macros/ax_nagios_get_paths]) +m4_include([autoconf-macros/ax_nagios_get_files]) diff --git a/autoconf-macros/.gitignore b/autoconf-macros/.gitignore new file mode 100644 index 0000000..80f408e --- /dev/null +++ b/autoconf-macros/.gitignore @@ -0,0 +1 @@ +nbproject/ diff --git a/autoconf-macros/CHANGELOG.md b/autoconf-macros/CHANGELOG.md new file mode 100644 index 0000000..f71288f --- /dev/null +++ b/autoconf-macros/CHANGELOG.md @@ -0,0 +1,7 @@ +1.0.1 +----- + * Fix bug determining inetd,xinetd if neither are running (Bryan Heden) + +1.0.0 +----- + * Initial Release (John Frickson) \ No newline at end of file diff --git a/autoconf-macros/LICENSE b/autoconf-macros/LICENSE new file mode 100644 index 0000000..a983462 --- /dev/null +++ b/autoconf-macros/LICENSE @@ -0,0 +1,264 @@ +The GNU General Public License, Version 2, June 1991 (GPLv2) +============================================================ + +> Copyright (C) 1989, 1991 Free Software Foundation, Inc. +> 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + + +Preamble +-------- + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public License is intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. This General Public License applies to most +of the Free Software Foundation's software and to any other program whose +authors commit to using it. (Some other Free Software Foundation software is +covered by the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom to +distribute copies of free software (and charge for this service if you wish), +that you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs; and that you know you can +do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny +you these rights or to ask you to surrender the rights. These restrictions +translate to certain responsibilities for you if you distribute copies of the +software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a +fee, you must give the recipients all the rights that you have. You must make +sure that they, too, receive or can get the source code. And you must show them +these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer +you this license which gives you legal permission to copy, distribute and/or +modify the software. + +Also, for each author's protection and ours, we want to make certain that +everyone understands that there is no warranty for this free software. If the +software is modified by someone else and passed on, we want its recipients to +know that what they have is not the original, so that any problems introduced by +others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish +to avoid the danger that redistributors of a free program will individually +obtain patent licenses, in effect making the program proprietary. To prevent +this, we have made it clear that any patent must be licensed for everyone's free +use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification +follow. + + +Terms And Conditions For Copying, Distribution And Modification +--------------------------------------------------------------- + +**0.** This License applies to any program or other work which contains a notice +placed by the copyright holder saying it may be distributed under the terms of +this General Public License. The "Program", below, refers to any such program or +work, and a "work based on the Program" means either the Program or any +derivative work under copyright law: that is to say, a work containing the +Program or a portion of it, either verbatim or with modifications and/or +translated into another language. (Hereinafter, translation is included without +limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by +this License; they are outside its scope. The act of running the Program is not +restricted, and the output from the Program is covered only if its contents +constitute a work based on the Program (independent of having been made by +running the Program). Whether that is true depends on what the Program does. + +**1.** You may copy and distribute verbatim copies of the Program's source code +as you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and +disclaimer of warranty; keep intact all the notices that refer to this License +and to the absence of any warranty; and give any other recipients of the Program +a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at +your option offer warranty protection in exchange for a fee. + +**2.** You may modify your copy or copies of the Program or any portion of it, +thus forming a work based on the Program, and copy and distribute such +modifications or work under the terms of Section 1 above, provided that you also +meet all of these conditions: + +* **a)** You must cause the modified files to carry prominent notices stating + that you changed the files and the date of any change. + +* **b)** You must cause any work that you distribute or publish, that in whole + or in part contains or is derived from the Program or any part thereof, to + be licensed as a whole at no charge to all third parties under the terms of + this License. + +* **c)** If the modified program normally reads commands interactively when + run, you must cause it, when started running for such interactive use in the + most ordinary way, to print or display an announcement including an + appropriate copyright notice and a notice that there is no warranty (or + else, saying that you provide a warranty) and that users may redistribute + the program under these conditions, and telling the user how to view a copy + of this License. (Exception: if the Program itself is interactive but does + not normally print such an announcement, your work based on the Program is + not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Program, and can be reasonably +considered independent and separate works in themselves, then this License, and +its terms, do not apply to those sections when you distribute them as separate +works. But when you distribute the same sections as part of a whole which is a +work based on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the entire whole, +and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise the +right to control the distribution of derivative or collective works based on the +Program. + +In addition, mere aggregation of another work not based on the Program with the +Program (or with a work based on the Program) on a volume of a storage or +distribution medium does not bring the other work under the scope of this +License. + +**3.** You may copy and distribute the Program (or a work based on it, under +Section 2) in object code or executable form under the terms of Sections 1 and 2 +above provided that you also do one of the following: + +* **a)** Accompany it with the complete corresponding machine-readable source + code, which must be distributed under the terms of Sections 1 and 2 above on + a medium customarily used for software interchange; or, + +* **b)** Accompany it with a written offer, valid for at least three years, to + give any third party, for a charge no more than your cost of physically + performing source distribution, a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of Sections 1 + and 2 above on a medium customarily used for software interchange; or, + +* **c)** Accompany it with the information you received as to the offer to + distribute corresponding source code. (This alternative is allowed only for + noncommercial distribution and only if you received the program in object + code or executable form with such an offer, in accord with Subsection b + above.) + +The source code for a work means the preferred form of the work for making +modifications to it. For an executable work, complete source code means all the +source code for all modules it contains, plus any associated interface +definition files, plus the scripts used to control compilation and installation +of the executable. However, as a special exception, the source code distributed +need not include anything that is normally distributed (in either source or +binary form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component itself +accompanies the executable. + +If distribution of executable or object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the source code +from the same place counts as distribution of the source code, even though third +parties are not compelled to copy the source along with the object code. + +**4.** You may not copy, modify, sublicense, or distribute the Program except as +expressly provided under this License. Any attempt otherwise to copy, modify, +sublicense or distribute the Program is void, and will automatically terminate +your rights under this License. However, parties who have received copies, or +rights, from you under this License will not have their licenses terminated so +long as such parties remain in full compliance. + +**5.** You are not required to accept this License, since you have not signed +it. However, nothing else grants you permission to modify or distribute the +Program or its derivative works. These actions are prohibited by law if you do +not accept this License. Therefore, by modifying or distributing the Program (or +any work based on the Program), you indicate your acceptance of this License to +do so, and all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + +**6.** Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the original +licensor to copy, distribute or modify the Program subject to these terms and +conditions. You may not impose any further restrictions on the recipients' +exercise of the rights granted herein. You are not responsible for enforcing +compliance by third parties to this License. + +**7.** If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), conditions +are imposed on you (whether by court order, agreement or otherwise) that +contradict the conditions of this License, they do not excuse you from the +conditions of this License. If you cannot distribute so as to satisfy +simultaneously your obligations under this License and any other pertinent +obligations, then as a consequence you may not distribute the Program at all. +For example, if a patent license would not permit royalty-free redistribution of +the Program by all those who receive copies directly or indirectly through you, +then the only way you could satisfy both it and this License would be to refrain +entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply and the +section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or +other property right claims or to contest validity of any such claims; this +section has the sole purpose of protecting the integrity of the free software +distribution system, which is implemented by public license practices. Many +people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose that +choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +**8.** If the distribution and/or use of the Program is restricted in certain +countries either by patents or by copyrighted interfaces, the original copyright +holder who places the Program under this License may add an explicit +geographical distribution limitation excluding those countries, so that +distribution is permitted only in or among countries not thus excluded. In such +case, this License incorporates the limitation as if written in the body of this +License. + +**9.** The Free Software Foundation may publish revised and/or new versions of +the General Public License from time to time. Such new versions will be similar +in spirit to the present version, but may differ in detail to address new +problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies +a version number of this License which applies to it and "any later version", +you have the option of following the terms and conditions either of that version +or of any later version published by the Free Software Foundation. If the +Program does not specify a version number of this License, you may choose any +version ever published by the Free Software Foundation. + +**10.** If you wish to incorporate parts of the Program into other free programs +whose distribution conditions are different, write to the author to ask for +permission. For software which is copyrighted by the Free Software Foundation, +write to the Free Software Foundation; we sometimes make exceptions for this. +Our decision will be guided by the two goals of preserving the free status of +all derivatives of our free software and of promoting the sharing and reuse of +software generally. + + +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. + +**12.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA +BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER +OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. \ No newline at end of file diff --git a/autoconf-macros/LICENSE.md b/autoconf-macros/LICENSE.md new file mode 100644 index 0000000..a983462 --- /dev/null +++ b/autoconf-macros/LICENSE.md @@ -0,0 +1,264 @@ +The GNU General Public License, Version 2, June 1991 (GPLv2) +============================================================ + +> Copyright (C) 1989, 1991 Free Software Foundation, Inc. +> 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + +Everyone is permitted to copy and distribute verbatim copies of this license +document, but changing it is not allowed. + + +Preamble +-------- + +The licenses for most software are designed to take away your freedom to share +and change it. By contrast, the GNU General Public License is intended to +guarantee your freedom to share and change free software--to make sure the +software is free for all its users. This General Public License applies to most +of the Free Software Foundation's software and to any other program whose +authors commit to using it. (Some other Free Software Foundation software is +covered by the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our +General Public Licenses are designed to make sure that you have the freedom to +distribute copies of free software (and charge for this service if you wish), +that you receive source code or can get it if you want it, that you can change +the software or use pieces of it in new free programs; and that you know you can +do these things. + +To protect your rights, we need to make restrictions that forbid anyone to deny +you these rights or to ask you to surrender the rights. These restrictions +translate to certain responsibilities for you if you distribute copies of the +software, or if you modify it. + +For example, if you distribute copies of such a program, whether gratis or for a +fee, you must give the recipients all the rights that you have. You must make +sure that they, too, receive or can get the source code. And you must show them +these terms so they know their rights. + +We protect your rights with two steps: (1) copyright the software, and (2) offer +you this license which gives you legal permission to copy, distribute and/or +modify the software. + +Also, for each author's protection and ours, we want to make certain that +everyone understands that there is no warranty for this free software. If the +software is modified by someone else and passed on, we want its recipients to +know that what they have is not the original, so that any problems introduced by +others will not reflect on the original authors' reputations. + +Finally, any free program is threatened constantly by software patents. We wish +to avoid the danger that redistributors of a free program will individually +obtain patent licenses, in effect making the program proprietary. To prevent +this, we have made it clear that any patent must be licensed for everyone's free +use or not licensed at all. + +The precise terms and conditions for copying, distribution and modification +follow. + + +Terms And Conditions For Copying, Distribution And Modification +--------------------------------------------------------------- + +**0.** This License applies to any program or other work which contains a notice +placed by the copyright holder saying it may be distributed under the terms of +this General Public License. The "Program", below, refers to any such program or +work, and a "work based on the Program" means either the Program or any +derivative work under copyright law: that is to say, a work containing the +Program or a portion of it, either verbatim or with modifications and/or +translated into another language. (Hereinafter, translation is included without +limitation in the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not covered by +this License; they are outside its scope. The act of running the Program is not +restricted, and the output from the Program is covered only if its contents +constitute a work based on the Program (independent of having been made by +running the Program). Whether that is true depends on what the Program does. + +**1.** You may copy and distribute verbatim copies of the Program's source code +as you receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice and +disclaimer of warranty; keep intact all the notices that refer to this License +and to the absence of any warranty; and give any other recipients of the Program +a copy of this License along with the Program. + +You may charge a fee for the physical act of transferring a copy, and you may at +your option offer warranty protection in exchange for a fee. + +**2.** You may modify your copy or copies of the Program or any portion of it, +thus forming a work based on the Program, and copy and distribute such +modifications or work under the terms of Section 1 above, provided that you also +meet all of these conditions: + +* **a)** You must cause the modified files to carry prominent notices stating + that you changed the files and the date of any change. + +* **b)** You must cause any work that you distribute or publish, that in whole + or in part contains or is derived from the Program or any part thereof, to + be licensed as a whole at no charge to all third parties under the terms of + this License. + +* **c)** If the modified program normally reads commands interactively when + run, you must cause it, when started running for such interactive use in the + most ordinary way, to print or display an announcement including an + appropriate copyright notice and a notice that there is no warranty (or + else, saying that you provide a warranty) and that users may redistribute + the program under these conditions, and telling the user how to view a copy + of this License. (Exception: if the Program itself is interactive but does + not normally print such an announcement, your work based on the Program is + not required to print an announcement.) + +These requirements apply to the modified work as a whole. If identifiable +sections of that work are not derived from the Program, and can be reasonably +considered independent and separate works in themselves, then this License, and +its terms, do not apply to those sections when you distribute them as separate +works. But when you distribute the same sections as part of a whole which is a +work based on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the entire whole, +and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest your +rights to work written entirely by you; rather, the intent is to exercise the +right to control the distribution of derivative or collective works based on the +Program. + +In addition, mere aggregation of another work not based on the Program with the +Program (or with a work based on the Program) on a volume of a storage or +distribution medium does not bring the other work under the scope of this +License. + +**3.** You may copy and distribute the Program (or a work based on it, under +Section 2) in object code or executable form under the terms of Sections 1 and 2 +above provided that you also do one of the following: + +* **a)** Accompany it with the complete corresponding machine-readable source + code, which must be distributed under the terms of Sections 1 and 2 above on + a medium customarily used for software interchange; or, + +* **b)** Accompany it with a written offer, valid for at least three years, to + give any third party, for a charge no more than your cost of physically + performing source distribution, a complete machine-readable copy of the + corresponding source code, to be distributed under the terms of Sections 1 + and 2 above on a medium customarily used for software interchange; or, + +* **c)** Accompany it with the information you received as to the offer to + distribute corresponding source code. (This alternative is allowed only for + noncommercial distribution and only if you received the program in object + code or executable form with such an offer, in accord with Subsection b + above.) + +The source code for a work means the preferred form of the work for making +modifications to it. For an executable work, complete source code means all the +source code for all modules it contains, plus any associated interface +definition files, plus the scripts used to control compilation and installation +of the executable. However, as a special exception, the source code distributed +need not include anything that is normally distributed (in either source or +binary form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component itself +accompanies the executable. + +If distribution of executable or object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the source code +from the same place counts as distribution of the source code, even though third +parties are not compelled to copy the source along with the object code. + +**4.** You may not copy, modify, sublicense, or distribute the Program except as +expressly provided under this License. Any attempt otherwise to copy, modify, +sublicense or distribute the Program is void, and will automatically terminate +your rights under this License. However, parties who have received copies, or +rights, from you under this License will not have their licenses terminated so +long as such parties remain in full compliance. + +**5.** You are not required to accept this License, since you have not signed +it. However, nothing else grants you permission to modify or distribute the +Program or its derivative works. These actions are prohibited by law if you do +not accept this License. Therefore, by modifying or distributing the Program (or +any work based on the Program), you indicate your acceptance of this License to +do so, and all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + +**6.** Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the original +licensor to copy, distribute or modify the Program subject to these terms and +conditions. You may not impose any further restrictions on the recipients' +exercise of the rights granted herein. You are not responsible for enforcing +compliance by third parties to this License. + +**7.** If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), conditions +are imposed on you (whether by court order, agreement or otherwise) that +contradict the conditions of this License, they do not excuse you from the +conditions of this License. If you cannot distribute so as to satisfy +simultaneously your obligations under this License and any other pertinent +obligations, then as a consequence you may not distribute the Program at all. +For example, if a patent license would not permit royalty-free redistribution of +the Program by all those who receive copies directly or indirectly through you, +then the only way you could satisfy both it and this License would be to refrain +entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply and the +section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any patents or +other property right claims or to contest validity of any such claims; this +section has the sole purpose of protecting the integrity of the free software +distribution system, which is implemented by public license practices. Many +people have made generous contributions to the wide range of software +distributed through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing to +distribute software through any other system and a licensee cannot impose that +choice. + +This section is intended to make thoroughly clear what is believed to be a +consequence of the rest of this License. + +**8.** If the distribution and/or use of the Program is restricted in certain +countries either by patents or by copyrighted interfaces, the original copyright +holder who places the Program under this License may add an explicit +geographical distribution limitation excluding those countries, so that +distribution is permitted only in or among countries not thus excluded. In such +case, this License incorporates the limitation as if written in the body of this +License. + +**9.** The Free Software Foundation may publish revised and/or new versions of +the General Public License from time to time. Such new versions will be similar +in spirit to the present version, but may differ in detail to address new +problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies +a version number of this License which applies to it and "any later version", +you have the option of following the terms and conditions either of that version +or of any later version published by the Free Software Foundation. If the +Program does not specify a version number of this License, you may choose any +version ever published by the Free Software Foundation. + +**10.** If you wish to incorporate parts of the Program into other free programs +whose distribution conditions are different, write to the author to ask for +permission. For software which is copyrighted by the Free Software Foundation, +write to the Free Software Foundation; we sometimes make exceptions for this. +Our decision will be guided by the two goals of preserving the free status of +all derivatives of our free software and of promoting the sharing and reuse of +software generally. + + +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. + +**12.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR +INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA +BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER +OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. \ No newline at end of file diff --git a/autoconf-macros/README.md b/autoconf-macros/README.md new file mode 100644 index 0000000..11e5223 --- /dev/null +++ b/autoconf-macros/README.md @@ -0,0 +1,199 @@ +autoconf-macros +=============== + +The purpose of Nagios autoconf-macros is to have a central place for +autoconf macros that can be maintained in one place, but be used by any +of the Nagios software. It is intended to be used as a git subtree. +See the [Usage](#usage) and [References](#references) sections below. + +Since this project will be included in several parent projects, any +changes must be as project-neutral as possible. + +Make sure to check out the [CHANGELOG](CHANGELOG.md) for relevant +information, as well. + + +Contents +-------- + +The collection consists of the following macros: + +### AX_NAGIOS_GET_OS alias AC_NAGIOS_GET_OS + +> Output Variable : `opsys` + +This macro detects the operating system, and transforms it into a generic +label. The most common OS's that use Nagios software are recognized and +used in subsequent macros. + +### AX_NAGIOS_GET_DISTRIB_TYPE alias AC_NAGIOS_GET_DISTRIB_TYPE + +> Output Variables : `dist_type`, `dist_ver` + +This macro detects the distribution type. For Linux, this would be rh +(for Red Hat and derivatives), suse (OpenSUSE, SLES, derivatives), gentoo +(Gentoo and derivatives), debian (Debian and derivatives), and so on. +For BSD, this would be openbsd, netbsd, freebsd, dragonfly, etc. It can +also be aix, solaris, osx, and so on for Unix operating systems. + +### AX_NAGIOS_GET_INIT alias AC_NAGIOS_GET_INIT + +> Output Variable : `init_type` + +This macro detects what software is used to start daemons on bootup +or on request, generally knows as the "init system". The init_type +will generally be one of sysv (many), bsd (Slackware), newbsd (*BSD), +launchd (OS X), smf10 or smf11 (Solaris), systemd (newer Linux), +gentoo (older Gentoo), upstart (several), or unknown. + +### AX_NAGIOS_GET_INETD alias AC_NAGIOS_GET_INETD + +> Output Variable : `inetd_type` + +This macro detects what software is used to start daemons or services +on demand, which historically has been "inetd". The inetd_type +will generally be one of inetd, xinetd, launchd (OS X), smf10 or smf11 +(Solaris), systemd (newer Linux), upstart (several), or unknown. + +### AX_NAGIOS_GET_PATHS alias AC_NAGIOS_GET_PATHS + +> Output Variables : **many!** + +This macro determines the installation paths for binaries, config files, +PID files, and so on. For a "standard" install of Nagios, NRPE, NDO Utils, +etc., most will be in the /usr/local/nagios hierarchy with startup files +located in /etc. For distributions or software repositories, the +"--enable-install-method=os" option can be used. This will determine the +O/S dependent directories, such as /usr/bin, /usr/sbin, /var/lib/nagios, +/usr/lib/nagios, etc. or for OS X, /Library/LaunchDaemons. + +### AX_NAGIOS_GET_FILES alias AC_NAGIOS_GET_FILES + +> Output Variables : `src_init`, `src_inetd`, `src_tmpfile` + +Each Nagios project will have a top-level directory named "/startup/". +In that directory will be "*.in" files for the various "init_type" and +"inetd_type" systems. This macro will determine which file(s) from +that directory will be needed. + +### AX_NAGIOS_GET_SSL alias AC_NAGIOS_GET_SSL + +> Output Variables : `HAVE_KRB5_H`, `HAVE_SSL`, `SSL_INC_DIR`, `SSL_LIB_DIR`, `CFLAGS`, `LDFLAGS`, `LIBS` + +This macro checks various directories for SSL libraries and header files. +The searches are based on known install locations on various operating +systems and distributions, for openssl, gnutls-openssl, and nss_compat_ossl. +If it finds the headers and libraries, it will then do an `AC_LINK_IFELSE` +on a simple program to make sure a compile and link will work correctly. + + +Usage +----- + +This repo is intended to be used as a git subtree, so changes will +automatically propagate, and still be reasonably easy to use. + +* First, Create, checkout, clone, or branch your project. If you do an +`ls -AF` it might look something like this: + + .git/ .gitignore ChangeLog LICENSE Makefile.in + README configure.ac include/ src/ + +* Then make a reference to _this_ project inside your project. + + git remote add autoconf-macros git@github.com:NagiosEnterprises/autoconf-macros + git subtree add --prefix=macros/ autoconf-macros master + +* After executing the above two commands, if you do an `ls -AF` now, +it should look like this: + + .git/ .gitignore ChangeLog LICENSE Makefile.in + README configure.ac include/ macros/ src/ + +* The `macros/` directory has been added. + +* Now do a `git push` to save everything. + +* If you make any changes to autoconf-macros, commit them separately +from any parent-project changes to keep from polluting the commit +history with unrelated comments. + +* To submit your changes to autoconf-macros: + + git subtree push --prefix=macros autoconf-macros peters-updates +This will create a new branch called `peters-updates`. You then need to +create a _pull request_ to get your changes merged into autoconf-macros +master. + +* To get the latest version of `autoconf-macros` into your parent project: + + git subtgree pull --squash --prefix=macros autoconf-macros master + + +References +---------- + +Now that autoconf-macros is available to your project, you will need to +reference it. + +* Create (or add these lines to) file `YourProject/aclocal.m4` + + m4_include([macros/ax_nagios_get_os]) + m4_include([macros/ax_nagios_get_distrib]) + m4_include([macros/ax_nagios_get_init]) + m4_include([macros/ax_nagios_get_inetd]) + m4_include([macros/ax_nagios_get_paths]) + m4_include([macros/ax_nagios_get_files]) + m4_include([macros/ax_nagios_get_ssl]) + +* In your `YourProject/configure.ac` add the following lines. A good place +to put them would be right after any `AC_PROG_*` entries: + + AC_NAGIOS_GET_OS + AC_NAGIOS_GET_DISTRIB_TYPE + AC_NAGIOS_GET_INIT + AC_NAGIOS_GET_INETD + AC_NAGIOS_GET_PATHS + AC_NAGIOS_GET_FILES + +* If you need SSL functionality, add the following to `YourProject/configure.ac` +where you want to check for SSL: + + AC_NAGIOS_GET_SSL + +* You will now be able to reference any of the variables in `config.h.in` +and any files listed in the `AC_CONFIG_FILES` macro in `configure.ac`. + + +License Notice +-------------- + +Copyright (c) 2016-2017 Nagios Enterprises, LLC + +This work is made available to you under the terms of Version 2 of +the GNU General Public License. A copy of that license should have +been provided with this software, but in any event can be obtained +from http://www.fsf.org. + +This work is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 or visit their web page on the internet at +http://www.fsf.org. + + +Questions? +---------- + +If you have questions about this addon, or problems getting things +working, first try searching the nagios-users mailing list archives. +Details on searching the list archives can be found at +http://www.nagios.org + +If you don't find an answer there, post a message in the Nagios +Plugin Development forum at https://support.nagios.com/forum/viewforum.php?f=35 diff --git a/autoconf-macros/add_group_user b/autoconf-macros/add_group_user new file mode 100755 index 0000000..cf18ae9 --- /dev/null +++ b/autoconf-macros/add_group_user @@ -0,0 +1,164 @@ +#!/bin/sh + +#---------------------- +# Initialize variables +#---------------------- +dist="$1" +uid="$2" +gid="$3" +rc=0 + +#------------------------------------------------------------------ +# Determine if the user should be created with a shell environment +# 0 = no shell (more secure) +# 1 = shell (less secure but sometimes required) +#------------------------------------------------------------------ +shell=0 +if [ $# -eq 4 ]; then + if [ x$4 = x1 ]; then + shell=1 + fi +fi + +#------------------------------------- +# Check if the specified group exists +#------------------------------------- +group_exists(){ + case $dist in + osx) rc=`dscl . -read /Groups/$gid >/dev/null 2>&1; echo $?` ;; + hpux) rc=`grget -n $gid >/dev/null 2>&1; echo $?` ;; + aix) rc=`lsgroup -a $gid >/dev/null 2>&1; echo $?` ;; + *) rc=`getent group $gid > /dev/null 2>&1; echo $?` ;; + esac + + echo $rc +} + +#------------------------ +# Add the specified user +#------------------------ +add_user(){ + rc=`id "$uid" > /dev/null 2>&1; echo $?` + if test $rc -eq 0; then + echo "User $uid already exists" > /dev/stderr + echo 0 + return + fi + + case $dist in + aix) + echo useradd -g $gid $uid > /dev/stderr + rc=`useradd -g $gid $uid; echo $?` + ;; + + hpux) + echo useradd -m -g $gid $uid > /dev/stderr + rc=`useradd -m -g $gid $uid; echo $?` + ;; + + solaris) + echo useradd -m -d /export/home/$uid -g $gid $uid > /dev/stderr + rc=`useradd -m -d /export/home/$uid -g $gid $uid; echo $?` + ;; + + osx) + newid=`dscl . -list /Users UniqueID | tr -s ' ' | cut -d' ' -f2 | sort -n | tail -1` + newid=`expr 1 + $newid` + echo dscl . -create /Users/$uid > /dev/stderr + dscl . -create /Users/$uid + echo dscl . -create /Users/$uid UniqueID $newid > /dev/stderr + dscl . -create /Users/$uid UniqueID $newid + if [ $shell = 0 ]; then + echo dscl . -create /Users/$uid UserShell /usr/bin/false > /dev/stderr + dscl . -create /Users/$uid UserShell /usr/bin/false + fi + echo dscl . -create /Users/$uid PrimaryGroupID 20 > /dev/stderr + dscl . -create /Users/$uid PrimaryGroupID 20 + echo dscl . -append /Groups/$gid GroupMembership $uid > /dev/stderr + rc=`dscl . -append /Groups/$gid GroupMembership $uid; echo $?` + ;; + + freebsd) + if [ $shell = 0 ]; then + echo pw add user $uid -g $gid -s /usr/bin/false > /dev/stderr + rc=`pw add user $uid -g $gid -s /usr/bin/false; echo $?` + else + echo pw add user $uid -g $gid > /dev/stderr + rc=`pw add user $uid -g $gid; echo $?` + fi + ;; + + netbsd|openbsd) + echo useradd -g $gid $uid > /dev/stderr + rc=`useradd -g $gid $uid; echo $?` + ;; + + *) + if [ $shell = 0 ]; then + echo useradd -r -g $gid $uid > /dev/stderr + rc=`useradd -r -g $gid $uid; echo $?` + else + echo useradd -g $gid $uid > /dev/stderr + rc=`useradd -g $gid $uid; echo $?` + fi + ;; + esac + + echo $rc +} + +#------------------------- +# Add the specified group +#------------------------- +add_group(){ + rc=`group_exists` + if test $rc -eq 0; then + echo "Group $gid already exists" > /dev/stderr + echo 0 + return + fi + + case $dist in + aix) + echo mkgroup $gid > /dev/stderr + rc=`mkgroup "$gid"; echo $?` + ;; + + hpux|solaris) + echo groupadd $gid > /dev/stderr + rc=`groupadd "$gid"; echo $?` + ;; + + osx) + newid=`dscl . -list /Groups gid | tr -s ' ' | cut -d' ' -f2 | sort -n | tail -1` + newid=`expr 1 + $newid` + echo dscl . -create /Groups/$gid gid $newid > /dev/stderr + rc=`dscl . -create /Groups/$gid gid $newid; echo $?` + ;; + + freebsd) + echo pw add group $gid > /dev/stderr + rc=`pw add group $gid; echo $?` + ;; + + netbsd|openbsd) + echo groupadd $gid > /dev/stderr + rc=`groupadd $gid; echo $?` + ;; + + *) + echo groupadd -r $gid > /dev/stderr + rc=`groupadd -r $gid; echo $?` + ;; + esac + + echo $rc +} + + +rc=`add_group` +if test $rc -ne 0; then + exit 1; +fi +rc=`add_user` +exit $rc diff --git a/autoconf-macros/ax_nagios_get_distrib b/autoconf-macros/ax_nagios_get_distrib new file mode 100644 index 0000000..08a554c --- /dev/null +++ b/autoconf-macros/ax_nagios_get_distrib @@ -0,0 +1,160 @@ +# =========================================================================== +# SYNOPSIS +# +# AX_NAGIOS_GET_DISTRIB_TYPE +# +# DESCRIPTION +# +# This macro determines the O/S distribution of the computer it is run on. +# $dist_type will be set and will be one of: +# unknown (could not be determined) +# freebsd, netbsd, openbsd, dragonfly, etc (The BSDs) +# suse, rh, debian, gentoo (and possibly their descendants) +# Other major Linux distributions (and possibly their descendants) +# The O/S name for the rest +# +# LICENSE +# +# Copyright (c) 2016 Nagios Core Development Team +# +# This 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. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. +# =========================================================================== + +AU_ALIAS([AC_NAGIOS_GET_DISTRIB_TYPE], [AX_NAGIOS_GET_DISTRIB_TYPE]) +AC_DEFUN([AX_NAGIOS_GET_DISTRIB_TYPE], +[ + +AC_SUBST(dist_type) +AC_SUBST(dist_ver) + +# +# Get user hints for possible cross-compile +# + AC_MSG_CHECKING(what the distribution type is ) + AC_ARG_WITH(dist-type, AS_HELP_STRING([--with-dist-type=type], + [specify distribution type (suse, rh, debian, etc.)]), + [ + # + # Run this if --with was specified + # + if test "x$withval" = x -o x$withval = xno; then + dist_type_wanted=yes + else + dist_type_wanted=no + dist_type="$withval" + dist_ver="unknown" + AC_MSG_RESULT($dist_type) + fi + ], [ + # + # Run this if --with was not specified + # + dist_type_wanted=yes + ]) + + if test x$dist_type = xno; then + dist_type_wanted=yes + elif test x$dist_type = xyes; then + AC_MSG_ERROR([you must enter a distribution type if '--with-dist-type' is specified]) + fi + + # + # Determine distribution type if it wasn't supplied + # + dist_ver="unknown" + + if test $dist_type_wanted=yes; then + dist_type="unknown" + + if test "$opsys" != "linux"; then + dist_type="$opsys" + AS_CASE([$opsys], + [bsd], + dist_type=`uname -s | tr ["[A-Z]" "[a-z]"]` + dist_ver=`uname -r`, + [aix], + dist_ver="`uname -v`.`uname -r`", + [hp-ux], + dist_ver=`uname -r | cut -d'.' -f1-3`, + [solaris], + dist_ver=`uname -r | cut -d'.' -f2`, + [*], + dist_ver=$OSTYPE + ) + + else + + if test -r "/etc/gentoo-release"; then + dist_type="gentoo" + dist_ver=`cat /etc/gentoo-release` + + elif test -r "/etc/os-release"; then + . /etc/os-release + if test x"$ID_LIKE" != x; then + dist_type=`echo $ID_LIKE | cut -d' ' -f1 | tr ["[A-Z]" "[a-z]"]` + elif test x"$ID" = xol; then + dist_type=rh + else + dist_type=`echo $ID | tr ["[A-Z]" "[a-z]"]` + fi + if test x"$dist_type" = sles; then + dist_type=suse + fi + if test x"$VERSION_ID" != x; then + dist_ver=$VERSION_ID + elif test x"$VERSION" != x; then + dist_ver=`echo $VERSION | cut -d'.' -f1 | tr -d [:alpha:][:blank:][:punct:]` + fi + + elif test -r "/etc/redhat-release"; then + dist_type=rh + dist_ver=`cat /etc/redhat-release` + + elif test -r "/etc/debian_version"; then + dist_type="debian" + if test -r "/etc/lsb-release"; then + . /etc/lsb-release + dist_ver=`echo "$DISTRIB_RELEASE"` + else + dist_ver=`cat /etc/debian_version` + fi + + elif test -r "/etc/SuSE-release"; then + dist_type=suse + dist_ver=`grep VERSION /etc/SuSE-release` + + fi + + fi + + if test "$dist_ver" != "unknown"; then + dist_ver=`echo "$dist_ver" | cut -d'.' -f1 | tr -d [:alpha:][:blank:][:punct:]` + fi + fi + + AC_MSG_RESULT($dist_type) +]) diff --git a/autoconf-macros/ax_nagios_get_files b/autoconf-macros/ax_nagios_get_files new file mode 100644 index 0000000..e2e4a0e --- /dev/null +++ b/autoconf-macros/ax_nagios_get_files @@ -0,0 +1,131 @@ +# =========================================================================== +# SYNOPSIS +# +# AX_NAGIOS_GET_FILES +# +# DESCRIPTION +# +# This macro figures out which init and/or inetd files to use based +# on the results of the AX_NAGIOS_GET_OS, AX_NAGIOS_GET_DISTRIB_TYPE, +# AX_NAGIOS_GET_INIT and AX_NAGIOS_GET_INETD macros. It will select +# the appropriate files(s) from the 'startup' directory and copy it. +# +# LICENSE +# +# Copyright (c) 2016 Nagios Core Development Team +# +# This 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. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. +# =========================================================================== + +AU_ALIAS([AC_NAGIOS_GET_FILES], [AX_NAGIOS_GET_FILES]) +AC_DEFUN([AX_NAGIOS_GET_FILES], +[ + +AC_SUBST(src_init) +AC_SUBST(src_inetd) +AC_SUBST(src_tmpfile) +AC_SUBST(bsd_enable) + +src_inetd="" +src_init="" +bsd_enable="" + +AC_MSG_CHECKING(for which init file to use ) + +AS_CASE([$init_type], + + [sysv], + src_init=default-init, + + [systemd], + src_tmpfile=tmpfile.conf + src_init=default-service, + + [bsd], + src_init=bsd-init, + + [newbsd], + if test $dist_type = freebsd ; then + bsd_enable="_enable" + src_init=default-init + elif test $dist_type = openbsd ; then + bsd_enable="_flags" + src_init=openbsd-init + elif test $dist_type = netbsd ; then + bsd_enable="" + src_init=newbsd-init + fi, + +# [gentoo], + + [openrc], + src_init=openrc-init, + + [smf*], + src_init="solaris-init.xml" + src_inetd="solaris-inetd.xml", + + [upstart], + if test $dist_type = rh ; then + src_init=rh-upstart-init + else + src_init=upstart-init + fi, + + [launchd], + src_init="mac-init.plist", + + [*], + src_init="unknown" +) +AC_MSG_RESULT($src_init) + +AC_MSG_CHECKING(for which inetd files to use ) + +if test x$src_inetd = x; then + + AS_CASE([$inetd_type], + [inetd*], + src_inetd=default-inetd, + + [xinetd], + src_inetd=default-xinetd, + + [systemd], + src_inetd=default-socket, + + [launchd], + src_inetd="mac-inetd.plist", + + [*], + src_inetd="unknown" + ) + +fi +AC_MSG_RESULT($src_inetd) + +]) diff --git a/autoconf-macros/ax_nagios_get_init b/autoconf-macros/ax_nagios_get_init new file mode 100644 index 0000000..e04db8c --- /dev/null +++ b/autoconf-macros/ax_nagios_get_init @@ -0,0 +1,200 @@ +# =========================================================================== +# SYNOPSIS +# +# AX_NAGIOS_GET_INIT +# +# DESCRIPTION +# +# This macro determines the O/S distribution of the computer it is run on. +# $init_type will be set and will be one of: +# unknown (could not be determined) +# launchd (Mac OS X) +# bsd (Slackware Linux) +# newbsd (FreeBSD, OpenBSD, NetBSD, Dragonfly, etc) +# smf10 (Solaris) +# smf11 (Solaris) +# systemd (Linux SystemD) +# gentoo (Older Gentoo) +# openrc (Recent Gentoo and some others) +# upstart (Older Debian) +# sysv (The rest) +# +# LICENSE +# +# Copyright (c) 2016 Nagios Core Development Team +# +# This 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. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. +# =========================================================================== + +AU_ALIAS([AC_NAGIOS_GET_INIT], [AX_NAGIOS_GET_INIT]) +AC_DEFUN([AX_NAGIOS_GET_INIT], +[ + +AC_SUBST(init_type) + +# +# Get user hints for possible cross-compile +# + AC_MSG_CHECKING(what init system is being used ) + AC_ARG_WITH(init_type,AS_HELP_STRING([--with-init-type=type], + [specify init type (bsd, sysv, systemd, launchd, smf10, smf11, upstart, + openrc, etc.)]), + [ + # + # Run this if --with was specified + # + if test "x$withval" = x -o x$withval = xno; then + init_type_wanted=yes + else + init_type_wanted=no + init_type="$withval" + AC_MSG_RESULT($init_type) + fi + ], [ + # + # Run this if --with was not specified + # + init_type_wanted=yes + ]) + + if test x$init_type = xno; then + init_type_wanted=yes + elif test x$init_type = xyes; then + AC_MSG_ERROR([you must enter an init type if '--with-init-type' is specified]) + fi + + # + # Determine init type if it wasn't supplied + # + if test $init_type_wanted = yes; then + init_type="" + + if test x"$opsys" = x; then + init_type="unknown" + init_type_wanted=no + elif test x"$dist_type" = x; then + init_type="unknown" + init_type_wanted=no + elif test "$opsys" = "osx"; then + init_type="launchd" + init_type_wanted=no + elif test "$opsys" = "bsd"; then + init_type="newbsd" + init_type_wanted=no + elif test "$dist_type" = "solaris"; then + if test -d "/lib/svc/manifest"; then + init_type="smf11" + init_type_wanted=no + elif test -d "/lib/svc/monitor"; then + init_type="smf10" + init_type_wanted=no + else + init_type="sysv" + init_type_wanted=no + fi + elif test "$dist_type" = "slackware"; then + init_type="bsd" + init_type_wanted=no + elif test "$dist_type" = "aix"; then + init_type="bsd" + init_type_wanted=no + elif test "$dist_type" = "hp-ux"; then + init_type="unknown" + init_type_wanted=no + fi + fi + + PSCMD="ps -p1 -o args" + if test $dist_type = solaris; then + PSCMD="env UNIX95=1; ps -p1 -o args" + fi + + if test "$init_type_wanted" = yes; then + pid1=`$PSCMD | grep -vi COMMAND | cut -d' ' -f1` + if test x"$pid1" = "x"; then + init_type="unknown" + init_type_wanted=no + fi + if `echo $pid1 | grep "systemd" > /dev/null`; then + init_type="systemd" + init_type_wanted=no + fi + + if test "$init_type_wanted" = yes; then + if test "$pid1" = "init"; then + if test -e "/sbin/init"; then + pid1="/sbin/init"; + elif test -e "/usr/sbin/init"; then + pid1="/usr/sbin/init" + else + init_type="unknown" + init_type_wanted=no + fi + fi + if test -L "$pid1"; then + pid1=`readlink "$pid1"` + fi + fi + + if test "$init_type_wanted" = yes; then + if `echo $pid1 | grep "systemd" > /dev/null`; then + init_type="systemd" + init_type_wanted=no + elif test -f "/sbin/rc"; then + if test -f /sbin/runscript; then + init_type_wanted=no + if `/sbin/start-stop-daemon -V | grep "OpenRC" > /dev/null`; then + init_type="openrc" + else + init_type="gentoo" + fi + fi + fi + fi + + if test "$init_type_wanted" = yes; then + if test "$pid1" = "/sbin/init" -o "$pid1" = "/usr/sbin/init"; then + if `$pid1 --version 2>/dev/null | grep "upstart" >/dev/null`; then + init_type="upstart" + init_type_wanted=no + elif test -f "/etc/rc" -a ! -L "/etc/rc"; then + init_type="newbsd" + init_type_wanted=no + else + init_type="sysv" + init_type_wanted=no + fi + fi + fi + + if test "$init_type_wanted" = yes; then + init_type="unknown" + fi + fi + + AC_MSG_RESULT($init_type) +]) diff --git a/autoconf-macros/ax_nagios_get_os b/autoconf-macros/ax_nagios_get_os new file mode 100644 index 0000000..f55800c --- /dev/null +++ b/autoconf-macros/ax_nagios_get_os @@ -0,0 +1,101 @@ +# =========================================================================== +# SYNOPSIS +# +# AX_NAGIOS_GET_OS +# +# DESCRIPTION +# +# This macro determines the operating system of the computer it is run on. +# +# LICENSE +# +# Copyright (c) 2016 Nagios Core Development Team +# +# This 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. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. +# =========================================================================== + +AU_ALIAS([AC_NAGIOS_GET_OS], [AX_NAGIOS_GET_OS]) +AC_DEFUN([AX_NAGIOS_GET_OS], +[ + +AC_SUBST(opsys) +AC_SUBST(arch) + +# +# Get user hints +# + AC_MSG_CHECKING(what the operating system is ) + AC_ARG_WITH(opsys, AS_HELP_STRING([--with-opsys=OS], + [specify operating system (linux, osx, bsd, solaris, irix, cygwin, + aix, hp-ux, etc.)]), + [ + # + # Run this if --with was specified + # + if test "x$withval" = x -o x$withval = xno; then + opsys_wanted=yes + else + opsys_wanted=no + opsys="$withval" + AC_MSG_RESULT($opsys) + fi + ], [ + # + # Run this if --with was not specified + # + opsys_wanted=yes + ]) + + if test x$opsys = xno; then + opsys="" + opsys_wanted=yes + elif test x$opsys = xyes; then + AC_MSG_ERROR([you must enter an O/S type if '--with-opsys' is specified]) + fi + + # + # Determine operating system if it wasn't supplied + # + if test $opsys_wanted=yes; then + opsys=`uname -s | tr ["[A-Z]" "[a-z]"]` + if test x"$opsys" = "x"; then opsys="unknown"; fi + AS_CASE([$opsys], + [darwin*], opsys="osx", + [*bsd*], opsys="bsd", + [dragonfly], opsys="bsd", + [sunos], opsys="solaris", + [gnu/hurd], opsys="linux", + [irix*], opsys="irix", + [cygwin*], opsys="cygwin", + [mingw*], opsys="mingw", + [msys*], opsys="msys") + fi + + arch=`uname -m | tr ["[A-Z]" "[a-z]"]` + + AC_MSG_RESULT($opsys) +]) diff --git a/autoconf-macros/ax_nagios_get_paths b/autoconf-macros/ax_nagios_get_paths new file mode 100644 index 0000000..1dfc3fb --- /dev/null +++ b/autoconf-macros/ax_nagios_get_paths @@ -0,0 +1,783 @@ +# =========================================================================== +# SYNOPSIS +# +# AX_NAGIOS_GET_PATHS +# +# DESCRIPTION +# +# This macro figures out the installation & run paths for various systems +# The argument are: +# the O/S determined by the AX_NAGIOS_GET_OS macro. +# the distribution type as determined by AX_NAGIOS_GET_DISTRIB_TYPE +# the init type as determined by AX_NAGIOS_GET_INIT +# the inetd type as determined by AX_NAGIOS_GET_INETD +# +# LICENSE +# +# Copyright (c) 2016 Nagios Core Development Team +# +# This 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. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +# Public License for more details. +# +# You should have received a copy of the GNU General Public License along +# with this program. If not, see . +# +# As a special exception, the respective Autoconf Macro's copyright owner +# gives unlimited permission to copy, distribute and modify the configure +# scripts that are the output of Autoconf when processing the Macro. You +# need not follow the terms of the GNU General Public License when using +# or distributing such scripts, even though portions of the text of the +# Macro appear in them. The GNU General Public License (GPL) does govern +# all other use of the material that constitutes the Autoconf Macro. +# +# This special exception to the GPL applies to versions of the Autoconf +# Macro released by the Autoconf Archive. When you make and distribute a +# modified version of the Autoconf Macro, you may extend this special +# exception to the GPL to apply to your modified version as well. +# =========================================================================== + +AU_ALIAS([AC_NAGIOS_GET_PATHS], [AX_NAGIOS_GET_PATHS]) +AC_DEFUN([AX_NAGIOS_GET_PATHS], +[ + +AC_SUBST(pkgsysconfdir) +AC_SUBST(objsysconfdir) +AC_SUBST(initname) +AC_SUBST(inetdname) +AC_SUBST(pluginsdir) +AC_SUBST(brokersdir) +AC_SUBST(cgibindir) +AC_SUBST(webdir) +AC_SUBST(privatesysconfdir) +AC_SUBST(pkglocalstatedir) +AC_SUBST(logdir) +AC_SUBST(piddir) +AC_SUBST(pipedir) +AC_SUBST(spooldir) +AC_SUBST(initdir) +AC_SUBST(initdiroverridden) +AC_SUBST(inetddir) +AC_SUBST(tmpfilesd) +AC_SUBST(subsyslockdir) +AC_SUBST(subsyslockfile) + +if test x$DBG_PATHS != x; then + echo + echo Incoming paths: + echo " prefix $prefix" + echo " exec_prefix $exec_prefix" + echo " bindir $bindir" + echo " libexecdir $libexecdir" + echo " sysconfdir $sysconfdir" + echo " localstatedir $localstatedir" + echo " datarootdir $datarootdir" + echo " datadir $datadir" + echo " localedir $localedir" + echo +fi + +AC_MSG_CHECKING(for which paths to use ) + +AC_ARG_ENABLE(install_method, + AS_HELP_STRING([--enable-install-method=], + [sets the install method to use: 'default' (the default) will install to + /usr/local/nagios, 'os' will try to determine which method to use based + on OS type and distribution. Fine tuning using the '--bindir', etc. + overrides above will still work]), + install_method=$enableval, + install_method=default +) + +AC_ARG_ENABLE(showdirs_only, + AS_HELP_STRING([--enable-showdirs-only=yes], + [This option will cause 'configure' to stop after determining the install + locations based on '--enable-install-method', so you can see the + destinations before a full './configure', 'make', 'make install' + process.]), + showdirs_only=$enableval, + showdirs_only=no +) + +AS_CASE([$install_method], + [yes], install_method="os", + [no], install_method="default", + [default|os], :, + [*], echo >&6; AC_MSG_ERROR(['--enable-install-method=$install_method' is invalid]) +) + +if test $showdirs_only != "no"; then showdirs_only="yes"; fi + +AS_CASE([$dist_type], + [*solaris*|*hp-ux*|*aix*|*osx*], opsys=unix) + + + # Does this package need to know: +need_cgi=no # where the cgi-bin directory is +need_web=no # where the website directory is +need_brk=no # where the event broker modules directory is +need_plg=no # where the plugins directory is +need_pipe=no # where the pipe directory is +need_spl=no # where the spool directory is +need_loc=no # where the locale directory is +need_log_subdir=no # where the loc sub-directory is +need_etc_subdir=no # where the etc sub-directory is +need_pls_dir=no # where the package locate state directory is + +if test x"$INIT_PROG" = x; then + INIT_PROG="$PKG_NAME" +fi + +AS_CASE([$PKG_NAME], + [nagios], + need_log_subdir=yes + need_etc_subdir=yes + need_pls_dir=yes + need_brk=yes + need_pipe=yes + need_spl=yes + need_loc=yes + need_cgi=yes + need_web=yes, + + [ndoutils], + need_brk=yes + need_spl=yes, + + [nrpe], + need_plg=yes, + + [nsca], + need_cgi=no, + + [plugins], + need_loc=yes + need_plg=yes +) + +AC_ARG_WITH(pkgsysconfdir, AS_HELP_STRING([--with-pkgsysconfdir=DIR], + [where configuration files should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + pkgsysconfdir="$withval" + fi) +AC_ARG_WITH(objsysconfdir, AS_HELP_STRING([--with-objsysconfdir=DIR], + [where object configuration files should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + objsysconfdir="$withval" + fi) +AC_ARG_WITH(privatesysconfdir, AS_HELP_STRING([--with-privatesysconfdir=DIR], + [where private configuration files should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + privatesysconfdir="$withval" + fi) +AC_ARG_WITH(webdir, AS_HELP_STRING([--with-webdir=DIR], + [where the website files should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + webdir="$withval" + fi) +AC_ARG_WITH(pluginsdir, AS_HELP_STRING([--with-pluginsdir=DIR], + [where the plugins should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + pluginsdir="$withval" + fi) +AC_ARG_WITH(brokersdir, AS_HELP_STRING([--with-brokersdir=DIR], + [where the broker modules should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + brokersdir="$withval" + fi) +AC_ARG_WITH(cgibindir, AS_HELP_STRING([--with-cgibindir=DIR], + [where the CGI programs should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + cgibindir="$withval" + fi) +AC_ARG_WITH(logdir, AS_HELP_STRING([--with-logdir=DIR], + [where log files should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + logdir="$withval" + fi) +AC_ARG_WITH(piddir, AS_HELP_STRING([--with-piddir=DIR], + [where the PID file should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + piddir="$withval" + fi) +AC_ARG_WITH(pipedir, AS_HELP_STRING([--with-pipedir=DIR], + [where socket and pipe files should be placed]), + if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + pipedir="$withval" + fi) + + +# +# Setup the base directory +# + +if test $install_method = "default"; then + if test $opsys = "unix"; then + if test x"$prefix" = "xNONE"; then prefix="/usr/local/nagios"; fi + else + if test x"$prefix" = "xNONE"; then prefix=${ac_default_prefix}; fi + fi + datarootdir=${datarootdir="$prefix"} + +else + if test x"$datadir" = x'${datarootdir}'; then AS_UNSET(datadir); fi + if test x"$sysconfdir" = x'${prefix}/etc'; then AS_UNSET(sysconfdir); fi + + if test x"$prefix" = "xNONE"; then + if test $dist_type = freebsd -o $dist_type = openbsd -o $dist_type = osx; then + prefix="/usr/local" + elif test $dist_type = netbsd; then + prefix="/usr/pkg" + else + prefix="/usr" + fi + fi + if test x"$exec_prefix" = "xNONE"; then exec_prefix=$prefix; fi + if test x"$localstatedir" = x'${prefix}/var'; then + if test $dist_type = "osx"; then + localstatedir="/private/var" + else + localstatedir="/var" + fi + fi + + if test $opsys = "unix"; then + if test x"$datarootdir" = x'${prefix}/share'; then + if test $dist_type = "hp-ux"; then + datarootdir="/usr/local/share" + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/nagios" + fi + elif test $dist_type = "osx"; then + datarootdir="/usr/local/share" + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/local/nagios" + fi + elif test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/lib/nagios" + fi + fi + if test $dist_type = "osx"; then + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/local/libexec/nagios" + fi + fi + elif test $opsys = "bsd"; then + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir=${exec_prefix}/libexec/nagios; + fi + elif test x"$libexecdir" = x'${exec_prefix}/lib'; then + libexecdir=${libexecdir}/nagios; + elif test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir=${exec_prefix}/lib/nagios; + fi + +fi + +if test x"$exec_prefix" = "xNONE"; then exec_prefix=${prefix}; fi + +tmpfilesd=${tmpfilesd="/usr/lib/tmpfiles.d"} +if test ! -d "$tmpfilesd"; then + tmpfilesd="N/A" +else + tmpfilesd="$tmpfilesd/$INIT_PROG.conf" +fi +subsyslockdir=${subsyslockdir="/run"} +if test ! -d "$subsyslockdir"; then + subsyslockdir="N/A" + subsyslockfile="N/A" +else + subsyslockfile="$subsyslockdir/$INIT_PROG.lock" +fi +if test "$need_loc" = no; then + localedir="N/A" +fi + +if test $install_method = "default" ; then + # + # Do the default setup + # + datadir=${datadir="$datarootdir"} + if test $need_web = yes; then + webdir=${webdir="$datadir"} + else + webdir="N/A" + fi + if test $opsys = "unix"; then + sysconfdir=${sysconfdir="/etc/opt"} + fi + pkgsysconfdir=${pkgsysconfdir="$sysconfdir"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir"} + logdir=${logdir="$localstatedir"} + piddir=${piddir="$localstatedir"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/rw"} + else + pipedir="N/A" + fi + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir"} + else + pkglocalstatedir="N/A" + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/var"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$bindir"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + cgibindir=${cgibindir="$prefix/sbin"} + else + cgibindir="N/A" + fi + +elif test $opsys = "linux"; then + + # + # Linux "Standard" install + # + install_method="$install_method : FHS" + datadir=${datadir="$datarootdir/nagios"} + if test $need_web = yes; then + webdir=${webdir="$datadir/html"} + else + webdir="N/A" + fi + sysconfdir=${sysconfdir="/etc"} + pkgsysconfdir=${pkgsysconfdir="$sysconfdir/nagios"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir/private"} + if test $need_log_subdir = yes; then + logdir=${logdir="$localstatedir/log/$INIT_PROG"} + else + logdir=${logdir="$localstatedir/log"} + fi + piddir=${piddir="$localstatedir/run/${INIT_PROG}"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/run/${INIT_PROG}"} + else + pipedir="N/A" + fi + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir/lib/$INIT_PROG"} + else + pkglocalstatedir="N/A" + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/spool/$INIT_PROG"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$libexecdir/brokers"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir/plugins"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + cgibindir=${cgibindir="$libexecdir/cgi-bin"} + else + cgibindir="N/A" + fi + +elif test $opsys = "unix"; then + + # + # "Standard" Unix install + # + install_method="$install_method : Unix Standard" + if test $dist_type = osx; then + install_method="$install_method : OS X Standard" + fi + datadir=${datadir="$datarootdir/nagios"} + if test $need_web = yes; then + webdir=${webdir="$datadir/html"} + else + webdir="N/A" + fi + if test $dist_type = osx; then + sysconfdir=${sysconfdir="/private/etc"} + else + sysconfdir=${sysconfdir="/etc"} + fi + pkgsysconfdir=${pkgsysconfdir="$sysconfdir/nagios"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir/private"} + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir/lib/$INIT_PROG"} + else + pkglocalstatedir="N/A" + fi + if test "$need_loc" = yes; then + localedir=${localedir="/usr/local/share/locale//LC_MESSAGES/nagios-plugins.mo"} + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/spool/$INIT_PROG"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$libexecdir/brokers"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir/plugins"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + cgibindir=${cgibindir="$libexecdir/cgi-bin"} + else + cgibindir="N/A" + fi + AS_CASE([$dist_type], + [*hp-ux*], + piddir=${piddir="$pkgsysconfdir"} + pipedir=${pipedir="$pkglocalstatedir"} + logdir=${logdir="$pkglocalstatedir/log"}, + + [*], + piddir=${piddir="$localstatedir/run/${INIT_PROG}"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/run/${INIT_PROG}"} + else + pipedir="N/A" + fi + if test $need_log_subdir = yes; then + logdir=${logdir="$localstatedir/log/$INIT_PROG"} + else + logdir=${logdir="$localstatedir/log"} + fi + ) + +elif test $opsys = "bsd"; then + + # + # "Standard" BSD install + # + install_method="$install_method : BSD" + if test $dist_type = freebsd -o $dist_type = openbsd; then + prefix=${prefix="/usr/local"} + exec_prefix=${exec_prefix="/usr/local"} + if test $dist_type = freebsd; then + install_method="$install_method : FreeBSD" + else + install_method="$install_method : OpenBSD" + fi + elif test $dist_type = netbsd; then + prefix=${prefix="/usr/pkg"} + exec_prefix=${exec_prefix="/usr/pkg"} + install_method="$install_method : NetBSD" + fi + datadir=${datadir="$datarootdir/nagios"} + if test $need_web = yes -o $need_cgi = yes; then + if test $dist_type = freebsd; then + webdir=${webdir="$prefix/www/nagios"} + elif test $dist_type = netbsd; then + webdir=${webdir="$prefix/share/nagios"} + elif test $dist_type = openbsd; then + webdir=${webdir="/var/www/nagios"} + fi + else + webdir="N/A" + fi + if test $dist_type = freebsd; then + sysconfdir=${sysconfdir="/usr/local/etc"} + else + sysconfdir=${sysconfdir="/etc"} + fi + pkgsysconfdir=${pkgsysconfdir="$sysconfdir/nagios"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir/private"} + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir/lib/$INIT_PROG"} + else + pkglocalstatedir="N/A" + fi + if test "$need_loc" = yes; then + localedir=${localedir="/usr/local/share/locale//LC_MESSAGES/nagios-plugins.mo"} + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/spool/$INIT_PROG"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$libexecdir/brokers"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir/plugins"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + if test $dist_type = freebsd; then + cgibindir=${cgibindir="$webdir/cgi-bin"} + elif test $dist_type = netbsd; then + cgibindir=${pluginsdir="$libexecdir/cgi-bin"} + elif test $dist_type = openbsd; then + cgibindir=${pluginsdir="/var/www/cgi-bin/nagios"} + fi + else + cgibindir="N/A" + fi + piddir=${piddir="$localstatedir/run/${INIT_PROG}"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/run/${INIT_PROG}"} + else + pipedir="N/A" + fi + if test $need_log_subdir = yes; then + logdir=${logdir="$localstatedir/log/$INIT_PROG"} + else + logdir=${logdir="$localstatedir/log"} + fi + +else + + # + # Unknown install + # + install_method="unknown" + webdir=unknown + pkgsysconfdir=unknown + objsysconfdir=unknown + privatesysconfdir=unknown + logdir=unknown + piddir=unknown + pipedir=unknown + pkglocalstatedir=unknown + spooldir=unknown + brokersdir=unknown + pluginsdir=unknown + cgibindir=unknown + +fi + +eval prefix=$prefix +eval exec_prefix=$exec_prefix +eval bindir=$bindir +eval datarootdir=$datarootdir +eval datadir=$datadir +eval libexecdir=$libexecdir +eval brokersdir=$brokersdir +eval pluginsdir=$pluginsdir +eval cgibindir=$cgibindir +eval localstatedir=$localstatedir +eval pkglocalstatedir=$pkglocalstatedir +eval webdir=$webdir +eval localedir=$localedir +eval sysconfdir=$sysconfdir +eval pkgsysconfdir=$pkgsysconfdir +eval piddir=$piddir + + +# We test systemd first because in case +# someone tries to install Nagios on a +# system with a newer version, that doesn't +# have the defined versions ..we can just +# (hopefully) fall back to SysV +# And if that doesn't work, well... +AS_CASE([$init_type], + + [systemd], + if test -d "/lib/systemd/system"; then + initdir=${initdir="/lib/systemd/system"} + elif test -d "/usr/lib/systemd/system"; then + initdir=${initdir="/usr/lib/systemd/system"} + elif test -d "/usr/local/lib/systemd/system"; then + initdir=${initdir="/usr/local/lib/systemd/system"} + elif test -d "/run/systemd/system"; then + initdir=${initdir="/run/systemd/system"} + elif test -d "/etc/systemd/system"; then + initdir=${initdir="/etc/systemd/system"} + elif test -d "/etc/systemd/user"; then + initdir=${initdir="/etc/systemd/user"} + elif test -d "/run/systemd/user"; then + initdir=${initdir="/run/systemd/user"} + elif test -d "/usr/lib/systemd/user"; then + initdir=${initdir="/usr/lib/systemd/user"} + elif test -d "/usr/local/lib/systemd/user"; then + initdir=${initdir="/usr/local/lib/systemd/user"} + elif test -d "/usr/share/systemd/user"; then + initdir=${initdir="/usr/share/systemd/user"} + elif test -d "/usr/local/share/systemd/user"; then + initdir=${initdir="/usr/local/share/systemd/user"} + elif test -d "$HOME/.config/systemd/user"; then + initdir=${initdir="$HOME/.config/systemd/user"} + elif test -d "$HOME/.local/share/systemd/user"; then + initdir=${initdir="$HOME/.local/share/systemd/user"} + elif test -d "$XDG_CONFIG_HOME/systemd/user/"; then + initdir=${initdir="$XDG_CONFIG_HOME/systemd/user/"} + elif test -d "$XDG_RUNTIME_DIR/systemd/user/"; then + initdir=${initdir="$XDG_RUNTIME_DIR/systemd/user/"} + elif test -d "$XDG_DATA_HOME/systemd/user/"; then + initdir=${initdir="$XDG_DATA_HOME/systemd/user/"} + else + init_type="sysv" + fi + initname=${initname="$INIT_PROG.service"}, +) + +# +# Init scripts/files +# +AS_CASE([$init_type], + + [sysv], + if test $dist_type = "hp-ux"; then + initdir=${initdir="/sbin/init.d"} + else + initdir=${initdir="/etc/init.d"} + fi + initname=${initname="$INIT_PROG"} + initconfdir=${initconfdir="/etc/conf.d"} + initconf=${initconf="$initconfdir/$INIT_PROG"}, + + + [bsd], + if test $dist_type = "aix"; then + initdir=${initdir="/sbin/rc.d/init.d"} + initname=${initname="$INIT_PROG"} + else + initdir=${initdir="/etc/rc.d"} + initname=${initname="rc.$INIT_PROG"} + fi, + + [newbsd], + initdir=${initdir="/usr/local/etc/rc.d"} + initname=${initname="$INIT_PROG"}, + + [gentoo], + initdir=${initdir="/etc/init.d"} + initname=${initname="$INIT_PROG"} + initconfdir=${initconfdir="/etc/init.d"} + initconf=${initconf="$initconfdir/$INIT_PROG"}, + + [openrc], + initdir=${initdir="/etc/init.d"} + initname=${initname="$INIT_PROG"} + initconfdir=${initconfdir="/etc/conf.d"} + initconf=${initconf="$initconfdir/$INIT_PROG"}, + + [smf*], + if test $init_type = smf10; then + initdir=${initdir="/var/svc/manifest/network/nagios"} + else + initdir=${initdir="/lib/svc/manifest/network/nagios"} + fi + initname=${initname="$INIT_PROG.xml"} + initconfdir=unknown + initconf=unknown, + + [upstart], + initdir=${initdir="/etc/init"} + initname=${initname="$INIT_PROG.conf"} + initconfdir=${initconfdir="/etc/default"} + initconf=${initconf="$initconfdir/$INIT_PROG"}, + + [launchd], + initdir=${initdir="/Library/LaunchDaemons"} + initname=${initname="org.nagios.$INIT_PROG.plist"}, +# initconfdir=${initconfdir="/private/etc"} +# initconf=${initconf="$initconfdir/$INIT_PROG"}, + + [systemd], + init_type=systemd, + + [*], + initdir=unknown + initname=unknown) + +# Now see if they supplied any overwriting values +initdiroverridden=no +AC_ARG_WITH(initdir, + AS_HELP_STRING([--with-initdir=], + [overrides path for initdir]), + initdir=$withval + initdiroverridden=yes, + initdir=$initdir +) + +# +# Inetd (per connection) scripts/files +# +AS_CASE([$inetd_type], + [inetd*], + inetddir=${inetddir="/etc"} + inetdname=${inetdname="inetd.conf"}, + + [xinetd], + inetddir=${inetddir="/etc/xinetd.d"} + inetdname=${inetdname="$INIT_PROG"}, + + [systemd], + if test $dist_type = "debian"; then + inetddir=${inetddir="/lib/systemd/system"} + else + inetddir=${inetddir="/usr/lib/systemd/system"} + fi + netdname=${inetdname="$INIT_PROG.socket"}, + + [smf*], + if test $init_type = smf10; then + inetddir=${inetddir="/var/svc/manifest/network/nagios"} + else + inetddir=${inetddir="/lib/svc/manifest/network/nagios"} + fi + inetdname=${inetdname="$INIT_PROG.xml"}, + +# [upstart], +# inetddir=${inetddir="/etc/init.d"} +# inetdname=${inetdname="$INIT_PROG"}, + + [launchd], + inetddir=${inetddir="/Library/LaunchDaemons"} + inetdname=${inetdname="org.nagios.$INIT_PROG.plist"}, + + [*], + inetddir=${inetddir="unknown"} + inetdname=${inetdname="unknown"}) + +AC_MSG_RESULT($install_method) +]) diff --git a/ci/.gitignore b/ci/.gitignore new file mode 100644 index 0000000..ce84331 --- /dev/null +++ b/ci/.gitignore @@ -0,0 +1,6 @@ +*~ +\#* +#pnp4nagios.spec need for github build, dammit +outputs +*.tgz +*.zip diff --git a/ci/maketar.sh b/ci/maketar.sh new file mode 100755 index 0000000..7bd81a0 --- /dev/null +++ b/ci/maketar.sh @@ -0,0 +1,117 @@ +#!/bin/sh +# collect up all the "base" files into a tar file +# exclude the stuff that gets created during a build + +# usage: maketar.sh [version] [release] [releasedate] +# defaults from configure.ac if not provided + +# also makes a zip file + +startdir=$(pwd) +me=$(realpath -e -L $0) +distdir=$(dirname $me) +basedir=$(realpath -e -L $distdir/..) +#echo "distdir $distdir" +#echo "basedir $basedir" + +VERSION=$1 +CVER=$(awk -F, '/^AC_INIT/ {print $2}' $basedir/configure.ac|tr -d '[]') +if test "x${VERSION}" = "x" ; +then + VERSION=$CVER + echo "VERSION ($VERSION) from configure.ac" +elif test "${VERSION}" != "${CVER}" ; +then + echo "$0 version requested $VERSION mismatch configure.ac $CVER" + exit 1 +fi + +RELEASE=$2 +if test "x${RELEASE}" = "x" ; +then + RELEASE=$(awk -F'"' '/^PACKAGE_RELEASE=/{print $2}' $basedir/configure.ac) + echo "RELEASE ($RELEASE) from configure.ac" +fi + +RELDATE=$3 +if test "x${RELDATE}" = "x" ; +then + RELDATE=$(awk -F'"' '/^PKG_REL_DATE=/{print $2}' $basedir/configure.ac) + echo "RELDATE ($RELDATE) from configure.ac" +fi + +echo "Version $VERSION Release $RELEASE Date $RELDATE" + +tdir=$(mktemp -p "/tmp" -d "pnp4nagiosDIST_XXXXXXXX") +#echo "tempdir $tdir" +cd $tdir + +#directory for dist +mkdir pnp4nagios-${VERSION} + + +#populate with symbolic links from main code directory +cd pnp4nagios-${VERSION} + + +for f in AUTHORS ChangeLog ci config.guess config.sub contrib \ + configure aclocal.m4 autoconf-macros \ + pnp4nagios.te pnp4nagios.fc.in \ + COPYING helpers include INSTALL install-sh lib \ + Makefile.in man README.md sample-config scripts \ + share src subst.in summary.in THANKS ; +do +# echo "ln -s $basedir/$f ." + ln -s $basedir/$f . +done + +# update version/release/release_date +cp $basedir/configure.ac . +touch configure.ac +rm ci/pnp4nagios.spec +cp ci/pnp4nagios.spec.in ci/pnp4nagios.spec +sed -i "s/@PACKAGE_VERSION@/${VERSION}/" ci/pnp4nagios.spec +sed -i "s/@PACKAGE_RELEASE@/${RELEASE}/" ci/pnp4nagios.spec +sed -i "s/PACKAGE_RELEASE=\"[^\"]*\"/PACKAGE_RELEASE=\"${RELEASE}\"/" \ + configure.ac +sed -i "s/PKG_REL_DATE=\"[^\"]*\"/PKG_REL_DATE=\"${RELDATE}\"/" \ + configure.ac + + +cd .. + +# any file that is a 'FILE.in' is kept, but the +# resulting 'FILE' is not. +find -L pnp4nagios-${VERSION} -name '*.in' >dist.exclude +sed -i 's/.in$//' dist.exclude +# .. no object files +find -L pnp4nagios-${VERSION} -name '*.o' >>dist.exclude +# .. no binaries +echo "./pnp4nagios-${VERSION}/src/npcd" >>dist.exclude +echo "./pnp4nagios-${VERSION}/src/utils" >>dist.exclude +echo "./pnp4nagios-${VERSION}/src/pnpsender" >>dist.exclude +# ...and no archives in dist, either +find -L pnp4nagios-${VERSION} -name 'pnp4nagios-*.tgz' >>dist.exclude +find -L pnp4nagios-${VERSION} -name 'pnp4nagios-*.zip' >>dist.exclude +find -L pnp4nagios-${VERSION} -path '*/ci/outputs' >>dist.exclude +find -L pnp4nagios-${VERSION} -path '*/ci/outputs/*' >>dist.exclude + +# exception is pnp4nagios.spec +grep -v ci/pnp4nagios.spec dist.exclude >dist.x +mv dist.x dist.exclude + +#GNU makefile 'dist' guideline is that files in the archive +#should have world rx permissions +chmod 0755 -R pnp4nagios-${VERSION} + +#make the tar archive, rereferencing symbolic links +tar chzf pnp4nagios-${VERSION}.tgz -X dist.exclude --exclude-backups pnp4nagios-${VERSION} +mv pnp4nagios-${VERSION}.tgz $distdir + +zip -r -q pnp4nagios-${VERSION}.zip pnp4nagios-${VERSION}/ -x\*~ -x\*\# -x\@dist.exclude +mv pnp4nagios-${VERSION}.zip $distdir +cd $startdir +# clean up temp directory +rm -rf $tdir + + diff --git a/ci/mockbuild.sh b/ci/mockbuild.sh new file mode 100755 index 0000000..f29b1df --- /dev/null +++ b/ci/mockbuild.sh @@ -0,0 +1,44 @@ +#!/bin/sh + +NAME=pnp4nagios +VERSION=$(grep '^Version: ' ${NAME}.spec | cut -d ':' -f2 | awk -F'%' '{print $1}' | tr -d ' ') +RELEASE=$(grep '^Release: ' ${NAME}.spec | cut -d ':' -f2 | awk -F'%' '{print $1}' | tr -d ' ') + +dnf install -y epel-release +dnf install -y mock + +cp ${NAME}.spec ${NAME}.spec.base + +echo "VERSION = ${VERSION}" +echo "RELEASE = ${RELEASE}" +mkdir outputs + +# want to use the plain-vanilla pnp4nagios.spec so that +# it's the one that is included in the srpm + +BREL="${RELEASE}.alma%{?dist}" +sed "/^Release:/c\ +Release: ${BREL}" <${NAME}.spec.base >${NAME}.spec + +config='alma+epel-8-x86_64' +mock -v -r $config \ + --additional-package=selinux-policy-targeted \ + --additional-package=selinux-policy-devel \ + --additional-package=perl-Time-HiRes \ + --additional-package=rrdtool \ + --spec=${NAME}.spec \ + --sources=${NAME}-${VERSION}.tgz \ + --resultdir=./outputs -N + +cp ${NAME}.spec.base ${NAME}.spec +config='fedora-38-x86_64' +mock -v -r $config \ + --additional-package=selinux-policy-targeted \ + --additional-package=selinux-policy-devel \ + --additional-package=perl-Time-HiRes \ + --additional-package=rrdtool \ + --spec=${NAME}.spec \ + --sources=${NAME}-${VERSION}.tgz --resultdir=./outputs -N + + +ls -lR . diff --git a/ci/pnp4nagios.spec b/ci/pnp4nagios.spec new file mode 100755 index 0000000..b3e59a0 --- /dev/null +++ b/ci/pnp4nagios.spec @@ -0,0 +1,498 @@ +%global debug_package %{nil} +%global with_selinux 1 +%global _libdir %{_prefix}/lib64 + +Name: pnp4nagios +Version: 0.6.27 +Release: 5%{?dist} +Summary: Nagios performance data analysis tool + +Group: Applications/System +License: GPLv2 +URL: https://github.com/pnp4nagios/pnp4nagios +Source0: %{name}-%{version}.tgz +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root + +BuildRequires: autoconf, automake, libtool +Requires: rrdtool-perl +Requires: perl(Time::HiRes) +Requires: nagios +Requires: httpd +Requires: rrdtool-perl +Requires: php >= 5.6 +Requires: php-gd +Requires: php-xml +Requires: php-mbstring +# This ensures that the *-selinux package and all it’s dependencies are not pulled +# into containers and other systems that do not use SELinux +%if 0%{?fedora} || 0%{?rhel} >= 8 +Requires: (%{name}-selinux if selinux-policy-%{selinuxtype}) +%else +Requires: %{name}-selinux +%endif + +%if 0%{?rhel} > 6 || 0%{?fedora} > 20 +# For necessary macros +BuildRequires: systemd +%else +Requires(preun): initscripts, chkconfig +Requires(post): initscripts, chkconfig +Requires(postun): initscripts +%endif + + +%description +PNP is an addon to nagios which analyzes performance data provided by plugins +and stores them automatically into RRD-databases. + +%if 0%{?with_selinux} +# SELinux subpackage +%package selinux +Summary: SELinux context for %{name} +BuildArch: noarch +%global selinuxtype targeted +%global modulename pnp4nagios +Requires: selinux-policy-%{selinuxtype} +Requires(post): selinux-policy-%{selinuxtype} +Requires: checkpolicy, selinux-policy-devel, bzip2 +%{?selinux_requires} + +%description selinux +SElinux security policy for %{name}. +%endif + + + + +%prep +%setup -q +#autoreconf +cp contrib/fedora/pnp4nagios-README.fedora README.fedora +sed -i -e 's/^INSTALL_OPTS="-o $nagios_user -g $nagios_grp"/INSTALL_OPTS=""/' \ + configure +sed -i -e '/^\t$(MAKE) strip-post-install$/d' src/Makefile.in + + +%build + + +autoconf +%configure --prefix='' \ + --bindir=%{_sbindir} \ + --libexecdir=%{_libexecdir}/%{name} \ + --sysconfdir=%{_sysconfdir}/%{name} \ + --localstatedir=%{_localstatedir}/log/%{name} \ + --datadir=%{_datadir}/nagios/html/%{name} \ + --datarootdir=%{_datadir}/nagios/html/%{name} \ + %if 0%{with_selinux} + --enable-selinux=yes \ + %else + --with-selinux=no \ + %endif + --with-dist-type=rh \ + --with-init-type=systemd \ + --with-initdir=%{_unitdir} \ + --with-http_server=apache \ + --with-http_server_base=%{_sysconfdir}/httpd \ + --with-http_user=apache \ + --with-http_group=apache \ + --with-kohana_system=%{_datadir}/nagios/html/%{name}/kohana/system \ + --with-nagios_user=nagios \ + --with-nagios_group=nagios \ + --with-nagios_unit=nagios \ + --with-cache_dir=%{_localstatedir}/cache/pnp4nagios \ + --with-perfdata-dir=%{_localstatedir}/lib/%{name} \ + --with-perfdata-spool-dir=%{_localstatedir}/spool/%{name} \ + --with-pnp-logdir=%{_localstatedir}/log/%{name} + +%{__make} %{?_smp_mflags} all + +%install +if [ "$RPM_BUILD_ROOT" != "/" ]; then + rm -rf $RPM_BUILD_ROOT +fi +%{__make} install DESTDIR=$RPM_BUILD_ROOT INSTALL_OPTS="" HTTP_INSTALL_OPTS="" MIX_OPTS="" INIT_OPTS="" NOSAMPLES=1 + +# NO...do NOT remove -sample from filename suffix +#for i in $RPM_BUILD_ROOT/%{_sysconfdir}/pnp4nagios/*-sample \ +# $RPM_BUILD_ROOT/%{_sysconfdir}/pnp4nagios/*/*-sample +#do +# mv ${i} ${i%%-sample} +#done +rm -f $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/config.php.* +rm -f $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/config_local.php +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/config.php +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/*.cfg +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/*.md +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/check_commands/*.cfg-sample + +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/lib/%{name} +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/spool/%{name} +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/log/%{name} +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/log/%{name}/stats +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/log/%{name}/kohana +# +install -Dp -m 0644 contrib/fedora/pnp4nagios.logrotate.conf \ + $RPM_BUILD_ROOT%{_sysconfdir}/logrotate.d/pnp4nagios +# +mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/scripts/services +mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/services +mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/logfiles +install -m 0666 contrib/fedora/logwatch/scripts/services/pnp4nagios \ + $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/scripts/services/ +install -m 0644 contrib/fedora/logwatch/conf/services/pnp4nagios.conf \ + $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/services/ +install -m 0644 contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf \ + $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/logfiles/ +# +#mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/httpd/conf.d +#sed 's|/usr/local/nagios/etc/htpasswd.users|@NAGIOS_PWD@|' \ +# sample-config/httpd.conf \ +# > $RPM_BUILD_ROOT%{_sysconfdir}/httpd/conf.d/%{name}.conf +install -Dp -m 0644 scripts/npcd.service \ + $RPM_BUILD_ROOT%{_unitdir}/npcd.service + +#### broker api changed +#mkdir -p $RPM_BUILD_ROOT%{_libdir}/nagios/brokers +#mv $RPM_BUILD_ROOT%{_libdir}/npcdmod.o \ +# $RPM_BUILD_ROOT%{_libdir}/nagios/brokers/npcdmod.o +## rm -f $RPM_BUILD_ROOT%{_libdir}/%{name}/npcmod.o + +#mv $RPM_BUILD_ROOT/man $RPM_BUILD_ROOT%{_datadir}/ + +# Move kohana to pnp4nagios, there is another kohana in fedore/EPEL, +# which can be installed. +#mv $RPM_BUILD_ROOT%{_libdir}/kohana \ +# $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/kohana +#sed -i 's|%{_libdir}/pnp4nagios/kohana|%{_datadir}/nagios/html/%{name}/kohana|' \ +# $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/index.php +mv $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/install.ignore.not \ + $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/install.ignore +rm $RPM_BUILD_ROOT%{_sysconfdir}/pnp4nagios/background.pdf + +%if 0%{with_selinux} +install -d $RPM_BUILD_ROOT%{_localstatedir}/lib/selinux/tmp/%{name} +install -m 0644 %{name}.fc $RPM_BUILD_ROOT%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.fc +install -m 0644 %{name}.te $RPM_BUILD_ROOT%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.te +%endif + +%package logrotate +Summary: config for rotating pnp4nagios logs +Requires: logrotate +Group: Applications/System + +%description logrotate +config file used by logrotate, set up for pnp4nagios logs + + +%package logwatch +Summary: config and scripts for checking pnp4nagios log files +Requires: logwatch +Group: Applications/System + +%description logwatch +config files and log scanning script for checking pnp4nagios log +files for errors, and flagging them for attention. + + +%clean +#if [ "$RPM_BUILD_ROOT" != "/" ]; then +# rm -rf $RPM_BUILD_ROOT +#fi + + + +%files +%defattr(644,root,root,755) +%doc AUTHORS ChangeLog COPYING +%doc INSTALL README.md README.fedora +%doc THANKS contrib/ +%config(noreplace) %attr(644,root,root) %{_sysconfdir}/%{name}/pages/background-*.pdf +%config(noreplace) %attr(644,root,root) %{_sysconfdir}/%{name}/config.php +%config(noreplace) %attr(644,root,root) %{_sysconfdir}/%{name}/*.cfg +%attr(755,root,root) %{_sysconfdir}/%{name}/SetLogLevels +%attr(755,root,root) %{_sysconfdir}/%{name}/verify_pnp_config +%attr(644,root,root) %{_sysconfdir}/%{name}/README_config.md +%{_sysconfdir}/%{name}/check_commands/* +%{_sysconfdir}/%{name}/contrib/* +%dir %{_sysconfdir}/%{name}/config.d +%dir %attr(744,apache,apache) /var/cache/pnp4nagios +%attr(755,root,root) %{_sysconfdir}/%{name}/config_tools/NagiosCfgMod.pl +%attr(755,root,root) %{_sysconfdir}/%{name}/config_tools/TemplateMod.pl +%{_sysconfdir}/%{name}/config_samples/* +%{_sysconfdir}/%{name}/pnp4nagios_release + +%attr(755,root,root) %{_sbindir}/npcd +%config(noreplace) %attr(644,root,root) %{_unitdir}/npcd.service +%dir %{_libexecdir}/%{name} +%attr(755,root,root) %{_libexecdir}/%{name}/* +%attr(755,nagios,nagios) %{_localstatedir}/lib/%{name} +%dir %attr(755,nagios,nagios) %{_localstatedir}/log/%{name} +%dir %attr(755,nagios,nagios) %{_localstatedir}/log/%{name}/stats +%dir %attr(755,nagios,nagios) %{_localstatedir}/log/%{name}/lock +%dir %attr(755,apache,apache) %{_localstatedir}/log/%{name}/kohana +%dir %attr(755,nagios,nagios) %{_localstatedir}/spool/%{name} +%{_datadir}/nagios/html/%{name}/ +%{_mandir}/man8/* + +%files logrotate +%config(noreplace) %{_sysconfdir}/logrotate.d/%{name} + +%files logwatch +%defattr(644,root,root) +%config(noreplace) %{_sysconfdir}/logwatch/scripts/services/%{name} +%config(noreplace) %{_sysconfdir}/logwatch/conf/services/%{name}.conf +%config(noreplace) %{_sysconfdir}/logwatch/conf/logfiles/%{name}.conf + +%if 0%{?with_selinux} +%files selinux +%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.te +%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.fc + +%pre selinux +%selinux_relabel_pre -s %{selinuxtype} + +%post selinux +pushd %{_localstatedir}/lib/selinux/tmp/%{name} >/dev/null +if semodule -E nagios 2>/dev/null >/dev/null ; +then + semodule_unpackage nagios.pp nagios.mod nagios.fc + for pnpdir in /etc/pnp4nagios /var/log/pnp4nagios /var/lib/pnp4nagios /usr/lib/pnp4nagios + do + if grep -q $pnpdir nagios.fc ; + then + sed -i "\\|$pnpdir|s/^/#/" %{modulename}.fc + fi + done +fi +rm nagios.* +%{__make} %{?_smp_mflags} -f /usr/share/selinux/devel/Makefile all +bzip2 %{name}.pp +install -m 0600 %{modulename}.pp.bz2 %{_datadir}/selinux/packages/%{selinuxtype}/ +popd >/dev/null +rm -rf /var/lib/selinux/tmp/%{name} +%selinux_modules_install -s %{selinuxtype} %{_datadir}/selinux/packages/%{selinuxtype}/%{modulename}.pp.bz2 + +%postun selinux +if [ $1 -eq 0 ]; then + %selinux_modules_uninstall -s %{selinuxtype} %{modulename} +fi + +%posttrans selinux +%selinux_relabel_post -s %{selinuxtype} + +%endif + + +%post +# config sample update +pushd %{_sysconfdir}/pnp4nagios >/dev/null +if [ -e %{_sysconfdir}/nagios/objects/templates.cfg ] ; +then + perl %{_sysconfdir}/pnp4nagios/config_tools/TemplateMod.pl -i %{_sysconfdir}/nagios/objects/templates.cfg -o config_samples/nagios/objects/templates.cfg +fi +if [ -e %{_sysconfdir}/nagios/nagios.cfg ] ; +then + nagver=`nagios --version | gawk '/^Nagios /' | gawk -v RS=' ' '/^[0-9]/'` + perl %{_sysconfdir}/pnp4nagios/config_tools/NagiosCfgMod.pl -i %{_sysconfdir}/nagios/nagios.cfg -m sync -o config_samples/nagios/nagios-sync.cfg -n $nagver + perl %{_sysconfdir}/pnp4nagios/config_tools/NagiosCfgMod.pl -i %{_sysconfdir}/nagios/nagios.cfg -m bulk -o config_samples/nagios/nagios-bulk.cfg -n $nagver + perl %{_sysconfdir}/pnp4nagios/config_tools/NagiosCfgMod.pl -i %{_sysconfdir}/nagios/nagios.cfg -m npcd -o config_samples/nagios/nagios-npcd.cfg -n $nagver +fi +# determine default paper size based on locale +if test -e "/etc/locale.conf" ; then + localefile=/etc/locale.conf +elif test -e "/etc/default/coale" ; then + localefile=/etc/default/locale +else + localefile="" +fi +if test "x${localefile}" = "x" ; then + PAPERSIZE=A4 +else + country=`grep "_..\." -o ${localefile} | sed 's/[\._]//g'` + if echo 'BZ,CA,CL,CO,CR,SV,GT,MX,NI,PA,PH,PR,US,VE' | grep -q ${country} ; then + PAPERSIZE=letter + else + PAPERSIZE=A4 + fi +fi +if [ ! -e %{_sysconfdir}/pnp4nagios/background.pdf ] ; then + ln -rs %{_sysconfdir}/pnp4nagios/pages/background-${PAPERSIZE}.pdf %{_sysconfdir}/pnp4nagios/background.pdf +fi + +popd >/dev/null +%systemd_post npcd.service + +%preun +%systemd_preun npcd.service + +%postun +%systemd_postun_with_restart npcd.service + + + + +%changelog +* Mon Feb 19 2024 Chuck Lane - 0.6.27-6 +- get rpm in sync with 'build-from-source' autoconf setup + +* Thu Nov 23 2023 Chuck Lane - 0.6.27-5 +- add selinux info, improved packaging + +* Mon Sep 11 2023 Chuck Lane - 0.6.27-4 +- change to defining XDG_CACHE_HOME in php, many links in docs fixed + +* Mon Aug 28 2023 Chuck Lane - 0.6.27-3 +- one more pnp8.2 fix, update release number + +* Fri Aug 18 2023 Chuck Lane - 0.6.27-1 +- many pnp8.2 deprecation fixes, get XDG_CACHE_HOME in systemd setup + +* Tue Dec 20 2022 Chuck Lane - 0.6.26-14 +- minor config cleanups, add logwatch and logrotate subpackages + +* Sun Sep 11 2022 Chuck Lane - 0.6.26-3 +- upgrade to php8 + +* Mon Jun 08 2015 Ján ONDREJ (SAL) - 0.6.25-1 +- Update to upstream. + +* Sun Aug 17 2014 Fedora Release Engineering - 0.6.22-3 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_21_22_Mass_Rebuild + +* Fri Jul 04 2014 Ján ONDREJ (SAL) - 0.6.22-2 +- Fix two URL Cross-Site Scripting Vulnerabilities (bz#1115983) + +* Thu Jul 03 2014 Ján ONDREJ (SAL) - 0.6.22-1 +- Update to upstream (fixes XSS flaw in an error page - bz#1115770) + +* Sat Jun 07 2014 Fedora Release Engineering - 0.6.21-5 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_21_Mass_Rebuild + +* Sun Aug 04 2013 Fedora Release Engineering - 0.6.21-4 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_20_Mass_Rebuild + +* Wed Jul 17 2013 Petr Pisar - 0.6.21-3 +- Perl 5.18 rebuild + +* Wed Jul 03 2013 Ján ONDREJ (SAL) - 0.6.21-2 +- Broken configuration for httpd 2.4 fixed (bz#871465) +- fixed dates in changelog items + +* Tue Jun 04 2013 Ján ONDREJ (SAL) - 0.6.21-1 +- update to upstream + +* Sat Mar 23 2013 Ján ONDREJ (SAL) - 0.6.20-2 +- added autoreconf to prep section (bz#926359) + +* Sun Mar 03 2013 Ján ONDREJ (SAL) - 0.6.20-1 +- update to upstream + +* Sun Feb 17 2013 Ján ONDREJ (SAL) - 0.6.19-2 +- updated hostextinfo URL for pnp4nagios 0.6 +- spec file cleanup + +* Sat Feb 16 2013 Ján ONDREJ (SAL) - 0.6.19-1 +- update to upstream + +* Mon Sep 03 2012 Ján ONDREJ (SAL) - 0.6.16-4 +- CVE-2012-3457 - process_perfdata.cfg world readable + +* Thu Apr 05 2012 Ján ONDREJ (SAL) - 0.6.16-2 +- Removed double slashes fro directories (BZ#810212). + +* Thu Nov 24 2011 Ján ONDREJ (SAL) - 0.6.16-1 +- update to upstream + +* Mon Nov 21 2011 Ján ONDREJ (SAL) - 0.6.15-4 +- add back kohana, it's a different version +- added BR: perl(Time::HiRes) + +* Mon Nov 21 2011 Ján ONDREJ (SAL) - 0.6.15-2 +- exclude kohana sources and require php-Kohana package + +* Wed Nov 16 2011 Ján ONDREJ (SAL) - 0.6.15-1 +- update to upstream +- remove /usr/share/nagios/html/pnp4nagios/install.php +- added /etc/httpd/conf.d/pnp4nagios.conf +- removed -sample suffix from rest of sample files + +* Tue Oct 11 2011 Ján ONDREJ (SAL) - 0.6.1-3 +- Updated renaming of "-sample" config files. + +* Wed Sep 14 2011 Ján ONDREJ (SAL) - 0.6.1-1 +- Update to 0.6.1. + +* Tue Sep 13 2011 Ján ONDREJ (SAL) - 0.4.14-7 +- added perl-Time-HiRes to build requires + +* Tue Sep 13 2011 Ján ONDREJ (SAL) - 0.4.14-6 +- rebuilt for EPEL-6 + +* Wed Feb 09 2011 Fedora Release Engineering - 0.4.14-5 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_15_Mass_Rebuild + +* Mon Sep 27 2010 Xavier Bachelot 0.4.14-4 +- Bump release for rebuild. + +* Sun Jul 18 2010 Xavier Bachelot 0.4.14-3 +- Add patch to fix PHP deprecated warnings with PHP 5.3. + (Patch from Jan Ondrej - RHBZ#572851) + +* Thu Aug 27 2009 Xavier Bachelot 0.4.14-2 +- Ship contrib directory as doc. + +* Thu Aug 27 2009 Xavier Bachelot 0.4.14-1 +- Update to 0.4.14 (RHBZ#518069). +- Fix typo in README.fedora (RHBZ#490664). +- Move npcdmod.o to a better place. +- BR: rrdtool-perl + +* Sun Jul 26 2009 Fedora Release Engineering - 0.4.12-4 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_12_Mass_Rebuild + +* Thu Feb 26 2009 Fedora Release Engineering - 0.4.12-3 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_11_Mass_Rebuild + +* Thu Dec 4 2008 Michael Schwendt 0.4.12-2 +- Include /usr/libexec/pnp4nagios directory. + +* Tue Oct 21 2008 Robert M. Albrecht 0.4.12-1 +- Upstream released 0.4.12 + +* Tue Sep 02 2008 Xavier Bachelot 0.4.10-3 +- Fix logrotate conf (RHBZ#460861). + +* Fri Jul 18 2008 Xavier Bachelot 0.4.10-2 +- Fix typo in logrotate conf. + +* Wed Jul 09 2008 Xavier Bachelot 0.4.10-1 +- Update to 0.4.10. + +* Tue May 27 2008 Xavier Bachelot 0.4.9-3 +- Fix npcd init script to use /etc/pnp4nagios. + +* Tue May 27 2008 Xavier Bachelot 0.4.9-2 +- Install npcd unstripped to let rpm do it. + +* Sat May 24 2008 Xavier Bachelot 0.4.9-1 +- Update to 0.4.9. +- Rename to pnp4nagios to match other distros packages. + +* Mon Apr 14 2008 Xavier Bachelot 0.4.7-5 +- Log to file by default. +- Kill pnpsender man page. + +* Mon Apr 07 2008 Xavier Bachelot 0.4.7-4 +- Install inside of nagios html dir. + +* Mon Apr 07 2008 Xavier Bachelot 0.4.7-3 +- Provide properly named config files. +- Add missing Requires:. +- Add a logrotate conf file. + +* Fri Apr 04 2008 Xavier Bachelot 0.4.7-2 +- Add an initscript for npcd. + +* Wed Mar 19 2008 Xavier Bachelot 0.4.7-1 +- Initial build. diff --git a/ci/pnp4nagios.spec.in b/ci/pnp4nagios.spec.in new file mode 100755 index 0000000..afa3b78 --- /dev/null +++ b/ci/pnp4nagios.spec.in @@ -0,0 +1,498 @@ +%global debug_package %{nil} +%global with_selinux 1 +%global _libdir %{_prefix}/lib64 + +Name: pnp4nagios +Version: @PACKAGE_VERSION@ +Release: @PACKAGE_RELEASE@%{?dist} +Summary: Nagios performance data analysis tool + +Group: Applications/System +License: GPLv2 +URL: https://github.com/pnp4nagios/pnp4nagios +Source0: %{name}-%{version}.tgz +BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root + +BuildRequires: autoconf, automake, libtool +Requires: rrdtool-perl +Requires: perl(Time::HiRes) +Requires: nagios +Requires: httpd +Requires: rrdtool-perl +Requires: php >= 5.6 +Requires: php-gd +Requires: php-xml +Requires: php-mbstring +# This ensures that the *-selinux package and all it’s dependencies are not pulled +# into containers and other systems that do not use SELinux +%if 0%{?fedora} || 0%{?rhel} >= 8 +Requires: (%{name}-selinux if selinux-policy-%{selinuxtype}) +%else +Requires: %{name}-selinux +%endif + +%if 0%{?rhel} > 6 || 0%{?fedora} > 20 +# For necessary macros +BuildRequires: systemd +%else +Requires(preun): initscripts, chkconfig +Requires(post): initscripts, chkconfig +Requires(postun): initscripts +%endif + + +%description +PNP is an addon to nagios which analyzes performance data provided by plugins +and stores them automatically into RRD-databases. + +%if 0%{?with_selinux} +# SELinux subpackage +%package selinux +Summary: SELinux context for %{name} +BuildArch: noarch +%global selinuxtype targeted +%global modulename pnp4nagios +Requires: selinux-policy-%{selinuxtype} +Requires(post): selinux-policy-%{selinuxtype} +Requires: checkpolicy, selinux-policy-devel, bzip2 +%{?selinux_requires} + +%description selinux +SElinux security policy for %{name}. +%endif + + + + +%prep +%setup -q +#autoreconf +cp contrib/fedora/pnp4nagios-README.fedora README.fedora +sed -i -e 's/^INSTALL_OPTS="-o $nagios_user -g $nagios_grp"/INSTALL_OPTS=""/' \ + configure +sed -i -e '/^\t$(MAKE) strip-post-install$/d' src/Makefile.in + + +%build + + +autoconf +%configure --prefix='' \ + --bindir=%{_sbindir} \ + --libexecdir=%{_libexecdir}/%{name} \ + --sysconfdir=%{_sysconfdir}/%{name} \ + --localstatedir=%{_localstatedir}/log/%{name} \ + --datadir=%{_datadir}/nagios/html/%{name} \ + --datarootdir=%{_datadir}/nagios/html/%{name} \ + %if 0%{with_selinux} + --enable-selinux=yes \ + %else + --with-selinux=no \ + %endif + --with-dist-type=rh \ + --with-init-type=systemd \ + --with-initdir=%{_unitdir} \ + --with-http_server=apache \ + --with-http_server_base=%{_sysconfdir}/httpd \ + --with-http_user=apache \ + --with-http_group=apache \ + --with-kohana_system=%{_datadir}/nagios/html/%{name}/kohana/system \ + --with-nagios_user=nagios \ + --with-nagios_group=nagios \ + --with-nagios_unit=nagios \ + --with-cache_dir=%{_localstatedir}/cache/pnp4nagios \ + --with-perfdata-dir=%{_localstatedir}/lib/%{name} \ + --with-perfdata-spool-dir=%{_localstatedir}/spool/%{name} \ + --with-pnp-logdir=%{_localstatedir}/log/%{name} + +%{__make} %{?_smp_mflags} all + +%install +if [ "$RPM_BUILD_ROOT" != "/" ]; then + rm -rf $RPM_BUILD_ROOT +fi +%{__make} install DESTDIR=$RPM_BUILD_ROOT INSTALL_OPTS="" HTTP_INSTALL_OPTS="" MIX_OPTS="" INIT_OPTS="" NOSAMPLES=1 + +# NO...do NOT remove -sample from filename suffix +#for i in $RPM_BUILD_ROOT/%{_sysconfdir}/pnp4nagios/*-sample \ +# $RPM_BUILD_ROOT/%{_sysconfdir}/pnp4nagios/*/*-sample +#do +# mv ${i} ${i%%-sample} +#done +rm -f $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/config.php.* +rm -f $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/config_local.php +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/config.php +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/*.cfg +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/*.md +chmod a-x $RPM_BUILD_ROOT%{_sysconfdir}/%{name}/check_commands/*.cfg-sample + +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/lib/%{name} +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/spool/%{name} +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/log/%{name} +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/log/%{name}/stats +mkdir -p $RPM_BUILD_ROOT%{_localstatedir}/log/%{name}/kohana +# +install -Dp -m 0644 contrib/fedora/pnp4nagios.logrotate.conf \ + $RPM_BUILD_ROOT%{_sysconfdir}/logrotate.d/pnp4nagios +# +mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/scripts/services +mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/services +mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/logfiles +install -m 0666 contrib/fedora/logwatch/scripts/services/pnp4nagios \ + $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/scripts/services/ +install -m 0644 contrib/fedora/logwatch/conf/services/pnp4nagios.conf \ + $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/services/ +install -m 0644 contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf \ + $RPM_BUILD_ROOT%{_sysconfdir}/logwatch/conf/logfiles/ +# +#mkdir -p $RPM_BUILD_ROOT%{_sysconfdir}/httpd/conf.d +#sed 's|/usr/local/nagios/etc/htpasswd.users|@NAGIOS_PWD@|' \ +# sample-config/httpd.conf \ +# > $RPM_BUILD_ROOT%{_sysconfdir}/httpd/conf.d/%{name}.conf +install -Dp -m 0644 scripts/npcd.service \ + $RPM_BUILD_ROOT%{_unitdir}/npcd.service + +#### broker api changed +#mkdir -p $RPM_BUILD_ROOT%{_libdir}/nagios/brokers +#mv $RPM_BUILD_ROOT%{_libdir}/npcdmod.o \ +# $RPM_BUILD_ROOT%{_libdir}/nagios/brokers/npcdmod.o +## rm -f $RPM_BUILD_ROOT%{_libdir}/%{name}/npcmod.o + +#mv $RPM_BUILD_ROOT/man $RPM_BUILD_ROOT%{_datadir}/ + +# Move kohana to pnp4nagios, there is another kohana in fedore/EPEL, +# which can be installed. +#mv $RPM_BUILD_ROOT%{_libdir}/kohana \ +# $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/kohana +#sed -i 's|%{_libdir}/pnp4nagios/kohana|%{_datadir}/nagios/html/%{name}/kohana|' \ +# $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/index.php +mv $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/install.ignore.not \ + $RPM_BUILD_ROOT%{_datadir}/nagios/html/%{name}/install.ignore +rm $RPM_BUILD_ROOT%{_sysconfdir}/pnp4nagios/background.pdf + +%if 0%{with_selinux} +install -d $RPM_BUILD_ROOT%{_localstatedir}/lib/selinux/tmp/%{name} +install -m 0644 %{name}.fc $RPM_BUILD_ROOT%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.fc +install -m 0644 %{name}.te $RPM_BUILD_ROOT%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.te +%endif + +%package logrotate +Summary: config for rotating pnp4nagios logs +Requires: logrotate +Group: Applications/System + +%description logrotate +config file used by logrotate, set up for pnp4nagios logs + + +%package logwatch +Summary: config and scripts for checking pnp4nagios log files +Requires: logwatch +Group: Applications/System + +%description logwatch +config files and log scanning script for checking pnp4nagios log +files for errors, and flagging them for attention. + + +%clean +#if [ "$RPM_BUILD_ROOT" != "/" ]; then +# rm -rf $RPM_BUILD_ROOT +#fi + + + +%files +%defattr(644,root,root,755) +%doc AUTHORS ChangeLog COPYING +%doc INSTALL README.md README.fedora +%doc THANKS contrib/ +%config(noreplace) %attr(644,root,root) %{_sysconfdir}/%{name}/pages/background-*.pdf +%config(noreplace) %attr(644,root,root) %{_sysconfdir}/%{name}/config.php +%config(noreplace) %attr(644,root,root) %{_sysconfdir}/%{name}/*.cfg +%attr(755,root,root) %{_sysconfdir}/%{name}/SetLogLevels +%attr(755,root,root) %{_sysconfdir}/%{name}/verify_pnp_config +%attr(644,root,root) %{_sysconfdir}/%{name}/README_config.md +%{_sysconfdir}/%{name}/check_commands/* +%{_sysconfdir}/%{name}/contrib/* +%dir %{_sysconfdir}/%{name}/config.d +%dir %attr(744,apache,apache) /var/cache/pnp4nagios +%attr(755,root,root) %{_sysconfdir}/%{name}/config_tools/NagiosCfgMod.pl +%attr(755,root,root) %{_sysconfdir}/%{name}/config_tools/TemplateMod.pl +%{_sysconfdir}/%{name}/config_samples/* +%{_sysconfdir}/%{name}/pnp4nagios_release + +%attr(755,root,root) %{_sbindir}/npcd +%config(noreplace) %attr(644,root,root) %{_unitdir}/npcd.service +%dir %{_libexecdir}/%{name} +%attr(755,root,root) %{_libexecdir}/%{name}/* +%attr(755,nagios,nagios) %{_localstatedir}/lib/%{name} +%dir %attr(755,nagios,nagios) %{_localstatedir}/log/%{name} +%dir %attr(755,nagios,nagios) %{_localstatedir}/log/%{name}/stats +%dir %attr(755,nagios,nagios) %{_localstatedir}/log/%{name}/lock +%dir %attr(755,apache,apache) %{_localstatedir}/log/%{name}/kohana +%dir %attr(755,nagios,nagios) %{_localstatedir}/spool/%{name} +%{_datadir}/nagios/html/%{name}/ +%{_mandir}/man8/* + +%files logrotate +%config(noreplace) %{_sysconfdir}/logrotate.d/%{name} + +%files logwatch +%defattr(644,root,root) +%config(noreplace) %{_sysconfdir}/logwatch/scripts/services/%{name} +%config(noreplace) %{_sysconfdir}/logwatch/conf/services/%{name}.conf +%config(noreplace) %{_sysconfdir}/logwatch/conf/logfiles/%{name}.conf + +%if 0%{?with_selinux} +%files selinux +%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.te +%{_localstatedir}/lib/selinux/tmp/%{name}/%{modulename}.fc + +%pre selinux +%selinux_relabel_pre -s %{selinuxtype} + +%post selinux +pushd %{_localstatedir}/lib/selinux/tmp/%{name} >/dev/null +if semodule -E nagios 2>/dev/null >/dev/null ; +then + semodule_unpackage nagios.pp nagios.mod nagios.fc + for pnpdir in /etc/pnp4nagios /var/log/pnp4nagios /var/lib/pnp4nagios /usr/lib/pnp4nagios + do + if grep -q $pnpdir nagios.fc ; + then + sed -i "\\|$pnpdir|s/^/#/" %{modulename}.fc + fi + done +fi +rm nagios.* +%{__make} %{?_smp_mflags} -f /usr/share/selinux/devel/Makefile all +bzip2 %{name}.pp +install -m 0600 %{modulename}.pp.bz2 %{_datadir}/selinux/packages/%{selinuxtype}/ +popd >/dev/null +rm -rf /var/lib/selinux/tmp/%{name} +%selinux_modules_install -s %{selinuxtype} %{_datadir}/selinux/packages/%{selinuxtype}/%{modulename}.pp.bz2 + +%postun selinux +if [ $1 -eq 0 ]; then + %selinux_modules_uninstall -s %{selinuxtype} %{modulename} +fi + +%posttrans selinux +%selinux_relabel_post -s %{selinuxtype} + +%endif + + +%post +# config sample update +pushd %{_sysconfdir}/pnp4nagios >/dev/null +if [ -e %{_sysconfdir}/nagios/objects/templates.cfg ] ; +then + perl %{_sysconfdir}/pnp4nagios/config_tools/TemplateMod.pl -i %{_sysconfdir}/nagios/objects/templates.cfg -o config_samples/nagios/objects/templates.cfg +fi +if [ -e %{_sysconfdir}/nagios/nagios.cfg ] ; +then + nagver=`nagios --version | gawk '/^Nagios /' | gawk -v RS=' ' '/^[0-9]/'` + perl %{_sysconfdir}/pnp4nagios/config_tools/NagiosCfgMod.pl -i %{_sysconfdir}/nagios/nagios.cfg -m sync -o config_samples/nagios/nagios-sync.cfg -n $nagver + perl %{_sysconfdir}/pnp4nagios/config_tools/NagiosCfgMod.pl -i %{_sysconfdir}/nagios/nagios.cfg -m bulk -o config_samples/nagios/nagios-bulk.cfg -n $nagver + perl %{_sysconfdir}/pnp4nagios/config_tools/NagiosCfgMod.pl -i %{_sysconfdir}/nagios/nagios.cfg -m npcd -o config_samples/nagios/nagios-npcd.cfg -n $nagver +fi +# determine default paper size based on locale +if test -e "/etc/locale.conf" ; then + localefile=/etc/locale.conf +elif test -e "/etc/default/coale" ; then + localefile=/etc/default/locale +else + localefile="" +fi +if test "x${localefile}" = "x" ; then + PAPERSIZE=A4 +else + country=`grep "_..\." -o ${localefile} | sed 's/[\._]//g'` + if echo 'BZ,CA,CL,CO,CR,SV,GT,MX,NI,PA,PH,PR,US,VE' | grep -q ${country} ; then + PAPERSIZE=letter + else + PAPERSIZE=A4 + fi +fi +if [ ! -e %{_sysconfdir}/pnp4nagios/background.pdf ] ; then + ln -rs %{_sysconfdir}/pnp4nagios/pages/background-${PAPERSIZE}.pdf %{_sysconfdir}/pnp4nagios/background.pdf +fi + +popd >/dev/null +%systemd_post npcd.service + +%preun +%systemd_preun npcd.service + +%postun +%systemd_postun_with_restart npcd.service + + + + +%changelog +* Mon Feb 19 2024 Chuck Lane - 0.6.27-6 +- get rpm in sync with 'build-from-source' autoconf setup + +* Thu Nov 23 2023 Chuck Lane - 0.6.27-5 +- add selinux info, improved packaging + +* Mon Sep 11 2023 Chuck Lane - 0.6.27-4 +- change to defining XDG_CACHE_HOME in php, many links in docs fixed + +* Mon Aug 28 2023 Chuck Lane - 0.6.27-3 +- one more pnp8.2 fix, update release number + +* Fri Aug 18 2023 Chuck Lane - 0.6.27-1 +- many pnp8.2 deprecation fixes, get XDG_CACHE_HOME in systemd setup + +* Tue Dec 20 2022 Chuck Lane - 0.6.26-14 +- minor config cleanups, add logwatch and logrotate subpackages + +* Sun Sep 11 2022 Chuck Lane - 0.6.26-3 +- upgrade to php8 + +* Mon Jun 08 2015 Ján ONDREJ (SAL) - 0.6.25-1 +- Update to upstream. + +* Sun Aug 17 2014 Fedora Release Engineering - 0.6.22-3 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_21_22_Mass_Rebuild + +* Fri Jul 04 2014 Ján ONDREJ (SAL) - 0.6.22-2 +- Fix two URL Cross-Site Scripting Vulnerabilities (bz#1115983) + +* Thu Jul 03 2014 Ján ONDREJ (SAL) - 0.6.22-1 +- Update to upstream (fixes XSS flaw in an error page - bz#1115770) + +* Sat Jun 07 2014 Fedora Release Engineering - 0.6.21-5 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_21_Mass_Rebuild + +* Sun Aug 04 2013 Fedora Release Engineering - 0.6.21-4 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_20_Mass_Rebuild + +* Wed Jul 17 2013 Petr Pisar - 0.6.21-3 +- Perl 5.18 rebuild + +* Wed Jul 03 2013 Ján ONDREJ (SAL) - 0.6.21-2 +- Broken configuration for httpd 2.4 fixed (bz#871465) +- fixed dates in changelog items + +* Tue Jun 04 2013 Ján ONDREJ (SAL) - 0.6.21-1 +- update to upstream + +* Sat Mar 23 2013 Ján ONDREJ (SAL) - 0.6.20-2 +- added autoreconf to prep section (bz#926359) + +* Sun Mar 03 2013 Ján ONDREJ (SAL) - 0.6.20-1 +- update to upstream + +* Sun Feb 17 2013 Ján ONDREJ (SAL) - 0.6.19-2 +- updated hostextinfo URL for pnp4nagios 0.6 +- spec file cleanup + +* Sat Feb 16 2013 Ján ONDREJ (SAL) - 0.6.19-1 +- update to upstream + +* Mon Sep 03 2012 Ján ONDREJ (SAL) - 0.6.16-4 +- CVE-2012-3457 - process_perfdata.cfg world readable + +* Thu Apr 05 2012 Ján ONDREJ (SAL) - 0.6.16-2 +- Removed double slashes fro directories (BZ#810212). + +* Thu Nov 24 2011 Ján ONDREJ (SAL) - 0.6.16-1 +- update to upstream + +* Mon Nov 21 2011 Ján ONDREJ (SAL) - 0.6.15-4 +- add back kohana, it's a different version +- added BR: perl(Time::HiRes) + +* Mon Nov 21 2011 Ján ONDREJ (SAL) - 0.6.15-2 +- exclude kohana sources and require php-Kohana package + +* Wed Nov 16 2011 Ján ONDREJ (SAL) - 0.6.15-1 +- update to upstream +- remove /usr/share/nagios/html/pnp4nagios/install.php +- added /etc/httpd/conf.d/pnp4nagios.conf +- removed -sample suffix from rest of sample files + +* Tue Oct 11 2011 Ján ONDREJ (SAL) - 0.6.1-3 +- Updated renaming of "-sample" config files. + +* Wed Sep 14 2011 Ján ONDREJ (SAL) - 0.6.1-1 +- Update to 0.6.1. + +* Tue Sep 13 2011 Ján ONDREJ (SAL) - 0.4.14-7 +- added perl-Time-HiRes to build requires + +* Tue Sep 13 2011 Ján ONDREJ (SAL) - 0.4.14-6 +- rebuilt for EPEL-6 + +* Wed Feb 09 2011 Fedora Release Engineering - 0.4.14-5 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_15_Mass_Rebuild + +* Mon Sep 27 2010 Xavier Bachelot 0.4.14-4 +- Bump release for rebuild. + +* Sun Jul 18 2010 Xavier Bachelot 0.4.14-3 +- Add patch to fix PHP deprecated warnings with PHP 5.3. + (Patch from Jan Ondrej - RHBZ#572851) + +* Thu Aug 27 2009 Xavier Bachelot 0.4.14-2 +- Ship contrib directory as doc. + +* Thu Aug 27 2009 Xavier Bachelot 0.4.14-1 +- Update to 0.4.14 (RHBZ#518069). +- Fix typo in README.fedora (RHBZ#490664). +- Move npcdmod.o to a better place. +- BR: rrdtool-perl + +* Sun Jul 26 2009 Fedora Release Engineering - 0.4.12-4 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_12_Mass_Rebuild + +* Thu Feb 26 2009 Fedora Release Engineering - 0.4.12-3 +- Rebuilt for https://fedoraproject.org/wiki/Fedora_11_Mass_Rebuild + +* Thu Dec 4 2008 Michael Schwendt 0.4.12-2 +- Include /usr/libexec/pnp4nagios directory. + +* Tue Oct 21 2008 Robert M. Albrecht 0.4.12-1 +- Upstream released 0.4.12 + +* Tue Sep 02 2008 Xavier Bachelot 0.4.10-3 +- Fix logrotate conf (RHBZ#460861). + +* Fri Jul 18 2008 Xavier Bachelot 0.4.10-2 +- Fix typo in logrotate conf. + +* Wed Jul 09 2008 Xavier Bachelot 0.4.10-1 +- Update to 0.4.10. + +* Tue May 27 2008 Xavier Bachelot 0.4.9-3 +- Fix npcd init script to use /etc/pnp4nagios. + +* Tue May 27 2008 Xavier Bachelot 0.4.9-2 +- Install npcd unstripped to let rpm do it. + +* Sat May 24 2008 Xavier Bachelot 0.4.9-1 +- Update to 0.4.9. +- Rename to pnp4nagios to match other distros packages. + +* Mon Apr 14 2008 Xavier Bachelot 0.4.7-5 +- Log to file by default. +- Kill pnpsender man page. + +* Mon Apr 07 2008 Xavier Bachelot 0.4.7-4 +- Install inside of nagios html dir. + +* Mon Apr 07 2008 Xavier Bachelot 0.4.7-3 +- Provide properly named config files. +- Add missing Requires:. +- Add a logrotate conf file. + +* Fri Apr 04 2008 Xavier Bachelot 0.4.7-2 +- Add an initscript for npcd. + +* Wed Mar 19 2008 Xavier Bachelot 0.4.7-1 +- Initial build. diff --git a/configure b/configure index bd70687..de66cb0 100755 --- a/configure +++ b/configure @@ -1,84 +1,104 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.61 for pnp 0.6.26. +# Generated by GNU Autoconf 2.71 for pnp4nagios 0.6.27. # # Report bugs to . # -# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -# 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +# +# Copyright (C) 1992-1996, 1998-2017, 2020-2021 Free Software Foundation, +# Inc. +# +# # This configure script is free software; the Free Software Foundation # gives unlimited permission to copy, distribute and modify it. -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +as_nop=: +if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 +then : emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; +else $as_nop + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi +# Reset variables that may have inherited troublesome values from +# the environment. -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: - fi - rm -f conf$$.sh -fi - -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) +# IFS needs to be set, to space, tab, and newline, in precisely that order. +# (If _AS_PATH_WALK were called with IFS unset, it would have the +# side effect of setting IFS to empty, thus disabling word splitting.) +# Quoting is to prevent editors from complaining about space-tab. as_nl=' ' +export as_nl IFS=" "" $as_nl" +PS1='$ ' +PS2='> ' +PS4='+ ' + +# Ensure predictable behavior from utilities with locale-dependent output. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# We cannot yet rely on "unset" to work, but we need these variables +# to be unset--not just set to an empty or harmless value--now, to +# avoid bugs in old shells (e.g. pre-3.0 UWIN ksh). This construct +# also avoids known problems related to "unset" and subshell syntax +# in other old shells (e.g. bash 2.01 and pdksh 5.2.14). +for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH +do eval test \${$as_var+y} \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done + +# Ensure that fds 0, 1, and 2 are open. +if (exec 3>&0) 2>/dev/null; then :; else exec 0&1) 2>/dev/null; then :; else exec 1>/dev/null; fi +if (exec 3>&2) ; then :; else exec 2>/dev/null; fi + +# The user is always right. +if ${PATH_SEPARATOR+false} :; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + # Find who we are. Look in the path if we contain no directory separator. -case $0 in +as_myself= +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + test -r "$as_dir$0" && as_myself=$as_dir$0 && break + done IFS=$as_save_IFS ;; @@ -89,32 +109,336 @@ if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var -done -PS1='$ ' -PS2='> ' -PS4='+ ' -# NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var +# Use a proper internal environment variable to ensure we don't fall + # into an infinite loop, continuously re-executing ourselves. + if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then + _as_can_reexec=no; export _as_can_reexec; + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 fi -done + # We don't want this to propagate to other subprocesses. + { _as_can_reexec=; unset _as_can_reexec;} +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="as_nop=: +if test \${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 +then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else \$as_nop + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ) +then : + +else \$as_nop + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1 +blah=\$(echo \$(echo blah)) +test x\"\$blah\" = xblah || exit 1 +test -x / || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null +then : + as_have_required=yes +else $as_nop + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null +then : + +else $as_nop + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + as_run=a "$as_shell" -c "$as_bourne_compatible""$as_required" 2>/dev/null +then : + CONFIG_SHELL=$as_shell as_have_required=yes + if as_run=a "$as_shell" -c "$as_bourne_compatible""$as_suggested" 2>/dev/null +then : + break 2 +fi +fi + done;; + esac + as_found=false +done +IFS=$as_save_IFS +if $as_found +then : + +else $as_nop + if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + as_run=a "$SHELL" -c "$as_bourne_compatible""$as_required" 2>/dev/null +then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi +fi + + + if test "x$CONFIG_SHELL" != x +then : + export CONFIG_SHELL + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 +fi + + if test x$as_have_required = xno +then : + printf "%s\n" "$0: This script requires a shell more modern than all" + printf "%s\n" "$0: the shells that I found on your system." + if test ${ZSH_VERSION+y} ; then + printf "%s\n" "$0: In particular, zsh $ZSH_VERSION has bugs and should" + printf "%s\n" "$0: be upgraded to zsh 4.3.4 or later." + else + printf "%s\n" "$0: Please tell bug-autoconf@gnu.org and +$0: pnp4nagios-devel@lists.sourceforge.net about your +$0: system, including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit +# as_fn_nop +# --------- +# Do nothing but, unlike ":", preserve the value of $?. +as_fn_nop () +{ + return $? +} +as_nop=as_fn_nop + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null +then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else $as_nop + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null +then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else $as_nop + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + +# as_fn_nop +# --------- +# Do nothing but, unlike ":", preserve the value of $?. +as_fn_nop () +{ + return $? +} +as_nop=as_fn_nop + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + printf "%s\n" "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error -# Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -128,13 +452,17 @@ else as_basename=false fi +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi -# Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +printf "%s\n" X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -149,294 +477,19 @@ echo X/"$0" | } s/.*/./; q'` -# CDPATH. -$as_unset CDPATH +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits -if test "x$CONFIG_SHELL" = x; then - if (eval ":") 2>/dev/null; then - as_have_required=yes -else - as_have_required=no -fi - - if test $as_have_required = yes && (eval ": -(as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} - -exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi - -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi - -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : -else - exitcode=1 - echo positional parameters were not saved. -fi - -test \$exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=\$LINENO - as_lineno_2=\$LINENO - test \"x\$as_lineno_1\" != \"x\$as_lineno_2\" && - test \"x\`expr \$as_lineno_1 + 1\`\" = \"x\$as_lineno_2\") || { (exit 1); exit 1; } -") 2> /dev/null; then - : -else - as_candidate_shells= - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - case $as_dir in - /*) - for as_base in sh bash ksh sh5; do - as_candidate_shells="$as_candidate_shells $as_dir/$as_base" - done;; - esac -done -IFS=$as_save_IFS - - - for as_shell in $as_candidate_shells $SHELL; do - # Try only shells that exist, to save several forks. - if { test -f "$as_shell" || test -f "$as_shell.exe"; } && - { ("$as_shell") 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - -fi - - -: -_ASEOF -}; then - CONFIG_SHELL=$as_shell - as_have_required=yes - if { "$as_shell" 2> /dev/null <<\_ASEOF -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then - emulate sh - NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which - # is contrary to our usage. Disable this feature. - alias -g '${1+"$@"}'='"$@"' - setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; -esac - -fi - - -: -(as_func_return () { - (exit $1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} - -exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi - -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi - -if ( set x; as_func_ret_success y && test x = "$1" ); then - : -else - exitcode=1 - echo positional parameters were not saved. -fi - -test $exitcode = 0) || { (exit 1); exit 1; } - -( - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2") || { (exit 1); exit 1; } - -_ASEOF -}; then - break -fi - -fi - - done - - if test "x$CONFIG_SHELL" != x; then - for as_var in BASH_ENV ENV - do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var - done - export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} -fi - - - if test $as_have_required = no; then - echo This script requires a shell more modern than all the - echo shells that I found on your system. Please install a - echo modern shell, or manually run the script under such a - echo shell if you do have one. - { (exit 1); exit 1; } -fi - - -fi - -fi - - - -(eval "as_func_return () { - (exit \$1) -} -as_func_success () { - as_func_return 0 -} -as_func_failure () { - as_func_return 1 -} -as_func_ret_success () { - return 0 -} -as_func_ret_failure () { - return 1 -} - -exitcode=0 -if as_func_success; then - : -else - exitcode=1 - echo as_func_success failed. -fi - -if as_func_failure; then - exitcode=1 - echo as_func_failure succeeded. -fi - -if as_func_ret_success; then - : -else - exitcode=1 - echo as_func_ret_success failed. -fi - -if as_func_ret_failure; then - exitcode=1 - echo as_func_ret_failure succeeded. -fi - -if ( set x; as_func_ret_success y && test x = \"\$1\" ); then - : -else - exitcode=1 - echo positional parameters were not saved. -fi - -test \$exitcode = 0") || { - echo No shell found that supports shell functions. - echo Please tell autoconf@gnu.org about your system, - echo including any error possibly output before this - echo message -} - - - - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) sed -n ' p /[$]LINENO/= @@ -453,9 +506,12 @@ test \$exitcode = 0") || { s/-\n.*// ' >$as_me.lineno && chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } + { printf "%s\n" "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + # If we had to re-execute with $CONFIG_SHELL, we're ensured to have + # already done that, so ensure we don't try to do so again and fall + # in an infinite loop. This has already happened in practice. + _as_can_reexec=no; export _as_can_reexec # Don't try to exec as it changes $[0], causing all sort of problems # (the dirname of $[0] is not the place where we might find the # original and so on. Autoconf is especially sensitive to this). @@ -465,83 +521,65 @@ test \$exitcode = 0") || { } -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - +# Determine whether it's possible to make 'echo' print without a newline. +# These variables are no longer used directly by Autoconf, but are AC_SUBSTed +# for compatibility with existing Makefiles. ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi +# For backward compatibility with old third-party macros, we provide +# the shell variables $as_echo and $as_echo_n. New code should use +# AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively. +as_echo='printf %s\n' +as_echo_n='printf %s' + rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi else - as_ln_s='cp -p' + as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null if mkdir -p . 2>/dev/null; then - as_mkdir_p=: + as_mkdir_p='mkdir -p "$as_dir"' else test -d ./-p && rmdir ./-p as_mkdir_p=false fi -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x +as_test_x='test -x' +as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" @@ -550,11 +588,11 @@ as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - -exec 7<&0 &1 +test -n "$DJDIR" || exec 7<&0 &1 # Name of the host. -# hostname on some systems (SVR3.2, Linux) returns a bogus exit status, +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, # so uname gets run too. ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` @@ -569,145 +607,243 @@ cross_compiling=no subdirs= MFLAGS= MAKEFLAGS= -SHELL=${CONFIG_SHELL-/bin/sh} # Identity of this package. -PACKAGE_NAME='pnp' -PACKAGE_TARNAME='pnp' -PACKAGE_VERSION='0.6.26' -PACKAGE_STRING='pnp 0.6.26' +PACKAGE_NAME='pnp4nagios' +PACKAGE_TARNAME='pnp4nagios' +PACKAGE_VERSION='0.6.27' +PACKAGE_STRING='pnp4nagios 0.6.27' PACKAGE_BUGREPORT='pnp4nagios-devel@lists.sourceforge.net' +PACKAGE_URL='https://github.com/pnp4nagios/pnp4nagios' ac_unique_file="src/" ac_default_prefix=/usr/local/pnp4nagios # Factoring default headers for most tests. ac_includes_default="\ -#include -#ifdef HAVE_SYS_TYPES_H -# include +#include +#ifdef HAVE_STDIO_H +# include #endif -#ifdef HAVE_SYS_STAT_H -# include -#endif -#ifdef STDC_HEADERS +#ifdef HAVE_STDLIB_H # include -# include -#else -# ifdef HAVE_STDLIB_H -# include -# endif #endif #ifdef HAVE_STRING_H -# if !defined STDC_HEADERS && defined HAVE_MEMORY_H -# include -# endif # include #endif -#ifdef HAVE_STRINGS_H -# include -#endif #ifdef HAVE_INTTYPES_H # include #endif #ifdef HAVE_STDINT_H # include #endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif #ifdef HAVE_UNISTD_H # include #endif" -ac_subst_vars='SHELL -PATH_SEPARATOR -PACKAGE_NAME -PACKAGE_TARNAME -PACKAGE_VERSION -PACKAGE_STRING -PACKAGE_BUGREPORT -exec_prefix -prefix -program_transform_name -bindir -sbindir -libexecdir -datarootdir -datadir -sysconfdir -sharedstatedir -localstatedir -includedir -oldincludedir -docdir -infodir -htmldir -dvidir -pdfdir -psdir -libdir -localedir -mandir -DEFS -ECHO_C -ECHO_N -ECHO_T -LIBS -build_alias -host_alias -target_alias -PKG_NAME -PKG_VERSION -PKG_HOME_URL -PKG_REL_DATE -ac_configure_args -XML_STRUCTURE_VERSION -INSTALL_PROGRAM -INSTALL_SCRIPT -INSTALL_DATA -INSTALL -build -build_cpu -build_vendor -build_os -host -host_cpu -host_vendor -host_os -CC -CFLAGS -LDFLAGS -CPPFLAGS -ac_ct_CC -EXEEXT -OBJEXT -SET_MAKE -STRIP -CP -CPP -GREP -EGREP -LIBOBJS -KOHANA -KOHANA_SYSTEM -nagios_user -nagios_grp -INSTALL_OPTS -PERL -PERL_LIB_PATH -RRDTOOL -PERFDATA_LOG -PERFDATA_DIR -PERFDATA_SPOOL_DIR -DEBUG -HTTPD_CONF -BASE_URL -init_dir -pnpsender_name -npcd_name -pp_pl_name -MOD_CFLAGS +ac_header_c_list= +ac_func_c_list= +ac_subst_vars='LTLIBOBJS MOD_LDFLAGS +MOD_CFLAGS +PAPERSIZE +PNP_URL +CACHE_DIR +HTTP_CONFDIR +HTTP_INSTALL_OPTS +HTTP_GROUP +HTTP_USER +HTTP_UNIT +HTTP_SERVER +pp_pl_name +npcd_name +pnpsender_name +PERFDATA_SPOOL_DIR +PERFDATA_DIR +PERFDATA_STATS +PERFDATA_LOG +PNP_LOGDIR +INSTALL_OPTS +nagios_grp +nagios_user +NAGIOS_OBJ +NAGIOS_PWD +NAGIOS_UNIT +NAGIOS_VER +NAGIOS_CFG +SE +SELINUX_DEVELDIR +SELINUX +RRDTOOL +INIT_OPTS +root_grp +CPP +LIBOBJS +KOHANA_SYSTEM +KOHANA RRDS -LTLIBOBJS' +PERL_LIB_PATH +PERL +CP +LN_S +SED +AWK +EGREP +GREP +STRIP +SET_MAKE +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +INSTALL_SUFFIX +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +bsd_enable +src_tmpfile +src_inetd +src_init +subsyslockfile +subsyslockdir +tmpfilesd +inetddir +initdiroverridden +initdir +spooldir +pipedir +piddir +logdir +pkglocalstatedir +privatesysconfdir +webdir +cgibindir +brokersdir +pluginsdir +inetdname +initname +objsysconfdir +pkgsysconfdir +INIT_PERM +init_type +dist_ver +dist_type +arch +opsys +target_os +target_vendor +target_cpu +target +host_os +host_vendor +host_cpu +host +build_os +build_vendor +build_cpu +build +DEBUG_LEVEL +XML_STRUCTURE_VERSION +ac_configure_args +PKG_REL_DATE +PACKAGE_RELEASE +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +runstatedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' ac_subst_files='' +ac_user_opts=' +enable_option_checking +with_debug_level +with_opsys +with_dist_type +with_init_type +enable_install_method +enable_showdirs_only +with_pkgsysconfdir +with_objsysconfdir +with_privatesysconfdir +with_webdir +with_pluginsdir +with_brokersdir +with_cgibindir +with_logdir +with_piddir +with_pipedir +with_initdir +with_libdir +with_perl_lib_path +with_kohana +with_kohana_system +with_root_group +with_rrdtool +enable_selinux +with_selinux_develdir +with_nagios_cfg +with_nagios_version +with_nagios_unit +with_nagios_pwd +with_nagios_objects +with_nagios_user +with_nagios_group +with_pnp_logdir +with_perfdata_dir +with_perfdata_spool_dir +with_http_server +with_http_server_base +with_http_user +with_http_group +with_http_confdir +with_cache_dir +with_pnp_url +with_papersize +' ac_precious_vars='build_alias host_alias target_alias @@ -722,6 +858,8 @@ CPP' # Initialize some variables set by options. ac_init_help= ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= # The variables have the same names as the options, with # dashes changed to underlines. cache_file=/dev/null @@ -753,6 +891,7 @@ datadir='${datarootdir}' sysconfdir='${prefix}/etc' sharedstatedir='${prefix}/com' localstatedir='${prefix}/var' +runstatedir='${localstatedir}/run' includedir='${prefix}/include' oldincludedir='/usr/include' docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' @@ -777,12 +916,11 @@ do fi case $ac_option in - *=*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; - *) ac_optarg=yes ;; + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; esac - # Accept the important Cygnus configure options, so we can diagnose typos. - case $ac_dashdash$ac_option in --) ac_dashdash=yes ;; @@ -820,13 +958,20 @@ do datarootdir=$ac_optarg ;; -disable-* | --disable-*) - ac_feature=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 - { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=no ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; -docdir | --docdir | --docdi | --doc | --do) ac_prev=docdir ;; @@ -839,13 +984,20 @@ do dvidir=$ac_optarg ;; -enable-* | --enable-*) - ac_feature=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_feature" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid feature name: $ac_feature" >&2 - { (exit 1); exit 1; }; } - ac_feature=`echo $ac_feature | sed 's/[-.]/_/g'` - eval enable_$ac_feature=\$ac_optarg ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ @@ -990,6 +1142,15 @@ do | -silent | --silent | --silen | --sile | --sil) silent=yes ;; + -runstatedir | --runstatedir | --runstatedi | --runstated \ + | --runstate | --runstat | --runsta | --runst | --runs \ + | --run | --ru | --r) + ac_prev=runstatedir ;; + -runstatedir=* | --runstatedir=* | --runstatedi=* | --runstated=* \ + | --runstate=* | --runstat=* | --runsta=* | --runst=* | --runs=* \ + | --run=* | --ru=* | --r=*) + runstatedir=$ac_optarg ;; + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) ac_prev=sbindir ;; -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ @@ -1036,22 +1197,36 @@ do ac_init_version=: ;; -with-* | --with-*) - ac_package=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 - { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=\$ac_optarg ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; -without-* | --without-*) - ac_package=`expr "x$ac_option" : 'x-*without-\(.*\)'` + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. - expr "x$ac_package" : ".*[^-._$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid package name: $ac_package" >&2 - { (exit 1); exit 1; }; } - ac_package=`echo $ac_package | sed 's/[-.]/_/g'` - eval with_$ac_package=no ;; + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: \`$ac_useropt'" + ac_useropt_orig=$ac_useropt + ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; --x) # Obsolete; use --with-x. @@ -1071,26 +1246,26 @@ do | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) { echo "$as_me: error: unrecognized option: $ac_option -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" ;; *=*) ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` # Reject names that are not valid shell variable names. - expr "x$ac_envvar" : ".*[^_$as_cr_alnum]" >/dev/null && - { echo "$as_me: error: invalid variable name: $ac_envvar" >&2 - { (exit 1); exit 1; }; } + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; *) # FIXME: should be removed in autoconf 3.0. - echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + printf "%s\n" "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && - echo "$as_me: WARNING: invalid host type: $ac_option" >&2 - : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} + printf "%s\n" "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac @@ -1098,23 +1273,36 @@ done if test -n "$ac_prev"; then ac_option=--`echo $ac_prev | sed 's/_/-/g'` - { echo "$as_me: error: missing argument to $ac_option" >&2 - { (exit 1); exit 1; }; } + as_fn_error $? "missing argument to $ac_option" fi -# Be sure to have absolute directory names. +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ datadir sysconfdir sharedstatedir localstatedir includedir \ oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ - libdir localedir mandir + libdir localedir mandir runstatedir do eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. case $ac_val in [\\/$]* | ?:[\\/]* ) continue;; NONE | '' ) case $ac_var in *prefix ) continue;; esac;; esac - { echo "$as_me: error: expected an absolute directory name for --$ac_var: $ac_val" >&2 - { (exit 1); exit 1; }; } + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done # There might be people who depend on the old broken behavior: `$host' @@ -1128,8 +1316,6 @@ target=$target_alias if test "x$host_alias" != x; then if test "x$build_alias" = x; then cross_compiling=maybe - echo "$as_me: WARNING: If you wanted to set the --build type, don't use --host. - If a cross compiler is detected then cross compile mode will be used." >&2 elif test "x$build_alias" != "x$host_alias"; then cross_compiling=yes fi @@ -1144,23 +1330,21 @@ test "$silent" = yes && exec 6>/dev/null ac_pwd=`pwd` && test -n "$ac_pwd" && ac_ls_di=`ls -di .` && ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || - { echo "$as_me: error: Working directory cannot be determined" >&2 - { (exit 1); exit 1; }; } + as_fn_error $? "working directory cannot be determined" test "X$ac_ls_di" = "X$ac_pwd_ls_di" || - { echo "$as_me: error: pwd does not report name of working directory" >&2 - { (exit 1); exit 1; }; } + as_fn_error $? "pwd does not report name of working directory" # Find the source files, if location was not specified. if test -z "$srcdir"; then ac_srcdir_defaulted=yes # Try the directory containing this script, then the parent directory. - ac_confdir=`$as_dirname -- "$0" || -$as_expr X"$0" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$0" : 'X\(//\)[^/]' \| \ - X"$0" : 'X\(//\)$' \| \ - X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X"$0" | + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$as_myself" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -1187,13 +1371,11 @@ else fi if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." - { echo "$as_me: error: cannot find sources ($ac_unique_file) in $srcdir" >&2 - { (exit 1); exit 1; }; } + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" ac_abs_confdir=`( - cd "$srcdir" && test -r "./$ac_unique_file" || { echo "$as_me: error: $ac_msg" >&2 - { (exit 1); exit 1; }; } + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` # When building in place, set srcdir=. if test "$ac_abs_confdir" = "$ac_pwd"; then @@ -1219,7 +1401,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures pnp 0.6.26 to adapt to many kinds of systems. +\`configure' configures pnp4nagios 0.6.27 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1233,7 +1415,7 @@ Configuration: --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit - -q, --quiet, --silent do not print \`checking...' messages + -q, --quiet, --silent do not print \`checking ...' messages --cache-file=FILE cache test results in FILE [disabled] -C, --config-cache alias for \`--cache-file=config.cache' -n, --no-create do not create output files @@ -1241,9 +1423,9 @@ Configuration: Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX - [$ac_default_prefix] + [$ac_default_prefix] --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX - [PREFIX] + [PREFIX] By default, \`make install' will install all the files in \`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify @@ -1253,25 +1435,26 @@ for instance \`--prefix=\$HOME'. For better control, use the options below. Fine tuning of the installation directories: - --bindir=DIR user executables [EPREFIX/bin] - --sbindir=DIR system admin executables [EPREFIX/sbin] - --libexecdir=DIR program executables [EPREFIX/libexec] - --sysconfdir=DIR read-only single-machine data [PREFIX/etc] - --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] - --localstatedir=DIR modifiable single-machine data [PREFIX/var] - --libdir=DIR object code libraries [EPREFIX/lib] - --includedir=DIR C header files [PREFIX/include] - --oldincludedir=DIR C header files for non-gcc [/usr/include] - --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] - --datadir=DIR read-only architecture-independent data [DATAROOTDIR] - --infodir=DIR info documentation [DATAROOTDIR/info] - --localedir=DIR locale-dependent data [DATAROOTDIR/locale] - --mandir=DIR man documentation [DATAROOTDIR/man] - --docdir=DIR documentation root [DATAROOTDIR/doc/pnp] - --htmldir=DIR html documentation [DOCDIR] - --dvidir=DIR dvi documentation [DOCDIR] - --pdfdir=DIR pdf documentation [DOCDIR] - --psdir=DIR ps documentation [DOCDIR] + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --runstatedir=DIR modifiable per-process data [LOCALSTATEDIR/run] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/pnp4nagios] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] _ACEOF cat <<\_ACEOF @@ -1279,32 +1462,82 @@ _ACEOF System types: --build=BUILD configure for building on BUILD [guessed] --host=HOST cross-compile to build programs to run on HOST [BUILD] + --target=TARGET configure for building compilers for TARGET [HOST] _ACEOF fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of pnp 0.6.26:";; + short | recursive ) echo "Configuration of pnp4nagios 0.6.27:";; esac cat <<\_ACEOF +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-install-method= + sets the install method to use: 'default' (the + default) will install to /usr/local/nagios, 'os' + will try to determine which method to use based on + OS type and distribution. Fine tuning using the + '--bindir', etc. overrides above will still work + --enable-showdirs-only=yes + This option will cause 'configure' to stop after + determining the install locations based on + '--enable-install-method', so you can see the + destinations before a full './configure', 'make', + 'make install' process. + --disable-selinux Disable selinux build + Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) - --with-layout=\default,debian\ sets directory layout + --with-debug_level= + --with-opsys=OS specify operating system (linux, osx, bsd, solaris, + irix, cygwin, aix, hp-ux, etc.) + --with-dist-type=type specify distribution type (suse, rh, debian, etc.) + --with-init-type=type specify init type (bsd, sysv, systemd, launchd, + smf10, smf11, upstart, openrc, etc.) + --with-pkgsysconfdir=DIR + where configuration files should be placed + --with-objsysconfdir=DIR + where object configuration files should be placed + --with-privatesysconfdir=DIR + where private configuration files should be placed + --with-webdir=DIR where the website files should be placed + --with-pluginsdir=DIR where the plugins should be placed + --with-brokersdir=DIR where the broker modules should be placed + --with-cgibindir=DIR where the CGI programs should be placed + --with-logdir=DIR where log files should be placed + --with-piddir=DIR where the PID file should be placed + --with-pipedir=DIR where socket and pipe files should be placed + --with-initdir= overrides path for initdir + --with-libdir=<$libdir> pnp4nagios libs are kept + --with-perl_lib_path= sets path to rrdtool RRDs perl modules. --without-kohana does not install the kohana framework --with-kohana_system= Points to an already installed kohana framework + --with-root-group= sets group name for installing init + --with-rrdtool= sets path to rrdtool + --with-selinux_develdir= sets path to nagios.cfg file + --with-nagios-version= nagios version string, like 3.1 etc + --with-nagios_unit= sets name of unit for nagios service + --with-nagios-pwd= sets path to Nagios password file + --with-nagios-objects= location of nagios object config files --with-nagios-user= sets user name to run nagios --with-nagios-group= sets group name to run nagios - --with-perl_lib_path= sets path to rrdtool RRDs perl modules. - --with-rrdtool= sets path to rrdtool - --with-perfdata-logfile= Tell me where I should store the 'process_perfdata.pl' Logfile + --with-pnp-logdir= Tell me where I should store the RRD Database Files --with-perfdata-spool-dir= Tell me where I should store perfdata files for bulk mode with npcd - --with-debug Enable debuging for process_perfdata.pl - --with-httpd-conf= sets path to Apache conf.d directory - --with-base-url=/${PKG_NAME} - --with-init-dir= sets directory to place init script into + --with-http_server=(http,apache,apache2,lighttpd,nginx) http server software + --with-http_server_base=(http server base dir) + --with-http_user= sets user name for http server + --with-http_group= sets group name for http server + --with-http_confdir= sets path to http server conf.d directory + --with-cache_dir= +--with-pnp_url= + --with-papersize= paper size to use A4 or letter Some influential environment variables: CC C compiler command @@ -1312,7 +1545,7 @@ Some influential environment variables: LDFLAGS linker flags, e.g. -L if you have libraries in a nonstandard directory LIBS libraries to pass to the linker, e.g. -l - CPPFLAGS C/C++/Objective C preprocessor flags, e.g. -I if + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if you have headers in a nonstandard directory CPP C preprocessor @@ -1320,6 +1553,7 @@ Use these variables to override the choices made by `configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to . +pnp4nagios home page: . _ACEOF ac_status=$? fi @@ -1327,15 +1561,17 @@ fi if test "$ac_init_help" = "recursive"; then # If there are subdirs, report their specific --help. for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue - test -d "$ac_dir" || continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -1363,7 +1599,8 @@ esac ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix cd "$ac_dir" || { ac_status=$?; continue; } - # Check for guested configure. + # Check for configure.gnu first; this name is used for a wrapper for + # Metaconfig's "Configure" on case-insensitive file systems. if test -f "$ac_srcdir/configure.gnu"; then echo && $SHELL "$ac_srcdir/configure.gnu" --help=recursive @@ -1371,7 +1608,7 @@ ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix echo && $SHELL "$ac_srcdir/configure" --help=recursive else - echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + printf "%s\n" "$as_me: WARNING: no configuration information is in $ac_dir" >&2 fi || ac_status=$? cd "$ac_pwd" || { ac_status=$?; break; } done @@ -1380,24 +1617,426 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -pnp configure 0.6.26 -generated by GNU Autoconf 2.61 +pnp4nagios configure 0.6.27 +generated by GNU Autoconf 2.71 -Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, -2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. +Copyright (C) 2021 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF exit fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest.beam + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +printf %s "checking for $2... " >&6; } +if eval test \${$3+y} +then : + printf %s "(cached) " >&6 +else $as_nop + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main (void) +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main (void) +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + +else $as_nop + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +eval ac_res=\$$3 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_type + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +printf %s "checking for $2... " >&6; } +if eval test \${$3+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$3=yes" +else $as_nop + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +eval ac_res=\$$3 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest.beam conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + test -x conftest$ac_exeext + } +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +printf %s "checking for $2... " >&6; } +if eval test \${$3+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. */ + +#include +#undef $2 + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int +main (void) +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + eval "$3=yes" +else $as_nop + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to run conftest.$ac_ext, and return whether this succeeded. Assumes that +# executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: program exited with status $ac_status" >&5 + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + } +then : + ac_retval=0 +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +printf %s "checking for $2.$3... " >&6; } +if eval test \${$4+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main (void) +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$4=yes" +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main (void) +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$4=yes" +else $as_nop + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +eval ac_res=\$$4 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_member +ac_configure_args_raw= +for ac_arg +do + case $ac_arg in + *\'*) + ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append ac_configure_args_raw " '$ac_arg'" +done + +case $ac_configure_args_raw in + *$as_nl*) + ac_safe_unquote= ;; + *) + ac_unsafe_z='|&;<>()$`\\"*?[ '' ' # This string ends in space, tab. + ac_unsafe_a="$ac_unsafe_z#~" + ac_safe_unquote="s/ '\\([^$ac_unsafe_a][^$ac_unsafe_z]*\\)'/ \\1/g" + ac_configure_args_raw=` printf "%s\n" "$ac_configure_args_raw" | sed "$ac_safe_unquote"`;; +esac + cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by pnp $as_me 0.6.26, which was -generated by GNU Autoconf 2.61. Invocation command line was +It was created by pnp4nagios $as_me 0.6.27, which was +generated by GNU Autoconf 2.71. Invocation command line was - $ $0 $@ + $ $0$ac_configure_args_raw _ACEOF exec 5>>config.log @@ -1430,9 +2069,13 @@ as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - echo "PATH: $as_dir" -done + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + printf "%s\n" "PATH: $as_dir" + done IFS=$as_save_IFS } >&5 @@ -1466,12 +2109,12 @@ do | -silent | --silent | --silen | --sile | --sil) continue ;; *\'*) - ac_arg=`echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + ac_arg=`printf "%s\n" "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; esac case $ac_pass in - 1) ac_configure_args0="$ac_configure_args0 '$ac_arg'" ;; + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; 2) - ac_configure_args1="$ac_configure_args1 '$ac_arg'" + as_fn_append ac_configure_args1 " '$ac_arg'" if test $ac_must_keep_next = true; then ac_must_keep_next=false # Got value, back to normal. else @@ -1487,13 +2130,13 @@ do -* ) ac_must_keep_next=true ;; esac fi - ac_configure_args="$ac_configure_args '$ac_arg'" + as_fn_append ac_configure_args " '$ac_arg'" ;; esac done done -$as_unset ac_configure_args0 || test "${ac_configure_args0+set}" != set || { ac_configure_args0=; export ac_configure_args0; } -$as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_configure_args1=; export ac_configure_args1; } +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} # When interrupted or exit'd, cleanup temporary files, and complete # config.log. We remove comments because anyway the quotes in there @@ -1501,15 +2144,15 @@ $as_unset ac_configure_args1 || test "${ac_configure_args1+set}" != set || { ac_ # WARNING: Use '\'' to represent an apostrophe within the trap. # WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. trap 'exit_status=$? + # Sanitize IFS. + IFS=" "" $as_nl" # Save into config.log some information that might help in debugging. { echo - cat <<\_ASBOX -## ---------------- ## + printf "%s\n" "## ---------------- ## ## Cache variables. ## -## ---------------- ## -_ASBOX +## ---------------- ##" echo # The following way of writing the cache mishandles newlines in values, ( @@ -1518,12 +2161,13 @@ _ASBOX case $ac_val in #( *${as_nl}*) case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; + *_cv_*) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; esac case $ac_var in #( _ | IFS | as_nl) ;; #( - *) $as_unset $ac_var ;; + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; esac ;; esac done @@ -1542,1256 +2186,123 @@ echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; ) echo - cat <<\_ASBOX -## ----------------- ## + printf "%s\n" "## ----------------- ## ## Output variables. ## -## ----------------- ## -_ASBOX +## ----------------- ##" echo for ac_var in $ac_subst_vars do eval ac_val=\$$ac_var case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac - echo "$ac_var='\''$ac_val'\''" + printf "%s\n" "$ac_var='\''$ac_val'\''" done | sort echo if test -n "$ac_subst_files"; then - cat <<\_ASBOX -## ------------------- ## + printf "%s\n" "## ------------------- ## ## File substitutions. ## -## ------------------- ## -_ASBOX +## ------------------- ##" echo for ac_var in $ac_subst_files do eval ac_val=\$$ac_var case $ac_val in - *\'\''*) ac_val=`echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + *\'\''*) ac_val=`printf "%s\n" "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; esac - echo "$ac_var='\''$ac_val'\''" + printf "%s\n" "$ac_var='\''$ac_val'\''" done | sort echo fi if test -s confdefs.h; then - cat <<\_ASBOX -## ----------- ## + printf "%s\n" "## ----------- ## ## confdefs.h. ## -## ----------- ## -_ASBOX +## ----------- ##" echo cat confdefs.h echo fi test "$ac_signal" != 0 && - echo "$as_me: caught signal $ac_signal" - echo "$as_me: exit $exit_status" + printf "%s\n" "$as_me: caught signal $ac_signal" + printf "%s\n" "$as_me: exit $exit_status" } >&5 rm -f core *.core core.conftest.* && rm -f -r conftest* confdefs* conf$$* $ac_clean_files && exit $exit_status ' 0 for ac_signal in 1 2 13 15; do - trap 'ac_signal='$ac_signal'; { (exit 1); exit 1; }' $ac_signal + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal done ac_signal=0 # confdefs.h avoids OS command line length limits that DEFS can exceed. rm -f -r conftest* confdefs.h +printf "%s\n" "/* confdefs.h */" > confdefs.h + # Predefined preprocessor variables. -cat >>confdefs.h <<_ACEOF -#define PACKAGE_NAME "$PACKAGE_NAME" -_ACEOF +printf "%s\n" "#define PACKAGE_NAME \"$PACKAGE_NAME\"" >>confdefs.h +printf "%s\n" "#define PACKAGE_TARNAME \"$PACKAGE_TARNAME\"" >>confdefs.h -cat >>confdefs.h <<_ACEOF -#define PACKAGE_TARNAME "$PACKAGE_TARNAME" -_ACEOF +printf "%s\n" "#define PACKAGE_VERSION \"$PACKAGE_VERSION\"" >>confdefs.h +printf "%s\n" "#define PACKAGE_STRING \"$PACKAGE_STRING\"" >>confdefs.h -cat >>confdefs.h <<_ACEOF -#define PACKAGE_VERSION "$PACKAGE_VERSION" -_ACEOF +printf "%s\n" "#define PACKAGE_BUGREPORT \"$PACKAGE_BUGREPORT\"" >>confdefs.h - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_STRING "$PACKAGE_STRING" -_ACEOF - - -cat >>confdefs.h <<_ACEOF -#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" -_ACEOF +printf "%s\n" "#define PACKAGE_URL \"$PACKAGE_URL\"" >>confdefs.h # Let the site file select an alternate cache file if it wants to. -# Prefer explicitly selected file to automatically selected ones. +# Prefer an explicitly selected file to automatically selected ones. if test -n "$CONFIG_SITE"; then - set x "$CONFIG_SITE" + ac_site_files="$CONFIG_SITE" elif test "x$prefix" != xNONE; then - set x "$prefix/share/config.site" "$prefix/etc/config.site" + ac_site_files="$prefix/share/config.site $prefix/etc/config.site" else - set x "$ac_default_prefix/share/config.site" \ - "$ac_default_prefix/etc/config.site" + ac_site_files="$ac_default_prefix/share/config.site $ac_default_prefix/etc/config.site" fi -shift -for ac_site_file + +for ac_site_file in $ac_site_files do - if test -r "$ac_site_file"; then - { echo "$as_me:$LINENO: loading site script $ac_site_file" >&5 -echo "$as_me: loading site script $ac_site_file" >&6;} + case $ac_site_file in #( + */*) : + ;; #( + *) : + ac_site_file=./$ac_site_file ;; +esac + if test -f "$ac_site_file" && test -r "$ac_site_file"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +printf "%s\n" "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 - . "$ac_site_file" + . "$ac_site_file" \ + || { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } fi done -if test -r "$cache_file"; then - # Some versions of bash will fail to source /dev/null (special - # files actually), so we avoid doing that. - if test -f "$cache_file"; then - { echo "$as_me:$LINENO: loading cache $cache_file" >&5 -echo "$as_me: loading cache $cache_file" >&6;} - case $cache_file in - [\\/]* | ?:[\\/]* ) . "$cache_file";; - *) . "./$cache_file";; - esac - fi -else - { echo "$as_me:$LINENO: creating cache $cache_file" >&5 -echo "$as_me: creating cache $cache_file" >&6;} - >$cache_file -fi -# Check that the precious variables saved in the cache have kept the same -# value. -ac_cache_corrupted=false -for ac_var in $ac_precious_vars; do - eval ac_old_set=\$ac_cv_env_${ac_var}_set - eval ac_new_set=\$ac_env_${ac_var}_set - eval ac_old_val=\$ac_cv_env_${ac_var}_value - eval ac_new_val=\$ac_env_${ac_var}_value - case $ac_old_set,$ac_new_set in - set,) - { echo "$as_me:$LINENO: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,set) - { echo "$as_me:$LINENO: error: \`$ac_var' was not set in the previous run" >&5 -echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} - ac_cache_corrupted=: ;; - ,);; - *) - if test "x$ac_old_val" != "x$ac_new_val"; then - { echo "$as_me:$LINENO: error: \`$ac_var' has changed since the previous run:" >&5 -echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} - { echo "$as_me:$LINENO: former value: $ac_old_val" >&5 -echo "$as_me: former value: $ac_old_val" >&2;} - { echo "$as_me:$LINENO: current value: $ac_new_val" >&5 -echo "$as_me: current value: $ac_new_val" >&2;} - ac_cache_corrupted=: - fi;; - esac - # Pass precious variables to config.status. - if test "$ac_new_set" = set; then - case $ac_new_val in - *\'*) ac_arg=$ac_var=`echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; - *) ac_arg=$ac_var=$ac_new_val ;; - esac - case " $ac_configure_args " in - *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. - *) ac_configure_args="$ac_configure_args '$ac_arg'" ;; - esac - fi -done -if $ac_cache_corrupted; then - { echo "$as_me:$LINENO: error: changes in the environment can compromise the build" >&5 -echo "$as_me: error: changes in the environment can compromise the build" >&2;} - { { echo "$as_me:$LINENO: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&5 -echo "$as_me: error: run \`make distclean' and/or \`rm $cache_file' and start over" >&2;} - { (exit 1); exit 1; }; } -fi - - - - - - - - - - - - - - - - - - - - - - - - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - - -ac_config_headers="$ac_config_headers include/config.h:include/config.h.in" - - - - -cat >>confdefs.h <<\_ACEOF -#define DEFAULT_NAGIOS_USER nagios -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define DEFAULT_NAGIOS_GROUP nagios -_ACEOF - - -PKG_NAME=pnp4nagios -PKG_VERSION="0.6.26" -PKG_HOME_URL="http://www.pnp4nagios.org/pnp/start" -PKG_REL_DATE="08-21-2017" - - - - - -XML_STRUCTURE_VERSION="4" - - - -ac_aux_dir= -for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do - if test -f "$ac_dir/install-sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install-sh -c" - break - elif test -f "$ac_dir/install.sh"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/install.sh -c" - break - elif test -f "$ac_dir/shtool"; then - ac_aux_dir=$ac_dir - ac_install_sh="$ac_aux_dir/shtool install -c" - break - fi -done -if test -z "$ac_aux_dir"; then - { { echo "$as_me:$LINENO: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&5 -echo "$as_me: error: cannot find install-sh or install.sh in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" >&2;} - { (exit 1); exit 1; }; } -fi - -# These three variables are undocumented and unsupported, -# and are intended to be withdrawn in a future Autoconf release. -# They can cause serious problems if a builder's source tree is in a directory -# whose full name contains unusual characters. -ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. -ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. -ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. - - -# Find a good install program. We prefer a C program (faster), -# so one script is as good as another. But avoid the broken or -# incompatible versions: -# SysV /etc/install, /usr/sbin/install -# SunOS /usr/etc/install -# IRIX /sbin/install -# AIX /bin/install -# AmigaOS /C/install, which installs bootblocks on floppy discs -# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag -# AFS /usr/afsws/bin/install, which mishandles nonexistent args -# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" -# OS/2's system install, which has a completely different semantic -# ./install, which can be erroneously created by make from ./install.sh. -{ echo "$as_me:$LINENO: checking for a BSD-compatible install" >&5 -echo $ECHO_N "checking for a BSD-compatible install... $ECHO_C" >&6; } -if test -z "$INSTALL"; then -if test "${ac_cv_path_install+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - # Account for people who put trailing slashes in PATH elements. -case $as_dir/ in - ./ | .// | /cC/* | \ - /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ - ?:\\/os2\\/install\\/* | ?:\\/OS2\\/INSTALL\\/* | \ - /usr/ucb/* ) ;; - *) - # OSF1 and SCO ODT 3.0 have their own names for install. - # Don't use installbsd from OSF since it installs stuff as root - # by default. - for ac_prog in ginstall scoinst install; do - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_prog$ac_exec_ext" && $as_test_x "$as_dir/$ac_prog$ac_exec_ext"; }; then - if test $ac_prog = install && - grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then - # AIX install. It has an incompatible calling convention. - : - elif test $ac_prog = install && - grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then - # program-specific install script used by HP pwplus--don't use. - : - else - ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" - break 3 - fi - fi - done - done - ;; -esac -done -IFS=$as_save_IFS - - -fi - if test "${ac_cv_path_install+set}" = set; then - INSTALL=$ac_cv_path_install - else - # As a last resort, use the slow shell script. Don't cache a - # value for INSTALL within a source directory, because that will - # break other packages using the cache if that directory is - # removed, or if the value is a relative name. - INSTALL=$ac_install_sh - fi -fi -{ echo "$as_me:$LINENO: result: $INSTALL" >&5 -echo "${ECHO_T}$INSTALL" >&6; } - -# Use test -z because SunOS4 sh mishandles braces in ${var-val}. -# It thinks the first close brace ends the variable substitution. -test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' - -test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' - -test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' - - - -#dnl What OS are we running? -# Make sure we can run config.sub. -$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || - { { echo "$as_me:$LINENO: error: cannot run $SHELL $ac_aux_dir/config.sub" >&5 -echo "$as_me: error: cannot run $SHELL $ac_aux_dir/config.sub" >&2;} - { (exit 1); exit 1; }; } - -{ echo "$as_me:$LINENO: checking build system type" >&5 -echo $ECHO_N "checking build system type... $ECHO_C" >&6; } -if test "${ac_cv_build+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_build_alias=$build_alias -test "x$ac_build_alias" = x && - ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` -test "x$ac_build_alias" = x && - { { echo "$as_me:$LINENO: error: cannot guess build type; you must specify one" >&5 -echo "$as_me: error: cannot guess build type; you must specify one" >&2;} - { (exit 1); exit 1; }; } -ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || - { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&5 -echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $ac_build_alias failed" >&2;} - { (exit 1); exit 1; }; } - -fi -{ echo "$as_me:$LINENO: result: $ac_cv_build" >&5 -echo "${ECHO_T}$ac_cv_build" >&6; } -case $ac_cv_build in -*-*-*) ;; -*) { { echo "$as_me:$LINENO: error: invalid value of canonical build" >&5 -echo "$as_me: error: invalid value of canonical build" >&2;} - { (exit 1); exit 1; }; };; -esac -build=$ac_cv_build -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_build -shift -build_cpu=$1 -build_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -build_os=$* -IFS=$ac_save_IFS -case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac - - -{ echo "$as_me:$LINENO: checking host system type" >&5 -echo $ECHO_N "checking host system type... $ECHO_C" >&6; } -if test "${ac_cv_host+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "x$host_alias" = x; then - ac_cv_host=$ac_cv_build -else - ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || - { { echo "$as_me:$LINENO: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&5 -echo "$as_me: error: $SHELL $ac_aux_dir/config.sub $host_alias failed" >&2;} - { (exit 1); exit 1; }; } -fi - -fi -{ echo "$as_me:$LINENO: result: $ac_cv_host" >&5 -echo "${ECHO_T}$ac_cv_host" >&6; } -case $ac_cv_host in -*-*-*) ;; -*) { { echo "$as_me:$LINENO: error: invalid value of canonical host" >&5 -echo "$as_me: error: invalid value of canonical host" >&2;} - { (exit 1); exit 1; }; };; -esac -host=$ac_cv_host -ac_save_IFS=$IFS; IFS='-' -set x $ac_cv_host -shift -host_cpu=$1 -host_vendor=$2 -shift; shift -# Remember, the first character of IFS is used to create $*, -# except with old shells: -host_os=$* -IFS=$ac_save_IFS -case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac - - - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. -set dummy ${ac_tool_prefix}gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_CC"; then - ac_ct_CC=$CC - # Extract the first word of "gcc", so it can be a program name with args. -set dummy gcc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="gcc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf@gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf@gnu.org." >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -else - CC="$ac_cv_prog_CC" -fi - -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. -set dummy ${ac_tool_prefix}cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="${ac_tool_prefix}cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - - fi -fi -if test -z "$CC"; then - # Extract the first word of "cc", so it can be a program name with args. -set dummy cc; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else - ac_prog_rejected=no -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then - ac_prog_rejected=yes - continue - fi - ac_cv_prog_CC="cc" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -if test $ac_prog_rejected = yes; then - # We found a bogon in the path, so make sure we never use it. - set dummy $ac_cv_prog_CC - shift - if test $# != 0; then - # We chose a different compiler from the bogus one. - # However, it has the same basename, so the bogon will be chosen - # first if we set CC to just the basename; use the full file name. - shift - ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" - fi -fi -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - -fi -if test -z "$CC"; then - if test -n "$ac_tool_prefix"; then - for ac_prog in cl.exe - do - # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. -set dummy $ac_tool_prefix$ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$CC"; then - ac_cv_prog_CC="$CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_CC="$ac_tool_prefix$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -CC=$ac_cv_prog_CC -if test -n "$CC"; then - { echo "$as_me:$LINENO: result: $CC" >&5 -echo "${ECHO_T}$CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - - test -n "$CC" && break - done -fi -if test -z "$CC"; then - ac_ct_CC=$CC - for ac_prog in cl.exe -do - # Extract the first word of "$ac_prog", so it can be a program name with args. -set dummy $ac_prog; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test -n "$ac_ct_CC"; then - ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_prog_ac_ct_CC="$ac_prog" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - -fi -fi -ac_ct_CC=$ac_cv_prog_ac_ct_CC -if test -n "$ac_ct_CC"; then - { echo "$as_me:$LINENO: result: $ac_ct_CC" >&5 -echo "${ECHO_T}$ac_ct_CC" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - - test -n "$ac_ct_CC" && break -done - - if test "x$ac_ct_CC" = x; then - CC="" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ echo "$as_me:$LINENO: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf@gnu.org." >&5 -echo "$as_me: WARNING: In the future, Autoconf will not detect cross-tools -whose name does not start with the host triplet. If you think this -configuration is useful to you, please write to autoconf@gnu.org." >&2;} -ac_tool_warned=yes ;; -esac - CC=$ac_ct_CC - fi -fi - -fi - - -test -z "$CC" && { { echo "$as_me:$LINENO: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&5 -echo "$as_me: error: no acceptable C compiler found in \$PATH -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } - -# Provide some information about the compiler. -echo "$as_me:$LINENO: checking for C compiler version" >&5 -ac_compiler=`set X $ac_compile; echo $2` -{ (ac_try="$ac_compiler --version >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler --version >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -v >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler -v >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } -{ (ac_try="$ac_compiler -V >&5" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compiler -V >&5") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } - -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -ac_clean_files_save=$ac_clean_files -ac_clean_files="$ac_clean_files a.out a.exe b.out" -# Try to create an executable without -o first, disregard a.out. -# It will help us diagnose broken compilers, and finding out an intuition -# of exeext. -{ echo "$as_me:$LINENO: checking for C compiler default output file name" >&5 -echo $ECHO_N "checking for C compiler default output file name... $ECHO_C" >&6; } -ac_link_default=`echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` -# -# List of possible output files, starting from the most likely. -# The algorithm is not robust to junk in `.', hence go to wildcards (a.*) -# only as a last resort. b.out is created by i960 compilers. -ac_files='a_out.exe a.exe conftest.exe a.out conftest a.* conftest.* b.out' -# -# The IRIX 6 linker writes into existing files which may not be -# executable, retaining their permissions. Remove them first so a -# subsequent execution test works. -ac_rmfiles= -for ac_file in $ac_files -do - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; - * ) ac_rmfiles="$ac_rmfiles $ac_file";; - esac -done -rm -f $ac_rmfiles - -if { (ac_try="$ac_link_default" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link_default") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. -# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' -# in a Makefile. We should not override ac_cv_exeext if it was cached, -# so that the user can short-circuit this test for compilers unknown to -# Autoconf. -for ac_file in $ac_files '' -do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) - ;; - [ab].out ) - # We found the default executable, but exeext='' is most - # certainly right. - break;; - *.* ) - if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; - then :; else - ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - fi - # We set ac_cv_exeext here because the later test for it is not - # safe: cross compilers may not add the suffix if given an `-o' - # argument, so we may need to know it at that point already. - # Even if this section looks crufty: it has the advantage of - # actually working. - break;; - * ) - break;; - esac -done -test "$ac_cv_exeext" = no && ac_cv_exeext= - -else - ac_file='' -fi - -{ echo "$as_me:$LINENO: result: $ac_file" >&5 -echo "${ECHO_T}$ac_file" >&6; } -if test -z "$ac_file"; then - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { echo "$as_me:$LINENO: error: C compiler cannot create executables -See \`config.log' for more details." >&5 -echo "$as_me: error: C compiler cannot create executables -See \`config.log' for more details." >&2;} - { (exit 77); exit 77; }; } -fi - -ac_exeext=$ac_cv_exeext - -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether the C compiler works" >&5 -echo $ECHO_N "checking whether the C compiler works... $ECHO_C" >&6; } -# FIXME: These cross compiler hacks should be removed for Autoconf 3.0 -# If not cross compiling, check that we can run a simple program. -if test "$cross_compiling" != yes; then - if { ac_try='./$ac_file' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - cross_compiling=no - else - if test "$cross_compiling" = maybe; then - cross_compiling=yes - else - { { echo "$as_me:$LINENO: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } - fi - fi -fi -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - -rm -f a.out a.exe conftest$ac_cv_exeext b.out -ac_clean_files=$ac_clean_files_save -# Check that the compiler produces executables we can run. If not, either -# the compiler is broken, or we cross compile. -{ echo "$as_me:$LINENO: checking whether we are cross compiling" >&5 -echo $ECHO_N "checking whether we are cross compiling... $ECHO_C" >&6; } -{ echo "$as_me:$LINENO: result: $cross_compiling" >&5 -echo "${ECHO_T}$cross_compiling" >&6; } - -{ echo "$as_me:$LINENO: checking for suffix of executables" >&5 -echo $ECHO_N "checking for suffix of executables... $ECHO_C" >&6; } -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - # If both `conftest.exe' and `conftest' are `present' (well, observable) -# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will -# work properly (i.e., refer to `conftest.exe'), while it won't with -# `rm'. -for ac_file in conftest.exe conftest conftest.*; do - test -f "$ac_file" || continue - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.o | *.obj ) ;; - *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` - break;; - * ) break;; - esac -done -else - { { echo "$as_me:$LINENO: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi - -rm -f conftest$ac_cv_exeext -{ echo "$as_me:$LINENO: result: $ac_cv_exeext" >&5 -echo "${ECHO_T}$ac_cv_exeext" >&6; } - -rm -f conftest.$ac_ext -EXEEXT=$ac_cv_exeext -ac_exeext=$EXEEXT -{ echo "$as_me:$LINENO: checking for suffix of object files" >&5 -echo $ECHO_N "checking for suffix of object files... $ECHO_C" >&6; } -if test "${ac_cv_objext+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.o conftest.obj -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; then - for ac_file in conftest.o conftest.obj conftest.*; do - test -f "$ac_file" || continue; - case $ac_file in - *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf ) ;; - *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` - break;; - esac -done -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -{ { echo "$as_me:$LINENO: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&5 -echo "$as_me: error: cannot compute suffix of object files: cannot compile -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi - -rm -f conftest.$ac_cv_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_objext" >&5 -echo "${ECHO_T}$ac_cv_objext" >&6; } -OBJEXT=$ac_cv_objext -ac_objext=$OBJEXT -{ echo "$as_me:$LINENO: checking whether we are using the GNU C compiler" >&5 -echo $ECHO_N "checking whether we are using the GNU C compiler... $ECHO_C" >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ -#ifndef __GNUC__ - choke me +# Test code for whether the C compiler supports C89 (global declarations) +ac_c_conftest_c89_globals=' +/* Does the compiler advertise C89 conformance? + Do not test the value of __STDC__, because some compilers set it to 0 + while being otherwise adequately conformant. */ +#if !defined __STDC__ +# error "Compiler does not advertise C89 conformance" #endif - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_compiler_gnu=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_compiler_gnu=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -ac_cv_c_compiler_gnu=$ac_compiler_gnu - -fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_compiler_gnu" >&5 -echo "${ECHO_T}$ac_cv_c_compiler_gnu" >&6; } -GCC=`test $ac_compiler_gnu = yes && echo yes` -ac_test_CFLAGS=${CFLAGS+set} -ac_save_CFLAGS=$CFLAGS -{ echo "$as_me:$LINENO: checking whether $CC accepts -g" >&5 -echo $ECHO_N "checking whether $CC accepts -g... $ECHO_C" >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_save_c_werror_flag=$ac_c_werror_flag - ac_c_werror_flag=yes - ac_cv_prog_cc_g=no - CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_g=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - CFLAGS="" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_c_werror_flag=$ac_save_c_werror_flag - CFLAGS="-g" - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_g=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag -fi -{ echo "$as_me:$LINENO: result: $ac_cv_prog_cc_g" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_g" >&6; } -if test "$ac_test_CFLAGS" = set; then - CFLAGS=$ac_save_CFLAGS -elif test $ac_cv_prog_cc_g = yes; then - if test "$GCC" = yes; then - CFLAGS="-g -O2" - else - CFLAGS="-g" - fi -else - if test "$GCC" = yes; then - CFLAGS="-O2" - else - CFLAGS= - fi -fi -{ echo "$as_me:$LINENO: checking for $CC option to accept ISO C89" >&5 -echo $ECHO_N "checking for $CC option to accept ISO C89... $ECHO_C" >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_cv_prog_cc_c89=no -ac_save_CC=$CC -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ +#include #include -#include -#include -#include -/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct stat; +/* Most of the following tests are stolen from RCS 5.7 src/conf.sh. */ struct buf { int x; }; -FILE * (*rcsopen) (struct buf *, struct stat *, int); +struct buf * (*rcsopen) (struct buf *, struct stat *, int); static char *e (p, i) char **p; int i; @@ -2809,102 +2320,2988 @@ static char *f (char * (*g) (char **, int), char **p, ...) } /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has - function prototypes and stuff, but not '\xHH' hex character constants. - These don't provoke an error unfortunately, instead are silently treated - as 'x'. The following induces an error, until -std is added to get - proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an - array size at least. It's necessary to write '\x00'==0 to get something - that's true only with -std. */ -int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + function prototypes and stuff, but not \xHH hex character constants. + These do not provoke an error unfortunately, instead are silently treated + as an "x". The following induces an error, until -std is added to get + proper ANSI mode. Curiously \x00 != x always comes out true, for an + array size at least. It is necessary to write \x00 == 0 to get something + that is true only with -std. */ +int osf4_cc_array ['\''\x00'\'' == 0 ? 1 : -1]; /* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters inside strings and character constants. */ -#define FOO(x) 'x' -int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; +#define FOO(x) '\''x'\'' +int xlc6_cc_array[FOO(a) == '\''x'\'' ? 1 : -1]; int test (int i, double x); struct s1 {int (*f) (int a);}; struct s2 {int (*f) (double a);}; -int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); -int argc; -char **argv; -int -main () +int pairnames (int, char **, int *(*)(struct buf *, struct stat *, int), + int, int);' + +# Test code for whether the C compiler supports C89 (body of main). +ac_c_conftest_c89_main=' +ok |= (argc == 0 || f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]); +' + +# Test code for whether the C compiler supports C99 (global declarations) +ac_c_conftest_c99_globals=' +// Does the compiler advertise C99 conformance? +#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L +# error "Compiler does not advertise C99 conformance" +#endif + +#include +extern int puts (const char *); +extern int printf (const char *, ...); +extern int dprintf (int, const char *, ...); +extern void *malloc (size_t); + +// Check varargs macros. These examples are taken from C99 6.10.3.5. +// dprintf is used instead of fprintf to avoid needing to declare +// FILE and stderr. +#define debug(...) dprintf (2, __VA_ARGS__) +#define showlist(...) puts (#__VA_ARGS__) +#define report(test,...) ((test) ? puts (#test) : printf (__VA_ARGS__)) +static void +test_varargs_macros (void) { -return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; - ; + int x = 1234; + int y = 5678; + debug ("Flag"); + debug ("X = %d\n", x); + showlist (The first, second, and third items.); + report (x>y, "x is %d but y is %d", x, y); +} + +// Check long long types. +#define BIG64 18446744073709551615ull +#define BIG32 4294967295ul +#define BIG_OK (BIG64 / BIG32 == 4294967297ull && BIG64 % BIG32 == 0) +#if !BIG_OK + #error "your preprocessor is broken" +#endif +#if BIG_OK +#else + #error "your preprocessor is broken" +#endif +static long long int bignum = -9223372036854775807LL; +static unsigned long long int ubignum = BIG64; + +struct incomplete_array +{ + int datasize; + double data[]; +}; + +struct named_init { + int number; + const wchar_t *name; + double average; +}; + +typedef const char *ccp; + +static inline int +test_restrict (ccp restrict text) +{ + // See if C++-style comments work. + // Iterate through items via the restricted pointer. + // Also check for declarations in for loops. + for (unsigned int i = 0; *(text+i) != '\''\0'\''; ++i) + continue; return 0; } -_ACEOF -for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ - -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" + +// Check varargs and va_copy. +static bool +test_varargs (const char *format, ...) +{ + va_list args; + va_start (args, format); + va_list args_copy; + va_copy (args_copy, args); + + const char *str = ""; + int number = 0; + float fnumber = 0; + + while (*format) + { + switch (*format++) + { + case '\''s'\'': // string + str = va_arg (args_copy, const char *); + break; + case '\''d'\'': // int + number = va_arg (args_copy, int); + break; + case '\''f'\'': // float + fnumber = va_arg (args_copy, double); + break; + default: + break; + } + } + va_end (args_copy); + va_end (args); + + return *str && number && fnumber; +} +' + +# Test code for whether the C compiler supports C99 (body of main). +ac_c_conftest_c99_main=' + // Check bool. + _Bool success = false; + success |= (argc != 0); + + // Check restrict. + if (test_restrict ("String literal") == 0) + success = true; + char *restrict newvar = "Another string"; + + // Check varargs. + success &= test_varargs ("s, d'\'' f .", "string", 65, 34.234); + test_varargs_macros (); + + // Check flexible array members. + struct incomplete_array *ia = + malloc (sizeof (struct incomplete_array) + (sizeof (double) * 10)); + ia->datasize = 10; + for (int i = 0; i < ia->datasize; ++i) + ia->data[i] = i * 1.234; + + // Check named initializers. + struct named_init ni = { + .number = 34, + .name = L"Test wide string", + .average = 543.34343, + }; + + ni.number = 58; + + int dynamic_array[ni.number]; + dynamic_array[0] = argv[0][0]; + dynamic_array[ni.number - 1] = 543; + + // work around unused variable warnings + ok |= (!success || bignum == 0LL || ubignum == 0uLL || newvar[0] == '\''x'\'' + || dynamic_array[ni.number - 1] != 543); +' + +# Test code for whether the C compiler supports C11 (global declarations) +ac_c_conftest_c11_globals=' +// Does the compiler advertise C11 conformance? +#if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112L +# error "Compiler does not advertise C11 conformance" +#endif + +// Check _Alignas. +char _Alignas (double) aligned_as_double; +char _Alignas (0) no_special_alignment; +extern char aligned_as_int; +char _Alignas (0) _Alignas (int) aligned_as_int; + +// Check _Alignof. +enum +{ + int_alignment = _Alignof (int), + int_array_alignment = _Alignof (int[100]), + char_alignment = _Alignof (char) +}; +_Static_assert (0 < -_Alignof (int), "_Alignof is signed"); + +// Check _Noreturn. +int _Noreturn does_not_return (void) { for (;;) continue; } + +// Check _Static_assert. +struct test_static_assert +{ + int x; + _Static_assert (sizeof (int) <= sizeof (long int), + "_Static_assert does not work in struct"); + long int y; +}; + +// Check UTF-8 literals. +#define u8 syntax error! +char const utf8_literal[] = u8"happens to be ASCII" "another string"; + +// Check duplicate typedefs. +typedef long *long_ptr; +typedef long int *long_ptr; +typedef long_ptr long_ptr; + +// Anonymous structures and unions -- taken from C11 6.7.2.1 Example 1. +struct anonymous +{ + union { + struct { int i; int j; }; + struct { int k; long int l; } w; + }; + int m; +} v1; +' + +# Test code for whether the C compiler supports C11 (body of main). +ac_c_conftest_c11_main=' + _Static_assert ((offsetof (struct anonymous, i) + == offsetof (struct anonymous, w.k)), + "Anonymous union alignment botch"); + v1.i = 2; + v1.w.k = 5; + ok |= v1.i != 5; +' + +# Test code for whether the C compiler supports C11 (complete). +ac_c_conftest_c11_program="${ac_c_conftest_c89_globals} +${ac_c_conftest_c99_globals} +${ac_c_conftest_c11_globals} + +int +main (int argc, char **argv) +{ + int ok = 0; + ${ac_c_conftest_c89_main} + ${ac_c_conftest_c99_main} + ${ac_c_conftest_c11_main} + return ok; +} +" + +# Test code for whether the C compiler supports C99 (complete). +ac_c_conftest_c99_program="${ac_c_conftest_c89_globals} +${ac_c_conftest_c99_globals} + +int +main (int argc, char **argv) +{ + int ok = 0; + ${ac_c_conftest_c89_main} + ${ac_c_conftest_c99_main} + return ok; +} +" + +# Test code for whether the C compiler supports C89 (complete). +ac_c_conftest_c89_program="${ac_c_conftest_c89_globals} + +int +main (int argc, char **argv) +{ + int ok = 0; + ${ac_c_conftest_c89_main} + return ok; +} +" + +as_fn_append ac_header_c_list " stdio.h stdio_h HAVE_STDIO_H" +as_fn_append ac_header_c_list " stdlib.h stdlib_h HAVE_STDLIB_H" +as_fn_append ac_header_c_list " string.h string_h HAVE_STRING_H" +as_fn_append ac_header_c_list " inttypes.h inttypes_h HAVE_INTTYPES_H" +as_fn_append ac_header_c_list " stdint.h stdint_h HAVE_STDINT_H" +as_fn_append ac_header_c_list " strings.h strings_h HAVE_STRINGS_H" +as_fn_append ac_header_c_list " sys/stat.h sys_stat_h HAVE_SYS_STAT_H" +as_fn_append ac_header_c_list " sys/types.h sys_types_h HAVE_SYS_TYPES_H" +as_fn_append ac_header_c_list " unistd.h unistd_h HAVE_UNISTD_H" +as_fn_append ac_header_c_list " vfork.h vfork_h HAVE_VFORK_H" +as_fn_append ac_func_c_list " fork HAVE_FORK" +as_fn_append ac_func_c_list " vfork HAVE_VFORK" + +# Auxiliary files required by this configure script. +ac_aux_files="install-sh config.guess config.sub" + +# Locations in which to look for auxiliary files. +ac_aux_dir_candidates="${srcdir}${PATH_SEPARATOR}${srcdir}/..${PATH_SEPARATOR}${srcdir}/../.." + +# Search for a directory containing all of the required auxiliary files, +# $ac_aux_files, from the $PATH-style list $ac_aux_dir_candidates. +# If we don't find one directory that contains all the files we need, +# we report the set of missing files from the *first* directory in +# $ac_aux_dir_candidates and give up. +ac_missing_aux_files="" +ac_first_candidate=: +printf "%s\n" "$as_me:${as_lineno-$LINENO}: looking for aux files: $ac_aux_files" >&5 +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in $ac_aux_dir_candidates do - CC="$ac_save_CC $ac_arg" - rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_prog_cc_c89=$ac_arg -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + as_found=: + printf "%s\n" "$as_me:${as_lineno-$LINENO}: trying $as_dir" >&5 + ac_aux_dir_found=yes + ac_install_sh= + for ac_aux in $ac_aux_files + do + # As a special case, if "install-sh" is required, that requirement + # can be satisfied by any of "install-sh", "install.sh", or "shtool", + # and $ac_install_sh is set appropriately for whichever one is found. + if test x"$ac_aux" = x"install-sh" + then + if test -f "${as_dir}install-sh"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}install-sh found" >&5 + ac_install_sh="${as_dir}install-sh -c" + elif test -f "${as_dir}install.sh"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}install.sh found" >&5 + ac_install_sh="${as_dir}install.sh -c" + elif test -f "${as_dir}shtool"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}shtool found" >&5 + ac_install_sh="${as_dir}shtool install -c" + else + ac_aux_dir_found=no + if $ac_first_candidate; then + ac_missing_aux_files="${ac_missing_aux_files} install-sh" + else + break + fi + fi + else + if test -f "${as_dir}${ac_aux}"; then + printf "%s\n" "$as_me:${as_lineno-$LINENO}: ${as_dir}${ac_aux} found" >&5 + else + ac_aux_dir_found=no + if $ac_first_candidate; then + ac_missing_aux_files="${ac_missing_aux_files} ${ac_aux}" + else + break + fi + fi + fi + done + if test "$ac_aux_dir_found" = yes; then + ac_aux_dir="$as_dir" + break + fi + ac_first_candidate=false -fi - -rm -f core conftest.err conftest.$ac_objext - test "x$ac_cv_prog_cc_c89" != "xno" && break + as_found=false done -rm -f conftest.$ac_ext -CC=$ac_save_CC +IFS=$as_save_IFS +if $as_found +then : +else $as_nop + as_fn_error $? "cannot find required auxiliary files:$ac_missing_aux_files" "$LINENO" 5 fi -# AC_CACHE_VAL -case "x$ac_cv_prog_cc_c89" in - x) - { echo "$as_me:$LINENO: result: none needed" >&5 -echo "${ECHO_T}none needed" >&6; } ;; - xno) - { echo "$as_me:$LINENO: result: unsupported" >&5 -echo "${ECHO_T}unsupported" >&6; } ;; - *) - CC="$CC $ac_cv_prog_cc_c89" - { echo "$as_me:$LINENO: result: $ac_cv_prog_cc_c89" >&5 -echo "${ECHO_T}$ac_cv_prog_cc_c89" >&6; } ;; -esac +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +if test -f "${ac_aux_dir}config.guess"; then + ac_config_guess="$SHELL ${ac_aux_dir}config.guess" +fi +if test -f "${ac_aux_dir}config.sub"; then + ac_config_sub="$SHELL ${ac_aux_dir}config.sub" +fi +if test -f "$ac_aux_dir/configure"; then + ac_configure="$SHELL ${ac_aux_dir}configure" +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +printf "%s\n" "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +printf "%s\n" "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +printf "%s\n" "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +printf "%s\n" "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +printf "%s\n" "$as_me: former value: \`$ac_old_val'" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +printf "%s\n" "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`printf "%s\n" "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +printf "%s\n" "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`${MAKE-make} distclean' and/or \`rm $cache_file' + and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking whether ${MAKE-make} sets \$(MAKE)" >&5 -echo $ECHO_N "checking whether ${MAKE-make} sets \$(MAKE)... $ECHO_C" >&6; } -set x ${MAKE-make}; ac_make=`echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` -if { as_var=ac_cv_prog_make_${ac_make}_set; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + +PKG_NAME="$PACKAGE_NAME" +PKG_VERSION="$PACKAGE_VERSION" + +# +# release and release_date +# ...gets overwritten by github release-building +# +PACKAGE_RELEASE="4" +PKG_REL_DATE="2023-10-15" + + + + +ac_config_headers="$ac_config_headers include/config.h:include/config.h.in" + + +# +if echo $PATH | grep -qv '/sbin' ; then + echo "PATH variable doesn't include sbin, probable failure" + exit 1 +fi +# + +XML_STRUCTURE_VERSION="4" + + +DEBUG_LEVEL=0 + +# Check whether --with-debug_level was given. +if test ${with_debug_level+y} +then : + withval=$with_debug_level; DEBUG_LEVEL=$withval +else $as_nop + DEBUG_LEVEL=0 +fi + +if test $DEBUG_LEVEL -gt 0 ; then +CFLAGS="${CFLAGS} -O0 -ggdb3 -g3" +fi + + +#dnl What OS are we running? + + + + # Make sure we can run config.sub. +$SHELL "${ac_aux_dir}config.sub" sun4 >/dev/null 2>&1 || + as_fn_error $? "cannot run $SHELL ${ac_aux_dir}config.sub" "$LINENO" 5 + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 +printf %s "checking build system type... " >&6; } +if test ${ac_cv_build+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "${ac_aux_dir}config.guess"` +test "x$ac_build_alias" = x && + as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 +ac_cv_build=`$SHELL "${ac_aux_dir}config.sub" $ac_build_alias` || + as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $ac_build_alias failed" "$LINENO" 5 + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 +printf "%s\n" "$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 +printf %s "checking host system type... " >&6; } +if test ${ac_cv_host+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build else + ac_cv_host=`$SHELL "${ac_aux_dir}config.sub" $host_alias` || + as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $host_alias failed" "$LINENO" 5 +fi + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 +printf "%s\n" "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + +#dnl kinda doubt much cross-compiling, but just in case... +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking target system type" >&5 +printf %s "checking target system type... " >&6; } +if test ${ac_cv_target+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test "x$target_alias" = x; then + ac_cv_target=$ac_cv_host +else + ac_cv_target=`$SHELL "${ac_aux_dir}config.sub" $target_alias` || + as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $target_alias failed" "$LINENO" 5 +fi + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5 +printf "%s\n" "$ac_cv_target" >&6; } +case $ac_cv_target in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5;; +esac +target=$ac_cv_target +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_target +shift +target_cpu=$1 +target_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +target_os=$* +IFS=$ac_save_IFS +case $target_os in *\ *) target_os=`echo "$target_os" | sed 's/ /-/g'`;; esac + + +# The aliases save the names the user supplied, while $host etc. +# will get canonicalized. +test -n "$target_alias" && + test "$program_prefix$program_suffix$program_transform_name" = \ + NONENONEs,x,x, && + program_prefix=${target_alias}- + + +INIT_PROG=npcd + + + + + +# +# Get user hints +# + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking what the operating system is " >&5 +printf %s "checking what the operating system is ... " >&6; } + +# Check whether --with-opsys was given. +if test ${with_opsys+y} +then : + withval=$with_opsys; + # + # Run this if --with was specified + # + if test "x$withval" = x -o x$withval = xno; then + opsys_wanted=yes + else + opsys_wanted=no + opsys="$withval" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $opsys" >&5 +printf "%s\n" "$opsys" >&6; } + fi + +else $as_nop + + # + # Run this if --with was not specified + # + opsys_wanted=yes + +fi + + + if test x$opsys = xno; then + opsys="" + opsys_wanted=yes + elif test x$opsys = xyes; then + as_fn_error $? "you must enter an O/S type if '--with-opsys' is specified" "$LINENO" 5 + fi + + # + # Determine operating system if it wasn't supplied + # + if test $opsys_wanted=yes; then + opsys=`uname -s | tr "[A-Z]" "[a-z]"` + if test x"$opsys" = "x"; then opsys="unknown"; fi + case $opsys in #( + darwin*) : + opsys="osx" ;; #( + *bsd*) : + opsys="bsd" ;; #( + dragonfly) : + opsys="bsd" ;; #( + sunos) : + opsys="solaris" ;; #( + gnu/hurd) : + opsys="linux" ;; #( + irix*) : + opsys="irix" ;; #( + cygwin*) : + opsys="cygwin" ;; #( + mingw*) : + opsys="mingw" ;; #( + msys*) : + opsys="msys" ;; #( + *) : + ;; +esac + fi + + arch=`uname -m | tr "[A-Z]" "[a-z]"` + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $opsys" >&5 +printf "%s\n" "$opsys" >&6; } + + + + + + +# +# Get user hints for possible cross-compile +# + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking what the distribution type is " >&5 +printf %s "checking what the distribution type is ... " >&6; } + +# Check whether --with-dist-type was given. +if test ${with_dist_type+y} +then : + withval=$with_dist_type; + # + # Run this if --with was specified + # + if test "x$withval" = x -o x$withval = xno; then + dist_type_wanted=yes + else + dist_type_wanted=no + dist_type="$withval" + dist_ver="unknown" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $dist_type" >&5 +printf "%s\n" "$dist_type" >&6; } + fi + +else $as_nop + + # + # Run this if --with was not specified + # + dist_type_wanted=yes + +fi + + + if test x$dist_type = xno; then + dist_type_wanted=yes + elif test x$dist_type = xyes; then + as_fn_error $? "you must enter a distribution type if '--with-dist-type' is specified" "$LINENO" 5 + fi + + # + # Determine distribution type if it wasn't supplied + # + dist_ver="unknown" + + if test $dist_type_wanted=yes; then + dist_type="unknown" + + if test "$opsys" != "linux"; then + dist_type="$opsys" + case $opsys in #( + bsd) : + dist_type=`uname -s | tr "A-Z" "a-z"` + dist_ver=`uname -r` ;; #( + aix) : + dist_ver="`uname -v`.`uname -r`" ;; #( + hp-ux) : + dist_ver=`uname -r | cut -d'.' -f1-3` ;; #( + solaris) : + dist_ver=`uname -r | cut -d'.' -f2` ;; #( + *) : + dist_ver=$OSTYPE + ;; #( + *) : + ;; +esac + + else + + if test -r "/etc/gentoo-release"; then + dist_type="gentoo" + dist_ver=`cat /etc/gentoo-release` + + elif test -r "/etc/os-release"; then + . /etc/os-release + if test x"$ID_LIKE" != x; then + dist_type=`echo $ID_LIKE | cut -d' ' -f1 | tr "[A-Z]" "[a-z]"` + elif test x"$ID" = xol; then + dist_type=rh + else + dist_type=`echo $ID | tr "[A-Z]" "[a-z]"` + fi + if test x"$dist_type" = sles; then + dist_type=suse + fi + if test x"$VERSION_ID" != x; then + dist_ver=$VERSION_ID + elif test x"$VERSION" != x; then + dist_ver=`echo $VERSION | cut -d'.' -f1 | tr -d :alpha::blank::punct:` + fi + + elif test -r "/etc/redhat-release"; then + dist_type=rh + dist_ver=`cat /etc/redhat-release` + + elif test -r "/etc/debian_version"; then + dist_type="debian" + if test -r "/etc/lsb-release"; then + . /etc/lsb-release + dist_ver=`echo "$DISTRIB_RELEASE"` + else + dist_ver=`cat /etc/debian_version` + fi + + elif test -r "/etc/SuSE-release"; then + dist_type=suse + dist_ver=`grep VERSION /etc/SuSE-release` + + fi + + fi + + if test "$dist_ver" != "unknown"; then + dist_ver=`echo "$dist_ver" | cut -d'.' -f1 | tr -d :alpha::blank::punct:` + fi + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $dist_type" >&5 +printf "%s\n" "$dist_type" >&6; } + + + + + +# +# Get user hints for possible cross-compile +# + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking what init system is being used " >&5 +printf %s "checking what init system is being used ... " >&6; } + +# Check whether --with-init_type was given. +if test ${with_init_type+y} +then : + withval=$with_init_type; + # + # Run this if --with was specified + # + if test "x$withval" = x -o x$withval = xno; then + init_type_wanted=yes + else + init_type_wanted=no + init_type="$withval" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $init_type" >&5 +printf "%s\n" "$init_type" >&6; } + fi + +else $as_nop + + # + # Run this if --with was not specified + # + init_type_wanted=yes + +fi + + + if test x$init_type = xno; then + init_type_wanted=yes + elif test x$init_type = xyes; then + as_fn_error $? "you must enter an init type if '--with-init-type' is specified" "$LINENO" 5 + fi + + # + # Determine init type if it wasn't supplied + # + if test $init_type_wanted = yes; then + init_type="" + + if test x"$opsys" = x; then + init_type="unknown" + init_type_wanted=no + elif test x"$dist_type" = x; then + init_type="unknown" + init_type_wanted=no + elif test "$opsys" = "osx"; then + init_type="launchd" + init_type_wanted=no + elif test "$opsys" = "bsd"; then + init_type="newbsd" + init_type_wanted=no + elif test "$dist_type" = "solaris"; then + if test -d "/lib/svc/manifest"; then + init_type="smf11" + init_type_wanted=no + elif test -d "/lib/svc/monitor"; then + init_type="smf10" + init_type_wanted=no + else + init_type="sysv" + init_type_wanted=no + fi + elif test "$dist_type" = "slackware"; then + init_type="bsd" + init_type_wanted=no + elif test "$dist_type" = "aix"; then + init_type="bsd" + init_type_wanted=no + elif test "$dist_type" = "hp-ux"; then + init_type="unknown" + init_type_wanted=no + fi + fi + + PSCMD="ps -p1 -o args" + if test $dist_type = solaris; then + PSCMD="env UNIX95=1; ps -p1 -o args" + fi + + if test "$init_type_wanted" = yes; then + pid1=`$PSCMD | grep -vi COMMAND | cut -d' ' -f1` + if test x"$pid1" = "x"; then + init_type="unknown" + init_type_wanted=no + fi + if `echo $pid1 | grep "systemd" > /dev/null`; then + init_type="systemd" + init_type_wanted=no + fi + + if test "$init_type_wanted" = yes; then + if test "$pid1" = "init"; then + if test -e "/sbin/init"; then + pid1="/sbin/init"; + elif test -e "/usr/sbin/init"; then + pid1="/usr/sbin/init" + else + init_type="unknown" + init_type_wanted=no + fi + fi + if test -L "$pid1"; then + pid1=`readlink "$pid1"` + fi + fi + + if test "$init_type_wanted" = yes; then + if `echo $pid1 | grep "systemd" > /dev/null`; then + init_type="systemd" + init_type_wanted=no + elif test -f "/sbin/rc"; then + if test -f /sbin/runscript; then + init_type_wanted=no + if `/sbin/start-stop-daemon -V | grep "OpenRC" > /dev/null`; then + init_type="openrc" + else + init_type="gentoo" + fi + fi + fi + fi + + if test "$init_type_wanted" = yes; then + if test "$pid1" = "/sbin/init" -o "$pid1" = "/usr/sbin/init"; then + if `$pid1 --version 2>/dev/null | grep "upstart" >/dev/null`; then + init_type="upstart" + init_type_wanted=no + elif test -f "/etc/rc" -a ! -L "/etc/rc"; then + init_type="newbsd" + init_type_wanted=no + else + init_type="sysv" + init_type_wanted=no + fi + fi + fi + + if test "$init_type_wanted" = yes; then + init_type="unknown" + fi + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $init_type" >&5 +printf "%s\n" "$init_type" >&6; } + + +if test $init_type = systemd ; then + INIT_PERM=0644 +else + INIT_PERM=0755 +fi + + + + + + + + + + + + + + + + + + + + + + + + + + +if test x$DBG_PATHS != x; then + echo + echo Incoming paths: + echo " prefix $prefix" + echo " exec_prefix $exec_prefix" + echo " bindir $bindir" + echo " libexecdir $libexecdir" + echo " sysconfdir $sysconfdir" + echo " localstatedir $localstatedir" + echo " datarootdir $datarootdir" + echo " datadir $datadir" + echo " localedir $localedir" + echo +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for which paths to use " >&5 +printf %s "checking for which paths to use ... " >&6; } + +# Check whether --enable-install_method was given. +if test ${enable_install_method+y} +then : + enableval=$enable_install_method; install_method=$enableval +else $as_nop + install_method=default + +fi + + +# Check whether --enable-showdirs_only was given. +if test ${enable_showdirs_only+y} +then : + enableval=$enable_showdirs_only; showdirs_only=$enableval +else $as_nop + showdirs_only=no + +fi + + +case $install_method in #( + yes) : + install_method="os" ;; #( + no) : + install_method="default" ;; #( + default|os) : + : ;; #( + *) : + echo >&6; as_fn_error $? "'--enable-install-method=$install_method' is invalid" "$LINENO" 5 + ;; #( + *) : + ;; +esac + +if test $showdirs_only != "no"; then showdirs_only="yes"; fi + +case $dist_type in #( + *solaris*|*hp-ux*|*aix*|*osx*) : + opsys=unix ;; #( + *) : + ;; +esac + + + # Does this package need to know: +need_cgi=no # where the cgi-bin directory is +need_web=no # where the website directory is +need_brk=no # where the event broker modules directory is +need_plg=no # where the plugins directory is +need_pipe=no # where the pipe directory is +need_spl=no # where the spool directory is +need_loc=no # where the locale directory is +need_log_subdir=no # where the loc sub-directory is +need_etc_subdir=no # where the etc sub-directory is +need_pls_dir=no # where the package locate state directory is + +if test x"$INIT_PROG" = x; then + INIT_PROG="$PKG_NAME" +fi + +case $PKG_NAME in #( + nagios) : + need_log_subdir=yes + need_etc_subdir=yes + need_pls_dir=yes + need_brk=yes + need_pipe=yes + need_spl=yes + need_loc=yes + need_cgi=yes + need_web=yes ;; #( + ndoutils) : + need_brk=yes + need_spl=yes ;; #( + nrpe) : + need_plg=yes ;; #( + nsca) : + need_cgi=no ;; #( + plugins) : + need_loc=yes + need_plg=yes + ;; #( + *) : + ;; +esac + + +# Check whether --with-pkgsysconfdir was given. +if test ${with_pkgsysconfdir+y} +then : + withval=$with_pkgsysconfdir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + pkgsysconfdir="$withval" + fi +fi + + +# Check whether --with-objsysconfdir was given. +if test ${with_objsysconfdir+y} +then : + withval=$with_objsysconfdir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + objsysconfdir="$withval" + fi +fi + + +# Check whether --with-privatesysconfdir was given. +if test ${with_privatesysconfdir+y} +then : + withval=$with_privatesysconfdir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + privatesysconfdir="$withval" + fi +fi + + +# Check whether --with-webdir was given. +if test ${with_webdir+y} +then : + withval=$with_webdir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + webdir="$withval" + fi +fi + + +# Check whether --with-pluginsdir was given. +if test ${with_pluginsdir+y} +then : + withval=$with_pluginsdir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + pluginsdir="$withval" + fi +fi + + +# Check whether --with-brokersdir was given. +if test ${with_brokersdir+y} +then : + withval=$with_brokersdir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + brokersdir="$withval" + fi +fi + + +# Check whether --with-cgibindir was given. +if test ${with_cgibindir+y} +then : + withval=$with_cgibindir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + cgibindir="$withval" + fi +fi + + +# Check whether --with-logdir was given. +if test ${with_logdir+y} +then : + withval=$with_logdir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + logdir="$withval" + fi +fi + + +# Check whether --with-piddir was given. +if test ${with_piddir+y} +then : + withval=$with_piddir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + piddir="$withval" + fi +fi + + +# Check whether --with-pipedir was given. +if test ${with_pipedir+y} +then : + withval=$with_pipedir; if test x$withval != x -a x$withval != xno -a x$withval != xyes; then + pipedir="$withval" + fi +fi + + + +# +# Setup the base directory +# + +if test $install_method = "default"; then + if test $opsys = "unix"; then + if test x"$prefix" = "xNONE"; then prefix="/usr/local/nagios"; fi + else + if test x"$prefix" = "xNONE"; then prefix=${ac_default_prefix}; fi + fi + datarootdir=${datarootdir="$prefix"} + +else + if test x"$datadir" = x'${datarootdir}'; then { datadir=; unset datadir;}; fi + if test x"$sysconfdir" = x'${prefix}/etc'; then { sysconfdir=; unset sysconfdir;}; fi + + if test x"$prefix" = "xNONE"; then + if test $dist_type = freebsd -o $dist_type = openbsd -o $dist_type = osx; then + prefix="/usr/local" + elif test $dist_type = netbsd; then + prefix="/usr/pkg" + else + prefix="/usr" + fi + fi + if test x"$exec_prefix" = "xNONE"; then exec_prefix=$prefix; fi + if test x"$localstatedir" = x'${prefix}/var'; then + if test $dist_type = "osx"; then + localstatedir="/private/var" + else + localstatedir="/var" + fi + fi + + if test $opsys = "unix"; then + if test x"$datarootdir" = x'${prefix}/share'; then + if test $dist_type = "hp-ux"; then + datarootdir="/usr/local/share" + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/nagios" + fi + elif test $dist_type = "osx"; then + datarootdir="/usr/local/share" + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/local/nagios" + fi + elif test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/lib/nagios" + fi + fi + if test $dist_type = "osx"; then + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir="/usr/local/libexec/nagios" + fi + fi + elif test $opsys = "bsd"; then + if test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir=${exec_prefix}/libexec/nagios; + fi + elif test x"$libexecdir" = x'${exec_prefix}/lib'; then + libexecdir=${libexecdir}/nagios; + elif test x"$libexecdir" = x'${exec_prefix}/libexec'; then + libexecdir=${exec_prefix}/lib/nagios; + fi + +fi + +if test x"$exec_prefix" = "xNONE"; then exec_prefix=${prefix}; fi + +tmpfilesd=${tmpfilesd="/usr/lib/tmpfiles.d"} +if test ! -d "$tmpfilesd"; then + tmpfilesd="N/A" +else + tmpfilesd="$tmpfilesd/$INIT_PROG.conf" +fi +subsyslockdir=${subsyslockdir="/run"} +if test ! -d "$subsyslockdir"; then + subsyslockdir="N/A" + subsyslockfile="N/A" +else + subsyslockfile="$subsyslockdir/$INIT_PROG.lock" +fi +if test "$need_loc" = no; then + localedir="N/A" +fi + +if test $install_method = "default" ; then + # + # Do the default setup + # + datadir=${datadir="$datarootdir"} + if test $need_web = yes; then + webdir=${webdir="$datadir"} + else + webdir="N/A" + fi + if test $opsys = "unix"; then + sysconfdir=${sysconfdir="/etc/opt"} + fi + pkgsysconfdir=${pkgsysconfdir="$sysconfdir"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir"} + logdir=${logdir="$localstatedir"} + piddir=${piddir="$localstatedir"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/rw"} + else + pipedir="N/A" + fi + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir"} + else + pkglocalstatedir="N/A" + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/var"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$bindir"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + cgibindir=${cgibindir="$prefix/sbin"} + else + cgibindir="N/A" + fi + +elif test $opsys = "linux"; then + + # + # Linux "Standard" install + # + install_method="$install_method : FHS" + datadir=${datadir="$datarootdir/nagios"} + if test $need_web = yes; then + webdir=${webdir="$datadir/html"} + else + webdir="N/A" + fi + sysconfdir=${sysconfdir="/etc"} + pkgsysconfdir=${pkgsysconfdir="$sysconfdir/nagios"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir/private"} + if test $need_log_subdir = yes; then + logdir=${logdir="$localstatedir/log/$INIT_PROG"} + else + logdir=${logdir="$localstatedir/log"} + fi + piddir=${piddir="$localstatedir/run/${INIT_PROG}"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/run/${INIT_PROG}"} + else + pipedir="N/A" + fi + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir/lib/$INIT_PROG"} + else + pkglocalstatedir="N/A" + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/spool/$INIT_PROG"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$libexecdir/brokers"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir/plugins"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + cgibindir=${cgibindir="$libexecdir/cgi-bin"} + else + cgibindir="N/A" + fi + +elif test $opsys = "unix"; then + + # + # "Standard" Unix install + # + install_method="$install_method : Unix Standard" + if test $dist_type = osx; then + install_method="$install_method : OS X Standard" + fi + datadir=${datadir="$datarootdir/nagios"} + if test $need_web = yes; then + webdir=${webdir="$datadir/html"} + else + webdir="N/A" + fi + if test $dist_type = osx; then + sysconfdir=${sysconfdir="/private/etc"} + else + sysconfdir=${sysconfdir="/etc"} + fi + pkgsysconfdir=${pkgsysconfdir="$sysconfdir/nagios"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir/private"} + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir/lib/$INIT_PROG"} + else + pkglocalstatedir="N/A" + fi + if test "$need_loc" = yes; then + localedir=${localedir="/usr/local/share/locale//LC_MESSAGES/nagios-plugins.mo"} + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/spool/$INIT_PROG"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$libexecdir/brokers"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir/plugins"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + cgibindir=${cgibindir="$libexecdir/cgi-bin"} + else + cgibindir="N/A" + fi + case $dist_type in #( + *hp-ux*) : + piddir=${piddir="$pkgsysconfdir"} + pipedir=${pipedir="$pkglocalstatedir"} + logdir=${logdir="$pkglocalstatedir/log"} ;; #( + *) : + piddir=${piddir="$localstatedir/run/${INIT_PROG}"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/run/${INIT_PROG}"} + else + pipedir="N/A" + fi + if test $need_log_subdir = yes; then + logdir=${logdir="$localstatedir/log/$INIT_PROG"} + else + logdir=${logdir="$localstatedir/log"} + fi + ;; #( + *) : + ;; +esac + +elif test $opsys = "bsd"; then + + # + # "Standard" BSD install + # + install_method="$install_method : BSD" + if test $dist_type = freebsd -o $dist_type = openbsd; then + prefix=${prefix="/usr/local"} + exec_prefix=${exec_prefix="/usr/local"} + if test $dist_type = freebsd; then + install_method="$install_method : FreeBSD" + else + install_method="$install_method : OpenBSD" + fi + elif test $dist_type = netbsd; then + prefix=${prefix="/usr/pkg"} + exec_prefix=${exec_prefix="/usr/pkg"} + install_method="$install_method : NetBSD" + fi + datadir=${datadir="$datarootdir/nagios"} + if test $need_web = yes -o $need_cgi = yes; then + if test $dist_type = freebsd; then + webdir=${webdir="$prefix/www/nagios"} + elif test $dist_type = netbsd; then + webdir=${webdir="$prefix/share/nagios"} + elif test $dist_type = openbsd; then + webdir=${webdir="/var/www/nagios"} + fi + else + webdir="N/A" + fi + if test $dist_type = freebsd; then + sysconfdir=${sysconfdir="/usr/local/etc"} + else + sysconfdir=${sysconfdir="/etc"} + fi + pkgsysconfdir=${pkgsysconfdir="$sysconfdir/nagios"} + if test $need_etc_subdir = yes; then + objsysconfdir=${objsysconfdir="$pkgsysconfdir/objects"} + else + objsysconfdir="N/A" + fi + privatesysconfdir=${privatesysconfdir="$pkgsysconfdir/private"} + if test "$need_pls_dir" = yes; then + pkglocalstatedir=${pkglocalstatedir="$localstatedir/lib/$INIT_PROG"} + else + pkglocalstatedir="N/A" + fi + if test "$need_loc" = yes; then + localedir=${localedir="/usr/local/share/locale//LC_MESSAGES/nagios-plugins.mo"} + fi + if test "$need_spl" = yes; then + spooldir=${spooldir="$localstatedir/spool/$INIT_PROG"} + else + spooldir="N/A" + fi + if test $need_brk = yes; then + brokersdir=${brokersdir="$libexecdir/brokers"} + else + brokersdir="N/A" + fi + if test $need_plg = yes; then + pluginsdir=${pluginsdir="$libexecdir/plugins"} + else + pluginsdir="N/A" + fi + if test $need_cgi = yes; then + if test $dist_type = freebsd; then + cgibindir=${cgibindir="$webdir/cgi-bin"} + elif test $dist_type = netbsd; then + cgibindir=${pluginsdir="$libexecdir/cgi-bin"} + elif test $dist_type = openbsd; then + cgibindir=${pluginsdir="/var/www/cgi-bin/nagios"} + fi + else + cgibindir="N/A" + fi + piddir=${piddir="$localstatedir/run/${INIT_PROG}"} + if test "$need_pipe" = yes; then + pipedir=${pipedir="$localstatedir/run/${INIT_PROG}"} + else + pipedir="N/A" + fi + if test $need_log_subdir = yes; then + logdir=${logdir="$localstatedir/log/$INIT_PROG"} + else + logdir=${logdir="$localstatedir/log"} + fi + +else + + # + # Unknown install + # + install_method="unknown" + webdir=unknown + pkgsysconfdir=unknown + objsysconfdir=unknown + privatesysconfdir=unknown + logdir=unknown + piddir=unknown + pipedir=unknown + pkglocalstatedir=unknown + spooldir=unknown + brokersdir=unknown + pluginsdir=unknown + cgibindir=unknown + +fi + +eval prefix=$prefix +eval exec_prefix=$exec_prefix +eval bindir=$bindir +eval datarootdir=$datarootdir +eval datadir=$datadir +eval libexecdir=$libexecdir +eval brokersdir=$brokersdir +eval pluginsdir=$pluginsdir +eval cgibindir=$cgibindir +eval localstatedir=$localstatedir +eval pkglocalstatedir=$pkglocalstatedir +eval webdir=$webdir +eval localedir=$localedir +eval sysconfdir=$sysconfdir +eval pkgsysconfdir=$pkgsysconfdir +eval piddir=$piddir + + +# We test systemd first because in case +# someone tries to install Nagios on a +# system with a newer version, that doesn't +# have the defined versions ..we can just +# (hopefully) fall back to SysV +# And if that doesn't work, well... +case $init_type in #( + systemd) : + if test -d "/lib/systemd/system"; then + initdir=${initdir="/lib/systemd/system"} + elif test -d "/usr/lib/systemd/system"; then + initdir=${initdir="/usr/lib/systemd/system"} + elif test -d "/usr/local/lib/systemd/system"; then + initdir=${initdir="/usr/local/lib/systemd/system"} + elif test -d "/run/systemd/system"; then + initdir=${initdir="/run/systemd/system"} + elif test -d "/etc/systemd/system"; then + initdir=${initdir="/etc/systemd/system"} + elif test -d "/etc/systemd/user"; then + initdir=${initdir="/etc/systemd/user"} + elif test -d "/run/systemd/user"; then + initdir=${initdir="/run/systemd/user"} + elif test -d "/usr/lib/systemd/user"; then + initdir=${initdir="/usr/lib/systemd/user"} + elif test -d "/usr/local/lib/systemd/user"; then + initdir=${initdir="/usr/local/lib/systemd/user"} + elif test -d "/usr/share/systemd/user"; then + initdir=${initdir="/usr/share/systemd/user"} + elif test -d "/usr/local/share/systemd/user"; then + initdir=${initdir="/usr/local/share/systemd/user"} + elif test -d "$HOME/.config/systemd/user"; then + initdir=${initdir="$HOME/.config/systemd/user"} + elif test -d "$HOME/.local/share/systemd/user"; then + initdir=${initdir="$HOME/.local/share/systemd/user"} + elif test -d "$XDG_CONFIG_HOME/systemd/user/"; then + initdir=${initdir="$XDG_CONFIG_HOME/systemd/user/"} + elif test -d "$XDG_RUNTIME_DIR/systemd/user/"; then + initdir=${initdir="$XDG_RUNTIME_DIR/systemd/user/"} + elif test -d "$XDG_DATA_HOME/systemd/user/"; then + initdir=${initdir="$XDG_DATA_HOME/systemd/user/"} + else + init_type="sysv" + fi + initname=${initname="$INIT_PROG.service"} ;; #( + *) : + ;; +esac + +# +# Init scripts/files +# +case $init_type in #( + sysv) : + if test $dist_type = "hp-ux"; then + initdir=${initdir="/sbin/init.d"} + else + initdir=${initdir="/etc/init.d"} + fi + initname=${initname="$INIT_PROG"} + initconfdir=${initconfdir="/etc/conf.d"} + initconf=${initconf="$initconfdir/$INIT_PROG"} ;; #( + bsd) : + if test $dist_type = "aix"; then + initdir=${initdir="/sbin/rc.d/init.d"} + initname=${initname="$INIT_PROG"} + else + initdir=${initdir="/etc/rc.d"} + initname=${initname="rc.$INIT_PROG"} + fi ;; #( + newbsd) : + initdir=${initdir="/usr/local/etc/rc.d"} + initname=${initname="$INIT_PROG"} ;; #( + gentoo) : + initdir=${initdir="/etc/init.d"} + initname=${initname="$INIT_PROG"} + initconfdir=${initconfdir="/etc/init.d"} + initconf=${initconf="$initconfdir/$INIT_PROG"} ;; #( + openrc) : + initdir=${initdir="/etc/init.d"} + initname=${initname="$INIT_PROG"} + initconfdir=${initconfdir="/etc/conf.d"} + initconf=${initconf="$initconfdir/$INIT_PROG"} ;; #( + smf*) : + if test $init_type = smf10; then + initdir=${initdir="/var/svc/manifest/network/nagios"} + else + initdir=${initdir="/lib/svc/manifest/network/nagios"} + fi + initname=${initname="$INIT_PROG.xml"} + initconfdir=unknown + initconf=unknown ;; #( + upstart) : + initdir=${initdir="/etc/init"} + initname=${initname="$INIT_PROG.conf"} + initconfdir=${initconfdir="/etc/default"} + initconf=${initconf="$initconfdir/$INIT_PROG"} ;; #( + launchd) : + initdir=${initdir="/Library/LaunchDaemons"} + initname=${initname="org.nagios.$INIT_PROG.plist"} ;; #( + # initconfdir=${initconfdir="/private/etc"} +# initconf=${initconf="$initconfdir/$INIT_PROG"}, + + systemd) : + init_type=systemd ;; #( + *) : + initdir=unknown + initname=unknown ;; #( + *) : + ;; +esac + +# Now see if they supplied any overwriting values +initdiroverridden=no + +# Check whether --with-initdir was given. +if test ${with_initdir+y} +then : + withval=$with_initdir; initdir=$withval + initdiroverridden=yes +else $as_nop + initdir=$initdir + +fi + + +# +# Inetd (per connection) scripts/files +# +case $inetd_type in #( + inetd*) : + inetddir=${inetddir="/etc"} + inetdname=${inetdname="inetd.conf"} ;; #( + xinetd) : + inetddir=${inetddir="/etc/xinetd.d"} + inetdname=${inetdname="$INIT_PROG"} ;; #( + systemd) : + if test $dist_type = "debian"; then + inetddir=${inetddir="/lib/systemd/system"} + else + inetddir=${inetddir="/usr/lib/systemd/system"} + fi + netdname=${inetdname="$INIT_PROG.socket"} ;; #( + smf*) : + if test $init_type = smf10; then + inetddir=${inetddir="/var/svc/manifest/network/nagios"} + else + inetddir=${inetddir="/lib/svc/manifest/network/nagios"} + fi + inetdname=${inetdname="$INIT_PROG.xml"} ;; #( + # [upstart], +# inetddir=${inetddir="/etc/init.d"} +# inetdname=${inetdname="$INIT_PROG"}, + + launchd) : + inetddir=${inetddir="/Library/LaunchDaemons"} + inetdname=${inetdname="org.nagios.$INIT_PROG.plist"} ;; #( + *) : + inetddir=${inetddir="unknown"} + inetdname=${inetdname="unknown"} ;; #( + *) : + ;; +esac + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $install_method" >&5 +printf "%s\n" "$install_method" >&6; } + + + + + + + + +src_inetd="" +src_init="" +bsd_enable="" + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for which init file to use " >&5 +printf %s "checking for which init file to use ... " >&6; } + +case $init_type in #( + sysv) : + src_init=default-init ;; #( + systemd) : + src_tmpfile=tmpfile.conf + src_init=default-service ;; #( + bsd) : + src_init=bsd-init ;; #( + newbsd) : + if test $dist_type = freebsd ; then + bsd_enable="_enable" + src_init=default-init + elif test $dist_type = openbsd ; then + bsd_enable="_flags" + src_init=openbsd-init + elif test $dist_type = netbsd ; then + bsd_enable="" + src_init=newbsd-init + fi ;; #( + # [gentoo], + + openrc) : + src_init=openrc-init ;; #( + smf*) : + src_init="solaris-init.xml" + src_inetd="solaris-inetd.xml" ;; #( + upstart) : + if test $dist_type = rh ; then + src_init=rh-upstart-init + else + src_init=upstart-init + fi ;; #( + launchd) : + src_init="mac-init.plist" ;; #( + *) : + src_init="unknown" + ;; #( + *) : + ;; +esac +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $src_init" >&5 +printf "%s\n" "$src_init" >&6; } + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for which inetd files to use " >&5 +printf %s "checking for which inetd files to use ... " >&6; } + +if test x$src_inetd = x; then + + case $inetd_type in #( + inetd*) : + src_inetd=default-inetd ;; #( + xinetd) : + src_inetd=default-xinetd ;; #( + systemd) : + src_inetd=default-socket ;; #( + launchd) : + src_inetd="mac-inetd.plist" ;; #( + *) : + src_inetd="unknown" + ;; #( + *) : + ;; +esac + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $src_inetd" >&5 +printf "%s\n" "$src_inetd" >&6; } + + +if test $opsys = bsd -a $dist_type = netbsd ; then + sysconfdir="${prefix}/etc" + pkgsysconfdir="${sysconfdir}/pnp4nagios" + datarootdir="${datarootdir}/pnp4nagios" + libdir="${prefix}/lib/pnp4nagios" + libexecdir="${prefix}/libexec/pnp4nagios" + if test $initdiroverridden = no -a $init_type = newbsd ; then + initdir=/etc/rc.d + fi +fi + + +# for some reason AX_NAGIOS_GET_PATHS doesn't AC_SUBST this... + + + + # Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 +printf %s "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if test ${ac_cv_path_install+y} +then : + printf %s "(cached) " >&6 +else $as_nop + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + # Account for fact that we put trailing slashes in our PATH walk. +case $as_dir in #(( + ./ | /[cC]/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_prog$ac_exec_ext"; then + if test $ac_prog = install && + grep dspmsg "$as_dir$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir/" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; +esac + + done +IFS=$as_save_IFS + +rm -rf conftest.one conftest.two conftest.dir + +fi + if test ${ac_cv_path_install+y}; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 +printf "%s\n" "$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + +INSTALL_SUFFIX="-S" +inbk=`install --help 2>&1|grep -o -e '-B suffix'|head -n 1` +if test "$inbk" = "-B suffix" ; then + INSTALL_SUFFIX="-B" +fi + + + + + + + + + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +printf "%s\n" "$ac_ct_CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + if test "$as_dir$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +printf "%s\n" "$ac_ct_CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}clang", so it can be a program name with args. +set dummy ${ac_tool_prefix}clang; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}clang" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +printf "%s\n" "$CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "clang", so it can be a program name with args. +set dummy clang; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_CC+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="clang" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +printf "%s\n" "$ac_ct_CC" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +fi + + +test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion -version; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main (void) +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +printf %s "checking whether the C compiler works... " >&6; } +ac_link_default=`printf "%s\n" "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test ${ac_cv_exeext+y} && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else $as_nop + ac_file='' +fi +if test -z "$ac_file" +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +printf %s "checking for C compiler default output file name... " >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +printf "%s\n" "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +printf %s "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else $as_nop + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +printf "%s\n" "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main (void) +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +printf %s "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +printf "%s\n" "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +printf %s "checking for suffix of object files... " >&6; } +if test ${ac_cv_objext+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main (void) +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +printf "%s\n" "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else $as_nop + printf "%s\n" "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +printf "%s\n" "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the compiler supports GNU C" >&5 +printf %s "checking whether the compiler supports GNU C... " >&6; } +if test ${ac_cv_c_compiler_gnu+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main (void) +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_compiler_gnu=yes +else $as_nop + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +printf "%s\n" "$ac_cv_c_compiler_gnu" >&6; } +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+y} +ac_save_CFLAGS=$CFLAGS +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +printf %s "checking whether $CC accepts -g... " >&6; } +if test ${ac_cv_prog_cc_g+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_g=yes +else $as_nop + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + +else $as_nop + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +printf "%s\n" "$ac_cv_prog_cc_g" >&6; } +if test $ac_test_CFLAGS; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +ac_prog_cc_stdc=no +if test x$ac_prog_cc_stdc = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C11 features" >&5 +printf %s "checking for $CC option to enable C11 features... " >&6; } +if test ${ac_cv_prog_cc_c11+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_cv_prog_cc_c11=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_c_conftest_c11_program +_ACEOF +for ac_arg in '' -std=gnu11 +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_c11=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + test "x$ac_cv_prog_cc_c11" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC +fi + +if test "x$ac_cv_prog_cc_c11" = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +printf "%s\n" "unsupported" >&6; } +else $as_nop + if test "x$ac_cv_prog_cc_c11" = x +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +printf "%s\n" "none needed" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5 +printf "%s\n" "$ac_cv_prog_cc_c11" >&6; } + CC="$CC $ac_cv_prog_cc_c11" +fi + ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c11 + ac_prog_cc_stdc=c11 +fi +fi +if test x$ac_prog_cc_stdc = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C99 features" >&5 +printf %s "checking for $CC option to enable C99 features... " >&6; } +if test ${ac_cv_prog_cc_c99+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_cv_prog_cc_c99=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_c_conftest_c99_program +_ACEOF +for ac_arg in '' -std=gnu99 -std=c99 -c99 -qlanglvl=extc1x -qlanglvl=extc99 -AC99 -D_STDC_C99= +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_c99=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + test "x$ac_cv_prog_cc_c99" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC +fi + +if test "x$ac_cv_prog_cc_c99" = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +printf "%s\n" "unsupported" >&6; } +else $as_nop + if test "x$ac_cv_prog_cc_c99" = x +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +printf "%s\n" "none needed" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 +printf "%s\n" "$ac_cv_prog_cc_c99" >&6; } + CC="$CC $ac_cv_prog_cc_c99" +fi + ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c99 + ac_prog_cc_stdc=c99 +fi +fi +if test x$ac_prog_cc_stdc = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $CC option to enable C89 features" >&5 +printf %s "checking for $CC option to enable C89 features... " >&6; } +if test ${ac_cv_prog_cc_c89+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_c_conftest_c89_program +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC +fi + +if test "x$ac_cv_prog_cc_c89" = xno +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +printf "%s\n" "unsupported" >&6; } +else $as_nop + if test "x$ac_cv_prog_cc_c89" = x +then : + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +printf "%s\n" "none needed" >&6; } +else $as_nop + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +printf "%s\n" "$ac_cv_prog_cc_c89" >&6; } + CC="$CC $ac_cv_prog_cc_c89" +fi + ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c89 + ac_prog_cc_stdc=c89 +fi +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +printf %s "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`printf "%s\n" "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval test \${ac_cv_prog_make_${ac_make}_set+y} +then : + printf %s "(cached) " >&6 +else $as_nop cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' _ACEOF -# GNU make sometimes prints "make[1]: Entering...", which would confuse us. +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. case `${MAKE-make} -f conftest.make 2>/dev/null` in *@@@%%%=?*=@@@%%%*) eval ac_cv_prog_make_${ac_make}_set=yes;; @@ -2914,22 +5311,23 @@ esac rm -f conftest.make fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } SET_MAKE= else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } SET_MAKE="MAKE=${MAKE-make}" fi # Extract the first word of "strip", so it can be a program name with args. set dummy strip; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_STRIP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_STRIP+y} +then : + printf %s "(cached) " >&6 +else $as_nop case $STRIP in [\\/]* | ?:[\\/]*) ac_cv_path_STRIP="$STRIP" # Let the user override the test with a path. @@ -2939,15 +5337,19 @@ else for as_dir in $PATH do IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_STRIP="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_STRIP="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS test -z "$ac_cv_path_STRIP" && ac_cv_path_STRIP="true" @@ -2956,332 +5358,54 @@ esac fi STRIP=$ac_cv_path_STRIP if test -n "$STRIP"; then - { echo "$as_me:$LINENO: result: $STRIP" >&5 -echo "${ECHO_T}$STRIP" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $STRIP" >&5 +printf "%s\n" "$STRIP" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } fi - - - -# Extract the first word of "cp", so it can be a program name with args. -set dummy cp; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_CP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - case $CP in - [\\/]* | ?:[\\/]*) - ac_cv_path_CP="$CP" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_CP="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done -done -IFS=$as_save_IFS - - ;; -esac -fi -CP=$ac_cv_path_CP -if test -n "$CP"; then - { echo "$as_me:$LINENO: result: $CP" >&5 -echo "${ECHO_T}$CP" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } -fi - - - -# Checks for libraries. - -# Checks for header files. - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu -{ echo "$as_me:$LINENO: checking how to run the C preprocessor" >&5 -echo $ECHO_N "checking how to run the C preprocessor... $ECHO_C" >&6; } -# On Suns, sometimes $CPP names a directory. -if test -n "$CPP" && test -d "$CPP"; then - CPP= -fi -if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Double quotes because CPP needs to be expanded - for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" - do - ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - # Broken: fails on valid input. -continue -fi - -rm -f conftest.err conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - # Broken: success on invalid input. -continue -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - # Passes both tests. -ac_preproc_ok=: -break -fi - -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - break -fi - - done - ac_cv_prog_CPP=$CPP - -fi - CPP=$ac_cv_prog_CPP -else - ac_cv_prog_CPP=$CPP -fi -{ echo "$as_me:$LINENO: result: $CPP" >&5 -echo "${ECHO_T}$CPP" >&6; } -ac_preproc_ok=false -for ac_c_preproc_warn_flag in '' yes -do - # Use a header file that comes with gcc, so configuring glibc - # with a fresh cross-compiler works. - # Prefer to if __STDC__ is defined, since - # exists even on freestanding compilers. - # On the NeXT, cc -E runs the code through the compiler's parser, - # not just through cpp. "Syntax error" is here to catch this case. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#ifdef __STDC__ -# include -#else -# include -#endif - Syntax error -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - : -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - # Broken: fails on valid input. -continue -fi - -rm -f conftest.err conftest.$ac_ext - - # OK, works on sane cases. Now check whether nonexistent headers - # can be detected and how. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - # Broken: success on invalid input. -continue -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - # Passes both tests. -ac_preproc_ok=: -break -fi - -rm -f conftest.err conftest.$ac_ext - -done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. -rm -f conftest.err conftest.$ac_ext -if $ac_preproc_ok; then - : -else - { { echo "$as_me:$LINENO: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&5 -echo "$as_me: error: C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details." >&2;} - { (exit 1); exit 1; }; } -fi - -ac_ext=c -ac_cpp='$CPP $CPPFLAGS' -ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' -ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' -ac_compiler_gnu=$ac_cv_c_compiler_gnu - - -{ echo "$as_me:$LINENO: checking for grep that handles long lines and -e" >&5 -echo $ECHO_N "checking for grep that handles long lines and -e... $ECHO_C" >&6; } -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - # Extract the first word of "grep ggrep" to use in msg output -if test -z "$GREP"; then -set dummy grep ggrep; ac_prog_name=$2 -if test "${ac_cv_path_GREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +printf %s "checking for grep that handles long lines and -e... " >&6; } +if test ${ac_cv_path_GREP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -z "$GREP"; then ac_path_GREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in grep ggrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue - # Check for GNU ac_path_GREP and select it if it is found. + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in grep ggrep + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_GREP" || continue +# Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP case `"$ac_path_GREP" --version 2>&1` in *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; *) ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + printf %s 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" - echo 'GREP' >> "conftest.nl" + printf "%s\n" 'GREP' >> "conftest.nl" "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` + as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_GREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_GREP="$ac_path_GREP" @@ -3293,77 +5417,67 @@ case `"$ac_path_GREP" --version 2>&1` in rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac - - $ac_path_GREP_found && break 3 + $ac_path_GREP_found && break 3 + done + done done -done - -done IFS=$as_save_IFS - - -fi - -GREP="$ac_cv_path_GREP" -if test -z "$GREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } -fi - + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi else ac_cv_path_GREP=$GREP fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_GREP" >&5 -echo "${ECHO_T}$ac_cv_path_GREP" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +printf "%s\n" "$ac_cv_path_GREP" >&6; } GREP="$ac_cv_path_GREP" -{ echo "$as_me:$LINENO: checking for egrep" >&5 -echo $ECHO_N "checking for egrep... $ECHO_C" >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +printf %s "checking for egrep... " >&6; } +if test ${ac_cv_path_EGREP+y} +then : + printf %s "(cached) " >&6 +else $as_nop if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else - # Extract the first word of "egrep" to use in msg output -if test -z "$EGREP"; then -set dummy egrep; ac_prog_name=$2 -if test "${ac_cv_path_EGREP+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else + if test -z "$EGREP"; then ac_path_EGREP_found=false -# Loop through the user's path and test for each of PROGNAME-LIST -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin do IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_prog in egrep; do - for ac_exec_ext in '' $ac_executable_extensions; do - ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" - { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue - # Check for GNU ac_path_EGREP and select it if it is found. + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in egrep + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP case `"$ac_path_EGREP" --version 2>&1` in *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; *) ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >"conftest.in" + printf %s 0123456789 >"conftest.in" while : do cat "conftest.in" "conftest.in" >"conftest.tmp" mv "conftest.tmp" "conftest.in" cp "conftest.in" "conftest.nl" - echo 'EGREP' >> "conftest.nl" + printf "%s\n" 'EGREP' >> "conftest.nl" "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break - ac_count=`expr $ac_count + 1` + as_fn_arith $ac_count + 1 && ac_count=$as_val if test $ac_count -gt ${ac_path_EGREP_max-0}; then # Best one so far, save it but keep looking for a better one ac_cv_path_EGREP="$ac_path_EGREP" @@ -3375,1319 +5489,467 @@ case `"$ac_path_EGREP" --version 2>&1` in rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac - - $ac_path_EGREP_found && break 3 + $ac_path_EGREP_found && break 3 + done + done done -done - -done IFS=$as_save_IFS - - -fi - -EGREP="$ac_cv_path_EGREP" -if test -z "$EGREP"; then - { { echo "$as_me:$LINENO: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&5 -echo "$as_me: error: no acceptable $ac_prog_name could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" >&2;} - { (exit 1); exit 1; }; } -fi - + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi else ac_cv_path_EGREP=$EGREP fi - fi fi -{ echo "$as_me:$LINENO: result: $ac_cv_path_EGREP" >&5 -echo "${ECHO_T}$ac_cv_path_EGREP" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +printf "%s\n" "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" -{ echo "$as_me:$LINENO: checking for ANSI C header files" >&5 -echo $ECHO_N "checking for ANSI C header files... $ECHO_C" >&6; } -if test "${ac_cv_header_stdc+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#include -#include - -int -main () -{ - - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_stdc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_stdc=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext - -if test $ac_cv_header_stdc = yes; then - # SunOS 4.x string.h does not declare mem*, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "memchr" >/dev/null 2>&1; then - : -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "free" >/dev/null 2>&1; then - : -else - ac_cv_header_stdc=no -fi -rm -f conftest* - -fi - -if test $ac_cv_header_stdc = yes; then - # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. - if test "$cross_compiling" = yes; then - : -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#if ((' ' & 0x0FF) == 0x020) -# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') -# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) -#else -# define ISLOWER(c) \ - (('a' <= (c) && (c) <= 'i') \ - || ('j' <= (c) && (c) <= 'r') \ - || ('s' <= (c) && (c) <= 'z')) -# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) -#endif - -#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) -int -main () -{ - int i; - for (i = 0; i < 256; i++) - if (XOR (islower (i), ISLOWER (i)) - || toupper (i) != TOUPPER (i)) - return 2; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then - : -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_header_stdc=no -fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext -fi - - -fi -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_stdc" >&5 -echo "${ECHO_T}$ac_cv_header_stdc" >&6; } -if test $ac_cv_header_stdc = yes; then - -cat >>confdefs.h <<\_ACEOF -#define STDC_HEADERS 1 -_ACEOF - -fi - - - - - - -ac_header_dirent=no -for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do - as_ac_Header=`echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_hdr that defines DIR" >&5 -echo $ECHO_N "checking for $ac_hdr that defines DIR... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include <$ac_hdr> - -int -main () -{ -if ((DIR *) 0) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 -_ACEOF - -ac_header_dirent=$ac_hdr; break -fi - -done -# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. -if test $ac_header_dirent = dirent.h; then - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } -if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char opendir (); -int -main () -{ -return opendir (); - ; - return 0; -} -_ACEOF -for ac_lib in '' dir; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_search_opendir=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then - break -fi -done -if test "${ac_cv_search_opendir+set}" = set; then - : -else - ac_cv_search_opendir=no -fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } -ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" - -fi - -else - { echo "$as_me:$LINENO: checking for library containing opendir" >&5 -echo $ECHO_N "checking for library containing opendir... $ECHO_C" >&6; } -if test "${ac_cv_search_opendir+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - ac_func_search_save_LIBS=$LIBS -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char opendir (); -int -main () -{ -return opendir (); - ; - return 0; -} -_ACEOF -for ac_lib in '' x; do - if test -z "$ac_lib"; then - ac_res="none required" - else - ac_res=-l$ac_lib - LIBS="-l$ac_lib $ac_func_search_save_LIBS" - fi - rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - ac_cv_search_opendir=$ac_res -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext - if test "${ac_cv_search_opendir+set}" = set; then - break -fi -done -if test "${ac_cv_search_opendir+set}" = set; then - : -else - ac_cv_search_opendir=no -fi -rm conftest.$ac_ext -LIBS=$ac_func_search_save_LIBS -fi -{ echo "$as_me:$LINENO: result: $ac_cv_search_opendir" >&5 -echo "${ECHO_T}$ac_cv_search_opendir" >&6; } -ac_res=$ac_cv_search_opendir -if test "$ac_res" != no; then - test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" - -fi - -fi - -{ echo "$as_me:$LINENO: checking for sys/wait.h that is POSIX.1 compatible" >&5 -echo $ECHO_N "checking for sys/wait.h that is POSIX.1 compatible... $ECHO_C" >&6; } -if test "${ac_cv_header_sys_wait_h+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include -#ifndef WEXITSTATUS -# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) -#endif -#ifndef WIFEXITED -# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) -#endif - -int -main () -{ - int s; - wait (&s); - s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_header_sys_wait_h=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_header_sys_wait_h=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_header_sys_wait_h" >&5 -echo "${ECHO_T}$ac_cv_header_sys_wait_h" >&6; } -if test $ac_cv_header_sys_wait_h = yes; then - -cat >>confdefs.h <<\_ACEOF -#define HAVE_SYS_WAIT_H 1 -_ACEOF - -fi - -#AC_CHECK_HEADERS(netinet/in.h string.h sys/socket.h unistd.h stdio.h stdlib.h getopt.h signal.h) -# On IRIX 5.3, sys/types and inttypes.h are conflicting. - - - - - - - - - -for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ - inttypes.h stdint.h unistd.h +for ac_prog in gawk mawk nawk awk do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_AWK+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default - -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - eval "$as_ac_Header=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_Header=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - - - - - - - - - - - - - - - - - - - - - - - - -for ac_header in dirent.h stdio.h errno.h unistd.h syslog.h signal.h stdlib.h dirent.h string.h pthread.h getopt.h grp.h pwd.h sys/mman.h sys/types.h sys/wait.h sys/stat.h sys/socket.h sys/loadavg.h netinet/in.h fcntl.h limits.h +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_AWK="$ac_prog" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 +printf "%s\n" "$AWK" >&6; } else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ----------------------------------------------------- ## -## Report this to pnp4nagios-devel@lists.sourceforge.net ## -## ----------------------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } - -fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi + test -n "$AWK" && break done - -# Checks for typedefs, structures, and compiler characteristics. -{ echo "$as_me:$LINENO: checking for pid_t" >&5 -echo $ECHO_N "checking for pid_t... $ECHO_C" >&6; } -if test "${ac_cv_type_pid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -typedef pid_t ac__type_new_; -int -main () -{ -if ((ac__type_new_ *) 0) - return 0; -if (sizeof (ac__type_new_)) - return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 +printf %s "checking for a sed that does not truncate output... " >&6; } +if test ${ac_cv_path_SED+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ + for ac_i in 1 2 3 4 5 6 7; do + ac_script="$ac_script$as_nl$ac_script" + done + echo "$ac_script" 2>/dev/null | sed 99q >conftest.sed + { ac_script=; unset ac_script;} + if test -z "$SED"; then + ac_path_SED_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_prog in sed gsed + do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_SED="$as_dir$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_SED" || continue +# Check for GNU ac_path_SED and select it if it is found. + # Check for GNU $ac_path_SED +case `"$ac_path_SED" --version 2>&1` in +*GNU*) + ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; +*) + ac_count=0 + printf %s 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + printf "%s\n" '' >> "conftest.nl" + "$ac_path_SED" -f conftest.sed < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_SED_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_SED="$ac_path_SED" + ac_path_SED_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_pid_t=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - ac_cv_type_pid_t=no + $ac_path_SED_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_SED"; then + as_fn_error $? "no acceptable sed could be found in \$PATH" "$LINENO" 5 + fi +else + ac_cv_path_SED=$SED fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_pid_t" >&5 -echo "${ECHO_T}$ac_cv_type_pid_t" >&6; } -if test $ac_cv_type_pid_t = yes; then - : +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 +printf "%s\n" "$ac_cv_path_SED" >&6; } + SED="$ac_cv_path_SED" + rm -f conftest.sed + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 +printf %s "checking whether ln -s works... " >&6; } +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } else - -cat >>confdefs.h <<_ACEOF -#define pid_t int -_ACEOF - + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 +printf "%s\n" "no, using $LN_S" >&6; } fi -{ echo "$as_me:$LINENO: checking return type of signal handlers" >&5 -echo $ECHO_N "checking return type of signal handlers... $ECHO_C" >&6; } -if test "${ac_cv_type_signal+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include -#include +# Extract the first word of "cp", so it can be a program name with args. +set dummy cp; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_CP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $CP in + [\\/]* | ?:[\\/]*) + ac_cv_path_CP="$CP" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_CP="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS -int -main () -{ -return *(signal (0, 0)) (0) == 1; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_type_signal=int +fi +CP=$ac_cv_path_CP +if test -n "$CP"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CP" >&5 +printf "%s\n" "$CP" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_type_signal=void -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_signal" >&5 -echo "${ECHO_T}$ac_cv_type_signal" >&6; } - -cat >>confdefs.h <<_ACEOF -#define RETSIGTYPE $ac_cv_type_signal -_ACEOF - - -{ echo "$as_me:$LINENO: checking for uid_t in sys/types.h" >&5 -echo $ECHO_N "checking for uid_t in sys/types.h... $ECHO_C" >&6; } -if test "${ac_cv_type_uid_t+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include - -_ACEOF -if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | - $EGREP "uid_t" >/dev/null 2>&1; then - ac_cv_type_uid_t=yes -else - ac_cv_type_uid_t=no -fi -rm -f conftest* - -fi -{ echo "$as_me:$LINENO: result: $ac_cv_type_uid_t" >&5 -echo "${ECHO_T}$ac_cv_type_uid_t" >&6; } -if test $ac_cv_type_uid_t = no; then - -cat >>confdefs.h <<\_ACEOF -#define uid_t int -_ACEOF - - -cat >>confdefs.h <<\_ACEOF -#define gid_t int -_ACEOF - + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } fi -# Checks for structure members -#AC_CHECK_MEMBER([struct dirent.d_type], [AC_MSG_RESULT([We successfully have a `dirent_d_type'!])], -# [AC_MSG_ERROR([We need `dirent.d_type'!])], -# [#include ]) +# Extract the first word of "perl", so it can be a program name with args. +set dummy perl; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_PERL+y} +then : + printf %s "(cached) " >&6 +else $as_nop + case $PERL in + [\\/]* | ?:[\\/]*) + ac_cv_path_PERL="$PERL" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_PERL="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS - - - { echo "$as_me:$LINENO: checking for struct dirent.d_type" >&5 -echo $ECHO_N "checking for struct dirent.d_type... $ECHO_C" >&6; } -if test "${ac_cv_member_struct_dirent_d_type+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef HAVE_DIRENT_H -# include -#else -# define dirent direct -# ifdef HAVE_SYS_NDIR_H -# include -# endif -# ifdef HAVE_SYS_DIR_H -# include -# endif -# ifdef HAVE_NDIR_H -# include -# endif -#endif - - -int -main () -{ -static struct dirent ac_aggr; -if (ac_aggr.d_type) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; + ;; esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_dirent_d_type=yes +fi +PERL=$ac_cv_path_PERL +if test -n "$PERL"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PERL" >&5 +printf "%s\n" "$PERL" >&6; } else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ - -#include -#ifdef HAVE_DIRENT_H -# include -#else -# define dirent direct -# ifdef HAVE_SYS_NDIR_H -# include -# endif -# ifdef HAVE_SYS_DIR_H -# include -# endif -# ifdef HAVE_NDIR_H -# include -# endif -#endif + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi -int -main () -{ -static struct dirent ac_aggr; -if (sizeof ac_aggr.d_type) -return 0; - ; - return 0; -} -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_cv_member_struct_dirent_d_type=yes + +eval sbindir=$sbindir + +# Checks for libraries. +if test "q$target_cpu" = "qx86_64" +then : + x64="64" +else $as_nop + x64="" +fi + +if test x$libdir = x ; then + if test -d "/usr/lib${x64}" ; then + libdir="${prefix}/usr/lib${x64}/${PACKAGE_NAME}" + elif test -d "/lib${x64}"; then + libdir="${prefix}/lib${x64}/${PACKAGE_NAME}" + elif test -d "/usr/lib" ; then + libdir="${prefix}/usr/lib/${PACKAGE_NAME}" + else + libdir="${prefix}/lib/${PACKAGE_NAME}" + fi +fi + +# Check whether --with-libdir was given. +if test ${with_libdir+y} +then : + withval=$with_libdir; libdir=$withval + +fi + + + +# Check for Perl lib path +PERL_LIB_PATH=no + +# Check whether --with-perl_lib_path was given. +if test ${with_perl_lib_path+y} +then : + withval=$with_perl_lib_path; PERL_LIB_PATH=$withval +else $as_nop + PERL_LIB_PATH=no +fi + + + +# +# Checking for Perl Modules +# +foo=`$PERL -V` +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $foo" >&5 +printf "%s\n" "$foo" >&6; } +bar=`rpm -qa` +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $bar" >&5 +printf "%s\n" "$bar" >&6; } + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for Perl Module Time::HiRes" >&5 +printf %s "checking for Perl Module Time::HiRes... " >&6; } +$PERL -MTime::HiRes -e exit >/dev/null 2>&1 +if test $? -ne 0; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "Perl Module Time::HiRes not available" "$LINENO" 5 else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_member_struct_dirent_d_type=no + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for Perl Module Getopt::Long" >&5 +printf %s "checking for Perl Module Getopt::Long... " >&6; } +$PERL -MGetopt::Long -e exit >/dev/null 2>&1 +if test $? -ne 0; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "Perl Module Getopt::Long not available" "$LINENO" 5 +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } fi -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -fi -{ echo "$as_me:$LINENO: result: $ac_cv_member_struct_dirent_d_type" >&5 -echo "${ECHO_T}$ac_cv_member_struct_dirent_d_type" >&6; } -if test $ac_cv_member_struct_dirent_d_type = yes; then - -cat >>confdefs.h <<_ACEOF -#define HAVE_STRUCT_DIRENT_D_TYPE 1 -_ACEOF - - +RRDS=0 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for optional Perl Module RRDs" >&5 +printf %s "checking for optional Perl Module RRDs... " >&6; } +$PERL -I${PERL_LIB_PATH} -MRRDs -e exit >/dev/null 2>&1 +if test $? -ne 0; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: Perl Module RRDs not available" >&5 +printf "%s\n" "$as_me: WARNING: Perl Module RRDs not available" >&2;} + RRDS=0 +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + RRDS=1 fi +# Check whether --with-kohana was given. +if test ${with_kohana+y} +then : + withval=$with_kohana; KOHANA=no +else $as_nop + KOHANA=yes +fi + + + +# Check whether --with-kohana_system was given. +if test ${with_kohana_system+y} +then : + withval=$with_kohana_system; KOHANA_SYSTEM=$withval +else $as_nop + KOHANA_SYSTEM="${datarootdir}/kohana/system" +fi + +eval KOHANA_SYSTEM="${KOHANA_SYSTEM}" + + # Checks for library functions. -for ac_header in vfork.h +ac_header= ac_cache= +for ac_item in $ac_header_c_list do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ----------------------------------------------------- ## -## Report this to pnp4nagios-devel@lists.sourceforge.net ## -## ----------------------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } - -fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - + if test $ac_cache; then + ac_fn_c_check_header_compile "$LINENO" $ac_header ac_cv_header_$ac_cache "$ac_includes_default" + if eval test \"x\$ac_cv_header_$ac_cache\" = xyes; then + printf "%s\n" "#define $ac_item 1" >> confdefs.h + fi + ac_header= ac_cache= + elif test $ac_header; then + ac_cache=$ac_item + else + ac_header=$ac_item + fi done -for ac_func in fork vfork -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + + + + + +if test $ac_cv_header_stdlib_h = yes && test $ac_cv_header_string_h = yes +then : + +printf "%s\n" "#define STDC_HEADERS 1" >>confdefs.h + +fi + + ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default +" +if test "x$ac_cv_type_pid_t" = xyes +then : + +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif + #if defined _WIN64 && !defined __CYGWIN__ + LLP64 + #endif int -main () +main (void) { -return $ac_func (); + ; return 0; } + _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" +if ac_fn_c_try_compile "$LINENO" +then : + ac_pid_type='int' +else $as_nop + ac_pid_type='__int64' fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +printf "%s\n" "#define pid_t $ac_pid_type" >>confdefs.h -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF fi + + + +ac_func= +for ac_item in $ac_func_c_list +do + if test $ac_func; then + ac_fn_c_check_func "$LINENO" $ac_func ac_cv_func_$ac_func + if eval test \"x\$ac_cv_func_$ac_func\" = xyes; then + echo "#define $ac_item 1" >> confdefs.h + fi + ac_func= + else + ac_func=$ac_item + fi done + + if test "x$ac_cv_func_fork" = xyes; then - { echo "$as_me:$LINENO: checking for working fork" >&5 -echo $ECHO_N "checking for working fork... $ECHO_C" >&6; } -if test "${ac_cv_func_fork_works+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for working fork" >&5 +printf %s "checking for working fork... " >&6; } +if test ${ac_cv_func_fork_works+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test "$cross_compiling" = yes +then : ac_cv_func_fork_works=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int -main () +main (void) { /* By Ruediger Kuhlmann. */ @@ -4697,42 +5959,19 @@ main () return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO" +then : ac_cv_func_fork_works=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_func_fork_works=no +else $as_nop + ac_cv_func_fork_works=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_fork_works" >&5 -echo "${ECHO_T}$ac_cv_func_fork_works" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_fork_works" >&5 +printf "%s\n" "$ac_cv_func_fork_works" >&6; } else ac_cv_func_fork_works=$ac_cv_func_fork @@ -4747,31 +5986,37 @@ if test "x$ac_cv_func_fork_works" = xcross; then ac_cv_func_fork_works=yes ;; esac - { echo "$as_me:$LINENO: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&5 -echo "$as_me: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&5 +printf "%s\n" "$as_me: WARNING: result $ac_cv_func_fork_works guessed because of cross compilation" >&2;} fi ac_cv_func_vfork_works=$ac_cv_func_vfork if test "x$ac_cv_func_vfork" = xyes; then - { echo "$as_me:$LINENO: checking for working vfork" >&5 -echo $ECHO_N "checking for working vfork... $ECHO_C" >&6; } -if test "${ac_cv_func_vfork_works+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for working vfork" >&5 +printf %s "checking for working vfork... " >&6; } +if test ${ac_cv_func_vfork_works+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test "$cross_compiling" = yes +then : ac_cv_func_vfork_works=cross -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Thanks to Paul Eggert for this test. */ $ac_includes_default +#include #include #ifdef HAVE_VFORK_H # include #endif + +static void +do_nothing (int sig) +{ + (void) sig; +} + /* On some sparc systems, changes by the child to local and incoming argument registers are propagated back to the parent. The compiler is told about this with #include , but some compilers @@ -4779,11 +6024,7 @@ $ac_includes_default static variable whose address is put into a register that is clobbered by the vfork. */ static void -#ifdef __cplusplus sparc_address_test (int arg) -# else -sparc_address_test (arg) int arg; -#endif { static pid_t child; if (!child) { @@ -4801,13 +6042,18 @@ sparc_address_test (arg) int arg; } int -main () +main (void) { pid_t parent = getpid (); pid_t child; sparc_address_test (0); + /* On Solaris 2.4, changes by the child to the signal handler + also munge signal handlers in the parent. To detect this, + start by putting the parent's handler in a known state. */ + signal (SIGTERM, SIG_DFL); + child = vfork (); if (child == 0) { @@ -4829,6 +6075,10 @@ main () || p != p5 || p != p6 || p != p7) _exit(1); + /* Alter the child's signal handler. */ + if (signal (SIGTERM, do_nothing) != SIG_DFL) + _exit(1); + /* On some systems (e.g. IRIX 3.3), vfork doesn't separate parent from child file descriptors. If the child closes a descriptor before it execs or exits, this munges the parent's descriptor @@ -4844,6 +6094,9 @@ main () /* Was there some problem with vforking? */ child < 0 + /* Did the child munge the parent's signal handler? */ + || signal (SIGTERM, SIG_DFL) != SIG_DFL + /* Did the child fail? (This shouldn't happen.) */ || status @@ -4856,390 +6109,131 @@ main () } } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO" +then : ac_cv_func_vfork_works=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_func_vfork_works=no +else $as_nop + ac_cv_func_vfork_works=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_vfork_works" >&5 -echo "${ECHO_T}$ac_cv_func_vfork_works" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_vfork_works" >&5 +printf "%s\n" "$ac_cv_func_vfork_works" >&6; } fi; if test "x$ac_cv_func_fork_works" = xcross; then ac_cv_func_vfork_works=$ac_cv_func_vfork - { echo "$as_me:$LINENO: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&5 -echo "$as_me: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&5 +printf "%s\n" "$as_me: WARNING: result $ac_cv_func_vfork_works guessed because of cross compilation" >&2;} fi if test "x$ac_cv_func_vfork_works" = xyes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_WORKING_VFORK 1 -_ACEOF +printf "%s\n" "#define HAVE_WORKING_VFORK 1" >>confdefs.h else -cat >>confdefs.h <<\_ACEOF -#define vfork fork -_ACEOF +printf "%s\n" "#define vfork fork" >>confdefs.h fi if test "x$ac_cv_func_fork_works" = xyes; then -cat >>confdefs.h <<\_ACEOF -#define HAVE_WORKING_FORK 1 -_ACEOF +printf "%s\n" "#define HAVE_WORKING_FORK 1" >>confdefs.h fi +ac_fn_c_check_func "$LINENO" "bzero" "ac_cv_func_bzero" +if test "x$ac_cv_func_bzero" = xyes +then : + printf "%s\n" "#define HAVE_BZERO 1" >>confdefs.h +fi +ac_fn_c_check_func "$LINENO" "socket" "ac_cv_func_socket" +if test "x$ac_cv_func_socket" = xyes +then : + printf "%s\n" "#define HAVE_SOCKET 1" >>confdefs.h +fi +ac_fn_c_check_func "$LINENO" "alarm" "ac_cv_func_alarm" +if test "x$ac_cv_func_alarm" = xyes +then : + printf "%s\n" "#define HAVE_ALARM 1" >>confdefs.h +fi +ac_fn_c_check_func "$LINENO" "strerror" "ac_cv_func_strerror" +if test "x$ac_cv_func_strerror" = xyes +then : + printf "%s\n" "#define HAVE_STRERROR 1" >>confdefs.h +fi +ac_fn_c_check_func "$LINENO" "strspn" "ac_cv_func_strspn" +if test "x$ac_cv_func_strspn" = xyes +then : + printf "%s\n" "#define HAVE_STRSPN 1" >>confdefs.h +fi +ac_fn_c_check_func "$LINENO" "getloadavg" "ac_cv_func_getloadavg" +if test "x$ac_cv_func_getloadavg" = xyes +then : + printf "%s\n" "#define HAVE_GETLOADAVG 1" >>confdefs.h -for ac_func in bzero socket alarm strerror strspn getloadavg -do -as_ac_var=`echo "ac_cv_func_$ac_func" | $as_tr_sh` -{ echo "$as_me:$LINENO: checking for $ac_func" >&5 -echo $ECHO_N "checking for $ac_func... $ECHO_C" >&6; } -if { as_var=$as_ac_var; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 +printf %s "checking for GNU libc compatible malloc... " >&6; } +if test ${ac_cv_func_malloc_0_nonnull+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test "$cross_compiling" = yes +then : + case "$host_os" in # (( + # Guess yes on platforms where we know the result. + *-gnu* | freebsd* | netbsd* | openbsd* | bitrig* \ + | hpux* | solaris* | cygwin* | mingw* | msys* ) + ac_cv_func_malloc_0_nonnull=yes ;; + # If we don't know, assume the worst. + *) ac_cv_func_malloc_0_nonnull=no ;; + esac +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ -/* Define $ac_func to an innocuous variant, in case declares $ac_func. - For example, HP-UX 11i declares gettimeofday. */ -#define $ac_func innocuous_$ac_func - -/* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $ac_func (); below. - Prefer to if __STDC__ is defined, since - exists even on freestanding compilers. */ - -#ifdef __STDC__ -# include -#else -# include -#endif - -#undef $ac_func - -/* Override any GCC internal prototype to avoid an error. - Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -#ifdef __cplusplus -extern "C" -#endif -char $ac_func (); -/* The GNU C library defines this for functions which it implements - to always fail with ENOSYS. Some functions are actually named - something starting with __ and the normal name is an alias. */ -#if defined __stub_$ac_func || defined __stub___$ac_func -choke me -#endif +#include int -main () +main (void) { -return $ac_func (); +void *p = malloc (0); + int result = !p; + free (p); + return result; ; return 0; } _ACEOF -rm -f conftest.$ac_objext conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest$ac_exeext && - $as_test_x conftest$ac_exeext; then - eval "$as_ac_var=yes" -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - eval "$as_ac_var=no" -fi - -rm -f core conftest.err conftest.$ac_objext conftest_ipa8_conftest.oo \ - conftest$ac_exeext conftest.$ac_ext -fi -ac_res=`eval echo '${'$as_ac_var'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -if test `eval echo '${'$as_ac_var'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_func" | $as_tr_cpp` 1 -_ACEOF - -fi -done - - - -for ac_header in stdlib.h -do -as_ac_Header=`echo "ac_cv_header_$ac_header" | $as_tr_sh` -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - { echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } -else - # Is the header compilable? -{ echo "$as_me:$LINENO: checking $ac_header usability" >&5 -echo $ECHO_N "checking $ac_header usability... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -$ac_includes_default -#include <$ac_header> -_ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then - ac_header_compiler=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_compiler=no -fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_compiler" >&5 -echo "${ECHO_T}$ac_header_compiler" >&6; } - -# Is the header present? -{ echo "$as_me:$LINENO: checking $ac_header presence" >&5 -echo $ECHO_N "checking $ac_header presence... $ECHO_C" >&6; } -cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#include <$ac_header> -_ACEOF -if { (ac_try="$ac_cpp conftest.$ac_ext" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_cpp conftest.$ac_ext") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } >/dev/null && { - test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || - test ! -s conftest.err - }; then - ac_header_preproc=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_header_preproc=no -fi - -rm -f conftest.err conftest.$ac_ext -{ echo "$as_me:$LINENO: result: $ac_header_preproc" >&5 -echo "${ECHO_T}$ac_header_preproc" >&6; } - -# So? What about this header? -case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in - yes:no: ) - { echo "$as_me:$LINENO: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&5 -echo "$as_me: WARNING: $ac_header: accepted by the compiler, rejected by the preprocessor!" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the compiler's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the compiler's result" >&2;} - ac_header_preproc=yes - ;; - no:yes:* ) - { echo "$as_me:$LINENO: WARNING: $ac_header: present but cannot be compiled" >&5 -echo "$as_me: WARNING: $ac_header: present but cannot be compiled" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: check for missing prerequisite headers?" >&5 -echo "$as_me: WARNING: $ac_header: check for missing prerequisite headers?" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: see the Autoconf documentation" >&5 -echo "$as_me: WARNING: $ac_header: see the Autoconf documentation" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&5 -echo "$as_me: WARNING: $ac_header: section \"Present But Cannot Be Compiled\"" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: proceeding with the preprocessor's result" >&5 -echo "$as_me: WARNING: $ac_header: proceeding with the preprocessor's result" >&2;} - { echo "$as_me:$LINENO: WARNING: $ac_header: in the future, the compiler will take precedence" >&5 -echo "$as_me: WARNING: $ac_header: in the future, the compiler will take precedence" >&2;} - ( cat <<\_ASBOX -## ----------------------------------------------------- ## -## Report this to pnp4nagios-devel@lists.sourceforge.net ## -## ----------------------------------------------------- ## -_ASBOX - ) | sed "s/^/$as_me: WARNING: /" >&2 - ;; -esac -{ echo "$as_me:$LINENO: checking for $ac_header" >&5 -echo $ECHO_N "checking for $ac_header... $ECHO_C" >&6; } -if { as_var=$as_ac_Header; eval "test \"\${$as_var+set}\" = set"; }; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - eval "$as_ac_Header=\$ac_header_preproc" -fi -ac_res=`eval echo '${'$as_ac_Header'}'` - { echo "$as_me:$LINENO: result: $ac_res" >&5 -echo "${ECHO_T}$ac_res" >&6; } - -fi -if test `eval echo '${'$as_ac_Header'}'` = yes; then - cat >>confdefs.h <<_ACEOF -#define `echo "HAVE_$ac_header" | $as_tr_cpp` 1 -_ACEOF - -fi - -done - -{ echo "$as_me:$LINENO: checking for GNU libc compatible malloc" >&5 -echo $ECHO_N "checking for GNU libc compatible malloc... $ECHO_C" >&6; } -if test "${ac_cv_func_malloc_0_nonnull+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then - ac_cv_func_malloc_0_nonnull=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF -/* end confdefs.h. */ -#if defined STDC_HEADERS || defined HAVE_STDLIB_H -# include -#else -char *malloc (); -#endif - -int -main () -{ -return ! malloc (0); - ; - return 0; -} -_ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO" +then : ac_cv_func_malloc_0_nonnull=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_func_malloc_0_nonnull=no +else $as_nop + ac_cv_func_malloc_0_nonnull=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_malloc_0_nonnull" >&5 -echo "${ECHO_T}$ac_cv_func_malloc_0_nonnull" >&6; } -if test $ac_cv_func_malloc_0_nonnull = yes; then +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 +printf "%s\n" "$ac_cv_func_malloc_0_nonnull" >&6; } +if test $ac_cv_func_malloc_0_nonnull = yes +then : -cat >>confdefs.h <<\_ACEOF -#define HAVE_MALLOC 1 -_ACEOF +printf "%s\n" "#define HAVE_MALLOC 1" >>confdefs.h -else - cat >>confdefs.h <<\_ACEOF -#define HAVE_MALLOC 0 -_ACEOF +else $as_nop + printf "%s\n" "#define HAVE_MALLOC 0" >>confdefs.h case " $LIBOBJS " in *" malloc.$ac_objext "* ) ;; @@ -5248,37 +6242,37 @@ _ACEOF esac -cat >>confdefs.h <<\_ACEOF -#define malloc rpl_malloc -_ACEOF +printf "%s\n" "#define malloc rpl_malloc" >>confdefs.h fi - -{ echo "$as_me:$LINENO: checking whether lstat dereferences a symlink specified with a trailing slash" >&5 -echo $ECHO_N "checking whether lstat dereferences a symlink specified with a trailing slash... $ECHO_C" >&6; } -if test "${ac_cv_func_lstat_dereferences_slashed_symlink+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether lstat correctly handles trailing slash" >&5 +printf %s "checking whether lstat correctly handles trailing slash... " >&6; } +if test ${ac_cv_func_lstat_dereferences_slashed_symlink+y} +then : + printf %s "(cached) " >&6 +else $as_nop rm -f conftest.sym conftest.file echo >conftest.file if test "$as_ln_s" = "ln -s" && ln -s conftest.file conftest.sym; then - if test "$cross_compiling" = yes; then - ac_cv_func_lstat_dereferences_slashed_symlink=no -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF + if test "$cross_compiling" = yes +then : + case "$host_os" in # (( + # Guess yes on glibc systems. + *-gnu*) ac_cv_func_lstat_dereferences_slashed_symlink=yes ;; + # If we don't know, assume the worst. + *) ac_cv_func_lstat_dereferences_slashed_symlink=no ;; + esac +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int -main () +main (void) { struct stat sbuf; - /* Linux will dereference the symlink and fail. + /* Linux will dereference the symlink and fail, as required by POSIX. That is better in the sense that it means we will not have to compile and use the lstat wrapper. */ return lstat ("conftest.sym/", &sbuf) == 0; @@ -5286,39 +6280,16 @@ struct stat sbuf; return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO" +then : ac_cv_func_lstat_dereferences_slashed_symlink=yes -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_func_lstat_dereferences_slashed_symlink=no +else $as_nop + ac_cv_func_lstat_dereferences_slashed_symlink=no fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - else # If the `ln -s' command failed, then we probably don't even # have an lstat function. @@ -5327,17 +6298,15 @@ fi rm -f conftest.sym conftest.file fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 -echo "${ECHO_T}$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_lstat_dereferences_slashed_symlink" >&5 +printf "%s\n" "$ac_cv_func_lstat_dereferences_slashed_symlink" >&6; } test $ac_cv_func_lstat_dereferences_slashed_symlink = yes && -cat >>confdefs.h <<_ACEOF -#define LSTAT_FOLLOWS_SLASHED_SYMLINK 1 -_ACEOF +printf "%s\n" "#define LSTAT_FOLLOWS_SLASHED_SYMLINK 1" >>confdefs.h -if test $ac_cv_func_lstat_dereferences_slashed_symlink = no; then +if test "x$ac_cv_func_lstat_dereferences_slashed_symlink" = xno; then case " $LIBOBJS " in *" lstat.$ac_objext "* ) ;; *) LIBOBJS="$LIBOBJS lstat.$ac_objext" @@ -5346,23 +6315,21 @@ esac fi -{ echo "$as_me:$LINENO: checking whether stat accepts an empty string" >&5 -echo $ECHO_N "checking whether stat accepts an empty string... $ECHO_C" >&6; } -if test "${ac_cv_func_stat_empty_string_bug+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - if test "$cross_compiling" = yes; then +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether stat accepts an empty string" >&5 +printf %s "checking whether stat accepts an empty string... " >&6; } +if test ${ac_cv_func_stat_empty_string_bug+y} +then : + printf %s "(cached) " >&6 +else $as_nop + if test "$cross_compiling" = yes +then : ac_cv_func_stat_empty_string_bug=yes -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int -main () +main (void) { struct stat sbuf; return stat ("", &sbuf) == 0; @@ -5370,42 +6337,19 @@ struct stat sbuf; return 0; } _ACEOF -rm -f conftest$ac_exeext -if { (ac_try="$ac_link" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_link") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { ac_try='./conftest$ac_exeext' - { (case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_try") 2>&5 - ac_status=$? - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); }; }; then +if ac_fn_c_try_run "$LINENO" +then : ac_cv_func_stat_empty_string_bug=no -else - echo "$as_me: program exited with status $ac_status" >&5 -echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - -( exit $ac_status ) -ac_cv_func_stat_empty_string_bug=yes +else $as_nop + ac_cv_func_stat_empty_string_bug=yes fi -rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext conftest.$ac_objext conftest.$ac_ext +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext fi - fi -{ echo "$as_me:$LINENO: result: $ac_cv_func_stat_empty_string_bug" >&5 -echo "${ECHO_T}$ac_cv_func_stat_empty_string_bug" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_stat_empty_string_bug" >&5 +printf "%s\n" "$ac_cv_func_stat_empty_string_bug" >&6; } if test $ac_cv_func_stat_empty_string_bug = yes; then case " $LIBOBJS " in *" stat.$ac_objext "* ) ;; @@ -5414,40 +6358,34 @@ if test $ac_cv_func_stat_empty_string_bug = yes; then esac -cat >>confdefs.h <<_ACEOF -#define HAVE_STAT_EMPTY_STRING_BUG 1 -_ACEOF +printf "%s\n" "#define HAVE_STAT_EMPTY_STRING_BUG 1" >>confdefs.h fi - -{ echo "$as_me:$LINENO: checking for an ANSI C-conforming const" >&5 -echo $ECHO_N "checking for an ANSI C-conforming const... $ECHO_C" >&6; } -if test "${ac_cv_c_const+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - cat >conftest.$ac_ext <<_ACEOF -/* confdefs.h. */ -_ACEOF -cat confdefs.h >>conftest.$ac_ext -cat >>conftest.$ac_ext <<_ACEOF +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +printf %s "checking for an ANSI C-conforming const... " >&6; } +if test ${ac_cv_c_const+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int -main () +main (void) { -/* FIXME: Include the comments suggested by Paul. */ + #ifndef __cplusplus - /* Ultrix mips cc rejects this. */ + /* Ultrix mips cc rejects this sort of thing. */ typedef int charset[2]; - const charset cs; + const charset cs = { 0, 0 }; /* SunOS 4.1.1 cc rejects this. */ char const *const *pcpcc; char **ppc; /* NEC SVR4.0.2 mips cc rejects this. */ struct point {int x, y;}; static struct point const zero = {0,0}; - /* AIX XL C 1.02.0.0 rejects this. + /* IBM XL C 1.02.0.0 rejects this. It does not let you subtract one const X* pointer from another in an arm of an if-expression whose if-part is not a constant expression */ @@ -5457,8 +6395,9 @@ main () ++pcpcc; ppc = (char**) pcpcc; pcpcc = (char const *const *) ppc; - { /* SCO 3.2v4 cc rejects this. */ - char *t; + { /* SCO 3.2v4 cc rejects this sort of thing. */ + char tx; + char *t = &tx; char const *s = 0 ? (char *) 0 : (char const *) 0; *t++ = 0; @@ -5474,10 +6413,10 @@ main () iptr p = 0; ++p; } - { /* AIX XL C 1.02.0.0 rejects this saying + { /* IBM XL C 1.02.0.0 rejects this sort of thing, saying "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ - struct s { int j; const int *ap[3]; }; - struct s *b; b->j = 5; + struct s { int j; const int *ap[3]; } bx; + struct s *b = &bx; b->j = 5; } { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ const int foo = 10; @@ -5490,202 +6429,685 @@ main () return 0; } _ACEOF -rm -f conftest.$ac_objext -if { (ac_try="$ac_compile" -case "(($ac_try" in - *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; - *) ac_try_echo=$ac_try;; -esac -eval "echo \"\$as_me:$LINENO: $ac_try_echo\"") >&5 - (eval "$ac_compile") 2>conftest.er1 - ac_status=$? - grep -v '^ *+' conftest.er1 >conftest.err - rm -f conftest.er1 - cat conftest.err >&5 - echo "$as_me:$LINENO: \$? = $ac_status" >&5 - (exit $ac_status); } && { - test -z "$ac_c_werror_flag" || - test ! -s conftest.err - } && test -s conftest.$ac_objext; then +if ac_fn_c_try_compile "$LINENO" +then : ac_cv_c_const=yes -else - echo "$as_me: failed program was:" >&5 -sed 's/^/| /' conftest.$ac_ext >&5 - - ac_cv_c_const=no +else $as_nop + ac_cv_c_const=no fi - -rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi -{ echo "$as_me:$LINENO: result: $ac_cv_c_const" >&5 -echo "${ECHO_T}$ac_cv_c_const" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +printf "%s\n" "$ac_cv_c_const" >&6; } if test $ac_cv_c_const = no; then -cat >>confdefs.h <<\_ACEOF -#define const +printf "%s\n" "#define const /**/" >>confdefs.h + +fi + + + +# Checks for header files. + +ac_header_dirent=no +for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do + as_ac_Header=`printf "%s\n" "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 +printf %s "checking for $ac_hdr that defines DIR... " >&6; } +if eval test \${$as_ac_Header+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include <$ac_hdr> + +int +main (void) +{ +if ((DIR *) 0) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + eval "$as_ac_Header=yes" +else $as_nop + eval "$as_ac_Header=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +eval ac_res=\$$as_ac_Header + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +printf "%s\n" "$ac_res" >&6; } +if eval test \"x\$"$as_ac_Header"\" = x"yes" +then : + cat >>confdefs.h <<_ACEOF +#define `printf "%s\n" "HAVE_$ac_hdr" | $as_tr_cpp` 1 _ACEOF +ac_header_dirent=$ac_hdr; break fi +done +# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. +if test $ac_header_dirent = dirent.h; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +printf %s "checking for library containing opendir... " >&6; } +if test ${ac_cv_search_opendir+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ -layout="default" - -# Check whether --with-layout was given. -if test "${with_layout+set}" = set; then - withval=$with_layout; layout=$withval -fi - - -case $layout in - debian) - prefix="/" - sysconfdir="/etc/${PKG_NAME}" - localstatedir="/var/log/${PKG_NAME}" - libexecdir="/usr/lib/${PKG_NAME}/libexec" - libdir="/usr/lib/${PKG_NAME}" - datarootdir="/usr/share/${PKG_NAME}/html" - PERFDATA_LOG="/var/log/${PKG_NAME}/perfdata.log" - PERFDATA_DIR="/var/lib/${PKG_NAME}/perfdata" - PERFDATA_SPOOL_DIR="/var/spool/${PKG_NAME}" - bindir="/usr/bin" - sbindir="/usr/sbin" - ;; - default-0.4) - prefix="/usr/local/nagios" - sysconfdir="\${prefix}/etc/pnp" - localstatedir="\${prefix}/var" - libexecdir="\${prefix}/libexec" - datarootdir="\${prefix}/share/pnp" - libdir="\${prefix}/lib/pnp" - PERFDATA_LOG="\${prefix}/var/perfdata.log" - PERFDATA_DIR="\${prefix}/share/perfdata" - PERFDATA_SPOOL_DIR="\${prefix}/var/spool/perfdata" - ;; - default) - PERFDATA_LOG="${localstatedir}/perfdata.log" - PERFDATA_DIR="${localstatedir}/perfdata" - PERFDATA_SPOOL_DIR="${localstatedir}/spool" - mandir="\${prefix}/man" - ;; -esac - - -# Check whether --with-kohana was given. -if test "${with_kohana+set}" = set; then - withval=$with_kohana; KOHANA=no -else - KOHANA=yes -fi - - - -# Check whether --with-kohana_system was given. -if test "${with_kohana_system+set}" = set; then - withval=$with_kohana_system; KOHANA_SYSTEM=$withval -else - KOHANA_SYSTEM=$libdir/kohana/system -fi - - - -# Check whether --with-nagios_user was given. -if test "${with_nagios_user+set}" = set; then - withval=$with_nagios_user; nagios_user=$withval -else - nagios_user=nagios -fi - - -# Check whether --with-nagios_group was given. -if test "${with_nagios_group+set}" = set; then - withval=$with_nagios_group; nagios_grp=$withval -else - nagios_grp=nagios -fi - - - -cat >>confdefs.h <<_ACEOF -#define DEFAULT_NAGIOS_USER "$nagios_user" +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +char opendir (); +int +main (void) +{ +return opendir (); + ; + return 0; +} _ACEOF - -cat >>confdefs.h <<_ACEOF -#define DEFAULT_NAGIOS_GROUP "$nagios_grp" -_ACEOF - -INSTALL_OPTS="-o $nagios_user -g $nagios_grp" - - -# Checks for programs. -# Extract the first word of "perl", so it can be a program name with args. -set dummy perl; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_PERL+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else - case $PERL in - [\\/]* | ?:[\\/]*) - ac_cv_path_PERL="$PERL" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH +for ac_lib in '' dir do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_PERL="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" fi + if ac_fn_c_try_link "$LINENO" +then : + ac_cv_search_opendir=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext + if test ${ac_cv_search_opendir+y} +then : + break +fi done -done -IFS=$as_save_IFS +if test ${ac_cv_search_opendir+y} +then : - ;; +else $as_nop + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +printf "%s\n" "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no +then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +printf %s "checking for library containing opendir... " >&6; } +if test ${ac_cv_search_opendir+y} +then : + printf %s "(cached) " >&6 +else $as_nop + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +char opendir (); +int +main (void) +{ +return opendir (); + ; + return 0; +} +_ACEOF +for ac_lib in '' x +do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO" +then : + ac_cv_search_opendir=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext + if test ${ac_cv_search_opendir+y} +then : + break +fi +done +if test ${ac_cv_search_opendir+y} +then : + +else $as_nop + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +printf "%s\n" "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no +then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for sys/wait.h that is POSIX.1 compatible" >&5 +printf %s "checking for sys/wait.h that is POSIX.1 compatible... " >&6; } +if test ${ac_cv_header_sys_wait_h+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#ifndef WEXITSTATUS +# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) +#endif +#ifndef WIFEXITED +# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) +#endif + +int +main (void) +{ + int s; + wait (&s); + s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_cv_header_sys_wait_h=yes +else $as_nop + ac_cv_header_sys_wait_h=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_wait_h" >&5 +printf "%s\n" "$ac_cv_header_sys_wait_h" >&6; } +if test $ac_cv_header_sys_wait_h = yes; then + +printf "%s\n" "#define HAVE_SYS_WAIT_H 1" >>confdefs.h + +fi + +ac_fn_c_check_header_compile "$LINENO" "dirent.h" "ac_cv_header_dirent_h" "$ac_includes_default" +if test "x$ac_cv_header_dirent_h" = xyes +then : + printf "%s\n" "#define HAVE_DIRENT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "stdio.h" "ac_cv_header_stdio_h" "$ac_includes_default" +if test "x$ac_cv_header_stdio_h" = xyes +then : + printf "%s\n" "#define HAVE_STDIO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "errno.h" "ac_cv_header_errno_h" "$ac_includes_default" +if test "x$ac_cv_header_errno_h" = xyes +then : + printf "%s\n" "#define HAVE_ERRNO_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "unistd.h" "ac_cv_header_unistd_h" "$ac_includes_default" +if test "x$ac_cv_header_unistd_h" = xyes +then : + printf "%s\n" "#define HAVE_UNISTD_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "syslog.h" "ac_cv_header_syslog_h" "$ac_includes_default" +if test "x$ac_cv_header_syslog_h" = xyes +then : + printf "%s\n" "#define HAVE_SYSLOG_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "signal.h" "ac_cv_header_signal_h" "$ac_includes_default" +if test "x$ac_cv_header_signal_h" = xyes +then : + printf "%s\n" "#define HAVE_SIGNAL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = xyes +then : + printf "%s\n" "#define HAVE_STDLIB_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "dirent.h" "ac_cv_header_dirent_h" "$ac_includes_default" +if test "x$ac_cv_header_dirent_h" = xyes +then : + printf "%s\n" "#define HAVE_DIRENT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "string.h" "ac_cv_header_string_h" "$ac_includes_default" +if test "x$ac_cv_header_string_h" = xyes +then : + printf "%s\n" "#define HAVE_STRING_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "pthread.h" "ac_cv_header_pthread_h" "$ac_includes_default" +if test "x$ac_cv_header_pthread_h" = xyes +then : + printf "%s\n" "#define HAVE_PTHREAD_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "getopt.h" "ac_cv_header_getopt_h" "$ac_includes_default" +if test "x$ac_cv_header_getopt_h" = xyes +then : + printf "%s\n" "#define HAVE_GETOPT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "grp.h" "ac_cv_header_grp_h" "$ac_includes_default" +if test "x$ac_cv_header_grp_h" = xyes +then : + printf "%s\n" "#define HAVE_GRP_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "pwd.h" "ac_cv_header_pwd_h" "$ac_includes_default" +if test "x$ac_cv_header_pwd_h" = xyes +then : + printf "%s\n" "#define HAVE_PWD_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/mman.h" "ac_cv_header_sys_mman_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_mman_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_MMAN_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/types.h" "ac_cv_header_sys_types_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_types_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_TYPES_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/wait.h" "ac_cv_header_sys_wait_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_wait_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_WAIT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/stat.h" "ac_cv_header_sys_stat_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_stat_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_STAT_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/socket.h" "ac_cv_header_sys_socket_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_socket_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_SOCKET_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "sys/loadavg.h" "ac_cv_header_sys_loadavg_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_loadavg_h" = xyes +then : + printf "%s\n" "#define HAVE_SYS_LOADAVG_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "netinet/in.h" "ac_cv_header_netinet_in_h" "$ac_includes_default" +if test "x$ac_cv_header_netinet_in_h" = xyes +then : + printf "%s\n" "#define HAVE_NETINET_IN_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "fcntl.h" "ac_cv_header_fcntl_h" "$ac_includes_default" +if test "x$ac_cv_header_fcntl_h" = xyes +then : + printf "%s\n" "#define HAVE_FCNTL_H 1" >>confdefs.h + +fi +ac_fn_c_check_header_compile "$LINENO" "limits.h" "ac_cv_header_limits_h" "$ac_includes_default" +if test "x$ac_cv_header_limits_h" = xyes +then : + printf "%s\n" "#define HAVE_LIMITS_H 1" >>confdefs.h + +fi + + +# Checks for typedefs, structures, and compiler characteristics. + + ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default +" +if test "x$ac_cv_type_pid_t" = xyes +then : + +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + + #if defined _WIN64 && !defined __CYGWIN__ + LLP64 + #endif + +int +main (void) +{ + + ; + return 0; +} + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : + ac_pid_type='int' +else $as_nop + ac_pid_type='__int64' +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + +printf "%s\n" "#define pid_t $ac_pid_type" >>confdefs.h + + +fi + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +printf %s "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if test ${ac_cv_prog_CPP+y} +then : + printf %s "(cached) " >&6 +else $as_nop + # Double quotes because $CC needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" cpp /lib/cpp + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + +else $as_nop + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + # Broken: success on invalid input. +continue +else $as_nop + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok +then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +printf "%s\n" "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + +else $as_nop + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO" +then : + # Broken: success on invalid input. +continue +else $as_nop + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok +then : + +else $as_nop + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5 +printf %s "checking for uid_t in sys/types.h... " >&6; } +if test ${ac_cv_type_uid_t+y} +then : + printf %s "(cached) " >&6 +else $as_nop + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "uid_t" >/dev/null 2>&1 +then : + ac_cv_type_uid_t=yes +else $as_nop + ac_cv_type_uid_t=no +fi +rm -rf conftest* + +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5 +printf "%s\n" "$ac_cv_type_uid_t" >&6; } +if test $ac_cv_type_uid_t = no; then + +printf "%s\n" "#define uid_t int" >>confdefs.h + + +printf "%s\n" "#define gid_t int" >>confdefs.h + +fi + + + + ac_fn_c_check_member "$LINENO" "struct dirent" "d_type" "ac_cv_member_struct_dirent_d_type" " +#include +#ifdef HAVE_DIRENT_H +# include +#else +# define dirent direct +# ifdef HAVE_SYS_NDIR_H +# include +# endif +# ifdef HAVE_SYS_DIR_H +# include +# endif +# ifdef HAVE_NDIR_H +# include +# endif +#endif + +" +if test "x$ac_cv_member_struct_dirent_d_type" = xyes +then : + +printf "%s\n" "#define HAVE_STRUCT_DIRENT_D_TYPE 1" >>confdefs.h + + +fi + + + + + +if test "x$initdiroverridden" != "xyes"; then + initname="npcd" +fi + +#initname=`echo "$initname" | ${SED} "s#${PKG_NAME}#npcd#"` +initconf=`echo "$initconf" | ${SED} "s#${pkgsysconfdir}#npcd.cfg#"` + +case $src_init in + default-service) + src_init=npcd.service + initname=npcd.service + ;; + default-init) + src_init=rc.npcd + ;; + newbsd-init) + src_init=newbsd.npcd + ;; + openrc-init) + src_init=openrc.npcd + ;; + upstart-init) + src_init=upstart.npcd + ;; + *) + as_fn_error $? "missing an init file for npcd on this distro" "$LINENO" 5 + ;; esac + + +if test "x$spooldir" = "xN/A" ; then + spooldir="$localstatedir/spool/pnp4nagios" fi -PERL=$ac_cv_path_PERL -if test -n "$PERL"; then - { echo "$as_me:$LINENO: result: $PERL" >&5 -echo "${ECHO_T}$PERL" >&6; } -else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } +lockfile=`echo "${lockfile}"|${SED} "s#${localstatedir}#npcd.lock#"` + +logdir=`echo "${logdir}"|${SED} 's#/log$##'` +logdir="${logdir}/log" +eval logdir="$logdir" + +case $host_os in +*bsd*|darwin*) + root_grp=wheel + ;; +*) + root_grp=root + ;; +esac + + +# Check whether --with-root_group was given. +if test ${with_root_group+y} +then : + withval=$with_root_group; root_grp=$withval fi -# Check for Perl lib path -PERL_LIB_PATH=no +INIT_OPTS="-o root -g $root_grp" -# Check whether --with-perl_lib_path was given. -if test "${with_perl_lib_path+set}" = set; then - withval=$with_perl_lib_path; PERL_LIB_PATH=$withval -else - PERL_LIB_PATH=no -fi # Check for rrdtool RRDTOOL=no # Check whether --with-rrdtool was given. -if test "${with_rrdtool+set}" = set; then +if test ${with_rrdtool+y} +then : withval=$with_rrdtool; RRDTOOL=$withval -else +else $as_nop RRDTOOL=no fi if test RRDTOOL=no; then # Extract the first word of "rrdtool", so it can be a program name with args. set dummy rrdtool; ac_word=$2 -{ echo "$as_me:$LINENO: checking for $ac_word" >&5 -echo $ECHO_N "checking for $ac_word... $ECHO_C" >&6; } -if test "${ac_cv_path_RRDTOOL+set}" = set; then - echo $ECHO_N "(cached) $ECHO_C" >&6 -else +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_path_RRDTOOL+y} +then : + printf %s "(cached) " >&6 +else $as_nop case $RRDTOOL in [\\/]* | ?:[\\/]*) ac_cv_path_RRDTOOL="$RRDTOOL" # Let the user override the test with a path. @@ -5695,15 +7117,19 @@ else for as_dir in $PATH do IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then - ac_cv_path_RRDTOOL="$as_dir/$ac_word$ac_exec_ext" - echo "$as_me:$LINENO: found $as_dir/$ac_word$ac_exec_ext" >&5 + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_path_RRDTOOL="$as_dir$ac_word$ac_exec_ext" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi done -done + done IFS=$as_save_IFS ;; @@ -5711,64 +7137,381 @@ esac fi RRDTOOL=$ac_cv_path_RRDTOOL if test -n "$RRDTOOL"; then - { echo "$as_me:$LINENO: result: $RRDTOOL" >&5 -echo "${ECHO_T}$RRDTOOL" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RRDTOOL" >&5 +printf "%s\n" "$RRDTOOL" >&6; } else - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } fi fi -{ echo "$as_me:$LINENO: checking rrdtool path $RRDTOOL" >&5 -echo $ECHO_N "checking rrdtool path $RRDTOOL... $ECHO_C" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking rrdtool path $RRDTOOL" >&5 +printf %s "checking rrdtool path $RRDTOOL... " >&6; } if test -d $RRDTOOL ;then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { { echo "$as_me:$LINENO: error: $RRDTOOL is a directory! PNP needs the Path to the rrdtool binary!" >&5 -echo "$as_me: error: $RRDTOOL is a directory! PNP needs the Path to the rrdtool binary!" >&2;} - { (exit 1); exit 1; }; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "$RRDTOOL is a directory! PNP needs the Path to the rrdtool binary!" "$LINENO" 5 fi -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -{ echo "$as_me:$LINENO: checking for executable Bit on $RRDTOOL" >&5 -echo $ECHO_N "checking for executable Bit on $RRDTOOL... $ECHO_C" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for executable Bit on $RRDTOOL" >&5 +printf %s "checking for executable Bit on $RRDTOOL... " >&6; } if ! test -x $RRDTOOL ;then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { { echo "$as_me:$LINENO: error: $RRDTOOL is not executable!" >&5 -echo "$as_me: error: $RRDTOOL is not executable!" >&2;} - { (exit 1); exit 1; }; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + as_fn_error $? "$RRDTOOL is not executable!" "$LINENO" 5 fi -{ echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking selinux capability" >&5 +printf %s "checking selinux capability... " >&6; } +if test -e /etc/selinux/config ; +then + source /etc/selinux/config + CAN_SELINUX="yes" + SELINUX_POLICY="$SELINUXTYPE" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } +else + CAN_SELINUX="no" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi -# Check whether --with-perfdata-logfile was given. -if test "${with_perfdata_logfile+set}" = set; then - withval=$with_perfdata_logfile; PERFDATA_LOG=$withval +SELINUX="no" +# Check whether --enable-selinux was given. +if test ${enable_selinux+y} +then : + enableval=$enable_selinux; +fi + +if test "x$enable_selinux" != "xno" +then : + + SELINUX=$CAN_SELINUX + +fi + +SELINUX_DEVELDIR="no" +if test "x${SELINUX}" = "xyes" ; then + +# Check whether --with-selinux_develdir was given. +if test ${with_selinux_develdir+y} +then : + withval=$with_selinux_develdir; SELINUX_DEVELDIR=$withval +else $as_nop + SELINUX_DEVELDIR=no +fi + + if test "x${SELINUX_DEVELDIR}" = "xno" ; then + if test -e "/usr/share/selinux/devel/Makefile" ; then + SELINUX_DEVELDIR="/usr/share/selinux/devel" + elif test -e "/usr/share/selinux/mcs/include/Makefile" ; then + SELINUX_DEVELDIR="/usr/share/selinux/mcs/include" + elif test -e "/usr/share/doc/selinux-policy-dev/examples/Makefile" ; then + SELINUX_DEVELDIR="/usr/share/doc/selinux-policy-dev/examples" + else + as_fn_error $? "Directory with selinux policy Makefile not fund, use --with-selinux_develdir to specify" "$LINENO" 5 + fi + fi fi +SE="" +if test $SELINUX = no ; then + SE='#' +fi + + + + +# Check whether --with-nagios_cfg was given. +if test ${with_nagios_cfg+y} +then : + withval=$with_nagios_cfg; NAGIOS_CFG=$withval +else $as_nop + NAGIOS_CFG=no +fi + + + +# Check whether --with-nagios_version was given. +if test ${with_nagios_version+y} +then : + withval=$with_nagios_version; NAGIOS_VER=$withval +else $as_nop + NAGIOS_VER=no +fi + + +NAGIOS_EXE=no + +if test x$NAGIOS_CFG = xno -a x$NAGIOS_VER = xno ; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Look for running nagios server" >&5 +printf %s "checking Look for running nagios server... " >&6; } + rnag=`ps -A -o command | ${EGREP} '/nagios4?( |$)' | head -n 1 | ${AWK} '{print $1;}'` + + if test x$rnag = x ; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: not seen" >&5 +printf "%s\n" "not seen" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $rnag" >&5 +printf "%s\n" "$rnag" >&6; } + ncfg=`ps -A -o command | ${EGREP} '/nagios4? +.*\.cfg' | head -n 1 | ${AWK} -v RS=' ' '/\.cfg/{print $1;}'` + if test x$ncfg != x ; then + NAGIOS_CFG=$ncfg + fi + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Nagios executable" >&5 +printf %s "checking Nagios executable... " >&6; } + if test x$rnag = x ; then + rnag=`which nagios 2>/dev/null` + if test x$rnag = x ; then + rnag=`which nagios4 2>/dev/null` + fi + fi + if test x$rnag = x ; then + rnag=no + fi + NAGIOS_EXE=$rnag + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NAGIOS_EXE" >&5 +printf "%s\n" "$NAGIOS_EXE" >&6; } + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Nagios config file location" >&5 +printf %s "checking Nagios config file location... " >&6; } + + if test x$NAGIOS_CFG = xno; then + if test -e /etc/nagios/nagios.cfg ; then + NAGIOS_CFG=/etc/nagios/nagios.cfg + elif test -e /etc/nagios4/nagios.cfg ; then + NAGIOS_CFG=/etc/nagios4/nagios.cfg + elif test -e /usr/local/etc/nagios/nagios.cfg ; then + NAGIOS_CFG=/usr/local/etc/nagios/nagios.cfg + fi + fi + if test x${NAGIOS_CFG} = xno ; then + NAGIOS_CFG=/etc/nagios/nagios.cfg + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Not found, forced to $NAGIOS_CFG" >&5 +printf "%s\n" "Not found, forced to $NAGIOS_CFG" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NAGIOS_CFG" >&5 +printf "%s\n" "$NAGIOS_CFG" >&6; } + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Nagios version" >&5 +printf %s "checking Nagios version... " >&6; } + # if nagios not installed yet, probably will install a new version + # so just pick a recent version unless one is given in arguments + + if test x$NAGIOS_VER = xno; then + if test x$NAGIOS_EXE != xno ; then + NAGIOS_VER=`${NAGIOS_EXE} --help | ${AWK} '/^Nagios /' | ${AWK} -v RS=' ' '/^[0-9]/'` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NAGIOS_VER" >&5 +printf "%s\n" "$NAGIOS_VER" >&6; } + else + NAGIOS_VER=4.4.6 + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: not found, assuming $NAGIOS_VER" >&5 +printf "%s\n" "not found, assuming $NAGIOS_VER" >&6; } + fi + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: forced use of version $NAGIOS_VER" >&5 +printf "%s\n" "forced use of version $NAGIOS_VER" >&6; } + fi +fi + + + + +# Check whether --with-nagios_unit was given. +if test ${with_nagios_unit+y} +then : + withval=$with_nagios_unit; NAGIOS_UNIT=$withval +else $as_nop + NAGIOS_UNIT=no +fi + +if test x$NAGIOS_UNIT = xno; then + nagunit='' + case $init_type in + systemd) + nagunit=`systemctl list-units -q 'nagios*.service'|${AWK} '{print $1;}'` + ;; + sysv) + nagunit=`chkconfig --list 2>/dev/null|${GREPE} 'nagios.?\s+0'|${AWK} '{print $1;}'` + ;; +# not sure how to do other init_types + esac + if test "x$nagunit" != x; then + NAGIOS_UNIT=$nagunit + fi +fi +NAGIOS_UNIT=${NAGIOS_UNIT%.service} + + + +nagios_dir=`dirname $NAGIOS_CFG` + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Nagios password file" >&5 +printf %s "checking Nagios password file... " >&6; } +NAGIOS_PWD=no + +# Check whether --with-nagios_pwd was given. +if test ${with_nagios_pwd+y} +then : + withval=$with_nagios_pwd; NAGIOS_PWD=$withval +else $as_nop + NAGIOS_PWD=no +fi + +if test x$NAGIOS_PWD = xno; then + if test -e "${nagios_dir}/passwd" ; then + NAGIOS_PWD="${nagios_dir}/passwd" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NAGIOS_PWD" >&5 +printf "%s\n" "$NAGIOS_PWD" >&6; } + elif test -e "${nagios_dir}/htpasswd.users" ; then + NAGIOS_PWD="${nagios_dir}/htpasswd.users" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NAGIOS_PWD" >&5 +printf "%s\n" "$NAGIOS_PWD" >&6; } + elif test -e "${nagios_dir}/htdigest.users" ; then + NAGIOS_PWD="${nagios_dir}/htdigest.users" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NAGIOS_PWD" >&5 +printf "%s\n" "$NAGIOS_PWD" >&6; } + else + NAGIOS_PWD="${nagios_dir}/passwd" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: not found, assume default $NAGIOS_PWD" >&5 +printf "%s\n" "not found, assume default $NAGIOS_PWD" >&6; } + fi +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: forced to $NAGIOS_PWD" >&5 +printf "%s\n" "forced to $NAGIOS_PWD" >&6; } +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Nagios objects directory" >&5 +printf %s "checking Nagios objects directory... " >&6; } +NAGIOS_OBJ=no + +# Check whether --with-nagios_objects was given. +if test ${with_nagios_objects+y} +then : + withval=$with_nagios_objects; NAGIOS_OBJ=$withval +else $as_nop + NAGIOS_OBJ=no +fi + +if test x$NAGIOS_OBJ = xno; then + if test -e "${nagios_dir}/objects" ; then + NAGIOS_OBJ="${nagios_dir}/objects" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $NAGIOS_OBJ" >&5 +printf "%s\n" "$NAGIOS_OBJ" >&6; } + else + NAGIOS_OBJ="${nagios_dir}/objects" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: not found, assume default $NAGIOS_OBJ" >&5 +printf "%s\n" "not found, assume default $NAGIOS_OBJ" >&6; } + fi +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: forced to $NAGIOS_OBJ" >&5 +printf "%s\n" "forced to $NAGIOS_OBJ" >&6; } +fi + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Nagios user/group" >&5 +printf %s "checking Nagios user/group... " >&6; } +nagios_user=no +nagios_grp=no +if test -e "$NAGIOS_CFG" ; then + nagios_user=`${AWK} -F= '/nagios_user/ {print $2;}' $NAGIOS_CFG` + nagios_grp=`${AWK} -F= '/nagios_group/ {print $2;}' $NAGIOS_CFG` +fi + + +# Check whether --with-nagios_user was given. +if test ${with_nagios_user+y} +then : + withval=$with_nagios_user; nagios_user=$withval +fi + + +# Check whether --with-nagios_group was given. +if test ${with_nagios_group+y} +then : + withval=$with_nagios_group; nagios_grp=$withval +fi + + +ugmsg="" +if test x$nagios_user = xno ; then + ugmsg="using default" + nagios_user=nagios +fi + +if test x$nagios_grp = xno ; then + ugmsg="using_default" + nagios_grp=nagios +fi + +if test x$ugmsg = x ; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: ${nagios_user} / ${nagios_grp}" >&5 +printf "%s\n" "${nagios_user} / ${nagios_grp}" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ugmsg ${nagios_user} / ${nagios_grp}" >&5 +printf "%s\n" "$ugmsg ${nagios_user} / ${nagios_grp}" >&6; } +fi + + + +INSTALL_OPTS="-o $nagios_user -g $nagios_grp" + + +# +# pnp4nagios locations and files +# +PNP_LOGDIR="${logdir}/pnp4nagios" + +# Check whether --with-pnp-logdir was given. +if test ${with_pnp_logdir+y} +then : + withval=$with_pnp_logdir; PNP_LOGDIR=$withval + +fi + + + +PERFDATA_LOG="${PNP_LOGDIR}/perfdata.log" + + +PERFDATA_STATS="${PNP_LOGDIR}/stats" + + + +PERFDATA_DIR="${PNP_LOGDIR}/rrd" # Check whether --with-perfdata-dir was given. -if test "${with_perfdata_dir+set}" = set; then +if test ${with_perfdata_dir+y} +then : withval=$with_perfdata_dir; PERFDATA_DIR=$withval fi +PERFDATA_SPOOL_DIR="$spooldir" # Check whether --with-perfdata-spool-dir was given. -if test "${with_perfdata_spool_dir+set}" = set; then +if test ${with_perfdata_spool_dir+y} +then : withval=$with_perfdata_spool_dir; PERFDATA_SPOOL_DIR=$withval fi @@ -5776,70 +7519,6 @@ fi -# Check whether --with-debug was given. -if test "${with_debug+set}" = set; then - withval=$with_debug; DEBUG="2" -else - DEBUG="0" - -fi - - - -HTTP_CONF=no - -# Check whether --with-httpd_conf was given. -if test "${with_httpd_conf+set}" = set; then - withval=$with_httpd_conf; HTTPD_CONF=$withval -else - HTTPD_CONF=no -fi - -if test x$HTTPD_CONF = xno; then - if test -d /etc/httpd/conf.d; then - HTTPD_CONF="/etc/httpd/conf.d" - elif test -d /etc/apache2/conf.d; then - HTTPD_CONF="/etc/apache2/conf.d" - elif test -d /etc/apache/conf.d; then - HTTPD_CONF="/etc/apache/conf.d" - else - HTTPD_CONF="/etc/httpd/conf.d" - fi -fi - - -init_dir=/etc/rc.d/init.d -if test -d /etc/rc.d/init.d; then - init_dir="/etc/rc.d/init.d" -elif test -d /usr/local/etc/rc.d; then - init_dir="/usr/local/etc/rc.d" -elif test -d /etc/rc.d; then - init_dir="/etc/rc.d" -elif test -d /etc/init.d; then - init_dir="/etc/init.d" -elif test -d /sbin/init.d; then - init_dir="/sbin/init.d" -fi - -BASE_URL=${PKG_NAME} - -# Check whether --with-base-url was given. -if test "${with_base_url+set}" = set; then - withval=$with_base_url; BASE_URL=$withval -else - BASE_URL=/${PKG_NAME} -fi - - - - -# Check whether --with-init_dir was given. -if test "${with_init_dir+set}" = set; then - withval=$with_init_dir; init_dir=$withval -fi - - - pnpsender_name=pnpsender @@ -5849,8 +7528,260 @@ npcd_name=npcd pp_pl_name=process_perfdata.pl -{ echo "$as_me:$LINENO: checking for linker flags for loadable modules" >&5 -echo $ECHO_N "checking for linker flags for loadable modules... $ECHO_C" >&6; } + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking http server" >&5 +printf %s "checking http server... " >&6; } +HTTP_SERVER=no + +# Check whether --with-http_server was given. +if test ${with_http_server+y} +then : + withval=$with_http_server; HTTP_SERVER=$withval +fi + + +if test "x${HTTP_SERVER}" = xno ; then + http_server_types="httpd + apache + apache2 + lighttpd + nginx" + http_unit=x + for HTTP_SERVER in $http_server_types + do + case "$init_type" in + systemd) + http_unit=`systemctl list-units -q "${HTTP_SERVER}.service"|${AWK} '{print $1;}'` + ;; + sysv) + http_unit=`chkconfig --list 2>/dev/null|${GREPE} "${HTTP_SERVER}\s+0"|${AWK} '{print $1;}'` + ;; + esac + if test "x${http_unit}" != x ; then + break; + fi + done +fi + + +# Check whether --with-http_server_base was given. +if test ${with_http_server_base+y} +then : + withval=$with_http_server_base; http_base=$withval +else $as_nop + http_base=no +fi + + +if test x$http_base = xno ; then + case "${HTTP_SERVER}" in + apache*) + if apachectl -t -D DUMP_RUN_CFG >/dev/null 2>/dev/null ; + then + http_base=`apachectl -t -D DUMP_RUN_CFG | ${AWK} '/^ServerRoot:/ {print $2;}'` + http_base=`echo "$srvroot"|${SED} 's/"//'` + HTTP_USER=`apachectl -t -D DUMP_RUN_CFG | ${AWK} '/^User:/ {print $2;}'` + HTTP_USER=`echo "${HTTP_USER}"|${SED} 's/name=//'` + HTTP_USER=`echo "${HTTP_USER}"|${SED} 's/"//g'` + HTTP_GROUP=`apachectl -t -D DUMP_RUN_CFG | ${AWK} '/^Group:/ {print $2;}'` + HTTP_GROUP=`echo "${HTTP_GROUP}"|${SED} 's/name=//'` + HTTP_GROUP=`echo "${HTTP_GROUP}"|${SED} 's/"//g'` + HTTP_CONFDIR=`apachectl -t -D DUMP_INCLUDES| ${GREP} "$http_base/.*\.conf" | ${AWK} '/\/conf/{print $2;}' | ${SED} -E 's/^\/+$//' | head -n 1` + + HTTP_CONFDIR=`apachectl -t -D DUMP_INCLUDES |${GREP} "$http_base/.*\.conf" | awk '/\/conf/{print $2;}'|${SED} -E 's/\/[^\/]+$//' | head -n 1` + fi + ;; + esac +fi + + + +if test "x${http_base}" = xno ; then + if test -e "/etc/${HTTP_SERVER}" ; then + http_base="/etc/${HTTP_SERVER}" + elif test -e "/usr/local/${HTTP_SERVER}" ; then + http_base="/usr/local/${HTTP_SERVER}" + elif test -e "/usr/local/etc/${HTTP_SERVER}" ; then + http_base="/usr/local/etc/${HTTP_SERVER}" + elif test -e "/usr/pkg/etc/${HTTP_SERVER}" ; then + http_base="/usr/pkg/etc/${HTTP_SERVER}" + fi +fi + +if test "x$http_base" = "xno" ; then + as_fn_error $? "http server base directory not found" "$LINENO" 5 +fi + +if test "x$HTTP_CONFDIR" = x ; then + case "$HTTP_SERVER" in + apache* | httpd ) + if test -e "${http_base}/conf/httpd.conf" ; then + hconf="${http_base}/conf/httpd.conf" + elif test -e "${http_base}/httpd.conf" ; then + hconf="${http_base}/httpd.conf" + elif test -e "${http_base}/apache.conf" ; then + hconf="${http_base}/apache.conf" + elif test -e "${http_base}/apache2.conf" ; then + hconf="${http_base}/apache2.conf" + else + echo "HTTPD main configure file not found" + hconf="${http_base}/httpd.conf" + fi + if test -e $hconf ; then + HTTP_USER=`${AWK} '/^User/{print $2;}' $hconf` + HTTP_GROUP=`${AWK} '/^Group/{print $2;}' $hconf` + HTTP_CONFDIR=`${AWK} '/^IncludeOptional .*\*/{print $2;}' $hconf|head -n 1` + if test "x${HTTP_CONFDIR}" != x ; then + HTTP_CONFDIR=`dirname "${http_base}/${HTTP_CONFDIR}"` + fi + fi + HTTP_USER=${HTTP_USER:-daemon} + HTTP_GROUP=${HTTP_GROUP:-daemon} + HTTP_CONFDIR=${HTTP_CONFDIR:-$http_base} + ;; + lighttpd ) + HTTP_USER=lighttpd + HTTP_GROUP=lighttpd + HTTP_CONFDIR="${http_base}/conf.d" + ;; + nginx ) + HTTP_USER=nobody + HTTP_GROUP=root + HTTP_CONFDIR="${http_base}/conf.d" + ;; + esac +fi + +if test ! -e ${HTTP_CONFDIR} ; then + HTTP_CONFDIR=${http_base} +fi + + +if test "${HTTP_SERVER}" = "httpd" ; then + HTTP_SERVER=apache +elif test "${HTTP_SERVER}" = "apache2" ; then + HTTP_SERVER=apache +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $HTTP_SERVER" >&5 +printf "%s\n" "$HTTP_SERVER" >&6; } + +HTTP_UNIT=${HTTP_UNIT%.service} + + + + +# Check whether --with-http_user was given. +if test ${with_http_user+y} +then : + withval=$with_http_user; http_user=$withval +else $as_nop + http_user=$HTTP_USER +fi + + +# Check whether --with-http_group was given. +if test ${with_http_group+y} +then : + withval=$with_http_group; http_group=$withval +else $as_nop + http_group=$HTTP_GROUP +fi + + +HTTP_USER=${http_user} +HTTP_GROUP=${http_group} + +if test x${HTTP_USER} = xno ; then + as_fn_error $? "http_user not defined" "$LINENO" 5 +elif test x${HTTP_GROUP} = xno ; then + as_fn_error $? "http_group not defined" "$LINENO" 5 +fi + + + +HTTP_INSTALL_OPTS="-o $HTTP_USER -g $HTTP_GROUP" + + + + +# Check whether --with-http_confdir was given. +if test ${with_http_confdir+y} +then : + withval=$with_http_confdir; HTTP_CONFDIR=$withval +fi + + + + + +# Check whether --with-cache_dir was given. +if test ${with_cache_dir+y} +then : + withval=$with_cache_dir; CACHE_DIR=$withval +else $as_nop + CACHE_DIR=no +fi + +if test "x$CACHE_DIR" = "xno" ; then + if test -e "/var/cache" ; then + CACHE_DIR=/var/cache/pnp4nagios + else + as_fn_error $? "/var/cache missing, need to define cache_dir" "$LINENO" 5 + fi +fi + + + +# Check whether --with-pnp_url was given. +if test ${with_pnp_url+y} +then : + withval=$with_pnp_url; PNP_URL=$withval +else $as_nop + PNP_URL=/pnp4nagios +fi + + + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking Default paper size for pdf generation" >&5 +printf %s "checking Default paper size for pdf generation... " >&6; } + +PAPERSIZE=no + +# Check whether --with-papersize was given. +if test ${with_papersize+y} +then : + withval=$with_papersize; PAPERSIZE=$withval +else $as_nop + PAPERSIZE=no +fi + +if test x${PAPERSIZE} = xno ; then + localefile=no + if test -e "/etc/locale.conf" ; then + localefile=/etc/locale.conf + elif test -e "/etc/default/locale" ; then + localefile=/etc/default/locale + fi + if test x${localefile} = xno ; then + PAPERSIZE=A4 + else + country=`${GREP} "_..\." -o ${localefile} | ${SED} 's/[\._]//g'` + if echo 'BZ,CA,CL,CO,CR,SV,GT,MX,NI,PA,PH,PR,US,VE' | ${GREP} -q ${country} ; then + PAPERSIZE=letter + else + PAPERSIZE=A4 + fi + fi +fi + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $PAPERSIZE" >&5 +printf "%s\n" "$PAPERSIZE" >&6; } + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for linker flags for loadable modules" >&5 +printf %s "checking for linker flags for loadable modules... " >&6; } case $host_os in solaris2*|sysv4*) MOD_LDFLAGS="-G" @@ -5879,134 +7810,70 @@ case $host_os in MOD_LDFLAGS="-shared" ;; esac -{ echo "$as_me:$LINENO: result: $MOD_LDFLAGS" >&5 -echo "${ECHO_T}$MOD_LDFLAGS" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MOD_LDFLAGS" >&5 +printf "%s\n" "$MOD_LDFLAGS" >&6; } -# -# Checking for Perl Modules -# -{ echo "$as_me:$LINENO: checking for Perl Module Time::HiRes" >&5 -echo $ECHO_N "checking for Perl Module Time::HiRes... $ECHO_C" >&6; } -$PERL -MTime::HiRes -e exit >/dev/null 2>&1 -if test $? -ne 0; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { { echo "$as_me:$LINENO: error: Perl Module Time::HiRes not available" >&5 -echo "$as_me: error: Perl Module Time::HiRes not available" >&2;} - { (exit 1); exit 1; }; } -else - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -fi - -{ echo "$as_me:$LINENO: checking for Perl Module Getopt::Long" >&5 -echo $ECHO_N "checking for Perl Module Getopt::Long... $ECHO_C" >&6; } -$PERL -MGetopt::Long -e exit >/dev/null 2>&1 -if test $? -ne 0; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { { echo "$as_me:$LINENO: error: Perl Module Getopt::Long not available" >&5 -echo "$as_me: error: Perl Module Getopt::Long not available" >&2;} - { (exit 1); exit 1; }; } -else - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } -fi - -RRDS=0 -{ echo "$as_me:$LINENO: checking for optional Perl Module RRDs" >&5 -echo $ECHO_N "checking for optional Perl Module RRDs... $ECHO_C" >&6; } -$PERL -I${PERL_LIB_PATH} -MRRDs -e exit >/dev/null 2>&1 -if test $? -ne 0; then - { echo "$as_me:$LINENO: result: no" >&5 -echo "${ECHO_T}no" >&6; } - { echo "$as_me:$LINENO: WARNING: Perl Module RRDs not available" >&5 -echo "$as_me: WARNING: Perl Module RRDs not available" >&2;} - RRDS=0 -else - { echo "$as_me:$LINENO: result: yes" >&5 -echo "${ECHO_T}yes" >&6; } - RRDS=1 -fi - ac_config_files="$ac_config_files subst Makefile share/Makefile lib/Makefile scripts/Makefile src/Makefile sample-config/Makefile man/Makefile" -cat >confcache <<\_ACEOF -# This file is a shell script that caches the results of configure -# tests run on this system so they can be shared between configure -# scripts and configure runs, see configure's option --config-cache. -# It is not useful on other systems. If it contains results you don't -# want to keep, you may remove or edit it. -# -# config.status only pays attention to the cache file if you give it -# the --recheck option to rerun configure. -# -# `ac_cv_env_foo' variables (set or unset) will be overridden when -# loading this file, other *unset* `ac_cv_foo' will be assigned the -# following values. +ac_config_files="$ac_config_files include/stamp-h" + +ac_config_files="$ac_config_files scripts/rrd_modify.pl scripts/rc.npcd scripts/rc.pnp_gearman_worker" + +ac_config_files="$ac_config_files scripts/npcd.service scripts/pnp_gearman_worker.service" + +ac_config_files="$ac_config_files scripts/newbsd.npcd" + +ac_config_files="$ac_config_files scripts/check_pnp_rrds.pl share/pnp/index.php share/pnp/install.php" + +ac_config_files="$ac_config_files sample-config/README_config.md" + +ac_config_files="$ac_config_files sample-config/SetLogLevels" + +ac_config_files="$ac_config_files sample-config/config_tools/NagiosCfgMod.pl" + +ac_config_files="$ac_config_files sample-config/config_tools/TemplateMod.pl" + +ac_config_files="$ac_config_files sample-config/config_tools/verify_pnp_config" + +ac_config_files="$ac_config_files sample-config/config_samples/apache.pnp4nagios.conf" + +ac_config_files="$ac_config_files sample-config/config_samples/config.php" + +ac_config_files="$ac_config_files sample-config/config_samples/lighttpd.pnp4nagios.conf" + +ac_config_files="$ac_config_files sample-config/config_samples/nagios.cfg" + +ac_config_files="$ac_config_files sample-config/config_samples/nginx.pnp4nagios.conf" + +ac_config_files="$ac_config_files sample-config/config_samples/npcd.cfg" + +ac_config_files="$ac_config_files sample-config/config_samples/pnp-bulk.cfg" + +ac_config_files="$ac_config_files sample-config/config_samples/pnp-npcd.cfg" + +ac_config_files="$ac_config_files sample-config/config_samples/pnp-sync.cfg" + +ac_config_files="$ac_config_files sample-config/config_samples/process_perfdata.cfg" + +ac_config_files="$ac_config_files sample-config/pnp4nagios_release" + +ac_config_files="$ac_config_files man/npcd.8 ci/pnp4nagios.spec" + +ac_config_files="$ac_config_files pnp4nagios.fc src/config.c src/npcdmod.c" + +ac_config_files="$ac_config_files contrib/fedora/pnp4nagios.logrotate.conf" + +ac_config_files="$ac_config_files contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf" + +ac_config_files="$ac_config_files contrib/fedora/logwatch/scripts/services/pnp4nagios" + +ac_config_files="$ac_config_files contrib/ssi/status-header.ssi" -_ACEOF -# The following way of writing the cache mishandles newlines in values, -# but we know of no workaround that is simple, portable, and efficient. -# So, we kill variables containing newlines. -# Ultrix sh set writes to stderr and can't be redirected directly, -# and sets the high bit in the cache file unless we assign to the vars. -( - for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do - eval ac_val=\$$ac_var - case $ac_val in #( - *${as_nl}*) - case $ac_var in #( - *_cv_*) { echo "$as_me:$LINENO: WARNING: Cache variable $ac_var contains a newline." >&5 -echo "$as_me: WARNING: Cache variable $ac_var contains a newline." >&2;} ;; - esac - case $ac_var in #( - _ | IFS | as_nl) ;; #( - *) $as_unset $ac_var ;; - esac ;; - esac - done - (set) 2>&1 | - case $as_nl`(ac_space=' '; set) 2>&1` in #( - *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes (double-quote - # substitution turns \\\\ into \\, and sed turns \\ into \). - sed -n \ - "s/'/'\\\\''/g; - s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" - ;; #( - *) - # `set' quotes correctly as required by POSIX, so do not add quotes. - sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" - ;; - esac | - sort -) | - sed ' - /^ac_cv_env_/b end - t clear - :clear - s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ - t end - s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ - :end' >>confcache -if diff "$cache_file" confcache >/dev/null 2>&1; then :; else - if test -w "$cache_file"; then - test "x$cache_file" != "x/dev/null" && - { echo "$as_me:$LINENO: updating cache $cache_file" >&5 -echo "$as_me: updating cache $cache_file" >&6;} - cat confcache >$cache_file - else - { echo "$as_me:$LINENO: not updating unwritable cache $cache_file" >&5 -echo "$as_me: not updating unwritable cache $cache_file" >&6;} - fi -fi -rm -f confcache test "x$prefix" = xNONE && prefix=$ac_default_prefix # Let make expand exec_prefix. @@ -6016,14 +7883,15 @@ DEFS=-DHAVE_CONFIG_H ac_libobjs= ac_ltlibobjs= +U= for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue # 1. Remove the extension, and $U if already installed. ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' - ac_i=`echo "$ac_i" | sed "$ac_script"` + ac_i=`printf "%s\n" "$ac_i" | sed "$ac_script"` # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR # will be set to the directory where LIBOBJS objects are built. - ac_libobjs="$ac_libobjs \${LIBOBJDIR}$ac_i\$U.$ac_objext" - ac_ltlibobjs="$ac_ltlibobjs \${LIBOBJDIR}$ac_i"'$U.lo' + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' done LIBOBJS=$ac_libobjs @@ -6031,12 +7899,14 @@ LTLIBOBJS=$ac_ltlibobjs -: ${CONFIG_STATUS=./config.status} +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" -{ echo "$as_me:$LINENO: creating $CONFIG_STATUS" >&5 -echo "$as_me: creating $CONFIG_STATUS" >&6;} -cat >$CONFIG_STATUS <<_ACEOF +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +printf "%s\n" "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 #! $SHELL # Generated by $as_me. # Run this file to recreate the current configuration. @@ -6046,81 +7916,99 @@ cat >$CONFIG_STATUS <<_ACEOF debug=false ac_cs_recheck=false ac_cs_silent=false -SHELL=\${CONFIG_SHELL-$SHELL} -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -## --------------------- ## -## M4sh Initialization. ## -## --------------------- ## +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then +as_nop=: +if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 +then : emulate sh NULLCMD=: - # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST -else - case `(set -o) 2>/dev/null` in - *posix*) set -o posix ;; +else $as_nop + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; esac - fi +# Reset variables that may have inherited troublesome values from +# the environment. -# PATH needs CR -# Avoid depending upon Character Ranges. -as_cr_letters='abcdefghijklmnopqrstuvwxyz' -as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' -as_cr_Letters=$as_cr_letters$as_cr_LETTERS -as_cr_digits='0123456789' -as_cr_alnum=$as_cr_Letters$as_cr_digits - -# The user is always right. -if test "${PATH_SEPARATOR+set}" != set; then - echo "#! /bin/sh" >conf$$.sh - echo "exit 0" >>conf$$.sh - chmod +x conf$$.sh - if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then - PATH_SEPARATOR=';' - else - PATH_SEPARATOR=: - fi - rm -f conf$$.sh -fi - -# Support unset when possible. -if ( (MAIL=60; unset MAIL) || exit) >/dev/null 2>&1; then - as_unset=unset -else - as_unset=false -fi - - -# IFS -# We need space, tab and new line, in precisely that order. Quoting is -# there to prevent editors from complaining about space-tab. -# (If _AS_PATH_WALK were called with IFS unset, it would disable word -# splitting by setting IFS to empty value.) +# IFS needs to be set, to space, tab, and newline, in precisely that order. +# (If _AS_PATH_WALK were called with IFS unset, it would have the +# side effect of setting IFS to empty, thus disabling word splitting.) +# Quoting is to prevent editors from complaining about space-tab. as_nl=' ' +export as_nl IFS=" "" $as_nl" +PS1='$ ' +PS2='> ' +PS4='+ ' + +# Ensure predictable behavior from utilities with locale-dependent output. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# We cannot yet rely on "unset" to work, but we need these variables +# to be unset--not just set to an empty or harmless value--now, to +# avoid bugs in old shells (e.g. pre-3.0 UWIN ksh). This construct +# also avoids known problems related to "unset" and subshell syntax +# in other old shells (e.g. bash 2.01 and pdksh 5.2.14). +for as_var in BASH_ENV ENV MAIL MAILPATH CDPATH +do eval test \${$as_var+y} \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done + +# Ensure that fds 0, 1, and 2 are open. +if (exec 3>&0) 2>/dev/null; then :; else exec 0&1) 2>/dev/null; then :; else exec 1>/dev/null; fi +if (exec 3>&2) ; then :; else exec 2>/dev/null; fi + +# The user is always right. +if ${PATH_SEPARATOR+false} :; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + # Find who we are. Look in the path if we contain no directory separator. -case $0 in +as_myself= +case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break -done + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + test -r "$as_dir$0" && as_myself=$as_dir$0 && break + done IFS=$as_save_IFS ;; @@ -6131,32 +8019,95 @@ if test "x$as_myself" = x; then as_myself=$0 fi if test ! -f "$as_myself"; then - echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 - { (exit 1); exit 1; } + printf "%s\n" "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 fi -# Work around bugs in pre-3.0 UWIN ksh. -for as_var in ENV MAIL MAILPATH -do ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var -done -PS1='$ ' -PS2='> ' -PS4='+ ' -# NLS nuisances. -for as_var in \ - LANG LANGUAGE LC_ADDRESS LC_ALL LC_COLLATE LC_CTYPE LC_IDENTIFICATION \ - LC_MEASUREMENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER \ - LC_TELEPHONE LC_TIME -do - if (set +x; test -z "`(eval $as_var=C; export $as_var) 2>&1`"); then - eval $as_var=C; export $as_var - else - ($as_unset $as_var) >/dev/null 2>&1 && $as_unset $as_var + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 fi -done + printf "%s\n" "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null +then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else $as_nop + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null +then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else $as_nop + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + -# Required to use basename. if expr a : '\(a\)' >/dev/null 2>&1 && test "X`expr 00001 : '.*\(...\)'`" = X001; then as_expr=expr @@ -6170,13 +8121,17 @@ else as_basename=false fi +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi -# Name of the executable. as_me=`$as_basename -- "$0" || $as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ X"$0" : 'X\(//\)$' \| \ X"$0" : 'X\(/\)' \| . 2>/dev/null || -echo X/"$0" | +printf "%s\n" X/"$0" | sed '/^.*\/\([^/][^/]*\)\/*$/{ s//\1/ q @@ -6191,615 +8146,78 @@ echo X/"$0" | } s/.*/./; q'` -# CDPATH. -$as_unset CDPATH +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits - - as_lineno_1=$LINENO - as_lineno_2=$LINENO - test "x$as_lineno_1" != "x$as_lineno_2" && - test "x`expr $as_lineno_1 + 1`" = "x$as_lineno_2" || { - - # Create $as_me.lineno as a copy of $as_myself, but with $LINENO - # uniformly replaced by the line number. The first 'sed' inserts a - # line-number line after each line using $LINENO; the second 'sed' - # does the real work. The second script uses 'N' to pair each - # line-number line with the line containing $LINENO, and appends - # trailing '-' during substitution so that $LINENO is not a special - # case at line end. - # (Raja R Harinath suggested sed '=', and Paul Eggert wrote the - # scripts with optimization help from Paolo Bonzini. Blame Lee - # E. McMahon (1931-1989) for sed's syntax. :-) - sed -n ' - p - /[$]LINENO/= - ' <$as_myself | - sed ' - s/[$]LINENO.*/&-/ - t lineno - b - :lineno - N - :loop - s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ - t loop - s/-\n.*// - ' >$as_me.lineno && - chmod +x "$as_me.lineno" || - { echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2 - { (exit 1); exit 1; }; } - - # Don't try to exec as it changes $[0], causing all sort of problems - # (the dirname of $[0] is not the place where we might find the - # original and so on. Autoconf is especially sensitive to this). - . "./$as_me.lineno" - # Exit status is that of the last command. - exit -} - - -if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then - as_dirname=dirname -else - as_dirname=false -fi - +# Determine whether it's possible to make 'echo' print without a newline. +# These variables are no longer used directly by Autoconf, but are AC_SUBSTed +# for compatibility with existing Makefiles. ECHO_C= ECHO_N= ECHO_T= -case `echo -n x` in +case `echo -n x` in #((((( -n*) - case `echo 'x\c'` in + case `echo 'xy\c'` in *c*) ECHO_T=' ';; # ECHO_T is single tab character. - *) ECHO_C='\c';; + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; esac;; *) ECHO_N='-n';; esac -if expr a : '\(a\)' >/dev/null 2>&1 && - test "X`expr 00001 : '.*\(...\)'`" = X001; then - as_expr=expr -else - as_expr=false -fi +# For backward compatibility with old third-party macros, we provide +# the shell variables $as_echo and $as_echo_n. New code should use +# AS_ECHO(["message"]) and AS_ECHO_N(["message"]), respectively. +as_echo='printf %s\n' +as_echo_n='printf %s' rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file else rm -f conf$$.dir - mkdir conf$$.dir + mkdir conf$$.dir 2>/dev/null fi -echo >conf$$.file -if ln -s conf$$.file conf$$ 2>/dev/null; then - as_ln_s='ln -s' - # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -p'. - ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || - as_ln_s='cp -p' -elif ln conf$$.file conf$$ 2>/dev/null; then - as_ln_s=ln +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi else - as_ln_s='cp -p' + as_ln_s='cp -pR' fi rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file rmdir conf$$.dir 2>/dev/null -if mkdir -p . 2>/dev/null; then - as_mkdir_p=: -else - test -d ./-p && rmdir ./-p - as_mkdir_p=false -fi -if test -x / >/dev/null 2>&1; then - as_test_x='test -x' -else - if ls -dL / >/dev/null 2>&1; then - as_ls_L_option=L - else - as_ls_L_option= - fi - as_test_x=' - eval sh -c '\'' - if test -d "$1"; then - test -d "$1/."; - else - case $1 in - -*)set "./$1";; - esac; - case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in - ???[sx]*):;;*)false;;esac;fi - '\'' sh - ' -fi -as_executable_p=$as_test_x - -# Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" - -# Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" - - -exec 6>&1 - -# Save the log message, to keep $[0] and so on meaningful, and to -# report actual input values of CONFIG_FILES etc. instead of their -# values after options handling. -ac_log=" -This file was extended by pnp $as_me 0.6.26, which was -generated by GNU Autoconf 2.61. Invocation command line was - - CONFIG_FILES = $CONFIG_FILES - CONFIG_HEADERS = $CONFIG_HEADERS - CONFIG_LINKS = $CONFIG_LINKS - CONFIG_COMMANDS = $CONFIG_COMMANDS - $ $0 $@ - -on `(hostname || uname -n) 2>/dev/null | sed 1q` -" - -_ACEOF - -cat >>$CONFIG_STATUS <<_ACEOF -# Files that config.status was made for. -config_files="$ac_config_files" -config_headers="$ac_config_headers" - -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF -ac_cs_usage="\ -\`$as_me' instantiates files from templates according to the -current configuration. - -Usage: $0 [OPTIONS] [FILE]... - - -h, --help print this help, then exit - -V, --version print version number and configuration settings, then exit - -q, --quiet do not print progress messages - -d, --debug don't remove temporary files - --recheck update $as_me by reconfiguring in the same conditions - --file=FILE[:TEMPLATE] - instantiate the configuration file FILE - --header=FILE[:TEMPLATE] - instantiate the configuration header FILE - -Configuration files: -$config_files - -Configuration headers: -$config_headers - -Report bugs to ." - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF -ac_cs_version="\\ -pnp config.status 0.6.26 -configured by $0, generated by GNU Autoconf 2.61, - with options \\"`echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`\\" - -Copyright (C) 2006 Free Software Foundation, Inc. -This config.status script is free software; the Free Software Foundation -gives unlimited permission to copy, distribute and modify it." - -ac_pwd='$ac_pwd' -srcdir='$srcdir' -INSTALL='$INSTALL' -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF -# If no file are specified by the user, then we need to provide default -# value. By we need to know if files were specified by the user. -ac_need_defaults=: -while test $# != 0 -do - case $1 in - --*=*) - ac_option=`expr "X$1" : 'X\([^=]*\)='` - ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` - ac_shift=: - ;; - *) - ac_option=$1 - ac_optarg=$2 - ac_shift=shift - ;; - esac - - case $ac_option in - # Handling of the options. - -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) - ac_cs_recheck=: ;; - --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) - echo "$ac_cs_version"; exit ;; - --debug | --debu | --deb | --de | --d | -d ) - debug=: ;; - --file | --fil | --fi | --f ) - $ac_shift - CONFIG_FILES="$CONFIG_FILES $ac_optarg" - ac_need_defaults=false;; - --header | --heade | --head | --hea ) - $ac_shift - CONFIG_HEADERS="$CONFIG_HEADERS $ac_optarg" - ac_need_defaults=false;; - --he | --h) - # Conflict between --help and --header - { echo "$as_me: error: ambiguous option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; };; - --help | --hel | -h ) - echo "$ac_cs_usage"; exit ;; - -q | -quiet | --quiet | --quie | --qui | --qu | --q \ - | -silent | --silent | --silen | --sile | --sil | --si | --s) - ac_cs_silent=: ;; - - # This is an error. - -*) { echo "$as_me: error: unrecognized option: $1 -Try \`$0 --help' for more information." >&2 - { (exit 1); exit 1; }; } ;; - - *) ac_config_targets="$ac_config_targets $1" - ac_need_defaults=false ;; - - esac - shift -done - -ac_configure_extra_args= - -if $ac_cs_silent; then - exec 6>/dev/null - ac_configure_extra_args="$ac_configure_extra_args --silent" -fi - -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF -if \$ac_cs_recheck; then - echo "running CONFIG_SHELL=$SHELL $SHELL $0 "$ac_configure_args \$ac_configure_extra_args " --no-create --no-recursion" >&6 - CONFIG_SHELL=$SHELL - export CONFIG_SHELL - exec $SHELL "$0"$ac_configure_args \$ac_configure_extra_args --no-create --no-recursion -fi - -_ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF -exec 5>>config.log +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () { - echo - sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX -## Running $as_me. ## -_ASBOX - echo "$ac_log" -} >&5 -_ACEOF -cat >>$CONFIG_STATUS <<_ACEOF -_ACEOF - -cat >>$CONFIG_STATUS <<\_ACEOF - -# Handling of arguments. -for ac_config_target in $ac_config_targets -do - case $ac_config_target in - "include/config.h") CONFIG_HEADERS="$CONFIG_HEADERS include/config.h:include/config.h.in" ;; - "subst") CONFIG_FILES="$CONFIG_FILES subst" ;; - "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; - "share/Makefile") CONFIG_FILES="$CONFIG_FILES share/Makefile" ;; - "lib/Makefile") CONFIG_FILES="$CONFIG_FILES lib/Makefile" ;; - "scripts/Makefile") CONFIG_FILES="$CONFIG_FILES scripts/Makefile" ;; - "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; - "sample-config/Makefile") CONFIG_FILES="$CONFIG_FILES sample-config/Makefile" ;; - "man/Makefile") CONFIG_FILES="$CONFIG_FILES man/Makefile" ;; - - *) { { echo "$as_me:$LINENO: error: invalid argument: $ac_config_target" >&5 -echo "$as_me: error: invalid argument: $ac_config_target" >&2;} - { (exit 1); exit 1; }; };; - esac -done - - -# If the user did not use the arguments to specify the items to instantiate, -# then the envvar interface is used. Set only those that are not. -# We use the long form for the default assignment because of an extremely -# bizarre bug on SunOS 4.1.3. -if $ac_need_defaults; then - test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files - test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers -fi - -# Have a temporary directory for convenience. Make it in the build tree -# simply because there is no reason against having it here, and in addition, -# creating and moving files from /tmp can sometimes cause problems. -# Hook for its removal unless debugging. -# Note that there is a small window in which the directory will not be cleaned: -# after its creation but before its name has been assigned to `$tmp'. -$debug || -{ - tmp= - trap 'exit_status=$? - { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status -' 0 - trap '{ (exit 1); exit 1; }' 1 2 13 15 -} -# Create a (secure) tmp directory for tmp files. - -{ - tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && - test -n "$tmp" && test -d "$tmp" -} || -{ - tmp=./conf$$-$RANDOM - (umask 077 && mkdir "$tmp") -} || -{ - echo "$me: cannot create a temporary directory in ." >&2 - { (exit 1); exit 1; } -} - -# -# Set up the sed scripts for CONFIG_FILES section. -# - -# No need to generate the scripts if there are no CONFIG_FILES. -# This happens for instance when ./config.status config.h -if test -n "$CONFIG_FILES"; then - -_ACEOF - - - -ac_delim='%!_!# ' -for ac_last_try in false false false false false :; do - cat >conf$$subs.sed <<_ACEOF -SHELL!$SHELL$ac_delim -PATH_SEPARATOR!$PATH_SEPARATOR$ac_delim -PACKAGE_NAME!$PACKAGE_NAME$ac_delim -PACKAGE_TARNAME!$PACKAGE_TARNAME$ac_delim -PACKAGE_VERSION!$PACKAGE_VERSION$ac_delim -PACKAGE_STRING!$PACKAGE_STRING$ac_delim -PACKAGE_BUGREPORT!$PACKAGE_BUGREPORT$ac_delim -exec_prefix!$exec_prefix$ac_delim -prefix!$prefix$ac_delim -program_transform_name!$program_transform_name$ac_delim -bindir!$bindir$ac_delim -sbindir!$sbindir$ac_delim -libexecdir!$libexecdir$ac_delim -datarootdir!$datarootdir$ac_delim -datadir!$datadir$ac_delim -sysconfdir!$sysconfdir$ac_delim -sharedstatedir!$sharedstatedir$ac_delim -localstatedir!$localstatedir$ac_delim -includedir!$includedir$ac_delim -oldincludedir!$oldincludedir$ac_delim -docdir!$docdir$ac_delim -infodir!$infodir$ac_delim -htmldir!$htmldir$ac_delim -dvidir!$dvidir$ac_delim -pdfdir!$pdfdir$ac_delim -psdir!$psdir$ac_delim -libdir!$libdir$ac_delim -localedir!$localedir$ac_delim -mandir!$mandir$ac_delim -DEFS!$DEFS$ac_delim -ECHO_C!$ECHO_C$ac_delim -ECHO_N!$ECHO_N$ac_delim -ECHO_T!$ECHO_T$ac_delim -LIBS!$LIBS$ac_delim -build_alias!$build_alias$ac_delim -host_alias!$host_alias$ac_delim -target_alias!$target_alias$ac_delim -PKG_NAME!$PKG_NAME$ac_delim -PKG_VERSION!$PKG_VERSION$ac_delim -PKG_HOME_URL!$PKG_HOME_URL$ac_delim -PKG_REL_DATE!$PKG_REL_DATE$ac_delim -ac_configure_args!$ac_configure_args$ac_delim -XML_STRUCTURE_VERSION!$XML_STRUCTURE_VERSION$ac_delim -INSTALL_PROGRAM!$INSTALL_PROGRAM$ac_delim -INSTALL_SCRIPT!$INSTALL_SCRIPT$ac_delim -INSTALL_DATA!$INSTALL_DATA$ac_delim -INSTALL!$INSTALL$ac_delim -build!$build$ac_delim -build_cpu!$build_cpu$ac_delim -build_vendor!$build_vendor$ac_delim -build_os!$build_os$ac_delim -host!$host$ac_delim -host_cpu!$host_cpu$ac_delim -host_vendor!$host_vendor$ac_delim -host_os!$host_os$ac_delim -CC!$CC$ac_delim -CFLAGS!$CFLAGS$ac_delim -LDFLAGS!$LDFLAGS$ac_delim -CPPFLAGS!$CPPFLAGS$ac_delim -ac_ct_CC!$ac_ct_CC$ac_delim -EXEEXT!$EXEEXT$ac_delim -OBJEXT!$OBJEXT$ac_delim -SET_MAKE!$SET_MAKE$ac_delim -STRIP!$STRIP$ac_delim -CP!$CP$ac_delim -CPP!$CPP$ac_delim -GREP!$GREP$ac_delim -EGREP!$EGREP$ac_delim -LIBOBJS!$LIBOBJS$ac_delim -KOHANA!$KOHANA$ac_delim -KOHANA_SYSTEM!$KOHANA_SYSTEM$ac_delim -nagios_user!$nagios_user$ac_delim -nagios_grp!$nagios_grp$ac_delim -INSTALL_OPTS!$INSTALL_OPTS$ac_delim -PERL!$PERL$ac_delim -PERL_LIB_PATH!$PERL_LIB_PATH$ac_delim -RRDTOOL!$RRDTOOL$ac_delim -PERFDATA_LOG!$PERFDATA_LOG$ac_delim -PERFDATA_DIR!$PERFDATA_DIR$ac_delim -PERFDATA_SPOOL_DIR!$PERFDATA_SPOOL_DIR$ac_delim -DEBUG!$DEBUG$ac_delim -HTTPD_CONF!$HTTPD_CONF$ac_delim -BASE_URL!$BASE_URL$ac_delim -init_dir!$init_dir$ac_delim -pnpsender_name!$pnpsender_name$ac_delim -npcd_name!$npcd_name$ac_delim -pp_pl_name!$pp_pl_name$ac_delim -MOD_CFLAGS!$MOD_CFLAGS$ac_delim -MOD_LDFLAGS!$MOD_LDFLAGS$ac_delim -RRDS!$RRDS$ac_delim -LTLIBOBJS!$LTLIBOBJS$ac_delim -_ACEOF - - if test `sed -n "s/.*$ac_delim\$/X/p" conf$$subs.sed | grep -c X` = 91; then - break - elif $ac_last_try; then - { { echo "$as_me:$LINENO: error: could not make $CONFIG_STATUS" >&5 -echo "$as_me: error: could not make $CONFIG_STATUS" >&2;} - { (exit 1); exit 1; }; } - else - ac_delim="$ac_delim!$ac_delim _$ac_delim!! " - fi -done - -ac_eof=`sed -n '/^CEOF[0-9]*$/s/CEOF/0/p' conf$$subs.sed` -if test -n "$ac_eof"; then - ac_eof=`echo "$ac_eof" | sort -nru | sed 1q` - ac_eof=`expr $ac_eof + 1` -fi - -cat >>$CONFIG_STATUS <<_ACEOF -cat >"\$tmp/subs-1.sed" <<\CEOF$ac_eof -/@[a-zA-Z_][a-zA-Z_0-9]*@/!b end -_ACEOF -sed ' -s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g -s/^/s,@/; s/!/@,|#_!!_#|/ -:n -t n -s/'"$ac_delim"'$/,g/; t -s/$/\\/; p -N; s/^.*\n//; s/[,\\&]/\\&/g; s/@/@|#_!!_#|/g; b n -' >>$CONFIG_STATUS >$CONFIG_STATUS <<_ACEOF -:end -s/|#_!!_#|//g -CEOF$ac_eof -_ACEOF - - -# VPATH may cause trouble with some makes, so we remove $(srcdir), -# ${srcdir} and @srcdir@ from VPATH if srcdir is ".", strip leading and -# trailing colons and then remove the whole line if VPATH becomes empty -# (actually we leave an empty line to preserve line numbers). -if test "x$srcdir" = x.; then - ac_vpsub='/^[ ]*VPATH[ ]*=/{ -s/:*\$(srcdir):*/:/ -s/:*\${srcdir}:*/:/ -s/:*@srcdir@:*/:/ -s/^\([^=]*=[ ]*\):*/\1/ -s/:*$// -s/^[^=]*=[ ]*$// -}' -fi - -cat >>$CONFIG_STATUS <<\_ACEOF -fi # test -n "$CONFIG_FILES" - - -for ac_tag in :F $CONFIG_FILES :H $CONFIG_HEADERS -do - case $ac_tag in - :[FHLC]) ac_mode=$ac_tag; continue;; - esac - case $ac_mode$ac_tag in - :[FHL]*:*);; - :L* | :C*:*) { { echo "$as_me:$LINENO: error: Invalid tag $ac_tag." >&5 -echo "$as_me: error: Invalid tag $ac_tag." >&2;} - { (exit 1); exit 1; }; };; - :[FH]-) ac_tag=-:-;; - :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; - esac - ac_save_IFS=$IFS - IFS=: - set x $ac_tag - IFS=$ac_save_IFS - shift - ac_file=$1 - shift - - case $ac_mode in - :L) ac_source=$1;; - :[FH]) - ac_file_inputs= - for ac_f - do - case $ac_f in - -) ac_f="$tmp/stdin";; - *) # Look for the file first in the build tree, then in the source tree - # (if the path is not absolute). The absolute path cannot be DOS-style, - # because $ac_f cannot contain `:'. - test -f "$ac_f" || - case $ac_f in - [\\/$]*) false;; - *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; - esac || - { { echo "$as_me:$LINENO: error: cannot find input file: $ac_f" >&5 -echo "$as_me: error: cannot find input file: $ac_f" >&2;} - { (exit 1); exit 1; }; };; - esac - ac_file_inputs="$ac_file_inputs $ac_f" - done - - # Let's still pretend it is `configure' which instantiates (i.e., don't - # use $as_me), people would be surprised to read: - # /* config.h. Generated by config.status. */ - configure_input="Generated from "`IFS=: - echo $* | sed 's|^[^:]*/||;s|:[^:]*/|, |g'`" by configure." - if test x"$ac_file" != x-; then - configure_input="$ac_file. $configure_input" - { echo "$as_me:$LINENO: creating $ac_file" >&5 -echo "$as_me: creating $ac_file" >&6;} - fi - - case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin";; - esac - ;; - esac - - ac_dir=`$as_dirname -- "$ac_file" || -$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ - X"$ac_file" : 'X\(//\)[^/]' \| \ - X"$ac_file" : 'X\(//\)$' \| \ - X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || -echo X"$ac_file" | - sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ - s//\1/ - q - } - /^X\(\/\/\)[^/].*/{ - s//\1/ - q - } - /^X\(\/\/\)$/{ - s//\1/ - q - } - /^X\(\/\).*/{ - s//\1/ - q - } - s/.*/./; q'` - { as_dir="$ac_dir" case $as_dir in #( -*) as_dir=./$as_dir;; esac - test -d "$as_dir" || { $as_mkdir_p && mkdir -p "$as_dir"; } || { + test -d "$as_dir" || eval $as_mkdir_p || { as_dirs= while :; do case $as_dir in #( - *\'*) as_qdir=`echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #( + *\'*) as_qdir=`printf "%s\n" "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( *) as_qdir=$as_dir;; esac as_dirs="'$as_qdir' $as_dirs" @@ -6808,7 +8226,7 @@ $as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ X"$as_dir" : 'X\(//\)[^/]' \| \ X"$as_dir" : 'X\(//\)$' \| \ X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || -echo X"$as_dir" | +printf "%s\n" X"$as_dir" | sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ s//\1/ q @@ -6829,17 +8247,689 @@ echo X"$as_dir" | test -d "$as_dir" && break done test -z "$as_dirs" || eval "mkdir $as_dirs" - } || test -d "$as_dir" || { { echo "$as_me:$LINENO: error: cannot create directory $as_dir" >&5 -echo "$as_me: error: cannot create directory $as_dir" >&2;} - { (exit 1); exit 1; }; }; } + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by pnp4nagios $as_me 0.6.27, which was +generated by GNU Autoconf 2.71. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Report bugs to . +pnp4nagios home page: ." + +_ACEOF +ac_cs_config=`printf "%s\n" "$ac_configure_args" | sed "$ac_safe_unquote"` +ac_cs_config_escaped=`printf "%s\n" "$ac_cs_config" | sed "s/^ //; s/'/'\\\\\\\\''/g"` +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config='$ac_cs_config_escaped' +ac_cs_version="\\ +pnp4nagios config.status 0.6.27 +configured by $0, generated by GNU Autoconf 2.71, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2021 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +AWK='$AWK' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + printf "%s\n" "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + printf "%s\n" "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`printf "%s\n" "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`printf "%s\n" "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + printf "%s\n" "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \printf "%s\n" "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + printf "%s\n" "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "include/config.h") CONFIG_HEADERS="$CONFIG_HEADERS include/config.h:include/config.h.in" ;; + "subst") CONFIG_FILES="$CONFIG_FILES subst" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "share/Makefile") CONFIG_FILES="$CONFIG_FILES share/Makefile" ;; + "lib/Makefile") CONFIG_FILES="$CONFIG_FILES lib/Makefile" ;; + "scripts/Makefile") CONFIG_FILES="$CONFIG_FILES scripts/Makefile" ;; + "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;; + "sample-config/Makefile") CONFIG_FILES="$CONFIG_FILES sample-config/Makefile" ;; + "man/Makefile") CONFIG_FILES="$CONFIG_FILES man/Makefile" ;; + "include/stamp-h") CONFIG_FILES="$CONFIG_FILES include/stamp-h" ;; + "scripts/rrd_modify.pl") CONFIG_FILES="$CONFIG_FILES scripts/rrd_modify.pl" ;; + "scripts/rc.npcd") CONFIG_FILES="$CONFIG_FILES scripts/rc.npcd" ;; + "scripts/rc.pnp_gearman_worker") CONFIG_FILES="$CONFIG_FILES scripts/rc.pnp_gearman_worker" ;; + "scripts/npcd.service") CONFIG_FILES="$CONFIG_FILES scripts/npcd.service" ;; + "scripts/pnp_gearman_worker.service") CONFIG_FILES="$CONFIG_FILES scripts/pnp_gearman_worker.service" ;; + "scripts/newbsd.npcd") CONFIG_FILES="$CONFIG_FILES scripts/newbsd.npcd" ;; + "scripts/check_pnp_rrds.pl") CONFIG_FILES="$CONFIG_FILES scripts/check_pnp_rrds.pl" ;; + "share/pnp/index.php") CONFIG_FILES="$CONFIG_FILES share/pnp/index.php" ;; + "share/pnp/install.php") CONFIG_FILES="$CONFIG_FILES share/pnp/install.php" ;; + "sample-config/README_config.md") CONFIG_FILES="$CONFIG_FILES sample-config/README_config.md" ;; + "sample-config/SetLogLevels") CONFIG_FILES="$CONFIG_FILES sample-config/SetLogLevels" ;; + "sample-config/config_tools/NagiosCfgMod.pl") CONFIG_FILES="$CONFIG_FILES sample-config/config_tools/NagiosCfgMod.pl" ;; + "sample-config/config_tools/TemplateMod.pl") CONFIG_FILES="$CONFIG_FILES sample-config/config_tools/TemplateMod.pl" ;; + "sample-config/config_tools/verify_pnp_config") CONFIG_FILES="$CONFIG_FILES sample-config/config_tools/verify_pnp_config" ;; + "sample-config/config_samples/apache.pnp4nagios.conf") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/apache.pnp4nagios.conf" ;; + "sample-config/config_samples/config.php") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/config.php" ;; + "sample-config/config_samples/lighttpd.pnp4nagios.conf") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/lighttpd.pnp4nagios.conf" ;; + "sample-config/config_samples/nagios.cfg") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/nagios.cfg" ;; + "sample-config/config_samples/nginx.pnp4nagios.conf") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/nginx.pnp4nagios.conf" ;; + "sample-config/config_samples/npcd.cfg") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/npcd.cfg" ;; + "sample-config/config_samples/pnp-bulk.cfg") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/pnp-bulk.cfg" ;; + "sample-config/config_samples/pnp-npcd.cfg") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/pnp-npcd.cfg" ;; + "sample-config/config_samples/pnp-sync.cfg") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/pnp-sync.cfg" ;; + "sample-config/config_samples/process_perfdata.cfg") CONFIG_FILES="$CONFIG_FILES sample-config/config_samples/process_perfdata.cfg" ;; + "sample-config/pnp4nagios_release") CONFIG_FILES="$CONFIG_FILES sample-config/pnp4nagios_release" ;; + "man/npcd.8") CONFIG_FILES="$CONFIG_FILES man/npcd.8" ;; + "ci/pnp4nagios.spec") CONFIG_FILES="$CONFIG_FILES ci/pnp4nagios.spec" ;; + "pnp4nagios.fc") CONFIG_FILES="$CONFIG_FILES pnp4nagios.fc" ;; + "src/config.c") CONFIG_FILES="$CONFIG_FILES src/config.c" ;; + "src/npcdmod.c") CONFIG_FILES="$CONFIG_FILES src/npcdmod.c" ;; + "contrib/fedora/pnp4nagios.logrotate.conf") CONFIG_FILES="$CONFIG_FILES contrib/fedora/pnp4nagios.logrotate.conf" ;; + "contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf") CONFIG_FILES="$CONFIG_FILES contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf" ;; + "contrib/fedora/logwatch/scripts/services/pnp4nagios") CONFIG_FILES="$CONFIG_FILES contrib/fedora/logwatch/scripts/services/pnp4nagios" ;; + "contrib/ssi/status-header.ssi") CONFIG_FILES="$CONFIG_FILES contrib/ssi/status-header.ssi" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test ${CONFIG_FILES+y} || CONFIG_FILES=$config_files + test ${CONFIG_HEADERS+y} || CONFIG_HEADERS=$config_headers +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`printf "%s\n" "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + printf "%s\n" "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +printf "%s\n" "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`printf "%s\n" "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +printf "%s\n" X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p ac_builddir=. case "$ac_dir" in .) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; *) - ac_dir_suffix=/`echo "$ac_dir" | sed 's,^\.[\\/],,'` + ac_dir_suffix=/`printf "%s\n" "$ac_dir" | sed 's|^\.[\\/]||'` # A ".." for each directory in $ac_dir_suffix. - ac_top_builddir_sub=`echo "$ac_dir_suffix" | sed 's,/[^\\/]*,/..,g;s,/,,'` + ac_top_builddir_sub=`printf "%s\n" "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` case $ac_top_builddir_sub in "") ac_top_builddir_sub=. ac_top_build_prefix= ;; *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; @@ -6879,12 +8969,12 @@ ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix esac _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # If the template does not know about datarootdir, expand it. # FIXME: This hack should be removed a few years after 2.60. ac_datarootdir_hack=; ac_datarootdir_seen= - -case `sed -n '/datarootdir/ { +ac_sed_dataroot=' +/datarootdir/ { p q } @@ -6892,36 +8982,37 @@ case `sed -n '/datarootdir/ { /@docdir@/p /@infodir@/p /@localedir@/p -/@mandir@/p -' $ac_file_inputs` in +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in *datarootdir*) ac_datarootdir_seen=yes;; *@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) - { echo "$as_me:$LINENO: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 -echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +printf "%s\n" "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} _ACEOF -cat >>$CONFIG_STATUS <<_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_datarootdir_hack=' s&@datadir@&$datadir&g s&@docdir@&$docdir&g s&@infodir@&$infodir&g s&@localedir@&$localedir&g s&@mandir@&$mandir&g - s&\\\${datarootdir}&$datarootdir&g' ;; + s&\\\${datarootdir}&$datarootdir&g' ;; esac _ACEOF # Neutralize VPATH when `$srcdir' = `.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? -cat >>$CONFIG_STATUS <<_ACEOF - sed "$ac_vpsub +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub $extrasub _ACEOF -cat >>$CONFIG_STATUS <<\_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 :t /@[a-zA-Z_][a-zA-Z_0-9]*@/!b -s&@configure_input@&$configure_input&;t t +s|@configure_input@|$ac_sed_conf_input|;t t s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t s&@srcdir@&$ac_srcdir&;t t s&@abs_srcdir@&$ac_abs_srcdir&;t t s&@top_srcdir@&$ac_top_srcdir&;t t @@ -6931,132 +9022,69 @@ s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t s&@INSTALL@&$ac_INSTALL&;t t $ac_datarootdir_hack -" $ac_file_inputs | sed -f "$tmp/subs-1.sed" >$tmp/out +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && - { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && - { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && - { echo "$as_me:$LINENO: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&5 -echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' -which seems to be undefined. Please make sure it is defined." >&2;} + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +printf "%s\n" "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} - rm -f "$tmp/stdin" + rm -f "$ac_tmp/stdin" case $ac_file in - -) cat "$tmp/out"; rm -f "$tmp/out";; - *) rm -f "$ac_file"; mv "$tmp/out" $ac_file;; - esac + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; :H) # # CONFIG_HEADER # -_ACEOF - -# Transform confdefs.h into a sed script `conftest.defines', that -# substitutes the proper values into config.h.in to produce config.h. -rm -f conftest.defines conftest.tail -# First, append a space to every undef/define line, to ease matching. -echo 's/$/ /' >conftest.defines -# Then, protect against being on the right side of a sed subst, or in -# an unquoted here document, in config.status. If some macros were -# called several times there might be several #defines for the same -# symbol, which is useless. But do not sort them, since the last -# AC_DEFINE must be honored. -ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* -# These sed commands are passed to sed as "A NAME B PARAMS C VALUE D", where -# NAME is the cpp macro being defined, VALUE is the value it is being given. -# PARAMS is the parameter list in the macro definition--in most cases, it's -# just an empty string. -ac_dA='s,^\\([ #]*\\)[^ ]*\\([ ]*' -ac_dB='\\)[ (].*,\\1define\\2' -ac_dC=' ' -ac_dD=' ,' - -uniq confdefs.h | - sed -n ' - t rset - :rset - s/^[ ]*#[ ]*define[ ][ ]*// - t ok - d - :ok - s/[\\&,]/\\&/g - s/^\('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/ '"$ac_dA"'\1'"$ac_dB"'\2'"${ac_dC}"'\3'"$ac_dD"'/p - s/^\('"$ac_word_re"'\)[ ]*\(.*\)/'"$ac_dA"'\1'"$ac_dB$ac_dC"'\2'"$ac_dD"'/p - ' >>conftest.defines - -# Remove the space that was appended to ease matching. -# Then replace #undef with comments. This is necessary, for -# example, in the case of _POSIX_SOURCE, which is predefined and required -# on some systems where configure will not decide to define it. -# (The regexp can be short, since the line contains either #define or #undef.) -echo 's/ $// -s,^[ #]*u.*,/* & */,' >>conftest.defines - -# Break up conftest.defines: -ac_max_sed_lines=50 - -# First sed command is: sed -f defines.sed $ac_file_inputs >"$tmp/out1" -# Second one is: sed -f defines.sed "$tmp/out1" >"$tmp/out2" -# Third one will be: sed -f defines.sed "$tmp/out2" >"$tmp/out1" -# et cetera. -ac_in='$ac_file_inputs' -ac_out='"$tmp/out1"' -ac_nxt='"$tmp/out2"' - -while : -do - # Write a here document: - cat >>$CONFIG_STATUS <<_ACEOF - # First, check the format of the line: - cat >"\$tmp/defines.sed" <<\\CEOF -/^[ ]*#[ ]*undef[ ][ ]*$ac_word_re[ ]*\$/b def -/^[ ]*#[ ]*define[ ][ ]*$ac_word_re[( ]/b def -b -:def -_ACEOF - sed ${ac_max_sed_lines}q conftest.defines >>$CONFIG_STATUS - echo 'CEOF - sed -f "$tmp/defines.sed"' "$ac_in >$ac_out" >>$CONFIG_STATUS - ac_in=$ac_out; ac_out=$ac_nxt; ac_nxt=$ac_in - sed 1,${ac_max_sed_lines}d conftest.defines >conftest.tail - grep . conftest.tail >/dev/null || break - rm -f conftest.defines - mv conftest.tail conftest.defines -done -rm -f conftest.defines conftest.tail - -echo "ac_result=$ac_in" >>$CONFIG_STATUS -cat >>$CONFIG_STATUS <<\_ACEOF if test x"$ac_file" != x-; then - echo "/* $configure_input */" >"$tmp/config.h" - cat "$ac_result" >>"$tmp/config.h" - if diff $ac_file "$tmp/config.h" >/dev/null 2>&1; then - { echo "$as_me:$LINENO: $ac_file is unchanged" >&5 -echo "$as_me: $ac_file is unchanged" >&6;} + { + printf "%s\n" "/* $configure_input */" >&1 \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +printf "%s\n" "$as_me: $ac_file is unchanged" >&6;} else - rm -f $ac_file - mv "$tmp/config.h" $ac_file + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else - echo "/* $configure_input */" - cat "$ac_result" + printf "%s\n" "/* $configure_input */" >&1 \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 fi - rm -f "$tmp/out12" ;; esac + + case $ac_file$ac_mode in + "include/stamp-h":F) date '+%Y-%m-%dT%H:%M:%S%z' > include/stamp-h ;; + + esac done # for ac_tag -{ (exit 0); exit 0; } +as_fn_exit 0 _ACEOF -chmod +x $CONFIG_STATUS ac_clean_files=$ac_clean_files_save +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + # configure is writing to config.log, and then calls config.status. # config.status does its own redirection, appending to config.log. @@ -7076,29 +9104,160 @@ if test "$no_create" != yes; then exec 5>>config.log # Use ||, not &&, to avoid exiting from the if with $? = 1, which # would make configure fail if this is the last instruction. - $ac_cs_success || { (exit 1); exit 1; } + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +printf "%s\n" "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi +#### need to use 'subst' instead of configure for this +#### to deal with 'use lib "no"' case for perl scripts $PERL subst summary $PERL subst scripts/process_perfdata.pl $PERL subst scripts/rrd_convert.pl -$PERL subst scripts/rrd_modify.pl -$PERL subst scripts/rc.npcd -$PERL subst scripts/rc.pnp_gearman_worker -$PERL subst scripts/check_pnp_rrds.pl -$PERL subst share/pnp/index.php -$PERL subst share/pnp/install.php -$PERL subst sample-config/httpd.conf -$PERL subst sample-config/lighttpd.pnp4nagios.conf -$PERL subst sample-config/nginx.pnp4nagios.conf -$PERL subst sample-config/nagios.cfg-sample -$PERL subst sample-config/misccommands.cfg-sample -$PERL subst sample-config/pnp/config.php -$PERL subst sample-config/pnp/npcd.cfg-sample -$PERL subst sample-config/pnp/process_perfdata.cfg-sample -$PERL subst sample-config/pnp/pnp4nagios_release -$PERL subst contrib/ssi/status-header.ssi -$PERL subst man/npcd.8 +# +if test "x$RRDS" = "x1"; then + $PERL -MRRDs -e '1;' 2>/dev/null + if test "$?" -ne 0; then + RRDS=0 + else + rrds_version=`$PERL -MRRDs -e 'print \$RRDs::VERSION;'` + fi +fi +rrdtest=`${RRDTOOL}|head -n1|cut -d' ' -f1| ${AWK} '{print tolower($0)}'` +rrdtest=`basename $rrdtest` +if test "x$rrdtest" != "xrrdtool" ; then + rrdtool_message="WARNING: '$RRDTOOL' does not look like rrdtool" +else + rrdtool_version=`${RRDTOOL}|head -n1|cut -d' ' -f2` + rrdtool_message="${RRDTOOL} Version ${rrdtool_version}" +fi + +echo "" +echo "" +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: *** Configuration summary for $PKG_NAME $PKG_VERSION $PKG_REL_DATE ***:" >&5 +printf "%s\n" "*** Configuration summary for $PKG_NAME $PKG_VERSION $PKG_REL_DATE ***:" >&6; } + +echo "" +echo " General Options:" +echo " -------------------------" + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Host OS: $host_os" >&5 +printf "%s\n" " Host OS: $host_os" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Distribution: $dist_type, $dist_ver" >&5 +printf "%s\n" " Distribution: $dist_type, $dist_ver" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: SELINUX enabled: $SELINUX" >&5 +printf "%s\n" " SELINUX enabled: $SELINUX" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Install \${prefix}: $prefix" >&5 +printf "%s\n" " Install \${prefix}: $prefix" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Nagios version: $NAGIOS_VER" >&5 +printf "%s\n" " Nagios version: $NAGIOS_VER" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Nagios user/group: $nagios_user,$nagios_grp" >&5 +printf "%s\n" " Nagios user/group: $nagios_user,$nagios_grp" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Root user/group: root,$root_grp" >&5 +printf "%s\n" " Root user/group: root,$root_grp" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: PNP HTML dir: $datarootdir" >&5 +printf "%s\n" " PNP HTML dir: $datarootdir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: Config dir: $pkgsysconfdir" >&5 +printf "%s\n" " Config dir: $pkgsysconfdir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: rrdtool binary: $rrdtool_message" >&5 +printf "%s\n" " rrdtool binary: $rrdtool_message" >&6; } +if test "x$RRDS" = "x0" ; then +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: RRDs Perl Modules: *** NOT FOUND ***" >&5 +printf "%s\n" " RRDs Perl Modules: *** NOT FOUND ***" >&6; } +else +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: RRDs Perl Modules: (Version $rrds_version) FOUND" >&5 +printf "%s\n" " RRDs Perl Modules: (Version $rrds_version) FOUND" >&6; } +fi +if test "x$PERL_LIB_PATH" != "x" ; then +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: RRDs Perl search path: $PERL_LIB_PATH" >&5 +printf "%s\n" " RRDs Perl search path: $PERL_LIB_PATH" >&6; } +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: RRD Files stored in: $PERFDATA_DIR" >&5 +printf "%s\n" " RRD Files stored in: $PERFDATA_DIR" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: process_perfdata Logfile: $PERFDATA_LOG" >&5 +printf "%s\n" " process_perfdata Logfile: $PERFDATA_LOG" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: NPCD perfdata stored in: $PERFDATA_SPOOL_DIR" >&5 +printf "%s\n" " NPCD perfdata stored in: $PERFDATA_SPOOL_DIR" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: fontconfig cache dir: $CACHE_DIR" >&5 +printf "%s\n" " fontconfig cache dir: $CACHE_DIR" >&6; } + + + +echo "" +echo " Web Interface Options:" +echo " ------------------------" + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: http server: $HTTP_SERVER" >&5 +printf "%s\n" " http server: $HTTP_SERVER" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: http configs dir: $HTTP_CONFDIR" >&5 +printf "%s\n" " http configs dir: $HTTP_CONFDIR" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: put pnp http config File: ${HTTP_CONFDIR}/${PACKAGE_NAME}.conf" >&5 +printf "%s\n" " put pnp http config File: ${HTTP_CONFDIR}/${PACKAGE_NAME}.conf" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: http user/group: $HTTP_USER,$HTTP_GROUP" >&5 +printf "%s\n" " http user/group: $HTTP_USER,$HTTP_GROUP" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: HTML URL: https://localhost${PNP_URL}/" >&5 +printf "%s\n" " HTML URL: https://localhost${PNP_URL}/" >&6; } + +if test "x$DESTDIR" != "x" ; then +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: WARNING \${DESTDIR} set: $DESTDIR" >&5 +printf "%s\n" " WARNING \${DESTDIR} set: $DESTDIR" >&6; } +fi + +if test "x${DEBUG_LEVEL}" != "x0" ; then +echo " Debug output:" +echo " -------------" +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: DEBUG_LEVEL: ${DEBUG_LEVEL}" >&5 +printf "%s\n" " DEBUG_LEVEL: ${DEBUG_LEVEL}" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: perl exec: $PERL" >&5 +printf "%s\n" " perl exec: $PERL" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: shell exec: $SHELL" >&5 +printf "%s\n" " shell exec: $SHELL" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: libexecdir: $libexecdir" >&5 +printf "%s\n" " libexecdir: $libexecdir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: libdir: $libdir" >&5 +printf "%s\n" " libdir: $libdir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: sysconfdir: $sysconfdir" >&5 +printf "%s\n" " sysconfdir: $sysconfdir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: datarootdir: $datarootdir" >&5 +printf "%s\n" " datarootdir: $datarootdir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: datadir: $datadir" >&5 +printf "%s\n" " datadir: $datadir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: exec prefix: $exec_prefix" >&5 +printf "%s\n" " exec prefix: $exec_prefix" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: sbindir: $sbindir" >&5 +printf "%s\n" " sbindir: $sbindir" >&6; } +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: bindir: $bindir" >&5 +printf "%s\n" " bindir: $bindir" >&6; } +fi + +if test $opsys = unix ; then + if test "x$prefix" = "x/usr/local/nagios" ; then + echo "" + echo "" + echo "prefix=$prefix" + echo "You probably wanted to do:" + echo " ./configure --prefix=/usr/local/pnp4nagios" + echo "(or some similar prefix) to get the correct prefix." + fi +fi +if test "$install_method" = default ; then + if test $opsys = bsd ; then + echo "" + echo "" + echo "prefix=$prefix" + echo "You probably wanted to do:" + echo " ./configure --enable-install-method=os " + echo "to get the correct installation paths" + fi +fi + +echo "" +echo "" +echo "Review the options above for accuracy. If they look okay," +echo "type 'make all' to compile the main program" +echo "" +echo "For more info run ./configure --with-debug_level=1" -$PERL summary diff --git a/configure.ac b/configure.ac old mode 100644 new mode 100755 index 56f10d7..015c49f --- a/configure.ac +++ b/configure.ac @@ -1,130 +1,255 @@ -# -*- Autoconf -*- +# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. -AC_PREREQ(2.61) -AC_INIT(pnp, 0.6.26, pnp4nagios-devel@lists.sourceforge.net) +# Disable caching +define([AC_CACHE_LOAD],) +define([AC_CACHE_SAVE],) + +AC_PREREQ([2.61]) + +AC_INIT([pnp4nagios],[0.6.27],[pnp4nagios-devel@lists.sourceforge.net],[],[https://github.com/pnp4nagios/pnp4nagios]) +PKG_NAME="$PACKAGE_NAME" +PKG_VERSION="$PACKAGE_VERSION" + +# +# release and release_date +# ...gets overwritten by github release-building +# +PACKAGE_RELEASE="5" +PKG_REL_DATE="2024-03-18" +AC_SUBST(PACKAGE_RELEASE) +AC_SUBST(PKG_REL_DATE) + AC_CONFIG_SRCDIR(src/) AC_CONFIG_HEADERS(include/config.h:include/config.h.in) -AC_PREFIX_DEFAULT(/usr/local/pnp4nagios) -AC_DEFINE([DEFAULT_NAGIOS_USER], [nagios], [Default Nagios User]) -AC_DEFINE([DEFAULT_NAGIOS_GROUP], [nagios], [Default Nagios Group]) - -PKG_NAME=pnp4nagios -PKG_VERSION="0.6.26" -PKG_HOME_URL="http://www.pnp4nagios.org/pnp/start" -PKG_REL_DATE="08-21-2017" -AC_SUBST(PKG_NAME) -AC_SUBST(PKG_VERSION) -AC_SUBST(PKG_HOME_URL) -AC_SUBST(PKG_REL_DATE) +# +if echo $PATH | grep -qv '/sbin' ; then + echo "PATH variable doesn't include sbin, probable failure" + exit 1 +fi +# AC_SUBST(ac_configure_args) XML_STRUCTURE_VERSION="4" AC_SUBST(XML_STRUCTURE_VERSION) -dnl Figure out how to invoke "install" and what install options to use. - -AC_PROG_INSTALL -AC_SUBST(INSTALL) +DEBUG_LEVEL=0 +AC_ARG_WITH(debug_level, [ --with-debug_level= ], +DEBUG_LEVEL=$withval, DEBUG_LEVEL=0) +if test $DEBUG_LEVEL -gt 0 ; then +CFLAGS="${CFLAGS} -O0 -ggdb3 -g3" +fi +AC_SUBST(DEBUG_LEVEL) #dnl What OS are we running? AC_CANONICAL_HOST +#dnl kinda doubt much cross-compiling, but just in case... +AC_CANONICAL_TARGET + +dnl Get Nagios autoconf-macros +AC_PREFIX_DEFAULT(/usr/local/pnp4nagios) +INIT_PROG=npcd +AX_NAGIOS_GET_OS +AX_NAGIOS_GET_DISTRIB_TYPE +AX_NAGIOS_GET_INIT + +dnl permissions for 'init' files +if test $init_type = systemd ; then + INIT_PERM=0644 +else + INIT_PERM=0755 +fi +AC_SUBST(INIT_PERM) + + +AX_NAGIOS_GET_PATHS +AX_NAGIOS_GET_FILES +dnl undo some of the AX_NAGIOS_GET_PATHS problem with netbsd +if test $opsys = bsd -a $dist_type = netbsd ; then + sysconfdir="${prefix}/etc" + pkgsysconfdir="${sysconfdir}/pnp4nagios" + datarootdir="${datarootdir}/pnp4nagios" + libdir="${prefix}/lib/pnp4nagios" + libexecdir="${prefix}/libexec/pnp4nagios" + if test $initdiroverridden = no -a $init_type = newbsd ; then + initdir=/etc/rc.d + fi +fi + + +# for some reason AX_NAGIOS_GET_PATHS doesn't AC_SUBST this... +AC_SUBST(datadir) dnl Checks for programs. +AC_PROG_INSTALL +dnl netbsd (and others?) uses different switch for suffix +dnl -S for GNU variety install, taken as default +INSTALL_SUFFIX="-S" +dnl -B for netbsd +inbk=`install --help 2>&1|grep -o -e '-B suffix'|head -n 1` +if test "$inbk" = "-B suffix" ; then + INSTALL_SUFFIX="-B" +fi +AC_SUBST(INSTALL_SUFFIX) + AC_PROG_CC AC_PROG_MAKE_SET AC_PATH_PROG([STRIP],[strip],[true]) - - - +AC_PROG_GREP +AC_PROG_EGREP +AC_PROG_AWK +AC_PROG_SED +AC_PROG_LN_S AC_PATH_PROG(CP,cp) +AC_PATH_PROG(PERL,perl) + +eval sbindir=$sbindir # Checks for libraries. +AS_IF([test "q$target_cpu" = "qx86_64"],[x64="64"],[x64=""]) -# Checks for header files. -AC_HEADER_STDC -AC_HEADER_DIRENT -AC_HEADER_SYS_WAIT -#AC_CHECK_HEADERS(netinet/in.h string.h sys/socket.h unistd.h stdio.h stdlib.h getopt.h signal.h) -AC_CHECK_HEADERS(dirent.h stdio.h errno.h unistd.h syslog.h signal.h stdlib.h dirent.h string.h pthread.h getopt.h grp.h pwd.h sys/mman.h sys/types.h sys/wait.h sys/stat.h sys/socket.h sys/loadavg.h netinet/in.h fcntl.h limits.h) +if test x$libdir = x ; then + if test -d "/usr/lib${x64}" ; then + libdir="${prefix}/usr/lib${x64}/${PACKAGE_NAME}" + elif test -d "/lib${x64}"; then + libdir="${prefix}/lib${x64}/${PACKAGE_NAME}" + elif test -d "/usr/lib" ; then + libdir="${prefix}/usr/lib/${PACKAGE_NAME}" + else + libdir="${prefix}/lib/${PACKAGE_NAME}" + fi +fi +AC_ARG_WITH(libdir,[ --with-libdir=<$libdir> pnp4nagios libs are kept ], + libdir=$withval + ) +AC_SUBST(libdir) -# Checks for typedefs, structures, and compiler characteristics. -AC_TYPE_PID_T -AC_TYPE_SIGNAL -AC_TYPE_UID_T - -# Checks for structure members -#AC_CHECK_MEMBER([struct dirent.d_type], [AC_MSG_RESULT([We successfully have a `dirent_d_type'!])], -# [AC_MSG_ERROR([We need `dirent.d_type'!])], -# [#include ]) - -AC_STRUCT_DIRENT_D_TYPE - -# Checks for library functions. -AC_FUNC_FORK -AC_CHECK_FUNCS([bzero socket alarm strerror strspn getloadavg]) - -AC_FUNC_MALLOC -AC_FUNC_STAT - -AC_C_CONST - -dnl Layout Methods -layout="default" -AC_ARG_WITH(layout,[ --with-layout=\[default,debian\] sets directory layout],layout=$withval) - -case $layout in - debian) - prefix="/" - sysconfdir="/etc/${PKG_NAME}" - localstatedir="/var/log/${PKG_NAME}" - libexecdir="/usr/lib/${PKG_NAME}/libexec" - libdir="/usr/lib/${PKG_NAME}" - datarootdir="/usr/share/${PKG_NAME}/html" - PERFDATA_LOG="/var/log/${PKG_NAME}/perfdata.log" - PERFDATA_DIR="/var/lib/${PKG_NAME}/perfdata" - PERFDATA_SPOOL_DIR="/var/spool/${PKG_NAME}" - bindir="/usr/bin" - sbindir="/usr/sbin" - ;; - default-0.4) - prefix="/usr/local/nagios" - sysconfdir="\${prefix}/etc/pnp" - localstatedir="\${prefix}/var" - libexecdir="\${prefix}/libexec" - datarootdir="\${prefix}/share/pnp" - libdir="\${prefix}/lib/pnp" - PERFDATA_LOG="\${prefix}/var/perfdata.log" - PERFDATA_DIR="\${prefix}/share/perfdata" - PERFDATA_SPOOL_DIR="\${prefix}/var/spool/perfdata" - ;; - default) - PERFDATA_LOG="${localstatedir}/perfdata.log" - PERFDATA_DIR="${localstatedir}/perfdata" - PERFDATA_SPOOL_DIR="${localstatedir}/spool" - mandir="\${prefix}/man" - ;; -esac - -AC_ARG_WITH(kohana,[ --without-kohana does not install the kohana framework],KOHANA=no,KOHANA=yes) -AC_SUBST(KOHANA) -AC_ARG_WITH(kohana_system,[ --with-kohana_system= Points to an already installed kohana framework],KOHANA_SYSTEM=$withval,KOHANA_SYSTEM=$libdir/kohana/system) -AC_SUBST(KOHANA_SYSTEM) -AC_ARG_WITH(nagios_user,[ --with-nagios-user= sets user name to run nagios],nagios_user=$withval,nagios_user=nagios) -AC_ARG_WITH(nagios_group,[ --with-nagios-group= sets group name to run nagios],nagios_grp=$withval,nagios_grp=nagios) -AC_SUBST(nagios_user) -AC_SUBST(nagios_grp) -AC_DEFINE_UNQUOTED(DEFAULT_NAGIOS_USER,"$nagios_user") -AC_DEFINE_UNQUOTED(DEFAULT_NAGIOS_GROUP,"$nagios_grp") -INSTALL_OPTS="-o $nagios_user -g $nagios_grp" -AC_SUBST(INSTALL_OPTS) - -# Checks for programs. -AC_PATH_PROG(PERL,perl) # Check for Perl lib path PERL_LIB_PATH=no AC_ARG_WITH(perl_lib_path,[ --with-perl_lib_path= sets path to rrdtool RRDs perl modules.],PERL_LIB_PATH=$withval,PERL_LIB_PATH=no) AC_SUBST(PERL_LIB_PATH) + +# +# Checking for Perl Modules +# +foo=`$PERL -V` +AC_MSG_RESULT($foo) +bar=`rpm -qa` +AC_MSG_RESULT($bar) + +AC_MSG_CHECKING(for Perl Module Time::HiRes) +$PERL -MTime::HiRes -e exit >/dev/null 2>&1 +if test $? -ne 0; then + AC_MSG_RESULT(no) + AC_MSG_ERROR(Perl Module Time::HiRes not available) +else + AC_MSG_RESULT(yes) +fi + +AC_MSG_CHECKING(for Perl Module Getopt::Long) +$PERL -MGetopt::Long -e exit >/dev/null 2>&1 +if test $? -ne 0; then + AC_MSG_RESULT(no) + AC_MSG_ERROR(Perl Module Getopt::Long not available) +else + AC_MSG_RESULT(yes) +fi + +RRDS=0 +AC_MSG_CHECKING(for optional Perl Module RRDs) +$PERL -I${PERL_LIB_PATH} -MRRDs -e exit >/dev/null 2>&1 +if test $? -ne 0; then + AC_MSG_RESULT(no) + AC_MSG_WARN(Perl Module RRDs not available) + RRDS=0 +else + AC_MSG_RESULT(yes) + RRDS=1 +fi +AC_SUBST(RRDS) + +AC_ARG_WITH(kohana,[ --without-kohana does not install the kohana framework],KOHANA=no,KOHANA=yes) +AC_SUBST(KOHANA) +AC_ARG_WITH(kohana_system,[ --with-kohana_system= Points to an already installed kohana framework],KOHANA_SYSTEM=$withval,KOHANA_SYSTEM="${datarootdir}/kohana/system") +eval KOHANA_SYSTEM="${KOHANA_SYSTEM}" +AC_SUBST(KOHANA_SYSTEM) + +# Checks for library functions. +AC_FUNC_FORK +AC_CHECK_FUNCS([bzero socket alarm strerror strspn getloadavg]) +AC_FUNC_MALLOC +AC_FUNC_STAT +AC_C_CONST + + +# Checks for header files. + +AC_HEADER_DIRENT +AC_HEADER_SYS_WAIT +AC_CHECK_HEADERS(dirent.h stdio.h errno.h unistd.h syslog.h signal.h stdlib.h dirent.h string.h pthread.h getopt.h grp.h pwd.h sys/mman.h sys/types.h sys/wait.h sys/stat.h sys/socket.h sys/loadavg.h netinet/in.h fcntl.h limits.h) + +# Checks for typedefs, structures, and compiler characteristics. +AC_TYPE_PID_T +AC_TYPE_UID_T +AC_STRUCT_DIRENT_D_TYPE + + +dnl decide on startup files, depending on distro + +if test "x$initdiroverridden" != "xyes"; then + initname="npcd" +fi + +#initname=`echo "$initname" | ${SED} "s#${PKG_NAME}#npcd#"` +initconf=`echo "$initconf" | ${SED} "s#${pkgsysconfdir}#npcd.cfg#"` + +case $src_init in + default-service) + src_init=npcd.service + initname=npcd.service + ;; + default-init) + src_init=rc.npcd + ;; + newbsd-init) + src_init=newbsd.npcd + ;; + openrc-init) + src_init=openrc.npcd + ;; + upstart-init) + src_init=upstart.npcd + ;; + *) + AC_MSG_ERROR([missing an init file for npcd on this distro]) + ;; +esac + + +if test "x$spooldir" = "xN/A" ; then + spooldir="$localstatedir/spool/pnp4nagios" +fi +lockfile=`echo "${lockfile}"|${SED} "s#${localstatedir}#npcd.lock#"` + +logdir=`echo "${logdir}"|${SED} 's#/log$##'` +logdir="${logdir}/log" +eval logdir="$logdir" + +case $host_os in +*bsd*|darwin*) + root_grp=wheel + ;; +*) + root_grp=root + ;; +esac + +AC_ARG_WITH(root_group,AS_HELP_STRING([--with-root-group=],[sets group name for installing init]),root_grp=$withval) +AC_SUBST(root_grp) +INIT_OPTS="-o root -g $root_grp" +AC_SUBST(INIT_OPTS) + + # Check for rrdtool RRDTOOL=no AC_ARG_WITH(rrdtool,[ --with-rrdtool= sets path to rrdtool],RRDTOOL=$withval,RRDTOOL=no) @@ -147,67 +272,258 @@ AC_MSG_RESULT(yes) AC_SUBST(RRDTOOL) +dnl ======== SElinux info =============== -AC_ARG_WITH(perfdata-logfile,[ --with-perfdata-logfile= Tell me where I should store the 'process_perfdata.pl' Logfile], - PERFDATA_LOG=$withval - ) +AC_MSG_CHECKING(selinux capability) +if test -e /etc/selinux/config ; +then + source /etc/selinux/config + CAN_SELINUX="yes" + SELINUX_POLICY="$SELINUXTYPE" + AC_MSG_RESULT(yes) +else + CAN_SELINUX="no" + AC_MSG_RESULT(no) +fi + +SELINUX="no" +AC_ARG_ENABLE([selinux], + AS_HELP_STRING([--disable-selinux], [Disable selinux build])) + +AS_IF([test "x$enable_selinux" != "xno"], [ + SELINUX=$CAN_SELINUX +]) + +SELINUX_DEVELDIR="no" +if test "x${SELINUX}" = "xyes" ; then + AC_ARG_WITH(selinux_develdir, + [ --with-selinux_develdir= sets path to nagios.cfg file], NAGIOS_CFG=$withval, NAGIOS_CFG=no) + +AC_ARG_WITH(nagios_version,[ --with-nagios-version= nagios version string, like 3.1 etc], NAGIOS_VER=$withval, NAGIOS_VER=no) + +NAGIOS_EXE=no + +if test x$NAGIOS_CFG = xno -a x$NAGIOS_VER = xno ; then + AC_MSG_CHECKING(Look for running nagios server) + rnag=`ps -A -o command | ${EGREP} '/nagios4?( |$)' | head -n 1 | ${AWK} '{print $1;}'` + + if test x$rnag = x ; then + AC_MSG_RESULT([not seen]) + else + AC_MSG_RESULT($rnag) + ncfg=`ps -A -o command | ${EGREP} '/nagios4? +.*\.cfg' | head -n 1 | ${AWK} -v RS=' ' '/\.cfg/{print $1;}'` + if test x$ncfg != x ; then + NAGIOS_CFG=$ncfg + fi + fi + + AC_MSG_CHECKING(Nagios executable) + if test x$rnag = x ; then + rnag=`which nagios 2>/dev/null` + if test x$rnag = x ; then + rnag=`which nagios4 2>/dev/null` + fi + fi + if test x$rnag = x ; then + rnag=no + fi + NAGIOS_EXE=$rnag + AC_MSG_RESULT($NAGIOS_EXE) + + AC_MSG_CHECKING(Nagios config file location) + + if test x$NAGIOS_CFG = xno; then + if test -e /etc/nagios/nagios.cfg ; then + NAGIOS_CFG=/etc/nagios/nagios.cfg + elif test -e /etc/nagios4/nagios.cfg ; then + NAGIOS_CFG=/etc/nagios4/nagios.cfg + elif test -e /usr/local/etc/nagios/nagios.cfg ; then + NAGIOS_CFG=/usr/local/etc/nagios/nagios.cfg + fi + fi + if test x${NAGIOS_CFG} = xno ; then + NAGIOS_CFG=/etc/nagios/nagios.cfg + AC_MSG_RESULT([Not found, forced to $NAGIOS_CFG]) + else + AC_MSG_RESULT($NAGIOS_CFG) + fi + + AC_MSG_CHECKING(Nagios version) + # if nagios not installed yet, probably will install a new version + # so just pick a recent version unless one is given in arguments + + if test x$NAGIOS_VER = xno; then + if test x$NAGIOS_EXE != xno ; then + NAGIOS_VER=`${NAGIOS_EXE} --help | ${AWK} '/^Nagios /' | ${AWK} -v RS=' ' '/^[[0-9]]/'` + AC_MSG_RESULT($NAGIOS_VER) + else + NAGIOS_VER=4.4.6 + AC_MSG_RESULT([not found, assuming $NAGIOS_VER]) + fi + else + AC_MSG_RESULT([forced use of version $NAGIOS_VER]) + fi +fi +AC_SUBST(NAGIOS_CFG) +AC_SUBST(NAGIOS_VER) + +dnl check for service/init for nagios +AC_ARG_WITH(nagios_unit,[ --with-nagios_unit= sets name of unit for nagios service], NAGIOS_UNIT=$withval,NAGIOS_UNIT=no) +if test x$NAGIOS_UNIT = xno; then + nagunit='' + case $init_type in + systemd) + nagunit=`systemctl list-units -q 'nagios*.service'|${AWK} '{print $1;}'` + ;; + sysv) + nagunit=`chkconfig --list 2>/dev/null|${GREPE} 'nagios.?\s+0'|${AWK} '{print $1;}'` + ;; +# not sure how to do other init_types + esac + if test "x$nagunit" != x; then + NAGIOS_UNIT=$nagunit + fi +fi +NAGIOS_UNIT=${NAGIOS_UNIT%.service} +AC_SUBST(NAGIOS_UNIT) + + +nagios_dir=`dirname $NAGIOS_CFG` + +dnl check for location of Nagios password file + +AC_MSG_CHECKING(Nagios password file) +NAGIOS_PWD=no +AC_ARG_WITH(nagios_pwd,[ --with-nagios-pwd= sets path to Nagios password file], NAGIOS_PWD=$withval,NAGIOS_PWD=no) +if test x$NAGIOS_PWD = xno; then + if test -e "${nagios_dir}/passwd" ; then + NAGIOS_PWD="${nagios_dir}/passwd" + AC_MSG_RESULT($NAGIOS_PWD) + elif test -e "${nagios_dir}/htpasswd.users" ; then + NAGIOS_PWD="${nagios_dir}/htpasswd.users" + AC_MSG_RESULT($NAGIOS_PWD) + elif test -e "${nagios_dir}/htdigest.users" ; then + NAGIOS_PWD="${nagios_dir}/htdigest.users" + AC_MSG_RESULT($NAGIOS_PWD) + else + NAGIOS_PWD="${nagios_dir}/passwd" + AC_MSG_RESULT([not found, assume default $NAGIOS_PWD]) + fi +else + AC_MSG_RESULT([forced to $NAGIOS_PWD]) +fi +AC_SUBST(NAGIOS_PWD) + +dnl directory for nagios "object" files +AC_MSG_CHECKING(Nagios objects directory) +NAGIOS_OBJ=no +AC_ARG_WITH(nagios_objects,[ --with-nagios-objects= location of nagios object config files], NAGIOS_OBJ=$withval,NAGIOS_OBJ=no) +if test x$NAGIOS_OBJ = xno; then + if test -e "${nagios_dir}/objects" ; then + NAGIOS_OBJ="${nagios_dir}/objects" + AC_MSG_RESULT($NAGIOS_OBJ) + else + NAGIOS_OBJ="${nagios_dir}/objects" + AC_MSG_RESULT([not found, assume default $NAGIOS_OBJ]) + fi +else + AC_MSG_RESULT([forced to $NAGIOS_OBJ]) +fi +AC_SUBST(NAGIOS_OBJ) + + +AC_MSG_CHECKING(Nagios user/group) +nagios_user=no +nagios_grp=no +if test -e "$NAGIOS_CFG" ; then + nagios_user=`${AWK} -F= '/nagios_user/ {print $2;}' $NAGIOS_CFG` + nagios_grp=`${AWK} -F= '/nagios_group/ {print $2;}' $NAGIOS_CFG` +fi + +AC_ARG_WITH(nagios_user,[ --with-nagios-user= sets user name to run nagios],nagios_user=$withval) +AC_ARG_WITH(nagios_group,[ --with-nagios-group= sets group name to run nagios],nagios_grp=$withval) + +ugmsg="" +if test x$nagios_user = xno ; then + ugmsg="using default" + nagios_user=nagios +fi + +if test x$nagios_grp = xno ; then + ugmsg="using_default" + nagios_grp=nagios +fi + +if test x$ugmsg = x ; then + AC_MSG_RESULT([${nagios_user} / ${nagios_grp}]) +else + AC_MSG_RESULT([$ugmsg ${nagios_user} / ${nagios_grp}]) +fi + +AC_SUBST(nagios_user) +AC_SUBST(nagios_grp) +INSTALL_OPTS="-o $nagios_user -g $nagios_grp" +AC_SUBST(INSTALL_OPTS) + +# +# pnp4nagios locations and files +# +PNP_LOGDIR="${logdir}/pnp4nagios" +AC_ARG_WITH(pnp-logdir,[ --with-pnp-logdir= Tell me where I should store the RRD Database Files], PERFDATA_DIR=$withval ) AC_SUBST(PERFDATA_DIR) +PERFDATA_SPOOL_DIR="$spooldir" AC_ARG_WITH(perfdata-spool-dir,[ --with-perfdata-spool-dir= Tell me where I should store perfdata files for bulk mode with npcd], PERFDATA_SPOOL_DIR=$withval ) AC_SUBST(PERFDATA_SPOOL_DIR) -AC_ARG_WITH(debug,[ --with-debug Enable debuging for process_perfdata.pl], - DEBUG="2", - DEBUG="0" - ) -AC_SUBST(DEBUG) - -dnl Check for location of Apache conf.d directory -HTTP_CONF=no -AC_ARG_WITH(httpd_conf,[ --with-httpd-conf= sets path to Apache conf.d directory],HTTPD_CONF=$withval,HTTPD_CONF=no) -if test x$HTTPD_CONF = xno; then - if test -d /etc/httpd/conf.d; then - HTTPD_CONF="/etc/httpd/conf.d" - elif test -d /etc/apache2/conf.d; then - HTTPD_CONF="/etc/apache2/conf.d" - elif test -d /etc/apache/conf.d; then - HTTPD_CONF="/etc/apache/conf.d" - else - HTTPD_CONF="/etc/httpd/conf.d" - fi -fi -AC_SUBST(HTTPD_CONF) - -dnl Check for location of init scripts -init_dir=/etc/rc.d/init.d -if test -d /etc/rc.d/init.d; then - init_dir="/etc/rc.d/init.d" -elif test -d /usr/local/etc/rc.d; then - init_dir="/usr/local/etc/rc.d" -elif test -d /etc/rc.d; then - init_dir="/etc/rc.d" -elif test -d /etc/init.d; then - init_dir="/etc/init.d" -elif test -d /sbin/init.d; then - init_dir="/sbin/init.d" -fi - -BASE_URL=${PKG_NAME} -AC_ARG_WITH(base-url,[ --with-base-url=/${PKG_NAME} ],BASE_URL=$withval,BASE_URL=/${PKG_NAME}) -AC_SUBST(BASE_URL) - -dnl User can override init script location -AC_ARG_WITH(init_dir,[ --with-init-dir= sets directory to place init script into],init_dir=$withval) -AC_SUBST(init_dir) +dnl ---not sure if these three are used --- pnpsender_name=pnpsender AC_SUBST(pnpsender_name) @@ -217,6 +533,218 @@ AC_SUBST(npcd_name) pp_pl_name=process_perfdata.pl AC_SUBST(pp_pl_name) + +dnl =================== http server settings ================ + + +AC_MSG_CHECKING(http server) +HTTP_SERVER=no +AC_ARG_WITH(http_server, + [ --with-http_server=(http,apache,apache2,lighttpd,nginx) http server software], + HTTP_SERVER=$withval) + +if test "x${HTTP_SERVER}" = xno ; then + http_server_types="httpd + apache + apache2 + lighttpd + nginx" + http_unit=x + for HTTP_SERVER in $http_server_types + do + case "$init_type" in + systemd) + http_unit=`systemctl list-units -q "${HTTP_SERVER}.service"|${AWK} '{print $1;}'` + ;; + sysv) + http_unit=`chkconfig --list 2>/dev/null|${GREPE} "${HTTP_SERVER}\s+0"|${AWK} '{print $1;}'` + ;; + esac + if test "x${http_unit}" != x ; then + break; + fi + done +fi + +AC_ARG_WITH(http_server_base, + [ --with-http_server_base=(http server base dir)], + http_base=$withval, http_base=no) + +if test x$http_base = xno ; then + case "${HTTP_SERVER}" in + apache*) + if apachectl -t -D DUMP_RUN_CFG >/dev/null 2>/dev/null ; + then + http_base=`apachectl -t -D DUMP_RUN_CFG | ${AWK} '/^ServerRoot:/ {print $2;}'` + http_base=`echo "$srvroot"|${SED} 's/"//'` + HTTP_USER=`apachectl -t -D DUMP_RUN_CFG | ${AWK} '/^User:/ {print $2;}'` + HTTP_USER=`echo "${HTTP_USER}"|${SED} 's/name=//'` + HTTP_USER=`echo "${HTTP_USER}"|${SED} 's/"//g'` + HTTP_GROUP=`apachectl -t -D DUMP_RUN_CFG | ${AWK} '/^Group:/ {print $2;}'` + HTTP_GROUP=`echo "${HTTP_GROUP}"|${SED} 's/name=//'` + HTTP_GROUP=`echo "${HTTP_GROUP}"|${SED} 's/"//g'` + HTTP_CONFDIR=`apachectl -t -D DUMP_INCLUDES| ${GREP} "$http_base/.*\.conf" | ${AWK} '/\/conf/{print $2;}' | ${SED} -E 's/[^\/]+$//' | head -n 1` + + HTTP_CONFDIR=`apachectl -t -D DUMP_INCLUDES |${GREP} "$http_base/.*\.conf" | awk '/\/conf/{print $2;}'|${SED} -E 's/\/[[^\/]]+$//' | head -n 1` + fi + ;; + esac +fi + + + +if test "x${http_base}" = xno ; then + if test -e "/etc/${HTTP_SERVER}" ; then + http_base="/etc/${HTTP_SERVER}" + elif test -e "/usr/local/${HTTP_SERVER}" ; then + http_base="/usr/local/${HTTP_SERVER}" + elif test -e "/usr/local/etc/${HTTP_SERVER}" ; then + http_base="/usr/local/etc/${HTTP_SERVER}" + elif test -e "/usr/pkg/etc/${HTTP_SERVER}" ; then + http_base="/usr/pkg/etc/${HTTP_SERVER}" + fi +fi + +if test "x$http_base" = "xno" ; then + AC_MSG_ERROR(http server base directory not found) +fi + +if test "x$HTTP_CONFDIR" = x ; then + case "$HTTP_SERVER" in + apache* | httpd ) + if test -e "${http_base}/conf/httpd.conf" ; then + hconf="${http_base}/conf/httpd.conf" + elif test -e "${http_base}/httpd.conf" ; then + hconf="${http_base}/httpd.conf" + elif test -e "${http_base}/apache.conf" ; then + hconf="${http_base}/apache.conf" + elif test -e "${http_base}/apache2.conf" ; then + hconf="${http_base}/apache2.conf" + else + echo "HTTPD main configure file not found" + hconf="${http_base}/httpd.conf" + fi + if test -e $hconf ; then + HTTP_USER=`${AWK} '/^User/{print $2;}' $hconf` + HTTP_GROUP=`${AWK} '/^Group/{print $2;}' $hconf` + HTTP_CONFDIR=`${AWK} '/^IncludeOptional .*\*/{print $2;}' $hconf|head -n 1` + if test "x${HTTP_CONFDIR}" != x ; then + HTTP_CONFDIR=`dirname "${http_base}/${HTTP_CONFDIR}"` + fi + fi + HTTP_USER=${HTTP_USER:-daemon} + HTTP_GROUP=${HTTP_GROUP:-daemon} + HTTP_CONFDIR=${HTTP_CONFDIR:-$http_base} + ;; + lighttpd ) + HTTP_USER=lighttpd + HTTP_GROUP=lighttpd + HTTP_CONFDIR="${http_base}/conf.d" + ;; + nginx ) + HTTP_USER=nobody + HTTP_GROUP=root + HTTP_CONFDIR="${http_base}/conf.d" + ;; + esac +fi + +if test ! -e ${HTTP_CONFDIR} ; then + HTTP_CONFDIR=${http_base} +fi + + +if test "${HTTP_SERVER}" = "httpd" ; then + HTTP_SERVER=apache +elif test "${HTTP_SERVER}" = "apache2" ; then + HTTP_SERVER=apache +fi +AC_MSG_RESULT($HTTP_SERVER) +AC_SUBST(HTTP_SERVER) +HTTP_UNIT=${HTTP_UNIT%.service} +AC_SUBST(HTTP_UNIT) + +dnl user/grp are based on "tar" install defaults +dnl becuase package managers do their own thing. +dnl so if these user/group settings look unfamiliar, that +dnl might be why + +AC_ARG_WITH(http_user,[ --with-http_user= sets user name for http server],http_user=$withval,http_user=$HTTP_USER) +AC_ARG_WITH(http_group,[ --with-http_group= sets group name for http server],http_group=$withval,http_group=$HTTP_GROUP) + +HTTP_USER=${http_user} +HTTP_GROUP=${http_group} + +if test x${HTTP_USER} = xno ; then + AC_MSG_ERROR(http_user not defined) +elif test x${HTTP_GROUP} = xno ; then + AC_MSG_ERROR(http_group not defined) +fi + +AC_SUBST(HTTP_USER) +AC_SUBST(HTTP_GROUP) +HTTP_INSTALL_OPTS="-o $HTTP_USER -g $HTTP_GROUP" +AC_SUBST(HTTP_INSTALL_OPTS) + +dnl override the http server config directory, if requested + +AC_ARG_WITH(http_confdir,[ --with-http_confdir= sets path to http server conf.d directory],HTTP_CONFDIR=$withval) +AC_SUBST(HTTP_CONFDIR) + +dnl cache directory, needed for XDG_CACHE_DIR + +AC_ARG_WITH(cache_dir,[ --with-cache_dir=], +CACHE_DIR=$withval,CACHE_DIR=no) +if test "x$CACHE_DIR" = "xno" ; then + if test -e "/var/cache" ; then + CACHE_DIR=/var/cache/pnp4nagios + else + AC_MSG_ERROR([/var/cache missing, need to define cache_dir]) + fi +fi +AC_SUBST(CACHE_DIR) + +dnl set the url that points to pnp4nagios graphs +AC_ARG_WITH(pnp_url, + [--with-pnp_url=], + PNP_URL=$withval, + PNP_URL=/pnp4nagios) + +AC_SUBST(PNP_URL) + +AC_MSG_CHECKING(Default paper size for pdf generation) +dnl autoconf resets locale, so can't use LC_PAPER +dnl look for system-wide locale setting entry +dnl countries/regions that primarily use "letter" size paper: +dnl Belize Canada Chile Colombia Costa Rica El Salvador Guatemala Mexico +dnl Nicaragua Panama Philippines Puerto Rico United States Venezuela +dnl +dnl codes: BZ,CA,CL,CO,CR,SV,GT,MX,NI,PA,PH,PR,US,VE +dnl ---- the rest of the world mostly uses A4. + +PAPERSIZE=no +AC_ARG_WITH(papersize,[ --with-papersize= paper size to use A4 or letter],PAPERSIZE=$withval,PAPERSIZE=no) +if test x${PAPERSIZE} = xno ; then + localefile=no + if test -e "/etc/locale.conf" ; then + localefile=/etc/locale.conf + elif test -e "/etc/default/locale" ; then + localefile=/etc/default/locale + fi + if test x${localefile} = xno ; then + PAPERSIZE=A4 + else + country=`${GREP} "_..\." -o ${localefile} | ${SED} 's/[[\._]]//g'` + if echo 'BZ,CA,CL,CO,CR,SV,GT,MX,NI,PA,PH,PR,US,VE' | ${GREP} -q ${country} ; then + PAPERSIZE=letter + else + PAPERSIZE=A4 + fi + fi +fi +AC_SUBST(PAPERSIZE) +AC_MSG_RESULT($PAPERSIZE) + dnl - Modified version from www.erlang.org dnl - Some 12/15/05 mods made after reading http://xaxxon.slackworks.com/phuku/dl.html AC_MSG_CHECKING(for linker flags for loadable modules) @@ -252,62 +780,152 @@ AC_MSG_RESULT([$MOD_LDFLAGS]) AC_SUBST(MOD_CFLAGS) AC_SUBST(MOD_LDFLAGS) -# -# Checking for Perl Modules -# -AC_MSG_CHECKING(for Perl Module Time::HiRes) -$PERL -MTime::HiRes -e exit >/dev/null 2>&1 -if test $? -ne 0; then - AC_MSG_RESULT(no) - AC_MSG_ERROR(Perl Module Time::HiRes not available) -else - AC_MSG_RESULT(yes) -fi - -AC_MSG_CHECKING(for Perl Module Getopt::Long) -$PERL -MGetopt::Long -e exit >/dev/null 2>&1 -if test $? -ne 0; then - AC_MSG_RESULT(no) - AC_MSG_ERROR(Perl Module Getopt::Long not available) -else - AC_MSG_RESULT(yes) -fi - -RRDS=0 -AC_MSG_CHECKING(for optional Perl Module RRDs) -$PERL -I${PERL_LIB_PATH} -MRRDs -e exit >/dev/null 2>&1 -if test $? -ne 0; then - AC_MSG_RESULT(no) - AC_MSG_WARN(Perl Module RRDs not available) - RRDS=0 -else - AC_MSG_RESULT(yes) - RRDS=1 -fi -AC_SUBST(RRDS) AC_CONFIG_FILES( subst Makefile share/Makefile lib/Makefile scripts/Makefile src/Makefile sample-config/Makefile man/Makefile ) -AC_OUTPUT() +AC_CONFIG_FILES([include/stamp-h], [date '+%Y-%m-%dT%H:%M:%S%z' > include/stamp-h]) +AC_CONFIG_FILES(scripts/rrd_modify.pl scripts/rc.npcd scripts/rc.pnp_gearman_worker) +AC_CONFIG_FILES(scripts/npcd.service scripts/pnp_gearman_worker.service) +AC_CONFIG_FILES(scripts/newbsd.npcd) +AC_CONFIG_FILES(scripts/check_pnp_rrds.pl share/pnp/index.php share/pnp/install.php) +AC_CONFIG_FILES(sample-config/README_config.md) +AC_CONFIG_FILES(sample-config/SetLogLevels) +AC_CONFIG_FILES(sample-config/config_tools/NagiosCfgMod.pl) +AC_CONFIG_FILES(sample-config/config_tools/TemplateMod.pl) +AC_CONFIG_FILES(sample-config/config_tools/verify_pnp_config) +AC_CONFIG_FILES(sample-config/config_samples/apache.pnp4nagios.conf) +AC_CONFIG_FILES(sample-config/config_samples/config.php) +AC_CONFIG_FILES(sample-config/config_samples/lighttpd.pnp4nagios.conf) +AC_CONFIG_FILES(sample-config/config_samples/nagios.cfg) +AC_CONFIG_FILES(sample-config/config_samples/nginx.pnp4nagios.conf) +AC_CONFIG_FILES(sample-config/config_samples/npcd.cfg) +AC_CONFIG_FILES(sample-config/config_samples/pnp-bulk.cfg) +AC_CONFIG_FILES(sample-config/config_samples/pnp-npcd.cfg) +AC_CONFIG_FILES(sample-config/config_samples/pnp-sync.cfg) +AC_CONFIG_FILES(sample-config/config_samples/process_perfdata.cfg) +AC_CONFIG_FILES(sample-config/pnp4nagios_release) +AC_CONFIG_FILES(man/npcd.8 ci/pnp4nagios.spec) +AC_CONFIG_FILES(pnp4nagios.fc src/config.c src/npcdmod.c) +AC_CONFIG_FILES(contrib/fedora/pnp4nagios.logrotate.conf) +AC_CONFIG_FILES(contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf) +AC_CONFIG_FILES(contrib/fedora/logwatch/scripts/services/pnp4nagios) +AC_CONFIG_FILES(contrib/ssi/status-header.ssi) +AC_OUTPUT + +#### need to use 'subst' instead of configure for this +#### to deal with 'use lib "no"' case for perl scripts $PERL subst summary $PERL subst scripts/process_perfdata.pl $PERL subst scripts/rrd_convert.pl -$PERL subst scripts/rrd_modify.pl -$PERL subst scripts/rc.npcd -$PERL subst scripts/rc.pnp_gearman_worker -$PERL subst scripts/check_pnp_rrds.pl -$PERL subst share/pnp/index.php -$PERL subst share/pnp/install.php -$PERL subst sample-config/httpd.conf -$PERL subst sample-config/lighttpd.pnp4nagios.conf -$PERL subst sample-config/nginx.pnp4nagios.conf -$PERL subst sample-config/nagios.cfg-sample -$PERL subst sample-config/misccommands.cfg-sample -$PERL subst sample-config/pnp/config.php -$PERL subst sample-config/pnp/npcd.cfg-sample -$PERL subst sample-config/pnp/process_perfdata.cfg-sample -$PERL subst sample-config/pnp/pnp4nagios_release -$PERL subst contrib/ssi/status-header.ssi -$PERL subst man/npcd.8 +# +if test "x$RRDS" = "x1"; then + $PERL -MRRDs -e '1;' 2>/dev/null + if test "$?" -ne 0; then + RRDS=0 + else + rrds_version=`$PERL -MRRDs -e 'print \$RRDs::VERSION;'` + fi +fi +rrdtest=`${RRDTOOL}|head -n1|cut -d' ' -f1| ${AWK} '{print tolower($0)}'` +rrdtest=`basename $rrdtest` +if test "x$rrdtest" != "xrrdtool" ; then + rrdtool_message="WARNING: '$RRDTOOL' does not look like rrdtool" +else + rrdtool_version=`${RRDTOOL}|head -n1|cut -d' ' -f2` + rrdtool_message="${RRDTOOL} Version ${rrdtool_version}" +fi -$PERL summary +dnl Review options +echo "" +echo "" +AC_MSG_RESULT([*** Configuration summary for $PKG_NAME $PKG_VERSION $PKG_REL_DATE ***:]) + +echo "" +echo " General Options:" +echo " -------------------------" + +AC_MSG_RESULT([ Host OS: $host_os]) +AC_MSG_RESULT([ Distribution: $dist_type, $dist_ver]) +AC_MSG_RESULT([ SELINUX enabled: $SELINUX]) +AC_MSG_RESULT([ Install \${prefix}: $prefix]) +AC_MSG_RESULT([ Nagios version: $NAGIOS_VER]) +AC_MSG_RESULT([ Nagios user/group: $nagios_user,$nagios_grp]) +AC_MSG_RESULT([ Root user/group: root,$root_grp]) +AC_MSG_RESULT([ PNP HTML dir: $datarootdir]) +AC_MSG_RESULT([ Config dir: $pkgsysconfdir]) +AC_MSG_RESULT([ rrdtool binary: $rrdtool_message]) +if test "x$RRDS" = "x0" ; then +AC_MSG_RESULT([ RRDs Perl Modules: *** NOT FOUND ***]) +else +AC_MSG_RESULT([ RRDs Perl Modules: (Version $rrds_version) FOUND]) +fi +if test "x$PERL_LIB_PATH" != "x" ; then +AC_MSG_RESULT([ RRDs Perl search path: $PERL_LIB_PATH]) +fi +dnl +AC_MSG_RESULT([ RRD Files stored in: $PERFDATA_DIR]) +AC_MSG_RESULT([ process_perfdata Logfile: $PERFDATA_LOG]) +AC_MSG_RESULT([ NPCD perfdata stored in: $PERFDATA_SPOOL_DIR]) +AC_MSG_RESULT([ fontconfig cache dir: $CACHE_DIR]) + + + +echo "" +echo " Web Interface Options:" +echo " ------------------------" + +AC_MSG_RESULT([ http server: $HTTP_SERVER]) +AC_MSG_RESULT([ http configs dir: $HTTP_CONFDIR]) +AC_MSG_RESULT([ put pnp http config File: ${HTTP_CONFDIR}/${PACKAGE_NAME}.conf]) +AC_MSG_RESULT([ http user/group: $HTTP_USER,$HTTP_GROUP]) +AC_MSG_RESULT([ HTML URL: https://localhost${PNP_URL}/]) + +if test "x$DESTDIR" != "x" ; then +AC_MSG_RESULT([ WARNING \${DESTDIR} set: $DESTDIR]) +fi + +if test "x${DEBUG_LEVEL}" != "x0" ; then +echo " Debug output:" +echo " -------------" +AC_MSG_RESULT([ DEBUG_LEVEL: ${DEBUG_LEVEL}]) +AC_MSG_RESULT([ perl exec: $PERL]) +AC_MSG_RESULT([ shell exec: $SHELL]) +AC_MSG_RESULT([ libexecdir: $libexecdir]) +AC_MSG_RESULT([ libdir: $libdir]) +AC_MSG_RESULT([ sysconfdir: $sysconfdir]) +AC_MSG_RESULT([ datarootdir: $datarootdir]) +AC_MSG_RESULT([ datadir: $datadir]) +AC_MSG_RESULT([ exec prefix: $exec_prefix]) +AC_MSG_RESULT([ sbindir: $sbindir]) +AC_MSG_RESULT([ bindir: $bindir]) +fi + +if test $opsys = unix ; then + if test "x$prefix" = "x/usr/local/nagios" ; then + echo "" + echo "" + echo "prefix=$prefix" + echo "You probably wanted to do:" + echo " ./configure --prefix=/usr/local/pnp4nagios" + echo "(or some similar prefix) to get the correct prefix." + fi +fi +if test "$install_method" = default ; then + if test $opsys = bsd ; then + echo "" + echo "" + echo "prefix=$prefix" + echo "You probably wanted to do:" + echo " ./configure --enable-install-method=os " + echo "to get the correct installation paths" + fi +fi + +echo "" +echo "" +echo "Review the options above for accuracy. If they look okay," +echo "type 'make all' to compile the main program" +echo "" +echo "For more info run ./configure --with-debug_level=1" +dnl +dnl diff --git a/contrib/.gitignore b/contrib/.gitignore new file mode 100644 index 0000000..52950e0 --- /dev/null +++ b/contrib/.gitignore @@ -0,0 +1,4 @@ +fedora/logwatch/conf/logfiles/pnp4nagios.conf +fedora/logwatch/scripts/services/pnp4nagios +fedora/pnp4nagios.logrotate.conf +ssi/status-header.ssi diff --git a/contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf.in b/contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf.in new file mode 100644 index 0000000..bf0cc99 --- /dev/null +++ b/contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf.in @@ -0,0 +1,25 @@ +########################################################################## +# $Id$ +########################################################################## + +######################################################## +# This was written and is maintained by: +# Chuck Lane +# +######################################################## + +# What actual file? Defaults to LogPath if not absolute path.... +LogFile = @PERFDATA_LOG@ +Logfile = @logdir@/npcd.log + +# If the archives are searched, here is one or more line +# (optionally containing wildcards) that tell where they are... +#If you use a "-" in naming add that as well -mgt +Archive = @PERFDATA_LOG@?[0-9]+ +Archive = @PERFDATA_LOG@?[0-9]+.gz +Archive = @logdir@/npcd.log.[0-9]+ +Archive = @logdir@/npcd.log.[0-9]+.gz + + +*ApplyEuroDate = +# vi: shiftwidth=3 tabstop=3 et diff --git a/contrib/fedora/logwatch/conf/services/pnp4nagios.conf b/contrib/fedora/logwatch/conf/services/pnp4nagios.conf new file mode 100644 index 0000000..a203659 --- /dev/null +++ b/contrib/fedora/logwatch/conf/services/pnp4nagios.conf @@ -0,0 +1,21 @@ + +# You can put comments anywhere you want to. They are effective for the +# rest of the line. + +# this is in the format of = . Whitespace at the beginning +# and end of the lines is removed. Whitespace before and after the = sign +# is removed. Everything is case *insensitive*. + +# Yes = True = On = 1 +# No = False = Off = 0 + +Title = pnp4nagios-messages + +# Which logfile group... +LogFile = pnp4nagios + +# *OnlyService = vsftpd +#*RemoveHeaders = + + +# vi: shiftwidth=3 tabstop=3 et diff --git a/contrib/fedora/logwatch/scripts/services/pnp4nagios.in b/contrib/fedora/logwatch/scripts/services/pnp4nagios.in new file mode 100644 index 0000000..8169d61 --- /dev/null +++ b/contrib/fedora/logwatch/scripts/services/pnp4nagios.in @@ -0,0 +1,71 @@ +#!@PERL@ +########################################################################## +# $Id: $ +########################################################################## +# $Log: $ +# Rev for pnp4nagios 0.6.26 2022/10/23 lane@dchooz.org +########################################################################## + +use strict; +use Logwatch ':all'; + +my $Debug = $ENV{'LOGWATCH_DEBUG'} || 0; +my $DebugCounter = 0; + +my @OtherList = (); + +if ( $Debug >= 5 ) { + print STDERR "\n\nDEBUG: Inside pnp4nagios Filter \n\n"; + $DebugCounter = 1; +} + +my $line = 0; +#my $date = '\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d \[\d+\] \[\d+\]'; +while (defined(my $ThisLine = )) { + if ( $Debug >= 5 ) { + print STDERR "DEBUG($DebugCounter): $ThisLine"; + $DebugCounter++; + } + chomp($ThisLine); + $ThisLine =~ s/^File truncated// if $line == 0; + $line++; + + if ( + ($ThisLine =~ /Found Performance Data for/) or + ($ThisLine =~ /\d+ lines processed/) or + ($ThisLine =~ /\/var\/spool\/pnp4nagios\/service-perfdata\.\d+-PID-\d+ deleted/) or + ($ThisLine =~ /\/var\/spool\/pnp4nagios\/host-perfdata\.\d+-PID-\d+ deleted/) or + ($ThisLine =~ /PNP exiting \(runtime/) or + ($ThisLine =~ /process_perfdata.pl-[\.\d]+ starting in BULK Mode called by (NPCD|Nagios)/) or + ($ThisLine =~ /process_perfdata.pl-[\.\d]+ starting in SYNC Mode/) or + ($ThisLine =~ /process_perfdata.pl-[\.\d]+ starting in STDIN Mode/) or + ($ThisLine =~ /NPCD: Found \d+ files in/) or + ($ThisLine =~ /NPCD: ThreadCounter \d+\/\d+ File is/) or + ($ThisLine =~ /NPCD: Regular File: (host|service)-perfdata\.\d+/) or + ($ThisLine =~ /NPCD: A thread was started on thread_counter = \d+/) or + ($ThisLine =~ /NPCD: Processing file (host|service)-perfdata\.\d+ with ID \d+ - going to exec/) or + ($ThisLine =~ /NPCD: Have to wait: Filecounter = \d+ - thread_counter = \d+/) or + ($ThisLine =~ /NPCD: No more files to process\.\.\. waiting for \d+ seconds/) or + 0 # this line prevents blame-shifting as lines are added above + ) + { + if ( $Debug >= 6 ) { + print STDERR "DEBUG($DebugCounter): line ignored\n"; + } + } else + { + # Report any unmatched entries... + push @OtherList, "$ThisLine\n"; + } +} + +########################################################### + +if ($#OtherList >= 0) { + print "\n**Unmatched Entries**\n"; + print @OtherList; +} + +exit(0); + +# vi: shiftwidth=3 tabstop=3 syntax=perl et diff --git a/contrib/fedora/npcd.service b/contrib/fedora/npcd.service new file mode 100644 index 0000000..2ee275e --- /dev/null +++ b/contrib/fedora/npcd.service @@ -0,0 +1,17 @@ +[Unit] +Description=npcd rrd processor for pnp4nagios +Documentation=http://docs.pnp4nagios.org/ +After=network.target local-fs.target + +[Service] +Type=forking +User=nagios +Group=nagios +PIDFile=/run/nagios/npcd.pid +Environment="CONFIG_FILE=/etc/pnp4nagios/npcd.cfg" +EnvironmentFile=-/etc/sysconfig/npcd +ExecStart=/usr/sbin/npcd -d -f ${CONFIG_FILE} +ExecStop=/bin/kill -s QUIT $MAINPID + +[Install] +WantedBy=nagios.service diff --git a/contrib/fedora/npcd.sysconfig b/contrib/fedora/npcd.sysconfig new file mode 100644 index 0000000..7e1e1c6 --- /dev/null +++ b/contrib/fedora/npcd.sysconfig @@ -0,0 +1,5 @@ +# +# +# if the config file is in a different location, change it here +# +#CONFIG_FILE=/etc/pnp4nagios/npcd.cfg diff --git a/contrib/fedora/pnp4nagios-README.fedora b/contrib/fedora/pnp4nagios-README.fedora new file mode 100644 index 0000000..16ef7c3 --- /dev/null +++ b/contrib/fedora/pnp4nagios-README.fedora @@ -0,0 +1,89 @@ +(For Fedora and other redhat-ish variants) + +**** httpd integration **** +pnp4nagios.httpd.plugin.conf -> /etc/systemd/system/httpd.service.d/pnp4nagios.conf +systemctl daemon-reload +...this sets the XDG_CACHE_HOME environment variable needed by +fontconfig that is in turn needed by rrdtool graph generation +it should be an apache-writable directory, typically /var/cache/httpd + + +**** nagios integration ***** + + +* Default Mode + +/etc/nagios/nagios.cfg + + process_performance_data=1 + service_perfdata_command=process-service-perfdata + +/etc/nagios/commands.cfg + +define command { + command_name process-service-perfdata + command_line /usr/bin/perl /usr/libexec/pnp4nagios/process_perfdata.pl +} + +define command { + command_name process-host-perfdata + command_line /usr/bin/perl /usr/libexec/pnp4nagios/process_perfdata.pl -d HOSTPERFDATA +} + + +* Bulk Mode + +/etc/nagios/nagios.cfg : + +process_performance_data=1 +# +# service performance data +# +service_perfdata_file=/var/spool/nagios/service-perfdata +service_perfdata_file_template=DATATYPE::SERVICEPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tSERVICEDESC::$SERVICEDESC$\tSERVICEPERFDATA::$SERVICEPERFDATA$\tSERVICECHECKCOMMAND::$SERVICECHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$\tSERVICESTATE::$SERVICESTATE$\tSERVICESTATETYPE::$SERVICESTATETYPE$ +service_perfdata_file_mode=a +service_perfdata_file_processing_interval=15 +service_perfdata_file_processing_command=process-service-perfdata-file + +/etc/nagios/commands.cfg : + +define command{ + command_name process-service-perfdata-file + command_line $USER1$/process_perfdata.pl --bulk=/var/spool/nagios/service-perfdata + } + +define command{ + command_name process-host-perfdata-file + command_line $USER1$/process_perfdata.pl --bulk=/var/spool/nagios/host-perfdata + } + + +* Bulk Mode with NPCD + +npcd daemon needs to be started : +service npcd start +chkconfig npcd on + +The configuration is identical to the bulk mode except for the used command. + +/etc/nagios/commands.cfg : + +define command{ + command_name process-service-perfdata-file + command_line /bin/mv /var/spool/nagios/service-perfdata /var/spool/pnp4nagios/service-perfdata.$TIMET$ + } + +define command{ + command_name process-host-perfdata-file + command_line /bin/mv /var/spool/nagios/host-perfdata /var/spool/pnp4nagios/service-perfdata.$TIMET$ + } + + +* Nagios integration + +/etc/nagios/hostextinfo.cfg : + +define hostextinfo { + host_name localhost + action_url /pnp4nagios/graph?host=$HOSTNAME$ + } diff --git a/contrib/fedora/pnp4nagios-npcd.sysvinit b/contrib/fedora/pnp4nagios-npcd.sysvinit new file mode 100644 index 0000000..83f3582 --- /dev/null +++ b/contrib/fedora/pnp4nagios-npcd.sysvinit @@ -0,0 +1,103 @@ +#!/bin/sh +# +# npcd Nagios Performancedata C Daemon +# +# chkconfig: - 98 02 +# description: Nagios Performancedata C Daemon + +### BEGIN INIT INFO +# Provides: +# Required-Start: +# Required-Stop: +# Should-Start: +# Should-Stop: +# Default-Start: +# Default-Stop: +# Short-Description: +# Description: +### END INIT INFO + +# Source function library. +. /etc/rc.d/init.d/functions + +exec="/usr/sbin/npcd" +prog="npcd" +config="/etc/pnp4nagios/npcd.cfg" + +[ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog + +lockfile=/var/lock/subsys/$prog + +start() { + [ -x $exec ] || exit 5 + [ -f $config ] || exit 6 + echo -n $"Starting $prog: " + daemon $exec -f $config -d + retval=$? + echo + [ $retval -eq 0 ] && touch $lockfile + return $retval +} + +stop() { + echo -n $"Stopping $prog: " + killproc $prog + retval=$? + echo + [ $retval -eq 0 ] && rm -f $lockfile + return $retval +} + +restart() { + stop + start +} + +reload() { + restart +} + +force_reload() { + restart +} + +rh_status() { + status $prog +} + +rh_status_q() { + rh_status >/dev/null 2>&1 +} + + +case "$1" in + start) + rh_status_q && exit 0 + $1 + ;; + stop) + rh_status_q || exit 0 + $1 + ;; + restart) + $1 + ;; + reload) + rh_status_q || exit 7 + $1 + ;; + force-reload) + force_reload + ;; + status) + rh_status + ;; + condrestart|try-restart) + rh_status_q || exit 0 + restart + ;; + *) + echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}" + exit 2 +esac +exit $? diff --git a/contrib/fedora/pnp4nagios.logrotate.conf.in b/contrib/fedora/pnp4nagios.logrotate.conf.in new file mode 100644 index 0000000..2e1905c --- /dev/null +++ b/contrib/fedora/pnp4nagios.logrotate.conf.in @@ -0,0 +1,7 @@ +@logdir@/*.log { + compress + missingok + notifempty + rotate 5 + size 100k +} diff --git a/contrib/pnp4nagios.spec b/contrib/pnp4nagios.spec deleted file mode 100644 index 1216f9d..0000000 --- a/contrib/pnp4nagios.spec +++ /dev/null @@ -1,128 +0,0 @@ -# $Id:$ -# Upstream: pnp4nagios-devel@lists.sourceforge.net -Name: pnp4nagios -Version: 0.6.16 -Release: 1 -Summary: PNP is not PerfParse. A Nagios/Icinga perfdata graphing solution - -Group: Applications/System -License: GPLv2 -URL: http://www.pnp4nagios.org/ -Source: http://downloads.sourceforge.net/pnp4nagios/%{name}-%{version}.tar.gz -BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-root - -BuildRequires: rrdtool-devel -BuildRequires: perl-rrdtool -Requires: rrdtool -Requires: perl-rrdtool -Obsoletes: pnp - -%description -PNP is an addon to Nagios/Icinga which analyzes performance data provided by plugins and stores them automatically into RRD-databases. - -%prep -%setup - - -%build -sed -i -e 's/INSTALL_OPTS="-o $nagios_user -g $nagios_grp"/INSTALL_OPTS=""/' configure -sed -i -e 's/INIT_OPTS=-o root -g root/INIT_OPTS=/' scripts/Makefile.in -# hardcode that until a proper fix is upstream -sed -i -e 's/MANDIR=@mandir@/MANDIR=\/usr\/share\/man/' man/Makefile.in -%configure --with-perfdata-logfile=%{_localstatedir}/log/nagios/perfdata.log \ - --sysconfdir=%{_sysconfdir}/%{name} \ - --datarootdir=%{_datadir}/%{name} \ - --with-perfdata-dir=%{_datadir}/%{name}/perfdata \ - --with-perfdata-spool-dir=%{_localstatedir}/spool/nagios \ - --mandir=%{_mandir} \ - --libdir=%{_libdir}/%{name} # only kohana is installed there and maybe we have a system wide kohana already -make %{?_smp_mflags} all - - -%install -rm -rf %{buildroot} -%{__mkdir} -p %{buildroot}%{_sysconfdir}/httpd/conf.d/ -make fullinstall DESTDIR=%{buildroot} -mv %{buildroot}%{_sysconfdir}/%{name}/check_commands/check_nwstat.cfg-sample %{buildroot}%{_sysconfdir}/%{name}/check_commands/check_nwstat.cfg -mv %{buildroot}%{_sysconfdir}/%{name}/pages/web_traffic.cfg-sample %{buildroot}%{_sysconfdir}/%{name}/pages/web_traffic.cfg -mv %{buildroot}%{_sysconfdir}/%{name}/rra.cfg-sample %{buildroot}%{_sysconfdir}/%{name}/rra.cfg - -sed -i -e 's*log_file = /var/npcd.log*log_file = /var/log/nagios/npcd.log*' %{buildroot}%{_sysconfdir}/%{name}/npcd.cfg - -# drop local versioning, we already provide our own upgrade safety -rm -f %{buildroot}%{_sysconfdir}/%{name}/config.php.%{version} -rm -f %{buildroot}%{_sysconfdir}/%{name}/config_local.php - - -%clean -rm -rf $RPM_BUILD_ROOT - - -%files -%defattr(-,nagios,nagios,-) -%doc AUTHORS -%doc ChangeLog -%doc COPYING -%doc INSTALL -%doc README -%doc THANKS -%config(noreplace) %{_sysconfdir}/%{name}/check_commands/check_all_local_disks.cfg-sample -%config(noreplace) %{_sysconfdir}/%{name}/check_commands/check_nrpe.cfg-sample -%config(noreplace) %{_sysconfdir}/%{name}/check_commands/check_nwstat.cfg -%config(noreplace) %{_sysconfdir}/%{name}/npcd.cfg -%config(noreplace) %{_sysconfdir}/%{name}/pages/web_traffic.cfg -%config(noreplace) %{_sysconfdir}/%{name}/process_perfdata.cfg -%config(noreplace) %{_sysconfdir}/%{name}/rra.cfg -%config(noreplace) %{_sysconfdir}/httpd/conf.d/%{name}.conf -%{_sysconfdir}/%{name}/background.pdf -%{_sysconfdir}/%{name}/config.php -%{_sysconfdir}/%{name}/misccommands.cfg-sample -%{_sysconfdir}/%{name}/nagios.cfg-sample -%{_sysconfdir}/%{name}/pnp4nagios_release -%attr(755,root,root) %{_sysconfdir}/rc.d/init.d/npcd -%attr(755,root,root) %{_sysconfdir}/rc.d/init.d/pnp_gearman_worker -%{_bindir}/npcd -%{_libdir}/pnp4nagios/npcdmod.o -%{_libdir}/%{name} -%{_libexecdir}/check_pnp_rrds.pl -%{_libexecdir}/process_perfdata.pl -%{_libexecdir}/rrd_convert.pl -%{_datadir}/%{name} -%{_mandir}/man8/npcd.8.gz - - -%changelog -* Mon Feb 06 2012 Michael Friedrich - 0.6.16-1 -- Updated to version 0.6.16. -- drop (Build)Requires nagios, we can use other core(s) as well -- verify_pnp_config.pl => verify_pnp_config_v2.pl not installed anymore -- npcd.cfg and process_perfdata.cfg get now installed by make install w/o -sample suffix -- recognize new initscript for pnp_gearman_worker -- autoremove versionized config.php, we use config(noreplace) -- drop config_local.php which would override default settings -- fix npcd.8 man page prefix install - -* Tue Feb 15 2011 Christoph Maser - 0.6.11-1 -- Updated to version 0.6.11. - -* Tue Aug 31 2010 Christoph Maser - 0.6.6-1 -- Updated to version 0.6.6. - -* Thu Dec 24 2009 Christoph Maser - 0.6.2 - 2 -- add --with-perfdata-spool-dir and --with-perfdata--dir -- mark httpd-config snippet as config file - -* Thu Dec 24 2009 Christoph Maser - 0.6.2 - 1 -- Update to version 0.6.2 -- Rename to pnp4nagios - -* Mon Mar 23 2009 Christoph Maser - 0.4.14 - 2 -- Update to version 0.4.14 - -* Mon Mar 23 2009 Christoph Maser - 0.4.13 - 2 -- modify log path -- add documentation files - -* Mon Mar 23 2009 Christoph Maser - 0.4.13 - 1 -- Initial package (using brain ;) - diff --git a/contrib/ssi/status-header.ssi.in b/contrib/ssi/status-header.ssi.in index 19a0e0e..e16d15d 100644 --- a/contrib/ssi/status-header.ssi.in +++ b/contrib/ssi/status-header.ssi.in @@ -1,5 +1,5 @@ - - + + '; - } + $compiled = ''; + } - return $compiled."\n"; - } + return $compiled . "\n"; + } - /** - * Creates a image link. - * - * @param string image source, or an array of attributes - * @param string|array image alt attribute, or an array of attributes - * @param boolean include the index_page in the link - * @return string - */ - public static function image($src = NULL, $alt = NULL, $index = FALSE) - { - // Create attribute list - $attributes = is_array($src) ? $src : array('src' => $src); + /** + * Creates a image link. + * + * @param string image source, or an array of attributes + * @param string|array image alt attribute, or an array of attributes + * @param boolean include the index_page in the link + * @return string + */ + public static function image($src = null, $alt = null, $index = false) + { + // Create attribute list + $attributes = is_array($src) ? $src : array('src' => $src); - if (is_array($alt)) - { - $attributes += $alt; - } - elseif ( ! empty($alt)) - { - // Add alt to attributes - $attributes['alt'] = $alt; - } + if (is_array($alt)) { + $attributes += $alt; + } elseif (! empty($alt)) { + // Add alt to attributes + $attributes['alt'] = $alt; + } - if (strpos($attributes['src'], '://') === FALSE) - { - // Make the src attribute into an absolute URL - $attributes['src'] = url::base($index).$attributes['src']; - } + if (strpos($attributes['src'], '://') === false) { + // Make the src attribute into an absolute URL + $attributes['src'] = url::base($index) . $attributes['src']; + } - return ''; - } + return ''; + } - /** - * Compiles an array of HTML attributes into an attribute string. - * - * @param string|array array of attributes - * @return string - */ - public static function attributes($attrs) - { - if (empty($attrs)) - return ''; + /** + * Compiles an array of HTML attributes into an attribute string. + * + * @param string|array array of attributes + * @return string + */ + public static function attributes($attrs) + { + if (empty($attrs)) { + return ''; + } - if (is_string($attrs)) - return ' '.$attrs; + if (is_string($attrs)) { + return ' ' . $attrs; + } - $compiled = ''; - foreach ($attrs as $key => $val) - { - $compiled .= ' '.$key.'="'.html::specialchars($val).'"'; - } + $compiled = ''; + foreach ($attrs as $key => $val) { + $compiled .= ' ' . $key . '="' . html::specialchars($val) . '"'; + } - return $compiled; - } - -} // End html + return $compiled; + } +} +// End html diff --git a/lib/kohana/system/helpers/inflector.php b/lib/kohana/system/helpers/inflector.php index 1e4fee2..96ad973 100644 --- a/lib/kohana/system/helpers/inflector.php +++ b/lib/kohana/system/helpers/inflector.php @@ -1,4 +1,12 @@ - 1) { + return $str; + } - // Do nothing with a single count - if ($count === 0 OR $count > 1) - return $str; + // Cache key name + $key = 'singular_' . $str . $count; - // Cache key name - $key = 'singular_'.$str.$count; + if (isset(inflector::$cache[$key])) { + return inflector::$cache[$key]; + } - if (isset(inflector::$cache[$key])) - return inflector::$cache[$key]; + if (inflector::uncountable($str)) { + return inflector::$cache[$key] = $str; + } - if (inflector::uncountable($str)) - return inflector::$cache[$key] = $str; + if (empty(inflector::$irregular)) { + // Cache irregular words + inflector::$irregular = Kohana::config('inflector.irregular'); + } - if (empty(inflector::$irregular)) - { - // Cache irregular words - inflector::$irregular = Kohana::config('inflector.irregular'); - } + if ($irregular = array_search($str, inflector::$irregular)) { + $str = $irregular; + } elseif (preg_match('/[sxz]es$/', $str) or preg_match('/[^aeioudgkprt]hes$/', $str)) { + // Remove "es" + $str = substr($str, 0, -2); + } elseif (preg_match('/[^aeiou]ies$/', $str)) { + $str = substr($str, 0, -3) . 'y'; + } elseif (substr($str, -1) === 's' and substr($str, -2) !== 'ss') { + $str = substr($str, 0, -1); + } - if ($irregular = array_search($str, inflector::$irregular)) - { - $str = $irregular; - } - elseif (preg_match('/[sxz]es$/', $str) OR preg_match('/[^aeioudgkprt]hes$/', $str)) - { - // Remove "es" - $str = substr($str, 0, -2); - } - elseif (preg_match('/[^aeiou]ies$/', $str)) - { - $str = substr($str, 0, -3).'y'; - } - elseif (substr($str, -1) === 's' AND substr($str, -2) !== 'ss') - { - $str = substr($str, 0, -1); - } + return inflector::$cache[$key] = $str; + } - return inflector::$cache[$key] = $str; - } + /** + * Makes a singular word plural. + * + * @param string word to pluralize + * @return string + */ + public static function plural($str, $count = null) + { + // Remove garbage + $str = strtolower(trim($str)); - /** - * Makes a singular word plural. - * - * @param string word to pluralize - * @return string - */ - public static function plural($str, $count = NULL) - { - // Remove garbage - $str = strtolower(trim($str)); + if (is_string($count)) { + // Convert to integer when using a digit string + $count = (int) $count; + } - if (is_string($count)) - { - // Convert to integer when using a digit string - $count = (int) $count; - } + // Do nothing with singular + if ($count === 1) { + return $str; + } - // Do nothing with singular - if ($count === 1) - return $str; + // Cache key name + $key = 'plural_' . $str . $count; - // Cache key name - $key = 'plural_'.$str.$count; + if (isset(inflector::$cache[$key])) { + return inflector::$cache[$key]; + } - if (isset(inflector::$cache[$key])) - return inflector::$cache[$key]; + if (inflector::uncountable($str)) { + return inflector::$cache[$key] = $str; + } - if (inflector::uncountable($str)) - return inflector::$cache[$key] = $str; + if (empty(inflector::$irregular)) { + // Cache irregular words + inflector::$irregular = Kohana::config('inflector.irregular'); + } - if (empty(inflector::$irregular)) - { - // Cache irregular words - inflector::$irregular = Kohana::config('inflector.irregular'); - } + if (isset(inflector::$irregular[$str])) { + $str = inflector::$irregular[$str]; + } elseif (preg_match('/[sxz]$/', $str) or preg_match('/[^aeioudgkprt]h$/', $str)) { + $str .= 'es'; + } elseif (preg_match('/[^aeiou]y$/', $str)) { + // Change "y" to "ies" + $str = substr_replace($str, 'ies', -1); + } else { + $str .= 's'; + } - if (isset(inflector::$irregular[$str])) - { - $str = inflector::$irregular[$str]; - } - elseif (preg_match('/[sxz]$/', $str) OR preg_match('/[^aeioudgkprt]h$/', $str)) - { - $str .= 'es'; - } - elseif (preg_match('/[^aeiou]y$/', $str)) - { - // Change "y" to "ies" - $str = substr_replace($str, 'ies', -1); - } - else - { - $str .= 's'; - } + // Set the cache and return + return inflector::$cache[$key] = $str; + } - // Set the cache and return - return inflector::$cache[$key] = $str; - } + /** + * Makes a phrase camel case. + * + * @param string phrase to camelize + * @return string + */ + public static function camelize($str) + { + $str = 'x' . strtolower(trim($str)); + $str = ucwords(preg_replace('/[\s_]+/', ' ', $str)); - /** - * Makes a phrase camel case. - * - * @param string phrase to camelize - * @return string - */ - public static function camelize($str) - { - $str = 'x'.strtolower(trim($str)); - $str = ucwords(preg_replace('/[\s_]+/', ' ', $str)); + return substr(str_replace(' ', '', $str), 1); + } - return substr(str_replace(' ', '', $str), 1); - } + /** + * Makes a phrase underscored instead of spaced. + * + * @param string phrase to underscore + * @return string + */ + public static function underscore($str) + { + return preg_replace('/\s+/', '_', trim($str)); + } - /** - * Makes a phrase underscored instead of spaced. - * - * @param string phrase to underscore - * @return string - */ - public static function underscore($str) - { - return preg_replace('/\s+/', '_', trim($str)); - } - - /** - * Makes an underscored or dashed phrase human-reable. - * - * @param string phrase to make human-reable - * @return string - */ - public static function humanize($str) - { - return preg_replace('/[_-]+/', ' ', trim($str)); - } - -} // End inflector \ No newline at end of file + /** + * Makes an underscored or dashed phrase human-reable. + * + * @param string phrase to make human-reable + * @return string + */ + public static function humanize($str) + { + return preg_replace('/[_-]+/', ' ', trim($str)); + } +} +// End inflector diff --git a/lib/kohana/system/helpers/num.php b/lib/kohana/system/helpers/num.php index 3eb5d5a..0b2dc13 100644 --- a/lib/kohana/system/helpers/num.php +++ b/lib/kohana/system/helpers/num.php @@ -1,4 +1,12 @@ - 0); + } - return (request::accepts_at_quality($type, $explicit_check) > 0); - } + /** + * Compare the q values for given array of content types and return the one with the highest value. + * If items are found to have the same q value, the first one encountered in the given array wins. + * If all items in the given array have a q value of 0, FALSE is returned. + * + * @param array content types + * @param boolean set to TRUE to disable wildcard checking + * @return mixed string mime type with highest q value, FALSE if none of the given types are accepted + */ + public static function preferred_accept($types, $explicit_check = false) + { + // Initialize + $mime_types = array(); + $max_q = 0; + $preferred = false; - /** - * Compare the q values for given array of content types and return the one with the highest value. - * If items are found to have the same q value, the first one encountered in the given array wins. - * If all items in the given array have a q value of 0, FALSE is returned. - * - * @param array content types - * @param boolean set to TRUE to disable wildcard checking - * @return mixed string mime type with highest q value, FALSE if none of the given types are accepted - */ - public static function preferred_accept($types, $explicit_check = FALSE) - { - // Initialize - $mime_types = array(); - $max_q = 0; - $preferred = FALSE; + // Load q values for all given content types + foreach (array_unique($types) as $type) { + $mime_types[$type] = request::accepts_at_quality($type, $explicit_check); + } - // Load q values for all given content types - foreach (array_unique($types) as $type) - { - $mime_types[$type] = request::accepts_at_quality($type, $explicit_check); - } + // Look for the highest q value + foreach ($mime_types as $type => $q) { + if ($q > $max_q) { + $max_q = $q; + $preferred = $type; + } + } - // Look for the highest q value - foreach ($mime_types as $type => $q) - { - if ($q > $max_q) - { - $max_q = $q; - $preferred = $type; - } - } + return $preferred; + } - return $preferred; - } + /** + * Returns quality factor at which the client accepts content type. + * + * @param string content type (e.g. "image/jpg", "jpg") + * @param boolean set to TRUE to disable wildcard checking + * @return integer|float + */ + public static function accepts_at_quality($type = null, $explicit_check = false) + { + request::parse_accept_header(); - /** - * Returns quality factor at which the client accepts content type. - * - * @param string content type (e.g. "image/jpg", "jpg") - * @param boolean set to TRUE to disable wildcard checking - * @return integer|float - */ - public static function accepts_at_quality($type = NULL, $explicit_check = FALSE) - { - request::parse_accept_header(); + // Normalize type + $type = strtolower((string) $type); - // Normalize type - $type = strtolower((string) $type); + // General content type (e.g. "jpg") + if (strpos($type, '/') === false) { + // Don't accept anything by default + $q = 0; - // General content type (e.g. "jpg") - if (strpos($type, '/') === FALSE) - { - // Don't accept anything by default - $q = 0; + // Look up relevant mime types + foreach ((array) Kohana::config('mimes.' . $type) as $type) { + $q2 = request::accepts_at_quality($type, $explicit_check); + $q = ($q2 > $q) ? $q2 : $q; + } - // Look up relevant mime types - foreach ((array) Kohana::config('mimes.'.$type) as $type) - { - $q2 = request::accepts_at_quality($type, $explicit_check); - $q = ($q2 > $q) ? $q2 : $q; - } + return $q; + } - return $q; - } + // Content type with subtype given (e.g. "image/jpg") + $type = explode('/', $type, 2); - // Content type with subtype given (e.g. "image/jpg") - $type = explode('/', $type, 2); + // Exact match + if (isset(request::$accept_types[$type[0]][$type[1]])) { + return request::$accept_types[$type[0]][$type[1]]; + } - // Exact match - if (isset(request::$accept_types[$type[0]][$type[1]])) - return request::$accept_types[$type[0]][$type[1]]; + // Wildcard match (if not checking explicitly) + if ($explicit_check === false and isset(request::$accept_types[$type[0]]['*'])) { + return request::$accept_types[$type[0]]['*']; + } - // Wildcard match (if not checking explicitly) - if ($explicit_check === FALSE AND isset(request::$accept_types[$type[0]]['*'])) - return request::$accept_types[$type[0]]['*']; + // Catch-all wildcard match (if not checking explicitly) + if ($explicit_check === false and isset(request::$accept_types['*']['*'])) { + return request::$accept_types['*']['*']; + } - // Catch-all wildcard match (if not checking explicitly) - if ($explicit_check === FALSE AND isset(request::$accept_types['*']['*'])) - return request::$accept_types['*']['*']; + // Content type not accepted + return 0; + } - // Content type not accepted - return 0; - } + /** + * Parses client's HTTP Accept request header, and builds array structure representing it. + * + * @return void + */ + protected static function parse_accept_header() + { + // Run this function just once + if (request::$accept_types !== null) { + return; + } - /** - * Parses client's HTTP Accept request header, and builds array structure representing it. - * - * @return void - */ - protected static function parse_accept_header() - { - // Run this function just once - if (request::$accept_types !== NULL) - return; + // Initialize accept_types array + request::$accept_types = array(); - // Initialize accept_types array - request::$accept_types = array(); + // No HTTP Accept header found + if (empty($_SERVER['HTTP_ACCEPT'])) { + // Accept everything + request::$accept_types['*']['*'] = 1; + return; + } - // No HTTP Accept header found - if (empty($_SERVER['HTTP_ACCEPT'])) - { - // Accept everything - request::$accept_types['*']['*'] = 1; - return; - } + // Remove linebreaks and parse the HTTP Accept header + foreach (explode(',', str_replace(array("\r", "\n"), '', $_SERVER['HTTP_ACCEPT'])) as $accept_entry) { + // Explode each entry in content type and possible quality factor + $accept_entry = explode(';', trim($accept_entry), 2); - // Remove linebreaks and parse the HTTP Accept header - foreach (explode(',', str_replace(array("\r", "\n"), '', $_SERVER['HTTP_ACCEPT'])) as $accept_entry) - { - // Explode each entry in content type and possible quality factor - $accept_entry = explode(';', trim($accept_entry), 2); + // Explode each content type (e.g. "text/html") + $type = explode('/', $accept_entry[0], 2); - // Explode each content type (e.g. "text/html") - $type = explode('/', $accept_entry[0], 2); + // Skip invalid content types + if (! isset($type[1])) { + continue; + } - // Skip invalid content types - if ( ! isset($type[1])) - continue; + // Assume a default quality factor of 1 if no custom q value found + $q = (isset($accept_entry[1]) and preg_match('~\bq\s*+=\s*+([.0-9]+)~', $accept_entry[1], $match)) ? (float) $match[1] : 1; - // Assume a default quality factor of 1 if no custom q value found - $q = (isset($accept_entry[1]) AND preg_match('~\bq\s*+=\s*+([.0-9]+)~', $accept_entry[1], $match)) ? (float) $match[1] : 1; - - // Populate accept_types array - if ( ! isset(request::$accept_types[$type[0]][$type[1]]) OR $q > request::$accept_types[$type[0]][$type[1]]) - { - request::$accept_types[$type[0]][$type[1]] = $q; - } - } - } - -} // End request \ No newline at end of file + // Populate accept_types array + if (! isset(request::$accept_types[$type[0]][$type[1]]) or $q > request::$accept_types[$type[0]][$type[1]]) { + request::$accept_types[$type[0]][$type[1]] = $q; + } + } + } +} +// End request diff --git a/lib/kohana/system/helpers/security.php b/lib/kohana/system/helpers/security.php index cd48d2e..17ef063 100644 --- a/lib/kohana/system/helpers/security.php +++ b/lib/kohana/system/helpers/security.php @@ -1,4 +1,12 @@ -xss_clean($str); + } - /** - * Sanitize a string with the xss_clean method. - * - * @param string string to sanitize - * @return string - */ - public static function xss_clean($str) - { - return Input::instance()->xss_clean($str); - } + /** + * Remove image tags from a string. + * + * @param string string to sanitize + * @return string + */ + public static function strip_image_tags($str) + { + return preg_replace('#\s]*)["\']?[^>]*)?>#is', '$1', $str); + } - /** - * Remove image tags from a string. - * - * @param string string to sanitize - * @return string - */ - public static function strip_image_tags($str) - { - return preg_replace('#\s]*)["\']?[^>]*)?>#is', '$1', $str); - } - - /** - * Remove PHP tags from a string. - * - * @param string string to sanitize - * @return string - */ - public static function encode_php_tags($str) - { - return str_replace(array(''), array('<?', '?>'), $str); - } - -} // End security \ No newline at end of file + /** + * Remove PHP tags from a string. + * + * @param string string to sanitize + * @return string + */ + public static function encode_php_tags($str) + { + return str_replace(array(''), array('<?', '?>'), $str); + } +} +// End security diff --git a/lib/kohana/system/helpers/text.php b/lib/kohana/system/helpers/text.php index d0e573e..2b184fe 100644 --- a/lib/kohana/system/helpers/text.php +++ b/lib/kohana/system/helpers/text.php @@ -1,4 +1,12 @@ - 1) { + if (ctype_alpha($str)) { + // Add a random digit + $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57)); + } elseif (ctype_digit($str)) { + // Add a random letter + $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90)); + } + } - // Make sure alnum strings contain at least one letter and one digit - if ($type === 'alnum' AND $length > 1) - { - if (ctype_alpha($str)) - { - // Add a random digit - $str[mt_rand(0, $length - 1)] = chr(mt_rand(48, 57)); - } - elseif (ctype_digit($str)) - { - // Add a random letter - $str[mt_rand(0, $length - 1)] = chr(mt_rand(65, 90)); - } - } + return $str; + } - return $str; - } + /** + * Reduces multiple slashes in a string to single slashes. + * + * @param string string to reduce slashes of + * @return string + */ + public static function reduce_slashes($str) + { + return preg_replace('#(? $badword) { + $badwords[$key] = str_replace('\*', '\S*?', preg_quote((string) $badword)); + } - /** - * Replaces the given words with a string. - * - * @param string phrase to replace words in - * @param array words to replace - * @param string replacement string - * @param boolean replace words across word boundries (space, period, etc) - * @return string - */ - public static function censor($str, $badwords, $replacement = '#', $replace_partial_words = FALSE) - { - foreach ((array) $badwords as $key => $badword) - { - $badwords[$key] = str_replace('\*', '\S*?', preg_quote((string) $badword)); - } + $regex = '(' . implode('|', $badwords) . ')'; - $regex = '('.implode('|', $badwords).')'; + if ($replace_partial_words == true) { + // Just using \b isn't sufficient when we need to replace a badword that already contains word boundaries itself + $regex = '(?<=\b|\s|^)' . $regex . '(?=\b|\s|$)'; + } - if ($replace_partial_words == TRUE) - { - // Just using \b isn't sufficient when we need to replace a badword that already contains word boundaries itself - $regex = '(?<=\b|\s|^)'.$regex.'(?=\b|\s|$)'; - } + $regex = '!' . $regex . '!ui'; - $regex = '!'.$regex.'!ui'; + if (utf8::strlen($replacement) == 1) { + $regex .= 'e'; + return preg_replace($regex, 'str_repeat($replacement, utf8::strlen(\'$1\'))', $str); + } - if (utf8::strlen($replacement) == 1) - { - $regex .= 'e'; - return preg_replace($regex, 'str_repeat($replacement, utf8::strlen(\'$1\'))', $str); - } + return preg_replace($regex, $replacement, $str); + } - return preg_replace($regex, $replacement, $str); - } + /** + * Finds the text that is similar between a set of words. + * + * @param array words to find similar text of + * @return string + */ + public static function similar(array $words) + { + // First word is the word to match against + $word = current($words); - /** - * Finds the text that is similar between a set of words. - * - * @param array words to find similar text of - * @return string - */ - public static function similar(array $words) - { - // First word is the word to match against - $word = current($words); + for ($i = 0, $max = strlen($word); $i < $max; ++$i) { + foreach ($words as $w) { + // Once a difference is found, break out of the loops + if (! isset($w[$i]) or $w[$i] !== $word[$i]) { + break 2; + } + } + } - for ($i = 0, $max = strlen($word); $i < $max; ++$i) - { - foreach ($words as $w) - { - // Once a difference is found, break out of the loops - if ( ! isset($w[$i]) OR $w[$i] !== $word[$i]) - break 2; - } - } + // Return the similar text + return substr($word, 0, $i); + } - // Return the similar text - return substr($word, 0, $i); - } + /** + * Converts text email addresses and anchors into links. + * + * @param string text to auto link + * @return string + */ + public static function auto_link($text) + { + // Auto link emails first to prevent problems with "www.domain.com@example.com" + return text::auto_link_urls(text::auto_link_emails($text)); + } - /** - * Converts text email addresses and anchors into links. - * - * @param string text to auto link - * @return string - */ - public static function auto_link($text) - { - // Auto link emails first to prevent problems with "www.domain.com@example.com" - return text::auto_link_urls(text::auto_link_emails($text)); - } + /** + * Converts text anchors into links. + * + * @param string text to auto link + * @return string + */ + public static function auto_link_urls($text) + { + // Finds all http/https/ftp/ftps links that are not part of an existing html anchor + if (preg_match_all('~\b(?)(?:ht|f)tps?://\S+(?:/|\b)~i', $text, $matches)) { + foreach ($matches[0] as $match) { + // Replace each link with an anchor + $text = str_replace($match, html::anchor($match), $text); + } + } - /** - * Converts text anchors into links. - * - * @param string text to auto link - * @return string - */ - public static function auto_link_urls($text) - { - // Finds all http/https/ftp/ftps links that are not part of an existing html anchor - if (preg_match_all('~\b(?)(?:ht|f)tps?://\S+(?:/|\b)~i', $text, $matches)) - { - foreach ($matches[0] as $match) - { - // Replace each link with an anchor - $text = str_replace($match, html::anchor($match), $text); - } - } + // Find all naked www.links.com (without http://) + if (preg_match_all('~\b(?|58;)(?!\.)[-+_a-z0-9.]++(?|58;)(?!\.)[-+_a-z0-9.]++(? and
markup to text. Basically nl2br() on steroids. + * + * @param string subject + * @return string + */ + public static function auto_p($str) + { + // Trim whitespace + if (($str = trim($str)) === '') { + return ''; + } - /** - * Automatically applies

and
markup to text. Basically nl2br() on steroids. - * - * @param string subject - * @return string - */ - public static function auto_p($str) - { - // Trim whitespace - if (($str = trim($str)) === '') - return ''; + // Standardize newlines + $str = str_replace(array("\r\n", "\r"), "\n", $str); - // Standardize newlines - $str = str_replace(array("\r\n", "\r"), "\n", $str); + // Trim whitespace on each line + $str = preg_replace('~^[ \t]+~m', '', $str); + $str = preg_replace('~[ \t]+$~m', '', $str); - // Trim whitespace on each line - $str = preg_replace('~^[ \t]+~m', '', $str); - $str = preg_replace('~[ \t]+$~m', '', $str); + // The following regexes only need to be executed if the string contains html + if ($html_found = (strpos($str, '<') !== false)) { + // Elements that should not be surrounded by p tags + $no_p = '(?:p|div|h[1-6r]|ul|ol|li|blockquote|d[dlt]|pre|t[dhr]|t(?:able|body|foot|head)|c(?:aption|olgroup)|form|s(?:elect|tyle)|a(?:ddress|rea)|ma(?:p|th))'; - // The following regexes only need to be executed if the string contains html - if ($html_found = (strpos($str, '<') !== FALSE)) - { - // Elements that should not be surrounded by p tags - $no_p = '(?:p|div|h[1-6r]|ul|ol|li|blockquote|d[dlt]|pre|t[dhr]|t(?:able|body|foot|head)|c(?:aption|olgroup)|form|s(?:elect|tyle)|a(?:ddress|rea)|ma(?:p|th))'; + // Put at least two linebreaks before and after $no_p elements + $str = preg_replace('~^<' . $no_p . '[^>]*+>~im', "\n$0", $str); + $str = preg_replace('~$~im', "$0\n", $str); + } - // Put at least two linebreaks before and after $no_p elements - $str = preg_replace('~^<'.$no_p.'[^>]*+>~im', "\n$0", $str); - $str = preg_replace('~$~im', "$0\n", $str); - } + // Do the

magic! + $str = '

' . trim($str) . '

'; + $str = preg_replace('~\n{2,}~', "

\n\n

", $str); - // Do the

magic! - $str = '

'.trim($str).'

'; - $str = preg_replace('~\n{2,}~', "

\n\n

", $str); + // The following regexes only need to be executed if the string contains html + if ($html_found !== false) { + // Remove p tags around $no_p elements + $str = preg_replace('~

(?=]*+>)~i', '', $str); + $str = preg_replace('~(]*+>)

~i', '$1', $str); + } - // The following regexes only need to be executed if the string contains html - if ($html_found !== FALSE) - { - // Remove p tags around $no_p elements - $str = preg_replace('~

(?=]*+>)~i', '', $str); - $str = preg_replace('~(]*+>)

~i', '$1', $str); - } + // Convert single linebreaks to
+ $str = preg_replace('~(?\n", $str); - // Convert single linebreaks to
- $str = preg_replace('~(?\n", $str); + return $str; + } - return $str; - } + /** + * Returns human readable sizes. + * @see Based on original functions written by: + * @see Aidan Lister: http://aidanlister.com/repos/v/function.size_readable.php + * @see Quentin Zervaas: http://www.phpriot.com/d/code/strings/filesize-format/ + * + * @param integer size in bytes + * @param string a definitive unit + * @param string the return string format + * @param boolean whether to use SI prefixes or IEC + * @return string + */ + public static function bytes($bytes, $force_unit = null, $format = null, $si = true) + { + // Format string + $format = ($format === null) ? '%01.2f %s' : (string) $format; - /** - * Returns human readable sizes. - * @see Based on original functions written by: - * @see Aidan Lister: http://aidanlister.com/repos/v/function.size_readable.php - * @see Quentin Zervaas: http://www.phpriot.com/d/code/strings/filesize-format/ - * - * @param integer size in bytes - * @param string a definitive unit - * @param string the return string format - * @param boolean whether to use SI prefixes or IEC - * @return string - */ - public static function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE) - { - // Format string - $format = ($format === NULL) ? '%01.2f %s' : (string) $format; + // IEC prefixes (binary) + if ($si == false or strpos($force_unit, 'i') !== false) { + $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); + $mod = 1024; + } else { + // SI prefixes (decimal) + $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB'); + $mod = 1000; + } - // IEC prefixes (binary) - if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE) - { - $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); - $mod = 1024; - } - // SI prefixes (decimal) - else - { - $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB'); - $mod = 1000; - } + // Determine unit to use + if (($power = array_search((string) $force_unit, $units)) === false) { + $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0; + } - // Determine unit to use - if (($power = array_search((string) $force_unit, $units)) === FALSE) - { - $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0; - } + return sprintf($format, $bytes / pow($mod, $power), $units[$power]); + } - return sprintf($format, $bytes / pow($mod, $power), $units[$power]); - } + /** + * Prevents widow words by inserting a non-breaking space between the last two words. + * @see http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin + * + * @param string string to remove widows from + * @return string + */ + public static function widont($str) + { + $str = rtrim($str); + $space = strrpos($str, ' '); - /** - * Prevents widow words by inserting a non-breaking space between the last two words. - * @see http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin - * - * @param string string to remove widows from - * @return string - */ - public static function widont($str) - { - $str = rtrim($str); - $space = strrpos($str, ' '); + if ($space !== false) { + $str = substr($str, 0, $space) . ' ' . substr($str, $space + 1); + } - if ($space !== FALSE) - { - $str = substr($str, 0, $space).' '.substr($str, $space + 1); - } - - return $str; - } - -} // End text \ No newline at end of file + return $str; + } +} +// End text diff --git a/lib/kohana/system/helpers/upload.php b/lib/kohana/system/helpers/upload.php index 422e9e8..2b43bb7 100644 --- a/lib/kohana/system/helpers/upload.php +++ b/lib/kohana/system/helpers/upload.php @@ -1,4 +1,12 @@ - 'Refresh', + '300' => 'Multiple Choices', + '301' => 'Moved Permanently', + '302' => 'Found', + '303' => 'See Other', + '304' => 'Not Modified', + '305' => 'Use Proxy', + '307' => 'Temporary Redirect' + ); - $codes = array - ( - 'refresh' => 'Refresh', - '300' => 'Multiple Choices', - '301' => 'Moved Permanently', - '302' => 'Found', - '303' => 'See Other', - '304' => 'Not Modified', - '305' => 'Use Proxy', - '307' => 'Temporary Redirect' - ); + // Validate the method and default to 302 + $method = isset($codes[$method]) ? (string) $method : '302'; - // Validate the method and default to 302 - $method = isset($codes[$method]) ? (string) $method : '302'; + if ($method === '300') { + $uri = (array) $uri; - if ($method === '300') - { - $uri = (array) $uri; + $output = '
    '; + foreach ($uri as $link) { + $output .= '
  • ' . html::anchor($link) . '
  • '; + } + $output .= '
'; - $output = '
    '; - foreach ($uri as $link) - { - $output .= '
  • '.html::anchor($link).'
  • '; - } - $output .= '
'; + // The first URI will be used for the Location header + $uri = $uri[0]; + } else { + $output = '

' . html::anchor($uri) . '

'; + } - // The first URI will be used for the Location header - $uri = $uri[0]; - } - else - { - $output = '

'.html::anchor($uri).'

'; - } + // Run the redirect event + Event::run('system.redirect', $uri); - // Run the redirect event - Event::run('system.redirect', $uri); + if (strpos($uri, '://') === false) { + // HTTP headers expect absolute URLs + $uri = url::site($uri, request::protocol()); + } - if (strpos($uri, '://') === FALSE) - { - // HTTP headers expect absolute URLs - $uri = url::site($uri, request::protocol()); - } + if ($method === 'refresh') { + header('Refresh: 0; url=' . $uri); + } else { + header('HTTP/1.1 ' . $method . ' ' . $codes[$method]); + header('Location: ' . $uri); + } - if ($method === 'refresh') - { - header('Refresh: 0; url='.$uri); - } - else - { - header('HTTP/1.1 '.$method.' '.$codes[$method]); - header('Location: '.$uri); - } + // We are about to exit, so run the send_headers event + Event::run('system.send_headers'); - // We are about to exit, so run the send_headers event - Event::run('system.send_headers'); - - exit('

'.$method.' - '.$codes[$method].'

'.$output); - } - -} // End url \ No newline at end of file + exit('

' . $method . ' - ' . $codes[$method] . '

' . $output); + } +} +// End url diff --git a/lib/kohana/system/helpers/valid.php b/lib/kohana/system/helpers/valid.php index 74517c0..acace95 100644 --- a/lib/kohana/system/helpers/valid.php +++ b/lib/kohana/system/helpers/valid.php @@ -1,4 +1,12 @@ -= 0; $i -= 2) { + // Add up every 2nd digit, starting from the right + $checksum += $number[$i]; + } - for ($i = $length - 1; $i >= 0; $i -= 2) - { - // Add up every 2nd digit, starting from the right - $checksum += $number[$i]; - } + for ($i = $length - 2; $i >= 0; $i -= 2) { + // Add up every 2nd digit doubled, starting from the right + $double = $number[$i] * 2; - for ($i = $length - 2; $i >= 0; $i -= 2) - { - // Add up every 2nd digit doubled, starting from the right - $double = $number[$i] * 2; + // Subtract 9 from the double where value is greater than 10 + $checksum += ($double >= 10) ? $double - 9 : $double; + } - // Subtract 9 from the double where value is greater than 10 - $checksum += ($double >= 10) ? $double - 9 : $double; - } + // If the checksum is a multiple of 10, the number is valid + return ($checksum % 10 === 0); + } - // If the checksum is a multiple of 10, the number is valid - return ($checksum % 10 === 0); - } + /** + * Checks if a phone number is valid. + * + * @param string phone number to check + * @return boolean + */ + public static function phone($number, $lengths = null) + { + if (! is_array($lengths)) { + $lengths = array(7,10,11); + } - /** - * Checks if a phone number is valid. - * - * @param string phone number to check - * @return boolean - */ - public static function phone($number, $lengths = NULL) - { - if ( ! is_array($lengths)) - { - $lengths = array(7,10,11); - } + // Remove all non-digit characters from the number + $number = preg_replace('/\D+/', '', $number); - // Remove all non-digit characters from the number - $number = preg_replace('/\D+/', '', $number); + // Check if the number is within range + return in_array(strlen($number), $lengths); + } - // Check if the number is within range - return in_array(strlen($number), $lengths); - } + /** + * Tests if a string is a valid date string. + * + * @param string date to check + * @return boolean + */ + public static function date($str) + { + return (strtotime($str) !== false); + } - /** - * Tests if a string is a valid date string. - * - * @param string date to check - * @return boolean - */ - public static function date($str) - { - return (strtotime($str) !== FALSE); - } + /** + * Checks whether a string consists of alphabetical characters only. + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function alpha($str, $utf8 = false) + { + return ($utf8 === true) + ? (bool) preg_match('/^\pL++$/uD', (string) $str) + : ctype_alpha((string) $str); + } - /** - * Checks whether a string consists of alphabetical characters only. - * - * @param string input string - * @param boolean trigger UTF-8 compatibility - * @return boolean - */ - public static function alpha($str, $utf8 = FALSE) - { - return ($utf8 === TRUE) - ? (bool) preg_match('/^\pL++$/uD', (string) $str) - : ctype_alpha((string) $str); - } + /** + * Checks whether a string consists of alphabetical characters and numbers only. + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function alpha_numeric($str, $utf8 = false) + { + return ($utf8 === true) + ? (bool) preg_match('/^[\pL\pN]++$/uD', (string) $str) + : ctype_alnum((string) $str); + } - /** - * Checks whether a string consists of alphabetical characters and numbers only. - * - * @param string input string - * @param boolean trigger UTF-8 compatibility - * @return boolean - */ - public static function alpha_numeric($str, $utf8 = FALSE) - { - return ($utf8 === TRUE) - ? (bool) preg_match('/^[\pL\pN]++$/uD', (string) $str) - : ctype_alnum((string) $str); - } + /** + * Checks whether a string consists of alphabetical characters, numbers, underscores and dashes only. + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function alpha_dash($str, $utf8 = false) + { + return ($utf8 === true) + ? (bool) preg_match('/^[-\pL\pN_]++$/uD', (string) $str) + : (bool) preg_match('/^[-a-z0-9_]++$/iD', (string) $str); + } - /** - * Checks whether a string consists of alphabetical characters, numbers, underscores and dashes only. - * - * @param string input string - * @param boolean trigger UTF-8 compatibility - * @return boolean - */ - public static function alpha_dash($str, $utf8 = FALSE) - { - return ($utf8 === TRUE) - ? (bool) preg_match('/^[-\pL\pN_]++$/uD', (string) $str) - : (bool) preg_match('/^[-a-z0-9_]++$/iD', (string) $str); - } + /** + * Checks whether a string consists of digits only (no dots or dashes). + * + * @param string input string + * @param boolean trigger UTF-8 compatibility + * @return boolean + */ + public static function digit($str, $utf8 = false) + { + return ($utf8 === true) + ? (bool) preg_match('/^\pN++$/uD', (string) $str) + : ctype_digit((string) $str); + } - /** - * Checks whether a string consists of digits only (no dots or dashes). - * - * @param string input string - * @param boolean trigger UTF-8 compatibility - * @return boolean - */ - public static function digit($str, $utf8 = FALSE) - { - return ($utf8 === TRUE) - ? (bool) preg_match('/^\pN++$/uD', (string) $str) - : ctype_digit((string) $str); - } + /** + * Checks whether a string is a valid number (negative and decimal numbers allowed). + * + * @see Uses locale conversion to allow decimal point to be locale specific. + * @see http://www.php.net/manual/en/function.localeconv.php + * + * @param string input string + * @return boolean + */ + public static function numeric($str) + { + // Use localeconv to set the decimal_point value: Usually a comma or period. + $locale = localeconv(); + return (bool) preg_match('/^-?[0-9' . $locale['decimal_point'] . ']++$/D', (string) $str); + } - /** - * Checks whether a string is a valid number (negative and decimal numbers allowed). - * - * @see Uses locale conversion to allow decimal point to be locale specific. - * @see http://www.php.net/manual/en/function.localeconv.php - * - * @param string input string - * @return boolean - */ - public static function numeric($str) - { - // Use localeconv to set the decimal_point value: Usually a comma or period. - $locale = localeconv(); - return (bool) preg_match('/^-?[0-9'.$locale['decimal_point'].']++$/D', (string) $str); - } + /** + * Checks whether a string is a valid text. Letters, numbers, whitespace, + * dashes, periods, and underscores are allowed. + * + * @param string text to check + * @return boolean + */ + public static function standard_text($str) + { + // pL matches letters + // pN matches numbers + // pZ matches whitespace + // pPc matches underscores + // pPd matches dashes + // pPo matches normal puncuation + return (bool) preg_match('/^[\pL\pN\pZ\p{Pc}\p{Pd}\p{Po}]++$/uD', (string) $str); + } - /** - * Checks whether a string is a valid text. Letters, numbers, whitespace, - * dashes, periods, and underscores are allowed. - * - * @param string text to check - * @return boolean - */ - public static function standard_text($str) - { - // pL matches letters - // pN matches numbers - // pZ matches whitespace - // pPc matches underscores - // pPd matches dashes - // pPo matches normal puncuation - return (bool) preg_match('/^[\pL\pN\pZ\p{Pc}\p{Pd}\p{Po}]++$/uD', (string) $str); - } + /** + * Checks if a string is a proper decimal format. The format array can be + * used to specify a decimal length, or a number and decimal length, eg: + * array(2) would force the number to have 2 decimal places, array(4,2) + * would force the number to have 4 digits and 2 decimal places. + * + * @param string input string + * @param array decimal format: y or x,y + * @return boolean + */ + public static function decimal($str, $format = null) + { + // Create the pattern + $pattern = '/^[0-9]%s\.[0-9]%s$/'; - /** - * Checks if a string is a proper decimal format. The format array can be - * used to specify a decimal length, or a number and decimal length, eg: - * array(2) would force the number to have 2 decimal places, array(4,2) - * would force the number to have 4 digits and 2 decimal places. - * - * @param string input string - * @param array decimal format: y or x,y - * @return boolean - */ - public static function decimal($str, $format = NULL) - { - // Create the pattern - $pattern = '/^[0-9]%s\.[0-9]%s$/'; + if (! empty($format)) { + if (count($format) > 1) { + // Use the format for number and decimal length + $pattern = sprintf($pattern, '{' . $format[0] . '}', '{' . $format[1] . '}'); + } elseif (count($format) > 0) { + // Use the format as decimal length + $pattern = sprintf($pattern, '+', '{' . $format[0] . '}'); + } + } else { + // No format + $pattern = sprintf($pattern, '+', '+'); + } - if ( ! empty($format)) - { - if (count($format) > 1) - { - // Use the format for number and decimal length - $pattern = sprintf($pattern, '{'.$format[0].'}', '{'.$format[1].'}'); - } - elseif (count($format) > 0) - { - // Use the format as decimal length - $pattern = sprintf($pattern, '+', '{'.$format[0].'}'); - } - } - else - { - // No format - $pattern = sprintf($pattern, '+', '+'); - } - - return (bool) preg_match($pattern, (string) $str); - } - -} // End valid + return (bool) preg_match($pattern, (string) $str); + } +} +// End valid diff --git a/lib/kohana/system/i18n/de_DE/cache.php b/lib/kohana/system/i18n/de_DE/cache.php index 53f32aa..d62f236 100644 --- a/lib/kohana/system/i18n/de_DE/cache.php +++ b/lib/kohana/system/i18n/de_DE/cache.php @@ -1,10 +1,14 @@ - 'Die Gruppe %s ist in Ihrer Konfiguration nicht definiert.', - 'extension_not_loaded' => 'Die PHP-Erweiterung %s muss geladen sein, um diesen Treiber benutzen zu können.', - 'unwritable' => 'Der eingestellte Speicherort %s ist nicht beschreibbar.', - 'resources' => 'Das Cachen von Ressourcen ist nicht möglich, da diese nicht serialisiert werden können.', - 'driver_error' => '%s' -); \ No newline at end of file + 'undefined_group' => 'Die Gruppe %s ist in Ihrer Konfiguration nicht definiert.', + 'extension_not_loaded' => 'Die PHP-Erweiterung %s muss geladen sein, um diesen Treiber benutzen zu können.', + 'unwritable' => 'Der eingestellte Speicherort %s ist nicht beschreibbar.', + 'resources' => 'Das Cachen von Ressourcen ist nicht möglich, da diese nicht serialisiert werden können.', + 'driver_error' => '%s' +); diff --git a/lib/kohana/system/i18n/de_DE/calendar.php b/lib/kohana/system/i18n/de_DE/calendar.php index d95f54b..1fc2610 100644 --- a/lib/kohana/system/i18n/de_DE/calendar.php +++ b/lib/kohana/system/i18n/de_DE/calendar.php @@ -1,59 +1,63 @@ - 'So', - 'mo' => 'Mo', - 'tu' => 'Di', - 'we' => 'Mi', - 'th' => 'Do', - 'fr' => 'Fr', - 'sa' => 'Sa', + // Two letter days + 'su' => 'So', + 'mo' => 'Mo', + 'tu' => 'Di', + 'we' => 'Mi', + 'th' => 'Do', + 'fr' => 'Fr', + 'sa' => 'Sa', - // Short day names - 'sun' => 'Son', - 'mon' => 'Mon', - 'tue' => 'Die', - 'wed' => 'Mit', - 'thu' => 'Don', - 'fri' => 'Fre', - 'sat' => 'Sam', + // Short day names + 'sun' => 'Son', + 'mon' => 'Mon', + 'tue' => 'Die', + 'wed' => 'Mit', + 'thu' => 'Don', + 'fri' => 'Fre', + 'sat' => 'Sam', - // Long day names - 'sunday' => 'Sonntag', - 'monday' => 'Montag', - 'tuesday' => 'Dienstag', - 'wednesday' => 'Mittwoch', - 'thursday' => 'Donnerstag', - 'friday' => 'Freitag', - 'saturday' => 'Samstag', + // Long day names + 'sunday' => 'Sonntag', + 'monday' => 'Montag', + 'tuesday' => 'Dienstag', + 'wednesday' => 'Mittwoch', + 'thursday' => 'Donnerstag', + 'friday' => 'Freitag', + 'saturday' => 'Samstag', - // Short month names - 'jan' => 'Jan', - 'feb' => 'Feb', - 'mar' => 'Mär', - 'apr' => 'Apr', - 'may' => 'Mai', - 'jun' => 'Jun', - 'jul' => 'Jul', - 'aug' => 'Aug', - 'sep' => 'Sep', - 'oct' => 'Okt', - 'nov' => 'Nov', - 'dec' => 'Dez', + // Short month names + 'jan' => 'Jan', + 'feb' => 'Feb', + 'mar' => 'Mär', + 'apr' => 'Apr', + 'may' => 'Mai', + 'jun' => 'Jun', + 'jul' => 'Jul', + 'aug' => 'Aug', + 'sep' => 'Sep', + 'oct' => 'Okt', + 'nov' => 'Nov', + 'dec' => 'Dez', - // Long month names - 'january' => 'Januar', - 'february' => 'Februar', - 'march' => 'März', - 'april' => 'April', - 'mayl' => 'Mai', - 'june' => 'Juni', - 'july' => 'Juli', - 'august' => 'August', - 'september' => 'September', - 'october' => 'Oktober', - 'november' => 'November', - 'december' => 'Dezember' -); \ No newline at end of file + // Long month names + 'january' => 'Januar', + 'february' => 'Februar', + 'march' => 'März', + 'april' => 'April', + 'mayl' => 'Mai', + 'june' => 'Juni', + 'july' => 'Juli', + 'august' => 'August', + 'september' => 'September', + 'october' => 'Oktober', + 'november' => 'November', + 'december' => 'Dezember' +); diff --git a/lib/kohana/system/i18n/de_DE/captcha.php b/lib/kohana/system/i18n/de_DE/captcha.php index 0a5ce5e..49ab256 100644 --- a/lib/kohana/system/i18n/de_DE/captcha.php +++ b/lib/kohana/system/i18n/de_DE/captcha.php @@ -1,33 +1,40 @@ - 'Die eingestellte Datei %s konnte nicht gefunden werden. Kontrollieren Sie bitte, bevor Sie Dateien benutzen, ob diese existieren. Sie können dafür die Funktion file_exists() benutzen.', - 'requires_GD2' => 'Die Captcha-Bibliothek erfordert GD2 mit FreeType-Unterstützung. Sehen Sie sich die Seite http://php.net/gd_info an, um weitere Informationen zu erhalten.', + 'file_not_found' => 'Die eingestellte Datei %s konnte nicht gefunden werden.' . + ' Kontrollieren Sie bitte, bevor Sie Dateien benutzen, ob diese existieren.' . + ' Sie können dafür die Funktion file_exists() benutzen.', + 'requires_GD2' => 'Die Captcha-Bibliothek erfordert GD2 mit FreeType-Unterstützung.' . + ' Sehen Sie sich die Seite http://php.net/gd_info an, um weitere Informationen zu erhalten.', - // Words of varying length for the Captcha_Word_Driver to pick from - // Note: use only alphanumeric characters - 'words' => array - ( - 'cd', 'tv', 'it', 'to', 'be', 'or', - 'sun', 'car', 'dog', 'bed', 'kid', 'egg', - 'bike', 'tree', 'bath', 'roof', 'road', 'hair', - 'hello', 'world', 'earth', 'beard', 'chess', 'water', - 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', - 'america', 'release', 'playing', 'working', 'foreign', 'general', - 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', - 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', - ), + // Words of varying length for the Captcha_Word_Driver to pick from + // Note: use only alphanumeric characters + 'words' => array + ( + 'cd', 'tv', 'it', 'to', 'be', 'or', + 'sun', 'car', 'dog', 'bed', 'kid', 'egg', + 'bike', 'tree', 'bath', 'roof', 'road', 'hair', + 'hello', 'world', 'earth', 'beard', 'chess', 'water', + 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', + 'america', 'release', 'playing', 'working', 'foreign', 'general', + 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', + 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', + ), - // Riddles for the Captcha_Riddle_Driver to pick from - // Note: use only alphanumeric characters - 'riddles' => array - ( - array('Hasst du Spam? (ja oder nein)', 'ja'), - array('Bist du ein Roboter? (ja oder nein)', 'nein'), - array('Feuer ist ... (heiß or kalt)', 'heiß'), - array('Die Jahreszeit, die nach Herbst kommt ist ...', 'Winter'), - array('Welcher Wochentag ist heute?', strftime('%A')), - array('In welchem Monat befinden wir uns gerade?', strftime('%B')), - ), + // Riddles for the Captcha_Riddle_Driver to pick from + // Note: use only alphanumeric characters + 'riddles' => array + ( + array('Hasst du Spam? (ja oder nein)', 'ja'), + array('Bist du ein Roboter? (ja oder nein)', 'nein'), + array('Feuer ist ... (heiß or kalt)', 'heiß'), + array('Die Jahreszeit, die nach Herbst kommt ist ...', 'Winter'), + array('Welcher Wochentag ist heute?', strftime('%A')), + array('In welchem Monat befinden wir uns gerade?', strftime('%B')), + ), ); diff --git a/lib/kohana/system/i18n/de_DE/core.php b/lib/kohana/system/i18n/de_DE/core.php index a47ded2..bc88086 100644 --- a/lib/kohana/system/i18n/de_DE/core.php +++ b/lib/kohana/system/i18n/de_DE/core.php @@ -1,34 +1,38 @@ - 'Pro Seitenaufruf kann es nur eine Instanz von Kohana geben', - 'uncaught_exception' => 'Unerwarteter Fehler vom Typ %s: %s in %s in Zeile %s', - 'invalid_method' => 'Ungültige Methode %s aufgerufen in %s', - 'invalid_property' => '%s ist keine Eigenschaft der Klasse %s.', - 'log_dir_unwritable' => 'Das Log-Verzeichnis ist nicht beschreibbar: %s', - 'resource_not_found' => '%s %s konnte nicht gefunden werden', - 'invalid_filetype' => 'Die Dateiendung .%s ist in Ihrer View-Konfiguration nicht vorhanden', - 'view_set_filename' => 'Sie müssen den Dateinamen der Ansicht festlegen, bevor render aufgerufen wird', - 'no_default_route' => 'Erstellen Sie bitte eine Standardroute config/routes.php', - 'no_controller' => 'Kohana gelang es nicht einen Controller zu finden, um diesen Aufruf zu verarbeiten: %s', - 'page_not_found' => 'Die Seite %s konnte nicht gefunden werden.', - 'stats_footer' => 'Seite geladen in {execution_time} Sekunden bei {memory_usage} Speichernutzung. Generiert von Kohana v{kohana_version}.', - 'error_file_line' => '%s [%s]:', - 'stack_trace' => 'Stack Trace', - 'generic_error' => 'Die Abfrage konnte nicht abgeschlossen werden', - 'errors_disabled' => 'Sie können zur Startseite zurück kehren oder es erneut versuchen.', + 'there_can_be_only_one' => 'Pro Seitenaufruf kann es nur eine Instanz von Kohana geben', + 'uncaught_exception' => 'Unerwarteter Fehler vom Typ %s: %s in %s in Zeile %s', + 'invalid_method' => 'Ungültige Methode %s aufgerufen in %s', + 'invalid_property' => '%s ist keine Eigenschaft der Klasse %s.', + 'log_dir_unwritable' => 'Das Log-Verzeichnis ist nicht beschreibbar: %s', + 'resource_not_found' => '%s %s konnte nicht gefunden werden', + 'invalid_filetype' => 'Die Dateiendung .%s ist in Ihrer View-Konfiguration nicht vorhanden', + 'view_set_filename' => 'Sie müssen den Dateinamen der Ansicht festlegen, bevor render aufgerufen wird', + 'no_default_route' => 'Erstellen Sie bitte eine Standardroute config/routes.php', + 'no_controller' => 'Kohana gelang es nicht einen Controller zu finden, um diesen Aufruf zu verarbeiten: %s', + 'page_not_found' => 'Die Seite %s konnte nicht gefunden werden.', + 'stats_footer' => 'Seite geladen in {execution_time} Sekunden bei {memory_usage} Speichernutzung. Generiert von Kohana v{kohana_version}.', + 'error_file_line' => '%s [%s]:', + 'stack_trace' => 'Stack Trace', + 'generic_error' => 'Die Abfrage konnte nicht abgeschlossen werden', + 'errors_disabled' => 'Sie können zur Startseite zurück kehren oder es erneut versuchen.', - // Drivers - 'driver_implements' => 'Der Treiber %s für die Bibliothek %s muss das Interface %s implementieren', - 'driver_not_found' => 'Der Treiber %s für die Bibliothek %s konnte nicht gefunden werden', + // Drivers + 'driver_implements' => 'Der Treiber %s für die Bibliothek %s muss das Interface %s implementieren', + 'driver_not_found' => 'Der Treiber %s für die Bibliothek %s konnte nicht gefunden werden', - // Resource names - 'config' => 'Die Konfigurationsdatei', - 'controller' => 'Der Controller', - 'helper' => 'Der Helfer', - 'library' => 'Die Bibliothek', - 'driver' => 'Der Treiber', - 'model' => 'Das Modell', - 'view' => 'Die Ansicht', -); \ No newline at end of file + // Resource names + 'config' => 'Die Konfigurationsdatei', + 'controller' => 'Der Controller', + 'helper' => 'Der Helfer', + 'library' => 'Die Bibliothek', + 'driver' => 'Der Treiber', + 'model' => 'Das Modell', + 'view' => 'Die Ansicht', +); diff --git a/lib/kohana/system/i18n/de_DE/database.php b/lib/kohana/system/i18n/de_DE/database.php index 58edf3b..c1c1b97 100644 --- a/lib/kohana/system/i18n/de_DE/database.php +++ b/lib/kohana/system/i18n/de_DE/database.php @@ -1,15 +1,19 @@ - 'Die Gruppe %s ist in Ihrer Konfiguration nicht definiert worden.', - 'error' => 'Es gab einen SQL-Fehler: %s', - 'connection' => 'Es gab einen Fehler bei der Verbindung mit der Datenbank: %s', - 'invalid_dsn' => 'Die von Ihnen angegebene DSN ist ungültig: %s', - 'must_use_set' => 'Sie müssen SET in Ihrem Query benutzen.', - 'must_use_where' => 'Sie müssen WHERE in Ihrem Query benutzen.', - 'must_use_table' => 'Sie müssen eine Tabelle für Ihren Query angeben.', - 'table_not_found' => 'Die Tabelle %s konnte in der Datenbank nicht gefunden werden.', - 'not_implemented' => 'Die Methode %s wird von diesem Datenbanktreiber nicht unterstützt.', - 'result_read_only' => 'Ergebnisse der Anfrage können nur gelesen werden.', -); \ No newline at end of file + 'undefined_group' => 'Die Gruppe %s ist in Ihrer Konfiguration nicht definiert worden.', + 'error' => 'Es gab einen SQL-Fehler: %s', + 'connection' => 'Es gab einen Fehler bei der Verbindung mit der Datenbank: %s', + 'invalid_dsn' => 'Die von Ihnen angegebene DSN ist ungültig: %s', + 'must_use_set' => 'Sie müssen SET in Ihrem Query benutzen.', + 'must_use_where' => 'Sie müssen WHERE in Ihrem Query benutzen.', + 'must_use_table' => 'Sie müssen eine Tabelle für Ihren Query angeben.', + 'table_not_found' => 'Die Tabelle %s konnte in der Datenbank nicht gefunden werden.', + 'not_implemented' => 'Die Methode %s wird von diesem Datenbanktreiber nicht unterstützt.', + 'result_read_only' => 'Ergebnisse der Anfrage können nur gelesen werden.', +); diff --git a/lib/kohana/system/i18n/de_DE/encrypt.php b/lib/kohana/system/i18n/de_DE/encrypt.php index 1933969..b2ccf4c 100644 --- a/lib/kohana/system/i18n/de_DE/encrypt.php +++ b/lib/kohana/system/i18n/de_DE/encrypt.php @@ -1,8 +1,12 @@ - 'Die Gruppe %s ist nicht in Ihrer Konfiguration enthalten.', - 'requires_mcrypt' => 'Um die Bibliothek Encrypt zu benutzen, muss mcrypt in Ihrer PHP-Installation aktiviert werden', - 'no_encryption_key' => 'Um die Bibliothek Encrypt zu benutzen, müssen Sie einen Schlüssel in Ihrer Konfiguration eintragen' + 'undefined_group' => 'Die Gruppe %s ist nicht in Ihrer Konfiguration enthalten.', + 'requires_mcrypt' => 'Um die Bibliothek Encrypt zu benutzen, muss mcrypt in Ihrer PHP-Installation aktiviert werden', + 'no_encryption_key' => 'Um die Bibliothek Encrypt zu benutzen, müssen Sie einen Schlüssel in Ihrer Konfiguration eintragen' ); diff --git a/lib/kohana/system/i18n/de_DE/errors.php b/lib/kohana/system/i18n/de_DE/errors.php index 92e281c..c28f2eb 100644 --- a/lib/kohana/system/i18n/de_DE/errors.php +++ b/lib/kohana/system/i18n/de_DE/errors.php @@ -1,16 +1,24 @@ - array( 1, 'Framework-Fehler', 'Lesen Sie bitte in der Kohana-Dokumentation, um mehr über den folgenden Fehler zu erfahren.'), - E_PAGE_NOT_FOUND => array( 1, 'Seite Nicht Gefunden', 'Die aufgerufene Seite wurde nicht gefunden. Sie wurde entweder verschoben, gelöscht oder archiviert.'), - E_DATABASE_ERROR => array( 1, 'Datenbank-Fehler', 'Ein Datenbankfehler ist während des Aufrufs aufgetreten. Überprüfen Sie bitte den unten stehenden Fehler für mehr Informationen.'), - E_RECOVERABLE_ERROR => array( 1, 'Behebbarer Fehler', 'Es ist ein Fehler aufgetreten, der das Laden der Seite verhindert hat. Wenn der Fehler weiterhin besteht, kontaktieren Sie bitte den Administrator der Seite.'), - E_ERROR => array( 1, 'Fataler Fehler', ''), - E_USER_ERROR => array( 1, 'Fataler Fehler', ''), - E_PARSE => array( 1, 'Syntax-Fehler', ''), - E_WARNING => array( 1, 'Warnung', ''), - E_USER_WARNING => array( 1, 'Warnung', ''), - E_STRICT => array( 2, 'Strict Mode Error', ''), - E_NOTICE => array( 2, 'Laufzeitfehler', ''), -); \ No newline at end of file + E_KOHANA => array( 1, 'Framework-Fehler', 'Lesen Sie bitte in der Kohana-Dokumentation, um mehr über den folgenden Fehler zu erfahren.'), + E_PAGE_NOT_FOUND => array( 1, 'Seite Nicht Gefunden', 'Die aufgerufene Seite wurde nicht gefunden. Sie wurde entweder verschoben, gelöscht oder archiviert.'), + E_DATABASE_ERROR => array( 1, 'Datenbank-Fehler', + 'Ein Datenbankfehler ist während des Aufrufs aufgetreten.' . + ' Überprüfen Sie bitte den unten stehenden Fehler für mehr Informationen.'), + E_RECOVERABLE_ERROR => array( 1, 'Behebbarer Fehler', + 'Es ist ein Fehler aufgetreten, der das Laden der Seite verhindert hat.' . +' Wenn der Fehler weiterhin besteht, kontaktieren Sie bitte den Administrator der Seite.'), + E_ERROR => array( 1, 'Fataler Fehler', ''), + E_USER_ERROR => array( 1, 'Fataler Fehler', ''), + E_PARSE => array( 1, 'Syntax-Fehler', ''), + E_WARNING => array( 1, 'Warnung', ''), + E_USER_WARNING => array( 1, 'Warnung', ''), + E_STRICT => array( 2, 'Strict Mode Error', ''), + E_NOTICE => array( 2, 'Laufzeitfehler', ''), +); diff --git a/lib/kohana/system/i18n/de_DE/event.php b/lib/kohana/system/i18n/de_DE/event.php index e299e05..f12d3fa 100644 --- a/lib/kohana/system/i18n/de_DE/event.php +++ b/lib/kohana/system/i18n/de_DE/event.php @@ -1,7 +1,11 @@ - 'Der Versuch, das ungültige Subjekt %s an %s anzuhängen, ist fehlgeschlagen. Subjekte müssen die Klasse Event_Subject erweitern.', - 'invalid_observer' => 'Der Versuch, den ungültigen Beobachter %s an %s anzuhängen, ist fehlgeschlagen. Beobachter müssen die Klasse Event_Observer erweitern.', + 'invalid_subject' => 'Der Versuch, das ungültige Subjekt %s an %s anzuhängen, ist fehlgeschlagen. Subjekte müssen die Klasse Event_Subject erweitern.', + 'invalid_observer' => 'Der Versuch, den ungültigen Beobachter %s an %s anzuhängen, ist fehlgeschlagen. Beobachter müssen die Klasse Event_Observer erweitern.', ); diff --git a/lib/kohana/system/i18n/de_DE/image.php b/lib/kohana/system/i18n/de_DE/image.php index b12b13c..ea85464 100644 --- a/lib/kohana/system/i18n/de_DE/image.php +++ b/lib/kohana/system/i18n/de_DE/image.php @@ -1,33 +1,39 @@ - 'Die Bildbibliothek versucht die PHP-Funktion getimagesize() zu benutzen, die aber nicht Bestandteil ihrer PHP-Installation ist.', - 'unsupported_method' => 'Der Bildtreiber, den Sie benutzen, unterstützt nicht die %s-Bildtransformation.', - 'file_not_found' => 'Das angegebene Bild %s konnte nicht gefunden werden. Stellen Sie bitte sicher, dass das Bild existiert. Benutzen Sie hierzu die Funktion file_exists().', - 'type_not_allowed' => 'Das angegebene Bild %s ist kein erlaubter Bildtyp.', - 'invalid_width' => 'Die von Ihnen festgelegte Bildbreite, %s, ist ungültig.', - 'invalid_height' => 'Die von Ihnen festgelegte Bildhöhe, %s, ist ungültig.', - 'invalid_dimensions' => 'Das festgelegte Format für %s ist ungültig.', - 'invalid_master' => 'Die festgelegte Master-Dimension ist ungültig.', - 'invalid_flip' => 'Die festgelegte Richtung der Spiegelung ist ungültig.', - 'directory_unwritable' => 'Das Verzeichnis %s ist nicht beschreibbar.', + 'getimagesize_missing' => 'Die Bildbibliothek versucht die PHP-Funktion getimagesize() zu benutzen, die aber nicht Bestandteil ihrer PHP-Installation ist.', + 'unsupported_method' => 'Der Bildtreiber, den Sie benutzen, unterstützt nicht die %s-Bildtransformation.', + 'file_not_found' => 'Das angegebene Bild %s konnte nicht gefunden werden.' . + ' Stellen Sie bitte sicher, dass das Bild existiert.' . + ' Benutzen Sie hierzu die Funktion file_exists().', + 'type_not_allowed' => 'Das angegebene Bild %s ist kein erlaubter Bildtyp.', + 'invalid_width' => 'Die von Ihnen festgelegte Bildbreite, %s, ist ungültig.', + 'invalid_height' => 'Die von Ihnen festgelegte Bildhöhe, %s, ist ungültig.', + 'invalid_dimensions' => 'Das festgelegte Format für %s ist ungültig.', + 'invalid_master' => 'Die festgelegte Master-Dimension ist ungültig.', + 'invalid_flip' => 'Die festgelegte Richtung der Spiegelung ist ungültig.', + 'directory_unwritable' => 'Das Verzeichnis %s ist nicht beschreibbar.', - // ImageMagick specific messages - 'imagemagick' => array - ( - 'not_found' => 'Das festgelegte ImageMagic-Verzeichnis enthält nicht das benötigte Programm %s.', - ), + // ImageMagick specific messages + 'imagemagick' => array + ( + 'not_found' => 'Das festgelegte ImageMagic-Verzeichnis enthält nicht das benötigte Programm %s.', + ), - // GraphicsMagick specific messages - 'graphicsmagick' => array - ( - 'not_found' => 'Das festgelegte GraphicsMagick-Verzeichnis enthält nicht das benötigte Programm %s.', - ), + // GraphicsMagick specific messages + 'graphicsmagick' => array + ( + 'not_found' => 'Das festgelegte GraphicsMagick-Verzeichnis enthält nicht das benötigte Programm %s.', + ), - // GD specific messages - 'gd' => array - ( - 'requires_v2' => 'Die Bildbibliothek erfordert GD2. Sehen Sie sich die Seite http://php.net/gd_info an, um weitere Informationen zu erhalten.', - ), + // GD specific messages + 'gd' => array + ( + 'requires_v2' => 'Die Bildbibliothek erfordert GD2. Sehen Sie sich die Seite http://php.net/gd_info an, um weitere Informationen zu erhalten.', + ), ); diff --git a/lib/kohana/system/i18n/de_DE/orm.php b/lib/kohana/system/i18n/de_DE/orm.php index b03df5b..37f3b49 100644 --- a/lib/kohana/system/i18n/de_DE/orm.php +++ b/lib/kohana/system/i18n/de_DE/orm.php @@ -1,3 +1,7 @@ - 'Die Gruppe %s ist nicht in der Pagination-Konfiguration definiert worden.', - 'page' => 'Seite', - 'pages' => 'Seiten', - 'item' => 'Element', - 'items' => 'Elemente', - 'of' => 'von', - 'first' => 'Erste', - 'last' => 'Letzte', - 'previous' => 'Vorherige', - 'next' => 'Nächste', + 'undefined_group' => 'Die Gruppe %s ist nicht in der Pagination-Konfiguration definiert worden.', + 'page' => 'Seite', + 'pages' => 'Seiten', + 'item' => 'Element', + 'items' => 'Elemente', + 'of' => 'von', + 'first' => 'Erste', + 'last' => 'Letzte', + 'previous' => 'Vorherige', + 'next' => 'Nächste', ); diff --git a/lib/kohana/system/i18n/de_DE/profiler.php b/lib/kohana/system/i18n/de_DE/profiler.php index 1b16433..ea567ba 100644 --- a/lib/kohana/system/i18n/de_DE/profiler.php +++ b/lib/kohana/system/i18n/de_DE/profiler.php @@ -1,15 +1,19 @@ - 'Benchmark-Tests', - 'post_data' => 'POST-Daten:', - 'no_post' => 'Keine POST-Daten', - 'session_data' => 'Session-Daten', - 'no_session' => 'Keine Session-Daten', - 'queries' => 'Datenbank-Anfragen', - 'no_queries' => 'Keine Anfragen', - 'no_database' => 'Datenbank nicht geladen', - 'cookie_data' => 'Cookie-Daten', - 'no_cookie' => 'Keine Cookie-Daten', + 'benchmarks' => 'Benchmark-Tests', + 'post_data' => 'POST-Daten:', + 'no_post' => 'Keine POST-Daten', + 'session_data' => 'Session-Daten', + 'no_session' => 'Keine Session-Daten', + 'queries' => 'Datenbank-Anfragen', + 'no_queries' => 'Keine Anfragen', + 'no_database' => 'Datenbank nicht geladen', + 'cookie_data' => 'Cookie-Daten', + 'no_cookie' => 'Keine Cookie-Daten', ); diff --git a/lib/kohana/system/i18n/de_DE/session.php b/lib/kohana/system/i18n/de_DE/session.php index abbd912..50e3f41 100644 --- a/lib/kohana/system/i18n/de_DE/session.php +++ b/lib/kohana/system/i18n/de_DE/session.php @@ -1,6 +1,10 @@ - 'Der Sessionname %s ist ungültig. Dieser darf nur aus alphanumerischen Zeichen und mindestens einem Buchstaben bestehen.', -); \ No newline at end of file + 'invalid_session_name' => 'Der Sessionname %s ist ungültig. Dieser darf nur aus alphanumerischen Zeichen und mindestens einem Buchstaben bestehen.', +); diff --git a/lib/kohana/system/i18n/de_DE/swift.php b/lib/kohana/system/i18n/de_DE/swift.php index 88b112b..3aaf038 100644 --- a/lib/kohana/system/i18n/de_DE/swift.php +++ b/lib/kohana/system/i18n/de_DE/swift.php @@ -1,6 +1,10 @@ - 'Fehler beim Senden einer E-Mail aufgetreten.' -); \ No newline at end of file + 'general_error' => 'Fehler beim Senden einer E-Mail aufgetreten.' +); diff --git a/lib/kohana/system/i18n/de_DE/upload.php b/lib/kohana/system/i18n/de_DE/upload.php index 181d389..edcf842 100644 --- a/lib/kohana/system/i18n/de_DE/upload.php +++ b/lib/kohana/system/i18n/de_DE/upload.php @@ -1,6 +1,10 @@ - 'Das Verzeichnis für hochgeladene Dateien, %s, ist nicht beschreibbar.', -); \ No newline at end of file + 'not_writable' => 'Das Verzeichnis für hochgeladene Dateien, %s, ist nicht beschreibbar.', +); diff --git a/lib/kohana/system/i18n/de_DE/validation.php b/lib/kohana/system/i18n/de_DE/validation.php index d1797da..1ac61b7 100644 --- a/lib/kohana/system/i18n/de_DE/validation.php +++ b/lib/kohana/system/i18n/de_DE/validation.php @@ -1,41 +1,45 @@ - 'Ungültige Validierungsregel benutzt: %s', - 'i18n_array' => 'Der i18n-Schlüssel %s muss ein Array sein, um diesen in der in_array-Regel benutzen zu können', - 'not_callable' => 'Die Callback-Funktion %s, die zur Validierung benutzt wird, ist nicht aufrufbar', + // Class errors + 'invalid_rule' => 'Ungültige Validierungsregel benutzt: %s', + 'i18n_array' => 'Der i18n-Schlüssel %s muss ein Array sein, um diesen in der in_array-Regel benutzen zu können', + 'not_callable' => 'Die Callback-Funktion %s, die zur Validierung benutzt wird, ist nicht aufrufbar', - // General errors - 'unknown_error' => 'Unbekannter Fehler bei der Validierungsregel von dem Feld %s aufgetreten.', - 'required' => 'Das Feld %s ist erforderlich.', - 'min_length' => 'Das Feld %s muss mindestens %d Zeichen lang sein.', - 'max_length' => 'Das Feld %s darf höchstens %d Zeichen lang sein.', - 'exact_length' => 'Das Feld %s muss genau %d Zeichen enthalten.', - 'in_array' => 'Das Feld %s muss ausgewählt werden.', - 'matches' => 'Das Feld %s muss mit dem Feld %s übereinstimmen.', - 'valid_url' => 'Das Feld %s muss eine gültige URL beinhalten.', - 'valid_email' => 'Das Feld %s muss eine gültige E-Mailadresse beinhalten.', - 'valid_ip' => 'Das Feld %s muss eine gültige IP-Adresse beinhalten.', - 'valid_type' => 'Das Feld %s darf nur %s beinhalten.', - 'range' => 'Das Feld %s muss zwischen festgelegten Bereichen sein.', - 'regex' => 'Das Feld %s entspricht nicht einer akzeptierten Eingabe.', - 'depends_on' => 'Das Feld %s hängt vom Feld %s ab.', + // General errors + 'unknown_error' => 'Unbekannter Fehler bei der Validierungsregel von dem Feld %s aufgetreten.', + 'required' => 'Das Feld %s ist erforderlich.', + 'min_length' => 'Das Feld %s muss mindestens %d Zeichen lang sein.', + 'max_length' => 'Das Feld %s darf höchstens %d Zeichen lang sein.', + 'exact_length' => 'Das Feld %s muss genau %d Zeichen enthalten.', + 'in_array' => 'Das Feld %s muss ausgewählt werden.', + 'matches' => 'Das Feld %s muss mit dem Feld %s übereinstimmen.', + 'valid_url' => 'Das Feld %s muss eine gültige URL beinhalten.', + 'valid_email' => 'Das Feld %s muss eine gültige E-Mailadresse beinhalten.', + 'valid_ip' => 'Das Feld %s muss eine gültige IP-Adresse beinhalten.', + 'valid_type' => 'Das Feld %s darf nur %s beinhalten.', + 'range' => 'Das Feld %s muss zwischen festgelegten Bereichen sein.', + 'regex' => 'Das Feld %s entspricht nicht einer akzeptierten Eingabe.', + 'depends_on' => 'Das Feld %s hängt vom Feld %s ab.', - // Upload errors - 'user_aborted' => 'Das Hochladen der Datei %s wurde abgebrochen.', - 'invalid_type' => 'Die Datei %s entspricht nicht den erlaubten Dateitypen.', - 'max_size' => 'Die Datei %s ist zu groß. Die maximale Größe beträgt %s.', - 'max_width' => 'Die Datei %s ist zu groß. Die maximal erlaubte Breite betägt %spx.', - 'max_height' => 'Die Datei %s ist zu groß. Die maximal erlaubte Höhe betägt %spx.', - 'min_width' => 'Die Datei %s ist zu klein. Die minimal erlaubte Breite betägt %spx.', - 'min_height' => 'Die Datei %s ist zu klein. Die minimal erlaubte Höhe betägt %spx.', + // Upload errors + 'user_aborted' => 'Das Hochladen der Datei %s wurde abgebrochen.', + 'invalid_type' => 'Die Datei %s entspricht nicht den erlaubten Dateitypen.', + 'max_size' => 'Die Datei %s ist zu groß. Die maximale Größe beträgt %s.', + 'max_width' => 'Die Datei %s ist zu groß. Die maximal erlaubte Breite betägt %spx.', + 'max_height' => 'Die Datei %s ist zu groß. Die maximal erlaubte Höhe betägt %spx.', + 'min_width' => 'Die Datei %s ist zu klein. Die minimal erlaubte Breite betägt %spx.', + 'min_height' => 'Die Datei %s ist zu klein. Die minimal erlaubte Höhe betägt %spx.', - // Field types - 'alpha' => 'alphabetische Zeichen', - 'alpha_numeric' => 'alphabetische und numerische Zeichen', - 'alpha_dash' => 'alphabetische Zeichen, Trennstriche und Unterstriche', - 'digit' => 'Zahlen', - 'numeric' => 'Nummern', + // Field types + 'alpha' => 'alphabetische Zeichen', + 'alpha_numeric' => 'alphabetische und numerische Zeichen', + 'alpha_dash' => 'alphabetische Zeichen, Trennstriche und Unterstriche', + 'digit' => 'Zahlen', + 'numeric' => 'Nummern', ); diff --git a/lib/kohana/system/i18n/en_US/cache.php b/lib/kohana/system/i18n/en_US/cache.php index bef0279..753ea11 100644 --- a/lib/kohana/system/i18n/en_US/cache.php +++ b/lib/kohana/system/i18n/en_US/cache.php @@ -1,10 +1,12 @@ - 'The %s group is not defined in your configuration.', - 'extension_not_loaded' => 'The %s PHP extension must be loaded to use this driver.', - 'unwritable' => 'The configured storage location, %s, is not writable.', - 'resources' => 'Caching of resources is impossible, because resources cannot be serialized.', - 'driver_error' => '%s', -); \ No newline at end of file + 'undefined_group' => 'The %s group is not defined in your configuration.', + 'extension_not_loaded' => 'The %s PHP extension must be loaded to use this driver.', + 'unwritable' => 'The configured storage location, %s, is not writable.', + 'resources' => 'Caching of resources is impossible, because resources cannot be serialized.', + 'driver_error' => '%s', +); diff --git a/lib/kohana/system/i18n/en_US/calendar.php b/lib/kohana/system/i18n/en_US/calendar.php index 21dad22..09527f9 100644 --- a/lib/kohana/system/i18n/en_US/calendar.php +++ b/lib/kohana/system/i18n/en_US/calendar.php @@ -1,59 +1,61 @@ - 'Su', - 'mo' => 'Mo', - 'tu' => 'Tu', - 'we' => 'We', - 'th' => 'Th', - 'fr' => 'Fr', - 'sa' => 'Sa', + // Two letter days + 'su' => 'Su', + 'mo' => 'Mo', + 'tu' => 'Tu', + 'we' => 'We', + 'th' => 'Th', + 'fr' => 'Fr', + 'sa' => 'Sa', - // Short day names - 'sun' => 'Sun', - 'mon' => 'Mon', - 'tue' => 'Tue', - 'wed' => 'Wed', - 'thu' => 'Thu', - 'fri' => 'Fri', - 'sat' => 'Sat', + // Short day names + 'sun' => 'Sun', + 'mon' => 'Mon', + 'tue' => 'Tue', + 'wed' => 'Wed', + 'thu' => 'Thu', + 'fri' => 'Fri', + 'sat' => 'Sat', - // Long day names - 'sunday' => 'Sunday', - 'monday' => 'Monday', - 'tuesday' => 'Tuesday', - 'wednesday' => 'Wednesday', - 'thursday' => 'Thursday', - 'friday' => 'Friday', - 'saturday' => 'Saturday', + // Long day names + 'sunday' => 'Sunday', + 'monday' => 'Monday', + 'tuesday' => 'Tuesday', + 'wednesday' => 'Wednesday', + 'thursday' => 'Thursday', + 'friday' => 'Friday', + 'saturday' => 'Saturday', - // Short month names - 'jan' => 'Jan', - 'feb' => 'Feb', - 'mar' => 'Mar', - 'apr' => 'Apr', - 'may' => 'May', - 'jun' => 'Jun', - 'jul' => 'Jul', - 'aug' => 'Aug', - 'sep' => 'Sep', - 'oct' => 'Oct', - 'nov' => 'Nov', - 'dec' => 'Dec', + // Short month names + 'jan' => 'Jan', + 'feb' => 'Feb', + 'mar' => 'Mar', + 'apr' => 'Apr', + 'may' => 'May', + 'jun' => 'Jun', + 'jul' => 'Jul', + 'aug' => 'Aug', + 'sep' => 'Sep', + 'oct' => 'Oct', + 'nov' => 'Nov', + 'dec' => 'Dec', - // Long month names - 'january' => 'January', - 'february' => 'February', - 'march' => 'March', - 'april' => 'April', - 'mayl' => 'May', - 'june' => 'June', - 'july' => 'July', - 'august' => 'August', - 'september' => 'September', - 'october' => 'October', - 'november' => 'November', - 'december' => 'December' -); \ No newline at end of file + // Long month names + 'january' => 'January', + 'february' => 'February', + 'march' => 'March', + 'april' => 'April', + 'mayl' => 'May', + 'june' => 'June', + 'july' => 'July', + 'august' => 'August', + 'september' => 'September', + 'october' => 'October', + 'november' => 'November', + 'december' => 'December' +); diff --git a/lib/kohana/system/i18n/en_US/captcha.php b/lib/kohana/system/i18n/en_US/captcha.php index 6040471..29c81cf 100644 --- a/lib/kohana/system/i18n/en_US/captcha.php +++ b/lib/kohana/system/i18n/en_US/captcha.php @@ -1,33 +1,35 @@ - 'The specified file, %s, was not found. Please verify that files exist by using file_exists() before using them.', - 'requires_GD2' => 'The Captcha library requires GD2 with FreeType support. Please see http://php.net/gd_info for more information.', + 'file_not_found' => 'The specified file, %s, was not found. Please verify that files exist by using file_exists() before using them.', + 'requires_GD2' => 'The Captcha library requires GD2 with FreeType support. Please see http://php.net/gd_info for more information.', - // Words of varying length for the Captcha_Word_Driver to pick from - // Note: use only alphanumeric characters - 'words' => array - ( - 'cd', 'tv', 'it', 'to', 'be', 'or', - 'sun', 'car', 'dog', 'bed', 'kid', 'egg', - 'bike', 'tree', 'bath', 'roof', 'road', 'hair', - 'hello', 'world', 'earth', 'beard', 'chess', 'water', - 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', - 'america', 'release', 'playing', 'working', 'foreign', 'general', - 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', - 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', - ), + // Words of varying length for the Captcha_Word_Driver to pick from + // Note: use only alphanumeric characters + 'words' => array + ( + 'cd', 'tv', 'it', 'to', 'be', 'or', + 'sun', 'car', 'dog', 'bed', 'kid', 'egg', + 'bike', 'tree', 'bath', 'roof', 'road', 'hair', + 'hello', 'world', 'earth', 'beard', 'chess', 'water', + 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', + 'america', 'release', 'playing', 'working', 'foreign', 'general', + 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', + 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', + ), - // Riddles for the Captcha_Riddle_Driver to pick from - // Note: use only alphanumeric characters - 'riddles' => array - ( - array('Do you hate spam? (yes or no)', 'yes'), - array('Are you a robot? (yes or no)', 'no'), - array('Fire is... (hot or cold)', 'hot'), - array('The season after fall is...', 'winter'), - array('Which day of the week is it today?', strftime('%A')), - array('Which month of the year are we in?', strftime('%B')), - ), + // Riddles for the Captcha_Riddle_Driver to pick from + // Note: use only alphanumeric characters + 'riddles' => array + ( + array('Do you hate spam? (yes or no)', 'yes'), + array('Are you a robot? (yes or no)', 'no'), + array('Fire is... (hot or cold)', 'hot'), + array('The season after fall is...', 'winter'), + array('Which day of the week is it today?', strftime('%A')), + array('Which month of the year are we in?', strftime('%B')), + ), ); diff --git a/lib/kohana/system/i18n/en_US/core.php b/lib/kohana/system/i18n/en_US/core.php index 9711b7c..2c981b2 100644 --- a/lib/kohana/system/i18n/en_US/core.php +++ b/lib/kohana/system/i18n/en_US/core.php @@ -1,34 +1,36 @@ - 'There can be only one instance of Kohana per page request', - 'uncaught_exception' => 'Uncaught %s: %s in file %s on line %s', - 'invalid_method' => 'Invalid method %s called in %s', - 'invalid_property' => 'The %s property does not exist in the %s class.', - 'log_dir_unwritable' => 'The log directory is not writable: %s', - 'resource_not_found' => 'The requested %s, %s, could not be found', - 'invalid_filetype' => 'The requested filetype, .%s, is not allowed in your view configuration file', - 'view_set_filename' => 'You must set the the view filename before calling render', - 'no_default_route' => 'Please set a default route in config/routes.php', - 'no_controller' => 'Kohana was not able to determine a controller to process this request: %s', - 'page_not_found' => 'The page you requested, %s, could not be found.', - 'stats_footer' => 'Loaded in {execution_time} seconds, using {memory_usage} of memory. Generated by Kohana v{kohana_version}.', - 'error_file_line' => '%s [%s]:', - 'stack_trace' => 'Stack Trace', - 'generic_error' => 'Unable to Complete Request', - 'errors_disabled' => 'You can go to the home page or try again.', + 'there_can_be_only_one' => 'There can be only one instance of Kohana per page request', + 'uncaught_exception' => 'Uncaught %s: %s in file %s on line %s', + 'invalid_method' => 'Invalid method %s called in %s', + 'invalid_property' => 'The %s property does not exist in the %s class.', + 'log_dir_unwritable' => 'The log directory is not writable: %s', + 'resource_not_found' => 'The requested %s, %s, could not be found', + 'invalid_filetype' => 'The requested filetype, .%s, is not allowed in your view configuration file', + 'view_set_filename' => 'You must set the the view filename before calling render', + 'no_default_route' => 'Please set a default route in config/routes.php', + 'no_controller' => 'Kohana was not able to determine a controller to process this request: %s', + 'page_not_found' => 'The page you requested, %s, could not be found.', + 'stats_footer' => 'Loaded in {execution_time} seconds, using {memory_usage} of memory. Generated by Kohana v{kohana_version}.', + 'error_file_line' => '%s [%s]:', + 'stack_trace' => 'Stack Trace', + 'generic_error' => 'Unable to Complete Request', + 'errors_disabled' => 'You can go to the home page or try again.', - // Drivers - 'driver_implements' => 'The %s driver for the %s library must implement the %s interface', - 'driver_not_found' => 'The %s driver for the %s library could not be found', + // Drivers + 'driver_implements' => 'The %s driver for the %s library must implement the %s interface', + 'driver_not_found' => 'The %s driver for the %s library could not be found', - // Resource names - 'config' => 'config file', - 'controller' => 'controller', - 'helper' => 'helper', - 'library' => 'library', - 'driver' => 'driver', - 'model' => 'model', - 'view' => 'view', + // Resource names + 'config' => 'config file', + 'controller' => 'controller', + 'helper' => 'helper', + 'library' => 'library', + 'driver' => 'driver', + 'model' => 'model', + 'view' => 'view', ); diff --git a/lib/kohana/system/i18n/en_US/database.php b/lib/kohana/system/i18n/en_US/database.php index 172e5c9..f0f47b2 100644 --- a/lib/kohana/system/i18n/en_US/database.php +++ b/lib/kohana/system/i18n/en_US/database.php @@ -1,15 +1,17 @@ - 'The %s group is not defined in your configuration.', - 'error' => 'There was an SQL error: %s', - 'connection' => 'There was an error connecting to the database: %s', - 'invalid_dsn' => 'The DSN you supplied is not valid: %s', - 'must_use_set' => 'You must set a SET clause for your query.', - 'must_use_where' => 'You must set a WHERE clause for your query.', - 'must_use_table' => 'You must set a database table for your query.', - 'table_not_found' => 'Table %s does not exist in your database.', - 'not_implemented' => 'The method you called, %s, is not supported by this driver.', - 'result_read_only' => 'Query results are read only.' -); \ No newline at end of file + 'undefined_group' => 'The %s group is not defined in your configuration.', + 'error' => 'There was an SQL error: %s', + 'connection' => 'There was an error connecting to the database: %s', + 'invalid_dsn' => 'The DSN you supplied is not valid: %s', + 'must_use_set' => 'You must set a SET clause for your query.', + 'must_use_where' => 'You must set a WHERE clause for your query.', + 'must_use_table' => 'You must set a database table for your query.', + 'table_not_found' => 'Table %s does not exist in your database.', + 'not_implemented' => 'The method you called, %s, is not supported by this driver.', + 'result_read_only' => 'Query results are read only.' +); diff --git a/lib/kohana/system/i18n/en_US/encrypt.php b/lib/kohana/system/i18n/en_US/encrypt.php index 9afd620..71555e8 100644 --- a/lib/kohana/system/i18n/en_US/encrypt.php +++ b/lib/kohana/system/i18n/en_US/encrypt.php @@ -1,8 +1,10 @@ - 'The %s group is not defined in your configuration.', - 'requires_mcrypt' => 'To use the Encrypt library, mcrypt must be enabled in your PHP installation', - 'no_encryption_key' => 'To use the Encrypt library, you must set an encryption key in your config file' + 'undefined_group' => 'The %s group is not defined in your configuration.', + 'requires_mcrypt' => 'To use the Encrypt library, mcrypt must be enabled in your PHP installation', + 'no_encryption_key' => 'To use the Encrypt library, you must set an encryption key in your config file' ); diff --git a/lib/kohana/system/i18n/en_US/errors.php b/lib/kohana/system/i18n/en_US/errors.php index 10f44ff..e50dcbd 100644 --- a/lib/kohana/system/i18n/en_US/errors.php +++ b/lib/kohana/system/i18n/en_US/errors.php @@ -1,15 +1,19 @@ - array( 1, 'Framework Error', 'Please check the Kohana documentation for information about the following error.'), - E_PAGE_NOT_FOUND => array( 1, 'Page Not Found', 'The requested page was not found. It may have moved, been deleted, or archived.'), - E_DATABASE_ERROR => array( 1, 'Database Error', 'A database error occurred while performing the requested procedure. Please review the database error below for more information.'), - E_ERROR => array( 1, 'Fatal Error', ''), - E_USER_ERROR => array( 1, 'Fatal Error', ''), - E_PARSE => array( 1, 'Syntax Error', ''), - E_WARNING => array( 1, 'Warning Message', ''), - E_USER_WARNING => array( 1, 'Warning Message', ''), - E_STRICT => array( 2, 'Strict Mode Error', ''), - E_NOTICE => array( 2, 'Runtime Message', ''), + E_KOHANA => array( 1, 'Framework Error', 'Please check the Kohana documentation for information about the following error.'), + E_PAGE_NOT_FOUND => array( 1, 'Page Not Found', 'The requested page was not found. It may have moved, been deleted, or archived.'), + E_DATABASE_ERROR => array( 1, 'Database Error', + 'A database error occurred while performing the requested procedure.' . + ' Please review the database error below for more information.'), + E_ERROR => array( 1, 'Fatal Error', ''), + E_USER_ERROR => array( 1, 'Fatal Error', ''), + E_PARSE => array( 1, 'Syntax Error', ''), + E_WARNING => array( 1, 'Warning Message', ''), + E_USER_WARNING => array( 1, 'Warning Message', ''), + E_STRICT => array( 2, 'Strict Mode Error', ''), + E_NOTICE => array( 2, 'Runtime Message', ''), ); diff --git a/lib/kohana/system/i18n/en_US/event.php b/lib/kohana/system/i18n/en_US/event.php index 282a0a2..42a3b0c 100644 --- a/lib/kohana/system/i18n/en_US/event.php +++ b/lib/kohana/system/i18n/en_US/event.php @@ -1,7 +1,9 @@ - 'Attempt to attach invalid subject %s to %s failed: Subjects must extend the Event_Subject class', - 'invalid_observer' => 'Attempt to attach invalid observer %s to %s failed: Observers must extend the Event_Observer class', + 'invalid_subject' => 'Attempt to attach invalid subject %s to %s failed: Subjects must extend the Event_Subject class', + 'invalid_observer' => 'Attempt to attach invalid observer %s to %s failed: Observers must extend the Event_Observer class', ); diff --git a/lib/kohana/system/i18n/en_US/image.php b/lib/kohana/system/i18n/en_US/image.php index 9f18493..4c0152c 100644 --- a/lib/kohana/system/i18n/en_US/image.php +++ b/lib/kohana/system/i18n/en_US/image.php @@ -1,33 +1,35 @@ - 'The Image library requires the getimagesize() PHP function, which is not available in your installation.', - 'unsupported_method' => 'Your configured driver does not support the %s image transformation.', - 'file_not_found' => 'The specified image, %s, was not found. Please verify that images exist by using file_exists() before manipulating them.', - 'type_not_allowed' => 'The specified image, %s, is not an allowed image type.', - 'invalid_width' => 'The width you specified, %s, is not valid.', - 'invalid_height' => 'The height you specified, %s, is not valid.', - 'invalid_dimensions' => 'The dimensions specified for %s are not valid.', - 'invalid_master' => 'The master dimension specified is not valid.', - 'invalid_flip' => 'The flip direction specified is not valid.', - 'directory_unwritable' => 'The specified directory, %s, is not writable.', + 'getimagesize_missing' => 'The Image library requires the getimagesize() PHP function, which is not available in your installation.', + 'unsupported_method' => 'Your configured driver does not support the %s image transformation.', + 'file_not_found' => 'The specified image, %s, was not found. Please verify that images exist by using file_exists() before manipulating them.', + 'type_not_allowed' => 'The specified image, %s, is not an allowed image type.', + 'invalid_width' => 'The width you specified, %s, is not valid.', + 'invalid_height' => 'The height you specified, %s, is not valid.', + 'invalid_dimensions' => 'The dimensions specified for %s are not valid.', + 'invalid_master' => 'The master dimension specified is not valid.', + 'invalid_flip' => 'The flip direction specified is not valid.', + 'directory_unwritable' => 'The specified directory, %s, is not writable.', - // ImageMagick specific messages - 'imagemagick' => array - ( - 'not_found' => 'The ImageMagick directory specified does not contain a required program, %s.', - ), - - // GraphicsMagick specific messages - 'graphicsmagick' => array - ( - 'not_found' => 'The GraphicsMagick directory specified does not contain a required program, %s.', - ), - - // GD specific messages - 'gd' => array - ( - 'requires_v2' => 'The Image library requires GD2. Please see http://php.net/gd_info for more information.', - ), + // ImageMagick specific messages + 'imagemagick' => array + ( + 'not_found' => 'The ImageMagick directory specified does not contain a required program, %s.', + ), + + // GraphicsMagick specific messages + 'graphicsmagick' => array + ( + 'not_found' => 'The GraphicsMagick directory specified does not contain a required program, %s.', + ), + + // GD specific messages + 'gd' => array + ( + 'requires_v2' => 'The Image library requires GD2. Please see http://php.net/gd_info for more information.', + ), ); diff --git a/lib/kohana/system/i18n/en_US/orm.php b/lib/kohana/system/i18n/en_US/orm.php index 3c5720b..ac7943b 100644 --- a/lib/kohana/system/i18n/en_US/orm.php +++ b/lib/kohana/system/i18n/en_US/orm.php @@ -1,3 +1,5 @@ - 'The %s group is not defined in your pagination configuration.', - 'page' => 'page', - 'pages' => 'pages', - 'item' => 'item', - 'items' => 'items', - 'of' => 'of', - 'first' => 'first', - 'last' => 'last', - 'previous' => 'previous', - 'next' => 'next', + 'undefined_group' => 'The %s group is not defined in your pagination configuration.', + 'page' => 'page', + 'pages' => 'pages', + 'item' => 'item', + 'items' => 'items', + 'of' => 'of', + 'first' => 'first', + 'last' => 'last', + 'previous' => 'previous', + 'next' => 'next', ); diff --git a/lib/kohana/system/i18n/en_US/profiler.php b/lib/kohana/system/i18n/en_US/profiler.php index a39c2f5..0201fba 100644 --- a/lib/kohana/system/i18n/en_US/profiler.php +++ b/lib/kohana/system/i18n/en_US/profiler.php @@ -1,15 +1,17 @@ - 'Benchmarks', - 'post_data' => 'Post Data', - 'no_post' => 'No post data', - 'session_data' => 'Session Data', - 'no_session' => 'No session data', - 'queries' => 'Database Queries', - 'no_queries' => 'No queries', - 'no_database' => 'Database not loaded', - 'cookie_data' => 'Cookie Data', - 'no_cookie' => 'No cookie data', + 'benchmarks' => 'Benchmarks', + 'post_data' => 'Post Data', + 'no_post' => 'No post data', + 'session_data' => 'Session Data', + 'no_session' => 'No session data', + 'queries' => 'Database Queries', + 'no_queries' => 'No queries', + 'no_database' => 'Database not loaded', + 'cookie_data' => 'Cookie Data', + 'no_cookie' => 'No cookie data', ); diff --git a/lib/kohana/system/i18n/en_US/session.php b/lib/kohana/system/i18n/en_US/session.php index ee781c6..4cdffaa 100644 --- a/lib/kohana/system/i18n/en_US/session.php +++ b/lib/kohana/system/i18n/en_US/session.php @@ -1,6 +1,8 @@ - 'The session_name, %s, is invalid. It must contain only alphanumeric characters and underscores. Also at least one letter must be present.', -); \ No newline at end of file + 'invalid_session_name' => 'The session_name, %s, is invalid. It must contain only alphanumeric characters and underscores. Also at least one letter must be present.', +); diff --git a/lib/kohana/system/i18n/en_US/swift.php b/lib/kohana/system/i18n/en_US/swift.php index 249c4a8..ce0cd4f 100644 --- a/lib/kohana/system/i18n/en_US/swift.php +++ b/lib/kohana/system/i18n/en_US/swift.php @@ -1,6 +1,8 @@ - 'An error occurred while sending the email message.' -); \ No newline at end of file + 'general_error' => 'An error occurred while sending the email message.' +); diff --git a/lib/kohana/system/i18n/en_US/upload.php b/lib/kohana/system/i18n/en_US/upload.php index 7f6e216..86806fd 100644 --- a/lib/kohana/system/i18n/en_US/upload.php +++ b/lib/kohana/system/i18n/en_US/upload.php @@ -1,6 +1,8 @@ - 'The upload destination folder, %s, does not appear to be writable.', -); \ No newline at end of file + 'not_writable' => 'The upload destination folder, %s, does not appear to be writable.', +); diff --git a/lib/kohana/system/i18n/en_US/validation.php b/lib/kohana/system/i18n/en_US/validation.php index d98e548..997c0a8 100644 --- a/lib/kohana/system/i18n/en_US/validation.php +++ b/lib/kohana/system/i18n/en_US/validation.php @@ -1,41 +1,43 @@ - 'Invalid validation rule used: %s', - 'i18n_array' => 'The %s i18n key must be an array to be used with the in_lang rule', - 'not_callable' => 'Callback %s used for Validation is not callable', + // Class errors + 'invalid_rule' => 'Invalid validation rule used: %s', + 'i18n_array' => 'The %s i18n key must be an array to be used with the in_lang rule', + 'not_callable' => 'Callback %s used for Validation is not callable', - // General errors - 'unknown_error' => 'Unknown validation error while validating the %s field.', - 'required' => 'The %s field is required.', - 'min_length' => 'The %s field must be at least %d characters long.', - 'max_length' => 'The %s field must be %d characters or fewer.', - 'exact_length' => 'The %s field must be exactly %d characters.', - 'in_array' => 'The %s field must be selected from the options listed.', - 'matches' => 'The %s field must match the %s field.', - 'valid_url' => 'The %s field must contain a valid URL.', - 'valid_email' => 'The %s field must contain a valid email address.', - 'valid_ip' => 'The %s field must contain a valid IP address.', - 'valid_type' => 'The %s field must only contain %s characters.', - 'range' => 'The %s field must be between specified ranges.', - 'regex' => 'The %s field does not match accepted input.', - 'depends_on' => 'The %s field depends on the %s field.', + // General errors + 'unknown_error' => 'Unknown validation error while validating the %s field.', + 'required' => 'The %s field is required.', + 'min_length' => 'The %s field must be at least %d characters long.', + 'max_length' => 'The %s field must be %d characters or fewer.', + 'exact_length' => 'The %s field must be exactly %d characters.', + 'in_array' => 'The %s field must be selected from the options listed.', + 'matches' => 'The %s field must match the %s field.', + 'valid_url' => 'The %s field must contain a valid URL.', + 'valid_email' => 'The %s field must contain a valid email address.', + 'valid_ip' => 'The %s field must contain a valid IP address.', + 'valid_type' => 'The %s field must only contain %s characters.', + 'range' => 'The %s field must be between specified ranges.', + 'regex' => 'The %s field does not match accepted input.', + 'depends_on' => 'The %s field depends on the %s field.', - // Upload errors - 'user_aborted' => 'The %s file was aborted during upload.', - 'invalid_type' => 'The %s file is not an allowed file type.', - 'max_size' => 'The %s file you uploaded was too large. The maximum size allowed is %s.', - 'max_width' => 'The %s file you uploaded was too big. The maximum allowed width is %spx.', - 'max_height' => 'The %s file you uploaded was too big. The maximum allowed height is %spx.', - 'min_width' => 'The %s file you uploaded was too small. The minimum allowed width is %spx.', - 'min_height' => 'The %s file you uploaded was too small. The minimum allowed height is %spx.', + // Upload errors + 'user_aborted' => 'The %s file was aborted during upload.', + 'invalid_type' => 'The %s file is not an allowed file type.', + 'max_size' => 'The %s file you uploaded was too large. The maximum size allowed is %s.', + 'max_width' => 'The %s file you uploaded was too big. The maximum allowed width is %spx.', + 'max_height' => 'The %s file you uploaded was too big. The maximum allowed height is %spx.', + 'min_width' => 'The %s file you uploaded was too small. The minimum allowed width is %spx.', + 'min_height' => 'The %s file you uploaded was too small. The minimum allowed height is %spx.', - // Field types - 'alpha' => 'alphabetical', - 'alpha_numeric' => 'alphabetical and numeric', - 'alpha_dash' => 'alphabetical, dash, and underscore', - 'digit' => 'digit', - 'numeric' => 'numeric', + // Field types + 'alpha' => 'alphabetical', + 'alpha_numeric' => 'alphabetical and numeric', + 'alpha_dash' => 'alphabetical, dash, and underscore', + 'digit' => 'digit', + 'numeric' => 'numeric', ); diff --git a/lib/kohana/system/i18n/es_ES/cache.php b/lib/kohana/system/i18n/es_ES/cache.php index c05e4cb..3671d62 100644 --- a/lib/kohana/system/i18n/es_ES/cache.php +++ b/lib/kohana/system/i18n/es_ES/cache.php @@ -1,10 +1,12 @@ - 'El grupo %s no esta definido en la configuracion.', - 'extension_not_loaded' => 'La extensión PHP %s tiene que estar cargada para poder utilizar este driver.', - 'unwritable' => 'El directorio seleccionado, %s, no tiene permisos de escritura.', - 'resources' => 'No es posible guardar el contenido en la cache, el contenido no es serializable.', - 'driver_error' => '%s', -); \ No newline at end of file + 'undefined_group' => 'El grupo %s no esta definido en la configuracion.', + 'extension_not_loaded' => 'La extensión PHP %s tiene que estar cargada para poder utilizar este driver.', + 'unwritable' => 'El directorio seleccionado, %s, no tiene permisos de escritura.', + 'resources' => 'No es posible guardar el contenido en la cache, el contenido no es serializable.', + 'driver_error' => '%s', +); diff --git a/lib/kohana/system/i18n/es_ES/calendar.php b/lib/kohana/system/i18n/es_ES/calendar.php index 961b223..e855cdb 100644 --- a/lib/kohana/system/i18n/es_ES/calendar.php +++ b/lib/kohana/system/i18n/es_ES/calendar.php @@ -1,55 +1,57 @@ - 'Do', - 'mo' => 'Lu', - 'tu' => 'Ma', - 'we' => 'Mi', - 'th' => 'Ju', - 'fr' => 'Vi', - 'sa' => 'Sa', - // Short day names - 'sun' => 'Dom', - 'mon' => 'Lun', - 'tue' => 'Mar', - 'wed' => 'Mie', - 'thu' => 'Jue', - 'fri' => 'Vie', - 'sat' => 'Sab', - // Long day names - 'sunday' => 'Domingo', - 'monday' => 'Lunes', - 'tuesday' => 'Martes', - 'wednesday' => 'Miércoles', - 'thursday' => 'Jueves', - 'friday' => 'Viernes', - 'saturday' => 'Sábado', - // Short month names - 'jan' => 'Ene', - 'feb' => 'Feb', - 'mar' => 'Mar', - 'apr' => 'Abr', - 'may' => 'May', - 'jun' => 'Jun', - 'jul' => 'Jul', - 'aug' => 'Ago', - 'sep' => 'Sep', - 'oct' => 'Oct', - 'nov' => 'Nov', - 'dec' => 'Dic', - // Long month names - 'january' => 'Enero', - 'february' => 'Febrero', - 'march' => 'Marzo', - 'april' => 'Abril', - 'mayl' => 'Mayo', - 'june' => 'Junio', - 'july' => 'Julio', - 'august' => 'Agosto', - 'september' => 'Septiembre', - 'october' => 'Octubre', - 'november' => 'Noviembre', - 'december' => 'Diciembre', -); \ No newline at end of file + // Two letter days + 'su' => 'Do', + 'mo' => 'Lu', + 'tu' => 'Ma', + 'we' => 'Mi', + 'th' => 'Ju', + 'fr' => 'Vi', + 'sa' => 'Sa', + // Short day names + 'sun' => 'Dom', + 'mon' => 'Lun', + 'tue' => 'Mar', + 'wed' => 'Mie', + 'thu' => 'Jue', + 'fri' => 'Vie', + 'sat' => 'Sab', + // Long day names + 'sunday' => 'Domingo', + 'monday' => 'Lunes', + 'tuesday' => 'Martes', + 'wednesday' => 'Miércoles', + 'thursday' => 'Jueves', + 'friday' => 'Viernes', + 'saturday' => 'Sábado', + // Short month names + 'jan' => 'Ene', + 'feb' => 'Feb', + 'mar' => 'Mar', + 'apr' => 'Abr', + 'may' => 'May', + 'jun' => 'Jun', + 'jul' => 'Jul', + 'aug' => 'Ago', + 'sep' => 'Sep', + 'oct' => 'Oct', + 'nov' => 'Nov', + 'dec' => 'Dic', + // Long month names + 'january' => 'Enero', + 'february' => 'Febrero', + 'march' => 'Marzo', + 'april' => 'Abril', + 'mayl' => 'Mayo', + 'june' => 'Junio', + 'july' => 'Julio', + 'august' => 'Agosto', + 'september' => 'Septiembre', + 'october' => 'Octubre', + 'november' => 'Noviembre', + 'december' => 'Diciembre', +); diff --git a/lib/kohana/system/i18n/es_ES/captcha.php b/lib/kohana/system/i18n/es_ES/captcha.php index 6c2cd15..b2b81cd 100644 --- a/lib/kohana/system/i18n/es_ES/captcha.php +++ b/lib/kohana/system/i18n/es_ES/captcha.php @@ -1,33 +1,36 @@ - 'El archivo especificado, %s, no ha sido encontrado. Por favor, verifica que el fichero existe utilizando file_exists() antes de intentar utilizarlo.', - 'requires_GD2' => 'La libreria Captcha requiere GD2 con soporte FreeType. Lea lo siguiente http://php.net/gd_info para ampliar la informacion.', - - // Words of varying length for the Captcha_Word_Driver to pick from - // Note: use only alphanumeric characters - 'words' => array - ( - 'cd', 'tv', 'it', 'to', 'be', 'or', - 'sun', 'car', 'dog', 'bed', 'kid', 'egg', - 'bike', 'tree', 'bath', 'roof', 'road', 'hair', - 'hello', 'world', 'earth', 'beard', 'chess', 'water', - 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', - 'america', 'release', 'playing', 'working', 'foreign', 'general', - 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', - 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', - ), + 'file_not_found' => 'El archivo especificado, %s, no ha sido encontrado.' . + ' Por favor, verifica que el fichero existe utilizando file_exists() antes de intentar utilizarlo.', + 'requires_GD2' => 'La libreria Captcha requiere GD2 con soporte FreeType. Lea lo siguiente http://php.net/gd_info para ampliar la informacion.', - // Riddles for the Captcha_Riddle_Driver to pick from - // Note: use only alphanumeric characters - 'riddles' => array - ( - array('¿Odias el spam? (si o no)', 'si'), - array('¿Eres un robot? (si o no)', 'no'), - array('El fuego es... (caliente o frio)', 'caliente'), - array('La estación que viene despues del otoño es...', 'invierno'), - array('¿Qué día de la semana es hoy?', strftime('%A')), - array('¿En qué mes del año estamos?', strftime('%B')), - ), + // Words of varying length for the Captcha_Word_Driver to pick from + // Note: use only alphanumeric characters + 'words' => array + ( + 'cd', 'tv', 'it', 'to', 'be', 'or', + 'sun', 'car', 'dog', 'bed', 'kid', 'egg', + 'bike', 'tree', 'bath', 'roof', 'road', 'hair', + 'hello', 'world', 'earth', 'beard', 'chess', 'water', + 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', + 'america', 'release', 'playing', 'working', 'foreign', 'general', + 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', + 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', + ), + + // Riddles for the Captcha_Riddle_Driver to pick from + // Note: use only alphanumeric characters + 'riddles' => array + ( + array('¿Odias el spam? (si o no)', 'si'), + array('¿Eres un robot? (si o no)', 'no'), + array('El fuego es... (caliente o frio)', 'caliente'), + array('La estación que viene despues del otoño es...', 'invierno'), + array('¿Qué día de la semana es hoy?', strftime('%A')), + array('¿En qué mes del año estamos?', strftime('%B')), + ), ); diff --git a/lib/kohana/system/i18n/es_ES/core.php b/lib/kohana/system/i18n/es_ES/core.php index 6cbe5e9..6fde43a 100644 --- a/lib/kohana/system/i18n/es_ES/core.php +++ b/lib/kohana/system/i18n/es_ES/core.php @@ -1,34 +1,36 @@ - 'Solo puede haber una instancia de Kohana por cada página.', - 'uncaught_exception' => '%s no capturada: %s en el archivo %s, linea %s', - 'invalid_method' => 'Método inválido %s llamado en %s.', - 'invalid_property' => 'La propiedad %s no existe en la clase %s.', - 'log_dir_unwritable' => 'Tu configuración del &8220;log.directory&8221; no apunta a un directorio con permiso de escritura.', - 'resource_not_found' => 'El fichero de %s con nombre %s, no pudo ser encontrado.', - 'invalid_filetype' => 'El tipo de fichero solicitado, .%s, no esta permitido en la configuración de tus vistas.', - 'view_set_filename' => 'Tienes que definir el nombre de la vista antes de llamar al metodo render', - 'no_default_route' => 'Por favor, especifica la ruta en config/routes.php.', - 'no_controller' => 'Kohana no pudo determinar un controlador para procesar: %s', - 'page_not_found' => 'La página que solicitase, %s, no se encuentra.', - 'stats_footer' => 'Cargado en {execution_time} segundos, usando {memory_usage} de memoria. Generado con Kohana v{kohana_version}.', - 'error_file_line' => '%s [%s]:', - 'stack_trace' => 'Stack Trace', - 'generic_error' => 'Imposible completar la solicitud', - 'errors_disabled' => 'Puedes volver a la página de inico o volver a intentarlo.', + 'there_can_be_only_one' => 'Solo puede haber una instancia de Kohana por cada página.', + 'uncaught_exception' => '%s no capturada: %s en el archivo %s, linea %s', + 'invalid_method' => 'Método inválido %s llamado en %s.', + 'invalid_property' => 'La propiedad %s no existe en la clase %s.', + 'log_dir_unwritable' => 'Tu configuración del &8220;log.directory&8221; no apunta a un directorio con permiso de escritura.', + 'resource_not_found' => 'El fichero de %s con nombre %s, no pudo ser encontrado.', + 'invalid_filetype' => 'El tipo de fichero solicitado, .%s, no esta permitido en la configuración de tus vistas.', + 'view_set_filename' => 'Tienes que definir el nombre de la vista antes de llamar al metodo render', + 'no_default_route' => 'Por favor, especifica la ruta en config/routes.php.', + 'no_controller' => 'Kohana no pudo determinar un controlador para procesar: %s', + 'page_not_found' => 'La página que solicitase, %s, no se encuentra.', + 'stats_footer' => 'Cargado en {execution_time} segundos, usando {memory_usage} de memoria. Generado con Kohana v{kohana_version}.', + 'error_file_line' => '%s [%s]:', + 'stack_trace' => 'Stack Trace', + 'generic_error' => 'Imposible completar la solicitud', + 'errors_disabled' => 'Puedes volver a la página de inico o volver a intentarlo.', - // Drivers - 'driver_implements' => 'El driver %s para la libreria %s debe implementar el interface %s', - 'driver_not_found' => 'No se ha encontrado el driver %s para la libreria %s', + // Drivers + 'driver_implements' => 'El driver %s para la libreria %s debe implementar el interface %s', + 'driver_not_found' => 'No se ha encontrado el driver %s para la libreria %s', - // Resource names - 'config' => 'fichero de configuración', - 'controller' => 'controlador', - 'helper' => 'helper', - 'library' => 'librería', - 'driver' => 'driver', - 'model' => 'modelo', - 'view' => 'vista', + // Resource names + 'config' => 'fichero de configuración', + 'controller' => 'controlador', + 'helper' => 'helper', + 'library' => 'librería', + 'driver' => 'driver', + 'model' => 'modelo', + 'view' => 'vista', ); diff --git a/lib/kohana/system/i18n/es_ES/database.php b/lib/kohana/system/i18n/es_ES/database.php index ebfea71..27e2ea0 100644 --- a/lib/kohana/system/i18n/es_ES/database.php +++ b/lib/kohana/system/i18n/es_ES/database.php @@ -1,15 +1,17 @@ - 'El grupo %s no esta definido en tu configuración.', - 'error' => 'Ocurrió un error de SQL: %s', - 'connection' => 'Ocurrió un error conectando a la base de datos: %s', - 'invalid_dsn' => 'El DSN que pusiste no es válido: %s', - 'must_use_set' => 'Necesitas una clausula SET para tu consulta.', - 'must_use_where' => 'Necesitas una clausula WHERE para tu consulta.', - 'must_use_table' => 'Necesitas especificar la tabla para tu consulta.', - 'table_not_found' => 'La tabla %s no existe en tu base de datos.', - 'not_implemented' => 'El método requerido, %s, no esta soportado por este driver.', - 'result_read_only' => 'Los resultados del query son de solo lectura.' -); \ No newline at end of file + 'undefined_group' => 'El grupo %s no esta definido en tu configuración.', + 'error' => 'Ocurrió un error de SQL: %s', + 'connection' => 'Ocurrió un error conectando a la base de datos: %s', + 'invalid_dsn' => 'El DSN que pusiste no es válido: %s', + 'must_use_set' => 'Necesitas una clausula SET para tu consulta.', + 'must_use_where' => 'Necesitas una clausula WHERE para tu consulta.', + 'must_use_table' => 'Necesitas especificar la tabla para tu consulta.', + 'table_not_found' => 'La tabla %s no existe en tu base de datos.', + 'not_implemented' => 'El método requerido, %s, no esta soportado por este driver.', + 'result_read_only' => 'Los resultados del query son de solo lectura.' +); diff --git a/lib/kohana/system/i18n/es_ES/encrypt.php b/lib/kohana/system/i18n/es_ES/encrypt.php index 80e32c2..5eb5f89 100644 --- a/lib/kohana/system/i18n/es_ES/encrypt.php +++ b/lib/kohana/system/i18n/es_ES/encrypt.php @@ -1,8 +1,10 @@ - 'El grupo %s no esta definidp en la configuración.', - 'requires_mcrypt' => 'Para usar la librería de Encriptación, mcrypt debe estar habilitado.', - 'no_encryption_key' => 'Para usar la librería de Encriptación, tienes que especificar una llave de encriptación en tu archivo de configuración.', + 'undefined_group' => 'El grupo %s no esta definidp en la configuración.', + 'requires_mcrypt' => 'Para usar la librería de Encriptación, mcrypt debe estar habilitado.', + 'no_encryption_key' => 'Para usar la librería de Encriptación, tienes que especificar una llave de encriptación en tu archivo de configuración.', ); diff --git a/lib/kohana/system/i18n/es_ES/errors.php b/lib/kohana/system/i18n/es_ES/errors.php index cc22414..f726c55 100644 --- a/lib/kohana/system/i18n/es_ES/errors.php +++ b/lib/kohana/system/i18n/es_ES/errors.php @@ -1,16 +1,22 @@ - array( 1, 'Error del Framework', 'Revisa la documentación de Kohana para información sobre el siguiente error.'), - E_PAGE_NOT_FOUND => array( 1, 'No se encuentra la página', 'No se encontró la página solicitada. Puede ser que haya sido movida, borrada o archivada.'), - E_DATABASE_ERROR => array( 1, 'Error de Base de Datos', 'Ocurrió un error en la base de datos mientras se ejecutaba el procedimiento requerido. Para más información, revisa el error que aparece más abajo.'), - E_RECOVERABLE_ERROR => array( 1, 'Error Recuperable', 'Se detectó un error que evitó que esta página cargara. Si el problema persiste, contacta con el administrador de la web.'), - E_ERROR => array( 1, 'Error Fatal', ''), - E_USER_ERROR => array( 1, 'Error Fatal', ''), - E_PARSE => array( 1, 'Error de Syntaxis', ''), - E_WARNING => array( 1, 'Advertencia', ''), - E_USER_WARNING => array( 1, 'Advertencia', ''), - E_STRICT => array( 2, 'Strict Mode Error', ''), - E_NOTICE => array( 2, 'Runtime Message', ''), -); \ No newline at end of file + E_KOHANA => array( 1, 'Error del Framework', 'Revisa la documentación de Kohana para información sobre el siguiente error.'), + E_PAGE_NOT_FOUND => array( 1, 'No se encuentra la página', 'No se encontró la página solicitada. Puede ser que haya sido movida, borrada o archivada.'), + E_DATABASE_ERROR => array( 1, 'Error de Base de Datos', + 'Ocurrió un error en la base de datos mientras se ejecutaba el procedimiento requerido.' . + ' Para más información, revisa el error que aparece más abajo.'), + E_RECOVERABLE_ERROR => array( 1, 'Error Recuperable', + 'Se detectó un error que evitó que esta página cargara.' . + ' Si el problema persiste, contacta con el administrador de la web.'), + E_ERROR => array( 1, 'Error Fatal', ''), + E_USER_ERROR => array( 1, 'Error Fatal', ''), + E_PARSE => array( 1, 'Error de Syntaxis', ''), + E_WARNING => array( 1, 'Advertencia', ''), + E_USER_WARNING => array( 1, 'Advertencia', ''), + E_STRICT => array( 2, 'Strict Mode Error', ''), + E_NOTICE => array( 2, 'Runtime Message', ''), +); diff --git a/lib/kohana/system/i18n/es_ES/event.php b/lib/kohana/system/i18n/es_ES/event.php index c990771..8fb5a7d 100644 --- a/lib/kohana/system/i18n/es_ES/event.php +++ b/lib/kohana/system/i18n/es_ES/event.php @@ -1,7 +1,9 @@ - 'Fallo el intento de añadir el sujeto %s a %s. Los sujetos deben extender la clase Event_Subject.', - 'invalid_observer' => 'Fallo el intento de añadir el observador %s a %s. Los observadores deben extender la clase Event_Observer.', + 'invalid_subject' => 'Fallo el intento de añadir el sujeto %s a %s. Los sujetos deben extender la clase Event_Subject.', + 'invalid_observer' => 'Fallo el intento de añadir el observador %s a %s. Los observadores deben extender la clase Event_Observer.', ); diff --git a/lib/kohana/system/i18n/es_ES/image.php b/lib/kohana/system/i18n/es_ES/image.php index 2b8f6a6..1811427 100644 --- a/lib/kohana/system/i18n/es_ES/image.php +++ b/lib/kohana/system/i18n/es_ES/image.php @@ -1,33 +1,35 @@ - 'La librería &8220;Image&8221; requiere la función PHP getimagesize, que no parece estar disponible en tu instalación.', - 'unsupported_method' => 'El driver que has elegido en la configuración no soporta el tipo de transformación %s.', - 'file_not_found' => 'La imagen especificada, %s no se ha encontrado. Por favor, verifica que existe utilizando file_exists() antes de manipularla.', - 'type_not_allowed' => 'El tipo de imagen especificado, %s, no es un tipo de imagen permitido.', - 'invalid_width' => 'El ancho que has especificado, %s, no es valido.', - 'invalid_height' => 'El alto que has especificado, %s, no es valido.', - 'invalid_dimensions' => 'Las dimensiones que has especificado para %s no son validas.', - 'invalid_master' => 'The master dim specified is not valid.', - 'invalid_flip' => 'La dirección de rotación especificada no es valida.', - 'directory_unwritable' => 'El directorio especificado, %s, no tiene permisos de escritura.', + 'getimagesize_missing' => 'La librería &8220;Image&8221; requiere la función PHP getimagesize, que no parece estar disponible en tu instalación.', + 'unsupported_method' => 'El driver que has elegido en la configuración no soporta el tipo de transformación %s.', + 'file_not_found' => 'La imagen especificada, %s no se ha encontrado. Por favor, verifica que existe utilizando file_exists() antes de manipularla.', + 'type_not_allowed' => 'El tipo de imagen especificado, %s, no es un tipo de imagen permitido.', + 'invalid_width' => 'El ancho que has especificado, %s, no es valido.', + 'invalid_height' => 'El alto que has especificado, %s, no es valido.', + 'invalid_dimensions' => 'Las dimensiones que has especificado para %s no son validas.', + 'invalid_master' => 'The master dim specified is not valid.', + 'invalid_flip' => 'La dirección de rotación especificada no es valida.', + 'directory_unwritable' => 'El directorio especificado, %s, no tiene permisos de escritura.', - // ImageMagick specific messages - 'imagemagick' => array - ( - 'not_found' => 'El directorio de ImageMagick especificado, no contiene el programa requerido, %s.', - ), + // ImageMagick specific messages + 'imagemagick' => array + ( + 'not_found' => 'El directorio de ImageMagick especificado, no contiene el programa requerido, %s.', + ), - // GraphicsMagick specific messages - 'graphicsmagick' => array - ( - 'not_found' => 'El directorio de GraphicsMagick especificado, no contiene el programa requerido, %s.', - ), + // GraphicsMagick specific messages + 'graphicsmagick' => array + ( + 'not_found' => 'El directorio de GraphicsMagick especificado, no contiene el programa requerido, %s.', + ), - // GD specific messages - 'gd' => array - ( - 'requires_v2' => 'La librería &8220;Image&8221; requiere GD2. Por favor, lee http://php.net/gd_info para más información.', - ), + // GD specific messages + 'gd' => array + ( + 'requires_v2' => 'La librería &8220;Image&8221; requiere GD2. Por favor, lee http://php.net/gd_info para más información.', + ), ); diff --git a/lib/kohana/system/i18n/es_ES/orm.php b/lib/kohana/system/i18n/es_ES/orm.php index 24070e9..f871f96 100644 --- a/lib/kohana/system/i18n/es_ES/orm.php +++ b/lib/kohana/system/i18n/es_ES/orm.php @@ -1,3 +1,5 @@ - 'El grupo %s no esta definido en la configuracion de la paginacion.', - 'page' => 'página', - 'pages' => 'páginas', - 'item' => 'elemento', - 'items' => 'elementos', - 'of' => 'de', - 'first' => 'primero', - 'last' => 'último', - 'previous' => 'anterior', - 'next' => 'siguiente', + 'undefined_group' => 'El grupo %s no esta definido en la configuracion de la paginacion.', + 'page' => 'página', + 'pages' => 'páginas', + 'item' => 'elemento', + 'items' => 'elementos', + 'of' => 'de', + 'first' => 'primero', + 'last' => 'último', + 'previous' => 'anterior', + 'next' => 'siguiente', ); diff --git a/lib/kohana/system/i18n/es_ES/profiler.php b/lib/kohana/system/i18n/es_ES/profiler.php index 506cf65..82e13ce 100644 --- a/lib/kohana/system/i18n/es_ES/profiler.php +++ b/lib/kohana/system/i18n/es_ES/profiler.php @@ -1,15 +1,17 @@ - 'Benchmarks', - 'post_data' => 'Datos Posteados', - 'no_post' => 'No hay datos posteados', - 'session_data' => 'Datos de sesión', - 'no_session' => 'No hay datos de sesión', - 'queries' => 'Consultas a la base de datos', - 'no_queries' => 'No hay consultas a la base de datos', - 'no_database' => 'No se encuentra la base de datos', - 'cookie_data' => 'Datos de la cookie', - 'no_cookie' => 'No se encuentran los datos de la cookie', + 'benchmarks' => 'Benchmarks', + 'post_data' => 'Datos Posteados', + 'no_post' => 'No hay datos posteados', + 'session_data' => 'Datos de sesión', + 'no_session' => 'No hay datos de sesión', + 'queries' => 'Consultas a la base de datos', + 'no_queries' => 'No hay consultas a la base de datos', + 'no_database' => 'No se encuentra la base de datos', + 'cookie_data' => 'Datos de la cookie', + 'no_cookie' => 'No se encuentran los datos de la cookie', ); diff --git a/lib/kohana/system/i18n/es_ES/session.php b/lib/kohana/system/i18n/es_ES/session.php index 2f503c2..3e2581c 100644 --- a/lib/kohana/system/i18n/es_ES/session.php +++ b/lib/kohana/system/i18n/es_ES/session.php @@ -1,6 +1,9 @@ - 'El parametro session_name, %s, no es valido. Solo debe contener caracteres alfanumericos y guiones bajos. Tambien al menos uno debe de ser una letra.', -); \ No newline at end of file + 'invalid_session_name' => 'El parametro session_name, %s, no es valido.' . + ' Solo debe contener caracteres alfanumericos y guiones bajos. Tambien al menos uno debe de ser una letra.', +); diff --git a/lib/kohana/system/i18n/es_ES/swift.php b/lib/kohana/system/i18n/es_ES/swift.php index 79fa6f4..7136dd3 100644 --- a/lib/kohana/system/i18n/es_ES/swift.php +++ b/lib/kohana/system/i18n/es_ES/swift.php @@ -1,6 +1,8 @@ - 'Ocurrió un error mientras se realizaba el envio del mensaje de correo.', -); \ No newline at end of file + 'general_error' => 'Ocurrió un error mientras se realizaba el envio del mensaje de correo.', +); diff --git a/lib/kohana/system/i18n/es_ES/upload.php b/lib/kohana/system/i18n/es_ES/upload.php index 57bbec4..041fe21 100644 --- a/lib/kohana/system/i18n/es_ES/upload.php +++ b/lib/kohana/system/i18n/es_ES/upload.php @@ -1,6 +1,8 @@ - 'El directorio seleccionado, %s, no tiene permisos de escritura.', -); \ No newline at end of file + 'not_writable' => 'El directorio seleccionado, %s, no tiene permisos de escritura.', +); diff --git a/lib/kohana/system/i18n/es_ES/validation.php b/lib/kohana/system/i18n/es_ES/validation.php index 9cb114a..92afe44 100644 --- a/lib/kohana/system/i18n/es_ES/validation.php +++ b/lib/kohana/system/i18n/es_ES/validation.php @@ -1,41 +1,43 @@ - 'La regla de validación usada es invalida: %s', - 'i18n_array' => 'La clave %s i18n debe de ser un array para ser utilizado en la regla in_lang', - 'not_callable' => 'La llamada de retorno %s utilizada para la validación no puede ser llamada', + // Class errors + 'invalid_rule' => 'La regla de validación usada es invalida: %s', + 'i18n_array' => 'La clave %s i18n debe de ser un array para ser utilizado en la regla in_lang', + 'not_callable' => 'La llamada de retorno %s utilizada para la validación no puede ser llamada', - // General errors - 'unknown_error' => 'Error de validación desconocido al comprobar el campo %s.', - 'required' => 'El campo %s es obligatorio.', - 'min_length' => 'El campo %s debe tener un mínimo de %d caracteres.', - 'max_length' => 'El campo %s debe tener un máximo de %d caracteres.', - 'exact_length' => 'El campo %s debe tener exactamente %d caracteres.', - 'in_array' => 'El campo %s debe ser seleccionado de las opciones listadas.', - 'matches' => 'El campo %s debe conincidir con el campo %s.', - 'valid_url' => 'El campo %s debe contener una url valida, empezando con %s://.', - 'valid_email' => 'El campo %s debe contener una dirección de email valida.', - 'valid_ip' => 'El campo %s debe contener una dirección IP valida.', - 'valid_type' => 'El campo %s debe contener unicamente %s.', - 'range' => 'El campo %s debe estar entre los rangos especificados.', - 'regex' => 'El campo %s no coincide con los datos aceptados.', - 'depends_on' => 'El campo %s depende del campo %s.', + // General errors + 'unknown_error' => 'Error de validación desconocido al comprobar el campo %s.', + 'required' => 'El campo %s es obligatorio.', + 'min_length' => 'El campo %s debe tener un mínimo de %d caracteres.', + 'max_length' => 'El campo %s debe tener un máximo de %d caracteres.', + 'exact_length' => 'El campo %s debe tener exactamente %d caracteres.', + 'in_array' => 'El campo %s debe ser seleccionado de las opciones listadas.', + 'matches' => 'El campo %s debe conincidir con el campo %s.', + 'valid_url' => 'El campo %s debe contener una url valida, empezando con %s://.', + 'valid_email' => 'El campo %s debe contener una dirección de email valida.', + 'valid_ip' => 'El campo %s debe contener una dirección IP valida.', + 'valid_type' => 'El campo %s debe contener unicamente %s.', + 'range' => 'El campo %s debe estar entre los rangos especificados.', + 'regex' => 'El campo %s no coincide con los datos aceptados.', + 'depends_on' => 'El campo %s depende del campo %s.', - // Upload errors - 'user_aborted' => 'El envio del archivo %s fue abortado antes de completarse.', - 'invalid_type' => 'El archivo %s no es un tipo de archivo permitido.', - 'max_size' => 'El archivo %s que estas enviando es muy grande. El tamaño máximo es de %s.', - 'max_width' => 'El archivo %s debe tener como ancho máximo %s, y tiene %spx.', - 'max_height' => 'El archivo %s debe tener como alto máximo %s, y tiene %spx.', - 'min_width' => 'El archivo %s que estas enviando es muy pequeño. El ancho mínimo permitido es de %spx.', - 'min_height' => 'El archivo %s que estas enviando es muy pequeño. El alto mínimo permitido es de %spx.', + // Upload errors + 'user_aborted' => 'El envio del archivo %s fue abortado antes de completarse.', + 'invalid_type' => 'El archivo %s no es un tipo de archivo permitido.', + 'max_size' => 'El archivo %s que estas enviando es muy grande. El tamaño máximo es de %s.', + 'max_width' => 'El archivo %s debe tener como ancho máximo %s, y tiene %spx.', + 'max_height' => 'El archivo %s debe tener como alto máximo %s, y tiene %spx.', + 'min_width' => 'El archivo %s que estas enviando es muy pequeño. El ancho mínimo permitido es de %spx.', + 'min_height' => 'El archivo %s que estas enviando es muy pequeño. El alto mínimo permitido es de %spx.', - // Field types - 'alpha' => 'caracteres del alfabeto', - 'alpha_numeric' => 'caracteres del alfabeto y numericos', - 'alpha_dash' => 'caracteres del alfabeto, guiones y subrayado', - 'digit' => 'digitos', - 'numeric' => 'caracteres numéricos', -); \ No newline at end of file + // Field types + 'alpha' => 'caracteres del alfabeto', + 'alpha_numeric' => 'caracteres del alfabeto y numericos', + 'alpha_dash' => 'caracteres del alfabeto, guiones y subrayado', + 'digit' => 'digitos', + 'numeric' => 'caracteres numéricos', +); diff --git a/lib/kohana/system/i18n/fr_FR/cache.php b/lib/kohana/system/i18n/fr_FR/cache.php index f6ae08d..c4a7863 100644 --- a/lib/kohana/system/i18n/fr_FR/cache.php +++ b/lib/kohana/system/i18n/fr_FR/cache.php @@ -1,10 +1,14 @@ - 'Le groupe %s n\'est pas défini dans votre configuration.', 'extension_not_loaded' => 'l\'extension PHP %s doit être chargée pour utiliser ce driver.', 'unwritable' => 'Le chemin %s configuré pour le cache n\'est pas accessible en écriture.', - 'resources' => 'La mise en cache des ressources est impossible car elles n\'ont pas pu être sérialisées.', - 'driver_error' => '%s' + 'resources' => 'La mise en cache des ressources est impossible car elles n\'ont pas pu être sérialisées.', + 'driver_error' => '%s' ); diff --git a/lib/kohana/system/i18n/fr_FR/calendar.php b/lib/kohana/system/i18n/fr_FR/calendar.php index bf1d52c..c64c3ab 100644 --- a/lib/kohana/system/i18n/fr_FR/calendar.php +++ b/lib/kohana/system/i18n/fr_FR/calendar.php @@ -1,59 +1,63 @@ - 'Di', - 'mo' => 'Lu', - 'tu' => 'Ma', - 'we' => 'Me', - 'th' => 'Je', - 'fr' => 'Ve', - 'sa' => 'Sa', + // Two letter days + 'su' => 'Di', + 'mo' => 'Lu', + 'tu' => 'Ma', + 'we' => 'Me', + 'th' => 'Je', + 'fr' => 'Ve', + 'sa' => 'Sa', - // Short day names - 'sun' => 'Dim', - 'mon' => 'Lun', - 'tue' => 'Mar', - 'wed' => 'Mer', - 'thu' => 'Jeu', - 'fri' => 'Ven', - 'sat' => 'Sam', + // Short day names + 'sun' => 'Dim', + 'mon' => 'Lun', + 'tue' => 'Mar', + 'wed' => 'Mer', + 'thu' => 'Jeu', + 'fri' => 'Ven', + 'sat' => 'Sam', - // Long day names - 'sunday' => 'Dimanche', - 'monday' => 'Lundi', - 'tuesday' => 'Mardi', - 'wednesday' => 'Mercredi', - 'thursday' => 'Jeudi', - 'friday' => 'Vendredi', - 'saturday' => 'Samedi', + // Long day names + 'sunday' => 'Dimanche', + 'monday' => 'Lundi', + 'tuesday' => 'Mardi', + 'wednesday' => 'Mercredi', + 'thursday' => 'Jeudi', + 'friday' => 'Vendredi', + 'saturday' => 'Samedi', - // Short month names - 'jan' => 'Jan', - 'feb' => 'Fév', - 'mar' => 'Mar', - 'apr' => 'Avr', - 'may' => 'Mai', - 'jun' => 'Jui', - 'jul' => 'Juil', - 'aug' => 'Aoû', - 'sep' => 'Sep', - 'oct' => 'Oct', - 'nov' => 'Nov', - 'dec' => 'Déc', + // Short month names + 'jan' => 'Jan', + 'feb' => 'Fév', + 'mar' => 'Mar', + 'apr' => 'Avr', + 'may' => 'Mai', + 'jun' => 'Jui', + 'jul' => 'Juil', + 'aug' => 'Aoû', + 'sep' => 'Sep', + 'oct' => 'Oct', + 'nov' => 'Nov', + 'dec' => 'Déc', - // Long month names - 'january' => 'Janvier', - 'february' => 'Février', - 'march' => 'Mars', - 'april' => 'Avril', - 'mayl' => 'Mai', - 'june' => 'Juin', - 'july' => 'Juillet', - 'august' => 'Août', - 'september' => 'Septembre', - 'october' => 'Octobre', - 'november' => 'Novembre', - 'december' => 'Décembre' -); \ No newline at end of file + // Long month names + 'january' => 'Janvier', + 'february' => 'Février', + 'march' => 'Mars', + 'april' => 'Avril', + 'mayl' => 'Mai', + 'june' => 'Juin', + 'july' => 'Juillet', + 'august' => 'Août', + 'september' => 'Septembre', + 'october' => 'Octobre', + 'november' => 'Novembre', + 'december' => 'Décembre' +); diff --git a/lib/kohana/system/i18n/fr_FR/captcha.php b/lib/kohana/system/i18n/fr_FR/captcha.php index 2b1af29..7ef5fca 100644 --- a/lib/kohana/system/i18n/fr_FR/captcha.php +++ b/lib/kohana/system/i18n/fr_FR/captcha.php @@ -1,33 +1,37 @@ - 'Le fichier spécifié, %s, est introuvable. Merci de vérifier que les fichiers existent, grâce à la fontion file_exists, avant de les utiliser.', 'requires_GD2' => 'La librairie Captcha requiert GD2 avec le support FreeType installé. Voir http://php.net/gd_info pour de plus amples renseignements, merci.', - - // Words of varying length for the Captcha_Word_Driver to pick from - // Note: use only alphanumeric characters - 'words' => array - ( - 'cd', 'tv', 'le', 'il', 'ou', 'an', - 'moi', 'age', 'coq', 'ici', 'bob', 'eau', - 'cake', 'agir', 'bain', 'dodo', 'elle', 'faux', - 'hello', 'monde', 'terre', 'adore', 'baton', 'chats', - 'absent', 'cendre', 'banane', 'cirque', 'violet', 'disque', - 'abricot', 'billets', 'cendres', 'frisson', 'nations', 'respect', - 'accepter', 'batterie', 'collines', 'desserts', 'feuilles', 'sandwich', - 'acheteurs', 'tellement', 'renverser', 'histoires', 'dimanches', 'cinquante', - ), - // Riddles for the Captcha_Riddle_Driver to pick from - // Note: use only alphanumeric characters - 'riddles' => array - ( - array('Détestez-vous le spam? (oui ou non)', 'oui'), - array('Etes vous un robot? (oui ou non)', 'non'), - array('Le feu est... (chaud ou froid)', 'chaud'), - array('La saison après l\'automne est l\'...', 'hiver'), - array('Quel jour est-il?', strftime('%A')), - array('Quel est le mois en cours?', strftime('%B')), - ) + // Words of varying length for the Captcha_Word_Driver to pick from + // Note: use only alphanumeric characters + 'words' => array + ( + 'cd', 'tv', 'le', 'il', 'ou', 'an', + 'moi', 'age', 'coq', 'ici', 'bob', 'eau', + 'cake', 'agir', 'bain', 'dodo', 'elle', 'faux', + 'hello', 'monde', 'terre', 'adore', 'baton', 'chats', + 'absent', 'cendre', 'banane', 'cirque', 'violet', 'disque', + 'abricot', 'billets', 'cendres', 'frisson', 'nations', 'respect', + 'accepter', 'batterie', 'collines', 'desserts', 'feuilles', 'sandwich', + 'acheteurs', 'tellement', 'renverser', 'histoires', 'dimanches', 'cinquante', + ), + + // Riddles for the Captcha_Riddle_Driver to pick from + // Note: use only alphanumeric characters + 'riddles' => array + ( + array('Détestez-vous le spam? (oui ou non)', 'oui'), + array('Etes vous un robot? (oui ou non)', 'non'), + array('Le feu est... (chaud ou froid)', 'chaud'), + array('La saison après l\'automne est l\'...', 'hiver'), + array('Quel jour est-il?', strftime('%A')), + array('Quel est le mois en cours?', strftime('%B')), + ) ); diff --git a/lib/kohana/system/i18n/fr_FR/core.php b/lib/kohana/system/i18n/fr_FR/core.php index 53d88be..fb7ba3e 100644 --- a/lib/kohana/system/i18n/fr_FR/core.php +++ b/lib/kohana/system/i18n/fr_FR/core.php @@ -1,34 +1,38 @@ - 'Il ne peut y avoir qu\'une instance de Kohana par page.', - 'uncaught_exception' => 'Uncaught %s: %s dans le fichier %s à la ligne %s', - 'invalid_method' => 'La méthode %s appelée dans %s est invalide.', - 'invalid_property' => 'La propriété %s n\'existe pas dans la classe %s.', - 'log_dir_unwritable' => 'Le répertoire spécifié dans votre fichier de configuration pour le fichier de log ne pointe pas vers un répertoire accessible en écriture.', - 'resource_not_found' => 'La ressource %s, %s, n\'a pas été trouvée.', - 'invalid_filetype' => 'Le type de ficher demandé, .%s, n\'est pas autorisé dans le fichier de configuration des vues (view configuration file).', - 'view_set_filename' => 'Vous devez renseigner le nom de la vue avant d\'appeller la méthode render', - 'no_default_route' => 'Aucune route par défaut n\a été définie. Veuillez la spécifer dans le fichier config/routes.php.', - 'no_controller' => 'Kohana n\'a pu déterminer aucun controlleur pour effectuer la requête: %s.', - 'page_not_found' => 'La page demandée %s n\'a pu être trouvée.', - 'stats_footer' => 'Chargé en {execution_time} secondes, {memory_usage} de mémoire utilisée. Généré par Kohana v{kohana_version}.', - 'error_file_line' => '%s [%s]:', - 'stack_trace' => 'Stack Trace', - 'generic_error' => 'Impossible de terminer la requête.', - 'errors_disabled' => 'Vous pouvez aller sur la page d\'accueil ou essayer encore.', + 'there_can_be_only_one' => 'Il ne peut y avoir qu\'une instance de Kohana par page.', + 'uncaught_exception' => 'Uncaught %s: %s dans le fichier %s à la ligne %s', + 'invalid_method' => 'La méthode %s appelée dans %s est invalide.', + 'invalid_property' => 'La propriété %s n\'existe pas dans la classe %s.', + 'log_dir_unwritable' => 'Le répertoire spécifié dans votre fichier de configuration pour le fichier de log ne pointe pas vers un répertoire accessible en écriture.', + 'resource_not_found' => 'La ressource %s, %s, n\'a pas été trouvée.', + 'invalid_filetype' => 'Le type de ficher demandé, .%s, n\'est pas autorisé dans le fichier de configuration des vues (view configuration file).', + 'view_set_filename' => 'Vous devez renseigner le nom de la vue avant d\'appeller la méthode render', + 'no_default_route' => 'Aucune route par défaut n\a été définie. Veuillez la spécifer dans le fichier config/routes.php.', + 'no_controller' => 'Kohana n\'a pu déterminer aucun controlleur pour effectuer la requête: %s.', + 'page_not_found' => 'La page demandée %s n\'a pu être trouvée.', + 'stats_footer' => 'Chargé en {execution_time} secondes, {memory_usage} de mémoire utilisée. Généré par Kohana v{kohana_version}.', + 'error_file_line' => '%s [%s]:', + 'stack_trace' => 'Stack Trace', + 'generic_error' => 'Impossible de terminer la requête.', + 'errors_disabled' => 'Vous pouvez aller sur la page d\'accueil ou essayer encore.', - // Drivers - 'driver_implements' => 'Le driver %s de la librairie %s doit implémenter l\'interface %s.', - 'driver_not_found' => 'Le driver %s de la librairie %s est introuvable.', + // Drivers + 'driver_implements' => 'Le driver %s de la librairie %s doit implémenter l\'interface %s.', + 'driver_not_found' => 'Le driver %s de la librairie %s est introuvable.', - // Resource names - 'config' => 'fichier de configuration', - 'controller' => 'contrôleur', - 'helper' => 'helper', - 'library' => 'librairie', - 'driver' => 'driver', - 'model' => 'modèle', - 'view' => 'vue', + // Resource names + 'config' => 'fichier de configuration', + 'controller' => 'contrôleur', + 'helper' => 'helper', + 'library' => 'librairie', + 'driver' => 'driver', + 'model' => 'modèle', + 'view' => 'vue', ); diff --git a/lib/kohana/system/i18n/fr_FR/database.php b/lib/kohana/system/i18n/fr_FR/database.php index 643a4fe..a45bbfe 100644 --- a/lib/kohana/system/i18n/fr_FR/database.php +++ b/lib/kohana/system/i18n/fr_FR/database.php @@ -1,15 +1,19 @@ - 'Le groupe de base de données %s n\'existe pas dans votre fichier de configuration.', - 'error' => 'L\'erreur SQL suivante est survenue: %s', - 'connection' => 'Il y a eu une erreur lors de la connexion à la base de données: %s', - 'invalid_dsn' => 'Le DSN que vous avez spécifié n\'est pas valide: %s', - 'must_use_set' => 'Vous devez spécifier une clause SET pour votre requête.', - 'must_use_where' => 'Vous devez spécifier une clause WHERE pour votre requête.', - 'must_use_table' => 'Vous devez spécifier une table de la base de données pour votre requête.', - 'table_not_found' => 'La table %s n\'existe pas dans votre base de données.', - 'not_implemented' => 'La méthode %s que vous avez appelée n\'est pas supportée par le driver de base de données.', - 'result_read_only' => 'Les résultats de la requête sont en lecture seule.' + 'undefined_group' => 'Le groupe de base de données %s n\'existe pas dans votre fichier de configuration.', + 'error' => 'L\'erreur SQL suivante est survenue: %s', + 'connection' => 'Il y a eu une erreur lors de la connexion à la base de données: %s', + 'invalid_dsn' => 'Le DSN que vous avez spécifié n\'est pas valide: %s', + 'must_use_set' => 'Vous devez spécifier une clause SET pour votre requête.', + 'must_use_where' => 'Vous devez spécifier une clause WHERE pour votre requête.', + 'must_use_table' => 'Vous devez spécifier une table de la base de données pour votre requête.', + 'table_not_found' => 'La table %s n\'existe pas dans votre base de données.', + 'not_implemented' => 'La méthode %s que vous avez appelée n\'est pas supportée par le driver de base de données.', + 'result_read_only' => 'Les résultats de la requête sont en lecture seule.' ); diff --git a/lib/kohana/system/i18n/fr_FR/encrypt.php b/lib/kohana/system/i18n/fr_FR/encrypt.php index 0ca75d5..f03da07 100644 --- a/lib/kohana/system/i18n/fr_FR/encrypt.php +++ b/lib/kohana/system/i18n/fr_FR/encrypt.php @@ -1,8 +1,14 @@ - 'Le groupe %s n\'est pas défini dans votre configuration.', - 'requires_mcrypt' => 'Afin de pouvoir utiliser la librairie de chiffrement (Encrypt library), mcrypt doit être activé dans votre installation PHP.', - 'no_encryption_key' => 'Afin de pouvoir utiliser la librairie de chiffrement (Encrypt library), vous devez définir une clé de chiffrement dans votre fichier de configuration.' + 'undefined_group' => 'Le groupe %s n\'est pas défini dans votre configuration.', + 'requires_mcrypt' => 'Afin de pouvoir utiliser la librairie de chiffrement (Encrypt library),' . + ' mcrypt doit être activé dans votre installation PHP.', + 'no_encryption_key' => 'Afin de pouvoir utiliser la librairie de chiffrement (Encrypt library),' . + ' vous devez définir une clé de chiffrement dans votre fichier de configuration.' ); diff --git a/lib/kohana/system/i18n/fr_FR/errors.php b/lib/kohana/system/i18n/fr_FR/errors.php index 4f4385b..ac18e05 100644 --- a/lib/kohana/system/i18n/fr_FR/errors.php +++ b/lib/kohana/system/i18n/fr_FR/errors.php @@ -1,16 +1,26 @@ - array( 1, 'Framework Error', 'Veuillez vous référer à la documentation de Kohana pour plus d\'informations sur l\'erreur suivante.'), - E_PAGE_NOT_FOUND => array( 1, 'Page Not Found', 'La page demandée n\'a pas été trouvée. Elle a peut-être été déplacée, supprimée, ou archivée.'), - E_DATABASE_ERROR => array( 1, 'Database Error', 'Une erreur de base de données est survenue lors de l\'exécution de la procèdure demandée. Veuillez vous référer à l\'erreur renvoyée ci-dessous pour plus d\'informations.'), - E_RECOVERABLE_ERROR => array( 1, 'Recoverable Error', 'Une erreur a empêché le chargement de la page. Si le problème persiste, veuillez contacter l\'administrateur du site.'), - E_ERROR => array( 1, 'Fatal Error', ''), - E_USER_ERROR => array( 1, 'Fatal Error', ''), - E_PARSE => array( 1, 'Syntax Error', ''), - E_WARNING => array( 1, 'Warning Message', ''), - E_USER_WARNING => array( 1, 'Warning Message', ''), - E_STRICT => array( 2, 'Strict Mode Error', ''), - E_NOTICE => array( 2, 'Runtime Message', ''), + E_KOHANA => array( 1, 'Framework Error', + 'Veuillez vous référer à la documentation de Kohana pour ' . + 'plus d\'informations sur l\'erreur suivante.'), + E_PAGE_NOT_FOUND => array( 1, 'Page Not Found', + 'La page demandée n\'a pas été trouvée. Elle a peut-être été déplacée, supprimée, ou archivée.'), + E_DATABASE_ERROR => array( 1, 'Database Error', + 'Une erreur de base de données est survenue lors de l\'exécution' . + ' de la procèdure demandée. Veuillez vous référer à l\'erreur renvoyée ci-dessous pour plus d\'informations.'), + E_RECOVERABLE_ERROR => array( 1, 'Recoverable Error', 'Une erreur a empêché le chargement de la page.' . + ' Si le problème persiste, veuillez contacter l\'administrateur du site.'), + E_ERROR => array( 1, 'Fatal Error', ''), + E_USER_ERROR => array( 1, 'Fatal Error', ''), + E_PARSE => array( 1, 'Syntax Error', ''), + E_WARNING => array( 1, 'Warning Message', ''), + E_USER_WARNING => array( 1, 'Warning Message', ''), + E_STRICT => array( 2, 'Strict Mode Error', ''), + E_NOTICE => array( 2, 'Runtime Message', ''), ); diff --git a/lib/kohana/system/i18n/fr_FR/event.php b/lib/kohana/system/i18n/fr_FR/event.php index 65dec21..53a235f 100644 --- a/lib/kohana/system/i18n/fr_FR/event.php +++ b/lib/kohana/system/i18n/fr_FR/event.php @@ -1,7 +1,11 @@ - 'Le sujet %s n\'a pas pu peut être attaché à %s. Les sujets doivent étendre la classe Event_Subject.', - 'invalid_observer' => 'L\'observeur %s n\'a pas pu peut être attaché à %s. Les observeurs doivent étendre la classe Event_Observer.', + 'invalid_subject' => 'Le sujet %s n\'a pas pu peut être attaché à %s. Les sujets doivent étendre la classe Event_Subject.', + 'invalid_observer' => 'L\'observeur %s n\'a pas pu peut être attaché à %s. Les observeurs doivent étendre la classe Event_Observer.', ); diff --git a/lib/kohana/system/i18n/fr_FR/image.php b/lib/kohana/system/i18n/fr_FR/image.php index aa1c4ad..d6081e7 100644 --- a/lib/kohana/system/i18n/fr_FR/image.php +++ b/lib/kohana/system/i18n/fr_FR/image.php @@ -1,33 +1,37 @@ - 'Le répertoire %s spécifié n\'est pas accessible en écriture.', - 'getimagesize_missing' => 'La librairie d\'image requiert la function PHP getimagesize. Celle-ci n\'est pas disponible dans votre installation.', - 'unsupported_method' => 'Le pilote configuré ne supporte pas la transformation d\'image %s.', - 'file_not_found' => 'L\'image spécifié %s n\'a pas été trouvée. Merci de vérifier que l\'image existe bien avec la fonction file_exists avant sa manipulation.', - 'type_not_allowed' => 'L\'image spécifié %s n\'est pas d\'un type autorisé.', - 'invalid_width' => 'La largeur que vous avez spécifiée, %s, est invalide.', - 'invalid_height' => 'La hauteur que vous avez spécifiée, %s, est invalide.', - 'invalid_dimensions' => 'Les dimensions spécifiées pour %s ne sont pas valides.', - 'invalid_master' => 'La dimension principale (master dim) n\'est pas valide.', - 'invalid_flip' => 'La direction de rotation spécifiée n\'est pas valide.', + 'getimagesize_missing' => 'La librairie d\'image requiert la function PHP getimagesize. Celle-ci n\'est pas disponible dans votre installation.', + 'unsupported_method' => 'Le pilote configuré ne supporte pas la transformation d\'image %s.', + 'file_not_found' => 'L\'image spécifié %s n\'a pas été trouvée. Merci de vérifier que l\'image existe bien avec la fonction file_exists avant sa manipulation.', + 'type_not_allowed' => 'L\'image spécifié %s n\'est pas d\'un type autorisé.', + 'invalid_width' => 'La largeur que vous avez spécifiée, %s, est invalide.', + 'invalid_height' => 'La hauteur que vous avez spécifiée, %s, est invalide.', + 'invalid_dimensions' => 'Les dimensions spécifiées pour %s ne sont pas valides.', + 'invalid_master' => 'La dimension principale (master dim) n\'est pas valide.', + 'invalid_flip' => 'La direction de rotation spécifiée n\'est pas valide.', - // ImageMagick specific messages - 'imagemagick' => array - ( - 'not_found' => 'Le répertoire ImageMagick spécifié ne contient pas le programme requis %s.', - ), - - // GraphicsMagick specific messages - 'graphicsmagick' => array - ( - 'not_found' => 'Le répertoire GraphicsMagick spécifié ne contient pas le programme requis %s.', - ), - - // GD specific messages - 'gd' => array - ( - 'requires_v2' => 'La librairie d\'image requiert GD2. Veuillez consulter http://php.net/gd_info pour de plus amples informations.', - ), -); \ No newline at end of file + // ImageMagick specific messages + 'imagemagick' => array + ( + 'not_found' => 'Le répertoire ImageMagick spécifié ne contient pas le programme requis %s.', + ), + + // GraphicsMagick specific messages + 'graphicsmagick' => array + ( + 'not_found' => 'Le répertoire GraphicsMagick spécifié ne contient pas le programme requis %s.', + ), + + // GD specific messages + 'gd' => array + ( + 'requires_v2' => 'La librairie d\'image requiert GD2. Veuillez consulter http://php.net/gd_info pour de plus amples informations.', + ), +); diff --git a/lib/kohana/system/i18n/fr_FR/orm.php b/lib/kohana/system/i18n/fr_FR/orm.php index 9c9d234..7c680c5 100644 --- a/lib/kohana/system/i18n/fr_FR/orm.php +++ b/lib/kohana/system/i18n/fr_FR/orm.php @@ -1,3 +1,7 @@ - 'Le groupe %s n\'est pas défini dans votre configuration de la pagination.', - 'page' => 'page', - 'pages' => 'pages', - 'item' => 'résultat', - 'items' => 'résultats', - 'of' => 'sur', - 'first' => 'premier', - 'last' => 'dernier', - 'previous' => 'précédent', - 'next' => 'suivant', + 'undefined_group' => 'Le groupe %s n\'est pas défini dans votre configuration de la pagination.', + 'page' => 'page', + 'pages' => 'pages', + 'item' => 'résultat', + 'items' => 'résultats', + 'of' => 'sur', + 'first' => 'premier', + 'last' => 'dernier', + 'previous' => 'précédent', + 'next' => 'suivant', ); diff --git a/lib/kohana/system/i18n/fr_FR/profiler.php b/lib/kohana/system/i18n/fr_FR/profiler.php index 02a95d1..a3d106c 100644 --- a/lib/kohana/system/i18n/fr_FR/profiler.php +++ b/lib/kohana/system/i18n/fr_FR/profiler.php @@ -1,15 +1,19 @@ - 'Benchmarks', - 'post_data' => 'Données POST', - 'no_post' => 'Aucune donnée POST', - 'session_data' => 'Données de session', - 'no_session' => 'Aucune donnée de session', - 'queries' => 'Requêtes', - 'no_queries' => 'Aucune requête', - 'no_database' => 'Base de données non chargée', - 'cookie_data' => 'Données du Cookie', - 'no_cookie' => 'Aucune donnée de Cookie', -); \ No newline at end of file + 'benchmarks' => 'Benchmarks', + 'post_data' => 'Données POST', + 'no_post' => 'Aucune donnée POST', + 'session_data' => 'Données de session', + 'no_session' => 'Aucune donnée de session', + 'queries' => 'Requêtes', + 'no_queries' => 'Aucune requête', + 'no_database' => 'Base de données non chargée', + 'cookie_data' => 'Données du Cookie', + 'no_cookie' => 'Aucune donnée de Cookie', +); diff --git a/lib/kohana/system/i18n/fr_FR/session.php b/lib/kohana/system/i18n/fr_FR/session.php index 70700a6..789af2f 100644 --- a/lib/kohana/system/i18n/fr_FR/session.php +++ b/lib/kohana/system/i18n/fr_FR/session.php @@ -1,6 +1,11 @@ - 'Le nom de session "session_name", %s, est invalide. Il doit contenir uniquement des caractères alphanumériques et au moins une lettre doit être présente.', + 'invalid_session_name' => 'Le nom de session "session_name", %s, est invalide.' . + ' Il doit contenir uniquement des caractères alphanumériques et au moins une lettre doit être présente.', ); diff --git a/lib/kohana/system/i18n/fr_FR/swift.php b/lib/kohana/system/i18n/fr_FR/swift.php index 5f31f9d..e012791 100644 --- a/lib/kohana/system/i18n/fr_FR/swift.php +++ b/lib/kohana/system/i18n/fr_FR/swift.php @@ -1,6 +1,10 @@ - 'Une erreur est survenue lors de l\'envoi du message.' + 'general_error' => 'Une erreur est survenue lors de l\'envoi du message.' ); diff --git a/lib/kohana/system/i18n/fr_FR/upload.php b/lib/kohana/system/i18n/fr_FR/upload.php index 3cace0e..2eab14a 100644 --- a/lib/kohana/system/i18n/fr_FR/upload.php +++ b/lib/kohana/system/i18n/fr_FR/upload.php @@ -1,4 +1,8 @@ - 'La règle de validation %s utilisée est invalide', - 'i18n_array' => 'La clé i18n %s doit être un tableau pour pouvoir être utilisée avec la règle in_lang', + // Class errors + 'invalid_rule' => 'La règle de validation %s utilisée est invalide', + 'i18n_array' => 'La clé i18n %s doit être un tableau pour pouvoir être utilisée avec la règle in_lang', 'not_callable' => 'La callback %s utilisé pour la Validation n\'est pas appellable', - // General errors - 'unknown_error' => 'Erreur de validation inconnue lors de la validation du champ %s.', - 'required' => 'Le champ %s est requis.', - 'min_length' => 'Le champ %s doit contenir au minimum %d caractères.', - 'max_length' => 'Le champ %s ne peut contenir plus de %d caractères.', - 'exact_length' => 'Le champ %s doit contenir exactement %d caractères.', - 'in_array' => 'Le champ %s doit être sélectionné dans parmi les options listées.', - 'matches' => 'Le champ %s doit correspondre au champ %s.', - 'valid_url' => 'Le champ %s doit contenir une URL valide.', - 'valid_email' => 'Le champ %s doit contenir une adresse email valide.', - 'valid_ip' => 'Le champ %s doit contenir une adresse IP valide.', - 'valid_type' => 'Le champ %s doit contenir uniquement %s caractères', - 'range' => 'Le champ %s doit être situé dans la plage de valeurs spécifiée.', - 'regex' => 'Le champ %s ne correspond pas aux valeurs acceptées.', - 'depends_on' => 'Le champ %s est dépendant du champ %s.', + // General errors + 'unknown_error' => 'Erreur de validation inconnue lors de la validation du champ %s.', + 'required' => 'Le champ %s est requis.', + 'min_length' => 'Le champ %s doit contenir au minimum %d caractères.', + 'max_length' => 'Le champ %s ne peut contenir plus de %d caractères.', + 'exact_length' => 'Le champ %s doit contenir exactement %d caractères.', + 'in_array' => 'Le champ %s doit être sélectionné dans parmi les options listées.', + 'matches' => 'Le champ %s doit correspondre au champ %s.', + 'valid_url' => 'Le champ %s doit contenir une URL valide.', + 'valid_email' => 'Le champ %s doit contenir une adresse email valide.', + 'valid_ip' => 'Le champ %s doit contenir une adresse IP valide.', + 'valid_type' => 'Le champ %s doit contenir uniquement %s caractères', + 'range' => 'Le champ %s doit être situé dans la plage de valeurs spécifiée.', + 'regex' => 'Le champ %s ne correspond pas aux valeurs acceptées.', + 'depends_on' => 'Le champ %s est dépendant du champ %s.', - // Upload errors - 'user_aborted' => 'L\'envoi du fichier %s sur le serveur a échoué.', - 'invalid_type' => 'Le type du fichier %s n\'est pas autorisé.', - 'max_size' => 'La taille du fichier %s que vous tentez d\'envoyer est trop volumineuse. La taille maximale autorisée est de %s', - 'max_width' => 'La largeur de l\'image %s que vous envoyez est trop grande. La largeur maximale autorisée est de %spx', - 'max_height' => 'La hauteur de l\'image %s que vous envoyez est trop grande. La hauteur maximale autorisée est de %spx', - 'min_width' => 'La largeur de l\'image %s que vous envoyez n\'est pas assez grande. La largeur minimale demandée est de %spx', - 'min_height' => 'La hauteur de l\'image %s que vous envoyez n\'est pas assez grande. La hauteur minimale demandée est de %spx', + // Upload errors + 'user_aborted' => 'L\'envoi du fichier %s sur le serveur a échoué.', + 'invalid_type' => 'Le type du fichier %s n\'est pas autorisé.', + 'max_size' => 'La taille du fichier %s que vous tentez d\'envoyer est trop volumineuse. La taille maximale autorisée est de %s', + 'max_width' => 'La largeur de l\'image %s que vous envoyez est trop grande. La largeur maximale autorisée est de %spx', + 'max_height' => 'La hauteur de l\'image %s que vous envoyez est trop grande. La hauteur maximale autorisée est de %spx', + 'min_width' => 'La largeur de l\'image %s que vous envoyez n\'est pas assez grande. La largeur minimale demandée est de %spx', + 'min_height' => 'La hauteur de l\'image %s que vous envoyez n\'est pas assez grande. La hauteur minimale demandée est de %spx', - // Field types - 'alpha' => 'alphabétiques', - 'alpha_numeric' => 'alphabétiques et numériques', - 'alpha_dash' => 'alphabétiques, tirets haut ou tirets bas (underscore)', - 'digit' => 'digitaux', - 'numeric' => 'numériques', -); \ No newline at end of file + // Field types + 'alpha' => 'alphabétiques', + 'alpha_numeric' => 'alphabétiques et numériques', + 'alpha_dash' => 'alphabétiques, tirets haut ou tirets bas (underscore)', + 'digit' => 'digitaux', + 'numeric' => 'numériques', +); diff --git a/lib/kohana/system/i18n/it_IT/cache.php b/lib/kohana/system/i18n/it_IT/cache.php index c2e9687..5557b48 100644 --- a/lib/kohana/system/i18n/it_IT/cache.php +++ b/lib/kohana/system/i18n/it_IT/cache.php @@ -1,10 +1,14 @@ - 'Il gruppo %s non è stato definito in configurazione.', - 'extension_not_loaded' => 'L\'estensione di PHP %s deve essere caricata per poter usare questo driver.', - 'unwritable' => 'La cartella di deposito, %s, non ha i permessi in scrittura.', - 'resources' => 'Risorsa non serializzabile. Impossibile immagazzinare.', - 'driver_error' => '%s', -); \ No newline at end of file + 'undefined_group' => 'Il gruppo %s non è stato definito in configurazione.', + 'extension_not_loaded' => 'L\'estensione di PHP %s deve essere caricata per poter usare questo driver.', + 'unwritable' => 'La cartella di deposito, %s, non ha i permessi in scrittura.', + 'resources' => 'Risorsa non serializzabile. Impossibile immagazzinare.', + 'driver_error' => '%s', +); diff --git a/lib/kohana/system/i18n/it_IT/calendar.php b/lib/kohana/system/i18n/it_IT/calendar.php index 98e61dd..405f112 100644 --- a/lib/kohana/system/i18n/it_IT/calendar.php +++ b/lib/kohana/system/i18n/it_IT/calendar.php @@ -1,59 +1,63 @@ - 'Do', - 'mo' => 'Lu', - 'tu' => 'Ma', - 'we' => 'Me', - 'th' => 'Gi', - 'fr' => 'Ve', - 'sa' => 'Sa', + // Two letter days + 'su' => 'Do', + 'mo' => 'Lu', + 'tu' => 'Ma', + 'we' => 'Me', + 'th' => 'Gi', + 'fr' => 'Ve', + 'sa' => 'Sa', - // Short day names - 'sun' => 'Dom', - 'mon' => 'Lun', - 'tue' => 'Mar', - 'wed' => 'Mer', - 'thu' => 'Gio', - 'fri' => 'Ven', - 'sat' => 'Sab', + // Short day names + 'sun' => 'Dom', + 'mon' => 'Lun', + 'tue' => 'Mar', + 'wed' => 'Mer', + 'thu' => 'Gio', + 'fri' => 'Ven', + 'sat' => 'Sab', - // Long day names - 'sunday' => 'Domenica', - 'monday' => 'Lunedì', - 'tuesday' => 'Martedì', - 'wednesday' => 'Mercoledì', - 'thursday' => 'Giovedì', - 'friday' => 'Venerdì', - 'saturday' => 'Sabato', + // Long day names + 'sunday' => 'Domenica', + 'monday' => 'Lunedì', + 'tuesday' => 'Martedì', + 'wednesday' => 'Mercoledì', + 'thursday' => 'Giovedì', + 'friday' => 'Venerdì', + 'saturday' => 'Sabato', - // Short month names - 'jan' => 'Gen', - 'feb' => 'Feb', - 'mar' => 'Mar', - 'apr' => 'Apr', - 'may' => 'Mag', - 'jun' => 'Giu', - 'jul' => 'Lug', - 'aug' => 'Ago', - 'sep' => 'Set', - 'oct' => 'Ott', - 'nov' => 'Nov', - 'dec' => 'Dic', + // Short month names + 'jan' => 'Gen', + 'feb' => 'Feb', + 'mar' => 'Mar', + 'apr' => 'Apr', + 'may' => 'Mag', + 'jun' => 'Giu', + 'jul' => 'Lug', + 'aug' => 'Ago', + 'sep' => 'Set', + 'oct' => 'Ott', + 'nov' => 'Nov', + 'dec' => 'Dic', - // Long month names - 'january' => 'Gennaio', - 'february' => 'Febbraio', - 'march' => 'Marzo', - 'april' => 'Aprile', - 'mayl' => 'Maggio', - 'june' => 'Giugno', - 'july' => 'Luglio', - 'august' => 'Agosto', - 'september' => 'Settembre', - 'october' => 'Ottobre', - 'november' => 'Novembre', - 'december' => 'Dicembre' -); \ No newline at end of file + // Long month names + 'january' => 'Gennaio', + 'february' => 'Febbraio', + 'march' => 'Marzo', + 'april' => 'Aprile', + 'mayl' => 'Maggio', + 'june' => 'Giugno', + 'july' => 'Luglio', + 'august' => 'Agosto', + 'september' => 'Settembre', + 'october' => 'Ottobre', + 'november' => 'Novembre', + 'december' => 'Dicembre' +); diff --git a/lib/kohana/system/i18n/it_IT/captcha.php b/lib/kohana/system/i18n/it_IT/captcha.php index 57faa35..f976479 100644 --- a/lib/kohana/system/i18n/it_IT/captcha.php +++ b/lib/kohana/system/i18n/it_IT/captcha.php @@ -1,33 +1,37 @@ - 'Il file specificato, %s, non è stato trovato. Verificarne l\'esistenza con file_exists prima di usarlo.', - 'requires_GD2' => 'La libreria Captcha richiede GD2 con supporto FreeType. Leggere http://php.net/gd_info per maggiori informazioni.', + 'file_not_found' => 'Il file specificato, %s, non è stato trovato. Verificarne l\'esistenza con file_exists prima di usarlo.', + 'requires_GD2' => 'La libreria Captcha richiede GD2 con supporto FreeType. Leggere http://php.net/gd_info per maggiori informazioni.', - // Words of varying length for the Captcha_Word_Driver to pick from - // Note: use only alphanumeric characters - 'words' => array - ( - 'cd', 'tv', 'it', 'to', 'be', 'or', - 'sun', 'car', 'dog', 'bed', 'kid', 'egg', - 'bike', 'tree', 'bath', 'roof', 'road', 'hair', - 'hello', 'world', 'earth', 'beard', 'chess', 'water', - 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', - 'america', 'release', 'playing', 'working', 'foreign', 'general', - 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', - 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', - ), + // Words of varying length for the Captcha_Word_Driver to pick from + // Note: use only alphanumeric characters + 'words' => array + ( + 'cd', 'tv', 'it', 'to', 'be', 'or', + 'sun', 'car', 'dog', 'bed', 'kid', 'egg', + 'bike', 'tree', 'bath', 'roof', 'road', 'hair', + 'hello', 'world', 'earth', 'beard', 'chess', 'water', + 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', + 'america', 'release', 'playing', 'working', 'foreign', 'general', + 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', + 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', + ), - // Riddles for the Captcha_Riddle_Driver to pick from - // Note: use only alphanumeric characters - 'riddles' => array - ( - array('Detesti lo spam? (si o no)', 'si'), - array('Sei un robot? (si o no)', 'no'), - array('Il fuoco è... (caldo o freddo)', 'caldo'), - array('La stagione che viene dopo l\'autunno è...', 'inverno'), - array('Che giorno della settimana è oggi?', strftime('%A')), - array('In quale mese dell\'anno siamo?', strftime('%B')), - ), + // Riddles for the Captcha_Riddle_Driver to pick from + // Note: use only alphanumeric characters + 'riddles' => array + ( + array('Detesti lo spam? (si o no)', 'si'), + array('Sei un robot? (si o no)', 'no'), + array('Il fuoco è... (caldo o freddo)', 'caldo'), + array('La stagione che viene dopo l\'autunno è...', 'inverno'), + array('Che giorno della settimana è oggi?', strftime('%A')), + array('In quale mese dell\'anno siamo?', strftime('%B')), + ), ); diff --git a/lib/kohana/system/i18n/it_IT/core.php b/lib/kohana/system/i18n/it_IT/core.php index 662092d..2b1f5f3 100644 --- a/lib/kohana/system/i18n/it_IT/core.php +++ b/lib/kohana/system/i18n/it_IT/core.php @@ -1,34 +1,38 @@ - 'Ci può essere una sola istanza di Kohana per ogni pagina richiesta.', - 'uncaught_exception' => 'Uncaught %s: %s in %s, linea %s', - 'invalid_method' => 'Metodo non valido %s chiamato in %s.', - 'invalid_property' => 'La proprietà %s non esiste nella classe %s.', - 'log_dir_unwritable' => 'Il parametro di configurazione log.directory non punta ad una cartella con permesso di scrittura.', - 'resource_not_found' => 'Il %s richiesto, %s, non è stato trovato.', - 'invalid_filetype' => 'Il tipo di file richiesto, .%s, non è presente nel file di configurazione.', - 'view_set_filename' => 'Bisogna definire il nome di una vista prima di chiamare il metodo render', - 'no_default_route' => 'Non è stato definito il default route in config/routes.php.', - 'no_controller' => 'Kohana non è in grado di determinare a quale controller inoltrare la richiesta: %s', - 'page_not_found' => 'La pagina richiesta, %s, non è stata trovata.', - 'stats_footer' => 'Caricato in {execution_time} secondi, usando {memory_usage} di memoria. Generato da Kohana v{kohana_version}.', - 'error_file_line' => 'Errore in %s linea: %s.', - 'stack_trace' => 'Tracciato', - 'generic_error' => 'Impossibile completare la richiesta', - 'errors_disabled' => 'Puoi andare alla pagina iniziale o ritentare.', + 'there_can_be_only_one' => 'Ci può essere una sola istanza di Kohana per ogni pagina richiesta.', + 'uncaught_exception' => 'Uncaught %s: %s in %s, linea %s', + 'invalid_method' => 'Metodo non valido %s chiamato in %s.', + 'invalid_property' => 'La proprietà %s non esiste nella classe %s.', + 'log_dir_unwritable' => 'Il parametro di configurazione log.directory non punta ad una cartella con permesso di scrittura.', + 'resource_not_found' => 'Il %s richiesto, %s, non è stato trovato.', + 'invalid_filetype' => 'Il tipo di file richiesto, .%s, non è presente nel file di configurazione.', + 'view_set_filename' => 'Bisogna definire il nome di una vista prima di chiamare il metodo render', + 'no_default_route' => 'Non è stato definito il default route in config/routes.php.', + 'no_controller' => 'Kohana non è in grado di determinare a quale controller inoltrare la richiesta: %s', + 'page_not_found' => 'La pagina richiesta, %s, non è stata trovata.', + 'stats_footer' => 'Caricato in {execution_time} secondi, usando {memory_usage} di memoria. Generato da Kohana v{kohana_version}.', + 'error_file_line' => 'Errore in %s linea: %s.', + 'stack_trace' => 'Tracciato', + 'generic_error' => 'Impossibile completare la richiesta', + 'errors_disabled' => 'Puoi andare alla pagina iniziale o ritentare.', - // Drivers - 'driver_implements' => 'Il driver %s per la libreria %s non implementa l\'interfaccia %s', - 'driver_not_found' => 'Il driver %s per la libreria %s non è stato trovato', - - // Resource names - 'config' => 'file di configurazione', - 'controller' => 'controller', - 'helper' => 'helper', - 'library' => 'libreria', - 'driver' => 'driver', - 'model' => 'modello', - 'view' => 'vista', + // Drivers + 'driver_implements' => 'Il driver %s per la libreria %s non implementa l\'interfaccia %s', + 'driver_not_found' => 'Il driver %s per la libreria %s non è stato trovato', + + // Resource names + 'config' => 'file di configurazione', + 'controller' => 'controller', + 'helper' => 'helper', + 'library' => 'libreria', + 'driver' => 'driver', + 'model' => 'modello', + 'view' => 'vista', ); diff --git a/lib/kohana/system/i18n/it_IT/database.php b/lib/kohana/system/i18n/it_IT/database.php index acd77ad..2207ae4 100644 --- a/lib/kohana/system/i18n/it_IT/database.php +++ b/lib/kohana/system/i18n/it_IT/database.php @@ -1,15 +1,19 @@ - 'Il gruppo %s non è stato definito nel file di configurazione.', - 'error' => 'Si è verificato un errore SQL: %s', - 'connection' => 'Si è verificato un errore durante la connessione al database: %s', - 'invalid_dsn' => 'Il DSN fornito non è valido: %s', - 'must_use_set' => 'È necessario definire una clausola SET per la query.', - 'must_use_where' => 'È necessario definire una clausola WHERE per la query.', - 'must_use_table' => 'È necessario definire una tabella per la query.', - 'table_not_found' => 'La tabella %s non esiste nella base di dati.', - 'not_implemented' => 'Il metodo chiamato, %s, non è supportato da questo driver.', - 'result_read_only' => 'Il risultato della query è in sola lettura.', -); \ No newline at end of file + 'undefined_group' => 'Il gruppo %s non è stato definito nel file di configurazione.', + 'error' => 'Si è verificato un errore SQL: %s', + 'connection' => 'Si è verificato un errore durante la connessione al database: %s', + 'invalid_dsn' => 'Il DSN fornito non è valido: %s', + 'must_use_set' => 'È necessario definire una clausola SET per la query.', + 'must_use_where' => 'È necessario definire una clausola WHERE per la query.', + 'must_use_table' => 'È necessario definire una tabella per la query.', + 'table_not_found' => 'La tabella %s non esiste nella base di dati.', + 'not_implemented' => 'Il metodo chiamato, %s, non è supportato da questo driver.', + 'result_read_only' => 'Il risultato della query è in sola lettura.', +); diff --git a/lib/kohana/system/i18n/it_IT/encrypt.php b/lib/kohana/system/i18n/it_IT/encrypt.php index 8f2b63d..2d39333 100644 --- a/lib/kohana/system/i18n/it_IT/encrypt.php +++ b/lib/kohana/system/i18n/it_IT/encrypt.php @@ -1,8 +1,12 @@ - 'Il gruppo %s non è definito nel file di configurazione.', - 'requires_mcrypt' => 'L\'uso della libreria Encrypt richiede l\'abilitazione di mcrypt.', - 'no_encryption_key' => 'Per usare la libreria Encrypt bisogna definire una chiave di codifica nel file di configurazione.' + 'undefined_group' => 'Il gruppo %s non è definito nel file di configurazione.', + 'requires_mcrypt' => 'L\'uso della libreria Encrypt richiede l\'abilitazione di mcrypt.', + 'no_encryption_key' => 'Per usare la libreria Encrypt bisogna definire una chiave di codifica nel file di configurazione.' ); diff --git a/lib/kohana/system/i18n/it_IT/errors.php b/lib/kohana/system/i18n/it_IT/errors.php index 1df3e7a..c19a2e1 100644 --- a/lib/kohana/system/i18n/it_IT/errors.php +++ b/lib/kohana/system/i18n/it_IT/errors.php @@ -1,16 +1,26 @@ - array( 1, 'Errore del Framework', 'Controlla la documentazione di Kohana per informazioni circa il seguente errore.'), - E_PAGE_NOT_FOUND => array( 1, 'Pagina non trovata', 'La pagina richiesta non è stata trovata. Potrebbe essere stata spostata, rimossa o archiviata.'), - E_DATABASE_ERROR => array( 1, 'Errore del Database', 'Si è verificato un errore durante l\'esecuzione della procedura richiesta. Per maggiori informazioni fare riferimento al messaggio sottostante.'), - E_RECOVERABLE_ERROR => array( 1, 'Errore Recuperabile', 'Un errore ha impedito il caricamento della pagina. Se l\'errore persiste contattare l\'amministratore del sito.'), - E_ERROR => array( 1, 'Errore Fatale', ''), - E_USER_ERROR => array( 1, 'Errore Fatale', ''), - E_PARSE => array( 1, 'Errore di Sintassi', ''), - E_WARNING => array( 1, 'Avviso', ''), - E_USER_WARNING => array( 1, 'Avviso', ''), - E_STRICT => array( 2, 'Strict Mode Error', ''), - E_NOTICE => array( 2, 'Runtime Message', ''), -); \ No newline at end of file + E_KOHANA => array( 1, 'Errore del Framework', + 'Controlla la documentazione di Kohana per informazioni circa il seguente errore.'), + E_PAGE_NOT_FOUND => array( 1, 'Pagina non trovata', + 'La pagina richiesta non è stata trovata. Potrebbe essere stata spostata, rimossa o archiviata.'), + E_DATABASE_ERROR => array( 1, 'Errore del Database', + 'Si è verificato un errore durante l\'esecuzione della procedura richiesta.' . + ' Per maggiori informazioni fare riferimento al messaggio sottostante.'), + E_RECOVERABLE_ERROR => array( 1, 'Errore Recuperabile', + 'Un errore ha impedito il caricamento della pagina.' . + ' Se l\'errore persiste contattare l\'amministratore del sito.'), + E_ERROR => array( 1, 'Errore Fatale', ''), + E_USER_ERROR => array( 1, 'Errore Fatale', ''), + E_PARSE => array( 1, 'Errore di Sintassi', ''), + E_WARNING => array( 1, 'Avviso', ''), + E_USER_WARNING => array( 1, 'Avviso', ''), + E_STRICT => array( 2, 'Strict Mode Error', ''), + E_NOTICE => array( 2, 'Runtime Message', ''), +); diff --git a/lib/kohana/system/i18n/it_IT/event.php b/lib/kohana/system/i18n/it_IT/event.php index 13c5374..062cf0f 100644 --- a/lib/kohana/system/i18n/it_IT/event.php +++ b/lib/kohana/system/i18n/it_IT/event.php @@ -1,7 +1,11 @@ - 'Fallito il tentativo di aggiungere il soggetto %s a %s. I soggetti devono estendere la classe Event_Subject.', - 'invalid_observer' => 'Fallito il tentativo di aggiungere l\'observer %s a %s. Gli observer devono estendere la classe Event_Observer.', + 'invalid_subject' => 'Fallito il tentativo di aggiungere il soggetto %s a %s. I soggetti devono estendere la classe Event_Subject.', + 'invalid_observer' => 'Fallito il tentativo di aggiungere l\'observer %s a %s. Gli observer devono estendere la classe Event_Observer.', ); diff --git a/lib/kohana/system/i18n/it_IT/image.php b/lib/kohana/system/i18n/it_IT/image.php index 493b027..1c7bf28 100644 --- a/lib/kohana/system/i18n/it_IT/image.php +++ b/lib/kohana/system/i18n/it_IT/image.php @@ -1,33 +1,37 @@ - 'La libreria Image richiede la funzione PHP getimagesize, che non è disponibile nella tua intallazione.', - 'unsupported_method' => 'Il driver impostato in configurazione non supporta il tipo di trasformazione %s.', - 'file_not_found' => 'L\'immagine specificata, %s, non è stata trovata. Verificarne l\'esistenza con file_exists prima di manipolarla.', - 'type_not_allowed' => 'Il tipo d\'immagine specificato, %s, non è permesso.', - 'invalid_width' => 'La larghezza specificata, %s, non è valida.', - 'invalid_height' => 'L\'altezza specificata, %s, non è valida.', - 'invalid_dimensions' => 'Le dimensioni specificate per %s non sono valide.', - 'invalid_master' => 'Master dimension specificato non valido.', - 'invalid_flip' => 'La direzione di rotazione specificata non è valida.', - 'directory_unwritable' => 'La directory specificata, %s, non consente la scrittura.', + 'getimagesize_missing' => 'La libreria Image richiede la funzione PHP getimagesize, che non è disponibile nella tua intallazione.', + 'unsupported_method' => 'Il driver impostato in configurazione non supporta il tipo di trasformazione %s.', + 'file_not_found' => 'L\'immagine specificata, %s, non è stata trovata. Verificarne l\'esistenza con file_exists prima di manipolarla.', + 'type_not_allowed' => 'Il tipo d\'immagine specificato, %s, non è permesso.', + 'invalid_width' => 'La larghezza specificata, %s, non è valida.', + 'invalid_height' => 'L\'altezza specificata, %s, non è valida.', + 'invalid_dimensions' => 'Le dimensioni specificate per %s non sono valide.', + 'invalid_master' => 'Master dimension specificato non valido.', + 'invalid_flip' => 'La direzione di rotazione specificata non è valida.', + 'directory_unwritable' => 'La directory specificata, %s, non consente la scrittura.', - // Messaggi specifici per ImageMagick - 'imagemagick' => array - ( - 'not_found' => 'La cartella di ImageMagick specificata non contiene il programma richiesto, %s.', - ), + // Messaggi specifici per ImageMagick + 'imagemagick' => array + ( + 'not_found' => 'La cartella di ImageMagick specificata non contiene il programma richiesto, %s.', + ), - // Messaggi specifici per GraphicsMagick - 'graphicsmagick' => array - ( - 'not_found' => 'La cartella di GraphicsMagick specificata non contiene il programma richiesto, %s.', - ), + // Messaggi specifici per GraphicsMagick + 'graphicsmagick' => array + ( + 'not_found' => 'La cartella di GraphicsMagick specificata non contiene il programma richiesto, %s.', + ), - // Messaggi specifici per GD - 'gd' => array - ( - 'requires_v2' => 'La libreria Image richiede GD2. Leggere http://php.net/gd_info per maggiori informazioni.', - ), + // Messaggi specifici per GD + 'gd' => array + ( + 'requires_v2' => 'La libreria Image richiede GD2. Leggere http://php.net/gd_info per maggiori informazioni.', + ), ); diff --git a/lib/kohana/system/i18n/it_IT/orm.php b/lib/kohana/system/i18n/it_IT/orm.php index 09e3a79..22c6740 100644 --- a/lib/kohana/system/i18n/it_IT/orm.php +++ b/lib/kohana/system/i18n/it_IT/orm.php @@ -1,3 +1,7 @@ - 'Il gruppo %s non è stato definito nel file di configurazione per la paginazione.', - 'page' => 'pagina', - 'pages' => 'pagine', - 'item' => 'elemento', - 'items' => 'elementi', - 'of' => 'di', - 'first' => 'primo', - 'last' => 'ultimo', - 'previous' => 'precedente', - 'next' => 'successivo', + 'undefined_group' => 'Il gruppo %s non è stato definito nel file di configurazione per la paginazione.', + 'page' => 'pagina', + 'pages' => 'pagine', + 'item' => 'elemento', + 'items' => 'elementi', + 'of' => 'di', + 'first' => 'primo', + 'last' => 'ultimo', + 'previous' => 'precedente', + 'next' => 'successivo', ); diff --git a/lib/kohana/system/i18n/it_IT/profiler.php b/lib/kohana/system/i18n/it_IT/profiler.php index 5cdd502..43fe888 100644 --- a/lib/kohana/system/i18n/it_IT/profiler.php +++ b/lib/kohana/system/i18n/it_IT/profiler.php @@ -1,15 +1,19 @@ - 'Benchmarks', - 'post_data' => 'Dati postati', - 'no_post' => 'Non ci sono dati postati', - 'session_data' => 'Dati di sessione', - 'no_session' => 'Non ci sono dati di sessione', - 'queries' => 'Query al database', - 'no_queries' => 'Non ci sono query al database', - 'no_database' => 'Database non caricato', - 'cookie_data' => 'Dati del cookie', - 'no_cookie' => 'I dati del cookie non sono stati trovati', + 'benchmarks' => 'Benchmarks', + 'post_data' => 'Dati postati', + 'no_post' => 'Non ci sono dati postati', + 'session_data' => 'Dati di sessione', + 'no_session' => 'Non ci sono dati di sessione', + 'queries' => 'Query al database', + 'no_queries' => 'Non ci sono query al database', + 'no_database' => 'Database non caricato', + 'cookie_data' => 'Dati del cookie', + 'no_cookie' => 'I dati del cookie non sono stati trovati', ); diff --git a/lib/kohana/system/i18n/it_IT/session.php b/lib/kohana/system/i18n/it_IT/session.php index d831894..bb1cb17 100644 --- a/lib/kohana/system/i18n/it_IT/session.php +++ b/lib/kohana/system/i18n/it_IT/session.php @@ -1,6 +1,12 @@ - 'Il parametro session_name, %s, non è valido. Può contenere solo caratteri alfanumerici o il trattino basso. Almeno una lettera deve essere presente.', + 'invalid_session_name' => 'Il parametro session_name, %s, non è valido.' . + ' Può contenere solo caratteri alfanumerici o il trattino basso.' . + ' Almeno una lettera deve essere presente.', ); diff --git a/lib/kohana/system/i18n/it_IT/swift.php b/lib/kohana/system/i18n/it_IT/swift.php index 9f83b40..fa0709d 100644 --- a/lib/kohana/system/i18n/it_IT/swift.php +++ b/lib/kohana/system/i18n/it_IT/swift.php @@ -1,6 +1,10 @@ - 'Si è verificato un errore durante l\'invio del messaggio di posta elettronica.' -); \ No newline at end of file + 'general_error' => 'Si è verificato un errore durante l\'invio del messaggio di posta elettronica.' +); diff --git a/lib/kohana/system/i18n/it_IT/upload.php b/lib/kohana/system/i18n/it_IT/upload.php index 9ea084f..881a618 100644 --- a/lib/kohana/system/i18n/it_IT/upload.php +++ b/lib/kohana/system/i18n/it_IT/upload.php @@ -1,6 +1,10 @@ - 'La cartella di destinazione, %s, non sembra avere i permessi in scrittura.', + 'not_writable' => 'La cartella di destinazione, %s, non sembra avere i permessi in scrittura.', ); diff --git a/lib/kohana/system/i18n/it_IT/validation.php b/lib/kohana/system/i18n/it_IT/validation.php index 472a2e5..2a35b4e 100644 --- a/lib/kohana/system/i18n/it_IT/validation.php +++ b/lib/kohana/system/i18n/it_IT/validation.php @@ -1,41 +1,45 @@ - 'Regola di validazione usata non valida: %s', - 'i18n_array' => 'Il parametro i18n %s deve essere un array per essere utilizzato con la regola in_lang', - 'not_callable' => 'La callback %s usata per la Validation non puo essere richiamata', + // Errori della classe + 'invalid_rule' => 'Regola di validazione usata non valida: %s', + 'i18n_array' => 'Il parametro i18n %s deve essere un array per essere utilizzato con la regola in_lang', + 'not_callable' => 'La callback %s usata per la Validation non puo essere richiamata', - // Errori generici - 'unknown_error' => 'Errore sconosciuto durante la validazione del campo %s.', - 'required' => 'Il campo %s è obbligatorio.', - 'min_length' => 'Il campo %s deve essere lungo almeno %d caratteri.', - 'max_length' => 'Il campo %s non deve superare i %d caratteri.', - 'exact_length' => 'Il campo %s deve contenere esattamente %d caratteri.', - 'in_array' => 'Il campo %s deve essere selezionato dalla lista delle opzioni.', - 'matches' => 'Il campo %s deve coincidere con il campo %s.', - 'valid_url' => 'Il campo %s deve contenere un URL valido.', - 'valid_email' => 'Il campo %s deve contenere un indirizzo email valido.', - 'valid_ip' => 'Il campo %s deve contenere un indirizzo IP valido.', - 'valid_type' => 'Il campo %s deve contenere solo i caratteri %s.', - 'range' => 'Il campo %s deve trovarsi negli intervalli specificati.', - 'regex' => 'Il campo %s non coincide con i dati accettati.', - 'depends_on' => 'Il campo %s dipende dal campo %s.', + // Errori generici + 'unknown_error' => 'Errore sconosciuto durante la validazione del campo %s.', + 'required' => 'Il campo %s è obbligatorio.', + 'min_length' => 'Il campo %s deve essere lungo almeno %d caratteri.', + 'max_length' => 'Il campo %s non deve superare i %d caratteri.', + 'exact_length' => 'Il campo %s deve contenere esattamente %d caratteri.', + 'in_array' => 'Il campo %s deve essere selezionato dalla lista delle opzioni.', + 'matches' => 'Il campo %s deve coincidere con il campo %s.', + 'valid_url' => 'Il campo %s deve contenere un URL valido.', + 'valid_email' => 'Il campo %s deve contenere un indirizzo email valido.', + 'valid_ip' => 'Il campo %s deve contenere un indirizzo IP valido.', + 'valid_type' => 'Il campo %s deve contenere solo i caratteri %s.', + 'range' => 'Il campo %s deve trovarsi negli intervalli specificati.', + 'regex' => 'Il campo %s non coincide con i dati accettati.', + 'depends_on' => 'Il campo %s dipende dal campo %s.', - // Errori di upload - 'user_aborted' => 'Il caricamento del file %s è stato interrotto.', - 'invalid_type' => 'Il file %s non è un tipo di file permesso.', - 'max_size' => 'Il file %s inviato è troppo grande. La dimensone massima consentita è %s.', - 'max_width' => 'Il file %s inviato è troppo grande. La larghezza massima consentita è %spx.', - 'max_height' => 'Il file %s inviato è troppo grande. L\'altezza massima consentita è %spx.', - 'min_width' => 'Il file %s inviato è troppo piccolo. La larghezza minima consentita è %spx.', - 'min_height' => 'Il file %s inviato è troppo piccolo. L\'altezza minima consentita è %spx.', + // Errori di upload + 'user_aborted' => 'Il caricamento del file %s è stato interrotto.', + 'invalid_type' => 'Il file %s non è un tipo di file permesso.', + 'max_size' => 'Il file %s inviato è troppo grande. La dimensone massima consentita è %s.', + 'max_width' => 'Il file %s inviato è troppo grande. La larghezza massima consentita è %spx.', + 'max_height' => 'Il file %s inviato è troppo grande. L\'altezza massima consentita è %spx.', + 'min_width' => 'Il file %s inviato è troppo piccolo. La larghezza minima consentita è %spx.', + 'min_height' => 'Il file %s inviato è troppo piccolo. L\'altezza minima consentita è %spx.', - // Tipi di valore dei campi - 'alpha' => 'alfabetico', - 'alpha_numeric' => 'alfanumerico', - 'alpha_dash' => 'alfabetico, trattino e sottolineato', - 'digit' => 'cifra', - 'numeric' => 'numerico', + // Tipi di valore dei campi + 'alpha' => 'alfabetico', + 'alpha_numeric' => 'alfanumerico', + 'alpha_dash' => 'alfabetico, trattino e sottolineato', + 'digit' => 'cifra', + 'numeric' => 'numerico', ); diff --git a/lib/kohana/system/i18n/nl_NL/cache.php b/lib/kohana/system/i18n/nl_NL/cache.php index b6f1631..2c0e068 100644 --- a/lib/kohana/system/i18n/nl_NL/cache.php +++ b/lib/kohana/system/i18n/nl_NL/cache.php @@ -1,10 +1,14 @@ - 'De %s groep is niet gedefinieerd in uw configuratie.', - 'extension_not_loaded' => 'De %s PHP extensie moet geladen zijn om deze driver te gebruiken.', - 'unwritable' => 'De geconfigureerde opslaglocatie, %s, is niet schrijfbaar.', - 'resources' => 'Het cachen van resources is onmogelijk omdat resources niet geserialized kunnen worden.', - 'driver_error' => '%s', -); \ No newline at end of file + 'undefined_group' => 'De %s groep is niet gedefinieerd in uw configuratie.', + 'extension_not_loaded' => 'De %s PHP extensie moet geladen zijn om deze driver te gebruiken.', + 'unwritable' => 'De geconfigureerde opslaglocatie, %s, is niet schrijfbaar.', + 'resources' => 'Het cachen van resources is onmogelijk omdat resources niet geserialized kunnen worden.', + 'driver_error' => '%s', +); diff --git a/lib/kohana/system/i18n/nl_NL/calendar.php b/lib/kohana/system/i18n/nl_NL/calendar.php index ce8fa88..43e5997 100644 --- a/lib/kohana/system/i18n/nl_NL/calendar.php +++ b/lib/kohana/system/i18n/nl_NL/calendar.php @@ -1,59 +1,63 @@ - 'zo', - 'mo' => 'ma', - 'tu' => 'di', - 'we' => 'wo', - 'th' => 'do', - 'fr' => 'vr', - 'sa' => 'za', + // Two letter days + 'su' => 'zo', + 'mo' => 'ma', + 'tu' => 'di', + 'we' => 'wo', + 'th' => 'do', + 'fr' => 'vr', + 'sa' => 'za', - // Short day names - 'sun' => 'zon', - 'mon' => 'maa', - 'tue' => 'din', - 'wed' => 'woe', - 'thu' => 'don', - 'fri' => 'vri', - 'sat' => 'zat', + // Short day names + 'sun' => 'zon', + 'mon' => 'maa', + 'tue' => 'din', + 'wed' => 'woe', + 'thu' => 'don', + 'fri' => 'vri', + 'sat' => 'zat', - // Long day names - 'sunday' => 'zondag', - 'monday' => 'maandag', - 'tuesday' => 'dinsdag', - 'wednesday' => 'woensdag', - 'thursday' => 'donderdag', - 'friday' => 'vrijdag', - 'saturday' => 'zaterdag', + // Long day names + 'sunday' => 'zondag', + 'monday' => 'maandag', + 'tuesday' => 'dinsdag', + 'wednesday' => 'woensdag', + 'thursday' => 'donderdag', + 'friday' => 'vrijdag', + 'saturday' => 'zaterdag', - // Short month names - 'jan' => 'jan', - 'feb' => 'feb', - 'mar' => 'maa', - 'apr' => 'apr', - 'may' => 'mei', - 'jun' => 'jun', - 'jul' => 'jul', - 'aug' => 'aug', - 'sep' => 'sep', - 'oct' => 'okt', - 'nov' => 'nov', - 'dec' => 'dec', + // Short month names + 'jan' => 'jan', + 'feb' => 'feb', + 'mar' => 'maa', + 'apr' => 'apr', + 'may' => 'mei', + 'jun' => 'jun', + 'jul' => 'jul', + 'aug' => 'aug', + 'sep' => 'sep', + 'oct' => 'okt', + 'nov' => 'nov', + 'dec' => 'dec', - // Long month names - 'january' => 'januari', - 'february' => 'februari', - 'march' => 'maart', - 'april' => 'april', - 'mayl' => 'mei', - 'june' => 'juni', - 'july' => 'juli', - 'august' => 'augustus', - 'september' => 'september', - 'october' => 'oktober', - 'november' => 'november', - 'december' => 'december', -); \ No newline at end of file + // Long month names + 'january' => 'januari', + 'february' => 'februari', + 'march' => 'maart', + 'april' => 'april', + 'mayl' => 'mei', + 'june' => 'juni', + 'july' => 'juli', + 'august' => 'augustus', + 'september' => 'september', + 'october' => 'oktober', + 'november' => 'november', + 'december' => 'december', +); diff --git a/lib/kohana/system/i18n/nl_NL/captcha.php b/lib/kohana/system/i18n/nl_NL/captcha.php index 842d5fb..415bb42 100644 --- a/lib/kohana/system/i18n/nl_NL/captcha.php +++ b/lib/kohana/system/i18n/nl_NL/captcha.php @@ -1,33 +1,37 @@ - 'Het opgegeven bestand, %s, werd niet gevonden. Controleer met file_exists() of bestanden bestaan, voordat je ze gebruikt.', - 'requires_GD2' => 'De Captcha library vereist GD2 met FreeType ondersteuning. Zie http://php.net/gd_info voor meer informatie.', + 'file_not_found' => 'Het opgegeven bestand, %s, werd niet gevonden. Controleer met file_exists() of bestanden bestaan, voordat je ze gebruikt.', + 'requires_GD2' => 'De Captcha library vereist GD2 met FreeType ondersteuning. Zie http://php.net/gd_info voor meer informatie.', - // Words of varying length for the Captcha_Word_Driver to pick from - // Note: use only alphanumeric characters - 'words' => array - ( - 'cd', 'tv', 'ok', 'pc', 'nu', 'ik', - 'zon', 'kar', 'kat', 'bed', 'tof', 'hoi', - 'puin', 'hoop', 'mens', 'roof', 'auto', 'haar', - 'water', 'beter', 'aarde', 'appel', 'mango', 'liter', - 'ananas', 'bakker', 'wekker', 'kroket', 'zingen', 'dansen', - 'fietsen', 'zwemmen', 'kolonel', 'potlood', 'kookpot', 'voetbal', - 'barbecue', 'computer', 'generaal', 'koelkast', 'fietsers', 'spelling', - 'appelmoes', 'president', 'kangoeroe', 'frankrijk', 'luxemburg', 'apartheid', - ), + // Words of varying length for the Captcha_Word_Driver to pick from + // Note: use only alphanumeric characters + 'words' => array + ( + 'cd', 'tv', 'ok', 'pc', 'nu', 'ik', + 'zon', 'kar', 'kat', 'bed', 'tof', 'hoi', + 'puin', 'hoop', 'mens', 'roof', 'auto', 'haar', + 'water', 'beter', 'aarde', 'appel', 'mango', 'liter', + 'ananas', 'bakker', 'wekker', 'kroket', 'zingen', 'dansen', + 'fietsen', 'zwemmen', 'kolonel', 'potlood', 'kookpot', 'voetbal', + 'barbecue', 'computer', 'generaal', 'koelkast', 'fietsers', 'spelling', + 'appelmoes', 'president', 'kangoeroe', 'frankrijk', 'luxemburg', 'apartheid', + ), - // Riddles for the Captcha_Riddle_Driver to pick from - // Note: use only alphanumeric characters - 'riddles' => array - ( - array('Haat jij spam? (ja of nee)', 'ja'), - array('Ben jij een robot? (ja of nee)', 'nee'), - array('Vuur is... (heet of koud)', 'heet'), - array('Het seizoen na herfst is...', 'winter'), - array('Welke dag van de week is het vandaag?', strftime('%A')), - array('In welke maand van het jaar zijn we?', strftime('%B')), - ), + // Riddles for the Captcha_Riddle_Driver to pick from + // Note: use only alphanumeric characters + 'riddles' => array + ( + array('Haat jij spam? (ja of nee)', 'ja'), + array('Ben jij een robot? (ja of nee)', 'nee'), + array('Vuur is... (heet of koud)', 'heet'), + array('Het seizoen na herfst is...', 'winter'), + array('Welke dag van de week is het vandaag?', strftime('%A')), + array('In welke maand van het jaar zijn we?', strftime('%B')), + ), ); diff --git a/lib/kohana/system/i18n/nl_NL/core.php b/lib/kohana/system/i18n/nl_NL/core.php index e3668af..d7717f6 100644 --- a/lib/kohana/system/i18n/nl_NL/core.php +++ b/lib/kohana/system/i18n/nl_NL/core.php @@ -1,34 +1,38 @@ - 'Er kan maar één instantie van Kohana zijn per pagina oproep.', - 'uncaught_exception' => 'Uncaught %s: %s in bestand %s op lijn %s', - 'invalid_method' => 'Ongeldige method %s opgeroepen in %s.', - 'invalid_property' => 'De %s property bestaat niet in de %s class.', - 'log_dir_unwritable' => 'De log directory is niet schrijfbaar: %s', - 'resource_not_found' => 'De opgevraagde %s, %s, kon niet gevonden worden.', - 'invalid_filetype' => 'Het opgevraagde bestandstype, .%s, wordt niet toegestaan door het view configuratiebestand.', - 'view_set_filename' => 'Je moet de view bestandsnaam opgeven voordat je render aanroept.', - 'no_default_route' => 'Zet een default route in config/routes.php.', - 'no_controller' => 'Kohana kon geen controller aanduiden om deze pagina te verwerken: %s', - 'page_not_found' => 'De opgevraagde pagina, %s, kon niet gevonden worden.', - 'stats_footer' => 'Geladen in {execution_time} seconden, met een geheugengebruik van {memory_usage}. Aangedreven door Kohana v{kohana_version}.', - 'error_file_line' => '%s [%s]:', - 'stack_trace' => 'Stack Trace', - 'generic_error' => 'Oproep kon niet afgewerkt worden', - 'errors_disabled' => 'Ga naar de homepage of probeer opnieuw.', + 'there_can_be_only_one' => 'Er kan maar één instantie van Kohana zijn per pagina oproep.', + 'uncaught_exception' => 'Uncaught %s: %s in bestand %s op lijn %s', + 'invalid_method' => 'Ongeldige method %s opgeroepen in %s.', + 'invalid_property' => 'De %s property bestaat niet in de %s class.', + 'log_dir_unwritable' => 'De log directory is niet schrijfbaar: %s', + 'resource_not_found' => 'De opgevraagde %s, %s, kon niet gevonden worden.', + 'invalid_filetype' => 'Het opgevraagde bestandstype, .%s, wordt niet toegestaan door het view configuratiebestand.', + 'view_set_filename' => 'Je moet de view bestandsnaam opgeven voordat je render aanroept.', + 'no_default_route' => 'Zet een default route in config/routes.php.', + 'no_controller' => 'Kohana kon geen controller aanduiden om deze pagina te verwerken: %s', + 'page_not_found' => 'De opgevraagde pagina, %s, kon niet gevonden worden.', + 'stats_footer' => 'Geladen in {execution_time} seconden, met een geheugengebruik van {memory_usage}. Aangedreven door Kohana v{kohana_version}.', + 'error_file_line' => '%s [%s]:', + 'stack_trace' => 'Stack Trace', + 'generic_error' => 'Oproep kon niet afgewerkt worden', + 'errors_disabled' => 'Ga naar de homepage of probeer opnieuw.', - // Drivers - 'driver_implements' => 'De %s driver voor de %s library moet de %s interface implementeren.', - 'driver_not_found' => 'De %s driver voor de %s library werd niet gevonden.', + // Drivers + 'driver_implements' => 'De %s driver voor de %s library moet de %s interface implementeren.', + 'driver_not_found' => 'De %s driver voor de %s library werd niet gevonden.', - // Resource names - 'config' => 'configuratiebestand', - 'controller' => 'controller', - 'helper' => 'helper', - 'library' => 'library', - 'driver' => 'driver', - 'model' => 'model', - 'view' => 'view', -); \ No newline at end of file + // Resource names + 'config' => 'configuratiebestand', + 'controller' => 'controller', + 'helper' => 'helper', + 'library' => 'library', + 'driver' => 'driver', + 'model' => 'model', + 'view' => 'view', +); diff --git a/lib/kohana/system/i18n/nl_NL/database.php b/lib/kohana/system/i18n/nl_NL/database.php index b520283..8d87f15 100644 --- a/lib/kohana/system/i18n/nl_NL/database.php +++ b/lib/kohana/system/i18n/nl_NL/database.php @@ -1,15 +1,19 @@ - 'De %s groep is niet opgegeven in je configuratie.', - 'error' => 'Er was een SQL fout: %s', - 'connection' => 'Fout bij het verbinden met de database: %s', - 'invalid_dsn' => 'De DSN die je opgaf is ongeldig: %s', - 'must_use_set' => 'Je moet een SET clause opgeven voor je query.', - 'must_use_where' => 'Je moet een WHERE clause opgeven voor je query.', - 'must_use_table' => 'Je moet een database tabel opgeven voor je query.', - 'table_not_found' => 'De tabel %s bestaat niet in je database.', - 'not_implemented' => 'De method die je opriep, %s, wordt niet ondersteund door deze driver.', - 'result_read_only' => 'Query resultaten kunnen alleen maar gelezen worden.', -); \ No newline at end of file + 'undefined_group' => 'De %s groep is niet opgegeven in je configuratie.', + 'error' => 'Er was een SQL fout: %s', + 'connection' => 'Fout bij het verbinden met de database: %s', + 'invalid_dsn' => 'De DSN die je opgaf is ongeldig: %s', + 'must_use_set' => 'Je moet een SET clause opgeven voor je query.', + 'must_use_where' => 'Je moet een WHERE clause opgeven voor je query.', + 'must_use_table' => 'Je moet een database tabel opgeven voor je query.', + 'table_not_found' => 'De tabel %s bestaat niet in je database.', + 'not_implemented' => 'De method die je opriep, %s, wordt niet ondersteund door deze driver.', + 'result_read_only' => 'Query resultaten kunnen alleen maar gelezen worden.', +); diff --git a/lib/kohana/system/i18n/nl_NL/encrypt.php b/lib/kohana/system/i18n/nl_NL/encrypt.php index 980cdb1..23399a0 100644 --- a/lib/kohana/system/i18n/nl_NL/encrypt.php +++ b/lib/kohana/system/i18n/nl_NL/encrypt.php @@ -1,8 +1,12 @@ - 'De %s groep is niet gedefinieerd in je configuratie.', - 'requires_mcrypt' => 'Om de Encrypt library te gebruiken, moet mcrypt ingeschakeld zijn in je PHP installatie.', - 'no_encryption_key' => 'Om de Encrypt library te gebruiken, moet je een encryption key zetten in je config bestand.', + 'undefined_group' => 'De %s groep is niet gedefinieerd in je configuratie.', + 'requires_mcrypt' => 'Om de Encrypt library te gebruiken, moet mcrypt ingeschakeld zijn in je PHP installatie.', + 'no_encryption_key' => 'Om de Encrypt library te gebruiken, moet je een encryption key zetten in je config bestand.', ); diff --git a/lib/kohana/system/i18n/nl_NL/errors.php b/lib/kohana/system/i18n/nl_NL/errors.php index 2d4dc94..b80cf56 100644 --- a/lib/kohana/system/i18n/nl_NL/errors.php +++ b/lib/kohana/system/i18n/nl_NL/errors.php @@ -1,16 +1,26 @@ - array( 1, 'Framework Error', 'Bekijk de Kohana documentatie voor meer informatie over deze fout.'), - E_PAGE_NOT_FOUND => array( 1, 'Pagina Niet Gevonden', 'De opgevraagde pagina werd niet gevonden. Mogelijk werd deze verplaatst of verwijderd.'), - E_DATABASE_ERROR => array( 1, 'Database Error', 'Er vond een database fout plaats bij het verwerken van de opgeroepen procedure. Bekijk het errorbericht hieronder voor meer informatie.'), - E_RECOVERABLE_ERROR => array( 1, 'Recoverable Error', 'Er vond een fout plaats waardoor deze pagina niet geladen kon worden. Als dit probleem aanhoudt, contacteer dan a.u.b. de website beheerder.'), - E_ERROR => array( 1, 'Fatal Error', ''), - E_USER_ERROR => array( 1, 'Fatal Error', ''), - E_PARSE => array( 1, 'Syntax Error', ''), - E_WARNING => array( 1, 'Warning Message', ''), - E_USER_WARNING => array( 1, 'Warning Message', ''), - E_STRICT => array( 2, 'Strict Mode Error', ''), - E_NOTICE => array( 2, 'Runtime Message', ''), -); \ No newline at end of file + E_KOHANA => array( 1, 'Framework Error', + 'Bekijk de Kohana documentatie voor meer informatie over deze fout.'), + E_PAGE_NOT_FOUND => array( 1, 'Pagina Niet Gevonden', + 'De opgevraagde pagina werd niet gevonden. Mogelijk werd deze verplaatst of verwijderd.'), + E_DATABASE_ERROR => array( 1, 'Database Error', + 'Er vond een database fout plaats bij het verwerken van de opgeroepen procedure.' . + ' Bekijk het errorbericht hieronder voor meer informatie.'), + E_RECOVERABLE_ERROR => array( 1, 'Recoverable Error', + 'Er vond een fout plaats waardoor deze pagina niet geladen kon worden.' . + ' Als dit probleem aanhoudt, contacteer dan a.u.b. de website beheerder.'), + E_ERROR => array( 1, 'Fatal Error', ''), + E_USER_ERROR => array( 1, 'Fatal Error', ''), + E_PARSE => array( 1, 'Syntax Error', ''), + E_WARNING => array( 1, 'Warning Message', ''), + E_USER_WARNING => array( 1, 'Warning Message', ''), + E_STRICT => array( 2, 'Strict Mode Error', ''), + E_NOTICE => array( 2, 'Runtime Message', ''), +); diff --git a/lib/kohana/system/i18n/nl_NL/event.php b/lib/kohana/system/i18n/nl_NL/event.php index 2909e3f..1352b44 100644 --- a/lib/kohana/system/i18n/nl_NL/event.php +++ b/lib/kohana/system/i18n/nl_NL/event.php @@ -1,7 +1,11 @@ - 'Poging om ongeldig subject %s te binden aan %s mislukt. Subjects moeten de Event_Subject class extenden.', - 'invalid_observer' => 'Poging om ongeldige observer %s te binden aan %s mislukt. Observers moeten de Event_Subject class extenden.', + 'invalid_subject' => 'Poging om ongeldig subject %s te binden aan %s mislukt. Subjects moeten de Event_Subject class extenden.', + 'invalid_observer' => 'Poging om ongeldige observer %s te binden aan %s mislukt. Observers moeten de Event_Subject class extenden.', ); diff --git a/lib/kohana/system/i18n/nl_NL/image.php b/lib/kohana/system/i18n/nl_NL/image.php index e7c3cd7..6a10811 100644 --- a/lib/kohana/system/i18n/nl_NL/image.php +++ b/lib/kohana/system/i18n/nl_NL/image.php @@ -1,27 +1,32 @@ - 'De Image library vereist de getimagesize() functie en die is niet beschikbaar op dit systeem.', - 'unsupported_method' => 'De huidige Image driver ondersteunt volgende transformatie niet: %s.', - 'file_not_found' => 'De opgegeven afbeelding, %s, werd niet gevonden. Controleer a.u.b. eerst of afbeeldingen bestaan via de file_exists() functie voordat je ze begint te bewerken.', - 'type_not_allowed' => 'De opgegeven afbeelding, %s, is geen toegestaan afbeeldingstype.', - 'invalid_width' => 'De breedte die je opgaf, %s, is ongeldig.', - 'invalid_height' => 'De hoogte die je opgaf, %s, is ongeldig.', - 'invalid_dimensions' => 'De afmetingen die je opgaf voor %s zijn ongeldig.', - 'invalid_master' => 'De master afmeting die je opgaf, is ongeldig.', - 'invalid_flip' => 'De spiegelrichting die je opgaf, is ongeldig.', - 'directory_unwritable' => 'De opgegeven directory, %s, is niet schrijfbaar.', + 'getimagesize_missing' => 'De Image library vereist de getimagesize() functie en die is niet beschikbaar op dit systeem.', + 'unsupported_method' => 'De huidige Image driver ondersteunt volgende transformatie niet: %s.', + 'file_not_found' => 'De opgegeven afbeelding, %s, werd niet gevonden.' . + ' Controleer a.u.b. eerst of afbeeldingen bestaan via de file_exists() functie voordat je ze begint te bewerken.', + 'type_not_allowed' => 'De opgegeven afbeelding, %s, is geen toegestaan afbeeldingstype.', + 'invalid_width' => 'De breedte die je opgaf, %s, is ongeldig.', + 'invalid_height' => 'De hoogte die je opgaf, %s, is ongeldig.', + 'invalid_dimensions' => 'De afmetingen die je opgaf voor %s zijn ongeldig.', + 'invalid_master' => 'De master afmeting die je opgaf, is ongeldig.', + 'invalid_flip' => 'De spiegelrichting die je opgaf, is ongeldig.', + 'directory_unwritable' => 'De opgegeven directory, %s, is niet schrijfbaar.', - // ImageMagick specific messages - 'imagemagick' => array - ( - 'not_found' => 'De opgegeven ImageMagick directory bevat een vereist programma niet: %s.', - ), + // ImageMagick specific messages + 'imagemagick' => array + ( + 'not_found' => 'De opgegeven ImageMagick directory bevat een vereist programma niet: %s.', + ), - // GD specific messages - 'gd' => array - ( - 'requires_v2' => 'De Image library vereist GD2. Kijk op http://php.net/gd_info voor meer informatie.', - ), + // GD specific messages + 'gd' => array + ( + 'requires_v2' => 'De Image library vereist GD2. Kijk op http://php.net/gd_info voor meer informatie.', + ), ); diff --git a/lib/kohana/system/i18n/nl_NL/orm.php b/lib/kohana/system/i18n/nl_NL/orm.php index bea9238..30be928 100644 --- a/lib/kohana/system/i18n/nl_NL/orm.php +++ b/lib/kohana/system/i18n/nl_NL/orm.php @@ -1,3 +1,7 @@ - 'De %s groep werd niet gedefinieerd in uw pagination configuratie.', - 'page' => 'pagina', - 'pages' => 'pagina\'s', - 'item' => 'item', - 'items' => 'items', - 'of' => 'van', - 'first' => 'eerste', - 'last' => 'laatste', - 'previous' => 'vorige', - 'next' => 'volgende', + 'undefined_group' => 'De %s groep werd niet gedefinieerd in uw pagination configuratie.', + 'page' => 'pagina', + 'pages' => 'pagina\'s', + 'item' => 'item', + 'items' => 'items', + 'of' => 'van', + 'first' => 'eerste', + 'last' => 'laatste', + 'previous' => 'vorige', + 'next' => 'volgende', ); diff --git a/lib/kohana/system/i18n/nl_NL/profiler.php b/lib/kohana/system/i18n/nl_NL/profiler.php index 03d0f84..7ee18f9 100644 --- a/lib/kohana/system/i18n/nl_NL/profiler.php +++ b/lib/kohana/system/i18n/nl_NL/profiler.php @@ -1,15 +1,19 @@ - 'Benchmarks', - 'post_data' => 'Post Data', - 'no_post' => 'Geen post data', - 'session_data' => 'Session Data', - 'no_session' => 'Geen session data', - 'queries' => 'Database Queries', - 'no_queries' => 'Geen queries', - 'no_database' => 'Database niet geladen', - 'cookie_data' => 'Cookie Data', - 'no_cookie' => 'Geen cookie data', + 'benchmarks' => 'Benchmarks', + 'post_data' => 'Post Data', + 'no_post' => 'Geen post data', + 'session_data' => 'Session Data', + 'no_session' => 'Geen session data', + 'queries' => 'Database Queries', + 'no_queries' => 'Geen queries', + 'no_database' => 'Database niet geladen', + 'cookie_data' => 'Cookie Data', + 'no_cookie' => 'Geen cookie data', ); diff --git a/lib/kohana/system/i18n/nl_NL/session.php b/lib/kohana/system/i18n/nl_NL/session.php index 391a46d..837fc3a 100644 --- a/lib/kohana/system/i18n/nl_NL/session.php +++ b/lib/kohana/system/i18n/nl_NL/session.php @@ -1,6 +1,12 @@ - 'De sessienaam, %s, is ongeldig. Hij mag alleen maar bestaan uit alfanumerieke tekens en underscores. Hij moet ook minstens één letter bevatten.', -); \ No newline at end of file + 'invalid_session_name' => 'De sessienaam, %s, is ongeldig.' . + ' Hij mag alleen maar bestaan uit alfanumerieke tekens en underscores.' . + ' Hij moet ook minstens één letter bevatten.', +); diff --git a/lib/kohana/system/i18n/nl_NL/swift.php b/lib/kohana/system/i18n/nl_NL/swift.php index bdd2af7..71a3f0f 100644 --- a/lib/kohana/system/i18n/nl_NL/swift.php +++ b/lib/kohana/system/i18n/nl_NL/swift.php @@ -1,6 +1,10 @@ - 'Er vond een fout plaats bij het verzenden van de e-mail.', -); \ No newline at end of file + 'general_error' => 'Er vond een fout plaats bij het verzenden van de e-mail.', +); diff --git a/lib/kohana/system/i18n/nl_NL/upload.php b/lib/kohana/system/i18n/nl_NL/upload.php index 4a6549f..e556dcf 100644 --- a/lib/kohana/system/i18n/nl_NL/upload.php +++ b/lib/kohana/system/i18n/nl_NL/upload.php @@ -1,6 +1,10 @@ - 'De upload doelmap, %s, is niet schrijfbaar.', -); \ No newline at end of file + 'not_writable' => 'De upload doelmap, %s, is niet schrijfbaar.', +); diff --git a/lib/kohana/system/i18n/nl_NL/validation.php b/lib/kohana/system/i18n/nl_NL/validation.php index 4eb6c60..bb7751d 100644 --- a/lib/kohana/system/i18n/nl_NL/validation.php +++ b/lib/kohana/system/i18n/nl_NL/validation.php @@ -1,39 +1,43 @@ - 'Ongeldige validatieregel gebruikt: %s', + // Class errors + 'invalid_rule' => 'Ongeldige validatieregel gebruikt: %s', - // Algemene errors - 'unknown_error' => 'Onbekende validatiefout bij het valideren van het %s veld.', - 'required' => 'Het %s veld is verplicht.', - 'min_length' => 'Het %s veld moet minstens %s karakters lang zijn.', - 'max_length' => 'Het %s veld mag maximum %s karakters lang zijn.', - 'exact_length' => 'Het %s veld moet exact %s karakters lang zijn.', - 'in_array' => 'Het %s veld moet geselecteerd worden uit de gegeven opties.', - 'matches' => 'Het %s veld moet overeenkomen met het %s veld.', - 'valid_url' => 'Het %s veld moet een geldige URL zijn.', - 'valid_email' => 'Het %s veld moet een geldig e-mailadres zijn.', - 'valid_ip' => 'Het %s veld moet een geldig IP-adres zijn.', - 'valid_type' => 'Het %s veld mag alleen maar %s karakters bevatten.', - 'range' => 'Het %s veld moet tussen bepaalde waardes liggen.', - 'regex' => 'Het %s veld valideert niet als geldige invoer.', - 'depends_on' => 'Het %s veld is afhankelijk van het %s veld.', + // Algemene errors + 'unknown_error' => 'Onbekende validatiefout bij het valideren van het %s veld.', + 'required' => 'Het %s veld is verplicht.', + 'min_length' => 'Het %s veld moet minstens %s karakters lang zijn.', + 'max_length' => 'Het %s veld mag maximum %s karakters lang zijn.', + 'exact_length' => 'Het %s veld moet exact %s karakters lang zijn.', + 'in_array' => 'Het %s veld moet geselecteerd worden uit de gegeven opties.', + 'matches' => 'Het %s veld moet overeenkomen met het %s veld.', + 'valid_url' => 'Het %s veld moet een geldige URL zijn.', + 'valid_email' => 'Het %s veld moet een geldig e-mailadres zijn.', + 'valid_ip' => 'Het %s veld moet een geldig IP-adres zijn.', + 'valid_type' => 'Het %s veld mag alleen maar %s karakters bevatten.', + 'range' => 'Het %s veld moet tussen bepaalde waardes liggen.', + 'regex' => 'Het %s veld valideert niet als geldige invoer.', + 'depends_on' => 'Het %s veld is afhankelijk van het %s veld.', - // Upload errors - 'user_aborted' => 'Het uploaden van het %s bestand werd afgebroken.', - 'invalid_type' => 'Het bestandstype van het %s bestand is niet toegestaan.', - 'max_size' => 'Het %s bestand dat je wilde uploaden is te groot. De maximum toegelaten grootte is %s.', - 'max_width' => 'Het %s upgeloade bestand is te groot: maximum toegelaten breedte is %spx.', - 'max_height' => 'Het %s upgeloade bestand is te groot: maximum toegelaten hoogte is %spx.', - 'min_width' => 'Het %s upgeloade bestand is te klein: minimum toegelaten breedte is %spx.', - 'min_height' => 'Het %s upgeloade bestand is te klein: minimum toegelaten breedte is %spx.', + // Upload errors + 'user_aborted' => 'Het uploaden van het %s bestand werd afgebroken.', + 'invalid_type' => 'Het bestandstype van het %s bestand is niet toegestaan.', + 'max_size' => 'Het %s bestand dat je wilde uploaden is te groot. De maximum toegelaten grootte is %s.', + 'max_width' => 'Het %s upgeloade bestand is te groot: maximum toegelaten breedte is %spx.', + 'max_height' => 'Het %s upgeloade bestand is te groot: maximum toegelaten hoogte is %spx.', + 'min_width' => 'Het %s upgeloade bestand is te klein: minimum toegelaten breedte is %spx.', + 'min_height' => 'Het %s upgeloade bestand is te klein: minimum toegelaten breedte is %spx.', - // Field types - 'alpha' => 'alfabetisch', - 'alpha_numeric' => 'alfanumeriek', - 'alpha_dash' => 'alfabetisch, streepje, en underscore', - 'digit' => 'cijfers', - 'numeric' => 'getal', -); \ No newline at end of file + // Field types + 'alpha' => 'alfabetisch', + 'alpha_numeric' => 'alfanumeriek', + 'alpha_dash' => 'alfabetisch, streepje, en underscore', + 'digit' => 'cijfers', + 'numeric' => 'getal', +); diff --git a/lib/kohana/system/i18n/ru_RU/cache.php b/lib/kohana/system/i18n/ru_RU/cache.php index 855e834..8264a6d 100644 --- a/lib/kohana/system/i18n/ru_RU/cache.php +++ b/lib/kohana/system/i18n/ru_RU/cache.php @@ -1,10 +1,14 @@ - 'Группа "%s" не определена Вашей конфигурацией.', - 'extension_not_loaded' => 'Расширение PHP "%s" должно быть загружено для использования этого драйвера.', - 'unwritable' => 'Целевая директория хранения кеша, %s, не доступна для записи.', - 'resources' => 'Кеширование ресурсов невозможно, так как ресурсы не могут быть сериализованы.', - 'driver_error' => '%s', + 'undefined_group' => 'Группа "%s" не определена Вашей конфигурацией.', + 'extension_not_loaded' => 'Расширение PHP "%s" должно быть загружено для использования этого драйвера.', + 'unwritable' => 'Целевая директория хранения кеша, %s, не доступна для записи.', + 'resources' => 'Кеширование ресурсов невозможно, так как ресурсы не могут быть сериализованы.', + 'driver_error' => '%s', ); diff --git a/lib/kohana/system/i18n/ru_RU/calendar.php b/lib/kohana/system/i18n/ru_RU/calendar.php index a78ad34..3c4eb90 100644 --- a/lib/kohana/system/i18n/ru_RU/calendar.php +++ b/lib/kohana/system/i18n/ru_RU/calendar.php @@ -1,59 +1,63 @@ - 'Пн', - 'tu' => 'Вт', - 'we' => 'Ср', - 'th' => 'Чт', - 'fr' => 'Пт', - 'sa' => 'Сб', - 'su' => 'Вс', + // Two letter days + 'mo' => 'Пн', + 'tu' => 'Вт', + 'we' => 'Ср', + 'th' => 'Чт', + 'fr' => 'Пт', + 'sa' => 'Сб', + 'su' => 'Вс', - // Short day names - 'mon' => 'Пнд', - 'tue' => 'Втр', - 'wed' => 'Срд', - 'thu' => 'Чтв', - 'fri' => 'Птн', - 'sat' => 'Сбт', - 'sun' => 'Вск', + // Short day names + 'mon' => 'Пнд', + 'tue' => 'Втр', + 'wed' => 'Срд', + 'thu' => 'Чтв', + 'fri' => 'Птн', + 'sat' => 'Сбт', + 'sun' => 'Вск', - // Long day names - 'monday' => 'Понедельник', - 'tuesday' => 'Вторник', - 'wednesday' => 'Среда', - 'thursday' => 'Четверг', - 'friday' => 'Пятница', - 'saturday' => 'Суббота', - 'sunday' => 'Воскресенье', + // Long day names + 'monday' => 'Понедельник', + 'tuesday' => 'Вторник', + 'wednesday' => 'Среда', + 'thursday' => 'Четверг', + 'friday' => 'Пятница', + 'saturday' => 'Суббота', + 'sunday' => 'Воскресенье', - // Short month names - 'jan' => 'Янв', - 'feb' => 'Фев', - 'mar' => 'Мар', - 'apr' => 'Апр', - 'may' => 'Май', - 'jun' => 'Июн', - 'jul' => 'Июл', - 'aug' => 'Авг', - 'sep' => 'Сен', - 'oct' => 'Окт', - 'nov' => 'Ноя', - 'dec' => 'Дек', + // Short month names + 'jan' => 'Янв', + 'feb' => 'Фев', + 'mar' => 'Мар', + 'apr' => 'Апр', + 'may' => 'Май', + 'jun' => 'Июн', + 'jul' => 'Июл', + 'aug' => 'Авг', + 'sep' => 'Сен', + 'oct' => 'Окт', + 'nov' => 'Ноя', + 'dec' => 'Дек', - // Long month names - 'january' => 'Январь', - 'february' => 'Февраль', - 'march' => 'Март', - 'april' => 'Апрель', - 'mayl' => 'Май', - 'june' => 'Июнь', - 'july' => 'Июль', - 'august' => 'Август', - 'september' => 'Сентябрь', - 'october' => 'Октябрь', - 'november' => 'Ноябрь', - 'december' => 'Декабрь' + // Long month names + 'january' => 'Январь', + 'february' => 'Февраль', + 'march' => 'Март', + 'april' => 'Апрель', + 'mayl' => 'Май', + 'june' => 'Июнь', + 'july' => 'Июль', + 'august' => 'Август', + 'september' => 'Сентябрь', + 'october' => 'Октябрь', + 'november' => 'Ноябрь', + 'december' => 'Декабрь' ); diff --git a/lib/kohana/system/i18n/ru_RU/captcha.php b/lib/kohana/system/i18n/ru_RU/captcha.php index 98dd5d1..9278587 100644 --- a/lib/kohana/system/i18n/ru_RU/captcha.php +++ b/lib/kohana/system/i18n/ru_RU/captcha.php @@ -1,33 +1,37 @@ - 'Файл "%s" не найден. Убедитесь в наличии файлов функцией file_exists() перед их использованием.', 'requires_GD2' => 'Библиотека Captcha нуждается в расширении GD2 с поддержкой FreeType. Подробности на http://php.net/gd_info .', - // Words of varying length for the Captcha_Word_Driver to pick from - // Note: use only alphanumeric characters - 'words' => array - ( - 'cd', 'tv', 'it', 'to', 'be', 'or', - 'sun', 'car', 'dog', 'bed', 'kid', 'egg', - 'bike', 'tree', 'bath', 'roof', 'road', 'hair', - 'hello', 'world', 'earth', 'beard', 'chess', 'water', - 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', - 'america', 'release', 'playing', 'working', 'foreign', 'general', - 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', - 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', - ), + // Words of varying length for the Captcha_Word_Driver to pick from + // Note: use only alphanumeric characters + 'words' => array + ( + 'cd', 'tv', 'it', 'to', 'be', 'or', + 'sun', 'car', 'dog', 'bed', 'kid', 'egg', + 'bike', 'tree', 'bath', 'roof', 'road', 'hair', + 'hello', 'world', 'earth', 'beard', 'chess', 'water', + 'barber', 'bakery', 'banana', 'market', 'purple', 'writer', + 'america', 'release', 'playing', 'working', 'foreign', 'general', + 'aircraft', 'computer', 'laughter', 'alphabet', 'kangaroo', 'spelling', + 'architect', 'president', 'cockroach', 'encounter', 'terrorism', 'cylinders', + ), - // Riddles for the Captcha_Riddle_Driver to pick from - // Note: use only alphanumeric characters - 'riddles' => array - ( - array('Do you hate spam? (yes or no)', 'yes'), - array('Are you a robot? (yes or no)', 'no'), - array('Fire is... (hot or cold)', 'hot'), - array('The season after fall is...', 'winter'), - array('Which day of the week is it today?', strftime('%A')), - array('Which month of the year are we in?', strftime('%B')), - ), + // Riddles for the Captcha_Riddle_Driver to pick from + // Note: use only alphanumeric characters + 'riddles' => array + ( + array('Do you hate spam? (yes or no)', 'yes'), + array('Are you a robot? (yes or no)', 'no'), + array('Fire is... (hot or cold)', 'hot'), + array('The season after fall is...', 'winter'), + array('Which day of the week is it today?', strftime('%A')), + array('Which month of the year are we in?', strftime('%B')), + ), ); diff --git a/lib/kohana/system/i18n/ru_RU/core.php b/lib/kohana/system/i18n/ru_RU/core.php index 45840eb..847e666 100644 --- a/lib/kohana/system/i18n/ru_RU/core.php +++ b/lib/kohana/system/i18n/ru_RU/core.php @@ -1,34 +1,38 @@ - 'Наличие более, чем одного экземпляра Kohana, в пределах одного запроса страницы, невозможно', - 'uncaught_exception' => 'Не пойманное %s: %s в файле %s, на строке %s', - 'invalid_method' => 'Вызов метода %s из файла %s невозможен', - 'invalid_property' => 'Свойство %s не входит в состав класса %s.', - 'log_dir_unwritable' => 'Директория для хранения журналов, %s, не доступна для записи', - 'resource_not_found' => 'Запрошенный %s, %s, не найден', - 'invalid_filetype' => 'Запрошенный тип файла, .%s, не разрешён конфигурацией видов', - 'view_set_filename' => 'Необходимо задать файл вида перед вызовом render()', - 'no_default_route' => 'Установите путь по умолчанию в файле config/routes.php.', - 'no_controller' => 'Kohana не удалось найти контроллер для обработки этого запроса: %s', - 'page_not_found' => 'Запрошенная страница, %s, не найдена.', - 'stats_footer' => 'Загружено за {execution_time} секунд, используя {memory_usage} памяти. Сгенерировано Kohana v{kohana_version}.', - 'error_file_line' => '%s [%s]:', - 'stack_trace' => 'Стек вызовов', - 'generic_error' => 'Не удалось обработать запрос', - 'errors_disabled' => 'Вы можете вернуться на начальную страницу или повторить попытку.', + 'there_can_be_only_one' => 'Наличие более, чем одного экземпляра Kohana, в пределах одного запроса страницы, невозможно', + 'uncaught_exception' => 'Не пойманное %s: %s в файле %s, на строке %s', + 'invalid_method' => 'Вызов метода %s из файла %s невозможен', + 'invalid_property' => 'Свойство %s не входит в состав класса %s.', + 'log_dir_unwritable' => 'Директория для хранения журналов, %s, не доступна для записи', + 'resource_not_found' => 'Запрошенный %s, %s, не найден', + 'invalid_filetype' => 'Запрошенный тип файла, .%s, не разрешён конфигурацией видов', + 'view_set_filename' => 'Необходимо задать файл вида перед вызовом render()', + 'no_default_route' => 'Установите путь по умолчанию в файле config/routes.php.', + 'no_controller' => 'Kohana не удалось найти контроллер для обработки этого запроса: %s', + 'page_not_found' => 'Запрошенная страница, %s, не найдена.', + 'stats_footer' => 'Загружено за {execution_time} секунд, используя {memory_usage} памяти. Сгенерировано Kohana v{kohana_version}.', + 'error_file_line' => '%s [%s]:', + 'stack_trace' => 'Стек вызовов', + 'generic_error' => 'Не удалось обработать запрос', + 'errors_disabled' => 'Вы можете вернуться на начальную страницу или повторить попытку.', - // Drivers - 'driver_implements' => 'Драйвер %s библиотеки %s не реализует интерфейс %s', - 'driver_not_found' => 'Драйвер %s библиотеки %s не найден', + // Drivers + 'driver_implements' => 'Драйвер %s библиотеки %s не реализует интерфейс %s', + 'driver_not_found' => 'Драйвер %s библиотеки %s не найден', - // Resource names - 'config' => 'конфигурация', - 'controller' => 'контроллер', - 'helper' => 'помощник', - 'library' => 'библиотека', - 'driver' => 'драйвер', - 'model' => 'модель', - 'view' => 'вид', + // Resource names + 'config' => 'конфигурация', + 'controller' => 'контроллер', + 'helper' => 'помощник', + 'library' => 'библиотека', + 'driver' => 'драйвер', + 'model' => 'модель', + 'view' => 'вид', ); diff --git a/lib/kohana/system/i18n/ru_RU/database.php b/lib/kohana/system/i18n/ru_RU/database.php index ab13b9f..1c111e1 100644 --- a/lib/kohana/system/i18n/ru_RU/database.php +++ b/lib/kohana/system/i18n/ru_RU/database.php @@ -1,15 +1,19 @@ - 'Группа %s не определена Вашей конфигурацией.', - 'error' => 'Ошибка SQL: %s', - 'connection' => 'Не удалось подключиться к базе данных: %s', - 'invalid_dsn' => 'Переданный DSN некорректен: %s', - 'must_use_set' => 'Необходимо использовать оператор SET в этом запросе.', - 'must_use_where' => 'Необходимо использовать оператор WHERE в этом запросе.', - 'must_use_table' => 'Необходимо указать таблицу базы данных в этом запросе.', - 'table_not_found' => 'Таблица %s не существует в Вашей базе данных.', - 'not_implemented' => 'Запрошенный метод, %s, не поддерживается этим драйвером.', - 'result_read_only' => 'Результат запроса доступен только для чтения.' + 'undefined_group' => 'Группа %s не определена Вашей конфигурацией.', + 'error' => 'Ошибка SQL: %s', + 'connection' => 'Не удалось подключиться к базе данных: %s', + 'invalid_dsn' => 'Переданный DSN некорректен: %s', + 'must_use_set' => 'Необходимо использовать оператор SET в этом запросе.', + 'must_use_where' => 'Необходимо использовать оператор WHERE в этом запросе.', + 'must_use_table' => 'Необходимо указать таблицу базы данных в этом запросе.', + 'table_not_found' => 'Таблица %s не существует в Вашей базе данных.', + 'not_implemented' => 'Запрошенный метод, %s, не поддерживается этим драйвером.', + 'result_read_only' => 'Результат запроса доступен только для чтения.' ); diff --git a/lib/kohana/system/i18n/ru_RU/encrypt.php b/lib/kohana/system/i18n/ru_RU/encrypt.php index 49f1237..b3be0e1 100644 --- a/lib/kohana/system/i18n/ru_RU/encrypt.php +++ b/lib/kohana/system/i18n/ru_RU/encrypt.php @@ -1,8 +1,12 @@ - 'Группа %s не определена вашей конфигурацией.', - 'requires_mcrypt' => 'Для использования библиотеки Encrypt необходимо включить расширение "mcrypt" в конфигурации PHP.', - 'no_encryption_key' => 'Для использования библиотеки Encrypt необходимо задать ключ шифрования в конфигурационном файле.' + 'undefined_group' => 'Группа %s не определена вашей конфигурацией.', + 'requires_mcrypt' => 'Для использования библиотеки Encrypt необходимо включить расширение "mcrypt" в конфигурации PHP.', + 'no_encryption_key' => 'Для использования библиотеки Encrypt необходимо задать ключ шифрования в конфигурационном файле.' ); diff --git a/lib/kohana/system/i18n/ru_RU/errors.php b/lib/kohana/system/i18n/ru_RU/errors.php index ca6c6b8..0f5a4d4 100644 --- a/lib/kohana/system/i18n/ru_RU/errors.php +++ b/lib/kohana/system/i18n/ru_RU/errors.php @@ -1,16 +1,25 @@ - array( 1, 'Ошибка фреймворка', 'Информация об этой ошибке доступна в документации Kohana.'), - E_PAGE_NOT_FOUND => array( 1, 'Page Not Found', 'Запрошенная страница не найдена. Возможно, она была перемещена, удалена, или архивирована.'), - E_DATABASE_ERROR => array( 1, 'Database Error', 'При обработке запроса произошла ошибка в базе данных. Пожалуйста, уточните причину ошибки ниже'), - E_RECOVERABLE_ERROR => array( 1, 'Recoverable Error', 'Обнаружена ошибка, препятствующая загрузке этой страницы. Если это повторится, пожалуйста, уведомите администрацию сайта.'), - E_ERROR => array( 1, 'Фатальная ошибка', ''), - E_USER_ERROR => array( 1, 'Фатальная ошибка', ''), - E_PARSE => array( 1, 'Синтаксическая ошибка', ''), - E_WARNING => array( 1, 'Предупреждение', ''), - E_USER_WARNING => array( 1, 'Предупреждение', ''), - E_STRICT => array( 2, 'Стилистическая ошибка', ''), - E_NOTICE => array( 2, 'Уведомление', ''), + E_KOHANA => array( 1, 'Ошибка фреймворка', + 'Информация об этой ошибке доступна в документации Kohana.'), + E_PAGE_NOT_FOUND => array( 1, 'Page Not Found', + 'Запрошенная страница не найдена. Возможно, она была перемещена, удалена, или архивирована.'), + E_DATABASE_ERROR => array( 1, 'Database Error', + 'При обработке запроса произошла ошибка в базе данных. Пожалуйста, уточните причину ошибки ниже'), + E_RECOVERABLE_ERROR => array( 1, 'Recoverable Error', + 'Обнаружена ошибка, препятствующая загрузке этой страницы.' . + ' Если это повторится, пожалуйста, уведомите администрацию сайта.'), + E_ERROR => array( 1, 'Фатальная ошибка', ''), + E_USER_ERROR => array( 1, 'Фатальная ошибка', ''), + E_PARSE => array( 1, 'Синтаксическая ошибка', ''), + E_WARNING => array( 1, 'Предупреждение', ''), + E_USER_WARNING => array( 1, 'Предупреждение', ''), + E_STRICT => array( 2, 'Стилистическая ошибка', ''), + E_NOTICE => array( 2, 'Уведомление', ''), ); diff --git a/lib/kohana/system/i18n/ru_RU/event.php b/lib/kohana/system/i18n/ru_RU/event.php index 92b091b..e18d68c 100644 --- a/lib/kohana/system/i18n/ru_RU/event.php +++ b/lib/kohana/system/i18n/ru_RU/event.php @@ -1,7 +1,11 @@ - 'Попытка привязать некорректный субъект %s к %s не удалась: Субъект должен быть наследником класса Event_Subject', - 'invalid_observer' => 'Попытка привязать некорректный наблюдатель %s к %s не удалась: Наблюдатель должен быть наследником класса Event_Observer', + 'invalid_subject' => 'Попытка привязать некорректный субъект %s к %s не удалась: Субъект должен быть наследником класса Event_Subject', + 'invalid_observer' => 'Попытка привязать некорректный наблюдатель %s к %s не удалась: Наблюдатель должен быть наследником класса Event_Observer', ); diff --git a/lib/kohana/system/i18n/ru_RU/image.php b/lib/kohana/system/i18n/ru_RU/image.php index e00757e..dd5ef59 100644 --- a/lib/kohana/system/i18n/ru_RU/image.php +++ b/lib/kohana/system/i18n/ru_RU/image.php @@ -1,28 +1,32 @@ - 'Библиотеке Image необходима функция getimagesize(), недоступная в вашей инсталляции PHP.', - 'unsupported_method' => 'Указанный драйвер не поддерживает операцию %s.', - 'file_not_found' => 'Заданное изображение, %s, не найдено. Удостоверьтесь в наличии изображения функцией file_exists() перед его обработкой.', - 'type_not_allowed' => 'Заданное изображение, %s, не является разрешённым типом изображений.', - 'invalid_width' => 'Заданная ширина, %s, некорректна.', - 'invalid_height' => 'Заданная высота, %s, некорректна.', - 'invalid_dimensions' => 'Заданный размер для %s некорректен.', - 'invalid_master' => 'Заданная основная сторона некорректна.', - 'invalid_flip' => 'Направление разворота некорректно.', + 'getimagesize_missing' => 'Библиотеке Image необходима функция getimagesize(), недоступная в вашей инсталляции PHP.', + 'unsupported_method' => 'Указанный драйвер не поддерживает операцию %s.', + 'file_not_found' => 'Заданное изображение, %s, не найдено. Удостоверьтесь в наличии изображения функцией file_exists() перед его обработкой.', + 'type_not_allowed' => 'Заданное изображение, %s, не является разрешённым типом изображений.', + 'invalid_width' => 'Заданная ширина, %s, некорректна.', + 'invalid_height' => 'Заданная высота, %s, некорректна.', + 'invalid_dimensions' => 'Заданный размер для %s некорректен.', + 'invalid_master' => 'Заданная основная сторона некорректна.', + 'invalid_flip' => 'Направление разворота некорректно.', - 'directory_unwritable' => 'Заданная директория, %s, недоступна для записи.', + 'directory_unwritable' => 'Заданная директория, %s, недоступна для записи.', - // ImageMagick specific messages - 'imagemagick' => array - ( - 'not_found' => 'Директория ImageMagick не содержит запрошенную программу, %s.', - ), + // ImageMagick specific messages + 'imagemagick' => array + ( + 'not_found' => 'Директория ImageMagick не содержит запрошенную программу, %s.', + ), - // GD specific messages - 'gd' => array - ( - 'requires_v2' => 'Библиотеке Image необходимо расширение GD2. Подробности на http://php.net/gd_info .', - ), + // GD specific messages + 'gd' => array + ( + 'requires_v2' => 'Библиотеке Image необходимо расширение GD2. Подробности на http://php.net/gd_info .', + ), ); diff --git a/lib/kohana/system/i18n/ru_RU/orm.php b/lib/kohana/system/i18n/ru_RU/orm.php index 2c9a382..4c5df33 100644 --- a/lib/kohana/system/i18n/ru_RU/orm.php +++ b/lib/kohana/system/i18n/ru_RU/orm.php @@ -1,3 +1,7 @@ - 'Группа %s не определена конфигурацией нумератора страниц.', - 'page' => 'страница', - 'pages' => 'страницы', - 'item' => 'пункт', - 'items' => 'пунктов', - 'of' => 'из', - 'first' => 'первая', - 'last' => 'последняя', - 'previous' => 'предыдущая', - 'next' => 'следующая', + 'undefined_group' => 'Группа %s не определена конфигурацией нумератора страниц.', + 'page' => 'страница', + 'pages' => 'страницы', + 'item' => 'пункт', + 'items' => 'пунктов', + 'of' => 'из', + 'first' => 'первая', + 'last' => 'последняя', + 'previous' => 'предыдущая', + 'next' => 'следующая', ); diff --git a/lib/kohana/system/i18n/ru_RU/profiler.php b/lib/kohana/system/i18n/ru_RU/profiler.php index 2d45e7e..aa4a53d 100644 --- a/lib/kohana/system/i18n/ru_RU/profiler.php +++ b/lib/kohana/system/i18n/ru_RU/profiler.php @@ -1,15 +1,19 @@ - 'Производительность', - 'post_data' => 'Данные POST', - 'no_post' => 'Нет данных POST', - 'session_data' => 'Данные сессии', - 'no_session' => 'Нет данных сессии', - 'queries' => 'Запросов к БД', - 'no_queries' => 'Нет запросов к БД', - 'no_database' => 'БД не загружена', - 'cookie_data' => 'Данные cookie', - 'no_cookie' => 'Нет данных cookie', + 'benchmarks' => 'Производительность', + 'post_data' => 'Данные POST', + 'no_post' => 'Нет данных POST', + 'session_data' => 'Данные сессии', + 'no_session' => 'Нет данных сессии', + 'queries' => 'Запросов к БД', + 'no_queries' => 'Нет запросов к БД', + 'no_database' => 'БД не загружена', + 'cookie_data' => 'Данные cookie', + 'no_cookie' => 'Нет данных cookie', ); diff --git a/lib/kohana/system/i18n/ru_RU/session.php b/lib/kohana/system/i18n/ru_RU/session.php index 882fb27..435ec50 100644 --- a/lib/kohana/system/i18n/ru_RU/session.php +++ b/lib/kohana/system/i18n/ru_RU/session.php @@ -1,6 +1,10 @@ - 'Имя сессии, %s, некорректно. Оно должно состоять только из буквенно-цифровых символов, и, как минимум, одной буквы.', + 'invalid_session_name' => 'Имя сессии, %s, некорректно. Оно должно состоять только из буквенно-цифровых символов, и, как минимум, одной буквы.', ); diff --git a/lib/kohana/system/i18n/ru_RU/swift.php b/lib/kohana/system/i18n/ru_RU/swift.php index 9033d0c..faaff91 100644 --- a/lib/kohana/system/i18n/ru_RU/swift.php +++ b/lib/kohana/system/i18n/ru_RU/swift.php @@ -1,6 +1,10 @@ - 'Отправка письма не удалась.' + 'general_error' => 'Отправка письма не удалась.' ); diff --git a/lib/kohana/system/i18n/ru_RU/upload.php b/lib/kohana/system/i18n/ru_RU/upload.php index 1363ee2..79dcf31 100644 --- a/lib/kohana/system/i18n/ru_RU/upload.php +++ b/lib/kohana/system/i18n/ru_RU/upload.php @@ -1,23 +1,27 @@ - 'POST-переменная %s не найдена.', - 'file_exceeds_limit' => 'Размер закачанного файла превышает максимальный разрешённый конфигурацией PHP', - 'file_partial' => 'Файл закачан не полностью', - 'no_file_selected' => 'Вы не выбрали файл для закачивания', - 'invalid_filetype' => 'Тип файла, который вы пытаетесь закачать, не разрешён.', - 'invalid_filesize' => 'Размер файла, который вы пытаетесь закачать, превышает максимальный разрешённый (%s)', - 'invalid_dimensions' => 'Разрешение картинки, которую вы пытаетесь закачать, превышает максимальное разрешённое (%s)', - 'destination_error' => 'Не удалось переместить закачанный файл в пункт назначения.', - 'no_filepath' => 'Путь для закачивания некорректен.', - 'no_file_types' => 'Вы не разрешили ни один тип файлов.', - 'bad_filename' => 'Файл с таким именем уже существует на сервере.', - 'not_writable' => 'Запись в целевой каталог, %s, не возможна.', - 'error_on_file' => 'Ошибка при закачивании %s:', - // Error code responses - 'set_allowed' => 'В целях безопасности, установите разрешённые для закачивания типы файлов.', - 'max_file_size' => 'В целях безопасности, не используйте MAX_FILE_SIZE для ограничения размера закачиваемых файлов.', - 'no_tmp_dir' => 'Временная директория для закачивания файлов не найдена.', - 'tmp_unwritable' => 'Нет прав записи во временную директорию для закачивания файлов, %s.' + 'userfile_not_set' => 'POST-переменная %s не найдена.', + 'file_exceeds_limit' => 'Размер закачанного файла превышает максимальный разрешённый конфигурацией PHP', + 'file_partial' => 'Файл закачан не полностью', + 'no_file_selected' => 'Вы не выбрали файл для закачивания', + 'invalid_filetype' => 'Тип файла, который вы пытаетесь закачать, не разрешён.', + 'invalid_filesize' => 'Размер файла, который вы пытаетесь закачать, превышает максимальный разрешённый (%s)', + 'invalid_dimensions' => 'Разрешение картинки, которую вы пытаетесь закачать, превышает максимальное разрешённое (%s)', + 'destination_error' => 'Не удалось переместить закачанный файл в пункт назначения.', + 'no_filepath' => 'Путь для закачивания некорректен.', + 'no_file_types' => 'Вы не разрешили ни один тип файлов.', + 'bad_filename' => 'Файл с таким именем уже существует на сервере.', + 'not_writable' => 'Запись в целевой каталог, %s, не возможна.', + 'error_on_file' => 'Ошибка при закачивании %s:', + // Error code responses + 'set_allowed' => 'В целях безопасности, установите разрешённые для закачивания типы файлов.', + 'max_file_size' => 'В целях безопасности, не используйте MAX_FILE_SIZE для ограничения размера закачиваемых файлов.', + 'no_tmp_dir' => 'Временная директория для закачивания файлов не найдена.', + 'tmp_unwritable' => 'Нет прав записи во временную директорию для закачивания файлов, %s.' ); diff --git a/lib/kohana/system/i18n/ru_RU/validation.php b/lib/kohana/system/i18n/ru_RU/validation.php index edf6a02..2d1d363 100644 --- a/lib/kohana/system/i18n/ru_RU/validation.php +++ b/lib/kohana/system/i18n/ru_RU/validation.php @@ -1,39 +1,43 @@ - 'Некорректное правило валидации: %s', + // Class errors + 'invalid_rule' => 'Некорректное правило валидации: %s', - // General errors - 'unknown_error' => 'Неизвестная ошибка при валидации поля %s.', - 'required' => 'Поле %s обязательно для заполнения.', - 'min_length' => 'Поле %s должно быть не короче %d символов.', - 'max_length' => 'Поле %s должно быть не длиннее %d символов.', - 'exact_length' => 'Поле %s должно быть длиной в %d символов.', - 'in_array' => 'Поле %s должно содержать одно из перечисленных значений.', - 'matches' => 'Поле %s должно совпадать с полем %s.', - 'valid_url' => 'Поле %s должно содержать корректный URL.', - 'valid_email' => 'Поле %s должно содержать корректный email.', - 'valid_ip' => 'Поле %s должно содержать корректный IP-адрес.', - 'valid_type' => 'Поле %s должно содержать только символы %s.', - 'range' => 'Поле %s должно сожержать значение из заданных пределов.', - 'regex' => 'Поле %s не является принимаемым значением.', - 'depends_on' => 'Поле %s зависит от поля %s.', + // General errors + 'unknown_error' => 'Неизвестная ошибка при валидации поля %s.', + 'required' => 'Поле %s обязательно для заполнения.', + 'min_length' => 'Поле %s должно быть не короче %d символов.', + 'max_length' => 'Поле %s должно быть не длиннее %d символов.', + 'exact_length' => 'Поле %s должно быть длиной в %d символов.', + 'in_array' => 'Поле %s должно содержать одно из перечисленных значений.', + 'matches' => 'Поле %s должно совпадать с полем %s.', + 'valid_url' => 'Поле %s должно содержать корректный URL.', + 'valid_email' => 'Поле %s должно содержать корректный email.', + 'valid_ip' => 'Поле %s должно содержать корректный IP-адрес.', + 'valid_type' => 'Поле %s должно содержать только символы %s.', + 'range' => 'Поле %s должно сожержать значение из заданных пределов.', + 'regex' => 'Поле %s не является принимаемым значением.', + 'depends_on' => 'Поле %s зависит от поля %s.', - // Upload errors - 'user_aborted' => 'Загрузка файла %s отменена пользователем.', - 'invalid_type' => 'Загруженный файл, %s, не является файлом разрешённого типа.', - 'max_size' => 'Загруженный файл, %s, слишком велик. Максимальный разрешённый размер файла: %s.', - 'max_width' => 'Загруженный файл, %s, слишком велик. Максимальная разрешённая ширина: %s пикселей.', - 'max_height' => 'Загруженный файл, %s, слишком велик. Максимальная разрешённая высота: %s пикселей.', - 'min_width' => 'Загруженный файл, %s, слишком мал. Минимальная разрешённая ширина: %s пикселей.', - 'min_height' => 'Загруженный файл, %s, слишком мал. Минимальная разрешённая высота: %s пикселей.', + // Upload errors + 'user_aborted' => 'Загрузка файла %s отменена пользователем.', + 'invalid_type' => 'Загруженный файл, %s, не является файлом разрешённого типа.', + 'max_size' => 'Загруженный файл, %s, слишком велик. Максимальный разрешённый размер файла: %s.', + 'max_width' => 'Загруженный файл, %s, слишком велик. Максимальная разрешённая ширина: %s пикселей.', + 'max_height' => 'Загруженный файл, %s, слишком велик. Максимальная разрешённая высота: %s пикселей.', + 'min_width' => 'Загруженный файл, %s, слишком мал. Минимальная разрешённая ширина: %s пикселей.', + 'min_height' => 'Загруженный файл, %s, слишком мал. Минимальная разрешённая высота: %s пикселей.', - // Field types - 'alpha' => 'буквенное', - 'alpha_numeric' => 'буквенно-цифровое', - 'alpha_dash' => 'буквенное, c дефисом и символом подчёркивания', - 'digit' => 'цифровое', - 'numeric' => 'числовое', + // Field types + 'alpha' => 'буквенное', + 'alpha_numeric' => 'буквенно-цифровое', + 'alpha_dash' => 'буквенное, c дефисом и символом подчёркивания', + 'digit' => 'цифровое', + 'numeric' => 'числовое', ); diff --git a/lib/kohana/system/libraries/Cache.php b/lib/kohana/system/libraries/Cache.php index 8a02a90..add0835 100644 --- a/lib/kohana/system/libraries/Cache.php +++ b/lib/kohana/system/libraries/Cache.php @@ -1,4 +1,11 @@ -config = $config; - // Cache the config in the object - $this->config = $config; + // Set driver name + $driver = 'Cache_' . ucfirst($this->config['driver']) . '_Driver'; - // Set driver name - $driver = 'Cache_'.ucfirst($this->config['driver']).'_Driver'; + // Load the driver + if (! Kohana::auto_load($driver)) { + throw new Kohana_Exception('core.driver_not_found', $this->config['driver'], get_class($this)); + } - // Load the driver - if ( ! Kohana::auto_load($driver)) - throw new Kohana_Exception('core.driver_not_found', $this->config['driver'], get_class($this)); + // Initialize the driver + $this->driver = new $driver($this->config['params']); - // Initialize the driver - $this->driver = new $driver($this->config['params']); + // Validate the driver + if (! ($this->driver instanceof Cache_Driver)) { + throw new Kohana_Exception('core.driver_implements', $this->config['driver'], get_class($this), 'Cache_Driver'); + } - // Validate the driver - if ( ! ($this->driver instanceof Cache_Driver)) - throw new Kohana_Exception('core.driver_implements', $this->config['driver'], get_class($this), 'Cache_Driver'); + Kohana::log('debug', 'Cache Library initialized'); - Kohana::log('debug', 'Cache Library initialized'); + if (Cache::$loaded !== true) { + $this->config['requests'] = (int) $this->config['requests']; - if (Cache::$loaded !== TRUE) - { - $this->config['requests'] = (int) $this->config['requests']; + if ($this->config['requests'] > 0 and mt_rand(1, $this->config['requests']) === 1) { + // Do garbage collection + $this->driver->delete_expired(); - if ($this->config['requests'] > 0 AND mt_rand(1, $this->config['requests']) === 1) - { - // Do garbage collection - $this->driver->delete_expired(); + Kohana::log('debug', 'Cache: Expired caches deleted.'); + } - Kohana::log('debug', 'Cache: Expired caches deleted.'); - } + // Cache has been loaded once + Cache::$loaded = true; + } + } - // Cache has been loaded once - Cache::$loaded = TRUE; - } - } + /** + * Fetches a cache by id. NULL is returned when a cache item is not found. + * + * @param string cache id + * @return mixed cached data or NULL + */ + public function get($id) + { + // Sanitize the ID + $id = $this->sanitize_id($id); - /** - * Fetches a cache by id. NULL is returned when a cache item is not found. - * - * @param string cache id - * @return mixed cached data or NULL - */ - public function get($id) - { - // Sanitize the ID - $id = $this->sanitize_id($id); + return $this->driver->get($id); + } - return $this->driver->get($id); - } + /** + * Fetches all of the caches for a given tag. An empty array will be + * returned when no matching caches are found. + * + * @param string cache tag + * @return array all cache items matching the tag + */ + public function find($tag) + { + return $this->driver->find($tag); + } - /** - * Fetches all of the caches for a given tag. An empty array will be - * returned when no matching caches are found. - * - * @param string cache tag - * @return array all cache items matching the tag - */ - public function find($tag) - { - return $this->driver->find($tag); - } + /** + * Set a cache item by id. Tags may also be added and a custom lifetime + * can be set. Non-string data is automatically serialized. + * + * @param string unique cache id + * @param mixed data to cache + * @param array|string tags for this item + * @param integer number of seconds until the cache expires + * @return boolean + */ + private function set($id, $data, $tags = null, $lifetime = null) + { + if (is_resource($data)) { + throw new Kohana_Exception('cache.resources'); + } - /** - * Set a cache item by id. Tags may also be added and a custom lifetime - * can be set. Non-string data is automatically serialized. - * - * @param string unique cache id - * @param mixed data to cache - * @param array|string tags for this item - * @param integer number of seconds until the cache expires - * @return boolean - */ - function set($id, $data, $tags = NULL, $lifetime = NULL) - { - if (is_resource($data)) - throw new Kohana_Exception('cache.resources'); + // Sanitize the ID + $id = $this->sanitize_id($id); - // Sanitize the ID - $id = $this->sanitize_id($id); + if ($lifetime === null) { + // Get the default lifetime + $lifetime = $this->config['lifetime']; + } - if ($lifetime === NULL) - { - // Get the default lifetime - $lifetime = $this->config['lifetime']; - } + return $this->driver->set($id, $data, (array) $tags, $lifetime); + } - return $this->driver->set($id, $data, (array) $tags, $lifetime); - } + /** + * Delete a cache item by id. + * + * @param string cache id + * @return boolean + */ + public function delete($id) + { + // Sanitize the ID + $id = $this->sanitize_id($id); - /** - * Delete a cache item by id. - * - * @param string cache id - * @return boolean - */ - public function delete($id) - { - // Sanitize the ID - $id = $this->sanitize_id($id); + return $this->driver->delete($id); + } - return $this->driver->delete($id); - } + /** + * Delete all cache items with a given tag. + * + * @param string cache tag name + * @return boolean + */ + public function delete_tag($tag) + { + return $this->driver->delete($tag, true); + } - /** - * Delete all cache items with a given tag. - * - * @param string cache tag name - * @return boolean - */ - public function delete_tag($tag) - { - return $this->driver->delete($tag, TRUE); - } + /** + * Delete ALL cache items items. + * + * @return boolean + */ + public function delete_all() + { + return $this->driver->delete(true); + } - /** - * Delete ALL cache items items. - * - * @return boolean - */ - public function delete_all() - { - return $this->driver->delete(TRUE); - } - - /** - * Replaces troublesome characters with underscores. - * - * @param string cache id - * @return string - */ - protected function sanitize_id($id) - { - // Change slashes and spaces to underscores - return str_replace(array('/', '\\', ' '), '_', $id); - } - -} // End Cache + /** + * Replaces troublesome characters with underscores. + * + * @param string cache id + * @return string + */ + protected function sanitize_id($id) + { + // Change slashes and spaces to underscores + return str_replace(array('/', '\\', ' '), '_', $id); + } +} +// End Cache diff --git a/lib/kohana/system/libraries/Calendar.php b/lib/kohana/system/libraries/Calendar.php index 193a6fb..208c8a6 100644 --- a/lib/kohana/system/libraries/Calendar.php +++ b/lib/kohana/system/libraries/Calendar.php @@ -1,4 +1,11 @@ - 3) ? '%A' : '%a'; - /** - * Returns an array of the names of the days, using the current locale. - * - * @param integer left of day names - * @return array - */ - public static function days($length = TRUE) - { - // strftime day format - $format = ($length > 3) ? '%A' : '%a'; + // Days of the week + $days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); - // Days of the week - $days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); + if (Calendar::$start_monday === true) { + // Push Sunday to the end of the days + array_push($days, array_shift($days)); + } - if (Calendar::$start_monday === TRUE) - { - // Push Sunday to the end of the days - array_push($days, array_shift($days)); - } + if (strpos(Kohana::config('locale.language.0'), 'en') !== 0) { + // This is a bit awkward, but it works properly and is reliable + foreach ($days as $i => $day) { + // Convert the English names to i18n names + $days[$i] = strftime($format, strtotime($day)); + } + } - if (strpos(Kohana::config('locale.language.0'), 'en') !== 0) - { - // This is a bit awkward, but it works properly and is reliable - foreach ($days as $i => $day) - { - // Convert the English names to i18n names - $days[$i] = strftime($format, strtotime($day)); - } - } + if (is_int($length) or ctype_digit($length)) { + foreach ($days as $i => $day) { + // Shorten the days to the expected length + $days[$i] = utf8::substr($day, 0, $length); + } + } - if (is_int($length) OR ctype_digit($length)) - { - foreach ($days as $i => $day) - { - // Shorten the days to the expected length - $days[$i] = utf8::substr($day, 0, $length); - } - } + return $days; + } - return $days; - } + /** + * Create a new Calendar instance. A month and year can be specified. + * By default, the current month and year are used. + * + * @param integer month number + * @param integer year number + * @return object + */ + public static function factory($month = null, $year = null) + { + return new Calendar($month, $year); + } - /** - * Create a new Calendar instance. A month and year can be specified. - * By default, the current month and year are used. - * - * @param integer month number - * @param integer year number - * @return object - */ - public static function factory($month = NULL, $year = NULL) - { - return new Calendar($month, $year); - } + /** + * Create a new Calendar instance. A month and year can be specified. + * By default, the current month and year are used. + * + * @param integer month number + * @param integer year number + * @return void + */ + public function __construct($month = null, $year = null) + { + empty($month) and $month = date('n'); // Current month + empty($year) and $year = date('Y'); // Current year - /** - * Create a new Calendar instance. A month and year can be specified. - * By default, the current month and year are used. - * - * @param integer month number - * @param integer year number - * @return void - */ - public function __construct($month = NULL, $year = NULL) - { - empty($month) and $month = date('n'); // Current month - empty($year) and $year = date('Y'); // Current year + // Set the month and year + $this->month = (int) $month; + $this->year = (int) $year; - // Set the month and year - $this->month = (int) $month; - $this->year = (int) $year; + if (Calendar::$start_monday === true) { + // Week starts on Monday + $this->week_start = 1; + } + } - if (Calendar::$start_monday === TRUE) - { - // Week starts on Monday - $this->week_start = 1; - } - } + /** + * Allows fetching the current month and year. + * + * @param string key to get + * @return mixed + */ + public function __get($key) + { + if ($key === 'month' or $key === 'year') { + return $this->$key; + } + } - /** - * Allows fetching the current month and year. - * - * @param string key to get - * @return mixed - */ - public function __get($key) - { - if ($key === 'month' OR $key === 'year') - { - return $this->$key; - } - } + /** + * Calendar_Event factory method. + * + * @param string unique name for the event + * @return object Calendar_Event + */ + public function event($name = null) + { + return new Calendar_Event($this); + } - /** - * Calendar_Event factory method. - * - * @param string unique name for the event - * @return object Calendar_Event - */ - public function event($name = NULL) - { - return new Calendar_Event($this); - } + /** + * Calendar_Event factory method. + * + * @chainable + * @param string standard event type + * @return object + */ + public function standard($name) + { + switch ($name) { + case 'today': + // Add an event for the current day + $this->attach($this->event()->condition('timestamp', strtotime('today'))->add_class('today')); + break; + case 'prev-next': + // Add an event for padding days + $this->attach($this->event()->condition('current', false)->add_class('prev-next')); + break; + case 'holidays': + // Base event + $event = $this->event()->condition('current', true)->add_class('holiday'); - /** - * Calendar_Event factory method. - * - * @chainable - * @param string standard event type - * @return object - */ - public function standard($name) - { - switch ($name) - { - case 'today': - // Add an event for the current day - $this->attach($this->event()->condition('timestamp', strtotime('today'))->add_class('today')); - break; - case 'prev-next': - // Add an event for padding days - $this->attach($this->event()->condition('current', FALSE)->add_class('prev-next')); - break; - case 'holidays': - // Base event - $event = $this->event()->condition('current', TRUE)->add_class('holiday'); + // Attach New Years + $holiday = clone $event; + $this->attach($holiday->condition('month', 1)->condition('day', 1)); - // Attach New Years - $holiday = clone $event; - $this->attach($holiday->condition('month', 1)->condition('day', 1)); + // Attach Valentine's Day + $holiday = clone $event; + $this->attach($holiday->condition('month', 2)->condition('day', 14)); - // Attach Valentine's Day - $holiday = clone $event; - $this->attach($holiday->condition('month', 2)->condition('day', 14)); + // Attach St. Patrick's Day + $holiday = clone $event; + $this->attach($holiday->condition('month', 3)->condition('day', 17)); - // Attach St. Patrick's Day - $holiday = clone $event; - $this->attach($holiday->condition('month', 3)->condition('day', 17)); + // Attach Easter + $holiday = clone $event; + $this->attach($holiday->condition('easter', true)); - // Attach Easter - $holiday = clone $event; - $this->attach($holiday->condition('easter', TRUE)); + // Attach Memorial Day + $holiday = clone $event; + $this->attach($holiday->condition('month', 5)->condition('day_of_week', 1)->condition('last_occurrence', true)); - // Attach Memorial Day - $holiday = clone $event; - $this->attach($holiday->condition('month', 5)->condition('day_of_week', 1)->condition('last_occurrence', TRUE)); + // Attach Independance Day + $holiday = clone $event; + $this->attach($holiday->condition('month', 7)->condition('day', 4)); - // Attach Independance Day - $holiday = clone $event; - $this->attach($holiday->condition('month', 7)->condition('day', 4)); + // Attach Labor Day + $holiday = clone $event; + $this->attach($holiday->condition('month', 9)->condition('day_of_week', 1)->condition('occurrence', 1)); - // Attach Labor Day - $holiday = clone $event; - $this->attach($holiday->condition('month', 9)->condition('day_of_week', 1)->condition('occurrence', 1)); + // Attach Halloween + $holiday = clone $event; + $this->attach($holiday->condition('month', 10)->condition('day', 31)); - // Attach Halloween - $holiday = clone $event; - $this->attach($holiday->condition('month', 10)->condition('day', 31)); + // Attach Thanksgiving + $holiday = clone $event; + $this->attach($holiday->condition('month', 11)->condition('day_of_week', 4)->condition('occurrence', 4)); - // Attach Thanksgiving - $holiday = clone $event; - $this->attach($holiday->condition('month', 11)->condition('day_of_week', 4)->condition('occurrence', 4)); + // Attach Christmas + $holiday = clone $event; + $this->attach($holiday->condition('month', 12)->condition('day', 25)); + break; + case 'weekends': + // Weekend events + $this->attach($this->event()->condition('weekend', true)->add_class('weekend')); + break; + } - // Attach Christmas - $holiday = clone $event; - $this->attach($holiday->condition('month', 12)->condition('day', 25)); - break; - case 'weekends': - // Weekend events - $this->attach($this->event()->condition('weekend', TRUE)->add_class('weekend')); - break; - } + return $this; + } - return $this; - } + /** + * Returns an array for use with a view. The array contains an array for + * each week. Each week contains 7 arrays, with a day number and status: + * TRUE if the day is in the month, FALSE if it is padding. + * + * @return array + */ + public function weeks() + { + // First day of the month as a timestamp + $first = mktime(1, 0, 0, $this->month, 1, $this->year); - /** - * Returns an array for use with a view. The array contains an array for - * each week. Each week contains 7 arrays, with a day number and status: - * TRUE if the day is in the month, FALSE if it is padding. - * - * @return array - */ - public function weeks() - { - // First day of the month as a timestamp - $first = mktime(1, 0, 0, $this->month, 1, $this->year); + // Total number of days in this month + $total = (int) date('t', $first); - // Total number of days in this month - $total = (int) date('t', $first); + // Last day of the month as a timestamp + $last = mktime(1, 0, 0, $this->month, $total, $this->year); - // Last day of the month as a timestamp - $last = mktime(1, 0, 0, $this->month, $total, $this->year); + // Make the month and week empty arrays + $month = $week = array(); - // Make the month and week empty arrays - $month = $week = array(); + // Number of days added. When this reaches 7, start a new week + $days = 0; + $week_number = 1; - // Number of days added. When this reaches 7, start a new week - $days = 0; - $week_number = 1; + if (($w = (int) date('w', $first) - $this->week_start) < 0) { + $w = 6; + } - if (($w = (int) date('w', $first) - $this->week_start) < 0) - { - $w = 6; - } + if ($w > 0) { + // Number of days in the previous month + $n = (int) date('t', mktime(1, 0, 0, $this->month - 1, 1, $this->year)); - if ($w > 0) - { - // Number of days in the previous month - $n = (int) date('t', mktime(1, 0, 0, $this->month - 1, 1, $this->year)); + // i = number of day, t = number of days to pad + for ($i = $n - $w + 1, $t = $w; $t > 0; $t--, $i++) { + // Notify the listeners + $this->notify(array($this->month - 1, $i, $this->year, $week_number, false)); - // i = number of day, t = number of days to pad - for ($i = $n - $w + 1, $t = $w; $t > 0; $t--, $i++) - { - // Notify the listeners - $this->notify(array($this->month - 1, $i, $this->year, $week_number, FALSE)); + // Add previous month padding days + $week[] = array($i, false, $this->observed_data); + $days++; + } + } - // Add previous month padding days - $week[] = array($i, FALSE, $this->observed_data); - $days++; - } - } + // i = number of day + for ($i = 1; $i <= $total; $i++) { + if ($days % 7 === 0) { + // Start a new week + $month[] = $week; + $week = array(); - // i = number of day - for ($i = 1; $i <= $total; $i++) - { - if ($days % 7 === 0) - { - // Start a new week - $month[] = $week; - $week = array(); + $week_number++; + } - $week_number++; - } + // Notify the listeners + $this->notify(array($this->month, $i, $this->year, $week_number, true)); - // Notify the listeners - $this->notify(array($this->month, $i, $this->year, $week_number, TRUE)); + // Add days to this month + $week[] = array($i, true, $this->observed_data); + $days++; + } - // Add days to this month - $week[] = array($i, TRUE, $this->observed_data); - $days++; - } + if (($w = (int) date('w', $last) - $this->week_start) < 0) { + $w = 6; + } - if (($w = (int) date('w', $last) - $this->week_start) < 0) - { - $w = 6; - } + if ($w >= 0) { + // i = number of day, t = number of days to pad + for ($i = 1, $t = 6 - $w; $t > 0; $t--, $i++) { + // Notify the listeners + $this->notify(array($this->month + 1, $i, $this->year, $week_number, false)); - if ($w >= 0) - { - // i = number of day, t = number of days to pad - for ($i = 1, $t = 6 - $w; $t > 0; $t--, $i++) - { - // Notify the listeners - $this->notify(array($this->month + 1, $i, $this->year, $week_number, FALSE)); + // Add next month padding days + $week[] = array($i, false, $this->observed_data); + } + } - // Add next month padding days - $week[] = array($i, FALSE, $this->observed_data); - } - } + if (! empty($week)) { + // Append the remaining days + $month[] = $week; + } - if ( ! empty($week)) - { - // Append the remaining days - $month[] = $week; - } + return $month; + } - return $month; - } + /** + * Adds new data from an observer. All event data contains and array of CSS + * classes and an array of output messages. + * + * @param array observer data. + * @return void + */ + public function add_data(array $data) + { + // Add new classes + $this->observed_data['classes'] += $data['classes']; - /** - * Adds new data from an observer. All event data contains and array of CSS - * classes and an array of output messages. - * - * @param array observer data. - * @return void - */ - public function add_data(array $data) - { - // Add new classes - $this->observed_data['classes'] += $data['classes']; + if (! empty($data['output'])) { + // Only add output if it's not empty + $this->observed_data['output'][] = $data['output']; + } + } - if ( ! empty($data['output'])) - { - // Only add output if it's not empty - $this->observed_data['output'][] = $data['output']; - } - } + /** + * Resets the observed data and sends a notify to all attached events. + * + * @param array UNIX timestamp + * @return void + */ + public function notify($data) + { + // Reset observed data + $this->observed_data = array + ( + 'classes' => array(), + 'output' => array(), + ); - /** - * Resets the observed data and sends a notify to all attached events. - * - * @param array UNIX timestamp - * @return void - */ - public function notify($data) - { - // Reset observed data - $this->observed_data = array - ( - 'classes' => array(), - 'output' => array(), - ); + // Send a notify + parent::notify($data); + } - // Send a notify - parent::notify($data); - } + /** + * Convert the calendar to HTML using the kohana_calendar view. + * + * @return string + */ + public function render() + { + $view = new View('kohana_calendar', array + ( + 'month' => $this->month, + 'year' => $this->year, + 'weeks' => $this->weeks(), + )); - /** - * Convert the calendar to HTML using the kohana_calendar view. - * - * @return string - */ - public function render() - { - $view = new View('kohana_calendar', array - ( - 'month' => $this->month, - 'year' => $this->year, - 'weeks' => $this->weeks(), - )); + return $view->render(); + } - return $view->render(); - } - - /** - * Magically convert this object to a string, the rendered calendar. - * - * @return string - */ - public function __toString() - { - return $this->render(); - } - -} // End Calendar \ No newline at end of file + /** + * Magically convert this object to a string, the rendered calendar. + * + * @return string + */ + public function __toString() + { + return $this->render(); + } +} +// End Calendar diff --git a/lib/kohana/system/libraries/Calendar_Event.php b/lib/kohana/system/libraries/Calendar_Event.php index ba9b5ad..5c8ef60 100644 --- a/lib/kohana/system/libraries/Calendar_Event.php +++ b/lib/kohana/system/libraries/Calendar_Event.php @@ -1,4 +1,11 @@ -conditions[$key]); + } else { + if ($key === 'callback') { + // Do nothing + } elseif (in_array($key, $this->booleans)) { + // Make the value boolean + $value = (bool) $value; + } else { + // Make the value an int + $value = (int) $value; + } - /** - * Adds a condition to the event. The condition can be one of the following: - * - * timestamp - UNIX timestamp - * day - day number (1-31) - * week - week number (1-5) - * month - month number (1-12) - * year - year number (4 digits) - * day_of_week - day of week (1-7) - * current - active month (boolean) (only show data for the month being rendered) - * weekend - weekend day (boolean) - * first_day - first day of month (boolean) - * last_day - last day of month (boolean) - * occurrence - occurrence of the week day (1-5) (use with "day_of_week") - * last_occurrence - last occurrence of week day (boolean) (use with "day_of_week") - * easter - Easter day (boolean) - * callback - callback test (boolean) - * - * To unset a condition, call condition with a value of NULL. - * - * @chainable - * @param string condition key - * @param mixed condition value - * @return object - */ - public function condition($key, $value) - { - if ($value === NULL) - { - unset($this->conditions[$key]); - } - else - { - if ($key === 'callback') - { - // Do nothing - } - elseif (in_array($key, $this->booleans)) - { - // Make the value boolean - $value = (bool) $value; - } - else - { - // Make the value an int - $value = (int) $value; - } + $this->conditions[$key] = $value; + } - $this->conditions[$key] = $value; - } + return $this; + } - return $this; - } + /** + * Add a CSS class for this event. This can be called multiple times. + * + * @chainable + * @param string CSS class name + * @return object + */ + public function add_class($class) + { + $this->classes[$class] = $class; - /** - * Add a CSS class for this event. This can be called multiple times. - * - * @chainable - * @param string CSS class name - * @return object - */ - public function add_class($class) - { - $this->classes[$class] = $class; + return $this; + } - return $this; - } + /** + * Remove a CSS class for this event. This can be called multiple times. + * + * @chainable + * @param string CSS class name + * @return object + */ + public function remove_class($class) + { + unset($this->classes[$class]); - /** - * Remove a CSS class for this event. This can be called multiple times. - * - * @chainable - * @param string CSS class name - * @return object - */ - public function remove_class($class) - { - unset($this->classes[$class]); + return $this; + } - return $this; - } + /** + * Set HTML output for this event. + * + * @chainable + * @param string HTML output + * @return object + */ + public function output($str) + { + $this->output = $str; - /** - * Set HTML output for this event. - * - * @chainable - * @param string HTML output - * @return object - */ - public function output($str) - { - $this->output = $str; + return $this; + } - return $this; - } + /** + * Add a CSS class for this event. This can be called multiple times. + * + * @chainable + * @param string CSS class name + * @return object + */ + public function notify($data) + { + // Split the date and current status + list ($month, $day, $year, $week, $current) = $data; - /** - * Add a CSS class for this event. This can be called multiple times. - * - * @chainable - * @param string CSS class name - * @return object - */ - public function notify($data) - { - // Split the date and current status - list ($month, $day, $year, $week, $current) = $data; + // Get a timestamp for the day + $timestamp = mktime(0, 0, 0, $month, $day, $year); - // Get a timestamp for the day - $timestamp = mktime(0, 0, 0, $month, $day, $year); + // Date conditionals + $condition = array + ( + 'timestamp' => (int) $timestamp, + 'day' => (int) date('j', $timestamp), + 'week' => (int) $week, + 'month' => (int) date('n', $timestamp), + 'year' => (int) date('Y', $timestamp), + 'day_of_week' => (int) date('w', $timestamp), + 'current' => (bool) $current, + ); - // Date conditionals - $condition = array - ( - 'timestamp' => (int) $timestamp, - 'day' => (int) date('j', $timestamp), - 'week' => (int) $week, - 'month' => (int) date('n', $timestamp), - 'year' => (int) date('Y', $timestamp), - 'day_of_week' => (int) date('w', $timestamp), - 'current' => (bool) $current, - ); + // Tested conditions + $tested = array(); - // Tested conditions - $tested = array(); + foreach ($condition as $key => $value) { + // Timestamps need to be handled carefully + if ($key === 'timestamp' and isset($this->conditions['timestamp'])) { + // This adds 23 hours, 59 minutes and 59 seconds to today's timestamp, as 24 hours + // is classed as a new day + $next_day = $timestamp + 86399; - foreach ($condition as $key => $value) - { - // Timestamps need to be handled carefully - if($key === 'timestamp' AND isset($this->conditions['timestamp'])) - { - // This adds 23 hours, 59 minutes and 59 seconds to today's timestamp, as 24 hours - // is classed as a new day - $next_day = $timestamp + 86399; - - if($this->conditions['timestamp'] < $timestamp OR $this->conditions['timestamp'] > $next_day) - return FALSE; - } - // Test basic conditions first - elseif (isset($this->conditions[$key]) AND $this->conditions[$key] !== $value) - return FALSE; + if ($this->conditions['timestamp'] < $timestamp or $this->conditions['timestamp'] > $next_day) { + return false; + } + } elseif (isset($this->conditions[$key]) and $this->conditions[$key] !== $value) { + // Test basic conditions first + return false; + } - // Condition has been tested - $tested[$key] = TRUE; - } + // Condition has been tested + $tested[$key] = true; + } - if (isset($this->conditions['weekend'])) - { - // Weekday vs Weekend - $condition['weekend'] = ($condition['day_of_week'] === 0 OR $condition['day_of_week'] === 6); - } + if (isset($this->conditions['weekend'])) { + // Weekday vs Weekend + $condition['weekend'] = ($condition['day_of_week'] === 0 or $condition['day_of_week'] === 6); + } - if (isset($this->conditions['first_day'])) - { - // First day of month - $condition['first_day'] = ($condition['day'] === 1); - } + if (isset($this->conditions['first_day'])) { + // First day of month + $condition['first_day'] = ($condition['day'] === 1); + } - if (isset($this->conditions['last_day'])) - { - // Last day of month - $condition['last_day'] = ($condition['day'] === (int) date('t', $timestamp)); - } + if (isset($this->conditions['last_day'])) { + // Last day of month + $condition['last_day'] = ($condition['day'] === (int) date('t', $timestamp)); + } - if (isset($this->conditions['occurrence'])) - { - // Get the occurance of the current day - $condition['occurrence'] = $this->day_occurrence($timestamp); - } + if (isset($this->conditions['occurrence'])) { + // Get the occurance of the current day + $condition['occurrence'] = $this->day_occurrence($timestamp); + } - if (isset($this->conditions['last_occurrence'])) - { - // Test if the next occurance of this date is next month - $condition['last_occurrence'] = ((int) date('n', $timestamp + 604800) !== $condition['month']); - } + if (isset($this->conditions['last_occurrence'])) { + // Test if the next occurance of this date is next month + $condition['last_occurrence'] = ((int) date('n', $timestamp + 604800) !== $condition['month']); + } - if (isset($this->conditions['easter'])) - { - if ($condition['month'] === 3 OR $condition['month'] === 4) - { - // This algorithm is from Practical Astronomy With Your Calculator, 2nd Edition by Peter - // Duffett-Smith. It was originally from Butcher's Ecclesiastical Calendar, published in - // 1876. This algorithm has also been published in the 1922 book General Astronomy by - // Spencer Jones; in The Journal of the British Astronomical Association (Vol.88, page - // 91, December 1977); and in Astronomical Algorithms (1991) by Jean Meeus. + if (isset($this->conditions['easter'])) { + if ($condition['month'] === 3 or $condition['month'] === 4) { + // This algorithm is from Practical Astronomy With Your Calculator, 2nd Edition by Peter + // Duffett-Smith. It was originally from Butcher's Ecclesiastical Calendar, published in + // 1876. This algorithm has also been published in the 1922 book General Astronomy by + // Spencer Jones; in The Journal of the British Astronomical Association (Vol.88, page + // 91, December 1977); and in Astronomical Algorithms (1991) by Jean Meeus. - $a = $condition['year'] % 19; - $b = (int) ($condition['year'] / 100); - $c = $condition['year'] % 100; - $d = (int) ($b / 4); - $e = $b % 4; - $f = (int) (($b + 8) / 25); - $g = (int) (($b - $f + 1) / 3); - $h = (19 * $a + $b - $d - $g + 15) % 30; - $i = (int) ($c / 4); - $k = $c % 4; - $l = (32 + 2 * $e + 2 * $i - $h - $k) % 7; - $m = (int) (($a + 11 * $h + 22 * $l) / 451); - $p = ($h + $l - 7 * $m + 114) % 31; + $a = $condition['year'] % 19; + $b = (int) ($condition['year'] / 100); + $c = $condition['year'] % 100; + $d = (int) ($b / 4); + $e = $b % 4; + $f = (int) (($b + 8) / 25); + $g = (int) (($b - $f + 1) / 3); + $h = (19 * $a + $b - $d - $g + 15) % 30; + $i = (int) ($c / 4); + $k = $c % 4; + $l = (32 + 2 * $e + 2 * $i - $h - $k) % 7; + $m = (int) (($a + 11 * $h + 22 * $l) / 451); + $p = ($h + $l - 7 * $m + 114) % 31; - $month = (int) (($h + $l - 7 * $m + 114) / 31); - $day = $p + 1; + $month = (int) (($h + $l - 7 * $m + 114) / 31); + $day = $p + 1; - $condition['easter'] = ($condition['month'] === $month AND $condition['day'] === $day); - } - else - { - // Easter can only happen in March or April - $condition['easter'] = FALSE; - } - } + $condition['easter'] = ($condition['month'] === $month and $condition['day'] === $day); + } else { + // Easter can only happen in March or April + $condition['easter'] = false; + } + } - if (isset($this->conditions['callback'])) - { - // Use a callback to determine validity - $condition['callback'] = call_user_func($this->conditions['callback'], $condition, $this); - } + if (isset($this->conditions['callback'])) { + // Use a callback to determine validity + $condition['callback'] = call_user_func($this->conditions['callback'], $condition, $this); + } - $conditions = array_diff_key($this->conditions, $tested); + $conditions = array_diff_key($this->conditions, $tested); - foreach ($conditions as $key => $value) - { - if ($key === 'callback') - { - // Callbacks are tested on a TRUE/FALSE basis - $value = TRUE; - } + foreach ($conditions as $key => $value) { + if ($key === 'callback') { + // Callbacks are tested on a TRUE/FALSE basis + $value = true; + } - // Test advanced conditions - if ($condition[$key] !== $value) - return FALSE; - } + // Test advanced conditions + if ($condition[$key] !== $value) { + return false; + } + } - $this->caller->add_data(array - ( - 'classes' => $this->classes, - 'output' => $this->output, - )); - } + $this->caller->add_data(array + ( + 'classes' => $this->classes, + 'output' => $this->output, + )); + } - /** - * Find the week day occurrence for a specific timestamp. The occurrence is - * relative to the current month. For example, the second Saturday of any - * given month will return "2" as the occurrence. This is used in combination - * with the "occurrence" condition. - * - * @param integer UNIX timestamp - * @return integer - */ - protected function day_occurrence($timestamp) - { - // Get the current month for the timestamp - $month = date('m', $timestamp); + /** + * Find the week day occurrence for a specific timestamp. The occurrence is + * relative to the current month. For example, the second Saturday of any + * given month will return "2" as the occurrence. This is used in combination + * with the "occurrence" condition. + * + * @param integer UNIX timestamp + * @return integer + */ + protected function day_occurrence($timestamp) + { + // Get the current month for the timestamp + $month = date('m', $timestamp); - // Default occurrence is one - $occurrence = 1; + // Default occurrence is one + $occurrence = 1; - // Reduce the timestamp by one week for each loop. This has the added - // benefit of preventing an infinite loop. - while ($timestamp -= 604800) - { - if (date('m', $timestamp) !== $month) - { - // Once the timestamp has gone into the previous month, the - // proper occurrence has been found. - return $occurrence; - } + // Reduce the timestamp by one week for each loop. This has the added + // benefit of preventing an infinite loop. + while ($timestamp -= 604800) { + if (date('m', $timestamp) !== $month) { + // Once the timestamp has gone into the previous month, the + // proper occurrence has been found. + return $occurrence; + } - // Increment the occurrence - $occurrence++; - } - } - -} // End Calendar Event + // Increment the occurrence + $occurrence++; + } + } +} +// End Calendar Event diff --git a/lib/kohana/system/libraries/Captcha.php b/lib/kohana/system/libraries/Captcha.php index f5f2b46..58b8bb4 100644 --- a/lib/kohana/system/libraries/Captcha.php +++ b/lib/kohana/system/libraries/Captcha.php @@ -1,4 +1,11 @@ - 'basic', + 'width' => 150, + 'height' => 50, + 'complexity' => 4, + 'background' => '', + 'fontpath' => '', + 'fonts' => array(), + 'promote' => false, + ); - // Config values - public static $config = array - ( - 'style' => 'basic', - 'width' => 150, - 'height' => 50, - 'complexity' => 4, - 'background' => '', - 'fontpath' => '', - 'fonts' => array(), - 'promote' => FALSE, - ); + /** + * Singleton instance of Captcha. + * + * @return object + */ + public static function instance() + { + // Create the instance if it does not exist + empty(Captcha::$instance) and new Captcha(); - /** - * Singleton instance of Captcha. - * - * @return object - */ - public static function instance() - { - // Create the instance if it does not exist - empty(Captcha::$instance) and new Captcha; + return Captcha::$instance; + } - return Captcha::$instance; - } + /** + * Constructs and returns a new Captcha object. + * + * @param string config group name + * @return object + */ + public static function factory($group = null) + { + return new Captcha($group); + } - /** - * Constructs and returns a new Captcha object. - * - * @param string config group name - * @return object - */ - public static function factory($group = NULL) - { - return new Captcha($group); - } + /** + * Constructs a new Captcha object. + * + * @throws Kohana_Exception + * @param string config group name + * @return void + */ + public function __construct($group = null) + { + // Create a singleton instance once + empty(Captcha::$instance) and Captcha::$instance = $this; - /** - * Constructs a new Captcha object. - * - * @throws Kohana_Exception - * @param string config group name - * @return void - */ - public function __construct($group = NULL) - { - // Create a singleton instance once - empty(Captcha::$instance) and Captcha::$instance = $this; + // No config group name given + if (! is_string($group)) { + $group = 'default'; + } - // No config group name given - if ( ! is_string($group)) - { - $group = 'default'; - } + // Load and validate config group + if (! is_array($config = Kohana::config('captcha.' . $group))) { + throw new Kohana_Exception('captcha.undefined_group', $group); + } - // Load and validate config group - if ( ! is_array($config = Kohana::config('captcha.'.$group))) - throw new Kohana_Exception('captcha.undefined_group', $group); + // All captcha config groups inherit default config group + if ($group !== 'default') { + // Load and validate default config group + if (! is_array($default = Kohana::config('captcha.default'))) { + throw new Kohana_Exception('captcha.undefined_group', 'default'); + } - // All captcha config groups inherit default config group - if ($group !== 'default') - { - // Load and validate default config group - if ( ! is_array($default = Kohana::config('captcha.default'))) - throw new Kohana_Exception('captcha.undefined_group', 'default'); + // Merge config group with default config group + $config += $default; + } - // Merge config group with default config group - $config += $default; - } + // Assign config values to the object + foreach ($config as $key => $value) { + if (array_key_exists($key, Captcha::$config)) { + Captcha::$config[$key] = $value; + } + } - // Assign config values to the object - foreach ($config as $key => $value) - { - if (array_key_exists($key, Captcha::$config)) - { - Captcha::$config[$key] = $value; - } - } + // Store the config group name as well, so the drivers can access it + Captcha::$config['group'] = $group; - // Store the config group name as well, so the drivers can access it - Captcha::$config['group'] = $group; + // If using a background image, check if it exists + if (! empty($config['background'])) { + Captcha::$config['background'] = str_replace('\\', '/', realpath($config['background'])); - // If using a background image, check if it exists - if ( ! empty($config['background'])) - { - Captcha::$config['background'] = str_replace('\\', '/', realpath($config['background'])); + if (! is_file(Captcha::$config['background'])) { + throw new Kohana_Exception('captcha.file_not_found', Captcha::$config['background']); + } + } - if ( ! is_file(Captcha::$config['background'])) - throw new Kohana_Exception('captcha.file_not_found', Captcha::$config['background']); - } + // If using any fonts, check if they exist + if (! empty($config['fonts'])) { + Captcha::$config['fontpath'] = str_replace('\\', '/', realpath($config['fontpath'])) . '/'; - // If using any fonts, check if they exist - if ( ! empty($config['fonts'])) - { - Captcha::$config['fontpath'] = str_replace('\\', '/', realpath($config['fontpath'])).'/'; + foreach ($config['fonts'] as $font) { + if (! is_file(Captcha::$config['fontpath'] . $font)) { + throw new Kohana_Exception('captcha.file_not_found', Captcha::$config['fontpath'] . $font); + } + } + } - foreach ($config['fonts'] as $font) - { - if ( ! is_file(Captcha::$config['fontpath'].$font)) - throw new Kohana_Exception('captcha.file_not_found', Captcha::$config['fontpath'].$font); - } - } + // Set driver name + $driver = 'Captcha_' . ucfirst($config['style']) . '_Driver'; - // Set driver name - $driver = 'Captcha_'.ucfirst($config['style']).'_Driver'; + // Load the driver + if (! Kohana::auto_load($driver)) { + throw new Kohana_Exception('core.driver_not_found', $config['style'], get_class($this)); + } - // Load the driver - if ( ! Kohana::auto_load($driver)) - throw new Kohana_Exception('core.driver_not_found', $config['style'], get_class($this)); + // Initialize the driver + $this->driver = new $driver(); - // Initialize the driver - $this->driver = new $driver; + // Validate the driver + if (! ($this->driver instanceof Captcha_Driver)) { + throw new Kohana_Exception('core.driver_implements', $config['style'], get_class($this), 'Captcha_Driver'); + } - // Validate the driver - if ( ! ($this->driver instanceof Captcha_Driver)) - throw new Kohana_Exception('core.driver_implements', $config['style'], get_class($this), 'Captcha_Driver'); + Kohana::log('debug', 'Captcha Library initialized'); + } - Kohana::log('debug', 'Captcha Library initialized'); - } + /** + * Validates a Captcha response and updates response counter. + * + * @param string captcha response + * @return boolean + */ + public static function valid($response) + { + // Maximum one count per page load + static $counted; - /** - * Validates a Captcha response and updates response counter. - * - * @param string captcha response - * @return boolean - */ - public static function valid($response) - { - // Maximum one count per page load - static $counted; + // User has been promoted, always TRUE and don't count anymore + if (Captcha::instance()->promoted()) { + return true; + } - // User has been promoted, always TRUE and don't count anymore - if (Captcha::instance()->promoted()) - return TRUE; + // Challenge result + $result = (bool) Captcha::instance()->driver->valid($response); - // Challenge result - $result = (bool) Captcha::instance()->driver->valid($response); + // Increment response counter + if ($counted !== true) { + $counted = true; - // Increment response counter - if ($counted !== TRUE) - { - $counted = TRUE; + // Valid response + if ($result === true) { + Captcha::instance()->valid_count(Session::instance()->get('captcha_valid_count') + 1); + } else { + // Invalid response + Captcha::instance()->invalid_count(Session::instance()->get('captcha_invalid_count') + 1); + } + } - // Valid response - if ($result === TRUE) - { - Captcha::instance()->valid_count(Session::instance()->get('captcha_valid_count') + 1); - } - // Invalid response - else - { - Captcha::instance()->invalid_count(Session::instance()->get('captcha_invalid_count') + 1); - } - } + return $result; + } - return $result; - } + /** + * Gets or sets the number of valid Captcha responses for this session. + * + * @param integer new counter value + * @param boolean trigger invalid counter (for internal use only) + * @return integer counter value + */ + public function valid_count($new_count = null, $invalid = false) + { + // Pick the right session to use + $session = ($invalid === true) ? 'captcha_invalid_count' : 'captcha_valid_count'; - /** - * Gets or sets the number of valid Captcha responses for this session. - * - * @param integer new counter value - * @param boolean trigger invalid counter (for internal use only) - * @return integer counter value - */ - public function valid_count($new_count = NULL, $invalid = FALSE) - { - // Pick the right session to use - $session = ($invalid === TRUE) ? 'captcha_invalid_count' : 'captcha_valid_count'; + // Update counter + if ($new_count !== null) { + $new_count = (int) $new_count; - // Update counter - if ($new_count !== NULL) - { - $new_count = (int) $new_count; + // Reset counter = delete session + if ($new_count < 1) { + Session::instance()->delete($session); + } else { + // Set counter to new value + Session::instance()->set($session, (int) $new_count); + } - // Reset counter = delete session - if ($new_count < 1) - { - Session::instance()->delete($session); - } - // Set counter to new value - else - { - Session::instance()->set($session, (int) $new_count); - } + // Return new count + return (int) $new_count; + } - // Return new count - return (int) $new_count; - } + // Return current count + return (int) Session::instance()->get($session); + } - // Return current count - return (int) Session::instance()->get($session); - } + /** + * Gets or sets the number of invalid Captcha responses for this session. + * + * @param integer new counter value + * @return integer counter value + */ + public function invalid_count($new_count = null) + { + return $this->valid_count($new_count, true); + } - /** - * Gets or sets the number of invalid Captcha responses for this session. - * - * @param integer new counter value - * @return integer counter value - */ - public function invalid_count($new_count = NULL) - { - return $this->valid_count($new_count, TRUE); - } + /** + * Resets the Captcha response counters and removes the count sessions. + * + * @return void + */ + public function reset_count() + { + $this->valid_count(0); + $this->valid_count(0, true); + } - /** - * Resets the Captcha response counters and removes the count sessions. - * - * @return void - */ - public function reset_count() - { - $this->valid_count(0); - $this->valid_count(0, TRUE); - } + /** + * Checks whether user has been promoted after having given enough valid responses. + * + * @param integer valid response count threshold + * @return boolean + */ + public function promoted($threshold = null) + { + // Promotion has been disabled + if (Captcha::$config['promote'] === false) { + return false; + } - /** - * Checks whether user has been promoted after having given enough valid responses. - * - * @param integer valid response count threshold - * @return boolean - */ - public function promoted($threshold = NULL) - { - // Promotion has been disabled - if (Captcha::$config['promote'] === FALSE) - return FALSE; + // Use the config threshold + if ($threshold === null) { + $threshold = Captcha::$config['promote']; + } - // Use the config threshold - if ($threshold === NULL) - { - $threshold = Captcha::$config['promote']; - } + // Compare the valid response count to the threshold + return ($this->valid_count() >= $threshold); + } - // Compare the valid response count to the threshold - return ($this->valid_count() >= $threshold); - } + /** + * Returns or outputs the Captcha challenge. + * + * @param boolean TRUE to output html, e.g. + * @return mixed html string or void + */ + public function render($html = true) + { + return $this->driver->render($html); + } - /** - * Returns or outputs the Captcha challenge. - * - * @param boolean TRUE to output html, e.g. - * @return mixed html string or void - */ - public function render($html = TRUE) - { - return $this->driver->render($html); - } - - /** - * Magically outputs the Captcha challenge. - * - * @return mixed - */ - public function __toString() - { - return $this->render(); - } - -} // End Captcha Class \ No newline at end of file + /** + * Magically outputs the Captcha challenge. + * + * @return mixed + */ + public function __toString() + { + return $this->render(); + } +} +// End Captcha Class diff --git a/lib/kohana/system/libraries/Controller.php b/lib/kohana/system/libraries/Controller.php index 2f64c21..2f2bdd8 100644 --- a/lib/kohana/system/libraries/Controller.php +++ b/lib/kohana/system/libraries/Controller.php @@ -1,4 +1,11 @@ -uri = URI::instance(); + // URI should always be available + $this->uri = URI::instance(); - // Input should always be available - $this->input = Input::instance(); - } + // Input should always be available + $this->input = Input::instance(); + } - /** - * Handles methods that do not exist. - * - * @param string method name - * @param array arguments - * @return void - */ - public function __call($method, $args) - { - // Default to showing a 404 page - Event::run('system.404'); - } + /** + * Handles methods that do not exist. + * + * @param string method name + * @param array arguments + * @return void + */ + public function __call($method, $args) + { + // Default to showing a 404 page + Event::run('system.404'); + } - /** - * Includes a View within the controller scope. - * - * @param string view filename - * @param array array of view variables - * @return string - */ - public function _kohana_load_view($kohana_view_filename, $kohana_input_data) - { - if ($kohana_view_filename == '') - return; + /** + * Includes a View within the controller scope. + * + * @param string view filename + * @param array array of view variables + * @return string + */ + public function kohana_load_view($kohana_view_filename, $kohana_input_data) + { + if ($kohana_view_filename == '') { + return; + } - // Buffering on - ob_start(); + // Buffering on + ob_start(); - // Import the view variables to local namespace - extract($kohana_input_data, EXTR_SKIP); + // Import the view variables to local namespace + extract($kohana_input_data, EXTR_SKIP); - // Views are straight HTML pages with embedded PHP, so importing them - // this way insures that $this can be accessed as if the user was in - // the controller, which gives the easiest access to libraries in views - try - { - include $kohana_view_filename; - } - catch (Exception $e) - { - ob_end_clean(); - throw $e; - } + // Views are straight HTML pages with embedded PHP, so importing them + // this way insures that $this can be accessed as if the user was in + // the controller, which gives the easiest access to libraries in views + try { + include $kohana_view_filename; + } catch (Exception $e) { + ob_end_clean(); + throw $e; + } - // Fetch the output and close the buffer - return ob_get_clean(); - } - -} // End Controller Class \ No newline at end of file + // Fetch the output and close the buffer + return ob_get_clean(); + } +} +// End Controller Class diff --git a/lib/kohana/system/libraries/Database.php b/lib/kohana/system/libraries/Database.php index 6267f63..ccaf26a 100644 --- a/lib/kohana/system/libraries/Database.php +++ b/lib/kohana/system/libraries/Database.php @@ -1,4 +1,13 @@ - TRUE, - 'persistent' => FALSE, - 'connection' => '', - 'character_set' => 'utf8', - 'table_prefix' => '', - 'object' => TRUE, - 'cache' => FALSE, - 'escape' => TRUE, - ); - - // Database driver object - protected $driver; - protected $link; - - // Un-compiled parts of the SQL query - protected $select = array(); - protected $set = array(); - protected $from = array(); - protected $join = array(); - protected $where = array(); - protected $orderby = array(); - protected $order = array(); - protected $groupby = array(); - protected $having = array(); - protected $distinct = FALSE; - protected $limit = FALSE; - protected $offset = FALSE; - protected $last_query = ''; - - // Stack of queries for push/pop - protected $query_history = array(); - - /** - * Returns a singleton instance of Database. - * - * @param mixed configuration array or DSN - * @return Database_Core - */ - public static function & instance($name = 'default', $config = NULL) - { - if ( ! isset(Database::$instances[$name])) - { - // Create a new instance - Database::$instances[$name] = new Database($config === NULL ? $name : $config); - } - - return Database::$instances[$name]; - } - - /** - * Returns the name of a given database instance. - * - * @param Database instance of Database - * @return string - */ - public static function instance_name(Database $db) - { - return array_search($db, Database::$instances, TRUE); - } - - /** - * Sets up the database configuration, loads the Database_Driver. - * - * @throws Kohana_Database_Exception - */ - public function __construct($config = array()) - { - if (empty($config)) - { - // Load the default group - $config = Kohana::config('database.default'); - } - elseif (is_array($config) AND count($config) > 0) - { - if ( ! array_key_exists('connection', $config)) - { - $config = array('connection' => $config); - } - } - elseif (is_string($config)) - { - // The config is a DSN string - if (strpos($config, '://') !== FALSE) - { - $config = array('connection' => $config); - } - // The config is a group name - else - { - $name = $config; - - // Test the config group name - if (($config = Kohana::config('database.'.$config)) === NULL) - throw new Kohana_Database_Exception('database.undefined_group', $name); - } - } - - // Merge the default config with the passed config - $this->config = array_merge($this->config, $config); - - if (is_string($this->config['connection'])) - { - // Make sure the connection is valid - if (strpos($this->config['connection'], '://') === FALSE) - throw new Kohana_Database_Exception('database.invalid_dsn', $this->config['connection']); - - // Parse the DSN, creating an array to hold the connection parameters - $db = array - ( - 'type' => FALSE, - 'user' => FALSE, - 'pass' => FALSE, - 'host' => FALSE, - 'port' => FALSE, - 'socket' => FALSE, - 'database' => FALSE - ); - - // Get the protocol and arguments - list ($db['type'], $connection) = explode('://', $this->config['connection'], 2); - - if (strpos($connection, '@') !== FALSE) - { - // Get the username and password - list ($db['pass'], $connection) = explode('@', $connection, 2); - // Check if a password is supplied - $logindata = explode(':', $db['pass'], 2); - $db['pass'] = (count($logindata) > 1) ? $logindata[1] : ''; - $db['user'] = $logindata[0]; - - // Prepare for finding the database - $connection = explode('/', $connection); - - // Find the database name - $db['database'] = array_pop($connection); - - // Reset connection string - $connection = implode('/', $connection); - - // Find the socket - if (preg_match('/^unix\([^)]++\)/', $connection)) - { - // This one is a little hairy: we explode based on the end of - // the socket, removing the 'unix(' from the connection string - list ($db['socket'], $connection) = explode(')', substr($connection, 5), 2); - } - elseif (strpos($connection, ':') !== FALSE) - { - // Fetch the host and port name - list ($db['host'], $db['port']) = explode(':', $connection, 2); - } - else - { - $db['host'] = $connection; - } - } - else - { - // File connection - $connection = explode('/', $connection); - - // Find database file name - $db['database'] = array_pop($connection); - - // Find database directory name - $db['socket'] = implode('/', $connection).'/'; - } - - // Reset the connection array to the database config - $this->config['connection'] = $db; - } - // Set driver name - $driver = 'Database_'.ucfirst($this->config['connection']['type']).'_Driver'; - - // Load the driver - if ( ! Kohana::auto_load($driver)) - throw new Kohana_Database_Exception('core.driver_not_found', $this->config['connection']['type'], get_class($this)); - - // Initialize the driver - $this->driver = new $driver($this->config); - - // Validate the driver - if ( ! ($this->driver instanceof Database_Driver)) - throw new Kohana_Database_Exception('core.driver_implements', $this->config['connection']['type'], get_class($this), 'Database_Driver'); - - Kohana::log('debug', 'Database Library initialized'); - } - - /** - * Simple connect method to get the database queries up and running. - * - * @return void - */ - public function connect() - { - // A link can be a resource or an object - if ( ! is_resource($this->link) AND ! is_object($this->link)) - { - $this->link = $this->driver->connect(); - if ( ! is_resource($this->link) AND ! is_object($this->link)) - throw new Kohana_Database_Exception('database.connection', $this->driver->show_error()); - - // Clear password after successful connect - $this->config['connection']['pass'] = NULL; - } - } - - /** - * Runs a query into the driver and returns the result. - * - * @param string SQL query to execute - * @return Database_Result - */ - public function query($sql = '') - { - if ($sql == '') return FALSE; - - // No link? Connect! - $this->link or $this->connect(); - - // Start the benchmark - $start = microtime(TRUE); - - if (func_num_args() > 1) //if we have more than one argument ($sql) - { - $argv = func_get_args(); - $binds = (is_array(next($argv))) ? current($argv) : array_slice($argv, 1); - } - - // Compile binds if needed - if (isset($binds)) - { - $sql = $this->compile_binds($sql, $binds); - } - - // Fetch the result - $result = $this->driver->query($this->last_query = $sql); - - // Stop the benchmark - $stop = microtime(TRUE); - - if ($this->config['benchmark'] == TRUE) - { - // Benchmark the query - Database::$benchmarks[] = array('query' => $sql, 'time' => $stop - $start, 'rows' => count($result)); - } - - return $result; - } - - /** - * Selects the column names for a database query. - * - * @param string string or array of column names to select - * @return Database_Core This Database object. - */ - public function select($sql = '*') - { - if (func_num_args() > 1) - { - $sql = func_get_args(); - } - elseif (is_string($sql)) - { - $sql = explode(',', $sql); - } - else - { - $sql = (array) $sql; - } - - foreach ($sql as $val) - { - if (($val = trim($val)) === '') continue; - - if (strpos($val, '(') === FALSE AND $val !== '*') - { - if (preg_match('/^DISTINCT\s++(.+)$/i', $val, $matches)) - { - // Only prepend with table prefix if table name is specified - $val = (strpos($matches[1], '.') !== FALSE) ? $this->config['table_prefix'].$matches[1] : $matches[1]; - - $this->distinct = TRUE; - } - else - { - $val = (strpos($val, '.') !== FALSE) ? $this->config['table_prefix'].$val : $val; - } - - $val = $this->driver->escape_column($val); - } - - $this->select[] = $val; - } - - return $this; - } - - /** - * Selects the from table(s) for a database query. - * - * @param string string or array of tables to select - * @return Database_Core This Database object. - */ - public function from($sql) - { - if (func_num_args() > 1) - { - $sql = func_get_args(); - } - elseif (is_string($sql)) - { - $sql = explode(',', $sql); - } - else - { - $sql = array($sql); - } - - foreach ($sql as $val) - { - if (is_string($val)) - { - if (($val = trim($val)) === '') continue; - - // TODO: Temporary solution, this should be moved to database driver (AS is checked for twice) - if (stripos($val, ' AS ') !== FALSE) - { - $val = str_ireplace(' AS ', ' AS ', $val); - - list($table, $alias) = explode(' AS ', $val); - - // Attach prefix to both sides of the AS - $val = $this->config['table_prefix'].$table.' AS '.$this->config['table_prefix'].$alias; - } - else - { - $val = $this->config['table_prefix'].$val; - } - } - - $this->from[] = $val; - } - - return $this; - } - - /** - * Generates the JOIN portion of the query. - * - * @param string table name - * @param string|array where key or array of key => value pairs - * @param string where value - * @param string type of join - * @return Database_Core This Database object. - */ - public function join($table, $key, $value = NULL, $type = '') - { - $join = array(); - - if ( ! empty($type)) - { - $type = strtoupper(trim($type)); - - if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'), TRUE)) - { - $type = ''; - } - else - { - $type .= ' '; - } - } - - $cond = array(); - $keys = is_array($key) ? $key : array($key => $value); - foreach ($keys as $key => $value) - { - $key = (strpos($key, '.') !== FALSE) ? $this->config['table_prefix'].$key : $key; - - if (is_string($value)) - { - // Only escape if it's a string - $value = $this->driver->escape_column($this->config['table_prefix'].$value); - } - - $cond[] = $this->driver->where($key, $value, 'AND ', count($cond), FALSE); - } - - if ( ! is_array($this->join)) - { - $this->join = array(); - } - - if ( ! is_array($table)) - { - $table = array($table); - } - - foreach ($table as $t) - { - if (is_string($t)) - { - // TODO: Temporary solution, this should be moved to database driver (AS is checked for twice) - if (stripos($t, ' AS ') !== FALSE) - { - $t = str_ireplace(' AS ', ' AS ', $t); - - list($table, $alias) = explode(' AS ', $t); - - // Attach prefix to both sides of the AS - $t = $this->config['table_prefix'].$table.' AS '.$this->config['table_prefix'].$alias; - } - else - { - $t = $this->config['table_prefix'].$t; - } - } - - $join['tables'][] = $this->driver->escape_column($t); - } - - $join['conditions'] = '('.trim(implode(' ', $cond)).')'; - $join['type'] = $type; - - $this->join[] = $join; - - return $this; - } - - - /** - * Selects the where(s) for a database query. - * - * @param string|array key name or array of key => value pairs - * @param string value to match with key - * @param boolean disable quoting of WHERE clause - * @return Database_Core This Database object. - */ - public function where($key, $value = NULL, $quote = TRUE) - { - $quote = (func_num_args() < 2 AND ! is_array($key)) ? -1 : $quote; - if (is_object($key)) - { - $keys = array((string) $key => ''); - } - elseif ( ! is_array($key)) - { - $keys = array($key => $value); - } - else - { - $keys = $key; - } - - foreach ($keys as $key => $value) - { - $key = (strpos($key, '.') !== FALSE) ? $this->config['table_prefix'].$key : $key; - $this->where[] = $this->driver->where($key, $value, 'AND ', count($this->where), $quote); - } - - return $this; - } - - /** - * Selects the or where(s) for a database query. - * - * @param string|array key name or array of key => value pairs - * @param string value to match with key - * @param boolean disable quoting of WHERE clause - * @return Database_Core This Database object. - */ - public function orwhere($key, $value = NULL, $quote = TRUE) - { - $quote = (func_num_args() < 2 AND ! is_array($key)) ? -1 : $quote; - if (is_object($key)) - { - $keys = array((string) $key => ''); - } - elseif ( ! is_array($key)) - { - $keys = array($key => $value); - } - else - { - $keys = $key; - } - - foreach ($keys as $key => $value) - { - $key = (strpos($key, '.') !== FALSE) ? $this->config['table_prefix'].$key : $key; - $this->where[] = $this->driver->where($key, $value, 'OR ', count($this->where), $quote); - } - - return $this; - } - - /** - * Selects the like(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string like value to match with field - * @param boolean automatically add starting and ending wildcards - * @return Database_Core This Database object. - */ - public function like($field, $match = '', $auto = TRUE) - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->like($field, $match, $auto, 'AND ', count($this->where)); - } - - return $this; - } - - /** - * Selects the or like(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string like value to match with field - * @param boolean automatically add starting and ending wildcards - * @return Database_Core This Database object. - */ - public function orlike($field, $match = '', $auto = TRUE) - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->like($field, $match, $auto, 'OR ', count($this->where)); - } - - return $this; - } - - /** - * Selects the not like(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string like value to match with field - * @param boolean automatically add starting and ending wildcards - * @return Database_Core This Database object. - */ - public function notlike($field, $match = '', $auto = TRUE) - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->notlike($field, $match, $auto, 'AND ', count($this->where)); - } - - return $this; - } - - /** - * Selects the or not like(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string like value to match with field - * @return Database_Core This Database object. - */ - public function ornotlike($field, $match = '', $auto = TRUE) - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->notlike($field, $match, $auto, 'OR ', count($this->where)); - } - - return $this; - } - - /** - * Selects the like(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string like value to match with field - * @return Database_Core This Database object. - */ - public function regex($field, $match = '') - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->regex($field, $match, 'AND ', count($this->where)); - } - - return $this; - } - - /** - * Selects the or like(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string like value to match with field - * @return Database_Core This Database object. - */ - public function orregex($field, $match = '') - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->regex($field, $match, 'OR ', count($this->where)); - } - - return $this; - } - - /** - * Selects the not regex(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string regex value to match with field - * @return Database_Core This Database object. - */ - public function notregex($field, $match = '') - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->notregex($field, $match, 'AND ', count($this->where)); - } - - return $this; - } - - /** - * Selects the or not regex(s) for a database query. - * - * @param string|array field name or array of field => match pairs - * @param string regex value to match with field - * @return Database_Core This Database object. - */ - public function ornotregex($field, $match = '') - { - $fields = is_array($field) ? $field : array($field => $match); - - foreach ($fields as $field => $match) - { - $field = (strpos($field, '.') !== FALSE) ? $this->config['table_prefix'].$field : $field; - $this->where[] = $this->driver->notregex($field, $match, 'OR ', count($this->where)); - } - - return $this; - } - - /** - * Chooses the column to group by in a select query. - * - * @param string column name to group by - * @return Database_Core This Database object. - */ - public function groupby($by) - { - if ( ! is_array($by)) - { - $by = explode(',', (string) $by); - } - - foreach ($by as $val) - { - $val = trim($val); - - if ($val != '') - { - // Add the table prefix if we are using table.column names - if(strpos($val, '.')) - { - $val = $this->config['table_prefix'].$val; - } - - $this->groupby[] = $this->driver->escape_column($val); - } - } - - return $this; - } - - /** - * Selects the having(s) for a database query. - * - * @param string|array key name or array of key => value pairs - * @param string value to match with key - * @param boolean disable quoting of WHERE clause - * @return Database_Core This Database object. - */ - public function having($key, $value = '', $quote = TRUE) - { - $this->having[] = $this->driver->where($key, $value, 'AND', count($this->having), TRUE); - return $this; - } - - /** - * Selects the or having(s) for a database query. - * - * @param string|array key name or array of key => value pairs - * @param string value to match with key - * @param boolean disable quoting of WHERE clause - * @return Database_Core This Database object. - */ - public function orhaving($key, $value = '', $quote = TRUE) - { - $this->having[] = $this->driver->where($key, $value, 'OR', count($this->having), TRUE); - return $this; - } - - /** - * Chooses which column(s) to order the select query by. - * - * @param string|array column(s) to order on, can be an array, single column, or comma seperated list of columns - * @param string direction of the order - * @return Database_Core This Database object. - */ - public function orderby($orderby, $direction = NULL) - { - if ( ! is_array($orderby)) - { - $orderby = array($orderby => $direction); - } - - foreach ($orderby as $column => $direction) - { - $direction = strtoupper(trim($direction)); - - // Add a direction if the provided one isn't valid - if ( ! in_array($direction, array('ASC', 'DESC', 'RAND()', 'RANDOM()', 'NULL'))) - { - $direction = 'ASC'; - } - - // Add the table prefix if a table.column was passed - if (strpos($column, '.')) - { - $column = $this->config['table_prefix'].$column; - } - - $this->orderby[] = $this->driver->escape_column($column).' '.$direction; - } - - return $this; - } - - /** - * Selects the limit section of a query. - * - * @param integer number of rows to limit result to - * @param integer offset in result to start returning rows from - * @return Database_Core This Database object. - */ - public function limit($limit, $offset = NULL) - { - $this->limit = (int) $limit; - - if ($offset !== NULL OR ! is_int($this->offset)) - { - $this->offset($offset); - } - - return $this; - } - - /** - * Sets the offset portion of a query. - * - * @param integer offset value - * @return Database_Core This Database object. - */ - public function offset($value) - { - $this->offset = (int) $value; - - return $this; - } - - /** - * Allows key/value pairs to be set for inserting or updating. - * - * @param string|array key name or array of key => value pairs - * @param string value to match with key - * @return Database_Core This Database object. - */ - public function set($key, $value = '') - { - if ( ! is_array($key)) - { - $key = array($key => $value); - } - - foreach ($key as $k => $v) - { - // Add a table prefix if the column includes the table. - if (strpos($k, '.')) - $k = $this->config['table_prefix'].$k; - - $this->set[$k] = $this->driver->escape($v); - } - - return $this; - } - - /** - * Compiles the select statement based on the other functions called and runs the query. - * - * @param string table name - * @param string limit clause - * @param string offset clause - * @return Database_Result - */ - public function get($table = '', $limit = NULL, $offset = NULL) - { - if ($table != '') - { - $this->from($table); - } - - if ( ! is_null($limit)) - { - $this->limit($limit, $offset); - } - - $sql = $this->driver->compile_select(get_object_vars($this)); - - $this->reset_select(); - - $result = $this->query($sql); - - $this->last_query = $sql; - - return $result; - } - - /** - * Compiles the select statement based on the other functions called and runs the query. - * - * @param string table name - * @param array where clause - * @param string limit clause - * @param string offset clause - * @return Database_Core This Database object. - */ - public function getwhere($table = '', $where = NULL, $limit = NULL, $offset = NULL) - { - if ($table != '') - { - $this->from($table); - } - - if ( ! is_null($where)) - { - $this->where($where); - } - - if ( ! is_null($limit)) - { - $this->limit($limit, $offset); - } - - $sql = $this->driver->compile_select(get_object_vars($this)); - - $this->reset_select(); - - $result = $this->query($sql); - - return $result; - } - - /** - * Compiles the select statement based on the other functions called and returns the query string. - * - * @param string table name - * @param string limit clause - * @param string offset clause - * @return string sql string - */ - public function compile($table = '', $limit = NULL, $offset = NULL) - { - if ($table != '') - { - $this->from($table); - } - - if ( ! is_null($limit)) - { - $this->limit($limit, $offset); - } - - $sql = $this->driver->compile_select(get_object_vars($this)); - - $this->reset_select(); - - return $sql; - } - - /** - * Compiles an insert string and runs the query. - * - * @param string table name - * @param array array of key/value pairs to insert - * @return Database_Result Query result - */ - public function insert($table = '', $set = NULL) - { - if ( ! is_null($set)) - { - $this->set($set); - } - - if ($this->set == NULL) - throw new Kohana_Database_Exception('database.must_use_set'); - - if ($table == '') - { - if ( ! isset($this->from[0])) - throw new Kohana_Database_Exception('database.must_use_table'); - - $table = $this->from[0]; - } - - // If caching is enabled, clear the cache before inserting - ($this->config['cache'] === TRUE) and $this->clear_cache(); - - $sql = $this->driver->insert($this->config['table_prefix'].$table, array_keys($this->set), array_values($this->set)); - - $this->reset_write(); - - return $this->query($sql); - } - - /** - * Adds an "IN" condition to the where clause - * - * @param string Name of the column being examined - * @param mixed An array or string to match against - * @param bool Generate a NOT IN clause instead - * @return Database_Core This Database object. - */ - public function in($field, $values, $not = FALSE) - { - if (is_array($values)) - { - $escaped_values = array(); - foreach ($values as $v) - { - if (is_numeric($v)) - { - $escaped_values[] = $v; - } - else - { - $escaped_values[] = "'".$this->driver->escape_str($v)."'"; - } - } - $values = implode(",", $escaped_values); - } - - $where = $this->driver->escape_column(((strpos($field,'.') !== FALSE) ? $this->config['table_prefix'] : ''). $field).' '.($not === TRUE ? 'NOT ' : '').'IN ('.$values.')'; - $this->where[] = $this->driver->where($where, '', 'AND ', count($this->where), -1); - - return $this; - } - - /** - * Adds a "NOT IN" condition to the where clause - * - * @param string Name of the column being examined - * @param mixed An array or string to match against - * @return Database_Core This Database object. - */ - public function notin($field, $values) - { - return $this->in($field, $values, TRUE); - } - - /** - * Compiles a merge string and runs the query. - * - * @param string table name - * @param array array of key/value pairs to merge - * @return Database_Result Query result - */ - public function merge($table = '', $set = NULL) - { - if ( ! is_null($set)) - { - $this->set($set); - } - - if ($this->set == NULL) - throw new Kohana_Database_Exception('database.must_use_set'); - - if ($table == '') - { - if ( ! isset($this->from[0])) - throw new Kohana_Database_Exception('database.must_use_table'); - - $table = $this->from[0]; - } - - $sql = $this->driver->merge($this->config['table_prefix'].$table, array_keys($this->set), array_values($this->set)); - - $this->reset_write(); - return $this->query($sql); - } - - /** - * Compiles an update string and runs the query. - * - * @param string table name - * @param array associative array of update values - * @param array where clause - * @return Database_Result Query result - */ - public function update($table = '', $set = NULL, $where = NULL) - { - if ( is_array($set)) - { - $this->set($set); - } - - if ( ! is_null($where)) - { - $this->where($where); - } - - if ($this->set == FALSE) - throw new Kohana_Database_Exception('database.must_use_set'); - - if ($table == '') - { - if ( ! isset($this->from[0])) - throw new Kohana_Database_Exception('database.must_use_table'); - - $table = $this->from[0]; - } - - $sql = $this->driver->update($this->config['table_prefix'].$table, $this->set, $this->where); - - $this->reset_write(); - return $this->query($sql); - } - - /** - * Compiles a delete string and runs the query. - * - * @param string table name - * @param array where clause - * @return Database_Result Query result - */ - public function delete($table = '', $where = NULL) - { - if ($table == '') - { - if ( ! isset($this->from[0])) - throw new Kohana_Database_Exception('database.must_use_table'); - - $table = $this->from[0]; - } - else - { - $table = $this->config['table_prefix'].$table; - } - - if (! is_null($where)) - { - $this->where($where); - } - - if (count($this->where) < 1) - throw new Kohana_Database_Exception('database.must_use_where'); - - $sql = $this->driver->delete($table, $this->where); - - $this->reset_write(); - return $this->query($sql); - } - - /** - * Returns the last query run. - * - * @return string SQL - */ - public function last_query() - { - return $this->last_query; - } - - /** - * Count query records. - * - * @param string table name - * @param array where clause - * @return integer - */ - public function count_records($table = FALSE, $where = NULL) - { - if (count($this->from) < 1) - { - if ($table == FALSE) - throw new Kohana_Database_Exception('database.must_use_table'); - - $this->from($table); - } - - if ($where !== NULL) - { - $this->where($where); - } - - $query = $this->select('COUNT(*) AS '.$this->escape_column('records_found'))->get()->result(TRUE); - - return (int) $query->current()->records_found; - } - - /** - * Resets all private select variables. - * - * @return void - */ - protected function reset_select() - { - $this->select = array(); - $this->from = array(); - $this->join = array(); - $this->where = array(); - $this->orderby = array(); - $this->groupby = array(); - $this->having = array(); - $this->distinct = FALSE; - $this->limit = FALSE; - $this->offset = FALSE; - } - - /** - * Resets all private insert and update variables. - * - * @return void - */ - protected function reset_write() - { - $this->set = array(); - $this->from = array(); - $this->where = array(); - } - - /** - * Lists all the tables in the current database. - * - * @return array - */ - public function list_tables() - { - $this->link or $this->connect(); - - return $this->driver->list_tables(); - } - - /** - * See if a table exists in the database. - * - * @param string table name - * @param boolean True to attach table prefix - * @return boolean - */ - public function table_exists($table_name, $prefix = TRUE) - { - if ($prefix) - return in_array($this->config['table_prefix'].$table_name, $this->list_tables()); - else - return in_array($table_name, $this->list_tables()); - } - - /** - * Combine a SQL statement with the bind values. Used for safe queries. - * - * @param string query to bind to the values - * @param array array of values to bind to the query - * @return string - */ - public function compile_binds($sql, $binds) - { - foreach ((array) $binds as $val) - { - // If the SQL contains no more bind marks ("?"), we're done. - if (($next_bind_pos = strpos($sql, '?')) === FALSE) - break; - - // Properly escape the bind value. - $val = $this->driver->escape($val); - - // Temporarily replace possible bind marks ("?"), in the bind value itself, with a placeholder. - $val = str_replace('?', '{%B%}', $val); - - // Replace the first bind mark ("?") with its corresponding value. - $sql = substr($sql, 0, $next_bind_pos).$val.substr($sql, $next_bind_pos + 1); - } - - // Restore placeholders. - return str_replace('{%B%}', '?', $sql); - } - - /** - * Get the field data for a database table, along with the field's attributes. - * - * @param string table name - * @return array - */ - public function field_data($table = '') - { - $this->link or $this->connect(); - - return $this->driver->field_data($this->config['table_prefix'].$table); - } - - /** - * Get the field data for a database table, along with the field's attributes. - * - * @param string table name - * @return array - */ - public function list_fields($table = '') - { - $this->link or $this->connect(); - - return $this->driver->list_fields($this->config['table_prefix'].$table); - } - - /** - * Escapes a value for a query. - * - * @param mixed value to escape - * @return string - */ - public function escape($value) - { - return $this->driver->escape($value); - } - - /** - * Escapes a string for a query. - * - * @param string string to escape - * @return string - */ - public function escape_str($str) - { - return $this->driver->escape_str($str); - } - - /** - * Escapes a table name for a query. - * - * @param string string to escape - * @return string - */ - public function escape_table($table) - { - return $this->driver->escape_table($table); - } - - /** - * Escapes a column name for a query. - * - * @param string string to escape - * @return string - */ - public function escape_column($table) - { - return $this->driver->escape_column($table); - } - - /** - * Returns table prefix of current configuration. - * - * @return string - */ - public function table_prefix() - { - return $this->config['table_prefix']; - } - - /** - * Clears the query cache. - * - * @param string|TRUE clear cache by SQL statement or TRUE for last query - * @return Database_Core This Database object. - */ - public function clear_cache($sql = NULL) - { - if ($sql === TRUE) - { - $this->driver->clear_cache($this->last_query); - } - elseif (is_string($sql)) - { - $this->driver->clear_cache($sql); - } - else - { - $this->driver->clear_cache(); - } - - return $this; - } - - /** - * Pushes existing query space onto the query stack. Use push - * and pop to prevent queries from clashing before they are - * executed - * - * @return Database_Core This Databaes object - */ - public function push() - { - array_push($this->query_history, array( - $this->select, - $this->from, - $this->join, - $this->where, - $this->orderby, - $this->order, - $this->groupby, - $this->having, - $this->distinct, - $this->limit, - $this->offset - )); - - $this->reset_select(); - - return $this; - } - - /** - * Pops from query stack into the current query space. - * - * @return Database_Core This Databaes object - */ - public function pop() - { - if (count($this->query_history) == 0) - { - // No history - return $this; - } - - list( - $this->select, - $this->from, - $this->join, - $this->where, - $this->orderby, - $this->order, - $this->groupby, - $this->having, - $this->distinct, - $this->limit, - $this->offset - ) = array_pop($this->query_history); - - return $this; - } - - /** - * Count the number of records in the last query, without LIMIT or OFFSET applied. - * - * @return integer - */ - public function count_last_query() - { - if ($sql = $this->last_query()) - { - if (stripos($sql, 'LIMIT') !== FALSE) - { - // Remove LIMIT from the SQL - $sql = preg_replace('/\sLIMIT\s+[^a-z]+/i', ' ', $sql); - } - - if (stripos($sql, 'OFFSET') !== FALSE) - { - // Remove OFFSET from the SQL - $sql = preg_replace('/\sOFFSET\s+\d+/i', '', $sql); - } - - // Get the total rows from the last query executed - $result = $this->query - ( - 'SELECT COUNT(*) AS '.$this->escape_column('total_rows').' '. - 'FROM ('.trim($sql).') AS '.$this->escape_table('counted_results') - ); - - // Return the total number of rows from the query - return (int) $result->current()->total_rows; - } - - return FALSE; - } - -} // End Database Class +class Database_Core +{ + // Database instances + public static $instances = array(); + + // Global benchmark + public static $benchmarks = array(); + + // Configuration + protected $config = array + ( + 'benchmark' => true, + 'persistent' => false, + 'connection' => '', + 'character_set' => 'utf8', + 'table_prefix' => '', + 'object' => true, + 'cache' => false, + 'escape' => true, + ); + + // Database driver object + protected $driver; + protected $link; + + // Un-compiled parts of the SQL query + protected $select = array(); + protected $set = array(); + protected $from = array(); + protected $join = array(); + protected $where = array(); + protected $orderby = array(); + protected $order = array(); + protected $groupby = array(); + protected $having = array(); + protected $distinct = false; + protected $limit = false; + protected $offset = false; + protected $last_query = ''; + + // Stack of queries for push/pop + protected $query_history = array(); + + /** + * Returns a singleton instance of Database. + * + * @param mixed configuration array or DSN + * @return Database_Core + */ + public static function & instance($name = 'default', $config = null) + { + if (! isset(Database::$instances[$name])) { + // Create a new instance + Database::$instances[$name] = new Database($config === null ? $name : $config); + } + + return Database::$instances[$name]; + } + + /** + * Returns the name of a given database instance. + * + * @param Database instance of Database + * @return string + */ + public static function instance_name(Database $db) + { + return array_search($db, Database::$instances, true); + } + + /** + * Sets up the database configuration, loads the Database_Driver. + * + * @throws Kohana_Database_Exception + */ + public function __construct($config = array()) + { + if (empty($config)) { + // Load the default group + $config = Kohana::config('database.default'); + } elseif (is_array($config) and count($config) > 0) { + if (! array_key_exists('connection', $config)) { + $config = array('connection' => $config); + } + } elseif (is_string($config)) { + // The config is a DSN string + if (strpos($config, '://') !== false) { + $config = array('connection' => $config); + } else { + // The config is a group name + $name = $config; + + // Test the config group name + if (($config = Kohana::config('database.' . $config)) === null) { + throw new Kohana_Database_Exception('database.undefined_group', $name); + } + } + } + + // Merge the default config with the passed config + $this->config = array_merge($this->config, $config); + + if (is_string($this->config['connection'])) { + // Make sure the connection is valid + if (strpos($this->config['connection'], '://') === false) { + throw new Kohana_Database_Exception('database.invalid_dsn', $this->config['connection']); + } + + // Parse the DSN, creating an array to hold the connection parameters + $db = array + ( + 'type' => false, + 'user' => false, + 'pass' => false, + 'host' => false, + 'port' => false, + 'socket' => false, + 'database' => false + ); + + // Get the protocol and arguments + list ($db['type'], $connection) = explode('://', $this->config['connection'], 2); + + if (strpos($connection, '@') !== false) { + // Get the username and password + list ($db['pass'], $connection) = explode('@', $connection, 2); + // Check if a password is supplied + $logindata = explode(':', $db['pass'], 2); + $db['pass'] = (count($logindata) > 1) ? $logindata[1] : ''; + $db['user'] = $logindata[0]; + + // Prepare for finding the database + $connection = explode('/', $connection); + + // Find the database name + $db['database'] = array_pop($connection); + + // Reset connection string + $connection = implode('/', $connection); + + // Find the socket + if (preg_match('/^unix\([^)]++\)/', $connection)) { + // This one is a little hairy: we explode based on the end of + // the socket, removing the 'unix(' from the connection string + list ($db['socket'], $connection) = explode(')', substr($connection, 5), 2); + } elseif (strpos($connection, ':') !== false) { + // Fetch the host and port name + list ($db['host'], $db['port']) = explode(':', $connection, 2); + } else { + $db['host'] = $connection; + } + } else { + // File connection + $connection = explode('/', $connection); + + // Find database file name + $db['database'] = array_pop($connection); + + // Find database directory name + $db['socket'] = implode('/', $connection) . '/'; + } + + // Reset the connection array to the database config + $this->config['connection'] = $db; + } + // Set driver name + $driver = 'Database_' . ucfirst($this->config['connection']['type']) . '_Driver'; + + // Load the driver + if (! Kohana::auto_load($driver)) { + throw new Kohana_Database_Exception('core.driver_not_found', $this->config['connection']['type'], get_class($this)); + } + + // Initialize the driver + $this->driver = new $driver($this->config); + + // Validate the driver + if (! ($this->driver instanceof Database_Driver)) { + throw new Kohana_Database_Exception('core.driver_implements', $this->config['connection']['type'], get_class($this), 'Database_Driver'); + } + + Kohana::log('debug', 'Database Library initialized'); + } + + /** + * Simple connect method to get the database queries up and running. + * + * @return void + */ + public function connect() + { + // A link can be a resource or an object + if (! is_resource($this->link) and ! is_object($this->link)) { + $this->link = $this->driver->connect(); + if (! is_resource($this->link) and ! is_object($this->link)) { + throw new Kohana_Database_Exception('database.connection', $this->driver->show_error()); + } + + // Clear password after successful connect + $this->config['connection']['pass'] = null; + } + } + + /** + * Runs a query into the driver and returns the result. + * + * @param string SQL query to execute + * @return Database_Result + */ + public function query($sql = '') + { + if ($sql == '') { + return false; + } + + // No link? Connect! + $this->link or $this->connect(); + + // Start the benchmark + $start = microtime(true); + + if (func_num_args() > 1) { //if we have more than one argument ($sql) + $argv = func_get_args(); + $binds = (is_array(next($argv))) ? current($argv) : array_slice($argv, 1); + } + + // Compile binds if needed + if (isset($binds)) { + $sql = $this->compile_binds($sql, $binds); + } + + // Fetch the result + $result = $this->driver->query($this->last_query = $sql); + + // Stop the benchmark + $stop = microtime(true); + + if ($this->config['benchmark'] == true) { + // Benchmark the query + Database::$benchmarks[] = array('query' => $sql, 'time' => $stop - $start, 'rows' => count($result)); + } + + return $result; + } + + /** + * Selects the column names for a database query. + * + * @param string string or array of column names to select + * @return Database_Core This Database object. + */ + public function select($sql = '*') + { + if (func_num_args() > 1) { + $sql = func_get_args(); + } elseif (is_string($sql)) { + $sql = explode(',', $sql); + } else { + $sql = (array) $sql; + } + + foreach ($sql as $val) { + if (($val = trim($val)) === '') { + continue; + } + + if (strpos($val, '(') === false and $val !== '*') { + if (preg_match('/^DISTINCT\s++(.+)$/i', $val, $matches)) { + // Only prepend with table prefix if table name is specified + $val = (strpos($matches[1], '.') !== false) ? $this->config['table_prefix'] . $matches[1] : $matches[1]; + + $this->distinct = true; + } else { + $val = (strpos($val, '.') !== false) ? $this->config['table_prefix'] . $val : $val; + } + + $val = $this->driver->escape_column($val); + } + + $this->select[] = $val; + } + + return $this; + } + + /** + * Selects the from table(s) for a database query. + * + * @param string string or array of tables to select + * @return Database_Core This Database object. + */ + public function from($sql) + { + if (func_num_args() > 1) { + $sql = func_get_args(); + } elseif (is_string($sql)) { + $sql = explode(',', $sql); + } else { + $sql = array($sql); + } + + foreach ($sql as $val) { + if (is_string($val)) { + if (($val = trim($val)) === '') { + continue; + } + + // TODO: Temporary solution, this should be moved to database driver (AS is checked for twice) + if (stripos($val, ' AS ') !== false) { + $val = str_ireplace(' AS ', ' AS ', $val); + + list($table, $alias) = explode(' AS ', $val); + + // Attach prefix to both sides of the AS + $val = $this->config['table_prefix'] . $table . ' AS ' . $this->config['table_prefix'] . $alias; + } else { + $val = $this->config['table_prefix'] . $val; + } + } + + $this->from[] = $val; + } + + return $this; + } + + /** + * Generates the JOIN portion of the query. + * + * @param string table name + * @param string|array where key or array of key => value pairs + * @param string where value + * @param string type of join + * @return Database_Core This Database object. + */ + public function join($table, $key, $value = null, $type = '') + { + $join = array(); + + if (! empty($type)) { + $type = strtoupper(trim($type)); + + if (! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER'), true)) { + $type = ''; + } else { + $type .= ' '; + } + } + + $cond = array(); + $keys = is_array($key) ? $key : array($key => $value); + foreach ($keys as $key => $value) { + $key = (strpos($key, '.') !== false) ? $this->config['table_prefix'] . $key : $key; + + if (is_string($value)) { + // Only escape if it's a string + $value = $this->driver->escape_column($this->config['table_prefix'] . $value); + } + + $cond[] = $this->driver->where($key, $value, 'AND ', count($cond), false); + } + + if (! is_array($this->join)) { + $this->join = array(); + } + + if (! is_array($table)) { + $table = array($table); + } + + foreach ($table as $t) { + if (is_string($t)) { + // TODO: Temporary solution, this should be moved to database driver (AS is checked for twice) + if (stripos($t, ' AS ') !== false) { + $t = str_ireplace(' AS ', ' AS ', $t); + + list($table, $alias) = explode(' AS ', $t); + + // Attach prefix to both sides of the AS + $t = $this->config['table_prefix'] . $table . ' AS ' . $this->config['table_prefix'] . $alias; + } else { + $t = $this->config['table_prefix'] . $t; + } + } + + $join['tables'][] = $this->driver->escape_column($t); + } + + $join['conditions'] = '(' . trim(implode(' ', $cond)) . ')'; + $join['type'] = $type; + + $this->join[] = $join; + + return $this; + } + + + /** + * Selects the where(s) for a database query. + * + * @param string|array key name or array of key => value pairs + * @param string value to match with key + * @param boolean disable quoting of WHERE clause + * @return Database_Core This Database object. + */ + public function where($key, $value = null, $quote = true) + { + $quote = (func_num_args() < 2 and ! is_array($key)) ? -1 : $quote; + if (is_object($key)) { + $keys = array((string) $key => ''); + } elseif (! is_array($key)) { + $keys = array($key => $value); + } else { + $keys = $key; + } + + foreach ($keys as $key => $value) { + $key = (strpos($key, '.') !== false) ? $this->config['table_prefix'] . $key : $key; + $this->where[] = $this->driver->where($key, $value, 'AND ', count($this->where), $quote); + } + + return $this; + } + + /** + * Selects the or where(s) for a database query. + * + * @param string|array key name or array of key => value pairs + * @param string value to match with key + * @param boolean disable quoting of WHERE clause + * @return Database_Core This Database object. + */ + public function orwhere($key, $value = null, $quote = true) + { + $quote = (func_num_args() < 2 and ! is_array($key)) ? -1 : $quote; + if (is_object($key)) { + $keys = array((string) $key => ''); + } elseif (! is_array($key)) { + $keys = array($key => $value); + } else { + $keys = $key; + } + + foreach ($keys as $key => $value) { + $key = (strpos($key, '.') !== false) ? $this->config['table_prefix'] . $key : $key; + $this->where[] = $this->driver->where($key, $value, 'OR ', count($this->where), $quote); + } + + return $this; + } + + /** + * Selects the like(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string like value to match with field + * @param boolean automatically add starting and ending wildcards + * @return Database_Core This Database object. + */ + public function like($field, $match = '', $auto = true) + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->like($field, $match, $auto, 'AND ', count($this->where)); + } + + return $this; + } + + /** + * Selects the or like(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string like value to match with field + * @param boolean automatically add starting and ending wildcards + * @return Database_Core This Database object. + */ + public function orlike($field, $match = '', $auto = true) + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->like($field, $match, $auto, 'OR ', count($this->where)); + } + + return $this; + } + + /** + * Selects the not like(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string like value to match with field + * @param boolean automatically add starting and ending wildcards + * @return Database_Core This Database object. + */ + public function notlike($field, $match = '', $auto = true) + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->notlike($field, $match, $auto, 'AND ', count($this->where)); + } + + return $this; + } + + /** + * Selects the or not like(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string like value to match with field + * @return Database_Core This Database object. + */ + public function ornotlike($field, $match = '', $auto = true) + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->notlike($field, $match, $auto, 'OR ', count($this->where)); + } + + return $this; + } + + /** + * Selects the like(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string like value to match with field + * @return Database_Core This Database object. + */ + public function regex($field, $match = '') + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->regex($field, $match, 'AND ', count($this->where)); + } + + return $this; + } + + /** + * Selects the or like(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string like value to match with field + * @return Database_Core This Database object. + */ + public function orregex($field, $match = '') + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->regex($field, $match, 'OR ', count($this->where)); + } + + return $this; + } + + /** + * Selects the not regex(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string regex value to match with field + * @return Database_Core This Database object. + */ + public function notregex($field, $match = '') + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->notregex($field, $match, 'AND ', count($this->where)); + } + + return $this; + } + + /** + * Selects the or not regex(s) for a database query. + * + * @param string|array field name or array of field => match pairs + * @param string regex value to match with field + * @return Database_Core This Database object. + */ + public function ornotregex($field, $match = '') + { + $fields = is_array($field) ? $field : array($field => $match); + + foreach ($fields as $field => $match) { + $field = (strpos($field, '.') !== false) ? $this->config['table_prefix'] . $field : $field; + $this->where[] = $this->driver->notregex($field, $match, 'OR ', count($this->where)); + } + + return $this; + } + + /** + * Chooses the column to group by in a select query. + * + * @param string column name to group by + * @return Database_Core This Database object. + */ + public function groupby($by) + { + if (! is_array($by)) { + $by = explode(',', (string) $by); + } + + foreach ($by as $val) { + $val = trim($val); + + if ($val != '') { + // Add the table prefix if we are using table.column names + if (strpos($val, '.')) { + $val = $this->config['table_prefix'] . $val; + } + + $this->groupby[] = $this->driver->escape_column($val); + } + } + + return $this; + } + + /** + * Selects the having(s) for a database query. + * + * @param string|array key name or array of key => value pairs + * @param string value to match with key + * @param boolean disable quoting of WHERE clause + * @return Database_Core This Database object. + */ + public function having($key, $value = '', $quote = true) + { + $this->having[] = $this->driver->where($key, $value, 'AND', count($this->having), true); + return $this; + } + + /** + * Selects the or having(s) for a database query. + * + * @param string|array key name or array of key => value pairs + * @param string value to match with key + * @param boolean disable quoting of WHERE clause + * @return Database_Core This Database object. + */ + public function orhaving($key, $value = '', $quote = true) + { + $this->having[] = $this->driver->where($key, $value, 'OR', count($this->having), true); + return $this; + } + + /** + * Chooses which column(s) to order the select query by. + * + * @param string|array column(s) to order on, can be an array, single column, or comma seperated list of columns + * @param string direction of the order + * @return Database_Core This Database object. + */ + public function orderby($orderby, $direction = null) + { + if (! is_array($orderby)) { + $orderby = array($orderby => $direction); + } + + foreach ($orderby as $column => $direction) { + $direction = strtoupper(trim($direction)); + + // Add a direction if the provided one isn't valid + if (! in_array($direction, array('ASC', 'DESC', 'RAND()', 'RANDOM()', 'NULL'))) { + $direction = 'ASC'; + } + + // Add the table prefix if a table.column was passed + if (strpos($column, '.')) { + $column = $this->config['table_prefix'] . $column; + } + + $this->orderby[] = $this->driver->escape_column($column) . ' ' . $direction; + } + + return $this; + } + + /** + * Selects the limit section of a query. + * + * @param integer number of rows to limit result to + * @param integer offset in result to start returning rows from + * @return Database_Core This Database object. + */ + public function limit($limit, $offset = null) + { + $this->limit = (int) $limit; + + if ($offset !== null or ! is_int($this->offset)) { + $this->offset($offset); + } + + return $this; + } + + /** + * Sets the offset portion of a query. + * + * @param integer offset value + * @return Database_Core This Database object. + */ + public function offset($value) + { + $this->offset = (int) $value; + + return $this; + } + + /** + * Allows key/value pairs to be set for inserting or updating. + * + * @param string|array key name or array of key => value pairs + * @param string value to match with key + * @return Database_Core This Database object. + */ + public function set($key, $value = '') + { + if (! is_array($key)) { + $key = array($key => $value); + } + + foreach ($key as $k => $v) { + // Add a table prefix if the column includes the table. + if (strpos($k, '.')) { + $k = $this->config['table_prefix'] . $k; + } + + $this->set[$k] = $this->driver->escape($v); + } + + return $this; + } + + /** + * Compiles the select statement based on the other functions called and runs the query. + * + * @param string table name + * @param string limit clause + * @param string offset clause + * @return Database_Result + */ + public function get($table = '', $limit = null, $offset = null) + { + if ($table != '') { + $this->from($table); + } + + if (! is_null($limit)) { + $this->limit($limit, $offset); + } + + $sql = $this->driver->compile_select(get_object_vars($this)); + + $this->reset_select(); + + $result = $this->query($sql); + + $this->last_query = $sql; + + return $result; + } + + /** + * Compiles the select statement based on the other functions called and runs the query. + * + * @param string table name + * @param array where clause + * @param string limit clause + * @param string offset clause + * @return Database_Core This Database object. + */ + public function getwhere($table = '', $where = null, $limit = null, $offset = null) + { + if ($table != '') { + $this->from($table); + } + + if (! is_null($where)) { + $this->where($where); + } + + if (! is_null($limit)) { + $this->limit($limit, $offset); + } + + $sql = $this->driver->compile_select(get_object_vars($this)); + + $this->reset_select(); + + $result = $this->query($sql); + + return $result; + } + + /** + * Compiles the select statement based on the other functions called and returns the query string. + * + * @param string table name + * @param string limit clause + * @param string offset clause + * @return string sql string + */ + public function compile($table = '', $limit = null, $offset = null) + { + if ($table != '') { + $this->from($table); + } + + if (! is_null($limit)) { + $this->limit($limit, $offset); + } + + $sql = $this->driver->compile_select(get_object_vars($this)); + + $this->reset_select(); + + return $sql; + } + + /** + * Compiles an insert string and runs the query. + * + * @param string table name + * @param array array of key/value pairs to insert + * @return Database_Result Query result + */ + public function insert($table = '', $set = null) + { + if (! is_null($set)) { + $this->set($set); + } + + if ($this->set == null) { + throw new Kohana_Database_Exception('database.must_use_set'); + } + + if ($table == '') { + if (! isset($this->from[0])) { + throw new Kohana_Database_Exception('database.must_use_table'); + } + + $table = $this->from[0]; + } + + // If caching is enabled, clear the cache before inserting + ($this->config['cache'] === true) and $this->clear_cache(); + + $sql = $this->driver->insert($this->config['table_prefix'] . $table, array_keys($this->set), array_values($this->set)); + + $this->reset_write(); + + return $this->query($sql); + } + + /** + * Adds an "IN" condition to the where clause + * + * @param string Name of the column being examined + * @param mixed An array or string to match against + * @param bool Generate a NOT IN clause instead + * @return Database_Core This Database object. + */ + public function in($field, $values, $not = false) + { + if (is_array($values)) { + $escaped_values = array(); + foreach ($values as $v) { + if (is_numeric($v)) { + $escaped_values[] = $v; + } else { + $escaped_values[] = "'" . $this->driver->escape_str($v) . "'"; + } + } + $values = implode(",", $escaped_values); + } + + $where = $this->driver->escape_column(((strpos($field, '.') !== false) ? + $this->config['table_prefix'] : '') . $field) . ' ' . + ($not === true ? 'NOT ' : '') . 'IN (' . $values . ')'; + $this->where[] = $this->driver->where($where, '', 'AND ', count($this->where), -1); + + return $this; + } + + /** + * Adds a "NOT IN" condition to the where clause + * + * @param string Name of the column being examined + * @param mixed An array or string to match against + * @return Database_Core This Database object. + */ + public function notin($field, $values) + { + return $this->in($field, $values, true); + } + + /** + * Compiles a merge string and runs the query. + * + * @param string table name + * @param array array of key/value pairs to merge + * @return Database_Result Query result + */ + public function merge($table = '', $set = null) + { + if (! is_null($set)) { + $this->set($set); + } + + if ($this->set == null) { + throw new Kohana_Database_Exception('database.must_use_set'); + } + + if ($table == '') { + if (! isset($this->from[0])) { + throw new Kohana_Database_Exception('database.must_use_table'); + } + + $table = $this->from[0]; + } + + $sql = $this->driver->merge($this->config['table_prefix'] . $table, array_keys($this->set), array_values($this->set)); + + $this->reset_write(); + return $this->query($sql); + } + + /** + * Compiles an update string and runs the query. + * + * @param string table name + * @param array associative array of update values + * @param array where clause + * @return Database_Result Query result + */ + public function update($table = '', $set = null, $where = null) + { + if (is_array($set)) { + $this->set($set); + } + + if (! is_null($where)) { + $this->where($where); + } + + if ($this->set == false) { + throw new Kohana_Database_Exception('database.must_use_set'); + } + + if ($table == '') { + if (! isset($this->from[0])) { + throw new Kohana_Database_Exception('database.must_use_table'); + } + + $table = $this->from[0]; + } + + $sql = $this->driver->update($this->config['table_prefix'] . $table, $this->set, $this->where); + + $this->reset_write(); + return $this->query($sql); + } + + /** + * Compiles a delete string and runs the query. + * + * @param string table name + * @param array where clause + * @return Database_Result Query result + */ + public function delete($table = '', $where = null) + { + if ($table == '') { + if (! isset($this->from[0])) { + throw new Kohana_Database_Exception('database.must_use_table'); + } + + $table = $this->from[0]; + } else { + $table = $this->config['table_prefix'] . $table; + } + + if (! is_null($where)) { + $this->where($where); + } + + if (count($this->where) < 1) { + throw new Kohana_Database_Exception('database.must_use_where'); + } + + $sql = $this->driver->delete($table, $this->where); + + $this->reset_write(); + return $this->query($sql); + } + + /** + * Returns the last query run. + * + * @return string SQL + */ + public function last_query() + { + return $this->last_query; + } + + /** + * Count query records. + * + * @param string table name + * @param array where clause + * @return integer + */ + public function count_records($table = false, $where = null) + { + if (count($this->from) < 1) { + if ($table == false) { + throw new Kohana_Database_Exception('database.must_use_table'); + } + + $this->from($table); + } + + if ($where !== null) { + $this->where($where); + } + + $query = $this->select('COUNT(*) AS ' . $this->escape_column('records_found'))->get()->result(true); + + return (int) $query->current()->records_found; + } + + /** + * Resets all private select variables. + * + * @return void + */ + protected function reset_select() + { + $this->select = array(); + $this->from = array(); + $this->join = array(); + $this->where = array(); + $this->orderby = array(); + $this->groupby = array(); + $this->having = array(); + $this->distinct = false; + $this->limit = false; + $this->offset = false; + } + + /** + * Resets all private insert and update variables. + * + * @return void + */ + protected function reset_write() + { + $this->set = array(); + $this->from = array(); + $this->where = array(); + } + + /** + * Lists all the tables in the current database. + * + * @return array + */ + public function list_tables() + { + $this->link or $this->connect(); + + return $this->driver->list_tables(); + } + + /** + * See if a table exists in the database. + * + * @param string table name + * @param boolean True to attach table prefix + * @return boolean + */ + public function table_exists($table_name, $prefix = true) + { + if ($prefix) { + return in_array($this->config['table_prefix'] . $table_name, $this->list_tables()); + } else { + return in_array($table_name, $this->list_tables()); + } + } + + /** + * Combine a SQL statement with the bind values. Used for safe queries. + * + * @param string query to bind to the values + * @param array array of values to bind to the query + * @return string + */ + public function compile_binds($sql, $binds) + { + foreach ((array) $binds as $val) { + // If the SQL contains no more bind marks ("?"), we're done. + if (($next_bind_pos = strpos($sql, '?')) === false) { + break; + } + + // Properly escape the bind value. + $val = $this->driver->escape($val); + + // Temporarily replace possible bind marks ("?"), in the bind value itself, with a placeholder. + $val = str_replace('?', '{%B%}', $val); + + // Replace the first bind mark ("?") with its corresponding value. + $sql = substr($sql, 0, $next_bind_pos) . $val . substr($sql, $next_bind_pos + 1); + } + + // Restore placeholders. + return str_replace('{%B%}', '?', $sql); + } + + /** + * Get the field data for a database table, along with the field's attributes. + * + * @param string table name + * @return array + */ + public function field_data($table = '') + { + $this->link or $this->connect(); + + return $this->driver->field_data($this->config['table_prefix'] . $table); + } + + /** + * Get the field data for a database table, along with the field's attributes. + * + * @param string table name + * @return array + */ + public function list_fields($table = '') + { + $this->link or $this->connect(); + + return $this->driver->list_fields($this->config['table_prefix'] . $table); + } + + /** + * Escapes a value for a query. + * + * @param mixed value to escape + * @return string + */ + public function escape($value) + { + return $this->driver->escape($value); + } + + /** + * Escapes a string for a query. + * + * @param string string to escape + * @return string + */ + public function escape_str($str) + { + return $this->driver->escape_str($str); + } + + /** + * Escapes a table name for a query. + * + * @param string string to escape + * @return string + */ + public function escape_table($table) + { + return $this->driver->escape_table($table); + } + + /** + * Escapes a column name for a query. + * + * @param string string to escape + * @return string + */ + public function escape_column($table) + { + return $this->driver->escape_column($table); + } + + /** + * Returns table prefix of current configuration. + * + * @return string + */ + public function table_prefix() + { + return $this->config['table_prefix']; + } + + /** + * Clears the query cache. + * + * @param string|TRUE clear cache by SQL statement or TRUE for last query + * @return Database_Core This Database object. + */ + public function clear_cache($sql = null) + { + if ($sql === true) { + $this->driver->clear_cache($this->last_query); + } elseif (is_string($sql)) { + $this->driver->clear_cache($sql); + } else { + $this->driver->clear_cache(); + } + + return $this; + } + + /** + * Pushes existing query space onto the query stack. Use push + * and pop to prevent queries from clashing before they are + * executed + * + * @return Database_Core This Databaes object + */ + public function push() + { + array_push($this->query_history, array( + $this->select, + $this->from, + $this->join, + $this->where, + $this->orderby, + $this->order, + $this->groupby, + $this->having, + $this->distinct, + $this->limit, + $this->offset + )); + + $this->reset_select(); + + return $this; + } + + /** + * Pops from query stack into the current query space. + * + * @return Database_Core This Databaes object + */ + public function pop() + { + if (count($this->query_history) == 0) { + // No history + return $this; + } + + list( + $this->select, + $this->from, + $this->join, + $this->where, + $this->orderby, + $this->order, + $this->groupby, + $this->having, + $this->distinct, + $this->limit, + $this->offset + ) = array_pop($this->query_history); + + return $this; + } + + /** + * Count the number of records in the last query, without LIMIT or OFFSET applied. + * + * @return integer + */ + public function count_last_query() + { + if ($sql = $this->last_query()) { + if (stripos($sql, 'LIMIT') !== false) { + // Remove LIMIT from the SQL + $sql = preg_replace('/\sLIMIT\s+[^a-z]+/i', ' ', $sql); + } + + if (stripos($sql, 'OFFSET') !== false) { + // Remove OFFSET from the SQL + $sql = preg_replace('/\sOFFSET\s+\d+/i', '', $sql); + } + + // Get the total rows from the last query executed + $result = $this->query( + 'SELECT COUNT(*) AS ' . $this->escape_column('total_rows') . ' ' . + 'FROM (' . trim($sql) . ') AS ' . $this->escape_table('counted_results') + ); + + // Return the total number of rows from the query + return (int) $result->current()->total_rows; + } + + return false; + } +} +// End Database Class /** * Sets the code for a Database exception. */ -class Kohana_Database_Exception extends Kohana_Exception { - - protected $code = E_DATABASE_ERROR; - -} // End Kohana Database Exception +class Kohana_Database_Exception extends Kohana_Exception +{ + protected $code = E_DATABASE_ERROR; +} +// End Kohana Database Exception diff --git a/lib/kohana/system/libraries/Database_Expression.php b/lib/kohana/system/libraries/Database_Expression.php index 940a636..9fd32ea 100644 --- a/lib/kohana/system/libraries/Database_Expression.php +++ b/lib/kohana/system/libraries/Database_Expression.php @@ -1,4 +1,11 @@ -expression = $expression; + } - public function __construct($expression) - { - $this->expression = $expression; - } - - public function __toString() - { - return (string) $this->expression; - } - -} // End Database Expr Class \ No newline at end of file + public function __toString() + { + return (string) $this->expression; + } +} +// End Database Expr Class diff --git a/lib/kohana/system/libraries/Encrypt.php b/lib/kohana/system/libraries/Encrypt.php index 3d564f9..f61bf18 100644 --- a/lib/kohana/system/libraries/Encrypt.php +++ b/lib/kohana/system/libraries/Encrypt.php @@ -1,4 +1,11 @@ - $size) { + // Shorten the key to the maximum size + $config['key'] = substr($config['key'], 0, $size); + } - if (strlen($config['key']) > $size) - { - // Shorten the key to the maximum size - $config['key'] = substr($config['key'], 0, $size); - } + // Find the initialization vector size + $config['iv_size'] = mcrypt_get_iv_size($config['cipher'], $config['mode']); - // Find the initialization vector size - $config['iv_size'] = mcrypt_get_iv_size($config['cipher'], $config['mode']); + // Cache the config in the object + $this->config = $config; - // Cache the config in the object - $this->config = $config; + Kohana::log('debug', 'Encrypt Library initialized'); + } - Kohana::log('debug', 'Encrypt Library initialized'); - } + /** + * Encrypts a string and returns an encrypted string that can be decoded. + * + * @param string data to be encrypted + * @return string encrypted data + */ + public function encode($data) + { + // Set the rand type if it has not already been set + if (Encrypt::$rand === null) { + if (KOHANA_IS_WIN) { + // Windows only supports the system random number generator + Encrypt::$rand = MCRYPT_RAND; + } else { + if (defined('MCRYPT_DEV_URANDOM')) { + // Use /dev/urandom + Encrypt::$rand = MCRYPT_DEV_URANDOM; + } elseif (defined('MCRYPT_DEV_RANDOM')) { + // Use /dev/random + Encrypt::$rand = MCRYPT_DEV_RANDOM; + } else { + // Use the system random number generator + Encrypt::$rand = MCRYPT_RAND; + } + } + } - /** - * Encrypts a string and returns an encrypted string that can be decoded. - * - * @param string data to be encrypted - * @return string encrypted data - */ - public function encode($data) - { - // Set the rand type if it has not already been set - if (Encrypt::$rand === NULL) - { - if (KOHANA_IS_WIN) - { - // Windows only supports the system random number generator - Encrypt::$rand = MCRYPT_RAND; - } - else - { - if (defined('MCRYPT_DEV_URANDOM')) - { - // Use /dev/urandom - Encrypt::$rand = MCRYPT_DEV_URANDOM; - } - elseif (defined('MCRYPT_DEV_RANDOM')) - { - // Use /dev/random - Encrypt::$rand = MCRYPT_DEV_RANDOM; - } - else - { - // Use the system random number generator - Encrypt::$rand = MCRYPT_RAND; - } - } - } + if (Encrypt::$rand === MCRYPT_RAND) { + // The system random number generator must always be seeded each + // time it is used, or it will not produce true random results + mt_srand(); + } - if (Encrypt::$rand === MCRYPT_RAND) - { - // The system random number generator must always be seeded each - // time it is used, or it will not produce true random results - mt_srand(); - } + // Create a random initialization vector of the proper size for the current cipher + $iv = mcrypt_create_iv($this->config['iv_size'], Encrypt::$rand); - // Create a random initialization vector of the proper size for the current cipher - $iv = mcrypt_create_iv($this->config['iv_size'], Encrypt::$rand); + // Encrypt the data using the configured options and generated iv + $data = mcrypt_encrypt($this->config['cipher'], $this->config['key'], $data, $this->config['mode'], $iv); - // Encrypt the data using the configured options and generated iv - $data = mcrypt_encrypt($this->config['cipher'], $this->config['key'], $data, $this->config['mode'], $iv); + // Use base64 encoding to convert to a string + return base64_encode($iv . $data); + } - // Use base64 encoding to convert to a string - return base64_encode($iv.$data); - } + /** + * Decrypts an encoded string back to its original value. + * + * @param string encoded string to be decrypted + * @return string decrypted data + */ + public function decode($data) + { + // Convert the data back to binary + $data = base64_decode($data); - /** - * Decrypts an encoded string back to its original value. - * - * @param string encoded string to be decrypted - * @return string decrypted data - */ - public function decode($data) - { - // Convert the data back to binary - $data = base64_decode($data); + // Extract the initialization vector from the data + $iv = substr($data, 0, $this->config['iv_size']); - // Extract the initialization vector from the data - $iv = substr($data, 0, $this->config['iv_size']); + // Remove the iv from the data + $data = substr($data, $this->config['iv_size']); - // Remove the iv from the data - $data = substr($data, $this->config['iv_size']); - - // Return the decrypted data, trimming the \0 padding bytes from the end of the data - return rtrim(mcrypt_decrypt($this->config['cipher'], $this->config['key'], $data, $this->config['mode'], $iv), "\0"); - } - -} // End Encrypt + // Return the decrypted data, trimming the \0 padding bytes from the end of the data + return rtrim(mcrypt_decrypt($this->config['cipher'], $this->config['key'], $data, $this->config['mode'], $iv), "\0"); + } +} +// End Encrypt diff --git a/lib/kohana/system/libraries/Event_Observer.php b/lib/kohana/system/libraries/Event_Observer.php index 086c8a2..c53fc6d 100644 --- a/lib/kohana/system/libraries/Event_Observer.php +++ b/lib/kohana/system/libraries/Event_Observer.php @@ -1,4 +1,11 @@ -update($caller); + } - /** - * Initializes a new observer and attaches the subject as the caller. - * - * @param object Event_Subject - * @return void - */ - public function __construct(SplSubject $caller) - { - // Update the caller - $this->update($caller); - } + /** + * Updates the observer subject with a new caller. + * + * @chainable + * @param object Event_Subject + * @return object + */ + public function update(SplSubject $caller) + { + if (! ($caller instanceof Event_Subject)) { + throw new Kohana_Exception('event.invalid_subject', get_class($caller), get_class($this)); + } - /** - * Updates the observer subject with a new caller. - * - * @chainable - * @param object Event_Subject - * @return object - */ - public function update(SplSubject $caller) - { - if ( ! ($caller instanceof Event_Subject)) - throw new Kohana_Exception('event.invalid_subject', get_class($caller), get_class($this)); + // Update the caller + $this->caller = $caller; - // Update the caller - $this->caller = $caller; + return $this; + } - return $this; - } + /** + * Detaches this observer from the subject. + * + * @chainable + * @return object + */ + public function remove() + { + // Detach this observer from the caller + $this->caller->detach($this); - /** - * Detaches this observer from the subject. - * - * @chainable - * @return object - */ - public function remove() - { - // Detach this observer from the caller - $this->caller->detach($this); + return $this; + } - return $this; - } - - /** - * Notify the observer of a new message. This function must be defined in - * all observers and must take exactly one parameter of any type. - * - * @param mixed message string, object, or array - * @return void - */ - abstract public function notify($message); - -} // End Event Observer \ No newline at end of file + /** + * Notify the observer of a new message. This function must be defined in + * all observers and must take exactly one parameter of any type. + * + * @param mixed message string, object, or array + * @return void + */ + abstract public function notify($message); +} +// End Event Observer diff --git a/lib/kohana/system/libraries/Event_Subject.php b/lib/kohana/system/libraries/Event_Subject.php index d1ccc54..185ba4f 100644 --- a/lib/kohana/system/libraries/Event_Subject.php +++ b/lib/kohana/system/libraries/Event_Subject.php @@ -1,4 +1,11 @@ -listeners[spl_object_hash($obj)] = $obj; - // Add a new listener - $this->listeners[spl_object_hash($obj)] = $obj; + return $this; + } - return $this; - } + /** + * Detach an observer from the object. + * + * @chainable + * @param object Event_Observer + * @return object + */ + public function detach(SplObserver $obj) + { + // Remove the listener + unset($this->listeners[spl_object_hash($obj)]); - /** - * Detach an observer from the object. - * - * @chainable - * @param object Event_Observer - * @return object - */ - public function detach(SplObserver $obj) - { - // Remove the listener - unset($this->listeners[spl_object_hash($obj)]); + return $this; + } - return $this; - } + /** + * Notify all attached observers of a new message. + * + * @chainable + * @param mixed message string, object, or array + * @return object + */ + public function notify($message) + { + foreach ($this->listeners as $obj) { + $obj->notify($message); + } - /** - * Notify all attached observers of a new message. - * - * @chainable - * @param mixed message string, object, or array - * @return object - */ - public function notify($message) - { - foreach ($this->listeners as $obj) - { - $obj->notify($message); - } - - return $this; - } - -} // End Event Subject \ No newline at end of file + return $this; + } +} +// End Event Subject diff --git a/lib/kohana/system/libraries/Image.php b/lib/kohana/system/libraries/Image.php index 2de0658..6c05319 100644 --- a/lib/kohana/system/libraries/Image.php +++ b/lib/kohana/system/libraries/Image.php @@ -1,4 +1,11 @@ - 'gif', - IMAGETYPE_JPEG => 'jpg', - IMAGETYPE_PNG => 'png', - IMAGETYPE_TIFF_II => 'tiff', - IMAGETYPE_TIFF_MM => 'tiff', - ); - - // Driver instance - protected $driver; - - // Driver actions - protected $actions = array(); - - // Reference to the current image filename - protected $image = ''; - - /** - * Creates a new Image instance and returns it. - * - * @param string filename of image - * @param array non-default configurations - * @return object - */ - public static function factory($image, $config = NULL) - { - return new Image($image, $config); - } - - /** - * Creates a new image editor instance. - * - * @throws Kohana_Exception - * @param string filename of image - * @param array non-default configurations - * @return void - */ - public function __construct($image, $config = NULL) - { - static $check; - - // Make the check exactly once - ($check === NULL) and $check = function_exists('getimagesize'); - - if ($check === FALSE) - throw new Kohana_Exception('image.getimagesize_missing'); - - // Check to make sure the image exists - if ( ! is_file($image)) - throw new Kohana_Exception('image.file_not_found', $image); - - // Disable error reporting, to prevent PHP warnings - $ER = error_reporting(0); - - // Fetch the image size and mime type - $image_info = getimagesize($image); - - // Turn on error reporting again - error_reporting($ER); - - // Make sure that the image is readable and valid - if ( ! is_array($image_info) OR count($image_info) < 3) - throw new Kohana_Exception('image.file_unreadable', $image); - - // Check to make sure the image type is allowed - if ( ! isset(Image::$allowed_types[$image_info[2]])) - throw new Kohana_Exception('image.type_not_allowed', $image); - - // Image has been validated, load it - $this->image = array - ( - 'file' => str_replace('\\', '/', realpath($image)), - 'width' => $image_info[0], - 'height' => $image_info[1], - 'type' => $image_info[2], - 'ext' => Image::$allowed_types[$image_info[2]], - 'mime' => $image_info['mime'] - ); - - // Load configuration - $this->config = (array) $config + Kohana::config('image'); - - // Set driver class name - $driver = 'Image_'.ucfirst($this->config['driver']).'_Driver'; - - // Load the driver - if ( ! Kohana::auto_load($driver)) - throw new Kohana_Exception('core.driver_not_found', $this->config['driver'], get_class($this)); - - // Initialize the driver - $this->driver = new $driver($this->config['params']); - - // Validate the driver - if ( ! ($this->driver instanceof Image_Driver)) - throw new Kohana_Exception('core.driver_implements', $this->config['driver'], get_class($this), 'Image_Driver'); - } - - /** - * Handles retrieval of pre-save image properties - * - * @param string property name - * @return mixed - */ - public function __get($property) - { - if (isset($this->image[$property])) - { - return $this->image[$property]; - } - else - { - throw new Kohana_Exception('core.invalid_property', $property, get_class($this)); - } - } - - /** - * Resize an image to a specific width and height. By default, Kohana will - * maintain the aspect ratio using the width as the master dimension. If you - * wish to use height as master dim, set $image->master_dim = Image::HEIGHT - * This method is chainable. - * - * @throws Kohana_Exception - * @param integer width - * @param integer height - * @param integer one of: Image::NONE, Image::AUTO, Image::WIDTH, Image::HEIGHT - * @return object - */ - public function resize($width, $height, $master = NULL) - { - if ( ! $this->valid_size('width', $width)) - throw new Kohana_Exception('image.invalid_width', $width); - - if ( ! $this->valid_size('height', $height)) - throw new Kohana_Exception('image.invalid_height', $height); - - if (empty($width) AND empty($height)) - throw new Kohana_Exception('image.invalid_dimensions', __FUNCTION__); - - if ($master === NULL) - { - // Maintain the aspect ratio by default - $master = Image::AUTO; - } - elseif ( ! $this->valid_size('master', $master)) - throw new Kohana_Exception('image.invalid_master'); - - $this->actions['resize'] = array - ( - 'width' => $width, - 'height' => $height, - 'master' => $master, - ); - - return $this; - } - - /** - * Crop an image to a specific width and height. You may also set the top - * and left offset. - * This method is chainable. - * - * @throws Kohana_Exception - * @param integer width - * @param integer height - * @param integer top offset, pixel value or one of: top, center, bottom - * @param integer left offset, pixel value or one of: left, center, right - * @return object - */ - public function crop($width, $height, $top = 'center', $left = 'center') - { - if ( ! $this->valid_size('width', $width)) - throw new Kohana_Exception('image.invalid_width', $width); - - if ( ! $this->valid_size('height', $height)) - throw new Kohana_Exception('image.invalid_height', $height); - - if ( ! $this->valid_size('top', $top)) - throw new Kohana_Exception('image.invalid_top', $top); - - if ( ! $this->valid_size('left', $left)) - throw new Kohana_Exception('image.invalid_left', $left); - - if (empty($width) AND empty($height)) - throw new Kohana_Exception('image.invalid_dimensions', __FUNCTION__); - - $this->actions['crop'] = array - ( - 'width' => $width, - 'height' => $height, - 'top' => $top, - 'left' => $left, - ); - - return $this; - } - - /** - * Allows rotation of an image by 180 degrees clockwise or counter clockwise. - * - * @param integer degrees - * @return object - */ - public function rotate($degrees) - { - $degrees = (int) $degrees; - - if ($degrees > 180) - { - do - { - // Keep subtracting full circles until the degrees have normalized - $degrees -= 360; - } - while($degrees > 180); - } - - if ($degrees < -180) - { - do - { - // Keep adding full circles until the degrees have normalized - $degrees += 360; - } - while($degrees < -180); - } - - $this->actions['rotate'] = $degrees; - - return $this; - } - - /** - * Flip an image horizontally or vertically. - * - * @throws Kohana_Exception - * @param integer direction - * @return object - */ - public function flip($direction) - { - if ($direction !== Image::HORIZONTAL AND $direction !== Image::VERTICAL) - throw new Kohana_Exception('image.invalid_flip'); - - $this->actions['flip'] = $direction; - - return $this; - } - - /** - * Change the quality of an image. - * - * @param integer quality as a percentage - * @return object - */ - public function quality($amount) - { - $this->actions['quality'] = max(1, min($amount, 100)); - - return $this; - } - - /** - * Sharpen an image. - * - * @param integer amount to sharpen, usually ~20 is ideal - * @return object - */ - public function sharpen($amount) - { - $this->actions['sharpen'] = max(1, min($amount, 100)); - - return $this; - } - - /** - * Save the image to a new image or overwrite this image. - * - * @throws Kohana_Exception - * @param string new image filename - * @param integer permissions for new image - * @param boolean keep or discard image process actions - * @return object - */ - public function save($new_image = FALSE, $chmod = 0644, $keep_actions = FALSE) - { - // If no new image is defined, use the current image - empty($new_image) and $new_image = $this->image['file']; - - // Separate the directory and filename - $dir = pathinfo($new_image, PATHINFO_DIRNAME); - $file = pathinfo($new_image, PATHINFO_BASENAME); - - // Normalize the path - $dir = str_replace('\\', '/', realpath($dir)).'/'; - - if ( ! is_writable($dir)) - throw new Kohana_Exception('image.directory_unwritable', $dir); - - if ($status = $this->driver->process($this->image, $this->actions, $dir, $file)) - { - if ($chmod !== FALSE) - { - // Set permissions - chmod($new_image, $chmod); - } - } - - // Reset actions. Subsequent save() or render() will not apply previous actions. - if ($keep_actions === FALSE) - $this->actions = array(); - - return $status; - } - - /** - * Output the image to the browser. - * - * @param boolean keep or discard image process actions - * @return object - */ - public function render($keep_actions = FALSE) - { - $new_image = $this->image['file']; - - // Separate the directory and filename - $dir = pathinfo($new_image, PATHINFO_DIRNAME); - $file = pathinfo($new_image, PATHINFO_BASENAME); - - // Normalize the path - $dir = str_replace('\\', '/', realpath($dir)).'/'; - - // Process the image with the driver - $status = $this->driver->process($this->image, $this->actions, $dir, $file, $render = TRUE); - - // Reset actions. Subsequent save() or render() will not apply previous actions. - if ($keep_actions === FALSE) - $this->actions = array(); - - return $status; - } - - /** - * Sanitize a given value type. - * - * @param string type of property - * @param mixed property value - * @return boolean - */ - protected function valid_size($type, & $value) - { - if (is_null($value)) - return TRUE; - - if ( ! is_scalar($value)) - return FALSE; - - switch ($type) - { - case 'width': - case 'height': - if (is_string($value) AND ! ctype_digit($value)) - { - // Only numbers and percent signs - if ( ! preg_match('/^[0-9]++%$/D', $value)) - return FALSE; - } - else - { - $value = (int) $value; - } - break; - case 'top': - if (is_string($value) AND ! ctype_digit($value)) - { - if ( ! in_array($value, array('top', 'bottom', 'center'))) - return FALSE; - } - else - { - $value = (int) $value; - } - break; - case 'left': - if (is_string($value) AND ! ctype_digit($value)) - { - if ( ! in_array($value, array('left', 'right', 'center'))) - return FALSE; - } - else - { - $value = (int) $value; - } - break; - case 'master': - if ($value !== Image::NONE AND - $value !== Image::AUTO AND - $value !== Image::WIDTH AND - $value !== Image::HEIGHT) - return FALSE; - break; - } - - return TRUE; - } - -} // End Image \ No newline at end of file +class Image_Core +{ + // Master Dimension + const NONE = 1; + const AUTO = 2; + const HEIGHT = 3; + const WIDTH = 4; + // Flip Directions + const HORIZONTAL = 5; + const VERTICAL = 6; + + // Allowed image types + public static $allowed_types = array + ( + IMAGETYPE_GIF => 'gif', + IMAGETYPE_JPEG => 'jpg', + IMAGETYPE_PNG => 'png', + IMAGETYPE_TIFF_II => 'tiff', + IMAGETYPE_TIFF_MM => 'tiff', + ); + + // Driver instance + protected $driver; + + // Driver actions + protected $actions = array(); + + // Reference to the current image filename + protected $image = ''; + + /** + * Creates a new Image instance and returns it. + * + * @param string filename of image + * @param array non-default configurations + * @return object + */ + public static function factory($image, $config = null) + { + return new Image($image, $config); + } + + /** + * Creates a new image editor instance. + * + * @throws Kohana_Exception + * @param string filename of image + * @param array non-default configurations + * @return void + */ + public function __construct($image, $config = null) + { + static $check; + + // Make the check exactly once + ($check === null) and $check = function_exists('getimagesize'); + + if ($check === false) { + throw new Kohana_Exception('image.getimagesize_missing'); + } + + // Check to make sure the image exists + if (! is_file($image)) { + throw new Kohana_Exception('image.file_not_found', $image); + } + + // Disable error reporting, to prevent PHP warnings + $ER = error_reporting(0); + + // Fetch the image size and mime type + $image_info = getimagesize($image); + + // Turn on error reporting again + error_reporting($ER); + + // Make sure that the image is readable and valid + if (! is_array($image_info) or count($image_info) < 3) { + throw new Kohana_Exception('image.file_unreadable', $image); + } + + // Check to make sure the image type is allowed + if (! isset(Image::$allowed_types[$image_info[2]])) { + throw new Kohana_Exception('image.type_not_allowed', $image); + } + + // Image has been validated, load it + $this->image = array + ( + 'file' => str_replace('\\', '/', realpath($image)), + 'width' => $image_info[0], + 'height' => $image_info[1], + 'type' => $image_info[2], + 'ext' => Image::$allowed_types[$image_info[2]], + 'mime' => $image_info['mime'] + ); + + // Load configuration + $this->config = (array) $config + Kohana::config('image'); + + // Set driver class name + $driver = 'Image_' . ucfirst($this->config['driver']) . '_Driver'; + + // Load the driver + if (! Kohana::auto_load($driver)) { + throw new Kohana_Exception('core.driver_not_found', $this->config['driver'], get_class($this)); + } + + // Initialize the driver + $this->driver = new $driver($this->config['params']); + + // Validate the driver + if (! ($this->driver instanceof Image_Driver)) { + throw new Kohana_Exception('core.driver_implements', $this->config['driver'], get_class($this), 'Image_Driver'); + } + } + + /** + * Handles retrieval of pre-save image properties + * + * @param string property name + * @return mixed + */ + public function __get($property) + { + if (isset($this->image[$property])) { + return $this->image[$property]; + } else { + throw new Kohana_Exception('core.invalid_property', $property, get_class($this)); + } + } + + /** + * Resize an image to a specific width and height. By default, Kohana will + * maintain the aspect ratio using the width as the master dimension. If you + * wish to use height as master dim, set $image->master_dim = Image::HEIGHT + * This method is chainable. + * + * @throws Kohana_Exception + * @param integer width + * @param integer height + * @param integer one of: Image::NONE, Image::AUTO, Image::WIDTH, Image::HEIGHT + * @return object + */ + public function resize($width, $height, $master = null) + { + if (! $this->valid_size('width', $width)) { + throw new Kohana_Exception('image.invalid_width', $width); + } + + if (! $this->valid_size('height', $height)) { + throw new Kohana_Exception('image.invalid_height', $height); + } + + if (empty($width) and empty($height)) { + throw new Kohana_Exception('image.invalid_dimensions', __FUNCTION__); + } + + if ($master === null) { + // Maintain the aspect ratio by default + $master = Image::AUTO; + } elseif (! $this->valid_size('master', $master)) { + throw new Kohana_Exception('image.invalid_master'); + } + + $this->actions['resize'] = array + ( + 'width' => $width, + 'height' => $height, + 'master' => $master, + ); + + return $this; + } + + /** + * Crop an image to a specific width and height. You may also set the top + * and left offset. + * This method is chainable. + * + * @throws Kohana_Exception + * @param integer width + * @param integer height + * @param integer top offset, pixel value or one of: top, center, bottom + * @param integer left offset, pixel value or one of: left, center, right + * @return object + */ + public function crop($width, $height, $top = 'center', $left = 'center') + { + if (! $this->valid_size('width', $width)) { + throw new Kohana_Exception('image.invalid_width', $width); + } + + if (! $this->valid_size('height', $height)) { + throw new Kohana_Exception('image.invalid_height', $height); + } + + if (! $this->valid_size('top', $top)) { + throw new Kohana_Exception('image.invalid_top', $top); + } + + if (! $this->valid_size('left', $left)) { + throw new Kohana_Exception('image.invalid_left', $left); + } + + if (empty($width) and empty($height)) { + throw new Kohana_Exception('image.invalid_dimensions', __FUNCTION__); + } + + $this->actions['crop'] = array + ( + 'width' => $width, + 'height' => $height, + 'top' => $top, + 'left' => $left, + ); + + return $this; + } + + /** + * Allows rotation of an image by 180 degrees clockwise or counter clockwise. + * + * @param integer degrees + * @return object + */ + public function rotate($degrees) + { + $degrees = (int) $degrees; + + if ($degrees > 180) { + do { + // Keep subtracting full circles until the degrees have normalized + $degrees -= 360; + } while ($degrees > 180); + } + + if ($degrees < -180) { + do { + // Keep adding full circles until the degrees have normalized + $degrees += 360; + } while ($degrees < -180); + } + + $this->actions['rotate'] = $degrees; + + return $this; + } + + /** + * Flip an image horizontally or vertically. + * + * @throws Kohana_Exception + * @param integer direction + * @return object + */ + public function flip($direction) + { + if ($direction !== Image::HORIZONTAL and $direction !== Image::VERTICAL) { + throw new Kohana_Exception('image.invalid_flip'); + } + + $this->actions['flip'] = $direction; + + return $this; + } + + /** + * Change the quality of an image. + * + * @param integer quality as a percentage + * @return object + */ + public function quality($amount) + { + $this->actions['quality'] = max(1, min($amount, 100)); + + return $this; + } + + /** + * Sharpen an image. + * + * @param integer amount to sharpen, usually ~20 is ideal + * @return object + */ + public function sharpen($amount) + { + $this->actions['sharpen'] = max(1, min($amount, 100)); + + return $this; + } + + /** + * Save the image to a new image or overwrite this image. + * + * @throws Kohana_Exception + * @param string new image filename + * @param integer permissions for new image + * @param boolean keep or discard image process actions + * @return object + */ + public function save($new_image = false, $chmod = 0644, $keep_actions = false) + { + // If no new image is defined, use the current image + empty($new_image) and $new_image = $this->image['file']; + + // Separate the directory and filename + $dir = pathinfo($new_image, PATHINFO_DIRNAME); + $file = pathinfo($new_image, PATHINFO_BASENAME); + + // Normalize the path + $dir = str_replace('\\', '/', realpath($dir)) . '/'; + + if (! is_writable($dir)) { + throw new Kohana_Exception('image.directory_unwritable', $dir); + } + + if ($status = $this->driver->process($this->image, $this->actions, $dir, $file)) { + if ($chmod !== false) { + // Set permissions + chmod($new_image, $chmod); + } + } + + // Reset actions. Subsequent save() or render() will not apply previous actions. + if ($keep_actions === false) { + $this->actions = array(); + } + + return $status; + } + + /** + * Output the image to the browser. + * + * @param boolean keep or discard image process actions + * @return object + */ + public function render($keep_actions = false) + { + $new_image = $this->image['file']; + + // Separate the directory and filename + $dir = pathinfo($new_image, PATHINFO_DIRNAME); + $file = pathinfo($new_image, PATHINFO_BASENAME); + + // Normalize the path + $dir = str_replace('\\', '/', realpath($dir)) . '/'; + + // Process the image with the driver + $status = $this->driver->process($this->image, $this->actions, $dir, $file, $render = true); + + // Reset actions. Subsequent save() or render() will not apply previous actions. + if ($keep_actions === false) { + $this->actions = array(); + } + + return $status; + } + + /** + * Sanitize a given value type. + * + * @param string type of property + * @param mixed property value + * @return boolean + */ + protected function valid_size($type, &$value) + { + if (is_null($value)) { + return true; + } + + if (! is_scalar($value)) { + return false; + } + + switch ($type) { + case 'width': + case 'height': + if (is_string($value) and ! ctype_digit($value)) { + // Only numbers and percent signs + if (! preg_match('/^[0-9]++%$/D', $value)) { + return false; + } + } else { + $value = (int) $value; + } + break; + case 'top': + if (is_string($value) and ! ctype_digit($value)) { + if (! in_array($value, array('top', 'bottom', 'center'))) { + return false; + } + } else { + $value = (int) $value; + } + break; + case 'left': + if (is_string($value) and ! ctype_digit($value)) { + if (! in_array($value, array('left', 'right', 'center'))) { + return false; + } + } else { + $value = (int) $value; + } + break; + case 'master': + if ( + $value !== Image::NONE and + $value !== Image::AUTO and + $value !== Image::WIDTH and + $value !== Image::HEIGHT + ) { + return false; + } + break; + } + + return true; + } +} +// End Image diff --git a/lib/kohana/system/libraries/Input.php b/lib/kohana/system/libraries/Input.php index 0e23c80..20852bf 100644 --- a/lib/kohana/system/libraries/Input.php +++ b/lib/kohana/system/libraries/Input.php @@ -1,4 +1,11 @@ -use_xss_clean = (bool) Kohana::config('core.global_xss_filtering'); - /** - * Sanitizes global GET, POST and COOKIE data. Also takes care of - * magic_quotes and register_globals, if they have been enabled. - * - * @return void - */ - public function __construct() - { - // Use XSS clean? - $this->use_xss_clean = (bool) Kohana::config('core.global_xss_filtering'); + if (Input::$instance === null) { + // register_globals is enabled + if (ini_get('register_globals')) { + if (isset($_REQUEST['GLOBALS'])) { + // Prevent GLOBALS override attacks + exit('Global variable overload attack.'); + } - if (Input::$instance === NULL) - { - // magic_quotes_runtime is enabled - if (get_magic_quotes_runtime()) - { - set_magic_quotes_runtime(0); - Kohana::log('debug', 'Disable magic_quotes_runtime! It is evil and deprecated: http://php.net/magic_quotes'); - } + // Destroy the REQUEST global + $_REQUEST = array(); - // magic_quotes_gpc is enabled - if (get_magic_quotes_gpc()) - { - $this->magic_quotes_gpc = TRUE; - Kohana::log('debug', 'Disable magic_quotes_gpc! It is evil and deprecated: http://php.net/magic_quotes'); - } + // These globals are standard and should not be removed + $preserve = array('GLOBALS', '_REQUEST', '_GET', '_POST', '_FILES', '_COOKIE', '_SERVER', '_ENV', '_SESSION'); - // register_globals is enabled - if (ini_get('register_globals')) - { - if (isset($_REQUEST['GLOBALS'])) - { - // Prevent GLOBALS override attacks - exit('Global variable overload attack.'); - } + // This loop has the same effect as disabling register_globals + foreach (array_diff(array_keys($GLOBALS), $preserve) as $key) { + global $$key; + $$key = null; - // Destroy the REQUEST global - $_REQUEST = array(); + // Unset the global variable + unset($GLOBALS[$key], $$key); + } - // These globals are standard and should not be removed - $preserve = array('GLOBALS', '_REQUEST', '_GET', '_POST', '_FILES', '_COOKIE', '_SERVER', '_ENV', '_SESSION'); + // Warn the developer about register globals + Kohana::log('debug', 'Disable register_globals! It is evil and deprecated: http://php.net/register_globals'); + } - // This loop has the same effect as disabling register_globals - foreach (array_diff(array_keys($GLOBALS), $preserve) as $key) - { - global $$key; - $$key = NULL; + if (is_array($_GET)) { + foreach ($_GET as $key => $val) { + // Sanitize $_GET + $_GET[$this->clean_input_keys($key)] = $this->clean_input_data($val); + } + } else { + $_GET = array(); + } - // Unset the global variable - unset($GLOBALS[$key], $$key); - } + if (is_array($_POST)) { + foreach ($_POST as $key => $val) { + // Sanitize $_POST + $_POST[$this->clean_input_keys($key)] = $this->clean_input_data($val); + } + } else { + $_POST = array(); + } - // Warn the developer about register globals - Kohana::log('debug', 'Disable register_globals! It is evil and deprecated: http://php.net/register_globals'); - } + if (is_array($_COOKIE)) { + foreach ($_COOKIE as $key => $val) { + // Ignore special attributes in RFC2109 compliant cookies + if ($key == '$Version' or $key == '$Path' or $key == '$Domain') { + continue; + } - if (is_array($_GET)) - { - foreach ($_GET as $key => $val) - { - // Sanitize $_GET - $_GET[$this->clean_input_keys($key)] = $this->clean_input_data($val); - } - } - else - { - $_GET = array(); - } + // Sanitize $_COOKIE + $_COOKIE[$this->clean_cookie($key)] = $this->clean_input_data($val); + } + } else { + $_COOKIE = array(); + } - if (is_array($_POST)) - { - foreach ($_POST as $key => $val) - { - // Sanitize $_POST - $_POST[$this->clean_input_keys($key)] = $this->clean_input_data($val); - } - } - else - { - $_POST = array(); - } + // Create a singleton + Input::$instance = $this; - if (is_array($_COOKIE)) - { - foreach ($_COOKIE as $key => $val) - { - // Ignore special attributes in RFC2109 compliant cookies - if ($key == '$Version' OR $key == '$Path' OR $key == '$Domain') - continue; + Kohana::log('debug', 'Global GET, POST and COOKIE data sanitized'); + } + } - // Sanitize $_COOKIE - $_COOKIE[$this->clean_input_keys($key)] = $this->clean_input_data($val); - } - } - else - { - $_COOKIE = array(); - } + /** + * Fetch an item from the $_GET array. + * + * @param string key to find + * @param mixed default value + * @param boolean XSS clean the value + * @return mixed + */ + public function get($key = array(), $default = null, $xss_clean = false) + { + return $this->search_array($_GET, $key, $default, $xss_clean); + } - // Create a singleton - Input::$instance = $this; + /** + * Fetch an item from the $_POST array. + * + * @param string key to find + * @param mixed default value + * @param boolean XSS clean the value + * @return mixed + */ + public function post($key = array(), $default = null, $xss_clean = false) + { + return $this->search_array($_POST, $key, $default, $xss_clean); + } - Kohana::log('debug', 'Global GET, POST and COOKIE data sanitized'); - } - } + /** + * Fetch an item from the $_COOKIE array. + * + * @param string key to find + * @param mixed default value + * @param boolean XSS clean the value + * @return mixed + */ + public function cookie($key = array(), $default = null, $xss_clean = false) + { + return $this->search_array($_COOKIE, $key, $default, $xss_clean); + } - /** - * Fetch an item from the $_GET array. - * - * @param string key to find - * @param mixed default value - * @param boolean XSS clean the value - * @return mixed - */ - public function get($key = array(), $default = NULL, $xss_clean = FALSE) - { - return $this->search_array($_GET, $key, $default, $xss_clean); - } + /** + * Fetch an item from the $_SERVER array. + * + * @param string key to find + * @param mixed default value + * @param boolean XSS clean the value + * @return mixed + */ + public function server($key = array(), $default = null, $xss_clean = false) + { + return $this->search_array($_SERVER, $key, $default, $xss_clean); + } - /** - * Fetch an item from the $_POST array. - * - * @param string key to find - * @param mixed default value - * @param boolean XSS clean the value - * @return mixed - */ - public function post($key = array(), $default = NULL, $xss_clean = FALSE) - { - return $this->search_array($_POST, $key, $default, $xss_clean); - } + /** + * Fetch an item from a global array. + * + * @param array array to search + * @param string key to find + * @param mixed default value + * @param boolean XSS clean the value + * @return mixed + */ + protected function search_array($array, $key, $default = null, $xss_clean = false) + { + if ($key === array()) { + return $array; + } - /** - * Fetch an item from the $_COOKIE array. - * - * @param string key to find - * @param mixed default value - * @param boolean XSS clean the value - * @return mixed - */ - public function cookie($key = array(), $default = NULL, $xss_clean = FALSE) - { - return $this->search_array($_COOKIE, $key, $default, $xss_clean); - } + if (! isset($array[$key])) { + return $default; + } - /** - * Fetch an item from the $_SERVER array. - * - * @param string key to find - * @param mixed default value - * @param boolean XSS clean the value - * @return mixed - */ - public function server($key = array(), $default = NULL, $xss_clean = FALSE) - { - return $this->search_array($_SERVER, $key, $default, $xss_clean); - } + // Get the value + $value = $array[$key]; - /** - * Fetch an item from a global array. - * - * @param array array to search - * @param string key to find - * @param mixed default value - * @param boolean XSS clean the value - * @return mixed - */ - protected function search_array($array, $key, $default = NULL, $xss_clean = FALSE) - { - if ($key === array()) - return $array; + if ($this->use_xss_clean === false and $xss_clean === true) { + // XSS clean the value + $value = $this->xss_clean($value); + } - if ( ! isset($array[$key])) - return $default; + return $value; + } - // Get the value - $value = $array[$key]; + /** + * Fetch the IP Address. + * + * @return string + */ + public function ip_address() + { + if ($this->ip_address !== null) { + return $this->ip_address; + } - if ($this->use_xss_clean === FALSE AND $xss_clean === TRUE) - { - // XSS clean the value - $value = $this->xss_clean($value); - } + // Server keys that could contain the client IP address + $keys = array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'); - return $value; - } + foreach ($keys as $key) { + if ($ip = $this->server($key)) { + $this->ip_address = $ip; - /** - * Fetch the IP Address. - * - * @return string - */ - public function ip_address() - { - if ($this->ip_address !== NULL) - return $this->ip_address; + // An IP address has been found + break; + } + } - // Server keys that could contain the client IP address - $keys = array('HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'); + if ($comma = strrpos($this->ip_address, ',') !== false) { + $this->ip_address = substr($this->ip_address, $comma + 1); + } - foreach ($keys as $key) - { - if ($ip = $this->server($key)) - { - $this->ip_address = $ip; + if (! valid::ip($this->ip_address)) { + // Use an empty IP + $this->ip_address = '0.0.0.0'; + } - // An IP address has been found - break; - } - } + return $this->ip_address; + } - if ($comma = strrpos($this->ip_address, ',') !== FALSE) - { - $this->ip_address = substr($this->ip_address, $comma + 1); - } + /** + * Clean cross site scripting exploits from string. + * HTMLPurifier may be used if installed, otherwise defaults to built in method. + * Note - This function should only be used to deal with data upon submission. + * It's not something that should be used for general runtime processing + * since it requires a fair amount of processing overhead. + * + * @param string data to clean + * @param string xss_clean method to use ('htmlpurifier' or defaults to built-in method) + * @return string + */ + public function xss_clean($data, $tool = null) + { + if ($tool === null) { + // Use the default tool + $tool = Kohana::config('core.global_xss_filtering'); + } - if ( ! valid::ip($this->ip_address)) - { - // Use an empty IP - $this->ip_address = '0.0.0.0'; - } + if (is_array($data)) { + foreach ($data as $key => $val) { + $data[$key] = $this->xss_clean($val, $tool); + } - return $this->ip_address; - } + return $data; + } - /** - * Clean cross site scripting exploits from string. - * HTMLPurifier may be used if installed, otherwise defaults to built in method. - * Note - This function should only be used to deal with data upon submission. - * It's not something that should be used for general runtime processing - * since it requires a fair amount of processing overhead. - * - * @param string data to clean - * @param string xss_clean method to use ('htmlpurifier' or defaults to built-in method) - * @return string - */ - public function xss_clean($data, $tool = NULL) - { - if ($tool === NULL) - { - // Use the default tool - $tool = Kohana::config('core.global_xss_filtering'); - } + // Do not clean empty strings + if (trim($data) === '') { + return $data; + } - if (is_array($data)) - { - foreach ($data as $key => $val) - { - $data[$key] = $this->xss_clean($val, $tool); - } + if ($tool === true) { + // NOTE: This is necessary because switch is NOT type-sensative! + $tool = 'default'; + } - return $data; - } + switch ($tool) { + case 'htmlpurifier': + /** + * @todo License should go here, http://htmlpurifier.org/ + */ + if (! class_exists('HTMLPurifier_Config', false)) { + // Load HTMLPurifier + require Kohana::find_file('vendor', 'htmlpurifier/HTMLPurifier.auto', true); + require 'HTMLPurifier.func.php'; + } - // Do not clean empty strings - if (trim($data) === '') - return $data; + // Set configuration + $config = HTMLPurifier_Config::createDefault(); + $config->set('HTML', 'TidyLevel', 'none'); // Only XSS cleaning now - if ($tool === TRUE) - { - // NOTE: This is necessary because switch is NOT type-sensative! - $tool = 'default'; - } + // Run HTMLPurifier + $data = HTMLPurifier($data, $config); + break; + default: + // http://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.php + // +----------------------------------------------------------------------+ + // | Copyright (c) 2001-2006 Bitflux GmbH | + // +----------------------------------------------------------------------+ + // | Licensed under the Apache License, Version 2.0 (the "License"); | + // | you may not use this file except in compliance with the License. | + // | You may obtain a copy of the License at | + // | http://www.apache.org/licenses/LICENSE-2.0 | + // | Unless required by applicable law or agreed to in writing, software | + // | distributed under the License is distributed on an "AS IS" BASIS, | + // | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | + // | implied. See the License for the specific language governing | + // | permissions and limitations under the License. | + // +----------------------------------------------------------------------+ + // | Author: Christian Stocker | + // +----------------------------------------------------------------------+ + // + // Kohana Modifications: + // * Changed double quotes to single quotes, changed indenting and spacing + // * Removed magic_quotes stuff + // * Increased regex readability: + // * Used delimeters that aren't found in the pattern + // * Removed all unneeded escapes + // * Deleted U modifiers and swapped greediness where needed + // * Increased regex speed: + // * Made capturing parentheses non-capturing where possible + // * Removed parentheses where possible + // * Split up alternation alternatives + // * Made some quantifiers possessive - switch ($tool) - { - case 'htmlpurifier': - /** - * @todo License should go here, http://htmlpurifier.org/ - */ - if ( ! class_exists('HTMLPurifier_Config', FALSE)) - { - // Load HTMLPurifier - require Kohana::find_file('vendor', 'htmlpurifier/HTMLPurifier.auto', TRUE); - require 'HTMLPurifier.func.php'; - } + // Fix &entity\n; + $data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data); + $data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data); + $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data); + $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8'); - // Set configuration - $config = HTMLPurifier_Config::createDefault(); - $config->set('HTML', 'TidyLevel', 'none'); // Only XSS cleaning now + // Remove any attribute starting with "on" or xmlns + $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data); - // Run HTMLPurifier - $data = HTMLPurifier($data, $config); - break; - default: - // http://svn.bitflux.ch/repos/public/popoon/trunk/classes/externalinput.php - // +----------------------------------------------------------------------+ - // | Copyright (c) 2001-2006 Bitflux GmbH | - // +----------------------------------------------------------------------+ - // | Licensed under the Apache License, Version 2.0 (the "License"); | - // | you may not use this file except in compliance with the License. | - // | You may obtain a copy of the License at | - // | http://www.apache.org/licenses/LICENSE-2.0 | - // | Unless required by applicable law or agreed to in writing, software | - // | distributed under the License is distributed on an "AS IS" BASIS, | - // | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | - // | implied. See the License for the specific language governing | - // | permissions and limitations under the License. | - // +----------------------------------------------------------------------+ - // | Author: Christian Stocker | - // +----------------------------------------------------------------------+ - // - // Kohana Modifications: - // * Changed double quotes to single quotes, changed indenting and spacing - // * Removed magic_quotes stuff - // * Increased regex readability: - // * Used delimeters that aren't found in the pattern - // * Removed all unneeded escapes - // * Deleted U modifiers and swapped greediness where needed - // * Increased regex speed: - // * Made capturing parentheses non-capturing where possible - // * Removed parentheses where possible - // * Split up alternation alternatives - // * Made some quantifiers possessive + // Remove javascript: and vbscript: protocols + $data = preg_replace( + '#([a-z]*)[\x00-\x20]*=' . + '[\x00-\x20]*([`\'"]*)' . + '[\x00-\x20]*j[\x00-\x20]*a' . + '[\x00-\x20]*v[\x00-\x20]*a' . + '[\x00-\x20]*s[\x00-\x20]*c' . + '[\x00-\x20]*r[\x00-\x20]*i' . + '[\x00-\x20]*p[\x00-\x20]*t' . + '[\x00-\x20]*:#iu', + '$1=$2nojavascript...', + $data + ); + $data = preg_replace( + '#([a-z]*)[\x00-\x20]*=' . + '([\'"]*)[\x00-\x20]*v' . + '[\x00-\x20]*b[\x00-\x20]*s' . + '[\x00-\x20]*c[\x00-\x20]*r' . + '[\x00-\x20]*i[\x00-\x20]*p' . + '[\x00-\x20]*t[\x00-\x20]*:#iu', + '$1=$2novbscript...', + $data + ); + $data = preg_replace( + '#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', + '$1=$2nomozbinding...', + $data + ); - // Fix &entity\n; - $data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data); - $data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data); - $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data); - $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8'); + // Only works in IE: + $data = preg_replace( + '#(<[^>]+?)style[\x00-\x20]*=' . + '[\x00-\x20]*[`\'"]*.*?' . + 'expression[\x00-\x20]*\([^>]*+>#i', + '$1>', + $data + ); + $data = preg_replace( + '#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', + '$1>', + $data + ); + $data = preg_replace( + '#(<[^>]+?)style[\x00-\x20]*=' . + '[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c' . + '[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p' . + '[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', + '$1>', + $data + ); - // Remove any attribute starting with "on" or xmlns - $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data); + // Remove namespaced elements (we do not need them) + $data = preg_replace('#]*+>#i', '', $data); - // Remove javascript: and vbscript: protocols - $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data); - $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data); - $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data); + do { + // Remove really unwanted tags + $old_data = $data; + $data = preg_replace( + '#]*+>#i', + '', + $data + ); + } while ($old_data !== $data); + break; + } - // Only works in IE: - $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data); - $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data); - $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data); + return $data; + } - // Remove namespaced elements (we do not need them) - $data = preg_replace('#]*+>#i', '', $data); + /** + * This is a helper method. It enforces W3C specifications for allowed + * key name strings, to prevent malicious exploitation. + * + * @param string string to clean + * @return string + */ + public function clean_input_keys($str) + { + $chars = PCRE_UNICODE_PROPERTIES ? '\pL' : 'a-zA-Z'; - do - { - // Remove really unwanted tags - $old_data = $data; - $data = preg_replace('#]*+>#i', '', $data); - } - while ($old_data !== $data); - break; - } + if (! preg_match('#^[' . $chars . '0-9:_.\-]++$#uD', $str)) { + exit('Disallowed key characters in global data.'); + } - return $data; - } + return $str; + } - /** - * This is a helper method. It enforces W3C specifications for allowed - * key name strings, to prevent malicious exploitation. - * - * @param string string to clean - * @return string - */ - public function clean_input_keys($str) - { - $chars = PCRE_UNICODE_PROPERTIES ? '\pL' : 'a-zA-Z'; + public function clean_cookie($str) + { + $chars = PCRE_UNICODE_PROPERTIES ? '\pL' : 'a-zA-Z'; - if ( ! preg_match('#^['.$chars.'0-9:_.-]++$#uD', $str)) - { - exit('Disallowed key characters in global data.'); - } + if (! preg_match('#^[\%' . $chars . '0-9:_.\-\$\@]++$#uD', $str)) { + exit("Disallowed key characters in global data."); + } - return $str; - } + return $str; + } - /** - * This is a helper method. It escapes data and forces all newline - * characters to "\n". - * - * @param unknown_type string to clean - * @return string - */ - public function clean_input_data($str) - { - if (is_array($str)) - { - $new_array = array(); - foreach ($str as $key => $val) - { - // Recursion! - $new_array[$this->clean_input_keys($key)] = $this->clean_input_data($val); - } - return $new_array; - } + /** + * This is a helper method. It escapes data and forces all newline + * characters to "\n". + * + * @param unknown_type string to clean + * @return string + */ + public function clean_input_data($str) + { + if (is_array($str)) { + $new_array = array(); + foreach ($str as $key => $val) { + // Recursion! + $new_array[$this->clean_input_keys($key)] = $this->clean_input_data($val); + } + return $new_array; + } - if ($this->magic_quotes_gpc === TRUE) - { - // Remove annoying magic quotes - $str = stripslashes($str); - } + if ($this->magic_quotes_gpc === true) { + // Remove annoying magic quotes + $str = stripslashes($str); + } - if ($this->use_xss_clean === TRUE) - { - $str = $this->xss_clean($str); - } + if ($this->use_xss_clean === true) { + $str = $this->xss_clean($str); + } - if (strpos($str, "\r") !== FALSE) - { - // Standardize newlines - $str = str_replace(array("\r\n", "\r"), "\n", $str); - } + if (strpos($str, "\r") !== false) { + // Standardize newlines + $str = str_replace(array("\r\n", "\r"), "\n", $str); + } - return $str; - } - -} // End Input Class + return $str; + } +} +// End Input Class diff --git a/lib/kohana/system/libraries/Model.php b/lib/kohana/system/libraries/Model.php index 0c9fd8d..4b12847 100644 --- a/lib/kohana/system/libraries/Model.php +++ b/lib/kohana/system/libraries/Model.php @@ -1,4 +1,12 @@ -db)) - { - // Load the default database - $this->db = Database::instance($this->db); - } - } - -} // End Model \ No newline at end of file + /** + * Loads the database instance, if the database is not already loaded. + * + * @return void + */ + public function __construct() + { + if (! is_object($this->db)) { + // Load the default database + $this->db = Database::instance($this->db); + } + } +} +// End Model diff --git a/lib/kohana/system/libraries/ORM.php b/lib/kohana/system/libraries/ORM.php index c104860..8dcabb7 100644 --- a/lib/kohana/system/libraries/ORM.php +++ b/lib/kohana/system/libraries/ORM.php @@ -1,4 +1,12 @@ -object_name = strtolower(substr(get_class($this), 0, -6)); - $this->object_plural = inflector::plural($this->object_name); - - if (!isset($this->sorting)) - { - // Default sorting - $this->sorting = array($this->primary_key => 'asc'); - } - - // Initialize database - $this->__initialize(); - - // Clear the object - $this->clear(); - - if (is_object($id)) - { - // Load an object - $this->load_values((array) $id); - } - elseif (!empty($id)) - { - // Find an object - $this->find($id); - } - } - - /** - * Prepares the model database connection, determines the table name, - * and loads column information. - * - * @return void - */ - public function __initialize() - { - if ( ! is_object($this->db)) - { - // Get database instance - $this->db = Database::instance($this->db); - } - - if (empty($this->table_name)) - { - // Table name is the same as the object name - $this->table_name = $this->object_name; - - if ($this->table_names_plural === TRUE) - { - // Make the table name plural - $this->table_name = inflector::plural($this->table_name); - } - } - - if (is_array($this->ignored_columns)) - { - // Make the ignored columns mirrored = mirrored - $this->ignored_columns = array_combine($this->ignored_columns, $this->ignored_columns); - } - - // Load column information - $this->reload_columns(); - } - - /** - * Allows serialization of only the object data and state, to prevent - * "stale" objects being unserialized, which also requires less memory. - * - * @return array - */ - public function __sleep() - { - // Store only information about the object - return array('object_name', 'object', 'changed', 'loaded', 'saved', 'sorting'); - } - - /** - * Prepares the database connection and reloads the object. - * - * @return void - */ - public function __wakeup() - { - // Initialize database - $this->__initialize(); - - if ($this->reload_on_wakeup === TRUE) - { - // Reload the object - $this->reload(); - } - } - - /** - * Handles pass-through to database methods. Calls to query methods - * (query, get, insert, update) are not allowed. Query builder methods - * are chainable. - * - * @param string method name - * @param array method arguments - * @return mixed - */ - public function __call($method, array $args) - { - if (method_exists($this->db, $method)) - { - if (in_array($method, array('query', 'get', 'insert', 'update', 'delete'))) - throw new Kohana_Exception('orm.query_methods_not_allowed'); - - // Method has been applied to the database - $this->db_applied[$method] = $method; - - // Number of arguments passed - $num_args = count($args); - - if ($method === 'select' AND $num_args > 3) - { - // Call select() manually to avoid call_user_func_array - $this->db->select($args); - } - else - { - // We use switch here to manually call the database methods. This is - // done for speed: call_user_func_array can take over 300% longer to - // make calls. Most database methods are 4 arguments or less, so this - // avoids almost any calls to call_user_func_array. - - switch ($num_args) - { - case 0: - if (in_array($method, array('open_paren', 'close_paren', 'enable_cache', 'disable_cache'))) - { - // Should return ORM, not Database - $this->db->$method(); - } - else - { - // Support for things like reset_select, reset_write, list_tables - return $this->db->$method(); - } - break; - case 1: - $this->db->$method($args[0]); - break; - case 2: - $this->db->$method($args[0], $args[1]); - break; - case 3: - $this->db->$method($args[0], $args[1], $args[2]); - break; - case 4: - $this->db->$method($args[0], $args[1], $args[2], $args[3]); - break; - default: - // Here comes the snail... - call_user_func_array(array($this->db, $method), $args); - break; - } - } - - return $this; - } - else - { - throw new Kohana_Exception('core.invalid_method', $method, get_class($this)); - } - } - - /** - * Handles retrieval of all model values, relationships, and metadata. - * - * @param string column name - * @return mixed - */ - public function __get($column) - { - if (array_key_exists($column, $this->object)) - { - return $this->object[$column]; - } - elseif (isset($this->related[$column])) - { - return $this->related[$column]; - } - elseif ($column === 'primary_key_value') - { - return $this->object[$this->primary_key]; - } - elseif ($model = $this->related_object($column)) - { - // This handles the has_one and belongs_to relationships - - if (in_array($model->object_name, $this->belongs_to) OR ! array_key_exists($this->foreign_key($column), $model->object)) - { - // Foreign key lies in this table (this model belongs_to target model) OR an invalid has_one relationship - $where = array($model->table_name.'.'.$model->primary_key => $this->object[$this->foreign_key($column)]); - } - else - { - // Foreign key lies in the target table (this model has_one target model) - $where = array($this->foreign_key($column, $model->table_name) => $this->primary_key_value); - } - - // one<>alias:one relationship - return $this->related[$column] = $model->find($where); - } - elseif (isset($this->has_many[$column])) - { - // Load the "middle" model - $through = ORM::factory(inflector::singular($this->has_many[$column])); - - // Load the "end" model - $model = ORM::factory(inflector::singular($column)); - - // Join ON target model's primary key set to 'through' model's foreign key - // User-defined foreign keys must be defined in the 'through' model - $join_table = $through->table_name; - $join_col1 = $through->foreign_key($model->object_name, $join_table); - $join_col2 = $model->table_name.'.'.$model->primary_key; - - // one<>alias:many relationship - return $this->related[$column] = $model - ->join($join_table, $join_col1, $join_col2) - ->where($through->foreign_key($this->object_name, $join_table), $this->object[$this->primary_key]) - ->find_all(); - } - elseif (in_array($column, $this->has_many)) - { - // one<>many relationship - $model = ORM::factory(inflector::singular($column)); - return $this->related[$column] = $model - ->where($this->foreign_key($column, $model->table_name), $this->object[$this->primary_key]) - ->find_all(); - } - elseif (in_array($column, $this->has_and_belongs_to_many)) - { - // Load the remote model, always singular - $model = ORM::factory(inflector::singular($column)); - - if ($this->has($model, TRUE)) - { - // many<>many relationship - return $this->related[$column] = $model - ->in($model->table_name.'.'.$model->primary_key, $this->changed_relations[$column]) - ->find_all(); - } - else - { - // empty many<>many relationship - return $this->related[$column] = $model - ->where($model->table_name.'.'.$model->primary_key, NULL) - ->find_all(); - } - } - elseif (isset($this->ignored_columns[$column])) - { - return NULL; - } - elseif (in_array($column, array - ( - 'object_name', 'object_plural', // Object - 'primary_key', 'primary_val', 'table_name', 'table_columns', // Table - 'loaded', 'saved', // Status - 'has_one', 'belongs_to', 'has_many', 'has_and_belongs_to_many', 'load_with' // Relationships - ))) - { - // Model meta information - return $this->$column; - } - else - { - throw new Kohana_Exception('core.invalid_property', $column, get_class($this)); - } - } - - /** - * Handles setting of all model values, and tracks changes between values. - * - * @param string column name - * @param mixed column value - * @return void - */ - public function __set($column, $value) - { - if (isset($this->ignored_columns[$column])) - { - return NULL; - } - elseif (isset($this->object[$column]) OR array_key_exists($column, $this->object)) - { - if (isset($this->table_columns[$column])) - { - // Data has changed - $this->changed[$column] = $column; - - // Object is no longer saved - $this->saved = FALSE; - } - - $this->object[$column] = $this->load_type($column, $value); - } - elseif (in_array($column, $this->has_and_belongs_to_many) AND is_array($value)) - { - // Load relations - $model = ORM::factory(inflector::singular($column)); - - if ( ! isset($this->object_relations[$column])) - { - // Load relations - $this->has($model); - } - - // Change the relationships - $this->changed_relations[$column] = $value; - - if (isset($this->related[$column])) - { - // Force a reload of the relationships - unset($this->related[$column]); - } - } - else - { - throw new Kohana_Exception('core.invalid_property', $column, get_class($this)); - } - } - - /** - * Checks if object data is set. - * - * @param string column name - * @return boolean - */ - public function __isset($column) - { - return (isset($this->object[$column]) OR isset($this->related[$column])); - } - - /** - * Unsets object data. - * - * @param string column name - * @return void - */ - public function __unset($column) - { - unset($this->object[$column], $this->changed[$column], $this->related[$column]); - } - - /** - * Displays the primary key of a model when it is converted to a string. - * - * @return string - */ - public function __toString() - { - return (string) $this->object[$this->primary_key]; - } - - /** - * Returns the values of this object as an array. - * - * @return array - */ - public function as_array() - { - $object = array(); - - foreach ($this->object as $key => $val) - { - // Reconstruct the array (calls __get) - $object[$key] = $this->$key; - } - - return $object; - } - - /** - * Binds another one-to-one object to this model. One-to-one objects - * can be nested using 'object1:object2' syntax - * - * @param string $target_path - * @return void - */ - public function with($target_path) - { - if (isset($this->with_applied[$target_path])) - { - // Don't join anything already joined - return $this; - } - - // Split object parts - $objects = explode(':', $target_path); - $target = $this; - foreach ($objects as $object) - { - // Go down the line of objects to find the given target - $parent = $target; - $target = $parent->related_object($object); - - if ( ! $target) - { - // Can't find related object - return $this; - } - } - - $target_name = $object; - - // Pop-off top object to get the parent object (user:photo:tag becomes user:photo - the parent table prefix) - array_pop($objects); - $parent_path = implode(':', $objects); - - if (empty($parent_path)) - { - // Use this table name itself for the parent object - $parent_path = $this->table_name; - } - else - { - if( ! isset($this->with_applied[$parent_path])) - { - // If the parent object hasn't been joined yet, do it first (otherwise LEFT JOINs fail) - $this->with($parent_path); - } - } - - // Add to with_applied to prevent duplicate joins - $this->with_applied[$target_path] = TRUE; - - // Use the keys of the empty object to determine the columns - $select = array_keys($target->object); - foreach ($select as $i => $column) - { - // Add the prefix so that load_result can determine the relationship - $select[$i] = $target_path.'.'.$column.' AS '.$target_path.':'.$column; - } - - - // Select all of the prefixed keys in the object - $this->db->select($select); - - if (in_array($target->object_name, $parent->belongs_to) OR ! isset($target->object[$parent->foreign_key($target_name)])) - { - // Parent belongs_to target, use target's primary key as join column - $join_col1 = $target->foreign_key(TRUE, $target_path); - $join_col2 = $parent->foreign_key($target_name, $parent_path); - } - else - { - // Parent has_one target, use parent's primary key as join column - $join_col2 = $parent->foreign_key(TRUE, $parent_path); - $join_col1 = $parent->foreign_key($target_name, $target_path); - } - - // This allows for models to use different table prefixes (sharing the same database) - $join_table = new Database_Expression($target->db->table_prefix().$target->table_name.' AS '.$this->db->table_prefix().$target_path); - - // Join the related object into the result - $this->db->join($join_table, $join_col1, $join_col2, 'LEFT'); - - return $this; - } - - /** - * Finds and loads a single database row into the object. - * - * @chainable - * @param mixed primary key or an array of clauses - * @return ORM - */ - public function find($id = NULL) - { - if ($id !== NULL) - { - if (is_array($id)) - { - // Search for all clauses - $this->db->where($id); - } - else - { - // Search for a specific column - $this->db->where($this->table_name.'.'.$this->unique_key($id), $id); - } - } - - return $this->load_result(); - } - - /** - * Finds multiple database rows and returns an iterator of the rows found. - * - * @chainable - * @param integer SQL limit - * @param integer SQL offset - * @return ORM_Iterator - */ - public function find_all($limit = NULL, $offset = NULL) - { - if ($limit !== NULL AND ! isset($this->db_applied['limit'])) - { - // Set limit - $this->limit($limit); - } - - if ($offset !== NULL AND ! isset($this->db_applied['offset'])) - { - // Set offset - $this->offset($offset); - } - - return $this->load_result(TRUE); - } - - /** - * Creates a key/value array from all of the objects available. Uses find_all - * to find the objects. - * - * @param string key column - * @param string value column - * @return array - */ - public function select_list($key = NULL, $val = NULL) - { - if ($key === NULL) - { - $key = $this->primary_key; - } - - if ($val === NULL) - { - $val = $this->primary_val; - } - - // Return a select list from the results - return $this->select($key, $val)->find_all()->select_list($key, $val); - } - - /** - * Validates the current object. This method should generally be called - * via the model, after the $_POST Validation object has been created. - * - * @param object Validation array - * @return boolean - */ - public function validate(Validation $array, $save = FALSE) - { - $safe_array = $array->safe_array(); - - if ( ! $array->submitted()) - { - foreach ($safe_array as $key => $value) - { - // Get the value from this object - $value = $this->$key; - - if (is_object($value) AND $value instanceof ORM_Iterator) - { - // Convert the value to an array of primary keys - $value = $value->primary_key_array(); - } - - // Pre-fill data - $array[$key] = $value; - } - } - - // Validate the array - if ($status = $array->validate()) - { - // Grab only set fields (excludes missing data, unlike safe_array) - $fields = $array->as_array(); - - foreach ($fields as $key => $value) - { - if (isset($safe_array[$key])) - { - // Set new data, ignoring any missing fields or fields without rules - $this->$key = $value; - } - } - - if ($save === TRUE OR is_string($save)) - { - // Save this object - $this->save(); - - if (is_string($save)) - { - // Redirect to the saved page - url::redirect($save); - } - } - } - - // Return validation status - return $status; - } - - /** - * Saves the current object. - * - * @chainable - * @return ORM - */ - public function save() - { - if ( ! empty($this->changed)) - { - $data = array(); - foreach ($this->changed as $column) - { - // Compile changed data - $data[$column] = $this->object[$column]; - } - - if ($this->loaded === TRUE) - { - $query = $this->db - ->where($this->primary_key, $this->object[$this->primary_key]) - ->update($this->table_name, $data); - - // Object has been saved - $this->saved = TRUE; - } - else - { - $query = $this->db - ->insert($this->table_name, $data); - - if ($query->count() > 0) - { - if (empty($this->object[$this->primary_key])) - { - // Load the insert id as the primary key - $this->object[$this->primary_key] = $query->insert_id(); - } - - // Object is now loaded and saved - $this->loaded = $this->saved = TRUE; - } - } - - if ($this->saved === TRUE) - { - // All changes have been saved - $this->changed = array(); - } - } - - if ($this->saved === TRUE AND ! empty($this->changed_relations)) - { - foreach ($this->changed_relations as $column => $values) - { - // All values that were added - $added = array_diff($values, $this->object_relations[$column]); - - // All values that were saved - $removed = array_diff($this->object_relations[$column], $values); - - if (empty($added) AND empty($removed)) - { - // No need to bother - continue; - } - - // Clear related columns - unset($this->related[$column]); - - // Load the model - $model = ORM::factory(inflector::singular($column)); - - if (($join_table = array_search($column, $this->has_and_belongs_to_many)) === FALSE) - continue; - - if (is_int($join_table)) - { - // No "through" table, load the default JOIN table - $join_table = $model->join_table($this->table_name); - } - - // Foreign keys for the join table - $object_fk = $this->foreign_key(NULL); - $related_fk = $model->foreign_key(NULL); - - if ( ! empty($added)) - { - foreach ($added as $id) - { - // Insert the new relationship - $this->db->insert($join_table, array - ( - $object_fk => $this->object[$this->primary_key], - $related_fk => $id, - )); - } - } - - if ( ! empty($removed)) - { - $this->db - ->where($object_fk, $this->object[$this->primary_key]) - ->in($related_fk, $removed) - ->delete($join_table); - } - - // Clear all relations for this column - unset($this->object_relations[$column], $this->changed_relations[$column]); - } - } - - return $this; - } - - /** - * Deletes the current object from the database. This does NOT destroy - * relationships that have been created with other objects. - * - * @chainable - * @return ORM - */ - public function delete($id = NULL) - { - if ($id === NULL AND $this->loaded) - { - // Use the the primary key value - $id = $this->object[$this->primary_key]; - } - - // Delete this object - $this->db->where($this->primary_key, $id)->delete($this->table_name); - - return $this->clear(); - } - - /** - * Delete all objects in the associated table. This does NOT destroy - * relationships that have been created with other objects. - * - * @chainable - * @param array ids to delete - * @return ORM - */ - public function delete_all($ids = NULL) - { - if (is_array($ids)) - { - // Delete only given ids - $this->db->in($this->primary_key, $ids); - } - elseif (is_null($ids)) - { - // Delete all records - $this->db->where('1=1'); - } - else - { - // Do nothing - safeguard - return $this; - } - - // Delete all objects - $this->db->delete($this->table_name); - - return $this->clear(); - } - - /** - * Unloads the current object and clears the status. - * - * @chainable - * @return ORM - */ - public function clear() - { - // Create an array with all the columns set to NULL - $columns = array_keys($this->table_columns); - $values = array_combine($columns, array_fill(0, count($columns), NULL)); - - // Replace the current object with an empty one - $this->load_values($values); - - return $this; - } - - /** - * Reloads the current object from the database. - * - * @chainable - * @return ORM - */ - public function reload() - { - return $this->find($this->object[$this->primary_key]); - } - - /** - * Reload column definitions. - * - * @chainable - * @param boolean force reloading - * @return ORM - */ - public function reload_columns($force = FALSE) - { - if ($force === TRUE OR empty($this->table_columns)) - { - if (isset(ORM::$column_cache[$this->object_name])) - { - // Use cached column information - $this->table_columns = ORM::$column_cache[$this->object_name]; - } - else - { - // Load table columns - ORM::$column_cache[$this->object_name] = $this->table_columns = $this->list_fields(); - } - } - - return $this; - } - - /** - * Tests if this object has a relationship to a different model. - * - * @param object related ORM model - * @param boolean check for any relations to given model - * @return boolean - */ - public function has(ORM $model, $any = FALSE) - { - // Determine plural or singular relation name - $related = ($model->table_names_plural === TRUE) ? $model->object_plural : $model->object_name; - - if (($join_table = array_search($related, $this->has_and_belongs_to_many)) === FALSE) - return FALSE; - - if (is_int($join_table)) - { - // No "through" table, load the default JOIN table - $join_table = $model->join_table($this->table_name); - } - - if ( ! isset($this->object_relations[$related])) - { - // Load the object relationships - $this->changed_relations[$related] = $this->object_relations[$related] = $this->load_relations($join_table, $model); - } - - if ( ! $model->empty_primary_key()) - { - // Check if a specific object exists - return in_array($model->primary_key_value, $this->changed_relations[$related]); - } - elseif ($any) - { - // Check if any relations to given model exist - return ! empty($this->changed_relations[$related]); - } - else - { - return FALSE; - } - } - - /** - * Adds a new relationship to between this model and another. - * - * @param object related ORM model - * @return boolean - */ - public function add(ORM $model) - { - if ($this->has($model)) - return TRUE; - - // Get the faked column name - $column = $model->object_plural; - - // Add the new relation to the update - $this->changed_relations[$column][] = $model->primary_key_value; - - if (isset($this->related[$column])) - { - // Force a reload of the relationships - unset($this->related[$column]); - } - - return TRUE; - } - - /** - * Adds a new relationship to between this model and another. - * - * @param object related ORM model - * @return boolean - */ - public function remove(ORM $model) - { - if ( ! $this->has($model)) - return FALSE; - - // Get the faked column name - $column = $model->object_plural; - - if (($key = array_search($model->primary_key_value, $this->changed_relations[$column])) === FALSE) - return FALSE; - - // Remove the relationship - unset($this->changed_relations[$column][$key]); - - if (isset($this->related[$column])) - { - // Force a reload of the relationships - unset($this->related[$column]); - } - - return TRUE; - } - - /** - * Count the number of records in the table. - * - * @return integer - */ - public function count_all() - { - // Return the total number of records in a table - return $this->db->count_records($this->table_name); - } - - /** - * Proxy method to Database list_fields. - * - * @param string table name or NULL to use this table - * @return array - */ - public function list_fields($table = NULL) - { - if ($table === NULL) - { - $table = $this->table_name; - } - - // Proxy to database - return $this->db->list_fields($table); - } - - /** - * Proxy method to Database field_data. - * - * @param string table name - * @return array - */ - public function field_data($table) - { - // Proxy to database - return $this->db->field_data($table); - } - - /** - * Proxy method to Database field_data. - * - * @chainable - * @param string SQL query to clear - * @return ORM - */ - public function clear_cache($sql = NULL) - { - // Proxy to database - $this->db->clear_cache($sql); - - ORM::$column_cache = array(); - - return $this; - } - - /** - * Returns the unique key for a specific value. This method is expected - * to be overloaded in models if the model has other unique columns. - * - * @param mixed unique value - * @return string - */ - public function unique_key($id) - { - return $this->primary_key; - } - - /** - * Determines the name of a foreign key for a specific table. - * - * @param string related table name - * @param string prefix table name (used for JOINs) - * @return string - */ - public function foreign_key($table = NULL, $prefix_table = NULL) - { - if ($table === TRUE) - { - if (is_string($prefix_table)) - { - // Use prefix table name and this table's PK - return $prefix_table.'.'.$this->primary_key; - } - else - { - // Return the name of this table's PK - return $this->table_name.'.'.$this->primary_key; - } - } - - if (is_string($prefix_table)) - { - // Add a period for prefix_table.column support - $prefix_table .= '.'; - } - - if (isset($this->foreign_key[$table])) - { - // Use the defined foreign key name, no magic here! - $foreign_key = $this->foreign_key[$table]; - } - else - { - if ( ! is_string($table) OR ! array_key_exists($table.'_'.$this->primary_key, $this->object)) - { - // Use this table - $table = $this->table_name; - - if (strpos($table, '.') !== FALSE) - { - // Hack around support for PostgreSQL schemas - list ($schema, $table) = explode('.', $table, 2); - } - - if ($this->table_names_plural === TRUE) - { - // Make the key name singular - $table = inflector::singular($table); - } - } - - $foreign_key = $table.'_'.$this->primary_key; - } - - return $prefix_table.$foreign_key; - } - - /** - * This uses alphabetical comparison to choose the name of the table. - * - * Example: The joining table of users and roles would be roles_users, - * because "r" comes before "u". Joining products and categories would - * result in categories_products, because "c" comes before "p". - * - * Example: zoo > zebra > robber > ocean > angel > aardvark - * - * @param string table name - * @return string - */ - public function join_table($table) - { - if ($this->table_name > $table) - { - $table = $table.'_'.$this->table_name; - } - else - { - $table = $this->table_name.'_'.$table; - } - - return $table; - } - - /** - * Returns an ORM model for the given object name; - * - * @param string object name - * @return ORM - */ - protected function related_object($object) - { - if (isset($this->has_one[$object])) - { - $object = ORM::factory($this->has_one[$object]); - } - elseif (isset($this->belongs_to[$object])) - { - $object = ORM::factory($this->belongs_to[$object]); - } - elseif (in_array($object, $this->has_one) OR in_array($object, $this->belongs_to)) - { - $object = ORM::factory($object); - } - else - { - return FALSE; - } - - return $object; - } - - /** - * Loads an array of values into into the current object. - * - * @chainable - * @param array values to load - * @return ORM - */ - public function load_values(array $values) - { - if (array_key_exists($this->primary_key, $values)) - { - // Replace the object and reset the object status - $this->object = $this->changed = $this->related = array(); - - // Set the loaded and saved object status based on the primary key - $this->loaded = $this->saved = ($values[$this->primary_key] !== NULL); - } - - // Related objects - $related = array(); - - foreach ($values as $column => $value) - { - if (strpos($column, ':') === FALSE) - { - if (isset($this->table_columns[$column])) - { - // The type of the value can be determined, convert the value - $value = $this->load_type($column, $value); - } - - $this->object[$column] = $value; - } - else - { - list ($prefix, $column) = explode(':', $column, 2); - - $related[$prefix][$column] = $value; - } - } - - if ( ! empty($related)) - { - foreach ($related as $object => $values) - { - // Load the related objects with the values in the result - $this->related[$object] = $this->related_object($object)->load_values($values); - } - } - - return $this; - } - - /** - * Loads a value according to the types defined by the column metadata. - * - * @param string column name - * @param mixed value to load - * @return mixed - */ - protected function load_type($column, $value) - { - $type = gettype($value); - if ($type == 'object' OR $type == 'array' OR ! isset($this->table_columns[$column])) - return $value; - - // Load column data - $column = $this->table_columns[$column]; - - if ($value === NULL AND ! empty($column['null'])) - return $value; - - if ( ! empty($column['binary']) AND ! empty($column['exact']) AND (int) $column['length'] === 1) - { - // Use boolean for BINARY(1) fields - $column['type'] = 'boolean'; - } - - switch ($column['type']) - { - case 'int': - if ($value === '' AND ! empty($column['null'])) - { - // Forms will only submit strings, so empty integer values must be null - $value = NULL; - } - elseif ((float) $value > PHP_INT_MAX) - { - // This number cannot be represented by a PHP integer, so we convert it to a string - $value = (string) $value; - } - else - { - $value = (int) $value; - } - break; - case 'float': - $value = (float) $value; - break; - case 'boolean': - $value = (bool) $value; - break; - case 'string': - $value = (string) $value; - break; - } - - return $value; - } - - /** - * Loads a database result, either as a new object for this model, or as - * an iterator for multiple rows. - * - * @chainable - * @param boolean return an iterator or load a single row - * @return ORM for single rows - * @return ORM_Iterator for multiple rows - */ - protected function load_result($array = FALSE) - { - if ($array === FALSE) - { - // Only fetch 1 record - $this->db->limit(1); - } - - if ( ! isset($this->db_applied['select'])) - { - // Select all columns by default - $this->db->select($this->table_name.'.*'); - } - - if ( ! empty($this->load_with)) - { - foreach ($this->load_with as $alias => $object) - { - // Join each object into the results - if (is_string($alias)) - { - // Use alias - $this->with($alias); - } - else - { - // Use object - $this->with($object); - } - } - } - - if ( ! isset($this->db_applied['orderby']) AND ! empty($this->sorting)) - { - $sorting = array(); - foreach ($this->sorting as $column => $direction) - { - if (strpos($column, '.') === FALSE) - { - // Keeps sorting working properly when using JOINs on - // tables with columns of the same name - $column = $this->table_name.'.'.$column; - } - - $sorting[$column] = $direction; - } - - // Apply the user-defined sorting - $this->db->orderby($sorting); - } - - // Load the result - $result = $this->db->get($this->table_name); - - if ($array === TRUE) - { - // Return an iterated result - return new ORM_Iterator($this, $result); - } - - if ($result->count() === 1) - { - // Load object values - $this->load_values($result->result(FALSE)->current()); - } - else - { - // Clear the object, nothing was found - $this->clear(); - } - - return $this; - } - - /** - * Return an array of all the primary keys of the related table. - * - * @param string table name - * @param object ORM model to find relations of - * @return array - */ - protected function load_relations($table, ORM $model) - { - // Save the current query chain (otherwise the next call will clash) - $this->db->push(); - - $query = $this->db - ->select($model->foreign_key(NULL).' AS id') - ->from($table) - ->where($this->foreign_key(NULL, $table), $this->object[$this->primary_key]) - ->get() - ->result(TRUE); - - $this->db->pop(); - - $relations = array(); - foreach ($query as $row) - { - $relations[] = $row->id; - } - - return $relations; - } - - /** - * Returns whether or not primary key is empty - * - * @return bool - */ - protected function empty_primary_key() - { - return (empty($this->object[$this->primary_key]) AND $this->object[$this->primary_key] !== '0'); - } - -} // End ORM +class ORM_Core +{ + // Current relationships + protected $has_one = array(); + protected $belongs_to = array(); + protected $has_many = array(); + protected $has_and_belongs_to_many = array(); + + // Relationships that should always be joined + protected $load_with = array(); + + // Current object + protected $object = array(); + protected $changed = array(); + protected $related = array(); + protected $loaded = false; + protected $saved = false; + protected $sorting; + + // Related objects + protected $object_relations = array(); + protected $changed_relations = array(); + + // Model table information + protected $object_name; + protected $object_plural; + protected $table_name; + protected $table_columns; + protected $ignored_columns; + + // Table primary key and value + protected $primary_key = 'id'; + protected $primary_val = 'name'; + + // Array of foreign key name overloads + protected $foreign_key = array(); + + // Model configuration + protected $table_names_plural = true; + protected $reload_on_wakeup = true; + + // Database configuration + protected $db = 'default'; + protected $db_applied = array(); + + // With calls already applied + protected $with_applied = array(); + + // Stores column information for ORM models + protected static $column_cache = array(); + + /** + * Creates and returns a new model. + * + * @chainable + * @param string model name + * @param mixed parameter for find() + * @return ORM + */ + public static function factory($model, $id = null) + { + // Set class name + $model = ucfirst($model) . '_Model'; + + return new $model($id); + } + + /** + * Prepares the model database connection and loads the object. + * + * @param mixed parameter for find or object to load + * @return void + */ + public function __construct($id = null) + { + // Set the object name and plural name + $this->object_name = strtolower(substr(get_class($this), 0, -6)); + $this->object_plural = inflector::plural($this->object_name); + + if (!isset($this->sorting)) { + // Default sorting + $this->sorting = array($this->primary_key => 'asc'); + } + + // Initialize database + $this->__initialize(); + + // Clear the object + $this->clear(); + + if (is_object($id)) { + // Load an object + $this->load_values((array) $id); + } elseif (!empty($id)) { + // Find an object + $this->find($id); + } + } + + /** + * Prepares the model database connection, determines the table name, + * and loads column information. + * + * @return void + */ + public function __initialize() + { + if (! is_object($this->db)) { + // Get database instance + $this->db = Database::instance($this->db); + } + + if (empty($this->table_name)) { + // Table name is the same as the object name + $this->table_name = $this->object_name; + + if ($this->table_names_plural === true) { + // Make the table name plural + $this->table_name = inflector::plural($this->table_name); + } + } + + if (is_array($this->ignored_columns)) { + // Make the ignored columns mirrored = mirrored + $this->ignored_columns = array_combine($this->ignored_columns, $this->ignored_columns); + } + + // Load column information + $this->reload_columns(); + } + + /** + * Allows serialization of only the object data and state, to prevent + * "stale" objects being unserialized, which also requires less memory. + * + * @return array + */ + public function __sleep() + { + // Store only information about the object + return array('object_name', 'object', 'changed', 'loaded', 'saved', 'sorting'); + } + + /** + * Prepares the database connection and reloads the object. + * + * @return void + */ + public function __wakeup() + { + // Initialize database + $this->__initialize(); + + if ($this->reload_on_wakeup === true) { + // Reload the object + $this->reload(); + } + } + + /** + * Handles pass-through to database methods. Calls to query methods + * (query, get, insert, update) are not allowed. Query builder methods + * are chainable. + * + * @param string method name + * @param array method arguments + * @return mixed + */ + public function __call($method, array $args) + { + if (method_exists($this->db, $method)) { + if (in_array($method, array('query', 'get', 'insert', 'update', 'delete'))) { + throw new Kohana_Exception('orm.query_methods_not_allowed'); + } + + // Method has been applied to the database + $this->db_applied[$method] = $method; + + // Number of arguments passed + $num_args = count($args); + + if ($method === 'select' and $num_args > 3) { + // Call select() manually to avoid call_user_func_array + $this->db->select($args); + } else { + // We use switch here to manually call the database methods. This is + // done for speed: call_user_func_array can take over 300% longer to + // make calls. Most database methods are 4 arguments or less, so this + // avoids almost any calls to call_user_func_array. + + switch ($num_args) { + case 0: + if (in_array($method, array('open_paren', 'close_paren', 'enable_cache', 'disable_cache'))) { + // Should return ORM, not Database + $this->db->$method(); + } else { + // Support for things like reset_select, reset_write, list_tables + return $this->db->$method(); + } + break; + case 1: + $this->db->$method($args[0]); + break; + case 2: + $this->db->$method($args[0], $args[1]); + break; + case 3: + $this->db->$method($args[0], $args[1], $args[2]); + break; + case 4: + $this->db->$method($args[0], $args[1], $args[2], $args[3]); + break; + default: + // Here comes the snail... + call_user_func_array(array($this->db, $method), $args); + break; + } + } + + return $this; + } else { + throw new Kohana_Exception('core.invalid_method', $method, get_class($this)); + } + } + + /** + * Handles retrieval of all model values, relationships, and metadata. + * + * @param string column name + * @return mixed + */ + public function __get($column) + { + if (array_key_exists($column, $this->object)) { + return $this->object[$column]; + } elseif (isset($this->related[$column])) { + return $this->related[$column]; + } elseif ($column === 'primary_key_value') { + return $this->object[$this->primary_key]; + } elseif ($model = $this->related_object($column)) { + // This handles the has_one and belongs_to relationships + + if (in_array($model->object_name, $this->belongs_to) or ! array_key_exists($this->foreign_key($column), $model->object)) { + // Foreign key lies in this table (this model belongs_to target model) OR an invalid has_one relationship + $where = array($model->table_name . '.' . $model->primary_key => $this->object[$this->foreign_key($column)]); + } else { + // Foreign key lies in the target table (this model has_one target model) + $where = array($this->foreign_key($column, $model->table_name) => $this->primary_key_value); + } + + // one<>alias:one relationship + return $this->related[$column] = $model->find($where); + } elseif (isset($this->has_many[$column])) { + // Load the "middle" model + $through = ORM::factory(inflector::singular($this->has_many[$column])); + + // Load the "end" model + $model = ORM::factory(inflector::singular($column)); + + // Join ON target model's primary key set to 'through' model's foreign key + // User-defined foreign keys must be defined in the 'through' model + $join_table = $through->table_name; + $join_col1 = $through->foreign_key($model->object_name, $join_table); + $join_col2 = $model->table_name . '.' . $model->primary_key; + + // one<>alias:many relationship + return $this->related[$column] = $model + ->join($join_table, $join_col1, $join_col2) + ->where($through->foreign_key($this->object_name, $join_table), $this->object[$this->primary_key]) + ->find_all(); + } elseif (in_array($column, $this->has_many)) { + // one<>many relationship + $model = ORM::factory(inflector::singular($column)); + return $this->related[$column] = $model + ->where($this->foreign_key($column, $model->table_name), $this->object[$this->primary_key]) + ->find_all(); + } elseif (in_array($column, $this->has_and_belongs_to_many)) { + // Load the remote model, always singular + $model = ORM::factory(inflector::singular($column)); + + if ($this->has($model, true)) { + // many<>many relationship + return $this->related[$column] = $model + ->in($model->table_name . '.' . $model->primary_key, $this->changed_relations[$column]) + ->find_all(); + } else { + // empty many<>many relationship + return $this->related[$column] = $model + ->where($model->table_name . '.' . $model->primary_key, null) + ->find_all(); + } + } elseif (isset($this->ignored_columns[$column])) { + return null; + } elseif ( + in_array($column, array + ( + 'object_name', 'object_plural', // Object + 'primary_key', 'primary_val', 'table_name', 'table_columns', // Table + 'loaded', 'saved', // Status + 'has_one', 'belongs_to', 'has_many', 'has_and_belongs_to_many', 'load_with' // Relationships + )) + ) { + // Model meta information + return $this->$column; + } else { + throw new Kohana_Exception('core.invalid_property', $column, get_class($this)); + } + } + + /** + * Handles setting of all model values, and tracks changes between values. + * + * @param string column name + * @param mixed column value + * @return void + */ + public function __set($column, $value) + { + if (isset($this->ignored_columns[$column])) { + return null; + } elseif (isset($this->object[$column]) or array_key_exists($column, $this->object)) { + if (isset($this->table_columns[$column])) { + // Data has changed + $this->changed[$column] = $column; + + // Object is no longer saved + $this->saved = false; + } + + $this->object[$column] = $this->load_type($column, $value); + } elseif (in_array($column, $this->has_and_belongs_to_many) and is_array($value)) { + // Load relations + $model = ORM::factory(inflector::singular($column)); + + if (! isset($this->object_relations[$column])) { + // Load relations + $this->has($model); + } + + // Change the relationships + $this->changed_relations[$column] = $value; + + if (isset($this->related[$column])) { + // Force a reload of the relationships + unset($this->related[$column]); + } + } else { + throw new Kohana_Exception('core.invalid_property', $column, get_class($this)); + } + } + + /** + * Checks if object data is set. + * + * @param string column name + * @return boolean + */ + public function __isset($column) + { + return (isset($this->object[$column]) or isset($this->related[$column])); + } + + /** + * Unsets object data. + * + * @param string column name + * @return void + */ + public function __unset($column) + { + unset($this->object[$column], $this->changed[$column], $this->related[$column]); + } + + /** + * Displays the primary key of a model when it is converted to a string. + * + * @return string + */ + public function __toString() + { + return (string) $this->object[$this->primary_key]; + } + + /** + * Returns the values of this object as an array. + * + * @return array + */ + public function as_array() + { + $object = array(); + + foreach ($this->object as $key => $val) { + // Reconstruct the array (calls __get) + $object[$key] = $this->$key; + } + + return $object; + } + + /** + * Binds another one-to-one object to this model. One-to-one objects + * can be nested using 'object1:object2' syntax + * + * @param string $target_path + * @return void + */ + public function with($target_path) + { + if (isset($this->with_applied[$target_path])) { + // Don't join anything already joined + return $this; + } + + // Split object parts + $objects = explode(':', $target_path); + $target = $this; + foreach ($objects as $object) { + // Go down the line of objects to find the given target + $parent = $target; + $target = $parent->related_object($object); + + if (! $target) { + // Can't find related object + return $this; + } + } + + $target_name = $object; + + // Pop-off top object to get the parent object (user:photo:tag becomes user:photo - the parent table prefix) + array_pop($objects); + $parent_path = implode(':', $objects); + + if (empty($parent_path)) { + // Use this table name itself for the parent object + $parent_path = $this->table_name; + } else { + if (! isset($this->with_applied[$parent_path])) { + // If the parent object hasn't been joined yet, do it first (otherwise LEFT JOINs fail) + $this->with($parent_path); + } + } + + // Add to with_applied to prevent duplicate joins + $this->with_applied[$target_path] = true; + + // Use the keys of the empty object to determine the columns + $select = array_keys($target->object); + foreach ($select as $i => $column) { + // Add the prefix so that load_result can determine the relationship + $select[$i] = $target_path . '.' . $column . ' AS ' . $target_path . ':' . $column; + } + + + // Select all of the prefixed keys in the object + $this->db->select($select); + + if (in_array($target->object_name, $parent->belongs_to) or ! isset($target->object[$parent->foreign_key($target_name)])) { + // Parent belongs_to target, use target's primary key as join column + $join_col1 = $target->foreign_key(true, $target_path); + $join_col2 = $parent->foreign_key($target_name, $parent_path); + } else { + // Parent has_one target, use parent's primary key as join column + $join_col2 = $parent->foreign_key(true, $parent_path); + $join_col1 = $parent->foreign_key($target_name, $target_path); + } + + // This allows for models to use different table prefixes (sharing the same database) + $join_table = new Database_Expression($target->db->table_prefix() . $target->table_name . ' AS ' . $this->db->table_prefix() . $target_path); + + // Join the related object into the result + $this->db->join($join_table, $join_col1, $join_col2, 'LEFT'); + + return $this; + } + + /** + * Finds and loads a single database row into the object. + * + * @chainable + * @param mixed primary key or an array of clauses + * @return ORM + */ + public function find($id = null) + { + if ($id !== null) { + if (is_array($id)) { + // Search for all clauses + $this->db->where($id); + } else { + // Search for a specific column + $this->db->where($this->table_name . '.' . $this->unique_key($id), $id); + } + } + + return $this->load_result(); + } + + /** + * Finds multiple database rows and returns an iterator of the rows found. + * + * @chainable + * @param integer SQL limit + * @param integer SQL offset + * @return ORM_Iterator + */ + public function find_all($limit = null, $offset = null) + { + if ($limit !== null and ! isset($this->db_applied['limit'])) { + // Set limit + $this->limit($limit); + } + + if ($offset !== null and ! isset($this->db_applied['offset'])) { + // Set offset + $this->offset($offset); + } + + return $this->load_result(true); + } + + /** + * Creates a key/value array from all of the objects available. Uses find_all + * to find the objects. + * + * @param string key column + * @param string value column + * @return array + */ + public function select_list($key = null, $val = null) + { + if ($key === null) { + $key = $this->primary_key; + } + + if ($val === null) { + $val = $this->primary_val; + } + + // Return a select list from the results + return $this->select($key, $val)->find_all()->select_list($key, $val); + } + + /** + * Validates the current object. This method should generally be called + * via the model, after the $_POST Validation object has been created. + * + * @param object Validation array + * @return boolean + */ + public function validate(Validation $array, $save = false) + { + $safe_array = $array->safe_array(); + + if (! $array->submitted()) { + foreach ($safe_array as $key => $value) { + // Get the value from this object + $value = $this->$key; + + if (is_object($value) and $value instanceof ORM_Iterator) { + // Convert the value to an array of primary keys + $value = $value->primary_key_array(); + } + + // Pre-fill data + $array[$key] = $value; + } + } + + // Validate the array + if ($status = $array->validate()) { + // Grab only set fields (excludes missing data, unlike safe_array) + $fields = $array->as_array(); + + foreach ($fields as $key => $value) { + if (isset($safe_array[$key])) { + // Set new data, ignoring any missing fields or fields without rules + $this->$key = $value; + } + } + + if ($save === true or is_string($save)) { + // Save this object + $this->save(); + + if (is_string($save)) { + // Redirect to the saved page + url::redirect($save); + } + } + } + + // Return validation status + return $status; + } + + /** + * Saves the current object. + * + * @chainable + * @return ORM + */ + public function save() + { + if (! empty($this->changed)) { + $data = array(); + foreach ($this->changed as $column) { + // Compile changed data + $data[$column] = $this->object[$column]; + } + + if ($this->loaded === true) { + $query = $this->db + ->where($this->primary_key, $this->object[$this->primary_key]) + ->update($this->table_name, $data); + + // Object has been saved + $this->saved = true; + } else { + $query = $this->db + ->insert($this->table_name, $data); + + if ($query->count() > 0) { + if (empty($this->object[$this->primary_key])) { + // Load the insert id as the primary key + $this->object[$this->primary_key] = $query->insert_id(); + } + + // Object is now loaded and saved + $this->loaded = $this->saved = true; + } + } + + if ($this->saved === true) { + // All changes have been saved + $this->changed = array(); + } + } + + if ($this->saved === true and ! empty($this->changed_relations)) { + foreach ($this->changed_relations as $column => $values) { + // All values that were added + $added = array_diff($values, $this->object_relations[$column]); + + // All values that were saved + $removed = array_diff($this->object_relations[$column], $values); + + if (empty($added) and empty($removed)) { + // No need to bother + continue; + } + + // Clear related columns + unset($this->related[$column]); + + // Load the model + $model = ORM::factory(inflector::singular($column)); + + if (($join_table = array_search($column, $this->has_and_belongs_to_many)) === false) { + continue; + } + + if (is_int($join_table)) { + // No "through" table, load the default JOIN table + $join_table = $model->join_table($this->table_name); + } + + // Foreign keys for the join table + $object_fk = $this->foreign_key(null); + $related_fk = $model->foreign_key(null); + + if (! empty($added)) { + foreach ($added as $id) { + // Insert the new relationship + $this->db->insert($join_table, array + ( + $object_fk => $this->object[$this->primary_key], + $related_fk => $id, + )); + } + } + + if (! empty($removed)) { + $this->db + ->where($object_fk, $this->object[$this->primary_key]) + ->in($related_fk, $removed) + ->delete($join_table); + } + + // Clear all relations for this column + unset($this->object_relations[$column], $this->changed_relations[$column]); + } + } + + return $this; + } + + /** + * Deletes the current object from the database. This does NOT destroy + * relationships that have been created with other objects. + * + * @chainable + * @return ORM + */ + public function delete($id = null) + { + if ($id === null and $this->loaded) { + // Use the the primary key value + $id = $this->object[$this->primary_key]; + } + + // Delete this object + $this->db->where($this->primary_key, $id)->delete($this->table_name); + + return $this->clear(); + } + + /** + * Delete all objects in the associated table. This does NOT destroy + * relationships that have been created with other objects. + * + * @chainable + * @param array ids to delete + * @return ORM + */ + public function delete_all($ids = null) + { + if (is_array($ids)) { + // Delete only given ids + $this->db->in($this->primary_key, $ids); + } elseif (is_null($ids)) { + // Delete all records + $this->db->where('1=1'); + } else { + // Do nothing - safeguard + return $this; + } + + // Delete all objects + $this->db->delete($this->table_name); + + return $this->clear(); + } + + /** + * Unloads the current object and clears the status. + * + * @chainable + * @return ORM + */ + public function clear() + { + // Create an array with all the columns set to NULL + $columns = array_keys($this->table_columns); + $values = array_combine($columns, array_fill(0, count($columns), null)); + + // Replace the current object with an empty one + $this->load_values($values); + + return $this; + } + + /** + * Reloads the current object from the database. + * + * @chainable + * @return ORM + */ + public function reload() + { + return $this->find($this->object[$this->primary_key]); + } + + /** + * Reload column definitions. + * + * @chainable + * @param boolean force reloading + * @return ORM + */ + public function reload_columns($force = false) + { + if ($force === true or empty($this->table_columns)) { + if (isset(ORM::$column_cache[$this->object_name])) { + // Use cached column information + $this->table_columns = ORM::$column_cache[$this->object_name]; + } else { + // Load table columns + ORM::$column_cache[$this->object_name] = $this->table_columns = $this->list_fields(); + } + } + + return $this; + } + + /** + * Tests if this object has a relationship to a different model. + * + * @param object related ORM model + * @param boolean check for any relations to given model + * @return boolean + */ + public function has(ORM $model, $any = false) + { + // Determine plural or singular relation name + $related = ($model->table_names_plural === true) ? $model->object_plural : $model->object_name; + + if (($join_table = array_search($related, $this->has_and_belongs_to_many)) === false) { + return false; + } + + if (is_int($join_table)) { + // No "through" table, load the default JOIN table + $join_table = $model->join_table($this->table_name); + } + + if (! isset($this->object_relations[$related])) { + // Load the object relationships + $this->changed_relations[$related] = $this->object_relations[$related] = $this->load_relations($join_table, $model); + } + + if (! $model->empty_primary_key()) { + // Check if a specific object exists + return in_array($model->primary_key_value, $this->changed_relations[$related]); + } elseif ($any) { + // Check if any relations to given model exist + return ! empty($this->changed_relations[$related]); + } else { + return false; + } + } + + /** + * Adds a new relationship to between this model and another. + * + * @param object related ORM model + * @return boolean + */ + public function add(ORM $model) + { + if ($this->has($model)) { + return true; + } + + // Get the faked column name + $column = $model->object_plural; + + // Add the new relation to the update + $this->changed_relations[$column][] = $model->primary_key_value; + + if (isset($this->related[$column])) { + // Force a reload of the relationships + unset($this->related[$column]); + } + + return true; + } + + /** + * Adds a new relationship to between this model and another. + * + * @param object related ORM model + * @return boolean + */ + public function remove(ORM $model) + { + if (! $this->has($model)) { + return false; + } + + // Get the faked column name + $column = $model->object_plural; + + if (($key = array_search($model->primary_key_value, $this->changed_relations[$column])) === false) { + return false; + } + + // Remove the relationship + unset($this->changed_relations[$column][$key]); + + if (isset($this->related[$column])) { + // Force a reload of the relationships + unset($this->related[$column]); + } + + return true; + } + + /** + * Count the number of records in the table. + * + * @return integer + */ + public function count_all() + { + // Return the total number of records in a table + return $this->db->count_records($this->table_name); + } + + /** + * Proxy method to Database list_fields. + * + * @param string table name or NULL to use this table + * @return array + */ + public function list_fields($table = null) + { + if ($table === null) { + $table = $this->table_name; + } + + // Proxy to database + return $this->db->list_fields($table); + } + + /** + * Proxy method to Database field_data. + * + * @param string table name + * @return array + */ + public function field_data($table) + { + // Proxy to database + return $this->db->field_data($table); + } + + /** + * Proxy method to Database field_data. + * + * @chainable + * @param string SQL query to clear + * @return ORM + */ + public function clear_cache($sql = null) + { + // Proxy to database + $this->db->clear_cache($sql); + + ORM::$column_cache = array(); + + return $this; + } + + /** + * Returns the unique key for a specific value. This method is expected + * to be overloaded in models if the model has other unique columns. + * + * @param mixed unique value + * @return string + */ + public function unique_key($id) + { + return $this->primary_key; + } + + /** + * Determines the name of a foreign key for a specific table. + * + * @param string related table name + * @param string prefix table name (used for JOINs) + * @return string + */ + public function foreign_key($table = null, $prefix_table = null) + { + if ($table === true) { + if (is_string($prefix_table)) { + // Use prefix table name and this table's PK + return $prefix_table . '.' . $this->primary_key; + } else { + // Return the name of this table's PK + return $this->table_name . '.' . $this->primary_key; + } + } + + if (is_string($prefix_table)) { + // Add a period for prefix_table.column support + $prefix_table .= '.'; + } + + if (isset($this->foreign_key[$table])) { + // Use the defined foreign key name, no magic here! + $foreign_key = $this->foreign_key[$table]; + } else { + if (! is_string($table) or ! array_key_exists($table . '_' . $this->primary_key, $this->object)) { + // Use this table + $table = $this->table_name; + + if (strpos($table, '.') !== false) { + // Hack around support for PostgreSQL schemas + list ($schema, $table) = explode('.', $table, 2); + } + + if ($this->table_names_plural === true) { + // Make the key name singular + $table = inflector::singular($table); + } + } + + $foreign_key = $table . '_' . $this->primary_key; + } + + return $prefix_table . $foreign_key; + } + + /** + * This uses alphabetical comparison to choose the name of the table. + * + * Example: The joining table of users and roles would be roles_users, + * because "r" comes before "u". Joining products and categories would + * result in categories_products, because "c" comes before "p". + * + * Example: zoo > zebra > robber > ocean > angel > aardvark + * + * @param string table name + * @return string + */ + public function join_table($table) + { + if ($this->table_name > $table) { + $table = $table . '_' . $this->table_name; + } else { + $table = $this->table_name . '_' . $table; + } + + return $table; + } + + /** + * Returns an ORM model for the given object name; + * + * @param string object name + * @return ORM + */ + protected function related_object($object) + { + if (isset($this->has_one[$object])) { + $object = ORM::factory($this->has_one[$object]); + } elseif (isset($this->belongs_to[$object])) { + $object = ORM::factory($this->belongs_to[$object]); + } elseif (in_array($object, $this->has_one) or in_array($object, $this->belongs_to)) { + $object = ORM::factory($object); + } else { + return false; + } + + return $object; + } + + /** + * Loads an array of values into into the current object. + * + * @chainable + * @param array values to load + * @return ORM + */ + public function load_values(array $values) + { + if (array_key_exists($this->primary_key, $values)) { + // Replace the object and reset the object status + $this->object = $this->changed = $this->related = array(); + + // Set the loaded and saved object status based on the primary key + $this->loaded = $this->saved = ($values[$this->primary_key] !== null); + } + + // Related objects + $related = array(); + + foreach ($values as $column => $value) { + if (strpos($column, ':') === false) { + if (isset($this->table_columns[$column])) { + // The type of the value can be determined, convert the value + $value = $this->load_type($column, $value); + } + + $this->object[$column] = $value; + } else { + list ($prefix, $column) = explode(':', $column, 2); + + $related[$prefix][$column] = $value; + } + } + + if (! empty($related)) { + foreach ($related as $object => $values) { + // Load the related objects with the values in the result + $this->related[$object] = $this->related_object($object)->load_values($values); + } + } + + return $this; + } + + /** + * Loads a value according to the types defined by the column metadata. + * + * @param string column name + * @param mixed value to load + * @return mixed + */ + protected function load_type($column, $value) + { + $type = gettype($value); + if ($type == 'object' or $type == 'array' or ! isset($this->table_columns[$column])) { + return $value; + } + + // Load column data + $column = $this->table_columns[$column]; + + if ($value === null and ! empty($column['null'])) { + return $value; + } + + if (! empty($column['binary']) and ! empty($column['exact']) and (int) $column['length'] === 1) { + // Use boolean for BINARY(1) fields + $column['type'] = 'boolean'; + } + + switch ($column['type']) { + case 'int': + if ($value === '' and ! empty($column['null'])) { + // Forms will only submit strings, so empty integer values must be null + $value = null; + } elseif ((float) $value > PHP_INT_MAX) { + // This number cannot be represented by a PHP integer, so we convert it to a string + $value = (string) $value; + } else { + $value = (int) $value; + } + break; + case 'float': + $value = (float) $value; + break; + case 'boolean': + $value = (bool) $value; + break; + case 'string': + $value = (string) $value; + break; + } + + return $value; + } + + /** + * Loads a database result, either as a new object for this model, or as + * an iterator for multiple rows. + * + * @chainable + * @param boolean return an iterator or load a single row + * @return ORM for single rows + * @return ORM_Iterator for multiple rows + */ + protected function load_result($array = false) + { + if ($array === false) { + // Only fetch 1 record + $this->db->limit(1); + } + + if (! isset($this->db_applied['select'])) { + // Select all columns by default + $this->db->select($this->table_name . '.*'); + } + + if (! empty($this->load_with)) { + foreach ($this->load_with as $alias => $object) { + // Join each object into the results + if (is_string($alias)) { + // Use alias + $this->with($alias); + } else { + // Use object + $this->with($object); + } + } + } + + if (! isset($this->db_applied['orderby']) and ! empty($this->sorting)) { + $sorting = array(); + foreach ($this->sorting as $column => $direction) { + if (strpos($column, '.') === false) { + // Keeps sorting working properly when using JOINs on + // tables with columns of the same name + $column = $this->table_name . '.' . $column; + } + + $sorting[$column] = $direction; + } + + // Apply the user-defined sorting + $this->db->orderby($sorting); + } + + // Load the result + $result = $this->db->get($this->table_name); + + if ($array === true) { + // Return an iterated result + return new ORM_Iterator($this, $result); + } + + if ($result->count() === 1) { + // Load object values + $this->load_values($result->result(false)->current()); + } else { + // Clear the object, nothing was found + $this->clear(); + } + + return $this; + } + + /** + * Return an array of all the primary keys of the related table. + * + * @param string table name + * @param object ORM model to find relations of + * @return array + */ + protected function load_relations($table, ORM $model) + { + // Save the current query chain (otherwise the next call will clash) + $this->db->push(); + + $query = $this->db + ->select($model->foreign_key(null) . ' AS id') + ->from($table) + ->where($this->foreign_key(null, $table), $this->object[$this->primary_key]) + ->get() + ->result(true); + + $this->db->pop(); + + $relations = array(); + foreach ($query as $row) { + $relations[] = $row->id; + } + + return $relations; + } + + /** + * Returns whether or not primary key is empty + * + * @return bool + */ + protected function empty_primary_key() + { + return (empty($this->object[$this->primary_key]) and $this->object[$this->primary_key] !== '0'); + } +} +// End ORM diff --git a/lib/kohana/system/libraries/ORM_Iterator.php b/lib/kohana/system/libraries/ORM_Iterator.php index 41aa806..d09d662 100644 --- a/lib/kohana/system/libraries/ORM_Iterator.php +++ b/lib/kohana/system/libraries/ORM_Iterator.php @@ -1,4 +1,11 @@ -class_name = get_class($model); + $this->primary_key = $model->primary_key; + $this->primary_val = $model->primary_val; - public function __construct(ORM $model, Database_Result $result) - { - // Class attributes - $this->class_name = get_class($model); - $this->primary_key = $model->primary_key; - $this->primary_val = $model->primary_val; + // Database result + $this->result = $result->result(true); + } - // Database result - $this->result = $result->result(TRUE); - } + /** + * Returns an array of the results as ORM objects. + * + * @return array + */ + public function as_array() + { + $array = array(); - /** - * Returns an array of the results as ORM objects. - * - * @return array - */ - public function as_array() - { - $array = array(); + if ($results = $this->result->result_array()) { + // Import class name + $class = $this->class_name; - if ($results = $this->result->result_array()) - { - // Import class name - $class = $this->class_name; + foreach ($results as $obj) { + $array[] = new $class($obj); + } + } - foreach ($results as $obj) - { - $array[] = new $class($obj); - } - } + return $array; + } - return $array; - } + /** + * Return an array of all of the primary keys for this object. + * + * @return array + */ + public function primary_key_array() + { + $ids = array(); + foreach ($this->result as $row) { + $ids[] = $row->{$this->primary_key}; + } + return $ids; + } - /** - * Return an array of all of the primary keys for this object. - * - * @return array - */ - public function primary_key_array() - { - $ids = array(); - foreach ($this->result as $row) - { - $ids[] = $row->{$this->primary_key}; - } - return $ids; - } + /** + * Create a key/value array from the results. + * + * @param string key column + * @param string value column + * @return array + */ + public function select_list($key = null, $val = null) + { + if ($key === null) { + // Use the default key + $key = $this->primary_key; + } - /** - * Create a key/value array from the results. - * - * @param string key column - * @param string value column - * @return array - */ - public function select_list($key = NULL, $val = NULL) - { - if ($key === NULL) - { - // Use the default key - $key = $this->primary_key; - } + if ($val === null) { + // Use the default value + $val = $this->primary_val; + } - if ($val === NULL) - { - // Use the default value - $val = $this->primary_val; - } + $array = array(); + foreach ($this->result->result_array() as $row) { + $array[$row->$key] = $row->$val; + } + return $array; + } - $array = array(); - foreach ($this->result->result_array() as $row) - { - $array[$row->$key] = $row->$val; - } - return $array; - } + /** + * Return a range of offsets. + * + * @param integer start + * @param integer end + * @return array + */ + public function range($start, $end) + { + // Array of objects + $array = array(); - /** - * Return a range of offsets. - * - * @param integer start - * @param integer end - * @return array - */ - public function range($start, $end) - { - // Array of objects - $array = array(); + if ($this->result->offsetExists($start)) { + // Import the class name + $class = $this->class_name; - if ($this->result->offsetExists($start)) - { - // Import the class name - $class = $this->class_name; + // Set the end offset + $end = $this->result->offsetExists($end) ? $end : $this->count(); - // Set the end offset - $end = $this->result->offsetExists($end) ? $end : $this->count(); + for ($i = $start; $i < $end; $i++) { + // Insert each object in the range + $array[] = new $class($this->result->offsetGet($i)); + } + } - for ($i = $start; $i < $end; $i++) - { - // Insert each object in the range - $array[] = new $class($this->result->offsetGet($i)); - } - } + return $array; + } - return $array; - } + /** + * Countable: count + */ + public function count() + { + return $this->result->count(); + } - /** - * Countable: count - */ - public function count() - { - return $this->result->count(); - } + /** + * Iterator: current + */ + public function current() + { + if ($row = $this->result->current()) { + // Import class name + $class = $this->class_name; - /** - * Iterator: current - */ - public function current() - { - if ($row = $this->result->current()) - { - // Import class name - $class = $this->class_name; + $row = new $class($row); + } - $row = new $class($row); - } + return $row; + } - return $row; - } + /** + * Iterator: key + */ + public function key() + { + return $this->result->key(); + } - /** - * Iterator: key - */ - public function key() - { - return $this->result->key(); - } + /** + * Iterator: next + */ + public function next() + { + return $this->result->next(); + } - /** - * Iterator: next - */ - public function next() - { - return $this->result->next(); - } + /** + * Iterator: rewind + */ + public function rewind() + { + $this->result->rewind(); + } - /** - * Iterator: rewind - */ - public function rewind() - { - $this->result->rewind(); - } + /** + * Iterator: valid + */ + public function valid() + { + return $this->result->valid(); + } - /** - * Iterator: valid - */ - public function valid() - { - return $this->result->valid(); - } + /** + * ArrayAccess: offsetExists + */ + public function offsetExists($offset) + { + return $this->result->offsetExists($offset); + } - /** - * ArrayAccess: offsetExists - */ - public function offsetExists($offset) - { - return $this->result->offsetExists($offset); - } + /** + * ArrayAccess: offsetGet + */ + public function offsetGet($offset) + { + if ($this->result->offsetExists($offset)) { + // Import class name + $class = $this->class_name; - /** - * ArrayAccess: offsetGet - */ - public function offsetGet($offset) - { - if ($this->result->offsetExists($offset)) - { - // Import class name - $class = $this->class_name; + return new $class($this->result->offsetGet($offset)); + } + } - return new $class($this->result->offsetGet($offset)); - } - } + /** + * ArrayAccess: offsetSet + * + * @throws Kohana_Database_Exception + */ + public function offsetSet($offset, $value) + { + throw new Kohana_Database_Exception('database.result_read_only'); + } - /** - * ArrayAccess: offsetSet - * - * @throws Kohana_Database_Exception - */ - public function offsetSet($offset, $value) - { - throw new Kohana_Database_Exception('database.result_read_only'); - } - - /** - * ArrayAccess: offsetUnset - * - * @throws Kohana_Database_Exception - */ - public function offsetUnset($offset) - { - throw new Kohana_Database_Exception('database.result_read_only'); - } - -} // End ORM Iterator \ No newline at end of file + /** + * ArrayAccess: offsetUnset + * + * @throws Kohana_Database_Exception + */ + public function offsetUnset($offset) + { + throw new Kohana_Database_Exception('database.result_read_only'); + } +} +// End ORM Iterator diff --git a/lib/kohana/system/libraries/ORM_Tree.php b/lib/kohana/system/libraries/ORM_Tree.php index cdb09fd..aa47ff6 100644 --- a/lib/kohana/system/libraries/ORM_Tree.php +++ b/lib/kohana/system/libraries/ORM_Tree.php @@ -1,4 +1,12 @@ -related[$column])) { + // Load child model + $model = ORM::factory(inflector::singular($this->ORM_Tree_children)); - /** - * Overload ORM::__get to support "parent" and "children" properties. - * - * @param string column name - * @return mixed - */ - public function __get($column) - { - if ($column === 'parent') - { - if (empty($this->related[$column])) - { - // Load child model - $model = ORM::factory(inflector::singular($this->ORM_Tree_children)); + if (array_key_exists($this->ORM_Tree_parent_key, $this->object)) { + // Find children of this parent + $model->where($model->primary_key, $this->object[$this->ORM_Tree_parent_key])->find(); + } - if (array_key_exists($this->ORM_Tree_parent_key, $this->object)) - { - // Find children of this parent - $model->where($model->primary_key, $this->object[$this->ORM_Tree_parent_key])->find(); - } + $this->related[$column] = $model; + } - $this->related[$column] = $model; - } + return $this->related[$column]; + } elseif ($column === 'children') { + if (empty($this->related[$column])) { + $model = ORM::factory(inflector::singular($this->ORM_Tree_children)); - return $this->related[$column]; - } - elseif ($column === 'children') - { - if (empty($this->related[$column])) - { - $model = ORM::factory(inflector::singular($this->ORM_Tree_children)); + if ($this->ORM_Tree_children === $this->table_name) { + // Load children within this table + $this->related[$column] = $model + ->where($this->ORM_Tree_parent_key, $this->object[$this->primary_key]) + ->find_all(); + } else { + // Find first selection of children + $this->related[$column] = $model + ->where($this->foreign_key(), $this->object[$this->primary_key]) + ->where($this->ORM_Tree_parent_key, null) + ->find_all(); + } + } - if ($this->ORM_Tree_children === $this->table_name) - { - // Load children within this table - $this->related[$column] = $model - ->where($this->ORM_Tree_parent_key, $this->object[$this->primary_key]) - ->find_all(); - } - else - { - // Find first selection of children - $this->related[$column] = $model - ->where($this->foreign_key(), $this->object[$this->primary_key]) - ->where($this->ORM_Tree_parent_key, NULL) - ->find_all(); - } - } + return $this->related[$column]; + } - return $this->related[$column]; - } - - return parent::__get($column); - } - -} // End ORM Tree \ No newline at end of file + return parent::__get($column); + } +} +// End ORM Tree diff --git a/lib/kohana/system/libraries/ORM_Versioned.php b/lib/kohana/system/libraries/ORM_Versioned.php index 7c3ee5d..85eeb99 100644 --- a/lib/kohana/system/libraries/ORM_Versioned.php +++ b/lib/kohana/system/libraries/ORM_Versioned.php @@ -1,4 +1,8 @@ last_version = 1 + ($this->last_version === null ? $this->object['version'] : $this->last_version); + $this->__set('version', $this->last_version); - /** - * Overload ORM::save() to support versioned data - * - * @chainable - * @return ORM - */ - public function save() - { - $this->last_version = 1 + ($this->last_version === NULL ? $this->object['version'] : $this->last_version); - $this->__set('version', $this->last_version); + parent::save(); - parent::save(); + if ($this->saved) { + $data = array(); + foreach ($this->object as $key => $value) { + if ($key === 'id') { + continue; + } - if ($this->saved) - { - $data = array(); - foreach ($this->object as $key => $value) - { - if ($key === 'id') - continue; + $data[$key] = $value; + } + $data[$this->foreign_key()] = $this->id; - $data[$key] = $value; - } - $data[$this->foreign_key()] = $this->id; + $this->db->insert($this->table_name . '_versions', $data); + } - $this->db->insert($this->table_name.'_versions', $data); - } + return $this; + } - return $this; - } + /** + * Loads previous version from current object + * + * @chainable + * @return ORM + */ + public function previous() + { + if (! $this->loaded) { + return $this; + } - /** - * Loads previous version from current object - * - * @chainable - * @return ORM - */ - public function previous() - { - if ( ! $this->loaded) - return $this; + $this->last_version = ($this->last_version === null) ? $this->object['version'] : $this->last_version; + $version = $this->last_version - 1; - $this->last_version = ($this->last_version === NULL) ? $this->object['version'] : $this->last_version; - $version = $this->last_version - 1; + $query = $this->db + ->where($this->foreign_key(), $this->object[$this->primary_key]) + ->where('version', $version) + ->limit(1) + ->get($this->table_name . '_versions'); - $query = $this->db - ->where($this->foreign_key(), $this->object[$this->primary_key]) - ->where('version', $version) - ->limit(1) - ->get($this->table_name.'_versions'); + if ($query->count()) { + $this->load_values($query->result(false)->current()); + } - if ($query->count()) - { - $this->load_values($query->result(FALSE)->current()); - } + return $this; + } - return $this; - } + /** + * Restores the object with data from stored version + * + * @param integer version number you want to restore + * @return ORM + */ + public function restore($version) + { + if (! $this->loaded) { + return $this; + } - /** - * Restores the object with data from stored version - * - * @param integer version number you want to restore - * @return ORM - */ - public function restore($version) - { - if ( ! $this->loaded) - return $this; + $query = $this->db + ->where($this->foreign_key(), $this->object[$this->primary_key]) + ->where('version', $version) + ->limit(1) + ->get($this->table_name . '_versions'); - $query = $this->db - ->where($this->foreign_key(), $this->object[$this->primary_key]) - ->where('version', $version) - ->limit(1) - ->get($this->table_name.'_versions'); + if ($query->count()) { + $row = $query->result(false)->current(); - if ($query->count()) - { - $row = $query->result(FALSE)->current(); + foreach ($row as $key => $value) { + if ($key === $this->primary_key or $key === $this->foreign_key()) { + // Do not overwrite the primary key + continue; + } - foreach ($row as $key => $value) - { - if ($key === $this->primary_key OR $key === $this->foreign_key()) - { - // Do not overwrite the primary key - continue; - } + if ($key === 'version') { + // Always use the current version + $value = $this->version; + } - if ($key === 'version') - { - // Always use the current version - $value = $this->version; - } + $this->__set($key, $value); + } - $this->__set($key, $value); - } + $this->save(); + } - $this->save(); - } + return $this; + } - return $this; - } + /** + * Overloads ORM::delete() to delete all versioned entries of current object + * and the object itself + * + * @param integer id of the object you want to delete + * @return ORM + */ + public function delete($id = null) + { + if ($id === null) { + // Use the current object id + $id = $this->object[$this->primary_key]; + } - /** - * Overloads ORM::delete() to delete all versioned entries of current object - * and the object itself - * - * @param integer id of the object you want to delete - * @return ORM - */ - public function delete($id = NULL) - { - if ($id === NULL) - { - // Use the current object id - $id = $this->object[$this->primary_key]; - } + if ($status = parent::delete($id)) { + $this->db->where($this->foreign_key(), $id)->delete($this->table_name . '_versions'); + } - if ($status = parent::delete($id)) - { - $this->db->where($this->foreign_key(), $id)->delete($this->table_name.'_versions'); - } - - return $status; - } - -} \ No newline at end of file + return $status; + } +} diff --git a/lib/kohana/system/libraries/Pagination.php b/lib/kohana/system/libraries/Pagination.php index a8f7bb1..2f95d3b 100644 --- a/lib/kohana/system/libraries/Pagination.php +++ b/lib/kohana/system/libraries/Pagination.php @@ -1,4 +1,12 @@ -initialize($config); - // Pagination setup - $this->initialize($config); + Kohana::log('debug', 'Pagination Library initialized'); + } - Kohana::log('debug', 'Pagination Library initialized'); - } + /** + * Sets config values. + * + * @throws Kohana_Exception + * @param array configuration settings + * @return void + */ + public function initialize($config = array()) + { + // Load config group + if (isset($config['group'])) { + // Load and validate config group + if (! is_array($group_config = Kohana::config('pagination.' . $config['group']))) { + throw new Kohana_Exception('pagination.undefined_group', $config['group']); + } - /** - * Sets config values. - * - * @throws Kohana_Exception - * @param array configuration settings - * @return void - */ - public function initialize($config = array()) - { - // Load config group - if (isset($config['group'])) - { - // Load and validate config group - if ( ! is_array($group_config = Kohana::config('pagination.'.$config['group']))) - throw new Kohana_Exception('pagination.undefined_group', $config['group']); + // All pagination config groups inherit default config group + if ($config['group'] !== 'default') { + // Load and validate default config group + if (! is_array($default_config = Kohana::config('pagination.default'))) { + throw new Kohana_Exception('pagination.undefined_group', 'default'); + } - // All pagination config groups inherit default config group - if ($config['group'] !== 'default') - { - // Load and validate default config group - if ( ! is_array($default_config = Kohana::config('pagination.default'))) - throw new Kohana_Exception('pagination.undefined_group', 'default'); + // Merge config group with default config group + $group_config += $default_config; + } - // Merge config group with default config group - $group_config += $default_config; - } + // Merge custom config items with config group + $config += $group_config; + } - // Merge custom config items with config group - $config += $group_config; - } + // Assign config values to the object + foreach ($config as $key => $value) { + if (property_exists($this, $key)) { + $this->$key = $value; + } + } - // Assign config values to the object - foreach ($config as $key => $value) - { - if (property_exists($this, $key)) - { - $this->$key = $value; - } - } + // Clean view directory + $this->directory = trim($this->directory, '/') . '/'; - // Clean view directory - $this->directory = trim($this->directory, '/').'/'; + // Build generic URL with page in query string + if ($this->query_string !== '') { + // Extract current page + $this->current_page = isset($_GET[$this->query_string]) ? (int) $_GET[$this->query_string] : 1; - // Build generic URL with page in query string - if ($this->query_string !== '') - { - // Extract current page - $this->current_page = isset($_GET[$this->query_string]) ? (int) $_GET[$this->query_string] : 1; + // Insert {page} placeholder + $_GET[$this->query_string] = '{page}'; - // Insert {page} placeholder - $_GET[$this->query_string] = '{page}'; + // Create full URL + $base_url = ($this->base_url === '') ? Router::$current_uri : $this->base_url; + $this->url = url::site($base_url) . '?' . str_replace('%7Bpage%7D', '{page}', http_build_query($_GET)); - // Create full URL - $base_url = ($this->base_url === '') ? Router::$current_uri : $this->base_url; - $this->url = url::site($base_url).'?'.str_replace('%7Bpage%7D', '{page}', http_build_query($_GET)); + // Reset page number + $_GET[$this->query_string] = $this->current_page; + } else { + // Build generic URL with page as URI segment + // Use current URI if no base_url set + $this->url = ($this->base_url === '') ? Router::$segments : explode('/', trim($this->base_url, '/')); - // Reset page number - $_GET[$this->query_string] = $this->current_page; - } + // Convert uri 'label' to corresponding integer if needed + if (is_string($this->uri_segment)) { + if (($key = array_search($this->uri_segment, $this->url)) === false) { + // If uri 'label' is not found, auto add it to base_url + $this->url[] = $this->uri_segment; + $this->uri_segment = count($this->url) + 1; + } else { + $this->uri_segment = $key + 2; + } + } - // Build generic URL with page as URI segment - else - { - // Use current URI if no base_url set - $this->url = ($this->base_url === '') ? Router::$segments : explode('/', trim($this->base_url, '/')); + // Insert {page} placeholder + $this->url[$this->uri_segment - 1] = '{page}'; - // Convert uri 'label' to corresponding integer if needed - if (is_string($this->uri_segment)) - { - if (($key = array_search($this->uri_segment, $this->url)) === FALSE) - { - // If uri 'label' is not found, auto add it to base_url - $this->url[] = $this->uri_segment; - $this->uri_segment = count($this->url) + 1; - } - else - { - $this->uri_segment = $key + 2; - } - } + // Create full URL + $this->url = url::site(implode('/', $this->url)) . Router::$query_string; - // Insert {page} placeholder - $this->url[$this->uri_segment - 1] = '{page}'; + // Extract current page + $this->current_page = URI::instance()->segment($this->uri_segment); + } - // Create full URL - $this->url = url::site(implode('/', $this->url)).Router::$query_string; + // Core pagination values + $this->total_items = (int) max(0, $this->total_items); + $this->items_per_page = (int) max(1, $this->items_per_page); + $this->total_pages = (int) ceil($this->total_items / $this->items_per_page); + $this->current_page = (int) min(max(1, $this->current_page), max(1, $this->total_pages)); + $this->current_first_item = (int) min((($this->current_page - 1) * $this->items_per_page) + 1, $this->total_items); + $this->current_last_item = (int) min($this->current_first_item + $this->items_per_page - 1, $this->total_items); - // Extract current page - $this->current_page = URI::instance()->segment($this->uri_segment); - } + // If there is no first/last/previous/next page, relative to the + // current page, value is set to FALSE. Valid page number otherwise. + $this->first_page = ($this->current_page === 1) ? false : 1; + $this->last_page = ($this->current_page >= $this->total_pages) ? false : $this->total_pages; + $this->previous_page = ($this->current_page > 1) ? $this->current_page - 1 : false; + $this->next_page = ($this->current_page < $this->total_pages) ? $this->current_page + 1 : false; - // Core pagination values - $this->total_items = (int) max(0, $this->total_items); - $this->items_per_page = (int) max(1, $this->items_per_page); - $this->total_pages = (int) ceil($this->total_items / $this->items_per_page); - $this->current_page = (int) min(max(1, $this->current_page), max(1, $this->total_pages)); - $this->current_first_item = (int) min((($this->current_page - 1) * $this->items_per_page) + 1, $this->total_items); - $this->current_last_item = (int) min($this->current_first_item + $this->items_per_page - 1, $this->total_items); + // SQL values + $this->sql_offset = (int) ($this->current_page - 1) * $this->items_per_page; + $this->sql_limit = sprintf(' LIMIT %d OFFSET %d ', $this->items_per_page, $this->sql_offset); + } - // If there is no first/last/previous/next page, relative to the - // current page, value is set to FALSE. Valid page number otherwise. - $this->first_page = ($this->current_page === 1) ? FALSE : 1; - $this->last_page = ($this->current_page >= $this->total_pages) ? FALSE : $this->total_pages; - $this->previous_page = ($this->current_page > 1) ? $this->current_page - 1 : FALSE; - $this->next_page = ($this->current_page < $this->total_pages) ? $this->current_page + 1 : FALSE; + /** + * Generates the HTML for the chosen pagination style. + * + * @param string pagination style + * @return string pagination html + */ + public function render($style = null) + { + // Hide single page pagination + if ($this->auto_hide === true and $this->total_pages <= 1) { + return ''; + } - // SQL values - $this->sql_offset = (int) ($this->current_page - 1) * $this->items_per_page; - $this->sql_limit = sprintf(' LIMIT %d OFFSET %d ', $this->items_per_page, $this->sql_offset); - } + if ($style === null) { + // Use default style + $style = $this->style; + } - /** - * Generates the HTML for the chosen pagination style. - * - * @param string pagination style - * @return string pagination html - */ - public function render($style = NULL) - { - // Hide single page pagination - if ($this->auto_hide === TRUE AND $this->total_pages <= 1) - return ''; + // Return rendered pagination view + return View::factory($this->directory . $style, get_object_vars($this))->render(); + } - if ($style === NULL) - { - // Use default style - $style = $this->style; - } + /** + * Magically converts Pagination object to string. + * + * @return string pagination html + */ + public function __toString() + { + return $this->render(); + } - // Return rendered pagination view - return View::factory($this->directory.$style, get_object_vars($this))->render(); - } + /** + * Magically gets a pagination variable. + * + * @param string variable key + * @return mixed variable value if the key is found + * @return void if the key is not found + */ + public function __get($key) + { + if (isset($this->$key)) { + return $this->$key; + } + } - /** - * Magically converts Pagination object to string. - * - * @return string pagination html - */ - public function __toString() - { - return $this->render(); - } - - /** - * Magically gets a pagination variable. - * - * @param string variable key - * @return mixed variable value if the key is found - * @return void if the key is not found - */ - public function __get($key) - { - if (isset($this->$key)) - return $this->$key; - } - - /** - * Adds a secondary interface for accessing properties, e.g. $pagination->total_pages(). - * Note that $pagination->total_pages is the recommended way to access properties. - * - * @param string function name - * @return string - */ - public function __call($func, $args = NULL) - { - return $this->__get($func); - } - -} // End Pagination Class \ No newline at end of file + /** + * Adds a secondary interface for accessing properties, e.g. $pagination->total_pages(). + * Note that $pagination->total_pages is the recommended way to access properties. + * + * @param string function name + * @return string + */ + public function __call($func, $args = null) + { + return $this->__get($func); + } +} +// End Pagination Class diff --git a/lib/kohana/system/libraries/Profiler.php b/lib/kohana/system/libraries/Profiler.php index 9da053f..c351be9 100644 --- a/lib/kohana/system/libraries/Profiler.php +++ b/lib/kohana/system/libraries/Profiler.php @@ -1,4 +1,12 @@ -show or (is_array($this->show) and ! in_array($args[0], $this->show))) { + return false; + } - /** - * Magic __call method. Creates a new profiler section object. - * - * @param string input type - * @param string input name - * @return object - */ - public function __call($method, $args) - { - if ( ! $this->show OR (is_array($this->show) AND ! in_array($args[0], $this->show))) - return FALSE; + // Class name + $class = 'Profiler_' . ucfirst($method); - // Class name - $class = 'Profiler_'.ucfirst($method); + $class = new $class(); - $class = new $class(); + $this->profiles[$args[0]] = $class; - $this->profiles[$args[0]] = $class; + return $class; + } - return $class; - } + /** + * Disables the profiler for this page only. + * Best used when profiler is autoloaded. + * + * @return void + */ + public function disable() + { + // Removes itself from the event queue + Event::clear('system.display', array($this, 'render')); + } - /** - * Disables the profiler for this page only. - * Best used when profiler is autoloaded. - * - * @return void - */ - public function disable() - { - // Removes itself from the event queue - Event::clear('system.display', array($this, 'render')); - } + /** + * Render the profiler. Output is added to the bottom of the page by default. + * + * @param boolean return the output if TRUE + * @return void|string + */ + public function render($return = false) + { + $start = microtime(true); - /** - * Render the profiler. Output is added to the bottom of the page by default. - * - * @param boolean return the output if TRUE - * @return void|string - */ - public function render($return = FALSE) - { - $start = microtime(TRUE); + $get = isset($_GET['profiler']) ? explode(',', $_GET['profiler']) : array(); + $this->show = empty($get) ? Kohana::config('profiler.show') : $get; - $get = isset($_GET['profiler']) ? explode(',', $_GET['profiler']) : array(); - $this->show = empty($get) ? Kohana::config('profiler.show') : $get; + Event::run('profiler.run', $this); - Event::run('profiler.run', $this); + $styles = ''; + foreach ($this->profiles as $profile) { + $styles .= $profile->styles(); + } - $styles = ''; - foreach ($this->profiles as $profile) - { - $styles .= $profile->styles(); - } + // Don't display if there's no profiles + if (empty($this->profiles)) { + return; + } - // Don't display if there's no profiles - if (empty($this->profiles)) - return; + // Load the profiler view + $data = array + ( + 'profiles' => $this->profiles, + 'styles' => $styles, + 'execution_time' => microtime(true) - $start + ); + $view = new View('kohana_profiler', $data); - // Load the profiler view - $data = array - ( - 'profiles' => $this->profiles, - 'styles' => $styles, - 'execution_time' => microtime(TRUE) - $start - ); - $view = new View('kohana_profiler', $data); + // Return rendered view if $return is TRUE + if ($return === true) { + return $view->render(); + } - // Return rendered view if $return is TRUE - if ($return === TRUE) - return $view->render(); + // Add profiler data to the output + if (stripos(Kohana::$output, '') !== false) { + // Closing body tag was found, insert the profiler data before it + Kohana::$output = str_ireplace('', $view->render() . '', Kohana::$output); + } else { + // Append the profiler data to the output + Kohana::$output .= $view->render(); + } + } - // Add profiler data to the output - if (stripos(Kohana::$output, '') !== FALSE) - { - // Closing body tag was found, insert the profiler data before it - Kohana::$output = str_ireplace('', $view->render().'', Kohana::$output); - } - else - { - // Append the profiler data to the output - Kohana::$output .= $view->render(); - } - } + /** + * Benchmark times and memory usage from the Benchmark library. + * + * @return void + */ + public function benchmarks() + { + if (! $table = $this->table('benchmarks')) { + return; + } - /** - * Benchmark times and memory usage from the Benchmark library. - * - * @return void - */ - public function benchmarks() - { - if ( ! $table = $this->table('benchmarks')) - return; + $table->add_column(); + $table->add_column('kp-column kp-data'); + $table->add_column('kp-column kp-data'); + $table->add_column('kp-column kp-data'); + $table->add_row(array('Benchmarks', 'Time', 'Count', 'Memory'), 'kp-title', 'background-color: #FFE0E0'); - $table->add_column(); - $table->add_column('kp-column kp-data'); - $table->add_column('kp-column kp-data'); - $table->add_column('kp-column kp-data'); - $table->add_row(array('Benchmarks', 'Time', 'Count', 'Memory'), 'kp-title', 'background-color: #FFE0E0'); + $benchmarks = Benchmark::get(true); - $benchmarks = Benchmark::get(TRUE); + // Moves the first benchmark (total execution time) to the end of the array + $benchmarks = array_slice($benchmarks, 1) + array_slice($benchmarks, 0, 1); - // Moves the first benchmark (total execution time) to the end of the array - $benchmarks = array_slice($benchmarks, 1) + array_slice($benchmarks, 0, 1); + text::alternate(); + foreach ($benchmarks as $name => $benchmark) { + // Clean unique id from system benchmark names + $name = ucwords(str_replace(array('_', '-'), ' ', str_replace(SYSTEM_BENCHMARK . '_', '', $name))); - text::alternate(); - foreach ($benchmarks as $name => $benchmark) - { - // Clean unique id from system benchmark names - $name = ucwords(str_replace(array('_', '-'), ' ', str_replace(SYSTEM_BENCHMARK.'_', '', $name))); + $data = array($name, number_format($benchmark['time'], 3), $benchmark['count'], number_format($benchmark['memory'] / 1024 / 1024, 2) . 'MB'); + $class = text::alternate('', 'kp-altrow'); - $data = array($name, number_format($benchmark['time'], 3), $benchmark['count'], number_format($benchmark['memory'] / 1024 / 1024, 2).'MB'); - $class = text::alternate('', 'kp-altrow'); + if ($name == 'Total Execution') { + $class = 'kp-totalrow'; + } - if ($name == 'Total Execution') - $class = 'kp-totalrow'; + $table->add_row($data, $class); + } + } - $table->add_row($data, $class); - } - } + /** + * Database query benchmarks. + * + * @return void + */ + public function database() + { + if (! $table = $this->table('database')) { + return; + } - /** - * Database query benchmarks. - * - * @return void - */ - public function database() - { - if ( ! $table = $this->table('database')) - return; + $table->add_column(); + $table->add_column('kp-column kp-data'); + $table->add_column('kp-column kp-data'); + $table->add_row(array('Queries', 'Time', 'Rows'), 'kp-title', 'background-color: #E0FFE0'); - $table->add_column(); - $table->add_column('kp-column kp-data'); - $table->add_column('kp-column kp-data'); - $table->add_row(array('Queries', 'Time', 'Rows'), 'kp-title', 'background-color: #E0FFE0'); + $queries = Database::$benchmarks; - $queries = Database::$benchmarks; + text::alternate(); + $total_time = $total_rows = 0; + foreach ($queries as $query) { + $data = array($query['query'], number_format($query['time'], 3), $query['rows']); + $class = text::alternate('', 'kp-altrow'); + $table->add_row($data, $class); + $total_time += $query['time']; + $total_rows += $query['rows']; + } - text::alternate(); - $total_time = $total_rows = 0; - foreach ($queries as $query) - { - $data = array($query['query'], number_format($query['time'], 3), $query['rows']); - $class = text::alternate('', 'kp-altrow'); - $table->add_row($data, $class); - $total_time += $query['time']; - $total_rows += $query['rows']; - } + $data = array('Total: ' . count($queries), number_format($total_time, 3), $total_rows); + $table->add_row($data, 'kp-totalrow'); + } - $data = array('Total: ' . count($queries), number_format($total_time, 3), $total_rows); - $table->add_row($data, 'kp-totalrow'); - } + /** + * Session data. + * + * @return void + */ + public function session() + { + if (empty($_SESSION)) { + return; + } - /** - * Session data. - * - * @return void - */ - public function session() - { - if (empty($_SESSION)) return; + if (! $table = $this->table('session')) { + return; + } - if ( ! $table = $this->table('session')) - return; + $table->add_column('kp-name'); + $table->add_column(); + $table->add_row(array('Session', 'Value'), 'kp-title', 'background-color: #CCE8FB'); - $table->add_column('kp-name'); - $table->add_column(); - $table->add_row(array('Session', 'Value'), 'kp-title', 'background-color: #CCE8FB'); + text::alternate(); + foreach ($_SESSION as $name => $value) { + if (is_object($value)) { + $value = get_class($value) . ' [object]'; + } - text::alternate(); - foreach($_SESSION as $name => $value) - { - if (is_object($value)) - { - $value = get_class($value).' [object]'; - } + $data = array($name, $value); + $class = text::alternate('', 'kp-altrow'); + $table->add_row($data, $class); + } + } - $data = array($name, $value); - $class = text::alternate('', 'kp-altrow'); - $table->add_row($data, $class); - } - } + /** + * POST data. + * + * @return void + */ + public function post() + { + if (empty($_POST)) { + return; + } - /** - * POST data. - * - * @return void - */ - public function post() - { - if (empty($_POST)) return; + if (! $table = $this->table('post')) { + return; + } - if ( ! $table = $this->table('post')) - return; + $table->add_column('kp-name'); + $table->add_column(); + $table->add_row(array('POST', 'Value'), 'kp-title', 'background-color: #E0E0FF'); - $table->add_column('kp-name'); - $table->add_column(); - $table->add_row(array('POST', 'Value'), 'kp-title', 'background-color: #E0E0FF'); + text::alternate(); + foreach ($_POST as $name => $value) { + $data = array($name, $value); + $class = text::alternate('', 'kp-altrow'); + $table->add_row($data, $class); + } + } - text::alternate(); - foreach($_POST as $name => $value) - { - $data = array($name, $value); - $class = text::alternate('', 'kp-altrow'); - $table->add_row($data, $class); - } - } + /** + * Cookie data. + * + * @return void + */ + public function cookies() + { + if (empty($_COOKIE)) { + return; + } - /** - * Cookie data. - * - * @return void - */ - public function cookies() - { - if (empty($_COOKIE)) return; + if (! $table = $this->table('cookies')) { + return; + } - if ( ! $table = $this->table('cookies')) - return; + $table->add_column('kp-name'); + $table->add_column(); + $table->add_row(array('Cookies', 'Value'), 'kp-title', 'background-color: #FFF4D7'); - $table->add_column('kp-name'); - $table->add_column(); - $table->add_row(array('Cookies', 'Value'), 'kp-title', 'background-color: #FFF4D7'); - - text::alternate(); - foreach($_COOKIE as $name => $value) - { - $data = array($name, $value); - $class = text::alternate('', 'kp-altrow'); - $table->add_row($data, $class); - } - } -} \ No newline at end of file + text::alternate(); + foreach ($_COOKIE as $name => $value) { + $data = array($name, $value); + $class = text::alternate('', 'kp-altrow'); + $table->add_row($data, $class); + } + } +} diff --git a/lib/kohana/system/libraries/Profiler_Table.php b/lib/kohana/system/libraries/Profiler_Table.php index a0058a5..30075db 100644 --- a/lib/kohana/system/libraries/Profiler_Table.php +++ b/lib/kohana/system/libraries/Profiler_Table.php @@ -1,4 +1,12 @@ -columns[] = array('class' => $class, 'style' => $style); + } - /** - * Add column to table. - * - * @param string CSS class - * @param string CSS style - */ - public function add_column($class = '', $style = '') - { - $this->columns[] = array('class' => $class, 'style' => $style); - } + /** + * Add row to table. + * + * @param array data to go in table cells + * @param string CSS class + * @param string CSS style + */ + public function add_row($data, $class = '', $style = '') + { + $this->rows[] = array('data' => $data, 'class' => $class, 'style' => $style); + } - /** - * Add row to table. - * - * @param array data to go in table cells - * @param string CSS class - * @param string CSS style - */ - public function add_row($data, $class = '', $style = '') - { - $this->rows[] = array('data' => $data, 'class' => $class, 'style' => $style); - } - - /** - * Render table. - * - * @return string - */ - public function render() - { - $data['rows'] = $this->rows; - $data['columns'] = $this->columns; - return View::factory('kohana_profiler_table', $data)->render(); - } -} \ No newline at end of file + /** + * Render table. + * + * @return string + */ + public function render() + { + $data['rows'] = $this->rows; + $data['columns'] = $this->columns; + return View::factory('kohana_profiler_table', $data)->render(); + } +} diff --git a/lib/kohana/system/libraries/Router.php b/lib/kohana/system/libraries/Router.php index ef0e1e4..917bad0 100644 --- a/lib/kohana/system/libraries/Router.php +++ b/lib/kohana/system/libraries/Router.php @@ -1,4 +1,12 @@ - 1) { + // Custom routing + Router::$rsegments = Router::routed_uri(Router::$current_uri); + } - if ($default_route === FALSE AND count(Router::$routes) > 1) - { - // Custom routing - Router::$rsegments = Router::routed_uri(Router::$current_uri); - } + // The routed URI is now complete + Router::$routed_uri = Router::$rsegments; - // The routed URI is now complete - Router::$routed_uri = Router::$rsegments; + // Routed segments will never be empty + Router::$rsegments = explode('/', Router::$rsegments); - // Routed segments will never be empty - Router::$rsegments = explode('/', Router::$rsegments); + // Prepare to find the controller + $controller_path = ''; + $method_segment = null; - // Prepare to find the controller - $controller_path = ''; - $method_segment = NULL; + // Paths to search + $paths = Kohana::include_paths(); - // Paths to search - $paths = Kohana::include_paths(); + foreach (Router::$rsegments as $key => $segment) { + // Add the segment to the search path + $controller_path .= $segment; - foreach (Router::$rsegments as $key => $segment) - { - // Add the segment to the search path - $controller_path .= $segment; + $found = false; + foreach ($paths as $dir) { + // Search within controllers only + $dir .= 'controllers/'; - $found = FALSE; - foreach ($paths as $dir) - { - // Search within controllers only - $dir .= 'controllers/'; + if (is_dir($dir . $controller_path) or is_file($dir . $controller_path . EXT)) { + // Valid path + $found = true; - if (is_dir($dir.$controller_path) OR is_file($dir.$controller_path.EXT)) - { - // Valid path - $found = TRUE; + // The controller must be a file that exists with the search path + if ( + $c = str_replace('\\', '/', realpath($dir . $controller_path . EXT)) + and is_file($c) and strpos($c, $dir) === 0 + ) { + // Set controller name + Router::$controller = $segment; - // The controller must be a file that exists with the search path - if ($c = str_replace('\\', '/', realpath($dir.$controller_path.EXT)) - AND is_file($c) AND strpos($c, $dir) === 0) - { - // Set controller name - Router::$controller = $segment; + // Change controller path + Router::$controller_path = $c; - // Change controller path - Router::$controller_path = $c; + // Set the method segment + $method_segment = $key + 1; - // Set the method segment - $method_segment = $key + 1; + // Stop searching + break; + } + } + } - // Stop searching - break; - } - } - } + if ($found === false) { + // Maximum depth has been reached, stop searching + break; + } - if ($found === FALSE) - { - // Maximum depth has been reached, stop searching - break; - } + // Add another slash + $controller_path .= '/'; + } - // Add another slash - $controller_path .= '/'; - } + if ($method_segment !== null and isset(Router::$rsegments[$method_segment])) { + // Set method + Router::$method = Router::$rsegments[$method_segment]; - if ($method_segment !== NULL AND isset(Router::$rsegments[$method_segment])) - { - // Set method - Router::$method = Router::$rsegments[$method_segment]; + if (isset(Router::$rsegments[$method_segment + 1])) { + // Set arguments + Router::$arguments = array_slice(Router::$rsegments, $method_segment + 1); + } + } - if (isset(Router::$rsegments[$method_segment + 1])) - { - // Set arguments - Router::$arguments = array_slice(Router::$rsegments, $method_segment + 1); - } - } + // Last chance to set routing before a 404 is triggered + Event::run('system.post_routing'); - // Last chance to set routing before a 404 is triggered - Event::run('system.post_routing'); + if (Router::$controller === null) { + // No controller was found, so no page can be rendered + Event::run('system.404'); + } + } - if (Router::$controller === NULL) - { - // No controller was found, so no page can be rendered - Event::run('system.404'); - } - } + /** + * Attempts to determine the current URI using CLI, GET, PATH_INFO, ORIG_PATH_INFO, or PHP_SELF. + * + * @return void + */ + public static function find_uri() + { + if (PHP_SAPI === 'cli') { + // Command line requires a bit of hacking + if (isset($_SERVER['argv'][1])) { + Router::$current_uri = $_SERVER['argv'][1]; - /** - * Attempts to determine the current URI using CLI, GET, PATH_INFO, ORIG_PATH_INFO, or PHP_SELF. - * - * @return void - */ - public static function find_uri() - { - if (PHP_SAPI === 'cli') - { - // Command line requires a bit of hacking - if (isset($_SERVER['argv'][1])) - { - Router::$current_uri = $_SERVER['argv'][1]; + // Remove GET string from segments + if (($query = strpos(Router::$current_uri, '?')) !== false) { + list (Router::$current_uri, $query) = explode('?', Router::$current_uri, 2); - // Remove GET string from segments - if (($query = strpos(Router::$current_uri, '?')) !== FALSE) - { - list (Router::$current_uri, $query) = explode('?', Router::$current_uri, 2); + // Parse the query string into $_GET + parse_str($query, $_GET); - // Parse the query string into $_GET - parse_str($query, $_GET); + // Convert $_GET to UTF-8 + $_GET = utf8::clean($_GET); + } + } + } elseif (isset($_GET['kohana_uri'])) { + // Use the URI defined in the query string + Router::$current_uri = $_GET['kohana_uri']; - // Convert $_GET to UTF-8 - $_GET = utf8::clean($_GET); - } - } - } - elseif (isset($_GET['kohana_uri'])) - { - // Use the URI defined in the query string - Router::$current_uri = $_GET['kohana_uri']; + // Remove the URI from $_GET + unset($_GET['kohana_uri']); - // Remove the URI from $_GET - unset($_GET['kohana_uri']); + // Remove the URI from $_SERVER['QUERY_STRING'] + $_SERVER['QUERY_STRING'] = preg_replace('~\bkohana_uri\b[^&]*+&?~', '', $_SERVER['QUERY_STRING']); + } elseif (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO']) { + Router::$current_uri = $_SERVER['PATH_INFO']; + } elseif (isset($_SERVER['ORIG_PATH_INFO']) and $_SERVER['ORIG_PATH_INFO']) { + Router::$current_uri = $_SERVER['ORIG_PATH_INFO']; + } elseif (isset($_SERVER['PHP_SELF']) and $_SERVER['PHP_SELF']) { + Router::$current_uri = $_SERVER['PHP_SELF']; + } - // Remove the URI from $_SERVER['QUERY_STRING'] - $_SERVER['QUERY_STRING'] = preg_replace('~\bkohana_uri\b[^&]*+&?~', '', $_SERVER['QUERY_STRING']); - } - elseif (isset($_SERVER['PATH_INFO']) AND $_SERVER['PATH_INFO']) - { - Router::$current_uri = $_SERVER['PATH_INFO']; - } - elseif (isset($_SERVER['ORIG_PATH_INFO']) AND $_SERVER['ORIG_PATH_INFO']) - { - Router::$current_uri = $_SERVER['ORIG_PATH_INFO']; - } - elseif (isset($_SERVER['PHP_SELF']) AND $_SERVER['PHP_SELF']) - { - Router::$current_uri = $_SERVER['PHP_SELF']; - } - - if (($strpos_fc = strpos(Router::$current_uri, KOHANA)) !== FALSE) - { - // Remove the front controller from the current uri - Router::$current_uri = (string) substr(Router::$current_uri, $strpos_fc + strlen(KOHANA)); - } - - // Remove slashes from the start and end of the URI - Router::$current_uri = trim(Router::$current_uri, '/'); - - if (Router::$current_uri !== '') - { - if ($suffix = Kohana::config('core.url_suffix') AND strpos(Router::$current_uri, $suffix) !== FALSE) - { - // Remove the URL suffix - Router::$current_uri = preg_replace('#'.preg_quote($suffix).'$#u', '', Router::$current_uri); + if (($strpos_fc = strpos(Router::$current_uri, KOHANA)) !== false) { + // Remove the front controller from the current uri + Router::$current_uri = (string) substr(Router::$current_uri, $strpos_fc + strlen(KOHANA)); + } - // Set the URL suffix - Router::$url_suffix = $suffix; - } + // Remove slashes from the start and end of the URI + Router::$current_uri = trim(Router::$current_uri, '/'); - // Reduce multiple slashes into single slashes - Router::$current_uri = preg_replace('#//+#', '/', Router::$current_uri); - } - } + if (Router::$current_uri !== '') { + if ($suffix = Kohana::config('core.url_suffix') and strpos(Router::$current_uri, $suffix) !== false) { + // Remove the URL suffix + Router::$current_uri = preg_replace('#' . preg_quote($suffix) . '$#u', '', Router::$current_uri); - /** - * Generates routed URI from given URI. - * - * @param string URI to convert - * @return string Routed uri - */ - public static function routed_uri($uri) - { - if (Router::$routes === NULL) - { - // Load routes - Router::$routes = Kohana::config('routes'); - } + // Set the URL suffix + Router::$url_suffix = $suffix; + } - // Prepare variables - $routed_uri = $uri = trim($uri, '/'); + // Reduce multiple slashes into single slashes + Router::$current_uri = preg_replace('#//+#', '/', Router::$current_uri); + } + } - if (isset(Router::$routes[$uri])) - { - // Literal match, no need for regex - $routed_uri = Router::$routes[$uri]; - } - else - { - // Loop through the routes and see if anything matches - foreach (Router::$routes as $key => $val) - { - if ($key === '_default') continue; + /** + * Generates routed URI from given URI. + * + * @param string URI to convert + * @return string Routed uri + */ + public static function routed_uri($uri) + { + if (Router::$routes === null) { + // Load routes + Router::$routes = Kohana::config('routes'); + } - // Trim slashes - $key = trim($key, '/'); - $val = trim($val, '/'); + // Prepare variables + $routed_uri = $uri = trim($uri, '/'); - if (preg_match('#^'.$key.'$#u', $uri)) - { - if (strpos($val, '$') !== FALSE) - { - // Use regex routing - $routed_uri = preg_replace('#^'.$key.'$#u', $val, $uri); - } - else - { - // Standard routing - $routed_uri = $val; - } + if (isset(Router::$routes[$uri])) { + // Literal match, no need for regex + $routed_uri = Router::$routes[$uri]; + } else { + // Loop through the routes and see if anything matches + foreach (Router::$routes as $key => $val) { + if ($key === '_default') { + continue; + } - // A valid route has been found - break; - } - } - } + // Trim slashes + $key = trim($key, '/'); + $val = trim($val, '/'); - if (isset(Router::$routes[$routed_uri])) - { - // Check for double routing (without regex) - $routed_uri = Router::$routes[$routed_uri]; - } + if (preg_match('#^' . $key . '$#u', $uri)) { + if (strpos($val, '$') !== false) { + // Use regex routing + $routed_uri = preg_replace('#^' . $key . '$#u', $val, $uri); + } else { + // Standard routing + $routed_uri = $val; + } - return trim($routed_uri, '/'); - } + // A valid route has been found + break; + } + } + } -} // End Router \ No newline at end of file + if (isset(Router::$routes[$routed_uri])) { + // Check for double routing (without regex) + $routed_uri = Router::$routes[$routed_uri]; + } + + return trim($routed_uri, '/'); + } +} +// End Router diff --git a/lib/kohana/system/libraries/Session.php b/lib/kohana/system/libraries/Session.php index 7ae79cf..56fbe41 100644 --- a/lib/kohana/system/libraries/Session.php +++ b/lib/kohana/system/libraries/Session.php @@ -1,4 +1,12 @@ -input = Input::instance(); - - // This part only needs to be run once - if (Session::$instance === NULL) - { - // Load config - Session::$config = Kohana::config('session'); - - // Makes a mirrored array, eg: foo=foo - Session::$protect = array_combine(Session::$protect, Session::$protect); - - // Configure garbage collection - ini_set('session.gc_probability', (int) Session::$config['gc_probability']); - ini_set('session.gc_divisor', 100); - ini_set('session.gc_maxlifetime', (Session::$config['expiration'] == 0) ? 86400 : Session::$config['expiration']); - - // Create a new session - $this->create(); - - if (Session::$config['regenerate'] > 0 AND ($_SESSION['total_hits'] % Session::$config['regenerate']) === 0) - { - // Regenerate session id and update session cookie - $this->regenerate(); - } - else - { - // Always update session cookie to keep the session alive - cookie::set(Session::$config['name'], $_SESSION['session_id'], Session::$config['expiration']); - } - - // Close the session just before sending the headers, so that - // the session cookie(s) can be written. - Event::add('system.send_headers', array($this, 'write_close')); - - // Make sure that sessions are closed before exiting - register_shutdown_function(array($this, 'write_close')); - - // Singleton instance - Session::$instance = $this; - } - - Kohana::log('debug', 'Session Library initialized'); - } - - /** - * Get the session id. - * - * @return string - */ - public function id() - { - return $_SESSION['session_id']; - } - - /** - * Create a new session. - * - * @param array variables to set after creation - * @return void - */ - public function create($vars = NULL) - { - // Destroy any current sessions - $this->destroy(); - - if (Session::$config['driver'] !== 'native') - { - // Set driver name - $driver = 'Session_'.ucfirst(Session::$config['driver']).'_Driver'; - - // Load the driver - if ( ! Kohana::auto_load($driver)) - throw new Kohana_Exception('core.driver_not_found', Session::$config['driver'], get_class($this)); - - // Initialize the driver - Session::$driver = new $driver(); - - // Validate the driver - if ( ! (Session::$driver instanceof Session_Driver)) - throw new Kohana_Exception('core.driver_implements', Session::$config['driver'], get_class($this), 'Session_Driver'); - - // Register non-native driver as the session handler - session_set_save_handler - ( - array(Session::$driver, 'open'), - array(Session::$driver, 'close'), - array(Session::$driver, 'read'), - array(Session::$driver, 'write'), - array(Session::$driver, 'destroy'), - array(Session::$driver, 'gc') - ); - } - - // Validate the session name - if ( ! preg_match('~^(?=.*[a-z])[a-z0-9_]++$~iD', Session::$config['name'])) - throw new Kohana_Exception('session.invalid_session_name', Session::$config['name']); - - // Name the session, this will also be the name of the cookie - session_name(Session::$config['name']); - - // Set the session cookie parameters - session_set_cookie_params - ( - Session::$config['expiration'], - Kohana::config('cookie.path'), - Kohana::config('cookie.domain'), - Kohana::config('cookie.secure') - ); - - // Start the session! - session_start(); - - // Put session_id in the session variable - $_SESSION['session_id'] = session_id(); - - // Set defaults - if ( ! isset($_SESSION['_kf_flash_'])) - { - $_SESSION['total_hits'] = 0; - $_SESSION['_kf_flash_'] = array(); - - $_SESSION['user_agent'] = Kohana::$user_agent; - $_SESSION['ip_address'] = $this->input->ip_address(); - } - - // Set up flash variables - Session::$flash =& $_SESSION['_kf_flash_']; - - // Increase total hits - $_SESSION['total_hits'] += 1; - - // Validate data only on hits after one - if ($_SESSION['total_hits'] > 1) - { - // Validate the session - foreach (Session::$config['validate'] as $valid) - { - switch ($valid) - { - // Check user agent for consistency - case 'user_agent': - if ($_SESSION[$valid] !== Kohana::$user_agent) - return $this->create(); - break; - - // Check ip address for consistency - case 'ip_address': - if ($_SESSION[$valid] !== $this->input->$valid()) - return $this->create(); - break; - - // Check expiration time to prevent users from manually modifying it - case 'expiration': - if (time() - $_SESSION['last_activity'] > ini_get('session.gc_maxlifetime')) - return $this->create(); - break; - } - } - } - - // Expire flash keys - $this->expire_flash(); - - // Update last activity - $_SESSION['last_activity'] = time(); - - // Set the new data - Session::set($vars); - } - - /** - * Regenerates the global session id. - * - * @return void - */ - public function regenerate() - { - if (Session::$config['driver'] === 'native') - { - // Generate a new session id - // Note: also sets a new session cookie with the updated id - session_regenerate_id(TRUE); - - // Update session with new id - $_SESSION['session_id'] = session_id(); - } - else - { - // Pass the regenerating off to the driver in case it wants to do anything special - $_SESSION['session_id'] = Session::$driver->regenerate(); - } - - // Get the session name - $name = session_name(); - - if (isset($_COOKIE[$name])) - { - // Change the cookie value to match the new session id to prevent "lag" - $_COOKIE[$name] = $_SESSION['session_id']; - } - } - - /** - * Destroys the current session. - * - * @return void - */ - public function destroy() - { - if (session_id() !== '') - { - // Get the session name - $name = session_name(); - - // Destroy the session - session_destroy(); - - // Re-initialize the array - $_SESSION = array(); - - // Delete the session cookie - cookie::delete($name); - } - } - - /** - * Runs the system.session_write event, then calls session_write_close. - * - * @return void - */ - public function write_close() - { - static $run; - - if ($run === NULL) - { - $run = TRUE; - - // Run the events that depend on the session being open - Event::run('system.session_write'); - - // Expire flash keys - $this->expire_flash(); - - // Close the session - session_write_close(); - } - } - - /** - * Set a session variable. - * - * @param string|array key, or array of values - * @param mixed value (if keys is not an array) - * @return void - */ - public function set($keys, $val = FALSE) - { - if (empty($keys)) - return FALSE; - - if ( ! is_array($keys)) - { - $keys = array($keys => $val); - } - - foreach ($keys as $key => $val) - { - if (isset(Session::$protect[$key])) - continue; - - // Set the key - $_SESSION[$key] = $val; - } - } - - /** - * Set a flash variable. - * - * @param string|array key, or array of values - * @param mixed value (if keys is not an array) - * @return void - */ - public function set_flash($keys, $val = FALSE) - { - if (empty($keys)) - return FALSE; - - if ( ! is_array($keys)) - { - $keys = array($keys => $val); - } - - foreach ($keys as $key => $val) - { - if ($key == FALSE) - continue; - - Session::$flash[$key] = 'new'; - Session::set($key, $val); - } - } - - /** - * Freshen one, multiple or all flash variables. - * - * @param string variable key(s) - * @return void - */ - public function keep_flash($keys = NULL) - { - $keys = ($keys === NULL) ? array_keys(Session::$flash) : func_get_args(); - - foreach ($keys as $key) - { - if (isset(Session::$flash[$key])) - { - Session::$flash[$key] = 'new'; - } - } - } - - /** - * Expires old flash data and removes it from the session. - * - * @return void - */ - public function expire_flash() - { - static $run; - - // Method can only be run once - if ($run === TRUE) - return; - - if ( ! empty(Session::$flash)) - { - foreach (Session::$flash as $key => $state) - { - if ($state === 'old') - { - // Flash has expired - unset(Session::$flash[$key], $_SESSION[$key]); - } - else - { - // Flash will expire - Session::$flash[$key] = 'old'; - } - } - } - - // Method has been run - $run = TRUE; - } - - /** - * Get a variable. Access to sub-arrays is supported with key.subkey. - * - * @param string variable key - * @param mixed default value returned if variable does not exist - * @return mixed Variable data if key specified, otherwise array containing all session data. - */ - public function get($key = FALSE, $default = FALSE) - { - if (empty($key)) - return $_SESSION; - - $result = isset($_SESSION[$key]) ? $_SESSION[$key] : Kohana::key_string($_SESSION, $key); - - return ($result === NULL) ? $default : $result; - } - - /** - * Get a variable, and delete it. - * - * @param string variable key - * @param mixed default value returned if variable does not exist - * @return mixed - */ - public function get_once($key, $default = FALSE) - { - $return = Session::get($key, $default); - Session::delete($key); - - return $return; - } - - /** - * Delete one or more variables. - * - * @param string variable key(s) - * @return void - */ - public function delete($keys) - { - $args = func_get_args(); - - foreach ($args as $key) - { - if (isset(Session::$protect[$key])) - continue; - - // Unset the key - unset($_SESSION[$key]); - } - } - -} // End Session Class +class Session_Core +{ + // Session singleton + protected static $instance; + + // Protected key names (cannot be set by the user) + protected static $protect = array('session_id', 'user_agent', 'last_activity', 'ip_address', 'total_hits', '_kf_flash_'); + + // Configuration and driver + protected static $config; + protected static $driver; + + // Flash variables + protected static $flash; + + // Input library + protected $input; + + /** + * Singleton instance of Session. + */ + public static function instance() + { + if (Session::$instance == null) { + // Create a new instance + new Session(); + } + + return Session::$instance; + } + + /** + * On first session instance creation, sets up the driver and creates session. + */ + public function __construct() + { + $this->input = Input::instance(); + + // This part only needs to be run once + if (Session::$instance === null) { + // Load config + Session::$config = Kohana::config('session'); + + // Makes a mirrored array, eg: foo=foo + Session::$protect = array_combine(Session::$protect, Session::$protect); + + // Configure garbage collection + ini_set('session.gc_probability', (int) Session::$config['gc_probability']); + ini_set('session.gc_divisor', 100); + ini_set('session.gc_maxlifetime', (Session::$config['expiration'] == 0) ? 86400 : Session::$config['expiration']); + + // Create a new session + $this->create(); + + if (Session::$config['regenerate'] > 0 and ($_SESSION['total_hits'] % Session::$config['regenerate']) === 0) { + // Regenerate session id and update session cookie + $this->regenerate(); + } else { + // Always update session cookie to keep the session alive + cookie::set(Session::$config['name'], $_SESSION['session_id'], Session::$config['expiration']); + } + + // Close the session just before sending the headers, so that + // the session cookie(s) can be written. + Event::add('system.send_headers', array($this, 'write_close')); + + // Make sure that sessions are closed before exiting + register_shutdown_function(array($this, 'write_close')); + + // Singleton instance + Session::$instance = $this; + } + + Kohana::log('debug', 'Session Library initialized'); + } + + /** + * Get the session id. + * + * @return string + */ + public function id() + { + return $_SESSION['session_id']; + } + + /** + * Create a new session. + * + * @param array variables to set after creation + * @return void + */ + public function create($vars = null) + { + // Destroy any current sessions + $this->destroy(); + + if (Session::$config['driver'] !== 'native') { + // Set driver name + $driver = 'Session_' . ucfirst(Session::$config['driver']) . '_Driver'; + + // Load the driver + if (! Kohana::auto_load($driver)) { + throw new Kohana_Exception('core.driver_not_found', Session::$config['driver'], get_class($this)); + } + + // Initialize the driver + Session::$driver = new $driver(); + + // Validate the driver + if (! (Session::$driver instanceof Session_Driver)) { + throw new Kohana_Exception('core.driver_implements', Session::$config['driver'], get_class($this), 'Session_Driver'); + } + + // Register non-native driver as the session handler + session_set_save_handler( + array(Session::$driver, 'open'), + array(Session::$driver, 'close'), + array(Session::$driver, 'read'), + array(Session::$driver, 'write'), + array(Session::$driver, 'destroy'), + array(Session::$driver, 'gc') + ); + } + + // Validate the session name + if (! preg_match('~^(?=.*[a-z])[a-z0-9_]++$~iD', Session::$config['name'])) { + throw new Kohana_Exception('session.invalid_session_name', Session::$config['name']); + } + + // Name the session, this will also be the name of the cookie + session_name(Session::$config['name']); + + // Set the session cookie parameters + session_set_cookie_params( + Session::$config['expiration'], + Kohana::config('cookie.path'), + Kohana::config('cookie.domain'), + Kohana::config('cookie.secure') + ); + + // Start the session! + session_start(); + + // Put session_id in the session variable + $_SESSION['session_id'] = session_id(); + + // Set defaults + if (! isset($_SESSION['_kf_flash_'])) { + $_SESSION['total_hits'] = 0; + $_SESSION['_kf_flash_'] = array(); + + $_SESSION['user_agent'] = Kohana::$user_agent; + $_SESSION['ip_address'] = $this->input->ip_address(); + } + + // Set up flash variables + Session::$flash =& $_SESSION['_kf_flash_']; + + // Increase total hits + $_SESSION['total_hits'] += 1; + + // Validate data only on hits after one + if ($_SESSION['total_hits'] > 1) { + // Validate the session + foreach (Session::$config['validate'] as $valid) { + switch ($valid) { + // Check user agent for consistency + case 'user_agent': + if ($_SESSION[$valid] !== Kohana::$user_agent) { + return $this->create(); + } + break; + + // Check ip address for consistency + case 'ip_address': + if ($_SESSION[$valid] !== $this->input->$valid()) { + return $this->create(); + } + break; + + // Check expiration time to prevent users from manually modifying it + case 'expiration': + if (time() - $_SESSION['last_activity'] > ini_get('session.gc_maxlifetime')) { + return $this->create(); + } + break; + } + } + } + + // Expire flash keys + $this->expire_flash(); + + // Update last activity + $_SESSION['last_activity'] = time(); + + // Set the new data + Session::set($vars); + } + + /** + * Regenerates the global session id. + * + * @return void + */ + public function regenerate() + { + if (Session::$config['driver'] === 'native') { + // Generate a new session id + // Note: also sets a new session cookie with the updated id + session_regenerate_id(true); + + // Update session with new id + $_SESSION['session_id'] = session_id(); + } else { + // Pass the regenerating off to the driver in case it wants to do anything special + $_SESSION['session_id'] = Session::$driver->regenerate(); + } + + // Get the session name + $name = session_name(); + + if (isset($_COOKIE[$name])) { + // Change the cookie value to match the new session id to prevent "lag" + $_COOKIE[$name] = $_SESSION['session_id']; + } + } + + /** + * Destroys the current session. + * + * @return void + */ + public function destroy() + { + if (session_id() !== '') { + // Get the session name + $name = session_name(); + + // Destroy the session + session_destroy(); + + // Re-initialize the array + $_SESSION = array(); + + // Delete the session cookie + cookie::delete($name); + } + } + + /** + * Runs the system.session_write event, then calls session_write_close. + * + * @return void + */ + public function write_close() + { + static $run; + + if ($run === null) { + $run = true; + + // Run the events that depend on the session being open + Event::run('system.session_write'); + + // Expire flash keys + $this->expire_flash(); + + // Close the session + session_write_close(); + } + } + + /** + * Set a session variable. + * + * @param string|array key, or array of values + * @param mixed value (if keys is not an array) + * @return void + */ + public function set($keys, $val = false) + { + if (empty($keys)) { + return false; + } + + if (! is_array($keys)) { + $keys = array($keys => $val); + } + + foreach ($keys as $key => $val) { + if (isset(Session::$protect[$key])) { + continue; + } + + // Set the key + $_SESSION[$key] = $val; + } + } + + /** + * Set a flash variable. + * + * @param string|array key, or array of values + * @param mixed value (if keys is not an array) + * @return void + */ + public function set_flash($keys, $val = false) + { + if (empty($keys)) { + return false; + } + + if (! is_array($keys)) { + $keys = array($keys => $val); + } + + foreach ($keys as $key => $val) { + if ($key == false) { + continue; + } + + Session::$flash[$key] = 'new'; + Session::set($key, $val); + } + } + + /** + * Freshen one, multiple or all flash variables. + * + * @param string variable key(s) + * @return void + */ + public function keep_flash($keys = null) + { + $keys = ($keys === null) ? array_keys(Session::$flash) : func_get_args(); + + foreach ($keys as $key) { + if (isset(Session::$flash[$key])) { + Session::$flash[$key] = 'new'; + } + } + } + + /** + * Expires old flash data and removes it from the session. + * + * @return void + */ + public function expire_flash() + { + static $run; + + // Method can only be run once + if ($run === true) { + return; + } + + if (! empty(Session::$flash)) { + foreach (Session::$flash as $key => $state) { + if ($state === 'old') { + // Flash has expired + unset(Session::$flash[$key], $_SESSION[$key]); + } else { + // Flash will expire + Session::$flash[$key] = 'old'; + } + } + } + + // Method has been run + $run = true; + } + + /** + * Get a variable. Access to sub-arrays is supported with key.subkey. + * + * @param string variable key + * @param mixed default value returned if variable does not exist + * @return mixed Variable data if key specified, otherwise array containing all session data. + */ + public function get($key = false, $default = false) + { + if (empty($key)) { + return $_SESSION; + } + + $result = isset($_SESSION[$key]) ? $_SESSION[$key] : Kohana::key_string($_SESSION, $key); + + return ($result === null) ? $default : $result; + } + + /** + * Get a variable, and delete it. + * + * @param string variable key + * @param mixed default value returned if variable does not exist + * @return mixed + */ + public function get_once($key, $default = false) + { + $return = Session::get($key, $default); + Session::delete($key); + + return $return; + } + + /** + * Delete one or more variables. + * + * @param string variable key(s) + * @return void + */ + public function delete($keys) + { + $args = func_get_args(); + + foreach ($args as $key) { + if (isset(Session::$protect[$key])) { + continue; + } + + // Unset the key + unset($_SESSION[$key]); + } + } +} +// End Session Class diff --git a/lib/kohana/system/libraries/Tagcloud.php b/lib/kohana/system/libraries/Tagcloud.php index 8fd7bfc..deb0dd8 100644 --- a/lib/kohana/system/libraries/Tagcloud.php +++ b/lib/kohana/system/libraries/Tagcloud.php @@ -1,4 +1,12 @@ - 'tag'); + public $shuffle = false; - public $min_size = 80; - public $max_size = 140; - public $attributes = array('class' => 'tag'); - public $shuffle = FALSE; + // Tag elements, biggest and smallest values + protected $elements; + protected $biggest; + protected $smallest; - // Tag elements, biggest and smallest values - protected $elements; - protected $biggest; - protected $smallest; + /** + * Construct a new tagcloud. The elements must be passed in as an array, + * with each entry in the array having a "title" ,"link", and "count" key. + * Font sizes will be applied via the "style" attribute as a percentage. + * + * @param array elements of the tagcloud + * @param integer minimum font size + * @param integer maximum font size + * @return void + */ + public function __construct(array $elements, $min_size = null, $max_size = null, $shuffle = false) + { + $this->elements = $elements; - /** - * Construct a new tagcloud. The elements must be passed in as an array, - * with each entry in the array having a "title" ,"link", and "count" key. - * Font sizes will be applied via the "style" attribute as a percentage. - * - * @param array elements of the tagcloud - * @param integer minimum font size - * @param integer maximum font size - * @return void - */ - public function __construct(array $elements, $min_size = NULL, $max_size = NULL, $shuffle = FALSE) - { - $this->elements = $elements; - - if($shuffle !== FALSE) - { - $this->shuffle = TRUE; - } + if ($shuffle !== false) { + $this->shuffle = true; + } - $counts = array(); - foreach ($elements as $data) - { - $counts[] = $data['count']; - } + $counts = array(); + foreach ($elements as $data) { + $counts[] = $data['count']; + } - // Find the biggest and smallest values of the elements - $this->biggest = max($counts); - $this->smallest = min($counts); + // Find the biggest and smallest values of the elements + $this->biggest = max($counts); + $this->smallest = min($counts); - if ($min_size !== NULL) - { - $this->min_size = $min_size; - } + if ($min_size !== null) { + $this->min_size = $min_size; + } - if ($max_size !== NULL) - { - $this->max_size = $max_size; - } - } + if ($max_size !== null) { + $this->max_size = $max_size; + } + } - /** - * Magic __toString method. Returns all of the links as a single string. - * - * @return string - */ - public function __toString() - { - return implode("\n", $this->render()); - } + /** + * Magic __toString method. Returns all of the links as a single string. + * + * @return string + */ + public function __toString() + { + return implode("\n", $this->render()); + } - /** - * Renders the elements of the tagcloud into an array of links. - * - * @return array - */ - public function render() - { - if ($this->shuffle === TRUE) - { - shuffle($this->elements); - } + /** + * Renders the elements of the tagcloud into an array of links. + * + * @return array + */ + public function render() + { + if ($this->shuffle === true) { + shuffle($this->elements); + } - // Minimum values must be 1 to prevent divide by zero errors - $range = max($this->biggest - $this->smallest, 1); - $scale = max($this->max_size - $this->min_size, 1); + // Minimum values must be 1 to prevent divide by zero errors + $range = max($this->biggest - $this->smallest, 1); + $scale = max($this->max_size - $this->min_size, 1); - // Import the attributes locally to prevent overwrites - $attr = $this->attributes; + // Import the attributes locally to prevent overwrites + $attr = $this->attributes; - $output = array(); - foreach ($this->elements as $data) - { - if (strpos($data['title'], ' ') !== FALSE) - { - // Replace spaces with non-breaking spaces to prevent line wrapping - // in the middle of a link - $data['title'] = str_replace(' ', ' ', $data['title']); - } + $output = array(); + foreach ($this->elements as $data) { + if (strpos($data['title'], ' ') !== false) { + // Replace spaces with non-breaking spaces to prevent line wrapping + // in the middle of a link + $data['title'] = str_replace(' ', ' ', $data['title']); + } - // Determine the size based on the min/max scale and the smallest/biggest range - $size = ((($data['count'] - $this->smallest) * $scale) / $range) + $this->min_size; + // Determine the size based on the min/max scale and the smallest/biggest range + $size = ((($data['count'] - $this->smallest) * $scale) / $range) + $this->min_size; - $attr['style'] = 'font-size: '.round($size, 0).'%'; + $attr['style'] = 'font-size: ' . round($size, 0) . '%'; - $output[] = html::anchor($data['link'], $data['title'], $attr)."\n"; - } + $output[] = html::anchor($data['link'], $data['title'], $attr) . "\n"; + } - return $output; - } - -} // End Tagcloud \ No newline at end of file + return $output; + } +} +// End Tagcloud diff --git a/lib/kohana/system/libraries/URI.php b/lib/kohana/system/libraries/URI.php index d9ccdcf..58a0026 100644 --- a/lib/kohana/system/libraries/URI.php +++ b/lib/kohana/system/libraries/URI.php @@ -1,4 +1,12 @@ -build_array(URI::$segments, $offset, $associative); + } - /** - * Returns an array containing all the URI segments. - * - * @param integer segment offset - * @param boolean return an associative array - * @return array - */ - public function segment_array($offset = 0, $associative = FALSE) - { - return $this->build_array(URI::$segments, $offset, $associative); - } + /** + * Returns an array containing all the re-routed URI segments. + * + * @param integer rsegment offset + * @param boolean return an associative array + * @return array + */ + public function rsegment_array($offset = 0, $associative = false) + { + return $this->build_array(URI::$rsegments, $offset, $associative); + } - /** - * Returns an array containing all the re-routed URI segments. - * - * @param integer rsegment offset - * @param boolean return an associative array - * @return array - */ - public function rsegment_array($offset = 0, $associative = FALSE) - { - return $this->build_array(URI::$rsegments, $offset, $associative); - } + /** + * Returns an array containing all the URI arguments. + * + * @param integer segment offset + * @param boolean return an associative array + * @return array + */ + public function argument_array($offset = 0, $associative = false) + { + return $this->build_array(URI::$arguments, $offset, $associative); + } - /** - * Returns an array containing all the URI arguments. - * - * @param integer segment offset - * @param boolean return an associative array - * @return array - */ - public function argument_array($offset = 0, $associative = FALSE) - { - return $this->build_array(URI::$arguments, $offset, $associative); - } + /** + * Creates a simple or associative array from an array and an offset. + * Used as a helper for (r)segment_array and argument_array. + * + * @param array array to rebuild + * @param integer offset to start from + * @param boolean create an associative array + * @return array + */ + public function build_array($array, $offset = 0, $associative = false) + { + // Prevent the keys from being improperly indexed + array_unshift($array, 0); - /** - * Creates a simple or associative array from an array and an offset. - * Used as a helper for (r)segment_array and argument_array. - * - * @param array array to rebuild - * @param integer offset to start from - * @param boolean create an associative array - * @return array - */ - public function build_array($array, $offset = 0, $associative = FALSE) - { - // Prevent the keys from being improperly indexed - array_unshift($array, 0); + // Slice the array, preserving the keys + $array = array_slice($array, $offset + 1, count($array) - 1, true); - // Slice the array, preserving the keys - $array = array_slice($array, $offset + 1, count($array) - 1, TRUE); + if ($associative === false) { + return $array; + } - if ($associative === FALSE) - return $array; + $associative = array(); + $pairs = array_chunk($array, 2); - $associative = array(); - $pairs = array_chunk($array, 2); + foreach ($pairs as $pair) { + // Add the key/value pair to the associative array + $associative[$pair[0]] = isset($pair[1]) ? $pair[1] : ''; + } - foreach ($pairs as $pair) - { - // Add the key/value pair to the associative array - $associative[$pair[0]] = isset($pair[1]) ? $pair[1] : ''; - } + return $associative; + } - return $associative; - } + /** + * Returns the complete URI as a string. + * + * @return string + */ + public function string() + { + return URI::$current_uri; + } - /** - * Returns the complete URI as a string. - * - * @return string - */ - public function string() - { - return URI::$current_uri; - } + /** + * Magic method for converting an object to a string. + * + * @return string + */ + public function __toString() + { + return URI::$current_uri; + } - /** - * Magic method for converting an object to a string. - * - * @return string - */ - public function __toString() - { - return URI::$current_uri; - } + /** + * Returns the total number of URI segments. + * + * @return integer + */ + public function total_segments() + { + return count(URI::$segments); + } - /** - * Returns the total number of URI segments. - * - * @return integer - */ - public function total_segments() - { - return count(URI::$segments); - } + /** + * Returns the total number of re-routed URI segments. + * + * @return integer + */ + public function total_rsegments() + { + return count(URI::$rsegments); + } - /** - * Returns the total number of re-routed URI segments. - * - * @return integer - */ - public function total_rsegments() - { - return count(URI::$rsegments); - } + /** + * Returns the total number of URI arguments. + * + * @return integer + */ + public function total_arguments() + { + return count(URI::$arguments); + } - /** - * Returns the total number of URI arguments. - * - * @return integer - */ - public function total_arguments() - { - return count(URI::$arguments); - } + /** + * Returns the last URI segment. + * + * @param mixed default value returned if segment does not exist + * @return string + */ + public function last_segment($default = false) + { + if (($end = $this->total_segments()) < 1) { + return $default; + } - /** - * Returns the last URI segment. - * - * @param mixed default value returned if segment does not exist - * @return string - */ - public function last_segment($default = FALSE) - { - if (($end = $this->total_segments()) < 1) - return $default; + return URI::$segments[$end - 1]; + } - return URI::$segments[$end - 1]; - } + /** + * Returns the last re-routed URI segment. + * + * @param mixed default value returned if segment does not exist + * @return string + */ + public function last_rsegment($default = false) + { + if (($end = $this->total_segments()) < 1) { + return $default; + } - /** - * Returns the last re-routed URI segment. - * - * @param mixed default value returned if segment does not exist - * @return string - */ - public function last_rsegment($default = FALSE) - { - if (($end = $this->total_segments()) < 1) - return $default; + return URI::$rsegments[$end - 1]; + } - return URI::$rsegments[$end - 1]; - } + /** + * Returns the path to the current controller (not including the actual + * controller), as a web path. + * + * @param boolean return a full url, or only the path specifically + * @return string + */ + public function controller_path($full = true) + { + return ($full) ? url::site(URI::$controller_path) : URI::$controller_path; + } - /** - * Returns the path to the current controller (not including the actual - * controller), as a web path. - * - * @param boolean return a full url, or only the path specifically - * @return string - */ - public function controller_path($full = TRUE) - { - return ($full) ? url::site(URI::$controller_path) : URI::$controller_path; - } + /** + * Returns the current controller, as a web path. + * + * @param boolean return a full url, or only the controller specifically + * @return string + */ + public function controller($full = true) + { + return ($full) ? url::site(URI::$controller_path . URI::$controller) : URI::$controller; + } - /** - * Returns the current controller, as a web path. - * - * @param boolean return a full url, or only the controller specifically - * @return string - */ - public function controller($full = TRUE) - { - return ($full) ? url::site(URI::$controller_path.URI::$controller) : URI::$controller; - } - - /** - * Returns the current method, as a web path. - * - * @param boolean return a full url, or only the method specifically - * @return string - */ - public function method($full = TRUE) - { - return ($full) ? url::site(URI::$controller_path.URI::$controller.'/'.URI::$method) : URI::$method; - } - -} // End URI Class + /** + * Returns the current method, as a web path. + * + * @param boolean return a full url, or only the method specifically + * @return string + */ + public function method($full = true) + { + return ($full) ? url::site(URI::$controller_path . URI::$controller . '/' . URI::$method) : URI::$method; + } +} +// End URI Class diff --git a/lib/kohana/system/libraries/Validation.php b/lib/kohana/system/libraries/Validation.php index 5a48bfc..44755bc 100644 --- a/lib/kohana/system/libraries/Validation.php +++ b/lib/kohana/system/libraries/Validation.php @@ -1,4 +1,12 @@ -submitted = ! empty($array); - - parent::__construct($array, ArrayObject::ARRAY_AS_PROPS | ArrayObject::STD_PROP_LIST); - } - - /** - * Magic clone method, clears errors and messages. - * - * @return void - */ - public function __clone() - { - $this->errors = array(); - $this->messages = array(); - } - - /** - * Create a copy of the current validation rules and change the array. - * - * @chainable - * @param array new array to validate - * @return Validation - */ - public function copy(array $array) - { - $copy = clone $this; - - $copy->exchangeArray($array); - - return $copy; - } - - /** - * Test if the data has been submitted. - * - * @return boolean - */ - public function submitted($value = NULL) - { - if (is_bool($value)) - { - $this->submitted = $value; - } - - return $this->submitted; - } - - /** - * Returns an array of all the field names that have filters, rules, or callbacks. - * - * @return array - */ - public function field_names() - { - // All the fields that are being validated - $fields = array_keys(array_merge - ( - $this->pre_filters, - $this->rules, - $this->callbacks, - $this->post_filters - )); - - // Remove wildcard fields - $fields = array_diff($fields, array('*')); - - return $fields; - } - - /** - * Returns the array values of the current object. - * - * @return array - */ - public function as_array() - { - return $this->getArrayCopy(); - } - - /** - * Returns the ArrayObject values, removing all inputs without rules. - * To choose specific inputs, list the field name as arguments. - * - * @param boolean return only fields with filters, rules, and callbacks - * @return array - */ - public function safe_array() - { - // Load choices - $choices = func_get_args(); - $choices = empty($choices) ? NULL : array_combine($choices, $choices); - - // Get field names - $fields = $this->field_names(); - - $safe = array(); - foreach ($fields as $field) - { - if ($choices === NULL OR isset($choices[$field])) - { - if (isset($this[$field])) - { - $value = $this[$field]; - - if (is_object($value)) - { - // Convert the value back into an array - $value = $value->getArrayCopy(); - } - } - else - { - // Even if the field is not in this array, it must be set - $value = NULL; - } - - // Add the field to the array - $safe[$field] = $value; - } - } - - return $safe; - } - - /** - * Add additional rules that will forced, even for empty fields. All arguments - * passed will be appended to the list. - * - * @chainable - * @param string rule name - * @return object - */ - public function allow_empty_rules($rules) - { - // Any number of args are supported - $rules = func_get_args(); - - // Merge the allowed rules - $this->empty_rules = array_merge($this->empty_rules, $rules); - - return $this; - } - - /** - * Converts a filter, rule, or callback into a fully-qualified callback array. - * - * @return mixed - */ - protected function callback($callback) - { - if (is_string($callback)) - { - if (strpos($callback, '::') !== FALSE) - { - $callback = explode('::', $callback); - } - elseif (function_exists($callback)) - { - // No need to check if the callback is a method - $callback = $callback; - } - elseif (method_exists($this, $callback)) - { - // The callback exists in Validation - $callback = array($this, $callback); - } - elseif (method_exists('valid', $callback)) - { - // The callback exists in valid:: - $callback = array('valid', $callback); - } - } - - if ( ! is_callable($callback, FALSE)) - { - if (is_array($callback)) - { - if (is_object($callback[0])) - { - // Object instance syntax - $name = get_class($callback[0]).'->'.$callback[1]; - } - else - { - // Static class syntax - $name = $callback[0].'::'.$callback[1]; - } - } - else - { - // Function syntax - $name = $callback; - } - - throw new Kohana_Exception('validation.not_callable', $name); - } - - return $callback; - } - - /** - * Add a pre-filter to one or more inputs. Pre-filters are applied before - * rules or callbacks are executed. - * - * @chainable - * @param callback filter - * @param string fields to apply filter to, use TRUE for all fields - * @return object - */ - public function pre_filter($filter, $field = TRUE) - { - if ($field === TRUE OR $field === '*') - { - // Use wildcard - $fields = array('*'); - } - else - { - // Add the filter to specific inputs - $fields = func_get_args(); - $fields = array_slice($fields, 1); - } - - // Convert to a proper callback - $filter = $this->callback($filter); - - foreach ($fields as $field) - { - // Add the filter to specified field - $this->pre_filters[$field][] = $filter; - } - - return $this; - } - - /** - * Add a post-filter to one or more inputs. Post-filters are applied after - * rules and callbacks have been executed. - * - * @chainable - * @param callback filter - * @param string fields to apply filter to, use TRUE for all fields - * @return object - */ - public function post_filter($filter, $field = TRUE) - { - if ($field === TRUE) - { - // Use wildcard - $fields = array('*'); - } - else - { - // Add the filter to specific inputs - $fields = func_get_args(); - $fields = array_slice($fields, 1); - } - - // Convert to a proper callback - $filter = $this->callback($filter); - - foreach ($fields as $field) - { - // Add the filter to specified field - $this->post_filters[$field][] = $filter; - } - - return $this; - } - - /** - * Add rules to a field. Validation rules may only return TRUE or FALSE and - * can not manipulate the value of a field. - * - * @chainable - * @param string field name - * @param callback rules (one or more arguments) - * @return object - */ - public function add_rules($field, $rules) - { - // Get the rules - $rules = func_get_args(); - $rules = array_slice($rules, 1); - - if ($field === TRUE) - { - // Use wildcard - $field = '*'; - } - - foreach ($rules as $rule) - { - // Arguments for rule - $args = NULL; - - if (is_string($rule)) - { - if (preg_match('/^([^\[]++)\[(.+)\]$/', $rule, $matches)) - { - // Split the rule into the function and args - $rule = $matches[1]; - $args = preg_split('/(?array_fields[$field] = $field; - } - - // Convert to a proper callback - $rule = $this->callback($rule); - - // Add the rule, with args, to the field - $this->rules[$field][] = array($rule, $args); - } - - return $this; - } - - /** - * Add callbacks to a field. Callbacks must accept the Validation object - * and the input name. Callback returns are not processed. - * - * @chainable - * @param string field name - * @param callbacks callbacks (unlimited number) - * @return object - */ - public function add_callbacks($field, $callbacks) - { - // Get all callbacks as an array - $callbacks = func_get_args(); - $callbacks = array_slice($callbacks, 1); - - if ($field === TRUE) - { - // Use wildcard - $field = '*'; - } - - foreach ($callbacks as $callback) - { - // Convert to a proper callback - $callback = $this->callback($callback); - - // Add the callback to specified field - $this->callbacks[$field][] = $callback; - } - - return $this; - } - - /** - * Validate by processing pre-filters, rules, callbacks, and post-filters. - * All fields that have filters, rules, or callbacks will be initialized if - * they are undefined. Validation will only be run if there is data already - * in the array. - * - * @param object Validation object, used only for recursion - * @param object name of field for errors - * @return bool - */ - public function validate($object = NULL, $field_name = NULL) - { - if ($object === NULL) - { - // Use the current object - $object = $this; - } - - // Get all field names - $fields = $this->field_names(); - - // Copy the array from the object, to optimize multiple sets - $array = $this->getArrayCopy(); - - foreach ($fields as $field) - { - if ($field === '*') - { - // Ignore wildcard - continue; - } - - if ( ! isset($array[$field])) - { - if (isset($this->array_fields[$field])) - { - // This field must be an array - $array[$field] = array(); - } - else - { - $array[$field] = NULL; - } - } - } - - // Swap the array back into the object - $this->exchangeArray($array); - - // Get all defined field names - $fields = array_keys($array); - - foreach ($this->pre_filters as $field => $callbacks) - { - foreach ($callbacks as $callback) - { - if ($field === '*') - { - foreach ($fields as $f) - { - $this[$f] = is_array($this[$f]) ? array_map($callback, $this[$f]) : call_user_func($callback, $this[$f]); - } - } - else - { - $this[$field] = is_array($this[$field]) ? array_map($callback, $this[$field]) : call_user_func($callback, $this[$field]); - } - } - } - - if ($this->submitted === FALSE) - return FALSE; - - foreach ($this->rules as $field => $callbacks) - { - foreach ($callbacks as $callback) - { - // Separate the callback and arguments - list ($callback, $args) = $callback; - - // Function or method name of the rule - $rule = is_array($callback) ? $callback[1] : $callback; - - if ($field === '*') - { - foreach ($fields as $f) - { - // Note that continue, instead of break, is used when - // applying rules using a wildcard, so that all fields - // will be validated. - - if (isset($this->errors[$f])) - { - // Prevent other rules from being evaluated if an error has occurred - continue; - } - - if (empty($this[$f]) AND ! in_array($rule, $this->empty_rules)) - { - // This rule does not need to be processed on empty fields - continue; - } - - if ($args === NULL) - { - if ( ! call_user_func($callback, $this[$f])) - { - $this->errors[$f] = $rule; - - // Stop validating this field when an error is found - continue; - } - } - else - { - if ( ! call_user_func($callback, $this[$f], $args)) - { - $this->errors[$f] = $rule; - - // Stop validating this field when an error is found - continue; - } - } - } - } - else - { - if (isset($this->errors[$field])) - { - // Prevent other rules from being evaluated if an error has occurred - break; - } - - if ( ! in_array($rule, $this->empty_rules) AND ! $this->required($this[$field])) - { - // This rule does not need to be processed on empty fields - continue; - } - - if ($args === NULL) - { - if ( ! call_user_func($callback, $this[$field])) - { - $this->errors[$field] = $rule; - - // Stop validating this field when an error is found - break; - } - } - else - { - if ( ! call_user_func($callback, $this[$field], $args)) - { - $this->errors[$field] = $rule; - - // Stop validating this field when an error is found - break; - } - } - } - } - } - - foreach ($this->callbacks as $field => $callbacks) - { - foreach ($callbacks as $callback) - { - if ($field === '*') - { - foreach ($fields as $f) - { - // Note that continue, instead of break, is used when - // applying rules using a wildcard, so that all fields - // will be validated. - - if (isset($this->errors[$f])) - { - // Stop validating this field when an error is found - continue; - } - - call_user_func($callback, $this, $f); - } - } - else - { - if (isset($this->errors[$field])) - { - // Stop validating this field when an error is found - break; - } - - call_user_func($callback, $this, $field); - } - } - } - - foreach ($this->post_filters as $field => $callbacks) - { - foreach ($callbacks as $callback) - { - if ($field === '*') - { - foreach ($fields as $f) - { - $this[$f] = is_array($this[$f]) ? array_map($callback, $this[$f]) : call_user_func($callback, $this[$f]); - } - } - else - { - $this[$field] = is_array($this[$field]) ? array_map($callback, $this[$field]) : call_user_func($callback, $this[$field]); - } - } - } - - // Return TRUE if there are no errors - return $this->errors === array(); - } - - /** - * Add an error to an input. - * - * @chainable - * @param string input name - * @param string unique error name - * @return object - */ - public function add_error($field, $name) - { - $this->errors[$field] = $name; - - return $this; - } - - /** - * Sets or returns the message for an input. - * - * @chainable - * @param string input key - * @param string message to set - * @return string|object - */ - public function message($input = NULL, $message = NULL) - { - if ($message === NULL) - { - if ($input === NULL) - { - $messages = array(); - $keys = array_keys($this->messages); - - foreach ($keys as $input) - { - $messages[] = $this->message($input); - } - - return implode("\n", $messages); - } - - // Return nothing if no message exists - if (empty($this->messages[$input])) - return ''; - - // Return the HTML message string - return $this->messages[$input]; - } - else - { - $this->messages[$input] = $message; - } - - return $this; - } - - /** - * Return the errors array. - * - * @param boolean load errors from a lang file - * @return array - */ - public function errors($file = NULL) - { - if ($file === NULL) - { - return $this->errors; - } - else - { - - $errors = array(); - foreach ($this->errors as $input => $error) - { - // Key for this input error - $key = "$file.$input.$error"; - - if (($errors[$input] = Kohana::lang($key)) === $key) - { - // Get the default error message - $errors[$input] = Kohana::lang("$file.$input.default"); - } - } - - return $errors; - } - } - - /** - * Rule: required. Generates an error if the field has an empty value. - * - * @param mixed input value - * @return bool - */ - public function required($str) - { - if (is_object($str) AND $str instanceof ArrayObject) - { - // Get the array from the ArrayObject - $str = $str->getArrayCopy(); - } - - if (is_array($str)) - { - return ! empty($str); - } - else - { - return ! ($str === '' OR $str === NULL OR $str === FALSE); - } - } - - /** - * Rule: matches. Generates an error if the field does not match one or more - * other fields. - * - * @param mixed input value - * @param array input names to match against - * @return bool - */ - public function matches($str, array $inputs) - { - foreach ($inputs as $key) - { - if ($str !== (isset($this[$key]) ? $this[$key] : NULL)) - return FALSE; - } - - return TRUE; - } - - /** - * Rule: length. Generates an error if the field is too long or too short. - * - * @param mixed input value - * @param array minimum, maximum, or exact length to match - * @return bool - */ - public function length($str, array $length) - { - if ( ! is_string($str)) - return FALSE; - - $size = utf8::strlen($str); - $status = FALSE; - - if (count($length) > 1) - { - list ($min, $max) = $length; - - if ($size >= $min AND $size <= $max) - { - $status = TRUE; - } - } - else - { - $status = ($size === (int) $length[0]); - } - - return $status; - } - - /** - * Rule: depends_on. Generates an error if the field does not depend on one - * or more other fields. - * - * @param mixed field name - * @param array field names to check dependency - * @return bool - */ - public function depends_on($field, array $fields) - { - foreach ($fields as $depends_on) - { - if ( ! isset($this[$depends_on]) OR $this[$depends_on] == NULL) - return FALSE; - } - - return TRUE; - } - - /** - * Rule: chars. Generates an error if the field contains characters outside of the list. - * - * @param string field value - * @param array allowed characters - * @return bool - */ - public function chars($value, array $chars) - { - return ! preg_match('![^'.implode('', $chars).']!u', $value); - } - -} // End Validation +class Validation_Core extends ArrayObject +{ + // Filters + protected $pre_filters = array(); + protected $post_filters = array(); + + // Rules and callbacks + protected $rules = array(); + protected $callbacks = array(); + + // Rules that are allowed to run on empty fields + protected $empty_rules = array('required', 'matches'); + + // Errors + protected $errors = array(); + protected $messages = array(); + + // Fields that are expected to be arrays + protected $array_fields = array(); + + // Checks if there is data to validate. + protected $submitted; + + /** + * Creates a new Validation instance. + * + * @param array array to use for validation + * @return object + */ + public static function factory(array $array) + { + return new Validation($array); + } + + /** + * Sets the unique "any field" key and creates an ArrayObject from the + * passed array. + * + * @param array array to validate + * @return void + */ + public function __construct(array $array) + { + // The array is submitted if the array is not empty + $this->submitted = ! empty($array); + + parent::__construct($array, ArrayObject::ARRAY_AS_PROPS | ArrayObject::STD_PROP_LIST); + } + + /** + * Magic clone method, clears errors and messages. + * + * @return void + */ + public function __clone() + { + $this->errors = array(); + $this->messages = array(); + } + + /** + * Create a copy of the current validation rules and change the array. + * + * @chainable + * @param array new array to validate + * @return Validation + */ + public function copy(array $array) + { + $copy = clone $this; + + $copy->exchangeArray($array); + + return $copy; + } + + /** + * Test if the data has been submitted. + * + * @return boolean + */ + public function submitted($value = null) + { + if (is_bool($value)) { + $this->submitted = $value; + } + + return $this->submitted; + } + + /** + * Returns an array of all the field names that have filters, rules, or callbacks. + * + * @return array + */ + public function field_names() + { + // All the fields that are being validated + $fields = array_keys(array_merge( + $this->pre_filters, + $this->rules, + $this->callbacks, + $this->post_filters + )); + + // Remove wildcard fields + $fields = array_diff($fields, array('*')); + + return $fields; + } + + /** + * Returns the array values of the current object. + * + * @return array + */ + public function as_array() + { + return $this->getArrayCopy(); + } + + /** + * Returns the ArrayObject values, removing all inputs without rules. + * To choose specific inputs, list the field name as arguments. + * + * @param boolean return only fields with filters, rules, and callbacks + * @return array + */ + public function safe_array() + { + // Load choices + $choices = func_get_args(); + $choices = empty($choices) ? null : array_combine($choices, $choices); + + // Get field names + $fields = $this->field_names(); + + $safe = array(); + foreach ($fields as $field) { + if ($choices === null or isset($choices[$field])) { + if (isset($this[$field])) { + $value = $this[$field]; + + if (is_object($value)) { + // Convert the value back into an array + $value = $value->getArrayCopy(); + } + } else { + // Even if the field is not in this array, it must be set + $value = null; + } + + // Add the field to the array + $safe[$field] = $value; + } + } + + return $safe; + } + + /** + * Add additional rules that will forced, even for empty fields. All arguments + * passed will be appended to the list. + * + * @chainable + * @param string rule name + * @return object + */ + public function allow_empty_rules($rules) + { + // Any number of args are supported + $rules = func_get_args(); + + // Merge the allowed rules + $this->empty_rules = array_merge($this->empty_rules, $rules); + + return $this; + } + + /** + * Converts a filter, rule, or callback into a fully-qualified callback array. + * + * @return mixed + */ + protected function callback($callback) + { + if (is_string($callback)) { + if (strpos($callback, '::') !== false) { + $callback = explode('::', $callback); + } elseif (function_exists($callback)) { + // No need to check if the callback is a method + $callback = $callback; + } elseif (method_exists($this, $callback)) { + // The callback exists in Validation + $callback = array($this, $callback); + } elseif (method_exists('valid', $callback)) { + // The callback exists in valid:: + $callback = array('valid', $callback); + } + } + + if (! is_callable($callback, false)) { + if (is_array($callback)) { + if (is_object($callback[0])) { + // Object instance syntax + $name = get_class($callback[0]) . '->' . $callback[1]; + } else { + // Static class syntax + $name = $callback[0] . '::' . $callback[1]; + } + } else { + // Function syntax + $name = $callback; + } + + throw new Kohana_Exception('validation.not_callable', $name); + } + + return $callback; + } + + /** + * Add a pre-filter to one or more inputs. Pre-filters are applied before + * rules or callbacks are executed. + * + * @chainable + * @param callback filter + * @param string fields to apply filter to, use TRUE for all fields + * @return object + */ + public function pre_filter($filter, $field = true) + { + if ($field === true or $field === '*') { + // Use wildcard + $fields = array('*'); + } else { + // Add the filter to specific inputs + $fields = func_get_args(); + $fields = array_slice($fields, 1); + } + + // Convert to a proper callback + $filter = $this->callback($filter); + + foreach ($fields as $field) { + // Add the filter to specified field + $this->pre_filters[$field][] = $filter; + } + + return $this; + } + + /** + * Add a post-filter to one or more inputs. Post-filters are applied after + * rules and callbacks have been executed. + * + * @chainable + * @param callback filter + * @param string fields to apply filter to, use TRUE for all fields + * @return object + */ + public function post_filter($filter, $field = true) + { + if ($field === true) { + // Use wildcard + $fields = array('*'); + } else { + // Add the filter to specific inputs + $fields = func_get_args(); + $fields = array_slice($fields, 1); + } + + // Convert to a proper callback + $filter = $this->callback($filter); + + foreach ($fields as $field) { + // Add the filter to specified field + $this->post_filters[$field][] = $filter; + } + + return $this; + } + + /** + * Add rules to a field. Validation rules may only return TRUE or FALSE and + * can not manipulate the value of a field. + * + * @chainable + * @param string field name + * @param callback rules (one or more arguments) + * @return object + */ + public function add_rules($field, $rules) + { + // Get the rules + $rules = func_get_args(); + $rules = array_slice($rules, 1); + + if ($field === true) { + // Use wildcard + $field = '*'; + } + + foreach ($rules as $rule) { + // Arguments for rule + $args = null; + + if (is_string($rule)) { + if (preg_match('/^([^\[]++)\[(.+)\]$/', $rule, $matches)) { + // Split the rule into the function and args + $rule = $matches[1]; + $args = preg_split('/(?array_fields[$field] = $field; + } + + // Convert to a proper callback + $rule = $this->callback($rule); + + // Add the rule, with args, to the field + $this->rules[$field][] = array($rule, $args); + } + + return $this; + } + + /** + * Add callbacks to a field. Callbacks must accept the Validation object + * and the input name. Callback returns are not processed. + * + * @chainable + * @param string field name + * @param callbacks callbacks (unlimited number) + * @return object + */ + public function add_callbacks($field, $callbacks) + { + // Get all callbacks as an array + $callbacks = func_get_args(); + $callbacks = array_slice($callbacks, 1); + + if ($field === true) { + // Use wildcard + $field = '*'; + } + + foreach ($callbacks as $callback) { + // Convert to a proper callback + $callback = $this->callback($callback); + + // Add the callback to specified field + $this->callbacks[$field][] = $callback; + } + + return $this; + } + + /** + * Validate by processing pre-filters, rules, callbacks, and post-filters. + * All fields that have filters, rules, or callbacks will be initialized if + * they are undefined. Validation will only be run if there is data already + * in the array. + * + * @param object Validation object, used only for recursion + * @param object name of field for errors + * @return bool + */ + public function validate($object = null, $field_name = null) + { + if ($object === null) { + // Use the current object + $object = $this; + } + + // Get all field names + $fields = $this->field_names(); + + // Copy the array from the object, to optimize multiple sets + $array = $this->getArrayCopy(); + + foreach ($fields as $field) { + if ($field === '*') { + // Ignore wildcard + continue; + } + + if (! isset($array[$field])) { + if (isset($this->array_fields[$field])) { + // This field must be an array + $array[$field] = array(); + } else { + $array[$field] = null; + } + } + } + + // Swap the array back into the object + $this->exchangeArray($array); + + // Get all defined field names + $fields = array_keys($array); + + foreach ($this->pre_filters as $field => $callbacks) { + foreach ($callbacks as $callback) { + if ($field === '*') { + foreach ($fields as $f) { + $this[$f] = is_array($this[$f]) ? array_map($callback, $this[$f]) : call_user_func($callback, $this[$f]); + } + } else { + $this[$field] = is_array($this[$field]) ? array_map($callback, $this[$field]) : call_user_func($callback, $this[$field]); + } + } + } + + if ($this->submitted === false) { + return false; + } + + foreach ($this->rules as $field => $callbacks) { + foreach ($callbacks as $callback) { + // Separate the callback and arguments + list ($callback, $args) = $callback; + + // Function or method name of the rule + $rule = is_array($callback) ? $callback[1] : $callback; + + if ($field === '*') { + foreach ($fields as $f) { + // Note that continue, instead of break, is used when + // applying rules using a wildcard, so that all fields + // will be validated. + + if (isset($this->errors[$f])) { + // Prevent other rules from being evaluated if an error has occurred + continue; + } + + if (empty($this[$f]) and ! in_array($rule, $this->empty_rules)) { + // This rule does not need to be processed on empty fields + continue; + } + + if ($args === null) { + if (! call_user_func($callback, $this[$f])) { + $this->errors[$f] = $rule; + + // Stop validating this field when an error is found + continue; + } + } else { + if (! call_user_func($callback, $this[$f], $args)) { + $this->errors[$f] = $rule; + + // Stop validating this field when an error is found + continue; + } + } + } + } else { + if (isset($this->errors[$field])) { + // Prevent other rules from being evaluated if an error has occurred + break; + } + + if (! in_array($rule, $this->empty_rules) and ! $this->required($this[$field])) { + // This rule does not need to be processed on empty fields + continue; + } + + if ($args === null) { + if (! call_user_func($callback, $this[$field])) { + $this->errors[$field] = $rule; + + // Stop validating this field when an error is found + break; + } + } else { + if (! call_user_func($callback, $this[$field], $args)) { + $this->errors[$field] = $rule; + + // Stop validating this field when an error is found + break; + } + } + } + } + } + + foreach ($this->callbacks as $field => $callbacks) { + foreach ($callbacks as $callback) { + if ($field === '*') { + foreach ($fields as $f) { + // Note that continue, instead of break, is used when + // applying rules using a wildcard, so that all fields + // will be validated. + + if (isset($this->errors[$f])) { + // Stop validating this field when an error is found + continue; + } + + call_user_func($callback, $this, $f); + } + } else { + if (isset($this->errors[$field])) { + // Stop validating this field when an error is found + break; + } + + call_user_func($callback, $this, $field); + } + } + } + + foreach ($this->post_filters as $field => $callbacks) { + foreach ($callbacks as $callback) { + if ($field === '*') { + foreach ($fields as $f) { + $this[$f] = is_array($this[$f]) ? array_map($callback, $this[$f]) : call_user_func($callback, $this[$f]); + } + } else { + $this[$field] = is_array($this[$field]) ? array_map($callback, $this[$field]) : call_user_func($callback, $this[$field]); + } + } + } + + // Return TRUE if there are no errors + return $this->errors === array(); + } + + /** + * Add an error to an input. + * + * @chainable + * @param string input name + * @param string unique error name + * @return object + */ + public function add_error($field, $name) + { + $this->errors[$field] = $name; + + return $this; + } + + /** + * Sets or returns the message for an input. + * + * @chainable + * @param string input key + * @param string message to set + * @return string|object + */ + public function message($input = null, $message = null) + { + if ($message === null) { + if ($input === null) { + $messages = array(); + $keys = array_keys($this->messages); + + foreach ($keys as $input) { + $messages[] = $this->message($input); + } + + return implode("\n", $messages); + } + + // Return nothing if no message exists + if (empty($this->messages[$input])) { + return ''; + } + + // Return the HTML message string + return $this->messages[$input]; + } else { + $this->messages[$input] = $message; + } + + return $this; + } + + /** + * Return the errors array. + * + * @param boolean load errors from a lang file + * @return array + */ + public function errors($file = null) + { + if ($file === null) { + return $this->errors; + } else { + $errors = array(); + foreach ($this->errors as $input => $error) { + // Key for this input error + $key = "$file.$input.$error"; + + if (($errors[$input] = Kohana::lang($key)) === $key) { + // Get the default error message + $errors[$input] = Kohana::lang("$file.$input.default"); + } + } + + return $errors; + } + } + + /** + * Rule: required. Generates an error if the field has an empty value. + * + * @param mixed input value + * @return bool + */ + public function required($str) + { + if (is_object($str) and $str instanceof ArrayObject) { + // Get the array from the ArrayObject + $str = $str->getArrayCopy(); + } + + if (is_array($str)) { + return ! empty($str); + } else { + return ! ($str === '' or $str === null or $str === false); + } + } + + /** + * Rule: matches. Generates an error if the field does not match one or more + * other fields. + * + * @param mixed input value + * @param array input names to match against + * @return bool + */ + public function matches($str, array $inputs) + { + foreach ($inputs as $key) { + if ($str !== (isset($this[$key]) ? $this[$key] : null)) { + return false; + } + } + + return true; + } + + /** + * Rule: length. Generates an error if the field is too long or too short. + * + * @param mixed input value + * @param array minimum, maximum, or exact length to match + * @return bool + */ + public function length($str, array $length) + { + if (! is_string($str)) { + return false; + } + + $size = utf8::strlen($str); + $status = false; + + if (count($length) > 1) { + list ($min, $max) = $length; + + if ($size >= $min and $size <= $max) { + $status = true; + } + } else { + $status = ($size === (int) $length[0]); + } + + return $status; + } + + /** + * Rule: depends_on. Generates an error if the field does not depend on one + * or more other fields. + * + * @param mixed field name + * @param array field names to check dependency + * @return bool + */ + public function depends_on($field, array $fields) + { + foreach ($fields as $depends_on) { + if (! isset($this[$depends_on]) or $this[$depends_on] == null) { + return false; + } + } + + return true; + } + + /** + * Rule: chars. Generates an error if the field contains characters outside of the list. + * + * @param string field value + * @param array allowed characters + * @return bool + */ + public function chars($value, array $chars) + { + return ! preg_match('![^' . implode('', $chars) . ']!u', $value); + } +} +// End Validation diff --git a/lib/kohana/system/libraries/View.php b/lib/kohana/system/libraries/View.php index 2b8471c..468b3eb 100644 --- a/lib/kohana/system/libraries/View.php +++ b/lib/kohana/system/libraries/View.php @@ -1,4 +1,12 @@ -set_filename($name, $type); + } - /** - * Attempts to load a view and pre-load view data. - * - * @throws Kohana_Exception if the requested view cannot be found - * @param string view name - * @param array pre-load data - * @param string type of file: html, css, js, etc. - * @return void - */ - public function __construct($name = NULL, $data = NULL, $type = NULL) - { - if (is_string($name) AND $name !== '') - { - // Set the filename - $this->set_filename($name, $type); - } + if (is_array($data) and ! empty($data)) { + // Preload data using array_merge, to allow user extensions + $this->kohana_local_data = array_merge($this->kohana_local_data, $data); + } + } - if (is_array($data) AND ! empty($data)) - { - // Preload data using array_merge, to allow user extensions - $this->kohana_local_data = array_merge($this->kohana_local_data, $data); - } - } + /** + * Magic method access to test for view property + * + * @param string View property to test for + * @return boolean + */ + public function __isset($key = null) + { + return $this->is_set($key); + } - /** - * Magic method access to test for view property - * - * @param string View property to test for - * @return boolean - */ - public function __isset($key = NULL) - { - return $this->is_set($key); - } + /** + * Sets the view filename. + * + * @chainable + * @param string view filename + * @param string view file type + * @return object + */ + public function set_filename($name, $type = null) + { + if ($type == null) { + // Load the filename and set the content type + $this->kohana_filename = Kohana::find_file('views', $name, true); + $this->kohana_filetype = EXT; + } else { + // Check if the filetype is allowed by the configuration + if (! in_array($type, Kohana::config('view.allowed_filetypes'))) { + throw new Kohana_Exception('core.invalid_filetype', $type); + } - /** - * Sets the view filename. - * - * @chainable - * @param string view filename - * @param string view file type - * @return object - */ - public function set_filename($name, $type = NULL) - { - if ($type == NULL) - { - // Load the filename and set the content type - $this->kohana_filename = Kohana::find_file('views', $name, TRUE); - $this->kohana_filetype = EXT; - } - else - { - // Check if the filetype is allowed by the configuration - if ( ! in_array($type, Kohana::config('view.allowed_filetypes'))) - throw new Kohana_Exception('core.invalid_filetype', $type); + // Load the filename and set the content type + $this->kohana_filename = Kohana::find_file('views', $name, true, $type); + $this->kohana_filetype = Kohana::config('mimes.' . $type); - // Load the filename and set the content type - $this->kohana_filename = Kohana::find_file('views', $name, TRUE, $type); - $this->kohana_filetype = Kohana::config('mimes.'.$type); + if ($this->kohana_filetype == null) { + // Use the specified type + $this->kohana_filetype = $type; + } + } - if ($this->kohana_filetype == NULL) - { - // Use the specified type - $this->kohana_filetype = $type; - } - } + return $this; + } - return $this; - } + /** + * Sets a view variable. + * + * @param string|array name of variable or an array of variables + * @param mixed value when using a named variable + * @return object + */ + public function set($name, $value = null) + { + if (is_array($name)) { + foreach ($name as $key => $value) { + $this->__set($key, $value); + } + } else { + $this->__set($name, $value); + } - /** - * Sets a view variable. - * - * @param string|array name of variable or an array of variables - * @param mixed value when using a named variable - * @return object - */ - public function set($name, $value = NULL) - { - if (is_array($name)) - { - foreach ($name as $key => $value) - { - $this->__set($key, $value); - } - } - else - { - $this->__set($name, $value); - } + return $this; + } - return $this; - } + /** + * Checks for a property existence in the view locally or globally. Unlike the built in __isset(), + * this method can take an array of properties to test simultaneously. + * + * @param string $key property name to test for + * @param array $key array of property names to test for + * @return boolean property test result + * @return array associative array of keys and boolean test result + */ + public function is_set($key = false) + { + // Setup result; + $result = false; - /** - * Checks for a property existence in the view locally or globally. Unlike the built in __isset(), - * this method can take an array of properties to test simultaneously. - * - * @param string $key property name to test for - * @param array $key array of property names to test for - * @return boolean property test result - * @return array associative array of keys and boolean test result - */ - public function is_set( $key = FALSE ) - { - // Setup result; - $result = FALSE; + // If key is an array + if (is_array($key)) { + // Set the result to an array + $result = array(); - // If key is an array - if (is_array($key)) - { - // Set the result to an array - $result = array(); + // Foreach key + foreach ($key as $property) { + // Set the result to an associative array + $result[$property] = (array_key_exists($property, $this->kohana_local_data) or array_key_exists($property, View::$kohana_global_data)) ? true : false; + } + } else { + // Otherwise just check one property + $result = (array_key_exists($key, $this->kohana_local_data) or array_key_exists($key, View::$kohana_global_data)) ? true : false; + } - // Foreach key - foreach ($key as $property) - { - // Set the result to an associative array - $result[$property] = (array_key_exists($property, $this->kohana_local_data) OR array_key_exists($property, View::$kohana_global_data)) ? TRUE : FALSE; - } - } - else - { - // Otherwise just check one property - $result = (array_key_exists($key, $this->kohana_local_data) OR array_key_exists($key, View::$kohana_global_data)) ? TRUE : FALSE; - } + // Return the result + return $result; + } - // Return the result - return $result; - } + /** + * Sets a bound variable by reference. + * + * @param string name of variable + * @param mixed variable to assign by reference + * @return object + */ + public function bind($name, &$var) + { + $this->kohana_local_data[$name] =& $var; - /** - * Sets a bound variable by reference. - * - * @param string name of variable - * @param mixed variable to assign by reference - * @return object - */ - public function bind($name, & $var) - { - $this->kohana_local_data[$name] =& $var; + return $this; + } - return $this; - } + /** + * Sets a view global variable. + * + * @param string|array name of variable or an array of variables + * @param mixed value when using a named variable + * @return void + */ + public static function set_global($name, $value = null) + { + if (is_array($name)) { + foreach ($name as $key => $value) { + View::$kohana_global_data[$key] = $value; + } + } else { + View::$kohana_global_data[$name] = $value; + } + } - /** - * Sets a view global variable. - * - * @param string|array name of variable or an array of variables - * @param mixed value when using a named variable - * @return void - */ - public static function set_global($name, $value = NULL) - { - if (is_array($name)) - { - foreach ($name as $key => $value) - { - View::$kohana_global_data[$key] = $value; - } - } - else - { - View::$kohana_global_data[$name] = $value; - } - } + /** + * Magically sets a view variable. + * + * @param string variable key + * @param string variable value + * @return void + */ + public function __set($key, $value) + { + $this->kohana_local_data[$key] = $value; + } - /** - * Magically sets a view variable. - * - * @param string variable key - * @param string variable value - * @return void - */ - public function __set($key, $value) - { - $this->kohana_local_data[$key] = $value; - } + /** + * Magically gets a view variable. + * + * @param string variable key + * @return mixed variable value if the key is found + * @return void if the key is not found + */ + public function &__get($key) + { + if (isset($this->kohana_local_data[$key])) { + return $this->kohana_local_data[$key]; + } - /** - * Magically gets a view variable. - * - * @param string variable key - * @return mixed variable value if the key is found - * @return void if the key is not found - */ - public function &__get($key) - { - if (isset($this->kohana_local_data[$key])) - return $this->kohana_local_data[$key]; + if (isset(View::$kohana_global_data[$key])) { + return View::$kohana_global_data[$key]; + } - if (isset(View::$kohana_global_data[$key])) - return View::$kohana_global_data[$key]; + if (isset($this->$key)) { + return $this->$key; + } + } - if (isset($this->$key)) - return $this->$key; - } + /** + * Magically converts view object to string. + * + * @return string + */ + public function __toString() + { + try { + return $this->render(); + } catch (Exception $e) { + // Display the exception using its internal __toString method + return (string) $e; + } + } - /** - * Magically converts view object to string. - * - * @return string - */ - public function __toString() - { - try - { - return $this->render(); - } - catch (Exception $e) - { - // Display the exception using its internal __toString method - return (string) $e; - } - } + /** + * Renders a view. + * + * @param boolean set to TRUE to echo the output instead of returning it + * @param callback special renderer to pass the output through + * @return string if print is FALSE + * @return void if print is TRUE + */ + public function render($print = false, $renderer = false) + { + if (empty($this->kohana_filename)) { + throw new Kohana_Exception('core.view_set_filename'); + } - /** - * Renders a view. - * - * @param boolean set to TRUE to echo the output instead of returning it - * @param callback special renderer to pass the output through - * @return string if print is FALSE - * @return void if print is TRUE - */ - public function render($print = FALSE, $renderer = FALSE) - { - if (empty($this->kohana_filename)) - throw new Kohana_Exception('core.view_set_filename'); + if (is_string($this->kohana_filetype)) { + // Merge global and local data, local overrides global with the same name + $data = array_merge(View::$kohana_global_data, $this->kohana_local_data); - if (is_string($this->kohana_filetype)) - { - // Merge global and local data, local overrides global with the same name - $data = array_merge(View::$kohana_global_data, $this->kohana_local_data); + // Load the view in the controller for access to $this + $output = Kohana::$instance->kohana_load_view($this->kohana_filename, $data); - // Load the view in the controller for access to $this - $output = Kohana::$instance->_kohana_load_view($this->kohana_filename, $data); + if ($renderer !== false and is_callable($renderer, true)) { + // Pass the output through the user defined renderer + $output = call_user_func($renderer, $output); + } - if ($renderer !== FALSE AND is_callable($renderer, TRUE)) - { - // Pass the output through the user defined renderer - $output = call_user_func($renderer, $output); - } + if ($print === true) { + // Display the output + echo $output; + return; + } + } else { + // Set the content type and size + header('Content-Type: ' . $this->kohana_filetype[0]); - if ($print === TRUE) - { - // Display the output - echo $output; - return; - } - } - else - { - // Set the content type and size - header('Content-Type: '.$this->kohana_filetype[0]); + if ($print === true) { + if ($file = fopen($this->kohana_filename, 'rb')) { + // Display the output + fpassthru($file); + fclose($file); + } + return; + } - if ($print === TRUE) - { - if ($file = fopen($this->kohana_filename, 'rb')) - { - // Display the output - fpassthru($file); - fclose($file); - } - return; - } + // Fetch the file contents + $output = file_get_contents($this->kohana_filename); + } - // Fetch the file contents - $output = file_get_contents($this->kohana_filename); - } - - return $output; - } -} // End View \ No newline at end of file + return $output; + } +} +// End View diff --git a/lib/kohana/system/libraries/drivers/Cache.php b/lib/kohana/system/libraries/drivers/Cache.php index 7c5e3c3..908edbb 100644 --- a/lib/kohana/system/libraries/drivers/Cache.php +++ b/lib/kohana/system/libraries/drivers/Cache.php @@ -1,4 +1,12 @@ -directory = $directory; + } - // Directory is valid - $this->directory = $directory; - } + /** + * Finds an array of files matching the given id or tag. + * + * @param string cache id or tag + * @param bool search for tags + * @return array of filenames matching the id or tag + */ + public function exists($id, $tag = false) + { + if ($id === true) { + // Find all the files + return glob($this->directory . '*~*~*'); + } elseif ($tag === true) { + // Find all the files that have the tag name + $paths = glob($this->directory . '*~*' . $id . '*~*'); - /** - * Finds an array of files matching the given id or tag. - * - * @param string cache id or tag - * @param bool search for tags - * @return array of filenames matching the id or tag - */ - public function exists($id, $tag = FALSE) - { - if ($id === TRUE) - { - // Find all the files - return glob($this->directory.'*~*~*'); - } - elseif ($tag === TRUE) - { - // Find all the files that have the tag name - $paths = glob($this->directory.'*~*'.$id.'*~*'); + // Find all tags matching the given tag + $files = array(); + foreach ($paths as $path) { + // Split the files + $tags = explode('~', basename($path)); - // Find all tags matching the given tag - $files = array(); - foreach ($paths as $path) - { - // Split the files - $tags = explode('~', basename($path)); + // Find valid tags + if (count($tags) !== 3 or empty($tags[1])) { + continue; + } - // Find valid tags - if (count($tags) !== 3 OR empty($tags[1])) - continue; + // Split the tags by plus signs, used to separate tags + $tags = explode('+', $tags[1]); - // Split the tags by plus signs, used to separate tags - $tags = explode('+', $tags[1]); + if (in_array($tag, $tags)) { + // Add the file to the array, it has the requested tag + $files[] = $path; + } + } - if (in_array($tag, $tags)) - { - // Add the file to the array, it has the requested tag - $files[] = $path; - } - } + return $files; + } else { + // Find the file matching the given id + return glob($this->directory . $id . '~*'); + } + } - return $files; - } - else - { - // Find the file matching the given id - return glob($this->directory.$id.'~*'); - } - } + /** + * Sets a cache item to the given data, tags, and lifetime. + * + * @param string cache id to set + * @param string data in the cache + * @param array cache tags + * @param integer lifetime + * @return bool + */ + public function set($id, $data, array $tags = null, $lifetime) + { + // Remove old cache files + $this->delete($id); - /** - * Sets a cache item to the given data, tags, and lifetime. - * - * @param string cache id to set - * @param string data in the cache - * @param array cache tags - * @param integer lifetime - * @return bool - */ - public function set($id, $data, array $tags = NULL, $lifetime) - { - // Remove old cache files - $this->delete($id); + // Cache File driver expects unix timestamp + if ($lifetime !== 0) { + $lifetime += time(); + } - // Cache File driver expects unix timestamp - if ($lifetime !== 0) - { - $lifetime += time(); - } + if (! empty($tags)) { + // Convert the tags into a string list + $tags = implode('+', $tags); + } - if ( ! empty($tags)) - { - // Convert the tags into a string list - $tags = implode('+', $tags); - } + // Write out a serialized cache + return (bool) file_put_contents($this->directory . $id . '~' . $tags . '~' . $lifetime, serialize($data)); + } - // Write out a serialized cache - return (bool) file_put_contents($this->directory.$id.'~'.$tags.'~'.$lifetime, serialize($data)); - } + /** + * Finds an array of ids for a given tag. + * + * @param string tag name + * @return array of ids that match the tag + */ + public function find($tag) + { + // An array will always be returned + $result = array(); - /** - * Finds an array of ids for a given tag. - * - * @param string tag name - * @return array of ids that match the tag - */ - public function find($tag) - { - // An array will always be returned - $result = array(); + if ($paths = $this->exists($tag, true)) { + // Length of directory name + $offset = strlen($this->directory); - if ($paths = $this->exists($tag, TRUE)) - { - // Length of directory name - $offset = strlen($this->directory); + // Find all the files with the given tag + foreach ($paths as $path) { + // Get the id from the filename + list($id, $junk) = explode('~', basename($path), 2); - // Find all the files with the given tag - foreach ($paths as $path) - { - // Get the id from the filename - list($id, $junk) = explode('~', basename($path), 2); + if (($data = $this->get($id)) !== false) { + // Add the result to the array + $result[$id] = $data; + } + } + } - if (($data = $this->get($id)) !== FALSE) - { - // Add the result to the array - $result[$id] = $data; - } - } - } + return $result; + } - return $result; - } + /** + * Fetches a cache item. This will delete the item if it is expired or if + * the hash does not match the stored hash. + * + * @param string cache id + * @return mixed|NULL + */ + public function get($id) + { + if ($file = $this->exists($id)) { + // Use the first file + $file = current($file); - /** - * Fetches a cache item. This will delete the item if it is expired or if - * the hash does not match the stored hash. - * - * @param string cache id - * @return mixed|NULL - */ - public function get($id) - { - if ($file = $this->exists($id)) - { - // Use the first file - $file = current($file); + // Validate that the cache has not expired + if ($this->expired($file)) { + // Remove this cache, it has expired + $this->delete($id); + } else { + // Turn off errors while reading the file + $ER = error_reporting(0); - // Validate that the cache has not expired - if ($this->expired($file)) - { - // Remove this cache, it has expired - $this->delete($id); - } - else - { - // Turn off errors while reading the file - $ER = error_reporting(0); + if (($data = file_get_contents($file)) !== false) { + // Unserialize the data + $data = unserialize($data); + } else { + // Delete the data + unset($data); + } - if (($data = file_get_contents($file)) !== FALSE) - { - // Unserialize the data - $data = unserialize($data); - } - else - { - // Delete the data - unset($data); - } + // Turn errors back on + error_reporting($ER); + } + } - // Turn errors back on - error_reporting($ER); - } - } + // Return NULL if there is no data + return isset($data) ? $data : null; + } - // Return NULL if there is no data - return isset($data) ? $data : NULL; - } + /** + * Deletes a cache item by id or tag + * + * @param string cache id or tag, or TRUE for "all items" + * @param boolean use tags + * @return boolean + */ + public function delete($id, $tag = false) + { + $files = $this->exists($id, $tag); - /** - * Deletes a cache item by id or tag - * - * @param string cache id or tag, or TRUE for "all items" - * @param boolean use tags - * @return boolean - */ - public function delete($id, $tag = FALSE) - { - $files = $this->exists($id, $tag); + if (empty($files)) { + return false; + } - if (empty($files)) - return FALSE; + // Disable all error reporting while deleting + $ER = error_reporting(0); - // Disable all error reporting while deleting - $ER = error_reporting(0); + foreach ($files as $file) { + // Remove the cache file + if (! unlink($file)) { + Kohana::log('error', 'Cache: Unable to delete cache file: ' . $file); + } + } - foreach ($files as $file) - { - // Remove the cache file - if ( ! unlink($file)) - Kohana::log('error', 'Cache: Unable to delete cache file: '.$file); - } + // Turn on error reporting again + error_reporting($ER); - // Turn on error reporting again - error_reporting($ER); + return true; + } - return TRUE; - } + /** + * Deletes all cache files that are older than the current time. + * + * @return void + */ + public function delete_expired() + { + if ($files = $this->exists(true)) { + // Disable all error reporting while deleting + $ER = error_reporting(0); - /** - * Deletes all cache files that are older than the current time. - * - * @return void - */ - public function delete_expired() - { - if ($files = $this->exists(TRUE)) - { - // Disable all error reporting while deleting - $ER = error_reporting(0); + foreach ($files as $file) { + if ($this->expired($file)) { + // The cache file has already expired, delete it + if (! unlink($file)) { + Kohana::log('error', 'Cache: Unable to delete cache file: ' . $file); + } + } + } - foreach ($files as $file) - { - if ($this->expired($file)) - { - // The cache file has already expired, delete it - if ( ! unlink($file)) - Kohana::log('error', 'Cache: Unable to delete cache file: '.$file); - } - } + // Turn on error reporting again + error_reporting($ER); + } + } - // Turn on error reporting again - error_reporting($ER); - } - } + /** + * Check if a cache file has expired by filename. + * + * @param string filename + * @return bool + */ + protected function expired($file) + { + // Get the expiration time + $expires = (int) substr($file, strrpos($file, '~') + 1); - /** - * Check if a cache file has expired by filename. - * - * @param string filename - * @return bool - */ - protected function expired($file) - { - // Get the expiration time - $expires = (int) substr($file, strrpos($file, '~') + 1); - - // Expirations of 0 are "never expire" - return ($expires !== 0 AND $expires <= time()); - } - -} // End Cache File Driver \ No newline at end of file + // Expirations of 0 are "never expire" + return ($expires !== 0 and $expires <= time()); + } +} +// End Cache File Driver diff --git a/lib/kohana/system/libraries/drivers/Cache/Memcache.php b/lib/kohana/system/libraries/drivers/Cache/Memcache.php index d801de9..9aa8f72 100644 --- a/lib/kohana/system/libraries/drivers/Cache/Memcache.php +++ b/lib/kohana/system/libraries/drivers/Cache/Memcache.php @@ -1,4 +1,12 @@ -backend = new Memcache(); + $this->flags = Kohana::config('cache_memcache.compression') ? MEMCACHE_COMPRESSED : false; - $this->backend = new Memcache; - $this->flags = Kohana::config('cache_memcache.compression') ? MEMCACHE_COMPRESSED : FALSE; + $servers = Kohana::config('cache_memcache.servers'); - $servers = Kohana::config('cache_memcache.servers'); + foreach ($servers as $server) { + // Make sure all required keys are set + $server += array('host' => '127.0.0.1', 'port' => 11211, 'persistent' => false); - foreach ($servers as $server) - { - // Make sure all required keys are set - $server += array('host' => '127.0.0.1', 'port' => 11211, 'persistent' => FALSE); + // Add the server to the pool + $this->backend->addServer($server['host'], $server['port'], (bool) $server['persistent']) + or Kohana::log('error', 'Cache: Connection failed: ' . $server['host']); + } - // Add the server to the pool - $this->backend->addServer($server['host'], $server['port'], (bool) $server['persistent']) - or Kohana::log('error', 'Cache: Connection failed: '.$server['host']); - } + // Load tags + self::$tags = $this->backend->get(self::TAGS_KEY); - // Load tags - self::$tags = $this->backend->get(self::TAGS_KEY); + if (! is_array(self::$tags)) { + // Create a new tags array + self::$tags = array(); - if ( ! is_array(self::$tags)) - { - // Create a new tags array - self::$tags = array(); + // Tags have been created + self::$tags_changed = true; + } + } - // Tags have been created - self::$tags_changed = TRUE; - } - } + public function __destruct() + { + if (self::$tags_changed === true) { + // Save the tags + $this->backend->set(self::TAGS_KEY, self::$tags, $this->flags, 0); - public function __destruct() - { - if (self::$tags_changed === TRUE) - { - // Save the tags - $this->backend->set(self::TAGS_KEY, self::$tags, $this->flags, 0); + // Tags are now unchanged + self::$tags_changed = false; + } + } - // Tags are now unchanged - self::$tags_changed = FALSE; - } - } + public function find($tag) + { + if (isset(self::$tags[$tag]) and $results = $this->backend->get(self::$tags[$tag])) { + // Return all the found caches + return $results; + } else { + // No matching tags + return array(); + } + } - public function find($tag) - { - if (isset(self::$tags[$tag]) AND $results = $this->backend->get(self::$tags[$tag])) - { - // Return all the found caches - return $results; - } - else - { - // No matching tags - return array(); - } - } + public function get($id) + { + return (($return = $this->backend->get($id)) === false) ? null : $return; + } - public function get($id) - { - return (($return = $this->backend->get($id)) === FALSE) ? NULL : $return; - } + public function set($id, $data, array $tags = null, $lifetime) + { + if (! empty($tags)) { + // Tags will be changed + self::$tags_changed = true; - public function set($id, $data, array $tags = NULL, $lifetime) - { - if ( ! empty($tags)) - { - // Tags will be changed - self::$tags_changed = TRUE; + foreach ($tags as $tag) { + // Add the id to each tag + self::$tags[$tag][$id] = $id; + } + } - foreach ($tags as $tag) - { - // Add the id to each tag - self::$tags[$tag][$id] = $id; - } - } + if ($lifetime !== 0) { + // Memcache driver expects unix timestamp + $lifetime += time(); + } - if ($lifetime !== 0) - { - // Memcache driver expects unix timestamp - $lifetime += time(); - } + // Set a new value + return $this->backend->set($id, $data, $this->flags, $lifetime); + } - // Set a new value - return $this->backend->set($id, $data, $this->flags, $lifetime); - } + public function delete($id, $tag = false) + { + // Tags will be changed + self::$tags_changed = true; - public function delete($id, $tag = FALSE) - { - // Tags will be changed - self::$tags_changed = TRUE; + if ($id === true) { + if ($status = $this->backend->flush()) { + // Remove all tags, all items have been deleted + self::$tags = array(); - if ($id === TRUE) - { - if ($status = $this->backend->flush()) - { - // Remove all tags, all items have been deleted - self::$tags = array(); + // We must sleep after flushing, or overwriting will not work! + // @see http://php.net/manual/en/function.memcache-flush.php#81420 + sleep(1); + } - // We must sleep after flushing, or overwriting will not work! - // @see http://php.net/manual/en/function.memcache-flush.php#81420 - sleep(1); - } + return $status; + } elseif ($tag === true) { + if (isset(self::$tags[$id])) { + foreach (self::$tags[$id] as $_id) { + // Delete each id in the tag + $this->backend->delete($_id); + } - return $status; - } - elseif ($tag === TRUE) - { - if (isset(self::$tags[$id])) - { - foreach (self::$tags[$id] as $_id) - { - // Delete each id in the tag - $this->backend->delete($_id); - } + // Delete the tag + unset(self::$tags[$id]); + } - // Delete the tag - unset(self::$tags[$id]); - } + return true; + } else { + foreach (self::$tags as $tag => $_ids) { + if (isset(self::$tags[$tag][$id])) { + // Remove the id from the tags + unset(self::$tags[$tag][$id]); + } + } - return TRUE; - } - else - { - foreach (self::$tags as $tag => $_ids) - { - if (isset(self::$tags[$tag][$id])) - { - // Remove the id from the tags - unset(self::$tags[$tag][$id]); - } - } + return $this->backend->delete($id); + } + } - return $this->backend->delete($id); - } - } + public function delete_expired() + { + // Tags will be changed + self::$tags_changed = true; - public function delete_expired() - { - // Tags will be changed - self::$tags_changed = TRUE; + foreach (self::$tags as $tag => $_ids) { + foreach ($_ids as $id) { + if (! $this->backend->get($id)) { + // This id has disappeared, delete it from the tags + unset(self::$tags[$tag][$id]); + } + } - foreach (self::$tags as $tag => $_ids) - { - foreach ($_ids as $id) - { - if ( ! $this->backend->get($id)) - { - // This id has disappeared, delete it from the tags - unset(self::$tags[$tag][$id]); - } - } + if (empty(self::$tags[$tag])) { + // The tag no longer has any valid ids + unset(self::$tags[$tag]); + } + } - if (empty(self::$tags[$tag])) - { - // The tag no longer has any valid ids - unset(self::$tags[$tag]); - } - } - - // Memcache handles garbage collection internally - return TRUE; - } - -} // End Cache Memcache Driver + // Memcache handles garbage collection internally + return true; + } +} +// End Cache Memcache Driver diff --git a/lib/kohana/system/libraries/drivers/Cache/Sqlite.php b/lib/kohana/system/libraries/drivers/Cache/Sqlite.php index 9458d85..4749014 100644 --- a/lib/kohana/system/libraries/drivers/Cache/Sqlite.php +++ b/lib/kohana/system/libraries/drivers/Cache/Sqlite.php @@ -1,4 +1,12 @@ -db = new SQLiteDatabase($filename, '0666', $error); - // Open up an instance of the database - $this->db = new SQLiteDatabase($filename, '0666', $error); + // Throw an exception if there's an error + if (! empty($error)) { + throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error)); + } - // Throw an exception if there's an error - if ( ! empty($error)) - throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error)); + $query = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'caches'"; + $tables = $this->db->query($query, SQLITE_BOTH, $error); - $query = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'caches'"; - $tables = $this->db->query($query, SQLITE_BOTH, $error); + // Throw an exception if there's an error + if (! empty($error)) { + throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error)); + } - // Throw an exception if there's an error - if ( ! empty($error)) - throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error)); + if ($tables->numRows() == 0) { + Kohana::log('error', 'Cache: Initializing new SQLite cache database'); - if ($tables->numRows() == 0) - { - Kohana::log('error', 'Cache: Initializing new SQLite cache database'); + // Issue a CREATE TABLE command + $this->db->unbufferedQuery(Kohana::config('cache_sqlite.schema')); + } + } - // Issue a CREATE TABLE command - $this->db->unbufferedQuery(Kohana::config('cache_sqlite.schema')); - } - } + /** + * Checks if a cache id is already set. + * + * @param string cache id + * @return boolean + */ + public function exists($id) + { + // Find the id that matches + $query = "SELECT id FROM caches WHERE id = '$id'"; - /** - * Checks if a cache id is already set. - * - * @param string cache id - * @return boolean - */ - public function exists($id) - { - // Find the id that matches - $query = "SELECT id FROM caches WHERE id = '$id'"; + return ($this->db->query($query)->numRows() > 0); + } - return ($this->db->query($query)->numRows() > 0); - } + /** + * Sets a cache item to the given data, tags, and lifetime. + * + * @param string cache id to set + * @param string data in the cache + * @param array cache tags + * @param integer lifetime + * @return bool + */ + public function set($id, $data, array $tags = null, $lifetime) + { + // Serialize and escape the data + $data = sqlite_escape_string(serialize($data)); - /** - * Sets a cache item to the given data, tags, and lifetime. - * - * @param string cache id to set - * @param string data in the cache - * @param array cache tags - * @param integer lifetime - * @return bool - */ - public function set($id, $data, array $tags = NULL, $lifetime) - { - // Serialize and escape the data - $data = sqlite_escape_string(serialize($data)); + if (! empty($tags)) { + // Escape the tags, adding brackets so the tag can be explicitly matched + $tags = sqlite_escape_string('<' . implode('>,<', $tags) . '>'); + } - if ( ! empty($tags)) - { - // Escape the tags, adding brackets so the tag can be explicitly matched - $tags = sqlite_escape_string('<'.implode('>,<', $tags).'>'); - } + // Cache Sqlite driver expects unix timestamp + if ($lifetime !== 0) { + $lifetime += time(); + } - // Cache Sqlite driver expects unix timestamp - if ($lifetime !== 0) - { - $lifetime += time(); - } + $query = $this->exists($id) + ? "UPDATE caches SET tags = '$tags', expiration = '$lifetime', cache = '$data' WHERE id = '$id'" + : "INSERT INTO caches VALUES('$id', '$tags', '$lifetime', '$data')"; - $query = $this->exists($id) - ? "UPDATE caches SET tags = '$tags', expiration = '$lifetime', cache = '$data' WHERE id = '$id'" - : "INSERT INTO caches VALUES('$id', '$tags', '$lifetime', '$data')"; + // Run the query + $this->db->unbufferedQuery($query, SQLITE_BOTH, $error); - // Run the query - $this->db->unbufferedQuery($query, SQLITE_BOTH, $error); + if (! empty($error)) { + self::log_error($error); + return false; + } else { + return true; + } + } - if ( ! empty($error)) - { - self::log_error($error); - return FALSE; - } - else - { - return TRUE; - } - } + /** + * Finds an array of ids for a given tag. + * + * @param string tag name + * @return array of ids that match the tag + */ + public function find($tag) + { + $query = "SELECT id,cache FROM caches WHERE tags LIKE '%<{$tag}>%'"; + $query = $this->db->query($query, SQLITE_BOTH, $error); - /** - * Finds an array of ids for a given tag. - * - * @param string tag name - * @return array of ids that match the tag - */ - public function find($tag) - { - $query = "SELECT id,cache FROM caches WHERE tags LIKE '%<{$tag}>%'"; - $query = $this->db->query($query, SQLITE_BOTH, $error); + // An array will always be returned + $result = array(); - // An array will always be returned - $result = array(); + if (! empty($error)) { + self::log_error($error); + } elseif ($query->numRows() > 0) { + // Disable notices for unserializing + $ER = error_reporting(~E_NOTICE); - if ( ! empty($error)) - { - self::log_error($error); - } - elseif ($query->numRows() > 0) - { - // Disable notices for unserializing - $ER = error_reporting(~E_NOTICE); + while ($row = $query->fetchObject()) { + // Add each cache to the array + $result[$row->id] = unserialize($row->cache); + } - while ($row = $query->fetchObject()) - { - // Add each cache to the array - $result[$row->id] = unserialize($row->cache); - } + // Turn notices back on + error_reporting($ER); + } - // Turn notices back on - error_reporting($ER); - } + return $result; + } - return $result; - } + /** + * Fetches a cache item. This will delete the item if it is expired or if + * the hash does not match the stored hash. + * + * @param string cache id + * @return mixed|NULL + */ + public function get($id) + { + $query = "SELECT id, expiration, cache FROM caches WHERE id = '$id' LIMIT 0, 1"; + $query = $this->db->query($query, SQLITE_BOTH, $error); - /** - * Fetches a cache item. This will delete the item if it is expired or if - * the hash does not match the stored hash. - * - * @param string cache id - * @return mixed|NULL - */ - public function get($id) - { - $query = "SELECT id, expiration, cache FROM caches WHERE id = '$id' LIMIT 0, 1"; - $query = $this->db->query($query, SQLITE_BOTH, $error); + if (! empty($error)) { + self::log_error($error); + } elseif ($cache = $query->fetchObject()) { + // Make sure the expiration is valid and that the hash matches + if ($cache->expiration != 0 and $cache->expiration <= time()) { + // Cache is not valid, delete it now + $this->delete($cache->id); + } else { + // Disable notices for unserializing + $ER = error_reporting(~E_NOTICE); - if ( ! empty($error)) - { - self::log_error($error); - } - elseif ($cache = $query->fetchObject()) - { - // Make sure the expiration is valid and that the hash matches - if ($cache->expiration != 0 AND $cache->expiration <= time()) - { - // Cache is not valid, delete it now - $this->delete($cache->id); - } - else - { - // Disable notices for unserializing - $ER = error_reporting(~E_NOTICE); - - // Return the valid cache data - $data = $cache->cache; + // Return the valid cache data + $data = $cache->cache; - // Turn notices back on - error_reporting($ER); - } - } + // Turn notices back on + error_reporting($ER); + } + } - // No valid cache found - return NULL; - } + // No valid cache found + return null; + } - /** - * Deletes a cache item by id or tag - * - * @param string cache id or tag, or TRUE for "all items" - * @param bool delete a tag - * @return bool - */ - public function delete($id, $tag = FALSE) - { - if ($id === TRUE) - { - // Delete all caches - $where = '1'; - } - elseif ($tag === TRUE) - { - // Delete by tag - $where = "tags LIKE '%<{$id}>%'"; - } - else - { - // Delete by id - $where = "id = '$id'"; - } + /** + * Deletes a cache item by id or tag + * + * @param string cache id or tag, or TRUE for "all items" + * @param bool delete a tag + * @return bool + */ + public function delete($id, $tag = false) + { + if ($id === true) { + // Delete all caches + $where = '1'; + } elseif ($tag === true) { + // Delete by tag + $where = "tags LIKE '%<{$id}>%'"; + } else { + // Delete by id + $where = "id = '$id'"; + } - $this->db->unbufferedQuery('DELETE FROM caches WHERE '.$where, SQLITE_BOTH, $error); + $this->db->unbufferedQuery('DELETE FROM caches WHERE ' . $where, SQLITE_BOTH, $error); - if ( ! empty($error)) - { - self::log_error($error); - return FALSE; - } - else - { - return TRUE; - } - } + if (! empty($error)) { + self::log_error($error); + return false; + } else { + return true; + } + } - /** - * Deletes all cache files that are older than the current time. - */ - public function delete_expired() - { - // Delete all expired caches - $query = 'DELETE FROM caches WHERE expiration != 0 AND expiration <= '.time(); + /** + * Deletes all cache files that are older than the current time. + */ + public function delete_expired() + { + // Delete all expired caches + $query = 'DELETE FROM caches WHERE expiration != 0 AND expiration <= ' . time(); - $this->db->unbufferedQuery($query); + $this->db->unbufferedQuery($query); - return TRUE; - } - -} // End Cache SQLite Driver \ No newline at end of file + return true; + } +} +// End Cache SQLite Driver diff --git a/lib/kohana/system/libraries/drivers/Cache/Xcache.php b/lib/kohana/system/libraries/drivers/Cache/Xcache.php index 6254bbb..c3b0c48 100644 --- a/lib/kohana/system/libraries/drivers/Cache/Xcache.php +++ b/lib/kohana/system/libraries/drivers/Cache/Xcache.php @@ -1,4 +1,12 @@ -auth(); + $result = true; + for ($i = 0, $max = xcache_count(XC_TYPE_VAR); $i < $max; $i++) { + if (xcache_clear_cache(XC_TYPE_VAR, $i) !== null) { + $result = false; + break; + } + } - return FALSE; - } - else - { - // Do the login - $this->auth(); - $result = TRUE; - for ($i = 0, $max = xcache_count(XC_TYPE_VAR); $i < $max; $i++) - { - if (xcache_clear_cache(XC_TYPE_VAR, $i) !== NULL) - { - $result = FALSE; - break; - } - } + // Undo the login + $this->auth(true); + return $result; + } - // Undo the login - $this->auth(TRUE); - return $result; - } + return true; + } - return TRUE; - } + public function delete_expired() + { + return true; + } - public function delete_expired() - { - return TRUE; - } + private function auth($reverse = false) + { + static $backup = array(); - private function auth($reverse = FALSE) - { - static $backup = array(); + $keys = array('PHP_AUTH_USER', 'PHP_AUTH_PW'); - $keys = array('PHP_AUTH_USER', 'PHP_AUTH_PW'); + foreach ($keys as $key) { + if ($reverse) { + if (isset($backup[$key])) { + $_SERVER[$key] = $backup[$key]; + unset($backup[$key]); + } else { + unset($_SERVER[$key]); + } + } else { + $value = getenv($key); - foreach ($keys as $key) - { - if ($reverse) - { - if (isset($backup[$key])) - { - $_SERVER[$key] = $backup[$key]; - unset($backup[$key]); - } - else - { - unset($_SERVER[$key]); - } - } - else - { - $value = getenv($key); + if (! empty($value)) { + $backup[$key] = $value; + } - if ( ! empty($value)) - { - $backup[$key] = $value; - } - - $_SERVER[$key] = Kohana::config('cache_xcache.'.$key); - } - } - } - -} // End Cache Xcache Driver + $_SERVER[$key] = Kohana::config('cache_xcache.' . $key); + } + } + } +} +// End Cache Xcache Driver diff --git a/lib/kohana/system/libraries/drivers/Captcha.php b/lib/kohana/system/libraries/drivers/Captcha.php index a4343e1..51bcff3 100644 --- a/lib/kohana/system/libraries/drivers/Captcha.php +++ b/lib/kohana/system/libraries/drivers/Captcha.php @@ -1,4 +1,11 @@ -response = $this->generate_challenge(); - /** - * Constructs a new challenge. - * - * @return void - */ - public function __construct() - { - // Generate a new challenge - $this->response = $this->generate_challenge(); + // Store the correct Captcha response in a session + Event::add('system.post_controller', array($this, 'update_response_session')); + } - // Store the correct Captcha response in a session - Event::add('system.post_controller', array($this, 'update_response_session')); - } + /** + * Generate a new Captcha challenge. + * + * @return string the challenge answer + */ + abstract public function generate_challenge(); - /** - * Generate a new Captcha challenge. - * - * @return string the challenge answer - */ - abstract public function generate_challenge(); + /** + * Output the Captcha challenge. + * + * @param boolean html output + * @return mixed the rendered Captcha (e.g. an image, riddle, etc.) + */ + abstract public function render($html); - /** - * Output the Captcha challenge. - * - * @param boolean html output - * @return mixed the rendered Captcha (e.g. an image, riddle, etc.) - */ - abstract public function render($html); + /** + * Stores the response for the current Captcha challenge in a session so it is available + * on the next page load for Captcha::valid(). This method is called after controller + * execution (in the system.post_controller event) in order not to overwrite itself too soon. + * + * @return void + */ + public function update_response_session() + { + Session::instance()->set('captcha_response', sha1(strtoupper($this->response))); + } - /** - * Stores the response for the current Captcha challenge in a session so it is available - * on the next page load for Captcha::valid(). This method is called after controller - * execution (in the system.post_controller event) in order not to overwrite itself too soon. - * - * @return void - */ - public function update_response_session() - { - Session::instance()->set('captcha_response', sha1(strtoupper($this->response))); - } + /** + * Validates a Captcha response from a user. + * + * @param string captcha response + * @return boolean + */ + public function valid($response) + { + return (sha1(strtoupper($response)) === Session::instance()->get('captcha_response')); + } - /** - * Validates a Captcha response from a user. - * - * @param string captcha response - * @return boolean - */ - public function valid($response) - { - return (sha1(strtoupper($response)) === Session::instance()->get('captcha_response')); - } + /** + * Returns the image type. + * + * @param string filename + * @return string|FALSE image type ("png", "gif" or "jpeg") + */ + public function image_type($filename) + { + switch (strtolower(substr(strrchr($filename, '.'), 1))) { + case 'png': + return 'png'; - /** - * Returns the image type. - * - * @param string filename - * @return string|FALSE image type ("png", "gif" or "jpeg") - */ - public function image_type($filename) - { - switch (strtolower(substr(strrchr($filename, '.'), 1))) - { - case 'png': - return 'png'; + case 'gif': + return 'gif'; - case 'gif': - return 'gif'; + case 'jpg': + case 'jpeg': + // Return "jpeg" and not "jpg" because of the GD2 function names + return 'jpeg'; - case 'jpg': - case 'jpeg': - // Return "jpeg" and not "jpg" because of the GD2 function names - return 'jpeg'; + default: + return false; + } + } - default: - return FALSE; - } - } + /** + * Creates an image resource with the dimensions specified in config. + * If a background image is supplied, the image dimensions are used. + * + * @throws Kohana_Exception if no GD2 support + * @param string path to the background image file + * @return void + */ + public function image_create($background = null) + { + // Check for GD2 support + if (! function_exists('imagegd2')) { + throw new Kohana_Exception('captcha.requires_GD2'); + } - /** - * Creates an image resource with the dimensions specified in config. - * If a background image is supplied, the image dimensions are used. - * - * @throws Kohana_Exception if no GD2 support - * @param string path to the background image file - * @return void - */ - public function image_create($background = NULL) - { - // Check for GD2 support - if ( ! function_exists('imagegd2')) - throw new Kohana_Exception('captcha.requires_GD2'); + // Create a new image (black) + $this->image = imagecreatetruecolor(Captcha::$config['width'], Captcha::$config['height']); - // Create a new image (black) - $this->image = imagecreatetruecolor(Captcha::$config['width'], Captcha::$config['height']); + // Use a background image + if (! empty($background)) { + // Create the image using the right function for the filetype + $function = 'imagecreatefrom' . $this->image_type($background); + $this->background_image = $function($background); - // Use a background image - if ( ! empty($background)) - { - // Create the image using the right function for the filetype - $function = 'imagecreatefrom'.$this->image_type($background); - $this->background_image = $function($background); + // Resize the image if needed + if ( + imagesx($this->background_image) !== Captcha::$config['width'] + or imagesy($this->background_image) !== Captcha::$config['height'] + ) { + imagecopyresampled( + $this->image, + $this->background_image, + 0, + 0, + 0, + 0, + Captcha::$config['width'], + Captcha::$config['height'], + imagesx($this->background_image), + imagesy($this->background_image) + ); + } - // Resize the image if needed - if (imagesx($this->background_image) !== Captcha::$config['width'] - OR imagesy($this->background_image) !== Captcha::$config['height']) - { - imagecopyresampled - ( - $this->image, $this->background_image, 0, 0, 0, 0, - Captcha::$config['width'], Captcha::$config['height'], - imagesx($this->background_image), imagesy($this->background_image) - ); - } + // Free up resources + imagedestroy($this->background_image); + } + } - // Free up resources - imagedestroy($this->background_image); - } - } + /** + * Fills the background with a gradient. + * + * @param resource gd image color identifier for start color + * @param resource gd image color identifier for end color + * @param string direction: 'horizontal' or 'vertical', 'random' by default + * @return void + */ + public function image_gradient($color1, $color2, $direction = null) + { + $directions = array('horizontal', 'vertical'); - /** - * Fills the background with a gradient. - * - * @param resource gd image color identifier for start color - * @param resource gd image color identifier for end color - * @param string direction: 'horizontal' or 'vertical', 'random' by default - * @return void - */ - public function image_gradient($color1, $color2, $direction = NULL) - { - $directions = array('horizontal', 'vertical'); + // Pick a random direction if needed + if (! in_array($direction, $directions)) { + $direction = $directions[array_rand($directions)]; - // Pick a random direction if needed - if ( ! in_array($direction, $directions)) - { - $direction = $directions[array_rand($directions)]; + // Switch colors + if (mt_rand(0, 1) === 1) { + $temp = $color1; + $color1 = $color2; + $color2 = $temp; + } + } - // Switch colors - if (mt_rand(0, 1) === 1) - { - $temp = $color1; - $color1 = $color2; - $color2 = $temp; - } - } + // Extract RGB values + $color1 = imagecolorsforindex($this->image, $color1); + $color2 = imagecolorsforindex($this->image, $color2); - // Extract RGB values - $color1 = imagecolorsforindex($this->image, $color1); - $color2 = imagecolorsforindex($this->image, $color2); + // Preparations for the gradient loop + $steps = ($direction === 'horizontal') ? Captcha::$config['width'] : Captcha::$config['height']; - // Preparations for the gradient loop - $steps = ($direction === 'horizontal') ? Captcha::$config['width'] : Captcha::$config['height']; + $r1 = ($color1['red'] - $color2['red']) / $steps; + $g1 = ($color1['green'] - $color2['green']) / $steps; + $b1 = ($color1['blue'] - $color2['blue']) / $steps; - $r1 = ($color1['red'] - $color2['red']) / $steps; - $g1 = ($color1['green'] - $color2['green']) / $steps; - $b1 = ($color1['blue'] - $color2['blue']) / $steps; + if ($direction === 'horizontal') { + $x1 =& $i; + $y1 = 0; + $x2 =& $i; + $y2 = Captcha::$config['height']; + } else { + $x1 = 0; + $y1 =& $i; + $x2 = Captcha::$config['width']; + $y2 =& $i; + } - if ($direction === 'horizontal') - { - $x1 =& $i; - $y1 = 0; - $x2 =& $i; - $y2 = Captcha::$config['height']; - } - else - { - $x1 = 0; - $y1 =& $i; - $x2 = Captcha::$config['width']; - $y2 =& $i; - } + // Execute the gradient loop + for ($i = 0; $i <= $steps; $i++) { + $r2 = $color1['red'] - floor($i * $r1); + $g2 = $color1['green'] - floor($i * $g1); + $b2 = $color1['blue'] - floor($i * $b1); + $color = imagecolorallocate($this->image, $r2, $g2, $b2); - // Execute the gradient loop - for ($i = 0; $i <= $steps; $i++) - { - $r2 = $color1['red'] - floor($i * $r1); - $g2 = $color1['green'] - floor($i * $g1); - $b2 = $color1['blue'] - floor($i * $b1); - $color = imagecolorallocate($this->image, $r2, $g2, $b2); + imageline($this->image, $x1, $y1, $x2, $y2, $color); + } + } - imageline($this->image, $x1, $y1, $x2, $y2, $color); - } - } + /** + * Returns the img html element or outputs the image to the browser. + * + * @param boolean html output + * @return mixed html string or void + */ + public function image_render($html) + { + // Output html element + if ($html) { + return 'Captcha'; + } - /** - * Returns the img html element or outputs the image to the browser. - * - * @param boolean html output - * @return mixed html string or void - */ - public function image_render($html) - { - // Output html element - if ($html) - return 'Captcha'; + // Send the correct HTTP header + header('Content-Type: image/' . $this->image_type); - // Send the correct HTTP header - header('Content-Type: image/'.$this->image_type); + // Pick the correct output function + $function = 'image' . $this->image_type; + $function($this->image); - // Pick the correct output function - $function = 'image'.$this->image_type; - $function($this->image); - - // Free up resources - imagedestroy($this->image); - } - -} // End Captcha Driver \ No newline at end of file + // Free up resources + imagedestroy($this->image); + } +} +// End Captcha Driver diff --git a/lib/kohana/system/libraries/drivers/Captcha/Alpha.php b/lib/kohana/system/libraries/drivers/Captcha/Alpha.php index 2779580..02c4a00 100644 --- a/lib/kohana/system/libraries/drivers/Captcha/Alpha.php +++ b/lib/kohana/system/libraries/drivers/Captcha/Alpha.php @@ -1,4 +1,12 @@ -image + $this->image_create(Captcha::$config['background']); - /** - * Outputs the Captcha image. - * - * @param boolean html output - * @return mixed - */ - public function render($html) - { - // Creates $this->image - $this->image_create(Captcha::$config['background']); + // Add a random gradient + if (empty(Captcha::$config['background'])) { + $color1 = imagecolorallocate($this->image, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100)); + $color2 = imagecolorallocate($this->image, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100)); + $this->image_gradient($color1, $color2); + } - // Add a random gradient - if (empty(Captcha::$config['background'])) - { - $color1 = imagecolorallocate($this->image, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100)); - $color2 = imagecolorallocate($this->image, mt_rand(0, 100), mt_rand(0, 100), mt_rand(0, 100)); - $this->image_gradient($color1, $color2); - } + // Add a few random circles + for ($i = 0, $count = mt_rand(10, Captcha::$config['complexity'] * 3); $i < $count; $i++) { + $color = imagecolorallocatealpha($this->image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(80, 120)); + $size = mt_rand(5, Captcha::$config['height'] / 3); + imagefilledellipse($this->image, mt_rand(0, Captcha::$config['width']), mt_rand(0, Captcha::$config['height']), $size, $size, $color); + } - // Add a few random circles - for ($i = 0, $count = mt_rand(10, Captcha::$config['complexity'] * 3); $i < $count; $i++) - { - $color = imagecolorallocatealpha($this->image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(0, 255), mt_rand(80, 120)); - $size = mt_rand(5, Captcha::$config['height'] / 3); - imagefilledellipse($this->image, mt_rand(0, Captcha::$config['width']), mt_rand(0, Captcha::$config['height']), $size, $size, $color); - } + // Calculate character font-size and spacing + $default_size = min(Captcha::$config['width'], Captcha::$config['height'] * 2) / strlen($this->response); + $spacing = (int) (Captcha::$config['width'] * 0.9 / strlen($this->response)); - // Calculate character font-size and spacing - $default_size = min(Captcha::$config['width'], Captcha::$config['height'] * 2) / strlen($this->response); - $spacing = (int) (Captcha::$config['width'] * 0.9 / strlen($this->response)); + // Background alphabetic character attributes + $color_limit = mt_rand(96, 160); + $chars = 'ABEFGJKLPQRTVY'; - // Background alphabetic character attributes - $color_limit = mt_rand(96, 160); - $chars = 'ABEFGJKLPQRTVY'; + // Draw each Captcha character with varying attributes + for ($i = 0, $strlen = strlen($this->response); $i < $strlen; $i++) { + // Use different fonts if available + $font = Captcha::$config['fontpath'] . Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])]; - // Draw each Captcha character with varying attributes - for ($i = 0, $strlen = strlen($this->response); $i < $strlen; $i++) - { - // Use different fonts if available - $font = Captcha::$config['fontpath'].Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])]; + $angle = mt_rand(-40, 20); + // Scale the character size on image height + $size = $default_size / 10 * mt_rand(8, 12); + $box = imageftbbox($size, $angle, $font, $this->response[$i]); - $angle = mt_rand(-40, 20); - // Scale the character size on image height - $size = $default_size / 10 * mt_rand(8, 12); - $box = imageftbbox($size, $angle, $font, $this->response[$i]); + // Calculate character starting coordinates + $x = $spacing / 4 + $i * $spacing; + $y = Captcha::$config['height'] / 2 + ($box[2] - $box[5]) / 4; - // Calculate character starting coordinates - $x = $spacing / 4 + $i * $spacing; - $y = Captcha::$config['height'] / 2 + ($box[2] - $box[5]) / 4; + // Draw captcha text character + // Allocate random color, size and rotation attributes to text + $color = imagecolorallocate($this->image, mt_rand(150, 255), mt_rand(200, 255), mt_rand(0, 255)); - // Draw captcha text character - // Allocate random color, size and rotation attributes to text - $color = imagecolorallocate($this->image, mt_rand(150, 255), mt_rand(200, 255), mt_rand(0, 255)); + // Write text character to image + imagefttext($this->image, $size, $angle, $x, $y, $color, $font, $this->response[$i]); - // Write text character to image - imagefttext($this->image, $size, $angle, $x, $y, $color, $font, $this->response[$i]); + // Draw "ghost" alphabetic character + $text_color = imagecolorallocatealpha( + $this->image, + mt_rand($color_limit + 8, 255), + mt_rand($color_limit + 8, 255), + mt_rand($color_limit + 8, 255), + mt_rand(70, 120) + ); + $char = $chars[mt_rand(0, 14)]; + imagettftext($this->image, $size * 2, mt_rand(-45, 45), ($x - (mt_rand(5, 10))), ($y + (mt_rand(5, 10))), $text_color, $font, $char); + } - // Draw "ghost" alphabetic character - $text_color = imagecolorallocatealpha($this->image, mt_rand($color_limit + 8, 255), mt_rand($color_limit + 8, 255), mt_rand($color_limit + 8, 255), mt_rand(70, 120)); - $char = $chars[mt_rand(0, 14)]; - imagettftext($this->image, $size * 2, mt_rand(-45, 45), ($x - (mt_rand(5, 10))), ($y + (mt_rand(5, 10))), $text_color, $font, $char); - } - - // Output - return $this->image_render($html); - } - -} // End Captcha Alpha Driver Class \ No newline at end of file + // Output + return $this->image_render($html); + } +} +// End Captcha Alpha Driver Class diff --git a/lib/kohana/system/libraries/drivers/Captcha/Basic.php b/lib/kohana/system/libraries/drivers/Captcha/Basic.php index d212e72..cac26bf 100644 --- a/lib/kohana/system/libraries/drivers/Captcha/Basic.php +++ b/lib/kohana/system/libraries/drivers/Captcha/Basic.php @@ -1,4 +1,12 @@ -image + $this->image_create(Captcha::$config['background']); - /** - * Outputs the Captcha image. - * - * @param boolean html output - * @return mixed - */ - public function render($html) - { - // Creates $this->image - $this->image_create(Captcha::$config['background']); + // Add a random gradient + if (empty(Captcha::$config['background'])) { + $color1 = imagecolorallocate($this->image, mt_rand(200, 255), mt_rand(200, 255), mt_rand(150, 255)); + $color2 = imagecolorallocate($this->image, mt_rand(200, 255), mt_rand(200, 255), mt_rand(150, 255)); + $this->image_gradient($color1, $color2); + } - // Add a random gradient - if (empty(Captcha::$config['background'])) - { - $color1 = imagecolorallocate($this->image, mt_rand(200, 255), mt_rand(200, 255), mt_rand(150, 255)); - $color2 = imagecolorallocate($this->image, mt_rand(200, 255), mt_rand(200, 255), mt_rand(150, 255)); - $this->image_gradient($color1, $color2); - } + // Add a few random lines + for ($i = 0, $count = mt_rand(5, Captcha::$config['complexity'] * 4); $i < $count; $i++) { + $color = imagecolorallocatealpha($this->image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(100, 255), mt_rand(50, 120)); + imageline($this->image, mt_rand(0, Captcha::$config['width']), 0, mt_rand(0, Captcha::$config['width']), Captcha::$config['height'], $color); + } - // Add a few random lines - for ($i = 0, $count = mt_rand(5, Captcha::$config['complexity'] * 4); $i < $count; $i++) - { - $color = imagecolorallocatealpha($this->image, mt_rand(0, 255), mt_rand(0, 255), mt_rand(100, 255), mt_rand(50, 120)); - imageline($this->image, mt_rand(0, Captcha::$config['width']), 0, mt_rand(0, Captcha::$config['width']), Captcha::$config['height'], $color); - } + // Calculate character font-size and spacing + $default_size = min(Captcha::$config['width'], Captcha::$config['height'] * 2) / (strlen($this->response) + 1); + $spacing = (int) (Captcha::$config['width'] * 0.9 / strlen($this->response)); - // Calculate character font-size and spacing - $default_size = min(Captcha::$config['width'], Captcha::$config['height'] * 2) / (strlen($this->response) + 1); - $spacing = (int) (Captcha::$config['width'] * 0.9 / strlen($this->response)); + // Draw each Captcha character with varying attributes + for ($i = 0, $strlen = strlen($this->response); $i < $strlen; $i++) { + // Use different fonts if available + $font = Captcha::$config['fontpath'] . Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])]; - // Draw each Captcha character with varying attributes - for ($i = 0, $strlen = strlen($this->response); $i < $strlen; $i++) - { - // Use different fonts if available - $font = Captcha::$config['fontpath'].Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])]; + // Allocate random color, size and rotation attributes to text + $color = imagecolorallocate($this->image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150)); + $angle = mt_rand(-40, 20); - // Allocate random color, size and rotation attributes to text - $color = imagecolorallocate($this->image, mt_rand(0, 150), mt_rand(0, 150), mt_rand(0, 150)); - $angle = mt_rand(-40, 20); + // Scale the character size on image height + $size = $default_size / 10 * mt_rand(8, 12); + $box = imageftbbox($size, $angle, $font, $this->response[$i]); - // Scale the character size on image height - $size = $default_size / 10 * mt_rand(8, 12); - $box = imageftbbox($size, $angle, $font, $this->response[$i]); + // Calculate character starting coordinates + $x = $spacing / 4 + $i * $spacing; + $y = Captcha::$config['height'] / 2 + ($box[2] - $box[5]) / 4; - // Calculate character starting coordinates - $x = $spacing / 4 + $i * $spacing; - $y = Captcha::$config['height'] / 2 + ($box[2] - $box[5]) / 4; + // Write text character to image + imagefttext($this->image, $size, $angle, $x, $y, $color, $font, $this->response[$i]); + } - // Write text character to image - imagefttext($this->image, $size, $angle, $x, $y, $color, $font, $this->response[$i]); - } - - // Output - return $this->image_render($html); - } - -} // End Captcha Basic Driver Class \ No newline at end of file + // Output + return $this->image_render($html); + } +} +// End Captcha Basic Driver Class diff --git a/lib/kohana/system/libraries/drivers/Captcha/Black.php b/lib/kohana/system/libraries/drivers/Captcha/Black.php index 6a2e222..8155972 100644 --- a/lib/kohana/system/libraries/drivers/Captcha/Black.php +++ b/lib/kohana/system/libraries/drivers/Captcha/Black.php @@ -1,4 +1,12 @@ -image_create(Captcha::$config['background']); - /** - * Outputs the Captcha image. - * - * @param boolean html output - * @return mixed - */ - public function render($html) - { - // Creates a black image to start from - $this->image_create(Captcha::$config['background']); + // Add random white/gray arcs, amount depends on complexity setting + $count = (Captcha::$config['width'] + Captcha::$config['height']) / 2; + $count = $count / 5 * min(10, Captcha::$config['complexity']); + for ($i = 0; $i < $count; $i++) { + imagesetthickness($this->image, mt_rand(1, 2)); + $color = imagecolorallocatealpha($this->image, 255, 255, 255, mt_rand(0, 120)); + imagearc( + $this->image, + mt_rand( + -Captcha::$config['width'], + Captcha::$config['width'] + ), + mt_rand( + -Captcha::$config['height'], + Captcha::$config['height'] + ), + mt_rand( + -Captcha::$config['width'], + Captcha::$config['width'] + ), + mt_rand( + -Captcha::$config['height'], + Captcha::$config['height'] + ), + mt_rand(0, 360), + mt_rand(0, 360), + $color + ); + } - // Add random white/gray arcs, amount depends on complexity setting - $count = (Captcha::$config['width'] + Captcha::$config['height']) / 2; - $count = $count / 5 * min(10, Captcha::$config['complexity']); - for ($i = 0; $i < $count; $i++) - { - imagesetthickness($this->image, mt_rand(1, 2)); - $color = imagecolorallocatealpha($this->image, 255, 255, 255, mt_rand(0, 120)); - imagearc($this->image, mt_rand(-Captcha::$config['width'], Captcha::$config['width']), mt_rand(-Captcha::$config['height'], Captcha::$config['height']), mt_rand(-Captcha::$config['width'], Captcha::$config['width']), mt_rand(-Captcha::$config['height'], Captcha::$config['height']), mt_rand(0, 360), mt_rand(0, 360), $color); - } + // Use different fonts if available + $font = Captcha::$config['fontpath'] . Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])]; - // Use different fonts if available - $font = Captcha::$config['fontpath'].Captcha::$config['fonts'][array_rand(Captcha::$config['fonts'])]; + // Draw the character's white shadows + $size = (int) min(Captcha::$config['height'] / 2, Captcha::$config['width'] * 0.8 / strlen($this->response)); + $angle = mt_rand(-15 + strlen($this->response), 15 - strlen($this->response)); + $x = mt_rand(1, Captcha::$config['width'] * 0.9 - $size * strlen($this->response)); + $y = ((Captcha::$config['height'] - $size) / 2) + $size; + $color = imagecolorallocate($this->image, 255, 255, 255); + imagefttext($this->image, $size, $angle, $x + 1, $y + 1, $color, $font, $this->response); - // Draw the character's white shadows - $size = (int) min(Captcha::$config['height'] / 2, Captcha::$config['width'] * 0.8 / strlen($this->response)); - $angle = mt_rand(-15 + strlen($this->response), 15 - strlen($this->response)); - $x = mt_rand(1, Captcha::$config['width'] * 0.9 - $size * strlen($this->response)); - $y = ((Captcha::$config['height'] - $size) / 2) + $size; - $color = imagecolorallocate($this->image, 255, 255, 255); - imagefttext($this->image, $size, $angle, $x + 1, $y + 1, $color, $font, $this->response); + // Add more shadows for lower complexities + (Captcha::$config['complexity'] < 10) and imagefttext($this->image, $size, $angle, $x - 1, $y - 1, $color, $font, $this->response); + (Captcha::$config['complexity'] < 8) and imagefttext($this->image, $size, $angle, $x - 2, $y + 2, $color, $font, $this->response); + (Captcha::$config['complexity'] < 6) and imagefttext($this->image, $size, $angle, $x + 2, $y - 2, $color, $font, $this->response); + (Captcha::$config['complexity'] < 4) and imagefttext($this->image, $size, $angle, $x + 3, $y + 3, $color, $font, $this->response); + (Captcha::$config['complexity'] < 2) and imagefttext($this->image, $size, $angle, $x - 3, $y - 3, $color, $font, $this->response); - // Add more shadows for lower complexities - (Captcha::$config['complexity'] < 10) and imagefttext($this->image, $size, $angle, $x - 1, $y - 1, $color, $font , $this->response); - (Captcha::$config['complexity'] < 8) and imagefttext($this->image, $size, $angle, $x - 2, $y + 2, $color, $font , $this->response); - (Captcha::$config['complexity'] < 6) and imagefttext($this->image, $size, $angle, $x + 2, $y - 2, $color, $font , $this->response); - (Captcha::$config['complexity'] < 4) and imagefttext($this->image, $size, $angle, $x + 3, $y + 3, $color, $font , $this->response); - (Captcha::$config['complexity'] < 2) and imagefttext($this->image, $size, $angle, $x - 3, $y - 3, $color, $font , $this->response); + // Finally draw the foreground characters + $color = imagecolorallocate($this->image, 0, 0, 0); + imagefttext($this->image, $size, $angle, $x, $y, $color, $font, $this->response); - // Finally draw the foreground characters - $color = imagecolorallocate($this->image, 0, 0, 0); - imagefttext($this->image, $size, $angle, $x, $y, $color, $font, $this->response); - - // Output - return $this->image_render($html); - } - -} // End Captcha Black Driver Class \ No newline at end of file + // Output + return $this->image_render($html); + } +} +// End Captcha Black Driver Class diff --git a/lib/kohana/system/libraries/drivers/Captcha/Math.php b/lib/kohana/system/libraries/drivers/Captcha/Math.php index 4ac2024..7dc4a64 100644 --- a/lib/kohana/system/libraries/drivers/Captcha/Math.php +++ b/lib/kohana/system/libraries/drivers/Captcha/Math.php @@ -1,4 +1,12 @@ -math_exercice = implode(' + ', $numbers) . ' = '; - // Store the question for output - $this->math_exercice = implode(' + ', $numbers).' = '; + // Return the answer + return array_sum($numbers); + } - // Return the answer - return array_sum($numbers); - } - - /** - * Outputs the Captcha riddle. - * - * @param boolean html output - * @return mixed - */ - public function render($html) - { - return $this->math_exercice; - } - -} // End Captcha Math Driver Class \ No newline at end of file + /** + * Outputs the Captcha riddle. + * + * @param boolean html output + * @return mixed + */ + public function render($html) + { + return $this->math_exercice; + } +} +// End Captcha Math Driver Class diff --git a/lib/kohana/system/libraries/drivers/Captcha/Riddle.php b/lib/kohana/system/libraries/drivers/Captcha/Riddle.php index 765eeaa..ebdf86f 100644 --- a/lib/kohana/system/libraries/drivers/Captcha/Riddle.php +++ b/lib/kohana/system/libraries/drivers/Captcha/Riddle.php @@ -1,4 +1,12 @@ -riddle = $riddle[0]; - // Store the question for output - $this->riddle = $riddle[0]; + // Return the answer + return $riddle[1]; + } - // Return the answer - return $riddle[1]; - } - - /** - * Outputs the Captcha riddle. - * - * @param boolean html output - * @return mixed - */ - public function render($html) - { - return $this->riddle; - } - -} // End Captcha Riddle Driver Class \ No newline at end of file + /** + * Outputs the Captcha riddle. + * + * @param boolean html output + * @return mixed + */ + public function render($html) + { + return $this->riddle; + } +} +// End Captcha Riddle Driver Class diff --git a/lib/kohana/system/libraries/drivers/Captcha/Word.php b/lib/kohana/system/libraries/drivers/Captcha/Word.php index 856bd9b..d798f17 100644 --- a/lib/kohana/system/libraries/drivers/Captcha/Word.php +++ b/lib/kohana/system/libraries/drivers/Captcha/Word.php @@ -1,4 +1,12 @@ -escape_table($table) . ' WHERE ' . implode(' ', $where); + } - /** - * Builds a DELETE query. - * - * @param string table name - * @param array where clause - * @return string - */ - public function delete($table, $where) - { - return 'DELETE FROM '.$this->escape_table($table).' WHERE '.implode(' ', $where); - } + /** + * Builds an UPDATE query. + * + * @param string table name + * @param array key => value pairs + * @param array where clause + * @return string + */ + public function update($table, $values, $where) + { + foreach ($values as $key => $val) { + $valstr[] = $this->escape_column($key) . ' = ' . $val; + } + return 'UPDATE ' . $this->escape_table($table) . ' SET ' . implode(', ', $valstr) . ' WHERE ' . implode(' ', $where); + } - /** - * Builds an UPDATE query. - * - * @param string table name - * @param array key => value pairs - * @param array where clause - * @return string - */ - public function update($table, $values, $where) - { - foreach ($values as $key => $val) - { - $valstr[] = $this->escape_column($key).' = '.$val; - } - return 'UPDATE '.$this->escape_table($table).' SET '.implode(', ', $valstr).' WHERE '.implode(' ',$where); - } + /** + * Set the charset using 'SET NAMES '. + * + * @param string character set to use + */ + public function set_charset($charset) + { + throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); + } - /** - * Set the charset using 'SET NAMES '. - * - * @param string character set to use - */ - public function set_charset($charset) - { - throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); - } + /** + * Wrap the tablename in backticks, has support for: table.field syntax. + * + * @param string table name + * @return string + */ + abstract public function escape_table($table); - /** - * Wrap the tablename in backticks, has support for: table.field syntax. - * - * @param string table name - * @return string - */ - abstract public function escape_table($table); + /** + * Escape a column/field name, has support for special commands. + * + * @param string column name + * @return string + */ + abstract public function escape_column($column); - /** - * Escape a column/field name, has support for special commands. - * - * @param string column name - * @return string - */ - abstract public function escape_column($column); + /** + * Builds a WHERE portion of a query. + * + * @param mixed key + * @param string value + * @param string type + * @param int number of where clauses + * @param boolean escape the value + * @return string + */ + public function where($key, $value, $type, $num_wheres, $quote) + { + $prefix = ($num_wheres == 0) ? '' : $type; - /** - * Builds a WHERE portion of a query. - * - * @param mixed key - * @param string value - * @param string type - * @param int number of where clauses - * @param boolean escape the value - * @return string - */ - public function where($key, $value, $type, $num_wheres, $quote) - { - $prefix = ($num_wheres == 0) ? '' : $type; + if ($quote === -1) { + $value = ''; + } else { + if ($value === null) { + if (! $this->has_operator($key)) { + $key .= ' IS'; + } - if ($quote === -1) - { - $value = ''; - } - else - { - if ($value === NULL) - { - if ( ! $this->has_operator($key)) - { - $key .= ' IS'; - } + $value = ' NULL'; + } elseif (is_bool($value)) { + if (! $this->has_operator($key)) { + $key .= ' ='; + } - $value = ' NULL'; - } - elseif (is_bool($value)) - { - if ( ! $this->has_operator($key)) - { - $key .= ' ='; - } + $value = ($value == true) ? ' 1' : ' 0'; + } else { + if (! $this->has_operator($key) and ! empty($key)) { + $key = $this->escape_column($key) . ' ='; + } else { + preg_match('/^(.+?)([<>!=]+|\bIS(?:\s+NULL))\s*$/i', $key, $matches); + if (isset($matches[1]) and isset($matches[2])) { + $key = $this->escape_column(trim($matches[1])) . ' ' . trim($matches[2]); + } + } - $value = ($value == TRUE) ? ' 1' : ' 0'; - } - else - { - if ( ! $this->has_operator($key) AND ! empty($key)) - { - $key = $this->escape_column($key).' ='; - } - else - { - preg_match('/^(.+?)([<>!=]+|\bIS(?:\s+NULL))\s*$/i', $key, $matches); - if (isset($matches[1]) AND isset($matches[2])) - { - $key = $this->escape_column(trim($matches[1])).' '.trim($matches[2]); - } - } + $value = ' ' . (($quote == true) ? $this->escape($value) : $value); + } + } - $value = ' '.(($quote == TRUE) ? $this->escape($value) : $value); - } - } + return $prefix . $key . $value; + } - return $prefix.$key.$value; - } + /** + * Builds a LIKE portion of a query. + * + * @param mixed field name + * @param string value to match with field + * @param boolean add wildcards before and after the match + * @param string clause type (AND or OR) + * @param int number of likes + * @return string + */ + public function like($field, $match, $auto, $type, $num_likes) + { + $prefix = ($num_likes == 0) ? '' : $type; - /** - * Builds a LIKE portion of a query. - * - * @param mixed field name - * @param string value to match with field - * @param boolean add wildcards before and after the match - * @param string clause type (AND or OR) - * @param int number of likes - * @return string - */ - public function like($field, $match, $auto, $type, $num_likes) - { - $prefix = ($num_likes == 0) ? '' : $type; + $match = $this->escape_str($match); - $match = $this->escape_str($match); + if ($auto === true) { + // Add the start and end quotes + $match = '%' . str_replace('%', '\\%', $match) . '%'; + } - if ($auto === TRUE) - { - // Add the start and end quotes - $match = '%'.str_replace('%', '\\%', $match).'%'; - } + return $prefix . ' ' . $this->escape_column($field) . ' LIKE \'' . $match . '\''; + } - return $prefix.' '.$this->escape_column($field).' LIKE \''.$match . '\''; - } + /** + * Builds a NOT LIKE portion of a query. + * + * @param mixed field name + * @param string value to match with field + * @param string clause type (AND or OR) + * @param int number of likes + * @return string + */ + public function notlike($field, $match, $auto, $type, $num_likes) + { + $prefix = ($num_likes == 0) ? '' : $type; - /** - * Builds a NOT LIKE portion of a query. - * - * @param mixed field name - * @param string value to match with field - * @param string clause type (AND or OR) - * @param int number of likes - * @return string - */ - public function notlike($field, $match, $auto, $type, $num_likes) - { - $prefix = ($num_likes == 0) ? '' : $type; + $match = $this->escape_str($match); - $match = $this->escape_str($match); + if ($auto === true) { + // Add the start and end quotes + $match = '%' . $match . '%'; + } - if ($auto === TRUE) - { - // Add the start and end quotes - $match = '%'.$match.'%'; - } + return $prefix . ' ' . $this->escape_column($field) . ' NOT LIKE \'' . $match . '\''; + } - return $prefix.' '.$this->escape_column($field).' NOT LIKE \''.$match.'\''; - } + /** + * Builds a REGEX portion of a query. + * + * @param string field name + * @param string value to match with field + * @param string clause type (AND or OR) + * @param integer number of regexes + * @return string + */ + public function regex($field, $match, $type, $num_regexs) + { + throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); + } - /** - * Builds a REGEX portion of a query. - * - * @param string field name - * @param string value to match with field - * @param string clause type (AND or OR) - * @param integer number of regexes - * @return string - */ - public function regex($field, $match, $type, $num_regexs) - { - throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); - } + /** + * Builds a NOT REGEX portion of a query. + * + * @param string field name + * @param string value to match with field + * @param string clause type (AND or OR) + * @param integer number of regexes + * @return string + */ + public function notregex($field, $match, $type, $num_regexs) + { + throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); + } - /** - * Builds a NOT REGEX portion of a query. - * - * @param string field name - * @param string value to match with field - * @param string clause type (AND or OR) - * @param integer number of regexes - * @return string - */ - public function notregex($field, $match, $type, $num_regexs) - { - throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); - } + /** + * Builds an INSERT query. + * + * @param string table name + * @param array keys + * @param array values + * @return string + */ + public function insert($table, $keys, $values) + { + // Escape the column names + foreach ($keys as $key => $value) { + $keys[$key] = $this->escape_column($value); + } + return 'INSERT INTO ' . $this->escape_table($table) . ' (' . implode(', ', $keys) . ') VALUES (' . implode(', ', $values) . ')'; + } - /** - * Builds an INSERT query. - * - * @param string table name - * @param array keys - * @param array values - * @return string - */ - public function insert($table, $keys, $values) - { - // Escape the column names - foreach ($keys as $key => $value) - { - $keys[$key] = $this->escape_column($value); - } - return 'INSERT INTO '.$this->escape_table($table).' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } + /** + * Builds a MERGE portion of a query. + * + * @param string table name + * @param array keys + * @param array values + * @return string + */ + public function merge($table, $keys, $values) + { + throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); + } - /** - * Builds a MERGE portion of a query. - * - * @param string table name - * @param array keys - * @param array values - * @return string - */ - public function merge($table, $keys, $values) - { - throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); - } + /** + * Builds a LIMIT portion of a query. + * + * @param integer limit + * @param integer offset + * @return string + */ + abstract public function limit($limit, $offset = 0); - /** - * Builds a LIMIT portion of a query. - * - * @param integer limit - * @param integer offset - * @return string - */ - abstract public function limit($limit, $offset = 0); + /** + * Creates a prepared statement. + * + * @param string SQL query + * @return Database_Stmt + */ + public function stmt_prepare($sql = '') + { + throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); + } - /** - * Creates a prepared statement. - * - * @param string SQL query - * @return Database_Stmt - */ - public function stmt_prepare($sql = '') - { - throw new Kohana_Database_Exception('database.not_implemented', __FUNCTION__); - } + /** + * Compiles the SELECT statement. + * Generates a query string based on which functions were used. + * Should not be called directly, the get() function calls it. + * + * @param array select query values + * @return string + */ + abstract public function compile_select($database); - /** - * Compiles the SELECT statement. - * Generates a query string based on which functions were used. - * Should not be called directly, the get() function calls it. - * - * @param array select query values - * @return string - */ - abstract public function compile_select($database); + /** + * Determines if the string has an arithmetic operator in it. + * + * @param string string to check + * @return boolean + */ + public function has_operator($str) + { + return (bool) preg_match('/[<>!=]|\sIS(?:\s+NOT\s+)?\b|BETWEEN/i', trim($str)); + } - /** - * Determines if the string has an arithmetic operator in it. - * - * @param string string to check - * @return boolean - */ - public function has_operator($str) - { - return (bool) preg_match('/[<>!=]|\sIS(?:\s+NOT\s+)?\b|BETWEEN/i', trim($str)); - } + /** + * Escapes any input value. + * + * @param mixed value to escape + * @return string + */ + public function escape($value) + { + if (! $this->db_config['escape']) { + return $value; + } - /** - * Escapes any input value. - * - * @param mixed value to escape - * @return string - */ - public function escape($value) - { - if ( ! $this->db_config['escape']) - return $value; + switch (gettype($value)) { + case 'string': + $value = '\'' . $this->escape_str($value) . '\''; + break; + case 'boolean': + $value = (int) $value; + break; + case 'double': + // Convert to non-locale aware float to prevent possible commas + $value = sprintf('%F', $value); + break; + default: + $value = ($value === null) ? 'NULL' : $value; + break; + } - switch (gettype($value)) - { - case 'string': - $value = '\''.$this->escape_str($value).'\''; - break; - case 'boolean': - $value = (int) $value; - break; - case 'double': - // Convert to non-locale aware float to prevent possible commas - $value = sprintf('%F', $value); - break; - default: - $value = ($value === NULL) ? 'NULL' : $value; - break; - } + return (string) $value; + } - return (string) $value; - } + /** + * Escapes a string for a query. + * + * @param mixed value to escape + * @return string + */ + abstract public function escape_str($str); - /** - * Escapes a string for a query. - * - * @param mixed value to escape - * @return string - */ - abstract public function escape_str($str); + /** + * Lists all tables in the database. + * + * @return array + */ + abstract public function list_tables(); - /** - * Lists all tables in the database. - * - * @return array - */ - abstract public function list_tables(); + /** + * Lists all fields in a table. + * + * @param string table name + * @return array + */ + abstract public function list_fields($table); - /** - * Lists all fields in a table. - * - * @param string table name - * @return array - */ - abstract function list_fields($table); + /** + * Returns the last database error. + * + * @return string + */ + abstract public function show_error(); - /** - * Returns the last database error. - * - * @return string - */ - abstract public function show_error(); + /** + * Returns field data about a table. + * + * @param string table name + * @return array + */ + abstract public function field_data($table); - /** - * Returns field data about a table. - * - * @param string table name - * @return array - */ - abstract public function field_data($table); + /** + * Fetches SQL type information about a field, in a generic format. + * + * @param string field datatype + * @return array + */ + protected function sql_type($str) + { + static $sql_types; - /** - * Fetches SQL type information about a field, in a generic format. - * - * @param string field datatype - * @return array - */ - protected function sql_type($str) - { - static $sql_types; + if ($sql_types === null) { + // Load SQL data types + $sql_types = Kohana::config('sql_types'); + } - if ($sql_types === NULL) - { - // Load SQL data types - $sql_types = Kohana::config('sql_types'); - } + $str = strtolower(trim($str)); - $str = strtolower(trim($str)); + if (($open = strpos($str, '(')) !== false) { + // Find closing bracket + $close = strpos($str, ')', $open) - 1; - if (($open = strpos($str, '(')) !== FALSE) - { - // Find closing bracket - $close = strpos($str, ')', $open) - 1; + // Find the type without the size + $type = substr($str, 0, $open); + } else { + // No length + $type = $str; + } - // Find the type without the size - $type = substr($str, 0, $open); - } - else - { - // No length - $type = $str; - } + empty($sql_types[$type]) and exit( + 'Unknown field type: ' . $type . '. ' . + 'Please report this: http://trac.kohanaphp.com/newticket' + ); - empty($sql_types[$type]) and exit - ( - 'Unknown field type: '.$type.'. '. - 'Please report this: http://trac.kohanaphp.com/newticket' - ); + // Fetch the field definition + $field = $sql_types[$type]; - // Fetch the field definition - $field = $sql_types[$type]; + switch ($field['type']) { + case 'string': + case 'float': + if (isset($close)) { + // Add the length to the field info + $field['length'] = substr($str, $open + 1, $close - $open); + } + break; + case 'int': + // Add unsigned value + $field['unsigned'] = (strpos($str, 'unsigned') !== false); + break; + } - switch ($field['type']) - { - case 'string': - case 'float': - if (isset($close)) - { - // Add the length to the field info - $field['length'] = substr($str, $open + 1, $close - $open); - } - break; - case 'int': - // Add unsigned value - $field['unsigned'] = (strpos($str, 'unsigned') !== FALSE); - break; - } + return $field; + } - return $field; - } + /** + * Clears the internal query cache. + * + * @param string SQL query + */ + public function clear_cache($sql = null) + { + if (empty($sql)) { + $this->query_cache = array(); + } else { + unset($this->query_cache[$this->query_hash($sql)]); + } - /** - * Clears the internal query cache. - * - * @param string SQL query - */ - public function clear_cache($sql = NULL) - { - if (empty($sql)) - { - $this->query_cache = array(); - } - else - { - unset($this->query_cache[$this->query_hash($sql)]); - } + Kohana::log('debug', 'Database cache cleared: ' . get_class($this)); + } - Kohana::log('debug', 'Database cache cleared: '.get_class($this)); - } - - /** - * Creates a hash for an SQL query string. Replaces newlines with spaces, - * trims, and hashes. - * - * @param string SQL query - * @return string - */ - protected function query_hash($sql) - { - return sha1(str_replace("\n", ' ', trim($sql))); - } - -} // End Database Driver Interface + /** + * Creates a hash for an SQL query string. Replaces newlines with spaces, + * trims, and hashes. + * + * @param string SQL query + * @return string + */ + protected function query_hash($sql) + { + return sha1(str_replace("\n", ' ', trim($sql))); + } +} +// End Database Driver Interface /** * Database_Result * */ -abstract class Database_Result implements ArrayAccess, Iterator, Countable { +abstract class Database_Result implements ArrayAccess, Iterator, Countable +{ + // Result resource, insert id, and SQL + protected $result; + protected $insert_id; + protected $sql; - // Result resource, insert id, and SQL - protected $result; - protected $insert_id; - protected $sql; + // Current and total rows + protected $current_row = 0; + protected $total_rows = 0; - // Current and total rows - protected $current_row = 0; - protected $total_rows = 0; + // Fetch function and return type + protected $fetch_type; + protected $return_type; - // Fetch function and return type - protected $fetch_type; - protected $return_type; + /** + * Returns the SQL used to fetch the result. + * + * @return string + */ + public function sql() + { + return $this->sql; + } - /** - * Returns the SQL used to fetch the result. - * - * @return string - */ - public function sql() - { - return $this->sql; - } + /** + * Returns the insert id from the result. + * + * @return mixed + */ + public function insert_id() + { + return $this->insert_id; + } - /** - * Returns the insert id from the result. - * - * @return mixed - */ - public function insert_id() - { - return $this->insert_id; - } + /** + * Prepares the query result. + * + * @param boolean return rows as objects + * @param mixed type + * @return Database_Result + */ + abstract public function result($object = true, $type = false); - /** - * Prepares the query result. - * - * @param boolean return rows as objects - * @param mixed type - * @return Database_Result - */ - abstract function result($object = TRUE, $type = FALSE); + /** + * Builds an array of query results. + * + * @param boolean return rows as objects + * @param mixed type + * @return array + */ + abstract public function result_array($object = null, $type = false); - /** - * Builds an array of query results. - * - * @param boolean return rows as objects - * @param mixed type - * @return array - */ - abstract function result_array($object = NULL, $type = FALSE); + /** + * Gets the fields of an already run query. + * + * @return array + */ + abstract public function list_fields(); - /** - * Gets the fields of an already run query. - * - * @return array - */ - abstract public function list_fields(); + /** + * Seek to an offset in the results. + * + * @return boolean + */ + abstract public function seek($offset); - /** - * Seek to an offset in the results. - * - * @return boolean - */ - abstract public function seek($offset); + /** + * Countable: count + */ + public function count() + { + return $this->total_rows; + } - /** - * Countable: count - */ - public function count() - { - return $this->total_rows; - } + /** + * ArrayAccess: offsetExists + */ + public function offsetExists($offset) + { + if ($this->total_rows > 0) { + $min = 0; + $max = $this->total_rows - 1; - /** - * ArrayAccess: offsetExists - */ - public function offsetExists($offset) - { - if ($this->total_rows > 0) - { - $min = 0; - $max = $this->total_rows - 1; + return ! ($offset < $min or $offset > $max); + } - return ! ($offset < $min OR $offset > $max); - } + return false; + } - return FALSE; - } + /** + * ArrayAccess: offsetGet + */ + public function offsetGet($offset) + { + if (! $this->seek($offset)) { + return false; + } - /** - * ArrayAccess: offsetGet - */ - public function offsetGet($offset) - { - if ( ! $this->seek($offset)) - return FALSE; + // Return the row by calling the defined fetching callback + return call_user_func($this->fetch_type, $this->result, $this->return_type); + } - // Return the row by calling the defined fetching callback - return call_user_func($this->fetch_type, $this->result, $this->return_type); - } + /** + * ArrayAccess: offsetSet + * + * @throws Kohana_Database_Exception + */ + final public function offsetSet($offset, $value) + { + throw new Kohana_Database_Exception('database.result_read_only'); + } - /** - * ArrayAccess: offsetSet - * - * @throws Kohana_Database_Exception - */ - final public function offsetSet($offset, $value) - { - throw new Kohana_Database_Exception('database.result_read_only'); - } + /** + * ArrayAccess: offsetUnset + * + * @throws Kohana_Database_Exception + */ + final public function offsetUnset($offset) + { + throw new Kohana_Database_Exception('database.result_read_only'); + } - /** - * ArrayAccess: offsetUnset - * - * @throws Kohana_Database_Exception - */ - final public function offsetUnset($offset) - { - throw new Kohana_Database_Exception('database.result_read_only'); - } + /** + * Iterator: current + */ + public function current() + { + return $this->offsetGet($this->current_row); + } - /** - * Iterator: current - */ - public function current() - { - return $this->offsetGet($this->current_row); - } + /** + * Iterator: key + */ + public function key() + { + return $this->current_row; + } - /** - * Iterator: key - */ - public function key() - { - return $this->current_row; - } + /** + * Iterator: next + */ + public function next() + { + ++$this->current_row; + return $this; + } - /** - * Iterator: next - */ - public function next() - { - ++$this->current_row; - return $this; - } + /** + * Iterator: prev + */ + public function prev() + { + --$this->current_row; + return $this; + } - /** - * Iterator: prev - */ - public function prev() - { - --$this->current_row; - return $this; - } + /** + * Iterator: rewind + */ + public function rewind() + { + $this->current_row = 0; + return $this; + } - /** - * Iterator: rewind - */ - public function rewind() - { - $this->current_row = 0; - return $this; - } - - /** - * Iterator: valid - */ - public function valid() - { - return $this->offsetExists($this->current_row); - } - -} // End Database Result Interface + /** + * Iterator: valid + */ + public function valid() + { + return $this->offsetExists($this->current_row); + } +} +// End Database Result Interface diff --git a/lib/kohana/system/libraries/drivers/Database/Mssql.php b/lib/kohana/system/libraries/drivers/Database/Mssql.php index 8b5ed50..823916c 100644 --- a/lib/kohana/system/libraries/drivers/Database/Mssql.php +++ b/lib/kohana/system/libraries/drivers/Database/Mssql.php @@ -1,4 +1,13 @@ -db_config = $config; + /** + * Sets the config for the class. + * + * @param array database configuration + */ + public function __construct($config) + { + $this->db_config = $config; - Kohana::log('debug', 'MSSQL Database Driver Initialized'); - } + Kohana::log('debug', 'MSSQL Database Driver Initialized'); + } - /** - * Closes the database connection. - */ - public function __destruct() - { - is_resource($this->link) and mssql_close($this->link); - } + /** + * Closes the database connection. + */ + public function __destruct() + { + is_resource($this->link) and mssql_close($this->link); + } - /** - * Make the connection - * - * @return return connection - */ - public function connect() - { - // Check if link already exists - if (is_resource($this->link)) - return $this->link; + /** + * Make the connection + * + * @return return connection + */ + public function connect() + { + // Check if link already exists + if (is_resource($this->link)) { + return $this->link; + } - // Import the connect variables - extract($this->db_config['connection']); + // Import the connect variables + extract($this->db_config['connection']); - // Persistent connections enabled? - $connect = ($this->db_config['persistent'] == TRUE) ? 'mssql_pconnect' : 'mssql_connect'; + // Persistent connections enabled? + $connect = ($this->db_config['persistent'] == true) ? 'mssql_pconnect' : 'mssql_connect'; - // Build the connection info - $host = isset($host) ? $host : $socket; + // Build the connection info + $host = isset($host) ? $host : $socket; - // Windows uses a comma instead of a colon - $port = (isset($port) AND is_string($port)) ? (KOHANA_IS_WIN ? ',' : ':').$port : ''; + // Windows uses a comma instead of a colon + $port = (isset($port) and is_string($port)) ? (KOHANA_IS_WIN ? ',' : ':') . $port : ''; - // Make the connection and select the database - if (($this->link = $connect($host.$port, $user, $pass, TRUE)) AND mssql_select_db($database, $this->link)) - { - /* This is being removed so I can use it, will need to come up with a more elegant workaround in the future... - * - if ($charset = $this->db_config['character_set']) - { - $this->set_charset($charset); - } - */ + // Make the connection and select the database + if (($this->link = $connect($host . $port, $user, $pass, true)) and mssql_select_db($database, $this->link)) { + /* This is being removed so I can use it, will need to come up with a more elegant workaround in the future... + * + if ($charset = $this->db_config['character_set']) + { + $this->set_charset($charset); + } + */ - // Clear password after successful connect - $this->db_config['connection']['pass'] = NULL; + // Clear password after successful connect + $this->db_config['connection']['pass'] = null; - return $this->link; - } + return $this->link; + } - return FALSE; - } + return false; + } - public function query($sql) - { - // Only cache if it's turned on, and only cache if it's not a write statement - if ($this->db_config['cache'] AND ! preg_match('#\b(?:INSERT|UPDATE|REPLACE|SET)\b#i', $sql)) - { - $hash = $this->query_hash($sql); + public function query($sql) + { + // Only cache if it's turned on, and only cache if it's not a write statement + if ($this->db_config['cache'] and ! preg_match('#\b(?:INSERT|UPDATE|REPLACE|SET)\b#i', $sql)) { + $hash = $this->query_hash($sql); - if ( ! isset($this->query_cache[$hash])) - { - // Set the cached object - $this->query_cache[$hash] = new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); - } - else - { - // Rewind cached result - $this->query_cache[$hash]->rewind(); - } + if (! isset($this->query_cache[$hash])) { + // Set the cached object + $this->query_cache[$hash] = new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); + } else { + // Rewind cached result + $this->query_cache[$hash]->rewind(); + } - // Return the cached query - return $this->query_cache[$hash]; - } + // Return the cached query + return $this->query_cache[$hash]; + } - return new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); - } + return new Mssql_Result(mssql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); + } - public function escape_table($table) - { - if (stripos($table, ' AS ') !== FALSE) - { - // Force 'AS' to uppercase - $table = str_ireplace(' AS ', ' AS ', $table); + public function escape_table($table) + { + if (stripos($table, ' AS ') !== false) { + // Force 'AS' to uppercase + $table = str_ireplace(' AS ', ' AS ', $table); - // Runs escape_table on both sides of an AS statement - $table = array_map(array($this, __FUNCTION__), explode(' AS ', $table)); + // Runs escape_table on both sides of an AS statement + $table = array_map(array($this, __FUNCTION__), explode(' AS ', $table)); - // Re-create the AS statement - return implode(' AS ', $table); - } - return '['.str_replace('.', '[.]', $table).']'; - } + // Re-create the AS statement + return implode(' AS ', $table); + } + return '[' . str_replace('.', '[.]', $table) . ']'; + } - public function escape_column($column) - { - if (!$this->db_config['escape']) - return $column; + public function escape_column($column) + { + if (!$this->db_config['escape']) { + return $column; + } - if ($column == '*') - return $column; + if ($column == '*') { + return $column; + } - // This matches any functions we support to SELECT. - if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) - { - if ( count($matches) == 3) - { - return $matches[1].'('.$this->escape_column($matches[2]).')'; - } - else if ( count($matches) == 5) - { - return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]); - } - } + // This matches any functions we support to SELECT. + if (preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) { + if (count($matches) == 3) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ')'; + } elseif (count($matches) == 5) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ') AS ' . $this->escape_column($matches[2]); + } + } - // This matches any modifiers we support to SELECT. - if ( ! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column)) - { - if (stripos($column, ' AS ') !== FALSE) - { - // Force 'AS' to uppercase - $column = str_ireplace(' AS ', ' AS ', $column); + // This matches any modifiers we support to SELECT. + if (! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column)) { + if (stripos($column, ' AS ') !== false) { + // Force 'AS' to uppercase + $column = str_ireplace(' AS ', ' AS ', $column); - // Runs escape_column on both sides of an AS statement - $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); + // Runs escape_column on both sides of an AS statement + $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); - // Re-create the AS statement - return implode(' AS ', $column); - } + // Re-create the AS statement + return implode(' AS ', $column); + } - return preg_replace('/[^.*]+/', '[$0]', $column); - } + return preg_replace('/[^.*]+/', '[$0]', $column); + } - $parts = explode(' ', $column); - $column = ''; + $parts = explode(' ', $column); + $column = ''; - for ($i = 0, $c = count($parts); $i < $c; $i++) - { - // The column is always last - if ($i == ($c - 1)) - { - $column .= preg_replace('/[^.*]+/', '[$0]', $parts[$i]); - } - else // otherwise, it's a modifier - { - $column .= $parts[$i].' '; - } - } - return $column; - } + for ($i = 0, $c = count($parts); $i < $c; $i++) { + // The column is always last + if ($i == ($c - 1)) { + $column .= preg_replace('/[^.*]+/', '[$0]', $parts[$i]); + } else // otherwise, it's a modifier + { + $column .= $parts[$i] . ' '; + } + } + return $column; + } - /** - * Limit in SQL Server 2000 only uses the keyword - * 'TOP'; 2007 may have an offset keyword, but - * I am unsure - for pagination style limit,offset - * functionality, a fancy query needs to be built. - * - * @param unknown_type $limit - * @return unknown - */ - public function limit($limit, $offset=null) - { - return 'TOP '.$limit; - } + /** + * Limit in SQL Server 2000 only uses the keyword + * 'TOP'; 2007 may have an offset keyword, but + * I am unsure - for pagination style limit,offset + * functionality, a fancy query needs to be built. + * + * @param unknown_type $limit + * @return unknown + */ + public function limit($limit, $offset = null) + { + return 'TOP ' . $limit; + } - public function compile_select($database) - { - $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT '; - $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; + public function compile_select($database) + { + $sql = ($database['distinct'] == true) ? 'SELECT DISTINCT ' : 'SELECT '; + $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; - if (count($database['from']) > 0) - { - // Escape the tables - $froms = array(); - foreach ($database['from'] as $from) - $froms[] = $this->escape_column($from); - $sql .= "\nFROM "; - $sql .= implode(', ', $froms); - } + if (count($database['from']) > 0) { + // Escape the tables + $froms = array(); + foreach ($database['from'] as $from) { + $froms[] = $this->escape_column($from); + } + $sql .= "\nFROM "; + $sql .= implode(', ', $froms); + } - if (count($database['join']) > 0) - { - foreach($database['join'] AS $join) - { - $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions']; - } - } + if (count($database['join']) > 0) { + foreach ($database['join'] as $join) { + $sql .= "\n" . $join['type'] . 'JOIN ' . implode(', ', $join['tables']) . ' ON ' . $join['conditions']; + } + } - if (count($database['where']) > 0) - { - $sql .= "\nWHERE "; - } + if (count($database['where']) > 0) { + $sql .= "\nWHERE "; + } - $sql .= implode("\n", $database['where']); + $sql .= implode("\n", $database['where']); - if (count($database['groupby']) > 0) - { - $sql .= "\nGROUP BY "; - $sql .= implode(', ', $database['groupby']); - } + if (count($database['groupby']) > 0) { + $sql .= "\nGROUP BY "; + $sql .= implode(', ', $database['groupby']); + } - if (count($database['having']) > 0) - { - $sql .= "\nHAVING "; - $sql .= implode("\n", $database['having']); - } + if (count($database['having']) > 0) { + $sql .= "\nHAVING "; + $sql .= implode("\n", $database['having']); + } - if (count($database['orderby']) > 0) - { - $sql .= "\nORDER BY "; - $sql .= implode(', ', $database['orderby']); - } + if (count($database['orderby']) > 0) { + $sql .= "\nORDER BY "; + $sql .= implode(', ', $database['orderby']); + } - if (is_numeric($database['limit'])) - { - $sql .= "\n"; - $sql .= $this->limit($database['limit']); - } + if (is_numeric($database['limit'])) { + $sql .= "\n"; + $sql .= $this->limit($database['limit']); + } - return $sql; - } + return $sql; + } - public function escape_str($str) - { - if (!$this->db_config['escape']) - return $str; + public function escape_str($str) + { + if (!$this->db_config['escape']) { + return $str; + } - is_resource($this->link) or $this->connect(); - //mssql_real_escape_string($str, $this->link); <-- this function doesn't exist + is_resource($this->link) or $this->connect(); + //mssql_real_escape_string($str, $this->link); <-- this function doesn't exist - $characters = array('/\x00/', '/\x1a/', '/\n/', '/\r/', '/\\\/', '/\'/'); - $replace = array('\\\x00', '\\x1a', '\\n', '\\r', '\\\\', "''"); - return preg_replace($characters, $replace, $str); - } + $characters = array('/\x00/', '/\x1a/', '/\n/', '/\r/', '/\\\/', '/\'/'); + $replace = array('\\\x00', '\\x1a', '\\n', '\\r', '\\\\', "''"); + return preg_replace($characters, $replace, $str); + } - public function list_tables() - { - $sql = 'SHOW TABLES FROM ['.$this->db_config['connection']['database'].']'; - $result = $this->query($sql)->result(FALSE, MSSQL_ASSOC); + public function list_tables() + { + $sql = 'SHOW TABLES FROM [' . $this->db_config['connection']['database'] . ']'; + $result = $this->query($sql)->result(false, MSSQL_ASSOC); - $retval = array(); - foreach ($result as $row) - { - $retval[] = current($row); - } + $retval = array(); + foreach ($result as $row) { + $retval[] = current($row); + } - return $retval; - } + return $retval; + } - public function show_error() - { - return mssql_get_last_message($this->link); - } + public function show_error() + { + return mssql_get_last_message($this->link); + } - public function list_fields($table) - { - $result = array(); + public function list_fields($table) + { + $result = array(); - foreach ($this->field_data($table) as $row) - { - // Make an associative array - $result[$row->Field] = $this->sql_type($row->Type); - } + foreach ($this->field_data($table) as $row) { + // Make an associative array + $result[$row->Field] = $this->sql_type($row->Type); + } - return $result; - } + return $result; + } - public function field_data($table) - { - $query = $this->query("SELECT COLUMN_NAME AS Field, DATA_TYPE as Type FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '".$this->escape_table($table)."'", $this->link); + public function field_data($table) + { + $query = $this->query( + "SELECT COLUMN_NAME AS Field, DATA_TYPE as Type FROM INFORMATION_SCHEMA.Columns WHERE TABLE_NAME = '" . + $this->escape_table($table) . "'", + $this->link + ); - return $query->result_array(TRUE); - } + return $query->result_array(true); + } } /** * MSSQL Result */ -class Mssql_Result extends Database_Result { +class Mssql_Result extends Database_Result +{ + // Fetch function and return type + protected $fetch_type = 'mssql_fetch_object'; + protected $return_type = MSSQL_ASSOC; - // Fetch function and return type - protected $fetch_type = 'mssql_fetch_object'; - protected $return_type = MSSQL_ASSOC; + /** + * Sets up the result variables. + * + * @param resource query result + * @param resource database link + * @param boolean return objects or arrays + * @param string SQL query that was run + */ + public function __construct($result, $link, $object = true, $sql = '') + { + $this->result = $result; - /** - * Sets up the result variables. - * - * @param resource query result - * @param resource database link - * @param boolean return objects or arrays - * @param string SQL query that was run - */ - public function __construct($result, $link, $object = TRUE, $sql) - { - $this->result = $result; + // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query + if (is_resource($result)) { + $this->current_row = 0; + $this->total_rows = mssql_num_rows($this->result); + $this->fetch_type = ($object === true) ? 'mssql_fetch_object' : 'mssql_fetch_array'; + } elseif (is_bool($result)) { + if ($result == false) { + // SQL error + throw new Kohana_Database_Exception('database.error', mssql_get_last_message($link) . ' - ' . $sql); + } else { + // Its an DELETE, INSERT, REPLACE, or UPDATE querys + $last_id = mssql_query('SELECT @@IDENTITY AS last_id', $link); + $result = mssql_fetch_assoc($last_id); + $this->insert_id = $result['last_id']; + $this->total_rows = mssql_rows_affected($link); + } + } - // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query - if (is_resource($result)) - { - $this->current_row = 0; - $this->total_rows = mssql_num_rows($this->result); - $this->fetch_type = ($object === TRUE) ? 'mssql_fetch_object' : 'mssql_fetch_array'; - } - elseif (is_bool($result)) - { - if ($result == FALSE) - { - // SQL error - throw new Kohana_Database_Exception('database.error', mssql_get_last_message($link).' - '.$sql); - } - else - { - // Its an DELETE, INSERT, REPLACE, or UPDATE querys - $last_id = mssql_query('SELECT @@IDENTITY AS last_id', $link); - $result = mssql_fetch_assoc($last_id); - $this->insert_id = $result['last_id']; - $this->total_rows = mssql_rows_affected($link); - } - } + // Set result type + $this->result($object); - // Set result type - $this->result($object); + // Store the SQL + $this->sql = $sql; + } - // Store the SQL - $this->sql = $sql; - } + /** + * Destruct, the cleanup crew! + */ + public function __destruct() + { + if (is_resource($this->result)) { + mssql_free_result($this->result); + } + } - /** - * Destruct, the cleanup crew! - */ - public function __destruct() - { - if (is_resource($this->result)) - { - mssql_free_result($this->result); - } - } + public function result($object = true, $type = MSSQL_ASSOC) + { + $this->fetch_type = ((bool) $object) ? 'mssql_fetch_object' : 'mssql_fetch_array'; - public function result($object = TRUE, $type = MSSQL_ASSOC) - { - $this->fetch_type = ((bool) $object) ? 'mssql_fetch_object' : 'mssql_fetch_array'; + // This check has to be outside the previous statement, because we do not + // know the state of fetch_type when $object = NULL + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + if ($this->fetch_type == 'mssql_fetch_object') { + $this->return_type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $this->return_type = $type; + } - // This check has to be outside the previous statement, because we do not - // know the state of fetch_type when $object = NULL - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - if ($this->fetch_type == 'mssql_fetch_object') - { - $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $this->return_type = $type; - } + return $this; + } - return $this; - } + public function as_array($object = null, $type = MSSQL_ASSOC) + { + return $this->result_array($object, $type); + } - public function as_array($object = NULL, $type = MSSQL_ASSOC) - { - return $this->result_array($object, $type); - } + public function result_array($object = null, $type = MSSQL_ASSOC) + { + $rows = array(); - public function result_array($object = NULL, $type = MSSQL_ASSOC) - { - $rows = array(); + if (is_string($object)) { + $fetch = $object; + } elseif (is_bool($object)) { + if ($object === true) { + $fetch = 'mssql_fetch_object'; - if (is_string($object)) - { - $fetch = $object; - } - elseif (is_bool($object)) - { - if ($object === TRUE) - { - $fetch = 'mssql_fetch_object'; + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $fetch = 'mssql_fetch_array'; + } + } else { + // Use the default config values + $fetch = $this->fetch_type; - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $fetch = 'mssql_fetch_array'; - } - } - else - { - // Use the default config values - $fetch = $this->fetch_type; + if ($fetch == 'mssql_fetch_object') { + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } + } - if ($fetch == 'mssql_fetch_object') - { - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - } + if (mssql_num_rows($this->result)) { + // Reset the pointer location to make sure things work properly + mssql_data_seek($this->result, 0); - if (mssql_num_rows($this->result)) - { - // Reset the pointer location to make sure things work properly - mssql_data_seek($this->result, 0); + while ($row = $fetch($this->result, $type)) { + $rows[] = $row; + } + } - while ($row = $fetch($this->result, $type)) - { - $rows[] = $row; - } - } + return isset($rows) ? $rows : array(); + } - return isset($rows) ? $rows : array(); - } + public function list_fields() + { + $field_names = array(); + while ($field = mssql_fetch_field($this->result)) { + $field_names[] = $field->name; + } - public function list_fields() - { - $field_names = array(); - while ($field = mssql_fetch_field($this->result)) - { - $field_names[] = $field->name; - } + return $field_names; + } - return $field_names; - } + public function seek($offset) + { + if (! $this->offsetExists($offset)) { + return false; + } - public function seek($offset) - { - if ( ! $this->offsetExists($offset)) - return FALSE; - - return mssql_data_seek($this->result, $offset); - } - -} // End mssql_Result Class + return mssql_data_seek($this->result, $offset); + } +} +// End mssql_Result Class diff --git a/lib/kohana/system/libraries/drivers/Database/Mysql.php b/lib/kohana/system/libraries/drivers/Database/Mysql.php index d5222f5..ba4295a 100644 --- a/lib/kohana/system/libraries/drivers/Database/Mysql.php +++ b/lib/kohana/system/libraries/drivers/Database/Mysql.php @@ -1,4 +1,13 @@ -db_config = $config; - /** - * Sets the config for the class. - * - * @param array database configuration - */ - public function __construct($config) - { - $this->db_config = $config; + Kohana::log('debug', 'MySQL Database Driver Initialized'); + } - Kohana::log('debug', 'MySQL Database Driver Initialized'); - } + /** + * Closes the database connection. + */ + public function __destruct() + { + is_resource($this->link) and mysql_close($this->link); + } - /** - * Closes the database connection. - */ - public function __destruct() - { - is_resource($this->link) and mysql_close($this->link); - } + public function connect() + { + // Check if link already exists + if (is_resource($this->link)) { + return $this->link; + } - public function connect() - { - // Check if link already exists - if (is_resource($this->link)) - return $this->link; + // Import the connect variables + extract($this->db_config['connection']); - // Import the connect variables - extract($this->db_config['connection']); + // Persistent connections enabled? + $connect = ($this->db_config['persistent'] == true) ? 'mysql_pconnect' : 'mysql_connect'; - // Persistent connections enabled? - $connect = ($this->db_config['persistent'] == TRUE) ? 'mysql_pconnect' : 'mysql_connect'; + // Build the connection info + $host = isset($host) ? $host : $socket; + $port = isset($port) ? ':' . $port : ''; - // Build the connection info - $host = isset($host) ? $host : $socket; - $port = isset($port) ? ':'.$port : ''; + // Make the connection and select the database + if (($this->link = $connect($host . $port, $user, $pass, true)) and mysql_select_db($database, $this->link)) { + if ($charset = $this->db_config['character_set']) { + $this->set_charset($charset); + } - // Make the connection and select the database - if (($this->link = $connect($host.$port, $user, $pass, TRUE)) AND mysql_select_db($database, $this->link)) - { - if ($charset = $this->db_config['character_set']) - { - $this->set_charset($charset); - } + // Clear password after successful connect + $this->db_config['connection']['pass'] = null; - // Clear password after successful connect - $this->db_config['connection']['pass'] = NULL; + return $this->link; + } - return $this->link; - } + return false; + } - return FALSE; - } + public function query($sql) + { + // Only cache if it's turned on, and only cache if it's not a write statement + if ($this->db_config['cache'] and ! preg_match('#\b(?:INSERT|UPDATE|REPLACE|SET|DELETE|TRUNCATE)\b#i', $sql)) { + $hash = $this->query_hash($sql); - public function query($sql) - { - // Only cache if it's turned on, and only cache if it's not a write statement - if ($this->db_config['cache'] AND ! preg_match('#\b(?:INSERT|UPDATE|REPLACE|SET|DELETE|TRUNCATE)\b#i', $sql)) - { - $hash = $this->query_hash($sql); + if (! isset($this->query_cache[$hash])) { + // Set the cached object + $this->query_cache[$hash] = new Mysql_Result(mysql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); + } else { + // Rewind cached result + $this->query_cache[$hash]->rewind(); + } - if ( ! isset($this->query_cache[$hash])) - { - // Set the cached object - $this->query_cache[$hash] = new Mysql_Result(mysql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); - } - else - { - // Rewind cached result - $this->query_cache[$hash]->rewind(); - } + // Return the cached query + return $this->query_cache[$hash]; + } - // Return the cached query - return $this->query_cache[$hash]; - } + return new Mysql_Result(mysql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); + } - return new Mysql_Result(mysql_query($sql, $this->link), $this->link, $this->db_config['object'], $sql); - } + public function set_charset($charset) + { + $this->query('SET NAMES ' . $this->escape_str($charset)); + } - public function set_charset($charset) - { - $this->query('SET NAMES '.$this->escape_str($charset)); - } + public function escape_table($table) + { + if (!$this->db_config['escape']) { + return $table; + } - public function escape_table($table) - { - if (!$this->db_config['escape']) - return $table; + if (stripos($table, ' AS ') !== false) { + // Force 'AS' to uppercase + $table = str_ireplace(' AS ', ' AS ', $table); - if (stripos($table, ' AS ') !== FALSE) - { - // Force 'AS' to uppercase - $table = str_ireplace(' AS ', ' AS ', $table); + // Runs escape_table on both sides of an AS statement + $table = array_map(array($this, __FUNCTION__), explode(' AS ', $table)); - // Runs escape_table on both sides of an AS statement - $table = array_map(array($this, __FUNCTION__), explode(' AS ', $table)); + // Re-create the AS statement + return implode(' AS ', $table); + } + return '`' . str_replace('.', '`.`', $table) . '`'; + } - // Re-create the AS statement - return implode(' AS ', $table); - } - return '`'.str_replace('.', '`.`', $table).'`'; - } + public function escape_column($column) + { + if (!$this->db_config['escape']) { + return $column; + } - public function escape_column($column) - { - if (!$this->db_config['escape']) - return $column; + if ($column == '*') { + return $column; + } - if ($column == '*') - return $column; + // This matches any functions we support to SELECT. + if (preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) { + if (count($matches) == 3) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ')'; + } elseif (count($matches) == 5) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ') AS ' . $this->escape_column($matches[2]); + } + } - // This matches any functions we support to SELECT. - if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) - { - if ( count($matches) == 3) - { - return $matches[1].'('.$this->escape_column($matches[2]).')'; - } - else if ( count($matches) == 5) - { - return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]); - } - } - - // This matches any modifiers we support to SELECT. - if ( ! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column)) - { - if (stripos($column, ' AS ') !== FALSE) - { - // Force 'AS' to uppercase - $column = str_ireplace(' AS ', ' AS ', $column); + // This matches any modifiers we support to SELECT. + if (! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column)) { + if (stripos($column, ' AS ') !== false) { + // Force 'AS' to uppercase + $column = str_ireplace(' AS ', ' AS ', $column); - // Runs escape_column on both sides of an AS statement - $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); + // Runs escape_column on both sides of an AS statement + $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); - // Re-create the AS statement - return implode(' AS ', $column); - } + // Re-create the AS statement + return implode(' AS ', $column); + } - return preg_replace('/[^.*]+/', '`$0`', $column); - } + return preg_replace('/[^.*]+/', '`$0`', $column); + } - $parts = explode(' ', $column); - $column = ''; + $parts = explode(' ', $column); + $column = ''; - for ($i = 0, $c = count($parts); $i < $c; $i++) - { - // The column is always last - if ($i == ($c - 1)) - { - $column .= preg_replace('/[^.*]+/', '`$0`', $parts[$i]); - } - else // otherwise, it's a modifier - { - $column .= $parts[$i].' '; - } - } - return $column; - } + for ($i = 0, $c = count($parts); $i < $c; $i++) { + // The column is always last + if ($i == ($c - 1)) { + $column .= preg_replace('/[^.*]+/', '`$0`', $parts[$i]); + } else // otherwise, it's a modifier + { + $column .= $parts[$i] . ' '; + } + } + return $column; + } - public function regex($field, $match, $type, $num_regexs) - { - $prefix = ($num_regexs == 0) ? '' : $type; + public function regex($field, $match, $type, $num_regexs) + { + $prefix = ($num_regexs == 0) ? '' : $type; - return $prefix.' '.$this->escape_column($field).' REGEXP \''.$this->escape_str($match).'\''; - } + return $prefix . ' ' . $this->escape_column($field) . ' REGEXP \'' . $this->escape_str($match) . '\''; + } - public function notregex($field, $match, $type, $num_regexs) - { - $prefix = $num_regexs == 0 ? '' : $type; + public function notregex($field, $match, $type, $num_regexs) + { + $prefix = $num_regexs == 0 ? '' : $type; - return $prefix.' '.$this->escape_column($field).' NOT REGEXP \''.$this->escape_str($match) . '\''; - } + return $prefix . ' ' . $this->escape_column($field) . ' NOT REGEXP \'' . $this->escape_str($match) . '\''; + } - public function merge($table, $keys, $values) - { - // Escape the column names - foreach ($keys as $key => $value) - { - $keys[$key] = $this->escape_column($value); - } - return 'REPLACE INTO '.$this->escape_table($table).' ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; - } + public function merge($table, $keys, $values) + { + // Escape the column names + foreach ($keys as $key => $value) { + $keys[$key] = $this->escape_column($value); + } + return 'REPLACE INTO ' . $this->escape_table($table) . ' (' . implode(', ', $keys) . ') VALUES (' . implode(', ', $values) . ')'; + } - public function limit($limit, $offset = 0) - { - return 'LIMIT '.$offset.', '.$limit; - } + public function limit($limit, $offset = 0) + { + return 'LIMIT ' . $offset . ', ' . $limit; + } - public function compile_select($database) - { - $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT '; - $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; + public function compile_select($database) + { + $sql = ($database['distinct'] == true) ? 'SELECT DISTINCT ' : 'SELECT '; + $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; - if (count($database['from']) > 0) - { - // Escape the tables - $froms = array(); - foreach ($database['from'] as $from) - { - $froms[] = $this->escape_column($from); - } - $sql .= "\nFROM ("; - $sql .= implode(', ', $froms).")"; - } + if (count($database['from']) > 0) { + // Escape the tables + $froms = array(); + foreach ($database['from'] as $from) { + $froms[] = $this->escape_column($from); + } + $sql .= "\nFROM ("; + $sql .= implode(', ', $froms) . ")"; + } - if (count($database['join']) > 0) - { - foreach($database['join'] AS $join) - { - $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions']; - } - } + if (count($database['join']) > 0) { + foreach ($database['join'] as $join) { + $sql .= "\n" . $join['type'] . 'JOIN ' . implode(', ', $join['tables']) . ' ON ' . $join['conditions']; + } + } - if (count($database['where']) > 0) - { - $sql .= "\nWHERE "; - } + if (count($database['where']) > 0) { + $sql .= "\nWHERE "; + } - $sql .= implode("\n", $database['where']); + $sql .= implode("\n", $database['where']); - if (count($database['groupby']) > 0) - { - $sql .= "\nGROUP BY "; - $sql .= implode(', ', $database['groupby']); - } + if (count($database['groupby']) > 0) { + $sql .= "\nGROUP BY "; + $sql .= implode(', ', $database['groupby']); + } - if (count($database['having']) > 0) - { - $sql .= "\nHAVING "; - $sql .= implode("\n", $database['having']); - } + if (count($database['having']) > 0) { + $sql .= "\nHAVING "; + $sql .= implode("\n", $database['having']); + } - if (count($database['orderby']) > 0) - { - $sql .= "\nORDER BY "; - $sql .= implode(', ', $database['orderby']); - } + if (count($database['orderby']) > 0) { + $sql .= "\nORDER BY "; + $sql .= implode(', ', $database['orderby']); + } - if (is_numeric($database['limit'])) - { - $sql .= "\n"; - $sql .= $this->limit($database['limit'], $database['offset']); - } + if (is_numeric($database['limit'])) { + $sql .= "\n"; + $sql .= $this->limit($database['limit'], $database['offset']); + } - return $sql; - } + return $sql; + } - public function escape_str($str) - { - if (!$this->db_config['escape']) - return $str; + public function escape_str($str) + { + if (!$this->db_config['escape']) { + return $str; + } - is_resource($this->link) or $this->connect(); + is_resource($this->link) or $this->connect(); - return mysql_real_escape_string($str, $this->link); - } + return mysql_real_escape_string($str, $this->link); + } - public function list_tables() - { - $tables = array(); + public function list_tables() + { + $tables = array(); - if ($query = $this->query('SHOW TABLES FROM '.$this->escape_table($this->db_config['connection']['database']))) - { - foreach ($query->result(FALSE) as $row) - { - $tables[] = current($row); - } - } + if ($query = $this->query('SHOW TABLES FROM ' . $this->escape_table($this->db_config['connection']['database']))) { + foreach ($query->result(false) as $row) { + $tables[] = current($row); + } + } - return $tables; - } + return $tables; + } - public function show_error() - { - return mysql_error($this->link); - } + public function show_error() + { + return mysql_error($this->link); + } - public function list_fields($table) - { - $result = NULL; + public function list_fields($table) + { + $result = null; - foreach ($this->field_data($table) as $row) - { - // Make an associative array - $result[$row->Field] = $this->sql_type($row->Type); + foreach ($this->field_data($table) as $row) { + // Make an associative array + $result[$row->Field] = $this->sql_type($row->Type); - if ($row->Key === 'PRI' AND $row->Extra === 'auto_increment') - { - // For sequenced (AUTO_INCREMENT) tables - $result[$row->Field]['sequenced'] = TRUE; - } + if ($row->Key === 'PRI' and $row->Extra === 'auto_increment') { + // For sequenced (AUTO_INCREMENT) tables + $result[$row->Field]['sequenced'] = true; + } - if ($row->Null === 'YES') - { - // Set NULL status - $result[$row->Field]['null'] = TRUE; - } - } + if ($row->Null === 'YES') { + // Set NULL status + $result[$row->Field]['null'] = true; + } + } - if (!isset($result)) - throw new Kohana_Database_Exception('database.table_not_found', $table); + if (!isset($result)) { + throw new Kohana_Database_Exception('database.table_not_found', $table); + } - return $result; - } + return $result; + } - public function field_data($table) - { - $result = $this->query('SHOW COLUMNS FROM '.$this->escape_table($table)); + public function field_data($table) + { + $result = $this->query('SHOW COLUMNS FROM ' . $this->escape_table($table)); - return $result->result_array(TRUE); - } - -} // End Database_Mysql_Driver Class + return $result->result_array(true); + } +} +// End Database_Mysql_Driver Class /** * MySQL Result */ -class Mysql_Result extends Database_Result { +class Mysql_Result extends Database_Result +{ + // Fetch function and return type + protected $fetch_type = 'mysql_fetch_object'; + protected $return_type = MYSQL_ASSOC; - // Fetch function and return type - protected $fetch_type = 'mysql_fetch_object'; - protected $return_type = MYSQL_ASSOC; + /** + * Sets up the result variables. + * + * @param resource query result + * @param resource database link + * @param boolean return objects or arrays + * @param string SQL query that was run + */ + public function __construct($result, $link, $object = true, $sql = '') + { + $this->result = $result; - /** - * Sets up the result variables. - * - * @param resource query result - * @param resource database link - * @param boolean return objects or arrays - * @param string SQL query that was run - */ - public function __construct($result, $link, $object = TRUE, $sql) - { - $this->result = $result; + // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query + if (is_resource($result)) { + $this->current_row = 0; + $this->total_rows = mysql_num_rows($this->result); + $this->fetch_type = ($object === true) ? 'mysql_fetch_object' : 'mysql_fetch_array'; + } elseif (is_bool($result)) { + if ($result == false) { + // SQL error + throw new Kohana_Database_Exception('database.error', mysql_error($link) . ' - ' . $sql); + } else { + // Its an DELETE, INSERT, REPLACE, or UPDATE query + $this->insert_id = mysql_insert_id($link); + $this->total_rows = mysql_affected_rows($link); + } + } - // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query - if (is_resource($result)) - { - $this->current_row = 0; - $this->total_rows = mysql_num_rows($this->result); - $this->fetch_type = ($object === TRUE) ? 'mysql_fetch_object' : 'mysql_fetch_array'; - } - elseif (is_bool($result)) - { - if ($result == FALSE) - { - // SQL error - throw new Kohana_Database_Exception('database.error', mysql_error($link).' - '.$sql); - } - else - { - // Its an DELETE, INSERT, REPLACE, or UPDATE query - $this->insert_id = mysql_insert_id($link); - $this->total_rows = mysql_affected_rows($link); - } - } + // Set result type + $this->result($object); - // Set result type - $this->result($object); + // Store the SQL + $this->sql = $sql; + } - // Store the SQL - $this->sql = $sql; - } + /** + * Destruct, the cleanup crew! + */ + public function __destruct() + { + if (is_resource($this->result)) { + mysql_free_result($this->result); + } + } - /** - * Destruct, the cleanup crew! - */ - public function __destruct() - { - if (is_resource($this->result)) - { - mysql_free_result($this->result); - } - } + public function result($object = true, $type = MYSQL_ASSOC) + { + $this->fetch_type = ((bool) $object) ? 'mysql_fetch_object' : 'mysql_fetch_array'; - public function result($object = TRUE, $type = MYSQL_ASSOC) - { - $this->fetch_type = ((bool) $object) ? 'mysql_fetch_object' : 'mysql_fetch_array'; + // This check has to be outside the previous statement, because we do not + // know the state of fetch_type when $object = NULL + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + if ($this->fetch_type == 'mysql_fetch_object' and $object === true) { + $this->return_type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $this->return_type = $type; + } - // This check has to be outside the previous statement, because we do not - // know the state of fetch_type when $object = NULL - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - if ($this->fetch_type == 'mysql_fetch_object' AND $object === TRUE) - { - $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $this->return_type = $type; - } + return $this; + } - return $this; - } + public function as_array($object = null, $type = MYSQL_ASSOC) + { + return $this->result_array($object, $type); + } - public function as_array($object = NULL, $type = MYSQL_ASSOC) - { - return $this->result_array($object, $type); - } + public function result_array($object = null, $type = MYSQL_ASSOC) + { + $rows = array(); - public function result_array($object = NULL, $type = MYSQL_ASSOC) - { - $rows = array(); + if (is_string($object)) { + $fetch = $object; + } elseif (is_bool($object)) { + if ($object === true) { + $fetch = 'mysql_fetch_object'; - if (is_string($object)) - { - $fetch = $object; - } - elseif (is_bool($object)) - { - if ($object === TRUE) - { - $fetch = 'mysql_fetch_object'; + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $fetch = 'mysql_fetch_array'; + } + } else { + // Use the default config values + $fetch = $this->fetch_type; - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $fetch = 'mysql_fetch_array'; - } - } - else - { - // Use the default config values - $fetch = $this->fetch_type; + if ($fetch == 'mysql_fetch_object') { + $type = (is_string($this->return_type) and Kohana::auto_load($this->return_type)) ? $this->return_type : 'stdClass'; + } + } - if ($fetch == 'mysql_fetch_object') - { - $type = (is_string($this->return_type) AND Kohana::auto_load($this->return_type)) ? $this->return_type : 'stdClass'; - } - } + if (mysql_num_rows($this->result)) { + // Reset the pointer location to make sure things work properly + mysql_data_seek($this->result, 0); - if (mysql_num_rows($this->result)) - { - // Reset the pointer location to make sure things work properly - mysql_data_seek($this->result, 0); + while ($row = $fetch($this->result, $type)) { + $rows[] = $row; + } + } - while ($row = $fetch($this->result, $type)) - { - $rows[] = $row; - } - } + return isset($rows) ? $rows : array(); + } - return isset($rows) ? $rows : array(); - } + public function list_fields() + { + $field_names = array(); + while ($field = mysql_fetch_field($this->result)) { + $field_names[] = $field->name; + } - public function list_fields() - { - $field_names = array(); - while ($field = mysql_fetch_field($this->result)) - { - $field_names[] = $field->name; - } + return $field_names; + } - return $field_names; - } + public function seek($offset) + { + if ($this->offsetExists($offset) and mysql_data_seek($this->result, $offset)) { + // Set the current row to the offset + $this->current_row = $offset; - public function seek($offset) - { - if ($this->offsetExists($offset) AND mysql_data_seek($this->result, $offset)) - { - // Set the current row to the offset - $this->current_row = $offset; - - return TRUE; - } - else - { - return FALSE; - } - } - -} // End Mysql_Result Class + return true; + } else { + return false; + } + } +} +// End Mysql_Result Class diff --git a/lib/kohana/system/libraries/drivers/Database/Mysqli.php b/lib/kohana/system/libraries/drivers/Database/Mysqli.php index 0dd9f05..cf44a2b 100644 --- a/lib/kohana/system/libraries/drivers/Database/Mysqli.php +++ b/lib/kohana/system/libraries/drivers/Database/Mysqli.php @@ -1,4 +1,13 @@ -db_config = $config; - /** - * Sets the config for the class. - * - * @param array database configuration - */ - public function __construct($config) - { - $this->db_config = $config; + Kohana::log('debug', 'MySQLi Database Driver Initialized'); + } - Kohana::log('debug', 'MySQLi Database Driver Initialized'); - } + /** + * Closes the database connection. + */ + public function __destruct() + { + is_object($this->link) and $this->link->close(); + } - /** - * Closes the database connection. - */ - public function __destruct() - { - is_object($this->link) and $this->link->close(); - } + public function connect() + { + // Check if link already exists + if (is_object($this->link)) { + return $this->link; + } - public function connect() - { - // Check if link already exists - if (is_object($this->link)) - return $this->link; + // Import the connect variables + extract($this->db_config['connection']); - // Import the connect variables - extract($this->db_config['connection']); + // Build the connection info + $host = isset($host) ? $host : $socket; - // Build the connection info - $host = isset($host) ? $host : $socket; + // Make the connection and select the database + if ($this->link = new mysqli($host, $user, $pass, $database, $port)) { + if ($charset = $this->db_config['character_set']) { + $this->set_charset($charset); + } - // Make the connection and select the database - if ($this->link = new mysqli($host, $user, $pass, $database, $port)) - { - if ($charset = $this->db_config['character_set']) - { - $this->set_charset($charset); - } + // Clear password after successful connect + $this->db_config['connection']['pass'] = null; - // Clear password after successful connect - $this->db_config['connection']['pass'] = NULL; + return $this->link; + } - return $this->link; - } + return false; + } - return FALSE; - } + public function query($sql) + { + // Only cache if it's turned on, and only cache if it's not a write statement + if ($this->db_config['cache'] and ! preg_match('#\b(?:INSERT|UPDATE|REPLACE|SET|DELETE|TRUNCATE)\b#i', $sql)) { + $hash = $this->query_hash($sql); - public function query($sql) - { - // Only cache if it's turned on, and only cache if it's not a write statement - if ($this->db_config['cache'] AND ! preg_match('#\b(?:INSERT|UPDATE|REPLACE|SET|DELETE|TRUNCATE)\b#i', $sql)) - { - $hash = $this->query_hash($sql); + if (! isset($this->query_cache[$hash])) { + // Set the cached object + $this->query_cache[$hash] = new Kohana_Mysqli_Result($this->link, $this->db_config['object'], $sql); + } else { + // Rewind cached result + $this->query_cache[$hash]->rewind(); + } - if ( ! isset($this->query_cache[$hash])) - { - // Set the cached object - $this->query_cache[$hash] = new Kohana_Mysqli_Result($this->link, $this->db_config['object'], $sql); - } - else - { - // Rewind cached result - $this->query_cache[$hash]->rewind(); - } + // Return the cached query + return $this->query_cache[$hash]; + } - // Return the cached query - return $this->query_cache[$hash]; - } + return new Kohana_Mysqli_Result($this->link, $this->db_config['object'], $sql); + } - return new Kohana_Mysqli_Result($this->link, $this->db_config['object'], $sql); - } + public function set_charset($charset) + { + if ($this->link->set_charset($charset) === false) { + throw new Kohana_Database_Exception('database.error', $this->show_error()); + } + } - public function set_charset($charset) - { - if ($this->link->set_charset($charset) === FALSE) - throw new Kohana_Database_Exception('database.error', $this->show_error()); - } + public function escape_str($str) + { + if (!$this->db_config['escape']) { + return $str; + } - public function escape_str($str) - { - if (!$this->db_config['escape']) - return $str; + is_object($this->link) or $this->connect(); - is_object($this->link) or $this->connect(); + return $this->link->real_escape_string($str); + } - return $this->link->real_escape_string($str); - } - - public function show_error() - { - return $this->link->error; - } - -} // End Database_Mysqli_Driver Class + public function show_error() + { + return $this->link->error; + } +} +// End Database_Mysqli_Driver Class /** * MySQLi Result */ -class Kohana_Mysqli_Result extends Database_Result { +class Kohana_Mysqli_Result extends Database_Result +{ + // Database connection + protected $link; - // Database connection - protected $link; + // Data fetching types + protected $fetch_type = 'mysqli_fetch_object'; + protected $return_type = MYSQLI_ASSOC; - // Data fetching types - protected $fetch_type = 'mysqli_fetch_object'; - protected $return_type = MYSQLI_ASSOC; + /** + * Sets up the result variables. + * + * @param object database link + * @param boolean return objects or arrays + * @param string SQL query that was run + */ + public function __construct($link, $object = true, $sql = '') + { + $this->link = $link; - /** - * Sets up the result variables. - * - * @param object database link - * @param boolean return objects or arrays - * @param string SQL query that was run - */ - public function __construct($link, $object = TRUE, $sql) - { - $this->link = $link; + if (! $this->link->multi_query($sql)) { + // SQL error + throw new Kohana_Database_Exception('database.error', $this->link->error . ' - ' . $sql); + } else { + $this->result = $this->link->store_result(); - if ( ! $this->link->multi_query($sql)) - { - // SQL error - throw new Kohana_Database_Exception('database.error', $this->link->error.' - '.$sql); - } - else - { - $this->result = $this->link->store_result(); + // If the query is an object, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query + if (is_object($this->result)) { + $this->current_row = 0; + $this->total_rows = $this->result->num_rows; + $this->fetch_type = ($object === true) ? 'fetch_object' : 'fetch_array'; + } elseif ($this->link->error) { + // SQL error + throw new Kohana_Database_Exception('database.error', $this->link->error . ' - ' . $sql); + } else { + // Its an DELETE, INSERT, REPLACE, or UPDATE query + $this->insert_id = $this->link->insert_id; + $this->total_rows = $this->link->affected_rows; + } + } - // If the query is an object, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query - if (is_object($this->result)) - { - $this->current_row = 0; - $this->total_rows = $this->result->num_rows; - $this->fetch_type = ($object === TRUE) ? 'fetch_object' : 'fetch_array'; - } - elseif ($this->link->error) - { - // SQL error - throw new Kohana_Database_Exception('database.error', $this->link->error.' - '.$sql); - } - else - { - // Its an DELETE, INSERT, REPLACE, or UPDATE query - $this->insert_id = $this->link->insert_id; - $this->total_rows = $this->link->affected_rows; - } - } + // Set result type + $this->result($object); - // Set result type - $this->result($object); + // Store the SQL + $this->sql = $sql; + } - // Store the SQL - $this->sql = $sql; - } + /** + * Magic __destruct function, frees the result. + */ + public function __destruct() + { + if (is_object($this->result)) { + $this->result->free_result(); - /** - * Magic __destruct function, frees the result. - */ - public function __destruct() - { - if (is_object($this->result)) - { - $this->result->free_result(); + // this is kinda useless, but needs to be done to avoid the "Commands out of sync; you + // can't run this command now" error. Basically, we get all results after the first one + // (the one we actually need) and free them. + if (is_resource($this->link) and $this->link->more_results()) { + do { + if ($result = $this->link->store_result()) { + $result->free_result(); + } + } while ($this->link->next_result()); + } + } + } - // this is kinda useless, but needs to be done to avoid the "Commands out of sync; you - // can't run this command now" error. Basically, we get all results after the first one - // (the one we actually need) and free them. - if (is_resource($this->link) AND $this->link->more_results()) - { - do - { - if ($result = $this->link->store_result()) - { - $result->free_result(); - } - } while ($this->link->next_result()); - } - } - } + public function result($object = true, $type = MYSQLI_ASSOC) + { + $this->fetch_type = ((bool) $object) ? 'fetch_object' : 'fetch_array'; - public function result($object = TRUE, $type = MYSQLI_ASSOC) - { - $this->fetch_type = ((bool) $object) ? 'fetch_object' : 'fetch_array'; + // This check has to be outside the previous statement, because we do not + // know the state of fetch_type when $object = NULL + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + if ($this->fetch_type == 'fetch_object') { + $this->return_type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $this->return_type = $type; + } - // This check has to be outside the previous statement, because we do not - // know the state of fetch_type when $object = NULL - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - if ($this->fetch_type == 'fetch_object') - { - $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $this->return_type = $type; - } + return $this; + } - return $this; - } + public function as_array($object = null, $type = MYSQLI_ASSOC) + { + return $this->result_array($object, $type); + } - public function as_array($object = NULL, $type = MYSQLI_ASSOC) - { - return $this->result_array($object, $type); - } + public function result_array($object = null, $type = MYSQLI_ASSOC) + { + $rows = array(); - public function result_array($object = NULL, $type = MYSQLI_ASSOC) - { - $rows = array(); + if (is_string($object)) { + $fetch = $object; + } elseif (is_bool($object)) { + if ($object === true) { + $fetch = 'fetch_object'; - if (is_string($object)) - { - $fetch = $object; - } - elseif (is_bool($object)) - { - if ($object === TRUE) - { - $fetch = 'fetch_object'; + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $fetch = 'fetch_array'; + } + } else { + // Use the default config values + $fetch = $this->fetch_type; - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $fetch = 'fetch_array'; - } - } - else - { - // Use the default config values - $fetch = $this->fetch_type; + if ($fetch == 'fetch_object') { + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } + } - if ($fetch == 'fetch_object') - { - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - } + if ($this->result->num_rows) { + // Reset the pointer location to make sure things work properly + $this->result->data_seek(0); - if ($this->result->num_rows) - { - // Reset the pointer location to make sure things work properly - $this->result->data_seek(0); + while ($row = $this->result->$fetch($type)) { + $rows[] = $row; + } + } - while ($row = $this->result->$fetch($type)) - { - $rows[] = $row; - } - } + return isset($rows) ? $rows : array(); + } - return isset($rows) ? $rows : array(); - } + public function list_fields() + { + $field_names = array(); + while ($field = $this->result->fetch_field()) { + $field_names[] = $field->name; + } - public function list_fields() - { - $field_names = array(); - while ($field = $this->result->fetch_field()) - { - $field_names[] = $field->name; - } + return $field_names; + } - return $field_names; - } + public function seek($offset) + { + if ($this->offsetExists($offset) and $this->result->data_seek($offset)) { + // Set the current row to the offset + $this->current_row = $offset; - public function seek($offset) - { - if ($this->offsetExists($offset) AND $this->result->data_seek($offset)) - { - // Set the current row to the offset - $this->current_row = $offset; + return true; + } - return TRUE; - } + return false; + } - return FALSE; - } + public function offsetGet($offset) + { + if (! $this->seek($offset)) { + return false; + } - public function offsetGet($offset) - { - if ( ! $this->seek($offset)) - return FALSE; - - // Return the row - $fetch = $this->fetch_type; - return $this->result->$fetch($this->return_type); - } - -} // End Mysqli_Result Class + // Return the row + $fetch = $this->fetch_type; + return $this->result->$fetch($this->return_type); + } +} +// End Mysqli_Result Class /** * MySQLi Prepared Statement (experimental) */ -class Kohana_Mysqli_Statement { +class Kohana_Mysqli_Statement +{ + protected $link = null; + protected $stmt; + protected $var_names = array(); + protected $var_values = array(); - protected $link = NULL; - protected $stmt; - protected $var_names = array(); - protected $var_values = array(); + public function __construct($sql, $link) + { + $this->link = $link; - public function __construct($sql, $link) - { - $this->link = $link; + $this->stmt = $this->link->prepare($sql); - $this->stmt = $this->link->prepare($sql); + return $this; + } - return $this; - } + public function __destruct() + { + $this->stmt->close(); + } - public function __destruct() - { - $this->stmt->close(); - } + // Sets the bind parameters + public function bind_params($param_types, $params) + { + $this->var_names = array_keys($params); + $this->var_values = array_values($params); + call_user_func_array(array($this->stmt, 'bind_param'), array_merge($param_types, $var_names)); - // Sets the bind parameters - public function bind_params($param_types, $params) - { - $this->var_names = array_keys($params); - $this->var_values = array_values($params); - call_user_func_array(array($this->stmt, 'bind_param'), array_merge($param_types, $var_names)); + return $this; + } - return $this; - } + public function bind_result($params) + { + call_user_func_array(array($this->stmt, 'bind_result'), $params); + } - public function bind_result($params) - { - call_user_func_array(array($this->stmt, 'bind_result'), $params); - } - - // Runs the statement - public function execute() - { - foreach ($this->var_names as $key => $name) - { - $$name = $this->var_values[$key]; - } - $this->stmt->execute(); - return $this->stmt; - } + // Runs the statement + public function execute() + { + foreach ($this->var_names as $key => $name) { + $$name = $this->var_values[$key]; + } + $this->stmt->execute(); + return $this->stmt; + } } diff --git a/lib/kohana/system/libraries/drivers/Database/Pdosqlite.php b/lib/kohana/system/libraries/drivers/Database/Pdosqlite.php index c2d1bb2..ce93260 100644 --- a/lib/kohana/system/libraries/drivers/Database/Pdosqlite.php +++ b/lib/kohana/system/libraries/drivers/Database/Pdosqlite.php @@ -1,4 +1,13 @@ - */ -class Database_Pdosqlite_Driver extends Database_Driver { +class Database_Pdosqlite_Driver extends Database_Driver +{ + // Database connection link + protected $link; + protected $db_config; - // Database connection link - protected $link; - protected $db_config; + /* + * Constructor: __construct + * Sets up the config for the class. + * + * Parameters: + * config - database configuration + * + */ + public function __construct($config) + { + $this->db_config = $config; - /* - * Constructor: __construct - * Sets up the config for the class. - * - * Parameters: - * config - database configuration - * - */ - public function __construct($config) - { - $this->db_config = $config; + Kohana::log('debug', 'PDO:Sqlite Database Driver Initialized'); + } - Kohana::log('debug', 'PDO:Sqlite Database Driver Initialized'); - } + public function connect() + { + // Import the connect variables + extract($this->db_config['connection']); - public function connect() - { - // Import the connect variables - extract($this->db_config['connection']); + try { + $this->link = new PDO( + 'sqlite:' . $socket . $database, + $user, + $pass, + array(PDO::ATTR_PERSISTENT => $this->db_config['persistent']) + ); - try - { - $this->link = new PDO('sqlite:'.$socket.$database, $user, $pass, - array(PDO::ATTR_PERSISTENT => $this->db_config['persistent'])); + $this->link->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL); + //$this->link->query('PRAGMA count_changes=1;'); - $this->link->setAttribute(PDO::ATTR_CASE, PDO::CASE_NATURAL); - //$this->link->query('PRAGMA count_changes=1;'); + if ($charset = $this->db_config['character_set']) { + $this->set_charset($charset); + } + } catch (PDOException $e) { + throw new Kohana_Database_Exception('database.error', $e->getMessage()); + } - if ($charset = $this->db_config['character_set']) - { - $this->set_charset($charset); - } - } - catch (PDOException $e) - { - throw new Kohana_Database_Exception('database.error', $e->getMessage()); - } + // Clear password after successful connect + $this->db_config['connection']['pass'] = null; - // Clear password after successful connect - $this->db_config['connection']['pass'] = NULL; + return $this->link; + } - return $this->link; - } + public function query($sql) + { + try { + $sth = $this->link->prepare($sql); + } catch (PDOException $e) { + throw new Kohana_Database_Exception('database.error', $e->getMessage()); + } + return new Pdosqlite_Result($sth, $this->link, $this->db_config['object'], $sql); + } - public function query($sql) - { - try - { - $sth = $this->link->prepare($sql); - } - catch (PDOException $e) - { - throw new Kohana_Database_Exception('database.error', $e->getMessage()); - } - return new Pdosqlite_Result($sth, $this->link, $this->db_config['object'], $sql); - } + public function set_charset($charset) + { + $this->link->query('PRAGMA encoding = ' . $this->escape_str($charset)); + } - public function set_charset($charset) - { - $this->link->query('PRAGMA encoding = '.$this->escape_str($charset)); - } + public function escape_table($table) + { + if (! $this->db_config['escape']) { + return $table; + } - public function escape_table($table) - { - if ( ! $this->db_config['escape']) - return $table; + return '`' . str_replace('.', '`.`', $table) . '`'; + } - return '`'.str_replace('.', '`.`', $table).'`'; - } + public function escape_column($column) + { + if (! $this->db_config['escape']) { + return $column; + } - public function escape_column($column) - { - if ( ! $this->db_config['escape']) - return $column; + if ($column == '*') { + return $column; + } - if ($column == '*') - return $column; + // This matches any functions we support to SELECT. + if (preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) { + if (count($matches) == 3) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ')'; + } elseif (count($matches) == 5) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ') AS ' . $this->escape_column($matches[2]); + } + } - // This matches any functions we support to SELECT. - if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) - { - if ( count($matches) == 3) - { - return $matches[1].'('.$this->escape_column($matches[2]).')'; - } - else if ( count($matches) == 5) - { - return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]); - } - } + // This matches any modifiers we support to SELECT. + if (! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column)) { + if (stripos($column, ' AS ') !== false) { + // Force 'AS' to uppercase + $column = str_ireplace(' AS ', ' AS ', $column); - // This matches any modifiers we support to SELECT. - if ( ! preg_match('/\b(?:rand|all|distinct(?:row)?|high_priority|sql_(?:small_result|b(?:ig_result|uffer_result)|no_cache|ca(?:che|lc_found_rows)))\s/i', $column)) - { - if (stripos($column, ' AS ') !== FALSE) - { - // Force 'AS' to uppercase - $column = str_ireplace(' AS ', ' AS ', $column); + // Runs escape_column on both sides of an AS statement + $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); - // Runs escape_column on both sides of an AS statement - $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); + // Re-create the AS statement + return implode(' AS ', $column); + } - // Re-create the AS statement - return implode(' AS ', $column); - } + return preg_replace('/[^.*]+/', '`$0`', $column); + } - return preg_replace('/[^.*]+/', '`$0`', $column); - } + $parts = explode(' ', $column); + $column = ''; - $parts = explode(' ', $column); - $column = ''; + for ($i = 0, $c = count($parts); $i < $c; $i++) { + // The column is always last + if ($i == ($c - 1)) { + $column .= preg_replace('/[^.*]+/', '`$0`', $parts[$i]); + } else // otherwise, it's a modifier + { + $column .= $parts[$i] . ' '; + } + } + return $column; + } - for ($i = 0, $c = count($parts); $i < $c; $i++) - { - // The column is always last - if ($i == ($c - 1)) - { - $column .= preg_replace('/[^.*]+/', '`$0`', $parts[$i]); - } - else // otherwise, it's a modifier - { - $column .= $parts[$i].' '; - } - } - return $column; - } + public function limit($limit, $offset = 0) + { + return 'LIMIT ' . $offset . ', ' . $limit; + } - public function limit($limit, $offset = 0) - { - return 'LIMIT '.$offset.', '.$limit; - } + public function compile_select($database) + { + $sql = ($database['distinct'] == true) ? 'SELECT DISTINCT ' : 'SELECT '; + $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; - public function compile_select($database) - { - $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT '; - $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; + if (count($database['from']) > 0) { + $sql .= "\nFROM "; + $sql .= implode(', ', $database['from']); + } - if (count($database['from']) > 0) - { - $sql .= "\nFROM "; - $sql .= implode(', ', $database['from']); - } + if (count($database['join']) > 0) { + foreach ($database['join'] as $join) { + $sql .= "\n" . $join['type'] . 'JOIN ' . implode(', ', $join['tables']) . ' ON ' . $join['conditions']; + } + } - if (count($database['join']) > 0) - { - foreach($database['join'] AS $join) - { - $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions']; - } - } + if (count($database['where']) > 0) { + $sql .= "\nWHERE "; + } - if (count($database['where']) > 0) - { - $sql .= "\nWHERE "; - } + $sql .= implode("\n", $database['where']); - $sql .= implode("\n", $database['where']); + if (count($database['groupby']) > 0) { + $sql .= "\nGROUP BY "; + $sql .= implode(', ', $database['groupby']); + } - if (count($database['groupby']) > 0) - { - $sql .= "\nGROUP BY "; - $sql .= implode(', ', $database['groupby']); - } + if (count($database['having']) > 0) { + $sql .= "\nHAVING "; + $sql .= implode("\n", $database['having']); + } - if (count($database['having']) > 0) - { - $sql .= "\nHAVING "; - $sql .= implode("\n", $database['having']); - } + if (count($database['orderby']) > 0) { + $sql .= "\nORDER BY "; + $sql .= implode(', ', $database['orderby']); + } - if (count($database['orderby']) > 0) - { - $sql .= "\nORDER BY "; - $sql .= implode(', ', $database['orderby']); - } + if (is_numeric($database['limit'])) { + $sql .= "\n"; + $sql .= $this->limit($database['limit'], $database['offset']); + } - if (is_numeric($database['limit'])) - { - $sql .= "\n"; - $sql .= $this->limit($database['limit'], $database['offset']); - } + return $sql; + } - return $sql; - } + public function escape_str($str) + { + if (! $this->db_config['escape']) { + return $str; + } - public function escape_str($str) - { - if ( ! $this->db_config['escape']) - return $str; + if (function_exists('sqlite_escape_string')) { + $res = sqlite_escape_string($str); + } else { + $res = str_replace("'", "''", $str); + } + return $res; + } - if (function_exists('sqlite_escape_string')) - { - $res = sqlite_escape_string($str); - } - else - { - $res = str_replace("'", "''", $str); - } - return $res; - } + public function list_tables() + { + $sql = "SELECT `name` FROM `sqlite_master` WHERE `type`='table' ORDER BY `name`;"; + try { + $result = $this->query($sql)->result(false, PDO::FETCH_ASSOC); + $tables = array(); + foreach ($result as $row) { + $tables[] = current($row); + } + } catch (PDOException $e) { + throw new Kohana_Database_Exception('database.error', $e->getMessage()); + } + return $tables; + } - public function list_tables() - { - $sql = "SELECT `name` FROM `sqlite_master` WHERE `type`='table' ORDER BY `name`;"; - try - { - $result = $this->query($sql)->result(FALSE, PDO::FETCH_ASSOC); - $tables = array(); - foreach ($result as $row) - { - $tables[] = current($row); - } - } - catch (PDOException $e) - { - throw new Kohana_Database_Exception('database.error', $e->getMessage()); - } - return $tables; - } + public function show_error() + { + $err = $this->link->errorInfo(); + return isset($err[2]) ? $err[2] : 'Unknown error!'; + } - public function show_error() - { - $err = $this->link->errorInfo(); - return isset($err[2]) ? $err[2] : 'Unknown error!'; - } + public function list_fields($table, $query = false) + { + static $tables; + if (is_object($query)) { + if (empty($tables[$table])) { + $tables[$table] = array(); - public function list_fields($table, $query = FALSE) - { - static $tables; - if (is_object($query)) - { - if (empty($tables[$table])) - { - $tables[$table] = array(); + foreach ($query->result() as $row) { + $tables[$table][] = $row->name; + } + } - foreach ($query->result() as $row) - { - $tables[$table][] = $row->name; - } - } + return $tables[$table]; + } else { + $result = $this->link->query('PRAGMA table_info(' . $this->escape_table($table) . ')'); - return $tables[$table]; - } - else - { - $result = $this->link->query( 'PRAGMA table_info('.$this->escape_table($table).')' ); + foreach ($result as $row) { + $tables[$table][$row['name']] = $this->sql_type($row['type']); + } - foreach ($result as $row) - { - $tables[$table][$row['name']] = $this->sql_type($row['type']); - } + return $tables[$table]; + } + } - return $tables[$table]; - } - } - - public function field_data($table) - { - Kohana::log('error', 'This method is under developing'); - } - /** - * Version number query string - * - * @access public - * @return string - */ - function version() - { - return $this->link->getAttribute(constant("PDO::ATTR_SERVER_VERSION")); - } - -} // End Database_PdoSqlite_Driver Class + public function field_data($table) + { + Kohana::log('error', 'This method is under developing'); + } + /** + * Version number query string + * + * @access public + * @return string + */ + public function version() + { + return $this->link->getAttribute(constant("PDO::ATTR_SERVER_VERSION")); + } +} +// End Database_PdoSqlite_Driver Class /* * PDO-sqlite Result */ -class Pdosqlite_Result extends Database_Result { +class Pdosqlite_Result extends Database_Result +{ + // Data fetching types + protected $fetch_type = PDO::FETCH_OBJ; + protected $return_type = PDO::FETCH_ASSOC; - // Data fetching types - protected $fetch_type = PDO::FETCH_OBJ; - protected $return_type = PDO::FETCH_ASSOC; + /** + * Sets up the result variables. + * + * @param resource query result + * @param resource database link + * @param boolean return objects or arrays + * @param string SQL query that was run + */ + public function __construct($result, $link, $object = true, $sql = '') + { + if (is_object($result) or $result = $link->prepare($sql)) { + // run the query. Return true if success, false otherwise + if (! $result->execute()) { + // Throw Kohana Exception with error message. See PDOStatement errorInfo() method + $arr_infos = $result->errorInfo(); + throw new Kohana_Database_Exception('database.error', $arr_infos[2]); + } - /** - * Sets up the result variables. - * - * @param resource query result - * @param resource database link - * @param boolean return objects or arrays - * @param string SQL query that was run - */ - public function __construct($result, $link, $object = TRUE, $sql) - { - if (is_object($result) OR $result = $link->prepare($sql)) - { - // run the query. Return true if success, false otherwise - if( ! $result->execute()) - { - // Throw Kohana Exception with error message. See PDOStatement errorInfo() method - $arr_infos = $result->errorInfo(); - throw new Kohana_Database_Exception('database.error', $arr_infos[2]); - } + if (preg_match('/^SELECT|PRAGMA|EXPLAIN/i', $sql)) { + $this->result = $result; + $this->current_row = 0; - if (preg_match('/^SELECT|PRAGMA|EXPLAIN/i', $sql)) - { - $this->result = $result; - $this->current_row = 0; + $this->total_rows = $this->sqlite_row_count(); - $this->total_rows = $this->sqlite_row_count(); + $this->fetch_type = ($object === true) ? PDO::FETCH_OBJ : PDO::FETCH_ASSOC; + } elseif (preg_match('/^DELETE|INSERT|UPDATE/i', $sql)) { + $this->insert_id = $link->lastInsertId(); - $this->fetch_type = ($object === TRUE) ? PDO::FETCH_OBJ : PDO::FETCH_ASSOC; - } - elseif (preg_match('/^DELETE|INSERT|UPDATE/i', $sql)) - { - $this->insert_id = $link->lastInsertId(); + $this->total_rows = $result->rowCount(); + } + } else { + // SQL error + throw new Kohana_Database_Exception('database.error', $link->errorInfo() . ' - ' . $sql); + } - $this->total_rows = $result->rowCount(); - } - } - else - { - // SQL error - throw new Kohana_Database_Exception('database.error', $link->errorInfo().' - '.$sql); - } + // Set result type + $this->result($object); - // Set result type - $this->result($object); + // Store the SQL + $this->sql = $sql; + } - // Store the SQL - $this->sql = $sql; - } + private function sqlite_row_count() + { + $count = 0; + while ($this->result->fetch()) { + $count++; + } - private function sqlite_row_count() - { - $count = 0; - while ($this->result->fetch()) - { - $count++; - } + // The query must be re-fetched now. + $this->result->execute(); - // The query must be re-fetched now. - $this->result->execute(); + return $count; + } - return $count; - } + /* + * Destructor: __destruct + * Magic __destruct function, frees the result. + */ + public function __destruct() + { + if (is_object($this->result)) { + $this->result->closeCursor(); + $this->result = null; + } + } - /* - * Destructor: __destruct - * Magic __destruct function, frees the result. - */ - public function __destruct() - { - if (is_object($this->result)) - { - $this->result->closeCursor(); - $this->result = NULL; - } - } + public function result($object = true, $type = PDO::FETCH_BOTH) + { + $this->fetch_type = (bool) $object ? PDO::FETCH_OBJ : PDO::FETCH_BOTH; - public function result($object = TRUE, $type = PDO::FETCH_BOTH) - { - $this->fetch_type = (bool) $object ? PDO::FETCH_OBJ : PDO::FETCH_BOTH; + if ($this->fetch_type == PDO::FETCH_OBJ) { + $this->return_type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $this->return_type = $type; + } - if ($this->fetch_type == PDO::FETCH_OBJ) - { - $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $this->return_type = $type; - } + return $this; + } - return $this; - } + public function as_array($object = null, $type = PDO::FETCH_ASSOC) + { + return $this->result_array($object, $type); + } - public function as_array($object = NULL, $type = PDO::FETCH_ASSOC) - { - return $this->result_array($object, $type); - } + public function result_array($object = null, $type = PDO::FETCH_ASSOC) + { + $rows = array(); - public function result_array($object = NULL, $type = PDO::FETCH_ASSOC) - { - $rows = array(); + if (is_string($object)) { + $fetch = $object; + } elseif (is_bool($object)) { + if ($object === true) { + $fetch = PDO::FETCH_OBJ; - if (is_string($object)) - { - $fetch = $object; - } - elseif (is_bool($object)) - { - if ($object === TRUE) - { - $fetch = PDO::FETCH_OBJ; + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $fetch = PDO::FETCH_OBJ; + } + } else { + // Use the default config values + $fetch = $this->fetch_type; - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $fetch = PDO::FETCH_OBJ; - } - } - else - { - // Use the default config values - $fetch = $this->fetch_type; + if ($fetch == PDO::FETCH_OBJ) { + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } + } + try { + while ($row = $this->result->fetch($fetch)) { + $rows[] = $row; + } + } catch (PDOException $e) { + throw new Kohana_Database_Exception('database.error', $e->getMessage()); + return false; + } + return $rows; + } - if ($fetch == PDO::FETCH_OBJ) - { - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - } - try - { - while ($row = $this->result->fetch($fetch)) - { - $rows[] = $row; - } - } - catch(PDOException $e) - { - throw new Kohana_Database_Exception('database.error', $e->getMessage()); - return FALSE; - } - return $rows; - } + public function list_fields() + { + $field_names = array(); + for ($i = 0, $max = $this->result->columnCount(); $i < $max; $i++) { + $info = $this->result->getColumnMeta($i); + $field_names[] = $info['name']; + } + return $field_names; + } - public function list_fields() - { - $field_names = array(); - for ($i = 0, $max = $this->result->columnCount(); $i < $max; $i++) - { - $info = $this->result->getColumnMeta($i); - $field_names[] = $info['name']; - } - return $field_names; - } + public function seek($offset) + { + // To request a scrollable cursor for your PDOStatement object, you must + // set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you + // prepare the statement. + Kohana::log('error', get_class($this) . ' does not support scrollable cursors, ' . __FUNCTION__ . ' call ignored'); - public function seek($offset) - { - // To request a scrollable cursor for your PDOStatement object, you must - // set the PDO::ATTR_CURSOR attribute to PDO::CURSOR_SCROLL when you - // prepare the statement. - Kohana::log('error', get_class($this).' does not support scrollable cursors, '.__FUNCTION__.' call ignored'); + return false; + } - return FALSE; - } + public function offsetGet($offset) + { + try { + return $this->result->fetch($this->fetch_type, PDO::FETCH_ORI_ABS, $offset); + } catch (PDOException $e) { + throw new Kohana_Database_Exception('database.error', $e->getMessage()); + } + } - public function offsetGet($offset) - { - try - { - return $this->result->fetch($this->fetch_type, PDO::FETCH_ORI_ABS, $offset); - } - catch(PDOException $e) - { - throw new Kohana_Database_Exception('database.error', $e->getMessage()); - } - } - - public function rewind() - { - // Same problem that seek() has, see above. - return $this->seek(0); - } - -} // End PdoSqlite_Result Class \ No newline at end of file + public function rewind() + { + // Same problem that seek() has, see above. + return $this->seek(0); + } +} +// End PdoSqlite_Result Class diff --git a/lib/kohana/system/libraries/drivers/Database/Pgsql.php b/lib/kohana/system/libraries/drivers/Database/Pgsql.php index c53c843..3b2bb56 100644 --- a/lib/kohana/system/libraries/drivers/Database/Pgsql.php +++ b/lib/kohana/system/libraries/drivers/Database/Pgsql.php @@ -1,4 +1,13 @@ -db_config = $config; - /** - * Sets the config for the class. - * - * @param array database configuration - */ - public function __construct($config) - { - $this->db_config = $config; + Kohana::log('debug', 'PgSQL Database Driver Initialized'); + } - Kohana::log('debug', 'PgSQL Database Driver Initialized'); - } + public function connect() + { + // Check if link already exists + if (is_resource($this->link)) { + return $this->link; + } - public function connect() - { - // Check if link already exists - if (is_resource($this->link)) - return $this->link; + // Import the connect variables + extract($this->db_config['connection']); - // Import the connect variables - extract($this->db_config['connection']); + // Persistent connections enabled? + $connect = ($this->db_config['persistent'] == true) ? 'pg_pconnect' : 'pg_connect'; - // Persistent connections enabled? - $connect = ($this->db_config['persistent'] == TRUE) ? 'pg_pconnect' : 'pg_connect'; + // Build the connection info + $port = isset($port) ? 'port=\'' . $port . '\'' : ''; + $host = isset($host) ? 'host=\'' . $host . '\' ' . $port : ''; // if no host, connect with the socket - // Build the connection info - $port = isset($port) ? 'port=\''.$port.'\'' : ''; - $host = isset($host) ? 'host=\''.$host.'\' '.$port : ''; // if no host, connect with the socket + $connection_string = $host . ' dbname=\'' . $database . '\' user=\'' . $user . '\' password=\'' . $pass . '\''; + // Make the connection and select the database + if ($this->link = $connect($connection_string)) { + if ($charset = $this->db_config['character_set']) { + echo $this->set_charset($charset); + } - $connection_string = $host.' dbname=\''.$database.'\' user=\''.$user.'\' password=\''.$pass.'\''; - // Make the connection and select the database - if ($this->link = $connect($connection_string)) - { - if ($charset = $this->db_config['character_set']) - { - echo $this->set_charset($charset); - } + // Clear password after successful connect + $this->db_config['connection']['pass'] = null; - // Clear password after successful connect - $this->db_config['connection']['pass'] = NULL; + return $this->link; + } - return $this->link; - } + return false; + } - return FALSE; - } + public function query($sql) + { + // Only cache if it's turned on, and only cache if it's not a write statement + if ($this->db_config['cache'] and ! preg_match('#\b(?:INSERT|UPDATE|SET)\b#i', $sql)) { + $hash = $this->query_hash($sql); - public function query($sql) - { - // Only cache if it's turned on, and only cache if it's not a write statement - if ($this->db_config['cache'] AND ! preg_match('#\b(?:INSERT|UPDATE|SET)\b#i', $sql)) - { - $hash = $this->query_hash($sql); + if (! isset($this->query_cache[$hash])) { + // Set the cached object + $this->query_cache[$hash] = new Pgsql_Result(pg_query($this->link, $sql), $this->link, $this->db_config['object'], $sql); + } else { + // Rewind cached result + $this->query_cache[$hash]->rewind(); + } - if ( ! isset($this->query_cache[$hash])) - { - // Set the cached object - $this->query_cache[$hash] = new Pgsql_Result(pg_query($this->link, $sql), $this->link, $this->db_config['object'], $sql); - } - else - { - // Rewind cached result - $this->query_cache[$hash]->rewind(); - } + return $this->query_cache[$hash]; + } - return $this->query_cache[$hash]; - } + // Suppress warning triggered when a database error occurs (e.g., a constraint violation) + return new Pgsql_Result(@pg_query($this->link, $sql), $this->link, $this->db_config['object'], $sql); + } - // Suppress warning triggered when a database error occurs (e.g., a constraint violation) - return new Pgsql_Result(@pg_query($this->link, $sql), $this->link, $this->db_config['object'], $sql); - } + public function set_charset($charset) + { + $this->query('SET client_encoding TO ' . pg_escape_string($this->link, $charset)); + } - public function set_charset($charset) - { - $this->query('SET client_encoding TO '.pg_escape_string($this->link, $charset)); - } + public function escape_table($table) + { + if (!$this->db_config['escape']) { + return $table; + } - public function escape_table($table) - { - if (!$this->db_config['escape']) - return $table; + return '"' . str_replace('.', '"."', $table) . '"'; + } - return '"'.str_replace('.', '"."', $table).'"'; - } + public function escape_column($column) + { + if (!$this->db_config['escape']) { + return $column; + } - public function escape_column($column) - { - if (!$this->db_config['escape']) - return $column; + if ($column == '*') { + return $column; + } - if ($column == '*') - return $column; + // This matches any functions we support to SELECT. + if (preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) { + if (count($matches) == 3) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ')'; + } elseif (count($matches) == 5) { + return $matches[1] . '(' . $this->escape_column($matches[2]) . ') AS ' . $this->escape_column($matches[2]); + } + } - // This matches any functions we support to SELECT. - if ( preg_match('/(avg|count|sum|max|min)\(\s*(.*)\s*\)(\s*as\s*(.+)?)?/i', $column, $matches)) - { - if ( count($matches) == 3) - { - return $matches[1].'('.$this->escape_column($matches[2]).')'; - } - else if ( count($matches) == 5) - { - return $matches[1].'('.$this->escape_column($matches[2]).') AS '.$this->escape_column($matches[2]); - } - } + // This matches any modifiers we support to SELECT. + if (! preg_match('/\b(?:all|distinct)\s/i', $column)) { + if (stripos($column, ' AS ') !== false) { + // Force 'AS' to uppercase + $column = str_ireplace(' AS ', ' AS ', $column); - // This matches any modifiers we support to SELECT. - if ( ! preg_match('/\b(?:all|distinct)\s/i', $column)) - { - if (stripos($column, ' AS ') !== FALSE) - { - // Force 'AS' to uppercase - $column = str_ireplace(' AS ', ' AS ', $column); + // Runs escape_column on both sides of an AS statement + $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); - // Runs escape_column on both sides of an AS statement - $column = array_map(array($this, __FUNCTION__), explode(' AS ', $column)); + // Re-create the AS statement + return implode(' AS ', $column); + } - // Re-create the AS statement - return implode(' AS ', $column); - } + return preg_replace('/[^.*]+/', '"$0"', $column); + } - return preg_replace('/[^.*]+/', '"$0"', $column); - } + $parts = explode(' ', $column); + $column = ''; - $parts = explode(' ', $column); - $column = ''; + for ($i = 0, $c = count($parts); $i < $c; $i++) { + // The column is always last + if ($i == ($c - 1)) { + $column .= preg_replace('/[^.*]+/', '"$0"', $parts[$i]); + } else // otherwise, it's a modifier + { + $column .= $parts[$i] . ' '; + } + } + return $column; + } - for ($i = 0, $c = count($parts); $i < $c; $i++) - { - // The column is always last - if ($i == ($c - 1)) - { - $column .= preg_replace('/[^.*]+/', '"$0"', $parts[$i]); - } - else // otherwise, it's a modifier - { - $column .= $parts[$i].' '; - } - } - return $column; - } + public function regex($field, $match, $type, $num_regexs) + { + $prefix = ($num_regexs == 0) ? '' : $type; - public function regex($field, $match, $type, $num_regexs) - { - $prefix = ($num_regexs == 0) ? '' : $type; + return $prefix . ' ' . $this->escape_column($field) . ' ~* \'' . $this->escape_str($match) . '\''; + } - return $prefix.' '.$this->escape_column($field).' ~* \''.$this->escape_str($match).'\''; - } + public function notregex($field, $match, $type, $num_regexs) + { + $prefix = $num_regexs == 0 ? '' : $type; - public function notregex($field, $match, $type, $num_regexs) - { - $prefix = $num_regexs == 0 ? '' : $type; + return $prefix . ' ' . $this->escape_column($field) . ' !~* \'' . $this->escape_str($match) . '\''; + } - return $prefix.' '.$this->escape_column($field).' !~* \''.$this->escape_str($match) . '\''; - } + public function limit($limit, $offset = 0) + { + return 'LIMIT ' . $limit . ' OFFSET ' . $offset; + } - public function limit($limit, $offset = 0) - { - return 'LIMIT '.$limit.' OFFSET '.$offset; - } + public function compile_select($database) + { + $sql = ($database['distinct'] == true) ? 'SELECT DISTINCT ' : 'SELECT '; + $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; - public function compile_select($database) - { - $sql = ($database['distinct'] == TRUE) ? 'SELECT DISTINCT ' : 'SELECT '; - $sql .= (count($database['select']) > 0) ? implode(', ', $database['select']) : '*'; + if (count($database['from']) > 0) { + $sql .= "\nFROM "; + $sql .= implode(', ', $database['from']); + } - if (count($database['from']) > 0) - { - $sql .= "\nFROM "; - $sql .= implode(', ', $database['from']); - } + if (count($database['join']) > 0) { + foreach ($database['join'] as $join) { + $sql .= "\n" . $join['type'] . 'JOIN ' . implode(', ', $join['tables']) . ' ON ' . $join['conditions']; + } + } - if (count($database['join']) > 0) - { - foreach($database['join'] AS $join) - { - $sql .= "\n".$join['type'].'JOIN '.implode(', ', $join['tables']).' ON '.$join['conditions']; - } - } + if (count($database['where']) > 0) { + $sql .= "\nWHERE "; + } - if (count($database['where']) > 0) - { - $sql .= "\nWHERE "; - } + $sql .= implode("\n", $database['where']); - $sql .= implode("\n", $database['where']); + if (count($database['groupby']) > 0) { + $sql .= "\nGROUP BY "; + $sql .= implode(', ', $database['groupby']); + } - if (count($database['groupby']) > 0) - { - $sql .= "\nGROUP BY "; - $sql .= implode(', ', $database['groupby']); - } + if (count($database['having']) > 0) { + $sql .= "\nHAVING "; + $sql .= implode("\n", $database['having']); + } - if (count($database['having']) > 0) - { - $sql .= "\nHAVING "; - $sql .= implode("\n", $database['having']); - } + if (count($database['orderby']) > 0) { + $sql .= "\nORDER BY "; + $sql .= implode(', ', $database['orderby']); + } - if (count($database['orderby']) > 0) - { - $sql .= "\nORDER BY "; - $sql .= implode(', ', $database['orderby']); - } + if (is_numeric($database['limit'])) { + $sql .= "\n"; + $sql .= $this->limit($database['limit'], $database['offset']); + } - if (is_numeric($database['limit'])) - { - $sql .= "\n"; - $sql .= $this->limit($database['limit'], $database['offset']); - } + return $sql; + } - return $sql; - } + public function escape_str($str) + { + if (!$this->db_config['escape']) { + return $str; + } - public function escape_str($str) - { - if (!$this->db_config['escape']) - return $str; + is_resource($this->link) or $this->connect(); - is_resource($this->link) or $this->connect(); + return pg_escape_string($this->link, $str); + } - return pg_escape_string($this->link, $str); - } + public function list_tables() + { + $sql = 'SELECT table_schema || \'.\' || table_name FROM information_schema.tables WHERE table_schema NOT IN (\'pg_catalog\', \'information_schema\')'; + $result = $this->query($sql)->result(false, PGSQL_ASSOC); - public function list_tables() - { - $sql = 'SELECT table_schema || \'.\' || table_name FROM information_schema.tables WHERE table_schema NOT IN (\'pg_catalog\', \'information_schema\')'; - $result = $this->query($sql)->result(FALSE, PGSQL_ASSOC); + $retval = array(); + foreach ($result as $row) { + $retval[] = current($row); + } - $retval = array(); - foreach ($result as $row) - { - $retval[] = current($row); - } + return $retval; + } - return $retval; - } + public function show_error() + { + return pg_last_error($this->link); + } - public function show_error() - { - return pg_last_error($this->link); - } + public function list_fields($table) + { + $result = null; - public function list_fields($table) - { - $result = NULL; + foreach ($this->field_data($table) as $row) { + // Make an associative array + $result[$row->column_name] = $this->sql_type($row->data_type); - foreach ($this->field_data($table) as $row) - { - // Make an associative array - $result[$row->column_name] = $this->sql_type($row->data_type); + if (!strncmp($row->column_default, 'nextval(', 8)) { + $result[$row->column_name]['sequenced'] = true; + } - if (!strncmp($row->column_default, 'nextval(', 8)) - { - $result[$row->column_name]['sequenced'] = TRUE; - } + if ($row->is_nullable === 'YES') { + $result[$row->column_name]['null'] = true; + } + } - if ($row->is_nullable === 'YES') - { - $result[$row->column_name]['null'] = TRUE; - } - } + if (!isset($result)) { + throw new Kohana_Database_Exception('database.table_not_found', $table); + } - if (!isset($result)) - throw new Kohana_Database_Exception('database.table_not_found', $table); + return $result; + } - return $result; - } - - public function field_data($table) - { - // http://www.postgresql.org/docs/8.3/static/infoschema-columns.html - $result = $this->query(' + public function field_data($table) + { + // http://www.postgresql.org/docs/8.3/static/infoschema-columns.html + $result = $this->query(' SELECT column_name, column_default, is_nullable, data_type, udt_name, character_maximum_length, numeric_precision, numeric_precision_radix, numeric_scale FROM information_schema.columns - WHERE table_name = \''. $this->escape_str($table) .'\' + WHERE table_name = \'' . $this->escape_str($table) . '\' ORDER BY ordinal_position '); - return $result->result_array(TRUE); - } - -} // End Database_Pgsql_Driver Class + return $result->result_array(true); + } +} +// End Database_Pgsql_Driver Class /** * PostgreSQL Result */ -class Pgsql_Result extends Database_Result { +class Pgsql_Result extends Database_Result +{ + // Data fetching types + protected $fetch_type = 'pgsql_fetch_object'; + protected $return_type = PGSQL_ASSOC; - // Data fetching types - protected $fetch_type = 'pgsql_fetch_object'; - protected $return_type = PGSQL_ASSOC; + /** + * Sets up the result variables. + * + * @param resource query result + * @param resource database link + * @param boolean return objects or arrays + * @param string SQL query that was run + */ + public function __construct($result, $link, $object = true, $sql = '') + { + $this->link = $link; + $this->result = $result; - /** - * Sets up the result variables. - * - * @param resource query result - * @param resource database link - * @param boolean return objects or arrays - * @param string SQL query that was run - */ - public function __construct($result, $link, $object = TRUE, $sql) - { - $this->link = $link; - $this->result = $result; + // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query + if (is_resource($result)) { + // Its an DELETE, INSERT, REPLACE, or UPDATE query + if (preg_match('/^(?:delete|insert|replace|update)\b/iD', trim($sql), $matches)) { + $this->insert_id = (strtolower($matches[0]) == 'insert') ? $this->insert_id() : false; + $this->total_rows = pg_affected_rows($this->result); + } else { + $this->current_row = 0; + $this->total_rows = pg_num_rows($this->result); + $this->fetch_type = ($object === true) ? 'pg_fetch_object' : 'pg_fetch_array'; + } + } else { + throw new Kohana_Database_Exception('database.error', pg_last_error() . ' - ' . $sql); + } - // If the query is a resource, it was a SELECT, SHOW, DESCRIBE, EXPLAIN query - if (is_resource($result)) - { - // Its an DELETE, INSERT, REPLACE, or UPDATE query - if (preg_match('/^(?:delete|insert|replace|update)\b/iD', trim($sql), $matches)) - { - $this->insert_id = (strtolower($matches[0]) == 'insert') ? $this->insert_id() : FALSE; - $this->total_rows = pg_affected_rows($this->result); - } - else - { - $this->current_row = 0; - $this->total_rows = pg_num_rows($this->result); - $this->fetch_type = ($object === TRUE) ? 'pg_fetch_object' : 'pg_fetch_array'; - } - } - else - { - throw new Kohana_Database_Exception('database.error', pg_last_error().' - '.$sql); - } + // Set result type + $this->result($object); - // Set result type - $this->result($object); + // Store the SQL + $this->sql = $sql; + } - // Store the SQL - $this->sql = $sql; - } + /** + * Magic __destruct function, frees the result. + */ + public function __destruct() + { + if (is_resource($this->result)) { + pg_free_result($this->result); + } + } - /** - * Magic __destruct function, frees the result. - */ - public function __destruct() - { - if (is_resource($this->result)) - { - pg_free_result($this->result); - } - } + public function result($object = true, $type = PGSQL_ASSOC) + { + $this->fetch_type = ((bool) $object) ? 'pg_fetch_object' : 'pg_fetch_array'; - public function result($object = TRUE, $type = PGSQL_ASSOC) - { - $this->fetch_type = ((bool) $object) ? 'pg_fetch_object' : 'pg_fetch_array'; + // This check has to be outside the previous statement, because we do not + // know the state of fetch_type when $object = NULL + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + if ($this->fetch_type == 'pg_fetch_object') { + $this->return_type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $this->return_type = $type; + } - // This check has to be outside the previous statement, because we do not - // know the state of fetch_type when $object = NULL - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - if ($this->fetch_type == 'pg_fetch_object') - { - $this->return_type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $this->return_type = $type; - } + return $this; + } - return $this; - } + public function as_array($object = null, $type = PGSQL_ASSOC) + { + return $this->result_array($object, $type); + } - public function as_array($object = NULL, $type = PGSQL_ASSOC) - { - return $this->result_array($object, $type); - } + public function result_array($object = null, $type = PGSQL_ASSOC) + { + $rows = array(); - public function result_array($object = NULL, $type = PGSQL_ASSOC) - { - $rows = array(); + if (is_string($object)) { + $fetch = $object; + } elseif (is_bool($object)) { + if ($object === true) { + $fetch = 'pg_fetch_object'; - if (is_string($object)) - { - $fetch = $object; - } - elseif (is_bool($object)) - { - if ($object === TRUE) - { - $fetch = 'pg_fetch_object'; + // NOTE - The class set by $type must be defined before fetching the result, + // autoloading is disabled to save a lot of stupid overhead. + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } else { + $fetch = 'pg_fetch_array'; + } + } else { + // Use the default config values + $fetch = $this->fetch_type; - // NOTE - The class set by $type must be defined before fetching the result, - // autoloading is disabled to save a lot of stupid overhead. - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - else - { - $fetch = 'pg_fetch_array'; - } - } - else - { - // Use the default config values - $fetch = $this->fetch_type; + if ($fetch == 'pg_fetch_object') { + $type = (is_string($type) and Kohana::auto_load($type)) ? $type : 'stdClass'; + } + } - if ($fetch == 'pg_fetch_object') - { - $type = (is_string($type) AND Kohana::auto_load($type)) ? $type : 'stdClass'; - } - } + if ($this->total_rows) { + pg_result_seek($this->result, 0); - if ($this->total_rows) - { - pg_result_seek($this->result, 0); + while ($row = $fetch($this->result, null, $type)) { + $rows[] = $row; + } + } - while ($row = $fetch($this->result, NULL, $type)) - { - $rows[] = $row; - } - } + return $rows; + } - return $rows; - } + public function insert_id() + { + if ($this->insert_id === null) { + $query = 'SELECT LASTVAL() AS insert_id'; - public function insert_id() - { - if ($this->insert_id === NULL) - { - $query = 'SELECT LASTVAL() AS insert_id'; + // Disable error reporting for this, just to silence errors on + // tables that have no serial column. + $ER = error_reporting(0); - // Disable error reporting for this, just to silence errors on - // tables that have no serial column. - $ER = error_reporting(0); + $result = pg_query($this->link, $query); + $insert_id = pg_fetch_array($result, null, PGSQL_ASSOC); - $result = pg_query($this->link, $query); - $insert_id = pg_fetch_array($result, NULL, PGSQL_ASSOC); + $this->insert_id = $insert_id['insert_id']; - $this->insert_id = $insert_id['insert_id']; + // Reset error reporting + error_reporting($ER); + } - // Reset error reporting - error_reporting($ER); - } + return $this->insert_id; + } - return $this->insert_id; - } + public function seek($offset) + { + if ($this->offsetExists($offset) and pg_result_seek($this->result, $offset)) { + // Set the current row to the offset + $this->current_row = $offset; - public function seek($offset) - { - if ($this->offsetExists($offset) AND pg_result_seek($this->result, $offset)) - { - // Set the current row to the offset - $this->current_row = $offset; + return true; + } - return TRUE; - } + return false; + } - return FALSE; - } + public function list_fields() + { + $field_names = array(); - public function list_fields() - { - $field_names = array(); + $fields = pg_num_fields($this->result); + for ($i = 0; $i < $fields; ++$i) { + $field_names[] = pg_field_name($this->result, $i); + } - $fields = pg_num_fields($this->result); - for ($i = 0; $i < $fields; ++$i) - { - $field_names[] = pg_field_name($this->result, $i); - } + return $field_names; + } - return $field_names; - } + /** + * ArrayAccess: offsetGet + */ + public function offsetGet($offset) + { + if (! $this->seek($offset)) { + return false; + } - /** - * ArrayAccess: offsetGet - */ - public function offsetGet($offset) - { - if ( ! $this->seek($offset)) - return FALSE; - - // Return the row by calling the defined fetching callback - $fetch = $this->fetch_type; - return $fetch($this->result, NULL, $this->return_type); - } - -} // End Pgsql_Result Class + // Return the row by calling the defined fetching callback + $fetch = $this->fetch_type; + return $fetch($this->result, null, $this->return_type); + } +} +// End Pgsql_Result Class /** * PostgreSQL Prepared Statement (experimental) */ -class Kohana_Pgsql_Statement { +class Kohana_Pgsql_Statement +{ + protected $link = null; + protected $stmt; - protected $link = NULL; - protected $stmt; + public function __construct($sql, $link) + { + $this->link = $link; - public function __construct($sql, $link) - { - $this->link = $link; + $this->stmt = $this->link->prepare($sql); - $this->stmt = $this->link->prepare($sql); + return $this; + } - return $this; - } + public function __destruct() + { + $this->stmt->close(); + } - public function __destruct() - { - $this->stmt->close(); - } + // Sets the bind parameters + public function bind_params() + { + $argv = func_get_args(); + return $this; + } - // Sets the bind parameters - public function bind_params() - { - $argv = func_get_args(); - return $this; - } + // sets the statement values to the bound parameters + public function set_vals() + { + return $this; + } - // sets the statement values to the bound parameters - public function set_vals() - { - return $this; - } - - // Runs the statement - public function execute() - { - return $this; - } + // Runs the statement + public function execute() + { + return $this; + } } diff --git a/lib/kohana/system/libraries/drivers/Image.php b/lib/kohana/system/libraries/drivers/Image.php index 5c4ab1b..9c0d38c 100644 --- a/lib/kohana/system/libraries/drivers/Image.php +++ b/lib/kohana/system/libraries/drivers/Image.php @@ -1,4 +1,12 @@ - $args) { + if (! $this->$func($args)) { + return false; + } + } - /** - * Executes a set of actions, defined in pairs. - * - * @param array actions - * @return boolean - */ - public function execute($actions) - { - foreach ($actions as $func => $args) - { - if ( ! $this->$func($args)) - return FALSE; - } + return true; + } - return TRUE; - } + /** + * Sanitize and normalize a geometry array based on the temporary image + * width and height. Valid properties are: width, height, top, left. + * + * @param array geometry properties + * @return void + */ + protected function sanitize_geometry(&$geometry) + { + list($width, $height) = $this->properties(); - /** - * Sanitize and normalize a geometry array based on the temporary image - * width and height. Valid properties are: width, height, top, left. - * - * @param array geometry properties - * @return void - */ - protected function sanitize_geometry( & $geometry) - { - list($width, $height) = $this->properties(); + // Turn off error reporting + $reporting = error_reporting(0); - // Turn off error reporting - $reporting = error_reporting(0); + // Width and height cannot exceed current image size + $geometry['width'] = min($geometry['width'], $width); + $geometry['height'] = min($geometry['height'], $height); - // Width and height cannot exceed current image size - $geometry['width'] = min($geometry['width'], $width); - $geometry['height'] = min($geometry['height'], $height); + // Set standard coordinates if given, otherwise use pixel values + if ($geometry['top'] === 'center') { + $geometry['top'] = floor(($height / 2) - ($geometry['height'] / 2)); + } elseif ($geometry['top'] === 'top') { + $geometry['top'] = 0; + } elseif ($geometry['top'] === 'bottom') { + $geometry['top'] = $height - $geometry['height']; + } - // Set standard coordinates if given, otherwise use pixel values - if ($geometry['top'] === 'center') - { - $geometry['top'] = floor(($height / 2) - ($geometry['height'] / 2)); - } - elseif ($geometry['top'] === 'top') - { - $geometry['top'] = 0; - } - elseif ($geometry['top'] === 'bottom') - { - $geometry['top'] = $height - $geometry['height']; - } + // Set standard coordinates if given, otherwise use pixel values + if ($geometry['left'] === 'center') { + $geometry['left'] = floor(($width / 2) - ($geometry['width'] / 2)); + } elseif ($geometry['left'] === 'left') { + $geometry['left'] = 0; + } elseif ($geometry['left'] === 'right') { + $geometry['left'] = $width - $geometry['height']; + } - // Set standard coordinates if given, otherwise use pixel values - if ($geometry['left'] === 'center') - { - $geometry['left'] = floor(($width / 2) - ($geometry['width'] / 2)); - } - elseif ($geometry['left'] === 'left') - { - $geometry['left'] = 0; - } - elseif ($geometry['left'] === 'right') - { - $geometry['left'] = $width - $geometry['height']; - } + // Restore error reporting + error_reporting($reporting); + } - // Restore error reporting - error_reporting($reporting); - } + /** + * Return the current width and height of the temporary image. This is mainly + * needed for sanitizing the geometry. + * + * @return array width, height + */ + abstract protected function properties(); - /** - * Return the current width and height of the temporary image. This is mainly - * needed for sanitizing the geometry. - * - * @return array width, height - */ - abstract protected function properties(); + /** + * Process an image with a set of actions. + * + * @param string image filename + * @param array actions to execute + * @param string destination directory path + * @param string destination filename + * @return boolean + */ + abstract public function process($image, $actions, $dir, $file); - /** - * Process an image with a set of actions. - * - * @param string image filename - * @param array actions to execute - * @param string destination directory path - * @param string destination filename - * @return boolean - */ - abstract public function process($image, $actions, $dir, $file); + /** + * Flip an image. Valid directions are horizontal and vertical. + * + * @param integer direction to flip + * @return boolean + */ + abstract public function flip($direction); - /** - * Flip an image. Valid directions are horizontal and vertical. - * - * @param integer direction to flip - * @return boolean - */ - abstract function flip($direction); + /** + * Crop an image. Valid properties are: width, height, top, left. + * + * @param array new properties + * @return boolean + */ + abstract public function crop($properties); - /** - * Crop an image. Valid properties are: width, height, top, left. - * - * @param array new properties - * @return boolean - */ - abstract function crop($properties); + /** + * Resize an image. Valid properties are: width, height, and master. + * + * @param array new properties + * @return boolean + */ + abstract public function resize($properties); - /** - * Resize an image. Valid properties are: width, height, and master. - * - * @param array new properties - * @return boolean - */ - abstract public function resize($properties); + /** + * Rotate an image. Valid amounts are -180 to 180. + * + * @param integer amount to rotate + * @return boolean + */ + abstract public function rotate($amount); - /** - * Rotate an image. Valid amounts are -180 to 180. - * - * @param integer amount to rotate - * @return boolean - */ - abstract public function rotate($amount); - - /** - * Sharpen and image. Valid amounts are 1 to 100. - * - * @param integer amount to sharpen - * @return boolean - */ - abstract public function sharpen($amount); - -} // End Image Driver \ No newline at end of file + /** + * Sharpen and image. Valid amounts are 1 to 100. + * + * @param integer amount to sharpen + * @return boolean + */ + abstract public function sharpen($amount); +} +// End Image Driver diff --git a/lib/kohana/system/libraries/drivers/Image/GD.php b/lib/kohana/system/libraries/drivers/Image/GD.php index b3610b3..2cf9c52 100644 --- a/lib/kohana/system/libraries/drivers/Image/GD.php +++ b/lib/kohana/system/libraries/drivers/Image/GD.php @@ -1,4 +1,12 @@ -image = $image; - // Load the image - $this->image = $image; + // Create the GD image resource + $this->tmp_image = $create($image['file']); - // Create the GD image resource - $this->tmp_image = $create($image['file']); + // Get the quality setting from the actions + $quality = arr::remove('quality', $actions); - // Get the quality setting from the actions - $quality = arr::remove('quality', $actions); + if ($status = $this->execute($actions)) { + // Prevent the alpha from being lost + imagealphablending($this->tmp_image, true); + imagesavealpha($this->tmp_image, true); - if ($status = $this->execute($actions)) - { - // Prevent the alpha from being lost - imagealphablending($this->tmp_image, TRUE); - imagesavealpha($this->tmp_image, TRUE); + switch ($save) { + case 'imagejpeg': + // Default the quality to 95 + ($quality === null) and $quality = 95; + break; + case 'imagegif': + // Remove the quality setting, GIF doesn't use it + unset($quality); + break; + case 'imagepng': + // Always use a compression level of 9 for PNGs. This does not + // affect quality, it only increases the level of compression! + $quality = 9; + break; + } - switch ($save) - { - case 'imagejpeg': - // Default the quality to 95 - ($quality === NULL) and $quality = 95; - break; - case 'imagegif': - // Remove the quality setting, GIF doesn't use it - unset($quality); - break; - case 'imagepng': - // Always use a compression level of 9 for PNGs. This does not - // affect quality, it only increases the level of compression! - $quality = 9; - break; - } + if ($render === false) { + // Set the status to the save return value, saving with the quality requested + $status = isset($quality) ? $save($this->tmp_image, $dir . $file, $quality) : $save($this->tmp_image, $dir . $file); + } else { + // Output the image directly to the browser + switch ($save) { + case 'imagejpeg': + header('Content-Type: image/jpeg'); + break; + case 'imagegif': + header('Content-Type: image/gif'); + break; + case 'imagepng': + header('Content-Type: image/png'); + break; + } - if ($render === FALSE) - { - // Set the status to the save return value, saving with the quality requested - $status = isset($quality) ? $save($this->tmp_image, $dir.$file, $quality) : $save($this->tmp_image, $dir.$file); - } - else - { - // Output the image directly to the browser - switch ($save) - { - case 'imagejpeg': - header('Content-Type: image/jpeg'); - break; - case 'imagegif': - header('Content-Type: image/gif'); - break; - case 'imagepng': - header('Content-Type: image/png'); - break; - } + $status = isset($quality) ? $save($this->tmp_image, null, $quality) : $save($this->tmp_image); + } - $status = isset($quality) ? $save($this->tmp_image, NULL, $quality) : $save($this->tmp_image); - } + // Destroy the temporary image + imagedestroy($this->tmp_image); + } - // Destroy the temporary image - imagedestroy($this->tmp_image); - } + return $status; + } - return $status; - } + public function flip($direction) + { + // Get the current width and height + $width = imagesx($this->tmp_image); + $height = imagesy($this->tmp_image); - public function flip($direction) - { - // Get the current width and height - $width = imagesx($this->tmp_image); - $height = imagesy($this->tmp_image); + // Create the flipped image + $flipped = $this->imagecreatetransparent($width, $height); - // Create the flipped image - $flipped = $this->imagecreatetransparent($width, $height); + if ($direction === Image::HORIZONTAL) { + for ($x = 0; $x < $width; $x++) { + $status = imagecopy($flipped, $this->tmp_image, $x, 0, $width - $x - 1, 0, 1, $height); + } + } elseif ($direction === Image::VERTICAL) { + for ($y = 0; $y < $height; $y++) { + $status = imagecopy($flipped, $this->tmp_image, 0, $y, 0, $height - $y - 1, $width, 1); + } + } else { + // Do nothing + return true; + } - if ($direction === Image::HORIZONTAL) - { - for ($x = 0; $x < $width; $x++) - { - $status = imagecopy($flipped, $this->tmp_image, $x, 0, $width - $x - 1, 0, 1, $height); - } - } - elseif ($direction === Image::VERTICAL) - { - for ($y = 0; $y < $height; $y++) - { - $status = imagecopy($flipped, $this->tmp_image, 0, $y, 0, $height - $y - 1, $width, 1); - } - } - else - { - // Do nothing - return TRUE; - } + if ($status === true) { + // Swap the new image for the old one + imagedestroy($this->tmp_image); + $this->tmp_image = $flipped; + } - if ($status === TRUE) - { - // Swap the new image for the old one - imagedestroy($this->tmp_image); - $this->tmp_image = $flipped; - } + return $status; + } - return $status; - } + public function crop($properties) + { + // Sanitize the cropping settings + $this->sanitize_geometry($properties); - public function crop($properties) - { - // Sanitize the cropping settings - $this->sanitize_geometry($properties); + // Get the current width and height + $width = imagesx($this->tmp_image); + $height = imagesy($this->tmp_image); - // Get the current width and height - $width = imagesx($this->tmp_image); - $height = imagesy($this->tmp_image); + // Create the temporary image to copy to + $img = $this->imagecreatetransparent($properties['width'], $properties['height']); - // Create the temporary image to copy to - $img = $this->imagecreatetransparent($properties['width'], $properties['height']); + // Execute the crop + if ($status = imagecopyresampled($img, $this->tmp_image, 0, 0, $properties['left'], $properties['top'], $width, $height, $width, $height)) { + // Swap the new image for the old one + imagedestroy($this->tmp_image); + $this->tmp_image = $img; + } - // Execute the crop - if ($status = imagecopyresampled($img, $this->tmp_image, 0, 0, $properties['left'], $properties['top'], $width, $height, $width, $height)) - { - // Swap the new image for the old one - imagedestroy($this->tmp_image); - $this->tmp_image = $img; - } + return $status; + } - return $status; - } + public function resize($properties) + { + // Get the current width and height + $width = imagesx($this->tmp_image); + $height = imagesy($this->tmp_image); - public function resize($properties) - { - // Get the current width and height - $width = imagesx($this->tmp_image); - $height = imagesy($this->tmp_image); + if (substr($properties['width'], -1) === '%') { + // Recalculate the percentage to a pixel size + $properties['width'] = round($width * (substr($properties['width'], 0, -1) / 100)); + } - if (substr($properties['width'], -1) === '%') - { - // Recalculate the percentage to a pixel size - $properties['width'] = round($width * (substr($properties['width'], 0, -1) / 100)); - } + if (substr($properties['height'], -1) === '%') { + // Recalculate the percentage to a pixel size + $properties['height'] = round($height * (substr($properties['height'], 0, -1) / 100)); + } - if (substr($properties['height'], -1) === '%') - { - // Recalculate the percentage to a pixel size - $properties['height'] = round($height * (substr($properties['height'], 0, -1) / 100)); - } - - // Recalculate the width and height, if they are missing - empty($properties['width']) and $properties['width'] = round($width * $properties['height'] / $height); - empty($properties['height']) and $properties['height'] = round($height * $properties['width'] / $width); - - if ($properties['master'] === Image::AUTO) - { - // Change an automatic master dim to the correct type - $properties['master'] = (($width / $properties['width']) > ($height / $properties['height'])) ? Image::WIDTH : Image::HEIGHT; - } + // Recalculate the width and height, if they are missing + empty($properties['width']) and $properties['width'] = round($width * $properties['height'] / $height); + empty($properties['height']) and $properties['height'] = round($height * $properties['width'] / $width); - if (empty($properties['height']) OR $properties['master'] === Image::WIDTH) - { - // Recalculate the height based on the width - $properties['height'] = round($height * $properties['width'] / $width); - } + if ($properties['master'] === Image::AUTO) { + // Change an automatic master dim to the correct type + $properties['master'] = (($width / $properties['width']) > ($height / $properties['height'])) ? Image::WIDTH : Image::HEIGHT; + } - if (empty($properties['width']) OR $properties['master'] === Image::HEIGHT) - { - // Recalculate the width based on the height - $properties['width'] = round($width * $properties['height'] / $height); - } + if (empty($properties['height']) or $properties['master'] === Image::WIDTH) { + // Recalculate the height based on the width + $properties['height'] = round($height * $properties['width'] / $width); + } - // Test if we can do a resize without resampling to speed up the final resize - if ($properties['width'] > $width / 2 AND $properties['height'] > $height / 2) - { - // Presize width and height - $pre_width = $width; - $pre_height = $height; + if (empty($properties['width']) or $properties['master'] === Image::HEIGHT) { + // Recalculate the width based on the height + $properties['width'] = round($width * $properties['height'] / $height); + } - // The maximum reduction is 10% greater than the final size - $max_reduction_width = round($properties['width'] * 1.1); - $max_reduction_height = round($properties['height'] * 1.1); + // Test if we can do a resize without resampling to speed up the final resize + if ($properties['width'] > $width / 2 and $properties['height'] > $height / 2) { + // Presize width and height + $pre_width = $width; + $pre_height = $height; - // Reduce the size using an O(2n) algorithm, until it reaches the maximum reduction - while ($pre_width / 2 > $max_reduction_width AND $pre_height / 2 > $max_reduction_height) - { - $pre_width /= 2; - $pre_height /= 2; - } + // The maximum reduction is 10% greater than the final size + $max_reduction_width = round($properties['width'] * 1.1); + $max_reduction_height = round($properties['height'] * 1.1); - // Create the temporary image to copy to - $img = $this->imagecreatetransparent($pre_width, $pre_height); + // Reduce the size using an O(2n) algorithm, until it reaches the maximum reduction + while ($pre_width / 2 > $max_reduction_width and $pre_height / 2 > $max_reduction_height) { + $pre_width /= 2; + $pre_height /= 2; + } - if ($status = imagecopyresized($img, $this->tmp_image, 0, 0, 0, 0, $pre_width, $pre_height, $width, $height)) - { - // Swap the new image for the old one - imagedestroy($this->tmp_image); - $this->tmp_image = $img; - } + // Create the temporary image to copy to + $img = $this->imagecreatetransparent($pre_width, $pre_height); - // Set the width and height to the presize - $width = $pre_width; - $height = $pre_height; - } + if ($status = imagecopyresized($img, $this->tmp_image, 0, 0, 0, 0, $pre_width, $pre_height, $width, $height)) { + // Swap the new image for the old one + imagedestroy($this->tmp_image); + $this->tmp_image = $img; + } - // Create the temporary image to copy to - $img = $this->imagecreatetransparent($properties['width'], $properties['height']); + // Set the width and height to the presize + $width = $pre_width; + $height = $pre_height; + } - // Execute the resize - if ($status = imagecopyresampled($img, $this->tmp_image, 0, 0, 0, 0, $properties['width'], $properties['height'], $width, $height)) - { - // Swap the new image for the old one - imagedestroy($this->tmp_image); - $this->tmp_image = $img; - } + // Create the temporary image to copy to + $img = $this->imagecreatetransparent($properties['width'], $properties['height']); - return $status; - } + // Execute the resize + if ($status = imagecopyresampled($img, $this->tmp_image, 0, 0, 0, 0, $properties['width'], $properties['height'], $width, $height)) { + // Swap the new image for the old one + imagedestroy($this->tmp_image); + $this->tmp_image = $img; + } - public function rotate($amount) - { - // Use current image to rotate - $img = $this->tmp_image; + return $status; + } - // White, with an alpha of 0 - $transparent = imagecolorallocatealpha($img, 255, 255, 255, 127); + public function rotate($amount) + { + // Use current image to rotate + $img = $this->tmp_image; - // Rotate, setting the transparent color - $img = imagerotate($img, 360 - $amount, $transparent, -1); + // White, with an alpha of 0 + $transparent = imagecolorallocatealpha($img, 255, 255, 255, 127); - // Fill the background with the transparent "color" - imagecolortransparent($img, $transparent); + // Rotate, setting the transparent color + $img = imagerotate($img, 360 - $amount, $transparent, -1); - // Merge the images - if ($status = imagecopymerge($this->tmp_image, $img, 0, 0, 0, 0, imagesx($this->tmp_image), imagesy($this->tmp_image), 100)) - { - // Prevent the alpha from being lost - imagealphablending($img, TRUE); - imagesavealpha($img, TRUE); + // Fill the background with the transparent "color" + imagecolortransparent($img, $transparent); - // Swap the new image for the old one - imagedestroy($this->tmp_image); - $this->tmp_image = $img; - } + // Merge the images + if ($status = imagecopymerge($this->tmp_image, $img, 0, 0, 0, 0, imagesx($this->tmp_image), imagesy($this->tmp_image), 100)) { + // Prevent the alpha from being lost + imagealphablending($img, true); + imagesavealpha($img, true); - return $status; - } + // Swap the new image for the old one + imagedestroy($this->tmp_image); + $this->tmp_image = $img; + } - public function sharpen($amount) - { - // Make sure that the sharpening function is available - if ( ! function_exists('imageconvolution')) - throw new Kohana_Exception('image.unsupported_method', __FUNCTION__); + return $status; + } - // Amount should be in the range of 18-10 - $amount = round(abs(-18 + ($amount * 0.08)), 2); + public function sharpen($amount) + { + // Make sure that the sharpening function is available + if (! function_exists('imageconvolution')) { + throw new Kohana_Exception('image.unsupported_method', __FUNCTION__); + } - // Gaussian blur matrix - $matrix = array - ( - array(-1, -1, -1), - array(-1, $amount, -1), - array(-1, -1, -1), - ); + // Amount should be in the range of 18-10 + $amount = round(abs(-18 + ($amount * 0.08)), 2); - // Perform the sharpen - return imageconvolution($this->tmp_image, $matrix, $amount - 8, 0); - } + // Gaussian blur matrix + $matrix = array + ( + array(-1, -1, -1), + array(-1, $amount, -1), + array(-1, -1, -1), + ); - protected function properties() - { - return array(imagesx($this->tmp_image), imagesy($this->tmp_image)); - } + // Perform the sharpen + return imageconvolution($this->tmp_image, $matrix, $amount - 8, 0); + } - /** - * Returns an image with a transparent background. Used for rotating to - * prevent unfilled backgrounds. - * - * @param integer image width - * @param integer image height - * @return resource - */ - protected function imagecreatetransparent($width, $height) - { - if (self::$blank_png === NULL) - { - // Decode the blank PNG if it has not been done already - self::$blank_png = imagecreatefromstring(base64_decode - ( - 'iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29'. - 'mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADqSURBVHjaYvz//z/DYAYAAcTEMMgBQAANegcCBN'. - 'CgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQ'. - 'AANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoH'. - 'AgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB'. - '3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAgAEAMpcDTTQWJVEAAAAASUVORK5CYII=' - )); + protected function properties() + { + return array(imagesx($this->tmp_image), imagesy($this->tmp_image)); + } - // Set the blank PNG width and height - self::$blank_png_width = imagesx(self::$blank_png); - self::$blank_png_height = imagesy(self::$blank_png); - } + /** + * Returns an image with a transparent background. Used for rotating to + * prevent unfilled backgrounds. + * + * @param integer image width + * @param integer image height + * @return resource + */ + protected function imagecreatetransparent($width, $height) + { + if (self::$blank_png === null) { + // Decode the blank PNG if it has not been done already + self::$blank_png = imagecreatefromstring(base64_decode( + 'iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29' . + 'mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAADqSURBVHjaYvz//z/DYAYAAcTEMMgBQAANegcCBN' . + 'CgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQ' . + 'AANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoH' . + 'AgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAAA16BwIE0KB' . + '3IEAADXoHAgTQoHcgQAANegcCBNCgdyBAgAEAMpcDTTQWJVEAAAAASUVORK5CYII=' + )); - $img = imagecreatetruecolor($width, $height); + // Set the blank PNG width and height + self::$blank_png_width = imagesx(self::$blank_png); + self::$blank_png_height = imagesy(self::$blank_png); + } - // Resize the blank image - imagecopyresized($img, self::$blank_png, 0, 0, 0, 0, $width, $height, self::$blank_png_width, self::$blank_png_height); + $img = imagecreatetruecolor($width, $height); - // Prevent the alpha from being lost - imagealphablending($img, FALSE); - imagesavealpha($img, TRUE); + // Resize the blank image + imagecopyresized($img, self::$blank_png, 0, 0, 0, 0, $width, $height, self::$blank_png_width, self::$blank_png_height); - return $img; - } + // Prevent the alpha from being lost + imagealphablending($img, false); + imagesavealpha($img, true); -} // End Image GD Driver \ No newline at end of file + return $img; + } +} +// End Image GD Driver diff --git a/lib/kohana/system/libraries/drivers/Image/GraphicsMagick.php b/lib/kohana/system/libraries/drivers/Image/GraphicsMagick.php index 8840eb8..b4d6e54 100644 --- a/lib/kohana/system/libraries/drivers/Image/GraphicsMagick.php +++ b/lib/kohana/system/libraries/drivers/Image/GraphicsMagick.php @@ -1,4 +1,12 @@ -ext = (PHP_SHLIB_SUFFIX === 'dll') ? '.exe' : ''; - // Set the command extension - $this->ext = (PHP_SHLIB_SUFFIX === 'dll') ? '.exe' : ''; - - // Check to make sure the provided path is correct - if ( ! is_file(realpath($config['directory']).'/gm'.$this->ext)) - throw new Kohana_Exception('image.graphicsmagick.not_found', 'gm'.$this->ext); + // Check to make sure the provided path is correct + if (! is_file(realpath($config['directory']) . '/gm' . $this->ext)) { + throw new Kohana_Exception('image.graphicsmagick.not_found', 'gm' . $this->ext); + } - // Set the installation directory - $this->dir = str_replace('\\', '/', realpath($config['directory'])).'/'; - } + // Set the installation directory + $this->dir = str_replace('\\', '/', realpath($config['directory'])) . '/'; + } - /** - * Creates a temporary image and executes the given actions. By creating a - * temporary copy of the image before manipulating it, this process is atomic. - */ - public function process($image, $actions, $dir, $file, $render = FALSE) - { - // We only need the filename - $image = $image['file']; + /** + * Creates a temporary image and executes the given actions. By creating a + * temporary copy of the image before manipulating it, this process is atomic. + */ + public function process($image, $actions, $dir, $file, $render = false) + { + // We only need the filename + $image = $image['file']; - // Unique temporary filename - $this->tmp_image = $dir.'k2img--'.sha1(time().$dir.$file).substr($file, strrpos($file, '.')); + // Unique temporary filename + $this->tmp_image = $dir . 'k2img--' . sha1(time() . $dir . $file) . substr($file, strrpos($file, '.')); - // Copy the image to the temporary file - copy($image, $this->tmp_image); + // Copy the image to the temporary file + copy($image, $this->tmp_image); - // Quality change is done last - $quality = (int) arr::remove('quality', $actions); + // Quality change is done last + $quality = (int) arr::remove('quality', $actions); - // Use 95 for the default quality - empty($quality) and $quality = 95; + // Use 95 for the default quality + empty($quality) and $quality = 95; - // All calls to these will need to be escaped, so do it now - $this->cmd_image = escapeshellarg($this->tmp_image); - $this->new_image = ($render)? $this->cmd_image : escapeshellarg($dir.$file); + // All calls to these will need to be escaped, so do it now + $this->cmd_image = escapeshellarg($this->tmp_image); + $this->new_image = ($render) ? $this->cmd_image : escapeshellarg($dir . $file); - if ($status = $this->execute($actions)) - { - // Use convert to change the image into its final version. This is - // done to allow the file type to change correctly, and to handle - // the quality conversion in the most effective way possible. - if ($error = exec(escapeshellcmd($this->dir.'gm'.$this->ext.' convert').' -quality '.$quality.'% '.$this->cmd_image.' '.$this->new_image)) - { - $this->errors[] = $error; - } - else - { - // Output the image directly to the browser - if ($render !== FALSE) - { - $contents = file_get_contents($this->tmp_image); - switch (substr($file, strrpos($file, '.') + 1)) - { - case 'jpg': - case 'jpeg': - header('Content-Type: image/jpeg'); - break; - case 'gif': - header('Content-Type: image/gif'); - break; - case 'png': - header('Content-Type: image/png'); - break; - } - echo $contents; - } - } - } + if ($status = $this->execute($actions)) { + // Use convert to change the image into its final version. This is + // done to allow the file type to change correctly, and to handle + // the quality conversion in the most effective way possible. + if ($error = exec(escapeshellcmd($this->dir . 'gm' . $this->ext . ' convert') . ' -quality ' . $quality . '% ' . $this->cmd_image . ' ' . $this->new_image)) { + $this->errors[] = $error; + } else { + // Output the image directly to the browser + if ($render !== false) { + $contents = file_get_contents($this->tmp_image); + switch (substr($file, strrpos($file, '.') + 1)) { + case 'jpg': + case 'jpeg': + header('Content-Type: image/jpeg'); + break; + case 'gif': + header('Content-Type: image/gif'); + break; + case 'png': + header('Content-Type: image/png'); + break; + } + echo $contents; + } + } + } - // Remove the temporary image - unlink($this->tmp_image); - $this->tmp_image = ''; + // Remove the temporary image + unlink($this->tmp_image); + $this->tmp_image = ''; - return $status; - } + return $status; + } - public function crop($prop) - { - // Sanitize and normalize the properties into geometry - $this->sanitize_geometry($prop); + public function crop($prop) + { + // Sanitize and normalize the properties into geometry + $this->sanitize_geometry($prop); - // Set the IM geometry based on the properties - $geometry = escapeshellarg($prop['width'].'x'.$prop['height'].'+'.$prop['left'].'+'.$prop['top']); + // Set the IM geometry based on the properties + $geometry = escapeshellarg($prop['width'] . 'x' . $prop['height'] . '+' . $prop['left'] . '+' . $prop['top']); - if ($error = exec(escapeshellcmd($this->dir.'gm'.$this->ext.' convert').' -crop '.$geometry.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + if ($error = exec(escapeshellcmd($this->dir . 'gm' . $this->ext . ' convert') . ' -crop ' . $geometry . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - return TRUE; - } + return true; + } - public function flip($dir) - { - // Convert the direction into a GM command - $dir = ($dir === Image::HORIZONTAL) ? '-flop' : '-flip'; + public function flip($dir) + { + // Convert the direction into a GM command + $dir = ($dir === Image::HORIZONTAL) ? '-flop' : '-flip'; - if ($error = exec(escapeshellcmd($this->dir.'gm'.$this->ext.' convert').' '.$dir.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + if ($error = exec(escapeshellcmd($this->dir . 'gm' . $this->ext . ' convert') . ' ' . $dir . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - return TRUE; - } + return true; + } - public function resize($prop) - { - switch ($prop['master']) - { - case Image::WIDTH: // Wx - $dim = escapeshellarg($prop['width'].'x'); - break; - case Image::HEIGHT: // xH - $dim = escapeshellarg('x'.$prop['height']); - break; - case Image::AUTO: // WxH - $dim = escapeshellarg($prop['width'].'x'.$prop['height']); - break; - case Image::NONE: // WxH! - $dim = escapeshellarg($prop['width'].'x'.$prop['height'].'!'); - break; - } + public function resize($prop) + { + switch ($prop['master']) { + case Image::WIDTH: // Wx + $dim = escapeshellarg($prop['width'] . 'x'); + break; + case Image::HEIGHT: // xH + $dim = escapeshellarg('x' . $prop['height']); + break; + case Image::AUTO: // WxH + $dim = escapeshellarg($prop['width'] . 'x' . $prop['height']); + break; + case Image::NONE: // WxH! + $dim = escapeshellarg($prop['width'] . 'x' . $prop['height'] . '!'); + break; + } - // Use "convert" to change the width and height - if ($error = exec(escapeshellcmd($this->dir.'gm'.$this->ext.' convert').' -resize '.$dim.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + // Use "convert" to change the width and height + if ($error = exec(escapeshellcmd($this->dir . 'gm' . $this->ext . ' convert') . ' -resize ' . $dim . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - return TRUE; - } + return true; + } - public function rotate($amt) - { - if ($error = exec(escapeshellcmd($this->dir.'gm'.$this->ext.' convert').' -rotate '.escapeshellarg($amt).' -background transparent '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + public function rotate($amt) + { + if ( + $error = exec(escapeshellcmd($this->dir . 'gm' . $this->ext . ' convert') . + ' -rotate ' . escapeshellarg($amt) . + ' -background transparent ' . + $this->cmd_image . + ' ' . $this->cmd_image) + ) { + $this->errors[] = $error; + return false; + } - return TRUE; - } + return true; + } - public function sharpen($amount) - { - // Set the sigma, radius, and amount. The amount formula allows a nice - // spread between 1 and 100 without pixelizing the image badly. - $sigma = 0.5; - $radius = $sigma * 2; - $amount = round(($amount / 80) * 3.14, 2); + public function sharpen($amount) + { + // Set the sigma, radius, and amount. The amount formula allows a nice + // spread between 1 and 100 without pixelizing the image badly. + $sigma = 0.5; + $radius = $sigma * 2; + $amount = round(($amount / 80) * 3.14, 2); - // Convert the amount to an GM command - $sharpen = escapeshellarg($radius.'x'.$sigma.'+'.$amount.'+0'); + // Convert the amount to an GM command + $sharpen = escapeshellarg($radius . 'x' . $sigma . '+' . $amount . '+0'); - if ($error = exec(escapeshellcmd($this->dir.'gm'.$this->ext.' convert').' -unsharp '.$sharpen.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + if ($error = exec(escapeshellcmd($this->dir . 'gm' . $this->ext . ' convert') . ' -unsharp ' . $sharpen . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - return TRUE; - } + return true; + } - protected function properties() - { - return array_slice(getimagesize($this->tmp_image), 0, 2, FALSE); - } - -} // End Image GraphicsMagick Driver \ No newline at end of file + protected function properties() + { + return array_slice(getimagesize($this->tmp_image), 0, 2, false); + } +} +// End Image GraphicsMagick Driver diff --git a/lib/kohana/system/libraries/drivers/Image/ImageMagick.php b/lib/kohana/system/libraries/drivers/Image/ImageMagick.php index 5a86663..962944c 100644 --- a/lib/kohana/system/libraries/drivers/Image/ImageMagick.php +++ b/lib/kohana/system/libraries/drivers/Image/ImageMagick.php @@ -1,4 +1,13 @@ -ext = (PHP_SHLIB_SUFFIX === 'dll') ? '.exe' : ''; - // Set the command extension - $this->ext = (PHP_SHLIB_SUFFIX === 'dll') ? '.exe' : ''; + // Check to make sure the provided path is correct + if (! is_file(realpath($config['directory']) . '/convert' . $this->ext)) { + throw new Kohana_Exception('image.imagemagick.not_found', 'convert' . $this->ext); + } - // Check to make sure the provided path is correct - if ( ! is_file(realpath($config['directory']).'/convert'.$this->ext)) - throw new Kohana_Exception('image.imagemagick.not_found', 'convert'.$this->ext); + // Set the installation directory + $this->dir = str_replace('\\', '/', realpath($config['directory'])) . '/'; + } - // Set the installation directory - $this->dir = str_replace('\\', '/', realpath($config['directory'])).'/'; - } + /** + * Creates a temporary image and executes the given actions. By creating a + * temporary copy of the image before manipulating it, this process is atomic. + */ + public function process($image, $actions, $dir, $file, $render = false) + { + // We only need the filename + $image = $image['file']; - /** - * Creates a temporary image and executes the given actions. By creating a - * temporary copy of the image before manipulating it, this process is atomic. - */ - public function process($image, $actions, $dir, $file, $render = FALSE) - { - // We only need the filename - $image = $image['file']; + // Unique temporary filename + $this->tmp_image = $dir . 'k2img--' . sha1(time() . $dir . $file) . substr($file, strrpos($file, '.')); - // Unique temporary filename - $this->tmp_image = $dir.'k2img--'.sha1(time().$dir.$file).substr($file, strrpos($file, '.')); + // Copy the image to the temporary file + copy($image, $this->tmp_image); - // Copy the image to the temporary file - copy($image, $this->tmp_image); + // Quality change is done last + $quality = (int) arr::remove('quality', $actions); - // Quality change is done last - $quality = (int) arr::remove('quality', $actions); + // Use 95 for the default quality + empty($quality) and $quality = 95; - // Use 95 for the default quality - empty($quality) and $quality = 95; + // All calls to these will need to be escaped, so do it now + $this->cmd_image = escapeshellarg($this->tmp_image); + $this->new_image = ($render) ? $this->cmd_image : escapeshellarg($dir . $file); - // All calls to these will need to be escaped, so do it now - $this->cmd_image = escapeshellarg($this->tmp_image); - $this->new_image = ($render)? $this->cmd_image : escapeshellarg($dir.$file); + if ($status = $this->execute($actions)) { + // Use convert to change the image into its final version. This is + // done to allow the file type to change correctly, and to handle + // the quality conversion in the most effective way possible. + if ($error = exec(escapeshellcmd($this->dir . 'convert' . $this->ext) . ' -quality ' . $quality . '% ' . $this->cmd_image . ' ' . $this->new_image)) { + $this->errors[] = $error; + } else { + // Output the image directly to the browser + if ($render !== false) { + $contents = file_get_contents($this->tmp_image); + switch (substr($file, strrpos($file, '.') + 1)) { + case 'jpg': + case 'jpeg': + header('Content-Type: image/jpeg'); + break; + case 'gif': + header('Content-Type: image/gif'); + break; + case 'png': + header('Content-Type: image/png'); + break; + } + echo $contents; + } + } + } - if ($status = $this->execute($actions)) - { - // Use convert to change the image into its final version. This is - // done to allow the file type to change correctly, and to handle - // the quality conversion in the most effective way possible. - if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -quality '.$quality.'% '.$this->cmd_image.' '.$this->new_image)) - { - $this->errors[] = $error; - } - else - { - // Output the image directly to the browser - if ($render !== FALSE) - { - $contents = file_get_contents($this->tmp_image); - switch (substr($file, strrpos($file, '.') + 1)) - { - case 'jpg': - case 'jpeg': - header('Content-Type: image/jpeg'); - break; - case 'gif': - header('Content-Type: image/gif'); - break; - case 'png': - header('Content-Type: image/png'); - break; - } - echo $contents; - } - } - } + // Remove the temporary image + unlink($this->tmp_image); + $this->tmp_image = ''; - // Remove the temporary image - unlink($this->tmp_image); - $this->tmp_image = ''; + return $status; + } - return $status; - } + public function crop($prop) + { + // Sanitize and normalize the properties into geometry + $this->sanitize_geometry($prop); - public function crop($prop) - { - // Sanitize and normalize the properties into geometry - $this->sanitize_geometry($prop); + // Set the IM geometry based on the properties + $geometry = escapeshellarg($prop['width'] . 'x' . $prop['height'] . '+' . $prop['left'] . '+' . $prop['top']); - // Set the IM geometry based on the properties - $geometry = escapeshellarg($prop['width'].'x'.$prop['height'].'+'.$prop['left'].'+'.$prop['top']); + if ($error = exec(escapeshellcmd($this->dir . 'convert' . $this->ext) . ' -crop ' . $geometry . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -crop '.$geometry.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + return true; + } - return TRUE; - } + public function flip($dir) + { + // Convert the direction into a IM command + $dir = ($dir === Image::HORIZONTAL) ? '-flop' : '-flip'; - public function flip($dir) - { - // Convert the direction into a IM command - $dir = ($dir === Image::HORIZONTAL) ? '-flop' : '-flip'; + if ($error = exec(escapeshellcmd($this->dir . 'convert' . $this->ext) . ' ' . $dir . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' '.$dir.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + return true; + } - return TRUE; - } + public function resize($prop) + { + switch ($prop['master']) { + case Image::WIDTH: // Wx + $dim = escapeshellarg($prop['width'] . 'x'); + break; + case Image::HEIGHT: // xH + $dim = escapeshellarg('x' . $prop['height']); + break; + case Image::AUTO: // WxH + $dim = escapeshellarg($prop['width'] . 'x' . $prop['height']); + break; + case Image::NONE: // WxH! + $dim = escapeshellarg($prop['width'] . 'x' . $prop['height'] . '!'); + break; + } - public function resize($prop) - { - switch ($prop['master']) - { - case Image::WIDTH: // Wx - $dim = escapeshellarg($prop['width'].'x'); - break; - case Image::HEIGHT: // xH - $dim = escapeshellarg('x'.$prop['height']); - break; - case Image::AUTO: // WxH - $dim = escapeshellarg($prop['width'].'x'.$prop['height']); - break; - case Image::NONE: // WxH! - $dim = escapeshellarg($prop['width'].'x'.$prop['height'].'!'); - break; - } + // Use "convert" to change the width and height + if ($error = exec(escapeshellcmd($this->dir . 'convert' . $this->ext) . ' -resize ' . $dim . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - // Use "convert" to change the width and height - if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -resize '.$dim.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + return true; + } - return TRUE; - } + public function rotate($amt) + { + if ( + $error = exec(escapeshellcmd($this->dir . 'convert' . $this->ext) . + ' -rotate ' . + escapeshellarg($amt) . + ' -background transparent ' . + $this->cmd_image . ' ' . + $this->cmd_image) + ) { + $this->errors[] = $error; + return false; + } - public function rotate($amt) - { - if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -rotate '.escapeshellarg($amt).' -background transparent '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + return true; + } - return TRUE; - } + public function sharpen($amount) + { + // Set the sigma, radius, and amount. The amount formula allows a nice + // spread between 1 and 100 without pixelizing the image badly. + $sigma = 0.5; + $radius = $sigma * 2; + $amount = round(($amount / 80) * 3.14, 2); - public function sharpen($amount) - { - // Set the sigma, radius, and amount. The amount formula allows a nice - // spread between 1 and 100 without pixelizing the image badly. - $sigma = 0.5; - $radius = $sigma * 2; - $amount = round(($amount / 80) * 3.14, 2); + // Convert the amount to an IM command + $sharpen = escapeshellarg($radius . 'x' . $sigma . '+' . $amount . '+0'); - // Convert the amount to an IM command - $sharpen = escapeshellarg($radius.'x'.$sigma.'+'.$amount.'+0'); + if ($error = exec(escapeshellcmd($this->dir . 'convert' . $this->ext) . ' -unsharp ' . $sharpen . ' ' . $this->cmd_image . ' ' . $this->cmd_image)) { + $this->errors[] = $error; + return false; + } - if ($error = exec(escapeshellcmd($this->dir.'convert'.$this->ext).' -unsharp '.$sharpen.' '.$this->cmd_image.' '.$this->cmd_image)) - { - $this->errors[] = $error; - return FALSE; - } + return true; + } - return TRUE; - } - - protected function properties() - { - return array_slice(getimagesize($this->tmp_image), 0, 2, FALSE); - } - -} // End Image ImageMagick Driver \ No newline at end of file + protected function properties() + { + return array_slice(getimagesize($this->tmp_image), 0, 2, false); + } +} +// End Image ImageMagick Driver diff --git a/lib/kohana/system/libraries/drivers/Session.php b/lib/kohana/system/libraries/drivers/Session.php index fb58c8d..8f8a9ed 100644 --- a/lib/kohana/system/libraries/drivers/Session.php +++ b/lib/kohana/system/libraries/drivers/Session.php @@ -1,4 +1,12 @@ -encrypt = new Encrypt(); + } - public function __construct() - { - // Load Encrypt library - if (Kohana::config('session.encryption')) - { - $this->encrypt = new Encrypt; - } + Kohana::log('debug', 'Session Cache Driver Initialized'); + } - Kohana::log('debug', 'Session Cache Driver Initialized'); - } + public function open($path, $name) + { + $config = Kohana::config('session.storage'); - public function open($path, $name) - { - $config = Kohana::config('session.storage'); + if (empty($config)) { + // Load the default group + $config = Kohana::config('cache.default'); + } elseif (is_string($config)) { + $name = $config; - if (empty($config)) - { - // Load the default group - $config = Kohana::config('cache.default'); - } - elseif (is_string($config)) - { - $name = $config; + // Test the config group name + if (($config = Kohana::config('cache.' . $config)) === null) { + throw new Kohana_Exception('cache.undefined_group', $name); + } + } - // Test the config group name - if (($config = Kohana::config('cache.'.$config)) === NULL) - throw new Kohana_Exception('cache.undefined_group', $name); - } + $config['lifetime'] = (Kohana::config('session.expiration') == 0) ? 86400 : Kohana::config('session.expiration'); + $this->cache = new Cache($config); - $config['lifetime'] = (Kohana::config('session.expiration') == 0) ? 86400 : Kohana::config('session.expiration'); - $this->cache = new Cache($config); + return is_object($this->cache); + } - return is_object($this->cache); - } + public function close() + { + return true; + } - public function close() - { - return TRUE; - } + public function read($id) + { + $id = 'session_' . $id; + if ($data = $this->cache->get($id)) { + return Kohana::config('session.encryption') ? $this->encrypt->decode($data) : $data; + } - public function read($id) - { - $id = 'session_'.$id; - if ($data = $this->cache->get($id)) - { - return Kohana::config('session.encryption') ? $this->encrypt->decode($data) : $data; - } + // Return value must be string, NOT a boolean + return ''; + } - // Return value must be string, NOT a boolean - return ''; - } + public function write($id, $data) + { + $id = 'session_' . $id; + $data = Kohana::config('session.encryption') ? $this->encrypt->encode($data) : $data; - public function write($id, $data) - { - $id = 'session_'.$id; - $data = Kohana::config('session.encryption') ? $this->encrypt->encode($data) : $data; + return $this->cache->set($id, $data); + } - return $this->cache->set($id, $data); - } + public function destroy($id) + { + $id = 'session_' . $id; + return $this->cache->delete($id); + } - public function destroy($id) - { - $id = 'session_'.$id; - return $this->cache->delete($id); - } + public function regenerate() + { + session_regenerate_id(true); - public function regenerate() - { - session_regenerate_id(TRUE); + // Return new session id + return session_id(); + } - // Return new session id - return session_id(); - } - - public function gc($maxlifetime) - { - // Just return, caches are automatically cleaned up - return TRUE; - } - -} // End Session Cache Driver + public function gc($maxlifetime) + { + // Just return, caches are automatically cleaned up + return true; + } +} +// End Session Cache Driver diff --git a/lib/kohana/system/libraries/drivers/Session/Cookie.php b/lib/kohana/system/libraries/drivers/Session/Cookie.php index 7b79106..93c6d7f 100644 --- a/lib/kohana/system/libraries/drivers/Session/Cookie.php +++ b/lib/kohana/system/libraries/drivers/Session/Cookie.php @@ -1,4 +1,12 @@ -cookie_name = Kohana::config('session.name') . '_data'; - public function __construct() - { - $this->cookie_name = Kohana::config('session.name').'_data'; + if (Kohana::config('session.encryption')) { + $this->encrypt = Encrypt::instance(); + } - if (Kohana::config('session.encryption')) - { - $this->encrypt = Encrypt::instance(); - } + Kohana::log('debug', 'Session Cookie Driver Initialized'); + } - Kohana::log('debug', 'Session Cookie Driver Initialized'); - } + public function open($path, $name) + { + return true; + } - public function open($path, $name) - { - return TRUE; - } + public function close() + { + return true; + } - public function close() - { - return TRUE; - } + public function read($id) + { + $data = (string) cookie::get($this->cookie_name); - public function read($id) - { - $data = (string) cookie::get($this->cookie_name); + if ($data == '') { + return $data; + } - if ($data == '') - return $data; + return empty($this->encrypt) ? base64_decode($data) : $this->encrypt->decode($data); + } - return empty($this->encrypt) ? base64_decode($data) : $this->encrypt->decode($data); - } + public function write($id, $data) + { + $data = empty($this->encrypt) ? base64_encode($data) : $this->encrypt->encode($data); - public function write($id, $data) - { - $data = empty($this->encrypt) ? base64_encode($data) : $this->encrypt->encode($data); + if (strlen($data) > 4048) { + Kohana::log('error', 'Session (' . $id . ') data exceeds the 4KB limit, ignoring write.'); + return false; + } - if (strlen($data) > 4048) - { - Kohana::log('error', 'Session ('.$id.') data exceeds the 4KB limit, ignoring write.'); - return FALSE; - } + return cookie::set($this->cookie_name, $data, Kohana::config('session.expiration')); + } - return cookie::set($this->cookie_name, $data, Kohana::config('session.expiration')); - } + public function destroy($id) + { + return cookie::delete($this->cookie_name); + } - public function destroy($id) - { - return cookie::delete($this->cookie_name); - } + public function regenerate() + { + session_regenerate_id(true); - public function regenerate() - { - session_regenerate_id(TRUE); + // Return new id + return session_id(); + } - // Return new id - return session_id(); - } - - public function gc($maxlifetime) - { - return TRUE; - } - -} // End Session Cookie Driver Class \ No newline at end of file + public function gc($maxlifetime) + { + return true; + } +} +// End Session Cookie Driver Class diff --git a/lib/kohana/system/libraries/drivers/Session/Database.php b/lib/kohana/system/libraries/drivers/Session/Database.php index b4144ff..b0e6ac7 100644 --- a/lib/kohana/system/libraries/drivers/Session/Database.php +++ b/lib/kohana/system/libraries/drivers/Session/Database.php @@ -1,4 +1,12 @@ -encrypt = Encrypt::instance(); + } - if ( ! empty($config['encryption'])) - { - // Load encryption - $this->encrypt = Encrypt::instance(); - } + if (is_array($config['storage'])) { + if (! empty($config['storage']['group'])) { + // Set the group name + $this->db = $config['storage']['group']; + } - if (is_array($config['storage'])) - { - if ( ! empty($config['storage']['group'])) - { - // Set the group name - $this->db = $config['storage']['group']; - } + if (! empty($config['storage']['table'])) { + // Set the table name + $this->table = $config['storage']['table']; + } + } - if ( ! empty($config['storage']['table'])) - { - // Set the table name - $this->table = $config['storage']['table']; - } - } + // Load database + $this->db = Database::instance($this->db); - // Load database - $this->db = Database::instance($this->db); + Kohana::log('debug', 'Session Database Driver Initialized'); + } - Kohana::log('debug', 'Session Database Driver Initialized'); - } + public function open($path, $name) + { + return true; + } - public function open($path, $name) - { - return TRUE; - } + public function close() + { + return true; + } - public function close() - { - return TRUE; - } + public function read($id) + { + // Load the session + $query = $this->db->from($this->table)->where('session_id', $id)->limit(1)->get()->result(true); - public function read($id) - { - // Load the session - $query = $this->db->from($this->table)->where('session_id', $id)->limit(1)->get()->result(TRUE); + if ($query->count() === 0) { + // No current session + $this->session_id = null; - if ($query->count() === 0) - { - // No current session - $this->session_id = NULL; + return ''; + } - return ''; - } + // Set the current session id + $this->session_id = $id; - // Set the current session id - $this->session_id = $id; + // Load the data + $data = $query->current()->data; - // Load the data - $data = $query->current()->data; + return ($this->encrypt === null) ? base64_decode($data) : $this->encrypt->decode($data); + } - return ($this->encrypt === NULL) ? base64_decode($data) : $this->encrypt->decode($data); - } + public function write($id, $data) + { + $data = array + ( + 'session_id' => $id, + 'last_activity' => time(), + 'data' => ($this->encrypt === null) ? base64_encode($data) : $this->encrypt->encode($data) + ); - public function write($id, $data) - { - $data = array - ( - 'session_id' => $id, - 'last_activity' => time(), - 'data' => ($this->encrypt === NULL) ? base64_encode($data) : $this->encrypt->encode($data) - ); + if ($this->session_id === null) { + // Insert a new session + $query = $this->db->insert($this->table, $data); + } elseif ($id === $this->session_id) { + // Do not update the session_id + unset($data['session_id']); - if ($this->session_id === NULL) - { - // Insert a new session - $query = $this->db->insert($this->table, $data); - } - elseif ($id === $this->session_id) - { - // Do not update the session_id - unset($data['session_id']); + // Update the existing session + $query = $this->db->update($this->table, $data, array('session_id' => $id)); + } else { + // Update the session and id + $query = $this->db->update($this->table, $data, array('session_id' => $this->session_id)); - // Update the existing session - $query = $this->db->update($this->table, $data, array('session_id' => $id)); - } - else - { - // Update the session and id - $query = $this->db->update($this->table, $data, array('session_id' => $this->session_id)); + // Set the new session id + $this->session_id = $id; + } - // Set the new session id - $this->session_id = $id; - } + return (bool) $query->count(); + } - return (bool) $query->count(); - } + public function destroy($id) + { + // Delete the requested session + $this->db->delete($this->table, array('session_id' => $id)); - public function destroy($id) - { - // Delete the requested session - $this->db->delete($this->table, array('session_id' => $id)); + // Session id is no longer valid + $this->session_id = null; - // Session id is no longer valid - $this->session_id = NULL; + return true; + } - return TRUE; - } + public function regenerate() + { + // Generate a new session id + session_regenerate_id(); - public function regenerate() - { - // Generate a new session id - session_regenerate_id(); + // Return new session id + return session_id(); + } - // Return new session id - return session_id(); - } + public function gc($maxlifetime) + { + // Delete all expired sessions + $query = $this->db->delete($this->table, array('last_activity <' => time() - $maxlifetime)); - public function gc($maxlifetime) - { - // Delete all expired sessions - $query = $this->db->delete($this->table, array('last_activity <' => time() - $maxlifetime)); + Kohana::log('debug', 'Session garbage collected: ' . $query->count() . ' row(s) deleted.'); - Kohana::log('debug', 'Session garbage collected: '.$query->count().' row(s) deleted.'); - - return TRUE; - } - -} // End Session Database Driver + return true; + } +} +// End Session Database Driver diff --git a/lib/kohana/system/views/kohana/template.php b/lib/kohana/system/views/kohana/template.php index b090fd8..2dff943 100644 --- a/lib/kohana/system/views/kohana/template.php +++ b/lib/kohana/system/views/kohana/template.php @@ -1,36 +1,36 @@ - + - - <?php echo html::specialchars($title) ?> + + <?php echo html::specialchars($title) ?> - + -

- +

+ - + \ No newline at end of file diff --git a/lib/kohana/system/views/kohana_calendar.php b/lib/kohana/system/views/kohana_calendar.php index 39545e2..a1d9e61 100644 --- a/lib/kohana/system/views/kohana_calendar.php +++ b/lib/kohana/system/views/kohana_calendar.php @@ -1,4 +1,4 @@ - date('n', $prev), 'year' => date('Y', $prev)))); -$next = Router::$current_uri.'?'.http_build_query(array_merge($qs, array('month' => date('n', $next), 'year' => date('Y', $next)))); +$prev = Router::$current_uri . '?' . http_build_query(array_merge($qs, array('month' => date('n', $prev), 'year' => date('Y', $prev)))); +$next = Router::$current_uri . '?' . http_build_query(array_merge($qs, array('month' => date('n', $next), 'year' => date('Y', $next)))); ?> @@ -23,30 +23,26 @@ $next = Router::$current_uri.'?'.http_build_query(array_merge($qs, array('month' - + - + -
  • ' . implode('
  • ', $data['output']) . '
  • '; + } else { + $classes = array(); + $output = ''; + } -if (is_array($data)) -{ - $classes = $data['classes']; - $output = empty($data['output']) ? '' : '
    • '.implode('
    • ', $data['output']).'
    '; -} -else -{ - $classes = array(); - $output = ''; -} - -?> + ?> - +
    diff --git a/lib/kohana/system/views/kohana_error_disabled.php b/lib/kohana/system/views/kohana_error_disabled.php index cd91132..c6e0b99 100644 --- a/lib/kohana/system/views/kohana_error_disabled.php +++ b/lib/kohana/system/views/kohana_error_disabled.php @@ -1,9 +1,9 @@ - + <?php echo $error ?> diff --git a/lib/kohana/system/views/kohana_error_page.php b/lib/kohana/system/views/kohana_error_page.php index 944064c..e3da425 100644 --- a/lib/kohana/system/views/kohana_error_page.php +++ b/lib/kohana/system/views/kohana_error_page.php @@ -1,9 +1,9 @@ - + <?php echo $error ?> @@ -13,13 +13,13 @@

    - +

    - +

    - +

    diff --git a/lib/kohana/system/views/kohana_profiler.php b/lib/kohana/system/views/kohana_profiler.php index da77a66..8228df9 100644 --- a/lib/kohana/system/views/kohana_profiler.php +++ b/lib/kohana/system/views/kohana_profiler.php @@ -1,36 +1,35 @@ - +
    render(); +foreach ($profiles as $profile) { + echo $profile->render(); } ?>

    Profiler executed in s

    diff --git a/lib/kohana/system/views/kohana_profiler_table.php b/lib/kohana/system/views/kohana_profiler_table.php index b6b4653..02a1eb2 100644 --- a/lib/kohana/system/views/kohana_profiler_table.php +++ b/lib/kohana/system/views/kohana_profiler_table.php @@ -1,25 +1,23 @@ - + - > - $column) - { - $class = empty($column['class']) ? '' : ' class="'.$column['class'].'"'; - $style = empty($column['style']) ? '' : ' style="'.$column['style'].'"'; - $value = $row['data'][$index]; - $value = (is_array($value) OR is_object($value)) ? '
    '.html::specialchars(print_r($value, TRUE)).'
    ' : html::specialchars($value); - echo '', $value, ''; - } - ?> - - + > + $column) { + $class = empty($column['class']) ? '' : ' class="' . $column['class'] . '"'; + $style = empty($column['style']) ? '' : ' style="' . $column['style'] . '"'; + $value = $row['data'][$index]; + $value = (is_array($value) or is_object($value)) ? '
    ' . html::specialchars(print_r($value, true)) . '
    ' : html::specialchars($value); + echo '', $value, ''; + } + ?> + +
    \ No newline at end of file diff --git a/lib/kohana/system/views/pagination/classic.php b/lib/kohana/system/views/pagination/classic.php index 5272c2c..a546234 100644 --- a/lib/kohana/system/views/pagination/classic.php +++ b/lib/kohana/system/views/pagination/classic.php @@ -1,39 +1,38 @@ - Last › */ ?>

    - - ‹  - + + ‹  + - - < - + + < + - + + + + + + - - - - - - - + - - > - + + > + - -  › - + +  › +

    \ No newline at end of file diff --git a/lib/kohana/system/views/pagination/digg.php b/lib/kohana/system/views/pagination/digg.php index 0e065a6..e592bea 100644 --- a/lib/kohana/system/views/pagination/digg.php +++ b/lib/kohana/system/views/pagination/digg.php @@ -1,83 +1,79 @@ -

    - - «  - - «  - + + «  + + «  + - + + + + + + + + - - - - - - - + + + + + + + + - + … + + - - - - - - - + $total_pages - 8) : /* « Previous 1 2 … 17 18 19 20 21 22 23 24 25 26 Next » */ ?> + 1 + 2 + … - … - - + + + + + + + - $total_pages - 8): /* « Previous 1 2 … 17 18 19 20 21 22 23 24 25 26 Next » */ ?> + + 1 + 2 + … - 1 - 2 - … + + + + + + + - - - - - - - + … + + - - - 1 - 2 - … - - - - - - - - - - … - - - - + - -  » - -  » - + +  » + +  » +

    \ No newline at end of file diff --git a/lib/kohana/system/views/pagination/extended.php b/lib/kohana/system/views/pagination/extended.php index 2427a4e..323949d 100644 --- a/lib/kohana/system/views/pagination/extended.php +++ b/lib/kohana/system/views/pagination/extended.php @@ -1,27 +1,33 @@ -

    - - «  - - «  - + + «  + + «  + - | + | - | + | +– + + + - | -  » - -  » - + | +  » + +  » + -

    \ No newline at end of file +

    diff --git a/lib/kohana/system/views/pagination/punbb.php b/lib/kohana/system/views/pagination/punbb.php index 6599831..8328b2b 100644 --- a/lib/kohana/system/views/pagination/punbb.php +++ b/lib/kohana/system/views/pagination/punbb.php @@ -1,37 +1,42 @@ -

    - : + : - 3): ?> - 1 - - + 3) : ?> + 1 + + - + + $total_pages) { + continue; + } ?> - $total_pages) continue ?> + + + + + - - - - - - - + - - - - + + + +

    \ No newline at end of file diff --git a/man/.gitignore b/man/.gitignore new file mode 100644 index 0000000..bcf9e1c --- /dev/null +++ b/man/.gitignore @@ -0,0 +1,2 @@ +Makefile +npcd.8 diff --git a/man/Makefile.in b/man/Makefile.in index 614ea84..c444622 100644 --- a/man/Makefile.in +++ b/man/Makefile.in @@ -18,6 +18,6 @@ distclean: clean devclean: distclean install: - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(MANDIR)/man8 - $(INSTALL) -m 755 $(INSTALL_OPTS) npcd.8 $(DESTDIR)$(MANDIR)/man8 + $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(prefix)$(MANDIR)/man8 + $(INSTALL) -m 755 $(INSTALL_OPTS) npcd.8 $(DESTDIR)$(prefix)$(MANDIR)/man8 diff --git a/man/npcd.8.in b/man/npcd.8.in index c3153ce..bc1cd1c 100644 --- a/man/npcd.8.in +++ b/man/npcd.8.in @@ -24,7 +24,7 @@ http://pnp4nagios.sourceforge.net Run \fBnpcd\fR as daemon in the background. .TP \fB\-f, \--config\fR \fI -Path to the \fBnpcd\fR config file (typically @sysconfdir@/npcd.cfg). +Path to the \fBnpcd\fR config file (typically @pkgsysconfdir@/npcd.cfg). .SH "RETURN VALUE" On success starting \fBnpcd\fR 0 is returned. .SH ERRORS @@ -32,7 +32,7 @@ On error starting \fBnpcd\fR 1 is returned. .SH FILES .br .nf -\fI@sysconfdir@/npcd.cfg\fR default config file +\fI@pkgsysconfdir@/npcd.cfg\fR default config file .SH AUTHORS Joerg Linge , Hendrik Baecker diff --git a/pnp4nagios.fc.in b/pnp4nagios.fc.in new file mode 100644 index 0000000..615ac2b --- /dev/null +++ b/pnp4nagios.fc.in @@ -0,0 +1,10 @@ +# @datarootdir@ to make configure STFU +@bindir@/npcd system_u:object_r:nagios_exec_t:s0 +#@datadir@(/.*)? system_u:object_r:nagios_spool_t:s0 +@pkgsysconfdir@(/.*)? system_u:object_r:nagios_etc_t:s0 +@piddir@/npcd.pid system_u:object_r:nagios_var_run_t:s0 +@PERFDATA_DIR@(/.*)? system_u:object_r:nagios_spool_t:s0 +@logdir@(/.*)? system_u:object_r:nagios_log_t:s0 +@PERFDATA_SPOOL_DIR@(/.*)? system_u:object_r:nagios_spool_t:s0 +#/etc/rc\.d/init\.d/npcd system_u:object_r:nagios_initrc_exec_t:s0 +#@initdir@/@initname@ system_u:object_r:nagios_initrc_exec_t:s0 diff --git a/pnp4nagios.te b/pnp4nagios.te new file mode 100644 index 0000000..a8cf06f --- /dev/null +++ b/pnp4nagios.te @@ -0,0 +1,28 @@ +# type var_log_t; +#allow httpd_t var_log_t:file { open getattr read write map }; + +module pnp4nagios 1.0; + +require { + type httpd_log_t; + type nagios_t; + type nagios_etc_t; + type nagios_spool_t; + type nagios_log_t; + type nagios_var_lib_t; + type httpd_t; + class dir { add_name create read write }; + class file { getattr create open read write map setattr lock }; +} +allow httpd_t nagios_log_t:file { getattr setattr create read write open map }; +allow httpd_t nagios_log_t:dir { add_name read write }; +allow httpd_t httpd_log_t:file { read open getattr write map }; +allow httpd_t nagios_var_lib_t:file { getattr read write open map }; +allow httpd_t nagios_spool_t:file { getattr open read map lock }; +allow httpd_t nagios_spool_t:dir { read }; +allow nagios_t nagios_spool_t:dir { create read write add_name }; +allow nagios_t nagios_var_lib_t:file { getattr read write open map }; +allow nagios_t nagios_etc_t:file { getattr read open map }; + + + diff --git a/sample-config/.gitignore b/sample-config/.gitignore new file mode 100644 index 0000000..4385310 --- /dev/null +++ b/sample-config/.gitignore @@ -0,0 +1,18 @@ +# created from .in files +Makefile +README_config.md +SetLogLevels +pnp4nagios_release +config_tools/NagiosCfgMod.pl +config_tools/verify_pnp_config +config_tools/TemplateMod.pl +config_samples/nagios.cfg +config_samples/npcd.cfg +config_samples/pnp-bulk.cfg +config_samples/pnp-npcd.cfg +config_samples/pnp-sync.cfg +config_samples/process_perfdata.cfg +config_samples/lighttpd.pnp4nagios.conf +config_samples/nginx.pnp4nagios.conf +config_samples/apache.pnp4nagios.conf +config_samples/config.php diff --git a/sample-config/Makefile.in b/sample-config/Makefile.in index 3f6b171..c591c34 100644 --- a/sample-config/Makefile.in +++ b/sample-config/Makefile.in @@ -1,84 +1,120 @@ prefix=@prefix@ -SYSCONFDIR=@sysconfdir@ +PKGSYSCONFDIR=@pkgsysconfdir@ BINDIR=@bindir@ LIBEXECDIR=@libexecdir@ LIBDIR=@libdir@ CGIDIR=@sbindir@ -HTMLDIR=@datadir@ +HTMLDIR=@datarootdir@ INSTALL=@INSTALL@ INSTALL_OPTS=@INSTALL_OPTS@ +BACKUP=-b @INSTALL_SUFFIX@ .orig +LN_S=@LN_S@ PERFDATADIR=@PERFDATA_DIR@ DATAROOTDIR=@datarootdir@ -PKG_NAME=@PKG_NAME@ -PKG_VERSION=@PKG_VERSION@ -HTTPD_CONF=@HTTPD_CONF@ +PACKAGE_NAME=@PACKAGE_NAME@ +PACKAGE_VERSION=@PACKAGE_VERSION@ +NAG_OBJ=@NAGIOS_OBJ@ +NAG_CFG=@NAGIOS_CFG@ +NAG_PWD=@NAGIOS_PWD@ +NAG_VER=@NAGIOS_VER@ +HTTP_SERVER=@HTTP_SERVER@ +HTTP_CONFDIR=@HTTP_CONFDIR@ CP=@CP@ +PERL=@PERL@ +PAPERSIZE=@PAPERSIZE@ -all html: +all: clean: - -rm -f pnp/config.php - -rm -f pnp/process_perfdata.cfg-sample - -rm -f pnp/npcd.cfg-sample - -rm -f misccommands.cfg-sample - -rm -f nagios.cfg-sample - -rm -f httpd.conf - -rm -f pnp/pnp4nagios_release - -rm -f lighttpd.pnp4nagios.conf - -rm -f nginx.pnp4nagios.conf + -rm -f config_samples/config.php + -rm -f config_samples/nagios_*.cfg + -rm -f config_samples/templates.cfg + -rm -f config_samples/process_perfdata.cfg + -rm -f config_samples/npcd.cfg + -rm -f config_samples/pnp-*.cfg + -rm -f pnp4nagios_release + -rm -f config_samples/apache.pnp4nagios.conf + -rm -f config_samples/lighttpd.pnp4nagios.conf + -rm -f config_samples/nginx.pnp4nagios.conf + -rm -f config_tools/NagiosCfgMod.pl + -rm -f README_config.md distclean: clean -rm -f Makefile devclean: distclean -install: - -rm -f $(DESTDIR)$(HTMLDIR)/conf/config.php - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(SYSCONFDIR) - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(SYSCONFDIR)/config.d - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(SYSCONFDIR)/check_commands - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(SYSCONFDIR)/pages - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/pnp4nagios_release $(DESTDIR)$(SYSCONFDIR) - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/background.pdf $(DESTDIR)$(SYSCONFDIR) - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/config.php $(DESTDIR)$(SYSCONFDIR)/config.php.$(PKG_VERSION); \ - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/config.php $(DESTDIR)$(SYSCONFDIR); \ +config_samples/nagios-sync.cfg: + $(PERL) config_tools/NagiosCfgMod.pl -i $(NAG_CFG) -o config_samples/nagios-sync.cfg -n $(NAG_VER) -m sync -install-config: +config_samples/nagios-bulk.cfg: + $(PERL) config_tools/NagiosCfgMod.pl -i $(NAG_CFG) -o config_samples/nagios-bulk.cfg -n $(NAG_VER) -m bulk - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(SYSCONFDIR) - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(SYSCONFDIR)/check_commands - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(SYSCONFDIR)/pages - - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/config.php $(DESTDIR)$(SYSCONFDIR)/config.php.$(PKG_VERSION); \ - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/config.php $(DESTDIR)$(SYSCONFDIR); \ - - if [ ! -e $(DESTDIR)$(SYSCONFDIR)/config_local.php ] ;then \ - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/config.php $(DESTDIR)$(SYSCONFDIR)/config_local.php; \ +config_samples/nagios-npcd.cfg: + $(PERL) config_tools/NagiosCfgMod.pl -i $(NAG_CFG) -o config_samples/nagios-npcd.cfg -n $(NAG_VER) -m npcd + +config_samples/templates.cfg: + $(PERL) config_tools/TemplateMod.pl -i $(NAG_OBJ)/templates.cfg -o config_samples/templates.cfg + +install-samples: config_samples/nagios-sync.cfg config_samples/nagios-bulk.cfg config_samples/nagios-npcd.cfg config_samples/templates.cfg + $(INSTALL) -m 644 config_samples/nagios-sync.cfg $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/ + $(INSTALL) -m 644 config_samples/nagios-bulk.cfg $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/ + $(INSTALL) -m 644 config_samples/nagios-npcd.cfg $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/ + $(INSTALL) -m 644 config_samples/templates.cfg $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/objects/ + +install: install-contrib + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR) + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/config.d + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/check_commands + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/pages + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/config_tools + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/config_samples + $(INSTALL) -m 755 README_config.md $(DESTDIR)$(PKGSYSCONFDIR)/ + $(INSTALL) -m 755 SetLogLevels $(DESTDIR)$(PKGSYSCONFDIR)/ + $(INSTALL) -m 755 $(BACKUP) config_tools/*.pl $(DESTDIR)$(PKGSYSCONFDIR)/config_tools/ + $(INSTALL) -m 755 $(BACKUP) config_tools/verify_pnp_config $(DESTDIR)$(PKGSYSCONFDIR)/ + $(INSTALL) -m 755 $(BACKUP) check_commands/* $(DESTDIR)$(PKGSYSCONFDIR)/check_commands/ + $(INSTALL) -m 755 $(BACKUP) config_samples/config.php $(DESTDIR)$(PKGSYSCONFDIR)/ + $(INSTALL) -m 755 $(BACKUP) config_samples/process_perfdata.cfg $(DESTDIR)$(PKGSYSCONFDIR)/process_perfdata.cfg + $(INSTALL) -m 755 $(BACKUP) config_samples/npcd.cfg $(DESTDIR)$(PKGSYSCONFDIR)/npcd.cfg + $(INSTALL) -m 644 $(BACKUP) config_samples/rra.cfg $(DESTDIR)$(PKGSYSCONFDIR) + $(INSTALL) -m 644 pnp4nagios_release $(DESTDIR)$(PKGSYSCONFDIR)/ + if ! diff -q pages/background-A4.pdf $(DESTDIR)$(PKGSYSCONFDIR)/pages/ >/dev/null 2>/dev/null ; then \ + $(INSTALL) -m 644 $(BACKUP) pages/background-A4.pdf $(DESTDIR)$(PKGSYSCONFDIR)/pages/ ; \ fi - - if [ -e $(DESTDIR)$(SYSCONFDIR)/process_perfdata.cfg ] ;then \ - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/process_perfdata.cfg-sample $(DESTDIR)$(SYSCONFDIR)/process_perfdata.cfg.$(PKG_VERSION); \ - else\ - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/process_perfdata.cfg-sample $(DESTDIR)$(SYSCONFDIR)/process_perfdata.cfg; \ + if ! diff -q pages/background-letter.pdf $(DESTDIR)$(PKGSYSCONFDIR)/pages/ >/dev/null 2>/dev/null ; then \ + $(INSTALL) -m 644 $(BACKUP) pages/background-letter.pdf $(DESTDIR)$(PKGSYSCONFDIR)/pages ; \ fi - - if [ -e $(DESTDIR)$(SYSCONFDIR)/npcd.cfg ] ;then \ - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/npcd.cfg-sample $(DESTDIR)$(SYSCONFDIR)/npcd.cfg.$(PKG_VERSION); \ - else\ - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/npcd.cfg-sample $(DESTDIR)$(SYSCONFDIR)/npcd.cfg; \ + if [ ! -e $(DESTDIR)$(PKGSYSCONFDIR)/background.pdf ] ; then \ + $(LN_S) $(DESTDIR)$(PKGSYSCONFDIR)/pages/background-$(PAPERSIZE).pdf $(DESTDIR)$(PKGSYSCONFDIR)/background.pdf ;\ + fi + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/objects + $(INSTALL) -m 644 config_samples/pnp-sync.cfg $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/objects/ + $(INSTALL) -m 644 config_samples/pnp-bulk.cfg $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/objects/ + $(INSTALL) -m 644 config_samples/pnp-npcd.cfg $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/nagios/objects/ + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/http_server_$(HTTP_SERVER) + $(INSTALL) -m 644 config_samples/$(HTTP_SERVER).pnp4nagios.conf $(DESTDIR)$(PKGSYSCONFDIR)/config_samples/http_server_$(HTTP_SERVER)/pnp4nagios.conf + if [ "x${NOSAMPLES}" = "x" ] ; then \ + $(MAKE) install-samples ; \ fi - - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/rra.cfg-sample $(DESTDIR)$(SYSCONFDIR) - $(INSTALL) -m 644 $(INSTALL_OPTS) misccommands.cfg-sample $(DESTDIR)$(SYSCONFDIR) - $(INSTALL) -m 644 $(INSTALL_OPTS) nagios.cfg-sample $(DESTDIR)$(SYSCONFDIR) - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/check_commands/check_nwstat.cfg-sample $(DESTDIR)$(SYSCONFDIR)/check_commands - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/check_commands/check_nrpe.cfg-sample $(DESTDIR)$(SYSCONFDIR)/check_commands - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/check_commands/check_all_local_disks.cfg-sample $(DESTDIR)$(SYSCONFDIR)/check_commands - $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/pages/web_traffic.cfg-sample $(DESTDIR)$(SYSCONFDIR)/pages -install-webconf: +install-contrib: + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/ssi + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/conf + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/conf/logfiles + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/conf/services + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/scripts + $(INSTALL) -m 755 -d $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/scripts/services + $(INSTALL) -m 644 $(BACKUP) ../contrib/ssi/status-header.ssi $(DESTDIR)$(PKGSYSCONFDIR)/contrib + $(INSTALL) -m 644 $(BACKUP) ../contrib/fedora/pnp4nagios.logrotate.conf $(DESTDIR)$(PKGSYSCONFDIR)/contrib + $(INSTALL) -m 644 $(BACKUP) ../contrib/fedora/logwatch/conf/logfiles/pnp4nagios.conf $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/conf/logfiles + $(INSTALL) -m 644 $(BACKUP) ../contrib/fedora/logwatch/conf/services/pnp4nagios.conf $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/conf/services + $(INSTALL) -m 644 $(BACKUP) ../contrib/fedora/logwatch/scripts/services/pnp4nagios $(DESTDIR)$(PKGSYSCONFDIR)/contrib/fedora/logwatch/scripts/services + + + - $(INSTALL) -m 755 -d $(DESTDIR)$(HTTPD_CONF) - $(INSTALL) -m 644 httpd.conf $(DESTDIR)$(HTTPD_CONF)/$(PKG_NAME).conf - diff --git a/sample-config/README_config.md.in b/sample-config/README_config.md.in new file mode 100644 index 0000000..ce4921a --- /dev/null +++ b/sample-config/README_config.md.in @@ -0,0 +1,130 @@ +Here are some steps to get your pnp4nagios working +with Nagios and your webserver; it is intended primarily +for the "new user". If you already have pnp4nagios +working with your Nagios and httpd server, you can +skip this, except perhaps as a source of tips. + + +In summary: + + * [A] get the Nagios data to pnp4nagios + * [B] make pnp4nagios links on Nagios pages + * [C] make pnp4nagios available on webserver + * [D] restart http server and Nagios to use new settings + +**[A] get the Nagios data to pnp4nagios** + +There are several options for feeding Nagios data to +pnp4nagios, and you need to choose one: + + * **sync**: gets executed on each update, + best choice for a "low activity" Nagios. + Warning: Nagios versions 4.4.0 to 4.4.12 + do **not** work with sync, because of a bug + in Nagios. If you see failures in process_perfdata + with "Cant find Nagios Environment." you're probably + running into this. + + * **bulk**: batches updates, but otherwise like + the synchronous option in how the updates are + processed into the RRD database. + + * **npcd**: bulk output, npcd server grabs the updates on + a regular schedule and deals with them; best for a + "high activity" Nagios. + +All three options are included, and you can switch between +them. + +First, + cp config_samples/nagios/objects/pnp-*.cfg @NAGIOS_OBJ@/ +Use "bulk" mode as an example: + cp config_samples/nagios/nagios-bulk.cfg @NAGIOS_CFG@ + + + + +**[B] make pnp4nagios links on Nagios pages** + +The one easy way to do this is to add a pair of new +definitions to the Nagios "templates.cfg" file to +make host and service templates that just contain a +action_url link to pnp4nagios code. Then add +a "use" line in the "generic-host" and "generic-service" +definitions so that they'll include the pnp4nagios templates. + +You can also edit the generic-* templates directly to add the +action urls. + +For an already-edited example templates.cfg file, just + cp config_samples/nagios/objects/templates.cfg @NAGIOS_OBJ@/ + + +**[C] make pnp4nagios available on webserver** + +This is done by a "pnp4nagios.conf" file that +(for Apache) is placed in /etc/httpd/conf.d/ +It defines urls like /pnp4nagios/... to get handled +by the pnp4nagios code. Most of what is needed is +to make sure that the pnp4nagios code is in the +same "security domain" as your Nagios server, so +that you don't have to enter passwords twice, once +for a Nagios page and again for a pnp4nagios graph. + +For password authentication, that is done by adjusting the +**AuthName** and **AuthType** to be the same as your +Nagios server, and pointing the **AuthUserFile** to the +Nagios file. An attempt at doing the "default setup" is +what is in the pnp4nagios.conf file. + +For more complicated authentication schemes (user certificates, +etc) the general rule is "copy what you use for Nagios". + +For an example config: + cp config_samples/http_server_apache/pnp4nagios.conf @HTTP_CONFDIR@/ + +**[D] restart http server and Nagios ** + +Before restarting, it can be useful to run the +**verify_pnp_config** script, but you will have to +specify which "mode" (sync|bulk|npcd) you are using +with (for example) + ./verify_pnp_config --mode=bulk + +If it looks good, restart the http server and Nagios +(hopefully with no errors). Point your browser to the +Nagios page, and look for the little "graph" icons next +to hosts and services. Clicking on an icon should bring +up an installation-check page. Again, if all good, the +green box at the bottom of the installation-check page +will tell you how to skip the installation-check and get +the graphs. Please note that it will take a while for +data to be stored in rrd files, and you may get some errors +about "missing file" before the rrd files are created. + +** Where to find configuration settings ** + +Where to find config info: + + @pkgsysconfdir@ + config.php + config_local.php (not present by default) + config.d/*.php (not present by default) + npcd.cfg + process_perfdata.cfg + rra.cfg + + @datarootdir@/application/config/config.php + +When things go wrong, it's useful to increase the logging level +and see more. The **SetLogLevel** script can be used to +assist with this, because log levels can be set for npcd, +process_perfdata, and .../application/config/config.php +for cgi execution. + +When it's a "selinux problem", then you need to check in +/var/log/messages or journalctl. The messages generally give +information about how to work around the security violations, +which can be extremely useful for updating the selinux +configuration for pnp4nagios. + diff --git a/sample-config/SetLogLevels.in b/sample-config/SetLogLevels.in new file mode 100755 index 0000000..f9857fe --- /dev/null +++ b/sample-config/SetLogLevels.in @@ -0,0 +1,68 @@ +#!/bin/sh +# set pnp4nagios log levels for several components, +# all at one time. +npcdcfg=@pkgsysconfdir@/npcd.cfg +ppcfg=@pkgsysconfdir@/process_perfdata.cfg +kohcfg=@datarootdir@/application/config/config.php + +# setloglev (npcd_level) (process_perfdata_level) (php level) +setloglev () { + sed -i "/^ *log_level *=/s/= *-*[0-9]/= $1/" $npcdcfg + sed -i "/^ *LOG_LEVEL *=/s/= *[0-9]/= $2/" $ppcfg + sed -i "/^ *\$config\['log_threshold'\]/s/= *[0-9]/= $3/" $kohcfg + if [ "@init_type@" = "systemd" -o "@init_type@" = "sysv" ] + then + if service npcd status >/dev/null 2>/dev/null + then + service npcd restart + fi + else + echo "if you run npcd, restart it" + fi +} + +case "$1" in + "" ) + echo -n "npcd.cfg: " + grep '^ *log_level *=' $npcdcfg + echo -n "process_perfdata.cfg: " + grep '^ *LOG_LEVEL' $ppcfg + echo -n "share/application/config/config.php: " + grep log_threshold $kohcfg + ;; + -* ) + echo "$0: usage" + echo "$0 with no parameters: show current levels" + echo "$0 0|off turn off logging" + echo "$0 1|err errors only" + echo "$0 2|warn warnings and errors" + echo "$0 3|debug debugging" + echo "not all components have the same levels," + echo "but 'off' and 'debug' are well matched" + echo "" + echo "the three files affected are: " + echo "$npcdcfg" + echo "$ppcfg" + echo "$kohcfg" + ;; + 0 | off | OFF ) + setloglev 0 0 0 + ;; + 1 | err* ) + setloglev 1 1 1 + ;; + 2 | warn* ) + setloglev 2 2 2 + ;; + 3 | deb* ) + setloglev -1 3 4 + ;; + * ) + echo "unknown argument, try $0 --help" + ;; +esac +exit 0 + + + + diff --git a/sample-config/pnp/check_commands/check_all_local_disks.cfg-sample b/sample-config/check_commands/check_all_local_disks.cfg-sample similarity index 100% rename from sample-config/pnp/check_commands/check_all_local_disks.cfg-sample rename to sample-config/check_commands/check_all_local_disks.cfg-sample diff --git a/sample-config/pnp/check_commands/check_nrpe.cfg-sample b/sample-config/check_commands/check_nrpe.cfg-sample similarity index 100% rename from sample-config/pnp/check_commands/check_nrpe.cfg-sample rename to sample-config/check_commands/check_nrpe.cfg-sample diff --git a/sample-config/pnp/check_commands/check_nwstat.cfg-sample b/sample-config/check_commands/check_nwstat.cfg-sample similarity index 100% rename from sample-config/pnp/check_commands/check_nwstat.cfg-sample rename to sample-config/check_commands/check_nwstat.cfg-sample diff --git a/sample-config/httpd.conf.in b/sample-config/config_samples/apache.pnp4nagios.conf.in similarity index 64% rename from sample-config/httpd.conf.in rename to sample-config/config_samples/apache.pnp4nagios.conf.in index 72b81cb..4646829 100644 --- a/sample-config/httpd.conf.in +++ b/sample-config/config_samples/apache.pnp4nagios.conf.in @@ -1,24 +1,32 @@ # SAMPLE CONFIG SNIPPETS FOR APACHE WEB SERVER -Alias @BASE_URL@ "@datarootdir@" +Alias @PNP_URL@ "@datarootdir@" AllowOverride None - Order allow,deny - Allow from all + = 2.3> + + Require all granted + # Require host 127.0.0.1 + + + + Order allow,deny + Allow from all + # - # Use the same value as defined in nagios.conf + # Use the same value as defined in nagios.cfg # AuthName "Nagios Access" AuthType Basic - AuthUserFile /usr/local/nagios/etc/htpasswd.users + AuthUserFile @NAGIOS_PWD@ Require valid-user # Turn on URL rewriting RewriteEngine On Options symLinksIfOwnerMatch # Installation directory - RewriteBase @BASE_URL@/ + RewriteBase @PNP_URL@/ # Protect application and system files from being viewed RewriteRule "^(?:application|modules|system)/" - [F] # Allow any files or directories that exist to be displayed directly diff --git a/sample-config/pnp/config.php.in b/sample-config/config_samples/config.php.in similarity index 77% rename from sample-config/pnp/config.php.in rename to sample-config/config_samples/config.php.in index eb01f73..dcc8d71 100644 --- a/sample-config/pnp/config.php.in +++ b/sample-config/config_samples/config.php.in @@ -1,6 +1,7 @@ # Example: conf['allowed_for_service_links'] = "nagiosadmin,operator"; -# +# $conf['allowed_for_service_links'] = "EVERYONE"; # @@ -135,7 +146,7 @@ $conf['allowed_for_host_search'] = "EVERYONE"; # # Who can use the host overview ? -# This function is called if no Service Description is given. +# This function is called if no Service Description is given. # $conf['allowed_for_host_overview'] = "EVERYONE"; @@ -147,13 +158,13 @@ $conf['allowed_for_host_overview'] = "EVERYONE"; $conf['allowed_for_pages'] = "EVERYONE"; # -# Which timerange should be used for the host overview site ? +# Which timerange should be used for the host overview site ? # use a key from array $views[] # $conf['overview-range'] = 1 ; # -# Scale the preview images used in /popup +# Scale the preview images used in /popup # $conf['popup-width'] = "300px"; @@ -164,7 +175,7 @@ $conf['popup-width'] = "300px"; $conf['ui-theme'] = 'smoothness'; # Language definitions to use. -# valid options are en_US, de_DE, es_ES, ru_RU, fr_FR +# valid options are en_US, de_DE, es_ES, ru_RU, fr_FR # $conf['lang'] = "en_US"; @@ -174,7 +185,7 @@ $conf['lang'] = "en_US"; $conf['date_fmt'] = "d.m.y G:i"; # -# This option breaks down the template name based on _ and then starts to +# This option breaks down the template name based on _ and then starts to # build it up and check the different template directories for a suitable template. # # Example: @@ -193,12 +204,13 @@ $conf['show_xml_icon'] = 1; # # Use FPDF Lib for PDF creation ? # -$conf['use_fpdf'] = 1; +$conf['use_fpdf'] = 1; # # Use this file as PDF background. # -$conf['background_pdf'] = '@sysconfdir@/background.pdf' ; +$conf['background_pdf'] = '@pkgsysconfdir@/background-A4.pdf' ; +#$conf['background_pdf'] = '@pkgsysconfdir@/background-letter.pdf' ; # # Enable Calendar @@ -206,16 +218,23 @@ $conf['background_pdf'] = '@sysconfdir@/background.pdf' ; $conf['use_calendar'] = 1; # -# Define default views with title and start timerange in seconds +# Define default views with title and start timerange in seconds # -# remarks: required escape on " with backslash +# supported keys: +# 'title' => The name of the view, e.g. "4 Hours" +# 'start' => The number of seconds before the current time from whence the graph x-axis should start +# 'extra_args' => additional arguments passed to rrdtool for this view's graph +# +# remarks: +# required escape on " with backslash +# extra_args are appended to args/opts defined elsewhere (e.g. in templates), but no effort is made to de-duplicate # #$views[] = array('title' => 'One Hour', 'start' => (60*60) ); -$views[] = array('title' => '4 Hours', 'start' => (60*60*4) ); -$views[] = array('title' => '25 Hours', 'start' => (60*60*25) ); -$views[] = array('title' => 'One Week', 'start' => (60*60*25*7) ); -$views[] = array('title' => 'One Month', 'start' => (60*60*24*32) ); -$views[] = array('title' => 'One Year', 'start' => (60*60*24*380) ); +$views[] = array('title' => '4 Hours', 'start' => (60 * 60 * 4) ); +$views[] = array('title' => '25 Hours', 'start' => (60 * 60 * 25) ); +$views[] = array('title' => 'One Week', 'start' => (60 * 60 * 25 * 7) ); +$views[] = array('title' => 'One Month', 'start' => (60 * 60 * 24 * 32) ); +$views[] = array('title' => 'One Year', 'start' => (60 * 60 * 24 * 380) ); # # rrdcached support @@ -247,7 +266,7 @@ $conf['mobile_devices'] = 'iPhone|iPod|iPad|android'; # # additional colour schemes # values taken from www.colorbrewer2.org -# for details on usage refer to the documentation of the helper functions +# for details on usage refer to the documentation of the helper functions # $scheme['Reds'] = array ('#FEE0D2','#FCBBA1','#FC9272','#FB6A4A','#EF3B2C','#CB181D','#A50F15','#67000D'); $scheme['Greens'] = array ('#E5F5E0','#C7E9C0','#A1D99B','#74C476','#41AB5D','#23AB45','#006D2C','#00441B'); @@ -272,4 +291,3 @@ $scheme['mixed2'] = array ('#b2182b','#2166ac','#d6604d','#4393c3','#f4a582',' '#F6E8C3','#C7EAE5','#DFC27D','#80CDC1','#BF812D','#35978F','#8C510A','#01665E'); $scheme['mixed3'] = array ('#67001F','#80CDC1','#B2182B','#35978F','#D6604D','#01665E','#F4A582','#003C30', '#FDDBC7','#92C5DE','#D1E5F0','#2166AC','#4393C3','#8C510A','#053061','#BF812D'); -?> diff --git a/sample-config/config_samples/config_local.php b/sample-config/config_samples/config_local.php new file mode 100644 index 0000000..9b8dbb6 --- /dev/null +++ b/sample-config/config_samples/config_local.php @@ -0,0 +1,5 @@ + "@datarootdir@" + "@PNP_URL@" => "@datarootdir@" ) -$HTTP["url"] =~ "(^@BASE_URL@)" { +$HTTP["url"] =~ "(^@PNP_URL@)" { auth.backend = "htpasswd" - auth.backend.htpasswd.userfile = "/usr/local/nagios/etc/htpasswd.users" + auth.backend.htpasswd.userfile = "@NAGIOS_PWD@" auth.require = ( "" => ( "method" => "basic", "realm" => "Nagios Access", diff --git a/sample-config/nagios.cfg-sample.in b/sample-config/config_samples/nagios.cfg.in similarity index 95% rename from sample-config/nagios.cfg-sample.in rename to sample-config/config_samples/nagios.cfg.in index fef969b..cb37713 100644 --- a/sample-config/nagios.cfg-sample.in +++ b/sample-config/config_samples/nagios.cfg.in @@ -39,4 +39,4 @@ host_perfdata_file_processing_command=process-host-perfdata-file # event_broker_options=-1 # minimum 4+8=12 process_performance_data=1 -broker_module=@libdir@/npcdmod.o config_file=@sysconfdir@/npcd.cfg +broker_module=@libdir@/npcdmod.o config_file=@pkgsysconfdir@/npcd.cfg diff --git a/sample-config/nginx.pnp4nagios.conf.in b/sample-config/config_samples/nginx.pnp4nagios.conf.in similarity index 92% rename from sample-config/nginx.pnp4nagios.conf.in rename to sample-config/config_samples/nginx.pnp4nagios.conf.in index 1a1bfc4..2289cc8 100644 --- a/sample-config/nginx.pnp4nagios.conf.in +++ b/sample-config/config_samples/nginx.pnp4nagios.conf.in @@ -1,11 +1,11 @@ # SAMPLE CONFIG SNIPPETS FOR NGINX WEB SERVER # Contributed by Thomas Charbonnel # -location @BASE_URL@ { +location @PNP_URL@ { # e.g. /usr/local/pnp4nagios/share; alias @datarootdir@; auth_basic "Nagios Access"; - auth_basic_user_file /usr/local/nagios/etc/htpasswd.users; + auth_basic_user_file @NAGIOS_PWD@; index index.php; # if we have e.g. /pnp4nagios/media/css/common.css # nginx will check diff --git a/sample-config/pnp/npcd.cfg-sample.in b/sample-config/config_samples/npcd.cfg.in similarity index 97% rename from sample-config/pnp/npcd.cfg-sample.in rename to sample-config/config_samples/npcd.cfg.in index 7811530..cbff179 100644 --- a/sample-config/pnp/npcd.cfg-sample.in +++ b/sample-config/config_samples/npcd.cfg.in @@ -30,8 +30,8 @@ group = @nagios_grp@ # log_type = # -#log_type = file -log_type = syslog +log_type = file +#log_type = syslog # log_file - define a path to your logfile @@ -40,7 +40,7 @@ log_type = syslog # log_file = # -log_file = @localstatedir@/npcd.log +log_file = @PNP_LOGDIR@/npcd.log # max_logfile_size - defines the maximum filesize (bytes) @@ -144,7 +144,7 @@ load_threshold = 0.0 # location of your pid file -pid_file=/var/run/npcd.pid +pid_file=@piddir@/npcd.pid ######################### diff --git a/sample-config/config_samples/pnp-bulk.cfg.in b/sample-config/config_samples/pnp-bulk.cfg.in new file mode 100644 index 0000000..e5c10f3 --- /dev/null +++ b/sample-config/config_samples/pnp-bulk.cfg.in @@ -0,0 +1,30 @@ +# -*- conf -*- +# definitions for PNP processing commands +# please choose one of the three files +# ( pnp-synchronous.cfg +# pnp-bulk.cfg +# pnp-npcd.cfg ) +# +# copy to your nagios object config directory +# /etc/nagios/objects +# then edit /etc/nagios/nagios.conf to load the config file +# +# OR copy to you nagios object config directory +# /etc/nagios/objects.d +# where all of the config files are loaded. +# + + +# +# Bulk mode +# +define command { + command_name process-service-perfdata-file + command_line @libexecdir@/process_perfdata.pl --bulk @PERFDATA_SPOOL_DIR@/service-perfdata +} + +define command { + command_name process-host-perfdata-file + command_line @libexecdir@/process_perfdata.pl --bulk @PERFDATA_SPOOL_DIR@/host-perfdata +} + diff --git a/sample-config/config_samples/pnp-npcd.cfg.in b/sample-config/config_samples/pnp-npcd.cfg.in new file mode 100644 index 0000000..5d108a9 --- /dev/null +++ b/sample-config/config_samples/pnp-npcd.cfg.in @@ -0,0 +1,28 @@ +# -*- conf -*- +# definitions for PNP processing commands +# please choose one of the three files +# ( pnp-synchronous.cfg +# pnp-bulk.cfg +# pnp-npcd.cfg ) +# +# copy to your nagios object config directory +# /etc/nagios/objects +# then edit /etc/nagios/nagios.conf to load the config file +# +# OR copy to you nagios object config directory +# /etc/nagios/objects.d +# where all of the config files are loaded. +# + +# +# Bulk with NPCD mode +# +define command { + command_name process-service-perfdata-file + command_line /bin/mv @PERFDATA_SPOOL_DIR@/service-perfdata @PERFDATA_SPOOL_DIR@/service-perfdata.$TIMET$ +} + +define command { + command_name process-host-perfdata-file + command_line /bin/mv @PERFDATA_SPOOL_DIR@/host-perfdata @PERFDATA_SPOOL_DIR@/host-perfdata.$TIMET$ +} diff --git a/sample-config/config_samples/pnp-sync.cfg.in b/sample-config/config_samples/pnp-sync.cfg.in new file mode 100644 index 0000000..73e3e46 --- /dev/null +++ b/sample-config/config_samples/pnp-sync.cfg.in @@ -0,0 +1,31 @@ +# -*- conf -*- +# definitions for PNP processing commands +# please choose one of the three files +# ( pnp-synchronous.cfg +# pnp-bulk.cfg +# pnp-npcd.cfg ) +# +# copy to your nagios object config directory +# /etc/nagios/objects +# then edit /etc/nagios/nagios.conf to load the config file +# +# OR copy to you nagios object config directory +# /etc/nagios/objects.d +# where all of the config files are loaded. +# + + +# +# synchronous mode +# + +define command { + command_name process-service-perfdata-pnp + command_line @PERL@ @libexecdir@/process_perfdata.pl +} + +define command { + command_name process-host-perfdata-pnp + command_line @PERL@ @libexecdir@/process_perfdata.pl -d HOSTPERFDATA +} + diff --git a/sample-config/pnp/process_perfdata.cfg-sample.in b/sample-config/config_samples/process_perfdata.cfg.in similarity index 77% rename from sample-config/pnp/process_perfdata.cfg-sample.in rename to sample-config/config_samples/process_perfdata.cfg.in index 67a7c4c..ecb2ee4 100644 --- a/sample-config/pnp/process_perfdata.cfg-sample.in +++ b/sample-config/config_samples/process_perfdata.cfg.in @@ -1,4 +1,4 @@ -# @PKG_NAME@–@PKG_VERSION@ +# @PACKAGE_NAME@–@PACKAGE_VERSION@ # Config File for process_perfdata.pl # # More info on RRDtool can be found at www.rrdtool.org @@ -26,7 +26,7 @@ RRDTOOL = @RRDTOOL@ # # Location of PNP config files # -CFG_DIR = @sysconfdir@ +CFG_DIR = @pkgsysconfdir@ # # Use a single RRD database per service @@ -47,7 +47,7 @@ RRD_HEARTBEAT = 8460 # # File with RRA options used to create new RRD files # -RRA_CFG = @sysconfdir@/rra.cfg +RRA_CFG = @pkgsysconfdir@/rra.cfg # # Interval at which PDPs are generated @@ -62,7 +62,7 @@ LOG_FILE = @PERFDATA_LOG@ # # Loglevel 0=silent 1=normal 2=debug # -LOG_LEVEL = @DEBUG@ +LOG_LEVEL = @DEBUG_LEVEL@ # # XML encoding @@ -88,7 +88,28 @@ RRD_DAEMON_OPTS = # # Spool directory used for internal statistics # -STATS_DIR = @localstatedir@/stats +STATS_DIR = @PERFDATA_STATS@ + +# +# Ignore certain performance data based on host name +# +# You can put it any regular expression that matches the host name +# +#IGNORE_HOST_PATTERN = + +# +# Ignore certain performance data based on service name +# +# You can put it any regular expression that matches the service name +# +#IGNORE_SERVICE_PATTERN = + +# +# Ignore certain performance data based on label of an individual data point +# +# You can put it any regular expression that matches the label +# +#IGNORE_LABEL_PATTERN = ######################################################### @@ -132,4 +153,4 @@ KEY = should_be_changed # The shared password will be read from this file. # Only the first 32 characters will be used. # -# KEY_FILE = @sysconfdir@/secret.key +#KEY_FILE = @pkgsysconfdir@/secret.key diff --git a/sample-config/pnp/rra.cfg-sample b/sample-config/config_samples/rra.cfg similarity index 100% rename from sample-config/pnp/rra.cfg-sample rename to sample-config/config_samples/rra.cfg diff --git a/sample-config/config_samples/templates.cfg b/sample-config/config_samples/templates.cfg new file mode 100644 index 0000000..36a16fc --- /dev/null +++ b/sample-config/config_samples/templates.cfg @@ -0,0 +1,224 @@ +############################################################################### +# TEMPLATES.CFG - SAMPLE OBJECT TEMPLATES +# +# +# NOTES: This config file provides you with some example object definition +# templates that are referred by other host, service, contact, etc. +# definitions in other config files. +# +# You don't need to keep these definitions in a separate file from your +# other object definitions. This has been done just to make things +# easier to understand. +# +############################################################################### + + + +############################################################################### +# +# CONTACT TEMPLATES +# +############################################################################### + +# Generic contact definition template +# This is NOT a real contact, just a template! + +define contact { + + name generic-contact ; The name of this contact template + service_notification_period 24x7 ; service notifications can be sent anytime + host_notification_period 24x7 ; host notifications can be sent anytime + service_notification_options w,u,c,r,f,s ; send notifications for all service states, flapping events, and scheduled downtime events + host_notification_options d,u,r,f,s ; send notifications for all host states, flapping events, and scheduled downtime events + service_notification_commands notify-service-by-email ; send service notifications via email + host_notification_commands notify-host-by-email ; send host notifications via email + register 0 ; DON'T REGISTER THIS DEFINITION - ITS NOT A REAL CONTACT, JUST A TEMPLATE! +} + + + +############################################################################### +# +# HOST TEMPLATES +# +############################################################################### + +# Generic host definition template +# This is NOT a real host, just a template! + +define host { + + name generic-host ; The name of this host template + use host-pnp ; pnp4nagios graphing + notifications_enabled 1 ; Host notifications are enabled + event_handler_enabled 1 ; Host event handler is enabled + flap_detection_enabled 1 ; Flap detection is enabled + process_perf_data 1 ; Process performance data + retain_status_information 1 ; Retain status information across program restarts + retain_nonstatus_information 1 ; Retain non-status information across program restarts + notification_period 24x7 ; Send host notifications at any time + register 0 ; DON'T REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE! +} + + + +# Linux host definition template +# This is NOT a real host, just a template! + +define host { + + name linux-server ; The name of this host template + use generic-host ; This template inherits other values from the generic-host template + check_period 24x7 ; By default, Linux hosts are checked round the clock + check_interval 5 ; Actively check the host every 5 minutes + retry_interval 1 ; Schedule host check retries at 1 minute intervals + max_check_attempts 10 ; Check each Linux host 10 times (max) + check_command check-host-alive ; Default command to check Linux hosts + notification_period workhours ; Linux admins hate to be woken up, so we only notify during the day + ; Note that the notification_period variable is being overridden from + ; the value that is inherited from the generic-host template! + notification_interval 120 ; Resend notifications every 2 hours + notification_options d,u,r ; Only send notifications for specific host states + contact_groups admins ; Notifications get sent to the admins by default + register 0 ; DON'T REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE! +} + + + +# Windows host definition template +# This is NOT a real host, just a template! + +define host { + + name windows-server ; The name of this host template + use generic-host ; Inherit default values from the generic-host template + check_period 24x7 ; By default, Windows servers are monitored round the clock + check_interval 5 ; Actively check the server every 5 minutes + retry_interval 1 ; Schedule host check retries at 1 minute intervals + max_check_attempts 10 ; Check each server 10 times (max) + check_command check-host-alive ; Default command to check if servers are "alive" + notification_period 24x7 ; Send notification out at any time - day or night + notification_interval 30 ; Resend notifications every 30 minutes + notification_options d,r ; Only send notifications for specific host states + contact_groups admins ; Notifications get sent to the admins by default + hostgroups windows-servers ; Host groups that Windows servers should be a member of + register 0 ; DON'T REGISTER THIS - ITS JUST A TEMPLATE +} + + + +# We define a generic printer template that can +# be used for most printers we monitor + +define host { + + name generic-printer ; The name of this host template + use generic-host ; Inherit default values from the generic-host template + check_period 24x7 ; By default, printers are monitored round the clock + check_interval 5 ; Actively check the printer every 5 minutes + retry_interval 1 ; Schedule host check retries at 1 minute intervals + max_check_attempts 10 ; Check each printer 10 times (max) + check_command check-host-alive ; Default command to check if printers are "alive" + notification_period workhours ; Printers are only used during the workday + notification_interval 30 ; Resend notifications every 30 minutes + notification_options d,r ; Only send notifications for specific host states + contact_groups admins ; Notifications get sent to the admins by default + statusmap_image printer.png + register 0 ; DON'T REGISTER THIS - ITS JUST A TEMPLATE +} + + + +# Define a template for switches that we can reuse +define host { + + name generic-switch ; The name of this host template + use generic-host ; Inherit default values from the generic-host template + check_period 24x7 ; By default, switches are monitored round the clock + check_interval 5 ; Switches are checked every 5 minutes + retry_interval 1 ; Schedule host check retries at 1 minute intervals + max_check_attempts 10 ; Check each switch 10 times (max) + check_command check-host-alive ; Default command to check if routers are "alive" + notification_period 24x7 ; Send notifications at any time + notification_interval 30 ; Resend notifications every 30 minutes + notification_options d,r ; Only send notifications for specific host states + contact_groups admins ; Notifications get sent to the admins by default + statusmap_image switch.png + register 0 ; DON'T REGISTER THIS - ITS JUST A TEMPLATE +} + +# Define a template for routers that we can reuse +define host{ + name generic-router ; The name of this host template + use generic-switch ; Inherit default values from the generic-host template + statusmap_image router.png + register 0 ; DONT REGISTER THIS - ITS JUST A TEMPLATE +} + + +############################################################################### +# +# SERVICE TEMPLATES +# +############################################################################### + +# Generic service definition template +# This is NOT a real service, just a template! + +define service { + + name generic-service ; The 'name' of this service template + use service-pnp ; pnp4nagios graphing + active_checks_enabled 1 ; Active service checks are enabled + passive_checks_enabled 1 ; Passive service checks are enabled/accepted + parallelize_check 1 ; Active service checks should be parallelized (disabling this can lead to major performance problems) + obsess_over_service 1 ; We should obsess over this service (if necessary) + check_freshness 0 ; Default is to NOT check service 'freshness' + notifications_enabled 1 ; Service notifications are enabled + event_handler_enabled 1 ; Service event handler is enabled + flap_detection_enabled 1 ; Flap detection is enabled + process_perf_data 1 ; Process performance data + retain_status_information 1 ; Retain status information across program restarts + retain_nonstatus_information 1 ; Retain non-status information across program restarts + is_volatile 0 ; The service is not volatile + check_period 24x7 ; The service can be checked at any time of the day + max_check_attempts 3 ; Re-check the service up to 3 times in order to determine its final (hard) state + check_interval 10 ; Check the service every 10 minutes under normal conditions + retry_interval 2 ; Re-check the service every two minutes until a hard state can be determined + contact_groups admins ; Notifications get sent out to everyone in the 'admins' group + notification_options w,u,c,r ; Send notifications about warning, unknown, critical, and recovery events + notification_interval 60 ; Re-notify about service problems every hour + notification_period 24x7 ; Notifications can be sent out at any time + register 0 ; DON'T REGISTER THIS DEFINITION - ITS NOT A REAL SERVICE, JUST A TEMPLATE! +} + + + +# Local service definition template +# This is NOT a real service, just a template! + +define service { + + name local-service ; The name of this service template + use generic-service ; Inherit default values from the generic-service definition + max_check_attempts 4 ; Re-check the service up to 4 times in order to determine its final (hard) state + check_interval 5 ; Check the service every 5 minutes under normal conditions + retry_interval 1 ; Re-check the service every minute until a hard state can be determined + register 0 ; DON'T REGISTER THIS DEFINITION - ITS NOT A REAL SERVICE, JUST A TEMPLATE! +} + +###################################################### +# +# pnp4nagios +# +define host { + name host-pnp + action_url /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=_HOST_ + register 0 +} + +define service { + name service-pnp + action_url /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=$SERVICEDESC$ + register 0 +} diff --git a/sample-config/config_tools/NagiosCfgMod.pl.in b/sample-config/config_tools/NagiosCfgMod.pl.in new file mode 100755 index 0000000..9eb67c8 --- /dev/null +++ b/sample-config/config_tools/NagiosCfgMod.pl.in @@ -0,0 +1,169 @@ +#! @PERL@ +use strict; +use Getopt::Long; + +my $infile; +my $outfile; +my $mode = 'sync'; +my $help; +my $nagver = '4.0'; + +GetOptions("mode|m=s" => \$mode, + "input|i=s" => \$infile, + "output|o=s" => \$outfile, + "nagver|n=s" => \$nagver, + "help|h|?" => \$help, + ) or die "error in command arguments"; + +if (defined($help)) { + help(); + exit 0; +} + +if ($mode =~ /^\s*sy/) { + $mode = 'sync'; +} elsif ($mode =~ /^\s*bu/) { + $mode = 'bulk'; +} elsif ($mode =~ /^\s*npcd/) { + $mode = 'npcd'; +} else { + die("invalid mode, must be one of sync, bulk, or npcd"); +} + +if (! $nagver =~ /^\d+(\.\d+)*$/) { + die ("invalid nagios version $nagver given, def: 4.0"); +} + + +my ($IN,$OUT); + +$infile = shift unless defined $infile; + +if (defined($infile)) { + open($IN,"<$infile") || die "error opening $infile"; +} else { + $IN = *STDIN; +} + +if (defined($outfile)) { + open($OUT,">$outfile") || die "error opening $outfile"; +} else { + $OUT = *STDOUT; +} + +my (@cfg) = (<$IN>); + +my $got; + +$got = 0; +my $lastcfgfile=$#cfg; +for (my $j = 0; $j <= $#cfg; $j++) { + my $line = $cfg[$j]; + if ($line =~ /^cfg_file=(\S+)/) { + my $sel = $1; + $lastcfgfile = $j; + if ($sel =~ /\/pnp-\w+\.cfg/) { + $cfg[$j] = '#'.$cfg[$j]; + } + } +} +splice(@cfg,$lastcfgfile+1,0,"cfg_file=@NAGIOS_OBJ@/pnp-$mode.cfg\n"); + + + +$got = 0; +for (my $j = 0; $j <= $#cfg; $j++) { + my $line = $cfg[$j]; + if ($line =~ /^process_performance_data=(\d)/) { + my $sel = $1; + $got = 1; + if ($sel == 0) { + $cfg[$j] = "#$line"; + splice(@cfg,$j+1,0,"process_performance_data=1\n"); + } + last; + } +} +push(@cfg,"process_performance_data=1\n") unless $got; + +if ($mode eq 'sync') { + if ($nagver ge v3.1) { + $got = 0; + + for (my $j = 0; $j <= $#cfg; $j++) { + my $line = $cfg[$j]; + if ($line =~ /^enable_environment_macros=(\d)/) { + my $sel = $1; + $got = 1; + if ($sel == 0) { + $cfg[$j] = "#$line"; + splice(@cfg,$j+1,0,"enable_environment_macros=1\n"); + } + last; + } + } + push(@cfg,"enable_environment_macros=1\n"); + } + + $got = 0; + + for (my $j = 0; $j <= $#cfg; $j++) { + my $line = $cfg[$j]; + if ($line =~ /^service_perfdata_command=(\S+)/) { + my $sel = $1; + $got = 1; + if ($sel ne 'process-service-perfdata') { + $cfg[$j] = "#$line"; + splice(@cfg,$j+1,0,"service_perfdata_command=process-service-perfdata-pnp\n"); + } + last; + } + } + push(@cfg,"service_perfdata_command=process-service-perfdata-pnp\n"); + + if ($nagver ge v3.0) { + $got = 0; + + for (my $j = 0; $j <= $#cfg; $j++) { + my $line = $cfg[$j]; + if ($line =~ /^host_perfdata_command=(\S+)/) { + my $sel = $1; + $got = 1; + if ($sel ne 'process-host-perfdata') { + $cfg[$j] = "#$line"; + splice(@cfg,$j+1,0,"host_perfdata_command=process-host-perfdata-pnp\n"); + } + last; + } + } + push(@cfg,"host_perfdata_command=process-host-perfdata-pnp\n"); + } +} elsif ($mode eq 'bulk' or $mode eq 'npcd') { + + for (my $j = 0; $j <= $#cfg; $j++) { + my $line = $cfg[$j]; + if ($line =~ /^(host|service)_perfdata_file(_template|_mode|_processing_interval|_processing_command)?=/) { + + $cfg[$j] = "#$line"; + } + } + push(@cfg, + '# *** the template definition differs from the one in the original nagios.cfg'."\n", + '#'."\n", + 'service_perfdata_file=@PERFDATA_SPOOL_DIR@/service-perfdata'."\n", + 'service_perfdata_file_template=DATATYPE::SERVICEPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tSERVICEDESC::$SERVICEDESC$\tSERVICEPERFDATA::$SERVICEPERFDATA$\tSERVICECHECKCOMMAND::$SERVICECHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$\tSERVICESTATE::$SERVICESTATE$\tSERVICESTATETYPE::$SERVICESTATETYPE$'."\n", + 'service_perfdata_file_mode=a'."\n", + 'service_perfdata_file_processing_interval=15'."\n", + 'service_perfdata_file_processing_command=process-service-perfdata-file'."\n", + '# *** the template definition differs from the one in the original nagios.cfg'."\n", + '#'."\n", + 'host_perfdata_file=@PERFDATA_SPOOL_DIR@/host-perfdata'."\n", + 'host_perfdata_file_template=DATATYPE::HOSTPERFDATA\tTIMET::$TIMET$\tHOSTNAME::$HOSTNAME$\tHOSTPERFDATA::$HOSTPERFDATA$\tHOSTCHECKCOMMAND::$HOSTCHECKCOMMAND$\tHOSTSTATE::$HOSTSTATE$\tHOSTSTATETYPE::$HOSTSTATETYPE$'."\n", + 'host_perfdata_file_mode=a'."\n", + 'host_perfdata_file_processing_interval=15'."\n", + 'host_perfdata_file_processing_command=process-host-perfdata-file'."\n", + ); + +} +print $OUT @cfg; + diff --git a/sample-config/config_tools/TemplateMod.pl.in b/sample-config/config_tools/TemplateMod.pl.in new file mode 100755 index 0000000..1a734a9 --- /dev/null +++ b/sample-config/config_tools/TemplateMod.pl.in @@ -0,0 +1,140 @@ +#!@PERL@ +use strict; +use Getopt::Long; + +my ($infile, $outfile, $help); + +GetOptions("input|i=s" => \$infile, + "output|o=s" => \$outfile, + "help|h" => \$help, + ); +if (defined($help)) { + help(); + exit 0; +} +die "input file missing" unless defined $infile && -e $infile; +die "output file missing" unless defined $outfile; + + + + + + +if (system("grep -q '_url */pnp4nagios/index' $infile") == 0) { + print "$infile already has pnp4nagios template info\n"; + exit 0; +} + + +open(T,"<$infile") || die "unable to open $infile"; +my (@templ) = (); +close(T); +open(OUT, ">$outfile") || die "unable to open $outfile"; + + + +my ($genhost0,$genhost1); +my ($gensvc0, $gensvc1); +my $host = ''; +my $service = ''; +my $inhost = 0; +my $inservice = 0; +my $j = -1; +foreach my $line (@templ) { + $j++; + + if ($inhost) { + if ($line =~ /^\s*\}/) { + $inhost = 0; + $genhost1 = $j if $host =~ /generic-host/; + } elsif ($line =~ /^\s*name\s+(\S+)/) { + $host = $1; + $genhost0 = $j if $host =~ /generic-host/; + } + next; + } elsif ($line =~ /^\s*define\s+host\s/) { + $inhost = 1; + $host = ''; + next; + } + + if ($inservice) { + if ($line =~ /^\s*\}/) { + $inservice = 0; + $gensvc1 = $j if $service =~ /generic-service/; + } elsif ($line =~ /^\s*name\s+(\S+)/) { + $service = $1; + $gensvc0 = $j if $service =~ /generic-service/; + } + } elsif ($line =~ /^\s*define\s+service\s/) { + $inservice = 1; + $service = ''; + } + +} + +my $diduse; + +$diduse = 0; +for ($j = $genhost0; $j <= $genhost1; $j++) { + if ($templ[$j] =~ /^\s*use\s/) { + $templ[$j] = ";".$templ[$j]; + splice(@templ,$j,0," use\t\t\t\t host-pnp ; graphing\n"); + $diduse=1; + last; + } +} +splice(@templ,$genhost0+1,0," use\t\t\t\t host-pnp ; graphing\n") unless $diduse; + +$j = -1; +foreach my $line (@templ) { + $j++; + + if ($inservice) { + if ($line =~ /^\s*\}/) { + $inservice = 0; + $gensvc1 = $j if $service =~ /generic-service/; + } elsif ($line =~ /^\s*name\s+(\S+)/) { + $service = $1; + $gensvc0 = $j if $service =~ /generic-service/; + } + } elsif ($line =~ /^\s*define\s+service\s/) { + $inservice = 1; + $service = ''; + } + +} + +$diduse = 0; +for ($j = $gensvc0; $j <= $gensvc1; $j++) { + if ($templ[$j] =~ /^\s*use\s/) { + $templ[$j] = ";".$templ[$j]; + splice(@templ,$j,0," use\t\t\t\t service-pnp ; graphing\n"); + $diduse=1; + last; + } +} +splice(@templ,$gensvc0+1,0," use\t\t\t\t service-pnp ; graphing\n") unless $diduse; + + +foreach my $line (@templ) { + print OUT $line; +} + +print OUT "######################################################\n"; +print OUT "#\n"; +print OUT "# pnp4nagios\n"; +print OUT "#\n"; +print OUT "define host {\n"; +print OUT " name host-pnp\n"; +print OUT " action_url /pnp4nagios/index.php/graph?host=\$HOSTNAME\$&srv=_HOST_\n"; +print OUT " register 0\n"; +print OUT "}\n"; +print OUT "\n"; +print OUT "define service {\n"; +print OUT " name service-pnp\n"; +print OUT " action_url /pnp4nagios/index.php/graph?host=\$HOSTNAME\$&srv=\$SERVICEDESC\$\n"; +print OUT " register 0\n"; +print OUT "}\n"; +close(OUT); +exit 0; diff --git a/scripts/verify_pnp_config_v2.pl b/sample-config/config_tools/verify_pnp_config.in similarity index 66% rename from scripts/verify_pnp_config_v2.pl rename to sample-config/config_tools/verify_pnp_config.in index e0bc2c7..9e438dd 100755 --- a/scripts/verify_pnp_config_v2.pl +++ b/sample-config/config_tools/verify_pnp_config.in @@ -1,4 +1,6 @@ -#!/usr/bin/perl +#!@PERL@ +# @datarootdir@ just to keep configure from bitching about it. +# # Copyright (c) 2005-2011 PNP4Nagios Developer Team (http://www.pnp4nagios.org) # # This program is free software; you can redistribute it and/or @@ -24,10 +26,20 @@ use File::Find; use File::Glob; use Term::ANSIColor; -my $version = 'pnp4nagios-head'; +my $version = '@PACKAGE_VERSION@'; # process command line parameters -use vars qw ( $help $debug $mode $vInfo $PNPCfg $MainCfg $last_check $object); +use vars qw ( $help $debug $mode $vInfo $PNPCfg $MainCfg $last_check $object $user $group $http_user $http_group +$dist_type $opsys); + +# use 'config' to set defaults +$MainCfg='@NAGIOS_CFG@'; +$PNPCfg='@pkgsysconfdir@'; +$http_user='@HTTP_USER@'; +$http_group='@HTTP_GROUP@'; +$dist_type='@dist_type@'; +$opsys='@opsys@'; + my $start_options = $0 . " " . join(" ", @ARGV); Getopt::Long::Configure('bundling'); GetOptions( @@ -37,10 +49,18 @@ GetOptions( "c|config=s" => \$MainCfg, "p|pnpcfg=s" => \$PNPCfg, "o|object=s" => \$object, + "u|user=s" => \$user, + "g|group=s" => \$group, ); -my @modes = ("bulk", "bulk+npcd", "sync", "npcdmod"); -my @products = ("nagios", "icinga"); +if ($help) { + usage(); + exit 0; +} + + +my @modes = ("bulk", "npcd", "sync","npcdmod"); +my @products = ("nagios", "icinga", "icinga2"); my @states = ("OK", "WARN", "CRIT", "UNKN", "INFO", "HINT", "DBG"); my @colors = ("bold green", "bold yellow", "bold red", "bold blue", "bold blue", "bold yellow", "black on_red"); my %process_perf_data_stats = ('hosts' => 0, 'services' => 0, 'noperf' => 0, 'noperf_but_enabled' => 0 , 0 => 0, 1 => 0); @@ -48,7 +68,7 @@ my %stats = ( 0 => 0, 1 => 0, 2 => 0, 3 => 0, 4 => 0, 5 =>0 ); my %sizing = ( 50 => 'sync', 200 => 'bulk', - 5000 => 'bulk+npcd', + 5000 => 'npcd', 10000 => 'npcdmod', ); @@ -59,9 +79,22 @@ if ( ! $MainCfg ){ } if ( ! $mode ){ - usage(); + if (open(N,"<$MainCfg")) { + while () { + if (/^cfg_file=\/.*\/pnp-(\w+)\.cfg/) { + $mode = $1; + last; + } + } + close(N); + } else { + die "error opening $MainCfg for reading"; + } + if (! $mode) { + usage(); usage_no_mode(); exit; + } } if ( ! $PNPCfg ){ @@ -86,9 +119,13 @@ my %statistics = ( my %cfg = (); my %commands = (); +my %modules = (); my $uid = 0; my $gid = 0; +my $http_uid = 0; +my $http_gid = 0; my $process_perfdata_cfg = 0; +my $OMD_ROOT = $ENV{OMD_ROOT} || ""; # # Begin @@ -99,9 +136,11 @@ info("My version is: ".$version,4); info("Start Options: ".$start_options, 4); # -# Read Main config file +# Read Main config file unless Icinga2 # -process_nagios_cfg(); +if ($MainCfg !~ /.conf/) { + process_nagios_cfg(); +} # # get the product name # @@ -112,26 +151,33 @@ if( $product eq 0 ){ }else{ info("Running product is '$product'", 0); } +if($product eq "icinga2" and $mode ne "npcd"){ + info_and_exit ("Icinga2 only supports 'npcd' mode", 2); +} # # Read objects cache file to get more information # Needs a running product # -check_config_var('object_cache_file', 'exists', 'break'); -if( -r $cfg{'object_cache_file'} ){ - process_objects_file($cfg{'object_cache_file'}); -}else{ - info_and_exit($cfg{'object_cache_file'}. " is not readable", 2); +if($product ne "icinga2"){ + check_config_var('object_cache_file', 'exists', 'break'); + if( -r $cfg{'object_cache_file'} ){ + process_objects_file($cfg{'object_cache_file'}); + }else{ + info_and_exit($cfg{'object_cache_file'}. " is not readable", 2); + } } # # Read resource.cfg # -check_config_var('resource_file', 'exists', 'break'); -if( -r $cfg{'resource_file'} ){ - process_npcd_cfg($cfg{'resource_file'}); -}else{ - info_and_exit($cfg{'resource_file'}. " is not readable", 2); +if($product ne "icinga2"){ + check_config_var('resource_file', 'exists', 'break'); + if( -r $cfg{'resource_file'} ){ + process_npcd_cfg($cfg{'resource_file'}); + }else{ + info_and_exit($cfg{'resource_file'}. " is not readable", 2); + } } # @@ -152,7 +198,7 @@ process_perfdata_cfg($ppcfg); # if( -r "$PNPCfg/pnp4nagios_release" ){ process_pnp4nagios_release("$PNPCfg/pnp4nagios_release"); - info("Found PNP4Nagios version ".get_config_var('PKG_VERSION'), 0); + info("Found PNP4Nagios version ".get_config_var('PACKAGE_VERSION'), 0); info("./configure Options ".get_config_var('CONFIGURE_ARGS'), 0) if get_config_var('CONFIGURE_ARGS'); }else{ info("No pnp4nagios_release file found. This might be an older version of PNP4Nagios", 0); @@ -162,24 +208,44 @@ if( -r "$PNPCfg/pnp4nagios_release" ){ # Start Main config checks # -if(config_var_exists($product.'_user') ){ - my $user = get_config_var($product.'_user'); +unless($user){ + if($product eq "icinga2"){ + $user = `icinga2 object list --type user | grep " name = "`; + ($user) = $user =~ m|"(.+)"|; + }else{ + if(config_var_exists($product.'_user') ){ + $user = get_config_var($product.'_user'); + } + } + info( "Configured User is '$user'", 0); +} +if($user){ $uid = getpwnam($user); - info( "Effective User is '$user'", 0); - if($uid){ + if(defined $uid){ + info( "Effective User is '$user'", 0); info("User $user exists with ID '$uid'", 0 ); }else{ - info_and_exit("User $user does not exist", 2 ); + info_and_exit("User $user does not exist", 2 ); } }else{ info_and_exit("Option '".$product."_user' not found in $MainCfg", 2); } -if(config_var_exists($product.'_group') ){ - my $group = get_config_var($product.'_group'); +unless($group){ + if($product eq "icinga2"){ + $group = `icinga2 object list --type user | grep "groups ="`; + ($group) = $group =~ m|\[(.+)\]|; + }else{ + if(config_var_exists($product.'_group') ){ + $group = get_config_var($product.'_group'); + } + } + info( "Configured Group is '$group'", 0); +} +if($group){ $gid = getgrnam($group); - info( "Effective group is '$group'", 0); - if($gid){ + if(defined $gid){ + info( "Effective group is '$group'", 0); info("Group $group exists with ID '$gid'", 0 ); }else{ info_and_exit("Group $group does not exist", 2 ); @@ -188,6 +254,31 @@ if(config_var_exists($product.'_group') ){ info_and_exit("Option '".$product."_group' not found in $MainCfg", 2); } + +if ($http_user) { + $http_uid = getpwnam($http_user); + if(defined $http_uid){ + info( "Effective User for http server is '$http_user'", 0); + info("User $http_user exists with ID '$http_uid'", 0 ); + }else{ + info_and_exit("User $http_user does not exist", 2 ); + } +}else{ + info_and_exit("Option '"."http_user' not found in $MainCfg", 2); +} + +if ($http_group) { + $http_gid = getgrnam($http_group); + if(defined $http_gid){ + info( "Effective group for http server is '$http_group'", 0); + info("User $http_group exists with GID '$http_gid'", 0 ); + }else{ + info_and_exit("User $http_group does not exist", 2 ); + } +}else{ + info_and_exit("Option '"."http_group' not found in $MainCfg", 2); +} + # # Start sync config checks # @@ -264,36 +355,78 @@ if($mode eq "bulk"){ check_process_perfdata_pl($command_line); } -if($mode eq "bulk+npcd"){ - info("========== Checking Bulk Mode + NPCD Config ============",4); +if($mode eq "npcd"){ + info("========== Checking Mode NPCD Config ============",4); - compare_config_var('process_performance_data', '1'); - check_config_var('service_perfdata_file', 'exists'); - check_config_var('service_perfdata_file_template', 'exists'); - check_perfdata_file_template(get_config_var('service_perfdata_file_template')); - check_config_var('service_perfdata_file_mode', 'exists'); - check_config_var('service_perfdata_file_processing_interval', 'exists'); - check_config_var('service_perfdata_file_processing_command', 'exists'); + if($product eq "icinga2"){ + my $ena = `icinga2 feature list | grep 'Enabled features' 2>&1 | grep perfdata`; + if($?){ + $last_check++; + } + unless ($ena){ + info_and_exit ("Feature 'perfdata' not enabled",2); + } + my @lines = `icinga2 object list --type PerfdataWriter 2>/dev/null`; + if($?){ + $last_check++; + }else{ + for (@lines) { + chomp; + next unless (/=/); + next if (/%/); + my ($cmd,$val) = $_ =~ m|\*\s+(.*?)\s*=\s*["]?(.*)["]?|; + $cfg{$cmd} = $val; + } + } + check_config_var('service_perfdata_path', 'exists'); + check_config_var('service_temp_path', 'exists'); + check_config_var('service_format_template', 'exists'); + check_perfdata_file_template(get_config_var('service_format_template')); + + check_config_var('host_perfdata_path', 'exists'); + check_config_var('host_temp_path', 'exists'); + check_config_var('host_format_template', 'exists'); + check_perfdata_file_template(get_config_var('host_format_template')); + }else{ + compare_config_var('process_performance_data', '1'); + check_config_var('service_perfdata_file', 'exists'); + check_config_var('service_perfdata_file_template', 'exists'); + check_perfdata_file_template(get_config_var('service_perfdata_file_template')); + check_config_var('service_perfdata_file_mode', 'exists'); + check_config_var('service_perfdata_file_processing_interval', 'exists'); + check_config_var('service_perfdata_file_processing_command', 'exists'); - check_config_var('host_perfdata_file', 'exists'); - check_config_var('host_perfdata_file_template', 'exists'); - check_perfdata_file_template(get_config_var('host_perfdata_file_template')); - check_config_var('host_perfdata_file_mode', 'exists'); - check_config_var('host_perfdata_file_processing_interval', 'exists'); - check_config_var('host_perfdata_file_processing_command', 'exists'); + check_config_var('host_perfdata_file', 'exists'); + check_config_var('host_perfdata_file_template', 'exists'); + check_perfdata_file_template(get_config_var('host_perfdata_file_template')); + check_config_var('host_perfdata_file_mode', 'exists'); + check_config_var('host_perfdata_file_processing_interval', 'exists'); + check_config_var('host_perfdata_file_processing_command', 'exists'); + } last_info("Needed config options are missing. http://docs.pnp4nagios.org",5,$last_check); # Options not allowed in bulk mode - check_config_var('service_perfdata_command', 'notexists'); - check_config_var('host_perfdata_command', 'notexists'); - check_config_var('broker_module', 'notexists'); + if($product ne "icinga2"){ + check_config_var('service_perfdata_command', 'notexists'); + check_config_var('host_perfdata_command', 'notexists'); + check_config_var('broker_module', 'notexists'); + } last_info("Config options are not allowed in bulk mode with npcd",5,$last_check); info(ucfirst($product)." config looks good so far",4); info("========== Checking config values ============",4); my $command_line; - my $npcd_cfg = check_proc_npcd(get_config_var($product.'_user')); + my $npcd_cfg = ""; + if($product eq "icinga2"){ + $npcd_cfg = "$PNPCfg/npcd.cfg"; + $npcd_cfg = "$OMD_ROOT/etc/pnp4nagios/npcd.cfg" if ($OMD_ROOT); + }else{ + $npcd_cfg = check_proc_npcd(get_config_var($product.'_user')); + } + unless (-f $npcd_cfg){ + $npcd_cfg = $PNPCfg . $npcd_cfg; + } if( -r $npcd_cfg){ info("$npcd_cfg is used by npcd and readable",0); @@ -306,14 +439,17 @@ if($mode eq "bulk+npcd"){ check_config_var('perfdata_spool_dir', 'exists'); count_spool_files(get_config_var('perfdata_spool_dir')); - $command_line = check_command_definition('service_perfdata_file_processing_command'); - $command_line = check_command_definition('host_perfdata_file_processing_command'); + if($product ne "icinga2"){ + $command_line = check_command_definition('service_perfdata_file_processing_command'); + $command_line = check_command_definition('host_perfdata_file_processing_command'); + } check_process_perfdata_pl($cfg{'perfdata_file_run_cmd'}); } if($mode eq "npcdmod"){ my $val; + my $npcdmod_npcd_cfg; info("========== Checking npcdmod Mode Config ============",4); @@ -342,14 +478,24 @@ if($mode eq "npcdmod"){ info_and_exit("event_broker_option bits 2 and/or 3 not enabled",2); } - check_config_var('broker_module', 'exists', 'break'); - $val = get_config_var('broker_module'); - # extract npcd.cfg patch from broker_module definition - my $npcdmod_npcd_cfg; - $val =~ /npcdmod\.o\s+config_file=(.*)$/; - if($1){ - $npcdmod_npcd_cfg=$1; + if($val){ + check_config_var('broker_module', 'exists', 'break'); + + # extract npcd.cfg patch from broker_module definition + $npcdmod_npcd_cfg = $1 if ($val =~ /npcdmod\.o\s+config_file=(.*)$/i); + }else{ + if(defined($modules{npcdmod})){ + info("module definition 'npcdmod'",0); + info("module: $modules{npcdmod}->{path}",0) if defined($modules{npcdmod}->{path}); + if($modules{npcdmod}->{args} =~ /config_file=(.*)$/){ + $npcdmod_npcd_cfg = $1; + } + }else{ + info_and_exit("definition for (broker_)module 'npcdmod' missing",2); + } + } + if($npcdmod_npcd_cfg){ info("npcdmod.o config file is $npcdmod_npcd_cfg",0); if( -r $npcdmod_npcd_cfg){ info("$npcdmod_npcd_cfg used by npcdmod.o is readable",0); @@ -386,8 +532,10 @@ if($mode eq "npcdmod"){ } info("========== Starting global checks ============",4); -check_config_var('status_file', 'exists', 'break'); -process_status_file(); +if($product ne "icinga2"){ + check_config_var('status_file', 'exists', 'break'); + process_status_file(); +} info("==== Starting rrdtool checks ====",4); check_rrdtool(); @@ -395,24 +543,84 @@ info("==== Starting directory checks ====",4); check_config_var('RRDPATH', 'exists', 'break'); check_perfdata_dir(get_config_var('RRDPATH')); -if($process_perf_data_stats{1} == 0){ - info("'process_perf_data 1' is not set for any of your hosts/services",2); -} -if($process_perf_data_stats{'noperf'} > 0){ - info($process_perf_data_stats{'noperf'}." hosts/services are not providing performance data",1); -} -if($process_perf_data_stats{'noperf_but_enabled'} > 0){ - info("'process_perf_data 1' is set for ".$process_perf_data_stats{'noperf_but_enabled'}." hosts/services which are not providing performance data!",1); -} -if($process_perf_data_stats{0} > 0){ - info("'process_perf_data 0' is set for ".$process_perf_data_stats{0}." of your hosts/services",1); -} -if($process_perf_data_stats{1} > 0){ - info("'process_perf_data 1' is set for ".$process_perf_data_stats{1}." of your hosts/services",0); -} +if($product eq "icinga2"){ + my @lines = `icinga2 object list --type host 2>/dev/null`; + if($?){ + $last_check++; + }else{ + for (@lines) { + chomp; + if(/name =/){ + $process_perf_data_stats{'hosts'}++; + next; + } + if(/enable_perfdata =/){ + my ($var,$val) = $_ =~ m|\*\s+(.*?)\s*=\s*["]?(.*)["]?|; + if($val eq "true"){ + $process_perf_data_stats{1}++; + }else{ + $process_perf_data_stats{0}++; + } + next; + } + } + } + @lines = `icinga2 object list --type service 2>/dev/null`; + if($?){ + $last_check++; + }else{ + for (@lines) { + chomp; + if(/name =/){ + $process_perf_data_stats{'services'}++; + next; + } + if(/enable_perfdata =/){ + my ($var,$val) = $_ =~ m|\*\s+(.*?)\s*=\s*["]?(.*)["]?|; + if($val eq "true"){ + $process_perf_data_stats{1}++; + }else{ + $process_perf_data_stats{0}++; + } + next; + } + } + } + if($process_perf_data_stats{1} == 0){ + info("'enable_perfdata = true' is not set for any of your hosts/services",2); + } + if($process_perf_data_stats{'noperf'} > 0){ + info($process_perf_data_stats{'noperf'}." hosts/services are not providing performance data",1); + } + if($process_perf_data_stats{'noperf_but_enabled'} > 0){ + info("'enable_perfdata = true' is set for ".$process_perf_data_stats{'noperf_but_enabled'}." hosts/services which are not providing performance data!",1); + } + if($process_perf_data_stats{0} > 0){ + info("'enable_perfdata = false' is set for ".$process_perf_data_stats{0}." of your hosts/services",1); + } + if($process_perf_data_stats{1} > 0){ + info("'enable_perfdata = true' is set for ".$process_perf_data_stats{1}." of your hosts/services",0); + } +}else{ + if($process_perf_data_stats{1} == 0){ + info("'process_perf_data 1' is not set for any of your hosts/services",2); + } + if($process_perf_data_stats{'noperf'} > 0){ + info($process_perf_data_stats{'noperf'}." hosts/services are not providing performance data",1); + } + if($process_perf_data_stats{'noperf_but_enabled'} > 0){ + info("'process_perf_data 1' is set for ".$process_perf_data_stats{'noperf_but_enabled'}." hosts/services which are not providing performance data!",1); + } + if($process_perf_data_stats{0} > 0){ + info("'process_perf_data 0' is set for ".$process_perf_data_stats{0}." of your hosts/services",1); + } + if($process_perf_data_stats{1} > 0){ + info("'process_perf_data 1' is set for ".$process_perf_data_stats{1}." of your hosts/services",0); + } +} if ( get_config_var('LOG_LEVEL') gt 0 ){ - info("Logging is enabled in process_perfdata.cfg. This will reduce the overall performance of PNP4Nagios",1) + info("Logging is enabled in process_perfdata.cfg. This will reduce the overall performance of PNP4Nagios",1); } info("==== System sizing ====",4); @@ -420,6 +628,12 @@ print_sizing(); info("==== Check statistics ====",4); print_stats(); + +if (-e "@datadir@/install.php" && + ! -e "@datadir@/install.ignore" ) { + info("Showing pnp4nagios config on webserver. Do ' mv @datarootdir@/install.ignore.not @datarootdir@/install.ignore ' to show graphs",1); +} + exit; # @@ -484,17 +698,19 @@ sub check_command_definition { } } if($mode eq "bulk"){ - if( $val =~ m/process_perfdata.pl\s+--bulk=/){ + if( $val =~ m/process_perfdata.pl\s+--bulk[=\s]/){ info ( "Command looks good",0 ); }else{ info_and_exit ( "Command looks suspect ($val)",2 ); } } - if($mode eq "bulk+npcd"){ + if($mode eq "npcd"){ my $dump_file = get_config_var( $option =~m/(.*)_processing_command/ ); my $perfdata_spool_dir = get_config_var( 'perfdata_spool_dir'); + my ($file) = $dump_file =~ m|.*(/.+)|; + $file .= '/$TIMET$'; #print "$dump_file\n"; - my $regex = qr/\/bin\/mv\s+$dump_file\s+$perfdata_spool_dir/; + my $regex = qr/\/bin\/mv\s+$dump_file\s+$perfdata_spool_dir($file)?/; if( $val =~ m/$regex/){ info ( "Command looks good",0 ); }else{ @@ -604,6 +820,18 @@ sub print_stats { sub print_sizing { my $object_count = ($process_perf_data_stats{'hosts'} + $process_perf_data_stats{'services'}); my $graph_count = ($process_perf_data_stats{'hosts'} + $process_perf_data_stats{'services'}); + if ($product eq "icinga2"){ + my $count = `icinga2 object list --type host | grep 'Object' | wc -l`; + if ($?){ + $last_check++; + } + $object_count += $count; + $count = `icinga2 object list --type service | grep 'Object' | wc -l`; + if ($?){ + $last_check++; + } + $object_count += $count; + } info("$object_count hosts/service objects defined",0); foreach my $limit ( sort {$a <=> $b} keys %sizing){ if($graph_count >= $limit and $sizing{$limit} eq $mode){ @@ -650,33 +878,81 @@ sub check_rrdtool { sub check_proc_npcd { my $user = shift; - my $out = `ps -u $user -o cmd | grep /npcd | grep -v grep`; - my $rc = $?; - chomp $out; - info("Check process: 'ps -u $user -o cmd | grep /npcd | grep -v grep'", 6); - info("Result: $out", 6); - info("Returncode: $rc", 6); - #extract npcd.cfg - $out =~ /-f\s?(\S+)/; - my $npcd_cfg = $1; - if($rc == 0){ + # may need to get cases based on $opsys, + # but this handles linux and bsd, maybe others + if (!open(PS,"ps -A -o user -o command|")) { + info("error running 'ps -A -o user -o command'",0); + return; + } + my $cfgfile; + + while () { + chomp; + my ($psuser,$pscomm,@psargs) = split(/\s+/); + next unless $psuser eq $user; + next unless $pscomm =~ /\/npcd(\s|$)/; + info("Check process matched: $_",6); + while (my $token = shift(@psargs)) { + if ($token eq '-f') { + $cfgfile=shift(@psargs); + last; + } + } + last if defined $cfgfile; + } + close(PS); + + if(defined($cfgfile)){ info("npcd daemon is running",0); - }else{ + } else { info("npcd daemon is not running",2); info_and_exit("A running npcd daemon is needed to process data.",4); } - return $npcd_cfg; + return $cfgfile; } +# process a nagios config file + +sub process_nagios_file { + my $file = shift; + my $NFILE; + + info("Reading $file", 4); + open ($NFILE, "<$file") || info_and_exit("Failed to open '$file'. $! ", 2); + while (<$NFILE>) { + if (/^\s*cfg_file\s*=(.*)/) { + my $subfile = $1; + $subfile =~ s/#.*$//; + $subfile =~ s/^\s+//; + $subfile =~ s/\s+$//; + process_objects_file($subfile); + } elsif (/^\s*cfg_dir\s*=(.*)/) { + my $subdir = $1; + $subdir =~ s/#.*$//; + $subdir =~ s/^\s+//; + $subdir =~ s/\s+$//; + my $SDIR; + opendir($SDIR,"$subdir") || info_and_exit("failed to open nagios config dir '$subdir'. $!",2); + my $subfile; + while (readdir $SDIR) { + next if /^./; + next unless /\.cfg$/; + process_objects_file("$subdir/$_"); + } + closedir($SDIR); + } else { + process_main_cfg_line(); + } + } + close ($NFILE); +} + + + # process nagios.cfg sub process_nagios_cfg { - info ("Reading $MainCfg", 4); - open (NFILE, "$MainCfg") || info_and_exit("Failed to open '$MainCfg'. $! ", 2); - while () { - process_main_cfg_line(); - } - close (NFILE); -} + process_nagios_file($MainCfg); +} # process process_perfdata.cfg sub process_perfdata_cfg { @@ -748,7 +1024,9 @@ sub process_main_cfg_line { return if (/^$/); return if (/^#/); s/#.*//; + s/;.*$//; s/\s*$//; + s/^\s*//; if (my ($par, $val) = /([^=]+)\s?=\s?(.*)/){ $par = trim($par); $val = trim($val);; @@ -774,6 +1052,7 @@ sub trim { sub process_objects_file { my ($file) = @_; my $cmd = ""; + my $mod = ""; my $line = ""; info ("Reading $file", 4); open (CFILE, "$file") || info_and_exit("Failed to open '$file'. $! ", 2); @@ -781,8 +1060,20 @@ sub process_objects_file { s/#.*//; next if (/^$/); chomp; - if (/command_name/) { - ($cmd) = /command_name\s*(.*)/; + if (/^\s*command_name\s+(.+)/) { + ($cmd) = $1; + next; + } + if (/^\s*module_name\s+(.+)/) { + ($mod) = $1; + next; + } + if (/^\s*path\s+(.+)/) { + $modules{$mod}->{path} = $1; + next; + } + if (/^\s*args\s+(.+)/) { + $modules{$mod}->{args} = $1; next; } next unless ( /command_line/); @@ -849,12 +1140,19 @@ sub process_status_file { if ($perf ne ""){ info ("$perf, ppd=$ppd", 4); } - } + } + if(/^programstatus/) { + $hst = 'internal'; + $srv = ''; + $perfdata_found = 1; + } if(/^hoststatus /){ - $process_perf_data_stats{'hosts'}++; + $process_perf_data_stats{'hosts'}++; + $perfdata_found=0; } if(/^servicestatus /){ - $process_perf_data_stats{'services'}++; + $process_perf_data_stats{'services'}++; + $perfdata_found=0; } } close (CFILE); @@ -927,7 +1225,8 @@ sub check_usrgrp { if ($gid) { my $fgid = (stat("$file"))[5]; my $fgroup = getgrgid($fgid); - info ("$file: group is $fgroup", 2, $break) if ($fgid != $gid); + info ("$file: group is $fgroup", 2, $break) + unless ($fgid == $gid || $fgid == $http_gid); } } @@ -960,6 +1259,9 @@ sub get_product { if ( exists $cfg{$string} ){ return $product; } + if ($MainCfg =~ /$product.[cfg|conf]/) { + return $product; + } } return 0; } @@ -973,7 +1275,7 @@ sub in_array{ sub usage{ print </dev/null 2>&1; then \ + chkconfig --add npcd; \ + elif which update-rc.d >/dev/null 2>&1; then \ + update-rc.d npcd defaults; \ + fi \ + elif [ x$(INIT_TYPE) = xsystemd ]; then \ + if which systemctl >/dev/null 2>&1; then \ + systemctl enable npcd.service ; \ + fi; \ + chmod 0644 $(INIT_DIR)/$(INIT_FILE); \ + elif [ x$(INIT_TYPE) = xupstart ]; then \ + if which initctl >/dev/null 2>&1; then \ + initctl reload-configuration; \ + fi \ + elif [ x$(INIT_TYPE) = xopenrc ]; then \ + if which rc-update >/dev/null 2>&1; then \ + rc-update add npcd default; \ + fi \ + fi -install-plugins: - $(INSTALL) -m 755 $(INSTALL_OPTS) check_pnp_rrds.pl $(DESTDIR)$(LIBEXECDIR) -install-rrdconvert: - $(INSTALL) -m 755 $(INSTALL_OPTS) rrd_convert.pl $(DESTDIR)$(LIBEXECDIR) - -install-rrdmodify: - $(INSTALL) -m 755 $(INSTALL_OPTS) rrd_modify.pl $(DESTDIR)$(LIBEXECDIR) install: - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(PERFDATADIR) + $(INSTALL) -m 2755 $(MIX_OPTS) -d $(DESTDIR)$(PERFDATADIR) $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(LIBEXECDIR) + $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(PERFDATA_SPOOL_DIR) + $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(LOGDIR) $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(LOGDIR)/stats - $(MAKE) install-processperfdata - $(MAKE) install-plugins - $(MAKE) install-rrdconvert - $(MAKE) install-rrdmodify - + $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(LOGDIR)/lock + $(INSTALL) -m 755 $(INIT_OPTS) -d $(DESTDIR)$(INIT_DIR) + $(INSTALL) -m $(INIT_PERM) $(INIT_OPTS) $(SRC_INIT) $(DESTDIR)$(INIT_DIR)/$(INIT_FILE) + $(INSTALL) -m 755 $(INSTALL_OPTS) process_perfdata.pl $(DESTDIR)$(LIBEXECDIR) + $(INSTALL) -m 755 $(INSTALL_OPTS) check_pnp_rrds.pl $(DESTDIR)$(LIBEXECDIR) + $(INSTALL) -m 755 $(INSTALL_OPTS) rrd_convert.pl $(DESTDIR)$(LIBEXECDIR) + $(INSTALL) -m 755 $(INSTALL_OPTS) rrd_modify.pl $(DESTDIR)$(LIBEXECDIR) + diff --git a/scripts/check_pnp_rrds.pl.in b/scripts/check_pnp_rrds.pl.in index 68cb5e7..9b9ec16 100644 --- a/scripts/check_pnp_rrds.pl.in +++ b/scripts/check_pnp_rrds.pl.in @@ -40,11 +40,22 @@ my $opt_w = 1; my $opt_c = 10; my $opt_t = 10; my $opt_p = "@PERFDATA_DIR@"; + +my $nagcfg = "@NAGIOS_CFG@"; +open(NC,"<$nagcfg") || die "unable to read nagios cfg at $nagcfg"; + my $opt_ncmd = "/usr/local/nagios/var/rw/nagios.cmd"; +while () { + next unless /^\s*command_file\s*=\s*(.*)/; + $opt_ncmd = $1; + last; +} +close(NC); + my $opt_phost = ""; my $opt_pservice = ""; my $opt_ignore; -my $VERSION = "@PKG_VERSION@"; +my $VERSION = "@PACKAGE_VERSION@"; my $PROGNAME = basename($0); my $PASV = 0; my $USER = getpwuid($<); @@ -278,7 +289,7 @@ sub print_usage () { } sub print_support { - print "SUPPORT: http://www.pnp4nagios.org/pnp/\n"; + print "SUPPORT: https://github.com/pnp4nagios/pnp4nagios\n"; print "\n\n"; } diff --git a/scripts/config4rpm_path.sh b/scripts/config4rpm_path.sh new file mode 100755 index 0000000..a39fc00 --- /dev/null +++ b/scripts/config4rpm_path.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# WHAT: Configure pnp4nagios to use rpm pkg's path, instead of /usr/local. +# WHY : To test new code locally without going through whole rpm creation/deployment workflow. +# +# Example output: +#*** Configuration summary for pnp4nagios-0.6.27 08-29-2023 *** +# +# General Options: +# ------------------------- ------------------- +# Nagios user/group: nagios nagios +# Install directory: /usr +# HTML Dir: /usr/share/nagios/html/pnp4nagios +# Config Dir: /etc/pnp4nagios +# Location of rrdtool binary: /usr/bin/rrdtool Version 1.7.2 +# RRDs Perl Modules: FOUND (Version 1.7002) +# RRD Files stored in: /var/lib/pnp4nagios +# process_perfdata.pl Logfile: /var/log/pnp4nagios/perfdata.log +# Perfdata files (NPCD) stored in: /var/spool/pnp4nagios +# +# Web Interface Options: +# ------------------------- ------------------- +# HTML URL: http://localhost/pnp4nagios +# Apache Config File: /etc/httpd/conf.d/pnp4nagios.conf +# +# +# Review the options above for accuracy. If they look okay, +# type 'make all' to compile. +# + +_name=pnp4nagios +_exec_prfix=/usr +_bindir=/usr/bin +_sbindir=/usr/sbin +_sysconfdir=/etc +_libexecdir=/usr/libexec +_libdir=/usr/lib64 +_localstatedir=/var +_datadir=/usr/share + +./configure --build=x86_64-redhat-linux-gnu \ + --host=x86_64-redhat-linux-gnu \ + --program-prefix= \ + --prefix=${_exec_prfix} \ + --exec-prefix=${_exec_prfix} \ + --bindir=${_bindir} \ + --sbindir=${_sbindir} \ + --sysconfdir=${_sysconfdir} \ + --datadir=${_datadir} \ + --includedir=/usr/include \ + --libdir=${_libexecdir} \ + --libexecdir=${_libexecdir} \ + --localstatedir=${_localstatedir} \ + --sharedstatedir=/var/lib \ + --mandir=/usr/share/man \ + --infodir=/usr/share/info \ + --libexecdir=/usr/libexec/${_name} \ + --sysconfdir=/etc/${_name} \ + --localstatedir=${_localstatedir}/log/${_name} \ + --datadir=${_datadir}/nagios/html/${_name} \ + --datarootdir=${_datadir}/nagios/html/${_name} \ + --with-perfdata-dir=${_localstatedir}/lib/${_name} \ + --with-perfdata-spool-dir=${_localstatedir}/spool/${_name} diff --git a/scripts/newbsd.npcd.in b/scripts/newbsd.npcd.in new file mode 100644 index 0000000..739a909 --- /dev/null +++ b/scripts/newbsd.npcd.in @@ -0,0 +1,32 @@ +#!/bin/sh +# +# $NetBSD: npcd.sh,v 1.6 2008/06/20 15:28:11 gdt Exp $ +# +# PROVIDE: npcd +# REQUIRE: DAEMON + +. /etc/rc.subr + +name="@npcd_name@" +command="@bindir@/${name}" +piddir="@piddir@" +pidfile="${piddir}/${name}.pid" +config="@pkgsysconfdir@/${name}.cfg" +@npcd_name@_user=@nagios_user@ +@npcd_name@_group=@nagios_grp@ + +command_args="-d -f $config" +required_files=$config + +start_precmd="npcd_precmd" + + +npcd_precmd() +{ + mkdir -p ${piddir} + chown @nagios_user@:@nagios_grp@ ${piddir} +} + + +load_rc_config $name +run_rc_command "$1" diff --git a/scripts/npcd.openrc.in b/scripts/npcd.openrc.in new file mode 100644 index 0000000..adf3f49 --- /dev/null +++ b/scripts/npcd.openrc.in @@ -0,0 +1,61 @@ +#!/sbin/openrc-run + +# These two facilitate the bindir variable substitution below. +prefix=@prefix@ +exec_prefix=@exec_prefix@ + +# This is a custom variable, and has the following default value if a +# specific config file is not defined by the user. +: ${NPCD_CONFIG:="@pkgsysconfdir@/npcd.cfg"} +: ${NAGIOS_CFG:="@NAGIOS_CFG@"} + +# The rest are OpenRC variables. +extra_commands="checkconfig" +extra_started_commands="reload" + +command="@bindir@/npcd" +command_args="-f ${NPCD_CONFIG}" +pidfile="@piddir@/npcd.pid" +verify="@pkgsysconfdir@/verify_pnp_config" + +depend(){ + use logger + after nagios +} + +reload(){ + checkconfig || return $? + ebegin "Reloading configuration" + start-stop-daemon --signal KILL --pidfile "${pidfile}" + eend $? +} + +checkconfig(){ + ebegin "Verifying config files" + + # Save the output in case verification fails and errors are printed. + OUTPUT=$( ${verify} -m bulk+npcd -p "${NPCD_CONFIG}" -c "${NAGIOS_CFG}") + + # Save the exit code from the verification so that `echo` doesn't + # clobber it. Then, if verification failed, show its + # output. Otherwise, succeed quietly. + local exit_code=$? + [ $exit_code -ne 0 ] && echo "${OUTPUT}" >&2 + eend $exit_code +} + +start_pre() { + # Without this, the "start" action will appear to succeed even if + # the config file contains errors, and the daemon fails to start. + # Another approach would be to wait for the PID file to appear, but + # this is fast enough and feels cleaner. + checkconfig || return $? +} + +stop_pre() { + # If this is a restart, check to make sure the user's config + # isn't busted before we stop the running daemon. + if [ "${RC_CMD}" = "restart" ] ; then + checkconfig || return $? + fi +} diff --git a/scripts/npcd.service.in b/scripts/npcd.service.in new file mode 100644 index 0000000..e725b19 --- /dev/null +++ b/scripts/npcd.service.in @@ -0,0 +1,16 @@ +[Unit] +Description=npcd rrd processor for pnp4nagios +Documentation=https://github.com/pnp4nagios/docs +After=network.target local-fs.target + +[Service] +Type=exec +User=@nagios_user@ +Group=@nagios_grp@ +PIDFile=@piddir@/npcd.pid +Environment="CONFIG_FILE=@pkgsysconfdir@/npcd.cfg" +ExecStart=@bindir@/npcd -f ${CONFIG_FILE} +#ExecStop=/bin/kill -s QUIT $MAINPID + +[Install] +WantedBy=@NAGIOS_UNIT@.service diff --git a/scripts/npcd.upstart.in b/scripts/npcd.upstart.in new file mode 100644 index 0000000..700f782 --- /dev/null +++ b/scripts/npcd.upstart.in @@ -0,0 +1,21 @@ +# pnp4nagios NPCD daemon for graphing Nagios data + +description "pnp4nagios npcd daemon" +author "C. Lane lane@dchooz.org" + +oom score never + +start on (local-filesystems and net-device-up IFACE!=lo) +stop on runlevel [!2345] + +reload signal SIGHUP + +expect fork +respawn + +pre-start script + + @pkgsysconfdir@/verify_pnp_config -m bulk+npcd -p @pkgsysconfdir@/npcd.cfg -c @NAGIOS_CFG@ +end script + +exec @bindir@/npcd -f @pkgsysconfdir@/npcd.cfg diff --git a/scripts/pnp_gearman_worker.service.in b/scripts/pnp_gearman_worker.service.in new file mode 100644 index 0000000..404e865 --- /dev/null +++ b/scripts/pnp_gearman_worker.service.in @@ -0,0 +1,16 @@ +[Unit] +Description=gearman rrd processor for pnp4nagios +Documentation=https://github.com/pnp4nagios/docs +After=network.target local-fs.target + +[Service] +Type=exec +User=@nagios_user@ +Group=@nagios_grp@ +PIDFile=@piddir@/gearman_worker.pid +Environment="CONFIG_FILE=@pkgsysconfdir@/process_perfdata.cfg" +ExecStart="@libexecdir@/process_perfdata.pl --config=${CONFIG_FILE} --gearman --pidfile=@piddir@/gearman_worker.pid" +ExecStop=/bin/kill -s QUIT "$MAINPID" + +[Install] +WantedBy=nagios.service diff --git a/scripts/process_perfdata.pl.in b/scripts/process_perfdata.pl.in index 2703c71..ee6f31c 100644 --- a/scripts/process_perfdata.pl.in +++ b/scripts/process_perfdata.pl.in @@ -1,6 +1,6 @@ #!@PERL@ # nagios: -epn -## @PKG_NAME@–@PKG_VERSION@ +## @PACKAGE_NAME@–@PACKAGE_VERSION@ ## Copyright (c) 2005-2015 Joerg Linge (http://www.pnp4nagios.org) ## ## This program is free software; you can redistribute it and/or @@ -27,39 +27,45 @@ if( $< == 0 ){ use warnings; use strict; use POSIX; +use Fcntl; use Getopt::Long; -use Time::HiRes qw(gettimeofday tv_interval); -use vars qw ( $TEMPLATE %NAGIOS $t0 $t1 $rt $delayed_write $rrdfile @ds_create $count $line $name $ds_update $dstype %CTPL); +use Time::HiRes qw(gettimeofday tv_interval usleep); +use vars qw ( $TEMPLATE %NAGIOS $t0 $t1 $delayed_write $rrdfile @ds_create $count $line $name $ds_update $dstype %CTPL %conf); -my %conf = ( +%conf = ( TIMEOUT => 15, - CFG_DIR => "@sysconfdir@/", + CFG_DIR => "@pkgsysconfdir@/", USE_RRDs => 1, RRDPATH => "@PERFDATA_DIR@", RRDTOOL => "@RRDTOOL@", RRD_STORAGE_TYPE => "SINGLE", RRD_HEARTBEAT => 8640, RRA_STEP => 60, - RRA_CFG => "@sysconfdir@/rra.cfg", - STATS_DIR => "@localstatedir@/stats", + RRA_CFG => "@pkgsysconfdir@/rra.cfg", + STATS_DIR => "@PNP_LOGDIR@/stats", + LOCKDIR => "@PNP_LOGDIR@/lock/", LOG_FILE => "@PERFDATA_LOG@", LOG_FILE_MAX_SIZE => "10485760", #Truncate after 10MB - LOG_LEVEL => @DEBUG@, + LOG_LEVEL => @DEBUG_LEVEL@, + MAXLOCK => 30*60, # kill older locks XML_ENC => "UTF-8", XML_UPDATE_DELAY => 0, # Write XML only if file is older then XML_UPDATE_DELAY seconds RRD_DAEMON_OPTS => "", - GEARMAN_HOST => "localhost:4730", # How many gearman worker childs to start - PREFORK => 2, # How many gearman worker childs to start + GEARMAN_HOST => "localhost:4730", # How many gearman worker childs to start + PREFORK => 2, # How many gearman worker childs to start REQUESTS_PER_CHILD => 20000, # Restart after a given count of requests ENCRYPTION => 1, # Decrypt mod_gearman packets KEY => 'should_be_changed', - KEY_FILE => '@sysconfdir@/secret.key', + KEY_FILE => '@pkgsysconfdir@/secret.key', UOM2TYPE => { 'c' => 'DERIVE', 'd' => 'DERIVE' }, + IGNORE_HOST_PATTERN => '', + IGNORE_SERVICE_PATTERN => '', + IGNORE_LABEL_PATTERN => '', ); my %const = ( XML_STRUCTURE_VERSION => "@XML_STRUCTURE_VERSION@", - VERSION => "@PKG_VERSION@", + VERSION => "@PACKAGE_VERSION@", ); # @@ -114,7 +120,7 @@ if ( $conf{USE_RRDs} == 1 ) { } # -# Include Gearman modules if needed +# Include Gearman modules if needed # if ( defined($opt_gm) ) { unless ( eval "use Gearman::Worker;1" ) { @@ -137,9 +143,9 @@ print_version() if ($opt_V); # Use the timeout specified on the command line and if none use what is in the configuration # If timeout is not in command line or the config file use the default $opt_t = $conf{TIMEOUT} if ( $opt_t == $opt_t_default && $opt_t != $conf{TIMEOUT} ); -print_log( "Default Timeout: $opt_t_default secs.", 2 ); -print_log( "Config Timeout: $conf{TIMEOUT} secs.", 2 ); -print_log( "Actual Timeout: $opt_t secs.", 2 ); +print_log( "INFO: Default Timeout: $opt_t_default secs.", 2 ); +print_log( "INFO: Config Timeout: $conf{TIMEOUT} secs.", 2 ); +print_log( "INFO: Actual Timeout: $opt_t secs.", 2 ); init_signals(); my %children = (); # keys are current child process IDs @@ -160,7 +166,7 @@ if( ! defined($opt_gm) ){ if($conf{ENCRYPTION} == 1){ print_log( "Encryptions is enabled", 0 ); read_keyfile($conf{'KEY_FILE'}); - # fill key up to 32 bytes + # fill key up to 32 bytes $conf{'KEY'} = substr($conf{'KEY'},0,32) . chr(0) x ( 32 - length( $conf{'KEY'} ) ); $cypher = Crypt::Rijndael->new( $conf{'KEY'}, Crypt::Rijndael::MODE_ECB() ); } @@ -173,8 +179,7 @@ if( ! defined($opt_gm) ){ # Main function to switch to the right mode. sub main { my $job = shift; - my $t0 = [gettimeofday]; - my $t1; + $t0 = [gettimeofday]; my $rt; my $lines = 0; # Gearman Worker @@ -182,8 +187,7 @@ sub main { print_log( "Gearman Worker Job start", 1 ); %NAGIOS = parse_env($job->arg); $lines = process_perfdata(); - $t1 = [gettimeofday]; - $rt = tv_interval $t0, $t1; + $rt = tv_interval($t0, [gettimeofday]); $stats{runtime} += $rt; $stats{rows}++; if( ( int $stats{timet} / 60 ) < ( int time / 60 )){ @@ -209,16 +213,16 @@ sub main { $lines = process_perfdata_stdin(); } else { # Synchronous mode - $opt_t = 5 if $opt_t > 5; # maximum timeout + $opt_t = 5 if $opt_t > 5; # maximum timeout alarm($opt_t); print_log( "process_perfdata.pl-$const{VERSION} starting in SYNC Mode", 1 ); %NAGIOS = parse_env(); $lines = process_perfdata(); } - $rt = tv_interval $t0, $t1; + $rt = tv_interval($t0, [gettimeofday]); $stats{runtime} = $rt; $stats{rows} = $lines; - store_internals(); + store_internals() if $lines > 0; print_log( "PNP exiting (runtime ${rt}s) ...", 1 ); exit 0; } @@ -257,7 +261,7 @@ sub parse_env { if ( ( !$ENV{NAGIOS_HOSTNAME} ) and ( !$ENV{ICINGA_HOSTNAME} ) ) { print_log( "Cant find Nagios Environment. Exiting ....", 1 ); - exit 2; + exit 22; } foreach my $key ( sort keys %ENV ) { if ( $key =~ /^(NAGIOS|ICINGA)_(.*)/ ) { @@ -296,6 +300,7 @@ sub process_perfdata { $stats{skipped}++; return 1; } + if ( ! defined($NAGIOS{PERFDATA}) && ! defined($opt_gm) ) { print_log( "No Performance Data for $NAGIOS{HOSTNAME} / $NAGIOS{SERVICEDESC} ", 1 ); if ( !$opt_b && !$opt_s ) { @@ -304,6 +309,20 @@ sub process_perfdata { } } + # Check if we want to ignore the host + my $pattern = $conf{IGNORE_HOST_PATTERN}; + if ( $pattern ne '' && $NAGIOS{HOSTNAME} =~ /$pattern/) { + print_log( "Ignoring host due to a pattern: $NAGIOS{HOSTNAME}", 1 ); + next; + } + + # Check if we want to ignore the service + $pattern = $conf{IGNORE_SERVICE_PATTERN}; + if ( $pattern ne '' && $NAGIOS{SERVICEDESC} =~ /$pattern/) { + print_log( "Ignoring service due to a pattern: $NAGIOS{SERVICEDESC}", 1 ); + next; + } + if ( $NAGIOS{PERFDATA} =~ /^(.*)\s\[(.*)\]$/ ) { $NAGIOS{PERFDATA} = $1; $NAGIOS{CHECK_COMMAND} = $2; @@ -329,50 +348,71 @@ sub process_perfdata_file { if ( $opt_b =~ /-PID-(\d+)/ ) { print_log( "Oops: $opt_b already processed by $1 - please check timeout settings", 0 ); } + # no file? + if (! -e "$opt_b") { + print_log( "ERROR: File $opt_b not found", 1 ); + return 0; + } + + GetLock('file1.lock',10,0.2); + + # empty file? + my $n = (stat($opt_b))[7]; + if (!defined($n) || $n == 0) { + print_log("empty file $opt_b",2); + if ($opt_b !~ /\-perfdata$/) { + my $iss = unlink $opt_b; + print_log("deleting $opt_b, OK=$iss",3); + } + ReleaseLock('file1.lock'); + return 0; + } print_log( "searching for $opt_b", 2 ); - if ( -e "$opt_b" ) { - my $pdfile = "$opt_b" . "-PID-" . $$; - print_log( "renaming $opt_b to $pdfile for bulk update", 2 ); - unless ( rename "$opt_b", "$pdfile" ) { - print_log( "ERROR: rename $opt_b to $pdfile failed", 1 ); - exit 4; - } - - print_log( "reading $pdfile for bulk update", 2 ); - open( PDFILE, "< $pdfile" ); - my $count = 0; - while () { - my $job_data = $_; - $count++; - print_log( "Processing Line $count", 2 ); - my @LINE = split(/\t/); - %NAGIOS = (); # cleaning %NAGIOS Hash - #foreach my $k (@LINE) { - # $k =~ /([A-Z 0-9_]+)::(.*)$/; - # $ENV{ 'NAGIOS_' . $1 } = $2 if ($2); - #} - parse_env($job_data); - if ( $NAGIOS{SERVICEPERFDATA} || $NAGIOS{HOSTPERFDATA} ) { - process_perfdata(); - } else { - print_log( "No Perfdata. Skipping line $count", 2 ); - $stats{skipped}++; - } - } - - print_log( "$count lines processed", 1 ); - - if ( unlink("$pdfile") == 1 ) { - print_log( "$pdfile deleted", 1 ); - }else { - print_log( "Could not delete $pdfile:$!", 1 ); - } - return $count; + my $pdfile = "$opt_b" . "-PID-" . $$; + print_log( "renaming $opt_b to $pdfile for bulk update", 2 ); + unless ( rename "$opt_b", "$pdfile" ) { + print_log( "ERROR: rename $opt_b to $pdfile failed", 1 ); + ReleaseLock('file1.lock'); + exit 4; } - else { - print_log( "ERROR: File $opt_b not found", 1 ); + ReleaseLock('file1.lock'); + # make a new empty file for Nagios to fill + if ($opt_b =~ /\-perfdata$/) { + my $tmpfh; + print_log("create new, empty $opt_b file",3); + if (!sysopen($tmpfh, $opt_b,O_WRONLY|O_CREAT|O_EXCL,0644)) { + print_log("failed to make new $opt_b",1); + } + close($tmpfh); } + + print_log( "reading $pdfile for bulk update", 2 ); + open( PDFILE, "< $pdfile" ); + my $count = 0; + while () { + my $job_data = $_; + $count++; + print_log( "Processing Line $count", 2 ); + my @LINE = split(/\t/); + %NAGIOS = (); # cleaning %NAGIOS Hash + parse_env($job_data); + if ( $NAGIOS{SERVICEPERFDATA} || $NAGIOS{HOSTPERFDATA} ) { + process_perfdata(); + } else { + print_log( "No Perfdata. Skipping line $count", 2 ); + $stats{skipped}++; + } + } + + print_log( "$count lines processed", 1 ); + + if ( unlink("$pdfile") == 1 ) { + print_log( "$pdfile deleted", 1 ); + }else { + print_log( "Could not delete $pdfile:$!", 1 ); + } + return $count; } # @@ -473,7 +513,7 @@ sub data2rrd { $DS = 1; # PNP 0.4.x Template compatibility $NAGIOS{RRDFILE} = ""; - + # $rrd_storage_type = "MULTIPLE"; $rrdfile = $conf{RRDPATH} . "/" . $data[$i]{hostname} . "/" . $data[$i]{servicedesc} . "_" . $data[$i]{name} . ".rrd"; @@ -630,7 +670,7 @@ sub open_template { my $xmlfile = shift; $delayed_write = 0; if( -e $xmlfile ){ - my $mtime = (stat($xmlfile))[9]; + my $mtime = (stat(_))[9]; my $t = time(); my $age = ($t - $mtime); if ( $age < $conf{'XML_UPDATE_DELAY'} ){ @@ -704,7 +744,7 @@ sub write_env_to_template { } # -# Recursive Template search +# Recursive Template search # sub adjust_template { my $command = shift; @@ -719,14 +759,14 @@ sub adjust_template { COMMAND => $command, TEMPLATE => $template, DSTYPE => $dstype, - RRD_STORAGE_TYPE => $conf{'RRD_STORAGE_TYPE'}, + RRD_STORAGE_TYPE => $conf{'RRD_STORAGE_TYPE'}, RRD_HEARTBEAT => $conf{'RRD_HEARTBEAT'}, USE_MIN_ON_CREATE => 0, USE_MAX_ON_CREATE => 0, ); read_custom_template ( ); - # + # if ( $CTPL{'TEMPLATE'} ne $initial_template ){ read_custom_template ( ); } @@ -751,7 +791,7 @@ sub read_custom_template { $dstype = $conf{'UOM2TYPE'}{$uom}; print_log( "DEBUG: DSTYPE adjusted to $dstype by UOM", 3 ); }else { - $dstype = 'GAUGE'; + $dstype = 'GAUGE'; } print_log( "DEBUG: RAW Command -> $command", 3 ); @@ -937,7 +977,7 @@ sub _parse { "min" => $6, "max" => $7 ); - + $p{label} =~ s/[&"']//g; # cleanup $p{name} =~ s/["']//g; # cleanup $p{name} =~ s/[\/\\]/_/g; # cleanup @@ -996,7 +1036,7 @@ sub cleanup { } # -# Urlencode +# Urlencode # sub urlencode { my $string = shift; @@ -1173,6 +1213,14 @@ sub parse_perfstring { @perfs = (); last; } + + # Check if we want to ignore the perfdata by label + my $ignore_pattern = $conf{IGNORE_LABEL_PATTERN}; + if ( $ignore_pattern ne '' && $p{label} =~ /$ignore_pattern/) { + print_log( "Ignoring perfdata label due to a pattern: $p{label}", 1 ); + next; + } + %CTPL = adjust_template( $NAGIOS{CHECK_COMMAND}, $p{uom}, $count ); if ( $CTPL{'USE_MAX_ON_CREATE'} == 1 && defined $p{max} ) { @@ -1259,24 +1307,29 @@ sub handle_signal { # if ( defined ( $opt_gm ) ){ if($signal eq "CHLD" && defined($opt_gm) ){ - my $pid = waitpid(-1, &WNOHANG); - if($pid == -1){ - print_log( "### no hanging child ###", 1 ); - } elsif ( WIFEXITED($?)) { - print_log( "### child $pid exited ###", 1 ); - $children--; - } else { - print_log( "### wrong signal ###", 1 ); - $children--; + while(my $pid = waitpid(-1, &WNOHANG)) { + if($pid == -1){ + print_log( "### no hanging child ###", 1 ); + last; + } elsif ( WIFEXITED($?)) { + print_log( "### child $pid exited ###", 1 ); + delete $children{$pid}; + $children--; + } else { + print_log( "### wrong signal ###", 1 ); + delete $children{$pid}; + $children--; + } + $SIG{'CHLD'} = \&handle_signal; } - $SIG{'CHLD'} = \&handle_signal; + return; } if($signal eq "INT" || $signal eq "TERM"){ local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children kill $signal => keys %children; print_log( "*** process_perfdata.pl terminated on signal $signal", 0 ); pidlock("remove"); - exit; # clean up with dignity + exit 11; # clean up with dignity } print_log( "*** process_perfdata.pl received signal $signal (ignored)", 0 ); }else{ @@ -1292,11 +1345,13 @@ sub handle_signal { } if ($opt_b && !$opt_s ) { my $pdfile = "$opt_b" . "-PID-" . $$; - if ( unlink("$pdfile") == 1 ) { - print_log( "*** TIMEOUT: $pdfile deleted", 0 ); - } - else { - print_log( "*** TIMEOUT: Could not delete $pdfile:$!", 0 ); + if ( -f $pdfile) { + if ( unlink("$pdfile") == 1 ) { + print_log( "*** TIMEOUT: $pdfile deleted", 0 ); + } + else { + print_log( "*** TIMEOUT: Could not delete $pdfile:$!", 0 ); + } } } my $temp_file = "$conf{RRDPATH}/$NAGIOS{HOSTNAME}/$NAGIOS{SERVICEDESC}.xml.$$"; @@ -1304,7 +1359,7 @@ sub handle_signal { unlink($temp_file); } $t1 = [gettimeofday]; - $rt = tv_interval $t0, $t1; + my $rt = tv_interval $t0, $t1; $stats{runtime} = $rt; print_log( "*** Timeout while processing Host: \"$NAGIOS{HOSTNAME}\" Service: \"$NAGIOS{SERVICEDESC}\"", 0 ); print_log( "*** process_perfdata.pl terminated on signal $signal", 0 ); @@ -1329,7 +1384,8 @@ sub init_stats { # # Store some internal runtime infos -# +# adding locking, since host/service perfdata jobs conflict on this +# sub store_internals { if( ! -w $conf{'STATS_DIR'}){ print_log("*** ERROR: ".$conf{'STATS_DIR'}." is not writable or does not exist",0); @@ -1337,7 +1393,7 @@ sub store_internals { } my $statsfile = $conf{'STATS_DIR'}."/".(int $stats{timet} / 60); open( STAT, ">> $statsfile" ) or die "Cant create statistic file ", $!; - printf(STAT "%d %f %d %d %d %d %d %d\n", $stats{timet},$stats{runtime},$stats{rows},$stats{update},$stats{create},$stats{error},$stats{invalid},$stats{skipped}); + printf(STAT "%d %f %d %d %d %d %d %d\n", $stats{timet},$stats{runtime},$stats{rows},$stats{update},$stats{create},$stats{error},$stats{invalid},$stats{skipped}); close(STAT); check_internals(); } @@ -1348,28 +1404,47 @@ sub store_internals { sub check_internals { my $file; my @files; + + if (!GetLock('stats',20,0.25)) { + print_log("ERROR: failed to get stats file lock, bailing",0); + return; + } + opendir(STATS, $conf{'STATS_DIR'}); while ( defined ( my $file = readdir STATS) ){ next if $file =~ /^\.\.?$/; # skip . and .. - next if $file =~ /-PID-/; # skip temporary files - next if $file == (int $stats{timet} / 60); # skip our current file + next if $file =~ /-PID-/; # skip temporary files + next if $file =~ /^\d+$/ && $file == (int $stats{timet} / 60); # skip our current file push @files, $file; } - read_internals(@files); + read_internals(@files); # releases lock after rename } # -# Read and aggregate files found by check_internals() +# Read and aggregate files found by check_internals() # sub read_internals { my @files = @_; my @chunks; + my @nfiles; foreach my $file (sort { $a <=> $b} @files){ - unless ( rename($conf{'STATS_DIR'}."/".$file, $conf{'STATS_DIR'}."/".$file."-PID-".$$) ){ - print_log( "ERROR: renaming stats file " . $conf{'STATS_DIR'}."/".$file . " to " . $conf{'STATS_DIR'}."/".$file."-PID-".$$ . " failed", 1 ); + my $curfile = $conf{'STATS_DIR'}."/".$file; + my $newfile = $conf{'STATS_DIR'}."/".$file."-PID-".$$; + unless ( -e $curfile) { + print_log("ERROR: stats file $curfile not found",1); + next; + } + unless ( rename($curfile, $newfile) ){ + print_log( "ERROR: renaming stats file $curfile to $newfile failed", 1 ); next; } - open( STAT, "< ".$conf{'STATS_DIR'}."/".$file."-PID-".$$ ); + push(@nfiles,$newfile); + } + ReleaseLock('stats'); + + foreach my $newfile (@nfiles) { + print_log("DEBUG: processing stats file $newfile",3); + open( STAT, "< $newfile" ); %stats = ( timet => 0, error => 0, @@ -1381,10 +1456,11 @@ sub read_internals { update => 0, ); while(){ + #print_log("DEBUG: stat info: $_",3); @chunks = split(); $stats{timet} = $chunks[0]; $stats{runtime} += $chunks[1]; - $stats{rows} += $chunks[2]; + $stats{rows} += $chunks[2]; $stats{update} += $chunks[3]; $stats{create} += $chunks[4]; $stats{error} += $chunks[5]; @@ -1392,25 +1468,25 @@ sub read_internals { $stats{skipped} += $chunks[7]; } close(STAT); - unlink($conf{'STATS_DIR'}."/".$file."-PID-".$$); + unlink($newfile); process_internals(); } } # -# +# # sub process_internals { my $last_rrd_dtorage_type = $conf{'RRD_STORAGE_TYPE'}; $conf{'RRD_STORAGE_TYPE'} = "MULTIPLE"; - %NAGIOS = ( + %NAGIOS = ( HOSTNAME => '.pnp-internal', DISP_HOSTNAME => 'pnp-internal', SERVICEDESC => 'runtime', DISP_SERVICEDESC => 'runtime', - TIMET => $stats{timet}, + TIMET => 'N', #$stats{timet}, DATATYPE => 'SERVICEPERFDATA', CHECK_COMMAND => 'pnp-runtime', - PERFDATA => "runtime=".$stats{runtime}."s rows=".$stats{rows}." errors=".$stats{error}." invalid=".$stats{invalid}." skipped=".$stats{skipped} ." update=".$stats{update}. " create=".$stats{create} + PERFDATA => "runtime=".$stats{runtime}."s rows=".$stats{rows}." errors=".$stats{error}." invalid=".$stats{invalid}." skipped=".$stats{skipped} ." update=".$stats{update}. " create=".$stats{create} ); parse_perfstring( $NAGIOS{PERFDATA} ); $conf{'RRD_STORAGE_TYPE'} = $last_rrd_dtorage_type; @@ -1427,7 +1503,7 @@ sub daemonize { open STDOUT, '>>/dev/null' or die "Can't write to /dev/null: $!"; open STDERR, '>>/dev/null' or die "Can't write to /dev/null: $!"; defined( my $pid = fork ) or die "Can't fork: $!"; - exit if $pid; + exit 12 if $pid; pidlock("create"); setsid or die "Can't start a new session: $!"; } else { @@ -1459,9 +1535,9 @@ sub new_child { $sigset = POSIX::SigSet->new(SIGINT); sigprocmask(SIG_BLOCK, $sigset) or die "Can't block SIGINT for fork: $!\n"; - + die "fork: $!" unless defined ($pid = fork); - + if ($pid) { # Parent records the child's birth and returns. sigprocmask(SIG_UNBLOCK, $sigset) @@ -1472,18 +1548,24 @@ sub new_child { } else { # Child can *not* return from this subroutine. $SIG{INT} = 'DEFAULT'; # make SIGINT kill us as it did before - + + # empty children list so we won't kill siblings if one children dies + %children = (); + + # do not delete pidfile if child exits + undef $opt_pidfile; + # unblock signals sigprocmask(SIG_UNBLOCK, $sigset) or die "Can't unblock SIGINT for fork: $!\n"; - + my $worker = Gearman::Worker->new(); - my @job_servers = split(/,/, $conf{'GEARMAN_HOST'}); # allow multiple gearman job servers + my @job_servers = split(/,/, $conf{'GEARMAN_HOST'}); # allow multiple gearman job servers $worker->job_servers(@job_servers); - $worker->register_function("perfdata", 2, sub { return main(@_); }); - my %opt = ( - on_complete => sub { $req++; }, - stop_if => sub { if ( $req > $conf{'REQUESTS_PER_CHILD'} ) { return 1;}; } + $worker->register_function("perfdata", undef, sub { return main(@_); }); + my %opt = ( + on_complete => sub { $req++; }, + stop_if => sub { if ( $req > $conf{'REQUESTS_PER_CHILD'} ) { return 1;}; } ); print_log("connecting to gearmand '".$conf{'GEARMAN_HOST'}."'",0); $worker->work( %opt ); @@ -1491,7 +1573,7 @@ sub new_child { # this exit is VERY important, otherwise the child will become # a producer of more and more children, forking yourself into # process death. - exit; + exit 13; } } # @@ -1583,14 +1665,14 @@ sub print_help { Hint the program, that it was invoked by NPCD -c, --config Optional process_perfdata config file - Default: @sysconfdir@/process_perfdata.cfg + Default: @pkgsysconfdir@/process_perfdata.cfg Gearman Worker Options: - --gearman + --gearman Start in Gearman worker mode --daemon Run as daemon - --pidfile=/var/run/process_perfdata.pid + --pidfile=/run/nagios/process_perfdata.pid The pidfile used while running in as Gearman worker daemon EOD @@ -1606,3 +1688,60 @@ sub print_version { exit 0; } +# GetLock(file,ntries,WaitBetweenTries_usec) +# wait is in seconds if < 10 +sub GetLock +{ + my $lockfile = shift; + $lockfile = 'ppd.lock' unless defined $lockfile; + my $dlockfile = $conf{LOCKDIR}.$lockfile; + my $tries = shift; + $tries = 10 unless defined $tries; + $tries = 10 if $tries < 1; + my $wait = shift; + $wait = $wait * 1000000 if defined($wait) && $wait < 10; + $wait = 1000000 unless defined $wait; + + my $FH; + my $madewhen; + while ($tries > 0) { + if (sysopen($FH,$dlockfile,O_WRONLY|O_CREAT|O_EXCL)) { + my $t = time(); + print $FH "$t\n"; + close($FH); + print_log("DEBUG: PID $$ got lock on $lockfile at $t",3); + return 1; + } + if (open($FH,"<$dlockfile")) { + while (<$FH>) { + chomp; + next if /^\s*$/; + $madewhen = $_ unless defined $madewhen; + } + close($FH); + next unless defined $madewhen; + my $dt = time() - $madewhen; + if ($dt > $conf{MAXLOCK}) { + print_log("DEBUG: old lock file $lockfile deleted",3); + unlink $dlockfile; + next; + } + } + $tries--; + print_log("DEBUG: PID $$ did not get lock on $lockfile, $tries remain",3); + usleep($wait); + } + print_log("WARN: PID $$ failed to get lock on $lockfile",1); + return 0; +} + +sub ReleaseLock +{ + my $lockfile = shift; + $lockfile = 'ppd.lock' unless defined $lockfile; + my $dlockfile = $conf{LOCKDIR}.$lockfile; + + my $iss = unlink $dlockfile; + print_log("DEBUG: PID $$ release lock on $lockfile, OK=$iss",3); +} + diff --git a/scripts/rc.npcd.in b/scripts/rc.npcd.in index 8e65073..6a52ef3 100644 --- a/scripts/rc.npcd.in +++ b/scripts/rc.npcd.in @@ -6,7 +6,7 @@ # Required-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 -# Short-Description: @PKG_NAME@ NPCD Daemon Version @PKG_VERSION@ +# Short-Description: @PACKAGE_NAME@ NPCD Daemon Version @PACKAGE_VERSION@ # Description: Nagios Performance Data C Daemon ### END INIT INFO @@ -16,12 +16,10 @@ # servicename=@npcd_name@ -prefix=@prefix@ -exec_prefix=${prefix} NpcdBin=@bindir@/@npcd_name@ -NpcdCfgFile=@sysconfdir@/npcd.cfg +NpcdCfgFile=@pkgsysconfdir@/npcd.cfg NpcdVarDir=@localstatedir@ -NpcdRunFile=/var/run/npcd.pid +NpcdRunFile=@piddir@/npcd.pid NpcdLockDir=/var/lock/subsys NpcdLockFile=@npcd_name@ NpcdUser=@nagios_user@ diff --git a/scripts/rc.pnp_gearman_worker.in b/scripts/rc.pnp_gearman_worker.in index b2325ba..6e0227a 100644 --- a/scripts/rc.pnp_gearman_worker.in +++ b/scripts/rc.pnp_gearman_worker.in @@ -12,9 +12,9 @@ ### END INIT INFO DAEMON="@libexecdir@/process_perfdata.pl" -CFG="@sysconfdir@/process_perfdata.cfg" +CFG="@pkgsysconfdir@/process_perfdata.cfg" NAME=pnp_gearman_worker -PIDFILE=@localstatedir@/${NAME}.pid +PIDFILE=@piddir@/${NAME}.pid LOCKFILE=/var/lock/subsys/${NAME} USER=@nagios_user@ USERID=`id -u` diff --git a/scripts/rrd_convert.pl.in b/scripts/rrd_convert.pl.in index 5eb0112..8de92a3 100644 --- a/scripts/rrd_convert.pl.in +++ b/scripts/rrd_convert.pl.in @@ -1,5 +1,5 @@ #!@PERL@ -## @PKG_NAME@–@PKG_VERSION@ rrd_convert.pl +## @PACKAGE_NAME@–@PACKAGE_VERSION@ rrd_convert.pl ## Copyright (c) 2006-2015 Joerg Linge (http://www.pnp4nagios.org) ## ## This program is free software; you can redistribute it and/or @@ -35,7 +35,7 @@ if( $< == 0 ){ # my %conf = ( - CFG_DIR => "@sysconfdir@/", + CFG_DIR => "@pkgsysconfdir@/", RRDPATH => "@PERFDATA_DIR@", RRDTOOL => "@RRDTOOL@", LOG_LEVEL => 0, @@ -567,7 +567,7 @@ sub write_custom_template { my $config_file = $conf{'CFG_DIR'}."/check_commands/".$command.".cfg"; my $storage_type = "MULTIPLE"; open(CFG, ">", $config_file); - print CFG "# Generated by rrd_convert.pl @PKG_VERSION@\n"; + print CFG "# Generated by rrd_convert.pl @PACKAGE_VERSION@\n"; print CFG "RRD_STORAGE_TYPE = MULTIPLE\n"; close(CFG); if ( -s $config_file ) { @@ -595,7 +595,7 @@ sub print_help{ print " [ --read= ]\n"; print "\n"; print "This script is used to switch to RRD_STORAGE_TYPE = MULTIPLE for all RRDs/a given Nagios Check Command/single RRDs \n"; - print "More info online http://docs.pnp4nagios.org/pnp-0.6/rrd_convert\n"; + print "More info online https://github.com/pnp4nagios/docs/blob/main/pages/pnp-0.6/rrd_convert.txt\n"; exit; } @@ -608,6 +608,6 @@ sub print_help_opt_p{ } sub print_version{ - print "Version @PKG_VERSION@\n"; + print "Version @PACKAGE_VERSION@\n"; exit; } diff --git a/scripts/rrd_modify.pl.in b/scripts/rrd_modify.pl.in index 125af69..6afd884 100644 --- a/scripts/rrd_modify.pl.in +++ b/scripts/rrd_modify.pl.in @@ -1,6 +1,6 @@ #!@PERL@ -w # nagios: -epn -## @PKG_NAME@–@PKG_VERSION@ +## @PACKAGE_NAME@–@PACKAGE_VERSION@ # # Copyright (c) 2006-2015 PNP4Nagios Developer Team (http://www.pnp4nagios.org) # @@ -23,7 +23,7 @@ # columns to an RRD file, so if this one doesn't fit your needs please have # a look there. # Please report any errors nevertheless. -# See http://docs.pnp4nagios.org/pnp-0.6/about#support for details. +# See https://github.com/pnp4nagios/pnp4nagios/issues for use strict; use warnings; diff --git a/share/.gitignore b/share/.gitignore new file mode 100644 index 0000000..bcc65b3 --- /dev/null +++ b/share/.gitignore @@ -0,0 +1,3 @@ +Makefile +pnp/index.php +pnp/install.php diff --git a/share/Makefile.in b/share/Makefile.in index 637cf28..2d98dc2 100644 --- a/share/Makefile.in +++ b/share/Makefile.in @@ -1,13 +1,15 @@ prefix=@prefix@ exec_prefix=@exec_prefix@ -LOGDIR=@localstatedir@ -CFGDIR=@sysconfdir@ +LOGDIR=@PNP_LOGDIR@ +CFGDIR=@pkgsysconfdir@ BINDIR=@bindir@ CGIDIR=@sbindir@ INSTALL=@INSTALL@ INSTALL_OPTS=@INSTALL_OPTS@ +HTTP_INSTALL_OPTS=@HTTP_INSTALL_OPTS@ DATAROOTDIR=@datarootdir@ + CP=@CP@ all html: @@ -22,7 +24,7 @@ distclean: clean devclean: distclean install: - $(INSTALL) -m 777 $(INSTALL_OPTS) -d $(DESTDIR)$(LOGDIR)/kohana + $(INSTALL) -m 755 $(HTTP_INSTALL_OPTS) -d $(DESTDIR)$(LOGDIR)/kohana $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR) $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/documents $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/documents/_media @@ -30,6 +32,7 @@ install: $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/documents/images/smileys $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/documents/en_US $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/documents/de_DE + $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/documents/templates $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/application $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/application/lib $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/application/cache @@ -62,6 +65,9 @@ install: for file in pnp/documents/de_DE/*; \ do $(INSTALL) -m 644 $(INSTALL_OPTS) $$file $(DESTDIR)$(DATAROOTDIR)/documents/de_DE; done + for file in pnp/documents/templates/*; \ + do $(INSTALL) -m 644 $(INSTALL_OPTS) $$file $(DESTDIR)$(DATAROOTDIR)/documents/templates; done + for file in pnp/application/models/*.php; \ do $(INSTALL) -m 644 $(INSTALL_OPTS) $$file $(DESTDIR)$(DATAROOTDIR)/application/models; done @@ -86,9 +92,6 @@ install: for file in pnp/application/helpers/*.php; \ do $(INSTALL) -m 644 $(INSTALL_OPTS) $$file $(DESTDIR)$(DATAROOTDIR)/application/helpers; done - for file in pnp/application/lib/*.php; \ - do $(INSTALL) -m 644 $(INSTALL_OPTS) $$file $(DESTDIR)$(DATAROOTDIR)/application/lib; done - for file in pnp/application/i18n/de_DE/*.php; \ do $(INSTALL) -m 644 $(INSTALL_OPTS) $$file $(DESTDIR)$(DATAROOTDIR)/application/i18n/de_DE; done @@ -169,4 +172,6 @@ install: $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(DATAROOTDIR)/templates $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/index.php $(DESTDIR)$(DATAROOTDIR) $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/install.php $(DESTDIR)$(DATAROOTDIR) + $(INSTALL) -m 644 $(INSTALL_OPTS) pnp/install.ignore.not $(DESTDIR)$(DATAROOTDIR) + diff --git a/share/pnp/application/config/config.php b/share/pnp/application/config/config.php index ad86085..c4fdf65 100644 --- a/share/pnp/application/config/config.php +++ b/share/pnp/application/config/config.php @@ -1,58 +1,74 @@ -auto_render = FALSE; + $this->auto_render = false; } - public function index(){ - url::redirect("start", 302); + public function index() + { + url::redirect("start", 302); } - public function search() { + public function search() + { $query = pnp::clean($this->input->get('term')); $result = array(); - if(strlen($query)>=1) { + if (strlen($query) >= 1) { $hosts = $this->data->getHosts(); - foreach($hosts as $host){ - if(preg_match("/$query/i",$host['name'])){ - array_push($result,$host['name']); + foreach ($hosts as $host) { + if (preg_match("/$query/i", $host['name'])) { + array_push($result, $host['name']); } } echo json_encode($result); } } - public function remove($what){ - if($what == 'timerange'){ + public function remove($what) + { + if ($what == 'timerange') { $this->session->delete('start'); $this->session->delete('end'); $this->session->set('timerange-reset', 1); } } - - public function filter($what){ - if($what == 'set-sfilter'){ - $this->session->set('sfilter', $_POST['sfilter']); - }elseif($what == 'set-spfilter'){ - $this->session->set('spfilter', $_POST['spfilter']); - }elseif($what == 'set-pfilter'){ - $this->session->set('pfilter', $_POST['pfilter']); + + public function filter($what) + { + $received_token = $_POST['csrf_token']; + $token = Security::token(); + + if (!Security::check($received_token, $token)) { + echo "CSRF Token invalid"; + return false; + } + + if ($what == 'set-sfilter') { + $this->session->set('sfilter', htmlspecialchars($_POST['sfilter'])); + } elseif ($what == 'set-spfilter') { + $this->session->set('spfilter', htmlspecialchars($_POST['spfilter'])); + } elseif ($what == 'set-pfilter') { + $this->session->set('pfilter', htmlspecialchars($_POST['pfilter'])); } } - public function basket($action=FALSE){ + public function basket($action = false) + { // Disable auto-rendering - $this->auto_render = FALSE; + $this->auto_render = false; $host = false; $service = false; $basket = array(); - if($action == "list"){ + if ($action == "list") { $basket = $this->session->get("basket"); - if(is_array($basket) && sizeof($basket) > 0){ - foreach($basket as $item){ - printf("
  • %s
  • \n", + if (is_array($basket) && (!empty($basket))) { + foreach ($basket as $item) { + printf( + "
  • %s
  • \n", "basket_action_remove", $item, $item, Kohana::lang('common.basket-remove', $item), url::base(), pnp::shorten($item) - ); + ); } } - }elseif($action == "add"){ - $item = $_POST['item']; + } elseif ($action == "add") { + $received_token = $_POST['csrf_token']; + $token = Security::token(); + + if (!Security::check($received_token, $token)) { + echo "CSRF Token invalid"; + return false; + } + + $item = htmlspecialchars($_POST['item']); $basket = $this->session->get("basket"); - if(!is_array($basket)){ + if (!is_array($basket)) { + $basket = []; $basket[] = "$item"; - }else{ - if(!in_array($item,$basket)){ + } else { + if (!in_array($item, $basket)) { $basket[] = $item; } } $this->session->set("basket", $basket); - foreach($basket as $item){ - printf("
  • %s
  • \n", - "basket_action_remove", - $item, - $item, - Kohana::lang('common.basket-remove', $item), - url::base(), - pnp::shorten($item) - ); + foreach ($basket as $item) { + printf( + "
  • %s
  • \n", + "basket_action_remove", + $item, + $item, + Kohana::lang('common.basket-remove', $item), + url::base(), + pnp::shorten($item) + ); } - }elseif($action == "sort"){ - $items = $_POST['items']; + } elseif ($action == "sort") { + $received_token = $_POST['csrf_token']; + $token = Security::token(); + + if (!Security::check($received_token, $token)) { + echo "CSRF Token invalid"; + return false; + } + + $item = htmlspecialchars($_POST['item']); $basket = explode(',', $items); array_pop($basket); $this->session->set("basket", $basket); - foreach($basket as $item){ - printf("
  • %s
  • \n", - "basket_action_remove", - $item, - $item, - Kohana::lang('common.basket-remove', $item), - url::base(), - pnp::shorten($item) - ); + foreach ($basket as $item) { + printf( + "
  • %s
  • \n", + "basket_action_remove", + $item, + $item, + Kohana::lang('common.basket-remove', $item), + url::base(), + pnp::shorten($item) + ); } - }elseif($action == "remove"){ + } elseif ($action == "remove") { + $received_token = $_POST['csrf_token']; + $token = Security::token(); + + if (!Security::check($received_token, $token)) { + echo "CSRF Token invalid"; + return false; + } + $basket = $this->session->get("basket"); - $item_to_remove = $_POST['item']; + $item_to_remove = htmlspecialchars($_POST['item']); $new_basket = array(); - foreach($basket as $item){ - if($item == $item_to_remove){ + foreach ($basket as $item) { + if ($item == $item_to_remove) { continue; } $new_basket[] = $item; } $basket = $new_basket; $this->session->set("basket", $basket); - foreach($basket as $item){ - printf("
  • %s
  • \n", - "basket_action_remove", - $item, - $item, - Kohana::lang('common.basket-remove', $item), - url::base(), - pnp::shorten($item) - ); + foreach ($basket as $item) { + printf( + "
  • %s
  • \n", + "basket_action_remove", + $item, + $item, + Kohana::lang('common.basket-remove', $item), + url::base(), + pnp::shorten($item) + ); } - }elseif($action == "clear"){ + } elseif ($action == "clear") { $this->session->delete("basket"); - }else{ + } else { echo "Action $action not known"; } $basket = $this->session->get("basket"); - if(is_array($basket) && sizeof($basket) == 0){ + if (is_array($basket) && empty($basket)) { echo Kohana::lang('common.basket-empty'); - }else{ + } else { echo "
    \n"; - echo "\n"; - echo "\n"; + echo "\n"; + echo "\n"; echo "
    \n"; } } - } diff --git a/share/pnp/application/controllers/color.php b/share/pnp/application/controllers/color.php index b75ce00..323f860 100644 --- a/share/pnp/application/controllers/color.php +++ b/share/pnp/application/controllers/color.php @@ -1,26 +1,36 @@ -template = $this->add_view('template'); $this->template->color = $this->add_view('color'); - $this->template->color->color_box = $this->add_view('color_box'); + $this->template->color->color_box = $this->add_view('color_box'); $this->template->color->logo_box = $this->add_view('logo_box'); } public function index() { $this->scheme = $this->config->scheme; - } } diff --git a/share/pnp/application/controllers/debug.php b/share/pnp/application/controllers/debug.php index b67354e..88af981 100644 --- a/share/pnp/application/controllers/debug.php +++ b/share/pnp/application/controllers/debug.php @@ -1,14 +1,20 @@ -data->getTimeRange($this->start,$this->end,$this->view); + $this->data->getTimeRange($this->start, $this->end, $this->view); - if(isset($this->host) && isset($this->service)){ - $this->url = "?host=".$this->host."&srv=".$this->service; - if($this->start){ - $this->url .= "&start=".$this->start; + if (isset($this->host) && isset($this->service)) { + $this->url = "?host=" . $this->host . "&srv=" . $this->service; + if ($this->start) { + $this->url .= "&start=" . $this->start; $this->session->set("start", $this->start); } - if($this->end){ - $this->url .= "&end=".$this->end; + if ($this->end) { + $this->url .= "&end=" . $this->end; $this->session->set("end", $this->end); } $services = $this->data->getServices($this->host); - $this->data->buildDataStruct($this->host,$this->service,$this->view); - $this->is_authorized = $this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']); - $this->title = "Service Details ". $this->host ." -> " . $this->data->MACRO['DISP_SERVICEDESC']; - }elseif(isset($this->host)){ + $this->data->buildDataStruct($this->host, $this->service, $this->view); + $this->is_authorized = $this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']); + $this->title = "Service Details " . $this->host . " -> " . $this->data->MACRO['DISP_SERVICEDESC']; + } elseif (isset($this->host)) { $this->is_authorized = $this->auth->is_authorized($this->host); - if($this->view == ""){ + if ($this->view == "") { $this->view = $this->config->conf['overview-range']; } - if($this->start){ - $this->url .= "&start=".$this->start; + if ($this->start) { + $this->url .= "&start=" . $this->start; $this->session->set("start", $this->start); } - if($this->end){ - $this->url .= "&end=".$this->end; + if ($this->end) { + $this->url .= "&end=" . $this->end; $this->session->set("end", $this->end); } $this->title = "Start $this->host"; $services = $this->data->getServices($this->host); $this->title = "Service Overview for $this->host"; - foreach($services as $service){ - if($service['state'] == 'active') - $this->data->buildDataStruct($this->host,$service['name'],$this->view); + foreach ($services as $service) { + if ($service['state'] == 'active') { + $this->data->buildDataStruct($this->host, $service['name'], $this->view); + } } - }else{ - if(isset($this->host)){ + } else { + if (isset($this->host)) { url::redirect("/graph"); - }else{ + } else { throw new Kohana_Exception('error.get-first-host'); - } + } } } } diff --git a/share/pnp/application/controllers/docs.php b/share/pnp/application/controllers/docs.php index 004b8b7..1e692ea 100644 --- a/share/pnp/application/controllers/docs.php +++ b/share/pnp/application/controllers/docs.php @@ -1,65 +1,91 @@ -template = $this->add_view('template'); - $this->template->docs = $this->add_view('docs'); - $this->template->docs->search_box = $this->add_view('search_box'); - $this->template->docs->docs_box = $this->add_view('docs_box'); - $this->template->docs->logo_box = $this->add_view('logo_box'); - $this->doc_language = $this->config->conf['doc_language']; + $this->template = $this->add_view('template'); + $this->template->docs = $this->add_view('docs'); + $this->template->docs->search_box = $this->add_view('search_box'); + $this->template->docs->docs_box = $this->add_view('docs_box'); + $this->template->docs->logo_box = $this->add_view('logo_box'); + $this->doc_language = $this->config->conf['doc_language']; } + //end __construct() - public function index(){ - url::redirect("docs/view/"); + + public function index() + { + url::redirect('docs/view/'); } + //end index() - public function view($lang=FALSE, $page=FALSE){ - if($lang == FALSE){ - if(!in_array($this->config->conf['lang'],$this->doc_language) ){ + + public function view($lang = false, $page = false) + { + if ($lang == false) { + if (!in_array($this->config->conf['lang'], $this->doc_language)) { $this->lang = $this->doc_language[0]; - }else{ - $this->lang = $this->config->conf['lang'] ; + } else { + $this->lang = $this->config->conf['lang']; } - }else{ - if(in_array($lang,$this->doc_language) ){ + } else { + if (in_array($lang, $this->doc_language)) { $this->lang = $lang; - }else{ + } else { $this->lang = $this->doc_language[0]; - url::redirect("docs/view/"); + url::redirect('docs/view/'); } } - - if($page == FALSE){ - url::redirect("docs/view/".$this->lang."/start"); + + if ($page == false) { + url::redirect('docs/view/' . $this->lang . '/start'); } $this->page = $page; - $file = sprintf("documents/%s/%s.html", $this->lang, $this->page); - $file_toc = sprintf("documents/%s/start.html", $this->lang); - if(!file_exists($file)){ - url::redirect("docs/view/start"); + $file = sprintf('documents/%s/%s.html', $this->lang, $this->page); + $file_toc = sprintf('documents/%s/start.html', $this->lang); + if (!file_exists($file)) { + url::redirect('docs/view/start'); } $this->content = file_get_contents($file); - $toc = file( $file_toc ); - $this->toc = ""; - $in = FALSE; - foreach($toc as $t){ - if(preg_match("/SECTION/", $t) ){ + $toc = file($file_toc); + $this->toc = ''; + $in = false; + foreach ($toc as $t) { + if (preg_match('/SECTION/', $t)) { $in = ! $in; continue; } - if($in == TRUE){ - $this->toc .= $t; + if ($in == true) { + $this->toc .= $t; } } # @@ -67,14 +93,16 @@ class Docs_Controller extends System_Controller { # $this->toc = str_replace("/de/pnp-0.6/", "", $this->toc); $this->toc = str_replace("/pnp-0.6/", "", $this->toc); - $this->toc = preg_replace("/

    .*<\/h2>/", "" , $this->toc); - $this->content = str_replace("/templates/", "http://docs.pnp4nagios.org/templates/", $this->content); + $this->toc = preg_replace("/

    .*<\/h2>/", "", $this->toc); + $this->content = str_replace("/templates/", url::base() . "documents/templates/", $this->content); $this->content = str_replace("/de/pnp-0.6/", "", $this->content); $this->content = str_replace("/pnp-0.6/", "", $this->content); - $this->content = str_replace("/_media", url::base()."documents/_media", $this->content); + $this->content = str_replace("/_media", url::base() . "documents/_media", $this->content); $this->content = str_replace("gallery", "", $this->content); - $this->content = str_replace("/_detail", url::base()."documents/_media", $this->content); - $this->content = str_replace("/lib/images", url::base()."documents/images", $this->content); + $this->content = str_replace("/_detail", url::base() . "documents/_media", $this->content); + $this->content = str_replace("/lib/images", url::base() . "documents/images", $this->content); $this->graph_width = ($this->config->conf['graph_width'] + 140); } + //end view() } +//end class diff --git a/share/pnp/application/controllers/graph.php b/share/pnp/application/controllers/graph.php index de24a08..4fa62ca 100644 --- a/share/pnp/application/controllers/graph.php +++ b/share/pnp/application/controllers/graph.php @@ -1,129 +1,148 @@ -template = $this->add_view('template'); - if (isset($this->version) && $this->version == "tiny" ) - $this->template->graph = $this->add_view('graph_tiny'); - else - $this->template->graph = $this->add_view('graph'); - $this->template->zoom_header = $this->add_view('zoom_header'); + $this->template = $this->add_view('template'); + if (isset($this->version) && $this->version == 'tiny') { + $this->template->graph = $this->add_view('graph_tiny'); + } else { + $this->template->graph = $this->add_view('graph'); + } + $this->template->zoom_header = $this->add_view('zoom_header'); $this->template->zoom_header->graph_width = ($this->config->conf['zgraph_width'] + 140); $this->template->zoom_header->graph_height = ($this->config->conf['zgraph_height'] + 230); $this->template->graph->icon_box = $this->add_view('icon_box'); - $this->template->graph->icon_box->position = "graph"; - $this->template->graph->icon_box->xml_icon = TRUE; - $this->template->graph->icon_box->pdf_icon = TRUE; + $this->template->graph->icon_box->position = 'graph'; + $this->template->graph->icon_box->xml_icon = true; + $this->template->graph->icon_box->pdf_icon = true; } + //end __construct() + public function index() { - $this->template->graph->graph_content = $this->add_view('graph_content'); - $this->template->graph->graph_content->graph_width = ($this->config->conf['graph_width'] + 85); + $this->template->graph->graph_content = $this->add_view('graph_content'); + $this->template->graph->graph_content->graph_width = ($this->config->conf['graph_width'] + 85); $this->template->graph->graph_content->timerange_select = $this->add_view('timerange_select'); - $this->template->graph->header = $this->add_view('header'); - $this->template->graph->search_box = $this->add_view('search_box'); - $this->template->graph->service_box = $this->add_view('service_box'); - $this->template->graph->basket_box = $this->add_view('basket_box'); - $this->template->graph->widget_menu = $this->add_view('widget_menu'); - $this->template->graph->graph_content->widget_graph = $this->add_view('widget_graph'); + $this->template->graph->header = $this->add_view('header'); + $this->template->graph->search_box = $this->add_view('search_box'); + $this->template->graph->service_box = $this->add_view('service_box'); + $this->template->graph->basket_box = $this->add_view('basket_box'); + $this->template->graph->widget_menu = $this->add_view('widget_menu'); + $this->template->graph->graph_content->widget_graph = $this->add_view('widget_graph'); // Change the status box while multisite theme is in use - if($this->theme == "multisite"){ - $this->template->graph->status_box = $this->add_view('multisite_box'); + if ($this->theme == 'multisite') { + $this->template->graph->status_box = $this->add_view('multisite_box'); $this->template->graph->status_box->base_url = $this->config->conf['multisite_base_url']; $this->template->graph->status_box->site = $this->config->conf['multisite_site']; - }else{ + } else { $this->template->graph->status_box = $this->add_view('status_box'); } // Service Details - if($this->host != "" && $this->service != ""){ + if ($this->host != '' && $this->service != '') { $this->service = pnp::clean($this->service); $this->host = pnp::clean($this->host); - $this->url = "?host=".urlencode($this->host)."&srv=".urlencode($this->service); + $this->url = '?host=' . urlencode($this->host) . '&srv=' . urlencode($this->service); $services = $this->data->getServices($this->host); - #Landingpage for mobile devices - if($this->isMobileDevice()){ - url::redirect( "mobile/host/".urlencode($this->host)."/".urlencode($this->service) ); + // Landingpage for mobile devices + if ($this->isMobileDevice()) { + url::redirect('mobile/host/' . urlencode($this->host) . '/' . urlencode($this->service)); } - #print Kohana::debug($services); - $this->data->buildDataStruct($this->host,$this->service,$this->view); - $this->is_authorized = $this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']); + // print Kohana::debug($services); + $this->data->buildDataStruct($this->host, $this->service, $this->view); + $this->is_authorized = $this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']); - $this->title = Kohana::lang('common.service-details') . " ". $this->host ." -> " . $this->data->MACRO['DISP_SERVICEDESC']; + $this->title = Kohana::lang('common.service-details') . ' ' . $this->host . ' -> ' . $this->data->MACRO['DISP_SERVICEDESC']; $this->template->graph->graph_content->graph_width = ($this->data->STRUCT[0]['GRAPH_WIDTH'] + 85); // Status Box Vars $this->template->graph->status_box->host = $this->data->MACRO['DISP_HOSTNAME']; $this->template->graph->status_box->lhost = $this->data->MACRO['HOSTNAME']; $this->template->graph->status_box->service = $this->data->MACRO['DISP_SERVICEDESC']; $this->template->graph->status_box->lservice = $this->data->MACRO['SERVICEDESC']; - $this->template->graph->status_box->timet = date($this->config->conf['date_fmt'],intval($this->data->MACRO['TIMET'])); + $this->template->graph->status_box->timet = date($this->config->conf['date_fmt'], intval($this->data->MACRO['TIMET'])); // Service Box Vars $this->template->graph->service_box->services = $services; - $this->template->graph->service_box->host = $this->host; + $this->template->graph->service_box->host = $this->host; // Timerange Box Vars - $this->template->graph->timerange_box = $this->add_view('timerange_box'); + $this->template->graph->timerange_box = $this->add_view('timerange_box'); $this->template->graph->timerange_box->timeranges = $this->data->TIMERANGE; // // Host Overview - }elseif($this->host != ""){ - $this->is_authorized = $this->auth->is_authorized($this->host); - $this->host = pnp::clean($this->host); - #Landingpage for mobile devices - if($this->isMobileDevice()){ - url::redirect( "mobile/host/".urlencode($this->host) ); + } elseif ($this->host != '') { + $this->is_authorized = $this->auth->is_authorized($this->host); + $this->host = pnp::clean($this->host); + // Landingpage for mobile devices + if ($this->isMobileDevice()) { + url::redirect('mobile/host/' . urlencode($this->host)); } - if($this->view == ""){ + if ($this->view == '') { $this->view = $this->config->conf['overview-range']; } - $this->url = "?host=".$this->host; - $this->title = Kohana::lang('common.start'). " ". $this->host; - $services = $this->data->getServices($this->host); + $this->url = '?host=' . $this->host; + $this->title = Kohana::lang('common.start') . ' ' . $this->host; + $services = $this->data->getServices($this->host); // Status Box Vars - $this->template->graph->status_box->host = $this->data->MACRO['DISP_HOSTNAME']; - $this->template->graph->status_box->lhost = $this->data->MACRO['HOSTNAME']; - $this->template->graph->status_box->shost = pnp::shorten($this->data->MACRO['DISP_HOSTNAME']); - $this->template->graph->status_box->timet = date($this->config->conf['date_fmt'],intval($this->data->MACRO['TIMET'])); + $this->template->graph->status_box->host = $this->data->MACRO['DISP_HOSTNAME']; + $this->template->graph->status_box->lhost = $this->data->MACRO['HOSTNAME']; + $this->template->graph->status_box->shost = pnp::shorten($this->data->MACRO['DISP_HOSTNAME']); + $this->template->graph->status_box->timet = date($this->config->conf['date_fmt'], intval($this->data->MACRO['TIMET'])); // Service Box Vars $this->template->graph->service_box->services = $services; - $this->template->graph->service_box->host = $this->host; + $this->template->graph->service_box->host = $this->host; // Timerange Box Vars - $this->template->graph->timerange_box = $this->add_view('timerange_box'); + $this->template->graph->timerange_box = $this->add_view('timerange_box'); $this->template->graph->timerange_box->timeranges = $this->data->TIMERANGE; - $this->template->graph->icon_box->xml_icon = FALSE; + $this->template->graph->icon_box->xml_icon = false; $this->title = Kohana::lang('common.service-overview', $this->host); - foreach($services as $service){ - if($service['state'] == 'active') - $this->data->buildDataStruct($this->host,$service['name'],$this->view); + foreach ($services as $service) { + if ($service['state'] == 'active') { + $this->data->buildDataStruct($this->host, $service['name'], $this->view); + } } - }else{ - #Landingpage for mobile devices - if($this->isMobileDevice()){ - url::redirect("mobile"); - return; + } else { + // Landingpage for mobile devices + if ($this->isMobileDevice()) { + url::redirect('mobile'); + return; } - if($this->isAuthorizedFor('host_overview' ) ){ + if ($this->isAuthorizedFor('host_overview')) { $this->host = $this->data->getFirstHost(); - if(isset($this->host)){ - url::redirect("graph?host=".$this->host); - }else{ + if (isset($this->host)) { + url::redirect('graph?host=' . $this->host); + } else { throw new Kohana_Exception('error.get-first-host'); } - }else{ + } else { throw new Kohana_Exception('error.not_authorized_for_host_overview'); - } + } } + //end if $this->template->graph->logo_box = $this->add_view('logo_box'); $this->template->graph->header->title = $this->title; } + //end index() } +//end class diff --git a/share/pnp/application/controllers/image.php b/share/pnp/application/controllers/image.php index b41ca83..31e9599 100644 --- a/share/pnp/application/controllers/image.php +++ b/share/pnp/application/controllers/image.php @@ -1,4 +1,11 @@ -auto_render = FALSE; - - if($this->input->get('w') != "" ) + $this->auto_render = false; + + if ($this->input->get('w') != "") { $this->rrdtool->config->conf['graph_width'] = intval($this->input->get('w')); - if($this->input->get('graph_width') != "" ) + } + if ($this->input->get('graph_width') != "") { $this->rrdtool->config->conf['graph_width'] = intval($this->input->get('graph_width')); + } - if($this->input->get('h') != "" ) + if ($this->input->get('h') != "") { $this->rrdtool->config->conf['graph_height'] = intval($this->input->get('h')); - if($this->input->get('graph_height') != "" ) + } + if ($this->input->get('graph_height') != "") { $this->rrdtool->config->conf['graph_height'] = intval($this->input->get('graph_height')); + } - if($this->input->get('graph_only') !== null) + if ($this->input->get('graph_only') !== null) { $this->rrdtool->config->conf['graph_only'] = 1; + } - if($this->input->get('no_legend') !== null) + if ($this->input->get('no_legend') !== null) { $this->rrdtool->config->conf['no_legend'] = 1; + } - $this->data->getTimeRange($this->start,$this->end,$this->view); + $this->data->getTimeRange($this->start, $this->end, $this->view); - if($this->tpl != ""){ - $this->data->buildDataStruct('__special',$this->tpl,$this->view,$this->source); + if ($this->tpl != "") { + $this->data->buildDataStruct('__special', $this->tpl, $this->view, $this->source); #print Kohana::debug($this->data->STRUCT); $image = $this->rrdtool->doImage($this->data->STRUCT[0]['RRD_CALL']); $this->rrdtool->streamImage($image); - }elseif(isset($this->host) && isset($this->service)){ - $this->data->buildDataStruct($this->host,$this->service,$this->view,$this->source); - if($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === FALSE) - $this->rrdtool->streamImage("ERROR: NOT_AUTHORIZED"); + } elseif (isset($this->host) && isset($this->service)) { + $this->data->buildDataStruct($this->host, $this->service, $this->view, $this->source); + if ($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === false) { + $this->rrdtool->streamImage("ERROR: NOT_AUTHORIZED"); + } #print Kohana::debug($this->data->STRUCT); - if(sizeof($this->data->STRUCT) > 0){ + if (!empty($this->data->STRUCT)) { $image = $this->rrdtool->doImage($this->data->STRUCT[0]['RRD_CALL']); - }else{ - $image = FALSE; + } else { + $image = false; } - $this->rrdtool->streamImage($image); - }else{ + $this->rrdtool->streamImage($image); + } else { url::redirect("start", 302); } } - - } diff --git a/share/pnp/application/controllers/json.php b/share/pnp/application/controllers/json.php index 306ec93..20a7ad7 100644 --- a/share/pnp/application/controllers/json.php +++ b/share/pnp/application/controllers/json.php @@ -1,4 +1,11 @@ -auto_render = FALSE; + $this->auto_render = false; // Service Details - if($this->host != "" && $this->service != ""){ + if ($this->host != "" && $this->service != "") { $services = $this->data->getServices($this->host); - $this->data->buildDataStruct($this->host,$this->service,$this->view); - if($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === FALSE){ + $this->data->buildDataStruct($this->host, $this->service, $this->view); + if ($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === false) { print json_encode("not authorized"); exit; } $i = 0; $json = array(); - foreach($this->data->STRUCT as $struct){ - $json[$i]['image_url'] = "host=".$struct['MACRO']['HOSTNAME']."&srv=".$struct['MACRO']['SERVICEDESC']."&source=".$struct['SOURCE']."&view=".$struct['VIEW']; + foreach ($this->data->STRUCT as $struct) { + $json[$i]['image_url'] = "host=" . $struct['MACRO']['HOSTNAME'] . + "&srv=" . $struct['MACRO']['SERVICEDESC'] . + "&source=" . $struct['SOURCE'] . "&view=" . + $struct['VIEW']; $json[$i]['ds_name'] = $struct['ds_name']; $json[$i]['start'] = $struct['TIMERANGE']['start']; $json[$i]['end'] = $struct['TIMERANGE']['end']; @@ -36,21 +47,24 @@ class Json_Controller extends System_Controller { } print json_encode($json); // Host Overview - }elseif($this->host != ""){ - if($this->auth->is_authorized($this->host) === FALSE){ + } elseif ($this->host != "") { + if ($this->auth->is_authorized($this->host) === false) { print json_encode("not authorized"); exit; } $services = $this->data->getServices($this->host); - foreach($services as $service){ - if($service['state'] == 'active'){ - $this->data->buildDataStruct($this->host,$service['name'],$this->view); - } + foreach ($services as $service) { + if ($service['state'] == 'active') { + $this->data->buildDataStruct($this->host, $service['name'], $this->view); + } } $i = 0; $json = array(); - foreach($this->data->STRUCT as $struct){ - $json[$i]['image_url'] = "host=".$struct['MACRO']['HOSTNAME']."&srv=".$struct['MACRO']['SERVICEDESC']."&source=".$struct['SOURCE']."&view=".$struct['VIEW']; + foreach ($this->data->STRUCT as $struct) { + $json[$i]['image_url'] = "host=" . $struct['MACRO']['HOSTNAME'] . + "&srv=" . $struct['MACRO']['SERVICEDESC'] . + "&source=" . $struct['SOURCE'] . "&view=" . + $struct['VIEW']; $json[$i]['servicedesc'] = $struct['MACRO']['SERVICEDESC']; $json[$i]['ds_name'] = $struct['ds_name']; $json[$i]['start'] = $struct['TIMERANGE']['start']; @@ -59,12 +73,12 @@ class Json_Controller extends System_Controller { $i++; } print json_encode($json); - }else{ + } else { $this->hosts = $this->data->getHosts(); $i = 0; $json = array(); - foreach($this->hosts as $host){ - if($host['state'] == "active"){ + foreach ($this->hosts as $host) { + if ($host['state'] == "active") { $json[$i]['hostname'] = $host['name']; $i++; } diff --git a/share/pnp/application/controllers/mobile.php b/share/pnp/application/controllers/mobile.php index dace76f..854568b 100644 --- a/share/pnp/application/controllers/mobile.php +++ b/share/pnp/application/controllers/mobile.php @@ -1,4 +1,11 @@ -session->set('classic-ui',0); + $this->session->set('classic-ui', 0); $this->template = $this->add_view('mobile'); } @@ -28,17 +35,17 @@ class Mobile_Controller extends System_Controller { $this->template->overview = $this->add_view('mobile_overview'); $this->template->overview->hosts = $this->data->getHosts(); } - public function host($host=NULL) + public function host($host = null) { $this->template->host = $this->add_view('mobile_host'); $this->is_authorized = $this->auth->is_authorized($host); $this->template->host->hostname = $host; $this->template->host->services = $this->data->getServices($host); } - public function graph($host=NULL, $service=NULL) + public function graph($host = null, $service = null) { $this->template->graph = $this->add_view('mobile_graph'); - $this->data->buildDataStruct($host,$service,$this->view); + $this->data->buildDataStruct($host, $service, $this->view); $this->is_authorized = $this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']); } public function search() @@ -46,48 +53,48 @@ class Mobile_Controller extends System_Controller { $this->template->query = $this->add_view('mobile_search'); $query = pnp::clean($this->input->post('term')); $result = array(); - if(strlen($query)>=1) { + if (strlen($query) >= 1) { $hosts = $this->data->getHosts(); - foreach($hosts as $host){ - if(preg_match("/$query/i",$host['name'])){ - array_push($result,$host['name']); + foreach ($hosts as $host) { + if (preg_match("/$query/i", $host['name'])) { + array_push($result, $host['name']); } } } $this->result = $result; } - public function pages($page=NULL) + public function pages($page = null) { - $this->is_authorized=TRUE; - if($this->view == ""){ + $this->is_authorized = true; + if ($this->view == "") { $this->view = $this->config->conf['overview-range']; } $this->page = $page; - if(is_null($this->page) ){ + if (is_null($this->page)) { $this->template->pages = $this->add_view('mobile_pages'); $this->template->pages->pages = $this->data->getPages(); return; } - $this->data->buildPageStruct($this->page,$this->view); + $this->data->buildPageStruct($this->page, $this->view); $this->template->pages = $this->add_view('mobile_graph'); } - public function special($tpl=NULL) + public function special($tpl = null) { $this->tpl = $tpl; - if(is_null($this->tpl) ){ + if (is_null($this->tpl)) { $this->template->special = $this->add_view('mobile_special'); $this->template->special->templates = $this->data->getSpecialTemplates(); return; } - $this->data->buildDataStruct('__special',$this->tpl,$this->view); + $this->data->buildDataStruct('__special', $this->tpl, $this->view); $this->template->special = $this->add_view('mobile_graph_special'); } - public function go($goto=FALSE) + public function go($goto = false) { - if($goto == 'classic'){ - $this->session->set('classic-ui',1); - url::redirect("graph"); + if ($goto == 'classic') { + $this->session->set('classic-ui', 1); + url::redirect("graph"); } } } diff --git a/share/pnp/application/controllers/page.php b/share/pnp/application/controllers/page.php index 7bd877e..4fde0fd 100644 --- a/share/pnp/application/controllers/page.php +++ b/share/pnp/application/controllers/page.php @@ -1,80 +1,103 @@ -template = $this->add_view('template'); - $this->template->page = $this->add_view('page'); - $this->template->zoom_header = $this->add_view('zoom_header'); - $this->template->zoom_header->graph_width = ($this->config->conf['graph_width'] + 140); - $this->template->zoom_header->graph_height = ($this->config->conf['graph_height'] + 230); - $this->template->page->graph_content = $this->add_view('graph_content'); - $this->template->page->graph_content->graph_width = ($this->config->conf['graph_width'] + 85); + $this->template = $this->add_view('template'); + $this->template->page = $this->add_view('page'); + $this->template->zoom_header = $this->add_view('zoom_header'); + $this->template->zoom_header->graph_width = ($this->config->conf['zgraph_width'] + 140); + $this->template->zoom_header->graph_height = ($this->config->conf['zgraph_height'] + 230); + $this->template->page->graph_content = $this->add_view('graph_content'); + $this->template->page->graph_content->graph_width = ($this->config->conf['graph_width'] + 85); $this->template->page->graph_content->timerange_select = $this->add_view('timerange_select'); - $this->template->page->header = $this->add_view('header'); - $this->template->page->search_box = $this->add_view('search_box'); - $this->template->page->logo_box = $this->add_view('logo_box'); - $this->is_authorized=TRUE; + $this->template->page->header = $this->add_view('header'); + $this->template->page->search_box = $this->add_view('search_box'); + $this->template->page->logo_box = $this->add_view('logo_box'); + $this->is_authorized = true; } + //end __construct() - public function index(){ - if( !$this->isAuthorizedFor('pages') ){ + + public function index() + { + if (!$this->isAuthorizedFor('pages')) { throw new Kohana_Exception('error.auth-pages'); } $this->page = pnp::clean($this->input->get('page')); - if($this->page == ""){ + if ($this->page == '') { $this->page = $this->data->getFirstPage(); } - if($this->page == ""){ + if ($this->page == '') { throw new Kohana_Exception('error.page-config-dir', $this->config->conf['page_dir']); } - if($this->view == ""){ + if ($this->view == '') { $this->view = $this->config->conf['overview-range']; } - $this->data->buildPageStruct($this->page,$this->view); - $this->template->page->header->title = Kohana::lang('common.page',$this->data->PAGE_DEF['page_name']); + $this->data->buildPageStruct($this->page, $this->view); + $this->template->page->header->title = Kohana::lang('common.page', $this->data->PAGE_DEF['page_name']); $this->url = "?page&page=$this->page"; // Timerange Box Vars - $this->template->page->timerange_box = $this->add_view('timerange_box'); + $this->template->page->timerange_box = $this->add_view('timerange_box'); $this->template->page->timerange_box->timeranges = $this->data->TIMERANGE; // Pages Box $this->pages = $this->data->getPages(); - $this->template->page->pages_box = $this->add_view('pages_box'); - $this->template->page->pages_box->pages = $this->pages; + $this->template->page->pages_box = $this->add_view('pages_box'); + $this->template->page->pages_box->pages = $this->pages; // Basket Box - $this->template->page->basket_box = $this->add_view('basket_box'); - // Icon Box + $this->template->page->basket_box = $this->add_view('basket_box'); + // Icon Box $this->template->page->icon_box = $this->add_view('icon_box'); - $this->template->page->icon_box->position = "page"; - + $this->template->page->icon_box->position = 'page'; } + //end index() - public function basket(){ - $basket = $this->session->get("basket"); - if(is_array($basket) && sizeof($basket) > 0){ - $this->data->buildBasketStruct($basket,$this->view); - $this->template->page->basket_box = $this->add_view('basket_box'); - $this->template->page->header->title = Kohana::lang('common.page-basket'); - $this->url = "basket?"; + + public function basket() + { + $basket = $this->session->get('basket'); + if (is_array($basket) && (!empty($basket))) { + $this->data->buildBasketStruct($basket, $this->view); + $this->template->page->basket_box = $this->add_view('basket_box'); + $this->template->page->header->title = Kohana::lang('common.page-basket'); + $this->url = 'basket?'; // Timerange Box Vars - $this->template->page->timerange_box = $this->add_view('timerange_box'); + $this->template->page->timerange_box = $this->add_view('timerange_box'); $this->template->page->timerange_box->timeranges = $this->data->TIMERANGE; // Pages Box $this->pages = $this->data->getPages(); - $this->template->page->pages_box = $this->add_view('pages_box'); - $this->template->page->pages_box->pages = $this->pages; - // Icon Box + $this->template->page->pages_box = $this->add_view('pages_box'); + $this->template->page->pages_box->pages = $this->pages; + // Icon Box $this->template->page->icon_box = $this->add_view('icon_box'); - $this->template->page->icon_box->position = "basket"; - }else{ - url::redirect("start", 302); + $this->template->page->icon_box->position = 'basket'; + } else { + url::redirect('start', 302); } } + //end basket() } +//end class diff --git a/share/pnp/application/controllers/pdf.php b/share/pnp/application/controllers/pdf.php index 15f2ab4..5fb8b7f 100644 --- a/share/pnp/application/controllers/pdf.php +++ b/share/pnp/application/controllers/pdf.php @@ -1,4 +1,13 @@ -use_bg = 0; @@ -18,52 +36,53 @@ class Pdf_Controller extends System_Controller { $this->pdf_margin_top = $this->config->conf['pdf_margin_top']; $this->pdf_margin_right = $this->config->conf['pdf_margin_right']; - // Define PDF background per url option - if(isset($this->bg) && $this->bg != ""){ - if( is_readable( Kohana::config( 'core.pnp_etc_path')."/".$this->bg ) ){ - $this->bg = Kohana::config('core.pnp_etc_path')."/".$this->bg; - }else{ + // Define PDF background per url option + if (isset($this->bg) && $this->bg != "") { + if (is_readable(Kohana::config('core.pnp_etc_path') . "/" . $this->bg)) { + $this->bg = Kohana::config('core.pnp_etc_path') . "/" . $this->bg; + } else { $this->bg = $this->config->conf['background_pdf']; } } // Use PDF background if readable - if(is_readable($this->bg)){ + if (is_readable($this->bg)) { $this->use_bg = 1; } - } - public function index(){ + public function index() + { $this->tpl = pnp::clean($this->input->get('tpl')); $this->type = "normal"; - $this->data->getTimeRange($this->start,$this->end,$this->view); + $this->data->getTimeRange($this->start, $this->end, $this->view); // Service Details - if($this->host != "" && $this->service != ""){ - $this->data->buildDataStruct($this->host,$this->service,$this->view); + if ($this->host != "" && $this->service != "") { + $this->data->buildDataStruct($this->host, $this->service, $this->view); // Host Overview - }elseif($this->host != ""){ - if($this->view == ""){ + } elseif ($this->host != "") { + if ($this->view == "") { $this->view = $this->config->conf['overview-range']; } $services = $this->data->getServices($this->host); - foreach($services as $service){ - if($service['state'] == 'active') - $this->data->buildDataStruct($this->host,$service['name'],$this->view); + foreach ($services as $service) { + if ($service['state'] == 'active') { + $this->data->buildDataStruct($this->host, $service['name'], $this->view); + } } // Special Templates - }elseif($this->tpl != ""){ - $this->data->buildDataStruct('__special',$this->tpl,$this->view); + } elseif ($this->tpl != "") { + $this->data->buildDataStruct('__special', $this->tpl, $this->view); $this->type = 'special'; - }else{ + } else { $this->host = $this->data->getFirstHost(); - if(isset($this->host)){ + if (isset($this->host)) { url::redirect("/graph?host=$this->host"); - }else{ + } else { throw new Kohana_User_Exception('Hostname not set ;-)', "RTFM my Friend, RTFM!"); - } + } } #throw new Kohana_Exception(print_r($this->data->STRUCT,TRUE)); /* @@ -72,53 +91,55 @@ class Pdf_Controller extends System_Controller { $pdf = new PDF("P", "mm", $this->pdf_page_size); $pdf->AliasNbPages(); $pdf->SetAutoPageBreak('off'); - $pdf->SetMargins($this->pdf_margin_left,$this->pdf_margin_top,$this->pdf_margin_right); + $pdf->SetMargins($this->pdf_margin_left, $this->pdf_margin_top, $this->pdf_margin_right); $pdf->AddPage(); - if($this->use_bg){ + if ($this->use_bg) { $pdf->setSourceFile($this->bg); - $tplIdx = $pdf->importPage(1,'/MediaBox'); + $tplIdx = $pdf->importPage(1, '/MediaBox'); $pdf->useTemplate($tplIdx); } $pdf->SetCreator('Created with PNP'); $pdf->SetFont('Arial', '', 10); // Title - $header = TRUE; - foreach($this->data->STRUCT as $key=>$data){ - if($key != 0){ - $header = FALSE; - } + $header = true; + foreach ($this->data->STRUCT as $key => $data) { + if ($key != 0) { + $header = false; + } if ($pdf->GetY() > 200) { $pdf->AddPage(); - if($this->use_bg){$pdf->useTemplate($tplIdx);} - } - if($this->type == 'normal'){ - if($data['LEVEL'] == 0){ - $pdf->SetFont('Arial', '', 12); - $pdf->CELL(120, 10, $data['MACRO']['DISP_HOSTNAME']." -- ".$data['MACRO']['DISP_SERVICEDESC'], 0, 1); - $pdf->SetFont('Arial', '', 10); - $pdf->CELL(120, 5, $data['TIMERANGE']['title']." (".$data['TIMERANGE']['f_start']." - ".$data['TIMERANGE']['f_end'].")", 0, 1); - $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); - }else{ - $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); + if ($this->use_bg) { + $pdf->useTemplate($tplIdx); } - }elseif($this->type == 'special'){ - if($header){ + } + if ($this->type == 'normal') { + if ($data['LEVEL'] == 0) { + $pdf->SetFont('Arial', '', 12); + $pdf->CELL(120, 10, $data['MACRO']['DISP_HOSTNAME'] . " -- " . $data['MACRO']['DISP_SERVICEDESC'], 0, 1); + $pdf->SetFont('Arial', '', 10); + $pdf->CELL(120, 5, $data['TIMERANGE']['title'] . " (" . $data['TIMERANGE']['f_start'] . " - " . $data['TIMERANGE']['f_end'] . ")", 0, 1); + $pdf->SetFont('Arial', '', 8); + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); + } else { + $pdf->SetFont('Arial', '', 8); + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); + } + } elseif ($this->type == 'special') { + if ($header) { $pdf->SetFont('Arial', '', 12); $pdf->CELL(120, 10, $data['MACRO']['TITLE'], 0, 1); $pdf->SetFont('Arial', '', 10); - $pdf->CELL(120, 5, $data['TIMERANGE']['title']." (".$data['TIMERANGE']['f_start']." - ".$data['TIMERANGE']['f_end'].")", 0, 1); + $pdf->CELL(120, 5, $data['TIMERANGE']['title'] . " (" . $data['TIMERANGE']['f_start'] . " - " . $data['TIMERANGE']['f_end'] . ")", 0, 1); $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); - }else{ + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); + } else { $pdf->SetFont('Arial', '', 10); - $pdf->CELL(120, 5, $data['TIMERANGE']['title']." (".$data['TIMERANGE']['f_start']." - ".$data['TIMERANGE']['f_end'].")", 0, 1); + $pdf->CELL(120, 5, $data['TIMERANGE']['title'] . " (" . $data['TIMERANGE']['f_start'] . " - " . $data['TIMERANGE']['f_end'] . ")", 0, 1); $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); } } - $image = $this->rrdtool->doImage($data['RRD_CALL'],$out='PDF'); + $image = $this->rrdtool->doImage($data['RRD_CALL'], $out = 'PDF'); $img = $this->rrdtool->saveImage($image); $Y = $pdf->GetY(); $cell_height = ($img['height'] * 0.23); @@ -127,25 +148,25 @@ class Pdf_Controller extends System_Controller { $pdf->CELL(120, $cell_height, '', 0, 1); unlink($img['file']); } - $pdf->Output("pnp4nagios.pdf","I"); - + $pdf->Output("pnp4nagios.pdf", "I"); } - public function page($page){ + public function page($page) + { $this->start = $this->input->get('start'); $this->end = $this->input->get('end'); $this->view = ""; - if(isset($_GET['view']) && $_GET['view'] != "" ){ + if (isset($_GET['view']) && $_GET['view'] != "") { $this->view = pnp::clean($_GET['view']); } - $this->data->getTimeRange($this->start,$this->end,$this->view); - $this->data->buildPageStruct($page,$this->view); + $this->data->getTimeRange($this->start, $this->end, $this->view); + $this->data->buildPageStruct($page, $this->view); // Define PDF background per url option - if(isset($this->data->PAGE_DEF['background_pdf'])){ - if( is_readable( Kohana::config( 'core.pnp_etc_path')."/".$this->data->PAGE_DEF['background_pdf'] ) ){ - $this->bg = Kohana::config('core.pnp_etc_path')."/".$this->data->PAGE_DEF['background_pdf']; + if (isset($this->data->PAGE_DEF['background_pdf'])) { + if (is_readable(Kohana::config('core.pnp_etc_path') . "/" . $this->data->PAGE_DEF['background_pdf'])) { + $this->bg = Kohana::config('core.pnp_etc_path') . "/" . $this->data->PAGE_DEF['background_pdf']; } } /* @@ -154,34 +175,36 @@ class Pdf_Controller extends System_Controller { $pdf = new PDF("P", "mm", $this->pdf_page_size); $pdf->AliasNbPages(); $pdf->SetAutoPageBreak('off'); - $pdf->SetMargins($this->pdf_margin_left,$this->pdf_margin_top,$this->pdf_margin_right); + $pdf->SetMargins($this->pdf_margin_left, $this->pdf_margin_top, $this->pdf_margin_right); $pdf->AddPage(); - if($this->use_bg){ + if ($this->use_bg) { $pdf->setSourceFile($this->bg); - $tplIdx = $pdf->importPage(1,'/MediaBox'); + $tplIdx = $pdf->importPage(1, '/MediaBox'); $pdf->useTemplate($tplIdx); } $pdf->SetCreator('Created with PNP'); $pdf->SetFont('Arial', '', 10); // Title - foreach($this->data->STRUCT as $data){ + foreach ($this->data->STRUCT as $data) { if ($pdf->GetY() > 200) { $pdf->AddPage(); - if($this->use_bg){$pdf->useTemplate($tplIdx);} + if ($this->use_bg) { + $pdf->useTemplate($tplIdx); + } } - if($data['LEVEL'] == 0){ + if ($data['LEVEL'] == 0) { $pdf->SetFont('Arial', '', 12); - $pdf->CELL(120, 10, $data['MACRO']['DISP_HOSTNAME']." -- ".$data['MACRO']['DISP_SERVICEDESC'], 0, 1); + $pdf->CELL(120, 10, $data['MACRO']['DISP_HOSTNAME'] . " -- " . $data['MACRO']['DISP_SERVICEDESC'], 0, 1); $pdf->SetFont('Arial', '', 10); - $pdf->CELL(120, 5, $data['TIMERANGE']['title']." (".$data['TIMERANGE']['f_start']." - ".$data['TIMERANGE']['f_end'].")", 0, 1); + $pdf->CELL(120, 5, $data['TIMERANGE']['title'] . " (" . $data['TIMERANGE']['f_start'] . " - " . $data['TIMERANGE']['f_end'] . ")", 0, 1); $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); - }else{ + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); + } else { $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); } - $image = $this->rrdtool->doImage($data['RRD_CALL'],$out='PDF'); + $image = $this->rrdtool->doImage($data['RRD_CALL'], $out = 'PDF'); $img = $this->rrdtool->saveImage($image); $Y = $pdf->GetY(); $cell_height = ($img['height'] * 0.23); @@ -190,20 +213,21 @@ class Pdf_Controller extends System_Controller { $pdf->CELL(120, $cell_height, '', 0, 1); unlink($img['file']); } - $pdf->Output("pnp4nagios.pdf","I"); + $pdf->Output("pnp4nagios.pdf", "I"); } - public function basket(){ + public function basket() + { $this->start = $this->input->get('start'); $this->end = $this->input->get('end'); $this->view = ""; - if(isset($_GET['view']) && $_GET['view'] != "" ){ + if (isset($_GET['view']) && $_GET['view'] != "") { $this->view = pnp::clean($_GET['view']); } - $this->data->getTimeRange($this->start,$this->end,$this->view); + $this->data->getTimeRange($this->start, $this->end, $this->view); $basket = $this->session->get("basket"); - if(is_array($basket) && sizeof($basket) > 0){ - $this->data->buildBasketStruct($basket,$this->view); + if (is_array($basket) && (!empty($basket))) { + $this->data->buildBasketStruct($basket, $this->view); } //echo Kohana::debug($this->data->STRUCT); /* @@ -212,34 +236,36 @@ class Pdf_Controller extends System_Controller { $pdf = new PDF("P", "mm", $this->pdf_page_size); $pdf->AliasNbPages(); $pdf->SetAutoPageBreak('off'); - $pdf->SetMargins($this->pdf_margin_left,$this->pdf_margin_top,$this->pdf_margin_right); + $pdf->SetMargins($this->pdf_margin_left, $this->pdf_margin_top, $this->pdf_margin_right); $pdf->AddPage(); - if($this->use_bg){ + if ($this->use_bg) { $pdf->setSourceFile($this->config->conf['background_pdf']); - $tplIdx = $pdf->importPage(1,'/MediaBox'); + $tplIdx = $pdf->importPage(1, '/MediaBox'); $pdf->useTemplate($tplIdx); } $pdf->SetCreator('Created with PNP'); $pdf->SetFont('Arial', '', 10); // Title - foreach($this->data->STRUCT as $data){ + foreach ($this->data->STRUCT as $data) { if ($pdf->GetY() > 200) { $pdf->AddPage(); - if($this->use_bg){$pdf->useTemplate($tplIdx);} + if ($this->use_bg) { + $pdf->useTemplate($tplIdx); + } } - if($data['LEVEL'] == 0){ + if ($data['LEVEL'] == 0) { $pdf->SetFont('Arial', '', 12); - $pdf->CELL(120, 10, $data['MACRO']['DISP_HOSTNAME']." -- ".$data['MACRO']['DISP_SERVICEDESC'], 0, 1); + $pdf->CELL(120, 10, $data['MACRO']['DISP_HOSTNAME'] . " -- " . $data['MACRO']['DISP_SERVICEDESC'], 0, 1); $pdf->SetFont('Arial', '', 10); - $pdf->CELL(120, 5, $data['TIMERANGE']['title']." (".$data['TIMERANGE']['f_start']." - ".$data['TIMERANGE']['f_end'].")", 0, 1); + $pdf->CELL(120, 5, $data['TIMERANGE']['title'] . " (" . $data['TIMERANGE']['f_start'] . " - " . $data['TIMERANGE']['f_end'] . ")", 0, 1); $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); - }else{ + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); + } else { $pdf->SetFont('Arial', '', 8); - $pdf->CELL(120, 5, "Datasource ".$data["ds_name"], 0, 1); + $pdf->CELL(120, 5, "Datasource " . $data["ds_name"], 0, 1); } - $image = $this->rrdtool->doImage($data['RRD_CALL'],$out='PDF'); + $image = $this->rrdtool->doImage($data['RRD_CALL'], $out = 'PDF'); $img = $this->rrdtool->saveImage($image); $Y = $pdf->GetY(); $cell_height = ($img['height'] * 0.23); @@ -248,8 +274,7 @@ class Pdf_Controller extends System_Controller { $pdf->CELL(120, $cell_height, '', 0, 1); unlink($img['file']); } - $pdf->Output("pnp4nagios.pdf","I"); - + $pdf->Output("pnp4nagios.pdf", "I"); } } @@ -258,23 +283,29 @@ class Pdf_Controller extends System_Controller { + * */ +// phpcs:disable PSR1.Files.SideEffects require Kohana::find_file('vendor/fpdf', 'fpdf'); require Kohana::find_file('vendor/fpdf', 'fpdi'); -class PDF extends FPDI { +// phpcs:enable PSR1.Files.SideEffects +// phpcs:disable PSR1.Classes.ClassDeclaration.MultipleClasses + +class PDF extends FPDI +{ //Page header - function Header() { - //Arial bold 10 - $this->SetFont('Arial', 'B', 10); - } + public function Header() + { + //Arial bold 10 + $this->SetFont('Arial', 'B', 10); + } //Page footer - function Footer() { - //Position at 1.5 cm from bottom - $this->SetY(-20); - //Arial italic 8 - $this->SetFont('Arial', 'I', 8); - //Page number - $this->Cell(0, 10, $this->PageNo() . '/{nb}', 0, 0, 'C'); + public function Footer() + { + //Position at 1.5 cm from bottom + $this->SetY(-20); + //Arial italic 8 + $this->SetFont('Arial', 'I', 8); + //Page number + $this->Cell(0, 10, $this->PageNo() . '/{nb}', 0, 0, 'C'); } } - diff --git a/share/pnp/application/controllers/popup.php b/share/pnp/application/controllers/popup.php index 162ca73..7da8202 100644 --- a/share/pnp/application/controllers/popup.php +++ b/share/pnp/application/controllers/popup.php @@ -1,14 +1,19 @@ -view == "" ){ + if ($this->view == "") { $this->view = $this->config->conf['overview-range']; } - $this->imgwidth = pnp::clean($this->input->get('width',$this->config->conf['popup-width'])); + $this->imgwidth = pnp::clean($this->input->get('width', $this->config->conf['popup-width'])); - $this->data->getTimeRange($this->start,$this->end,$this->view); + $this->data->getTimeRange($this->start, $this->end, $this->view); - if(isset($this->host) && isset($this->service)){ - $this->data->buildDataStruct($this->host,$this->service,$this->view,$this->source); + if (isset($this->host) && isset($this->service)) { + $this->data->buildDataStruct($this->host, $this->service, $this->view, $this->source); $this->template->host = $this->host; $this->template->srv = $this->service; $this->template->view = $this->view; @@ -34,7 +39,7 @@ class Popup_Controller extends System_Controller { $this->template->end = $this->end; $this->template->start = $this->start; $this->template->imgwidth = $this->imgwidth; - }else{ + } else { url::redirect("/graph"); } } diff --git a/share/pnp/application/controllers/special.php b/share/pnp/application/controllers/special.php index bc98518..abe6f3b 100644 --- a/share/pnp/application/controllers/special.php +++ b/share/pnp/application/controllers/special.php @@ -1,4 +1,11 @@ -template->graph = $this->add_view('graph'); $this->templates = $this->data->getSpecialTemplates(); $this->data->GRAPH_TYPE = 'special'; - if($this->tpl == ''){ - if($this->templates) + if ($this->tpl == '') { + if ($this->templates) { $this->tpl = $this->templates[0]; - url::redirect('special?tpl='.$this->tpl, 302); + } + url::redirect('special?tpl=' . $this->tpl, 302); } } - public function index(){ - $this->url = "?tpl=".$this->tpl; + public function index() + { + $this->url = "?tpl=" . $this->tpl; $this->template->zoom_header = $this->add_view('zoom_header'); - $this->template->zoom_header->graph_width = ($this->config->conf['graph_width'] + 140); - $this->template->zoom_header->graph_height = ($this->config->conf['graph_height'] + 230); + $this->template->zoom_header->graph_width = ($this->config->conf['zgraph_width'] + 140); + $this->template->zoom_header->graph_height = ($this->config->conf['zgraph_height'] + 230); $this->template->graph->graph_content = $this->add_view('graph_content_special'); $this->template->graph->graph_content->graph_width = ($this->config->conf['graph_width'] + 85); $this->template->graph->graph_content->timerange_select = $this->add_view('timerange_select'); @@ -38,7 +47,7 @@ class Special_Controller extends System_Controller { $this->template->graph->widget_menu = $this->add_view('widget_menu'); $this->template->graph->graph_content->widget_graph = $this->add_view('widget_graph'); #print Kohana::debug($services); - $this->data->buildDataStruct('__special',$this->tpl,$this->view); + $this->data->buildDataStruct('__special', $this->tpl, $this->view); $this->template->graph->icon_box = $this->add_view('icon_box'); $this->template->graph->icon_box->position = "special"; $this->template->graph->logo_box = $this->add_view('logo_box'); @@ -48,5 +57,4 @@ class Special_Controller extends System_Controller { $this->template->graph->header->title = $this->data->MACRO['TITLE']; //print Kohana::debug($this->data); } - } diff --git a/share/pnp/application/controllers/start.php b/share/pnp/application/controllers/start.php index b575655..cf23dc8 100644 --- a/share/pnp/application/controllers/start.php +++ b/share/pnp/application/controllers/start.php @@ -1,13 +1,20 @@ -data = new Data_Model(); - $this->config = new Config_Model(); - $this->rrdtool = new Rrdtool_Model(); - $this->auth = new Auth_Model(); - #$this->system = new System_Model(); + $this->data = new Data_Model(); + $this->config = new Config_Model(); + $this->rrdtool = new Rrdtool_Model(); + $this->auth = new Auth_Model(); + // $this->system = new System_Model(); $this->config->read_config(); - Kohana::config_set('locale.language',$this->config->conf['lang']); + Kohana::config_set('locale.language', $this->config->conf['lang']); // Check for mod_rewrite $this->check_mod_rewrite(); - $this->start = $this->input->get('start',FALSE); - $this->end = $this->input->get('end',FALSE); - $this->theme = pnp::clean($this->input->get('theme',FALSE)); - $this->view = pnp::clean($this->input->get('view', "")); - $this->host = pnp::clean($this->input->get('host',NULL)); - $this->service = pnp::clean($this->input->get('srv',NULL)); - $this->source = pnp::clean($this->input->get('source',NULL)); - $this->version = pnp::clean($this->input->get('version',NULL)); - $this->tpl = pnp::clean($this->input->get('tpl')); - $this->controller = Router::$controller; + $this->start = $this->input->get('start', false); + $this->end = $this->input->get('end', false); + $this->theme = pnp::clean($this->input->get('theme', false)); + $this->view = pnp::clean($this->input->get('view', '')); + $this->host = pnp::clean($this->input->get('host', null)); + $this->service = pnp::clean($this->input->get('srv', null)); + $this->source = pnp::clean($this->input->get('source', null)); + $this->version = pnp::clean($this->input->get('version', null)); + $this->tpl = pnp::clean($this->input->get('tpl')); + $this->controller = Router::$controller; - $this->data->getTimeRange($this->start,$this->end,$this->view); - if(Router::$controller != "image" && Router::$controller != "image_special"){ + $this->data->getTimeRange($this->start, $this->end, $this->view); + if (! in_array(Router::$controller, ['image', 'image_special', 'xport'])) { $this->session = Session::instance(); - # Session withou theme info - if($this->session->get("theme","new") == "new"){ - if($this->theme){ - # store $this->theme if available - Kohana::config_set('core.theme',$this->theme); - $this->session->set('theme', $this->theme ); - }else{ - # set $this->theme to default value - $this->theme = $this->config->conf['ui-theme']; - Kohana::config_set('core.theme',$this->theme); - } - # Sesion with theme info - }else{ - if($this->theme && $this->theme != 'default'){ - # store $this->theme if available - $this->session->set('theme', $this->theme ); - Kohana::config_set('core.theme',$this->theme); - }elseif($this->theme == 'default'){ - # reset to default theme - $this->theme = $this->config->conf['ui-theme']; - $this->session->set('theme', $this->theme ); - Kohana::config_set('core.theme',$this->theme); - }else{ - # set $this->theme with session infos - $this->theme = $this->session->get('theme'); - Kohana::config_set('core.theme',$this->theme); - } - } + // Initialize CSRF Token + $this->session->set('csrf_token', Security::token()); - if($this->start && $this->end ){ - if($this->session->get('timerange-reset',0) == 0){ - $this->session->set("start", $this->start); - $this->session->set("end", $this->end); - }else{ + // Session withou theme info + if ($this->session->get('theme', 'new') == 'new') { + if ($this->theme) { + // store $this->theme if available + Kohana::config_set('core.theme', $this->theme); + $this->session->set('theme', $this->theme); + } else { + // set $this->theme to default value + $this->theme = $this->config->conf['ui-theme']; + Kohana::config_set('core.theme', $this->theme); + } + // Sesion with theme info + } else { + if ($this->theme && $this->theme != 'default') { + // store $this->theme if available + $this->session->set('theme', $this->theme); + Kohana::config_set('core.theme', $this->theme); + } elseif ($this->theme == 'default') { + // reset to default theme + $this->theme = $this->config->conf['ui-theme']; + $this->session->set('theme', $this->theme); + Kohana::config_set('core.theme', $this->theme); + } else { + // set $this->theme with session infos + $this->theme = $this->session->get('theme'); + Kohana::config_set('core.theme', $this->theme); + } + } + //end if + + if ($this->start && $this->end) { + if ($this->session->get('timerange-reset', 0) == 0) { + $this->session->set('start', $this->start); + $this->session->set('end', $this->end); + } else { $this->session->set('timerange-reset', 0); } } - if($this->start && !$this->end){ - if($this->session->get('timerange-reset',0) == 0){ - $this->session->set("start", $this->start); - $this->session->set("end", ""); - }else{ + if ($this->start && !$this->end) { + if ($this->session->get('timerange-reset', 0) == 0) { + $this->session->set('start', $this->start); + $this->session->set('end', ''); + } else { $this->session->set('timerange-reset', 0); } } - if($this->end && !$this->start){ - if($this->session->get('timerange-reset',0) == 0){ - $this->session->set("end", $this->end); - $this->session->set("start", ""); - }else{ + if ($this->end && !$this->start) { + if ($this->session->get('timerange-reset', 0) == 0) { + $this->session->set('end', $this->end); + $this->session->set('start', ''); + } else { $this->session->set('timerange-reset', 0); } } } + //end if } + //end __construct() + public function __call($method, $arguments) { // Disable auto-rendering - $this->auto_render = FALSE; + $this->auto_render = false; // By defining a __call method, all pages routed to this controller // that result in 404 errors will be handled by this method, instead of // being displayed as "Page Not Found" errors. echo $this->_("The requested page doesn't exist") . " ($method)"; } + //end __call() + /** * Handle paths to current theme etc - * */ - public function add_view($view=false) + public function add_view($view = false) { $view = trim($view); if (empty($view)) { return false; } - if (!file_exists(APPPATH."/views/".$view.".php")) { + if (!file_exists(APPPATH . '/views/' . $view . '.php')) { return false; } - #return new View($this->theme_path.$view); + // return new View($this->theme_path.$view); return new View($view); } + //end add_view() - public function check_mod_rewrite(){ - if(!function_exists('apache_get_modules')){ - // Add index.php to every URL while not running withn apache mod_php - Kohana::config_set('core.index_page','index.php'); - return TRUE; + + public function check_mod_rewrite() + { + if (!function_exists('apache_get_modules')) { + // Add index.php to every URL while not running withn apache mod_php + Kohana::config_set('core.index_page', 'index.php'); + return true; } - if(!in_array('mod_rewrite', apache_get_modules())){ + if (!in_array('mod_rewrite', apache_get_modules())) { // Add index.php to every URL while mod_rewrite is not available - Kohana::config_set('core.index_page','index.php'); + Kohana::config_set('core.index_page', 'index.php'); } - if ( $this->config->conf['use_url_rewriting'] == 0 ){ - Kohana::config_set('core.index_page','index.php'); + if ($this->config->conf['use_url_rewriting'] == 0) { + Kohana::config_set('core.index_page', 'index.php'); } } + //end check_mod_rewrite() - public function isAuthorizedFor($auth) { + + public function isAuthorizedFor($auth) + { $conf = $this->config->conf; - if ($auth == "service_links") { + if ($auth == 'service_links') { + $users = explode(',', $conf['allowed_for_service_links']); + if (in_array('EVERYONE', $users)) { + return 1; + } elseif (in_array('NONE', $users)) { + return 0; + } elseif (in_array($this->auth->REMOTE_USER, $users)) { + return 1; + } else { + return 0; + } + } + if ($auth == 'host_search') { + $users = explode(',', $conf['allowed_for_host_search']); + if (in_array('EVERYONE', $users)) { + return 1; + } elseif (in_array('NONE', $users)) { + return 0; + } elseif (in_array($this->auth->REMOTE_USER, $users)) { + return 1; + } else { + return 0; + } + } + if ($auth == 'host_overview') { + $users = explode(',', $conf['allowed_for_host_overview']); + if (in_array('EVERYONE', $users)) { + return 1; + } elseif (in_array('NONE', $users)) { + return 0; + } elseif (in_array($this->auth->REMOTE_USER, $users)) { + return 1; + } else { + return 0; + } + } + if ($auth == 'pages') { + $users = explode(',', $conf['allowed_for_pages']); + if (in_array('EVERYONE', $users)) { + return 1; + } elseif (in_array('NONE', $users)) { + return 0; + } elseif (in_array($this->auth->REMOTE_USER, $users)) { + return 1; + } else { + return 0; + } + } + } + //end isAuthorizedFor() - $users = explode(",", $conf['allowed_for_service_links']); - if (in_array('EVERYONE', $users)) { - return 1; - } - elseif (in_array('NONE', $users)) { - return 0; - } - elseif (in_array($this->auth->REMOTE_USER, $users)) { - return 1; - } else { - return 0; - } + + public function isMobileDevice() + { + if ($this->session->get('classic-ui', 0) == 1) { + return false; } - if ($auth == "host_search") { - $users = explode(",", $conf['allowed_for_host_search']); - if (in_array('EVERYONE', $users)) { - return 1; - } - elseif (in_array('NONE', $users)) { - return 0; - } - elseif (in_array($this->auth->REMOTE_USER, $users)) { - return 1; - } else { - return 0; - } + if (preg_match('/' . $this->config->conf['mobile_devices'] . '/', $_SERVER['HTTP_USER_AGENT'])) { + return true; + } else { + return false; } - if ($auth == "host_overview") { - $users = explode(",", $conf['allowed_for_host_overview']); - if (in_array('EVERYONE', $users)) { - return 1; - } - elseif (in_array('NONE', $users)) { - return 0; - } - elseif (in_array($this->auth->REMOTE_USER, $users)) { - return 1; - } else { - return 0; - } - } - if ($auth == "pages") { - $users = explode(",", $conf['allowed_for_pages']); - if (in_array('EVERYONE', $users)) { - return 1; - } - elseif (in_array('NONE', $users)) { - return 0; - } - elseif (in_array($this->auth->REMOTE_USER, $users)) { - return 1; - } else { - return 0; - } - } - } - public function isMobileDevice (){ - if( $this->session->get('classic-ui',0) == 1){ - return FALSE; - } - if ( preg_match('/'.$this->config->conf['mobile_devices'].'/', $_SERVER['HTTP_USER_AGENT'] ) ){ - return TRUE; - }else{ - return FALSE; - } - } + } + //end isMobileDevice() } +//end class diff --git a/share/pnp/application/controllers/xml.php b/share/pnp/application/controllers/xml.php index 3931a72..3d80d18 100644 --- a/share/pnp/application/controllers/xml.php +++ b/share/pnp/application/controllers/xml.php @@ -1,4 +1,11 @@ -auto_render = FALSE; - if($this->service == "" && $this->host == ""){ + $this->auto_render = false; + if ($this->service == "" && $this->host == "") { url::redirect("graph", 302); } $this->data->readXML($this->host, $this->service); - if($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === FALSE){ + if ($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === false) { header('Content-Type: application/xml'); print "\n"; print "\n"; print "not authorized\n"; print "\n"; exit; - }else{ - $xmlfile = $this->config->conf['rrdbase'].$this->host."/".$this->service.".xml"; - if(is_readable($xmlfile)){ + } else { + $xmlfile = $this->config->conf['rrdbase'] . $this->host . "/" . $this->service . ".xml"; + if (is_readable($xmlfile)) { $fh = fopen($xmlfile, 'r'); header('Content-Type: application/xml'); fpassthru($fh); fclose($fh); exit; - }else{ + } else { header('Content-Type: application/xml'); print "\n"; print "\n"; diff --git a/share/pnp/application/controllers/xport.php b/share/pnp/application/controllers/xport.php index fa26fad..5560e84 100644 --- a/share/pnp/application/controllers/xport.php +++ b/share/pnp/application/controllers/xport.php @@ -1,26 +1,33 @@ -auto_render = FALSE; - $this->data->getTimeRange($this->start,$this->end,$this->view); - + $this->auto_render = false; + $this->data->getTimeRange($this->start, $this->end, $this->view); } - public function xml(){ - if(isset($this->host) && isset($this->service)){ - $this->data->buildXport($this->host,$this->service); - if($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === FALSE){ + public function xml() + { + if (isset($this->host) && isset($this->service)) { + $this->data->buildXport($this->host, $this->service); + if ($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === false) { header('Content-Type: application/xml'); print "\n"; print "\n"; @@ -30,45 +37,45 @@ class Xport_Controller extends System_Controller { } $data = $this->rrdtool->doXport($this->data->XPORT); header('Content-Type: application/xml'); - print $data; - }else{ + print $data; + } else { throw new Kohana_Exception('error.xport-host-service'); } } - public function json(){ - if(isset($this->host) && isset($this->service)){ - $this->data->buildXport($this->host,$this->service); - if($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === FALSE){ + public function json() + { + if (isset($this->host) && isset($this->service)) { + $this->data->buildXport($this->host, $this->service); + if ($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === false) { header('Content-type: application/json'); - print json_encode("not authorized"); + print json_encode("not authorized"); exit; } $data = $this->rrdtool->doXport($this->data->XPORT); $json = json_encode(simplexml_load_string($data)); header('Content-type: application/json'); - print $json; - }else{ + print $json; + } else { throw new Kohana_Exception('error.xport-host-service'); } } - public function csv(){ - if(isset($this->host) && isset($this->service)){ - $this->data->buildXport($this->host,$this->service); - if($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === FALSE){ + public function csv() + { + if (isset($this->host) && isset($this->service)) { + $this->data->buildXport($this->host, $this->service); + if ($this->auth->is_authorized($this->data->MACRO['AUTH_HOSTNAME'], $this->data->MACRO['AUTH_SERVICEDESC']) === false) { header("Content-Type: text/plain; charset=UTF-8"); - print "not authorized"; + print "not authorized"; exit; } $data = $this->rrdtool->doXport($this->data->XPORT); $csv = $this->data->xml2csv($data); header("Content-Type: text/plain; charset=UTF-8"); print $csv; - }else{ + } else { throw new Kohana_Exception('error.xport-host-service'); } } - - } diff --git a/share/pnp/application/controllers/zoom.php b/share/pnp/application/controllers/zoom.php index b7fda7a..6daa2b2 100644 --- a/share/pnp/application/controllers/zoom.php +++ b/share/pnp/application/controllers/zoom.php @@ -1,14 +1,21 @@ -start = abs((int)$this->start); - if($this->start < $start_limit) - $this->start = $start_limit; + if ($this->start < $start_limit) { + $this->start = $start_limit; + } + # + # Limit end to now + one hour # - # Limit end to now + one hour - # $end_limit = time() + 3600; $this->end = abs((int)$this->end); - if($this->end > $end_limit) + if ($this->end > $end_limit) { $this->end = $end_limit; + } - $this->data->getTimeRange($this->start,$this->end,$this->view); + $this->data->getTimeRange($this->start, $this->end, $this->view); - if(isset($this->tpl) && $this->tpl != 'undefined' ){ - if($this->start && $this->end ){ + if (isset($this->tpl) && $this->tpl != 'undefined') { + if ($this->start && $this->end) { $this->session->set("start", $this->start); $this->session->set("end", $this->end); } @@ -56,11 +65,11 @@ class Zoom_Controller extends System_Controller { $this->template->source = $this->source; $this->template->end = $this->end; $this->template->start = $this->start; - $this->url = "?tpl=".$this->tpl; + $this->url = "?tpl=" . $this->tpl; $this->template->graph_height = $this->graph_height; $this->template->graph_width = $this->graph_width; - }elseif(isset($this->host) && isset($this->service)){ - if($this->start && $this->end ){ + } elseif (isset($this->host) && isset($this->service)) { + if ($this->start && $this->end) { $this->session->set("start", $this->start); $this->session->set("end", $this->end); } @@ -70,10 +79,10 @@ class Zoom_Controller extends System_Controller { $this->template->source = $this->source; $this->template->end = $this->end; $this->template->start = $this->start; - $this->url = "?host=".urlencode($this->host)."&srv=".urlencode($this->service); + $this->url = "?host=" . urlencode($this->host) . "&srv=" . urlencode($this->service); $this->template->graph_height = $this->graph_height; $this->template->graph_width = $this->graph_width; - }else{ + } else { url::redirect("/graph"); } } diff --git a/share/pnp/application/helpers/nagios.php b/share/pnp/application/helpers/nagios.php index e1f70a9..45635e0 100644 --- a/share/pnp/application/helpers/nagios.php +++ b/share/pnp/application/helpers/nagios.php @@ -1,58 +1,79 @@ -read_config(); - $smon = date('m' , $start); - $sday = date('d' , $start); - $syear = date('Y' , $start); - $shour = date('G' , $start); - $smin = date('i' , $start); - $ssec = date('s' , $start); - $emon = date('m' , $end); - $eday = date('d' , $end); - $eyear = date('Y' , $end); - $ehour = date('G' , $end); - $emin = date('i' , $end); - $esec = date('s' , $end); + $smon = date('m', $start); + $sday = date('d', $start); + $syear = date('Y', $start); + $shour = date('G', $start); + $smin = date('i', $start); + $ssec = date('s', $start); + $emon = date('m', $end); + $eday = date('d', $end); + $eyear = date('Y', $end); + $ehour = date('G', $end); + $emin = date('i', $end); + $esec = date('s', $end); $nagios_base = $config->conf['nagios_base']; - print "\n"; + print "\n"; } - public static function AvailLink($hostname,$servicedesc,$start,$end){ + public static function AvailLink($hostname, $servicedesc, $start, $end) + { $config = new Config_Model(); $config->read_config(); - $hostname = urlencode($hostname); - $servicedesc = urlencode($servicedesc); - $smon = date('m' , $start); - $sday = date('d' , $start); - $syear = date('Y' , $start); - $shour = date('G' , $start); - $smin = date('i' , $start); - $ssec = date('s' , $start); - $emon = date('m' , $end); - $eday = date('d' , $end); - $eyear = date('Y' , $end); - $ehour = date('G' , $end); - $emin = date('i' , $end); - $esec = date('s' , $end); + $hostname = urlencode($hostname); + $servicedesc = urlencode($servicedesc); + $smon = date('m', $start); + $sday = date('d', $start); + $syear = date('Y', $start); + $shour = date('G', $start); + $smin = date('i', $start); + $ssec = date('s', $start); + $emon = date('m', $end); + $eday = date('d', $end); + $eyear = date('Y', $end); + $ehour = date('G', $end); + $emin = date('i', $end); + $esec = date('s', $end); $nagios_base = $config->conf['nagios_base']; - if($servicedesc == "Host+Perfdata"){ - print "\n"; + print " title=\"" . Kohana::lang('common.nagios-avail-link-title') . "\">\n"; + } } - - - -} diff --git a/share/pnp/application/helpers/pnp.php b/share/pnp/application/helpers/pnp.php index de6a7f1..17e236e 100644 --- a/share/pnp/application/helpers/pnp.php +++ b/share/pnp/application/helpers/pnp.php @@ -1,27 +1,35 @@ - $length){ + if (strlen($string) > $length) { $string = substr($string, 0, $length) . "..."; } return $string; @@ -29,13 +37,14 @@ class pnp_Core { /* * */ - public static function xml_version_check($string = FALSE){ - if($string === FALSE){ - return FALSE; + public static function xml_version_check($string = false) + { + if ($string === false) { + return false; } - if( $string == XML_STRUCTURE_VERSION ){ + if ($string == XML_STRUCTURE_VERSION) { $string = "valid"; - }else{ + } else { $string = Kohana::lang('error.xml-structure-mismatch', $string, XML_STRUCTURE_VERSION); } return $string; @@ -43,66 +52,85 @@ class pnp_Core { /* * */ - public static function zoom_icon($host,$service,$start,$end,$source,$view,$graph_width,$graph_height){ + public static function zoom_icon($host, $service, $start, $end, $source, $view, $graph_width, $graph_height) + { $service = urlencode(urlencode($service)); $host = urlencode(urlencode($host)); - print "\n"; + print "\n"; } /* * */ - public static function zoom_icon_special($tpl,$start,$end,$source,$view,$graph_width,$graph_height){ - print "\n"; + public static function zoom_icon_special($tpl, $start, $end, $source, $view, $graph_width, $graph_height) + { + print "" . + "\n"; } /* * */ - public static function add_to_basket_icon($host,$service,$source=FALSE){ - if($source === FALSE){ - print "\n"; - }else{ - print "\n"; + public static function add_to_basket_icon($host, $service, $source = false) + { + if ($source === false) { + print "\n"; + } else { + print "\n"; } } /* * */ - public static function multisite_link($base_url=FALSE,$site=FALSE,$host=FALSE,$service=FALSE){ - if($host && $service){ - $link = sprintf("'%s/view.py?view_name=service&site=%s&host=%s&service=%s'", $base_url,$site,urlencode($host),urlencode($service)); + public static function multisite_link($base_url = false, $site = false, $host = false, $service = false) + { + if ($host && $service) { + $link = sprintf("'%s/view.py?view_name=service&site=%s&host=%s&service=%s'", $base_url, $site, urlencode($host), urlencode($service)); return $link; } - if($host){ - $link = sprintf("'%s/view.py?view_name=host&site=%s&host=%s'", $base_url,$site,urlencode($host)); + if ($host) { + $link = sprintf("'%s/view.py?view_name=host&site=%s&host=%s'", $base_url, $site, urlencode($host)); return $link; } } - public static function addToUri($fields = array(),$base = True){ - if(!is_array($fields)){ + public static function addToUri($fields = array(), $base = true) + { + if (!is_array($fields)) { return false; } $get = $_GET; - if($base === True){ - $uri = url::base(TRUE); + if ($base === true) { + $uri = url::base(true); $uri .= Router::$current_uri; - }else{ + } else { $uri = ""; } $uri .= '?'; - foreach($fields as $key=>$value){ + foreach ($fields as $key => $value) { $get[$key] = $value; } - foreach($get as $key=>$value){ - if($value === ''){ - continue; - } - $uri .= $key."=".urlencode($value)."&"; + foreach ($get as $key => $value) { + if ($value === '') { + continue; + } + $uri .= $key . "=" . urlencode($value) . "&"; } - return rtrim($uri,"&"); + return rtrim($uri, "&"); } /* "normalize" and adjust value / unit (similar to format string %s in RRDtool) @@ -117,12 +145,13 @@ class pnp_Core { * unit := adjusted unit * divisor := number used to "normalize" value */ - public static function adjust_unit($value,$base=1000,$format='%.3lf'){ - preg_match('/^(-?[0-9\.,]+)\s*(\S?)(\S?)/',$value,$matches); + public static function adjust_unit($value, $base = 1000, $format = '%.3lf') + { + preg_match('/^(-?[0-9\.,]+)\s*(\S?)(\S?)/', $value, $matches); $mag = 0; $value = $matches[1]; - while ($value >= $base){ + while ($value >= $base) { $value /= $base; $mag++; } @@ -137,17 +166,17 @@ class pnp_Core { $matches[3] = $matches[2]; $matches[2] = " "; } - $pos = strpos(' KMGTP',strtoupper($matches[2])); - $unit = substr(' KMGTP',$mag+$pos,1).$matches[3]; + $pos = strpos(' KMGTP', strtoupper($matches[2])); + $unit = substr(' KMGTP', $mag + $pos, 1) . $matches[3]; } - $val_unit = sprintf ("$format %s", $value, $unit); - $val_fmt = sprintf ($format, $value); - $val_fmt = str_replace(' ','',$val_fmt); - return array ($val_unit,$val_fmt,$unit,pow($base,$mag)); + $val_unit = sprintf("$format %s", $value, $unit); + $val_fmt = sprintf($format, $value); + $val_fmt = str_replace(' ', '', $val_fmt); + return array ($val_unit,$val_fmt,$unit,pow($base, $mag)); } - public static function print_version(){ - return PNP_NAME . "-" . PNP_VERSION . " [ " . PNP_REL_DATE . " ]"; + public static function print_version() + { + return PNP_NAME . "-" . PNP_VERSION . " [ " . PNP_REL_DATE . " ]"; } - } diff --git a/share/pnp/application/helpers/rrd.php b/share/pnp/application/helpers/rrd.php index 81bb257..247289c 100644 --- a/share/pnp/application/helpers/rrd.php +++ b/share/pnp/application/helpers/rrd.php @@ -1,456 +1,519 @@ -= 1 ){ - $color .= "$ri"; - } else { - $color .= "00"; - } - if ( ($z & 2) >= 1 ){ - $color .= "$ri"; - } else { - $color .= "00"; - } - if ( ($z & 1) >= 1 ){ - $color .= "$ri"; - } else { - $color .= "00"; - } - $icolor = rrd::color_inverse($color); - $pos = array_search($color,$colors); - $ipos = array_search($icolor,$colors); - if ( $pos == false ) { - $colors[] = $color . $alpha; - } - if ( $ipos == false ) { - $colors[] = $icolor . $alpha; - } - } - } - if (array_key_exists($num, $colors)) { - return $colors[$num]; - } else { - return $colors[0]; - } - } + foreach ($value as $ri) { + for ($z = 1; $z < 8; $z++) { + $color = "#"; + if (($z & 4) >= 1) { + $color .= "$ri"; + } else { + $color .= "00"; + } + if (($z & 2) >= 1) { + $color .= "$ri"; + } else { + $color .= "00"; + } + if (($z & 1) >= 1) { + $color .= "$ri"; + } else { + $color .= "00"; + } + $icolor = rrd::color_inverse($color); + $pos = array_search($color, $colors); + $ipos = array_search($icolor, $colors); + if ($pos == false) { + $colors[] = $color . $alpha; + } + if ($ipos == false) { + $colors[] = $icolor . $alpha; + } + } + } + if (array_key_exists($num, $colors)) { + return $colors[$num]; + } else { + return $colors[0]; + } + } /* * Gradient Function * Concept by Stefan Triep */ - public static function gradient($vname=FALSE, $start_color='#0000a0', $end_color='#f0f0f0', $label=FALSE, $steps=20, $lower=FALSE){ - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); + public static function gradient($vname = false, $start_color = '#0000a0', $end_color = '#f0f0f0', $label = false, $steps = 20, $lower = false) + { + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); + } + if (preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i', $start_color, $matches)) { + $r1 = hexdec($matches[1]); + $g1 = hexdec($matches[2]); + $b1 = hexdec($matches[3]); + } else { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Wrong Color Format: '" . $start_color . "'"); } - if(preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i',$start_color,$matches)){ - $r1=hexdec($matches[1]); - $g1=hexdec($matches[2]); - $b1=hexdec($matches[3]); - }else{ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Wrong Color Format: '".$start_color."'"); - } - if(preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i',$end_color,$matches)){ - $r2=hexdec($matches[1]); - $g2=hexdec($matches[2]); - $b2=hexdec($matches[3]); - }else{ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Wrong Color Format: '".$end_color."'"); - } + if (preg_match('/^#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/i', $end_color, $matches)) { + $r2 = hexdec($matches[1]); + $g2 = hexdec($matches[2]); + $b2 = hexdec($matches[3]); + } else { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Wrong Color Format: '" . $end_color . "'"); + } - $diff_r=$r2-$r1; - $diff_g=$g2-$g1; - $diff_b=$b2-$b1; + $diff_r = $r2 - $r1; + $diff_g = $g2 - $g1; + $diff_b = $b2 - $b1; $spline = ""; - $spline_vname = "var".substr(sha1(rand()),1,4); - if(preg_match('/^([0-9]{1,3})%$/', $lower, $matches)){ - if($matches[1] > 100) - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Lower gradient start > 100% is not allowed: '".$lower."'"); - + $spline_vname = "var" . substr(sha1(rand()), 1, 4); + if (preg_match('/^([0-9]{1,3})%$/', $lower, $matches)) { + if ($matches[1] > 100) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Lower gradient start > 100% is not allowed: '" . $lower . "'"); + } + $lower = $matches[1]; $spline .= sprintf("CDEF:%sminimum=%s,100,/,%d,* ", $vname, $vname, $lower); - }elseif(preg_match('/^([0-9]+)$/', $lower, $matches)){ + } elseif (preg_match('/^([0-9]+)$/', $lower, $matches)) { $lower = $matches[1]; $spline .= sprintf("CDEF:%sminimum=%s,%d,- ", $vname, $vname, $lower); - }else{ + } else { $lower = 0; $spline .= sprintf("CDEF:%sminimum=%s,%s,- ", $vname, $vname, $vname); } # debug - # $spline .= sprintf("GPRINT:%sminimum:MAX:\"minumum %%lf\\n\" ",$vname); - for ($i=$steps; $i>0; $i--){ - $spline .= sprintf("CDEF:%s%d=%s,%sminimum,-,%d,/,%d,*,%sminimum,+ ",$spline_vname,$i,$vname,$vname,$steps,$i,$vname ); + # $spline .= sprintf("GPRINT:%sminimum:MAX:\"minumum %%lf\\n\" ",$vname); + for ($i = $steps; $i > 0; $i--) { + $spline .= sprintf("CDEF:%s%d=%s,%sminimum,-,%d,/,%d,*,%sminimum,+ ", $spline_vname, $i, $vname, $vname, $steps, $i, $vname); # debug - # $spline .= sprintf("GPRINT:%s%d:MAX:\"%22d %%lf\\n\" ",$spline_vname,$i,$i); - } - for ($i=$steps; $i>0; $i--){ - $factor=$i / $steps; - $r=round($r1 + $diff_r * $factor); - $g=round($g1 + $diff_g * $factor); - $b=round($b1 + $diff_b * $factor); - if (($i==$steps) and ($label!=FALSE)){ - $spline .= sprintf("AREA:%s%d#%02X%02X%02X:\"%s\" ", $spline_vname,$i,$r,$g,$b,$label); - }else{ - $spline .= sprintf("AREA:%s%d#%02X%02X%02X ", $spline_vname,$i,$r,$g,$b); + # $spline .= sprintf("GPRINT:%s%d:MAX:\"%22d %%lf\\n\" ",$spline_vname,$i,$i); + } + for ($i = $steps; $i > 0; $i--) { + $factor = $i / $steps; + $r = round($r1 + $diff_r * $factor); + $g = round($g1 + $diff_g * $factor); + $b = round($b1 + $diff_b * $factor); + if (($i == $steps) and ($label != false)) { + $spline .= sprintf("AREA:%s%d#%02X%02X%02X:\"%s\" ", $spline_vname, $i, $r, $g, $b, $label); + } else { + $spline .= sprintf("AREA:%s%d#%02X%02X%02X ", $spline_vname, $i, $r, $g, $b); } } return $spline; } - public static function cut($string, $length=18, $align='left'){ - if(strlen($string) > $length){ - $string = substr($string,0,($length-3))."..."; + public static function cut($string, $length = 18, $align = 'left') + { + if (strlen($string) > $length) { + $string = substr($string, 0, ($length - 3)) . "..."; } - if($align == 'left'){ - $format = "%-".$length."s"; - }else{ - $format = "%".$length."s"; + if ($align == 'left') { + $format = "%-" . $length . "s"; + } else { + $format = "%" . $length . "s"; } - $s = sprintf($format,$string); + $s = sprintf($format, $string); return $s; } - - public static function area($vname=FALSE, $color=FALSE, $text=FALSE, $stack=FALSE){ + + public static function area($vname = false, $color = false, $text = false, $stack = false) + { $line = ""; - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); - }else{ - $line .= "AREA:".$vname; + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); + } else { + $line .= "AREA:" . $vname; } - if($color === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'color' is missing"); - }else{ + if ($color === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'color' is missing"); + } else { $line .= $color; } $line .= ":\"$text\""; - if($stack != FALSE){ - $line .= ":STACK"; - } - $line .= " "; - return $line; - } - - public static function line($type=1,$vname=FALSE, $color=FALSE, $text=FALSE, $stack=FALSE){ - $line = ""; - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); - }else{ - $line .= "LINE".$type.":".$vname; - } - if($color === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'color' is missing"); - }else{ - $line .= $color; - } - $line .= ":\"$text\""; - if($stack != FALSE){ + if ($stack != false) { $line .= ":STACK"; } $line .= " "; return $line; } - public static function line1($vname=FALSE, $color=FALSE, $text=FALSE, $stack=FALSE){ - return rrd::line(1,$vname, $color,$text, $stack); - } - - public static function line2($vname=FALSE, $color=FALSE, $text=FALSE, $stack=FALSE){ - return rrd::line(2,$vname, $color,$text, $stack); - } - - public static function line3($vname=FALSE, $color=FALSE, $text=FALSE, $stack=FALSE){ - return rrd::line(3,$vname, $color,$text, $stack); - } - - public static function gprint($vname=FALSE, $cf="AVERAGE", $text="%6.2lf %s"){ + public static function line($type = 1, $vname = false, $color = false, $text = false, $stack = false) + { $line = ""; - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); + } else { + $line .= "LINE" . $type . ":" . $vname; } - - if(is_array($cf)){ - foreach($cf as $key => $val){ - $line .= sprintf("GPRINT:%s:%s:",$vname,$val); - if($key == sizeof($cf)-1){ - $line .= '"'.$text.' '.ucfirst(strtolower($val)).'\\l" '; - }else{ - $line .= '"'.$text.' '.ucfirst(strtolower($val)).'" '; + if ($color === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'color' is missing"); + } else { + $line .= $color; + } + $line .= ":\"$text\""; + if ($stack != false) { + $line .= ":STACK"; + } + $line .= " "; + return $line; + } + + public static function line1($vname = false, $color = false, $text = false, $stack = false) + { + return rrd::line(1, $vname, $color, $text, $stack); + } + + public static function line2($vname = false, $color = false, $text = false, $stack = false) + { + return rrd::line(2, $vname, $color, $text, $stack); + } + + public static function line3($vname = false, $color = false, $text = false, $stack = false) + { + return rrd::line(3, $vname, $color, $text, $stack); + } + + public static function gprint($vname = false, $cf = "AVERAGE", $text = "%6.2lf %s") + { + $line = ""; + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); + } + + if (is_array($cf)) { + foreach ($cf as $key => $val) { + $line .= sprintf("GPRINT:%s:%s:", $vname, $val); + if ($key == count($cf) - 1) { + $line .= '"' . $text . ' ' . ucfirst(strtolower($val)) . '\\l" '; + } else { + $line .= '"' . $text . ' ' . ucfirst(strtolower($val)) . '" '; } } - }else{ - $line .= sprintf("GPRINT:%s:%s:",$vname,$cf); - $line .= '"'.$text.'" '; + } else { + $line .= sprintf("GPRINT:%s:%s:", $vname, $cf); + $line .= '"' . $text . '" '; } - return $line; + return $line; } - /* - * Function to modify alignment of gprint - */ - public static function gprinta($vname=FALSE, $cf="AVERAGE", $text="%6.2lf %s", $align=""){ + /* + * Function to modify alignment of gprint + */ + public static function gprinta($vname = false, $cf = "AVERAGE", $text = "%6.2lf %s", $align = "") + { $line = ""; - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); } - if($align != ""){ + if ($align != "") { $align = '\\' . $align; } - if(is_array($cf)){ - foreach($cf as $key => $val){ - $line .= sprintf("GPRINT:%s:%s:",$vname,$val); - if(($key == sizeof($cf)-1)and($align != "")){ - $line .= '"'.$text.' '.ucfirst(strtolower($val)).$align.'" '; - }else{ - $line .= '"'.$text.' '.ucfirst(strtolower($val)).'" '; + if (is_array($cf)) { + foreach ($cf as $key => $val) { + $line .= sprintf("GPRINT:%s:%s:", $vname, $val); + if (($key == count($cf) - 1) and ($align != "")) { + $line .= '"' . $text . ' ' . ucfirst(strtolower($val)) . $align . '" '; + } else { + $line .= '"' . $text . ' ' . ucfirst(strtolower($val)) . '" '; } } - }else{ - $line .= sprintf("GPRINT:%s:%s:",$vname,$cf); - $line .= '"'.$text.'" '; + } else { + $line .= sprintf("GPRINT:%s:%s:", $vname, $cf); + $line .= '"' . $text . '" '; } return $line; } - public static function def($vname=FALSE, $rrdfile=FALSE, $ds=FALSE, $cf="AVERAGE"){ + public static function def($vname = false, $rrdfile = false, $ds = false, $cf = "AVERAGE") + { $line = ""; - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); } - if($rrdfile === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'rrdfile' is missing"); + if ($rrdfile === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'rrdfile' is missing"); } - if($rrdfile === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Third Parameter 'ds' is missing"); + if ($rrdfile === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Third Parameter 'ds' is missing"); } - $line = sprintf("DEF:%s=%s:%s:%s ",$vname,$rrdfile,$ds,$cf); + $line = sprintf("DEF:%s=%s:%s:%s ", $vname, $rrdfile, $ds, $cf); return $line; } - public static function cdef($vname=FALSE, $rpn=FALSE){ + public static function cdef($vname = false, $rpn = false) + { $line = ""; - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); } - if($rpn === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'rpn' is missing"); + if ($rpn === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'rpn' is missing"); } - $line = sprintf("CDEF:%s=%s ",$vname,$rpn); + $line = sprintf("CDEF:%s=%s ", $vname, $rpn); return $line; } - public static function vdef($vname=FALSE, $rpn=FALSE){ + public static function vdef($vname = false, $rpn = false) + { $line = ""; - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); } - if($rpn === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'rpn' is missing"); + if ($rpn === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'rpn' is missing"); } - $line = sprintf("VDEF:%s=%s ",$vname,$rpn); + $line = sprintf("VDEF:%s=%s ", $vname, $rpn); return $line; } - public static function hrule($value=FALSE, $color=FALSE, $text=FALSE){ + public static function hrule($value = false, $color = false, $text = false) + { $line = ""; - if($value === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ ."() First Parameter 'value' is missing"); + if ($value === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'value' is missing"); } - if($color === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'color' is missing"); + if ($color === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'color' is missing"); } - if($value == "~" ) { - return ""; - } - $line = sprintf("HRULE:%s%s:\"%s\" ",$value,$color,$text); + if ($value == "~") { + return ""; + } + $line = sprintf("HRULE:%s%s:\"%s\" ", $value, $color, $text); return $line; } - - public static function comment($text=FALSE){ + + public static function comment($text = false) + { $line = sprintf("COMMENT:\"%s\" ", $text); return $line; } - public static function tick($vname=FALSE, $color=FALSE, $fraction=FALSE, $label=FALSE){ - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'value' is missing"); + public static function tick($vname = false, $color = false, $fraction = false, $label = false) + { + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'value' is missing"); } - if($color === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'color' is missing"); + if ($color === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'color' is missing"); } - $line = sprintf("TICK:%s%s",$vname,$color); - if($fraction != FALSE) + $line = sprintf("TICK:%s%s", $vname, $color); + if ($fraction != false) { $line .= ":$fraction"; + } - if($label != FALSE) + if ($label != false) { $line .= ":$label"; - + } + $line .= " "; return $line; } + public static function alerter( + $vname = false, + $label = false, + $warning = false, + $critical = false, + $opacity = 'ff', + $unit = false, + $color_green = '#00ff00', + $color_btw = '#ffff00', + $color_red = '#ff0000', + $line_col = '#0000ff' + ) { - public static function alerter($vname=FALSE, $label=FALSE, $warning=FALSE, $critical=FALSE, $opacity = 'ff', $unit, $color_green = '#00ff00', $color_btw = '#ffff00', $color_red = '#ff0000', $line_col = '#0000ff') { - - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); - } - if($label === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'label' is missing"); - } - if($warning === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Third Parameter 'warning' is missing"); - } - if($critical === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Fourth Parameter 'critical' is missing"); - } - $line = ""; - $green_vname = "var".substr(sha1(rand()),1,4); - $btw_vname = "var".substr(sha1(rand()),1,4); - $blue_vname = "var".substr(sha1(rand()),1,4); - $red_vname = "var".substr(sha1(rand()),1,4); - if($warning < $critical){ - $line .= "CDEF:".$green_vname."=".$vname.",".$warning.",LT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$btw_vname."=".$vname.",".$critical.",LT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$blue_vname."=".$btw_vname.",".$warning.",GE,".$btw_vname.",UNKN,IF "; - $line .= "CDEF:".$red_vname."=".$vname.",".$critical.",GE,".$vname.",UNKN,IF "; - } else { - $line .= "CDEF:".$green_vname."=".$vname.",".$warning.",GT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$btw_vname."=".$vname.",".$critical.",GE,".$vname.",UNKN,IF "; - $line .= "CDEF:".$blue_vname."=".$btw_vname.",".$warning.",LE,".$btw_vname.",UNKN,IF "; - $line .= "CDEF:".$red_vname."=".$vname.",".$critical.",LT,".$vname.",UNKN,IF "; + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); } - $line .= rrd::area($green_vname, $color_green.$opacity); - $line .= rrd::area($blue_vname, $color_btw.$opacity); - $line .= rrd::area($red_vname, $color_red.$opacity); - $line .= rrd::line1($vname,$line_col,$label); - - return $line; - } - - public static function alerter_gr($vname=FALSE,$label=FALSE,$warning=FALSE,$critical=FALSE,$opacity='ff',$unit,$color_green='#00ff00',$color_btw='#ffff00',$color_red='#ff0000',$line_col='#0000ff',$start_color="#ffffff") { - - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); + if ($label === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'label' is missing"); } - if($label === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'label' is missing"); + if ($warning === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Third Parameter 'warning' is missing"); } - if($warning === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Third Parameter 'warning' is missing"); - } - if($critical === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Fourth Parameter 'critical' is missing"); + if ($critical === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Fourth Parameter 'critical' is missing"); } $line = ""; - $green_vname = "var".substr(sha1(rand()),1,4); - $btw_vname = "var".substr(sha1(rand()),1,4); - $blue_vname = "var".substr(sha1(rand()),1,4); - $red_vname = "var".substr(sha1(rand()),1,4); - $line = ""; - if($warning < $critical){ - $line .= "CDEF:".$green_vname."=".$vname.",".$warning.",LT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$btw_vname."=".$vname.",".$critical.",LT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$blue_vname."=".$btw_vname.",".$warning.",GE,".$btw_vname.",UNKN,IF "; - $line .= "CDEF:".$red_vname."=".$vname.",".$critical.",GE,".$vname.",UNKN,IF "; + $green_vname = "var" . substr(sha1(rand()), 1, 4); + $btw_vname = "var" . substr(sha1(rand()), 1, 4); + $blue_vname = "var" . substr(sha1(rand()), 1, 4); + $red_vname = "var" . substr(sha1(rand()), 1, 4); + if ($warning < $critical) { + $line .= "CDEF:" . $green_vname . "=" . $vname . "," . $warning . ",LT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $btw_vname . "=" . $vname . "," . $critical . ",LT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $blue_vname . "=" . $btw_vname . "," . $warning . ",GE," . $btw_vname . ",UNKN,IF "; + $line .= "CDEF:" . $red_vname . "=" . $vname . "," . $critical . ",GE," . $vname . ",UNKN,IF "; } else { - $line .= "CDEF:".$green_vname."=".$vname.",".$warning.",GT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$btw_vname."=".$vname.",".$critical.",GE,".$vname.",UNKN,IF "; - $line .= "CDEF:".$blue_vname."=".$btw_vname.",".$warning.",LE,".$btw_vname.",UNKN,IF "; - $line .= "CDEF:".$red_vname."=".$vname.",".$critical.",LT,".$vname.",UNKN,IF "; + $line .= "CDEF:" . $green_vname . "=" . $vname . "," . $warning . ",GT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $btw_vname . "=" . $vname . "," . $critical . ",GE," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $blue_vname . "=" . $btw_vname . "," . $warning . ",LE," . $btw_vname . ",UNKN,IF "; + $line .= "CDEF:" . $red_vname . "=" . $vname . "," . $critical . ",LT," . $vname . ",UNKN,IF "; } - $line .= rrd::gradient($green_vname, $start_color, $color_green.$opacity); - $line .= rrd::gradient($blue_vname, $start_color, $color_btw.$opacity); - $line .= rrd::gradient($red_vname, $start_color, $color_red.$opacity); - $line .= rrd::line1($vname,$line_col,$label); + $line .= rrd::area($green_vname, $color_green . $opacity); + $line .= rrd::area($blue_vname, $color_btw . $opacity); + $line .= rrd::area($red_vname, $color_red . $opacity); + $line .= rrd::line1($vname, $line_col, $label); + return $line; } - public static function ticker($vname=FALSE, $warning=FALSE, $critical=FALSE, $fraction = -0.05, $opacity = 'ff', $color_green = '#00ff00', $color_btw = '#ffff00', $color_red = '#ff0000') { - if($vname === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'vname' is missing"); - } - if($warning === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'warning' is missing"); - } - if($critical === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Third Parameter 'critical' is missing"); - } - $line = ""; - $green_vname = "var".substr(sha1(rand()),1,4); - $btw_vname = "var".substr(sha1(rand()),1,4); - $blue_vname = "var".substr(sha1(rand()),1,4); - $red_vname = "var".substr(sha1(rand()),1,4); - $green2_vname = "var".substr(sha1(rand()),1,4); - $line .= "CDEF:".$green_vname."=".$vname.",".$warning.",LT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$btw_vname."=".$vname.",".$critical.",LT,".$vname.",UNKN,IF "; - $line .= "CDEF:".$blue_vname."=".$btw_vname.",".$warning.",GE,".$btw_vname.",UNKN,IF "; - $line .= "CDEF:".$red_vname."=".$vname.",".$critical.",GE,".$vname.",UNKN,IF "; - $line .= "CDEF:".$green2_vname."=".$green_vname.",0,EQ,0.000001,".$green_vname.",IF "; - $line .= rrd::tick($green2_vname, $color_green.$opacity, $fraction); - $line .= rrd::tick($blue_vname, $color_btw.$opacity, $fraction); - $line .= rrd::tick($red_vname, $color_red.$opacity, $fraction); - - return $line; + public static function alerter_gr( + $vname = false, + $label = false, + $warning = false, + $critical = false, + $opacity = 'ff', + $unit = false, + $color_green = '#00ff00', + $color_btw = '#ffff00', + $color_red = '#ff0000', + $line_col = '#0000ff', + $start_color = "#ffffff" + ) { + + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); + } + if ($label === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'label' is missing"); + } + if ($warning === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Third Parameter 'warning' is missing"); + } + if ($critical === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Fourth Parameter 'critical' is missing"); + } + $line = ""; + $green_vname = "var" . substr(sha1(rand()), 1, 4); + $btw_vname = "var" . substr(sha1(rand()), 1, 4); + $blue_vname = "var" . substr(sha1(rand()), 1, 4); + $red_vname = "var" . substr(sha1(rand()), 1, 4); + $line = ""; + if ($warning < $critical) { + $line .= "CDEF:" . $green_vname . "=" . $vname . "," . $warning . ",LT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $btw_vname . "=" . $vname . "," . $critical . ",LT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $blue_vname . "=" . $btw_vname . "," . $warning . ",GE," . $btw_vname . ",UNKN,IF "; + $line .= "CDEF:" . $red_vname . "=" . $vname . "," . $critical . ",GE," . $vname . ",UNKN,IF "; + } else { + $line .= "CDEF:" . $green_vname . "=" . $vname . "," . $warning . ",GT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $btw_vname . "=" . $vname . "," . $critical . ",GE," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $blue_vname . "=" . $btw_vname . "," . $warning . ",LE," . $btw_vname . ",UNKN,IF "; + $line .= "CDEF:" . $red_vname . "=" . $vname . "," . $critical . ",LT," . $vname . ",UNKN,IF "; + } + $line .= rrd::gradient($green_vname, $start_color, $color_green . $opacity); + $line .= rrd::gradient($blue_vname, $start_color, $color_btw . $opacity); + $line .= rrd::gradient($red_vname, $start_color, $color_red . $opacity); + $line .= rrd::line1($vname, $line_col, $label); + return $line; } - public static function darkteint(){ - $line = ''; - $line .= '--color=BACK#000000 '; - $line .= '--color=FONT#F7F7F7 '; - $line .= '--color=SHADEA#ffffff '; - $line .= '--color=SHADEB#ffffff '; - $line .= '--color=CANVAS#000000 '; - $line .= '--color=GRID#00991A '; - $line .= '--color=MGRID#00991A '; - $line .= '--color=ARROW#00FF00 '; + public static function ticker( + $vname = false, + $warning = false, + $critical = false, + $fraction = -0.05, + $opacity = 'ff', + $color_green = '#00ff00', + $color_btw = '#ffff00', + $color_red = '#ff0000' + ) { - return $line; - } + if ($vname === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'vname' is missing"); + } + if ($warning === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'warning' is missing"); + } + if ($critical === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Third Parameter 'critical' is missing"); + } + $line = ""; + $green_vname = "var" . substr(sha1(rand()), 1, 4); + $btw_vname = "var" . substr(sha1(rand()), 1, 4); + $blue_vname = "var" . substr(sha1(rand()), 1, 4); + $red_vname = "var" . substr(sha1(rand()), 1, 4); + $green2_vname = "var" . substr(sha1(rand()), 1, 4); + $line .= "CDEF:" . $green_vname . "=" . $vname . "," . $warning . ",LT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $btw_vname . "=" . $vname . "," . $critical . ",LT," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $blue_vname . "=" . $btw_vname . "," . $warning . ",GE," . $btw_vname . ",UNKN,IF "; + $line .= "CDEF:" . $red_vname . "=" . $vname . "," . $critical . ",GE," . $vname . ",UNKN,IF "; + $line .= "CDEF:" . $green2_vname . "=" . $green_vname . ",0,EQ,0.000001," . $green_vname . ",IF "; + $line .= rrd::tick($green2_vname, $color_green . $opacity, $fraction); + $line .= rrd::tick($blue_vname, $color_btw . $opacity, $fraction); + $line .= rrd::tick($red_vname, $color_red . $opacity, $fraction); + + return $line; + } + + public static function darkteint() + { + $line = ''; + $line .= '--color=BACK#000000 '; + $line .= '--color=FONT#F7F7F7 '; + $line .= '--color=SHADEA#ffffff '; + $line .= '--color=SHADEB#ffffff '; + $line .= '--color=CANVAS#000000 '; + $line .= '--color=GRID#00991A '; + $line .= '--color=MGRID#00991A '; + $line .= '--color=ARROW#00FF00 '; + + return $line; + } # http://stackoverflow.com/questions/3512311/how-to-generate-lighter-darker-color-with-php - public static function colbright($hex, $steps) { - if($hex === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() First Parameter 'hex' is missing"); + public static function colbright($hex, $steps) + { + if ($hex === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() First Parameter 'hex' is missing"); } - if($steps === FALSE){ - throw new Kohana_exception("rrd::". __FUNCTION__ . "() Second Parameter 'steps' is missing"); + if ($steps === false) { + throw new Kohana_exception("rrd::" . __FUNCTION__ . "() Second Parameter 'steps' is missing"); } // Steps should be between -255 and 255. Negative = darker, positive = lighter $steps = max(-255, min(255, $steps)); @@ -458,7 +521,7 @@ class rrd_Core { // Normalize into a six character long hex string $hex = str_replace('#', '', $hex); if (strlen($hex) == 3) { - $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2); + $hex = str_repeat(substr($hex, 0, 1), 2) . str_repeat(substr($hex, 1, 1), 2) . str_repeat(substr($hex, 2, 1), 2); } // Split into three parts: R, G and B @@ -467,22 +530,22 @@ class rrd_Core { foreach ($color_parts as $color) { $color = hexdec($color); // Convert to decimal - $color = max(0,min(255,$color + $steps)); // Adjust color + $color = max(0, min(255, $color + $steps)); // Adjust color $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code } return $return; } - public static function debug($data=FALSE){ - if($data != FALSE){ - ob_start(); + public static function debug($data = false) + { + if ($data != false) { + ob_start(); - var_dump($data); + var_dump($data); $var_dump = ob_get_contents(); - $var_dump = preg_replace('/(HRULE|VDEF|DEF|CDEF|GPRINT|LINE|AREA|COMMENT)/',"\n\${1}", $var_dump); - ob_end_clean(); - throw new Kohana_exception("
    ".$var_dump."
    "); - } + $var_dump = preg_replace('/(HRULE|VDEF|DEF|CDEF|GPRINT|LINE|AREA|COMMENT)/', "\n\${1}", $var_dump); + ob_end_clean(); + throw new Kohana_exception("
    " . $var_dump . "
    "); + } } - -} +} diff --git a/share/pnp/application/i18n/de_DE/common.php b/share/pnp/application/i18n/de_DE/common.php index bd7657c..d911968 100644 --- a/share/pnp/application/i18n/de_DE/common.php +++ b/share/pnp/application/i18n/de_DE/common.php @@ -1,59 +1,60 @@ - 'Host: %s', - 'service' => 'Service: %s', - 'page' => 'Page: %s', - 'page-basket' => 'Page: Basket', - 'datasource' => 'Datasource: %s', - 'zoom-header' => 'Zoom', - 'status-box-header' => 'Status', - 'multisite-box-header' => 'Multisite Links', - 'search-box-header' => 'Suche', - 'icon-box-header' => 'Aktionen', - 'basket-box-header' => 'Mein Korb', - 'timerange-box-header' => 'Zeitbereiche', - 'service-box-header' => 'Services', - 'special-templates-box-header' => 'Special Templates', - 'pages-box-header' => 'Pages', - 'nagios-summary-link-title' => 'aktuellste Alarme für diesen Zeitbereich', - 'nagios-avail-link-title' => 'Nagios-Verügbarkeitsbericht für diesen Zeitbereich', - 'timerange-selector-legend' => 'Auswahl eines Zeitbereichs', - 'timerange-selector-title' => 'Auswahl eines Zeitbereichs', + 'Host: %s', + 'service' => 'Service: %s', + 'page' => 'Page: %s', + 'page-basket' => 'Page: Basket', + 'datasource' => 'Datasource: %s', + 'zoom-header' => 'Zoom', + 'status-box-header' => 'Status', + 'multisite-box-header' => 'Multisite Links', + 'search-box-header' => 'Suche', + 'icon-box-header' => 'Aktionen', + 'basket-box-header' => 'Mein Korb', + 'timerange-box-header' => 'Zeitbereiche', + 'service-box-header' => 'Services', + 'special-templates-box-header' => 'Special Templates', + 'pages-box-header' => 'Pages', + 'nagios-summary-link-title' => 'aktuellste Alarme für diesen Zeitbereich', + 'nagios-avail-link-title' => 'Nagios-Verügbarkeitsbericht für diesen Zeitbereich', + 'timerange-selector-legend' => 'Auswahl eines Zeitbereichs', + 'timerange-selector-title' => 'Auswahl eines Zeitbereichs', 'timerange-selector-submit-button' => 'absenden', 'timerange-selector-clear-button' => 'löschen', 'timerange-selector-link' => 'Spezieller Zeitbereich', 'timerange-selector-overview' => 'Übersicht', - 'start' => 'Start', - 'end' => 'Ende', - 'service-details' => 'Service-Details', - 'service-overview' => 'Service-Übersicht für "%s"', - 'title-pages-link' => 'Pages anzeigen', - 'title-pdf-link' => 'PDF anzeigen', - 'title-xml-link' => 'XML anzeigen', - 'title-statistics-link' => 'Interne PNP Statistiken', - 'title-calendar-link' => 'Einen Zeitbereich definieren', - 'title-special-templates-link' => 'Spezial Templates anzeigen', - 'title-docs-link' => 'Dokumentation', - 'title-home-link' => 'Zu den Graphen', - 'title-color-link' => 'View Color Schemes', - 'docs-home' => 'Home', - 'docs-box-header' => 'Menu', - 'docs-header' => 'Dokumentation Version %s', - 'back' => 'zurück', - 'mobile-all-hosts' => 'Alle Hosts', - 'mobile-search-hosts' => 'Hosts suchen', - 'mobile-pages' => 'Pages anzeigen', - 'mobile-special-templates' => 'Special Templates anzeigen', - 'mobile-statistics' => 'Interne PNP Statistiken', - 'mobile-go-classic' => 'Classic UI', - 'mobile-submit' => 'absenden', - 'basket-empty' => 'Basket ist leer', - 'basket-show' => 'Zeige Basket', - 'basket-clear' => 'Leere Basket', - 'basket-remove' => 'Entferne %s', - 'basket-add-item' => 'Graphen zum Basket hinzufügen', - 'basket-add-service' => 'Alle Graphen zum Basket hinzufügen', - 'color-box-header' => 'Colors', - 'color-header' => 'Colors Schemes', -); + 'start' => 'Start', + 'end' => 'Ende', + 'service-details' => 'Service-Details', + 'service-overview' => 'Service-Übersicht für "%s"', + 'title-pages-link' => 'Pages anzeigen', + 'title-pdf-link' => 'PDF anzeigen', + 'title-xml-link' => 'XML anzeigen', + 'title-statistics-link' => 'Interne PNP Statistiken', + 'title-calendar-link' => 'Einen Zeitbereich definieren', + 'title-special-templates-link' => 'Spezial Templates anzeigen', + 'title-docs-link' => 'Dokumentation', + 'title-home-link' => 'Zu den Graphen', + 'title-color-link' => 'View Color Schemes', + 'docs-home' => 'Home', + 'docs-box-header' => 'Menu', + 'docs-header' => 'Dokumentation Version %s', + 'back' => 'zurück', + 'mobile-all-hosts' => 'Alle Hosts', + 'mobile-search-hosts' => 'Hosts suchen', + 'mobile-pages' => 'Pages anzeigen', + 'mobile-special-templates' => 'Special Templates anzeigen', + 'mobile-statistics' => 'Interne PNP Statistiken', + 'mobile-go-classic' => 'Classic UI', + 'mobile-submit' => 'absenden', + 'basket-empty' => 'Basket ist leer', + 'basket-show' => 'Zeige Basket', + 'basket-clear' => 'Leere Basket', + 'basket-remove' => 'Entferne %s', + 'basket-add-item' => 'Graphen zum Basket hinzufügen', + 'basket-add-service' => 'Alle Graphen zum Basket hinzufügen', + 'color-box-header' => 'Colors', + 'color-header' => 'Colors Schemes', +]; diff --git a/share/pnp/application/i18n/de_DE/error.php b/share/pnp/application/i18n/de_DE/error.php index 5814b7b..5b94c13 100644 --- a/share/pnp/application/i18n/de_DE/error.php +++ b/share/pnp/application/i18n/de_DE/error.php @@ -1,32 +1,57 @@ - '"rrdtool"-Binary nicht in %s gefunden. FAQ online lesen', - 'config-not-found' => 'Config-Datei %s nicht gefunden. FAQ online lesen', - 'perfdata-dir-empty' => 'Das perfdata-Verzeichnis "%s" ist leer. Bitte die Nagios-Konfiguration prüfen. FAQ online lesen', - 'host-perfdata-dir-empty' => 'Das perfdata-Verzeichnis "%s" ist leer. Bitte die Nagios-Konfiguration prüfen. FAQ online lesen', - 'perfdata-dir-for-host' => 'Das perfdata-Verzeichnis "%s" für Host "%s" existiert nicht. FAQ online lesen', - 'xml-not-found' => 'XML-Datei "%s" nicht gefunden. FAQ online lesen', - 'get-first-service' => 'Konnte ersten Service für Host "%s" nicht finden. FAQ online lesen', - 'get-first-host' => 'Keinen Host gefunden. FAQ online lesen', - 'xml-structure-mismatch' => 'Version der XML-Struktur ungültig. Fand Version "%d", sollte aber "%d" sein. FAQ online lesen', - 'save-rrd-image' => 'Speichern des Graphen gescheitert. php fopen("%s") failed. FAQ online lesen', - 'xml-structure-without-version-tag' => 'Versionshinweis fehlt im XML-File. FAQ online lesen', - 'template-without-opt' => 'Template %s übergibt Array $opt[] nicht. FAQ online lesen', - 'template-without-def' => 'Template %s übergibt Array $def[] nicht. FAQ online lesen', - 'no-data-for-page' => 'Keine Daten für die Page "%s", FAQ online lesen', - 'page-not-readable' => 'Konfigurationsdatei "%s" ist nicht lesbar oder existiert nicht. FAQ online lesen', - 'auth-pages' => 'Sie sind nicht berechtigt, "Pages" anzusehen FAQ online lesen', - 'page-config-dir' => 'Keine page-Konfigurationsdatei in "%s" gefunden FAQ online lesen', - 'xport-host-service' => 'Xport-Controller benötigt "host"- und "srv"-URL-Parameter. FAQ online lesen', - 'mod-rewrite' => 'Apache Rewrite Module ist nicht aktiviert. Read FAQ online', - 'tpl-no-services-found' => 'Es wurden keine Services gefunden "%s". Read FAQ online', - 'tpl-no-hosts-found' => 'Es wurden keine Hosts gefunden "%s". Read FAQ online', - 'no-templates-found' => 'Es wurde kein passendes Template gefunden. Read FAQ online', - 'not_authorized' => 'You are not authorized to view this host/service', - 'remote_user_missing' => 'Remote user is missing. Authentication check cancled. Read FAQ online', - 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s) Read FAQ online', - 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', - 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', - 'gd-missing' => 'PHP GD functions are missing. More on www.php.net', -); + '"rrdtool"-Binary nicht in %s gefunden.' . + ' FAQ online lesen', + 'config-not-found' => 'Config-Datei %s nicht gefunden. ' . + 'FAQ online lesen', + 'perfdata-dir-empty' => 'Das perfdata-Verzeichnis "%s" ist leer.' . + ' Bitte die Nagios-Konfiguration prüfen. FAQ online lesen', + 'host-perfdata-dir-empty' => 'Das perfdata-Verzeichnis "%s" ist leer.' . + ' Bitte die Nagios-Konfiguration prüfen. FAQ online lesen', + 'perfdata-dir-for-host' => 'Das perfdata-Verzeichnis "%s" für Host "%s" existiert nicht.' . + ' FAQ online lesen', + 'xml-not-found' => 'XML-Datei "%s" nicht gefunden. ' . + 'FAQ online lesen', + 'get-first-service' => 'Konnte ersten Service für Host "%s" nicht finden.' . + ' FAQ online lesen', + 'get-first-host' => 'Keinen Host gefunden. FAQ online lesen', + 'xml-structure-mismatch' => 'Version der XML-Struktur ungültig. Fand Version "%d",' . + ' sollte aber "%d" sein. FAQ online lesen', + 'save-rrd-image' => 'Speichern des Graphen gescheitert. php fopen("%s") failed.' . + ' FAQ online lesen', + 'xml-structure-without-version-tag' => 'Versionshinweis fehlt im XML-File.' . + ' FAQ online lesen', + 'template-without-opt' => 'Template %s übergibt Array $opt[] nicht.' . + ' FAQ online lesen', + 'template-without-def' => 'Template %s übergibt Array $def[] nicht.' . + ' FAQ online lesen', + 'no-data-for-page' => 'Keine Daten für die Page "%s",' . + ' FAQ online lesen', + 'page-not-readable' => 'Konfigurationsdatei "%s" ist nicht lesbar' . + ' oder existiert nicht. FAQ online lesen', + 'auth-pages' => 'Sie sind nicht berechtigt, "Pages" anzusehen' . + ' FAQ online lesen', + 'page-config-dir' => 'Keine page-Konfigurationsdatei in "%s" gefunden' . + ' FAQ online lesen', + 'xport-host-service' => 'Xport-Controller benötigt "host"- und "srv"-URL-Parameter.' . + ' FAQ online lesen', + 'mod-rewrite' => 'Apache Rewrite Module ist nicht aktiviert.' . + ' Read FAQ online', + 'tpl-no-services-found' => 'Es wurden keine Services gefunden "%s".' . + ' Read FAQ online', + 'tpl-no-hosts-found' => 'Es wurden keine Hosts gefunden "%s".' . + ' Read FAQ online', + 'no-templates-found' => 'Es wurde kein passendes Template gefunden.' . + ' Read FAQ online', + 'not_authorized' => 'You are not authorized to view this host/service', + 'remote_user_missing' => 'Remote user is missing. Authentication check cancled.' . + ' Read FAQ online', + 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s) ' . + 'Read FAQ online', + 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', + 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', + 'gd-missing' => 'PHP GD functions are missing. More on' . + ' www.php.net', +]; diff --git a/share/pnp/application/i18n/en_US/common.php b/share/pnp/application/i18n/en_US/common.php index 6c67c09..f8608d5 100644 --- a/share/pnp/application/i18n/en_US/common.php +++ b/share/pnp/application/i18n/en_US/common.php @@ -1,59 +1,60 @@ - 'Datasource: %s', - 'host' => 'Host: %s', - 'service' => 'Service: %s', - 'page' => 'Page: %s', - 'page-basket' => 'Page: Basket', - 'zoom-header' => 'Zoom', - 'status-box-header' => 'Status', - 'multisite-box-header' => 'Multisite links', - 'search-box-header' => 'Search', - 'icon-box-header' => 'Actions', - 'basket-box-header' => 'My basket', - 'timerange-box-header' => 'Time ranges', - 'service-box-header' => 'Services', - 'special-templates-box-header' => 'Special Templates', - 'pages-box-header' => 'Pages', - 'nagios-summary-link-title' => 'Most recent alerts for this time range', - 'nagios-avail-link-title' => 'Nagios availability report for this time range', - 'timerange-selector-legend' => 'Select a custom time range', - 'timerange-selector-title' => 'Select a custom time range', + 'Datasource: %s', + 'host' => 'Host: %s', + 'service' => 'Service: %s', + 'page' => 'Page: %s', + 'page-basket' => 'Page: Basket', + 'zoom-header' => 'Zoom', + 'status-box-header' => 'Status', + 'multisite-box-header' => 'Multisite links', + 'search-box-header' => 'Search', + 'icon-box-header' => 'Actions', + 'basket-box-header' => 'My basket', + 'timerange-box-header' => 'Time ranges', + 'service-box-header' => 'Services', + 'special-templates-box-header' => 'Special Templates', + 'pages-box-header' => 'Pages', + 'nagios-summary-link-title' => 'Most recent alerts for this time range', + 'nagios-avail-link-title' => 'Nagios availability report for this time range', + 'timerange-selector-legend' => 'Select a custom time range', + 'timerange-selector-title' => 'Select a custom time range', 'timerange-selector-submit-button' => 'Submit', 'timerange-selector-clear-button' => 'Clear', 'timerange-selector-link' => 'Custom time range', 'timerange-selector-overview' => 'Overview', - 'start' => 'Start', - 'end' => 'End', - 'service-details' => 'Service details', - 'service-overview' => 'Service overview for "%s"', - 'title-pages-link' => 'View Pages', - 'title-pdf-link' => 'View PDF', - 'title-xml-link' => 'View XML', - 'title-statistics-link' => 'View internal statistics', - 'title-calendar-link' => 'Define a custom time range', - 'title-special-templates-link' => 'View Special Templates', - 'title-docs-link' => 'View Documentation', - 'title-home-link' => 'View Graphs', - 'title-color-link' => 'View Color Schemes', - 'docs-home' => 'Home', - 'docs-box-header' => 'Menu', - 'docs-header' => 'Documentation Version %s', - 'back' => 'back', - 'mobile-all-hosts' => 'All Hosts', - 'mobile-search-hosts' => 'Search Hosts', - 'mobile-pages' => 'View Pages', - 'mobile-special-templates' => 'View Special Templates', - 'mobile-statistics' => 'View internal statistics', - 'mobile-go-classic' => 'Classic UI', - 'mobile-submit' => 'Submit', - 'basket-empty' => 'Basket is empty', - 'basket-show' => 'Show basket', - 'basket-clear' => 'Clear basket', - 'basket-remove' => 'Remove %s', - 'basket-add-item' => 'Add this item to my basket', - 'basket-add-service' => 'Add this service to my basket', - 'color-box-header' => 'Colors', - 'color-header' => 'Colors Schemes', -); + 'start' => 'Start', + 'end' => 'End', + 'service-details' => 'Service details', + 'service-overview' => 'Service overview for "%s"', + 'title-pages-link' => 'View Pages', + 'title-pdf-link' => 'View PDF', + 'title-xml-link' => 'View XML', + 'title-statistics-link' => 'View internal statistics', + 'title-calendar-link' => 'Define a custom time range', + 'title-special-templates-link' => 'View Special Templates', + 'title-docs-link' => 'View Documentation', + 'title-home-link' => 'View Graphs', + 'title-color-link' => 'View Color Schemes', + 'docs-home' => 'Home', + 'docs-box-header' => 'Menu', + 'docs-header' => 'Documentation Version %s', + 'back' => 'back', + 'mobile-all-hosts' => 'All Hosts', + 'mobile-search-hosts' => 'Search Hosts', + 'mobile-pages' => 'View Pages', + 'mobile-special-templates' => 'View Special Templates', + 'mobile-statistics' => 'View internal statistics', + 'mobile-go-classic' => 'Classic UI', + 'mobile-submit' => 'Submit', + 'basket-empty' => 'Basket is empty', + 'basket-show' => 'Show basket', + 'basket-clear' => 'Clear basket', + 'basket-remove' => 'Remove %s', + 'basket-add-item' => 'Add this item to my basket', + 'basket-add-service' => 'Add this service to my basket', + 'color-box-header' => 'Colors', + 'color-header' => 'Colors Schemes', +]; diff --git a/share/pnp/application/i18n/en_US/error.php b/share/pnp/application/i18n/en_US/error.php index 8d5d395..7f400f4 100644 --- a/share/pnp/application/i18n/en_US/error.php +++ b/share/pnp/application/i18n/en_US/error.php @@ -1,32 +1,57 @@ - 'RRDTool not found in %s. Read FAQ online', - 'config-not-found' => 'Config file %s not found. Read FAQ online', - 'perfdata-dir-empty' => 'perfdata directory "%s" is empty. Please check your Nagios config. Read FAQ online', - 'host-perfdata-dir-empty' => 'perfdata directory "%s" is empty. Please check your Nagios config. Read FAQ online', - 'perfdata-dir-for-host' => 'perfdata directory "%s" for host "%s" does not exist. Read FAQ online', - 'xml-not-found' => 'XML file "%s" not found. Read FAQ online', - 'get-first-service' => 'Can´t find first service for host "%s". Read FAQ online', - 'get-first-host' => 'Can´t find any Host. Read FAQ online', - 'xml-structure-mismatch' => 'XML structure mismatch. Found version "%d" but should be "%d". Read FAQ online', - 'save-rrd-image' => 'php fopen("%s") failed. Read FAQ online', - 'xml-structure-without-version-tag' => 'XML structure mismatch. Version tag not found in "%s". Read FAQ online', - 'template-without-opt' => 'Template %s does not provide array $opt[]. Read FAQ online', - 'template-without-def' => 'Template %s does not provide array $def[]. Read FAQ online', - 'no-data-for-page' => 'Sorry, but we can´t find any data using config file "%s", Read FAQ online', - 'page-not-readable' => 'Config file "%s" is not readable or does not exist. Read FAQ online', - 'auth-pages' => 'You are not authorized to view "pages" Read FAQ online', - 'page-config-dir' => 'No page config file found in "%s" Read FAQ online', - 'xport-host-service' => 'Xport controller needs "host" and "srv" URL parameters. Read FAQ online', - 'mod-rewrite' => 'Apache Rewrite Module is not enabled. Read FAQ online', - 'tpl-no-services-found' => 'No services could be found "%s". Read FAQ online', - 'tpl-no-hosts-found' => 'No hosts could be found "%s". Read FAQ online', - 'no-templates-found' => 'No templates could be found. Read FAQ online', - 'not_authorized' => 'You are not authorized to view this host/service', - 'remote_user_missing' => 'Remote user is missing. Authentication check cancled. Read FAQ online', - 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s) Read FAQ online', - 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', - 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', - 'gd-missing' => 'PHP GD functions are missing. More on www.php.net', -); + 'RRDTool not found in %s.' . + ' Read FAQ online', + 'config-not-found' => 'Config file %s not found.' . + ' Read FAQ online', + 'perfdata-dir-empty' => 'perfdata directory "%s" is empty.' . + ' Please check your Nagios config. Read FAQ online', + 'host-perfdata-dir-empty' => 'perfdata directory "%s" is empty.' . + ' Please check your Nagios config. Read FAQ online', + 'perfdata-dir-for-host' => 'perfdata directory "%s" for host "%s" does not exist.' . + ' Read FAQ online', + 'xml-not-found' => 'XML file "%s" not found.' . + ' Read FAQ online', + 'get-first-service' => 'Can´t find first service for host "%s".' . + ' Read FAQ online', + 'get-first-host' => 'Can´t find any Host.' . + ' Read FAQ online', + 'xml-structure-mismatch' => 'XML structure mismatch.' . + ' Found version "%d" but should be "%d". Read FAQ online', + 'save-rrd-image' => 'php fopen("%s") failed.' . + ' Read FAQ online', + 'xml-structure-without-version-tag' => 'XML structure mismatch.' . + ' Version tag not found in "%s". Read FAQ online', + 'template-without-opt' => 'Template %s does not provide array $opt[].' . + ' Read FAQ online', + 'template-without-def' => 'Template %s does not provide array $def[].' . + ' Read FAQ online', + 'no-data-for-page' => 'Sorry, but we can´t find any data using config file "%s",' . + ' Read FAQ online', + 'page-not-readable' => 'Config file "%s" is not readable or does not exist.' . + ' Read FAQ online', + 'auth-pages' => 'You are not authorized to view "pages"' . + ' Read FAQ online', + 'page-config-dir' => 'No page config file found in "%s"' . + ' Read FAQ online', + 'xport-host-service' => 'Xport controller needs "host" and "srv" URL parameters.' . + ' Read FAQ online', + 'mod-rewrite' => 'Apache Rewrite Module is not enabled.' . + ' Read FAQ online', + 'tpl-no-services-found' => 'No services could be found "%s".' . + ' Read FAQ online', + 'tpl-no-hosts-found' => 'No hosts could be found "%s".' . + ' Read FAQ online', + 'no-templates-found' => 'No templates could be found.' . + ' Read FAQ online', + 'not_authorized' => 'You are not authorized to view this host/service', + 'remote_user_missing' => 'Remote user is missing. Authentication check canceled.' . + ' Read FAQ online', + 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s)' . + ' Read FAQ online', + 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', + 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', + 'gd-missing' => 'PHP GD functions are missing. More on www.php.net', +]; diff --git a/share/pnp/application/i18n/es_ES/common.php b/share/pnp/application/i18n/es_ES/common.php index 0c9cc0b..7cbc55c 100644 --- a/share/pnp/application/i18n/es_ES/common.php +++ b/share/pnp/application/i18n/es_ES/common.php @@ -1,58 +1,59 @@ - 'Fuente de Datos: %s', - 'host' => 'Equipo: %s', - 'service' => 'Servicio: %s', - 'page' => 'Page: %s', - 'page-basket' => 'Página: Cesta', - 'zoom-header' => 'Zoom', - 'status-box-header' => 'Estado', - 'multisite-box-header' => 'Multisite links', - 'search-box-header' => 'Buscar', - 'icon-box-header' => 'Acciones', - 'basket-box-header' => 'Mi Cesta', - 'timerange-box-header' => 'Intervalos de Tiempo', - 'service-box-header' => 'Servicios', - 'pages-box-header' => 'Páginas', - 'nagios-summary-link-title' => 'Alertas Recientes en el Intervalo de Tiempo', - 'nagios-avail-link-title' => 'Informe de Disponibilidad en el Intervalo de Tiempo', - 'timerange-selector-legend' => 'Seleccione un intervalo de tiempo personalizado', - 'timerange-selector-title' => 'Seleccione un intervalo de tiempo personalizado', + 'Fuente de Datos: %s', + 'host' => 'Equipo: %s', + 'service' => 'Servicio: %s', + 'page' => 'Page: %s', + 'page-basket' => 'Página: Cesta', + 'zoom-header' => 'Zoom', + 'status-box-header' => 'Estado', + 'multisite-box-header' => 'Multisite links', + 'search-box-header' => 'Buscar', + 'icon-box-header' => 'Acciones', + 'basket-box-header' => 'Mi Cesta', + 'timerange-box-header' => 'Intervalos de Tiempo', + 'service-box-header' => 'Servicios', + 'pages-box-header' => 'Páginas', + 'nagios-summary-link-title' => 'Alertas Recientes en el Intervalo de Tiempo', + 'nagios-avail-link-title' => 'Informe de Disponibilidad en el Intervalo de Tiempo', + 'timerange-selector-legend' => 'Seleccione un intervalo de tiempo personalizado', + 'timerange-selector-title' => 'Seleccione un intervalo de tiempo personalizado', 'timerange-selector-submit-button' => 'enviar', 'timerange-selector-clear-button' => 'limpiar', 'timerange-selector-link' => 'Intervalo de tiempo personalizado', 'timerange-selector-overview' => 'Overview', - 'start' => 'Comienzo', - 'end' => 'Fin', - 'service-details' => 'Detalles de Servicio', - 'service-overview' => 'Vista General de Servicio para "%s"', - 'title-pages-link' => 'Ver páginas', - 'title-pdf-link' => 'Ver PDF', - 'title-xml-link' => 'Ver XML', - 'title-statistics-link' => 'Ver estadísticas internas de PNP', - 'title-calendar-link' => 'Definir un intervalo de tiempo personalizado', - 'title-special-templates-link' => 'View Special Templates', - 'title-docs-link' => 'View Documentation', - 'title-home-link' => 'View Graphs', - 'title-color-link' => 'View Color Schemes', - 'docs-home' => 'Home', - 'docs-box-header' => 'Menu', - 'docs-header' => 'Documentation Version %s', - 'back' => 'back', - 'mobile-all-hosts' => 'All Hosts', - 'mobile-search-hosts' => 'Search Hosts', - 'mobile-pages' => 'View Pages', - 'mobile-special-templates' => 'View Special Templates', - 'mobile-statistics' => 'View internal statistics', - 'mobile-go-classic' => 'Classic UI', - 'mobile-submit' => 'Submit', - 'basket-empty' => 'Basket is empty', - 'basket-show' => 'Show basket', - 'basket-clear' => 'Clear basket', - 'basket-remove' => 'Remove %s', - 'basket-add-item' => 'Add this item to my basket', - 'basket-add-service' => 'Add this service to my basket', - 'color-box-header' => 'Colors', - 'color-header' => 'Colors Schemes', -); + 'start' => 'Comienzo', + 'end' => 'Fin', + 'service-details' => 'Detalles de Servicio', + 'service-overview' => 'Vista General de Servicio para "%s"', + 'title-pages-link' => 'Ver páginas', + 'title-pdf-link' => 'Ver PDF', + 'title-xml-link' => 'Ver XML', + 'title-statistics-link' => 'Ver estadísticas internas de PNP', + 'title-calendar-link' => 'Definir un intervalo de tiempo personalizado', + 'title-special-templates-link' => 'View Special Templates', + 'title-docs-link' => 'View Documentation', + 'title-home-link' => 'View Graphs', + 'title-color-link' => 'View Color Schemes', + 'docs-home' => 'Home', + 'docs-box-header' => 'Menu', + 'docs-header' => 'Documentation Version %s', + 'back' => 'back', + 'mobile-all-hosts' => 'All Hosts', + 'mobile-search-hosts' => 'Search Hosts', + 'mobile-pages' => 'View Pages', + 'mobile-special-templates' => 'View Special Templates', + 'mobile-statistics' => 'View internal statistics', + 'mobile-go-classic' => 'Classic UI', + 'mobile-submit' => 'Submit', + 'basket-empty' => 'Basket is empty', + 'basket-show' => 'Show basket', + 'basket-clear' => 'Clear basket', + 'basket-remove' => 'Remove %s', + 'basket-add-item' => 'Add this item to my basket', + 'basket-add-service' => 'Add this service to my basket', + 'color-box-header' => 'Colors', + 'color-header' => 'Colors Schemes', +]; diff --git a/share/pnp/application/i18n/es_ES/error.php b/share/pnp/application/i18n/es_ES/error.php index 5a638b1..e319e9d 100644 --- a/share/pnp/application/i18n/es_ES/error.php +++ b/share/pnp/application/i18n/es_ES/error.php @@ -1,32 +1,58 @@ - 'RRDTool no se encuentra en %s. Leer FAQ en línea', - 'config-not-found' => 'El fichero de configuración %s no se ha encontrado. Leer FAQ en línea', - 'perfdata-dir-empty' => 'El directorio de Perfdata "%s" está vacío. Compruebe la configuración de Nagios. Leer FAQ en línea', - 'host-perfdata-dir-empty' => 'El directorio de Perfdata "%s" está vacío. Compruebe la configuración de Nagios. Leer FAQ en línea', - 'perfdata-dir-for-host' => 'El directorio Perfdata "%s" para el Equipo "%s" no existe. Leer FAQ en línea', - 'xml-not-found' => 'Fichero XML "%s" no encontrado. Leer FAQ en línea', - 'get-first-service' => 'No puedo encontrar el primer servicio para el equipo "%s". Leer FAQ en línea', - 'get-first-host' => 'No puedo encuentrar ningún Equipo. Leer FAQ en línea', - 'xml-structure-mismatch' => 'Error en la Estructura XML. Versión Encontrada "%d" pero debería ser "%d". Read FAQ online', - 'save-rrd-image' => 'fallo en php fopen("%s"). Leer FAQ en línea', - 'xml-structure-without-version-tag' => 'Error en la estructura XML. Etiqueta de Versión no encontrada. Leer FAQ en línea', - 'template-without-opt' => 'La plantilla %s no tiene el array $opt[]. Leer FAQ en línea', - 'template-without-def' => 'La plantilla %s no tiene el array $def[]. Leer FAQ en línea', - 'no-data-for-page' => 'Lo siento, no puedo encontrar ningún dato usando el fichero de configuración "%s", Leer FAQ en línea', - 'page-not-readable' => 'El fichero de configuración "%s" no es legible o no existe. Leer FAQ en línea', - 'auth-pages' => 'No está autorizado a ver "páginas" Leer FAQ en línea', - 'page-config-dir' => 'No hay fichero de configuración de página en "%s" Leer FAQ en línea', - 'xport-host-service' => 'El controlador Xport necesita los parámetros de URL "host" y "srv". Leer FAQ en línea', - 'mod-rewrite' => 'El módulo Apache Rewrite no está habilitado. Leer FAQ en línea', - 'tpl-no-services-found' => 'No services could be found "%s". Read FAQ online', - 'tpl-no-hosts-found' => 'No hosts could be found "%s". Read FAQ online', - 'no-templates-found' => 'No templates could be found. Read FAQ online', - 'not_authorized' => 'You are not authorized to view this host/service', - 'remote_user_missing' => 'Remote user is missing. Authentication check cancled. Read FAQ online', - 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s) Read FAQ online', - 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', - 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', - 'gd-missing' => 'PHP GD functions are missing. More on www.php.net', -); + 'RRDTool no se encuentra en %s.' . +' Leer FAQ en línea', + 'config-not-found' => 'El fichero de configuración %s no se ha encontrado.' . +' Leer FAQ en línea', + 'perfdata-dir-empty' => 'El directorio de Perfdata "%s" está vacío. Compruebe la configuración de Nagios.' . +' Leer FAQ en línea', + 'host-perfdata-dir-empty' => 'El directorio de Perfdata "%s" está vacío. Compruebe la configuración de Nagios.' . +' Leer FAQ en línea', + 'perfdata-dir-for-host' => 'El directorio Perfdata "%s" para el Equipo "%s" no existe.' . +' Leer FAQ en línea', + 'xml-not-found' => 'Fichero XML "%s" no encontrado.' . +' Leer FAQ en línea', + 'get-first-service' => 'No puedo encontrar el primer servicio para el equipo "%s".' . +' Leer FAQ en línea', + 'get-first-host' => 'No puedo encuentrar ningún Equipo.' . +' Leer FAQ en línea', + 'xml-structure-mismatch' => 'Error en la Estructura XML. Versión Encontrada "%d" pero debería ser "%d".' . +' Read FAQ online', + 'save-rrd-image' => 'fallo en php fopen("%s").' . +' Leer FAQ en línea', + 'xml-structure-without-version-tag' => 'Error en la estructura XML. Etiqueta de Versión no encontrada.' . +' Leer FAQ en línea', + 'template-without-opt' => 'La plantilla %s no tiene el array $opt[].' . +' Leer FAQ en línea', + 'template-without-def' => 'La plantilla %s no tiene el array $def[].' . +' Leer FAQ en línea', + 'no-data-for-page' => 'Lo siento, no puedo encontrar ningún dato usando el fichero de configuración "%s",' . +' Leer FAQ en línea', + 'page-not-readable' => 'El fichero de configuración "%s" no es legible o no existe.' . +' Leer FAQ en línea', + 'auth-pages' => 'No está autorizado a ver "páginas"' . +' Leer FAQ en línea', + 'page-config-dir' => 'No hay fichero de configuración de página en "%s"' . +' Leer FAQ en línea', + 'xport-host-service' => 'El controlador Xport necesita los parámetros de URL "host" y "srv".' . +' Leer FAQ en línea', + 'mod-rewrite' => 'El módulo Apache Rewrite no está habilitado.' . +' Leer FAQ en línea', + 'tpl-no-services-found' => 'No services could be found "%s".' . +' Read FAQ online', + 'tpl-no-hosts-found' => 'No hosts could be found "%s".' . +' Read FAQ online', + 'no-templates-found' => 'No templates could be found.' . +' Read FAQ online', + 'not_authorized' => 'You are not authorized to view this host/service', + 'remote_user_missing' => 'Remote user is missing. Authentication check cancled.' . +' Read FAQ online', + 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s)' . +' Read FAQ online', + 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', + 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', + 'gd-missing' => 'PHP GD functions are missing. More on' . +' www.php.net', +]; diff --git a/share/pnp/application/i18n/fr_FR/common.php b/share/pnp/application/i18n/fr_FR/common.php index 3d9b933..53be09e 100644 --- a/share/pnp/application/i18n/fr_FR/common.php +++ b/share/pnp/application/i18n/fr_FR/common.php @@ -1,59 +1,60 @@ - 'Source de données : %s', - 'host' => 'Machine : %s', - 'service' => 'Service : %s', - 'page' => 'Page : %s', - 'page-basket' => 'Page : Panier', - 'zoom-header' => 'Zoom', - 'status-box-header' => 'État', - 'multisite-box-header' => 'Liens multisite', - 'search-box-header' => 'Recherche', - 'icon-box-header' => 'Actions', - 'basket-box-header' => 'Mon panier', - 'timerange-box-header' => 'Plage de temps', - 'service-box-header' => 'Services', - 'special-templates-box-header' => 'Patrons spécifiques', - 'pages-box-header' => 'Pages', - 'nagios-summary-link-title' => 'Alarmes les plus récentes dans cette plage de temps', - 'nagios-avail-link-title' => 'Disponibilité de Nagios pendant cette plage de temps', - 'timerange-selector-legend' => 'Selectionner une plage de temps', - 'timerange-selector-title' => 'Selectionner une plage de temps', + 'Source de données : %s', + 'host' => 'Machine : %s', + 'service' => 'Service : %s', + 'page' => 'Page : %s', + 'page-basket' => 'Page : Panier', + 'zoom-header' => 'Zoom', + 'status-box-header' => 'État', + 'multisite-box-header' => 'Liens multisite', + 'search-box-header' => 'Recherche', + 'icon-box-header' => 'Actions', + 'basket-box-header' => 'Mon panier', + 'timerange-box-header' => 'Plage de temps', + 'service-box-header' => 'Services', + 'special-templates-box-header' => 'Patrons spécifiques', + 'pages-box-header' => 'Pages', + 'nagios-summary-link-title' => 'Alarmes les plus récentes dans cette plage de temps', + 'nagios-avail-link-title' => 'Disponibilité de Nagios pendant cette plage de temps', + 'timerange-selector-legend' => 'Selectionner une plage de temps', + 'timerange-selector-title' => 'Selectionner une plage de temps', 'timerange-selector-submit-button' => 'démarrer', 'timerange-selector-clear-button' => 'effacer', 'timerange-selector-link' => 'Plage de temps personnalisée', 'timerange-selector-overview' => 'Overview', - 'start' => 'Début', - 'end' => 'Fin', - 'service-details' => 'Détails du service', - 'service-overview' => 'Aperçu du service sur "%s"', - 'title-pages-link' => 'Voir la page', - 'title-pdf-link' => 'Extraction PDF', - 'title-xml-link' => 'Extraction XML', - 'title-statistics-link' => 'Voir statistiques internes sur PNP', - 'title-calendar-link' => 'Définir une plage de temps', - 'title-special-templates-link' => 'Voir les patrons', - 'title-docs-link' => 'Accèder à la documentation', - 'title-home-link' => 'Accèder aux graphiques', - 'title-color-link' => 'View Color Schemes', - 'docs-home' => 'Accueil', - 'docs-box-header' => 'Menu', - 'docs-header' => 'Version de la documentation %s', - 'back' => 'back', - 'mobile-all-hosts' => 'All Hosts', - 'mobile-search-hosts' => 'Search Hosts', - 'mobile-pages' => 'View Pages', - 'mobile-special-templates' => 'View Special Templates', - 'mobile-statistics' => 'View internal statistics', - 'mobile-go-classic' => 'Classic UI', - 'mobile-submit' => 'Submit', - 'basket-empty' => 'Basket is empty', - 'basket-show' => 'Show basket', - 'basket-clear' => 'Clear basket', - 'basket-remove' => 'Remove %s', - 'basket-add-item' => 'Add this item to my basket', - 'basket-add-service' => 'Add this service to my basket', - 'color-box-header' => 'Colors', - 'color-header' => 'Colors Schemes', -); + 'start' => 'Début', + 'end' => 'Fin', + 'service-details' => 'Détails du service', + 'service-overview' => 'Aperçu du service sur "%s"', + 'title-pages-link' => 'Voir la page', + 'title-pdf-link' => 'Extraction PDF', + 'title-xml-link' => 'Extraction XML', + 'title-statistics-link' => 'Voir statistiques internes sur PNP', + 'title-calendar-link' => 'Définir une plage de temps', + 'title-special-templates-link' => 'Voir les patrons', + 'title-docs-link' => 'Accèder à la documentation', + 'title-home-link' => 'Accèder aux graphiques', + 'title-color-link' => 'View Color Schemes', + 'docs-home' => 'Accueil', + 'docs-box-header' => 'Menu', + 'docs-header' => 'Version de la documentation %s', + 'back' => 'back', + 'mobile-all-hosts' => 'All Hosts', + 'mobile-search-hosts' => 'Search Hosts', + 'mobile-pages' => 'View Pages', + 'mobile-special-templates' => 'View Special Templates', + 'mobile-statistics' => 'View internal statistics', + 'mobile-go-classic' => 'Classic UI', + 'mobile-submit' => 'Submit', + 'basket-empty' => 'Basket is empty', + 'basket-show' => 'Show basket', + 'basket-clear' => 'Clear basket', + 'basket-remove' => 'Remove %s', + 'basket-add-item' => 'Add this item to my basket', + 'basket-add-service' => 'Add this service to my basket', + 'color-box-header' => 'Colors', + 'color-header' => 'Colors Schemes', +]; diff --git a/share/pnp/application/i18n/fr_FR/error.php b/share/pnp/application/i18n/fr_FR/error.php index 2ea5229..f3ecf0a 100644 --- a/share/pnp/application/i18n/fr_FR/error.php +++ b/share/pnp/application/i18n/fr_FR/error.php @@ -1,32 +1,58 @@ - 'RRDTool non trouvé dans %s. Lire la FAQ', - 'config-not-found' => 'Fichier de config %s non trouvé. Lire la FAQ', - 'perfdata-dir-empty' => 'Répertoire perfdata "%s" vide. Merci de vérifier la configuration de Nagios. Lire la FAQ', - 'host-perfdata-dir-empty' => 'Répertoire perfdata "%s" vide. Merci de vérifier la configuration de Nagios. Lire la FAQ', - 'perfdata-dir-for-host' => 'Répertoire perfdata "%s" du serveur "%s" n\'existe pas. Lire la FAQ', - 'xml-not-found' => 'Fichier XML "%s" non trouvé. Lire la FAQ', - 'get-first-service' => 'Impossible de trouver le premier service du serveur "%s". Lire la FAQ', - 'get-first-host' => 'Impossible de trouver un serveur. Lire la FAQ', - 'xml-structure-mismatch' => 'Structure XML incorrecte. Version trouvé "%d" mais version attendu "%d". Lire la FAQ', - 'save-rrd-image' => 'Échec de la fonction php fopen("%s"). Lire la FAQ', - 'xml-structure-without-version-tag' => 'Structure XML incorrect. Balise de version introuvable dans "%s". Lire la FAQ', - 'template-without-opt' => 'Le template %s ne renvoie pas de tableau $opt[]. Lire la FAQ', - 'template-without-def' => 'Le template %s ne renvoie pas de tableau $def[]. Lire la FAQ', - 'no-data-for-page' => 'Désolé, mais impossible de trouver des données en utilisant le fichier de configuration "%s", Lire la FAQ', - 'page-not-readable' => 'Impossible de lire le fichier de configuration "%s" ou fichier introuvable. Lire la FAQ', - 'auth-pages' => 'Vous n\'êtes pas autorisé de voir "pages" Lire la FAQ', - 'page-config-dir' => 'Pas de fichier de configuration pour page dans "%s" Lire la FAQ', - 'xport-host-service' => 'Le contrôleur Xport nécessite les paramètres "host" et "srv" en paramètres d\'URL. Lire la FAQ', - 'mod-rewrite' => 'Module Apache Rewrite désactivé. Lire la FAQ', - 'tpl-no-services-found' => 'Impossible de trouver des services "%s". Read FAQ online', - 'tpl-no-hosts-found' => 'Impossible de trouver des serveurs "%s". Read FAQ online', - 'no-templates-found' => 'Impossible de trouver des modèles. Read FAQ online', - 'not_authorized' => 'You are not authorized to view this host/service', - 'remote_user_missing' => 'Remote user is missing. Authentication check cancled. Read FAQ online', - 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s) Read FAQ online', - 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', - 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', - 'gd-missing' => 'PHP GD functions are missing. More on www.php.net', -); + 'RRDTool non trouvé dans %s.' . +' Lire la FAQ', + 'config-not-found' => 'Fichier de config %s non trouvé.' . +' Lire la FAQ', + 'perfdata-dir-empty' => 'Répertoire perfdata "%s" vide. Merci de vérifier la configuration de Nagios.' . +' Lire la FAQ', + 'host-perfdata-dir-empty' => 'Répertoire perfdata "%s" vide. Merci de vérifier la configuration de Nagios.' . +' Lire la FAQ', + 'perfdata-dir-for-host' => 'Répertoire perfdata "%s" du serveur "%s" n\'existe pas.' . +' Lire la FAQ', + 'xml-not-found' => 'Fichier XML "%s" non trouvé.' . +' Lire la FAQ', + 'get-first-service' => 'Impossible de trouver le premier service du serveur "%s".' . +' Lire la FAQ', + 'get-first-host' => 'Impossible de trouver un serveur.' . +' Lire la FAQ', + 'xml-structure-mismatch' => 'Structure XML incorrecte. Version trouvé "%d" mais version attendu "%d".' . +' Lire la FAQ', + 'save-rrd-image' => 'Échec de la fonction php fopen("%s").' . +' Lire la FAQ', + 'xml-structure-without-version-tag' => 'Structure XML incorrect. Balise de version introuvable dans "%s".' . +' Lire la FAQ', + 'template-without-opt' => 'Le template %s ne renvoie pas de tableau $opt[].' . +' Lire la FAQ', + 'template-without-def' => 'Le template %s ne renvoie pas de tableau $def[].' . +' Lire la FAQ', + 'no-data-for-page' => 'Désolé, mais impossible de trouver des données en utilisant le fichier de configuration "%s",' . +' Lire la FAQ', + 'page-not-readable' => 'Impossible de lire le fichier de configuration "%s" ou fichier introuvable.' . +' Lire la FAQ', + 'auth-pages' => 'Vous n\'êtes pas autorisé de voir "pages"' . +' Lire la FAQ', + 'page-config-dir' => 'Pas de fichier de configuration pour page dans "%s"' . +' Lire la FAQ', + 'xport-host-service' => 'Le contrôleur Xport nécessite les paramètres "host" et "srv" en paramètres d\'URL.' . +' Lire la FAQ', + 'mod-rewrite' => 'Module Apache Rewrite désactivé.' . +' Lire la FAQ', + 'tpl-no-services-found' => 'Impossible de trouver des services "%s".' . +' Read FAQ online', + 'tpl-no-hosts-found' => 'Impossible de trouver des serveurs "%s".' . +' Read FAQ online', + 'no-templates-found' => 'Impossible de trouver des modèles.' . +' Read FAQ online', + 'not_authorized' => 'You are not authorized to view this host/service', + 'remote_user_missing' => 'Remote user is missing. Authentication check cancled.' . +' Read FAQ online', + 'livestatus_socket_error' => 'Livestatus Socket error: %s (%s)' . +' Read FAQ online', + 'not_authorized_for_host_overview' => 'You are not authorized to access this host overview page.', + 'xml-generic_error' => 'XML file "%s" not parsable.

    XML Errors:%s

    ', + 'gd-missing' => 'PHP GD functions are missing. More on' . +' www.php.net', +]; diff --git a/share/pnp/application/i18n/ru_RU/common.php b/share/pnp/application/i18n/ru_RU/common.php index b49834c..df3a76f 100644 --- a/share/pnp/application/i18n/ru_RU/common.php +++ b/share/pnp/application/i18n/ru_RU/common.php @@ -1,59 +1,60 @@ - 'Источник данных: %s', - 'host' => 'Хост: %s', - 'service' => 'Служба: %s', - 'page' => 'Страница: %s', - 'page-basket' => 'Страница: Мой набор', - 'zoom-header' => 'Детализация', - 'status-box-header' => 'Статус', - 'multisite-box-header' => 'Multisite links', - 'search-box-header' => 'Поиск', - 'icon-box-header' => 'Действия', - 'basket-box-header' => 'Мой набор', - 'timerange-box-header' => 'Интервалы времени', - 'service-box-header' => 'Службы', - 'special-templates-box-header' => 'Специальные шаблоны', - 'pages-box-header' => 'Страницы', - 'nagios-summary-link-title' => 'Последние алерты за данный промежуток', - 'nagios-avail-link-title' => 'Сводка доступности за данный промежуток', - 'timerange-selector-legend' => 'Выберите промежуток', - 'timerange-selector-title' => 'Установка собственного интервала времени', + 'Источник данных: %s', + 'host' => 'Хост: %s', + 'service' => 'Служба: %s', + 'page' => 'Страница: %s', + 'page-basket' => 'Страница: Мой набор', + 'zoom-header' => 'Детализация', + 'status-box-header' => 'Статус', + 'multisite-box-header' => 'Multisite links', + 'search-box-header' => 'Поиск', + 'icon-box-header' => 'Действия', + 'basket-box-header' => 'Мой набор', + 'timerange-box-header' => 'Интервалы времени', + 'service-box-header' => 'Службы', + 'special-templates-box-header' => 'Специальные шаблоны', + 'pages-box-header' => 'Страницы', + 'nagios-summary-link-title' => 'Последние алерты за данный промежуток', + 'nagios-avail-link-title' => 'Сводка доступности за данный промежуток', + 'timerange-selector-legend' => 'Выберите промежуток', + 'timerange-selector-title' => 'Установка собственного интервала времени', 'timerange-selector-submit-button' => 'ввести', 'timerange-selector-clear-button' => 'очистить', 'timerange-selector-link' => 'Собственный интервал', 'timerange-selector-overview' => 'Overview', - 'start' => 'Начало', - 'end' => 'Окончание', - 'service-details' => 'Подробности о службе', - 'service-overview' => 'Обзор служб для "%s"', - 'title-pages-link' => 'Обзор страниц', - 'title-pdf-link' => 'Просмотр PDF', - 'title-xml-link' => 'Просмотр XML', - 'title-statistics-link' => 'Просмотр внутренней статистики PNP', - 'title-calendar-link' => 'Установка собственного временного интервала', - 'title-special-templates-link' => 'Просмотр специальных шаблонов', - 'title-docs-link' => 'Просмотреть документацию', - 'title-home-link' => 'Просмотр графиков', - 'title-color-link' => 'View Color Schemes', - 'docs-home' => 'На главную', - 'docs-box-header' => 'Меню', - 'docs-header' => 'Версия документации %s', - 'back' => 'назад', - 'mobile-all-hosts' => 'Все хосты', - 'mobile-search-hosts' => 'Поиск хостов', - 'mobile-pages' => 'Просмотр страниц', - 'mobile-special-templates' => 'Просмотр специальных шаблонов', - 'mobile-statistics' => 'Просмотр внутренней статистики', - 'mobile-go-classic' => 'Классический UI', - 'mobile-submit' => 'Ввести', - 'basket-empty' => 'Корзина пуста', - 'basket-show' => 'Показать корзину', - 'basket-clear' => 'Clear basket', - 'basket-remove' => 'Убрать %s', - 'basket-add-item' => 'Добавить этот элемент в мою корзину', - 'basket-add-service' => 'Добавить эту службу в мою корзину', - 'color-box-header' => 'Colors', - 'color-header' => 'Colors Schemes', -); + 'start' => 'Начало', + 'end' => 'Окончание', + 'service-details' => 'Подробности о службе', + 'service-overview' => 'Обзор служб для "%s"', + 'title-pages-link' => 'Обзор страниц', + 'title-pdf-link' => 'Просмотр PDF', + 'title-xml-link' => 'Просмотр XML', + 'title-statistics-link' => 'Просмотр внутренней статистики PNP', + 'title-calendar-link' => 'Установка собственного временного интервала', + 'title-special-templates-link' => 'Просмотр специальных шаблонов', + 'title-docs-link' => 'Просмотреть документацию', + 'title-home-link' => 'Просмотр графиков', + 'title-color-link' => 'View Color Schemes', + 'docs-home' => 'На главную', + 'docs-box-header' => 'Меню', + 'docs-header' => 'Версия документации %s', + 'back' => 'назад', + 'mobile-all-hosts' => 'Все хосты', + 'mobile-search-hosts' => 'Поиск хостов', + 'mobile-pages' => 'Просмотр страниц', + 'mobile-special-templates' => 'Просмотр специальных шаблонов', + 'mobile-statistics' => 'Просмотр внутренней статистики', + 'mobile-go-classic' => 'Классический UI', + 'mobile-submit' => 'Ввести', + 'basket-empty' => 'Корзина пуста', + 'basket-show' => 'Показать корзину', + 'basket-clear' => 'Clear basket', + 'basket-remove' => 'Убрать %s', + 'basket-add-item' => 'Добавить этот элемент в мою корзину', + 'basket-add-service' => 'Добавить эту службу в мою корзину', + 'color-box-header' => 'Colors', + 'color-header' => 'Colors Schemes', +]; diff --git a/share/pnp/application/i18n/ru_RU/error.php b/share/pnp/application/i18n/ru_RU/error.php index 989c8d6..28c0ff8 100644 --- a/share/pnp/application/i18n/ru_RU/error.php +++ b/share/pnp/application/i18n/ru_RU/error.php @@ -1,32 +1,58 @@ - 'RRDTool не обнаружено в %s. Read FAQ online', - 'config-not-found' => 'Файл конфигурации %s не найден. Read FAQ online', - 'perfdata-dir-empty' => 'Директория с данными производительности "%s" пуста. Пожалуйста, проверьте конфигурацию Nagios. Read FAQ online', - 'host-perfdata-dir-empty' => 'Директория с данными производительности "%s" пуста. Пожалуйста, проверьте конфигурацию Nagios. Read FAQ online', - 'perfdata-dir-for-host' => 'Директория с данными производительности "%s" для хоста "%s" не существует. Read FAQ online', - 'xml-not-found' => 'XML файл "%s" не найден. Read FAQ online', - 'get-first-service' => 'Невозможно определить первую службу для хоста "%s". Read FAQ online', - 'get-first-host' => 'Ни по одному хосту данных не обнаружено. Read FAQ online', - 'xml-structure-mismatch' => 'Несоответствие структуры данных XML. Обнаружена версия "%d", ожидаемая версия - "%d". Read FAQ online', - 'save-rrd-image' => 'Функция php fopen("%s") завершилась неудачей. Read FAQ online', - 'xml-structure-without-version-tag' => 'Несоответствие структуры данных XML. Тэг версии не найден в "%s". Read FAQ online', - 'template-without-opt' => 'Шаблон %s не предоставляет массив $opt[]. Read FAQ online', - 'template-without-def' => 'Шаблон %s не предоставляет массив $def[]. Read FAQ online', - 'no-data-for-page' => 'Извините, не удалось обнаружить никаких данных используя конфигурационный файл "%s", Read FAQ online', - 'page-not-readable' => 'Конфигурационный файл "%s" не может быть прочитан или не существует. Read FAQ online', - 'auth-pages' => 'Вы не авторизованы для просмотра "страниц" Read FAQ online', - 'page-config-dir' => 'Файл конфигурации "страниц" не найден в "%s" Read FAQ online', - 'xport-host-service' => 'Контроллер Xport требует параметры "host" и "srv" в URL. Read FAQ online', - 'mod-rewrite' => 'Модуль Rewrite для Apache не включен. Read FAQ online', - 'tpl-no-services-found' => 'Службы "%s" не найдены. Read FAQ online', - 'tpl-no-hosts-found' => 'Хосты "%s" не найдены. Read FAQ online', - 'no-templates-found' => 'Шаблоны "%s" не найдены. Read FAQ online', - 'not_authorized' => 'Вы не авторизованы для просмотра данного хоста/службы', - 'remote_user_missing' => 'Удалённый пользователь не указан. Проверка аутентификации отменена. Read FAQ online', - 'livestatus_socket_error' => 'Ошибка Livestatus сокета: %s (%s) Read FAQ online', - 'not_authorized_for_host_overview' => 'Вы не авторизованы для доступа к странице обзора хоста.', - 'xml-generic_error' => 'Не удаётся распарсить XML файл "%s".

    Ошибки XML:%s

    ', - 'gd-missing' => 'PHP GD functions are missing. More on www.php.net', -); + 'RRDTool не обнаружено в %s.' . +' Read FAQ online', + 'config-not-found' => 'Файл конфигурации %s не найден.' . +' Read FAQ online', + 'perfdata-dir-empty' => 'Директория с данными производительности "%s" пуста. Пожалуйста, проверьте конфигурацию Nagios.' . +' Read FAQ online', + 'host-perfdata-dir-empty' => 'Директория с данными производительности "%s" пуста. Пожалуйста, проверьте конфигурацию Nagios.' . +' Read FAQ online', + 'perfdata-dir-for-host' => 'Директория с данными производительности "%s" для хоста "%s" не существует.' . +' Read FAQ online', + 'xml-not-found' => 'XML файл "%s" не найден.' . +' Read FAQ online', + 'get-first-service' => 'Невозможно определить первую службу для хоста "%s".' . +' Read FAQ online', + 'get-first-host' => 'Ни по одному хосту данных не обнаружено.' . +' Read FAQ online', + 'xml-structure-mismatch' => 'Несоответствие структуры данных XML. Обнаружена версия "%d", ожидаемая версия - "%d".' . +' Read FAQ online', + 'save-rrd-image' => 'Функция php fopen("%s") завершилась неудачей.' . +' Read FAQ online', + 'xml-structure-without-version-tag' => 'Несоответствие структуры данных XML. Тэг версии не найден в "%s".' . +' Read FAQ online', + 'template-without-opt' => 'Шаблон %s не предоставляет массив $opt[].' . +' Read FAQ online', + 'template-without-def' => 'Шаблон %s не предоставляет массив $def[].' . +' Read FAQ online', + 'no-data-for-page' => 'Извините, не удалось обнаружить никаких данных используя конфигурационный файл "%s",' . +' Read FAQ online', + 'page-not-readable' => 'Конфигурационный файл "%s" не может быть прочитан или не существует.' . +' Read FAQ online', + 'auth-pages' => 'Вы не авторизованы для просмотра "страниц"' . +' Read FAQ online', + 'page-config-dir' => 'Файл конфигурации "страниц" не найден в "%s"' . +' Read FAQ online', + 'xport-host-service' => 'Контроллер Xport требует параметры "host" и "srv" в URL.' . +' Read FAQ online', + 'mod-rewrite' => 'Модуль Rewrite для Apache не включен.' . +' Read FAQ online', + 'tpl-no-services-found' => 'Службы "%s" не найдены.' . +' Read FAQ online', + 'tpl-no-hosts-found' => 'Хосты "%s" не найдены.' . +' Read FAQ online', + 'no-templates-found' => 'Шаблоны "%s" не найдены.' . +' Read FAQ online', + 'not_authorized' => 'Вы не авторизованы для просмотра данного хоста/службы', + 'remote_user_missing' => 'Удалённый пользователь не указан. Проверка аутентификации отменена.' . +' Read FAQ online', + 'livestatus_socket_error' => 'Ошибка Livestatus сокета: %s (%s)' . +' Read FAQ online', + 'not_authorized_for_host_overview' => 'Вы не авторизованы для доступа к странице обзора хоста.', + 'xml-generic_error' => 'Не удаётся распарсить XML файл "%s".

    Ошибки XML:%s

    ', + 'gd-missing' => 'PHP GD functions are missing. More on' . +' www.php.net', +]; diff --git a/share/pnp/application/lib/json.php b/share/pnp/application/lib/json.php deleted file mode 100644 index 0cddbdd..0000000 --- a/share/pnp/application/lib/json.php +++ /dev/null @@ -1,806 +0,0 @@ - - * @author Matt Knapp - * @author Brett Stimmerman - * @copyright 2005 Michal Migurski - * @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $ - * @license http://www.opensource.org/licenses/bsd-license.php - * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 - */ - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_SLICE', 1); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_STR', 2); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_ARR', 3); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_OBJ', 4); - -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -define('SERVICES_JSON_IN_CMT', 5); - -/** - * Behavior switch for Services_JSON::decode() - */ -define('SERVICES_JSON_LOOSE_TYPE', 16); - -/** - * Behavior switch for Services_JSON::decode() - */ -define('SERVICES_JSON_SUPPRESS_ERRORS', 32); - -/** - * Converts to and from JSON format. - * - * Brief example of use: - * - * - * // create a new instance of Services_JSON - * $json = new Services_JSON(); - * - * // convert a complexe value to JSON notation, and send it to the browser - * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); - * $output = $json->encode($value); - * - * print($output); - * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] - * - * // accept incoming POST data, assumed to be in JSON notation - * $input = file_get_contents('php://input', 1000000); - * $value = $json->decode($input); - * - */ -class Services_JSON -{ - /** - * constructs a new JSON instance - * - * @param int $use object behavior flags; combine with boolean-OR - * - * possible values: - * - SERVICES_JSON_LOOSE_TYPE: loose typing. - * "{...}" syntax creates associative arrays - * instead of objects in decode(). - * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. - * Values which can't be encoded (e.g. resources) - * appear as NULL instead of throwing errors. - * By default, a deeply-nested resource will - * bubble up with an error, so all return values - * from encode() should be checked with isError() - */ - function Services_JSON($use = 0) - { - $this->use = $use; - } - - /** - * convert a string from one UTF-16 char to one UTF-8 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf16 UTF-16 character - * @return string UTF-8 character - * @access private - */ - function utf162utf8($utf16) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); - } - - $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); - - switch(true) { - case ((0x7F & $bytes) == $bytes): - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x7F & $bytes); - - case (0x07FF & $bytes) == $bytes: - // return a 2-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xC0 | (($bytes >> 6) & 0x1F)) - . chr(0x80 | ($bytes & 0x3F)); - - case (0xFFFF & $bytes) == $bytes: - // return a 3-byte UTF-8 character - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xE0 | (($bytes >> 12) & 0x0F)) - . chr(0x80 | (($bytes >> 6) & 0x3F)) - . chr(0x80 | ($bytes & 0x3F)); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * convert a string from one UTF-8 char to one UTF-16 char - * - * Normally should be handled by mb_convert_encoding, but - * provides a slower PHP-only method for installations - * that lack the multibye string extension. - * - * @param string $utf8 UTF-8 character - * @return string UTF-16 character - * @access private - */ - function utf82utf16($utf8) - { - // oh please oh please oh please oh please oh please - if(function_exists('mb_convert_encoding')) { - return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); - } - - switch(strlen($utf8)) { - case 1: - // this case should never be reached, because we are in ASCII range - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return $utf8; - - case 2: - // return a UTF-16 character from a 2-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0x07 & (ord($utf8{0}) >> 2)) - . chr((0xC0 & (ord($utf8{0}) << 6)) - | (0x3F & ord($utf8{1}))); - - case 3: - // return a UTF-16 character from a 3-byte UTF-8 char - // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr((0xF0 & (ord($utf8{0}) << 4)) - | (0x0F & (ord($utf8{1}) >> 2))) - . chr((0xC0 & (ord($utf8{1}) << 6)) - | (0x7F & ord($utf8{2}))); - } - - // ignoring UTF-32 for now, sorry - return ''; - } - - /** - * encodes an arbitrary variable into JSON format - * - * @param mixed $var any number, boolean, string, array, or object to be encoded. - * see argument 1 to Services_JSON() above for array-parsing behavior. - * if var is a strng, note that encode() always expects it - * to be in ASCII or UTF-8 format! - * - * @return mixed JSON string representation of input var or an error if a problem occurs - * @access public - */ - function encode($var) - { - switch (gettype($var)) { - case 'boolean': - return $var ? 'true' : 'false'; - - case 'NULL': - return 'null'; - - case 'integer': - return (int) $var; - - case 'double': - case 'float': - return (float) $var; - - case 'string': - // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT - $ascii = ''; - $strlen_var = strlen($var); - - /* - * Iterate over every character in the string, - * escaping with a slash or encoding to UTF-8 where necessary - */ - for ($c = 0; $c < $strlen_var; ++$c) { - - $ord_var_c = ord($var{$c}); - - switch (true) { - case $ord_var_c == 0x08: - $ascii .= '\b'; - break; - case $ord_var_c == 0x09: - $ascii .= '\t'; - break; - case $ord_var_c == 0x0A: - $ascii .= '\n'; - break; - case $ord_var_c == 0x0C: - $ascii .= '\f'; - break; - case $ord_var_c == 0x0D: - $ascii .= '\r'; - break; - - case $ord_var_c == 0x22: - case $ord_var_c == 0x2F: - case $ord_var_c == 0x5C: - // double quote, slash, slosh - $ascii .= '\\'.$var{$c}; - break; - - case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): - // characters U-00000000 - U-0000007F (same as ASCII) - $ascii .= $var{$c}; - break; - - case (($ord_var_c & 0xE0) == 0xC0): - // characters U-00000080 - U-000007FF, mask 110XXXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, ord($var{$c + 1})); - $c += 1; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF0) == 0xE0): - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2})); - $c += 2; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xF8) == 0xF0): - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3})); - $c += 3; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFC) == 0xF8): - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4})); - $c += 4; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - - case (($ord_var_c & 0xFE) == 0xFC): - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $char = pack('C*', $ord_var_c, - ord($var{$c + 1}), - ord($var{$c + 2}), - ord($var{$c + 3}), - ord($var{$c + 4}), - ord($var{$c + 5})); - $c += 5; - $utf16 = $this->utf82utf16($char); - $ascii .= sprintf('\u%04s', bin2hex($utf16)); - break; - } - } - - return '"'.$ascii.'"'; - - case 'array': - /* - * As per JSON spec if any array key is not an integer - * we must treat the the whole array as an object. We - * also try to catch a sparsely populated associative - * array with numeric keys here because some JS engines - * will create an array with empty indexes up to - * max_index which can cause memory issues and because - * the keys, which may be relevant, will be remapped - * otherwise. - * - * As per the ECMA and JSON specification an object may - * have any string as a property. Unfortunately due to - * a hole in the ECMA specification if the key is a - * ECMA reserved word or starts with a digit the - * parameter is only accessible using ECMAScript's - * bracket notation. - */ - - // treat as a JSON object - if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { - $properties = array_map(array($this, 'name_value'), - array_keys($var), - array_values($var)); - - foreach($properties as $property) { - if(Services_JSON::isError($property)) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - } - - // treat it like a regular array - $elements = array_map(array($this, 'encode'), $var); - - foreach($elements as $element) { - if(Services_JSON::isError($element)) { - return $element; - } - } - - return '[' . join(',', $elements) . ']'; - - case 'object': - $vars = get_object_vars($var); - - $properties = array_map(array($this, 'name_value'), - array_keys($vars), - array_values($vars)); - - foreach($properties as $property) { - if(Services_JSON::isError($property)) { - return $property; - } - } - - return '{' . join(',', $properties) . '}'; - - default: - return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) - ? 'null' - : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); - } - } - - /** - * array-walking function for use in generating JSON-formatted name-value pairs - * - * @param string $name name of key to use - * @param mixed $value reference to an array element to be encoded - * - * @return string JSON-formatted name-value pair, like '"name":value' - * @access private - */ - function name_value($name, $value) - { - $encoded_value = $this->encode($value); - - if(Services_JSON::isError($encoded_value)) { - return $encoded_value; - } - - return $this->encode(strval($name)) . ':' . $encoded_value; - } - - /** - * reduce a string by removing leading and trailing comments and whitespace - * - * @param $str string string value to strip of comments and whitespace - * - * @return string string value stripped of comments and whitespace - * @access private - */ - function reduce_string($str) - { - $str = preg_replace(array( - - // eliminate single line comments in '// ...' form - '#^\s*//(.+)$#m', - - // eliminate multi-line comments in '/* ... */' form, at start of string - '#^\s*/\*(.+)\*/#Us', - - // eliminate multi-line comments in '/* ... */' form, at end of string - '#/\*(.+)\*/\s*$#Us' - - ), '', $str); - - // eliminate extraneous space - return trim($str); - } - - /** - * decodes a JSON string into appropriate variable - * - * @param string $str JSON-formatted string - * - * @return mixed number, boolean, string, array, or object - * corresponding to given JSON input string. - * See argument 1 to Services_JSON() above for object-output behavior. - * Note that decode() always returns strings - * in ASCII or UTF-8 format! - * @access public - */ - function decode($str) - { - $str = $this->reduce_string($str); - - switch (strtolower($str)) { - case 'true': - return true; - - case 'false': - return false; - - case 'null': - return null; - - default: - $m = array(); - - if (is_numeric($str)) { - // Lookie-loo, it's a number - - // This would work on its own, but I'm trying to be - // good about returning integers where appropriate: - // return (float)$str; - - // Return float or int, as appropriate - return ((float)$str == (integer)$str) - ? (integer)$str - : (float)$str; - - } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { - // STRINGS RETURNED IN UTF-8 FORMAT - $delim = substr($str, 0, 1); - $chrs = substr($str, 1, -1); - $utf8 = ''; - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c < $strlen_chrs; ++$c) { - - $substr_chrs_c_2 = substr($chrs, $c, 2); - $ord_chrs_c = ord($chrs{$c}); - - switch (true) { - case $substr_chrs_c_2 == '\b': - $utf8 .= chr(0x08); - ++$c; - break; - case $substr_chrs_c_2 == '\t': - $utf8 .= chr(0x09); - ++$c; - break; - case $substr_chrs_c_2 == '\n': - $utf8 .= chr(0x0A); - ++$c; - break; - case $substr_chrs_c_2 == '\f': - $utf8 .= chr(0x0C); - ++$c; - break; - case $substr_chrs_c_2 == '\r': - $utf8 .= chr(0x0D); - ++$c; - break; - - case $substr_chrs_c_2 == '\\"': - case $substr_chrs_c_2 == '\\\'': - case $substr_chrs_c_2 == '\\\\': - case $substr_chrs_c_2 == '\\/': - if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || - ($delim == "'" && $substr_chrs_c_2 != '\\"')) { - $utf8 .= $chrs{++$c}; - } - break; - - case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)): - // single, escaped unicode character - $utf16 = chr(hexdec(substr($chrs, ($c + 2), 2))) - . chr(hexdec(substr($chrs, ($c + 4), 2))); - $utf8 .= $this->utf162utf8($utf16); - $c += 5; - break; - - case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): - $utf8 .= $chrs{$c}; - break; - - case ($ord_chrs_c & 0xE0) == 0xC0: - // characters U-00000080 - U-000007FF, mask 110XXXXX - //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 2); - ++$c; - break; - - case ($ord_chrs_c & 0xF0) == 0xE0: - // characters U-00000800 - U-0000FFFF, mask 1110XXXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 3); - $c += 2; - break; - - case ($ord_chrs_c & 0xF8) == 0xF0: - // characters U-00010000 - U-001FFFFF, mask 11110XXX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 4); - $c += 3; - break; - - case ($ord_chrs_c & 0xFC) == 0xF8: - // characters U-00200000 - U-03FFFFFF, mask 111110XX - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 5); - $c += 4; - break; - - case ($ord_chrs_c & 0xFE) == 0xFC: - // characters U-04000000 - U-7FFFFFFF, mask 1111110X - // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - $utf8 .= substr($chrs, $c, 6); - $c += 5; - break; - - } - - } - - return $utf8; - - } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { - // array, or object notation - - if ($str{0} == '[') { - $stk = array(SERVICES_JSON_IN_ARR); - $arr = array(); - } else { - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = array(); - } else { - $stk = array(SERVICES_JSON_IN_OBJ); - $obj = new stdClass(); - } - } - - array_push($stk, array('what' => SERVICES_JSON_SLICE, - 'where' => 0, - 'delim' => false)); - - $chrs = substr($str, 1, -1); - $chrs = $this->reduce_string($chrs); - - if ($chrs == '') { - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } else { - return $obj; - - } - } - - //print("\nparsing {$chrs}\n"); - - $strlen_chrs = strlen($chrs); - - for ($c = 0; $c <= $strlen_chrs; ++$c) { - - $top = end($stk); - $substr_chrs_c_2 = substr($chrs, $c, 2); - - if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { - // found a comma that is not inside a string, array, etc., - // OR we've reached the end of the character list - $slice = substr($chrs, $top['where'], ($c - $top['where'])); - array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); - //print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - // we are in an array, so just push an element onto the stack - array_push($arr, $this->decode($slice)); - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - // we are in an object, so figure - // out the property name and set an - // element in an associative array, - // for now - $parts = array(); - - if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // "name":value pair - $key = $this->decode($parts[1]); - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) { - // name:value pair, where name is unquoted - $key = $parts[1]; - $val = $this->decode($parts[2]); - - if ($this->use & SERVICES_JSON_LOOSE_TYPE) { - $obj[$key] = $val; - } else { - $obj->$key = $val; - } - } - - } - - } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { - // found a quote, and we are not inside a string - array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); - //print("Found start of string at {$c}\n"); - - } elseif (($chrs{$c} == $top['delim']) && - ($top['what'] == SERVICES_JSON_IN_STR) && - ((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) { - // found a quote, we're in a string, and it's not escaped - // we know that it's not escaped becase there is _not_ an - // odd number of backslashes at the end of the string so far - array_pop($stk); - //print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '[') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-bracket, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); - //print("Found start of array at {$c}\n"); - - } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { - // found a right-bracket, and we're in an array - array_pop($stk); - //print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($chrs{$c} == '{') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a left-brace, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); - //print("Found start of object at {$c}\n"); - - } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { - // found a right-brace, and we're in an object - array_pop($stk); - //print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } elseif (($substr_chrs_c_2 == '/*') && - in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { - // found a comment start, and we are in an array, object, or slice - array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); - $c++; - //print("Found start of comment at {$c}\n"); - - } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { - // found a comment end, and we're in one now - array_pop($stk); - $c++; - - for ($i = $top['where']; $i <= $c; ++$i) - $chrs = substr_replace($chrs, ' ', $i, 1); - - //print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n"); - - } - - } - - if (reset($stk) == SERVICES_JSON_IN_ARR) { - return $arr; - - } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { - return $obj; - - } - - } - } - } - - /** - * @todo Ultimately, this should just call PEAR::isError() - */ - function isError($data, $code = null) - { - if (class_exists('pear')) { - return PEAR::isError($data, $code); - } elseif (is_object($data) && (get_class($data) == 'services_json_error' || - is_subclass_of($data, 'services_json_error'))) { - return true; - } - - return false; - } -} - -if (class_exists('PEAR_Error')) { - - class Services_JSON_Error extends PEAR_Error - { - function Services_JSON_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - parent::PEAR_Error($message, $code, $mode, $options, $userinfo); - } - } - -} else { - - /** - * @todo Ultimately, this class shall be descended from PEAR_Error - */ - class Services_JSON_Error - { - function Services_JSON_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - - } - } - -} - -?> diff --git a/share/pnp/application/lib/jsonwrapper.php b/share/pnp/application/lib/jsonwrapper.php deleted file mode 100644 index 29509de..0000000 --- a/share/pnp/application/lib/jsonwrapper.php +++ /dev/null @@ -1,6 +0,0 @@ - diff --git a/share/pnp/application/lib/jsonwrapper_inner.php b/share/pnp/application/lib/jsonwrapper_inner.php deleted file mode 100644 index e7a0e3f..0000000 --- a/share/pnp/application/lib/jsonwrapper_inner.php +++ /dev/null @@ -1,23 +0,0 @@ -encode($arg); -} - -function json_decode($arg) -{ - global $services_json; - if (!isset($services_json)) { - $services_json = new Services_JSON(); - } - return $services_json->decode($arg); -} - -?> diff --git a/share/pnp/application/models/auth.php b/share/pnp/application/models/auth.php index 77f28d2..695788e 100644 --- a/share/pnp/application/models/auth.php +++ b/share/pnp/application/models/auth.php @@ -1,154 +1,185 @@ -config = new Config_Model; + public $socketDOMAIN = null; + + public $socketTYPE = null; + + public $socketHOST = null; + + public $socketPORT = 0; + + public $socketPROTO = null; + + public $ERR_TXT = ''; + + public $AUTH_ENABLED = false; + + public $REMOTE_USER = null; + + public $config = ''; + + + public function __construct() + { + $this->config = new Config_Model(); $this->config->read_config(); - if($this->config->conf['auth_enabled'] == 1){ - $this->AUTH_ENABLED = TRUE; - $this->socketPath = $this->config->conf['livestatus_socket']; + if ($this->config->conf['auth_enabled'] == 1) { + $this->AUTH_ENABLED = true; + $this->socketPath = $this->config->conf['livestatus_socket']; } // Try to get the login of the user - if(isset($_SERVER['REMOTE_USER'])){ + if (isset($_SERVER['REMOTE_USER'])) { $this->REMOTE_USER = $_SERVER['REMOTE_USER']; } - if($this->REMOTE_USER === NULL && $this->config->conf['auth_multisite_enabled'] == 1) { - $MSAUTH = new Auth_Multisite_Model($this->config->conf['auth_multisite_htpasswd'], - $this->config->conf['auth_multisite_serials'], - $this->config->conf['auth_multisite_secret'], - $this->config->conf['auth_multisite_login_url']); + if ($this->REMOTE_USER === null && $this->config->conf['auth_multisite_enabled'] == 1) { + $MSAUTH = new Auth_Multisite_Model( + $this->config->conf['auth_multisite_htpasswd'], + $this->config->conf['auth_multisite_serials'], + $this->config->conf['auth_multisite_secret'], + $this->config->conf['auth_multisite_login_url'] + ); $this->REMOTE_USER = $MSAUTH->check(); - if($this->REMOTE_USER !== null) + if ($this->REMOTE_USER !== null) { return; + } } - if($this->AUTH_ENABLED === TRUE && $this->REMOTE_USER === NULL){ - throw new Kohana_exception("error.remote_user_missing"); + if ($this->AUTH_ENABLED === true && $this->REMOTE_USER === null) { + throw new Kohana_exception('error.remote_user_missing'); } } + //end __construct() - public function __destruct() { - if($this->SOCKET !== NULL) { + + public function __destruct() + { + if ($this->SOCKET !== null) { socket_close($this->SOCKET); - $this->SOCKET = NULL; + $this->SOCKET = null; } } + //end __destruct() - public function connect(){ - $this->getSocketDetails($this->socketPath); + + public function connect() + { + $this->getSocketDetails($this->socketPath); $this->SOCKET = socket_create($this->socketDOMAIN, $this->socketTYPE, $this->socketPROTO); - if($this->SOCKET === FALSE) { - throw new Kohana_exception("error.livestatus_socket_error", socket_strerror(socket_last_error($this->SOCKET)), $this->socketPath); + if ($this->SOCKET === false) { + throw new Kohana_exception('error.livestatus_socket_error', socket_strerror(socket_last_error($this->SOCKET)), $this->socketPath); } - if($this->socketDOMAIN === AF_UNIX){ - $result = @socket_connect($this->SOCKET, $this->socketPATH); - }else{ - $result = @socket_connect($this->SOCKET, $this->socketHOST, $this->socketPORT); - } - if(!$result) { - throw new Kohana_exception("error.livestatus_socket_error", socket_strerror(socket_last_error($this->SOCKET)), $this->socketPath); + if ($this->socketDOMAIN === AF_UNIX) { + $result = @socket_connect($this->SOCKET, $this->socketPATH); + } else { + $result = @socket_connect($this->SOCKET, $this->socketHOST, $this->socketPORT); + } + if (!$result) { + throw new Kohana_exception('error.livestatus_socket_error', socket_strerror(socket_last_error($this->SOCKET)), $this->socketPath); } - } + //end connect() - private function queryLivestatus($query) { - if($this->SOCKET === NULL) { + + private function queryLivestatus($query) + { + if ($this->SOCKET === null) { $this->connect(); } - @socket_write($this->SOCKET, $query."\nOutputFormat: json\n\n"); + @socket_write($this->SOCKET, $query . "\nOutputFormat: json\n\n"); // Read 16 bytes to get the status code and body size - $read = @socket_read($this->SOCKET,2048); - if(!$read) { - throw new Kohana_exception("error.livestatus_socket_error", socket_strerror(socket_last_error($this->SOCKET))); + $read = @socket_read($this->SOCKET, 2048); + if (!$read) { + throw new Kohana_exception('error.livestatus_socket_error', socket_strerror(socket_last_error($this->SOCKET))); } - # print Kohana::debug("read ". $read); + // print Kohana::debug("read ". $read); // Catch problem while reading - if($read === false) { - throw new Kohana_exception("error.livestatus_socket_error", socket_strerror(socket_last_error($this->SOCKET))); + if ($read === false) { + throw new Kohana_exception('error.livestatus_socket_error', socket_strerror(socket_last_error($this->SOCKET))); } - + // Decode the json response $obj = json_decode(utf8_encode($read)); socket_close($this->SOCKET); - $this->SOCKET = NULL; + $this->SOCKET = null; return $obj; - } + //end queryLivestatus() - public function is_authorized($host = FALSE, $service = NULL){ - if($this->AUTH_ENABLED === FALSE){ - return TRUE; + + public function is_authorized($host = false, $service = null) + { + if ($this->AUTH_ENABLED === false) { + return true; } - if($host == "pnp-internal"){ - return TRUE; + if ($host == 'pnp-internal') { + return true; } - if($service === NULL || $service == "_HOST_" || $service == "Host Perfdata"){ - $users = explode(",", $this->config->conf['allowed_for_all_hosts']); + if ($service === null || $service == '_HOST_' || $service == 'Host Perfdata') { + $users = explode(',', $this->config->conf['allowed_for_all_hosts']); if (in_array($this->REMOTE_USER, $users)) { - return TRUE; + return true; } - $query = "GET hosts\nColumns: name\nFilter: name = $host\nAuthUser: ".$this->REMOTE_USER; + $query = "GET hosts\nColumns: name\nFilter: name = $host\nAuthUser: " . $this->REMOTE_USER; $result = $this->queryLivestatus($query); - }else{ - $users = explode(",", $this->config->conf['allowed_for_all_services']); + } else { + $users = explode(',', $this->config->conf['allowed_for_all_services']); if (in_array($this->REMOTE_USER, $users)) { - return TRUE; + return true; } - $query = "GET services\nColumns: host_name description\nFilter: host_name = $host\nFilter: description = $service\nAuthUser: ".$this->REMOTE_USER; + $query = "GET services\nColumns: host_name description\nFilter: host_name = $host\nFilter: description = $service\nAuthUser: " . $this->REMOTE_USER; $result = $this->queryLivestatus($query); } - if(sizeof($result) > 0){ - return TRUE; - }else{ - return FALSE; - } + return (!empty($result)); } + //end is_authorized() - public function getSocketDetails($string=FALSE){ - - if(preg_match('/^unix:(.*)$/',$string,$match) ){ - $this->socketDOMAIN = AF_UNIX; - $this->socketTYPE = SOCK_STREAM; - $this->socketPATH = $match[1]; - $this->socketPROTO = 0; - return; - } - if(preg_match('/^tcp:([a-zA-Z0-9-\.]+):([0-9]+)$/',$string,$match) ){ - $this->socketDOMAIN = AF_INET; - $this->socketTYPE = SOCK_STREAM; - $this->socketHOST = $match[1]; - $this->socketPORT = $match[2]; - $this->socketPROTO = SOL_TCP; - return; - } - # Fallback - if(preg_match('/^\/.*$/',$string,$match) ){ - $this->socketDOMAIN = AF_UNIX; - $this->socketTYPE = SOCK_STREAM; - $this->socketPATH = $string; - $this->socketPROTO = 0; - return; - } - return FALSE; - } + public function getSocketDetails($string = false) + { + if (preg_match('/^unix:(.*)$/', $string, $match)) { + $this->socketDOMAIN = AF_UNIX; + $this->socketTYPE = SOCK_STREAM; + $this->socketPATH = $match[1]; + $this->socketPROTO = 0; + return; + } + if (preg_match('/^tcp:([a-zA-Z0-9-\.]+):([0-9]+)$/', $string, $match)) { + $this->socketDOMAIN = AF_INET; + $this->socketTYPE = SOCK_STREAM; + $this->socketHOST = $match[1]; + $this->socketPORT = $match[2]; + $this->socketPROTO = SOL_TCP; + return; + } + // Fallback + if (preg_match('/^\/.*$/', $string, $match)) { + $this->socketDOMAIN = AF_UNIX; + $this->socketTYPE = SOCK_STREAM; + $this->socketPATH = $string; + $this->socketPROTO = 0; + return; + } + return false; + } + //end getSocketDetails() } +//end class diff --git a/share/pnp/application/models/auth_multisite.php b/share/pnp/application/models/auth_multisite.php index d4a3b41..f05e3be 100644 --- a/share/pnp/application/models/auth_multisite.php +++ b/share/pnp/application/models/auth_multisite.php @@ -1,13 +1,24 @@ -htpasswdPath = $htpasswdPath; $this->serialsPath = $serialsPath; $this->secretPath = $secretPath; @@ -16,96 +27,120 @@ class Auth_Multisite_Model { // When the auth.serial file exists, use this instead of the htpasswd // for validating the cookie. The structure of the file is equal, so // the same code can be used. - if(file_exists($this->serialsPath)) { + if (file_exists($this->serialsPath)) { $this->authFile = 'serial'; - - } elseif(file_exists($this->htpasswdPath)) { + } elseif (file_exists($this->htpasswdPath)) { $this->authFile = 'htpasswd'; - } else { - throw new Kohana_exception("error.auth_multisite_missing_htpasswd"); + throw new Kohana_exception('error.auth_multisite_missing_htpasswd'); } - if(!file_exists($this->secretPath)) { + if (!file_exists($this->secretPath)) { $this->redirectToLogin(); } } + //end __construct() - private function loadAuthFile($path) { - $creds = array(); - foreach(file($path) AS $line) { - if(strpos($line, ':') !== false) { + + private function loadAuthFile($path) + { + $creds = []; + foreach (file($path) as $line) { + if (strpos($line, ':') !== false) { list($username, $secret) = explode(':', $line, 2); - $creds[$username] = rtrim($secret); + $creds[$username] = rtrim($secret); } } return $creds; } + //end loadAuthFile() - private function loadSecret() { + + private function loadSecret() + { return trim(file_get_contents($this->secretPath)); } + //end loadSecret() - private function generateHash($username, $now, $user_secret) { + + private function generateHash($username, $now, $user_secret) + { $secret = $this->loadSecret(); return md5($username . $now . $user_secret . $secret); } + //end generateHash() - private function checkAuthCookie($cookieName) { - if(!isset($_COOKIE[$cookieName]) || $_COOKIE[$cookieName] == '') { + + private function checkAuthCookie($cookieName) + { + if (!isset($_COOKIE[$cookieName]) || $_COOKIE[$cookieName] == '') { throw new Exception(); } - list($username, $issueTime, $cookieHash) = explode(':', $_COOKIE[$cookieName], 3); + $cookie = $_COOKIE[$cookieName]; + if ($cookie[0] == '"') { + $cookie = trim($cookie, '"'); + } + list($username, $issueTime, $cookieHash) = explode(':', $cookie, 3); - if($this->authFile == 'htpasswd') + if ($this->authFile == 'htpasswd') { $users = $this->loadAuthFile($this->htpasswdPath); - else + } else { $users = $this->loadAuthFile($this->serialsPath); + } - if(!isset($users[$username])) { + if (!isset($users[$username])) { throw new Exception(); } $user_secret = $users[$username]; // Validate the hash - if($cookieHash != $this->generateHash($username, $issueTime, $user_secret)) { + if ($cookieHash != $this->generateHash($username, $issueTime, $user_secret)) { throw new Exception(); } // FIXME: Maybe renew the cookie here too - return $username; } + //end checkAuthCookie() - private function checkAuth() { + + private function checkAuth() + { // Loop all cookies trying to fetch a valid authentication // cookie for this installation - foreach(array_keys($_COOKIE) AS $cookieName) { - if(substr($cookieName, 0, 5) != 'auth_') { + foreach (array_keys($_COOKIE) as $cookieName) { + if (substr($cookieName, 0, 5) != 'auth_') { continue; } try { $name = $this->checkAuthCookie($cookieName); return $name; - } catch(Exception $e) {} + } catch (Exception $e) { + } } return ''; } + //end checkAuth() - private function redirectToLogin() { + + private function redirectToLogin() + { header('Location:' . $this->loginUrl . '?_origtarget=' . $_SERVER['REQUEST_URI']); } + //end redirectToLogin() - public function check() { + + public function check() + { $username = $this->checkAuth(); - if($username === '') { + if ($username === '') { $this->redirectToLogin(); exit(0); } return $username; } + //end check() } - -?> +//end class diff --git a/share/pnp/application/models/config.php b/share/pnp/application/models/config.php index 44e3d12..b671841 100644 --- a/share/pnp/application/models/config.php +++ b/share/pnp/application/models/config.php @@ -1,7 +1,13 @@ -get('h') != "" ) $conf['graph_height'] = intval($input->get('h')); - if($input->get('w') != "" ) $conf['graph_width'] = intval($input->get('w')); - if($input->get('graph_height') != "" ) $conf['graph_height'] = intval($input->get('graph_height')); - if($input->get('graph_width') != "" ) $conf['graph_width'] = intval($input->get('graph_width')); + if ($input->get('h') != "") { + $conf['graph_height'] = intval($input->get('h')); + } + if ($input->get('w') != "") { + $conf['graph_width'] = intval($input->get('w')); + } + if ($input->get('graph_height') != "") { + $conf['graph_height'] = intval($input->get('graph_height')); + } + if ($input->get('graph_width') != "") { + $conf['graph_width'] = intval($input->get('graph_width')); + } $this->conf = $conf; $this->views = $views; $this->scheme = $scheme; diff --git a/share/pnp/application/models/data.php b/share/pnp/application/models/data.php index 63b0e24..6a990b5 100644 --- a/share/pnp/application/models/data.php +++ b/share/pnp/application/models/data.php @@ -1,632 +1,678 @@ -config = new Config_Model(); + public $DS = []; + + public $MACRO = []; + + private $RRD = []; + + public $STRUCT = []; + + public $TIMERANGE = []; + + public $PAGE_DEF = []; + + public $PAGE_GRAPH = []; + + public $XPORT = ''; + + public $TEMPLATE_FILE = ''; + + public $GRAPH_TYPE = 'normal'; + + public $config = ''; + + public $auth = ''; + + + public function __construct() + { + $this->config = new Config_Model(); $this->config->read_config(); - $this->auth = new Auth_Model(); + $this->auth = new Auth_Model(); } +//end __construct() + /* - * Get All Special Templates - * - */ - public function getSpecialTemplates(){ - $conf = $this->config->conf; - $templates = array(); - if (is_dir($conf['special_template_dir'])){ + * Get All Special Templates + * + */ + public function getSpecialTemplates() + { + $conf = $this->config->conf; + $templates = []; + if (is_dir($conf['special_template_dir'])) { if ($dh = opendir($conf['special_template_dir'])) { while (($file = readdir($dh)) !== false) { - if ($file == "." || $file == "..") + if ($file == '.' || $file == '..') { continue; - if (!preg_match("/(.*)\.php$/", $file, $template)) + } + if (!preg_match('/(.*)\.php$/', $file, $template)) { continue; + } $templates[] = $template[1]; } } } - if(sizeof($templates) > 0){ + if (empty($templates)) { + return false; + } else { sort($templates); return $templates; - }else{ - return FALSE; } } +//end getSpecialTemplates() - public function getFirstSpecialTemplate(){ + + public function getFirstSpecialTemplate() + { $templates = $this->getSpecialTemplates(); - if($templates === FALSE){ - return FALSE; - }else{ + if ($templates === false) { + return false; + } else { return $templates[0]; } } - /* - * - * - */ - public function getHosts() { - $hosts = array(); - $conf = $this->config->conf; - $i = 0; - if (is_dir($conf['rrdbase'])) { - if ($dh = opendir($conf['rrdbase'])) { - while (($file = readdir($dh)) !== false) { - if ($file == "." || $file == ".." || $file == ".pnp-internal") - continue; - - if (is_file($conf['rrdbase'] . "/" . $file) ) - continue; +//end getFirstSpecialTemplate() - if($this->auth->is_authorized($file) === FALSE) - continue; - $stat = stat($conf['rrdbase'] . "/" . $file); - $age = (time() - $stat['mtime']); - $hosts[$i]['name'] = $file; - $hosts[$i]['sort'] = strtoupper($file); - if ($age < $conf['max_age']) { - $hosts[$i]['state'] = 'active'; - } else { - $hosts[$i]['state'] = 'inactive'; - } - $i++; - } - closedir($dh); - } else { - throw new Kohana_User_Exception('Perfdata Dir', "Can not open $path"); - } - } - if(sizeof($hosts)>0){ - # Obtain a list of columns - foreach ($hosts as $key => $row) { - $sort[$key] = $row['sort']; + public function getHosts() + { + $hosts = []; + $conf = $this->config->conf; + $i = 0; + if (is_dir($conf['rrdbase'])) { + if ($dh = opendir($conf['rrdbase'])) { + while (($file = readdir($dh)) !== false) { + if ($file == '.' || $file == '..' || $file == '.pnp-internal') { + continue; + } + + if (is_file($conf['rrdbase'] . '/' . $file)) { + continue; + } + + if ($this->auth->is_authorized($file) === false) { + continue; + } + + $stat = stat($conf['rrdbase'] . '/' . $file); + $age = (time() - $stat['mtime']); + $hosts[$i]['name'] = $file; + $hosts[$i]['sort'] = strtoupper($file); + if ($age < $conf['max_age']) { + $hosts[$i]['state'] = 'active'; + } else { + $hosts[$i]['state'] = 'inactive'; + } + $i++; + } +//end while + closedir($dh); + } else { + throw new Kohana_User_Exception('Perfdata Dir', "Can not open $path"); } - # Sort the data with volume descending, edition ascending - # Add $data as the last parameter, to sort by the common key +//end if + } +//end if + if (empty($hosts)) { + throw new Kohana_Exception('error.perfdata-dir-empty', $conf['rrdbase']); + } else { + // Obtain a list of columns + foreach ($hosts as $key => $row) { + $sort[$key] = $row['sort']; + } + // Sort the data with volume descending, edition ascending + // Add $data as the last parameter, to sort by the common key array_multisort($sort, SORT_ASC, $hosts); - }else{ - throw new Kohana_Exception('error.perfdata-dir-empty', $conf['rrdbase'] ); } return $hosts; } +//end getHosts() - /* - * - * - */ - function getRawServices($hostname) { - $services = array (); - $host = array(); + private function getRawServices($hostname) + { + $services = []; + $host = []; $conf = $this->config->conf; $i = 0; $path = $conf['rrdbase'] . $hostname; if (is_dir($path)) { if ($dh = opendir($path)) { - while ( ($file = readdir($dh) ) !== false) { - if ($file == "." || $file == "..") + while (($file = readdir($dh) ) !== false) { + if ($file == '.' || $file == '..') { continue; + } - if (!preg_match("/(.*)\.xml$/", $file, $servicedesc)) + if (!preg_match('/(.*)\.xml$/', $file, $servicedesc)) { continue; + } - $fullpath = $path . "/" . $file; - $stat = stat("$fullpath"); - $age = (time() - $stat['mtime']); - - $state = "active"; - if ($age > $conf['max_age']) { # 6Stunden - $state = "inactive"; + $fullpath = $path . '/' . $file; + $stat = stat("$fullpath"); + $age = (time() - $stat['mtime']); + + $state = 'active'; + if ($age > $conf['max_age']) { +// 6Stunden + $state = 'inactive'; } $services[$i]['state'] = $state; - $services[$i]['name'] = $servicedesc[1]; + $services[$i]['name'] = $servicedesc[1]; $i++; } +//end while } - }else{ - throw new Kohana_Exception('error.perfdata-dir-for-host', $path, $hostname ); +//end if + } else { + throw new Kohana_Exception('error.perfdata-dir-for-host', $path, $hostname); } - if( is_array($services) && sizeof($services) > 0){ - # Obtain a list of columns +//end if + if (is_array($services) && (!empty($services))) { + // Obtain a list of columns foreach ($services as $key => $row) { - $sort[$key] = $row['name']; + $sort[$key] = $row['name']; } - # Sort the data with volume descending, edition ascending - # Add $data as the last parameter, to sort by the common key + // Sort the data with volume descending, edition ascending + // Add $data as the last parameter, to sort by the common key array_multisort($sort, SORT_STRING, $services); - }else{ - throw new Kohana_Exception('error.host-perfdata-dir-empty', $path, $hostname ); - } + } else { + throw new Kohana_Exception('error.host-perfdata-dir-empty', $path, $hostname); + } return $services; } - /* - * - * - */ - function getServices($hostname) { - $services = array (); - $host = array(); +//end getRawServices() + + + public function getServices($hostname) + { + $services = []; + $host = []; $i = 0; $service_list = $this->getRawServices($hostname); - foreach( $service_list as $s ){ - if(!$this->readXML($hostname, $s['name'], FALSE)){ + foreach ($service_list as $s) { + if (!$this->readXML($hostname, $s['name'], false)) { continue; } - if($s['name'] == "_HOST_"){ + if ($s['name'] == '_HOST_') { // Check authorization - if($this->auth->is_authorized((string) $this->XML->NAGIOS_AUTH_HOSTNAME, "_HOST_") === FALSE) + if ($this->auth->is_authorized((string) $this->XML->NAGIOS_AUTH_HOSTNAME, '_HOST_') === false) { continue; - - $host[0]['name'] = "_HOST_"; - $host[0]['hostname'] = (string) $this->XML->NAGIOS_HOSTNAME; - $host[0]['state'] = $s['state']; - $host[0]['servicedesc'] = "Host Perfdata"; - $host[0]['is_multi'] = (string) $this->XML->DATASOURCE[0]->IS_MULTI[0]; - }else{ + } + + $host[0]['name'] = '_HOST_'; + $host[0]['hostname'] = (string) $this->XML->NAGIOS_HOSTNAME; + $host[0]['state'] = $s['state']; + $host[0]['servicedesc'] = 'Host Perfdata'; + $host[0]['is_multi'] = (string) $this->XML->DATASOURCE[0]->IS_MULTI[0]; + } else { // Check authorization - if($this->auth->is_authorized((string) $this->XML->NAGIOS_AUTH_HOSTNAME, (string) $this->XML->NAGIOS_AUTH_SERVICEDESC) === FALSE ) + if ($this->auth->is_authorized((string) $this->XML->NAGIOS_AUTH_HOSTNAME, (string) $this->XML->NAGIOS_AUTH_SERVICEDESC) === false) { continue; - - $services[$i]['name'] = $s['name']; + } + + $services[$i]['name'] = $s['name']; // Sorting check_multi - if( (string) $this->XML->NAGIOS_MULTI_PARENT == ""){ - $services[$i]['sort'] = strtoupper($s['name']); - }else{ - $services[$i]['sort'] = strtoupper((string) $this->XML->NAGIOS_MULTI_PARENT); - $services[$i]['sort'] .= (string) $this->XML->DATASOURCE[0]->IS_MULTI[0]; - $services[$i]['sort'] .= strtoupper($s['name']); + if ((string) $this->XML->NAGIOS_MULTI_PARENT == '') { + $services[$i]['sort'] = strtoupper($s['name']); + } else { + $services[$i]['sort'] = strtoupper((string) $this->XML->NAGIOS_MULTI_PARENT); + $services[$i]['sort'] .= (string) $this->XML->DATASOURCE[0]->IS_MULTI[0]; + $services[$i]['sort'] .= strtoupper($s['name']); } $services[$i]['state'] = $s['state']; $services[$i]['hostname'] = (string) $this->XML->NAGIOS_DISP_HOSTNAME; $services[$i]['servicedesc'] = (string) $this->XML->NAGIOS_DISP_SERVICEDESC; $services[$i]['is_multi'] = (string) $this->XML->DATASOURCE[0]->IS_MULTI[0]; } +//end if $i++; } - #print Kohana::debug($services); - if( is_array($services) && sizeof($services) > 0){ - # Obtain a list of columns +//end foreach + // print Kohana::debug($services); + if (is_array($services) && (!empty($services))) { + // Obtain a list of columns foreach ($services as $key => $row) { - $sort[$key] = $row['sort']; + $sort[$key] = $row['sort']; } - # Sort the data with volume descending, edition ascending - # Add $data as the last parameter, to sort by the common key + // Sort the data with volume descending, edition ascending + // Add $data as the last parameter, to sort by the common key array_multisort($sort, SORT_STRING, $services); - } - if(is_array($host) && sizeof($host) > 0 ){ + } + if (is_array($host) && (!empty($host))) { array_unshift($services, $host[0]); } return $services; } +//end getServices() - /* - * - * - */ - public function getFirstService($hostname) { - $conf = $this->config->conf; + + public function getFirstService($hostname) + { + $conf = $this->config->conf; $services = $this->getServices($hostname); foreach ($services as $srv) { - if ($srv['state'] == "active" ) { + if ($srv['state'] == 'active') { break; } } - if(sizeof($srv) == 0){ - throw new Kohana_Exception('error.get-first-service', $hostname ); + if (empty($srv)) { + throw new Kohana_Exception('error.get-first-service', $hostname); } return $srv['name']; } +//end getFirstService() - /* - * - * - */ - public function getFirstHost() { - $conf = $this->config->conf; + + public function getFirstHost() + { + $conf = $this->config->conf; $hosts = $this->getHosts(); foreach ($hosts as $host) { - if ($host['state'] == "active" ) { + if ($host['state'] == 'active') { break; } } - if(sizeof($host) == 0){ + if (empty($host)) { throw new Kohana_Exception('error.get-first-host'); } return $host['name']; } +//end getFirstHost() - /* - * - * - */ - public function readXML ($hostname, $servicedesc, $throw_exception=TRUE){ - $conf = $this->config->conf; - $xmlfile = $conf['rrdbase'].$hostname."/".$servicedesc.".xml"; - $xml = array(); + + public function readXML($hostname, $servicedesc, $throw_exception = true) + { + $conf = $this->config->conf; + $xmlfile = $conf['rrdbase'] . $hostname . '/' . $servicedesc . '.xml'; + $xml = []; if (file_exists($xmlfile)) { - libxml_use_internal_errors(TRUE); - libxml_clear_errors(TRUE); - if(! $xml = simplexml_load_file($xmlfile) ){; - if( $throw_exception == TRUE ){ + libxml_use_internal_errors(true); + libxml_clear_errors(); + if (! $xml = simplexml_load_file($xmlfile)) { + ; + if ($throw_exception == true) { $errors = '
    '; - foreach(libxml_get_errors() as $error) { - $errors .= $error->message."
    "; + foreach (libxml_get_errors() as $error) { + $errors .= $error->message . '
    '; } - throw new Kohana_Exception('error.xml-generic_error',$xmlfile, $errors); - }else{ - return FALSE; + throw new Kohana_Exception('error.xml-generic_error', $xmlfile, $errors); + } else { + return false; } } - $this->XML = array(); - $this->MACRO = array(); + $this->XML = []; + $this->MACRO = []; $this->MACRO['AUTH_SERVICEDESC'] = ''; - $this->MACRO['AUTH_HOSTNAME'] = ''; - $this->DS = array(); + $this->MACRO['AUTH_HOSTNAME'] = ''; + $this->DS = []; // Throw excaption without a valid structure version - if(!isset($xml->XML->VERSION) && $throw_exception == TRUE){ - throw new Kohana_Exception('error.xml-structure-without-version-tag',$xmlfile); + if (!isset($xml->XML->VERSION) && $throw_exception == true) { + throw new Kohana_Exception('error.xml-structure-without-version-tag', $xmlfile); } - if(!isset($xml->XML->VERSION) && $throw_exception == FALSE){ - return FALSE; + if (!isset($xml->XML->VERSION) && $throw_exception == false) { + return false; } - foreach ( $xml as $key=>$val ){ - if(preg_match('/^NAGIOS_(.*)$/', $key, $match)){ - #print $match[1]." => ".$val."\n"; - $key = $match[1]; + foreach ($xml as $key => $val) { + if (preg_match('/^NAGIOS_(.*)$/', $key, $match)) { + // print $match[1]." => ".$val."\n"; + $key = $match[1]; $this->MACRO[$key] = (string) $val; } } - $i=0; - foreach ( $xml->DATASOURCE as $datasource ){ - foreach ( $datasource as $key=>$val){ - #print "$key => $val\n"; - #$$key[$i] = (string) $val; + $i = 0; + foreach ($xml->DATASOURCE as $datasource) { + foreach ($datasource as $key => $val) { + // print "$key => $val\n"; + // $$key[$i] = (string) $val; $this->DS[$i][$key] = (string) $val; } - $i++; + $i++; } $this->XML = $xml; - return TRUE; - }else{ + return true; + } else { throw new Kohana_Exception('error.xml-not-found', $xmlfile); } +//end if } +//end readXML() - /* - * - * - */ - public function buildDataStruct ($host = FALSE, $service = FALSE, $view = NULL, $source = NULL){ - if($host === FALSE && $service === FALSE){ - return FALSE; + + public function buildDataStruct($host = false, $service = false, $view = null, $source = null) + { + if ($host === false && $service === false) { + return false; } $conf = $this->config->conf; /* * Special templates without Host/Service */ - if($host == '__special' ){ + if ($host == '__special') { // $service contains the template name - $this->includeTemplate($service,'special'); - }else{ - if( $this->readXML($host,$service) == FALSE ){ - throw new Kohana_Exception('error.xml-not-found', "Undefined error"); + $this->includeTemplate($service, 'special'); + } else { + if ($this->readXML($host, $service) == false) { + throw new Kohana_Exception('error.xml-not-found', 'Undefined error'); return false; } $this->includeTemplate($this->DS[0]['TEMPLATE']); } - if(isset($this->TIMERANGE['type']) && $this->TIMERANGE['type'] == "start-end"){ + if (isset($this->TIMERANGE['type']) && $this->TIMERANGE['type'] == 'start-end') { $view = intval($view); - $i=0; - foreach( $this->RRD['def'] as $key=>$val){ - if( ! is_null($source) && $source != $key ){ + $i = 0; + foreach ($this->RRD['def'] as $key => $val) { + if (! is_null($source) && $source != $key) { continue; } - $tmp_struct = array(); + $tmp_struct = []; $tmp_struct['LEVEL'] = $i; $tmp_struct['VIEW'] = $view; - $tmp_struct['TEMPLATE_FILE'] = $this->TEMPLATE_FILE;; - $tmp_struct['SOURCE'] = $key; - $tmp_struct['RRD_CALL'] = $this->TIMERANGE['cmd'] . " ". $this->RRD['opt'][$key] . " " . $this->RRD['def'][$key]; - $tmp_struct['TIMERANGE'] = $this->TIMERANGE; - $tmp_struct['GRAPH_WIDTH'] = $this->getGraphDimensions('width', $tmp_struct['RRD_CALL']); - $tmp_struct['GRAPH_HEIGHT'] = $this->getGraphDimensions('height', $tmp_struct['RRD_CALL']); - if(isset($this->RRD['ds_name'][$key]) ){ - $tmp_struct['ds_name'] = $this->RRD['ds_name'][$key]; - }elseif(array_key_exists($i, $this->DS)){ - $tmp_struct['ds_name'] = $this->DS[$i]['NAME']; - }else{ - $tmp_struct['ds_name'] = "UNDEF"; + $tmp_struct['TEMPLATE_FILE'] = $this->TEMPLATE_FILE; + ; + $tmp_struct['SOURCE'] = $key; + $tmp_struct['RRD_CALL'] = $this->TIMERANGE['cmd'] . ' ' . $this->RRD['opt'][$key] . ' ' . $this->RRD['def'][$key]; + $tmp_struct['TIMERANGE'] = $this->TIMERANGE; + $tmp_struct['GRAPH_WIDTH'] = $this->getGraphDimensions('width', $tmp_struct['RRD_CALL']); + $tmp_struct['GRAPH_HEIGHT'] = $this->getGraphDimensions('height', $tmp_struct['RRD_CALL']); + if (isset($this->RRD['ds_name'][$key])) { + $tmp_struct['ds_name'] = $this->RRD['ds_name'][$key]; + } elseif (array_key_exists($i, $this->DS)) { + $tmp_struct['ds_name'] = $this->DS[$i]['NAME']; + } else { + $tmp_struct['ds_name'] = 'UNDEF'; } - $tmp_struct['MACRO'] = $this->MACRO; - if(isset($this->XML->XML->VERSION)){ - $tmp_struct['VERSION'] = pnp::xml_version_check( (string) $this->XML->XML->VERSION); - }else{ - $tmp_struct['VERSION'] = pnp::xml_version_check("0"); + $tmp_struct['MACRO'] = $this->MACRO; + if (isset($this->XML->XML->VERSION)) { + $tmp_struct['VERSION'] = pnp::xml_version_check((string) $this->XML->XML->VERSION); + } else { + $tmp_struct['VERSION'] = pnp::xml_version_check('0'); } $this->addToDataStruct($tmp_struct); $i++; } - return; +//end foreach + return; } - if( $view === ""){ +//end if + if ($view === '') { $v = 0; - foreach($this->config->views as $view_key=>$view_val){ - $i=0; - foreach( $this->RRD['def'] as $key=>$val){ - if( ! is_null($source) && $source != $key ){ + foreach ($this->config->views as $view_key => $view_val) { + $i = 0; + foreach ($this->RRD['def'] as $key => $val) { + if (! is_null($source) && $source != $key) { continue; } - $tmp_struct = array(); + $tmp_struct = []; $tmp_struct['LEVEL'] = $i; $tmp_struct['VIEW'] = $view_key; - $tmp_struct['TEMPLATE_FILE'] = $this->TEMPLATE_FILE;; - $tmp_struct['SOURCE'] = $key; - $tmp_struct['RRD_CALL'] = $this->TIMERANGE[$v]['cmd'] . " " . $this->RRD['opt'][$key] . " " . $this->RRD['def'][$key]; - $tmp_struct['GRAPH_WIDTH'] = $this->getGraphDimensions('width', $tmp_struct['RRD_CALL']); - $tmp_struct['GRAPH_HEIGHT'] = $this->getGraphDimensions('height', $tmp_struct['RRD_CALL']); - if(isset($this->RRD['ds_name'][$key]) ){ - $tmp_struct['ds_name'] = $this->RRD['ds_name'][$key]; - }elseif(array_key_exists($i, $this->DS)){ - $tmp_struct['ds_name'] = $this->DS[$i]['NAME']; - }else{ - $tmp_struct['ds_name'] = "UNDEF"; + $tmp_struct['TEMPLATE_FILE'] = $this->TEMPLATE_FILE; + ; + $tmp_struct['SOURCE'] = $key; + $tmp_struct['RRD_CALL'] = $this->TIMERANGE[$v]['cmd'] . ' ' . $this->RRD['opt'][$key] . ' ' . $this->RRD['def'][$key]; + $tmp_struct['GRAPH_WIDTH'] = $this->getGraphDimensions('width', $tmp_struct['RRD_CALL']); + $tmp_struct['GRAPH_HEIGHT'] = $this->getGraphDimensions('height', $tmp_struct['RRD_CALL']); + if (isset($this->RRD['ds_name'][$key])) { + $tmp_struct['ds_name'] = $this->RRD['ds_name'][$key]; + } elseif (array_key_exists($i, $this->DS)) { + $tmp_struct['ds_name'] = $this->DS[$i]['NAME']; + } else { + $tmp_struct['ds_name'] = 'UNDEF'; } - $tmp_struct['TIMERANGE'] = $this->TIMERANGE[$v]; - $tmp_struct['MACRO'] = $this->MACRO; - if(isset($this->XML->XML->VERSION)){ - $tmp_struct['VERSION'] = pnp::xml_version_check( (string) $this->XML->XML->VERSION); - }else{ - $tmp_struct['VERSION'] = pnp::xml_version_check("0"); + $tmp_struct['TIMERANGE'] = $this->TIMERANGE[$v]; + $tmp_struct['MACRO'] = $this->MACRO; + if (isset($this->XML->XML->VERSION)) { + $tmp_struct['VERSION'] = pnp::xml_version_check((string) $this->XML->XML->VERSION); + } else { + $tmp_struct['VERSION'] = pnp::xml_version_check('0'); } $this->addToDataStruct($tmp_struct); $i++; } - $v++; +//end foreach + $v++; } - }else{ +//end foreach + } else { $view = intval($view); - $i=0; - foreach( $this->RRD['def'] as $key=>$val){ - if( ! is_null($source) && $source != $key ){ + $i = 0; + foreach ($this->RRD['def'] as $key => $val) { + if (! is_null($source) && $source != $key) { continue; } - $tmp_struct = array(); + $tmp_struct = []; $tmp_struct['LEVEL'] = $i; $tmp_struct['VIEW'] = $view; - $tmp_struct['TEMPLATE_FILE'] = $this->TEMPLATE_FILE;; - $tmp_struct['SOURCE'] = $key; - $tmp_struct['RRD_CALL'] = $this->TIMERANGE[$view]['cmd'] . " ". $this->RRD['opt'][$key] . " " . $this->RRD['def'][$key]; - $tmp_struct['TIMERANGE'] = $this->TIMERANGE[$view]; - $tmp_struct['GRAPH_WIDTH'] = $this->getGraphDimensions('width', $tmp_struct['RRD_CALL']); - $tmp_struct['GRAPH_HEIGHT'] = $this->getGraphDimensions('height', $tmp_struct['RRD_CALL']); - if(isset($this->RRD['ds_name'][$key]) ){ - $tmp_struct['ds_name'] = $this->RRD['ds_name'][$key]; - }elseif(array_key_exists($i, $this->DS)){ - $tmp_struct['ds_name'] = $this->DS[$i]['NAME']; - }else{ - $tmp_struct['ds_name'] = "UNDEF"; + $tmp_struct['TEMPLATE_FILE'] = $this->TEMPLATE_FILE; + ; + $tmp_struct['SOURCE'] = $key; + $tmp_struct['RRD_CALL'] = $this->TIMERANGE[$view]['cmd'] . ' ' . $this->RRD['opt'][$key] . ' ' . $this->RRD['def'][$key]; + $tmp_struct['TIMERANGE'] = $this->TIMERANGE[$view]; + $tmp_struct['GRAPH_WIDTH'] = $this->getGraphDimensions('width', $tmp_struct['RRD_CALL']); + $tmp_struct['GRAPH_HEIGHT'] = $this->getGraphDimensions('height', $tmp_struct['RRD_CALL']); + if (isset($this->RRD['ds_name'][$key])) { + $tmp_struct['ds_name'] = $this->RRD['ds_name'][$key]; + } elseif (array_key_exists($i, $this->DS)) { + $tmp_struct['ds_name'] = $this->DS[$i]['NAME']; + } else { + $tmp_struct['ds_name'] = 'UNDEF'; } - $tmp_struct['MACRO'] = $this->MACRO; - if(isset($this->XML->XML->VERSION)){ - $tmp_struct['VERSION'] = pnp::xml_version_check( (string) $this->XML->XML->VERSION); - }else{ - $tmp_struct['VERSION'] = pnp::xml_version_check("0"); + $tmp_struct['MACRO'] = $this->MACRO; + if (isset($this->XML->XML->VERSION)) { + $tmp_struct['VERSION'] = pnp::xml_version_check((string) $this->XML->XML->VERSION); + } else { + $tmp_struct['VERSION'] = pnp::xml_version_check('0'); } $this->addToDataStruct($tmp_struct); $i++; } +//end foreach } +//end if } +//end buildDataStruct() - /* - * - * - */ - private function addToDataStruct ($data=FALSE) { - if($data === FALSE) - return FALSE; + + private function addToDataStruct($data = false) + { + if ($data === false) { + return false; + } array_push($this->STRUCT, $data); - } + } +//end addToDataStruct() - /* - * - * - */ - private function includeTemplate($template=FALSE,$type='normal'){ - if($template===FALSE){ - return FALSE; + + private function includeTemplate($template = false, $type = 'normal') + { + if ($template === false) { + return false; } - $this->RRD = array(); + $this->RRD = []; /* - * Normal PNP Templates - */ - if($type == 'normal'){ - $template_file = $this->findTemplate( $template ); + * Normal PNP Templates + */ + if ($type == 'normal') { + $template_file = $this->findTemplate($template); $this->TEMPLATE_FILE = $template_file; - $hostname = $this->MACRO['HOSTNAME']; - $servicedesc = $this->MACRO['SERVICEDESC']; - $TIMERANGE = $this->TIMERANGE; - }elseif($type == 'special'){ - $template_file = $this->findTemplate( $template, $type ); + $hostname = $this->MACRO['HOSTNAME']; + $servicedesc = $this->MACRO['SERVICEDESC']; + $TIMERANGE = $this->TIMERANGE; + } elseif ($type == 'special') { + $template_file = $this->findTemplate($template, $type); $TIMERANGE = $this->TIMERANGE; } - $def = FALSE; - $opt = FALSE; - $ds_name = FALSE; + $def = false; + $opt = false; + $ds_name = false; /* - * 0.4.x Template compatibility - */ - foreach($this->DS as $key=>$val ){ + * 0.4.x Template compatibility + */ + foreach ($this->DS as $key => $val) { $key++; - foreach(array_keys($val) as $tag){ + foreach (array_keys($val) as $tag) { ${$tag}[$key] = $val[$tag]; } } - foreach($this->MACRO as $key=>$val ){ - ${"NAGIOS_".$key} = $val; + foreach ($this->MACRO as $key => $val) { + ${'NAGIOS_' . $key} = $val; } - if(isset($RRDFILE[1])){ + if (isset($RRDFILE[1])) { $rrdfile = $RRDFILE[1]; } // Include template - if($template_file == FALSE){ + if ($template_file == false) { throw new Kohana_Exception('error.no-templates-found'); - }else{ + } else { ob_start(); - include($template_file); + include $template_file; ob_end_clean(); } // Compatibility for very old Templates - if(!is_array($def) && $def != FALSE){ + if (!is_array($def) && $def != false) { $tmp[1] = $def; - $def = $tmp; - } - if(!is_array($opt) && $opt != FALSE){ - $tmp[1] = $opt; - $opt = $tmp; + $def = $tmp; } - if(!is_array($ds_name) && $ds_name != FALSE){ - $tmp[1] = $ds_name; + if (!is_array($opt) && $opt != false) { + $tmp[1] = $opt; + $opt = $tmp; + } + if (!is_array($ds_name) && $ds_name != false) { + $tmp[1] = $ds_name; $ds_name = $tmp; } - // - if($def != FALSE){ + if ($def != false) { $this->RRD['def'] = $this->array_reindex($def); - }else{ + } else { throw new Kohana_Exception('error.template-without-def', $template_file); } - if($opt != FALSE ){ + if ($opt != false) { $this->RRD['opt'] = $this->array_reindex($opt); - }else{ + } else { throw new Kohana_Exception('error.template-without-opt', $template_file); } - if( $ds_name != FALSE ){ + if ($ds_name != false) { $this->RRD['ds_name'] = $this->array_reindex($ds_name); } - return TRUE; + return true; } +//end includeTemplate() - # - # - # - private function getGraphDimensions($search, $command){ - if($search == 'width'){ - if(preg_match_all('/(-w|--width|--width=)\s([0-9]+)\s/i',$command,$match)){ - $value = array_pop($match[2]); + + private function getGraphDimensions($search, $command) + { + if ($search == 'width') { + if (preg_match_all('/(-w|--width|--width=)\s([0-9]+)\s/i', $command, $match)) { + $value = array_pop($match[2]); return $value; - }else{ + } else { return $this->config->conf['graph_width']; } } - if($search == 'height'){ - if(preg_match_all('/(-h|--height|--height=)\s([0-9]+)\s/i',$command,$match)){ - $value = array_pop($match[2]); + if ($search == 'height') { + if (preg_match_all('/(-h|--height|--height=)\s([0-9]+)\s/i', $command, $match)) { + $value = array_pop($match[2]); return $value; - }else{ + } else { return $this->config->conf['graph_height']; } } - return FALSE; + return false; } - # - # - # - private function array_reindex($data){ - $i=0; - foreach($data as $d){ +//end getGraphDimensions() + + + private function array_reindex($data) + { + $i = 0; + foreach ($data as $d) { $tmp[$i] = $d; - $i++; + $i++; } return $tmp; } - - /* - * - * - */ - public function findTemplate($template,$type='normal'){ +//end array_reindex() + + + public function findTemplate($template, $type = 'normal') + { $conf = $this->config->conf; /* * Normal templates */ - if($type == 'normal'){ - // Build a list of directories to search for templates - $template_dirs = array(); - if(array_key_exists('template_dirs', $this->config->conf)){ - foreach($this->config->conf['template_dirs'] as $dir){ + if ($type == 'normal') { + // Build a list of directories to search for templates + $template_dirs = []; + if (array_key_exists('template_dirs', $this->config->conf)) { + foreach ($this->config->conf['template_dirs'] as $dir) { $template_dirs[] = $dir; } - } - foreach(Kohana::config('core.template_dirs') as $dir){ + } + foreach (Kohana::config('core.template_dirs') as $dir) { $template_dirs[] = $dir; } - #throw new Kohana_Exception(print_r($template_dirs,TRUE)); - foreach($template_dirs as $dir){ - $match = $this->findRecursiveTemplate($template,$dir); - if($match != FALSE){ + // throw new Kohana_Exception(print_r($template_dirs,TRUE)); + foreach ($template_dirs as $dir) { + $match = $this->findRecursiveTemplate($template, $dir); + if ($match != false) { return $match; } } /* * Fallback to default templates */ - foreach($template_dirs as $dir){ - $match = $this->findRecursiveTemplate('default',$dir); - if($match != FALSE){ + foreach ($template_dirs as $dir) { + $match = $this->findRecursiveTemplate('default', $dir); + if ($match != false) { return $match; } } - return FALSE; + return false; } +//end if /* * Special Templates */ - if($type == 'special'){ + if ($type == 'special') { if (is_readable($conf['special_template_dir'] . '/' . $template . '.php')) { - $template_file = $conf['special_template_dir'].'/' . $template . '.php'; - }else{ + $template_file = $conf['special_template_dir'] . '/' . $template . '.php'; + } else { throw new Kohana_Exception("Special Template '$template' not found"); } return $template_file; } } +//end findTemplate() - /* - * - * - */ - function findRecursiveTemplate($template, $dir) { - if(!is_readable($dir)){ - return FALSE; + + private function findRecursiveTemplate($template, $dir) + { + if (!is_readable($dir)) { + return false; } - $template_file = ""; - $r_template_file = ""; - $r_template = ""; - $recursive = explode("_", $template); - if($this->config->conf['enable_recursive_template_search'] == 1){ + $template_file = ''; + $r_template_file = ''; + $r_template = ''; + $recursive = explode('_', $template); + if ($this->config->conf['enable_recursive_template_search'] == 1) { $i = 0; foreach ($recursive as $value) { if ($i == 0) { @@ -640,280 +686,341 @@ class Data_Model extends System_Model } $i++; } - if($r_template_file != ""){ + if ($r_template_file != '') { return $r_template_file; - }else{ - return FALSE; + } else { + return false; } - }else{ + } else { $file = $dir . '/' . $template . '.php'; if (is_readable($file)) { return $file; - }else{ - return FALSE; + } else { + return false; } } +//end if } +//end findRecursiveTemplate() - public function getTimeRange($start=FALSE ,$end=FALSE ,$view="") { - if($end != FALSE){ + + public function getTimeRange($start = false, $end = false, $view = '') + { + if ($end != false) { // we are in a custom timerange - if(!is_numeric($end)){ + if (!is_numeric($end)) { $timestamp = strtotime($end); - if(!$timestamp){ + if (!$timestamp) { throw new Kohana_User_Exception('Wrong Format', "End -> $end"); - }else{ + } else { $end = $timestamp; } } - }else{ + } else { $end = time(); } - if($start != FALSE ){ + if ($start != false) { // we are in a custom timerange - if(!is_numeric($start)){ + if (!is_numeric($start)) { $timestamp = strtotime($start); - if(!$timestamp){ + if (!$timestamp) { throw new Kohana_User_Exception('Wrong Format', "Start -> $start"); - }else{ + } else { $start = $timestamp; } } } - if($start && $end){ + if ($start && $end) { $timerange['title'] = Kohana::lang('common.timerange-selector-link'); $timerange['start'] = $start; - $timerange['f_start'] = date($this->config->conf['date_fmt'],$start); + $timerange['f_start'] = date($this->config->conf['date_fmt'], $start); $timerange['end'] = $end; - $timerange['f_end'] = date($this->config->conf['date_fmt'],$end); - $timerange['cmd'] = " --start $start --end $end "; - $timerange['type'] = "start-end"; - $this->TIMERANGE = $timerange; + $timerange['f_end'] = date($this->config->conf['date_fmt'], $end); + $timerange['cmd'] = $this->buildViewCmd(false, $start, $end); + $timerange['type'] = 'start-end'; + $this->TIMERANGE = $timerange; return; } - - $view=intval( pnp::clean($view) ); - if($view >= sizeof($this->config->views)){ - $view = 1; - } - if(!$end){ - $end = time(); - }elseif(!is_numeric($end)){ - $timestamp = strtotime($end); - if(!$timestamp){ + $view = intval(pnp::clean($view)); + if ($view >= count($this->config->views)) { + $view = 1; + } + + if (!$end) { + $end = time(); + } elseif (!is_numeric($end)) { + $timestamp = strtotime($end); + if (!$timestamp) { throw new Kohana_User_Exception('Wrong Format', "$end"); - }else{ - $end = $timestamp; - } - }else{ - $end = $end; - } + } else { + $end = $timestamp; + } + } else { + $end = $end; + } - if(!$start){ - $start = ( $end - $this->config->views[$view]['start']); - }elseif(!is_numeric($start)){ - $timestamp = strtotime($start); - if(!$timestamp){ + if (!$start) { + $start = ( $end - $this->config->views[$view]['start']); + } elseif (!is_numeric($start)) { + $timestamp = strtotime($start); + if (!$timestamp) { throw new Kohana_User_Exception('Wrong Format', "$start"); - }else{ - $start = $timestamp; - } - }else{ + } else { + $start = $timestamp; + } + } else { $start = pnp::clean($start); - } + } - if($start >= $end){ - //Fixme i18n - throw new Kohana_User_Exception('Wrong Timerange', "start >= end"); - } + if ($start >= $end) { + // Fixme i18n + throw new Kohana_User_Exception('Wrong Timerange', 'start >= end'); + } $timerange['title'] = $this->config->views[$view]['title']; $timerange['start'] = $start; - $timerange['f_start'] = date($this->config->conf['date_fmt'],$start); + $timerange['f_start'] = date($this->config->conf['date_fmt'], $start); $timerange['end'] = $end; - $timerange['f_end'] = date($this->config->conf['date_fmt'],$end); - $timerange['cmd'] = " --start $start --end $end "; - $timerange['type'] = "views"; - for ($i = 0; $i < sizeof($this->config->views); $i++) { - $timerange[$i]['title'] = $this->config->views[$i]['title']; - $timerange[$i]['start'] = $end - $this->config->views[$i]['start']; - $timerange[$i]['f_start'] = date($this->config->conf['date_fmt'],$end - $this->config->views[$i]['start']); - $timerange[$i]['end'] = $end; - $timerange[$i]['f_end'] = date($this->config->conf['date_fmt'],$end); - $timerange[$i]['cmd'] = " --start " . ($end - $this->config->views[$i]['start']) . " --end $end" ; - } + $timerange['f_end'] = date($this->config->conf['date_fmt'], $end); + $timerange['cmd'] = $this->buildViewCmd($view, $start, $end); + $timerange['type'] = 'views'; + for ($i = 0; $i < count($this->config->views); $i++) { + $timerange[$i]['title'] = $this->config->views[$i]['title']; + $timerange[$i]['start'] = ($end - $this->config->views[$i]['start']); + $timerange[$i]['f_start'] = date($this->config->conf['date_fmt'], ($end - $this->config->views[$i]['start'])); + $timerange[$i]['end'] = $end; + $timerange[$i]['f_end'] = date($this->config->conf['date_fmt'], $end); + $timerange[$i]['cmd'] = $this->buildViewCmd($i, ($end - $this->config->views[$i]['start']), $end); + $timerange[$i]['type'] = 'views'; + } $this->TIMERANGE = $timerange; } +//end getTimeRange() - public function buildBasketStruct($basket,$view = NULL){ - if(is_array($basket) && sizeof($basket) > 0){ - if($view == ""){ + + public function buildViewCmd($view = false, $start = false, $end = false) + { + // abstract creation of RRDtool options string, so we can add more features to a view; + // implemented in this file by replacing cmd builds containing '--start' + if ($view !== false && !array_key_exists($view, $this->config->views)) { + $view = 1; + } + $view = $this->config->views[$view]; + + $cmd = ''; + if ($start !== false) { + $cmd .= " --start $start"; + } elseif (array_key_exists('start', $view)) { + $cmd .= (' --start ' . $view['start']); + } + if ($end !== false) { + $cmd .= " --end $end"; + } elseif (array_key_exists('end', $view)) { + $cmd .= (' --end ' . $view['end']); + } + if (array_key_exists('extra_args', $view)) { + $cmd .= (' ' . $view['extra_args']); + } + + return "$cmd "; + } +//end buildViewCmd() + + + public function buildBasketStruct($basket, $view = null) + { + if (is_array($basket) && (!empty($basket))) { + if ($view == '') { $views = array_keys($this->config->views); - }else{ - $views = array($view); + } else { + $views = [$view]; } - foreach($views as $view){ - foreach($basket as $item){ - # explode host::service::source - $slices = explode("::",$item); - if(sizeof($slices) == 2) + foreach ($views as $view) { + foreach ($basket as $item) { + // explode host::service::source + $slices = explode('::', $item); + if (count($slices) == 2) { $this->buildDataStruct($slices[0], $slices[1], $view); - if(sizeof($slices) == 3) + } + if (count($slices) == 3) { $this->buildDataStruct($slices[0], $slices[1], $view, $slices[2]); + } } - # break on custom time ranges - if(isset($this->TIMERANGE['type']) && $this->TIMERANGE['type'] == "start-end"){ + // break on custom time ranges + if (isset($this->TIMERANGE['type']) && $this->TIMERANGE['type'] == 'start-end') { break; } } } +//end if } +//end buildBasketStruct() - public function buildPageStruct($page,$view){ - $servicelist = array(); + + public function buildPageStruct($page, $view) + { + $servicelist = []; $this->parse_page_cfg($page); $hosts = $this->getHostsByPage(); - # No regex so we keep the order defined by config - if($this->PAGE_DEF['use_regex'] == 0){ - #Loop through graph definitions - foreach($this->PAGE_GRAPH as $graph){ - $hosts_to_search_for = explode(",", $graph['host_name']); - foreach($hosts_to_search_for as $host){ - if(in_array($host, $hosts)){ + // No regex so we keep the order defined by config + if ($this->PAGE_DEF['use_regex'] == 0) { + // Loop through graph definitions + foreach ($this->PAGE_GRAPH as $graph) { + $hosts_to_search_for = explode(',', $graph['host_name']); + foreach ($hosts_to_search_for as $host) { + if (in_array($host, $hosts)) { $services = $this->getServices($host); - foreach($services as $service) { + foreach ($services as $service) { // search for definition - $data = $this->filterServiceByPage($graph,$host,$service); - if($data){ - $servicelist[] = array( 'host' => $host, 'service' => $service['name'], 'source' => $data['source']); - + $data = $this->filterServiceByPage($graph, $host, $service); + if ($data) { + $servicelist[] = [ + 'host' => $host, + 'service' => $service['name'], + 'source' => $data['source'], + ]; } } - } + } } } - }else{ - foreach($hosts as $host){ + } else { + foreach ($hosts as $host) { $services = $this->getServices($host); - foreach($services as $service) { + foreach ($services as $service) { // search for definition - $data = $this->filterServiceByPage($this->PAGE_GRAPH,$host,$service); - if($data){ - $servicelist[] = array( 'host' => $host, 'service' => $service['name'], 'source' => $data['source']); + $data = $this->filterServiceByPage($this->PAGE_GRAPH, $host, $service); + if ($data) { + $servicelist[] = [ + 'host' => $host, + 'service' => $service['name'], + 'source' => $data['source'], + ]; } } } } - #print Kohana::debug($servicelist); - if(sizeof($servicelist) > 0 ){ - foreach($servicelist as $s){ - $this->buildDataStruct($s['host'],$s['service'],$view,$s['source']); +//end if + // print Kohana::debug($servicelist); + if (empty($servicelist)) { + $this->ERROR = 'ERROR: ' . Kohana::lang('error.no-data-for-page', $page . '.cfg'); + } else { + foreach ($servicelist as $s) { + $this->buildDataStruct($s['host'], $s['service'], $view, $s['source']); } - }else{ - $this->ERROR = "ERROR: ". Kohana::lang('error.no-data-for-page', $page.".cfg" ); } } +//end buildPageStruct() - public function parse_page_cfg($page){ - $page_cfg = $this->config->conf['page_dir'].$page.".cfg"; - if(is_readable($page_cfg)){ + public function parse_page_cfg($page) + { + $page_cfg = $this->config->conf['page_dir'] . $page . '.cfg'; + if (is_readable($page_cfg)) { $data = file($page_cfg); - }else{ - throw new Kohana_Exception('error.page-not-readable', $page.".cfg" ); + } else { + throw new Kohana_Exception('error.page-not-readable', $page . '.cfg'); } - $l = 0; - $line = ""; - $tag = ""; - $inside=0; + $l = 0; + $line = ''; + $tag = ''; + $inside = 0; $this->PAGE_DEF['page_name'] = 'UNDEF'; $this->PAGE_DEF['use_regex'] = 0; - $this->PAGE_GRAPH = array(); - $allowed_tags = array("page", "graph"); - foreach($data as $line){ - if(preg_match('/(^#|^;)/',$line)) { + $this->PAGE_GRAPH = []; + $allowed_tags = [ + 'page', + 'graph', + ]; + foreach ($data as $line) { + if (preg_match('/(^#|^;)/', $line)) { continue; } - preg_match('/define\s+(\w+)\W+{/' ,$line, $tag); - if(isset($tag[1]) && in_array($tag[1],$allowed_tags)){ + preg_match('/define\s+(\w+)\W+{/', $line, $tag); + if (isset($tag[1]) && in_array($tag[1], $allowed_tags)) { $inside = 1; - $t = $tag[1]; + $t = $tag[1]; $l++; continue; } - if(preg_match('/\s?(\w+)\s+([^#]+)(#.*)?$/',$line, $key) && $inside == 1){ - $k=strtolower($key[1]); - $v=$key[2]; - if($t=='page'){ + if (preg_match('/\s?(\w+)\s+([^#]+)(#.*)?$/', $line, $key) && $inside == 1) { + $k = strtolower($key[1]); + $v = $key[2]; + if ($t == 'page') { $this->PAGE_DEF[$k] = trim($v); - }elseif($t=='graph'){ + } elseif ($t == 'graph') { $this->PAGE_GRAPH[$l][$k] = trim($v); } } - if(preg_match('/}/',$line)){ - $inside=0; - $t = ""; + if (preg_match('/}/', $line)) { + $inside = 0; + $t = ''; continue; } } +//end foreach } +//end parse_page_cfg() - /* - * - */ - public function getHostsByPage(){ - $hosts = $this->getHosts(); - $new_hosts = array(); - foreach( $hosts as $host){ - if($host['state'] == "inactive"){ + + public function getHostsByPage() + { + $hosts = $this->getHosts(); + $new_hosts = []; + foreach ($hosts as $host) { + if ($host['state'] == 'inactive') { continue; } - if($tmp = $this->filterHostByPage($host['name'])){ + if ($tmp = $this->filterHostByPage($host['name'])) { $new_hosts[] = $tmp; } } return $new_hosts; } - /* - * - */ - private function filterHostByPage($host){ - if(isset($this->PAGE_DEF['use_regex']) && $this->PAGE_DEF['use_regex'] == 1){ +//end getHostsByPage() + + + private function filterHostByPage($host) + { + if (isset($this->PAGE_DEF['use_regex']) && $this->PAGE_DEF['use_regex'] == 1) { // Search Host by regex - foreach( $this->PAGE_GRAPH as $g ){ - if(isset($g['host_name']) && preg_match('/'.$g['host_name'].'/',$host)){ + foreach ($this->PAGE_GRAPH as $g) { + if (isset($g['host_name']) && preg_match('/' . $g['host_name'] . '/', $host)) { return $host; } } - }else{ - foreach( $this->PAGE_GRAPH as $g ){ - $hosts_to_search_for = explode(",", $g['host_name']); - if(isset($g['host_name']) && in_array($host ,$hosts_to_search_for) ){ + } else { + foreach ($this->PAGE_GRAPH as $g) { + $hosts_to_search_for = explode(',', $g['host_name']); + if (isset($g['host_name']) && in_array($host, $hosts_to_search_for)) { return $host; } } } - return FALSE; + return false; } +//end filterHostByPage() - private function filterServiceByPage($g,$host,$service){ - $data = array(); - if(isset($this->PAGE_DEF['use_regex']) && $this->PAGE_DEF['use_regex'] == 1){ + + private function filterServiceByPage($g, $host, $service) + { + $data = []; + if (isset($this->PAGE_DEF['use_regex']) && $this->PAGE_DEF['use_regex'] == 1) { // Search Host by regex - foreach( $this->PAGE_GRAPH as $g ){ - if(isset($g['host_name']) && preg_match('/'.$g['host_name'].'/',$host)){ - if(isset($g['service_desc']) && preg_match('/'.$g['service_desc'].'/',$service['name'])){ + foreach ($this->PAGE_GRAPH as $g) { + if (isset($g['host_name']) && preg_match('/' . $g['host_name'] . '/', $host)) { + if (isset($g['service_desc']) && preg_match('/' . $g['service_desc'] . '/', $service['name'])) { $data['service_desc'] = $g['service_desc']; - $data['host_name'] = $g['host_name']; - $data['source'] = NULL; - // if we only want a single image - if(isset($g['source'])){ - $this->readXML($host,$service['name']); + $data['host_name'] = $g['host_name']; + $data['source'] = null; + // if we only want a single image + if (isset($g['source'])) { + $this->readXML($host, $service['name']); $this->includeTemplate($this->DS[0]['TEMPLATE']); $source = intval($g['source']); - if(array_key_exists($source,$this->RRD['def'])){ + if (array_key_exists($source, $this->RRD['def'])) { $data['source'] = $source; } } @@ -921,20 +1028,20 @@ class Data_Model extends System_Model } } } - }else{ - $hosts_to_search_for = explode(",", $g['host_name']); - $services_to_search_for = explode(",", $g['service_desc']); - if(isset($g['host_name']) && in_array($host ,$hosts_to_search_for) ){ - if(isset($g['service_desc']) && in_array($service['name'] ,$services_to_search_for) ){ + } else { + $hosts_to_search_for = explode(',', $g['host_name']); + $services_to_search_for = explode(',', $g['service_desc']); + if (isset($g['host_name']) && in_array($host, $hosts_to_search_for)) { + if (isset($g['service_desc']) && in_array($service['name'], $services_to_search_for)) { $data['service_desc'] = $g['service_desc']; - $data['host_name'] = $g['host_name']; - $data['source'] = NULL; - // if we only want a single image - if(isset($g['source'])){ - $this->readXML($host,$service['name']); + $data['host_name'] = $g['host_name']; + $data['source'] = null; + // if we only want a single image + if (isset($g['source'])) { + $this->readXML($host, $service['name']); $this->includeTemplate($this->DS[0]['TEMPLATE']); $source = intval($g['source']); - if(array_key_exists($source,$this->RRD['def'])){ + if (array_key_exists($source, $this->RRD['def'])) { $data['source'] = $source; } } @@ -942,172 +1049,184 @@ class Data_Model extends System_Model } } } - return FALSE; +//end if + return false; } +//end filterServiceByPage() - /* - * - */ - public function getPages() { - $pages = array(); + + public function getPages() + { + $pages = []; if (is_dir($this->config->conf['page_dir'])) { if ($dh = opendir($this->config->conf['page_dir'])) { - while (($file = readdir($dh)) !== false) { - if(preg_match('/(.*)\.cfg$/',basename($file),$page)){ - $pages[] = urlencode($page[1]); - } - } + while (($file = readdir($dh)) !== false) { + if (preg_match('/(.*)\.cfg$/', basename($file), $page)) { + $pages[] = urlencode($page[1]); + } + } closedir($dh); } else { die("Cannot open directory: $path"); } } - if(sizeof($pages)>0){ - + if (empty($pages)) { + return false; + } else { natsort($pages); - }else{ - return FALSE; } return $pages; } +//end getPages() - /* - * - */ - public function getFirstPage(){ + + public function getFirstPage() + { $pages = $this->getPages(); - if(sizeof($pages) > 0 ){ + if (empty($pages)) { + return false; + } else { return urldecode($pages[0]); - }else{ - return FALSE; } } +//end getFirstPage() - /* - * - */ - public function getPageDetails($page){ + + public function getPageDetails($page) + { $this->parse_page_cfg($page); return $this->PAGE_DEF['page_name']; } +//end getPageDetails() - /* - * - */ - public function buildXport($host,$service){ + + public function buildXport($host, $service) + { // FIXME add max rows to config - $this->XPORT = " -m 2000"; - $this->XPORT .= " --start=".$this->TIMERANGE['start']; - $this->XPORT .= " --end=".$this->TIMERANGE['end']; - $this->readXML($host,$service); + $this->XPORT = ' -m 2000'; + $this->XPORT .= $this->buildViewCmd(false, $this->TIMERANGE['start'], $this->TIMERANGE['end']); + $this->readXML($host, $service); $count = 0; - $RRAs = array('MIN','MAX','AVERAGE'); - foreach($this->DS as $key=>$value){ - foreach($RRAs as $RRA){ - $this->XPORT .= sprintf(" DEF:%d%s=%s:%d:%s ",$count,$RRA,$value['RRDFILE'],$value['DS'],$RRA); - $this->XPORT .= sprintf(" XPORT:%d%s:%s_%s " ,$count,$RRA,$value['NAME'],$RRA); + $RRAs = [ + 'MIN', + 'MAX', + 'AVERAGE', + ]; + foreach ($this->DS as $key => $value) { + foreach ($RRAs as $RRA) { + $this->XPORT .= sprintf(' DEF:%d%s=%s:%d:%s ', $count, $RRA, $value['RRDFILE'], $value['DS'], $RRA); + $this->XPORT .= sprintf(' XPORT:%d%s:%s_%s ', $count, $RRA, $value['NAME'], $RRA); } $count++; } } - /* - * - */ - public function xml2csv($string){ +//end buildXport() + + + public function xml2csv($string) + { $xml = simplexml_load_string($string); - $csv = "timestamp"; - foreach($xml->meta->legend->entry as $key=>$value){ - $csv .= ";" . $value ; + $csv = 'timestamp'; + foreach ($xml->meta->legend->entry as $key => $value) { + $csv .= ';' . $value; } /* - * from rrdtool 1.5 on, timestamp ( value->t ) is not set anymore - * from 1.6 on it can be reactivated by -- showrime option to rrdtool xport - * here we take care of the timestamp ourselves regardless which - * rrdtool version is used - */ + * from rrdtool 1.5 on, timestamp ( value->t ) is not set anymore + * from 1.6 on it can be reactivated by -- showrime option to rrdtool xport + * here we take care of the timestamp ourselves regardless which + * rrdtool version is used + */ $timestamp2 = $xml->meta->start; - $step = $xml->meta->step; - $csv .= "\n"; - foreach($xml->data->row as $key=>$value){ + $step = $xml->meta->step; + $csv .= "\n"; + foreach ($xml->data->row as $key => $value) { $csv .= $timestamp2; - foreach($value->v as $item){ - $csv .= ";".floatval((string) $item); + foreach ($value->v as $item) { + $csv .= ';' . floatval((string) $item); } - $csv .= "\n"; - $timestamp2 = $timestamp2 + $step; + $csv .= "\n"; + $timestamp2 = ($timestamp2 + $step); } - return $csv; + return $csv; } +//end xml2csv() + /* - * - * Used in Special Templates to gather data - */ - public function tplGetData ($hostname, $servicedesc, $throw_exception=TRUE){ - $conf = $this->config->conf; - $xmlfile = $conf['rrdbase'].$hostname."/".$servicedesc.".xml"; - $data = array(); + * + * Used in Special Templates to gather data + */ + public function tplGetData($hostname, $servicedesc, $throw_exception = true) + { + $conf = $this->config->conf; + $xmlfile = $conf['rrdbase'] . $hostname . '/' . $servicedesc . '.xml'; + $data = []; if (file_exists($xmlfile)) { $xml = simplexml_load_file($xmlfile); // Throw excaption without a valid structure version - if(!isset($xml->XML->VERSION) && $throw_exception == TRUE){ - throw new Kohana_Exception('error.xml-structure-without-version-tag',$xmlfile); + if (!isset($xml->XML->VERSION) && $throw_exception == true) { + throw new Kohana_Exception('error.xml-structure-without-version-tag', $xmlfile); } - if(!isset($xml->XML->VERSION) && $throw_exception == FALSE){ - return FALSE; + if (!isset($xml->XML->VERSION) && $throw_exception == false) { + return false; } - foreach ( $xml as $key=>$val ){ - if(preg_match('/^NAGIOS_(.*)$/', $key, $match)){ - $key = $match[1]; + foreach ($xml as $key => $val) { + if (preg_match('/^NAGIOS_(.*)$/', $key, $match)) { + $key = $match[1]; $data['MACRO'][$key] = (string) $val; } } - $i=0; - foreach ( $xml->DATASOURCE as $datasource ){ - foreach ( $datasource as $key=>$val){ + $i = 0; + foreach ($xml->DATASOURCE as $datasource) { + foreach ($datasource as $key => $val) { $data['DS'][$i][$key] = (string) $val; } - $i++; + $i++; } return $data; - }else{ + } else { throw new Kohana_Exception('error.xml-not-found', $xmlfile); } +//end if } +//end tplGetData() + + /* - * - * Used in Special Templates to gather data - */ - public function tplGetServices ($hostregex=FALSE, $serviceregex = ''){ - if($hostregex === FALSE){ - return FALSE; + * + * Used in Special Templates to gather data + */ + public function tplGetServices($hostregex = false, $serviceregex = '') + { + if ($hostregex === false) { + return false; } - $hostregex = sprintf("/%s/",$hostregex); - $serviceregex = sprintf("/%s/",$serviceregex); - $hosts = $this->getHosts(); - $new_hosts = array(); - foreach( $hosts as $host){ - if(preg_match($hostregex,$host['name'])){ + $hostregex = sprintf('/%s/', $hostregex); + $serviceregex = sprintf('/%s/', $serviceregex); + $hosts = $this->getHosts(); + $new_hosts = []; + foreach ($hosts as $host) { + if (preg_match($hostregex, $host['name'])) { $new_hosts[] = $host['name']; } } - if(sizeof($new_hosts) == 0){ + if (empty($new_hosts)) { throw new Kohana_Exception('error.tpl-no-hosts-found', $hostregex); } - $i = 0; - $new_services = array(); - foreach($new_hosts as $host){ + $i = 0; + $new_services = []; + foreach ($new_hosts as $host) { $services = $this->getRawServices($host); - if(sizeof($services) == 0){ + if (empty($services)) { throw new Kohana_Exception('error.tpl-no-services-found', $serviceregex); } - foreach($services as $service){ - if(preg_match($serviceregex, $service['name'])){ - $new_services[$i]['hostname'] = $host; - $new_services[$i]['host'] = $host; + foreach ($services as $service) { + if (preg_match($serviceregex, $service['name'])) { + $new_services[$i]['hostname'] = $host; + $new_services[$i]['host'] = $host; $new_services[$i]['service_description'] = $service['name']; $new_services[$i]['service'] = $service['name']; $i++; @@ -1115,11 +1234,12 @@ class Data_Model extends System_Model } } - if(sizeof($new_services) == 0){ + if (empty($new_services)) { throw new Kohana_Exception('error.tpl-no-services-found', $serviceregex); } return $new_services; - } -} +//end tplGetServices() +} +//end class diff --git a/share/pnp/application/models/rrdtool.php b/share/pnp/application/models/rrdtool.php index 472d2bf..b554848 100644 --- a/share/pnp/application/models/rrdtool.php +++ b/share/pnp/application/models/rrdtool.php @@ -1,229 +1,287 @@ -config = new Config_Model(); $this->config->read_config(); - #print Kohana::debug($this->config->views); + // print Kohana::debug($this->config->views); } +//end __construct() - private function rrdtool_execute() { - $descriptorspec = array ( - 0 => array ("pipe","r"), // stdin is a pipe that the child will read from - 1 => array ("pipe","w"), // stdout is a pipe that the child will write to - 2 => array ("pipe","w") // stderr is a pipe that the child will write to - ); - if(!isset($this->config->conf['rrdtool']) ) - return FALSE; + private function rrdtool_execute() + { + $descriptorspec = [ + 0 => [ + 'pipe', + 'r', + ], +// stdin is a pipe that the child will read from + 1 => [ + 'pipe', + 'w', + ], +// stdout is a pipe that the child will write to + 2 => [ + 'pipe', + 'w', + ], +// stderr is a pipe that the child will write to + ]; - if ( !is_executable($this->config->conf['rrdtool']) ) { - $data = "ERROR: ".$this->config->conf['rrdtool']." is not executable by PHP\n\n"; + if (!isset($this->config->conf['rrdtool'])) { + return false; + } + + if (!is_executable($this->config->conf['rrdtool'])) { + $data = 'ERROR: ' . $this->config->conf['rrdtool'] . " is not executable by PHP\n\n"; return $data; } - $rrdtool = $this->config->conf['rrdtool'] . " - "; + $rrdtool = $this->config->conf['rrdtool'] . ' - '; + + /* + this is needed by Fontconfig, used by pango, used by rrdtool graph + ** it's automatically set up for 'interactive' sessions, but web servers + ** don't have it (usually?). If there are 'red screens' instead of graphs, + ** there's a good chance this is why */ + + $fc_cache = $this->config->conf['fontconfig_cache']; + + + putenv('XDG_CACHE_HOME=' . $fc_cache); + $xdg_cache = getenv('XDG_CACHE_HOME'); + if (!$xdg_cache) { + $data = 'ERROR: environment var XDG_CACHE_HOME not defined (should be writable cache dir)'; + return $data; + } + if (!is_dir($xdg_cache) || !is_writeable($xdg_cache)) { + $data = 'ERROR: env XDG_CACHE_HOME (' . $xdg_cache . ') is not writable directory'; + return $data; + } + + + $command = $this->RRD_CMD; $process = proc_open($rrdtool, $descriptorspec, $pipes); - $debug = Array(); - $data = ""; + $debug = []; + $data = ''; if (is_resource($process)) { fwrite($pipes[0], $command); fclose($pipes[0]); - stream_set_timeout($pipes[1],1); - $data = stream_get_contents($pipes[1]); - stream_set_timeout($pipes[2],1); - $stderr = stream_get_contents($pipes[2]); + stream_set_timeout($pipes[1], 1); + $data = stream_get_contents($pipes[1]); + stream_set_timeout($pipes[2], 1); + $stderr = stream_get_contents($pipes[2]); $stdout_meta = stream_get_meta_data($pipes[1]); - if($stdout_meta['timed_out'] == 1){ + if ($stdout_meta['timed_out'] == 1) { $data = "ERROR: Timeout while reading rrdtool data.\n\n"; } fclose($pipes[1]); fclose($pipes[2]); proc_close($process); // Catch STDERR - if($stderr && strlen($stderr) >= 0 ){ - $data = "ERROR: STDERR => ".$stderr."\n\n"; + if ($stderr && strlen($stderr) >= 0) { + $data = 'ERROR: STDERR => ' . $stderr . "\n\n"; return $data; } // Catch STDOUT < 50 Characters - if($data && strlen($data) < 50 ){ - $data = "ERROR: STDOUT => ".$data."\n\n"; + if ($data && strlen($data) < 50) { + $data = 'ERROR: STDOUT => ' . $data . "\n\n"; return $data; } - }else{ - $data = "ERROR: proc_open(".$rrdtool." ... failed"; + } else { + $data = 'ERROR: proc_open(' . $rrdtool . ' ... failed'; } +//end if return $data; - } +//end rrdtool_execute() - public function doImage($RRD_CMD, $out='STDOUT') { + + public function doImage($RRD_CMD, $out = 'STDOUT') + { $conf = $this->config->conf; - # construct $command to rrdtool - if(isset($conf['RRD_DAEMON_OPTS']) && $conf['RRD_DAEMON_OPTS'] != '' ){ - $command = " graph --daemon=" . $conf['RRD_DAEMON_OPTS'] . " - "; - }else{ - $command = " graph - "; + // construct $command to rrdtool + if (isset($conf['RRD_DAEMON_OPTS']) && $conf['RRD_DAEMON_OPTS'] != '') { + $command = ' graph --daemon=' . $conf['RRD_DAEMON_OPTS'] . ' - '; + } else { + $command = ' graph - '; } - $width = 0; + $width = 0; $height = 0; - if ($out == 'PDF'){ - if($conf['pdf_graph_opt']){ + if ($out == 'PDF') { + if ($conf['pdf_graph_opt']) { $command .= $conf['pdf_graph_opt']; } - if (isset($conf['pdf_width']) && is_numeric($conf['pdf_width'])){ + if (isset($conf['pdf_width']) && is_numeric($conf['pdf_width'])) { $width = abs($conf['pdf_width']); } - if (isset($conf['pdf_height']) && is_numeric($conf['pdf_height'])){ + if (isset($conf['pdf_height']) && is_numeric($conf['pdf_height'])) { $height = abs($conf['pdf_height']); } - }else{ - if($conf['graph_opt']){ + } else { + if ($conf['graph_opt']) { $command .= $conf['graph_opt']; } - if(is_numeric($conf['graph_width'])){ + if (is_numeric($conf['graph_width'])) { $width = abs($conf['graph_width']); } - if(is_numeric($conf['graph_height'])){ + if (is_numeric($conf['graph_height'])) { $height = abs($conf['graph_height']); } } +//end if - if ($width > 0){ + if ($width > 0) { $command .= " --width=$width"; } - if ($height > 0){ + if ($height > 0) { $command .= " --height=$height"; } - if ($height < 81 || (isset($conf['graph_only']) && $conf['graph_only'])){ - $command .= " --only-graph"; - } - elseif (isset($conf['no_legend']) && $conf['no_legend']){ - $command .= " --no-legend"; + if ($height < 81 || (isset($conf['graph_only']) && $conf['graph_only'])) { + $command .= ' --only-graph'; + } elseif (isset($conf['no_legend']) && $conf['no_legend']) { + $command .= ' --no-legend'; } $command .= $RRD_CMD; - # Force empty vertical label - if( ! preg_match_all('/(-l|--vertical-label)/i',$command,$match)){ + // Force empty vertical label + if (! preg_match_all('/(-l|--vertical-label)/i', $command, $match)) { $command .= " --vertical-label=' ' "; } $this->RRD_CMD = $command; - $data = $this->rrdtool_execute(); - if($data){ + $data = $this->rrdtool_execute(); + if ($data) { return $data; - }else{ - return FALSE; + } else { + return false; } } +//end doImage() - /* - * - */ - public function doXport($RRD_CMD){ + + public function doXport($RRD_CMD) + { $conf = $this->config->conf; - if(isset($conf['RRD_DAEMON_OPTS']) && $conf['RRD_DAEMON_OPTS'] != '' ){ - $command = " xport --daemon=" . $conf['RRD_DAEMON_OPTS']; - }else{ - $command = " xport "; + if (isset($conf['RRD_DAEMON_OPTS']) && $conf['RRD_DAEMON_OPTS'] != '') { + $command = ' xport --daemon=' . $conf['RRD_DAEMON_OPTS']; + } else { + $command = ' xport '; } - $command .= $RRD_CMD; + $command .= $RRD_CMD; $this->RRD_CMD = $command; - $data = $this->rrdtool_execute(); - $data = preg_replace('/OK.*/','',$data); - if($data){ + $data = $this->rrdtool_execute(); + $data = preg_replace('/OK.*/', '', $data); + if ($data) { return $data; - }else{ - return FALSE; + } else { + return false; } } +//end doXport() - public function streamImage($data = FALSE){ - if ( $data === FALSE ){ - header("Content-type: image/png"); - echo base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A + + public function streamImage($data = false) + { + if ($data === false) { + header('Content-type: image/png'); + echo base64_decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A /wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9kCCAoDKSKZ0rEAAAAZdEVYdENv bW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADUlEQVQI12NgYGBgAAAABQABXvMqOgAAAABJ - RU5ErkJggg=='); - return; + RU5ErkJggg==' + ); + return; } if (preg_match('/^ERROR/', $data)) { - if(preg_match('/NOT_AUTHORIZED/', $data)){ + if (preg_match('/NOT_AUTHORIZED/', $data)) { // TODO: i18n $data .= "\n\nYou are not authorized to view this Image"; // Set font size $font_size = 3; - }else{ - $data .= $this->format_rrd_debug( $this->config->conf['rrdtool'] . $this->RRD_CMD) ; + } else { + $data .= $this->format_rrd_debug($this->config->conf['rrdtool'] . $this->RRD_CMD); // Set font size - $font_size = 1.5; + $font_size = 2; } - $ts=explode("\n",$data); - $width=0; - foreach ($ts as $k=>$string) { - $width=max($width,strlen($string)); + $ts = explode("\n", $data); + $width = 0; + foreach ($ts as $k => $string) { + $width = max($width, strlen($string)); } - $width = imagefontwidth($font_size)*$width; - if($width <= $this->config->conf['graph_width']+100){ - $width = $this->config->conf['graph_width']+100; + $width = imagefontwidth($font_size) * $width; + if ($width <= ($this->config->conf['graph_width'] + 100)) { + $width = ($this->config->conf['graph_width'] + 100); } - $height = imagefontheight($font_size)*count($ts); - if($height <= $this->config->conf['graph_height']+60){ - $height = $this->config->conf['graph_height']+60; + $height = imagefontheight($font_size) * count($ts); + if ($height <= ($this->config->conf['graph_height'] + 60)) { + $height = ($this->config->conf['graph_height'] + 60); } - $el=imagefontheight($font_size); - $em=imagefontwidth($font_size); + $el = imagefontheight($font_size); + $em = imagefontwidth($font_size); // Create the image pallette - $img = imagecreatetruecolor($width,$height); + $img = imagecreatetruecolor($width, $height); // Dark red background $bg = imagecolorallocate($img, 0xAA, 0x00, 0x00); - imagefilledrectangle($img, 0, 0,$width ,$height , $bg); + imagefilledrectangle($img, 0, 0, $width, $height, $bg); // White font color $color = imagecolorallocate($img, 255, 255, 255); - foreach ($ts as $k=>$string) { + foreach ($ts as $k => $string) { // Length of the string $len = strlen($string); // Y-coordinate of character, X changes, Y is static $ypos_offset = 5; $xpos_offset = 5; // Loop through the string - for($i=0;$i<$len;$i++){ + for ($i = 0; $i < $len; $i++) { // Position of the character horizontally - $xpos = $i * $em + $ypos_offset; - $ypos = $k * $el + $xpos_offset; + $xpos = ($i * $em + $ypos_offset); + $ypos = ($k * $el + $xpos_offset); // Draw character imagechar($img, $font_size, $xpos, $ypos, $string, $color); // Remove character from string - $string = substr($string, 1); + $string = substr($string, 1); } } - header("Content-type: image/png"); + header('Content-type: image/png'); imagepng($img); imagedestroy($img); - }else{ - header("Content-type: image/png"); + } else { + header('Content-type: image/png'); echo $data; } +//end if } +//end streamImage() - public function saveImage($data = FALSE){ - $img = array(); - $img['file'] = tempnam($this->config->conf['temp'],"PNP"); - if(!$fh = fopen($img['file'],'w') ){ + + public function saveImage($data = false) + { + $img = []; + $img['file'] = tempnam($this->config->conf['temp'], 'PNP'); + if (!$fh = fopen($img['file'], 'w')) { throw new Kohana_Exception('save-rrd-image', $img['file']); } fwrite($fh, $data); @@ -232,15 +290,19 @@ class Rrdtool_Model extends System_Model $image = imagecreatefrompng($img['file']); imagepng($image, $img['file']); list ($img['width'], $img['height'], $img['type'], $img['attr']) = getimagesize($img['file']); - }else{ + } else { throw new Kohana_Exception('error.gd-missing'); } return $img; } +//end saveImage() - private function format_rrd_debug($data) { - $data = preg_replace('/(HRULE|VDEF|DEF|CDEF|GPRINT|LINE|AREA|COMMENT)/',"\n\${1}", $data); + private function format_rrd_debug($data) + { + $data = preg_replace('/(HRULE|VDEF|DEF|CDEF|GPRINT|LINE|AREA|COMMENT)/', "\n\${1}", $data); return $data; - } + } +//end format_rrd_debug() } +//end class diff --git a/share/pnp/application/models/system.php b/share/pnp/application/models/system.php index fa291ad..02de34b 100644 --- a/share/pnp/application/models/system.php +++ b/share/pnp/application/models/system.php @@ -1,14 +1,19 @@ -metadata['Title'] = $isUTF8 ? $title : utf8_encode($title); + $this->metadata['Title'] = $isUTF8 ? $title : mb_convert_encoding($title, 'UTF-8', mb_list_encodings()); + // utf8_encode($title); } function SetAuthor($author, $isUTF8=false) { // Author of document - $this->metadata['Author'] = $isUTF8 ? $author : utf8_encode($author); + $this->metadata['Author'] = $isUTF8 ? $author : mb_convert_encoding($author, 'UTF-8', mb_list_encodings()); + // utf8_encode($author); } function SetSubject($subject, $isUTF8=false) { // Subject of document - $this->metadata['Subject'] = $isUTF8 ? $subject : utf8_encode($subject); + $this->metadata['Subject'] = $isUTF8 ? $subject : mb_convert_encoding($subject, 'UTF-8', mb_list_encodings()); + // utf8_encode($subject); } function SetKeywords($keywords, $isUTF8=false) { // Keywords of document - $this->metadata['Keywords'] = $isUTF8 ? $keywords : utf8_encode($keywords); + $this->metadata['Keywords'] = $isUTF8 ? $keywords : mb_convert_encoding($keywords, 'UTF-8', mb_list_encodings()); + // utf8_encode($keywords); } function SetCreator($creator, $isUTF8=false) { // Creator of document - $this->metadata['Creator'] = $isUTF8 ? $creator : utf8_encode($creator); + $this->metadata['Creator'] = $isUTF8 ? $creator : mb_convert_encoding($creator, 'UTF-8', mb_list_encodings()); + // utf8_encode($creator); } function AliasNbPages($alias='{nb}') @@ -1039,9 +1044,10 @@ protected function _dochecks() // Check mbstring overloading if(ini_get('mbstring.func_overload') & 2) $this->Error('mbstring overloading must be disabled'); + // magic quotes removed from php 7.4? // Ensure runtime magic quotes are disabled - if(get_magic_quotes_runtime()) - @set_magic_quotes_runtime(0); + //if(get_magic_quotes_runtime()) + // @set_magic_quotes_runtime(0); } protected function _checkoutput() @@ -1168,7 +1174,8 @@ protected function _httpencode($param, $value, $isUTF8) if($this->_isascii($value)) return $param.'="'.$value.'"'; if(!$isUTF8) - $value = utf8_encode($value); + $value = mb_convert_encoding($value, 'UTF-8', mb_list_encodings()); + // utf8_encode($value); if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE')!==false) return $param.'="'.rawurlencode($value).'"'; else diff --git a/share/pnp/application/vendor/fpdf/fpdi.php b/share/pnp/application/vendor/fpdf/fpdi.php index 8ecc661..dac9176 100755 --- a/share/pnp/application/vendor/fpdf/fpdi.php +++ b/share/pnp/application/vendor/fpdf/fpdi.php @@ -558,8 +558,8 @@ class FPDI extends FPDF_TPL $this->_straightOut('<<'); reset ($value[1]); - - while (list($k, $v) = each($value[1])) { + + foreach($value[1] as $k => $v) { $this->_straightOut($k . ' '); $this->_writeValue($v); } @@ -690,4 +690,4 @@ class FPDI extends FPDF_TPL $parser->closeFile(); } } -} \ No newline at end of file +} diff --git a/share/pnp/application/vendor/fpdf/fpdi_pdf_parser.php b/share/pnp/application/vendor/fpdf/fpdi_pdf_parser.php index 9e6d521..e01df03 100755 --- a/share/pnp/application/vendor/fpdf/fpdi_pdf_parser.php +++ b/share/pnp/application/vendor/fpdf/fpdi_pdf_parser.php @@ -305,6 +305,9 @@ class fpdi_pdf_parser extends pdf_parser } $res = $this->_getPageRotation($obj[1][1]['/Parent']); + if (! is_array($res)) + return false; + if ($res[0] == pdf_parser::TYPE_OBJECT) return $res[1]; diff --git a/share/pnp/application/vendor/fpdf/makefont/makefont.php b/share/pnp/application/vendor/fpdf/makefont/makefont.php index 052f35f..ea1ead4 100755 --- a/share/pnp/application/vendor/fpdf/makefont/makefont.php +++ b/share/pnp/application/vendor/fpdf/makefont/makefont.php @@ -384,8 +384,9 @@ function MakeDefinitionFile($file, $type, $enc, $embed, $subset, $map, $info) function MakeFont($fontfile, $enc='cp1252', $embed=true, $subset=true) { // Generate a font definition file - if(get_magic_quotes_runtime()) - @set_magic_quotes_runtime(false); + // magic quotes removed from php 7.4-ish + //if(get_magic_quotes_runtime()) + // @set_magic_quotes_runtime(false); ini_set('auto_detect_line_endings', '1'); if(!file_exists($fontfile)) diff --git a/share/pnp/application/views/basket_box.php b/share/pnp/application/views/basket_box.php index ea8a72c..6bbdeae 100644 --- a/share/pnp/application/views/basket_box.php +++ b/share/pnp/application/views/basket_box.php @@ -1,29 +1,30 @@ -session->get('basket'); echo "
    \n"; echo "
    \n"; -echo Kohana::lang('common.basket-box-header')."
    \n"; +echo Kohana::lang('common.basket-box-header') . "
    \n"; echo "
    \n"; echo "
    \n"; -if(is_array($basket) && sizeof($basket) > 0 ){ - foreach($basket as $key=>$item){ - echo "
  • ". - pnp::shorten($item)."
  • \n"; - } +if (is_array($basket) && !empty($basket)) { + foreach ($basket as $key => $item) { + echo "
  • " . + pnp::shorten($item) . "
  • \n"; + } } -if(is_array($basket) && sizeof($basket) > 0 ){ +if (is_array($basket) && !empty($basket)) { echo "
    \n"; - echo "\n"; - echo "\n"; + echo "\n"; + echo "\n"; echo "
    \n"; #echo "\n"; -}else{ - echo "
    ".Kohana::lang('common.basket-empty')."
    \n"; +} else { + echo "
    " . Kohana::lang('common.basket-empty') . "
    \n"; } echo "
    \n"; echo "
    \n"; diff --git a/share/pnp/application/views/color.php b/share/pnp/application/views/color.php index d461b8b..2826db3 100644 --- a/share/pnp/application/views/color.php +++ b/share/pnp/application/views/color.php @@ -6,33 +6,33 @@

    - scheme)) { - foreach( $this->scheme as $key => $colors ){ - print "

    \"" . $key . "\"

      "; - foreach($colors as $color){ - print "
    • " . "
    • \n"; - } - print "
    "; - } - print "

    "; - } ?> + scheme)) { + foreach ($this->scheme as $key => $colors) { + print "

    \"" . $key . "\"

      "; + foreach ($colors as $color) { + print "
    • " . "
    • \n"; + } + print "
    "; + } + print "

    "; + } ?>
    -
    +
    - + - -
    + +
    - +
    - +
    - + diff --git a/share/pnp/application/views/color_box.php b/share/pnp/application/views/color_box.php index 1c4d342..60b2b72 100644 --- a/share/pnp/application/views/color_box.php +++ b/share/pnp/application/views/color_box.php @@ -4,10 +4,16 @@
    -\n"; -echo "\n"; -echo "\n"; +\n"; +echo "\n"; +echo "\n"; ?>
    diff --git a/share/pnp/application/views/debug.php b/share/pnp/application/views/debug.php index 2681d16..1208a5d 100644 --- a/share/pnp/application/views/debug.php +++ b/share/pnp/application/views/debug.php @@ -1,50 +1,50 @@ -is_authorized === FALSE){ +is_authorized === false) { print "

    Your are not authorized to view this site

    "; - return; -} + return; +} ?>
    +
    - -
    -

    $this->data->STRUCT

    -
    +    
    +    
    +

    $this->data->STRUCT

    +
     data->STRUCT);?>
    -	
    -
    -
    -

    $this->data->DS

    -
    +    
    +
    +
    +

    $this->data->DS

    +
     data->DS);?>
    -	
    -
    -
    -

    $this->data->MACRO

    -
    +    
    +
    +
    +

    $this->data->MACRO

    +
     data->MACRO);?>
    -	
    -
    -
    -

    $this->session->get()

    -
    +    
    +
    +
    +

    $this->session->get()

    +
     session->get());?>
    -	
    -
    +
    +
    diff --git a/share/pnp/application/views/docs.php b/share/pnp/application/views/docs.php index 81114bc..1ce34ab 100644 --- a/share/pnp/application/views/docs.php +++ b/share/pnp/application/views/docs.php @@ -3,24 +3,30 @@
    - +
    -
    -content)) { -echo $this->content; -} ?> +
    +content)) { + echo $this->content; +} +?>
    - + - +
    diff --git a/share/pnp/application/views/docs_box.php b/share/pnp/application/views/docs_box.php index 8a24fa7..c811ba7 100644 --- a/share/pnp/application/views/docs_box.php +++ b/share/pnp/application/views/docs_box.php @@ -4,12 +4,18 @@
    -\n"; -echo "\n"; -echo "\n"; -foreach ( $this->doc_language as $lang ){ - echo " \n"; +\n"; +echo "\n"; +echo "\n"; +foreach ($this->doc_language as $lang) { + echo " \n"; } ?>
    diff --git a/share/pnp/application/views/graph.php b/share/pnp/application/views/graph.php index 045aa2b..cd39174 100644 --- a/share/pnp/application/views/graph.php +++ b/share/pnp/application/views/graph.php @@ -1,56 +1,76 @@
    - + -
    - -
    + +
    - +
    -
    - +
    + - + - + - + - + - + - + - - -
    -
    -
    - + +
    -
    +
    +
    + +
    +
    diff --git a/share/pnp/application/views/graph_content.php b/share/pnp/application/views/graph_content.php index 337f938..a75212c 100644 --- a/share/pnp/application/views/graph_content.php +++ b/share/pnp/application/views/graph_content.php @@ -1,101 +1,128 @@ \n"; +echo "
    \n"; -if($this->is_authorized == FALSE){ - echo "
    \n"; - echo "

    \n"; - echo "Alert: ".Kohana::lang('error.not_authorized')."

    \n"; +if ($this->is_authorized == false) { + echo "
    \n"; + echo "

    \n"; + echo "Alert: " . Kohana::lang('error.not_authorized') . "

    \n"; echo "
    \n"; return; } -if($this->data->ERROR != NULL){ - echo "
    \n"; - echo "

    \n"; - echo "Alert: ".$this->data->ERROR."

    \n"; +if ($this->data->ERROR != null) { + echo "
    \n"; + echo "

    \n"; + echo "Alert: " . $this->data->ERROR . "

    \n"; echo "
    \n"; return; } $count = 0; -foreach($this->data->STRUCT as $key=>$value){ - if($value['LEVEL'] == 0){ - echo "Host: ".$value['MACRO']['DISP_HOSTNAME']. " Service: ".$value['MACRO']['DISP_SERVICEDESC']."

    \n"; - echo "".$value['TIMERANGE']['title']. " " .$value['TIMERANGE']['f_start']. " - " . $value['TIMERANGE']['f_end']. "\n"; - $count = 0; - } - if($value['VERSION'] != "valid" && $count == 0){ - $count++; - echo "

    \n"; - echo "
    \n"; - echo "

    ".$value['VERSION']."

    \n"; - echo "
    \n"; - echo "

    \n"; - } +foreach ($this->data->STRUCT as $key => $value) { + if ($value['LEVEL'] == 0) { + echo "Host: " . $value['MACRO']['DISP_HOSTNAME'] . " Service: " . $value['MACRO']['DISP_SERVICEDESC'] . "

    \n"; + echo "" . $value['TIMERANGE']['title'] . " " . $value['TIMERANGE']['f_start'] . " - " . $value['TIMERANGE']['f_end'] . "\n"; + $count = 0; + } + if ($value['VERSION'] != "valid" && $count == 0) { + $count++; + echo "

    \n"; + echo "
    \n"; + echo "

    " . $value['VERSION'] . "

    \n"; + echo "
    \n"; + echo "

    \n"; + } echo "
    "; echo "\n"; echo "\n"; - echo "\n"; - echo "\n"; - echo "\n"; + echo "\n"; + echo "\n"; + echo "\n"; - echo "\n"; - echo "
    "; - echo Kohana::lang('common.datasource',$value['ds_name']).""; - echo nagios::SummaryLink($value['MACRO']['DISP_HOSTNAME'], - $value['TIMERANGE']['start'], - $value['TIMERANGE']['end']).""; - echo nagios::AvailLink($value['MACRO']['DISP_HOSTNAME'], - $value['MACRO']['DISP_SERVICEDESC'], - $value['TIMERANGE']['start'], - $value['TIMERANGE']['end']).""; - echo pnp::add_to_basket_icon( - $value['MACRO']['HOSTNAME'], - $value['MACRO']['SERVICEDESC'], - $value['SOURCE'] - ); + echo Kohana::lang('common.datasource', $value['ds_name']) . ""; + echo nagios::SummaryLink( + $value['MACRO']['DISP_HOSTNAME'], + $value['TIMERANGE']['start'], + $value['TIMERANGE']['end'] + ) . ""; + echo nagios::AvailLink( + $value['MACRO']['DISP_HOSTNAME'], + $value['MACRO']['DISP_SERVICEDESC'], + $value['TIMERANGE']['start'], + $value['TIMERANGE']['end'] + ) . ""; + echo pnp::add_to_basket_icon( + $value['MACRO']['HOSTNAME'], + $value['MACRO']['SERVICEDESC'], + $value['SOURCE'] + ); echo ""; - echo pnp::zoom_icon($value['MACRO']['HOSTNAME'], - $value['MACRO']['SERVICEDESC'], - $value['TIMERANGE']['start'], - $value['TIMERANGE']['end'], - $value['SOURCE'], - $value['VIEW'], - $value['GRAPH_WIDTH'], - $value['GRAPH_HEIGHT'])."
    \n"; - echo "
    \n"; - echo "
    \n"; - echo "
    \n"; - $path = pnp::addToUri( array( + echo ""; + echo pnp::zoom_icon( + $value['MACRO']['HOSTNAME'], + $value['MACRO']['SERVICEDESC'], + $value['TIMERANGE']['start'], + $value['TIMERANGE']['end'], + $value['SOURCE'], + $value['VIEW'], + $value['GRAPH_WIDTH'], + $value['GRAPH_HEIGHT'] + ) . "\n"; + echo "\n"; + echo "
    \n"; + echo "

    \n"; + ), false); + echo "\n"; + + # urlencode the graph id, to prevent # chars in service names being + # treated like a url fragment when zooming + $gid = array(); + #parse_str(ltrim($this->url, '?'), $gid); + #$gid = htmlentities("?host=".urlencode($gid["host"])."&srv=".urlencode($gid["srv"])); + + + // build the URI which renders the dynamic graph image + $path = array('host' => $value['MACRO']['HOSTNAME'], + 'srv' => $value['MACRO']['SERVICEDESC'], + 'source' => $value['SOURCE']); + $gid = htmlentities("?host=" . urlencode($path["host"]) . "&srv=" . urlencode($path["srv"])); + + echo "

    "; + + // only include `view` in the querystring if we are in a preset view; likewise, only + // include timerange start/end if we are not in a preset view; this will help later + // to differentiate between preset and custom timeranges, for display purposes + if ($value['TIMERANGE']['type'] == 'views') { + $path['view'] = $value['VIEW']; + } else { + $path['start'] = $value['TIMERANGE']['start']; + $path['end'] = $value['TIMERANGE']['end']; + } + + $path = pnp::addToUri($path, false); + + echo "\n"; + echo "
    \n"; + echo "

    \n"; } echo "\n"; ?> diff --git a/share/pnp/application/views/graph_content_special.php b/share/pnp/application/views/graph_content_special.php index 375520a..a5b85e3 100644 --- a/share/pnp/application/views/graph_content_special.php +++ b/share/pnp/application/views/graph_content_special.php @@ -1,50 +1,57 @@ \n"; +echo "

    \n"; $count = 0; -if($this->data->MACRO['TITLE']) - echo "".$this->data->MACRO['TITLE']."

    \n"; -if($this->data->MACRO['COMMENT']) - echo $this->data->MACRO['COMMENT']."

    \n"; +if ($this->data->MACRO['TITLE']) { + echo "" . $this->data->MACRO['TITLE'] . "

    \n"; +} +if ($this->data->MACRO['COMMENT']) { + echo $this->data->MACRO['COMMENT'] . "

    \n"; +} -foreach($this->data->STRUCT as $key=>$value){ - if($value['LEVEL'] == 0 ){ - echo "".$value['TIMERANGE']['title']. " " .$value['TIMERANGE']['f_start']. " - " . $value['TIMERANGE']['f_end']. "\n"; - $count = 0; - } +foreach ($this->data->STRUCT as $key => $value) { + if ($value['LEVEL'] == 0) { + echo "" . $value['TIMERANGE']['title'] . " " . $value['TIMERANGE']['f_start'] . " - " . $value['TIMERANGE']['f_end'] . "\n"; + $count = 0; + } echo "

    "; echo "\n"; echo "\n"; + echo Kohana::lang('common.datasource', $value['ds_name']) . "\n"; echo "\n"; + echo pnp::zoom_icon_special( + $this->tpl, + $value['TIMERANGE']['start'], + $value['TIMERANGE']['end'], + $value['SOURCE'], + $value['VIEW'], + $value['GRAPH_WIDTH'], + $value['GRAPH_HEIGHT'] + ) . "\n"; echo "
    "; - echo Kohana::lang('common.datasource',$value['ds_name']).""; - echo pnp::zoom_icon_special($this->tpl, - $value['TIMERANGE']['start'], - $value['TIMERANGE']['end'], - $value['SOURCE'], - $value['VIEW'], - $value['GRAPH_WIDTH'], - $value['GRAPH_HEIGHT'])."
    \n"; echo "
    \n"; echo "

    \n"; } diff --git a/share/pnp/application/views/graph_tiny.php b/share/pnp/application/views/graph_tiny.php index dde26aa..42b6aaa 100644 --- a/share/pnp/application/views/graph_tiny.php +++ b/share/pnp/application/views/graph_tiny.php @@ -1,19 +1,21 @@

    - - - + +
    -
    - + + + - -
    +
    + - -
    -
    + +
    +
    \ No newline at end of file diff --git a/share/pnp/application/views/header.php b/share/pnp/application/views/header.php index d4efaa1..0215076 100644 --- a/share/pnp/application/views/header.php +++ b/share/pnp/application/views/header.php @@ -1,4 +1,4 @@
    - +
    diff --git a/share/pnp/application/views/host_box.php b/share/pnp/application/views/host_box.php index d612934..271fab8 100644 --- a/share/pnp/application/views/host_box.php +++ b/share/pnp/application/views/host_box.php @@ -2,9 +2,9 @@ Status Box
    $host['state']))."

    "; -} + foreach ($hosts as $host) { + echo html::anchor('graph?host=' . $host['name'], $host['name'], array('class' => $host['state'])) . "

    "; + } } ?> diff --git a/share/pnp/application/views/icon_box.php b/share/pnp/application/views/icon_box.php index 34d99c1..77f142f 100644 --- a/share/pnp/application/views/icon_box.php +++ b/share/pnp/application/views/icon_box.php @@ -1,38 +1,59 @@
    - +
    $this->start,'end' => $this->end, 'view' => $this->view), False); -if($this->config->conf['use_calendar']){ - echo ""; +$qsa = pnp::addToUri(['start' => $this->start, 'end' => $this->end, 'view' => $this->view], false); +if ($this->config->conf['use_calendar']) { + echo ''; } -if($this->config->conf['use_fpdf'] == 1 && ( $position == "graph" || $position == "special") ){ - echo "\n"; +if ($this->config->conf['use_fpdf'] == 1 && ( $position == 'graph' || $position == 'special')) { + echo '\n"; } -if($this->config->conf['use_fpdf'] == 1 && $position == "basket"){ - echo "\n"; +if ($this->config->conf['use_fpdf'] == 1 && $position == 'basket') { + echo '\n"; } -if($this->config->conf['use_fpdf'] == 1 && $position == "page"){ - echo "page.$qsa."\">\n"; +if ($this->config->conf['use_fpdf'] == 1 && $position == 'page') { + echo '\n"; } -if($this->config->conf['show_xml_icon'] == 1 && $position == "graph" && $xml_icon == TRUE){ - $qsa = pnp::addToUri(array(), False); - echo "\n"; +if ($this->config->conf['show_xml_icon'] == 1 && $position == 'graph' && $xml_icon == true) { + $qsa = pnp::addToUri([], false); + echo '\n"; } -if($this->data->getFirstPage() && $this->isAuthorizedFor('pages') ){ - echo "\n"; +if ($this->data->getFirstPage() && $this->isAuthorizedFor('pages')) { + echo '\n"; } -echo "\n"; +echo '\n"; -if($this->data->getFirstSpecialTemplate() ){ - echo "\n"; +if ($this->data->getFirstSpecialTemplate()) { + echo '\n"; } -echo "\n"; +echo '\n"; ?>

    diff --git a/share/pnp/application/views/kohana_error_page.php b/share/pnp/application/views/kohana_error_page.php index 490ed62..856728d 100644 --- a/share/pnp/application/views/kohana_error_page.php +++ b/share/pnp/application/views/kohana_error_page.php @@ -1,19 +1,21 @@ - + - + -<?php echo $error ?> - - - - - +<?php echo $error; ?> + + + + + @@ -22,23 +24,23 @@

    - +

    Please check the documentation for information about the following error.

    -

    - +

    +

    file [line]:

    -

    +

    - -

    - + +

    +

    - +

    @@ -48,14 +50,14 @@
    - +
    \n"; -echo "\n"; -echo "\n"; +echo '\n"; +echo '\n"; +echo '\n"; ?>
    diff --git a/share/pnp/application/views/logo_box.php b/share/pnp/application/views/logo_box.php index fca461f..f14b1c8 100644 --- a/share/pnp/application/views/logo_box.php +++ b/share/pnp/application/views/logo_box.php @@ -1,8 +1,8 @@
    diff --git a/share/pnp/application/views/mobile.php b/share/pnp/application/views/mobile.php index 1c1afdf..c5ef56d 100644 --- a/share/pnp/application/views/mobile.php +++ b/share/pnp/application/views/mobile.php @@ -4,46 +4,64 @@ - - - - - + + + + +

    PNP4Nagios

    -Home +Home
    - - + - + - + - + - + - + - - +} +?> + +
    diff --git a/share/pnp/application/views/mobile_about.php b/share/pnp/application/views/mobile_about.php index 2f8bc29..530b168 100644 --- a/share/pnp/application/views/mobile_about.php +++ b/share/pnp/application/views/mobile_about.php @@ -1,3 +1,9 @@ +
    PNP4Nagios mobile interface based on jQuery Mobile
    diff --git a/share/pnp/application/views/mobile_graph.php b/share/pnp/application/views/mobile_graph.php index 87f4193..13d415b 100644 --- a/share/pnp/application/views/mobile_graph.php +++ b/share/pnp/application/views/mobile_graph.php @@ -1,43 +1,47 @@ is_authorized == FALSE){ -?> +if ($this->is_authorized == false) { + ?>
      -
    • Alert: 
    • +
    • Alert: 
    -
    data->STRUCT as $d){ - if($d['VIEW'] > $last_view){ # a new header begins - if($last_view != -1 ){ # close last div +foreach ($this->data->STRUCT as $d) { + if ($d['VIEW'] > $last_view) { +// a new header begins + if ($last_view != -1) { +// close last div print "
    \n"; } - printf("
    %s
    \n", $d['TIMERANGE']['title'] ); + printf("
    %s
    \n", $d['TIMERANGE']['title']); printf("
    %s\n", $d['ds_name']); - printf("
    \n", - $d['MACRO']['HOSTNAME'], + printf( + '
    \n", + $d['MACRO']['HOSTNAME'], $d['MACRO']['SERVICEDESC'], $d['VIEW'], $d['SOURCE'] - ); - $last_view++; - }else{ + ); + $last_view++; + } else { printf("
    %s
    \n", $d['ds_name']); - printf("
    \n", - $d['MACRO']['HOSTNAME'], + printf( + '
    \n", + $d['MACRO']['HOSTNAME'], $d['MACRO']['SERVICEDESC'], $d['VIEW'], $d['SOURCE'] - ); - } -} + ); + }//end if +}//end foreach ?>
    diff --git a/share/pnp/application/views/mobile_graph_special.php b/share/pnp/application/views/mobile_graph_special.php index c7b4b6d..a759296 100644 --- a/share/pnp/application/views/mobile_graph_special.php +++ b/share/pnp/application/views/mobile_graph_special.php @@ -1,33 +1,39 @@
    data->MACRO['TITLE']) - echo "".$this->data->MACRO['TITLE']."

    \n"; -if($this->data->MACRO['COMMENT']) - echo $this->data->MACRO['COMMENT']."

    \n"; +if ($this->data->MACRO['TITLE']) { + echo '' . $this->data->MACRO['TITLE'] . "

    \n"; +} +if ($this->data->MACRO['COMMENT']) { + echo $this->data->MACRO['COMMENT'] . "

    \n"; +} $last_view = -1; -foreach($this->data->STRUCT as $d){ - if($d['VIEW'] > $last_view){ # a new header begins - if($last_view != -1 ){ # close last div +foreach ($this->data->STRUCT as $d) { + if ($d['VIEW'] > $last_view) { +// a new header begins + if ($last_view != -1) { +// close last div print "

    \n"; } - printf("
    %s
    \n", $d['TIMERANGE']['title'] ); + printf("
    %s
    \n", $d['TIMERANGE']['title']); printf("
    %s\n", $d['ds_name']); - printf("
    \n", + printf( + '
    \n", $this->tpl, $d['VIEW'], $d['SOURCE'] ); $last_view++; - }else{ + } else { printf("
    %s
    \n", $d['ds_name']); - printf("
    \n", + printf( + '
    \n", $this->tpl, $d['VIEW'], $d['SOURCE'] ); - } -} + }//end if +}//end foreach ?>
    diff --git a/share/pnp/application/views/mobile_home.php b/share/pnp/application/views/mobile_home.php index 7723a2a..32480c8 100644 --- a/share/pnp/application/views/mobile_home.php +++ b/share/pnp/application/views/mobile_home.php @@ -1,17 +1,17 @@
    diff --git a/share/pnp/application/views/mobile_host.php b/share/pnp/application/views/mobile_host.php index 9eedbae..360ae2a 100644 --- a/share/pnp/application/views/mobile_host.php +++ b/share/pnp/application/views/mobile_host.php @@ -1,29 +1,35 @@ is_authorized == FALSE){ -?> +if ($this->is_authorized == false) { + ?>
    • Alert: 
    -
      $service){ - if($key == 0) - printf("
    • %s
    • \n", $service['hostname'] ); - - printf("
    • %s
    • ", - urlencode($service['hostname']), - urlencode($service['name']), - urlencode($service['hostname']), - urlencode($service['name']), - $service['servicedesc']); +foreach ($services as $key => $service) { + if ($key == 0) { + printf("
    • %s
    • \n", $service['hostname']); + } + + printf( + "
    • %s
    • ", + urlencode($service['hostname']), + urlencode($service['name']), + urlencode($service['hostname']), + urlencode($service['name']), + $service['servicedesc'] + ); } ?>
    diff --git a/share/pnp/application/views/mobile_overview.php b/share/pnp/application/views/mobile_overview.php index e037b75..96add70 100644 --- a/share/pnp/application/views/mobile_overview.php +++ b/share/pnp/application/views/mobile_overview.php @@ -1,13 +1,13 @@
      -%s\n", strtoupper(substr($host['name'], 0, 1)) ); - } - printf("
    • %s
    • ", $host['name'], $host['name']); - $l = substr($host['name'], 0, 1); +foreach ($hosts as $host) { + if (substr($host['name'], 0, 1) != $l) { + printf("
    • %s
    • \n", strtoupper(substr($host['name'], 0, 1))); + } + printf("
    • %s
    • ", $host['name'], $host['name']); + $l = substr($host['name'], 0, 1); } ?>
    diff --git a/share/pnp/application/views/mobile_pages.php b/share/pnp/application/views/mobile_pages.php index cead17f..c0f6a4f 100644 --- a/share/pnp/application/views/mobile_pages.php +++ b/share/pnp/application/views/mobile_pages.php @@ -1,9 +1,9 @@
      data->getPageDetails($page); - printf("
    • %s
    • ", $page, $this->data->PAGE_DEF['page_name']); +foreach ($pages as $page) { + $this->data->getPageDetails($page); + printf('
    • %s
    • ', $page, $this->data->PAGE_DEF['page_name']); } ?>
    diff --git a/share/pnp/application/views/mobile_search.php b/share/pnp/application/views/mobile_search.php index e8573d1..3e9266b 100644 --- a/share/pnp/application/views/mobile_search.php +++ b/share/pnp/application/views/mobile_search.php @@ -1,11 +1,11 @@ -isAuthorizedFor('host_search') ){ ?> +isAuthorizedFor('host_search')) { ?>
    - +
    @@ -16,8 +16,8 @@
      result as $host){ - printf("
    • %s
    • ", $host, $host); +foreach ($this->result as $host) { + printf('
    • %s
    • ', $host, $host); } ?>
    diff --git a/share/pnp/application/views/mobile_special.php b/share/pnp/application/views/mobile_special.php index 786d109..f345bbf 100644 --- a/share/pnp/application/views/mobile_special.php +++ b/share/pnp/application/views/mobile_special.php @@ -1,8 +1,8 @@
      %s", $template, $template); +foreach ($templates as $template) { + printf('
    • %s
    • ', $template, $template); } ?>
    diff --git a/share/pnp/application/views/multisite_box.php b/share/pnp/application/views/multisite_box.php index 13d64de..2058064 100644 --- a/share/pnp/application/views/multisite_box.php +++ b/share/pnp/application/views/multisite_box.php @@ -1,14 +1,14 @@
    - +
    -Host: ".html::specialchars(pnp::shorten($host))."
    \n"; +Host: ' . html::specialchars(pnp::shorten($host)) . "
    \n"; } -if(isset($service) && $service != "Host Perfdata"){ - echo "Service: ".html::specialchars(pnp::shorten($service))."\n"; +if (isset($service) && $service != 'Host Perfdata') { + echo 'Service: ' . html::specialchars(pnp::shorten($service)) . "\n"; } ?>
    diff --git a/share/pnp/application/views/page.php b/share/pnp/application/views/page.php index ac285c3..bdc4dbf 100644 --- a/share/pnp/application/views/page.php +++ b/share/pnp/application/views/page.php @@ -1,48 +1,64 @@
    - + -
    - -
    -
    - + +
    +
    +
    -
    - +
    + - + - + - + - + - - -
    + + +
    +
    -
    +
    diff --git a/share/pnp/application/views/pages_box.php b/share/pnp/application/views/pages_box.php index d2297f4..7a319dd 100644 --- a/share/pnp/application/views/pages_box.php +++ b/share/pnp/application/views/pages_box.php @@ -1,29 +1,34 @@ -isAuthorizedFor('pages') ) { ?> +isAuthorizedFor('pages')) { ?>
    - +
    -session->get('pfilter'); -?> + session->get('pfilter'); + ?> -
    - " - ?> +
    + ' + ?>
    -"; - $this->data->getPageDetails($page); - echo "data->PAGE_DEF['page_name']."\">".pnp::shorten($this->data->PAGE_DEF['page_name'])."
    \n"; - echo "\n"; -} -?> + '; + $this->data->getPageDetails($page); + echo '' . + pnp::shorten($this->data->PAGE_DEF['page_name']) . + "
    \n"; + echo "\n"; + } + ?>

    - + data->STRUCT as $KEY=>$VAL){ - $source = $VAL['SOURCE']; - echo "\n"; - echo "\n"; - echo "\n"; +foreach ($this->data->STRUCT as $KEY => $VAL) { + $source = $VAL['SOURCE']; + echo "\n"; + echo '\n"; + echo "\n"; } ?> diff --git a/share/pnp/application/views/search_box.php b/share/pnp/application/views/search_box.php index b15c212..e8f3191 100644 --- a/share/pnp/application/views/search_box.php +++ b/share/pnp/application/views/search_box.php @@ -1,17 +1,17 @@ -isAuthorizedFor('host_search') ){ ?> +isAuthorizedFor('host_search')) { ?>

    - +
    @@ -19,4 +19,6 @@ jQuery(function() {

    - + isAuthorizedFor('service_links') ) { ?> +isAuthorizedFor('service_links')) { ?>

    - +
    -session->get('sfilter'); -?> + ?>
    - " - ?> + ' + ?>
    -\n"; - $path = pnp::addToUri( array('host' => $host, 'srv' => $service['name']) ); - echo pnp::add_to_basket_icon($host, - $service['name']); + \n"; + $path = pnp::addToUri(['host' => $host, 'srv' => $service['name']]); + echo pnp::add_to_basket_icon( + $host, + $service['name'] + ); - echo ""; - echo pnp::shorten($service['servicedesc']). - "
    \n"; - echo "\n"; -} -?> + echo ''; + echo pnp::shorten($service['servicedesc']) . "
    \n"; + echo "\n"; + } + ?>

    - + templates) && $this->isAuthorizedFor('service_links') ) { ?> +templates) && $this->isAuthorizedFor('service_links')) { ?>

    - +
    -session->get('spfilter'); -?> + ?>
    - " - ?> + " + ?>
    -templates as $template){ - echo ""; - $path = pnp::addToUri( array('tpl' => $template) ); - echo "". - pnp::shorten($template). - "
    \n"; - echo "
    \n"; -} -?> + templates as $template) { + echo ""; + $path = pnp::addToUri(array('tpl' => $template)); + echo "" . + pnp::shorten($template) . + "
    \n"; + echo "
    \n"; + } + ?>

    diff --git a/share/pnp/application/views/status_box.php b/share/pnp/application/views/status_box.php index 4745c6b..bf8e350 100644 --- a/share/pnp/application/views/status_box.php +++ b/share/pnp/application/views/status_box.php @@ -3,16 +3,26 @@

    -Host: ". - html::anchor('graph'. - "?host=".$lhost, - html::specialchars(pnp::shorten($host))."
    ");?> -Service: " . - html::anchor('graph'. - "?host=".$lhost. - "&srv=".$lservice, - html::specialchars(pnp::shorten($service))."
    ");?> -Last Check: $timet
    "?> +Host: " . + html::anchor( + 'graph' . + "?host=" . $lhost, + html::specialchars(pnp::shorten($host)) . "
    " + ); +}?> +Service: " . + html::anchor( + 'graph' . + "?host=" . $lhost . + "&srv=" . $lservice, + html::specialchars(pnp::shorten($service)) . "
    " + ); +}?> +Last Check: $timet
    "; +}?>

    diff --git a/share/pnp/application/views/template.php b/share/pnp/application/views/template.php index 0cce888..9d2030d 100644 --- a/share/pnp/application/views/template.php +++ b/share/pnp/application/views/template.php @@ -1,15 +1,17 @@ - + -<?php if (isset($this->title)) echo html::specialchars($this->title) ?> +<?php if (isset($this->title)) { + echo html::specialchars($this->title); + } ?> -theme.'/jquery-ui.css') ?> - +theme . '/jquery-ui.css') ?> + @@ -20,12 +22,12 @@ jQuery(window).load( function() { jQuery('div.graph').each(function(){ - var img_width = jQuery(this).next('img').width(); - var rrd_width = parseInt(jQuery(this).css('width')); - var left = img_width - rrd_width - config->conf['right_zoom_offset'] ?>; - jQuery(this).css('left', left); - jQuery(this).css('cursor', 'e-resize'); - jQuery(this).attr('title', 'Click to zoom in'); + var img_width = jQuery(this).next('img').width(); + var rrd_width = parseInt(jQuery(this).css('width')); + var left = img_width - rrd_width - config->conf['right_zoom_offset'] ?>; + jQuery(this).css('left', left); + jQuery(this).css('cursor', 'e-resize'); + jQuery(this).attr('title', 'Click to zoom in'); }); jQuery('img.goto').css('visibility', 'visible'); @@ -33,50 +35,51 @@ jQuery(window).load( fadeSpeed: 500, onSelectEnd: redirect, minHeight: 'config->conf['graph_height'] ?>' }); function redirect(img, selection) { - if (!selection.width || !selection.height) - return; + if (!selection.width || !selection.height) + return; - var graph_width = parseInt(jQuery(img).css('width')); - var link = jQuery(img).attr('id'); - var ostart = Math.abs(jQuery(img).attr('start')); - var oend = Math.abs(jQuery(img).attr('end')); - var delta = (oend - ostart); - if( delta < 600 ) - delta = 600; - var sec_per_px = parseInt( delta / graph_width); - var start = ostart + Math.ceil( selection.x1 * sec_per_px ); - var end = ostart + ( selection.x2 * sec_per_px ); - window.location = link + '&start=' + start + '&end=' + end ; + var graph_width = parseInt(jQuery(img).css('width')); + var link = jQuery(img).attr('id'); + var ostart = Math.abs(jQuery(img).attr('start')); + var oend = Math.abs(jQuery(img).attr('end')); + var delta = (oend - ostart); + if( delta < 600 ) + delta = 600; + var sec_per_px = parseInt( delta / graph_width); + var start = ostart + Math.ceil( selection.x1 * sec_per_px ); + var end = ostart + ( selection.x2 * sec_per_px ); + window.location = link + '&start=' + start + '&end=' + end ; } - - var sfilter = "session->get('sfilter') ?>"; - var spfilter = "session->get('spfilter') ?>"; - var pfilter = "session->get('pfilter') ?>"; - - if(jQuery("#service-filter").length) { - console.log("send keyup") - jQuery("#service-filter").keyup() - } - if(jQuery("#special-filter").length) { - jQuery("#special-filter").keyup() - } - if(jQuery("#page-filter").length) { - jQuery("#page-filter").keyup() - } + + var sfilter = "session->get('sfilter') ?>"; + var spfilter = "session->get('spfilter') ?>"; + var pfilter = "session->get('pfilter') ?>"; + + if(jQuery("#service-filter").length) { + console.log("send keyup") + jQuery("#service-filter").keyup() + } + if(jQuery("#special-filter").length) { + jQuery("#special-filter").keyup() + } + if(jQuery("#page-filter").length) { + jQuery("#page-filter").keyup() + } }); jQuery(document).ready(function(){ - var path = ""; + var path = ""; jQuery("img").fadeIn(1500); jQuery("#basket_action_add a").live("click", function(){ var item = (this.id) + var token = "session->get('csrf_token') ?>" jQuery.ajax({ type: "POST", url: path + "ajax/basket/add", - data: { item: item }, + data: { item: item, "csrf_token": token }, success: function(msg){ jQuery("#basket_items").html(msg); - window.location.reload() + window.location.reload() } }); }); @@ -85,34 +88,36 @@ jQuery(document).ready(function(){ type: "POST", url: path + "ajax/basket/clear", success: function(msg){ - window.location.reload() + window.location.reload() } }); }); jQuery("#basket-show").live("click", function(){ - window.location.href = path + 'page/basket' + window.location.href = path + 'page/basket' }); jQuery(".basket_action_remove a").live("click", function(){ var item = (this.id) + var token = "session->get('csrf_token') ?>" jQuery.ajax({ type: "POST", url: path + "ajax/basket/remove/", - data: { item: item }, + data: { item: item, "csrf_token": token }, success: function(msg){ jQuery("#basket_items").html(msg); - window.location.reload() + window.location.reload() } }); }); jQuery("#basket_items" ).sortable({ update: function(event, ui) { - var items = jQuery(this).sortable('toArray').toString(); + var token = "session->get('csrf_token') ?>" + var items = jQuery(this).sortable('toArray').toString(); jQuery.ajax({ type: "POST", url: path + "ajax/basket/sort", - data: { items: items }, + data: { items: items, "csrf_token": token }, success: function(msg){ - window.location.reload() + window.location.reload() } }); } @@ -128,18 +133,19 @@ jQuery(document).ready(function(){ }); }); - jQuery("#service-filter").keyup(function () { + jQuery("#service-filter").keyup(function () { var sfilter = jQuery("#service-filter").val(); - if(sfilter != "") { - jQuery("#service-filter").css('background-color','#ff9999'); - }else{ - jQuery("#service-filter").css('background-color','white'); - } - jQuery.ajax({ - type: "POST", - url: path + "ajax/filter/set-sfilter", - data: { sfilter: sfilter } - }); + if(sfilter != "") { + jQuery("#service-filter").css('background-color','#ff9999'); + }else{ + jQuery("#service-filter").css('background-color','white'); + } + var token = "session->get('csrf_token') ?>" + jQuery.ajax({ + type: "POST", + url: path + "ajax/filter/set-sfilter", + data: { sfilter: sfilter, "csrf_token": token } + }); jQuery("#services span[id^='service']").each(function () { if (jQuery(this).attr('id').search(new RegExp("service-.*" + sfilter,"i")) == 0) { jQuery(this).show(); @@ -149,18 +155,19 @@ jQuery(document).ready(function(){ }); }); - jQuery("#special-filter").keyup(function () { + jQuery("#special-filter").keyup(function () { var spfilter = jQuery("#special-filter").val(); - if(spfilter != "") { - jQuery("#special-filter").css('background-color','#ff9999'); - }else{ - jQuery("#special-filter").css('background-color','white'); - } - jQuery.ajax({ - type: "POST", - url: path + "ajax/filter/set-spfilter", - data: { spfilter: spfilter } - }); + if(spfilter != "") { + jQuery("#special-filter").css('background-color','#ff9999'); + }else{ + jQuery("#special-filter").css('background-color','white'); + } + var token = "session->get('csrf_token') ?>" + jQuery.ajax({ + type: "POST", + url: path + "ajax/filter/set-spfilter", + data: { spfilter: spfilter, "csrf_token": token } + }); jQuery("#special-templates span[id^='special']").each(function () { if (jQuery(this).attr('id').search(new RegExp("special-.*" + spfilter,"i")) == 0) { jQuery(this).show(); @@ -170,18 +177,19 @@ jQuery(document).ready(function(){ }); }); - jQuery("#page-filter").keyup(function () { + jQuery("#page-filter").keyup(function () { var pfilter = jQuery("#page-filter").val(); - if(pfilter != "") { - jQuery("#page-filter").css('background-color','#ff9999'); - }else{ - jQuery("#page-filter").css('background-color','white'); - } - jQuery.ajax({ - type: "POST", - url: path + "ajax/filter/set-pfilter", - data: { pfilter: pfilter } - }); + if(pfilter != "") { + jQuery("#page-filter").css('background-color','#ff9999'); + }else{ + jQuery("#page-filter").css('background-color','white'); + } + var token = "session->get('csrf_token') ?>" + jQuery.ajax({ + type: "POST", + url: path + "ajax/filter/set-pfilter", + data: { pfilter: pfilter, "csrf_token": token } + }); jQuery("#pages span[id^='page']").each(function () { if (jQuery(this).attr('id').search(new RegExp("page-.*" + pfilter,"i")) == 0) { jQuery(this).show(); diff --git a/share/pnp/application/views/timerange_box.php b/share/pnp/application/views/timerange_box.php index f7cfd79..71cec94 100644 --- a/share/pnp/application/views/timerange_box.php +++ b/share/pnp/application/views/timerange_box.php @@ -1,26 +1,26 @@ -\n"; echo "

    \n"; -echo Kohana::lang('common.timerange-box-header')."\n"; +echo Kohana::lang('common.timerange-box-header') . "\n"; echo "
    \n"; echo "
    \n"; -$start = $this->session->get('start',''); -$end = $this->session->get('end',''); -$path = pnp::addToUri(array('start' => $start,'end' => $end)); -if($start && $end){ - echo "".Kohana::lang('common.timerange-selector-link')."
    \n"; +$start = $this->session->get('start', ''); +$end = $this->session->get('end', ''); +$path = pnp::addToUri(array('view' => '', 'start' => $start,'end' => $end)); +if ($start && $end) { + echo "" . Kohana::lang('common.timerange-selector-link') . "
    \n"; } -if($start && !$end){ - echo "".Kohana::lang('common.timerange-selector-link')."
    \n"; +if ($start && !$end) { + echo "" . Kohana::lang('common.timerange-selector-link') . "
    \n"; } $path = pnp::addToUri(array('view' => '', 'start' => '', 'end' => '')); -echo "".Kohana::lang('common.timerange-selector-overview')."
    \n"; +echo "" . Kohana::lang('common.timerange-selector-overview') . "
    \n"; -foreach($this->config->views as $key=>$view){ - $path = pnp::addToUri(array('view' => $key, 'start' => '', 'end' => '')); - echo "".$view['title']."
    \n"; +foreach ($this->config->views as $key => $view) { + $path = pnp::addToUri(array('view' => $key, 'start' => '', 'end' => '')); + echo "" . $view['title'] . "
    \n"; } echo "
    \n"; echo "

    \n"; -?> diff --git a/share/pnp/application/views/timerange_select.php b/share/pnp/application/views/timerange_select.php index 86ee344..6e7e704 100644 --- a/share/pnp/application/views/timerange_select.php +++ b/share/pnp/application/views/timerange_select.php @@ -1,37 +1,53 @@ -config->conf['use_calendar']){ -$start = $this->session->get('start',''); -$end = $this->session->get('end',''); -?> +config->conf['use_calendar']) { + $start = $this->session->get('start', ''); + $end = $this->session->get('end', ''); + ?>

    - + +
    Title diff --git a/share/pnp/application/views/widget_menu.sample.php b/share/pnp/application/views/widget_menu.sample.php index 6201301..1159c52 100644 --- a/share/pnp/application/views/widget_menu.sample.php +++ b/share/pnp/application/views/widget_menu.sample.php @@ -1,4 +1,9 @@ - +
    Title diff --git a/share/pnp/application/views/zoom.php b/share/pnp/application/views/zoom.php index 21678be..f2cbb32 100644 --- a/share/pnp/application/views/zoom.php +++ b/share/pnp/application/views/zoom.php @@ -1,37 +1,37 @@ - - -theme.'/jquery-ui.css') ?> - - - - + + +theme . '/jquery-ui.css'); ?> + + + + @@ -50,76 +50,78 @@ jQuery.noConflict();
    - +
    -

    data->TIMERANGE['f_start']?> --- data->TIMERANGE['f_end']?>

    +

    data->TIMERANGE['f_start']; ?> --- data->TIMERANGE['f_end']; ?>

    -url."\" >
    "; -if(!empty($tpl)){ - echo ""; -}else{ - $srv = urlencode($srv); - echo ""; -} -$start_down = $this->data->TIMERANGE['start'] - intval(($this->data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2); -$path = pnp::addToUri( array('start' => $start_down)); -printf("\n", - $path, - "Move Start to ".date($this->config->conf['date_fmt'],$start_down), - url::base()."media/images/go-left.png", - 10 +url . '" >
    '; +if (!empty($tpl)) { + echo ""; +} else { + $srv = urlencode($srv); + echo "data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2)); +$path = pnp::addToUri(['start' => $start_down]); +printf( + "\n", + $path, + 'Move Start to ' . date($this->config->conf['date_fmt'], $start_down), + url::base() . 'media/images/go-left.png', + 10 ); -$start_up = $this->data->TIMERANGE['start'] + intval(($this->data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2); -$path = pnp::addToUri( array('start' => $start_up)); -printf("\n", - $path, - "Move Start to ".date($this->config->conf['date_fmt'],$start_up), - url::base()."media/images/go-right.png", - 60 +$start_up = ($this->data->TIMERANGE['start'] + intval(($this->data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2)); +$path = pnp::addToUri(['start' => $start_up]); +printf( + "\n", + $path, + 'Move Start to ' . date($this->config->conf['date_fmt'], $start_up), + url::base() . 'media/images/go-right.png', + 60 ); -$path = pnp::addToUri( array('end' => time() )); -printf("\n", - $path, - "Move End to ".date($this->config->conf['date_fmt'],time()), - url::base()."media/images/go-now.png", - 10 +$path = pnp::addToUri(['end' => time() ]); +printf( + "\n", + $path, + 'Move End to ' . date($this->config->conf['date_fmt'], time()), + url::base() . 'media/images/go-now.png', + 10 ); -$end_up = $this->data->TIMERANGE['end'] + intval(($this->data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2); -$path = pnp::addToUri( array('end' => $end_up)); -printf("\n", - $path, - "Move End to ".date($this->config->conf['date_fmt'],$end_up), - url::base()."media/images/go-right.png", - 60 +$end_up = ($this->data->TIMERANGE['end'] + intval(($this->data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2)); +$path = pnp::addToUri(['end' => $end_up]); +printf( + "\n", + $path, + 'Move End to ' . date($this->config->conf['date_fmt'], $end_up), + url::base() . 'media/images/go-right.png', + 60 ); - -$end_down = $this->data->TIMERANGE['end'] - intval(($this->data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2); -$path = pnp::addToUri( array('end' => $end_down)); -printf("\n", - $path, - "Move End to ".date($this->config->conf['date_fmt'],$end_down), - url::base()."media/images/go-left.png", - 110 + +$end_down = ($this->data->TIMERANGE['end'] - intval(($this->data->TIMERANGE['end'] - $this->data->TIMERANGE['start']) / 2)); +$path = pnp::addToUri(['end' => $end_down]); +printf( + "\n", + $path, + 'Move End to ' . date($this->config->conf['date_fmt'], $end_down), + url::base() . 'media/images/go-left.png', + 110 ); - + ?>
    @@ -127,4 +129,3 @@ printf(" - diff --git a/share/pnp/application/views/zoom_header.php b/share/pnp/application/views/zoom_header.php index 43fb810..14532d0 100644 --- a/share/pnp/application/views/zoom_header.php +++ b/share/pnp/application/views/zoom_header.php @@ -1,4 +1,4 @@ function Gzoom (url) { -GzoomWindow = window.open(url, "PNP4Nagios", "width=,height=,location=no,status=no,resizable=yes,scrollbars=yes"); +GzoomWindow = window.open(url, "PNP4Nagios", "width=,height=,location=no,status=no,resizable=yes,scrollbars=yes"); GzoomWindow.focus(); } diff --git a/share/pnp/documents/de_DE/about.html b/share/pnp/documents/de_DE/about.html index 12370fd..95c2192 100644 --- a/share/pnp/documents/de_DE/about.html +++ b/share/pnp/documents/de_DE/about.html @@ -78,7 +78,7 @@ Mehrere Datenreihen werden durch Leerzeichen getrennt. Die eigentlichen Daten d&
  • RRDtool ab 1.x; besser 1.2, aber nicht zwingend.
    Achtung: wird RRDtool ohne Paket-Manager installiert, fehlen anschließend möglicherweise die dejavu-Fonts. Das äußert sich z.B. durch fehlende Schriften in den Grafiken
  • -
  • +
  • PHP >= 5.1.6 für das Webfrontend basierend auf Kohana
  • Nagios >= 2.x oder Icinga
  • @@ -103,7 +103,7 @@ PNP ist unter der Sourceforge.Net organisiert. PNP ist dort unter dem Projektnamen “PNP4Nagios” registriert. +Die Entwicklung von PNP wird auf Sourceforge.Net organisiert. PNP ist dort unter dem Projektnamen “PNP4Nagios” registriert.

    @@ -119,7 +119,7 @@ Mit der Version 0.6.x wurde von SVN auf GIT zum Verwalten des Sourcecodes gewech

    -Die aktuelle Entwicklung ist jederzeit unter https://github.com/lingej/pnp4nagios einzusehen. Beim Klicken auf pnp4nagios-head.tar.gz wird ein Archiv mit der letzten Version heruntergeladen. +Die aktuelle Entwicklung ist jederzeit unter https://github.com/pnp4nagios einzusehen. Beim Klicken auf pnp4nagios-head.tar.gz wird ein Archiv mit der letzten Version heruntergeladen.

    @@ -129,7 +129,9 @@ Die aktuelle Entwicklung ist jederzeit unter http://docs.pnp4nagios.org/de/pnp-0.6/verify genannten Punkte geprüft wurden. + VOR dem Stellen von Support-Anfragen sollte sichergestellt werden, dass die unter http://docs.pnp4nagios.org/de/pnp-0.6/verify genannten Punkte geprüft wurden. + + Sehen Sie: https://github.com/pnp4nagios/pnp4nagios/issues.

    @@ -166,7 +168,7 @@ Weiterhin können die Mailinglisten auf Sourceforge verwendet werden. Dort i

    -Die Performance-Daten werden mit Hilfe von RRDtool in sogenannten Round-Robin-Datenbanken gespeichert, die wie ein Ringpuffer funktionieren. Das bedeutet, dass nach einer gewissen Zeit die ältesten Daten “hinten” herausfallen und “vorne” durch neue ersetzt werden. +Die Performance-Daten werden mit Hilfe von RRDtool in sogenannten Round-Robin-Datenbanken gespeichert, die wie ein Ringpuffer funktionieren. Das bedeutet, dass nach einer gewissen Zeit die ältesten Daten “hinten” herausfallen und “vorne” durch neue ersetzt werden.

    @@ -183,4 +185,4 @@ Durch die Speicherung in diesem Format ändert sich die Dateigröße nac

    - \ No newline at end of file + diff --git a/share/pnp/documents/de_DE/advanced.html b/share/pnp/documents/de_DE/advanced.html index 5293e34..23b7531 100644 --- a/share/pnp/documents/de_DE/advanced.html +++ b/share/pnp/documents/de_DE/advanced.html @@ -61,7 +61,7 @@ define command{

    -Das Plugin check_multi ist eines der ersten Plugins, das die Funktionen von Nagios 3.0 richtig ausschöpft. Check_Multi ist in der Lage, mehrere Nagios-Plugins auszuführen, aber für Nagios als einen Service darzustellen. Die Ausgabe von check_multi erfolgt über mehrere Zeilen, um die Masse an Informationen wieder darstellen zu können. +Das Plugin check_multi ist eines der ersten Plugins, das die Funktionen von Nagios 3.0 richtig ausschöpft. Check_Multi ist in der Lage, mehrere Nagios-Plugins auszuführen, aber für Nagios als einen Service darzustellen. Die Ausgabe von check_multi erfolgt über mehrere Zeilen, um die Masse an Informationen wieder darstellen zu können.

    @@ -69,7 +69,7 @@ Daraus ergaben sich jedoch einige Schwierigkeiten für PNP. PNP muss aus den

    - +

    @@ -78,4 +78,4 @@ Daraus ergaben sich jedoch einige Schwierigkeiten für PNP. PNP muss aus den

    - \ No newline at end of file + diff --git a/share/pnp/documents/de_DE/config.html b/share/pnp/documents/de_DE/config.html index 8160faa..7a0c916 100644 --- a/share/pnp/documents/de_DE/config.html +++ b/share/pnp/documents/de_DE/config.html @@ -369,7 +369,7 @@ PNP4Nagios kann seit Version 0.6.12 als Gearman-Worker betrieben werden. So sind

    -Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter http://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben. +Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter https://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben.

    diff --git a/share/pnp/documents/de_DE/doc_complete.html b/share/pnp/documents/de_DE/doc_complete.html index 2c4d62c..74a301f 100644 --- a/share/pnp/documents/de_DE/doc_complete.html +++ b/share/pnp/documents/de_DE/doc_complete.html @@ -1,14 +1,12 @@ - - -

    +
    -

    Neues in PNP 0.6.x

    -
    +

    Neues in PNP 0.6.x

    +

    -PNP 0.6.x Preview +PNP 0.6.x Preview

    @@ -20,7 +18,7 @@ Mit Version 0.6.x steigen wir von Subversion auf GIT um. Der Sourcecode ist bere

    -http://pnp4nagios.git.sourceforge.net +https://github.com/pnp4nagios

    @@ -29,11 +27,11 @@ Mit Version 0.6.x steigen wir von Subversion auf GIT um. Der Sourcecode ist bere

      -
    • Webfrontend basiert auf Kohana
      +
    • Webfrontend basiert auf Kohana
    • -
    • Webfrontend basiert auf jQuery Themes
      +
    • Webfrontend basiert auf jQuery Themes
    • -
    • Javascript-Funktionen über jQuery Plugins
      +
    • Javascript-Funktionen über jQuery Plugins
    • process_perfdata.pl wird in der Lage sein, pro Datenreihe eine eigene RRD-Datenbank zu verwenden.
    • @@ -68,19 +66,16 @@ Mit Version 0.6.x steigen wir von Subversion auf GIT um. Der Sourcecode ist bere

    - -
    -
    +
    -

    Über PNP

    +

    Über PNP

    - +

    Anforderungen an Plugins

    @@ -144,7 +139,7 @@ Mehrere Datenreihen werden durch Leerzeichen getrennt. Die eigentlichen Daten d&

    - +

    Benötigte Software

      @@ -153,7 +148,7 @@ Mehrere Datenreihen werden durch Leerzeichen getrennt. Die eigentlichen Daten d&
    • RRDtool ab 1.x; besser 1.2, aber nicht zwingend.
      Achtung: wird RRDtool ohne Paket-Manager installiert, fehlen anschließend möglicherweise die dejavu-Fonts. Das äußert sich z.B. durch fehlende Schriften in den Grafiken
    • -
    • PHP >= 5.1.6 für das Webfrontend basierend auf Kohana
      +
    • PHP >= 5.1.6 für das Webfrontend basierend auf Kohana
    • Nagios >= 2.x oder Icinga
    • @@ -162,7 +157,7 @@ Achtung: wird RRDtool ohne Paket-Manager installiert, fehlen anschließend m&oum
    - +

    Lizenz

    @@ -172,13 +167,13 @@ PNP ist unter der

    Download

    -Die Entwicklung von PNP wird auf Sourceforge.Net organisiert. PNP ist dort unter dem Projektnamen “PNP4Nagios” registriert. +Die Entwicklung von PNP wird auf Sourceforge.Net organisiert. PNP ist dort unter dem Projektnamen “PNP4Nagios” registriert.

    @@ -194,11 +189,11 @@ Mit der Version 0.6.x wurde von SVN auf GIT zum Verwalten des Sourcecodes gewech

    -Die aktuelle Entwicklung ist jederzeit unter https://github.com/lingej/pnp4nagios einzusehen. Beim Klicken auf pnp4nagios-head.tar.gz wird ein Archiv mit der letzten Version heruntergeladen. +Die aktuelle Entwicklung ist jederzeit unter https://github.com/pnp4nagios einzusehen. Beim Klicken auf pnp4nagios-head.tar.gz wird ein Archiv mit der letzten Version heruntergeladen.

    - +

    Support

    @@ -235,13 +230,13 @@ Weiterhin können die Mailinglisten auf Sourceforge verwendet werden. Dort i

    - +

    Datenhaltung

    -Die Performance-Daten werden mit Hilfe von RRDtool in sogenannten Round-Robin-Datenbanken gespeichert, die wie ein Ringpuffer funktionieren. Das bedeutet, dass nach einer gewissen Zeit die ältesten Daten “hinten” herausfallen und “vorne” durch neue ersetzt werden. +Die Performance-Daten werden mit Hilfe von RRDtool in sogenannten Round-Robin-Datenbanken gespeichert, die wie ein Ringpuffer funktionieren. Das bedeutet, dass nach einer gewissen Zeit die ältesten Daten “hinten” herausfallen und “vorne” durch neue ersetzt werden.

    @@ -258,15 +253,12 @@ Durch die Speicherung in diesem Format ändert sich die Dateigröße nac

    - -
    -
    +
    +
    -

    Die Kunst Daten zu sammeln

    +

    Die Kunst Daten zu sammeln

    @@ -288,18 +280,18 @@ Bevor Ihr euch auf einen Modus festlegt, lest euch alles durch und entscheidet s

    - +

    Die Modi im Vergleich

    - +

    Synchronous Mode

    -Der “Sync Mode” ist der einfachste und am leichtesten einzurichten. Nagios ruft für jeden Service (bzw. Host) zusätzlich das Perl-Script process_perfdata.pl auf, um die Daten zu verarbeiten. +Der “Sync Mode” ist der einfachste und am leichtesten einzurichten. Nagios ruft für jeden Service (bzw. Host) zusätzlich das Perl-Script process_perfdata.pl auf, um die Daten zu verarbeiten.

    @@ -308,12 +300,12 @@ Dieser Modus belastet aber auch Nagios am meisten, daher ist es auch in kleinen

    - +

    Bulk Mode

    -Im Bulk-Mode schreibt Nagios die benötigten Daten in eine temporäre Datei. Nach Ablauf einer definierten Zeit wird die Datei an einem Stück abgearbeitet und gelöscht. +Im Bulk-Mode schreibt Nagios die benötigten Daten in eine temporäre Datei. Nach Ablauf einer definierten Zeit wird die Datei an einem Stück abgearbeitet und gelöscht.

    @@ -340,13 +332,13 @@ Auszug aus var/perfdata.log:

    - +

    Bulk Mode mit NPCD

    -Dies ist aus Nagios-Sicht die sauberste Art der Verarbeitung. Nagios wird nicht blockiert. +Dies ist aus Nagios-Sicht die sauberste Art der Verarbeitung. Nagios wird nicht blockiert.

    @@ -358,7 +350,7 @@ Der NPCD ( Nagios Performance C Daemon ) überwacht nun das Verzeichnis auf

    - +

    Bulk Mode mit npcdmod

    @@ -369,7 +361,7 @@ Der NPCD ( Nagios Performance C Daemon ) überwacht nun das Verzeichnis auf

    -In diesem Szenario kommt npcdmod.o, ein NEB-Modul, zum Einsatz. +In diesem Szenario kommt npcdmod.o, ein NEB-Modul, zum Einsatz. Diese Modul reduziert die Konfiguration des “Bulk Mode mit NPCD” auf zwei Zeilen in der nagios.cfg.

    @@ -378,12 +370,12 @@ Dieser Modus ist gleichzusetzen mit dem “Bulk Mode mit NPCD”. Es ist auch ge

    - +

    Gearman Mode

    - +

    @@ -391,11 +383,11 @@ PNP4Nagios kann seit Version 0.6.12 als Gearman Worker betrieben werden. So sind

    -Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter http://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben. +Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter https://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben.

    - +

    Die Entscheidung

    @@ -414,20 +406,549 @@ Die verwendeten Begriffe werden euch aber in der Dokumentation immer wieder &uum

    - +
    + + + +

    PNP 0.6.x Downloads

    +
    +
    + +

    Current stable PNP Version

    +
    + +

    + +Changes can be tracked on https://github.com/pnp4nagios +

    + +

    +with releases and downloads at https://github.com/pnp4nagios/pnp4nagios/releases +

    + +

    +Latest release and downloads at https://github.com/pnp4nagios/pnp4nagios/releases/latest +

    -
    + +

    Documentation

    +
    + +

    + +Documentation +

    + + +
    + +

    + +Last Update: Mon Aug 21 17:49:39 CEST 2017 +

    + +
    + +

    ChangeLog

    +
    +

    +pnp-0.6.27-4 09/05/2023 +

    • update URLs and related text
    • +
    • clean up autoconf stuff
    • +
    +

    +pnp-0.6.27 08/18/2023 +

    • >many php 8.2 fixes to remove 'deprecated' errors:
    • +
    • pre-defining class variables (instead of dynamic),
    • +
    • explicitly re-creating arrays as needed
    • +
    • converting utf8_encode to mbstring
    • +
    +

    +pnp-0.6.26-2 09/18/2022 +

    • various php8 fixes
    • +
    • rrdtools needs env XDG_CACHE_HOME for fontconfig
    • +
    • fix so that 'bucket' display works
    • +
    • fix so that pdf generation works
    • +
    +

    +pnp-0.6.?? ??/??/2015 +

    + +

    +pnp-0.6.26 08/21/2017 +

    +
      +
    • Bugfix: Use complete option arguments for compatibility with rrdtool 1.6.0 (sbraz)
      +
    • +
    • Bugfix: Zoom on a special template not possbile (stinnux)
      +
    • +
    • Update: Update for FPDF (1.81) and FPDI (1.6.1) (Jan T. Bein )
      +
    • +
    • Bugfix: address behaviour of rrdtool1.5+ tp not export timestamp by default
      +
    • +
    • Feature: Template for icinga2's built-in icinga check (Tontonitch)
      +
    • +
    • Bugfix: fix non well formed numeric value encountered (sni)
      +
    • +
    + +

    + +pnp-0.6.25 01/03/2015 +

    +
      +
    • Update: FPDF Update to Version 1.7
      +
    • +
    • Bugfix: Default source fixed by AWiddersheim
      +
    • +
    • Bugfix: Fixed urlencoding of Host- and Servicenames by Andreas Doehler
      +
    • +
    • Bugfix: Fixed Timeranges by AWiddersheim
      +
    • +
    + +

    + +pnp-0.6.24 07/30/2014 +

    +
      +
    • Bugfix: Fixed some more XSS issues
      +
    • +
    • Bugfix: Fixed PHP issue while running on PHP 5.6 ( Reported by Sven Nierlein )
      +
    • +
    + +

    + +pnp-0.6.22 06/04/2014 +

    +
      +
    • Bugfix: Fixed livestatus socket parsing ( Pekka Panula )
      +
    • +
    • Bugfix: Update check_mssql_health.php ( Miriam Zenk )
      +
    • +
    • Feature: Add “version=tiny” to got get a stripped down version of graph ( Ricardo Bartels )
      +
    • +
    • feature: Add STDIN Mode to process_perfdata.pl ( Robert Steininger )
      +
    • +
    • Bugfix: XSS issue fixed by Mikael Falkvidd. This issue was detected by Peter Österberg at Hexbit AB in a security assessment of op5 Monitor 6.3 on assignment by op5 AB.
      +
    • +
    + +

    + +pnp-0.6.21 03/24/2013 +

    +
      +
    • Feature: Helper functions rrd::alerter and rrd:alerter_gr both supports treshold detection (Martin Schirrmacher)
      +
    • +
    • Update: jQuery Mobile update to 1.3.0 ( was broken in 0.6.20 )
      +
    • +
    + +

    + +pnp-0.6.20 03/03/2013 +

    +
      +
    • Feature: Support check_mk Multisite Cookie Auth ( Lars Michelsen )
      +
    • +
    • Feature: Allow RRD unknown values ( Simon Meggle )
      +
    • +
    • feature: Interactive delete mode added to check_rrds.pl ( Simon Meggle )
      +
    • +
    • Bugfix: Allow multiple gearman servers ( Craig Barraclough )
      +
    • +
    • Bugfix: Fixed Graph Search ( Stefan Triep )
      +
    • +
    • Update: jQuery update to 1.8.1
      +
    • +
    • Update: jQueryUI update to 1.8.23
      +
    • +
    + +

    + +pnp-0.6.19 09/01/2012 +

    +
      +
    • Feature: Parameter “width” added to popup controller ( Andreas Doehler )
      +
    • +
    • Fix: simplify/improve apache rules ( Christoph Anton Mitterer )
      +
    • +
    • Fix: Check for missing PHP GD functions
      +
    • +
    • Bugfix: socketDOMAIN changed to AF_INET while using livstatus tcp socket ( Rene Koch )
      +
    • +
    + +

    + +pnp-0.6.18 06/28/2012 +

    +
      +
    • Bugfix: Fixed STORAGE_TYPE and CUSTOM_TEMPLATE vars used in custom templates
      +
    • +
    • Bugfix: Blank screen on PHP 5.4 fixed
      +
    • +
    • Feature: Allow multiple gearman job servers
      +
    • +
    • Feature: New helper function rrd::debug()
      +
    • +
    • Feature: New templates check_jmx4perl_*.php
      +
    • +
    + +

    + +pnp-0.6.17 03/25/2012 +

    +
      +
    • Bugfix: Fixed rrd_convert.pl while running with --dry-run
      +
    • +
    • Bugfix: logging.c include missing header files ( Lars Vogdt )
      +
    • +
    • Bugfix: Check if pnp4nagios/etc/rra.cfg is readable
      +
    • +
    • Bugfix: rrd_convert.pl use XML tag TEMPLATE instead of CHECKCOMMAND to selects RRDs ( Sven Velt )
      +
    • +
    • Feature: npcdmod.o increase perfdata buffer and log discarded perfdata ( Birger Schmidt )
      +
    • +
    • Feature: rrd_modify.pl to change number of data sources of an RRD file
      +
    • +
    • Feature: New template check_apachestatus_auto.php
      +
    • +
    • Feature: Implement etc/config.d to place config snippets ( Lars Michelsen )
      +
    • +
    + +

    + +pnp-0.6.16 11/21/2011 +

    +
      +
    • Bugfix: Fixed single quoted check_multi labels (Reported by Matthias Flacke)
      +
    • +
    • Bugfix: Append missing slash to perfdata_spool_dir ( Reported by Juergen-Michael Radtke )
      +
    • +
    • Bugfix: Fixed jQuery-ui multisite theme
      +
    • +
    • Feature: PDF margins are now adjustable via config.php ( Thomas Witzenrath )
      +
    • +
    • Feature: Support for PDF size 'letter' added ( Robert Becht )
      +
    • +
    + +

    + +pnp-0.6.15 09/15/2011 +

    +
      +
    • Bugfix: Fixed Overview link (reported by Stefan Triep)
      +
    • +
    • Bugfix: Fixed zoom popup (reported by Rudolf Labuschagne)
      +
    • +
    • Bugfix: Fixed double urlencode() (reported by Mathias Kettner)
      +
    • +
    • Feature: “Clear basket” button added (suggested by Stefan Triep)
      +
    • +
    • Feature: New helper function “rrd::alerter_gr()” ( committed by Stefan Trip )
      +
    • +
    + +

    + +pnp-0.6.14 08/05/2011 +

    +
      +
    • Feature: Webinterface for mobile devices based on jQuery Mobile
      +( https://jquerymobile.com/ )
      +
    • +
    • Feature: Zoom based on jQuery plugin imgAreaSelect
      +( https://github.com/odyniec/imgareaselect )
      +
    • +
    • Feature: New template check_mssql_health.php
      +
    • +
    • Bugfix: Fixed popups to work under nginx ( Joram Agten )
      +
    • +
    • Bugfix: Helper rrd::vdef() fixed
      +
    • +
    • Update: jQuery update to 1.6.2
      +
    • +
    • Update: jQuery-ui update to 1.8.14
      +
    • +
    + +

    + +pnp-0.6.13 05/19/2011 +

    +
      +
    • Feature: New option --ignore-hosts added to check_pnp_rrds.pl ( by Jochen Bern )
      +
    • +
    • Feature: New options zgraph_width and zgraph_height in config.php ( Mike Liebsch )
      +
    • +
    • Bugfix: rrd_convert.pl: parse_xml_filename() regex fix
      +
    • +
    • Info: Version used by OMD-0.48 OMD
      +
    • +
    + +

    + +pnp-0.6.12 04/22/2011 +

    +
      +
    • Feature: mod_gearman support added
      +
    • +
    • Feature: rrd_convert.pl is now able to convert all RRDs from RRD_STORAGE_TYPE=SINGLE to RRD_STORAGE_TYPE=MULTIPLE
      +
    • +
    • Feature: New template check_gearman.php
      +
    • +
    • Feature: Install process_perfdata.cfg and npcd.cfg by default
      +
    • +
    • Bugfix: rrd_convert.pl is now able to parse xml dumps created by rrdtool 1.4.x
      +
    • +
    • Bugfix: process_perfdata.pl default timeout value set to 15 seconds
      +
    • +
    + +

    + +pnp-0.6.11 01/15/2011 +

    +
      +
    • Bugfix: urldecoding fixed
      +
    • +
    • Bugfix: Zoom in/out is working again ( Reported by Thorben Soehl )
      +
    • +
    • Featue: npcd.cfg - New option perfdata_file_processing_interval used by npcdmod
      +
    • +
    • Info: Version used by OMD-0.46 OMD
      +
    • +
    + +

    + +pnp-0.6.10 12/15/2010 + +

    +
      +
    • Feature: Add RRDTool Option --only-graph if graph height is below 32px to create thumbnails
      +
    • +
    • Feature: RRDTool Option --width and --height is now allowed in templates
      +
    • +
    • Feature: RRDTool DS Type for UOM of “c” changed from COUNTER to DERIVE
      +
    • +
    • Feature: Pass query string from special controller to image controller ( Matthew Garrett )
      +
    • +
    • Feature: Authorisation against mk_livestatus API added
      +
    • +
    • Feature: Sample nginx webserver config added ( by evax@users.sourceforge.net )
      +
    • +
    • Feature: Kohana backport to support PHP 5.1.6 ( Kudos to Andreas Ericsson )
      +
    • +
    • Bugfix: Sort list of special templates
      +
    • +
    • Bugfix: Urlencode hostname and service description ( Reported by Yannick )
      +
    • +
    • Bugfix: corrected warning/critical thresholds in ticker/alerter functions
      +
    • +
    + +

    + +pnp-0.6.7 09/27/2010 + +

    +
      +
    • Bugfix: Page config parser fix (Beau Gunderson)
      +
    • +
    • Bugfix: Zoom window size fixed (Report by Rudolf Labuschagne)
      +
    • +
    • Bugfix: Fixed undefined offset while using 'ds_name' in templates (Reported by Vladimir Bilik)
      +
    • +
    • Bugfix: Npcdmod respects process_perf_data option used in hosts and services definitions ( Reported by Wolfgang Barth )
      +
    • +
    • Template: New Template check_nagiostats.php used with check_nagiostats written by Jochen Bern
      +
    • +
    + +

    + +pnp-0.6.6 08/07/2010 + +

    +
      +
    • Bugfix: Fixed max amount of graphs per template
      +
    • +
    • Bugfix: Autodetect PNP base URL
      +
    • +
    • Bugfix: Too short npcdmod perfdata_template to take perfdata + overhead, increased +1024byte
      +
    • +
    • Bugfix: Ignore files in var/perfdata and check for empty directories
      +
    • +
    • Bugfix: Reducing memory usage while parsing page config (Laurent Freval)
      +
    • +
    + +

    + +pnp-0.6.5 07/09/2010 + +

    +
      +
    • Feature: Special Templates are back tpl_special
      +
    • +
    • Feature: New rrdtool helper functions makes template design easier tpl_helper
      +
    • +
    • Feature: config.php → 'recursive_template_search' is enabled by default
      +
    • +
    • Feature: config.php → 'template_dirs' is now an array of directorys to search for PNP templates
      +
    • +
    + +

    + +pnp-0.6.4 06/03/2010 + +

    +
      +
    • Update: jQuery Update to 1.4.2
      +
    • +
    • Update: jQuery-ui Update to 1.8
      +
    • +
    • Feature: New configure Option --with-base-url
      +
    • +
    • Template: New template check_ntp_time.php (Mathias Kettner)
      +
    • +
    • Feature: New i18n files for fr_FR (Yannig Parre)
      +
    • +
    • Feature: New jQuery Theme 'multisite'
      +
    • +
    + +

    + +pnp-0.6.3 03/16/2010 + +

    +
      +
    • Feature: New helper script libexec/rrd_convert.pl → rrd_convert
      +
    • +
    • Bugfix: Ignore old XML files while building the service list
      +
    • +
    • Template: New template check_hpasm.php
      +
    • +
    • Bugfix: Installer now checks for json_decode()
      +
    • +
    • Workaround: Allow “trailing unfilled semicolons”. Workaround for nsclient++
      +
    • +
    • Template: Updates for check_openmanage.php, check_hp_bladecenter.php and check_dell_baldecenter.php ( Trond Hasle Amundsen )”
      +
    • +
    + +

    + +pnp-0.6.2 12/23/2009 + +

    +
      +
    • Feature: XML_WRITE_DELAY option added to process_perfdata.cfg as suggested by Mathias Kettner
      +
    • +
    • Feature: New template integer.php
      +
    • +
    • Update: FPDI update to 1.3.1
      +
    • +
    • Feature: PNP will now work with lighttpd and php-cgi
      +
    • +
    • Template: check_mk-ps.perf.php added ( by Mathias Kettner )
      +
    • +
    • Feature: PNP will now work without mod_rewrite → webfe
      +
    • +
    • Bugfix: Wrong pdf link used on site 'pages' and 'basket'
      +
    • +
    • Bugfix: Incorrect group permissions on spool directory
      +
    • +
    + +

    + +pnp-0.6.1 11/22/2009 + +

    +
      +
    • Feature: RRD heartbeat per check_command → tpl_custom
      +
    • +
    • Feature: New config.php option pdf_graph_opt
      +
    • +
    • Feature: Recognize the 'background_pdf' option in page definitions → pages
      +
    • +
    • Feature: Recognize the 'source' option in page definitions → pages
      +
    • +
    • Feature: Array $TIMERANGE now available for templates → timeranges
      +
    • +
    • Bugfix: ./configure --sysconfdir no longer ignored
      +
    • +
    • Feature: Store internal runtime statistics on a per minute base
      +
    • +
    • Feature: Added two widgets views/widget_menu.php and views/widget_graph.php
      +
    • +
    + +

    + +pnp-0.6.0 10/30/2009 + +

    +
      +
    • Webfrontend based on Kohana
      +
    • +
    • Webfrontend based on jQuery Themes
      +
    • +
    • Javascript-functions using jQuery plugins
      +
    • +
    • process_perfdata.pl will be able to use one RRD database per datasource
      +
    • +
    • improved installer. Specification of directory layouts using --with-layout
      +
    • +
    • RRDtool errors are now displayed as images. no more missing images
      +
    • +
    • PNP templates cannot overwrite internal variables anymore
      +
    • +
    • PNP templates of version 0.4.x can still be used
      +
    • +
    • PDF functions recoded
      +
    • +
    • Template default.php optimized
      +
    • +
    • Export from RRD databases into XML, CSV and JSON format using the RRDtool “xport” function
      +
    • +
    • Page functions recoded
      +
    • +
    • Error pages links to online FAQ
      +
    • +
    • Mouseover Popup in Nagios frontend via jQuery.clueTip plugin
      +
    • +
    • Full support of rrdcached
      +
    • +
    + +
    + +
    +
    -

    Upgrade auf Version 0.6.x

    +

    Upgrade auf Version 0.6.x

    -Das Web-Frontend ist komplett neu geschrieben worden und basiert nun auf dem PHP MVC Framework Kohana. Somit ergeben sich grundlegend andere Abhängigkeiten, die dringend vor der Installation geprüft werden müssen. +Das Web-Frontend ist komplett neu geschrieben worden und basiert nun auf dem PHP MVC Framework Kohana. Somit ergeben sich grundlegend andere Abhängigkeiten, die dringend vor der Installation geprüft werden müssen.

    @@ -447,7 +968,7 @@ Anmerkung: Es reicht aus, die *.rrd-Dateien vom alten ins neue Verzeichnis zu ko

    - +

    Vergleich der Struktur

    @@ -503,7 +1024,7 @@ Aus diesen Infos ergeben sich die zu ändernden Parameter und somit die Upgr

    - +

    Anpassungen

    @@ -587,7 +1108,7 @@ Man sollte daran denken, alle Vorkommen in der Datei zu ändern

    Upgrade Szenario mit NPCD

      @@ -636,15 +1157,12 @@ Man sollte daran denken, alle Vorkommen in der Datei zu ändern - -
    -
    -
    +
    +
    -

    Installation

    +

    Installation

    @@ -657,7 +1175,7 @@ Bitte vergessen Sie nicht, dass PNP nach der Installation noch konfiguriert werd

    - +

    Make und Co

    @@ -789,7 +1307,7 @@ Zusammenfassen lassen sich diese einzelnen Commands durch

    - +

    Update

    @@ -806,7 +1324,7 @@ Sie können die Schritte make install-webconf und make in

    - +

    Die Komponenten

    @@ -848,15 +1366,12 @@ Die Config-Datei config.php für das Web-Frontend in

    - -
    -
    +
    +
    -

    Konfiguration

    +

    Konfiguration

    @@ -869,13 +1384,13 @@ Die bevorzugte Methode der PNP-Entwickler ist der “Bulk Mode mit NPCD und npcd

    - -

    Synchronous Mode

    + +

    Synchronous Mode

    -Der Synchronous-Mode ist die einfachste Art, den Datensammler process_perfdata.pl in Nagios zu integrieren. Hierbei wird bei jedem Ereignis ein gesondertes Command process-service-perfdata (bzw. process-host-perfdata) ausgeführt. +Der Synchronous-Mode ist die einfachste Art, den Datensammler process_perfdata.pl in Nagios zu integrieren. Hierbei wird bei jedem Ereignis ein gesondertes Command process-service-perfdata (bzw. process-host-perfdata) ausgeführt.

    @@ -945,13 +1460,13 @@ define command {

    - -

    Bulk Mode

    + +

    Bulk Mode

    -Der Bulk-Mode ist etwas komplizierter als der Synchronous-Mode, reduziert die Last auf dem Nagios Server jedoch merklich, da nun nicht mehr für jeden Service bzw. Host zusätzlich der Datensammler process_perfdata.pl gestartet werden muss. +Der Bulk-Mode ist etwas komplizierter als der Synchronous-Mode, reduziert die Last auf dem Nagios Server jedoch merklich, da nun nicht mehr für jeden Service bzw. Host zusätzlich der Datensammler process_perfdata.pl gestartet werden muss.

    @@ -1038,13 +1553,13 @@ define command{

    - +

    Bulk Mode with NPCD

    -Die Konfiguration ist identisch mit dem “Bulk Mode”, einzig das verwendete Command ist leicht abgewandelt. +Die Konfiguration ist identisch mit dem “Bulk Mode”, einzig das verwendete Command ist leicht abgewandelt.

    @@ -1149,7 +1664,7 @@ Weitere Informationen zu NPCD findet ihr

    Bulk Mode with NPCD und npcdmod

    @@ -1160,7 +1675,7 @@ Weitere Informationen zu NPCD findet ihr Bei diesem Modus kommt das Eventbroker-Modul npcdmod.o zu Einsatz. Der Datenfluss ist jedoch identisch zum “Bulk Mode mit NPCD”. Die internen Perfdata-Routinen von Nagios, die über die “*_perf_data_*” Optionen in der nagios.cfg konfiguriert werden, kommen NICHT mehr zu Einsatz. Das Modul npcdmod.o kümmert sich um die für PNP nötige Aufbereitung der Daten. + Bei diesem Modus kommt das Eventbroker-Modul npcdmod.o zu Einsatz. Der Datenfluss ist jedoch identisch zum “Bulk Mode mit NPCD”. Die internen Perfdata-Routinen von Nagios, die über die “*_perf_data_*” Optionen in der nagios.cfg konfiguriert werden, kommen NICHT mehr zu Einsatz. Das Modul npcdmod.o kümmert sich um die für PNP nötige Aufbereitung der Daten.

    @@ -1210,13 +1725,13 @@ Auszug aus den nagios.log

    - -

    Gearman Mode

    + +

    Gearman Mode

    - +

    @@ -1224,7 +1739,7 @@ PNP4Nagios kann seit Version 0.6.12 als Gearman-Worker betrieben werden. So sind

    -Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter http://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben. +Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter https://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben.

    @@ -1275,15 +1790,12 @@ werden die Performance-Daten verarbeitet, die über den gearmand-Daemon auf

    - -
    -
    +
    +
    -

    Prüfen der Installation

    +

    Prüfen der Installation

    @@ -1314,7 +1826,7 @@ ACHTUNG: Direkt nach dem (Neu-)Start von Nagios nach dem Aktivieren der Verarbei

    - +

    Logfile

    @@ -1344,7 +1856,7 @@ Spätestens bei
    - +

    Was aber wenn nicht ?

    @@ -1370,7 +1882,7 @@ In den Detailinformationen zu jedem Host/Service gibt es das Feld “Performance Das folgende Bild zeigt die Informationen zu einem “PING”-Service. Das blaue Feld enthält den vom Plugin gelieferten Text, das rote die Performance-Daten, die Nagios erkannt hat.
    -Informationen zu "PING" +Informationen zu "PING"

    @@ -1412,20 +1924,17 @@ Das Perl-Scr

    - -
    -
    +
    +
    -

    verify_pnp_config

    +

    verify_pnp_config

    -Bei Problemen kann das Perl-Script verify_pnp_config von http://verify.pnp4nagios.org helfen die aktuelle Nagios Konfiguration zu prüfen und entsprechend Hinweise zur Lösung liefern. +Bei Problemen kann das Perl-Script verify_pnp_config von https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl helfen die aktuelle Nagios Konfiguration zu prüfen und entsprechend Hinweise zur Lösung liefern.

    @@ -1441,20 +1950,20 @@ Feedback, Verbesserungsvorschläge oder Patches bitte per Mail an support@pn

    - -

    Download

    + +

    Download

    -Das Verify Script ist unter http://verify.pnp4nagios.org verfügbar. +Das Verify Script ist unter https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl verfügbar.

    -wget http://verify.pnp4nagios.org/verify_pnp_config
    +wget https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl/verify_pnp_config
     
    - +

    Test

    @@ -1551,7 +2060,7 @@ lenny:~# perl verify_pnp_config --mode npcdmod --config=/usr/local/nagios/etc/na
    - +

    Performance data

    @@ -1573,15 +2082,12 @@ Die Zeichenketten werden als reguläre Ausdrücke angesehen (
    - -
    -
    +
    +
    -

    Das Nagios Web Frontend

    +

    Das Nagios Web Frontend

    @@ -1595,7 +2101,7 @@ Da es in diesem Bereich eine Änderung zwischen Nagios 2.x und der Version 3

    - +

    Nagios 2.x

    @@ -1623,7 +2129,7 @@ define serviceextinfo {
    - +

    Nagios 3.x

    @@ -1676,7 +2182,7 @@ Die Links auf die richtigen URLs werden automagisch erstellt.

    - +

    Preview Popup

    @@ -1686,7 +2192,7 @@ Außerdem gibt es die Möglichkeit, die Graphen bereits in der Statusüb

    -Ermöglicht wird dies durch die CGI Includes, die es uns erlauben, Javascript-Code an geeigneter Stelle im Seitenkopf der Statusübersicht einzubinden ( status.cgi ). +Ermöglicht wird dies durch die CGI Includes, die es uns erlauben, Javascript-Code an geeigneter Stelle im Seitenkopf der Statusübersicht einzubinden ( status.cgi ).

    @@ -1717,7 +2223,7 @@ define service {

    Nach einem Restart von Nagios (nach Anpassung der Definitionen) sieht das Ergebnis ungefähr so aus:
    - +

    @@ -1726,15 +2232,12 @@ Nach einem Restart von Nagios (nach Anpassung der Definitionen) sieht das Ergebn

    - -
    -
    +
    +
    -

    PNP Web Frontend

    +

    PNP Web Frontend

    @@ -1748,7 +2251,7 @@ Eigene Anpassungen sollten daher in der Datei etc/config_local.php erfolgen. Sol

    - +

    etc/pnp/config.php

    @@ -1872,15 +2375,12 @@ Sie können hier auch weitere Views definieren, sollten aber dabei berü

    - -
    -
    +
    +
    -

    Timeranges

    +

    Timeranges

    @@ -1973,15 +2473,12 @@ Beispiele zur Datumsangabe:

    - -
    -
    +
    -

    Pages

    +

    Pages

    @@ -2071,15 +2568,12 @@ In einigen Fällen möchten Sie vielleicht die Anzeige auf einen Graphen

    - -
    -
    +
    -

    Datenexport

    +

    Datenexport

    @@ -2119,15 +2613,12 @@ Anstatt view können Sie auch start und/oder

    - -
    -
    +
    -

    Was sind Templates ?

    +

    Was sind Templates ?

    @@ -2140,7 +2631,7 @@ Dabei bestimmt das verwendete check_command, welches Template zur Darstellung he

    - +

    Wann wird welches Template verwendet ?

    @@ -2216,7 +2707,7 @@ Das Template default.php nimmt somit eine Sonderstellung ein und wird immer verw

    - +

    Eigene Templates erstellen

    @@ -2240,7 +2731,7 @@ PNP-Templates müssen folgende Eigenschaften besitzen:

    -Die beiden PHP-Arrays $opt[] und $def[] zusammen bilden den Aufruf von 'rrdtool graph'. Somit sind alle Optionen möglich, die RRDtool bietet. Die Optionen von RRDtool sind auf der RRDtool Homepage genauestens beschrieben. +Die beiden PHP-Arrays $opt[] und $def[] zusammen bilden den Aufruf von 'rrdtool graph'. Somit sind alle Optionen möglich, die RRDtool bietet. Die Optionen von RRDtool sind auf der RRDtool Homepage genauestens beschrieben.

    @@ -2298,7 +2789,7 @@ Die drei GPRINT Zeilen bilden die Legende des Graphen. Die aktuellen Werte werde

    - +

    Verfügbare Variablen

    @@ -2366,15 +2857,12 @@ Aus <NAGIOS_SERVICEOUTPUT> wird die Variable $NAGIOS_SE

    - -
    -
    +
    +
    -

    Custom Templates

    +

    Custom Templates

    @@ -2392,7 +2880,7 @@ Folgende Optionen können darin definiert werden:

    - +

    CUSTOM_TEMPLATE

    @@ -2444,7 +2932,7 @@ Diese Option hat nur Einfluss, wenn die RRD Datenbank neu erstellt wird.

    - +

    DATATYPE

    @@ -2468,7 +2956,7 @@ Einzelnen Datenreihen spezielle Datentypen zuweisen
    DATATYPE = GAUGE,GAUGE,COUNTER,COUNTER

    -Weitere Datentypen sind in der RRDTool-Dokumentation unter rrdcreate erklärt. +Weitere Datentypen sind in der RRDTool-Dokumentation unter rrdcreate erklärt.

    @@ -2476,7 +2964,7 @@ Diese Option hat nur Einfluss, wenn die RRD Datenbank neu erstellt wird.

    - +

    USE_MIN_ON_CREATE und USE_MAX_ON_CREATE

    @@ -2487,7 +2975,7 @@ In einigen wenigen Situationen ist es notwendig, die für RRDTool gülti

    RRD-Datenbanken lassen sich mit definierten Minimum- und Maximum-Werten anlegen. -Weitere Infos unter http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html +Weitere Infos unter https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html

    @@ -2507,7 +2995,7 @@ Diese Option hat nur Einfluss, wenn die RRD Datenbank neu erstellt wird.

    - +

    RRD_STORAGE_TYPE

    RRD_STORAGE_TYPE = SINGLE
    @@ -2540,7 +3028,7 @@ Diese Option hat nur Einfluss, wenn die RRD Datenbank neu erstellt wird.

    - +

    RRD_HEARTBEAT

    @@ -2555,7 +3043,7 @@ Nach <RRD_HEARTBEAT> Sekunden erwartet RRDtool neue Daten.

    -Mehr dazu unter http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html +Mehr dazu unter https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html

    @@ -2563,7 +3051,7 @@ Diese Option hat nur Einfluss, wenn die RRD Datenbank neu erstellt wird.

    - +

    Hints on Template Names

    @@ -2696,19 +3184,16 @@ Welche der obigen Lösungen verwendet wird, ist weitgehend Geschmacksache.

    - -
    -
    +
    +
    -

    Advanced

    +

    Advanced

    - +

    Verteilte Systeme

    @@ -2758,13 +3243,13 @@ define command{
    - +

    Das check_multi-Plugin

    -Das Plugin check_multi ist eines der ersten Plugins, das die Funktionen von Nagios 3.0 richtig ausschöpft. Check_Multi ist in der Lage, mehrere Nagios-Plugins auszuführen, aber für Nagios als einen Service darzustellen. Die Ausgabe von check_multi erfolgt über mehrere Zeilen, um die Masse an Informationen wieder darstellen zu können. +Das Plugin check_multi ist eines der ersten Plugins, das die Funktionen von Nagios 3.0 richtig ausschöpft. Check_Multi ist in der Lage, mehrere Nagios-Plugins auszuführen, aber für Nagios als einen Service darzustellen. Die Ausgabe von check_multi erfolgt über mehrere Zeilen, um die Masse an Informationen wieder darstellen zu können.

    @@ -2772,7 +3257,7 @@ Daraus ergaben sich jedoch einige Schwierigkeiten für PNP. PNP muss aus den

    - +

    @@ -2781,15 +3266,12 @@ Daraus ergaben sich jedoch einige Schwierigkeiten für PNP. PNP muss aus den

    - -
    -
    +
    +
    -

    RRDtool Cache Daemon

    +

    RRDtool Cache Daemon

    @@ -2802,7 +3284,7 @@ Eine Optimierung stellt das Sammeln und Sortieren der Daten dar. Es ist für

    -In der aktuellen RRDtool-Version ( SVN trunk 1550+ ) ist der rrdcached enthalten, der genau diese Situation verbessern soll. +In der aktuellen RRDtool-Version ( SVN trunk 1550+ ) ist der rrdcached enthalten, der genau diese Situation verbessern soll.

    @@ -2810,7 +3292,7 @@ An dieser Stelle möchte ich mich bei Florian octo Forster, Kevin Brintnall

    - +

    Arbeitsweise

    @@ -2820,7 +3302,7 @@ Der rrdcached arbeitet als Daemon im Hintergrund und öffnet einen UNIX- ode

    - +

    rrdcached

    @@ -2880,7 +3362,7 @@ Daraus ergibt sich beispielsweise ein Aufruf von rrdached mit folgenden Paramete
     rrdcached -w 1800 -z 1800 -p /tmp/rrdcached.pid -j /tmp -s nagios -m 0660 -l unix:/tmp/rrdcached.sock
    - +

    rrdtool

    @@ -2897,7 +3379,7 @@ Dies muss natürlich mit den Startoptionen des rrdcached übereinstimmen

    - +

    Integration in PNP

    @@ -2938,15 +3420,12 @@ Die passenden Optionen sind bereits in den Beispieldateien enthalten.

    - -
    -
    +
    +
    -

    NPCD

    +

    NPCD

    @@ -2955,7 +3434,7 @@ NPCD (Nagios-Perfdata-C-Daemon) wurde geschrieben, um die asynchrone Bearbeitung

    - +

    Einleitung

    @@ -2977,7 +3456,7 @@ Man kann aber auch dem Nagios-Prozess mitteilen, dass die Verarbeitung der Perfo

    - +

    Wie NPCD arbeitet

    @@ -2999,7 +3478,7 @@ Da das Format der Performance-Daten-Dateien dem Format der 'normalen'

    - +

    Vor- und Nachteile

    @@ -3038,7 +3517,7 @@ Da das Format der Performance-Daten-Dateien dem Format der 'normalen'
    - +

    NPCD Config

    @@ -3070,7 +3549,7 @@ Die -sample Datei sollte in jedem Fall in npcd.cfg umb

    - +

    npcd.cfg-sample

    @@ -3105,7 +3584,7 @@ pid_file=/var/run/npcd.pid
    - +

    Die Direktiven

      @@ -3265,11 +3744,8 @@ pid_file=/var/run/npcd.pid

    - -
    -
    +
    +

    check_procs ist ein Beispiel für ein Plugin, das keine Performance-Daten ausgibt: @@ -3300,11 +3776,8 @@ Nun wird die Zahl zusammen mit einer Bezeichnung ausgegeben.

    ./check_procs.sh -a ndo2db -w 1: -c 0:
     PROCS OK: 2 processes with args 'ndo2db'| procs=2
    - -
    -
    +
    @@ -3367,7 +3840,4 @@ Es bleibt Drittanbietern überlassen, aus den Performance-Daten Graphen zu e Quelle: https://www.monitoring-plugins.org/doc/guidelines.html#AEN200

    - diff --git a/share/pnp/documents/de_DE/dwnld.html b/share/pnp/documents/de_DE/dwnld.html deleted file mode 120000 index bc99189..0000000 --- a/share/pnp/documents/de_DE/dwnld.html +++ /dev/null @@ -1 +0,0 @@ -en_US/dwnld.html \ No newline at end of file diff --git a/share/pnp/documents/de_DE/dwnld.html b/share/pnp/documents/de_DE/dwnld.html new file mode 100644 index 0000000..c332643 --- /dev/null +++ b/share/pnp/documents/de_DE/dwnld.html @@ -0,0 +1,530 @@ + + + +

    PNP 0.6.x Downloads

    +
    + +
    + +

    Current stable PNP Version

    +
    + +

    + +Changes can be tracked on https://github.com/pnp4nagios +

    + +

    +with releases and downloads at https://github.com/pnp4nagios/pnp4nagios/releases +

    + +

    +Latest release and downloads at https://github.com/pnp4nagios/pnp4nagios/releases/latest +

    +
    + +

    Documentation

    +
    + +

    + +Documentation +

    + + +
    + +

    + +Last Update: Mon Aug 21 17:49:39 CEST 2017 +

    + +
    + +

    ChangeLog

    +
    +

    +pnp-0.6.27-4 09/05/2023 +

    • update URLs and related text
    • +
    • clean up autoconf stuff
    • +
    +

    +pnp-0.6.27 08/18/2023 +

    • >many php 8.2 fixes to remove 'deprecated' errors:
    • +
    • pre-defining class variables (instead of dynamic),
    • +
    • explicitly re-creating arrays as needed
    • +
    • converting utf8_encode to mbstring
    • +
    +

    +pnp-0.6.26-2 09/18/2022 +

    • various php8 fixes
    • +
    • rrdtools needs env XDG_CACHE_HOME for fontconfig
    • +
    • fix so that 'bucket' display works
    • +
    • fix so that pdf generation works
    • +
    +

    +pnp-0.6.?? ??/??/2015 +

    + +

    +pnp-0.6.26 08/21/2017 +

    +
      +
    • Bugfix: Use complete option arguments for compatibility with rrdtool 1.6.0 (sbraz)
      +
    • +
    • Bugfix: Zoom on a special template not possbile (stinnux)
      +
    • +
    • Update: Update for FPDF (1.81) and FPDI (1.6.1) (Jan T. Bein )
      +
    • +
    • Bugfix: address behaviour of rrdtool1.5+ tp not export timestamp by default
      +
    • +
    • Feature: Template for icinga2's built-in icinga check (Tontonitch)
      +
    • +
    • Bugfix: fix non well formed numeric value encountered (sni)
      +
    • +
    + +

    + +pnp-0.6.25 01/03/2015 +

    +
      +
    • Update: FPDF Update to Version 1.7
      +
    • +
    • Bugfix: Default source fixed by AWiddersheim
      +
    • +
    • Bugfix: Fixed urlencoding of Host- and Servicenames by Andreas Doehler
      +
    • +
    • Bugfix: Fixed Timeranges by AWiddersheim
      +
    • +
    + +

    + +pnp-0.6.24 07/30/2014 +

    +
      +
    • Bugfix: Fixed some more XSS issues
      +
    • +
    • Bugfix: Fixed PHP issue while running on PHP 5.6 ( Reported by Sven Nierlein )
      +
    • +
    + +

    + +pnp-0.6.22 06/04/2014 +

    +
      +
    • Bugfix: Fixed livestatus socket parsing ( Pekka Panula )
      +
    • +
    • Bugfix: Update check_mssql_health.php ( Miriam Zenk )
      +
    • +
    • Feature: Add “version=tiny” to got get a stripped down version of graph ( Ricardo Bartels )
      +
    • +
    • feature: Add STDIN Mode to process_perfdata.pl ( Robert Steininger )
      +
    • +
    • Bugfix: XSS issue fixed by Mikael Falkvidd. This issue was detected by Peter Österberg at Hexbit AB in a security assessment of op5 Monitor 6.3 on assignment by op5 AB.
      +
    • +
    + +

    + +pnp-0.6.21 03/24/2013 +

    +
      +
    • Feature: Helper functions rrd::alerter and rrd:alerter_gr both supports treshold detection (Martin Schirrmacher)
      +
    • +
    • Update: jQuery Mobile update to 1.3.0 ( was broken in 0.6.20 )
      +
    • +
    + +

    + +pnp-0.6.20 03/03/2013 +

    +
      +
    • Feature: Support check_mk Multisite Cookie Auth ( Lars Michelsen )
      +
    • +
    • Feature: Allow RRD unknown values ( Simon Meggle )
      +
    • +
    • feature: Interactive delete mode added to check_rrds.pl ( Simon Meggle )
      +
    • +
    • Bugfix: Allow multiple gearman servers ( Craig Barraclough )
      +
    • +
    • Bugfix: Fixed Graph Search ( Stefan Triep )
      +
    • +
    • Update: jQuery update to 1.8.1
      +
    • +
    • Update: jQueryUI update to 1.8.23
      +
    • +
    + +

    + +pnp-0.6.19 09/01/2012 +

    +
      +
    • Feature: Parameter “width” added to popup controller ( Andreas Doehler )
      +
    • +
    • Fix: simplify/improve apache rules ( Christoph Anton Mitterer )
      +
    • +
    • Fix: Check for missing PHP GD functions
      +
    • +
    • Bugfix: socketDOMAIN changed to AF_INET while using livstatus tcp socket ( Rene Koch )
      +
    • +
    + +

    + +pnp-0.6.18 06/28/2012 +

    +
      +
    • Bugfix: Fixed STORAGE_TYPE and CUSTOM_TEMPLATE vars used in custom templates
      +
    • +
    • Bugfix: Blank screen on PHP 5.4 fixed
      +
    • +
    • Feature: Allow multiple gearman job servers
      +
    • +
    • Feature: New helper function rrd::debug()
      +
    • +
    • Feature: New templates check_jmx4perl_*.php
      +
    • +
    + +

    + +pnp-0.6.17 03/25/2012 +

    +
      +
    • Bugfix: Fixed rrd_convert.pl while running with --dry-run
      +
    • +
    • Bugfix: logging.c include missing header files ( Lars Vogdt )
      +
    • +
    • Bugfix: Check if pnp4nagios/etc/rra.cfg is readable
      +
    • +
    • Bugfix: rrd_convert.pl use XML tag TEMPLATE instead of CHECKCOMMAND to selects RRDs ( Sven Velt )
      +
    • +
    • Feature: npcdmod.o increase perfdata buffer and log discarded perfdata ( Birger Schmidt )
      +
    • +
    • Feature: rrd_modify.pl to change number of data sources of an RRD file
      +
    • +
    • Feature: New template check_apachestatus_auto.php
      +
    • +
    • Feature: Implement etc/config.d to place config snippets ( Lars Michelsen )
      +
    • +
    + +

    + +pnp-0.6.16 11/21/2011 +

    +
      +
    • Bugfix: Fixed single quoted check_multi labels (Reported by Matthias Flacke)
      +
    • +
    • Bugfix: Append missing slash to perfdata_spool_dir ( Reported by Juergen-Michael Radtke )
      +
    • +
    • Bugfix: Fixed jQuery-ui multisite theme
      +
    • +
    • Feature: PDF margins are now adjustable via config.php ( Thomas Witzenrath )
      +
    • +
    • Feature: Support for PDF size 'letter' added ( Robert Becht )
      +
    • +
    + +

    + +pnp-0.6.15 09/15/2011 +

    +
      +
    • Bugfix: Fixed Overview link (reported by Stefan Triep)
      +
    • +
    • Bugfix: Fixed zoom popup (reported by Rudolf Labuschagne)
      +
    • +
    • Bugfix: Fixed double urlencode() (reported by Mathias Kettner)
      +
    • +
    • Feature: “Clear basket” button added (suggested by Stefan Triep)
      +
    • +
    • Feature: New helper function “rrd::alerter_gr()” ( committed by Stefan Trip )
      +
    • +
    + +

    + +pnp-0.6.14 08/05/2011 +

    +
      +
    • Feature: Webinterface for mobile devices based on jQuery Mobile
      +( https://jquerymobile.com/ )
      +
    • +
    • Feature: Zoom based on jQuery plugin imgAreaSelect
      +( https://github.com/odyniec/imgareaselect )
      +
    • +
    • Feature: New template check_mssql_health.php
      +
    • +
    • Bugfix: Fixed popups to work under nginx ( Joram Agten )
      +
    • +
    • Bugfix: Helper rrd::vdef() fixed
      +
    • +
    • Update: jQuery update to 1.6.2
      +
    • +
    • Update: jQuery-ui update to 1.8.14
      +
    • +
    + +

    + +pnp-0.6.13 05/19/2011 +

    +
      +
    • Feature: New option --ignore-hosts added to check_pnp_rrds.pl ( by Jochen Bern )
      +
    • +
    • Feature: New options zgraph_width and zgraph_height in config.php ( Mike Liebsch )
      +
    • +
    • Bugfix: rrd_convert.pl: parse_xml_filename() regex fix
      +
    • +
    • Info: Version used by OMD-0.48 OMD
      +
    • +
    + +

    + +pnp-0.6.12 04/22/2011 +

    +
      +
    • Feature: mod_gearman support added
      +
    • +
    • Feature: rrd_convert.pl is now able to convert all RRDs from RRD_STORAGE_TYPE=SINGLE to RRD_STORAGE_TYPE=MULTIPLE
      +
    • +
    • Feature: New template check_gearman.php
      +
    • +
    • Feature: Install process_perfdata.cfg and npcd.cfg by default
      +
    • +
    • Bugfix: rrd_convert.pl is now able to parse xml dumps created by rrdtool 1.4.x
      +
    • +
    • Bugfix: process_perfdata.pl default timeout value set to 15 seconds
      +
    • +
    + +

    + +pnp-0.6.11 01/15/2011 +

    +
      +
    • Bugfix: urldecoding fixed
      +
    • +
    • Bugfix: Zoom in/out is working again ( Reported by Thorben Soehl )
      +
    • +
    • Featue: npcd.cfg - New option perfdata_file_processing_interval used by npcdmod
      +
    • +
    • Info: Version used by OMD-0.46 OMD
      +
    • +
    + +

    + +pnp-0.6.10 12/15/2010 + +

    +
      +
    • Feature: Add RRDTool Option --only-graph if graph height is below 32px to create thumbnails
      +
    • +
    • Feature: RRDTool Option --width and --height is now allowed in templates
      +
    • +
    • Feature: RRDTool DS Type for UOM of “c” changed from COUNTER to DERIVE
      +
    • +
    • Feature: Pass query string from special controller to image controller ( Matthew Garrett )
      +
    • +
    • Feature: Authorisation against mk_livestatus API added
      +
    • +
    • Feature: Sample nginx webserver config added ( by evax@users.sourceforge.net )
      +
    • +
    • Feature: Kohana backport to support PHP 5.1.6 ( Kudos to Andreas Ericsson )
      +
    • +
    • Bugfix: Sort list of special templates
      +
    • +
    • Bugfix: Urlencode hostname and service description ( Reported by Yannick )
      +
    • +
    • Bugfix: corrected warning/critical thresholds in ticker/alerter functions
      +
    • +
    + +

    + +pnp-0.6.7 09/27/2010 + +

    +
      +
    • Bugfix: Page config parser fix (Beau Gunderson)
      +
    • +
    • Bugfix: Zoom window size fixed (Report by Rudolf Labuschagne)
      +
    • +
    • Bugfix: Fixed undefined offset while using 'ds_name' in templates (Reported by Vladimir Bilik)
      +
    • +
    • Bugfix: Npcdmod respects process_perf_data option used in hosts and services definitions ( Reported by Wolfgang Barth )
      +
    • +
    • Template: New Template check_nagiostats.php used with check_nagiostats written by Jochen Bern
      +
    • +
    + +

    + +pnp-0.6.6 08/07/2010 + +

    +
      +
    • Bugfix: Fixed max amount of graphs per template
      +
    • +
    • Bugfix: Autodetect PNP base URL
      +
    • +
    • Bugfix: Too short npcdmod perfdata_template to take perfdata + overhead, increased +1024byte
      +
    • +
    • Bugfix: Ignore files in var/perfdata and check for empty directories
      +
    • +
    • Bugfix: Reducing memory usage while parsing page config (Laurent Freval)
      +
    • +
    + +

    + +pnp-0.6.5 07/09/2010 + +

    +
      +
    • Feature: Special Templates are back tpl_special
      +
    • +
    • Feature: New rrdtool helper functions makes template design easier tpl_helper
      +
    • +
    • Feature: config.php → 'recursive_template_search' is enabled by default
      +
    • +
    • Feature: config.php → 'template_dirs' is now an array of directorys to search for PNP templates
      +
    • +
    + +

    + +pnp-0.6.4 06/03/2010 + +

    +
      +
    • Update: jQuery Update to 1.4.2
      +
    • +
    • Update: jQuery-ui Update to 1.8
      +
    • +
    • Feature: New configure Option --with-base-url
      +
    • +
    • Template: New template check_ntp_time.php (Mathias Kettner)
      +
    • +
    • Feature: New i18n files for fr_FR (Yannig Parre)
      +
    • +
    • Feature: New jQuery Theme 'multisite'
      +
    • +
    + +

    + +pnp-0.6.3 03/16/2010 + +

    +
      +
    • Feature: New helper script libexec/rrd_convert.pl → rrd_convert
      +
    • +
    • Bugfix: Ignore old XML files while building the service list
      +
    • +
    • Template: New template check_hpasm.php
      +
    • +
    • Bugfix: Installer now checks for json_decode()
      +
    • +
    • Workaround: Allow “trailing unfilled semicolons”. Workaround for nsclient++
      +
    • +
    • Template: Updates for check_openmanage.php, check_hp_bladecenter.php and check_dell_baldecenter.php ( Trond Hasle Amundsen )”
      +
    • +
    + +

    + +pnp-0.6.2 12/23/2009 + +

    +
      +
    • Feature: XML_WRITE_DELAY option added to process_perfdata.cfg as suggested by Mathias Kettner
      +
    • +
    • Feature: New template integer.php
      +
    • +
    • Update: FPDI update to 1.3.1
      +
    • +
    • Feature: PNP will now work with lighttpd and php-cgi
      +
    • +
    • Template: check_mk-ps.perf.php added ( by Mathias Kettner )
      +
    • +
    • Feature: PNP will now work without mod_rewrite → webfe
      +
    • +
    • Bugfix: Wrong pdf link used on site 'pages' and 'basket'
      +
    • +
    • Bugfix: Incorrect group permissions on spool directory
      +
    • +
    + +

    + +pnp-0.6.1 11/22/2009 + +

    +
      +
    • Feature: RRD heartbeat per check_command → tpl_custom
      +
    • +
    • Feature: New config.php option pdf_graph_opt
      +
    • +
    • Feature: Recognize the 'background_pdf' option in page definitions → pages
      +
    • +
    • Feature: Recognize the 'source' option in page definitions → pages
      +
    • +
    • Feature: Array $TIMERANGE now available for templates → timeranges
      +
    • +
    • Bugfix: ./configure --sysconfdir no longer ignored
      +
    • +
    • Feature: Store internal runtime statistics on a per minute base
      +
    • +
    • Feature: Added two widgets views/widget_menu.php and views/widget_graph.php
      +
    • +
    + +

    + +pnp-0.6.0 10/30/2009 + +

    +
      +
    • Webfrontend based on Kohana
      +
    • +
    • Webfrontend based on jQuery Themes
      +
    • +
    • Javascript-functions using jQuery plugins
      +
    • +
    • process_perfdata.pl will be able to use one RRD database per datasource
      +
    • +
    • improved installer. Specification of directory layouts using --with-layout
      +
    • +
    • RRDtool errors are now displayed as images. no more missing images
      +
    • +
    • PNP templates cannot overwrite internal variables anymore
      +
    • +
    • PNP templates of version 0.4.x can still be used
      +
    • +
    • PDF functions recoded
      +
    • +
    • Template default.php optimized
      +
    • +
    • Export from RRD databases into XML, CSV and JSON format using the RRDtool “xport” function
      +
    • +
    • Page functions recoded
      +
    • +
    • Error pages links to online FAQ
      +
    • +
    • Mouseover Popup in Nagios frontend via jQuery.clueTip plugin
      +
    • +
    • Full support of rrdcached
      +
    • +
    + +
    + diff --git a/share/pnp/documents/de_DE/mobile.html b/share/pnp/documents/de_DE/mobile.html index 4885f57..030dd74 100644 --- a/share/pnp/documents/de_DE/mobile.html +++ b/share/pnp/documents/de_DE/mobile.html @@ -10,7 +10,7 @@ Mit PNP4Nagios 0.6.14 ist ein Webinterface für mobile Endgeräte in PNP

    -Das Design wurde mit jQuery Mobile realisiert und ist somit mit den aktuellen mobilen Browsern kompatibel. Auf der Liste der unterstützten Geräte sind die einzelnen Browser aufgeführt und nach Grad der Unterstützung klassifiziert. +Das Design wurde mit jQuery Mobile realisiert und ist somit mit den aktuellen mobilen Browsern kompatibel. Auf der Liste der unterstützten Geräte sind die einzelnen Browser aufgeführt und nach Grad der Unterstützung klassifiziert.

    diff --git a/share/pnp/documents/de_DE/modes.html b/share/pnp/documents/de_DE/modes.html index 833104a..746e47f 100644 --- a/share/pnp/documents/de_DE/modes.html +++ b/share/pnp/documents/de_DE/modes.html @@ -126,7 +126,7 @@ PNP4Nagios kann seit Version 0.6.12 als Gearman Worker betrieben werden. So sind

    -Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter http://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben. +Benötigt wird eine fertig eingerichtete mod_gearman Installation wie von Sven Nierlein unter https://labs.consol.de/lang/en/nagios/mod-gearman/ beschrieben.

    diff --git a/share/pnp/documents/de_DE/new-features.html b/share/pnp/documents/de_DE/new-features.html index cd7d20d..38f83aa 100644 --- a/share/pnp/documents/de_DE/new-features.html +++ b/share/pnp/documents/de_DE/new-features.html @@ -17,7 +17,7 @@ Mit Version 0.6.x steigen wir von Subversion auf GIT um. Der Sourcecode ist bere

    -http://pnp4nagios.git.sourceforge.net +https://github.com/pnp4nagios

    @@ -26,11 +26,11 @@ Mit Version 0.6.x steigen wir von Subversion auf GIT um. Der Sourcecode ist bere

      -
    • Webfrontend basiert auf Kohana
      +
    • Webfrontend basiert auf Kohana
    • -
    • Webfrontend basiert auf jQuery Themes
      +
    • Webfrontend basiert auf jQuery Themes
    • -
    • Javascript-Funktionen über jQuery Plugins
      +
    • Javascript-Funktionen über jQuery Plugins
    • process_perfdata.pl wird in der Lage sein, pro Datenreihe eine eigene RRD-Datenbank zu verwenden.
    • diff --git a/share/pnp/documents/de_DE/rrdcached.html b/share/pnp/documents/de_DE/rrdcached.html index 131ebf6..11a21b5 100644 --- a/share/pnp/documents/de_DE/rrdcached.html +++ b/share/pnp/documents/de_DE/rrdcached.html @@ -14,7 +14,7 @@ Eine Optimierung stellt das Sammeln und Sortieren der Daten dar. Es ist für

      -In der aktuellen RRDtool-Version ( SVN trunk 1550+ ) ist der rrdcached enthalten, der genau diese Situation verbessern soll. +In der aktuellen RRDtool-Version ( SVN trunk 1550+ ) ist der rrdcached enthalten, der genau diese Situation verbessern soll.

      diff --git a/share/pnp/documents/de_DE/start.html b/share/pnp/documents/de_DE/start.html index 489625c..cf0756c 100644 --- a/share/pnp/documents/de_DE/start.html +++ b/share/pnp/documents/de_DE/start.html @@ -26,7 +26,7 @@ Während der Entwicklung von PNP haben wir Wert auf eine einfache Installati

      -Um diese Aufgabe zu erfüllen, setzen wir bewusst auf Standards. PNP verarbeitet nur Performancedaten, die sich strikt an die Developer Guidelines für Nagios Plugins halten. Mit dieser Einschränkung wollen wir bewusst die Arbeit der Nagios Plugin Developer honorieren, die sich für die Einhaltung der Richtlinien einsetzen. +Um diese Aufgabe zu erfüllen, setzen wir bewusst auf Standards. PNP verarbeitet nur Performancedaten, die sich strikt an die Developer Guidelines für Nagios Plugins halten. Mit dieser Einschränkung wollen wir bewusst die Arbeit der Nagios Plugin Developer honorieren, die sich für die Einhaltung der Richtlinien einsetzen.

      diff --git a/share/pnp/documents/de_DE/tpl.html b/share/pnp/documents/de_DE/tpl.html index 99c6aee..35527ef 100644 --- a/share/pnp/documents/de_DE/tpl.html +++ b/share/pnp/documents/de_DE/tpl.html @@ -114,7 +114,7 @@ PNP-Templates müssen folgende Eigenschaften besitzen:

      -Die beiden PHP-Arrays $opt[] und $def[] zusammen bilden den Aufruf von 'rrdtool graph'. Somit sind alle Optionen möglich, die RRDtool bietet. Die Optionen von RRDtool sind auf der RRDtool Homepage genauestens beschrieben. +Die beiden PHP-Arrays $opt[] und $def[] zusammen bilden den Aufruf von 'rrdtool graph'. Somit sind alle Optionen möglich, die RRDtool bietet. Die Optionen von RRDtool sind auf der RRDtool Homepage genauestens beschrieben.

      diff --git a/share/pnp/documents/de_DE/tpl_custom.html b/share/pnp/documents/de_DE/tpl_custom.html index 6be07ef..2b2d140 100644 --- a/share/pnp/documents/de_DE/tpl_custom.html +++ b/share/pnp/documents/de_DE/tpl_custom.html @@ -95,7 +95,7 @@ Einzelnen Datenreihen spezielle Datentypen zuweisen

      DATATYPE = GAUGE,GAUGE,COUNTER,COUNTER

      -Weitere Datentypen sind in der RRDTool-Dokumentation unter rrdcreate erklärt. +Weitere Datentypen sind in der RRDTool-Dokumentation unter rrdcreate erklärt.

      @@ -114,7 +114,7 @@ In einigen wenigen Situationen ist es notwendig, die für RRDTool gülti

      RRD-Datenbanken lassen sich mit definierten Minimum- und Maximum-Werten anlegen. -Weitere Infos unter http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html +Weitere Infos unter https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html

      @@ -182,7 +182,7 @@ Nach <RRD_HEARTBEAT> Sekunden erwartet RRDtool neue Daten.

      -Mehr dazu unter http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html +Mehr dazu unter https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html

      diff --git a/share/pnp/documents/de_DE/tpl_helper.html b/share/pnp/documents/de_DE/tpl_helper.html index a6dfe81..9728d3b 100644 --- a/share/pnp/documents/de_DE/tpl_helper.html +++ b/share/pnp/documents/de_DE/tpl_helper.html @@ -21,7 +21,7 @@ string rrd::def ( $vname, $rrdfile, $ds, [ $cf='AVERAGE�

      $def = rrd::def('var1', $RRDFILE[0], $DS[0], 'MAX');

      -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html

      @@ -36,7 +36,7 @@ string rrd::cdef ( $vname, $rpn, )
      $def = rrd::cdef('var1_bits', 'var1,8,*' );

      -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html

      @@ -51,7 +51,7 @@ string rrd::vdef ( $vname, $rpn, )
      $def = rrd::vdef('var1_avg', 'var1,AVERAGE' );

      -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html

      @@ -75,7 +75,7 @@ Eine Linie, drei Pixel breit, und dem Label “Load”

      -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html

      @@ -94,7 +94,7 @@ Eine Fläche mit dem Label “Load”

      -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html

      @@ -107,14 +107,14 @@ Eine Fläche mit dem Label “Load” string rrd::gprint ( $vname, $cf, [ $text ] )

      $def .= rrd::gprint('var1', 'MAX', '%4.2lf %s Max' );
      -
      $def .= rrd::gprint('var1', array('MIN', 'MAX', 'AVERAGE'), '%4.2lf %s' );
      +
      $def .= rrd::gprint('var1', array('MIN', 'MAX', 'AVERAGE'), '%4.2lf %s' );

      Ist $cf ein Array, so wird automatisch eine Legende formatiert ausgegeben.

      -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html

      diff --git a/share/pnp/documents/de_DE/tpl_special.html b/share/pnp/documents/de_DE/tpl_special.html index 7ce7ee9..d411c22 100644 --- a/share/pnp/documents/de_DE/tpl_special.html +++ b/share/pnp/documents/de_DE/tpl_special.html @@ -82,7 +82,7 @@ Um die Entwicklung der Templates zu erleichtern und Einblick in die Datenstruktu

      Um Einblick in die Daten von $services zu erhalten, genügt die folgende Zeile.

      -
      throw new Kohana_exception(print_r($services,TRUE));
      +
      throw new Kohana_exception(print_r($services,TRUE));

      Ausgabe bei Aufruf von pnp4nagios/special?tpl=websrv_response_times @@ -116,7 +116,7 @@ Step 3: Durchlaufen des Array $services und erstellen der Graph-Definitionen. $hostname = rrd::cut($data['MACRO']['HOSTNAME'], 15); $def[0] .= rrd::def("var$key" , $data['DS'][0]['RRDFILE'], $data['DS'][0]['DS'] ); $def[0] .= rrd::line1("var$key", rrd::color($key), $hostname); - $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); + $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); }

      @@ -175,7 +175,7 @@ Mehr Informationen zu den PNP-Helper-Funktionen finden Sie $hostname = rrd::cut($data['MACRO']['HOSTNAME']); $def[0] .= rrd::def("var$key" , $data['DS'][0]['RRDFILE'], $data['DS'][0]['DS'] ); $def[0] .= rrd::line1("var$key", rrd::color($key), $hostname); - $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); + $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); } ?> diff --git a/share/pnp/documents/de_DE/upgrade.html b/share/pnp/documents/de_DE/upgrade.html index 37d32b6..7879570 100644 --- a/share/pnp/documents/de_DE/upgrade.html +++ b/share/pnp/documents/de_DE/upgrade.html @@ -6,7 +6,7 @@

      -Das Web-Frontend ist komplett neu geschrieben worden und basiert nun auf dem PHP MVC Framework Kohana. Somit ergeben sich grundlegend andere Abhängigkeiten, die dringend vor der Installation geprüft werden müssen. +Das Web-Frontend ist komplett neu geschrieben worden und basiert nun auf dem PHP MVC Framework Kohana. Somit ergeben sich grundlegend andere Abhängigkeiten, die dringend vor der Installation geprüft werden müssen.

      diff --git a/share/pnp/documents/de_DE/verify_pnp_config.html b/share/pnp/documents/de_DE/verify_pnp_config.html index b80a001..fdfab29 100644 --- a/share/pnp/documents/de_DE/verify_pnp_config.html +++ b/share/pnp/documents/de_DE/verify_pnp_config.html @@ -6,7 +6,7 @@

      -Bei Problemen kann das Perl-Script verify_pnp_config von http://verify.pnp4nagios.org helfen die aktuelle Nagios Konfiguration zu prüfen und entsprechend Hinweise zur Lösung liefern. +Bei Problemen kann das Perl-Script verify_pnp_config von https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl helfen die aktuelle Nagios Konfiguration zu prüfen und entsprechend Hinweise zur Lösung liefern.

      @@ -28,10 +28,10 @@ Feedback, Verbesserungsvorschläge oder Patches bitte per Mail an support@pn

      -Das Verify Script ist unter http://verify.pnp4nagios.org verfügbar. +Das Verify Script ist unter https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl verfügbar.

      -wget http://verify.pnp4nagios.org/verify_pnp_config
      +wget https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl/verify_pnp_config
       
      diff --git a/share/pnp/documents/de_DE/webfe.html b/share/pnp/documents/de_DE/webfe.html index 179e717..05cabde 100644 --- a/share/pnp/documents/de_DE/webfe.html +++ b/share/pnp/documents/de_DE/webfe.html @@ -106,7 +106,7 @@ Außerdem gibt es die Möglichkeit, die Graphen bereits in der Statusüb

      -Ermöglicht wird dies durch die CGI Includes, die es uns erlauben, Javascript-Code an geeigneter Stelle im Seitenkopf der Statusübersicht einzubinden ( status.cgi ). +Ermöglicht wird dies durch die CGI Includes, die es uns erlauben, Javascript-Code an geeigneter Stelle im Seitenkopf der Statusübersicht einzubinden ( status.cgi ).

      diff --git a/share/pnp/documents/en_US/about.html b/share/pnp/documents/en_US/about.html index 3c955c1..b1f37f4 100644 --- a/share/pnp/documents/en_US/about.html +++ b/share/pnp/documents/en_US/about.html @@ -11,7 +11,7 @@

      -PNP mandatory requires valid performance data of nagios plugins. +PNP requires valid performance data from nagios plugins.

      @@ -19,7 +19,8 @@ So what is this performance data?

      -The output of a nagios plugin up to nagios 2.x is limited to one line. When the plugin produces performance data, it is divided into two parts. The pipe symbol (“|”) is used as a delimiter. +The output of a nagios plugin (up to nagios 2.x?) is limited to one line. When the plugin produces performance data, +it is divided into two parts. The pipe symbol (“|”) is used as a delimiter.

      @@ -76,7 +77,7 @@ Several data series are separated by blanks. The actual data must not contains a

    • RRDtool >= 1.x, better 1.2 but not compulsory
      Attention: installing RRDtool without a packet manager might lead to missing dejavu fonts. If you see graphs without text then this may be the cause.
    • -
    • PHP >= 5.1.6 for the Webfrontend based on Kohana
      +
    • PHP >= 5.1.6 for the Webfrontend based on Kohana
    • Nagios >= 2.x or Icinga
    • @@ -91,7 +92,7 @@ Attention: installing RRDtool without a packet manager might lead to missing dej

      -PNP is licensed under GPL 2 +PNP is licensed under GPL 2

      @@ -101,28 +102,26 @@ PNP is licensed under Sourceforge.Net. PNP is registered under “PNP4nagios”. +Development of PNP is organized using github.com. PNP is registered under “PNP4nagios”.

      -The current stable version of 0.6.x can be found in the download area: Sourceforge Download +The current stable version of 0.6.x can be found in the download area: github release

      Starting with PNP 0.6.x the source code repository was switched from SVN to GIT.

      -

      -The current development can be viewed anytime at https://github.com/lingej/pnp4nagios. Clicking on pnp4nagios-head.tar.gz will download an archive containing the latest version. -
      - -

      Support

      - +TBD: The development effort (located at https://github.com/pnp4nagios) needs more effort applied to 'support', but for now there is the github system of +posting 'issues'. +

      Storage

      @@ -160,7 +161,7 @@ The mailing lists on Sourceforge can be used to request support (and are limited

      -Performance data will be stored in Round Robin Databases using RRDtool. That means that after some time the oldest data will be dropped at the “end” and it will be replaced by new values “at the beginning”. +Performance data will be stored in Round Robin Databases using RRDtool. That means that after some time the oldest data will be dropped at the “end” and it will be replaced by new values “at the beginning”.

      @@ -172,10 +173,6 @@ Using this storage format the size of the files will stay the same over time. Pe

      - -

      Statistics and links to Sourceforge

      -
      -

      back to contents | PNP modes @@ -183,4 +180,3 @@ Using this storage format the size of the files will stay the same over time. Pe

      - \ No newline at end of file diff --git a/share/pnp/documents/en_US/advanced.html b/share/pnp/documents/en_US/advanced.html index 33e7737..cac049b 100644 --- a/share/pnp/documents/en_US/advanced.html +++ b/share/pnp/documents/en_US/advanced.html @@ -27,7 +27,7 @@ If PNP finds a string enclosed in brackets at the end of performance data it wil

      Nagios documentation related to this topic can be found -here. The command used in the documentation can be adapted easily. +here. The command used in the documentation can be adapted easily.

       define command{
      @@ -53,7 +53,7 @@ define command{
       
       

      -The plugin check_multi is one of the first plugins which uses new features of Nagios 3.x. Check_multi can execute multiple Nagios plugins but returns only results like a single service. The output of check_multi comprises of several lines to be able to display the amount of information. +The plugin check_multi is one of the first plugins which uses new features of Nagios 3.x. Check_multi can execute multiple Nagios plugins but returns only results like a single service. The output of check_multi comprises of several lines to be able to display the amount of information.

      @@ -61,7 +61,7 @@ This results in some difficulties for PNP which has to extract the information o

      - +

      @@ -70,4 +70,4 @@ This results in some difficulties for PNP which has to extract the information o

      - \ No newline at end of file + diff --git a/share/pnp/documents/en_US/config.html b/share/pnp/documents/en_US/config.html index bf48d4d..70e9405 100644 --- a/share/pnp/documents/en_US/config.html +++ b/share/pnp/documents/en_US/config.html @@ -57,7 +57,7 @@ Starting with Nagios 3.0 it may be useful to enable processing of performance da

      -Nagios has to be notified about the referenced commands as well. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. +Nagios has to be notified about the referenced commands as well. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. You can see that calling process_perfdata.pl doesn't require any arguments apart from specifing the option -d ( DATATYPE ) if you want to process performance data resulting from host checks.

      @@ -144,7 +144,7 @@ The directives and their meaning:
       
       

      -The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. +The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg.

       define command{
      @@ -228,7 +228,7 @@ The directives and their meaning:
       
       

      -The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. +The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg.

       define command{
      @@ -342,7 +342,7 @@ Since version 0.6.12 PNP4Nagios can be driven as a gearman worker. This way larg
       

      -You need a mod_gearman environment up and running like described by Sven Nierlein on http://labs.consol.de/lang/en/nagios/mod-gearman/. +You need a mod_gearman environment up and running like described by Sven Nierlein on https://labs.consol.de/lang/en/nagios/mod-gearman/.

      diff --git a/share/pnp/documents/en_US/doc_complete.html b/share/pnp/documents/en_US/doc_complete.html index 7f67dc5..b8d7bec 100644 --- a/share/pnp/documents/en_US/doc_complete.html +++ b/share/pnp/documents/en_US/doc_complete.html @@ -1,14 +1,12 @@ - -

      -

      New in PNP 0.6.x

      -
      +

      New in PNP 0.6.x

      +

      -PNP 0.6.x Preview +PNP 0.6.x Preview

      @@ -16,7 +14,7 @@ The work on the new version 0.6.x is in full progress.

      -Starting with version 0.6.x we switch from subversion to GIT. The sourcecode is already available on sourceforge. +Starting with version 0.6.x we switch from subversion to GIT. The sourcecode is available on GitHub.

      @@ -24,11 +22,11 @@ Starting with version 0.6.x we switch from subversion to GIT. The

      +
    • Webfrontend based on Kohana
    • -
    • Webfrontend based on jQuery Themes
      +
    • Webfrontend based on jQuery Themes
    • -
    • Javascript-functions using jQuery plugins
      +
    • Javascript-functions using jQuery plugins
    • process_perfdata.pl will be able to use one RRD database per datasource
    • @@ -48,7 +46,7 @@ Starting with version 0.6.x we switch from subversion to GIT. The
      Page functions recoded
      -
    • +
    • Error pages links to online FAQ
    • Mouseover Popup in Nagios frontend via jQuery.clueTip plugin
    • @@ -61,20 +59,17 @@ Starting with version 0.6.x we switch from subversion to GIT. The -
      -

      About PNP

      +

      About PNP

      - +

      System requirements

      @@ -136,7 +131,7 @@ Several data series are separated by blanks. The actual data must not contains a

      - +

      Required Software

        @@ -145,7 +140,7 @@ Several data series are separated by blanks. The actual data must not contains a
      • RRDtool >= 1.x, better 1.2 but not compulsory
        Attention: installing RRDtool without a packet manager might lead to missing dejavu fonts. If you see graphs without text then this may be the cause.
      • -
      • PHP >= 5.1.6 for the Webfrontend based on Kohana
        +
      • PHP >= 5.1.6 for the Webfrontend based on Kohana
      • Nagios >= 2.x or Icinga
      • @@ -154,27 +149,27 @@ Attention: installing RRDtool without a packet manager might lead to missing dej
      - +

      License

      -PNP is licensed under GPL 2 +PNP is licensed under GPL 2

      - +

      Download

      -Development of PNP is organized using Sourceforge.Net. PNP is registered under “PNP4nagios”. +Development of PNP is organized using github.com. PNP is registered under “PNP4nagios”.

      -The current stable version of 0.6.x can be found in the download area: Sourceforge Download +The current stable version of 0.6.x can be found in the download area: Sourceforge Download

      @@ -182,13 +177,13 @@ Starting with PNP 0.6.x the source code repository was switched from SVN to GIT.

      -The current development can be viewed anytime at https://github.com/lingej/pnp4nagios. Clicking on pnp4nagios-head.tar.gz will download an archive containing the latest version. +The current development can be viewed anytime at https://github.com/pnp4nagios. Clicking on pnp4nagios-head.tar.gz will download an archive containing the latest version.

      - +

      Support

      @@ -200,7 +195,7 @@ PRIOR to support questions please make sure that you have verified certain thing

      -The developers and helpers are present on a separate board at http://www.monitoring-portal.org and will be informed about new postings in the PNP-section. Postings in english will be answered as well.
      +The developers and helpers are present on a separate board at https://www.monitoring-portal.org and will be informed about new postings in the PNP-section. Postings in english will be answered as well.
      After registering as a user please fill in the profile regarding operating system and PNP version used. Please mention if you used a package or compiled the sources. Please mark successfully solved threads by adding ”[solved]” to the title as it helps other users to find a solution for their problem. @@ -223,13 +218,13 @@ The mailing lists on Sourceforge can be used to request support (and are limited

      - +

      Storage

      -Performance data will be stored in Round Robin Databases using RRDtool. That means that after some time the oldest data will be dropped at the “end” and it will be replaced by new values “at the beginning”. +Performance data will be stored in Round Robin Databases using RRDtool. That means that after some time the oldest data will be dropped at the “end” and it will be replaced by new values “at the beginning”.

      @@ -241,26 +236,19 @@ Using this storage format the size of the files will stay the same over time. Pe

      - -

      Statistics and links to Sourceforge

      - -
      -

      The art of collecting data

      +

      The art of collecting data

      @@ -283,28 +271,28 @@ Before you choose a mode please read the documentation and decide which way will

      - +

      The modes in comparison

      - +

      Synchronous Mode

      -The “synchronous mode” is the simplest and easiest to set up. Nagios will call the perl script process_perfdata.pl for every service and host, respectively, to process the data. The synchronous mode will work very good up to about 1.000 services in a 5 minute interval. +The “synchronous mode” is the simplest and easiest to set up. Nagios will call the perl script process_perfdata.pl for every service and host, respectively, to process the data. The synchronous mode will work very good up to about 1.000 services in a 5 minute interval.

      - +

      Bulk Mode

      -In bulk mode Nagios writes the necessary data to a temporary file. After expiration of a defined time the file will be processed in one piece and deleted afterwards. +In bulk mode Nagios writes the necessary data to a temporary file. After expiration of a defined time the file will be processed in one piece and deleted afterwards.

      @@ -331,13 +319,13 @@ snippet of var/perfdata.log:

      - +

      Bulk Mode with NPCD

      -Viewing from Nagios this is the best way of processing because Nagios will not be blocked. +Viewing from Nagios this is the best way of processing because Nagios will not be blocked.

      @@ -349,7 +337,7 @@ The NPCD daemon (Nagios Performance C Daemon) will monitor the directory for new

      - +

      Bulk Mode with npcdmod

      @@ -360,7 +348,7 @@ The NPCD daemon (Nagios Performance C Daemon) will monitor the directory for new

      - This scenario includes npcdmod.o, an NEB-module. + This scenario includes npcdmod.o, an NEB-module. This module reduces the configuration of the “Bulk Mode with NPCD” to a mere two lines in nagios.cfg

      @@ -369,13 +357,13 @@ This mode is similar to “Bulk Mode with NPCD” and it is exactly the same fun

      - +

      Gearman Mode

      - +

      @@ -383,11 +371,11 @@ Since version 0.6.12 PNP4Nagios can be driven as a gearman worker. This way larg

      -You need a mod_gearman environment up and running like described by Sven Nierlein on http://labs.consol.de/lang/en/nagios/mod-gearman/. +You need a mod_gearman environment up and running like described by Sven Nierlein on https://labs.consol.de/lang/en/nagios/mod-gearman/.

      - +

      The decision

      @@ -401,62 +389,96 @@ Which mode you choose will depend on the size of your Nagios installation. You w

      - -
      +
      -

      PNP 0.6.x Downloads

      -
      - -
      - -

      Current stable PNP Version

      +

      PNP 0.6.x Downloads

      -

      - -Changes can be tracked on pnp4nagios.git.sourceforge.net -

      - -

      -The current Version is pnp4nagios-0.6.25.tar.gz -

      -
      - -

      Latest Devel Version

      -
      + +

      Current stable PNP Version

      +

      - pnp4nagios-head.tar.gz +Changes can be tracked on https://github.com/pnp4nagios

      -This is allways the latest GIT HEAD Version +with releases and downloads at https://github.com/pnp4nagios/pnp4nagios/releases

      + +

      +Latest release and downloads at https://github.com/pnp4nagios/pnp4nagios/releases/latest +

      +
      + +

      Documentation

      +
      + +

      + +Documentation +

      + +

      -Last Update: Sun Aug 20 19:30:01 CEST 2017 +Last Update: Mon Aug 21 17:49:39 CEST 2017

      - -

      ChangeLog

      -
      - + +

      ChangeLog

      +
      +

      +pnp-0.6.27-4 09/05/2023 +

      • update URLs and related text
      • +
      • clean up autoconf stuff
      • +
      +

      +pnp-0.6.27 08/18/2023 +

      • >many php 8.2 fixes to remove 'deprecated' errors:
      • +
      • pre-defining class variables (instead of dynamic),
      • +
      • explicitly re-creating arrays as needed
      • +
      • converting utf8_encode to mbstring
      • +
      +

      +pnp-0.6.26-2 09/18/2022 +

      • various php8 fixes
      • +
      • rrdtools needs env XDG_CACHE_HOME for fontconfig
      • +
      • fix so that 'bucket' display works
      • +
      • fix so that pdf generation works
      • +

      - pnp-0.6.?? ??/??/2015

      +pnp-0.6.26 08/21/2017 +

      +
        +
      • Bugfix: Use complete option arguments for compatibility with rrdtool 1.6.0 (sbraz)
        +
      • +
      • Bugfix: Zoom on a special template not possbile (stinnux)
        +
      • +
      • Update: Update for FPDF (1.81) and FPDI (1.6.1) (Jan T. Bein )
        +
      • +
      • Bugfix: address behaviour of rrdtool1.5+ tp not export timestamp by default
        +
      • +
      • Feature: Template for icinga2's built-in icinga check (Tontonitch)
        +
      • +
      • Bugfix: fix non well formed numeric value encountered (sni)
        +
      • +
      + +

      + pnp-0.6.25 01/03/2015

    • Feature: Zoom based on jQuery plugin imgAreaSelect
      -( http://odyniec.net/projects/imgareaselect/ )
      +( https://github.com/odyniec/imgareaselect )
    • Feature: New template check_mssql_health.php
    • @@ -653,7 +675,7 @@ Last Update: Sun Aug 20 19:30:01 CEST 2017
    • Bugfix: rrd_convert.pl: parse_xml_filename() regex fix
    • -
    • Info: Version used by OMD-0.48 OMD
      +
    • Info: Version used by OMD-0.48 OMD
    @@ -687,7 +709,7 @@ Last Update: Sun Aug 20 19:30:01 CEST 2017
  • Featue: npcd.cfg - New option perfdata_file_processing_interval used by npcdmod
  • -
  • Info: Version used by OMD-0.46 OMD
    +
  • Info: Version used by OMD-0.46 OMD
  • @@ -705,7 +727,7 @@ Last Update: Sun Aug 20 19:30:01 CEST 2017
  • Feature: Pass query string from special controller to image controller ( Matthew Garrett )
  • -
  • Feature: Authorisation against mk_livestatus API added
    +
  • Feature: Authorisation against mk_livestatus API added
  • Feature: Sample nginx webserver config added ( by evax@users.sourceforge.net )
  • @@ -823,7 +845,7 @@ Last Update: Sun Aug 20 19:30:01 CEST 2017
  • Update: FPDI update to 1.3.1
  • -
  • Feature: PNP will now work with lighttpd and php-cgi
    +
  • Feature: PNP will now work with lighttpd and php-cgi
  • Template: check_mk-ps.perf.php added ( by Mathias Kettner )
  • @@ -865,11 +887,11 @@ Last Update: Sun Aug 20 19:30:01 CEST 2017

      -
    • Webfrontend based on Kohana
      +
    • Webfrontend based on Kohana
    • -
    • Webfrontend based on jQuery Themes
      +
    • Webfrontend based on jQuery Themes
    • -
    • Javascript-functions using jQuery plugins
      +
    • Javascript-functions using jQuery plugins
    • process_perfdata.pl will be able to use one RRD database per datasource
    • @@ -898,20 +920,18 @@ Last Update: Sun Aug 20 19:30:01 CEST 2017
    - +
    -

    Upgrade to version 0.6.x

    +

    Upgrade to version 0.6.x

    -The web-frontend has been completely rewritten and is now based on the PHP MVC framework Kohana. This leads to changed dependencies which must be checked prior to installation. +The web-frontend has been completely rewritten and is now based on the PHP MVC framework Kohana. This leads to changed dependencies which must be checked prior to installation.

    @@ -931,7 +951,7 @@ Note: It is sufficient to copy the *.rrd files from the old to the new location.

    - +

    Comparison of the structure

    @@ -987,7 +1007,7 @@ Looking at these lines result in the parameters to be changed and the upgrade st

    - +

    Adjustments

    @@ -1073,7 +1093,7 @@ Please keep in mind that all occurrences have to be changed

    Upgrade scenario using NPCD

      @@ -1122,15 +1142,12 @@ Please keep in mind that all occurrences have to be changed - -
    -
    +
    -

    Installation

    +

    Installation

    @@ -1142,12 +1159,12 @@ Please note that PNP has to be configured after the installation.

    - +

    Make and more

    -The installation of PNP is controlled by makefiles. The system is analyzed after invocation of ./configure and the detected values are tranferred to makefiles. +The installation of PNP is controlled by makefiles. The system is analyzed after invocation of ./configure and the detected values are tranferred to makefiles.

    @@ -1279,7 +1296,7 @@ All these steps are combined in

    - +

    Update

    @@ -1296,7 +1313,7 @@ You can skip make install-webconf and make install-init
    - +

    The components

    @@ -1339,15 +1356,13 @@ the config file config.php for the web frontend in

    - +
    -

    Configuration

    +

    Configuration

    @@ -1356,13 +1371,13 @@ The configuration of the already mentioned Synchronous Mode + +

    Synchronous Mode

    - The synchronous mode is the simplest way to integrate the data collector process_perfdata.pl into nagios. Every event will trigger an execution of process-service-perfdata. + The synchronous mode is the simplest way to integrate the data collector process_perfdata.pl into nagios. Every event will trigger an execution of process-service-perfdata.

    @@ -1403,7 +1418,7 @@ Starting with Nagios 3.0 it may be useful to enable processing of performance da

    -Nagios has to be notified about the referenced commands as well. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. +Nagios has to be notified about the referenced commands as well. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. You can see that calling process_perfdata.pl doesn't require any arguments apart from specifing the option -d ( DATATYPE ) if you want to process performance data resulting from host checks.

    @@ -1423,13 +1438,13 @@ define command {
     

    - -

    Bulk Mode

    + +

    Bulk Mode

    -Bulk mode is a bit more complicated than the synchronous mode but reduces the load on the nagios server significantly because the data collector process_perfdata.pl is not invoked for every service/host check. +Bulk mode is a bit more complicated than the synchronous mode but reduces the load on the nagios server significantly because the data collector process_perfdata.pl is not invoked for every service/host check.

    @@ -1490,7 +1505,7 @@ The directives and their meaning:

    -The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. +The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg.

     define command{
    @@ -1514,13 +1529,13 @@ Because there is more data to process than in synchronous mode process_per
     
    - -

    Bulk Mode with NPCD

    + +

    Bulk Mode with NPCD

    - The configuration is identical to the Bulk Mode except for the used command. + The configuration is identical to the Bulk Mode except for the used command. Processing of performance data has to be enabled in nagios.cfg

    @@ -1574,7 +1589,7 @@ The directives and their meaning:

    -The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg. +The used commands have to be announced to Nagios. If you used the quickstart installation guides for Nagios you can modify the definitions in commands.cfg.

     define command{
    @@ -1613,7 +1628,7 @@ The option -d starts NPCD as a daemon in the background.
     

    - +

    Bulk Mode with NPCD and npcdmod

    @@ -1624,7 +1639,7 @@ The option -d starts NPCD as a daemon in the background.

    - This mode uses the event broker module npcdmod.o. The flow of data is identical to “bulk mode with NPCD”. The internal perfdata routines of Nagios activated by the “*_perf_data_*” directives in nagios.cfg are *NOT* used anymore. The module npcdmod.o takes over the task of processing the data required by PNP. + This mode uses the event broker module npcdmod.o. The flow of data is identical to “bulk mode with NPCD”. The internal perfdata routines of Nagios activated by the “*_perf_data_*” directives in nagios.cfg are *NOT* used anymore. The module npcdmod.o takes over the task of processing the data required by PNP.

    @@ -1674,13 +1689,13 @@ Excerpt from nagios.log

    - -

    Gearman Mode

    + +

    Gearman Mode

    - +

    @@ -1688,7 +1703,7 @@ Since version 0.6.12 PNP4Nagios can be driven as a gearman worker. This way larg

    -You need a mod_gearman environment up and running like described by Sven Nierlein on http://labs.consol.de/lang/en/nagios/mod-gearman/. +You need a mod_gearman environment up and running like described by Sven Nierlein on https://labs.consol.de/lang/en/nagios/mod-gearman/.

    @@ -1738,15 +1753,12 @@ the performance data will be processed which is provided by the gearmand daemon

    - -
    +
    -

    Checking the installation

    +

    Checking the installation

    @@ -1778,7 +1790,7 @@ ATTENTION: Immediately after (re-)starting Nagios after you enabled the processi

    - +

    Debug Logfile

    @@ -1799,7 +1811,7 @@ During normal operation the debug level should be set to 0 to avoid performance

    - +

    Something went wrong

    @@ -1822,7 +1834,7 @@ Using the web interface the detail information of hosts/services shows a field The following image shows the information of a “PING” service. The output of the plugin is surrounded by a blue border, the performance data by a red one.
    -status information +status information

    @@ -1857,42 +1869,39 @@ Have a look at the - -

    -
    +
    -

    verify_pnp_config

    +

    verify_pnp_config

    -In case of problems there is a script called verify_pnp_config.pl located on http://verify.pnp4nagios.org. It enables you to check the configuration settings as well as performance data of hosts or services. It can be used prior and during runtime of PNP. +In case of problems there is a script called verify_pnp_config.pl located on https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl. It enables you to check the configuration settings as well as performance data of hosts or services. It can be used prior and during runtime of PNP.

    -* ATTENTION *: It ONLY supports verifying Nagios 3.x and Icinga 1.x as Monitoring core. +* ATTENTION *: Check what versions of Nagios and Icinga are supported as Monitoring core.

    - -

    Download

    + +

    Download

    -wget http://verify.pnp4nagios.org/verify_pnp_config
    +wget https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl
     
    - +

    Test

    -The verify script is located on http://verify.pnp4nagios.org and needs three start options +The verify script is located on https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl and needs three start options

    • --mode One of the modes described on modes
      @@ -1975,7 +1984,7 @@ lenny:~# perl verify_pnp_config --mode npcdmod --config=/usr/local/nagios/etc/na
    - +

    Performance data

    @@ -1997,15 +2006,13 @@ The strings are taken as regular expressions (perl syntax).

    - +
    -

    Nagios web frontend

    +

    Nagios web frontend

    @@ -2017,38 +2024,17 @@ Nagios itself features external URLs using so called extended info configs. Due

    - -

    Nagios 2.x

    -
    - -

    - -With Nagios 2.x the integration of external URLs into the nagios web interface is made using Extended Info Objects for services. For PNP we use the directive action_url to call the PNP web frontend with the appropriate options. -

    -
    -define serviceextinfo {
    -   host_name             localhost
    -   service_description   load
    -   action_url            /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=$SERVICEDESC$
    -}
    -
    - -

    -You have to specify an additional Extended Info Definition for every service. -

    - -
    - +

    Nagios 3.x

    -Since nagios 3.0 the action_url-directive has be moved to the host or service definition. This way the definition of URLs to the PNP-interface has been simplified. The serviceextinfo and hostextinfo definitions are deprecated. +Since nagios 3.0 the action_url-directive has be moved to the host or service definition. This way the definition of URLs to the PNP-interface has been simplified. The serviceextinfo and hostextinfo definitions are deprecated.

    -First two nagios templates are defined. If you used the Nagios quickstart installation guides you can append these lines to templates.cfg: +First two nagios templates are defined. If you used the Nagios quickstart installation guides you can append these lines to templates.cfg:

     define host {
    @@ -2096,12 +2082,12 @@ The links to the correct URLs are created automagically.

    - +

    Popups

    -You can integrate PNP into Nagios in a way that you have current graphs without clicking any icons. This can be accomplished using the CGI Includes which allow us to include JavaScript code in the status detail view ( status.cgi ). +You can integrate PNP into Nagios in a way that you have current graphs without clicking any icons. This can be accomplished using the CGI Includes which allow us to include JavaScript code in the status detail view ( status.cgi ).

    @@ -2141,7 +2127,7 @@ define service { After a restart of Nagios (after modifying the definitions) the result might look like this:
    - +

    @@ -2150,15 +2136,13 @@ After a restart of Nagios (after modifying the definitions) the result might loo

    - +
    -

    PNP Web Frontend

    +

    PNP Web Frontend

    @@ -2171,7 +2155,7 @@ Own adjustments should be made in etc/config_local.php. If this fil

    - +

    etc/config.php

    @@ -2290,15 +2274,12 @@ You can add more views ($views[5], …) but please keep in mind that under norma

    - -
    +
    -

    Timeranges

    +

    Timeranges

    @@ -2381,16 +2362,13 @@ Examples of different specifications

    -
    -
    -

    Pages

    +

    Pages

    @@ -2477,16 +2455,13 @@ In some cases you may want to limit the display to just one graph. To accomplish

    -
    -
    -

    Data export

    +

    Data export

    @@ -2526,16 +2501,13 @@ Instead of view you can use start and/or end -

    -
    -

    What are templates?

    +

    What are templates?

    @@ -2548,7 +2520,7 @@ The selected check_command determines which template will be used to control the

    - +

    What template will be used when?

    @@ -2620,7 +2592,7 @@ The template default.php takes an exceptional position as it is used every time

    - +

    Creating own templates

    @@ -2644,7 +2616,7 @@ PNP template must have the following characteristics:

    -These two arrays are used to call 'rrdtool graph' so every option is possible that RRDtool supports. All options of RRDtool are described very thoroughly on the RRDtool Homepage. +These two arrays are used to call 'rrdtool graph' so every option is possible that RRDtool supports. All options of RRDtool are described very thoroughly on the RRDtool Homepage.

    @@ -2699,11 +2671,11 @@ $def[1] .= “GPRINT:var1:AVERAGE:\”%3.4lg %s$UNIT[1] AVERAGE \” ”;

    -The three GPRINT lines build up the caption for the graph. The current values are formatted using the printf syntax. +The three GPRINT lines build up the caption for the graph. The current values are formatted using the printf syntax.

    - +

    Available variables

    @@ -2771,15 +2743,13 @@ The value of the field <NAGIOS_SERVICEOUTPUT> is available as

    - +
    -

    Custom Templates

    +

    Custom Templates

    @@ -2797,7 +2767,7 @@ The following options can be defined in it:

    - +

    CUSTOM_TEMPLATE

    @@ -2850,7 +2820,7 @@ This option has effect only during creation of the RRD database.

    - +

    DATATYPE

    @@ -2872,7 +2842,7 @@ Setting datasources to different types
    DATATYPE = GAUGE,GAUGE,COUNTER,COUNTER

    -More datatypes are explained in the RRDTool documentation found at rrdcreate. +More datatypes are explained in the RRDTool documentation found at rrdcreate.

    @@ -2880,7 +2850,7 @@ This option has effect only during creation of the RRD database.

    - +

    USE_MIN_ON_CREATE and USE_MAX_ON_CREATE

    @@ -2890,7 +2860,7 @@ In a few situations it might be necessary to limit the values which are valid fo

    -RRD databases can be created with fixed minimum and maximum values. You will find further details at http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html. +RRD databases can be created with fixed minimum and maximum values. You will find further details at https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html.

    @@ -2910,7 +2880,7 @@ This option has effect only during creation of the RRD database.

    - +

    RRD_STORAGE_TYPE

    RRD_STORAGE_TYPE = SINGLE
    @@ -2942,7 +2912,7 @@ This option has effect only during creation of the RRD database.

    - +

    RRD_HEARTBEAT

    @@ -2957,7 +2927,7 @@ After <RRD_HEARTBEAT> seconds RRDtool expects new data.

    -More information at http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html +More information at https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html

    @@ -2965,7 +2935,7 @@ This option has effect only during creation of the RRD database.

    - +

    Hints on Template Names

    @@ -3098,16 +3068,13 @@ Which of above two solutions one follows is largely a matter of taste.

    - -
    +
    -

    Distributed Systems

    -
    +

    Distributed Systems

    +

    If Nagios is implemented as a distributed system you have to decide where PNP should be installed. @@ -3132,7 +3099,7 @@ If PNP finds a string enclosed in brackets at the end of performance data it wil

    Nagios documentation related to this topic can be found -here. The command used in the documentation can be adapted easily. +here. The command used in the documentation can be adapted easily.

     define command{
    @@ -3152,13 +3119,13 @@ define command{
     
    - -

    check_multi plugin

    -
    + +

    check_multi plugin

    +

    -The plugin check_multi is one of the first plugins which uses new features of Nagios 3.x. Check_multi can execute multiple Nagios plugins but returns only results like a single service. The output of check_multi comprises of several lines to be able to display the amount of information. +The plugin check_multi is one of the first plugins which uses new features of Nagios 3.x. Check_multi can execute multiple Nagios plugins but returns only results like a single service. The output of check_multi comprises of several lines to be able to display the amount of information.

    @@ -3166,7 +3133,7 @@ This results in some difficulties for PNP which has to extract the information o

    - +

    @@ -3175,15 +3142,12 @@ This results in some difficulties for PNP which has to extract the information o

    - -
    +
    -

    RRDtool Cache Daemon

    +

    RRDtool Cache Daemon

    @@ -3196,15 +3160,15 @@ One improvement is made by collecting and sorting the data. It is more effective

    -The current RRDtool ( SVN trunk 1550+ ) contains rrdcached which should improve exactly this situation. +The current RRDtool ( SVN trunk 1550+ ) contains rrdcached which should improve exactly this situation.

    -At this point I'd like to thank Florian octo Forster, Kevin Brintnall and Tobi Oetiker. The development of this daemon has been coordinated exemplary on the rrd-developers mailing list. +At this point I'd like to thank Florian octo Forster, Kevin Brintnall and Tobi Oetiker. The development of this daemon has been coordinated exemplary on the rrd-developers mailing list.

    - +

    Mode of operation

    @@ -3214,7 +3178,7 @@ The rrdcached is working as a daemon in the background and opens a UNIX or TCP s

    - +

    rrdcached

    @@ -3262,7 +3226,7 @@ Option -z defines a maximum delay which will be used to spread the write cycles

    Option -p defines a PID file

    -
    -p /var/run/rrdcached.pid
    +
    -p /run/rrdcached.pid

    Option -j defines the path to a journaling directory. All requests will be logged there so that they can be processed after a restart in case the daemon crashes. @@ -3275,7 +3239,7 @@ These options may result in a call of rrdcached with the following parameters

     rrdcached -w 1800 -z 1800 -p /tmp/rrdcached.pid -j /tmp  -s nagios -m 0660 -l unix:/tmp/rrdcached.sock
    - +

    rrdtool

    @@ -3292,7 +3256,7 @@ Of course this has to correspond with the options of rrdcached!

    - +

    Integration into PNP

    @@ -3308,7 +3272,7 @@ Because two components of PNP have to prepared for the use of rrdcached there ar # EXPERIMENTAL rrdcached Support # Use only with rrdtool svn revision 1511+ # -RRD_DAEMON_OPTS = unix:/var/run/rrdcached.sock +RRD_DAEMON_OPTS = unix:/run/rrdcached.sock

    @@ -3320,7 +3284,7 @@ RRD_DAEMON_OPTS = unix:/var/run/rrdcached.sock # Use only with rrdtool svn revision 1511+ # # $conf['RRD_DAEMON_OPTS'] = 'unix:/tmp/rrdcached.sock'; -$conf['RRD_DAEMON_OPTS'] = 'unix:/var/run/rrdcached.sock'; +$conf['RRD_DAEMON_OPTS'] = 'unix:/run/rrdcached.sock';

    @@ -3333,15 +3297,13 @@ The sample files contain the relevant options.

    - +
    -

    NPCD

    +

    NPCD

    @@ -3350,7 +3312,7 @@ NPCD (Nagios-Perfdata-C-Daemon) was written to provide an asynchronous mode to h

    - +

    Introduction

    @@ -3372,7 +3334,7 @@ This move is a very fast action for the Nagios core and the c

    - +

    How it works

    @@ -3394,7 +3356,7 @@ Since the perfdata files in the spool dir are in the same format as for the 

    - +

    Advantages / Disadvantages

    @@ -3433,7 +3395,7 @@ Since the perfdata files in the spool dir are in the same format as for the 
    - +

    NPCD Config

    @@ -3465,7 +3427,7 @@ If you decide to not rename the config file, it might be overwritten by a future

    - +

    npcd.cfg-sample

    @@ -3496,11 +3458,11 @@ use_load_threshold = 0 load_threshold = 10.0 # Process Options -pid_file=/var/run/npcd.pid +pid_file=/run/npcd.pid
    - +

    The directives

      @@ -3645,7 +3607,7 @@ pid_file=/var/run/npcd.pid
      • the path to the PID File
      • -
      • Default: /var/run/npcd.pid
        +
      • Default: /run/npcd.pid
      @@ -3660,10 +3622,7 @@ pid_file=/var/run/npcd.pid

    - -
    +

    @@ -3695,9 +3654,6 @@ Now you'll get the number together with the required label

    ./check_procs.sh -a ndo2db -w 1: -c 0:
     PROCS OK: 2 processes with args 'ndo2db'| procs=2
    -
    @@ -3761,7 +3717,4 @@ It is up to third party programs to convert the Nagios plugins performance data Origin: https://www.monitoring-plugins.org/doc/guidelines.html#AEN200

    -
    diff --git a/share/pnp/documents/en_US/dwnld.html b/share/pnp/documents/en_US/dwnld.html index 324340d..c332643 100644 --- a/share/pnp/documents/en_US/dwnld.html +++ b/share/pnp/documents/en_US/dwnld.html @@ -11,26 +11,27 @@

    -Changes can be tracked on pnp4nagios.git.sourceforge.net +Changes can be tracked on https://github.com/pnp4nagios

    -The current Version is pnp4nagios-0.6.25.tar.gz +with releases and downloads at https://github.com/pnp4nagios/pnp4nagios/releases

    +

    +Latest release and downloads at https://github.com/pnp4nagios/pnp4nagios/releases/latest +

    -

    Latest Devel Version

    +

    Documentation

    - pnp4nagios-head.tar.gz +Documentation

    -

    -This is allways the latest GIT HEAD Version -

    +

    @@ -42,9 +43,26 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017

    ChangeLog

    -

    - +pnp-0.6.27-4 09/05/2023 +

    • update URLs and related text
    • +
    • clean up autoconf stuff
    • +
    +

    +pnp-0.6.27 08/18/2023 +

    • >many php 8.2 fixes to remove 'deprecated' errors:
    • +
    • pre-defining class variables (instead of dynamic),
    • +
    • explicitly re-creating arrays as needed
    • +
    • converting utf8_encode to mbstring
    • +
    +

    +pnp-0.6.26-2 09/18/2022 +

    • various php8 fixes
    • +
    • rrdtools needs env XDG_CACHE_HOME for fontconfig
    • +
    • fix so that 'bucket' display works
    • +
    • fix so that pdf generation works
    • +
    +

    pnp-0.6.?? ??/??/2015

    @@ -236,10 +254,10 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017

  • Feature: Zoom based on jQuery plugin imgAreaSelect
    -( http://odyniec.net/projects/imgareaselect/ )
    +( https://github.com/odyniec/imgareaselect )
  • Feature: New template check_mssql_health.php
  • @@ -264,7 +282,7 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017
  • Bugfix: rrd_convert.pl: parse_xml_filename() regex fix
  • -
  • Info: Version used by OMD-0.48 OMD
    +
  • Info: Version used by OMD-0.48 OMD
  • @@ -298,7 +316,7 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017
  • Featue: npcd.cfg - New option perfdata_file_processing_interval used by npcdmod
  • -
  • Info: Version used by OMD-0.46 OMD
    +
  • Info: Version used by OMD-0.46 OMD
  • @@ -316,7 +334,7 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017
  • Feature: Pass query string from special controller to image controller ( Matthew Garrett )
  • -
  • Feature: Authorisation against mk_livestatus API added
    +
  • Feature: Authorisation against mk_livestatus API added
  • Feature: Sample nginx webserver config added ( by evax@users.sourceforge.net )
  • @@ -434,7 +452,7 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017
  • Update: FPDI update to 1.3.1
  • -
  • Feature: PNP will now work with lighttpd and php-cgi
    +
  • Feature: PNP will now work with lighttpd and php-cgi
  • Template: check_mk-ps.perf.php added ( by Mathias Kettner )
  • @@ -476,11 +494,11 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017

      -
    • Webfrontend based on Kohana
      +
    • Webfrontend based on Kohana
    • -
    • Webfrontend based on jQuery Themes
      +
    • Webfrontend based on jQuery Themes
    • -
    • Javascript-functions using jQuery plugins
      +
    • Javascript-functions using jQuery plugins
    • process_perfdata.pl will be able to use one RRD database per datasource
    • @@ -509,4 +527,4 @@ Last Update: Mon Aug 21 17:49:39 CEST 2017
    - \ No newline at end of file + diff --git a/share/pnp/documents/en_US/install.html b/share/pnp/documents/en_US/install.html index 48b8332..32ddb69 100644 --- a/share/pnp/documents/en_US/install.html +++ b/share/pnp/documents/en_US/install.html @@ -18,7 +18,7 @@ Please note that PNP has to be configured after the installation.

    -The installation of PNP is controlled by makefiles. The system is analyzed after invocation of ./configure and the detected values are tranferred to makefiles. +The installation of PNP is controlled by makefiles. The system is analyzed after invocation of ./configure and the detected values are tranferred to makefiles.

    @@ -210,4 +210,4 @@ the config file config.php for the web frontend in

    - \ No newline at end of file + diff --git a/share/pnp/documents/en_US/mobile.html b/share/pnp/documents/en_US/mobile.html index ca29775..705606d 100644 --- a/share/pnp/documents/en_US/mobile.html +++ b/share/pnp/documents/en_US/mobile.html @@ -10,7 +10,7 @@ Starting with PNP4Nagios 0.6.14 a web interface for mobile devices is integrated

    -The design was realised using jQuery Mobile and hence is compatible to current mobile browsers. The list of the supported devices shows a graded browser support chart. +The design was realised using jQuery Mobile and hence is compatible to current mobile browsers. The list of the supported devices shows a graded browser support chart.

    diff --git a/share/pnp/documents/en_US/modes.html b/share/pnp/documents/en_US/modes.html index dd80475..62c0508 100644 --- a/share/pnp/documents/en_US/modes.html +++ b/share/pnp/documents/en_US/modes.html @@ -124,7 +124,7 @@ Since version 0.6.12 PNP4Nagios can be driven as a gearman worker. This way larg

    -You need a mod_gearman environment up and running like described by Sven Nierlein on http://labs.consol.de/lang/en/nagios/mod-gearman/. +You need a mod_gearman environment up and running like described by Sven Nierlein on https://labs.consol.de/lang/en/nagios/mod-gearman/.

    diff --git a/share/pnp/documents/en_US/new-features.html b/share/pnp/documents/en_US/new-features.html index 915a6bd..a261263 100644 --- a/share/pnp/documents/en_US/new-features.html +++ b/share/pnp/documents/en_US/new-features.html @@ -13,7 +13,7 @@ The work on the new version 0.6.x is in full progress.

    -Starting with version 0.6.x we switch from subversion to GIT. The sourcecode is already available on sourceforge. +Starting with version 0.6.x we switch from subversion to GIT. The sourcecode is available on GitHub.

    @@ -21,11 +21,11 @@ Starting with version 0.6.x we switch from subversion to GIT. The

    +
  • Webfrontend based on Kohana
  • -
  • Webfrontend based on jQuery Themes
    +
  • Webfrontend based on jQuery Themes
  • -
  • Javascript-functions using jQuery plugins
    +
  • Javascript-functions using jQuery plugins
  • process_perfdata.pl will be able to use one RRD database per datasource
  • @@ -45,7 +45,7 @@ Starting with version 0.6.x we switch from subversion to GIT. The
    Page functions recoded
    -
  • +
  • Error pages links to online FAQ
  • Mouseover Popup in Nagios frontend via jQuery.clueTip plugin
  • diff --git a/share/pnp/documents/en_US/npcd.html b/share/pnp/documents/en_US/npcd.html index 7458788..20fecdd 100644 --- a/share/pnp/documents/en_US/npcd.html +++ b/share/pnp/documents/en_US/npcd.html @@ -156,7 +156,7 @@ use_load_threshold = 0 load_threshold = 10.0 # Process Options -pid_file=/var/run/npcd.pid +pid_file=/run/npcd.pid @@ -305,7 +305,7 @@ pid_file=/var/run/npcd.pid
    • the path to the PID File
    • -
    • Default: /var/run/npcd.pid
      +
    • Default: /run/npcd.pid
    diff --git a/share/pnp/documents/en_US/rrdcached.html b/share/pnp/documents/en_US/rrdcached.html index 0cb66b9..46e2c86 100644 --- a/share/pnp/documents/en_US/rrdcached.html +++ b/share/pnp/documents/en_US/rrdcached.html @@ -14,11 +14,11 @@ One improvement is made by collecting and sorting the data. It is more effective

    -The current RRDtool ( SVN trunk 1550+ ) contains rrdcached which should improve exactly this situation. +The current RRDtool ( SVN trunk 1550+ ) contains rrdcached which should improve exactly this situation.

    -At this point I'd like to thank Florian octo Forster, Kevin Brintnall and Tobi Oetiker. The development of this daemon has been coordinated exemplary on the rrd-developers mailing list. +At this point I'd like to thank Florian octo Forster, Kevin Brintnall and Tobi Oetiker. The development of this daemon has been coordinated exemplary on the rrd-developers mailing list.

    @@ -80,7 +80,7 @@ Option -z defines a maximum delay which will be used to spread the write cycles

    Option -p defines a PID file

    -
    -p /var/run/rrdcached.pid
    +
    -p /run/rrdcached.pid

    Option -j defines the path to a journaling directory. All requests will be logged there so that they can be processed after a restart in case the daemon crashes. @@ -126,7 +126,7 @@ Because two components of PNP have to prepared for the use of rrdcached there ar # EXPERIMENTAL rrdcached Support # Use only with rrdtool svn revision 1511+ # -RRD_DAEMON_OPTS = unix:/var/run/rrdcached.sock +RRD_DAEMON_OPTS = unix:/run/rrdcached.sock

    @@ -138,7 +138,7 @@ RRD_DAEMON_OPTS = unix:/var/run/rrdcached.sock # Use only with rrdtool svn revision 1511+ # # $conf['RRD_DAEMON_OPTS'] = 'unix:/tmp/rrdcached.sock'; -$conf['RRD_DAEMON_OPTS'] = 'unix:/var/run/rrdcached.sock'; +$conf['RRD_DAEMON_OPTS'] = 'unix:/run/rrdcached.sock';

    @@ -151,4 +151,4 @@ The sample files contain the relevant options.

    - \ No newline at end of file + diff --git a/share/pnp/documents/en_US/start.html b/share/pnp/documents/en_US/start.html index dbab286..a42ce57 100644 --- a/share/pnp/documents/en_US/start.html +++ b/share/pnp/documents/en_US/start.html @@ -16,7 +16,7 @@

    -PNP is an addon to Nagios which analyzes performance data provided by plugins and stores them automatically into RRD-databases (Round Robin Databases, see RRD Tool). +PNP is an addon to Nagios which analyzes performance data provided by plugins and stores them automatically into RRD-databases (Round Robin Databases, see RRD Tool).

    @@ -24,7 +24,7 @@ During development of PNP we set value on easy installation and little maintenan

    -To achieve this task we focused on using standards. PNP only processes performance data built according to the Developer Guidelines for nagios plugins. With this limitation we want to honour the work of Nagios Plugin Developers who stick to the guidelines. +To achieve this task we focused on using standards. PNP only processes performance data built according to the Developer Guidelines for nagios plugins. With this limitation we want to honour the work of Nagios Plugin Developers who stick to the guidelines.

    diff --git a/share/pnp/documents/en_US/tpl.html b/share/pnp/documents/en_US/tpl.html index 29b45ac..d5440d7 100644 --- a/share/pnp/documents/en_US/tpl.html +++ b/share/pnp/documents/en_US/tpl.html @@ -110,7 +110,7 @@ PNP template must have the following characteristics:

    -These two arrays are used to call 'rrdtool graph' so every option is possible that RRDtool supports. All options of RRDtool are described very thoroughly on the RRDtool Homepage. +These two arrays are used to call 'rrdtool graph' so every option is possible that RRDtool supports. All options of RRDtool are described very thoroughly on the RRDtool Homepage.

    @@ -165,7 +165,7 @@ $def[1] .= “GPRINT:var1:AVERAGE:\”%3.4lg %s$UNIT[1] AVERAGE \” ”;

    -The three GPRINT lines build up the caption for the graph. The current values are formatted using the printf syntax. +The three GPRINT lines build up the caption for the graph. The current values are formatted using the printf syntax.

    @@ -237,4 +237,4 @@ The value of the field <NAGIOS_SERVICEOUTPUT> is available as

    - \ No newline at end of file + diff --git a/share/pnp/documents/en_US/tpl_custom.html b/share/pnp/documents/en_US/tpl_custom.html index 08a1a52..9fa6d8e 100644 --- a/share/pnp/documents/en_US/tpl_custom.html +++ b/share/pnp/documents/en_US/tpl_custom.html @@ -94,7 +94,7 @@ Setting datasources to different types
    DATATYPE = GAUGE,GAUGE,COUNTER,COUNTER

    -More datatypes are explained in the RRDTool documentation found at rrdcreate. +More datatypes are explained in the RRDTool documentation found at rrdcreate.

    @@ -112,7 +112,7 @@ In a few situations it might be necessary to limit the values which are valid fo

    -RRD databases can be created with fixed minimum and maximum values. You will find further details at http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html. +RRD databases can be created with fixed minimum and maximum values. You will find further details at https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html.

    @@ -179,7 +179,7 @@ After <RRD_HEARTBEAT> seconds RRDtool expects new data.

    -More information at http://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html +More information at https://oss.oetiker.ch/rrdtool/doc/rrdcreate.en.html

    diff --git a/share/pnp/documents/en_US/tpl_helper.html b/share/pnp/documents/en_US/tpl_helper.html index f88eb93..e132729 100644 --- a/share/pnp/documents/en_US/tpl_helper.html +++ b/share/pnp/documents/en_US/tpl_helper.html @@ -21,7 +21,7 @@ string rrd::def ( $vname, $rrdfile, $ds, [ $cf='AVERAGE�

    $def = rrd::def('var1', $RRDFILE[0], $DS[0], 'MAX');

    -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html

    @@ -36,7 +36,7 @@ string rrd::cdef ( $vname, $rpn, )
    $def = rrd::cdef('var1_bits', 'var1,8,*' );

    -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html

    @@ -51,7 +51,7 @@ string rrd::vdef ( $vname, $rpn, )
    $def = rrd::vdef('var1_avg', 'var1,AVERAGE' );

    -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_data.en.html

    @@ -75,7 +75,7 @@ Draws a line three pixels wide with label “Load”

    -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html

    @@ -94,7 +94,7 @@ Draws an area with label “Load”

    -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html

    @@ -107,14 +107,14 @@ Draws an area with label “Load” string rrd::gprint ( $vname, $cf, [ $text ] )

    $def .= rrd::gprint('var1', 'MAX', '%4.2lf %s Max' );
    -
    $def .= rrd::gprint('var1', array('MIN', 'MAX', 'AVERAGE'), '%4.2lf %s' );
    +
    $def .= rrd::gprint('var1', array('MIN', 'MAX', 'AVERAGE'), '%4.2lf %s' );

    If $cf is an array the legend will be formatted automatically

    -http://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html +https://oss.oetiker.ch/rrdtool/doc/rrdgraph_graph.en.html

    @@ -164,7 +164,7 @@ Creates a color gradient from $start_color to $end_color

    -Example +Example

    @@ -201,7 +201,7 @@ Creates a colorized bar at the top of the chart which shows different colors dep

    -Example +Example

    @@ -220,7 +220,7 @@ Creates colorized areas, which show different colors depending on states OK, WAR
    $def .= rrd::alerter( "var1", $LABEL[0], $WARN[0], $CRIT[0], "FF", $UNIT[0] );

    -Example +Example

    @@ -239,9 +239,9 @@ Creates colorized gradients, which show different colors depending on states OK,
    $def .= rrd::alerter_gr( "var1", $LABEL[0], $WARN[0], $CRIT[0], "FF", $UNIT[0] );

    -Example +Example

    - \ No newline at end of file + diff --git a/share/pnp/documents/en_US/tpl_special.html b/share/pnp/documents/en_US/tpl_special.html index 958df3c..1c86acc 100644 --- a/share/pnp/documents/en_US/tpl_special.html +++ b/share/pnp/documents/en_US/tpl_special.html @@ -82,7 +82,7 @@ To ease template development and to give an insight on the data structures you c

    To show the data of $services you just need the following line:

    -
    throw new Kohana_exception(print_r($services,TRUE));
    +
    throw new Kohana_exception(print_r($services,TRUE));

    Output of pnp4nagios/special?tpl=websrv_response_times @@ -116,7 +116,7 @@ Step 3: Iterating the array $services and creating the graph definitions $hostname = rrd::cut($data['MACRO']['HOSTNAME'], 15); $def[0] .= rrd::def("var$key" , $data['DS'][0]['RRDFILE'], $data['DS'][0]['DS'] ); $def[0] .= rrd::line1("var$key", rrd::color($key), $hostname); - $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); + $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); }

    @@ -174,7 +174,7 @@ You will find more information on the PNP helpers $hostname = rrd::cut($data['MACRO']['HOSTNAME']); $def[0] .= rrd::def("var$key" , $data['DS'][0]['RRDFILE'], $data['DS'][0]['DS'] ); $def[0] .= rrd::line1("var$key", rrd::color($key), $hostname); - $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); + $def[0] .= rrd::gprint("var$key", array("MAX", "AVERAGE")); } ?> diff --git a/share/pnp/documents/en_US/upgrade.html b/share/pnp/documents/en_US/upgrade.html index 4bbce5b..8ff8481 100644 --- a/share/pnp/documents/en_US/upgrade.html +++ b/share/pnp/documents/en_US/upgrade.html @@ -6,7 +6,7 @@

    -The web-frontend has been completely rewritten and is now based on the PHP MVC framework Kohana. This leads to changed dependencies which must be checked prior to installation. +The web-frontend has been completely rewritten and is now based on the PHP MVC framework Kohana. This leads to changed dependencies which must be checked prior to installation.

    diff --git a/share/pnp/documents/en_US/verify_pnp_config.html b/share/pnp/documents/en_US/verify_pnp_config.html index 74a06bd..a40211d 100644 --- a/share/pnp/documents/en_US/verify_pnp_config.html +++ b/share/pnp/documents/en_US/verify_pnp_config.html @@ -6,11 +6,11 @@

    -In case of problems there is a script called verify_pnp_config.pl located on http://verify.pnp4nagios.org. It enables you to check the configuration settings as well as performance data of hosts or services. It can be used prior and during runtime of PNP. +In case of problems there is a script called verify_pnp_config.pl located on https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl. It enables you to check the configuration settings as well as performance data of hosts or services. It can be used prior and during runtime of PNP.

    -* ATTENTION *: It ONLY supports verifying Nagios 3.x and Icinga 1.x as Monitoring core. +* ATTENTION *: Check what versions of Nagios and Icinga are supported as Monitoring core.

    @@ -18,7 +18,7 @@ In case of problems there is a script called verify_pnp_config.pl l

    Download

    -wget http://verify.pnp4nagios.org/verify_pnp_config
    +wget https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl
     
    @@ -28,7 +28,7 @@ wget http://verify.pnp4nagios.org/verify_pnp_config

    -The verify script is located on http://verify.pnp4nagios.org and needs three start options +The verify script is located on https://github.com/pnp4nagios/pnp4nagios/blob/master/scripts/verify_pnp_config_v2.pl and needs three start options

    • --mode One of the modes described on modes
      @@ -133,4 +133,4 @@ The strings are taken as regular expressions (perl syntax).

      - \ No newline at end of file + diff --git a/share/pnp/documents/en_US/webfe.html b/share/pnp/documents/en_US/webfe.html index 36ed83e..f6c3f1c 100644 --- a/share/pnp/documents/en_US/webfe.html +++ b/share/pnp/documents/en_US/webfe.html @@ -13,38 +13,17 @@ Nagios itself features external URLs using so called extended info configs. Due

      - -

      Nagios 2.x

      -
      - -

      - -With Nagios 2.x the integration of external URLs into the nagios web interface is made using Extended Info Objects for services. For PNP we use the directive action_url to call the PNP web frontend with the appropriate options. -

      -
      -define serviceextinfo {
      -   host_name             localhost
      -   service_description   load
      -   action_url            /pnp4nagios/index.php/graph?host=$HOSTNAME$&srv=$SERVICEDESC$
      -}
      -
      - -

      -You have to specify an additional Extended Info Definition for every service. -

      - -
      - +

      Nagios 3.x

      -Since nagios 3.0 the action_url-directive has be moved to the host or service definition. This way the definition of URLs to the PNP-interface has been simplified. The serviceextinfo and hostextinfo definitions are deprecated. +Since nagios 3.0 the action_url-directive has be moved to the host or service definition. This way the definition of URLs to the PNP-interface has been simplified. The serviceextinfo and hostextinfo definitions are deprecated.

      -First two nagios templates are defined. If you used the Nagios quickstart installation guides you can append these lines to templates.cfg: +First two nagios templates are defined. If you used the Nagios quickstart installation guides you can append these lines to templates.cfg:

       define host {
      @@ -97,7 +76,7 @@ The links to the correct URLs are created automagically.

      -You can integrate PNP into Nagios in a way that you have current graphs without clicking any icons. This can be accomplished using the CGI Includes which allow us to include JavaScript code in the status detail view ( status.cgi ). +You can integrate PNP into Nagios in a way that you have current graphs without clicking any icons. This can be accomplished using the CGI Includes which allow us to include JavaScript code in the status detail view ( status.cgi ).

      @@ -146,4 +125,4 @@ After a restart of Nagios (after modifying the definitions) the result might loo

      - \ No newline at end of file + diff --git a/share/pnp/documents/templates/alerter.html b/share/pnp/documents/templates/alerter.html new file mode 100644 index 0000000..2b762b2 --- /dev/null +++ b/share/pnp/documents/templates/alerter.html @@ -0,0 +1,48 @@ +alerter.php +

      alerter.php

      +
      
      +<?php
      +#
      +# Copyright (c) 2006-2010 Joerg Linge (http://www.pnp4nagios.org)
      +# Plugin: check_icmp [Multigraph]
      +#
      +# RTA
      +#
      +$ds_name[1] = "Round Trip Times";
      +$opt[1]  = "--lower=0 --vertical-label \"RTA\" --title \"Ping times\" ";
      +$def[1]  =  rrd::def("var1", $RRDFILE[1], $DS[1], "AVERAGE") ;
      +$def[1] .=  rrd::alerter("var1","Round Trip Times", $WARN[1], $CRIT[1], "FF", $UNIT[1],"#00ff00","#ff8c00","#ff0000") ;
      +$def[1] .=  rrd::gprint("var1", array("LAST", "MAX", "AVERAGE"), "%6.2lf $UNIT[1]") ;
      +
      +if($WARN[1] != ""){
      +    if($UNIT[1] == "%%"){ $UNIT[1] = "%"; };
      +    $def[1] .= rrd::hrule($WARN[1], "#FF8c00", "Warning  ".$WARN[1].$UNIT[1]."\\n");
      +}
      +if($CRIT[1] != ""){
      +    if($UNIT[1] == "%%"){ $UNIT[1] = "%"; };
      +    $def[1] .= rrd::hrule($CRIT[1], "#FF0000", "Critical  ".$CRIT[1].$UNIT[1]."\\n");
      +}
      +
      +#
      +# Packets Lost
      +$ds_name[2] = "Packets Lost";
      +$opt[2] = "--vertical-label \"Packets lost\" -l0 -u105 --title \"Packets lost\" ";
      +
      +$def[2]  =  rrd::def("var1", $RRDFILE[2], $DS[2], "AVERAGE");
      +$def[2] .=  rrd::alerter("var1","Packet loss", $WARN[2], $CRIT[2], "FF", $UNIT[2],"#00ff00","#ff8c00","#ff0000") ;
      +$def[2] .=  rrd::gprint("var1", array("LAST", "MAX", "AVERAGE"), "%3.0lf $UNIT[2]") ;
      +
      +$def[2] .= rrd::hrule("100", "#000000", ":dashes") ;
      +
      +if($WARN[2] != ""){
      +    if($UNIT[2] == "%%"){ $UNIT[2] = "%"; };
      +    $def[2] .= rrd::hrule($WARN[2], "#FF8c00", "Warning  ".$WARN[2].$UNIT[2]."\\n");
      +}
      +if($CRIT[2] != ""){
      +    if($UNIT[2] == "%%"){ $UNIT[2] = "%"; };
      +    $def[2] .= rrd::hrule($CRIT[2], "#FF0000", "Critical  ".$CRIT[2].$UNIT[2]."\\n");
      +}
      +
      +?>
      +
      +
      diff --git a/share/pnp/documents/templates/check_apachestatus.html b/share/pnp/documents/templates/check_apachestatus.html new file mode 100644 index 0000000..0a27509 --- /dev/null +++ b/share/pnp/documents/templates/check_apachestatus.html @@ -0,0 +1,49 @@ +check_apachestatus.php +

      check_apachestatus.php

      +
      
      +<?php
      +
      +$opt[1] = "-T 55 -l 0 --vertical-label \"Apache Stats\"  --title \"Apache Statistics\" ";
      +$ds_name[1] = "Thread Statistics";
      +$def[1] = "";
      +
      +$colors = array(
      +        'wait' => '#DD8E45',
      +        'starting' => '#DDAF45',
      +        'read' => '#D0DD45',
      +        'write' => '#DD457C',
      +        'keep' => '#45DD99',
      +        'dns' => '#45C5DD',
      +        'close' => '#4596DD',
      +        'logging' => '#4557DD',
      +        'grace' => '#A445DD',
      +        'idle' => '#DD45D8',
      +        );
      +
      +$def[1] = "DEF:var12=$rrdfile:$DS[12]:AVERAGE " ;
      +$def[1] .= "LINE1:var12#00000080: " ;
      +$def[1] .= "AREA:var12#00FF6680:\"slots\t\" " ;
      +$def[1] .= "GPRINT:var12:AVERAGE:\"%.0lf Average\" ";
      +$def[1] .= "GPRINT:var12:MAX:\"%.0lf Max\" ";
      +$def[1] .= "GPRINT:var12:LAST:\"%.0lf Last\\n\" ";
      +
      +$keys = array(4,3,2,5,6,7,8,9,10,11);
      +foreach( $keys  as $key){
      +        $def[1] .= "DEF:var$key=$rrdfile:$DS[$key]:AVERAGE " ;
      +        $def[1] .= "STACK:var$key".$colors[$NAME[$key]].":\"$NAME[$key]\t\" " ;
      +        $def[1] .= "GPRINT:var$key:AVERAGE:\"%.0lf Average\" ";
      +        $def[1] .= "GPRINT:var$key:MAX:\"%.0lf Max\" ";
      +        $def[1] .= "GPRINT:var$key:LAST:\"%.0lf Last\\n\" ";
      +}
      +
      +$opt[2] = "-l 0 --vertical-label \"Apache Requests\"  --title \"Server $hostname\" ";
      +$ds_name[2] = "Request per Second";
      +$def[2]  = "DEF:var1=$rrdfile:$DS[1]:AVERAGE " ;
      +$def[2] .= "LINE1:var1#000000:\"Requests per Second\" " ;
      +$def[2] .= "GPRINT:var1:AVERAGE:\"%.2lf Average\" ";
      +$def[2] .= "GPRINT:var1:MAX:\"%.2lf Max\" ";
      +$def[2] .= "GPRINT:var1:LAST:\"%.2lf Last\\n\" ";
      +
      +?>
      +
      +
      diff --git a/share/pnp/documents/templates/check_cpu.html b/share/pnp/documents/templates/check_cpu.html new file mode 100644 index 0000000..b97885e --- /dev/null +++ b/share/pnp/documents/templates/check_cpu.html @@ -0,0 +1,60 @@ +check_cpu.php +

      check_cpu.php

      +
      
      +<?php
      +#
      +# Copyright (c)  2010 Yannig Perre (http://lesaventuresdeyannigdanslemondeit.blogspot.com)
      +# Plugin: check_cpu
      +#
      +$ds_name[1] = "CPU activity";
      +
      +$opt[1] = "--upper-limit 100 --vertical-label CPU -l0  --title \"CPU activity on $hostname\" ";
      +
      +$trend_array = array(
      +  "one_month"    => array(strtotime("-1 month", $this->TIMERANGE['end']), $this->TIMERANGE['end'], "1 month trend:dashes=10", "#FF007F", "line3"),
      +  "global_trend" => array($this->TIMERANGE['start'], $this->TIMERANGE['end'], "Global trend\\n:dashes=20", "#707070", "line2"),
      +);
      +
      +$def[1] =  rrd::def("var1", $RRDFILE[1], $DS[1]);
      +$def[1] .= rrd::def("var2", $RRDFILE[2], $DS[2]);
      +$def[1] .= rrd::cdef("user", "var2,var1,+");
      +$def[1] .= rrd::def("var3", $RRDFILE[3], $DS[3]);
      +$def[1] .= rrd::cdef("io", "var3,var2,+,var1,+");
      +
      +$trends_graphic = "";
      +
      +foreach(array_keys($trend_array) as $trend) {
      +  $def[1] .= rrd::def("var1$trend", $RRDFILE[1], $DS[1], "AVERAGE:start=".$trend_array[$trend][0]);
      +  $def[1] .= rrd::def("var2$trend", $RRDFILE[2], $DS[2], "AVERAGE:start=".$trend_array[$trend][0]);
      +  $def[1] .= rrd::cdef("user$trend", "var2$trend,var1$trend,+");
      +
      +  $def[1] .= rrd::vdef("dtrend$trend", "user$trend,LSLSLOPE");
      +  $def[1] .= rrd::vdef("htrend$trend", "user$trend,LSLINT");
      +  $def[1] .= rrd::cdef("curve_user$trend", "user$trend,POP,dtrend$trend,COUNT,*,htrend$trend,+");
      +  $trends_graphic .= rrd::$trend_array[$trend][4]("curve_user$trend", $trend_array[$trend][3], $trend_array[$trend][2]);
      +}
      +
      +if ($WARN[1] != "") { $def[1] .= rrd::hrule($WARN[1], "#FFFF00"); }
      +if ($CRIT[1] != "") { $def[1] .= rrd::hrule($CRIT[1], "#FF0000"); }
      +
      +$def[1] .= rrd::area("io", "#00FF00", "iowait");
      +$def[1] .= rrd::gprint("var3", "LAST", "%6.2lf");
      +$def[1] .= rrd::gprint("var3", "AVERAGE", "avg %6.2lf");
      +$def[1] .= rrd::gprint("var3", "MAX", "max %6.2lf\\n");
      +$def[1] .= rrd::area("user", "#005CFF", "user  ");
      +$def[1] .= rrd::gprint("var1", "LAST", "%6.2lf");
      +$def[1] .= rrd::gprint("var1", "AVERAGE", "avg %6.2lf");
      +$def[1] .= rrd::gprint("var1", "MAX", "max %6.2lf\\n");
      +$def[1] .= rrd::area("var2", "#FF5C00", "sys   ");
      +$def[1] .= rrd::gprint("var2", "LAST", "%6.2lf");
      +$def[1] .= rrd::gprint("var2", "AVERAGE", "avg %6.2lf");
      +$def[1] .= rrd::gprint("var2", "MAX", "max %6.2lf\\n");
      +$def[1] .= rrd::line1("io", "#000000");
      +$def[1] .= rrd::line1("user", "#000000", "Total");
      +$def[1] .= rrd::gprint("user", "LAST", " %6.2lf");
      +$def[1] .= rrd::gprint("user", "AVERAGE", "moy %6.2lf");
      +$def[1] .= rrd::gprint("user", "MAX", "max %6.2lf\\n");
      +$def[1] .= rrd::line1("var2", "#000000");
      +$def[1] .= $trends_graphic;
      +?>
      +
      diff --git a/share/pnp/documents/templates/check_http.html b/share/pnp/documents/templates/check_http.html new file mode 100644 index 0000000..f392918 --- /dev/null +++ b/share/pnp/documents/templates/check_http.html @@ -0,0 +1,62 @@ +check_http.php +

      check_http.php

      +
      
      +<?php
      +#
      +# Copyright (c) 2006-2008 Joerg Linge (http://www.pnp4nagios.org)
      +# Plugin: check_http_response
      +# $Id: check_http.php 367 2008-01-23 18:10:31Z pitchfork $
      +# Modified by Romuald FRONTEAU
      +#
      +# Response Time
      +#
      +$opt[1] = "--vertical-label \"$UNIT[1]\" --title \"Temps de reponse - $hostname / $servicedesc\" --slope-mode --color=BACK#000000 --color=FONT#F7F7F7 --color=SHADEA#ffffff --color=SHADEB#ffffff --color=CANVAS#000000 --color=GRID#00991A --color=MGRID#00991A --color=ARROW#FF0000 ";
      +#
      +#
      +#
      +$def[1] =  "DEF:var1=$RRDFILE[1]:$DS[1]:AVERAGE " ;
      +$def[1] .= "VDEF:slope=var1,LSLSLOPE " ;
      +$def[1] .= "VDEF:int=var1,LSLINT " ;
      +$def[1] .= "CDEF:proj=var1,POP,slope,COUNT,*,int,+ " ;
      +$def[1] .= "LINE2:proj#ff00ff:\"Projection \" " ;
      +$def[1] .= "GPRINT:var1:LAST:\"%6.2lf$UNIT[1] last\" " ;
      +$def[1] .= "GPRINT:var1:AVERAGE:\"%6.2lf$UNIT[1] avg\" " ;
      +$def[1] .= "GPRINT:var1:MAX:\"%6.2lf$UNIT[1] max\\n\" ";
      +$def[1] .=  "CDEF:sp1=var1,100,/,10,* " ;
      +$def[1] .=  "CDEF:sp2=var1,100,/,20,* " ;
      +$def[1] .=  "CDEF:sp3=var1,100,/,30,* " ;
      +$def[1] .=  "CDEF:sp4=var1,100,/,40,* " ;
      +$def[1] .=  "CDEF:sp5=var1,100,/,50,* " ;
      +$def[1] .=  "CDEF:sp6=var1,100,/,60,* " ;
      +$def[1] .=  "CDEF:sp7=var1,100,/,70,* " ;
      +$def[1] .=  "CDEF:sp8=var1,100,/,80,* " ;
      +$def[1] .=  "CDEF:sp9=var1,100,/,90,* " ;
      +
      +
      +$def[1] .= "AREA:var1#0000A0:\"$NAME[1] \" " ;
      +$def[1] .= "AREA:sp9#0000A0: " ;
      +$def[1] .= "AREA:sp8#0000C0: " ;
      +$def[1] .= "AREA:sp7#0010F0: " ;
      +$def[1] .= "AREA:sp6#0040F0: " ;
      +$def[1] .= "AREA:sp5#0070F0: " ;
      +$def[1] .= "AREA:sp4#00A0F0: " ;
      +$def[1] .= "AREA:sp3#00D0F0: " ;
      +$def[1] .= "AREA:sp2#A0F0F0: " ;
      +$def[1] .= "AREA:sp1#F0F0F0: " ;
      +
      +#
      +# Filesize
      +#
      +$opt[2] = "--vertical-label \"$UNIT[2]\" --title \"Size $hostname / $servicedesc\" ";
      +#
      +#
      +#
      +$def[2] =  "DEF:var1=$RRDFILE[2]:$DS[2]:AVERAGE " ;
      +$def[2] .= "AREA:var1#00FFFF:\"$NAME[2] \" " ;
      +$def[2] .= "LINE1:var1#000000 " ;
      +$def[2] .= "GPRINT:var1:LAST:\"%6.2lf$UNIT[2] last\" " ;
      +$def[2] .= "GPRINT:var1:AVERAGE:\"%6.2lf$UNIT[2] avg\" " ;
      +$def[2] .= "GPRINT:var1:MAX:\"%6.2lf$UNIT[2] max\\n\" ";
      +?>
      +
      +
      diff --git a/share/pnp/documents/templates/check_mk-cpu.loads.html b/share/pnp/documents/templates/check_mk-cpu.loads.html new file mode 100644 index 0000000..e939af2 --- /dev/null +++ b/share/pnp/documents/templates/check_mk-cpu.loads.html @@ -0,0 +1,72 @@ +check_mk-cpu.loads.php +

      check_mk-cpu.loads.php

      +
      
      +<?php
      +# +------------------------------------------------------------------+
      +# |             ____ _               _        __  __ _  __           |
      +# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
      +# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
      +# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
      +# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
      +# |                                                                  |
      +# | Copyright Mathias Kettner 2009             mk@mathias-kettner.de |
      +# +------------------------------------------------------------------+
      +#
      +# This file is part of Check_MK.
      +# The official homepage is at http://mathias-kettner.de/check_mk.
      +#
      +# check_mk 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 in version 2.  check_mk is  distributed
      +# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
      +# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
      +# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
      +# ails.  You should have  received  a copy of the  GNU  General Public
      +# License along with GNU Make; see the file  COPYING.  If  not,  write
      +# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
      +# Boston, MA 02110-1301 USA.
      +
      +# Modified by Romuald FRONTEAU
      +
      +$opt[1] = "--vertical-label Load --title \"CPU Load pour $hostname / $servicedesc\" --color=BACK#000000 --color=FONT#F7F7F7 --color=SHADEA#ffffff --color=SHADEB#ffffff --color=CANVAS#000000 --color=GRID#00991A --color=MGRID#00991A --color=ARROW#FF0000 ";
      +
      +$def[1] =  "DEF:var1=$rrdfile:$DS[1]:AVERAGE " ;
      +$def[1] .= "DEF:var2=$rrdfile:$DS[2]:AVERAGE " ;
      +$def[1] .= "DEF:var3=$rrdfile:$DS[3]:AVERAGE " ;
      +$def[1] .= "AREA:var1#F8D605:\"1 min \" " ;
      +$def[1] .= "GPRINT:var1:LAST:\"%6.2lf last\" " ;
      +$def[1] .= "GPRINT:var1:AVERAGE:\"%6.2lf avg\" " ;
      +$def[1] .= "GPRINT:var1:MAX:\"%6.2lf max\\n\" ";
      +
      +$def[1] .=  "CDEF:sp1=var2,100,/,10,* " ;
      +$def[1] .=  "CDEF:sp2=var2,100,/,20,* " ;
      +$def[1] .=  "CDEF:sp3=var2,100,/,30,* " ;
      +$def[1] .=  "CDEF:sp4=var2,100,/,40,* " ;
      +$def[1] .=  "CDEF:sp5=var2,100,/,50,* " ;
      +$def[1] .=  "CDEF:sp6=var2,100,/,60,* " ;
      +$def[1] .=  "CDEF:sp7=var2,100,/,70,* " ;
      +$def[1] .=  "CDEF:sp8=var2,100,/,80,* " ;
      +$def[1] .=  "CDEF:sp9=var2,100,/,90,* " ;
      +
      +$def[1] .= "AREA:var2#F85B05:\"5 min \" ";
      +$def[1] .= "AREA:sp9#F85B05: " ;
      +$def[1] .= "AREA:sp8#FB7328: " ;
      +$def[1] .= "AREA:sp7#FD8645: " ;
      +$def[1] .= "AREA:sp6#FD9862: " ;
      +$def[1] .= "AREA:sp5#FDA97D: " ;
      +$def[1] .= "AREA:sp4#C5D760: " ;
      +$def[1] .= "AREA:sp3#FBBE9E: " ;
      +$def[1] .= "AREA:sp2#FFD9C5: " ;
      +$def[1] .= "AREA:sp1#FFFFFF: " ;
      +
      +$def[1] .= "GPRINT:var2:LAST:\"%6.2lf last\" " ;
      +$def[1] .= "GPRINT:var2:AVERAGE:\"%6.2lf avg\" " ;
      +$def[1] .= "GPRINT:var2:MAX:\"%6.2lf max\\n\" ";
      +
      +$def[1] .= "LINE2:var3#FC2505:\"15 min \" " ;
      +$def[1] .= "GPRINT:var3:LAST:\"%6.2lf last\" " ;
      +$def[1] .= "GPRINT:var3:AVERAGE:\"%6.2lf avg\" " ;
      +$def[1] .= "GPRINT:var3:MAX:\"%6.2lf max\\n\" " ;
      +?>
      +
      +
      diff --git a/share/pnp/documents/templates/check_mk-df.html b/share/pnp/documents/templates/check_mk-df.html new file mode 100644 index 0000000..7c22ca5 --- /dev/null +++ b/share/pnp/documents/templates/check_mk-df.html @@ -0,0 +1,83 @@ +check_mk-df.php +

      check_mk-df.php

      +
      
      +<?php
      +# +------------------------------------------------------------------+
      +# |             ____ _               _        __  __ _  __           |
      +# |            / ___| |__   ___  ___| | __   |  \/  | |/ /           |
      +# |           | |   | '_ \ / _ \/ __| |/ /   | |\/| | ' /            |
      +# |           | |___| | | |  __/ (__|   <    | |  | | . \            |
      +# |            \____|_| |_|\___|\___|_|\_\___|_|  |_|_|\_\           |
      +# |                                                                  |
      +# | Copyright Mathias Kettner 2009             mk@mathias-kettner.de |
      +# +------------------------------------------------------------------+
      +#
      +# This file is part of Check_MK.
      +# The official homepage is at http://mathias-kettner.de/check_mk.
      +#
      +# check_mk 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 in version 2.  check_mk is  distributed
      +# in the hope that it will be useful, but WITHOUT ANY WARRANTY;  with-
      +# out even the implied warranty of  MERCHANTABILITY  or  FITNESS FOR A
      +# PARTICULAR PURPOSE. See the  GNU General Public License for more de-
      +# ails.  You should have  received  a copy of the  GNU  General Public
      +# License along with GNU Make; see the file  COPYING.  If  not,  write
      +# to the Free Software Foundation, Inc., 51 Franklin St,  Fifth Floor,
      +# Boston, MA 02110-1301 USA.
      +
      +# Modified by Romuald FRONTEAU
      +
      +# RRDtool Options
      +#$servicedes=$NAGIOS_SERVICEDESC
      +
      +$fsname = str_replace("_", "/", substr($servicedesc, 3));
      +$fstitle = $fsname;
      +
      +# Hack for windows: replace C// with C:\
      +if (strlen($fsname) == 3 && substr($fsname, 1, 2) == '//') {
      +    $fsname = $fsname[0] . "\:\\\\";
      +    $fstitle = $fsname[0] . ":\\";
      +}
      +
      +$sizegb = sprintf("%.1f", $MAX[1] / 1024.0);
      +$opt[1] = "--vertical-label Pourcentage --slope-mode -l 0 -u 100 --title '$hostname: Filesystem $fstitle (Total --> $sizegb GB)' ";
      +#
      +#
      +# Graphen Definitions
      +$def[1] = "DEF:fs=$rrdfile:$DS[1]:MAX ";
      +$def[1] .= "CDEF:var1=fs,$MAX[1],/,100,* ";
      +
      +$def[1] .=  "CDEF:sp1=var1,100,/,10,* " ;
      +$def[1] .=  "CDEF:sp2=var1,100,/,20,* " ;
      +$def[1] .=  "CDEF:sp3=var1,100,/,30,* " ;
      +$def[1] .=  "CDEF:sp4=var1,100,/,40,* " ;
      +$def[1] .=  "CDEF:sp5=var1,100,/,50,* " ;
      +$def[1] .=  "CDEF:sp6=var1,100,/,60,* " ;
      +$def[1] .=  "CDEF:sp7=var1,100,/,70,* " ;
      +$def[1] .=  "CDEF:sp8=var1,100,/,80,* " ;
      +$def[1] .=  "CDEF:sp9=var1,100,/,90,* " ;
      +
      +$def[1] .= "VDEF:slope=var1,LSLSLOPE " ;
      +$def[1] .= "VDEF:int=var1,LSLINT " ;
      +$def[1] .= "CDEF:proj=var1,POP,slope,COUNT,*,int,+ " ;
      +
      +$def[1] .= "AREA:var1#84C21F:\"% utilise sur $fsname\" ";
      +$def[1] .= "AREA:sp9#84C21F: " ;
      +$def[1] .= "AREA:sp8#8CC427: " ;
      +$def[1] .= "AREA:sp7#9CCA37: " ;
      +$def[1] .= "AREA:sp6#A5CD3F: " ;
      +$def[1] .= "AREA:sp5#B4D14F: " ;
      +$def[1] .= "AREA:sp4#C5D760: " ;
      +$def[1] .= "AREA:sp3#D5DC70: " ;
      +$def[1] .= "AREA:sp2#E6E280: " ;
      +$def[1] .= "AREA:sp1#F6E790: " ;
      +
      +$def[1] .= "LINE1:var1#226600: ";
      +$def[1] .= "GPRINT:var1:LAST:\"current\: %6.2lf %%\" ";
      +$def[1] .= "GPRINT:var1:MAX:\"max\: %6.2lf %%\" ";
      +$def[1] .= "GPRINT:var1:AVERAGE:\"avg\: %6.2lf %%\\n\" ";
      +$def[1] .= "LINE2:proj#F83F05:\"Projection \" " ;
      +?>
      +
      +
      diff --git a/share/pnp/documents/templates/check_oracle_health_tablespace-usage.html b/share/pnp/documents/templates/check_oracle_health_tablespace-usage.html new file mode 100644 index 0000000..08bdab1 --- /dev/null +++ b/share/pnp/documents/templates/check_oracle_health_tablespace-usage.html @@ -0,0 +1,49 @@ +check_oracle_health_tablespace-usage.php +

      check_oracle_health_tablespace-usage.php

      +
      
      +<?php
      +#
      +# Colors are simply doubled, because some DB have ridiculous count of performancedata. It should be o.k. in 
      +# the graphs though
      +$colors=array("CC3300","CC3333","CC3366","CC3399","CC33CC","CC33FF","336600","336633","336666","336699","3366CC","3366FF","33CC33","33CC66","609978","922A99","997D6D","174099","1E9920","E88854","AFC5E8","57FA44","FA6FF6","008080","D77038","272B26","70E0D9","0A19EB","E5E29D","930526","26FF4A","ABC2FF","E2A3FF","808000","000000","00FAFA","E5FA79","F8A6FF","FF36CA","B8FFE7","CD36FF",
      +"CC3300","CC3333","CC3366","CC3399","CC33CC","CC33FF","336600","336633","336666","336699","3366CC","3366FF","33CC33","33CC66","609978","922A99","997D6D","174099","1E9920","E88854","AFC5E8","57FA44","FA6FF6","008080","D77038","272B26","70E0D9","0A19EB","E5E29D","930526","26FF4A","ABC2FF","E2A3FF","808000","000000","00FAFA","E5FA79","F8A6FF"
      +);
      +
      +foreach($DS as $i => $VAL){
      +# Graph for tablespace percentage
      +    if(preg_match('/^tbs_.*_usage_pct$/',$NAME[$i], $matches)){
      +        $ds_name[1] = "TBS usage %";
      +        $short_name = $matches[0];
      +        $short_name = substr($short_name, 4,-10);
      +        $opt[1] = "--vertical-label \"TBS usage %\" -u102 -X0 -l0 --title \"Tablespace usage percent $servicedesc\" ";
      +        if(!isset($def[1])){
      +            $def[1] = "";
      +        }
      +        $def[1] .= "DEF:var$i=$RRDFILE[$i]:$DS[$i]:AVERAGE " ;
      +        $def[1] .= "LINE:var$i#".$colors[$i].":\"$short_name\" " ;
      +        $def[1] .= "GPRINT:var$i:LAST:\"%6.0lf PERC LAST \" ";
      +        $def[1] .= "GPRINT:var$i:MAX:\"%6.0lf PERC MAX \" ";
      +        $def[1] .= "GPRINT:var$i:AVERAGE:\"%6.2lf PERC AVERAGE \\n\" ";
      +    }
      +
      +# Graph for tablespace size
      +    if(preg_match('/^tbs_.*_usage$/',$NAME[$i], $matches)){
      +        $ds_name[2] = "TBS usage MB/GB";
      +        $short_name = $matches[0];
      +        $short_name = substr($short_name, 4,-6);
      +        $opt[2] = " -X 0 --vertical-label \"TBS usage MB/GB\" --title \"Tablespace usage MB/GB $servicedesc\" ";
      +        if(!isset($def[2])){
      +            $def[2] = "";
      +        }
      +        $def[2] .= "DEF:var$i=$RRDFILE[$i]:$DS[$i]:AVERAGE " ;
      +        $def[2] .= "LINE:var$i#".$colors[$i].":\"$short_name\" " ;
      +        $def[2] .= "GPRINT:var$i:LAST:\"%6.0lf $UNIT[$i] LAST \" ";
      +        $def[2] .= "GPRINT:var$i:MAX:\"%6.0lf  $UNIT[$i] MAX \" ";
      +        $def[2] .= "GPRINT:var$i:AVERAGE:\"%6.2lf  $UNIT[$i] AVERAGE \\n\" ";
      +    }
      +}
      +
      +?>
      +
      +
      +
      diff --git a/share/pnp/documents/templates/check_wlsagent.html b/share/pnp/documents/templates/check_wlsagent.html new file mode 100644 index 0000000..1262521 --- /dev/null +++ b/share/pnp/documents/templates/check_wlsagent.html @@ -0,0 +1,90 @@ +check_wlsagent.php +

      check_wlsagent.php

      +
      
      +<?php
      +
      +$ds_name[0] = "Heap usage / ".$servicedesc." ($hostname)";
      +
      +$opt[0] = "--vertical-label \"Heap usage (MB)\" -l 0 --title \"".$ds_name[0]."\" ";
      +
      +# Memory definition
      +$def[0]  = rrd::def("heapsize",   $RRDFILE[1], $DS[1]);
      +$def[0] .= rrd::def("usedmemory", $RRDFILE[2], $DS[2]);
      +$def[0] .= rrd::gradient("heapsize", "#ffffff", "#cceeee");
      +$def[0] .= rrd::line1("heapsize", "#ddcccc");
      +$def[0] .= rrd::gradient("usedmemory", "#ffffff", "#33cccc", 'Used memory');
      +$def[0] .= rrd::line1("usedmemory", "#339999");
      +$def[0] .= rrd::gprint("usedmemory", "LAST",    "last %4.lf");
      +$def[0] .= rrd::gprint("usedmemory", "MAX",     "max %4.lf");
      +$def[0] .= rrd::gprint("usedmemory", "AVERAGE", "average %4.2lf");
      +
      +$next_def = 1;
      +for($i = 2; $i < count($this->DS, 2); $i++) {
      + $label = $this->DS[$i]["LABEL"];
      + if(preg_match("/^ThreadPoolSize$/", $label, $tmp)) {
      +   $source = "ThreadPoolSize";
      +   $label = "Thread pool / $servicedesc ($hostname)";
      +   $ds_name[$next_def] = $label;
      +   $opt[$next_def] = "--vertical-label \"Thread count\" -l 0 --title \"$label\" ";
      +   $def[$next_def]  = rrd::def($source,           $this->DS[$i]["RRDFILE"],   $this->DS[$i]["DS"]);
      +   $def[$next_def] .= rrd::def($source."_active",           $this->DS[$i+1]["RRDFILE"],   $this->DS[$i+1]["DS"]);
      +   $def[$next_def] .= rrd::gradient($source, "#ffffff", "#cceeee");
      +   $def[$next_def] .= rrd::line1($source."_active", "#7777ff", "Active thread count");
      +   $def[$next_def] .= rrd::gprint($source."_active", "LAST",    "last %3.lf ");
      +   $def[$next_def] .= rrd::gprint($source."_active", "MAX",     "max %3.lf ");
      +   $def[$next_def] .= rrd::gprint($source."_active", "AVERAGE", "average %3.2lf\\n");
      +   $i++;
      + } elseif(preg_match("/^app-(.*)/", $label, $tmp)) {
      +   $source = $tmp[1];
      +   $label = "Application $source / $servicedesc ($hostname)";
      +   $ds_name[$next_def] = $label;
      +   $opt[$next_def] = "--vertical-label \"HTTP Sessions\" -l 0 --title \"$label\" ";
      +   $def[$next_def]  = rrd::def($source, $this->DS[$i]["RRDFILE"],   $this->DS[$i]["DS"]);
      +   $def[$next_def] .= rrd::gradient($source, "#ffefcf", "#ff9d00", "HTTP sessions");
      +   $def[$next_def] .= rrd::line1($source, "#ff7f00");
      +   $def[$next_def] .= rrd::gprint($source, "LAST",    "last %4.lf ");
      +   $def[$next_def] .= rrd::gprint($source, "MAX",     "max %4.lf ");
      +   $def[$next_def] .= rrd::gprint($source, "AVERAGE", "average %4.2lf\\n");
      + } elseif(preg_match("/^jdbc-(.*)-capacity$/", $label, $jdbc)) {
      +   $jdbc_name = $jdbc[1];
      +   $label = "Datasource $jdbc_name";
      +   $ds_name[$next_def] = $label;
      +   $opt[$next_def] = "--vertical-label \"JDBC connection\" -l 0 --title \"".$ds_name[$next_def]."\" ";
      +   $def[$next_def]  = rrd::def($jdbc_name."_capacity", $this->DS[$i]["RRDFILE"],   $this->DS[$i]["DS"]);
      +   $def[$next_def] .= rrd::def($jdbc_name."_active",   $this->DS[$i+1]["RRDFILE"], $this->DS[$i+1]["DS"]);
      +   $def[$next_def] .= rrd::def($jdbc_name."_waiting",  $this->DS[$i+2]["RRDFILE"], $this->DS[$i+2]["DS"]);
      +   $def[$next_def] .= rrd::cdef("neg_".$jdbc_name."_waiting", "-1,".$jdbc_name."_waiting,*");
      +   $def[$next_def] .= rrd::gradient($jdbc_name."_capacity", "#ffffff", "#cceeee");
      +   $def[$next_def] .= rrd::line1($jdbc_name."_capacity", "#ddcccc");
      +   $def[$next_def] .= rrd::gradient($jdbc_name."_active", "#55eded", "#ccffff", 'Actives   ');
      +   $def[$next_def] .= rrd::gprint($jdbc_name."_active", "LAST",    "last %.0lf ");
      +   $def[$next_def] .= rrd::gprint($jdbc_name."_active", "MAX",     "max %.0lf ");
      +   $def[$next_def] .= rrd::gprint($jdbc_name."_active", "AVERAGE", "avg %.2lf\\n");
      +   $def[$next_def] .= rrd::line1($jdbc_name."_active", "#000000");
      +   $def[$next_def] .= rrd::gradient("neg_".$jdbc_name."_waiting", "#eecccc", "#ff9dcc", 'Waiting');
      +   $def[$next_def] .= rrd::gprint($jdbc_name."_waiting", "LAST",    "last %.0lf ");
      +   $def[$next_def] .= rrd::gprint($jdbc_name."_waiting", "MAX",     "max %.0lf ");
      +   $def[$next_def] .= rrd::gprint($jdbc_name."_waiting", "AVERAGE", "avg %.2lf\\n");
      +   $def[$next_def] .= rrd::line1("neg_".$jdbc_name."_waiting", "#000000");
      +   $i += 2;
      + } elseif(preg_match("/^Throughput$/", $label, $jdbc)) {
      +   # CPU definition
      +   $ds_name[$next_def] = $label;
      +   $opt[$next_def] = "--vertical-label \"\" -l 0 --title \"".$ds_name[$next_def]."\" ";
      +   $def[$next_def]  = rrd::def("Throughput",      $this->DS[$i]["RRDFILE"], $this->DS[$i]["DS"]);
      +   $def[$next_def] .= rrd::gradient("Throughput", "FFAD00", "FF1D00");
      +   $def[$next_def] .= rrd::line1("Throughput", "#FF0000", "Throughput");
      +   $def[$next_def] .= rrd::gprint("Throughput", "LAST",    "last %2.lf");
      +   $def[$next_def] .= rrd::gprint("Throughput", "MAX",     "max %2.lf");
      +   $def[$next_def] .= rrd::gprint("Throughput", "AVERAGE", "average %2.2lf\\n");
      + } else {
      +   $ds_name[$next_def] = $label;
      +   $opt[$next_def] = "--vertical-label \"\" -l 0 --title \"".$ds_name[$next_def]."\" ";
      +   $def[$next_def]  = rrd::def($label, $this->DS[$i]["RRDFILE"], $this->DS[$i]["DS"]);
      +   $def[$next_def] .= rrd::line1($label, "#000000");
      + }
      + $next_def++;
      +}
      +?>
      +
      +
      diff --git a/share/pnp/documents/templates/gradient1.html b/share/pnp/documents/templates/gradient1.html new file mode 100644 index 0000000..412c922 --- /dev/null +++ b/share/pnp/documents/templates/gradient1.html @@ -0,0 +1,74 @@ +gradient1.php +

      gradient1.php

      +
      
      +<?php
      +#
      +# Copyright (c) 2006-2010 Joerg Linge (http://www.pnp4nagios.org)
      +# Plugin: check_icmp [Multigraph]
      +#
      +# RTA
      +#
      +$ds_name[1] = "Round Trip Times";
      +$opt[1]  = "--lower=0 --vertical-label \"RTA\" --title \"Ping times\" ";
      +$def[1]  =  rrd::def("var1", $RRDFILE[1], $DS[1], "AVERAGE") ;
      +$def[1] .=  rrd::gradient('var1','f0f0f0','0000a0','Round Trip Times',20);
      +$def[1] .=  rrd::gprint("var1", array("LAST", "MAX", "AVERAGE"), "%6.2lf $UNIT[1]") ;
      +
      +if($WARN[1] != ""){
      +    if($UNIT[1] == "%%"){ $UNIT[1] = "%"; };
      +    $def[1] .= rrd::hrule($WARN[1], "#FF8c00", "Warning  ".$WARN[1].$UNIT[1]."\\n");
      +}
      +if($CRIT[1] != ""){
      +    if($UNIT[1] == "%%"){ $UNIT[1] = "%"; };
      +    $def[1] .= rrd::hrule($CRIT[1], "#FF0000", "Critical  ".$CRIT[1].$UNIT[1]."\\n");
      +}
      +
      +?>
      +
      +
      +
      +<?php
      +#
      +#
      +$_WARNRULE = '#FFFF00';
      +$_CRITRULE = '#FF0000';
      +
      +$lower = $MAX[2] * -1;
      +if (strlen ($LABEL[1]) >= strlen ($LABEL[2])){
      +    $lenlabel = strlen ($LABEL[1]) + 2;
      +} else {
      +    $lenlabel = strlen ($LABEL[2]) + 2;
      +}
      +$label1 = sprintf("%' -".$lenlabel."s", $LABEL[1]);
      +$label2 = sprintf("%' -".$lenlabel."s", $LABEL[2]);
      +
      +    $ds_name[1] = "$LABEL[1] / $LABEL[2] " ;
      +    $opt[1] = "--vertical-label $UNIT[1] --title \"Traffic For $hostname / $servicedesc\" ";
      +    $opt[1] .= '--color=BACK#000000 ';
      +    $opt[1] .= '--color=FONT#F7F7F7 ';
      +    $opt[1] .= '--color=SHADEA#ffffff ';
      +    $opt[1] .= '--color=SHADEB#ffffff ';
      +    $opt[1] .= '--color=CANVAS#000000 ';
      +    $opt[1] .= '--color=GRID#00991A ';
      +    $opt[1] .= '--color=MGRID#00991A ';
      +    $opt[1] .= '--color=ARROW#00FF00 ';
      +    $opt[1] .= '--slope-mode ';
      +    $def[1] =  "DEF:inb=$RRDFILE[1]:$DS[1]:MAX " ;
      +    $def[1] .= "DEF:outb=$RRDFILE[2]:$DS[2]:MAX " ;
      +    $def[1] .= "CDEF:outbi=outb,-1,* " ;
      +    $def[1] .= rrd::gradient('inb','f0f0f0','0000a0',$label1,20);
      +    $def[1] .= "GPRINT:inb:LAST:\"%3.3lf $UNIT[1] LAST \" ";
      +    $def[1] .= "GPRINT:inb:MAX:\"%3.3lf $UNIT[1] MAX \" ";
      +    $def[1] .= "GPRINT:inb" . ':AVERAGE:"%3.3lf ' . $UNIT[1] . ' AVERAGE \j" ';
      +    $def[1] .= rrd::gradient('outbi','ffff42','ee7318',$label2,20);
      +    $def[1] .= "GPRINT:outb:LAST:\"%3.3lf $UNIT[2] LAST \" ";
      +    $def[1] .= "GPRINT:outb:MAX:\"%3.3lf $UNIT[2] MAX \" ";
      +    $def[1] .= "GPRINT:outb" . ':AVERAGE:"%3.3lf ' . $UNIT[2] . ' AVERAGE \j" ';
      +    $def[1] .= "COMMENT:\"  \\l\" " ;
      +    $def[1] .= "LINE1:0#ffffff " ;
      +    $def[1] .= "HRULE:" . $WARN[1] . $_WARNRULE . ':"Inbound Warning on  ' . $WARN[1] . ' ' . $UNIT[1] . '" ' ;
      +    $def[1] .= "HRULE:" . $WARN[2] * -1 . $_WARNRULE . ':"Outbound Warning on  ' . $WARN[2] . ' ' . $UNIT[2] . '\j" ';
      +    $def[1] .= "HRULE:" . $CRIT[1] . $_CRITRULE . ':"Inbound Critical on ' . $CRIT[1] . ' ' . $UNIT[1] . '" ';
      +    $def[1] .= "HRULE:" . $CRIT[2] * -1 . $_CRITRULE . ':"Outbound Critical on ' . $CRIT[2] . ' ' . $UNIT[2] . '\j" ';
      +?>
      +
      diff --git a/share/pnp/documents/templates/integer.html b/share/pnp/documents/templates/integer.html new file mode 100644 index 0000000..9b3e511 --- /dev/null +++ b/share/pnp/documents/templates/integer.html @@ -0,0 +1,31 @@ +integer.php +

      integer.php

      +
      
      +<?php
      +#
      +# Copyright (c) 2006-2009 Joerg Linge (http://www.pnp4nagios.org)
      +# Template for integer values
      +#
      +$def[1] = "";
      +$opt[1] = "";
      +$colors = array('#000000', '#0f0', '#ff0', '#f00', '#f0f', '#00f', '#0ff');
      +foreach ( $DS as $KEY => $VAL ){
      +        $opt[1] .= "--alt-y-grid -l 0 --vertical-label \"$LABEL[$KEY]\"  --title \"$LABEL[$KEY]\" ";
      +        $def[1] .= "DEF:var_float$KEY=$RRDFILE[$KEY]:$DS[$KEY]:MAX " ;
      +        $def[1] .= "CDEF:var$KEY=var_float$KEY,FLOOR " ;
      +        $def[1] .= "LINE1:var$KEY$colors[$KEY]:\"$LABEL[$KEY]\" " ;
      +
      +        if ($WARN[$KEY] != "") {
      +            $def[1] .= "HRULE:$WARN[$KEY]#FFFF00 ";
      +        }
      +        if ($CRIT[$KEY] != "") {
      +            $def[1] .= "HRULE:$CRIT[$KEY]#FF0000 ";
      +        }
      +
      +        $def[1] .= "GPRINT:var$KEY:LAST:\"%.0lf $UNIT[$KEY] LAST \" ";
      +        $def[1] .= "GPRINT:var$KEY:MAX:\"%.0lf $UNIT[$KEY] MAX \" ";
      +        $def[1] .= "GPRINT:var$KEY:AVERAGE:\"%.0lf $UNIT[$KEY] AVERAGE \\n\" ";
      +}
      +?>
      +
      +
      diff --git a/share/pnp/documents/templates/start.html b/share/pnp/documents/templates/start.html new file mode 100644 index 0000000..2d0982e --- /dev/null +++ b/share/pnp/documents/templates/start.html @@ -0,0 +1,25 @@ + +PNP Template Repository + +

      +====== PNP Template Repository ====== +

      + +The place to share your PNP Templates. +
      +
    2.6. Performance-Daten
    +
    PNP VersionTemplate NameComment +
    0.6.xinteger Generic Template used for integer values +
    0.6.xcheck_apachestatus Used with check_apachestatus.pl +
    0.6.xcheck_mk-df Used with check_mk +
    0.6.xcheck_mk-cpu.loads Used with check_mk +
    0.6.xcheck_http Used with check_http +
    0.6.xcheck_cpu Used with check_cpu +
    0.6.xcheck_oracle_health_tablespace-usage Used with check_oracle_health +
    0.6.5alerter Example for rrd::alerter function +
    0.6.5ticker Example for rrd::ticker function +
    0.6.5gradient Example for rrd::gradient function +
    0.6.x Used with check_wlsagent +
    + + diff --git a/share/pnp/documents/templates/ticker.html b/share/pnp/documents/templates/ticker.html new file mode 100644 index 0000000..6b035cd --- /dev/null +++ b/share/pnp/documents/templates/ticker.html @@ -0,0 +1,50 @@ +ticker.php +

    ticker.php

    +
    
    +<?php
    +#
    +# Copyright (c) 2006-2010 Joerg Linge (http://www.pnp4nagios.org)
    +# Plugin: check_icmp [Multigraph]
    +#
    +# RTA
    +#
    +$ds_name[1] = "Round Trip Times";
    +$opt[1]  = "--lower=0 --vertical-label \"RTA\" --title \"Ping times\" ";
    +$def[1]  =  rrd::def("var1", $RRDFILE[1], $DS[1], "AVERAGE") ;
    +$def[1] .=  rrd::ticker("var1", $WARN[1], $CRIT[1],-0.05,"ff","#00ff00","#ff8c00","#ff0000") ;
    +$def[1] .=  rrd::line1("var1", "#0000ff", "Round Trip Times") ;
    +$def[1] .=  rrd::gprint("var1", array("LAST", "MAX", "AVERAGE"), "%6.2lf $UNIT[1]") ;
    +
    +if($WARN[1] != ""){
    +    if($UNIT[1] == "%%"){ $UNIT[1] = "%"; };
    +    $def[1] .= rrd::hrule($WARN[1], "#FF8c00", "Warning  ".$WARN[1].$UNIT[1]."\\n");
    +}
    +if($CRIT[1] != ""){
    +    if($UNIT[1] == "%%"){ $UNIT[1] = "%"; };
    +    $def[1] .= rrd::hrule($CRIT[1], "#FF0000", "Critical  ".$CRIT[1].$UNIT[1]."\\n");
    +}
    +#
    +# Packets Lost
    +$ds_name[2] = "Packets Lost";
    +$opt[2] = "--vertical-label \"Packets lost\" -l0 -u105 --title \"Packets lost\" ";
    +
    +$def[2]  =  rrd::def("var1", $RRDFILE[2], $DS[2], "AVERAGE");
    +$def[2] .=  rrd::gradient("var1", "ff5c00", "ffdc00", "Packets Lost", 20) ;
    +$def[2] .=  rrd::ticker("var1", $WARN[2], $CRIT[2],-0.05,"ff","#00ff00","#ff8c00","#ff0000") ;
    +$def[2] .=  rrd::gprint("var1", array("LAST", "MAX", "AVERAGE"), "%3.0lf $UNIT[2]") ;
    +$def[2] .=  rrd::line1("var1", "#000000") ;
    +
    +$def[2] .= rrd::hrule("100", "#000000", ":dashes") ;
    +
    +if($WARN[2] != ""){
    +    if($UNIT[2] == "%%"){ $UNIT[2] = "%"; };
    +    $def[2] .= rrd::hrule($WARN[2], "#FF8c00", "Warning  ".$WARN[2].$UNIT[2]."\\n");
    +}
    +if($CRIT[2] != ""){
    +    if($UNIT[2] == "%%"){ $UNIT[2] = "%"; };
    +    $def[2] .= rrd::hrule($CRIT[2], "#FF0000", "Critical  ".$CRIT[2].$UNIT[2]."\\n");
    +}
    +
    +?>
    +
    +
    diff --git a/share/pnp/index.php.in b/share/pnp/index.php.in index b4cc9ce..df6d1fd 100644 --- a/share/pnp/index.php.in +++ b/share/pnp/index.php.in @@ -1,6 +1,8 @@ - + @@ -12,18 +11,18 @@ body { width: 42em; margin: 0 auto; font-family: sans-serif; font-size: 90%; } #tests table { border-collapse: collapse; width: 100%; } - #tests table th, - #tests table td { padding: 0.2em 0.4em; text-align: left; vertical-align: top; } - #tests table th { width: 12em; font-weight: normal; font-size: 1.2em; } - #tests table tr:nth-child(odd) { background: #eee; } - #tests table td.pass { color: #191; } - #tests table td.fail { color: #911; } - #tests table td.warn { background: #ff3; } - #tests #results { color: #fff; } - #tests #results p { padding: 0.8em 0.4em; } - #tests #results p.pass { background: #191; } - #tests #results p.fail { background: #911; } - #tests #results p.warn { background: #ff3; } + #tests table th, + #tests table td { padding: 0.2em 0.4em; text-align: left; vertical-align: top; } + #tests table th { width: 12em; font-weight: normal; font-size: 1.2em; } + #tests table tr:nth-child(odd) { background: #eee; } + #tests table td.pass { color: #191; } + #tests table td.fail { color: #911; } + #tests table td.warn { background: #ff3; } + #tests #results { color: #fff; } + #tests #results p { padding: 0.8em 0.4em; } + #tests #results p.pass { background: #191; } + #tests #results p.fail { background: #911; } + #tests #results p.warn { background: #ff3; } @@ -32,13 +31,16 @@ body { width: 42em; margin: 0 auto; font-family: sans-serif; font-size: 90%; }

    PNP4Nagios Environment Tests

    -

    The following options are determined by "configure". If any of the tests have failed, consult the documentation for more information on how to correct the problem.

    +

    The following options are determined by "configure". + If any of the tests have failed, consult the + documentation + for more information on how to correct the problem.

    - + @@ -50,81 +52,106 @@ body { width: 42em; margin: 0 auto; font-family: sans-serif; font-size: 90%; } - + - + - + - - + + + + + + + + + + - + - + - + - - + + + + + + + + + + - + - + - + - + - + - - + + + - - - - - + + + - + - - - + + + - + - - - - + + + + @@ -133,75 +160,92 @@ body { width: 42em; margin: 0 auto; font-family: sans-serif; font-size: 90%; }

    Kohana Environment Tests

    -

    The following tests have been run to determine if Kohana will work in your environment. If any of the tests have failed, consult the documentation for more information on how to correct the problem.

    +

    The following tests have been run to determine if Kohana will + work in your environment. If any of the tests have failed, + consult the + documentation + for more information on how to correct the problem.

    PNP4Nagios Version@PKG_NAME@-@PKG_VERSION@@PACKAGE_NAME@-@PACKAGE_VERSION@
    Prefix
    RRD Storage @PERFDATA_DIR@ is readable. @PERFDATA_DIR@ is not readable.
    RRDtool Binary @RRDTOOL@ is executable by PHP@RRDTOOL@ is not executable by PHP@RRDTOOL@ is not executable by PHP
    PHP mbstring extensionPassPHP mbstring extension not available/enabled
    PHP GD extension Pass PHP GD extension not available
    PHP function proc_open() PassPHP function proc_open not available/enabledPHP function proc_open not available/enabled
    PHP XML extensionPassPHP SimpleXML extension not available
    PHP zlib extension Pass PHP zlib extension not available
    PHP session extension Pass PHP session extension not available
    PHP JSON extension PassPHP JSON extension not availablePHP JSON extension not available
    PHP magic_quotes_gpc OffPHP magic_quotes_gpc is deprecated
    PHP magic_quotes_gpc is REMOVED
    PHP socket extension PassPHP socket extension not availablePHP socket extension not available
    Apache Rewrite Module PassApache mod_rewrite is not enabled
    Apache mod_rewrite is not enabled
    Apache Rewrite Module Not running within Apache mod_php
    -=')): ?> +=')) : ?> - + - + - + - + - + - + - - + + - + - - + + - +=')) : define("MB_OVERLOAD_STRING", 0) ?> + + - - - + + + - + - + - +
    PHP Version Kohana requires PHP 5.1 or newer, this version is .
    System Directory The configured system directory
    ('')
    does not exist or does not contain required files.
    Application Directory The configured application directory
    ('')
    does not exist or does not contain required files.
    Reflection Enabled PassPHP reflection is either not loaded or not compiled in.PHP reflection is either not loaded or not compiled in.
    Iconv Extension Loaded PassThe iconv extension is not loaded.The iconv extension is not loaded.
    Mbstring Not OverloadedThe mbstring extension is overloading PHP's native string functions.The mbstring extension is overloading PHPs native string functions. Pass
    URI Determination Pass Neither $_SERVER['REQUEST_URI'] or $_SERVER['PHP_SELF'] is available.
    - 0): ?> -

    @PKG_NAME@ may not work correctly with your environment. Remove or rename the file on your own risk.

    - -

    Your environment passed all requirements. Remove or rename the file now.

    + 0) : ?> +

    @PACKAGE_NAME@ may not work correctly with your environment. Remove or rename the file on your own risk.

    + +

    Your environment passed all requirements. To show the graphs: +
    + mv @datarootdir@/install.ignore.not + @datarootdir@/install.ignore. +

    diff --git a/share/pnp/media/images/pnp.png b/share/pnp/media/images/pnp.png index 3c8966e4410d75bbeb38df8bca229a4492853f0d..ee88ded1b51ac9edfeaadd8f1812e55a18260a12 100644 GIT binary patch delta 241 zcmV9elu03sMVJp(8D5EWm zeRLs7lzhHKN*H6X5)=Tu_fNNR6P$B;EG-#u-nJX32AneoDKr3lo^IoAUcuXbd}#!) zaT!7i9d1#3Dh-zQ{z%SYOTdz%=1N(D6xujtoWgy_6y6oMQvx^uo(qe?QiJ|&>C`??XVz>00000NkvXXu0mjfKsaiw delta 237 zcmV=LY;dUhZz7~Pq)#U?gZ=5VeD@B zB{w!=%QS&oq3DvQLe3wAGIf4H2nP5{ifYcJ9T # pnp version >= 0.6.5 # +include 'arrayfix.php'; # # from apache's scoreboard.h -# #define SERVER_DEAD 0 -# #define SERVER_STARTING 1 /* Server Starting up */ -# #define SERVER_READY 2 /* Waiting for connection (or accept() lock) */ -# #define SERVER_BUSY_READ 3 /* Reading a client request */ -# #define SERVER_BUSY_WRITE 4 /* Processing a client request */ -# #define SERVER_BUSY_KEEPALIVE 5 /* Waiting for more requests via keepalive */ -# #define SERVER_BUSY_LOG 6 /* Logging the request */ -# #define SERVER_BUSY_DNS 7 /* Looking up a hostname */ -# #define SERVER_CLOSING 8 /* Closing the connection */ -# #define SERVER_GRACEFUL 9 /* server is gracefully finishing request */ -# #define SERVER_IDLE_KILL 10 /* Server is cleaning up idle children. */ -# #define SERVER_NUM_STATUS 11 /* number of status settings */ +# #define SERVER_DEAD 0 +# #define SERVER_STARTING 1 /* Server Starting up */ +# #define SERVER_READY 2 /* Waiting for connection (or accept() lock) */ +# #define SERVER_BUSY_READ 3 /* Reading a client request */ +# #define SERVER_BUSY_WRITE 4 /* Processing a client request */ +# #define SERVER_BUSY_KEEPALIVE 5 /* Waiting for more requests via keepalive */ +# #define SERVER_BUSY_LOG 6 /* Logging the request */ +# #define SERVER_BUSY_DNS 7 /* Looking up a hostname */ +# #define SERVER_CLOSING 8 /* Closing the connection */ +# #define SERVER_GRACEFUL 9 /* server is gracefully finishing request */ +# #define SERVER_IDLE_KILL 10 /* Server is cleaning up idle children. */ +# #define SERVER_NUM_STATUS 11 /* number of status settings */ # perfdata example: -# Performance Data: 'Waiting for Connection'=90 'Starting Up'=0 'Reading Request'=10 'Sending Reply'=196 'Keepalive (read)'=360 'DNS Lookup'=0 'Closing Connection'=77 'Logging'=0 'Gracefully finishing'=0 'Idle cleanup'=0 'Open slot'=547 'Requests/sec'=119.0 'kB per sec'=8294.4KB 'kB per Request'=69.9KB +# Performance Data: 'Waiting for Connection'=90 'Starting Up'=0 'Reading Request'=10 +# 'Sending Reply'=196 'Keepalive (read)'=360 'DNS Lookup'=0 'Closing Connection'=77 +# 'Logging'=0 'Gracefully finishing'=0 'Idle cleanup'=0 'Open slot'=547 'Requests/sec'=119.0 +# 'kB per sec'=8294.4KB 'kB per Request'=69.9KB # # first graph - workers that do smth, not just idling.. -$ds_name[1]="Working slots"; +$ds_name[1] = "Working slots"; $opt[1] = " --vertical-label \"Workers\" --title \"Apache Workers: working on $hostname / $servicedesc\" "; $opt[1] .= " --slope-mode "; -$def[1] = rrd::def("var2",$RRDFILE[2],$DS[2],"AVERAGE"); #starting -$def[1] .= rrd::cdef("negstarting","var2,-1,*"); #starting -$def[1] .= rrd::def("var3",$RRDFILE[3],$DS[3],"AVERAGE"); #reading -$def[1] .= rrd::cdef("negreading","var3,-1,*"); #reading -$def[1] .= rrd::def("var4",$RRDFILE[4],$DS[4],"AVERAGE"); #reply -$def[1] .= rrd::def("var6",$RRDFILE[6],$DS[6],"AVERAGE"); #DNS LOOKUP -$def[1] .= rrd::cdef("negdns","var6,-1,*"); #DNS LOOKUP -$def[1] .= rrd::def("var7",$RRDFILE[7],$DS[7],"AVERAGE"); #closing -$def[1] .= rrd::cdef("negclosing","var7,-1,*"); #closing -$def[1] .= rrd::def("var8",$RRDFILE[8],$DS[8],"AVERAGE"); #logging -$def[1] .= rrd::cdef("neglogging","var8,-1,*"); #logging -$def[1] .= rrd::area("negclosing","#b7ff9e","closing",true ); #closing -$def[1] .= rrd::line1("negclosing","#2eae00"); -$def[1] .= rrd::gprint("var7",array("LAST","MAX","AVERAGE"),"%7.0lf") ; -$def[1] .= rrd::area("negstarting","#993300","starting"); #startung -$def[1] .= rrd::gprint("var2",array("LAST","MAX","AVERAGE"),"%7.0lf"); -$def[1] .= rrd::area("negreading","#001919","reading",true); #reading -$def[1] .= rrd::gprint("var3",array("LAST","MAX","AVERAGE"),"%7.0lf") ; -$def[1] .= rrd::area("negdns","#009900","DNS lookup",true); #dns lookup -$def[1] .= rrd::gprint("var6",array("LAST","MAX","AVERAGE"),"%7.0lf") ; -$def[1] .= rrd::area("neglogging","#ff0000","logging",true); #logging -$def[1] .= rrd::gprint("var8",array("LAST","MAX","AVERAGE"),"%7.0lf") ; -$def[1] .= rrd::area("var4","#6fb7ff","replying"); #replying -$def[1] .= rrd::line1("var4","#0019ff",FALSE,FALSE); -$def[1] .= rrd::gprint("var4",array("LAST","MAX","AVERAGE"),"%7.0lf") ; +$def[1] = rrd::def("var2", $RRDFILE[2], $DS[2], "AVERAGE"); #starting +$def[1] .= rrd::cdef("negstarting", "var2,-1,*"); #starting +$def[1] .= rrd::def("var3", $RRDFILE[3], $DS[3], "AVERAGE"); #reading +$def[1] .= rrd::cdef("negreading", "var3,-1,*"); #reading +$def[1] .= rrd::def("var4", $RRDFILE[4], $DS[4], "AVERAGE"); #reply +$def[1] .= rrd::def("var6", $RRDFILE[6], $DS[6], "AVERAGE"); #DNS LOOKUP +$def[1] .= rrd::cdef("negdns", "var6,-1,*"); #DNS LOOKUP +$def[1] .= rrd::def("var7", $RRDFILE[7], $DS[7], "AVERAGE"); #closing +$def[1] .= rrd::cdef("negclosing", "var7,-1,*"); #closing +$def[1] .= rrd::def("var8", $RRDFILE[8], $DS[8], "AVERAGE"); #logging +$def[1] .= rrd::cdef("neglogging", "var8,-1,*"); #logging +$def[1] .= rrd::area("negclosing", "#b7ff9e", "closing", true); #closing +$def[1] .= rrd::line1("negclosing", "#2eae00"); +$def[1] .= rrd::gprint("var7", array("LAST","MAX","AVERAGE"), "%7.0lf") ; +$def[1] .= rrd::area("negstarting", "#993300", "starting"); #startung +$def[1] .= rrd::gprint("var2", array("LAST","MAX","AVERAGE"), "%7.0lf"); +$def[1] .= rrd::area("negreading", "#001919", "reading", true); #reading +$def[1] .= rrd::gprint("var3", array("LAST","MAX","AVERAGE"), "%7.0lf") ; +$def[1] .= rrd::area("negdns", "#009900", "DNS lookup", true); #dns lookup +$def[1] .= rrd::gprint("var6", array("LAST","MAX","AVERAGE"), "%7.0lf") ; +$def[1] .= rrd::area("neglogging", "#ff0000", "logging", true); #logging +$def[1] .= rrd::gprint("var8", array("LAST","MAX","AVERAGE"), "%7.0lf") ; +$def[1] .= rrd::area("var4", "#6fb7ff", "replying"); #replying +$def[1] .= rrd::line1("var4", "#0019ff", false, false); +$def[1] .= rrd::gprint("var4", array("LAST","MAX","AVERAGE"), "%7.0lf") ; # second graph - idling workers #some idle actions like graceful shutdown, open slots & such -$ds_name[2]="Idling slots"; +$ds_name[2] = "Idling slots"; $opt[2] = " --vertical-label \"Workers\" --title \"Apache Workers: idling on $hostname / $servicedesc\" "; $opt[2] .= " --slope-mode "; -$def[2] = rrd::def("var2",$RRDFILE[5],$DS[5],"AVERAGE"); #keepalive (read) -$def[2] .= rrd::def("var3",$RRDFILE[1],$DS[1],"AVERAGE"); #waiting -$def[2] .= rrd::def("var4",$RRDFILE[10],$DS[10],"AVERAGE"); #idle cleanup -$def[2] .= rrd::def("var5",$RRDFILE[9],$DS[9],"AVERAGE"); #gracefully finishing -$def[2] .= rrd::area("var3","#ffe4c4","waiting for conn"); -$def[2] .= rrd::line1("var3","#eb891d"); -$def[2] .= rrd::gprint("var3",array("LAST","MAX","AVERAGE"),"%7.0lf") ;#TODO - add border lines like for finishing -$def[2] .= rrd::area("var2","#503020","keepalive",true); #TODO - add border lines like for finishing -$def[2] .= rrd::gprint("var2",array("LAST","MAX","AVERAGE"),"%7.0lf") ; -$def[2] .= rrd::area("var4","#66cdaa","idle cleanup",true); -$def[2] .= rrd::gprint("var4",array("LAST","MAX","AVERAGE"),"%7.0lf") ; -$def[2] .= rrd::area("var5","#6fb7ff","gracefully finishing",true); -$def[2] .= rrd::cdef("grline","var2,var3,var4,var5,+,+,+"); #line shouldn't be stacked over -$def[2] .= rrd::line1("grline","#0019ff",FALSE,FALSE); -$def[2] .= rrd::gprint("var5",array("LAST","MAX","AVERAGE"),"%7.0lf") ; +$def[2] = rrd::def("var2", $RRDFILE[5], $DS[5], "AVERAGE"); #keepalive (read) +$def[2] .= rrd::def("var3", $RRDFILE[1], $DS[1], "AVERAGE"); #waiting +$def[2] .= rrd::def("var4", $RRDFILE[10], $DS[10], "AVERAGE"); #idle cleanup +$def[2] .= rrd::def("var5", $RRDFILE[9], $DS[9], "AVERAGE"); #gracefully finishing +$def[2] .= rrd::area("var3", "#ffe4c4", "waiting for conn"); +$def[2] .= rrd::line1("var3", "#eb891d"); +$def[2] .= rrd::gprint("var3", array("LAST","MAX","AVERAGE"), "%7.0lf") ;#TODO - add border lines like for finishing +$def[2] .= rrd::area("var2", "#503020", "keepalive", true); #TODO - add border lines like for finishing +$def[2] .= rrd::gprint("var2", array("LAST","MAX","AVERAGE"), "%7.0lf") ; +$def[2] .= rrd::area("var4", "#66cdaa", "idle cleanup", true); +$def[2] .= rrd::gprint("var4", array("LAST","MAX","AVERAGE"), "%7.0lf") ; +$def[2] .= rrd::area("var5", "#6fb7ff", "gracefully finishing", true); +$def[2] .= rrd::cdef("grline", "var2,var3,var4,var5,+,+,+"); #line shouldn't be stacked over +$def[2] .= rrd::line1("grline", "#0019ff", false, false); +$def[2] .= rrd::gprint("var5", array("LAST","MAX","AVERAGE"), "%7.0lf") ; #third graph - open slots count -$ds_name[3]="Open slots"; +$ds_name[3] = "Open slots"; $opt[3] = " --vertical-label \"Workers\" --title \"Apache open slots on $hostname / $servicedesc\" "; $opt[3] .= " --slope-mode "; -$def[3] = rrd::def("var1",$RRDFILE[11],$DS[11],"AVERAGE"); -$def[3] .= rrd::area("var1","#e0e0e0","open slots" ); -$def[3] .= rrd::line1("var1","#858585"); -$def[3] .= rrd::gprint("var1",array("LAST","MAX","AVERAGE"),"%7.0lf") ; +$def[3] = rrd::def("var1", $RRDFILE[11], $DS[11], "AVERAGE"); +$def[3] .= rrd::area("var1", "#e0e0e0", "open slots"); +$def[3] .= rrd::line1("var1", "#858585"); +$def[3] .= rrd::gprint("var1", array("LAST","MAX","AVERAGE"), "%7.0lf") ; #fourth graph - server's traffic total and per request -$ds_name[4]="Apache Traffic"; +$ds_name[4] = "Apache Traffic"; $opt[4] = " --vertical-label \"Traffic\" -b 1024 --title \"Apache Traffic for $hostname / $servicedesc\" "; $opt[4] .= " --slope-mode "; -$def[4] = rrd::def("var1",$RRDFILE[13],$DS[13],"AVERAGE"); -$def[4] .= rrd::cdef("trbytes","var1,1024,*"); -$def[4] .= rrd::def("var2",$RRDFILE[14],$DS[14],"AVERAGE"); -$def[4] .= rrd::cdef("negperreq","var2,-1,*"); +$def[4] = rrd::def("var1", $RRDFILE[13], $DS[13], "AVERAGE"); +$def[4] .= rrd::cdef("trbytes", "var1,1024,*"); +$def[4] .= rrd::def("var2", $RRDFILE[14], $DS[14], "AVERAGE"); +$def[4] .= rrd::cdef("negperreq", "var2,-1,*"); $def[4] .= "VDEF:totalbytes=trbytes,TOTAL "; -$def[4] .= rrd::area("trbytes","#b0c0fb","throughput"); -$def[4] .= rrd::line1("trbytes","#3c63ff"); -$def[4] .= rrd::gprint("trbytes",array("LAST","MAX","AVERAGE"),"%7.2lf %sB/sec") ; -$def[4] .= rrd::line2("negperreq","#00ff00","kB/request"); -$def[4] .= rrd::gprint("var2",array("LAST","MAX","AVERAGE"),"%7.2lf %s$UNIT[14]") ; +$def[4] .= rrd::area("trbytes", "#b0c0fb", "throughput"); +$def[4] .= rrd::line1("trbytes", "#3c63ff"); +$def[4] .= rrd::gprint("trbytes", array("LAST","MAX","AVERAGE"), "%7.2lf %sB/sec") ; +$def[4] .= rrd::line2("negperreq", "#00ff00", "kB/request"); +$def[4] .= rrd::gprint("var2", array("LAST","MAX","AVERAGE"), "%7.2lf %s$UNIT[14]") ; $def[4] .= "GPRINT:totalbytes:\"%3.0lf %sB total\\n\" "; #fifth graph - requests per sec ( rate is calculated by apache, time smoothed, very averaged, shouldn't be believed) -$ds_name[5]="Apache requests"; +$ds_name[5] = "Apache requests"; $opt[5] = " --vertical-label \"Request/sec\" --title \"Apache request/sec for $hostname / $servicedesc\" "; $opt[5] .= " --slope-mode "; -$def[5] = rrd::def("var1",$RRDFILE[12],$DS[12],"AVERAGE"); -$def[5] .= rrd::area("var1","#b7ff9e","Requests / sec"); -$def[5] .= rrd::line1("var1","#2eae00"); -$def[5] .= rrd::gprint("var1",array("LAST","MAX","AVERAGE"),"%7.2lf %s") ; - -?> +$def[5] = rrd::def("var1", $RRDFILE[12], $DS[12], "AVERAGE"); +$def[5] .= rrd::area("var1", "#b7ff9e", "Requests / sec"); +$def[5] .= rrd::line1("var1", "#2eae00"); +$def[5] .= rrd::gprint("var1", array("LAST","MAX","AVERAGE"), "%7.2lf %s") ; diff --git a/share/pnp/templates.dist/check_apachestatus_auto.php b/share/pnp/templates.dist/check_apachestatus_auto.php index d9a4c2f..5336c01 100644 --- a/share/pnp/templates.dist/check_apachestatus_auto.php +++ b/share/pnp/templates.dist/check_apachestatus_auto.php @@ -1,30 +1,33 @@ DS as $KEY=>$VAL) { - if(preg_match($regex, $VAL['NAME'])) { - $def[$i] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$i] .= rrd::area ("var".$KEY, $color ,rrd::cut($VAL['NAME'],12), 'STACK' ); - $def[$i] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); +foreach ($this->DS as $KEY => $VAL) { + if (preg_match($regex, $VAL['NAME'])) { + $def[$i] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$i] .= rrd::area("var" . $KEY, $color, rrd::cut($VAL['NAME'], 12), 'STACK'); + $def[$i] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); } } $regex = '/Busy/'; $color = '#ff0000'; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match($regex, $VAL['NAME'])) { - $def[$i] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$i] .= rrd::area ("var".$KEY, $color, rrd::cut($VAL['NAME'],12), 'STACK' ); - $def[$i] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); +foreach ($this->DS as $KEY => $VAL) { + if (preg_match($regex, $VAL['NAME'])) { + $def[$i] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$i] .= rrd::area("var" . $KEY, $color, rrd::cut($VAL['NAME'], 12), 'STACK'); + $def[$i] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); } } # @@ -36,24 +39,24 @@ $opt[$i] = " --title 'Slots'"; $ds_name[$i] = "Slots"; $regex = '/^Slots$/'; $color = '#ff0000'; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match($regex, $VAL['NAME'])) { - $def[$i] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$i] .= rrd::area ("var".$KEY, $color,rrd::cut($VAL['NAME'],12) ); - $def[$i] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); - } +foreach ($this->DS as $KEY => $VAL) { + if (preg_match($regex, $VAL['NAME'])) { + $def[$i] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$i] .= rrd::area("var" . $KEY, $color, rrd::cut($VAL['NAME'], 12)); + $def[$i] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); + } } $regex = '/^OpenSlots$/'; $color = '#00ff00'; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match($regex, $VAL['NAME'])) { - $def[$i] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$i] .= rrd::area ("var".$KEY, $color,rrd::cut($VAL['NAME'],12) ); - $def[$i] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); - } +foreach ($this->DS as $KEY => $VAL) { + if (preg_match($regex, $VAL['NAME'])) { + $def[$i] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$i] .= rrd::area("var" . $KEY, $color, rrd::cut($VAL['NAME'], 12)); + $def[$i] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%6.0lf"); + } } # -# Requests per Second +# Requests per Second # $i++; $def[$i] = ""; @@ -61,41 +64,40 @@ $opt[$i] = " --title Requests/s"; $ds_name[$i] = "Requests/s"; $regex = '/ReqPerSec/'; $color = '#000000'; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match($regex, $VAL['NAME'])) { - $def[$i] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$i] .= rrd::line1 ("var".$KEY, $color, rrd::cut($VAL['NAME'],16), 'STACK' ); - $def[$i] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%6.1lf/s"); - } +foreach ($this->DS as $KEY => $VAL) { + if (preg_match($regex, $VAL['NAME'])) { + $def[$i] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$i] .= rrd::line1("var" . $KEY, $color, rrd::cut($VAL['NAME'], 16), 'STACK'); + $def[$i] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%6.1lf/s"); + } } # -# Bytes per Second +# Bytes per Second # $i++; $def[$i] = ""; $opt[$i] = " --title 'Bytes per Second'"; $ds_name[$i] = "Bytes/s"; -$regex='/BytesPerSec/'; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match($regex, $VAL['NAME'])) { - $def[$i] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$i] .= rrd::line1 ("var".$KEY, rrd::color($KEY),rrd::cut($VAL['NAME'],16), 'STACK' ); - $def[$i] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%6.1lf %sb/s"); - } +$regex = '/BytesPerSec/'; +foreach ($this->DS as $KEY => $VAL) { + if (preg_match($regex, $VAL['NAME'])) { + $def[$i] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$i] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($VAL['NAME'], 16), 'STACK'); + $def[$i] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%6.1lf %sb/s"); + } } # -# Stats +# Stats # $i++; $def[$i] = ""; $opt[$i] = " --title 'Worker States'"; $ds_name[$i] = "Worker States"; -$regex='/Starting|DNS|Reading|Sending|Keepalive|Closing|Logging|Finishing/'; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match($regex, $VAL['NAME'])) { - $def[$i] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$i] .= rrd::line1 ("var".$KEY, rrd::color($KEY),rrd::cut($VAL['NAME'],16), 'STACK' ); - $def[$i] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%6.0lf".$VAL['UNIT']); - } +$regex = '/Starting|DNS|Reading|Sending|Keepalive|Closing|Logging|Finishing/'; +foreach ($this->DS as $KEY => $VAL) { + if (preg_match($regex, $VAL['NAME'])) { + $def[$i] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$i] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($VAL['NAME'], 16), 'STACK'); + $def[$i] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%6.0lf" . $VAL['UNIT']); + } } -?> diff --git a/share/pnp/templates.dist/check_dell_bladechassis.php b/share/pnp/templates.dist/check_dell_bladechassis.php index 42028f6..9f93139 100644 --- a/share/pnp/templates.dist/check_dell_bladechassis.php +++ b/share/pnp/templates.dist/check_dell_bladechassis.php @@ -1,17 +1,19 @@ diff --git a/share/pnp/templates.dist/check_disk.php b/share/pnp/templates.dist/check_disk.php index e7c26ce..afc9f91 100644 --- a/share/pnp/templates.dist/check_disk.php +++ b/share/pnp/templates.dist/check_disk.php @@ -1,64 +1,65 @@ DS as $KEY=>$VAL) { +foreach ($this->DS as $KEY => $VAL) { # set initial values - $fmt = '%7.3lf'; - $pct = ''; - $upper = ""; - $maximum = ""; - $divis = 1; - $return = '\n'; - $unit = "B"; - $label = $unit; - if ($VAL['UNIT'] != "") { - $unit = $VAL['UNIT']; - $label = $unit; - if ($VAL['UNIT'] == "%%") { - $label = '%'; - $fmt = '%5.1lf'; - $pct = '%'; - } - } - if ($VAL['MAX'] != "") { - # adjust value and unit, details in .../helpers/pnp.php - $max = pnp::adjust_unit( $VAL['MAX'].$unit,1024,$fmt ); - $upper = "-u $max[1] "; - $maximum = "of $max[1] $max[2]$pct used"; - $label = $max[2]; - $divis = $max[3]; - $return = ''; - } - $ds_name[$KEY] = str_replace("_","/",$VAL['NAME']); - # set graph labels - $opt[$KEY] = "--vertical-label $label -l 0 $upper --title \"Filesystem $ds_name[$KEY]\" "; - # Graph Definitions - $def[$KEY] = rrd::def( "var1", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE" ); - # "normalize" graph values - $def[$KEY] .= rrd::cdef( "v_n","var1,$divis,/"); - $def[$KEY] .= rrd::area( "v_n", "#c6c6c6", $ds_name[$KEY] ); - $def[$KEY] .= rrd::line1( "v_n", "#003300" ); - # show values in legend - $def[$KEY] .= rrd::gprint( "v_n", "LAST", "$fmt $label$pct $maximum "); - $def[$KEY] .= rrd::gprint( "v_n", "AVERAGE", "$fmt $label$pct avg used $return"); - # create max line and legend - if ($VAL['MAX'] != "") { - $def[$KEY] .= rrd::gprint( "v_n", "MAX", "$fmt $label$pct max used \\n" ); - $def[$KEY] .= rrd::hrule( $max[1], "#003300", "Size of FS $max[0] \\n"); - } - # create warning line and legend - if ($VAL['WARN'] != "") { - $warn = pnp::adjust_unit( $VAL['WARN'].$unit,1024,$fmt ); - $def[$KEY] .= rrd::hrule( $warn[1], "#ffff00", "Warning on $warn[0] \\n" ); - } - # create critical line and legend - if ($VAL['CRIT'] != "") { - $crit = pnp::adjust_unit( $VAL['CRIT'].$unit,1024,$fmt ); - $def[$KEY] .= rrd::hrule( $crit[1], "#ff0000", "Critical on $crit[0]\\n" ); - } + $fmt = '%7.3lf'; + $pct = ''; + $upper = ""; + $maximum = ""; + $divis = 1; + $return = '\n'; + $unit = "B"; + $label = $unit; + if ($VAL['UNIT'] != "") { + $unit = $VAL['UNIT']; + $label = $unit; + if ($VAL['UNIT'] == "%%") { + $label = '%'; + $fmt = '%5.1lf'; + $pct = '%'; + } + } + if ($VAL['MAX'] != "") { + # adjust value and unit, details in .../helpers/pnp.php + $max = pnp::adjust_unit($VAL['MAX'] . $unit, 1024, $fmt); + $upper = "-u $max[1] "; + $maximum = "of $max[1] $max[2]$pct used"; + $label = $max[2]; + $divis = $max[3]; + $return = ''; + } + $ds_name[$KEY] = str_replace("_", "/", $VAL['NAME']); + # set graph labels + $opt[$KEY] = "--vertical-label $label -l 0 $upper --title \"Filesystem $ds_name[$KEY]\" "; + # Graph Definitions + $def[$KEY] = rrd::def("var1", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + # "normalize" graph values + $def[$KEY] .= rrd::cdef("v_n", "var1,$divis,/"); + $def[$KEY] .= rrd::area("v_n", "#c6c6c6", $ds_name[$KEY]); + $def[$KEY] .= rrd::line1("v_n", "#003300"); + # show values in legend + $def[$KEY] .= rrd::gprint("v_n", "LAST", "$fmt $label$pct $maximum "); + $def[$KEY] .= rrd::gprint("v_n", "AVERAGE", "$fmt $label$pct avg used $return"); + # create max line and legend + if ($VAL['MAX'] != "") { + $def[$KEY] .= rrd::gprint("v_n", "MAX", "$fmt $label$pct max used \\n"); + $def[$KEY] .= rrd::hrule($max[1], "#003300", "Size of FS $max[0] \\n"); + } + # create warning line and legend + if ($VAL['WARN'] != "") { + $warn = pnp::adjust_unit($VAL['WARN'] . $unit, 1024, $fmt); + $def[$KEY] .= rrd::hrule($warn[1], "#ffff00", "Warning on $warn[0] \\n"); + } + # create critical line and legend + if ($VAL['CRIT'] != "") { + $crit = pnp::adjust_unit($VAL['CRIT'] . $unit, 1024, $fmt); + $def[$KEY] .= rrd::hrule($crit[1], "#ff0000", "Critical on $crit[0]\\n"); + } } -?> diff --git a/share/pnp/templates.dist/check_dns.php b/share/pnp/templates.dist/check_dns.php index dad209a..cb35d5c 100644 --- a/share/pnp/templates.dist/check_dns.php +++ b/share/pnp/templates.dist/check_dns.php @@ -1,8 +1,10 @@ +$def[1] .= "GPRINT:var1:LAST:\"%3.4lg %s$UNIT[1] LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%3.4lg %s$UNIT[1] MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%3.4lg %s$UNIT[1] AVERAGE \" "; diff --git a/share/pnp/templates.dist/check_esx3.php b/share/pnp/templates.dist/check_esx3.php index 4154e4c..828f5bb 100644 --- a/share/pnp/templates.dist/check_esx3.php +++ b/share/pnp/templates.dist/check_esx3.php @@ -1,4 +1,5 @@ "#ff77ee", // Purple - 2 => "#fed409", // Yellow - 3 => "#007dd0", // Blue - 4 => "#ee0a04", // Red - 5 => "#56a901", // Green - 6 => "#ff6600", // Orange - 7 => "#a4a4a4", // Grey + 1 => "#ff77ee", // Purple + 2 => "#fed409", // Yellow + 3 => "#007dd0", // Blue + 4 => "#ee0a04", // Red + 5 => "#56a901", // Green + 6 => "#ff6600", // Orange + 7 => "#a4a4a4", // Grey 8 => "#336633" // darker green - ); + ); $opt[1] = ''; $def[1] = ''; @@ -47,23 +50,23 @@ $vlabel = ""; // Specific settings based on first DataSource, if we want to customize it. switch ($NAME[1]) { - case "cpu_usage": - $vlabel = "Percent"; - $opt[1] .= "--lower-limit=0 --upper-limit=105 "; - break; - case "mem_usage": - $vlabel = "Percent"; - $opt[1] .= "--lower-limit=0 --upper-limit=105 "; - break; - case "net_receive": - $vlabel = "Kb/sec"; - break; - case "cpu_usagemhz": - $vlabel = "CPU Usage"; - $filled = 1; - break; - default: - break; + case "cpu_usage": + $vlabel = "Percent"; + $opt[1] .= "--lower-limit=0 --upper-limit=105 "; + break; + case "mem_usage": + $vlabel = "Percent"; + $opt[1] .= "--lower-limit=0 --upper-limit=105 "; + break; + case "net_receive": + $vlabel = "Kb/sec"; + break; + case "cpu_usagemhz": + $vlabel = "CPU Usage"; + $filled = 1; + break; + default: + break; } $opt[1] .= " --imgformat=PNG --title=\" $hostname / $servicedesc\" --base=$base --vertical-label=\"$vlabel\" --slope-mode "; @@ -71,35 +74,34 @@ $opt[1] .= "--watermark=\"http://www.op5.com template: $TEMPLATE[1]\" "; $opt[1] .= "--units-exponent=0 "; for ($i = 1; $i <= count($DS); $i++) { - $def[1] .= "DEF:ds$i=$RRDFILE[$i]:$DS[$i]:AVERAGE " ; - $def[1] .= "CDEF:var$i=ds$i "; + $def[1] .= "DEF:ds$i=$RRDFILE[$i]:$DS[$i]:AVERAGE " ; + $def[1] .= "CDEF:var$i=ds$i "; - if (isset($color)) { - $color_list = $color; - } + if (isset($color)) { + $color_list = $color; + } - /* If we have few datasources we fill the area below with a semitransparent version of basecolor - This makes the graph look more "modern" */ - if ($filled || count($DS) <= 3) { - $def[1] .= "AREA:var$i". $color_list[$i] . "32 "; - } - $def[1] .= "LINE1:var$i" . $color_list[$i] . "FF:\"$NAME[$i]\t\" "; - $def[1] .= "GPRINT:var$i:LAST:\"Cur\\:%8.2lf $UNIT[$i]\" "; - $def[1] .= "GPRINT:var$i:AVERAGE:\"Avg\\:%8.2lf $UNIT[$i]\" "; - $def[1] .= "GPRINT:var$i:MAX:\"Max\\:%8.2lf $UNIT[$i]\\n\" "; + /* If we have few datasources we fill the area below with a semitransparent version of basecolor + This makes the graph look more "modern" */ + if ($filled || count($DS) <= 3) { + $def[1] .= "AREA:var$i" . $color_list[$i] . "32 "; + } + $def[1] .= "LINE1:var$i" . $color_list[$i] . "FF:\"$NAME[$i]\t\" "; + $def[1] .= "GPRINT:var$i:LAST:\"Cur\\:%8.2lf $UNIT[$i]\" "; + $def[1] .= "GPRINT:var$i:AVERAGE:\"Avg\\:%8.2lf $UNIT[$i]\" "; + $def[1] .= "GPRINT:var$i:MAX:\"Max\\:%8.2lf $UNIT[$i]\\n\" "; } for ($i = 1; $i <= count($DS); $i++) { - if ($UNIT[$i] == "%%") { - $UNIT[$i] = "%"; - } + if ($UNIT[$i] == "%%") { + $UNIT[$i] = "%"; + } - if (isset($WARN[$i]) && $WARN[$i] != "") { - $def[1] .= "HRULE:$WARN[$i]#FFFF00:\"Warning ($NAME[$i])\: " . $WARN[$i] . " " . $UNIT[$i] . " \\n\" " ; - } + if (isset($WARN[$i]) && $WARN[$i] != "") { + $def[1] .= "HRULE:$WARN[$i]#FFFF00:\"Warning ($NAME[$i])\: " . $WARN[$i] . " " . $UNIT[$i] . " \\n\" " ; + } - if (isset($CRIT[$i]) && $CRIT[$i] != "") { - $def[1] .= "HRULE:$CRIT[$i]#FF0000:\"Critical ($NAME[$i])\: " . $CRIT[$i] . " " . $UNIT[$i] . " \\n\" " ; - } + if (isset($CRIT[$i]) && $CRIT[$i] != "") { + $def[1] .= "HRULE:$CRIT[$i]#FF0000:\"Critical ($NAME[$i])\: " . $CRIT[$i] . " " . $UNIT[$i] . " \\n\" " ; + } } -?> diff --git a/share/pnp/templates.dist/check_fping.php b/share/pnp/templates.dist/check_fping.php index ae61063..62ff191 100644 --- a/share/pnp/templates.dist/check_fping.php +++ b/share/pnp/templates.dist/check_fping.php @@ -1,10 +1,13 @@ - diff --git a/share/pnp/templates.dist/check_gearman.php b/share/pnp/templates.dist/check_gearman.php index 3c84349..4220661 100644 --- a/share/pnp/templates.dist/check_gearman.php +++ b/share/pnp/templates.dist/check_gearman.php @@ -1,36 +1,38 @@ DS as $KEY=>$VAL) { - if(preg_match('/(.*)_([^_].*)$/',$VAL['LABEL'],$matches)){ - $queue = $matches[1]; - $state = $matches[2]; - if($state == "waiting"){ - $i++; - $opt[$i]=''; - $def[$i]=''; - } - $opt[$i] = "-l0 --title \"Gearman Queue '$queue'\" "; - # - $ds_name[$i] = "$queue"; - $def[$i] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[$i] .= rrd::line1("var$KEY", $color[$state], rrd::cut($state,16)); - $def[$i] .= rrd::gprint("var$KEY", array('LAST', 'MAX', 'AVERAGE'), "%6.2lf".$VAL['UNIT']) ; - }else{ - $i++; - $opt[$i] = "-l0 --title \"Gearman Statistics\" "; - # - $ds_name[$i] = $VAL['NAME']; - $def[$i] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[$i] .= rrd::line1("var$KEY", '#00C600', rrd::cut($VAL['NAME'],16)); - $def[$i] .= rrd::gprint("var$KEY", array('LAST', 'MAX', 'AVERAGE'), "%6.2lf") ; - } +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/(.*)_([^_].*)$/', $VAL['LABEL'], $matches)) { + $queue = $matches[1]; + $state = $matches[2]; + if ($state == "waiting") { + $i++; + $opt[$i] = ''; + $def[$i] = ''; + } + $opt[$i] = "-l0 --title \"Gearman Queue '$queue'\" "; + # + $ds_name[$i] = "$queue"; + $def[$i] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[$i] .= rrd::line1("var$KEY", $color[$state], rrd::cut($state, 16)); + $def[$i] .= rrd::gprint("var$KEY", array('LAST', 'MAX', 'AVERAGE'), "%6.2lf" . $VAL['UNIT']) ; + } else { + $i++; + $opt[$i] = "-l0 --title \"Gearman Statistics\" "; + # + $ds_name[$i] = $VAL['NAME']; + $def[$i] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[$i] .= rrd::line1("var$KEY", '#00C600', rrd::cut($VAL['NAME'], 16)); + $def[$i] .= rrd::gprint("var$KEY", array('LAST', 'MAX', 'AVERAGE'), "%6.2lf") ; + } } diff --git a/share/pnp/templates.dist/check_hp_bladechassis.php b/share/pnp/templates.dist/check_hp_bladechassis.php index d338bbb..2208c6c 100644 --- a/share/pnp/templates.dist/check_hp_bladechassis.php +++ b/share/pnp/templates.dist/check_hp_bladechassis.php @@ -1,10 +1,12 @@ diff --git a/share/pnp/templates.dist/check_hpasm.php b/share/pnp/templates.dist/check_hpasm.php index 763f22a..75c1413 100644 --- a/share/pnp/templates.dist/check_hpasm.php +++ b/share/pnp/templates.dist/check_hpasm.php @@ -1,42 +1,43 @@ $VAL){ - if(preg_match('/^fan_/',$NAME[$KEY])){ +foreach ($DS as $KEY => $VAL) { + if (preg_match('/^fan_/', $NAME[$KEY])) { $ds_name[1] = "Fan Speed"; $opt[1] = "-X0 --slope-mode -u $max_rpm --vertical-label \"RPMs\" --title \"HPASM Fan Speed\" "; - if(!isset($def[1])){ - $def[1] = ""; - } + if (!isset($def[1])) { + $def[1] = ""; + } $def[1] .= "DEF:ovar$KEY=$RRDFILE[$KEY]:$DS[$KEY]:AVERAGE " ; $def[1] .= "CDEF:var$KEY=ovar$KEY,100,/,$max_rpm,* " ; - $def[1] .= "LINE:var$KEY#".$colors[$col_f].":\"$NAME[$KEY]\" " ; + $def[1] .= "LINE:var$KEY#" . $colors[$col_f] . ":\"$NAME[$KEY]\" " ; $def[1] .= "GPRINT:var$KEY:LAST:\"%6.0lf RPM LAST \" "; $def[1] .= "GPRINT:var$KEY:MAX:\"%6.0lf RPM MAX \" "; $def[1] .= "GPRINT:var$KEY:AVERAGE:\"%6.2lf RPM AVERAGE \\n\" "; - $col_f++; + $col_f++; } - if(preg_match('/^temp_/',$NAME[$KEY])){ + if (preg_match('/^temp_/', $NAME[$KEY])) { $ds_name[2] = "Temperature"; $opt[2] = "--slope-mode --vertical-label \"Grad Celsius\" --title \"HPASM Temperature\" "; - if(!isset($def[2])){ - $def[2] = ""; - } + if (!isset($def[2])) { + $def[2] = ""; + } $def[2] .= "DEF:var$KEY=$RRDFILE[$KEY]:$DS[$KEY]:AVERAGE " ; - $def[2] .= "LINE:var$KEY#".$colors[$col_t].":\"$NAME[$KEY]\\t\" " ; + $def[2] .= "LINE:var$KEY#" . $colors[$col_t] . ":\"$NAME[$KEY]\\t\" " ; $def[2] .= "GPRINT:var$KEY:LAST:\"%6.0lf $UNIT[$KEY] LAST \" "; $def[2] .= "GPRINT:var$KEY:MAX:\"%6.0lf $UNIT[$KEY] MAX \" "; $def[2] .= "GPRINT:var$KEY:AVERAGE:\"%6.2lf $UNIT[$KEY] AVERAGE \\n\" "; - $col_t++; + $col_t++; } } -?> diff --git a/share/pnp/templates.dist/check_http.php b/share/pnp/templates.dist/check_http.php index d24d367..e45ca0f 100644 --- a/share/pnp/templates.dist/check_http.php +++ b/share/pnp/templates.dist/check_http.php @@ -1,23 +1,26 @@ diff --git a/share/pnp/templates.dist/check_icmp.php b/share/pnp/templates.dist/check_icmp.php deleted file mode 120000 index cdbf865..0000000 --- a/share/pnp/templates.dist/check_icmp.php +++ /dev/null @@ -1 +0,0 @@ -check_ping.php \ No newline at end of file diff --git a/share/pnp/templates.dist/check_icmp.php b/share/pnp/templates.dist/check_icmp.php new file mode 100644 index 0000000..f8305f0 --- /dev/null +++ b/share/pnp/templates.dist/check_icmp.php @@ -0,0 +1,52 @@ + +$def[1] .= "GPRINT:var2:MAX:\"%7.2lf %Sb/s max\" "; diff --git a/share/pnp/templates.dist/check_iftraffic_pct.php b/share/pnp/templates.dist/check_iftraffic_pct.php index 746355a..67ebab4 100644 --- a/share/pnp/templates.dist/check_iftraffic_pct.php +++ b/share/pnp/templates.dist/check_iftraffic_pct.php @@ -1,8 +1,11 @@ diff --git a/share/pnp/templates.dist/check_jmx4perl_connector_errors.php b/share/pnp/templates.dist/check_jmx4perl_connector_errors.php index 8c2f108..fba30c6 100644 --- a/share/pnp/templates.dist/check_jmx4perl_connector_errors.php +++ b/share/pnp/templates.dist/check_jmx4perl_connector_errors.php @@ -1,14 +1,16 @@ +$def[1] .= rrd::comment("jolokia.org\\r"); diff --git a/share/pnp/templates.dist/check_jmx4perl_connector_nr_requests.php b/share/pnp/templates.dist/check_jmx4perl_connector_nr_requests.php index 71ca663..6a03289 100644 --- a/share/pnp/templates.dist/check_jmx4perl_connector_nr_requests.php +++ b/share/pnp/templates.dist/check_jmx4perl_connector_nr_requests.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_jmx4perl_connector_proc_time.php b/share/pnp/templates.dist/check_jmx4perl_connector_proc_time.php index 0da72d3..cb82fe1 100644 --- a/share/pnp/templates.dist/check_jmx4perl_connector_proc_time.php +++ b/share/pnp/templates.dist/check_jmx4perl_connector_proc_time.php @@ -1,16 +1,16 @@ +$def[1] .= rrd::comment("jolokia.org\\r"); diff --git a/share/pnp/templates.dist/check_jmx4perl_connector_received.php b/share/pnp/templates.dist/check_jmx4perl_connector_received.php index 1c3779b..f8ea50c 100644 --- a/share/pnp/templates.dist/check_jmx4perl_connector_received.php +++ b/share/pnp/templates.dist/check_jmx4perl_connector_received.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_jmx4perl_connector_sent.php b/share/pnp/templates.dist/check_jmx4perl_connector_sent.php index 59ff535..cafa230 100644 --- a/share/pnp/templates.dist/check_jmx4perl_connector_sent.php +++ b/share/pnp/templates.dist/check_jmx4perl_connector_sent.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_jmx4perl_connector_threads.php b/share/pnp/templates.dist/check_jmx4perl_connector_threads.php index 0b3cdfb..ed4e940 100644 --- a/share/pnp/templates.dist/check_jmx4perl_connector_threads.php +++ b/share/pnp/templates.dist/check_jmx4perl_connector_threads.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_jmx4perl_memory_gc_count.php b/share/pnp/templates.dist/check_jmx4perl_memory_gc_count.php index e35a321..6161b46 100644 --- a/share/pnp/templates.dist/check_jmx4perl_memory_gc_count.php +++ b/share/pnp/templates.dist/check_jmx4perl_memory_gc_count.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_jmx4perl_memory_gc_time.php b/share/pnp/templates.dist/check_jmx4perl_memory_gc_time.php index 779e0c9..18850df 100644 --- a/share/pnp/templates.dist/check_jmx4perl_memory_gc_time.php +++ b/share/pnp/templates.dist/check_jmx4perl_memory_gc_time.php @@ -1,16 +1,16 @@ +$def[1] .= rrd::comment("jolokia.org\\r"); diff --git a/share/pnp/templates.dist/check_jmx4perl_memory_heap.php b/share/pnp/templates.dist/check_jmx4perl_memory_heap.php index 3ce8506..2ec16e9 100644 --- a/share/pnp/templates.dist/check_jmx4perl_memory_heap.php +++ b/share/pnp/templates.dist/check_jmx4perl_memory_heap.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_jmx4perl_thread_count.php b/share/pnp/templates.dist/check_jmx4perl_thread_count.php index 928bfd4..6ff9f64 100644 --- a/share/pnp/templates.dist/check_jmx4perl_thread_count.php +++ b/share/pnp/templates.dist/check_jmx4perl_thread_count.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_jmx4perl_thread_increase.php b/share/pnp/templates.dist/check_jmx4perl_thread_increase.php index 73745b0..9027805 100644 --- a/share/pnp/templates.dist/check_jmx4perl_thread_increase.php +++ b/share/pnp/templates.dist/check_jmx4perl_thread_increase.php @@ -1,21 +1,21 @@ +$def[1] .= rrd::comment("jolokia.org"); diff --git a/share/pnp/templates.dist/check_load.php b/share/pnp/templates.dist/check_load.php index c3b46af..11b3e81 100644 --- a/share/pnp/templates.dist/check_load.php +++ b/share/pnp/templates.dist/check_load.php @@ -1,8 +1,10 @@ diff --git a/share/pnp/templates.dist/check_local_disk.php b/share/pnp/templates.dist/check_local_disk.php deleted file mode 120000 index 3167fdb..0000000 --- a/share/pnp/templates.dist/check_local_disk.php +++ /dev/null @@ -1 +0,0 @@ -check_disk.php \ No newline at end of file diff --git a/share/pnp/templates.dist/check_local_disk.php b/share/pnp/templates.dist/check_local_disk.php new file mode 100644 index 0000000..afc9f91 --- /dev/null +++ b/share/pnp/templates.dist/check_local_disk.php @@ -0,0 +1,65 @@ +DS as $KEY => $VAL) { +# set initial values + $fmt = '%7.3lf'; + $pct = ''; + $upper = ""; + $maximum = ""; + $divis = 1; + $return = '\n'; + $unit = "B"; + $label = $unit; + if ($VAL['UNIT'] != "") { + $unit = $VAL['UNIT']; + $label = $unit; + if ($VAL['UNIT'] == "%%") { + $label = '%'; + $fmt = '%5.1lf'; + $pct = '%'; + } + } + if ($VAL['MAX'] != "") { + # adjust value and unit, details in .../helpers/pnp.php + $max = pnp::adjust_unit($VAL['MAX'] . $unit, 1024, $fmt); + $upper = "-u $max[1] "; + $maximum = "of $max[1] $max[2]$pct used"; + $label = $max[2]; + $divis = $max[3]; + $return = ''; + } + $ds_name[$KEY] = str_replace("_", "/", $VAL['NAME']); + # set graph labels + $opt[$KEY] = "--vertical-label $label -l 0 $upper --title \"Filesystem $ds_name[$KEY]\" "; + # Graph Definitions + $def[$KEY] = rrd::def("var1", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + # "normalize" graph values + $def[$KEY] .= rrd::cdef("v_n", "var1,$divis,/"); + $def[$KEY] .= rrd::area("v_n", "#c6c6c6", $ds_name[$KEY]); + $def[$KEY] .= rrd::line1("v_n", "#003300"); + # show values in legend + $def[$KEY] .= rrd::gprint("v_n", "LAST", "$fmt $label$pct $maximum "); + $def[$KEY] .= rrd::gprint("v_n", "AVERAGE", "$fmt $label$pct avg used $return"); + # create max line and legend + if ($VAL['MAX'] != "") { + $def[$KEY] .= rrd::gprint("v_n", "MAX", "$fmt $label$pct max used \\n"); + $def[$KEY] .= rrd::hrule($max[1], "#003300", "Size of FS $max[0] \\n"); + } + # create warning line and legend + if ($VAL['WARN'] != "") { + $warn = pnp::adjust_unit($VAL['WARN'] . $unit, 1024, $fmt); + $def[$KEY] .= rrd::hrule($warn[1], "#ffff00", "Warning on $warn[0] \\n"); + } + # create critical line and legend + if ($VAL['CRIT'] != "") { + $crit = pnp::adjust_unit($VAL['CRIT'] . $unit, 1024, $fmt); + $def[$KEY] .= rrd::hrule($crit[1], "#ff0000", "Critical on $crit[0]\\n"); + } +} diff --git a/share/pnp/templates.dist/check_local_load.php b/share/pnp/templates.dist/check_local_load.php deleted file mode 120000 index 18c488e..0000000 --- a/share/pnp/templates.dist/check_local_load.php +++ /dev/null @@ -1 +0,0 @@ -check_load.php \ No newline at end of file diff --git a/share/pnp/templates.dist/check_local_load.php b/share/pnp/templates.dist/check_local_load.php new file mode 100644 index 0000000..11b3e81 --- /dev/null +++ b/share/pnp/templates.dist/check_local_load.php @@ -0,0 +1,27 @@ + +# Erstellt von Joerg Peter Geissler # +include 'arrayfix.php'; if ($WARN[1] == "") { - $WARN[1] = 0; + $WARN[1] = 0; } if ($CRIT[1] == "") { - $CRIT[1] = 0; + $CRIT[1] = 0; } $opt[1] = "--vertical-label \"Temperature\" --title \"Temperature for $hostname / $servicedesc\" "; @@ -20,4 +22,3 @@ $def[1] .= "GPRINT:var1:MAX:\"%3.4lg %s$UNIT[1] MAX \" "; $def[1] .= "GPRINT:var1:AVERAGE:\"%3.4lg %s$UNIT[1] AVERAGE \\n\" "; $def[1] .= "HRULE:$WARN[1]#FFFF00:\"Warning on $WARN[1]C\" "; $def[1] .= "HRULE:$CRIT[1]#FF0000:\"Critical on $CRIT[1]C\" "; -?> diff --git a/share/pnp/templates.dist/check_mssql_health.php b/share/pnp/templates.dist/check_mssql_health.php index af26762..ceb5f94 100644 --- a/share/pnp/templates.dist/check_mssql_health.php +++ b/share/pnp/templates.dist/check_mssql_health.php @@ -1,372 +1,366 @@ -DS as $KEY=>$VAL) { - $warning = ($VAL['WARN'] != "") ? $VAL['WARN'] : ""; - $warnmin = ($VAL['WARN_MIN'] != "") ? $VAL['WARN_MIN'] : ""; - $warnmax = ($VAL['WARN_MAX'] != "") ? $VAL['WARN_MAX'] : ""; - $critical = ($VAL['CRIT'] != "") ? $VAL['CRIT'] : ""; - $critmin = ($VAL['CRIT_MIN'] != "") ? $VAL['CRIT_MIN'] : ""; - $critmax = ($VAL['CRIT_MAX'] != "") ? $VAL['CRIT_MAX'] : ""; - $minimum = ($VAL['MIN'] != "") ? $VAL['MIN'] : ""; - $maximum = ($VAL['MAX'] != "") ? $VAL['MAX'] : ""; - - if(preg_match('/^connection_time$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Time to connect"; - $opt[$defcnt] = "--vertical-label \"Seconds\" --title \"Time to establish a connection to $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("connectiontime",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::area("connectiontime","#111111"); - $def[$defcnt] .= rrd::gprint("connectiontime",array("LAST", "MAX", "AVERAGE"),"%3.2lf Seconds") ; - $defcnt++; - } - if(preg_match('/^cpu_busy$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "CPU Busy Time"; - $opt[$defcnt] = "--vertical-label \"%\" --title \"CPU busy time on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("cpubusy",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::cdef("ag","cpubusy,".$VAL['WARN'].",LE,cpubusy,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,cpubusy,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","cpubusy,".$VAL['CRIT'].",LE,cpubusy,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,cpubusy,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","cpubusy,100,LE,cpubusy,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,cpubusy,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green"); - $def[$defcnt] .= rrd::area("ay","#$yellow"); - $def[$defcnt] .= rrd::area("ar","#$red"); - $def[$defcnt] .= rrd::line1("cpubusy","#111111"); - $def[$defcnt] .= rrd::gprint("cpubusy","LAST","CPU is busy for %3.2lf percent of the time\\n"); - $defcnt++; - } - if(preg_match('/^io_busy$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "IO Busy Time"; - $opt[$defcnt] = "--vertical-label \"%\" --title \"IO busy time on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("iobusy",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::cdef("ag","iobusy,".$VAL['WARN'].",LE,iobusy,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,iobusy,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","iobusy,".$VAL['CRIT'].",LE,iobusy,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,iobusy,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","iobusy,100,LE,iobusy,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,iobusy,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green"); - $def[$defcnt] .= rrd::area("ay","#$yellow"); - $def[$defcnt] .= rrd::area("ar","#$red"); - $def[$defcnt] .= rrd::line1("iobusy","#111111"); - $def[$defcnt] .= rrd::gprint("iobusy","LAST","IO is busy for %3.2lf percent of the time\\n"); - $defcnt++; - } - if(preg_match('/^full_scans_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Full Table Scans / Sec"; - $opt[$defcnt] = "--vertical-label \"scans / sec\" --title \"Full table scans / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("fullscans",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","fullscans,".$VAL['WARN'].",LE,fullscans,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,fullscans,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","fullscans,".$VAL['CRIT'].",LE,fullscans,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,fullscans,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","fullscans,INF,LE,fullscans,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,fullscans,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green"); - $def[$defcnt] .= rrd::area("ay","#$yellow"); - $def[$defcnt] .= rrd::area("ar","#$red"); - $def[$defcnt] .= rrd::line1("fullscans","#000000", "Full table scans"); - $def[$defcnt] .= rrd::gprint("fullscans",array("MAX", "AVERAGE", "LAST"),"%3.2lf"); - $defcnt++; - } - if(preg_match('/^connected_users$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Connected Users"; - $opt[$defcnt] = "--vertical-label \"Users\" --title \"Users connected to $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("users",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","users,".$VAL['WARN'].",LE,users,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,users,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","users,".$VAL['CRIT'].",LE,users,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,users,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","users,INF,LE,users,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,users,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red") ; - $def[$defcnt] .= rrd::line1("users","#000000","connected users"); - $def[$defcnt] .= rrd::gprint("users",array("LAST","MAX","AVERAGE"),"%.0lf"); - $defcnt++; - } - - if(preg_match('/^(.*)_transactions_per_sec/', $VAL['NAME'], $match)) { - $dsname = $match[1]; - if(empty($opt[1])){ - $opt[1] = "--vertical-label \"Transactions/s\" -l0 --title \"Database transactions / sec\" "; - } - if(empty($def[1])){ - $def[1] = ""; - } - $ds_name[1] = "Transactions Per Seconds "; - $def[1] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[1] .= rrd::line1 ("var".$KEY, rrd::color($KEY), rrd::cut($dsname, 12) ) ; - $def[1] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%3.6lf %S" ); - - } - - if(preg_match('/^latch_waits_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Latch Waits / Sec"; - $opt[$defcnt] = "--vertical-label \"waits / sec\" --title \"Latch waits / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("waits",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","waits,".$VAL['WARN'].",LE,waits,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,waits,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","waits,".$VAL['CRIT'].",LE,waits,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,waits,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","waits,INF,LE,waits,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,waits,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green"); - $def[$defcnt] .= rrd::area("ay","#$yellow"); - $def[$defcnt] .= rrd::area("ar","#$red"); - $def[$defcnt] .= rrd::line1("waits","#000000", "waits/s"); - $def[$defcnt] .= rrd::gprint("waits",array("MAX","AVERAGE","LAST"),"%3.2lf"); - $defcnt++; - } - if(preg_match('/^latch_avg_wait_time$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Latch Wait Time"; - $opt[$defcnt] = "--vertical-label \"msec\" --title \"Latch avg wait time on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("waittime",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","waittime,".$VAL['WARN'].",LE,waittime,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,waittime,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","waittime,".$VAL['CRIT'].",LE,waittime,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,waittime,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","waittime,INF,LE,waittime,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,waittime,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red") ; - $def[$defcnt] .= rrd::line1("waittime","#000000"); - $def[$defcnt] .= rrd::gprint("waittime",array("MAX", "AVERAGE", "LAST"),"%3.2lf"); - $defcnt++; - } - if(preg_match('/^sql_initcompilations_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Initial Compilations"; - $opt[$defcnt] = "--vertical-label \"initcomps/s\" --title \"Initial compilations / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("comps",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","comps,".$VAL['WARN'].",LE,comps,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","comps,".$VAL['CRIT'].",LE,comps,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","comps,INF,LE,comps,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red") ; - $def[$defcnt] .= rrd::line1("comps","#000000","Compilations"); - $def[$defcnt] .= rrd::gprint("comps",array("MAX", "AVERAGE", "LAST"),"%3.2lf/s"); - $defcnt++; - } - if(preg_match('/^sql_recompilations_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Re-Compilations"; - $opt[$defcnt] = "--vertical-label \"re-comps/s\" --title \"Re-Compilations / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("comps",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","comps,".$VAL['WARN'].",LE,comps,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","comps,".$VAL['CRIT'].",LE,comps,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","comps,INF,LE,comps,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green"); - $def[$defcnt] .= rrd::area("ay","#$yellow"); - $def[$defcnt] .= rrd::area("ar","#$red"); - $def[$defcnt] .= rrd::line1("comps","#000000","Re-Compilations"); - $def[$defcnt] .= rrd::gprint("comps",array("MAX", "AVERAGE", "LAST"),"%3.2lf/s"); - $defcnt++; - } - if(preg_match('/^batch_requests_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Batch Requests"; - $opt[$defcnt] = "--vertical-label \"batchreqs/s\" --title \"Batch requests / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("breqs",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","breqs,".$VAL['WARN'].",LE,breqs,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,breqs,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","breqs,".$VAL['CRIT'].",LE,breqs,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,breqs,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","breqs,INF,LE,breqs,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,breqs,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red") ; - $def[$defcnt] .= rrd::line1("breqs","#000000","Batch Requests"); - $def[$defcnt] .= rrd::gprint("breqs",array("LAST","AVERAGE","MAX"),"%3.2lf"); - $defcnt++; - } - if(preg_match('/^checkpoint_pages_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Checkpoint Pages"; - $opt[$defcnt] = "--vertical-label \"pages/s\" --title \"Flushed pages / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("pages",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","pages,".$VAL['WARN'].",LE,pages,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,pages,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","pages,".$VAL['CRIT'].",LE,pages,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,pages,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","pages,INF,LE,pages,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,pages,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red") ; - $def[$defcnt] .= rrd::line1("pages","#000000", "pages flushed"); - $def[$defcnt] .= rrd::gprint("pages",array("LAST","AVERAGE","MAX"),"%3.2lf"); - $defcnt++; - } - if(preg_match('/^free_list_stalls_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Free List Stalls"; - $opt[$defcnt] = "--vertical-label \"stalls/s\" --title \"Free list stalls / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("stalls",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","stalls,".$VAL['WARN'].",LE,stalls,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,stalls,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","stalls,".$VAL['CRIT'].",LE,stalls,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,stalls,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","stalls,INF,LE,stalls,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,stalls,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green"); - $def[$defcnt] .= rrd::area("ay","#$yellow"); - $def[$defcnt] .= rrd::area("ar","#$red"); - $def[$defcnt] .= rrd::line1("stalls","#000000", "free list stalls"); - $def[$defcnt] .= rrd::gprint("stalls",array("LAST", "AVERAGE","MAX"),"%3.2lf"); - $defcnt++; - } - if(preg_match('/^lazy_writes_per_sec$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Lazy Writes"; - $opt[$defcnt] = "--vertical-label \"lazyw/s\" --title \"Lazy writes / sec on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("lazyw",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::cdef("ag","lazyw,".$VAL['WARN'].",LE,lazyw,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,lazyw,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","lazyw,".$VAL['CRIT'].",LE,lazyw,".$VAL['WARN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,lazyw,0,IF"); - $def[$defcnt] .= rrd::cdef("ar","lazyw,INF,LE,lazyw,".$VAL['CRIT'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,lazyw,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red"); - $def[$defcnt] .= rrd::line1("lazyw","#000000"); - $def[$defcnt] .= rrd::gprint("lazyw",array("LAST", "AVERAGE","MAX"),"%3.4lf"); - $defcnt++; - } - if(preg_match('/^page_life_expectancy$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Page Life Expectancy"; - $opt[$defcnt] = "--vertical-label \"s\" --title \"Page life expectancy on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("lifeexp",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::cdef("ar","lifeexp,".$VAL['CRIT_MIN'].",LE,lifeexp,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,lifeexp,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","lifeexp,".$VAL['WARN_MIN'].",LE,lifeexp,".$VAL['CRIT_MIN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,lifeexp,0,IF"); - $def[$defcnt] .= rrd::cdef("ag","lifeexp,INF,LE,lifeexp,".$VAL['WARN_MIN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,lifeexp,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red") ; - $def[$defcnt] .= rrd::line1("lifeexp","#000000","Page Live"); - $def[$defcnt] .= rrd::gprint("lifeexp",array("LAST", "AVERAGE", "MIN"),"%3.2lf") ; - $defcnt++; - } - if(preg_match('/^total_server_memory$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Total Server memory"; - $opt[$defcnt] = "--vertical-label \"Bytes\" --title \"Total sql server memory on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("mem",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST"); - $def[$defcnt] .= rrd::area("mem","#c3c3c3", "Memory"); - $def[$defcnt] .= rrd::line1("mem","#111111"); - $def[$defcnt] .= rrd::gprint("mem",array("MAX","AVERAGE", "LAST"),"%.1lf %SB") ; - $defcnt++; - } - if(preg_match('/^buffer_cache_hit_ratio$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Buffer Cache Hit Ratio"; - $opt[$defcnt] = "--vertical-label \"%\" --title \"Buffer cache hit ratio on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("bufcahitrat",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::cdef("ar","bufcahitrat,".$VAL['CRIT_MIN'].",LE,bufcahitrat,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,bufcahitrat,0,IF"); - $def[$defcnt] .= rrd::cdef("ay","bufcahitrat,".$VAL['WARN_MIN'].",LE,bufcahitrat,".$VAL['CRIT_MIN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,bufcahitrat,0,IF"); - $def[$defcnt] .= rrd::cdef("ag","bufcahitrat,100,LE,bufcahitrat,".$VAL['WARN_MIN'].",GT,INF,UNKN,IF,UNKN,IF,ISINF,bufcahitrat,0,IF"); - $def[$defcnt] .= rrd::area("ag","#$green") ; - $def[$defcnt] .= rrd::area("ay","#$yellow") ; - $def[$defcnt] .= rrd::area("ar","#$red") ; - $def[$defcnt] .= rrd::line1("bufcahitrat","#000000:"); - $def[$defcnt] .= rrd::gprint("bufcahitrat","LAST","Hit ratio is %3.2lf percent\\n") ; - $defcnt++; - } - - if(preg_match('/^(.*)_lock_timeouts_per_sec/', $VAL['NAME'], $match)) { - $dsname = $match[1]; - if(empty($opt[1])){ - $opt[1] = "--vertical-label \"Lock timeouts/s\" -l0 --title \"Locks timeouts / sec\" "; - } - if(empty($def[1])){ - $def[1] = ""; - } - $ds_name[1] = "Lock Timeouts Per Second "; - $def[1] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[1] .= rrd::line1 ("var".$KEY, rrd::color($KEY), rrd::cut($dsname, 12) ) ; - $def[1] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%3.6lf" ); - - } - - if(preg_match('/^(.*)_lock_waits_per_sec/', $VAL['NAME'], $match)) { - $dsname = $match[1]; - if(!defined($opt[1])){ - $opt[1] = "--vertical-label \"Lockwaity/s\" -l0 --title \"Lockwaits / sec\" "; - } - if(empty($def[1])){ - $def[1] = ""; - } - $ds_name[1] = "Lockwaits / sec "; - $def[1] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[1] .= rrd::line1 ("var".$KEY, rrd::color($KEY), rrd::cut($dsname, 12) ) ; - $def[1] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%3.6lf" ); - - } - - if(preg_match('/^(.*)_deadlocks_per_sec/', $VAL['NAME'], $match)) { - $dsname = $match[1]; - if(!defined($opt[1])){ - $opt[1] = "--vertical-label \"Deadlocks/s\" -l0 --title \"Deadlocks / sec\" "; - } - if(empty($def[1])){ - $def[1] = ""; - } - $ds_name[1] = "Deadlocks / sec "; - $def[1] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[1] .= rrd::line1 ("var".$KEY, rrd::color($KEY), rrd::cut($dsname, 12) ) ; - $def[1] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%3.6lf" ); - } - - if(preg_match('/^db_(.*)_free_pct/', $VAL['NAME'], $match)) { - $dsname = $match[1]; - if(!defined($opt[1])){ - $opt[1] = "--vertical-label \"%\" -l0 --title \"DB Freespace %\" "; - } - if(empty($def[1])){ - $def[1] = ""; - } - $ds_name[1] = "DB Freespace %"; - $def[1] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[1] .= rrd::line1 ("var".$KEY, rrd::color($KEY), rrd::cut($dsname, 12) ) ; - $def[1] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%3.2lf%%" ); - } - if(preg_match('/^db_(.*)_free$/', $VAL['NAME'], $match)) { - $dsname = $match[1]; - if(empty($opt[2])){ - $opt[2] = "--vertical-label \"MB\" --title \"DB Freespace MB\" "; - } - if(empty($def[2])){ - $def[2] = ""; - } - $ds_name[2] = "DB Freespace MB"; - $def[2] .= rrd::def ("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - $def[2] .= rrd::line1 ("var".$KEY, rrd::color($KEY), rrd::cut($dsname, 12) ) ; - $def[2] .= rrd::gprint ("var".$KEY, array("LAST","MAX","AVERAGE"), "%3.2lf %SM" ); - } - - if(preg_match('/^select$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Output from sql-query for $servicedesc"; - $opt[$defcnt] = "--vertical-label \"Counts\" --title \"Output from sql-query for $servicedesc on $hostname\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("var".$KEY,$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::area("var".$KEY,"#111111"); - $def[$defcnt] .= rrd::gprint("var".$KEY,array("LAST", "MAX", "AVERAGE"),"%3.2lf Counts") ; - $defcnt++; - } - - if(preg_match('/^(.*)bck_age$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "Last DB Backup"; - $opt[$defcnt] = "--vertical-label \"Hours\" --title \"Last DB Backup\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("var".$KEY,$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::area("var".$KEY,"#111111"); - $def[$defcnt] .= rrd::gprint("var".$KEY,array("LAST", "MAX", "AVERAGE"),"%3.2lf Counts") ; - $defcnt++; - } - - if(preg_match('/^sql_runtime$/', $VAL['NAME'])) { - $ds_name[$defcnt] = "SQL runtime"; - $opt[$defcnt] = "--vertical-label \"Seconds\" --title \"Execution time of the SQL statement\" "; - $def[$defcnt] = ""; - $def[$defcnt] .= rrd::def("runtime",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE:reduce=LAST") ; - $def[$defcnt] .= rrd::area("runtime","#111111"); - $def[$defcnt] .= rrd::gprint("runtime",array("LAST", "MAX", "AVERAGE"),"%3.2lf Seconds") ; - $defcnt++; - } -} -?> +DS as $KEY => $VAL) { + $warning = ($VAL['WARN'] != "") ? $VAL['WARN'] : ""; + $warnmin = ($VAL['WARN_MIN'] != "") ? $VAL['WARN_MIN'] : ""; + $warnmax = ($VAL['WARN_MAX'] != "") ? $VAL['WARN_MAX'] : ""; + $critical = ($VAL['CRIT'] != "") ? $VAL['CRIT'] : ""; + $critmin = ($VAL['CRIT_MIN'] != "") ? $VAL['CRIT_MIN'] : ""; + $critmax = ($VAL['CRIT_MAX'] != "") ? $VAL['CRIT_MAX'] : ""; + $minimum = ($VAL['MIN'] != "") ? $VAL['MIN'] : ""; + $maximum = ($VAL['MAX'] != "") ? $VAL['MAX'] : ""; + if (preg_match('/^connection_time$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Time to connect"; + $opt[$defcnt] = "--vertical-label \"Seconds\" --title \"Time to establish a connection to $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("connectiontime", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::area("connectiontime", "#111111"); + $def[$defcnt] .= rrd::gprint("connectiontime", array("LAST", "MAX", "AVERAGE"), "%3.2lf Seconds") ; + $defcnt++; + } + if (preg_match('/^cpu_busy$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "CPU Busy Time"; + $opt[$defcnt] = "--vertical-label \"%\" --title \"CPU busy time on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("cpubusy", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::cdef("ag", "cpubusy," . $VAL['WARN'] . ",LE,cpubusy,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,cpubusy,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "cpubusy," . $VAL['CRIT'] . ",LE,cpubusy," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,cpubusy,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "cpubusy,100,LE,cpubusy," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,cpubusy,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green"); + $def[$defcnt] .= rrd::area("ay", "#$yellow"); + $def[$defcnt] .= rrd::area("ar", "#$red"); + $def[$defcnt] .= rrd::line1("cpubusy", "#111111"); + $def[$defcnt] .= rrd::gprint("cpubusy", "LAST", "CPU is busy for %3.2lf percent of the time\\n"); + $defcnt++; + } + if (preg_match('/^io_busy$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "IO Busy Time"; + $opt[$defcnt] = "--vertical-label \"%\" --title \"IO busy time on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("iobusy", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::cdef("ag", "iobusy," . $VAL['WARN'] . ",LE,iobusy,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,iobusy,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "iobusy," . $VAL['CRIT'] . ",LE,iobusy," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,iobusy,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "iobusy,100,LE,iobusy," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,iobusy,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green"); + $def[$defcnt] .= rrd::area("ay", "#$yellow"); + $def[$defcnt] .= rrd::area("ar", "#$red"); + $def[$defcnt] .= rrd::line1("iobusy", "#111111"); + $def[$defcnt] .= rrd::gprint("iobusy", "LAST", "IO is busy for %3.2lf percent of the time\\n"); + $defcnt++; + } + if (preg_match('/^full_scans_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Full Table Scans / Sec"; + $opt[$defcnt] = "--vertical-label \"scans / sec\" --title \"Full table scans / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("fullscans", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "fullscans," . $VAL['WARN'] . ",LE,fullscans,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,fullscans,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "fullscans," . $VAL['CRIT'] . ",LE,fullscans," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,fullscans,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "fullscans,INF,LE,fullscans," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,fullscans,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green"); + $def[$defcnt] .= rrd::area("ay", "#$yellow"); + $def[$defcnt] .= rrd::area("ar", "#$red"); + $def[$defcnt] .= rrd::line1("fullscans", "#000000", "Full table scans"); + $def[$defcnt] .= rrd::gprint("fullscans", array("MAX", "AVERAGE", "LAST"), "%3.2lf"); + $defcnt++; + } + if (preg_match('/^connected_users$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Connected Users"; + $opt[$defcnt] = "--vertical-label \"Users\" --title \"Users connected to $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("users", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "users," . $VAL['WARN'] . ",LE,users,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,users,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "users," . $VAL['CRIT'] . ",LE,users," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,users,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "users,INF,LE,users," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,users,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red") ; + $def[$defcnt] .= rrd::line1("users", "#000000", "connected users"); + $def[$defcnt] .= rrd::gprint("users", array("LAST","MAX","AVERAGE"), "%.0lf"); + $defcnt++; + } + + if (preg_match('/^(.*)_transactions_per_sec/', $VAL['NAME'], $match)) { + $dsname = $match[1]; + if (empty($opt[1])) { + $opt[1] = "--vertical-label \"Transactions/s\" -l0 --title \"Database transactions / sec\" "; + } + if (empty($def[1])) { + $def[1] = ""; + } + $ds_name[1] = "Transactions Per Seconds "; + $def[1] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[1] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($dsname, 12)) ; + $def[1] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%3.6lf %S"); + } + + if (preg_match('/^latch_waits_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Latch Waits / Sec"; + $opt[$defcnt] = "--vertical-label \"waits / sec\" --title \"Latch waits / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("waits", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "waits," . $VAL['WARN'] . ",LE,waits,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,waits,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "waits," . $VAL['CRIT'] . ",LE,waits," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,waits,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "waits,INF,LE,waits," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,waits,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green"); + $def[$defcnt] .= rrd::area("ay", "#$yellow"); + $def[$defcnt] .= rrd::area("ar", "#$red"); + $def[$defcnt] .= rrd::line1("waits", "#000000", "waits/s"); + $def[$defcnt] .= rrd::gprint("waits", array("MAX","AVERAGE","LAST"), "%3.2lf"); + $defcnt++; + } + if (preg_match('/^latch_avg_wait_time$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Latch Wait Time"; + $opt[$defcnt] = "--vertical-label \"msec\" --title \"Latch avg wait time on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("waittime", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "waittime," . $VAL['WARN'] . ",LE,waittime,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,waittime,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "waittime," . $VAL['CRIT'] . ",LE,waittime," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,waittime,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "waittime,INF,LE,waittime," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,waittime,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red") ; + $def[$defcnt] .= rrd::line1("waittime", "#000000"); + $def[$defcnt] .= rrd::gprint("waittime", array("MAX", "AVERAGE", "LAST"), "%3.2lf"); + $defcnt++; + } + if (preg_match('/^sql_initcompilations_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Initial Compilations"; + $opt[$defcnt] = "--vertical-label \"initcomps/s\" --title \"Initial compilations / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("comps", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "comps," . $VAL['WARN'] . ",LE,comps,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "comps," . $VAL['CRIT'] . ",LE,comps," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "comps,INF,LE,comps," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red") ; + $def[$defcnt] .= rrd::line1("comps", "#000000", "Compilations"); + $def[$defcnt] .= rrd::gprint("comps", array("MAX", "AVERAGE", "LAST"), "%3.2lf/s"); + $defcnt++; + } + if (preg_match('/^sql_recompilations_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Re-Compilations"; + $opt[$defcnt] = "--vertical-label \"re-comps/s\" --title \"Re-Compilations / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("comps", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "comps," . $VAL['WARN'] . ",LE,comps,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "comps," . $VAL['CRIT'] . ",LE,comps," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "comps,INF,LE,comps," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,comps,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green"); + $def[$defcnt] .= rrd::area("ay", "#$yellow"); + $def[$defcnt] .= rrd::area("ar", "#$red"); + $def[$defcnt] .= rrd::line1("comps", "#000000", "Re-Compilations"); + $def[$defcnt] .= rrd::gprint("comps", array("MAX", "AVERAGE", "LAST"), "%3.2lf/s"); + $defcnt++; + } + if (preg_match('/^batch_requests_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Batch Requests"; + $opt[$defcnt] = "--vertical-label \"batchreqs/s\" --title \"Batch requests / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("breqs", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "breqs," . $VAL['WARN'] . ",LE,breqs,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,breqs,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "breqs," . $VAL['CRIT'] . ",LE,breqs," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,breqs,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "breqs,INF,LE,breqs," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,breqs,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red") ; + $def[$defcnt] .= rrd::line1("breqs", "#000000", "Batch Requests"); + $def[$defcnt] .= rrd::gprint("breqs", array("LAST","AVERAGE","MAX"), "%3.2lf"); + $defcnt++; + } + if (preg_match('/^checkpoint_pages_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Checkpoint Pages"; + $opt[$defcnt] = "--vertical-label \"pages/s\" --title \"Flushed pages / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("pages", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "pages," . $VAL['WARN'] . ",LE,pages,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,pages,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "pages," . $VAL['CRIT'] . ",LE,pages," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,pages,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "pages,INF,LE,pages," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,pages,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red") ; + $def[$defcnt] .= rrd::line1("pages", "#000000", "pages flushed"); + $def[$defcnt] .= rrd::gprint("pages", array("LAST","AVERAGE","MAX"), "%3.2lf"); + $defcnt++; + } + if (preg_match('/^free_list_stalls_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Free List Stalls"; + $opt[$defcnt] = "--vertical-label \"stalls/s\" --title \"Free list stalls / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("stalls", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "stalls," . $VAL['WARN'] . ",LE,stalls,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,stalls,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "stalls," . $VAL['CRIT'] . ",LE,stalls," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,stalls,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "stalls,INF,LE,stalls," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,stalls,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green"); + $def[$defcnt] .= rrd::area("ay", "#$yellow"); + $def[$defcnt] .= rrd::area("ar", "#$red"); + $def[$defcnt] .= rrd::line1("stalls", "#000000", "free list stalls"); + $def[$defcnt] .= rrd::gprint("stalls", array("LAST", "AVERAGE","MAX"), "%3.2lf"); + $defcnt++; + } + if (preg_match('/^lazy_writes_per_sec$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Lazy Writes"; + $opt[$defcnt] = "--vertical-label \"lazyw/s\" --title \"Lazy writes / sec on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("lazyw", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::cdef("ag", "lazyw," . $VAL['WARN'] . ",LE,lazyw,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,lazyw,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "lazyw," . $VAL['CRIT'] . ",LE,lazyw," . $VAL['WARN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,lazyw,0,IF"); + $def[$defcnt] .= rrd::cdef("ar", "lazyw,INF,LE,lazyw," . $VAL['CRIT'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,lazyw,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red"); + $def[$defcnt] .= rrd::line1("lazyw", "#000000"); + $def[$defcnt] .= rrd::gprint("lazyw", array("LAST", "AVERAGE","MAX"), "%3.4lf"); + $defcnt++; + } + if (preg_match('/^page_life_expectancy$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Page Life Expectancy"; + $opt[$defcnt] = "--vertical-label \"s\" --title \"Page life expectancy on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("lifeexp", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::cdef("ar", "lifeexp," . $VAL['CRIT_MIN'] . ",LE,lifeexp,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,lifeexp,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "lifeexp," . $VAL['WARN_MIN'] . ",LE,lifeexp," . $VAL['CRIT_MIN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,lifeexp,0,IF"); + $def[$defcnt] .= rrd::cdef("ag", "lifeexp,INF,LE,lifeexp," . $VAL['WARN_MIN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,lifeexp,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red") ; + $def[$defcnt] .= rrd::line1("lifeexp", "#000000", "Page Live"); + $def[$defcnt] .= rrd::gprint("lifeexp", array("LAST", "AVERAGE", "MIN"), "%3.2lf") ; + $defcnt++; + } + if (preg_match('/^total_server_memory$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Total Server memory"; + $opt[$defcnt] = "--vertical-label \"Bytes\" --title \"Total sql server memory on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("mem", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST"); + $def[$defcnt] .= rrd::area("mem", "#c3c3c3", "Memory"); + $def[$defcnt] .= rrd::line1("mem", "#111111"); + $def[$defcnt] .= rrd::gprint("mem", array("MAX","AVERAGE", "LAST"), "%.1lf %SB") ; + $defcnt++; + } + if (preg_match('/^buffer_cache_hit_ratio$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Buffer Cache Hit Ratio"; + $opt[$defcnt] = "--vertical-label \"%\" --title \"Buffer cache hit ratio on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("bufcahitrat", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::cdef("ar", "bufcahitrat," . $VAL['CRIT_MIN'] . ",LE,bufcahitrat,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,bufcahitrat,0,IF"); + $def[$defcnt] .= rrd::cdef("ay", "bufcahitrat," . $VAL['WARN_MIN'] . ",LE,bufcahitrat," . $VAL['CRIT_MIN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,bufcahitrat,0,IF"); + $def[$defcnt] .= rrd::cdef("ag", "bufcahitrat,100,LE,bufcahitrat," . $VAL['WARN_MIN'] . ",GT,INF,UNKN,IF,UNKN,IF,ISINF,bufcahitrat,0,IF"); + $def[$defcnt] .= rrd::area("ag", "#$green") ; + $def[$defcnt] .= rrd::area("ay", "#$yellow") ; + $def[$defcnt] .= rrd::area("ar", "#$red") ; + $def[$defcnt] .= rrd::line1("bufcahitrat", "#000000:"); + $def[$defcnt] .= rrd::gprint("bufcahitrat", "LAST", "Hit ratio is %3.2lf percent\\n") ; + $defcnt++; + } + + if (preg_match('/^(.*)_lock_timeouts_per_sec/', $VAL['NAME'], $match)) { + $dsname = $match[1]; + if (empty($opt[1])) { + $opt[1] = "--vertical-label \"Lock timeouts/s\" -l0 --title \"Locks timeouts / sec\" "; + } + if (empty($def[1])) { + $def[1] = ""; + } + $ds_name[1] = "Lock Timeouts Per Second "; + $def[1] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[1] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($dsname, 12)) ; + $def[1] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%3.6lf"); + } + + if (preg_match('/^(.*)_lock_waits_per_sec/', $VAL['NAME'], $match)) { + $dsname = $match[1]; + if (!defined($opt[1])) { + $opt[1] = "--vertical-label \"Lockwaity/s\" -l0 --title \"Lockwaits / sec\" "; + } + if (empty($def[1])) { + $def[1] = ""; + } + $ds_name[1] = "Lockwaits / sec "; + $def[1] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[1] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($dsname, 12)) ; + $def[1] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%3.6lf"); + } + + if (preg_match('/^(.*)_deadlocks_per_sec/', $VAL['NAME'], $match)) { + $dsname = $match[1]; + if (!defined($opt[1])) { + $opt[1] = "--vertical-label \"Deadlocks/s\" -l0 --title \"Deadlocks / sec\" "; + } + if (empty($def[1])) { + $def[1] = ""; + } + $ds_name[1] = "Deadlocks / sec "; + $def[1] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[1] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($dsname, 12)) ; + $def[1] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%3.6lf"); + } + + if (preg_match('/^db_(.*)_free_pct/', $VAL['NAME'], $match)) { + $dsname = $match[1]; + if (!defined($opt[1])) { + $opt[1] = "--vertical-label \"%\" -l0 --title \"DB Freespace %\" "; + } + if (empty($def[1])) { + $def[1] = ""; + } + $ds_name[1] = "DB Freespace %"; + $def[1] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[1] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($dsname, 12)) ; + $def[1] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%3.2lf%%"); + } + if (preg_match('/^db_(.*)_free$/', $VAL['NAME'], $match)) { + $dsname = $match[1]; + if (empty($opt[2])) { + $opt[2] = "--vertical-label \"MB\" --title \"DB Freespace MB\" "; + } + if (empty($def[2])) { + $def[2] = ""; + } + $ds_name[2] = "DB Freespace MB"; + $def[2] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + $def[2] .= rrd::line1("var" . $KEY, rrd::color($KEY), rrd::cut($dsname, 12)) ; + $def[2] .= rrd::gprint("var" . $KEY, array("LAST","MAX","AVERAGE"), "%3.2lf %SM"); + } + + if (preg_match('/^select$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Output from sql-query for $servicedesc"; + $opt[$defcnt] = "--vertical-label \"Counts\" --title \"Output from sql-query for $servicedesc on $hostname\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::area("var" . $KEY, "#111111"); + $def[$defcnt] .= rrd::gprint("var" . $KEY, array("LAST", "MAX", "AVERAGE"), "%3.2lf Counts") ; + $defcnt++; + } + + if (preg_match('/^(.*)bck_age$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "Last DB Backup"; + $opt[$defcnt] = "--vertical-label \"Hours\" --title \"Last DB Backup\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::area("var" . $KEY, "#111111"); + $def[$defcnt] .= rrd::gprint("var" . $KEY, array("LAST", "MAX", "AVERAGE"), "%3.2lf Counts") ; + $defcnt++; + } + + if (preg_match('/^sql_runtime$/', $VAL['NAME'])) { + $ds_name[$defcnt] = "SQL runtime"; + $opt[$defcnt] = "--vertical-label \"Seconds\" --title \"Execution time of the SQL statement\" "; + $def[$defcnt] = ""; + $def[$defcnt] .= rrd::def("runtime", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE:reduce=LAST") ; + $def[$defcnt] .= rrd::area("runtime", "#111111"); + $def[$defcnt] .= rrd::gprint("runtime", array("LAST", "MAX", "AVERAGE"), "%3.2lf Seconds") ; + $defcnt++; + } +} diff --git a/share/pnp/templates.dist/check_multi.php b/share/pnp/templates.dist/check_multi.php index cd0794a..814b33b 100644 --- a/share/pnp/templates.dist/check_multi.php +++ b/share/pnp/templates.dist/check_multi.php @@ -1,23 +1,27 @@ +$def[1] .= "GPRINT:var2:LAST:\"%3.4lg %s$UNIT[1] LAST \" "; +$def[1] .= "GPRINT:var2:MAX:\"%3.4lg %s$UNIT[1] MAX \" "; +$def[1] .= "GPRINT:var2:AVERAGE:\"%3.4lg %s$UNIT[1] AVERAGE \" "; diff --git a/share/pnp/templates.dist/check_multi_nagiostats.php b/share/pnp/templates.dist/check_multi_nagiostats.php index 64eac64..0647104 100644 --- a/share/pnp/templates.dist/check_multi_nagiostats.php +++ b/share/pnp/templates.dist/check_multi_nagiostats.php @@ -1,4 +1,5 @@ diff --git a/share/pnp/templates.dist/check_mysql_health.php b/share/pnp/templates.dist/check_mysql_health.php index 2a8f433..72e1c19 100644 --- a/share/pnp/templates.dist/check_mysql_health.php +++ b/share/pnp/templates.dist/check_mysql_health.php @@ -1,4 +1,5 @@ 60s) on $hostname\" "; $def[$defcnt] = ""; @@ -135,71 +136,71 @@ foreach ($DS as $i) { $def[$defcnt] .= "GPRINT:vlongrun:\"%.0lf long running processes \" " ; $defcnt++; } - if(preg_match('/^keycache_hitrate_now$/', $NAME[$i])) { + if (preg_match('/^keycache_hitrate_now$/', $NAME[$i])) { $ds_name[$defcnt] = "MyISAM key cache hitrate"; $opt[$defcnt] = "--vertical-label \"Percent\" --title \"MyISAM key cache hitrate on $hostname\" --upper-limit 100 --lower-limit 0 "; $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^keycache_hitrate$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "AREA:ag#$green: " ; - $def[$defcnt] .= "AREA:ay#$yellow: " ; - $def[$defcnt] .= "AREA:ar#$red: " ; - $def[$defcnt] .= "LINE1.5:hitrate#111111:\" \" "; - $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; - $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio (since epoch) is %3.2lf percent \\n\" "; - } - if(preg_match('/^keycache_hitrate_now$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; - $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; - $def[$defcnt] .= "GPRINT:vhitratenow:\"Hitratio (current) is %3.2lf percent \\n\" "; - } + if (preg_match('/^keycache_hitrate$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "AREA:ag#$green: " ; + $def[$defcnt] .= "AREA:ay#$yellow: " ; + $def[$defcnt] .= "AREA:ar#$red: " ; + $def[$defcnt] .= "LINE1.5:hitrate#111111:\" \" "; + $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; + $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio (since epoch) is %3.2lf percent \\n\" "; + } + if (preg_match('/^keycache_hitrate_now$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; + $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; + $def[$defcnt] .= "GPRINT:vhitratenow:\"Hitratio (current) is %3.2lf percent \\n\" "; + } } $defcnt++; } - if(preg_match('/^qcache_hitrate_now$/', $NAME[$i])) { + if (preg_match('/^qcache_hitrate_now$/', $NAME[$i])) { $ds_name[$defcnt] = "Query cache hitrate"; $opt[$defcnt] = "--vertical-label \"Percent\" --title \"Query cache hitrate on $hostname\" --upper-limit 100 --lower-limit 0 "; - $def[$defcnt] = ""; + $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^qcache_hitrate$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "AREA:ag#$green: " ; - $def[$defcnt] .= "AREA:ay#$yellow: " ; - $def[$defcnt] .= "AREA:ar#$red: " ; - $def[$defcnt] .= "LINE1.5:hitrate#111111:\" \" "; - $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; - $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio (since epoch) is %3.2lf percent \\n\" "; - } - if(preg_match('/^qcache_hitrate_now$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; - $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; - $def[$defcnt] .= "GPRINT:vhitratenow:\"Hitratio (current) is %3.2lf percent \\n\" "; - } - } + if (preg_match('/^qcache_hitrate$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "AREA:ag#$green: " ; + $def[$defcnt] .= "AREA:ay#$yellow: " ; + $def[$defcnt] .= "AREA:ar#$red: " ; + $def[$defcnt] .= "LINE1.5:hitrate#111111:\" \" "; + $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; + $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio (since epoch) is %3.2lf percent \\n\" "; + } + if (preg_match('/^qcache_hitrate_now$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; + $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; + $def[$defcnt] .= "GPRINT:vhitratenow:\"Hitratio (current) is %3.2lf percent \\n\" "; + } + } $defcnt++; $ds_name[$defcnt] = "Selects per second"; $opt[$defcnt] = "--vertical-label \"Selects / sec\" --title \"Selects per second on $hostname\" "; - $def[$defcnt] = ""; + $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^selects_per_sec$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:sps=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "AREA:sps#$now:\" \" "; - $def[$defcnt] .= "VDEF:vsps=sps,LAST " ; - $def[$defcnt] .= "GPRINT:vsps:\"%3.2lf Selects per second \\n\" "; - } + if (preg_match('/^selects_per_sec$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:sps=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "AREA:sps#$now:\" \" "; + $def[$defcnt] .= "VDEF:vsps=sps,LAST " ; + $def[$defcnt] .= "GPRINT:vsps:\"%3.2lf Selects per second \\n\" "; + } } $defcnt++; - } - if(preg_match('/^qcache_lowmem_prunes_rate$/', $NAME[$i])) { + } + if (preg_match('/^qcache_lowmem_prunes_rate$/', $NAME[$i])) { $ds_name[$defcnt] = "Query cache low memory prunes"; $opt[$defcnt] = "--vertical-label \"Prunes / sec\" --title \"Query cache low mem prunes on $hostname\" "; $def[$defcnt] = ""; @@ -209,7 +210,7 @@ foreach ($DS as $i) { $def[$defcnt] .= "GPRINT:vprunes:\"Rate is %3.2lf Prunes / Second \" " ; $defcnt++; } - if(preg_match('/^slow_queries_rate$/', $NAME[$i])) { + if (preg_match('/^slow_queries_rate$/', $NAME[$i])) { $ds_name[$defcnt] = "Slow query rate"; $opt[$defcnt] = "--vertical-label \"Slow queries / sec\" --title \"Slow queries on $hostname\" "; $def[$defcnt] = ""; @@ -219,125 +220,124 @@ foreach ($DS as $i) { $def[$defcnt] .= "GPRINT:vprunes:\"%3.2lf Slow queries / Second \" " ; $defcnt++; } - if(preg_match('/^tablelock_contention_now$/', $NAME[$i])) { + if (preg_match('/^tablelock_contention_now$/', $NAME[$i])) { $ds_name[$defcnt] = "Table lock contention"; # set upper limit to 10, because 3 means an already dead database $opt[$defcnt] = "--vertical-label \"Percent\" --title \"Table lock contention on $hostname\" --upper-limit 10 --lower-limit 0 "; $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^tablelock_contention$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:tbllckcont=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "CDEF:ag=tbllckcont,$WARN[$ii],LE,tbllckcont,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,tbllckcont,0,IF "; - $def[$defcnt] .= "CDEF:ay=tbllckcont,$CRIT[$ii],LE,tbllckcont,$WARN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tbllckcont,0,IF "; - $def[$defcnt] .= "CDEF:ar=tbllckcont,100,LE,tbllckcont,$CRIT[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tbllckcont,0,IF "; - $def[$defcnt] .= "AREA:ag#$green: " ; - $def[$defcnt] .= "AREA:ay#$yellow: " ; - $def[$defcnt] .= "AREA:ar#$red: " ; - $def[$defcnt] .= "LINE:tbllckcont#111111:\" \" "; - $def[$defcnt] .= "VDEF:vtbllckcont=tbllckcont,LAST " ; - $def[$defcnt] .= "GPRINT:vtbllckcont:\"Lock contention (since epoch) is %3.2lf%%\\n\" " ; - } - if(preg_match('/^tablelock_contention_now$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:tbllckcontnow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "LINE1.5:tbllckcontnow#$now:\" \" "; - $def[$defcnt] .= "VDEF:vtbllckcontnow=tbllckcontnow,LAST " ; - $def[$defcnt] .= "GPRINT:vtbllckcontnow:\"Lock contention (current) is %3.2lf%%\" "; - } + if (preg_match('/^tablelock_contention$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:tbllckcont=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "CDEF:ag=tbllckcont,$WARN[$ii],LE,tbllckcont,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,tbllckcont,0,IF "; + $def[$defcnt] .= "CDEF:ay=tbllckcont,$CRIT[$ii],LE,tbllckcont,$WARN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tbllckcont,0,IF "; + $def[$defcnt] .= "CDEF:ar=tbllckcont,100,LE,tbllckcont,$CRIT[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tbllckcont,0,IF "; + $def[$defcnt] .= "AREA:ag#$green: " ; + $def[$defcnt] .= "AREA:ay#$yellow: " ; + $def[$defcnt] .= "AREA:ar#$red: " ; + $def[$defcnt] .= "LINE:tbllckcont#111111:\" \" "; + $def[$defcnt] .= "VDEF:vtbllckcont=tbllckcont,LAST " ; + $def[$defcnt] .= "GPRINT:vtbllckcont:\"Lock contention (since epoch) is %3.2lf%%\\n\" " ; + } + if (preg_match('/^tablelock_contention_now$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:tbllckcontnow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "LINE1.5:tbllckcontnow#$now:\" \" "; + $def[$defcnt] .= "VDEF:vtbllckcontnow=tbllckcontnow,LAST " ; + $def[$defcnt] .= "GPRINT:vtbllckcontnow:\"Lock contention (current) is %3.2lf%%\" "; + } } $defcnt++; } - if(preg_match('/^tablecache_fillrate$/', $NAME[$i])) { + if (preg_match('/^tablecache_fillrate$/', $NAME[$i])) { $ds_name[$defcnt] = "Table cache hitrate"; $opt[$defcnt] = "--vertical-label \"Percent\" --title \"Table cache hitrate on $hostname\" --upper-limit 100 --lower-limit 0 "; $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^tablecache_hitrate$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "AREA:ag#$green: " ; - $def[$defcnt] .= "AREA:ay#$yellow: " ; - $def[$defcnt] .= "AREA:ar#$red: " ; - $def[$defcnt] .= "LINE:hitrate#111111:\" \" "; - $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; - $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio is %3.2lf percent \\n\" "; - } - if(preg_match('/^tablecache_fillrate$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; - $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; - $def[$defcnt] .= "GPRINT:vhitratenow:\"%3.2lf%% of the cache is filled \\n\" "; - } + if (preg_match('/^tablecache_hitrate$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "AREA:ag#$green: " ; + $def[$defcnt] .= "AREA:ay#$yellow: " ; + $def[$defcnt] .= "AREA:ar#$red: " ; + $def[$defcnt] .= "LINE:hitrate#111111:\" \" "; + $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; + $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio is %3.2lf percent \\n\" "; + } + if (preg_match('/^tablecache_fillrate$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; + $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; + $def[$defcnt] .= "GPRINT:vhitratenow:\"%3.2lf%% of the cache is filled \\n\" "; + } } $defcnt++; } - if(preg_match('/^pct_tmp_table_on_disk_now$/', $NAME[$i])) { + if (preg_match('/^pct_tmp_table_on_disk_now$/', $NAME[$i])) { $ds_name[$defcnt] = "Temporary tables created on disk "; $opt[$defcnt] = "--vertical-label \"Percent\" --title \"Temporary tables created on disk on $hostname\" --upper-limit 10 --lower-limit 0 "; $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^pct_tmp_table_on_disk$/', $NAME[$ii])) { - - $def[$defcnt] .= "DEF:tmptbldsk=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "CDEF:ag=tmptbldsk,$WARN[$ii],LE,tmptbldsk,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,tmptbldsk,0,IF "; - $def[$defcnt] .= "CDEF:ay=tmptbldsk,$CRIT[$ii],LE,tmptbldsk,$WARN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tmptbldsk,0,IF "; - $def[$defcnt] .= "CDEF:ar=tmptbldsk,100,LE,tmptbldsk,$CRIT[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tmptbldsk,0,IF "; - $def[$defcnt] .= "AREA:ag#$green: " ; - $def[$defcnt] .= "AREA:ay#$yellow: " ; - $def[$defcnt] .= "AREA:ar#$red: " ; - $def[$defcnt] .= "LINE:tmptbldsk#111111:\" \" "; - $def[$defcnt] .= "VDEF:vtmptbldsk=tmptbldsk,LAST " ; - $def[$defcnt] .= "GPRINT:vtmptbldsk:\"%3.2lf percent of temp tables were created on disk (since epoch)\\n\" " ; - } - if(preg_match('/^pct_tmp_table_on_disk_now$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:tmptbldsknow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "LINE1.5:tmptbldsknow#$now:\" \" "; - $def[$defcnt] .= "VDEF:vtmptbldsknow=tmptbldsknow,LAST " ; - $def[$defcnt] .= "GPRINT:vtmptbldsknow:\"%3.2lf percent of temp tables were created on disk (recently)\\n\" " ; - } + if (preg_match('/^pct_tmp_table_on_disk$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:tmptbldsk=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "CDEF:ag=tmptbldsk,$WARN[$ii],LE,tmptbldsk,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,tmptbldsk,0,IF "; + $def[$defcnt] .= "CDEF:ay=tmptbldsk,$CRIT[$ii],LE,tmptbldsk,$WARN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tmptbldsk,0,IF "; + $def[$defcnt] .= "CDEF:ar=tmptbldsk,100,LE,tmptbldsk,$CRIT[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,tmptbldsk,0,IF "; + $def[$defcnt] .= "AREA:ag#$green: " ; + $def[$defcnt] .= "AREA:ay#$yellow: " ; + $def[$defcnt] .= "AREA:ar#$red: " ; + $def[$defcnt] .= "LINE:tmptbldsk#111111:\" \" "; + $def[$defcnt] .= "VDEF:vtmptbldsk=tmptbldsk,LAST " ; + $def[$defcnt] .= "GPRINT:vtmptbldsk:\"%3.2lf percent of temp tables were created on disk (since epoch)\\n\" " ; + } + if (preg_match('/^pct_tmp_table_on_disk_now$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:tmptbldsknow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "LINE1.5:tmptbldsknow#$now:\" \" "; + $def[$defcnt] .= "VDEF:vtmptbldsknow=tmptbldsknow,LAST " ; + $def[$defcnt] .= "GPRINT:vtmptbldsknow:\"%3.2lf percent of temp tables were created on disk (recently)\\n\" " ; + } } $defcnt++; } - if(preg_match('/^thread_cache_hitrate_now$/', $NAME[$i])) { + if (preg_match('/^thread_cache_hitrate_now$/', $NAME[$i])) { $ds_name[$defcnt] = "Thread cache hitrate"; $opt[$defcnt] = "--vertical-label \"Percent\" --title \"Thread cache hitrate on $hostname\" --upper-limit 100 --lower-limit 0 "; - $def[$defcnt] = ""; + $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^thread_cache_hitrate$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; - $def[$defcnt] .= "AREA:ag#$green: " ; - $def[$defcnt] .= "AREA:ay#$yellow: " ; - $def[$defcnt] .= "AREA:ar#$red: " ; - $def[$defcnt] .= "LINE:hitrate#111111:\" \" "; - $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; - $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio (since epoch) is %3.2lf percent \\n\" "; - } - if(preg_match('/^thread_cache_hitrate_now$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; - $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; - $def[$defcnt] .= "GPRINT:vhitratenow:\"Hitratio (current) is %3.2lf percent \\n\" "; - } - } + if (preg_match('/^thread_cache_hitrate$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitrate=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "CDEF:ar=hitrate,$CRIT_MIN[$ii],LE,hitrate,0,GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ay=hitrate,$WARN_MIN[$ii],LE,hitrate,$CRIT_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "CDEF:ag=hitrate,100,LE,hitrate,$WARN_MIN[$ii],GT,INF,UNKN,IF,UNKN,IF,ISINF,hitrate,0,IF "; + $def[$defcnt] .= "AREA:ag#$green: " ; + $def[$defcnt] .= "AREA:ay#$yellow: " ; + $def[$defcnt] .= "AREA:ar#$red: " ; + $def[$defcnt] .= "LINE:hitrate#111111:\" \" "; + $def[$defcnt] .= "VDEF:vhitrate=hitrate,LAST " ; + $def[$defcnt] .= "GPRINT:vhitrate:\"Hitratio (since epoch) is %3.2lf percent \\n\" "; + } + if (preg_match('/^thread_cache_hitrate_now$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:hitratenow=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "LINE1.5:hitratenow#$now:\" \" "; + $def[$defcnt] .= "VDEF:vhitratenow=hitratenow,LAST " ; + $def[$defcnt] .= "GPRINT:vhitratenow:\"Hitratio (current) is %3.2lf percent \\n\" "; + } + } $defcnt++; $ds_name[$defcnt] = "Connects per second"; $opt[$defcnt] = "--vertical-label \"Conects / sec\" --title \"Connects per second on $hostname\" "; - $def[$defcnt] = ""; + $def[$defcnt] = ""; foreach ($DS as $ii) { - if(preg_match('/^connections_per_sec$/', $NAME[$ii])) { - $def[$defcnt] .= "DEF:sps=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; - $def[$defcnt] .= "AREA:sps#$now:\" \" "; - $def[$defcnt] .= "VDEF:vsps=sps,LAST " ; - $def[$defcnt] .= "GPRINT:vsps:\"%3.2lf Connects per second \\n\" "; - } + if (preg_match('/^connections_per_sec$/', $NAME[$ii])) { + $def[$defcnt] .= "DEF:sps=$RRDFILE[$ii]:$DS[$ii]:AVERAGE:reduce=LAST " ; + $def[$defcnt] .= "AREA:sps#$now:\" \" "; + $def[$defcnt] .= "VDEF:vsps=sps,LAST " ; + $def[$defcnt] .= "GPRINT:vsps:\"%3.2lf Connects per second \\n\" "; + } } $defcnt++; - } - if(preg_match('/^threads_connected$/', $NAME[$i])) { + } + if (preg_match('/^threads_connected$/', $NAME[$i])) { $ds_name[$defcnt] = "Connection threads"; $opt[$defcnt] = "--vertical-label \"Threads\" --title \"Connection threads on $hostname\" "; $def[$defcnt] = ""; @@ -347,7 +347,7 @@ foreach ($DS as $i) { $def[$defcnt] .= "GPRINT:vthreads:\"%.0lf Connection threads \" " ; $defcnt++; } - if(preg_match('/^threads_running$/', $NAME[$i])) { + if (preg_match('/^threads_running$/', $NAME[$i])) { $ds_name[$defcnt] = "Running threads"; $opt[$defcnt] = "--vertical-label \"Threads\" --title \"Running threads on $hostname\" "; $def[$defcnt] = ""; @@ -357,7 +357,7 @@ foreach ($DS as $i) { $def[$defcnt] .= "GPRINT:vthreads:\"%.0lf Running threads \" " ; $defcnt++; } - if(preg_match('/^threads_cached$/', $NAME[$i])) { + if (preg_match('/^threads_cached$/', $NAME[$i])) { $ds_name[$defcnt] = "Cached threads"; $opt[$defcnt] = "--vertical-label \"Threads\" --title \"Cached threads on $hostname\" "; $def[$defcnt] = ""; @@ -367,7 +367,7 @@ foreach ($DS as $i) { $def[$defcnt] .= "GPRINT:vthreads:\"%.0lf Cached threads \" " ; $defcnt++; } - if(preg_match('/^pct_open_files$/', $NAME[$i])) { + if (preg_match('/^pct_open_files$/', $NAME[$i])) { $ds_name[$defcnt] = "PCT Open Files"; $opt[$defcnt] = "--vertical-label \"OpenFiles\" --title \"PCT Open Files $hostname\" "; $def[$defcnt] = ""; @@ -377,24 +377,22 @@ foreach ($DS as $i) { $def[$defcnt] .= "GPRINT:vthreads:\"%.0lf Open Files \" " ; $defcnt++; } - if(preg_match('/^threads_created_per_sec$/', $NAME[$i])) { + if (preg_match('/^threads_created_per_sec$/', $NAME[$i])) { $ds_name[$defcnt] = "Created thread per second"; $opt[$defcnt] = "--vertical-label \"Created threads / sec\" --title \"Created threads per second on $hostname\" "; - $def[$defcnt] = ""; + $def[$defcnt] = ""; $def[$defcnt] .= "DEF:sps=$RRDFILE[$i]:$DS[$i]:AVERAGE:reduce=LAST " ; $def[$defcnt] .= "AREA:sps#$now:\" \" "; $def[$defcnt] .= "VDEF:vsps=sps,LAST " ; $def[$defcnt] .= "GPRINT:vsps:\"%3.2lf Created threads per second \\n\" "; - } - if(preg_match('/^connects_aborted_per_sec$/', $NAME[$i])) { + } + if (preg_match('/^connects_aborted_per_sec$/', $NAME[$i])) { $ds_name[$defcnt] = "Aborted Connects per second"; $opt[$defcnt] = "--vertical-label \"Aborted connects / sec\" --title \"Aborted Connects per second on $hostname\" "; - $def[$defcnt] = ""; + $def[$defcnt] = ""; $def[$defcnt] .= "DEF:sps=$RRDFILE[$i]:$DS[$i]:AVERAGE:reduce=LAST " ; $def[$defcnt] .= "AREA:sps#$now:\" \" "; $def[$defcnt] .= "VDEF:vsps=sps,LAST " ; $def[$defcnt] .= "GPRINT:vsps:\"%3.2lf Aborted Connects per second \\n\" "; - } + } } -?> - diff --git a/share/pnp/templates.dist/check_nt_cpu.php b/share/pnp/templates.dist/check_nt_cpu.php index 8a226ce..7a71d76 100644 --- a/share/pnp/templates.dist/check_nt_cpu.php +++ b/share/pnp/templates.dist/check_nt_cpu.php @@ -1,24 +1,24 @@ diff --git a/share/pnp/templates.dist/check_nt_disk.php b/share/pnp/templates.dist/check_nt_disk.php index 34df9ce..239b6f3 100644 --- a/share/pnp/templates.dist/check_nt_disk.php +++ b/share/pnp/templates.dist/check_nt_disk.php @@ -1,24 +1,25 @@ diff --git a/share/pnp/templates.dist/check_nt_mem.php b/share/pnp/templates.dist/check_nt_mem.php index 0eb2dd7..ee3e6c8 100644 --- a/share/pnp/templates.dist/check_nt_mem.php +++ b/share/pnp/templates.dist/check_nt_mem.php @@ -1,20 +1,21 @@ diff --git a/share/pnp/templates.dist/check_ntp_time.php b/share/pnp/templates.dist/check_ntp_time.php index a4df209..7092d1b 100644 --- a/share/pnp/templates.dist/check_ntp_time.php +++ b/share/pnp/templates.dist/check_ntp_time.php @@ -1,8 +1,10 @@ diff --git a/share/pnp/templates.dist/check_nwstat_CONNS.php b/share/pnp/templates.dist/check_nwstat_CONNS.php index d6087f2..3ab8f69 100644 --- a/share/pnp/templates.dist/check_nwstat_CONNS.php +++ b/share/pnp/templates.dist/check_nwstat_CONNS.php @@ -1,10 +1,12 @@ diff --git a/share/pnp/templates.dist/check_nwstat_LOAD.php b/share/pnp/templates.dist/check_nwstat_LOAD.php index 2bb0231..67f2e4f 100644 --- a/share/pnp/templates.dist/check_nwstat_LOAD.php +++ b/share/pnp/templates.dist/check_nwstat_LOAD.php @@ -1,10 +1,12 @@ diff --git a/share/pnp/templates.dist/check_nwstat_LOAD1.php b/share/pnp/templates.dist/check_nwstat_LOAD1.php deleted file mode 120000 index c328a6d..0000000 --- a/share/pnp/templates.dist/check_nwstat_LOAD1.php +++ /dev/null @@ -1 +0,0 @@ -check_nwstat_LOAD.php \ No newline at end of file diff --git a/share/pnp/templates.dist/check_nwstat_LOAD1.php b/share/pnp/templates.dist/check_nwstat_LOAD1.php new file mode 100644 index 0000000..67f2e4f --- /dev/null +++ b/share/pnp/templates.dist/check_nwstat_LOAD1.php @@ -0,0 +1,35 @@ + diff --git a/share/pnp/templates.dist/check_openmanage.php b/share/pnp/templates.dist/check_openmanage.php index 6ceefb9..3b22f2b 100644 --- a/share/pnp/templates.dist/check_openmanage.php +++ b/share/pnp/templates.dist/check_openmanage.php @@ -1,10 +1,11 @@ . - +include 'arrayfix.php'; # Array with different colors $colors = array("0022ff", "22ff22", "ff0000", "00aaaa", "ff00ff", - "ffa500", "cc0000", "0000cc", "0080C0", "8080C0", - "FF0080", "800080", "688e23", "408080", "808000", - "000000", "00FF00", "0080FF", "FF8000", "800000", - "FB31FB"); + "ffa500", "cc0000", "0000cc", "0080C0", "8080C0", + "FF0080", "800080", "688e23", "408080", "808000", + "000000", "00FF00", "0080FF", "FF8000", "800000", + "FB31FB"); # Counters $f = 0; # fan probe counter @@ -56,43 +57,45 @@ $enclosure_id = ''; $def_title = 'Dell OpenManage'; # Temperature unit -if (!defined('tempunit_defined')) { - define('tempunit_defined', 1); - - function tempunit($arg) +if (!defined('TEMPUNIT_DEFINED')) { + // phpcs:disable PSR1.Files.SideEffects + define('TEMPUNIT_DEFINED', 1); + function tempunit($arg) { - $unit = 'unknown'; - $vlabel = 'unknown'; - - switch ($arg) { - default: - $vlabel = "Celsius"; - $unit = "°C"; - break; - case "F": - $vlabel = "Fahrenheit"; - $unit = "°F"; - break; - case "K": - $vlabel = "Kelvin"; - $unit = "K"; - break; - case "R": - $vlabel = "Rankine"; - $unit = "°R"; - break; - } - return array($unit, $vlabel); + $unit = 'unknown'; + $vlabel = 'unknown'; + + switch ($arg) { + default: + $vlabel = "Celsius"; + $unit = "°C"; + break; + case "F": + $vlabel = "Fahrenheit"; + $unit = "°F"; + break; + case "K": + $vlabel = "Kelvin"; + $unit = "K"; + break; + case "R": + $vlabel = "Rankine"; + $unit = "°R"; + break; + } + return array($unit, $vlabel); } + // phpcs:enable PSR1.Files.SideEffects + } # Determine if we're running in legacy mode $legacy = "no"; -foreach ($this->DS as $KEY=>$VAL) { +foreach ($this->DS as $KEY => $VAL) { if (preg_match('/^(pwr_mon_|fan_|temp_|enclosure_|p\d+|f\d+|t\d+|e.+?t\d+)/', $VAL['LABEL'])) { - $legacy = "yes"; - break; + $legacy = "yes"; + break; } } @@ -100,7 +103,6 @@ foreach ($this->DS as $KEY=>$VAL) { # MAIN LOOP #------------------------------------------------------ if ($legacy == "yes") { # --legacy-- - $count = 0; # general counter $PWRcolor = "66FF00"; @@ -110,436 +112,408 @@ if ($legacy == "yes") { # --legacy-- $visited_pwr = 0; # Loop through the performance data - foreach ($this->DS as $KEY=>$VAL) { - - # AMPERAGE PROBE - if(preg_match('/^pwr_mon_/', $VAL['NAME']) || preg_match('/^p\d+[aw]$/', $VAL['NAME'])) { + foreach ($this->DS as $KEY => $VAL) { + # AMPERAGE PROBE + if (preg_match('/^pwr_mon_/', $VAL['NAME']) || preg_match('/^p\d+[aw]$/', $VAL['NAME'])) { + # Watt + if (preg_match('/system/', $VAL['NAME']) || preg_match('/^p\d+w$/', $VAL['NAME'])) { + # Long label + $VAL['NAME'] = preg_replace('/^pwr_mon_\d+_/', '', $VAL['NAME']); + $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); - # Watt - if (preg_match('/system/', $VAL['NAME']) || preg_match('/^p\d+w$/', $VAL['NAME'])) { - - # Long label - $VAL['NAME'] = preg_replace('/^pwr_mon_\d+_/', '', $VAL['NAME']); - $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); + # Short label + $VAL['NAME'] = preg_replace('/^p(\d+)w$/', 'Power Probe $1', $VAL['NAME']); - # Short label - $VAL['NAME'] = preg_replace('/^p(\d+)w$/', 'Power Probe $1', $VAL['NAME']); + ++$count; + $ds_name[$count] = "Power Consumption"; + $vlabel = "Watt"; - ++$count; - $ds_name[$count] = "Power Consumption"; - $vlabel = "Watt"; + $title = $ds_name[$count]; - $title = $ds_name[$count]; + $opt[$count] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; - $opt[$count] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; + if (isset($def[$count])) { + $def[$count] .= rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + } else { + $def[$count] = rrd::def("var" . $KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + } + $def[$count] .= rrd::area("var$KEY", "#" . $PWRcolor, $VAL['NAME']); + $def[$count] .= rrd::line1("var$KEY", "#000000"); + $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf W"); + } elseif (preg_match('/current/', $VAL['NAME']) || preg_match('/^p\d+a$/', $VAL['NAME'])) { + # Ampere + # Long label + $VAL['NAME'] = preg_replace('/^pwr_mon_\d+_/', '', $VAL['NAME']); + $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); + $VAL['NAME'] = preg_replace('/ current \d+$/', '', $VAL['NAME']); + $VAL['NAME'] = preg_replace('/ps/', 'PowerSupply', $VAL['NAME']); - if(isset($def[$count])){ - $def[$count] .= rrd::def("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - } - else { - $def[$count] = rrd::def("var".$KEY, $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - } - $def[$count] .= rrd::area("var$KEY", "#".$PWRcolor, $VAL['NAME']); - $def[$count] .= rrd::line1("var$KEY","#000000"); - $def[$count] .= rrd::gprint("var$KEY",array("LAST", "MAX", "AVERAGE"), "%6.0lf W"); - } - # Ampere - elseif (preg_match('/current/', $VAL['NAME']) || preg_match('/^p\d+a$/', $VAL['NAME'])) { + # Short label + $VAL['NAME'] = preg_replace('/^p(\d+)a$/', 'Amperage Probe $1', $VAL['NAME']); - # Long label - $VAL['NAME'] = preg_replace('/^pwr_mon_\d+_/', '', $VAL['NAME']); - $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); - $VAL['NAME'] = preg_replace('/ current \d+$/', '', $VAL['NAME']); - $VAL['NAME'] = preg_replace('/ps/', 'PowerSupply', $VAL['NAME']); + if ($visited_pwr == 0) { + ++$count; + $visited_pwr = 1; + } + $ds_name[$count] = "Amperage Probes"; + $vlabel = "Ampere"; - # Short label - $VAL['NAME'] = preg_replace('/^p(\d+)a$/', 'Amperage Probe $1', $VAL['NAME']); - - if ($visited_pwr == 0) { - ++$count; - $visited_pwr = 1; - } - $ds_name[$count] = "Amperage Probes"; - $vlabel = "Ampere"; + $title = $ds_name[$count]; - $title = $ds_name[$count]; + $opt[$count] = "-X0 --lower-limit 0 --slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; + if (isset($def[$count])) { + $def[$count] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$count] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } + $def[$count] .= rrd::line1("var$KEY", "#" . $colors[$a], $VAL['NAME']) ; + $def[$count] .= rrd::area("var$KEY", "#" . $colors[$a++] . "20") ; + $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%4.2lf A") ; + } + } - $opt[$count] = "-X0 --lower-limit 0 --slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; - if(isset($def[$count])){ - $def[$count] .= rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - else { - $def[$count] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - $def[$count] .= rrd::line1("var$KEY", "#".$colors[$a], $VAL['NAME']) ; - $def[$count] .= rrd::area("var$KEY","#".$colors[$a++]."20") ; - $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%4.2lf A") ; - } - } + # FANS (RPMs) + if (preg_match('/^fan_/', $VAL['NAME']) || preg_match('/^f\d+$/', $VAL['NAME'])) { + if ($visited_fan == 0) { + ++$count; + $visited_fan = 1; + } - # FANS (RPMs) - if(preg_match('/^fan_/', $VAL['NAME']) || preg_match('/^f\d+$/', $VAL['NAME'])){ - if ($visited_fan == 0) { - ++$count; - $visited_fan = 1; - } + # Long label + $VAL['NAME'] = preg_replace('/^fan_\d+_/', '', $VAL['NAME']); + $VAL['NAME'] = preg_replace('/_rpm$/', '', $VAL['NAME']); + $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); - # Long label - $VAL['NAME'] = preg_replace('/^fan_\d+_/', '', $VAL['NAME']); - $VAL['NAME'] = preg_replace('/_rpm$/', '', $VAL['NAME']); - $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); + # Short label + $VAL['NAME'] = preg_replace('/^f(\d+)$/', 'Fan Probe $1', $VAL['NAME']); - # Short label - $VAL['NAME'] = preg_replace('/^f(\d+)$/', 'Fan Probe $1', $VAL['NAME']); + $ds_name[$count] = "Fan Speed"; - $ds_name[$count] = "Fan Speed"; + $opt[$count] = "-X0 --slope-mode --vertical-label \"RPMs\" --title \"$def_title: Fan Speeds\" "; + if (isset($def[$count])) { + $def[$count] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$count] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + } + $def[$count] .= rrd::line1("var$KEY", "#" . $colors[$f++], $VAL['NAME']); + $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf RPM"); + } - $opt[$count] = "-X0 --slope-mode --vertical-label \"RPMs\" --title \"$def_title: Fan Speeds\" "; - if(isset($def[$count])){ - $def[$count] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - } - else { - $def[$count] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE"); - } - $def[$count] .= rrd::line1("var$KEY", "#".$colors[$f++],$VAL['NAME']); - $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%6.0lf RPM"); - } - - # TEMPERATURES (Celsius) - if(preg_match('/^temp_/', $VAL['NAME']) || preg_match('/^t\d+$/', $VAL['NAME'])){ - if ($visited_temp == 0) { - ++$count; - $visited_temp = 1; - } + # TEMPERATURES (Celsius) + if (preg_match('/^temp_/', $VAL['NAME']) || preg_match('/^t\d+$/', $VAL['NAME'])) { + if ($visited_temp == 0) { + ++$count; + $visited_temp = 1; + } - # Long label - $VAL['NAME'] = preg_replace('/^temp_\d+_/', '', $VAL['NAME']); - $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); + # Long label + $VAL['NAME'] = preg_replace('/^temp_\d+_/', '', $VAL['NAME']); + $VAL['NAME'] = preg_replace('/_/', ' ', $VAL['NAME']); - # Short label - $VAL['NAME'] = preg_replace('/^t(\d+)$/', 'Temperature Probe $1', $VAL['NAME']); + # Short label + $VAL['NAME'] = preg_replace('/^t(\d+)$/', 'Temperature Probe $1', $VAL['NAME']); - $ds_name[$count] = "Chassis Temperatures"; + $ds_name[$count] = "Chassis Temperatures"; - $warnThresh = "INF"; - $critThresh = "INF"; + $warnThresh = "INF"; + $critThresh = "INF"; - if ($VAL['WARN'] != "") { - $warnThresh = $VAL['WARN']; - } - if ($VAL['CRIT'] != "") { - $critThresh = $VAL['CRIT']; - } + if ($VAL['WARN'] != "") { + $warnThresh = $VAL['WARN']; + } + if ($VAL['CRIT'] != "") { + $critThresh = $VAL['CRIT']; + } - $opt[$count] = "--slope-mode --vertical-label \"Celsius\" --title \"$def_title: Chassis Temperatures\" "; - if(isset($def[$count])){ - $def[$count] .= rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - else { - $def[$count] = rrd::def("var$KEY", $VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - $def[$count] .= rrd::line1("var$KEY", "#".$colors[$t++], $VAL['NAME']); - $def[$count] .= rrd::gprint("var$KEY",array("LAST", "MAX", "AVERAGE"),"%6.0lf C"); - } - - # ENCLOSURE TEMPERATURES (Celsius) - if(preg_match('/^enclosure_(?P.+?)_temp_\d+$/', $VAL['NAME'], $matches) - || preg_match('/^e(?P.+?)t\d+$/', $VAL['NAME'], $matches)) { - $this_id = $matches['id']; + $opt[$count] = "--slope-mode --vertical-label \"Celsius\" --title \"$def_title: Chassis Temperatures\" "; + if (isset($def[$count])) { + $def[$count] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$count] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } + $def[$count] .= rrd::line1("var$KEY", "#" . $colors[$t++], $VAL['NAME']); + $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf C"); + } - if ($enclosure_id != $this_id) { - $e = 0; - ++$count; - $enclosure_id = $this_id; - } + # ENCLOSURE TEMPERATURES (Celsius) + if ( + preg_match('/^enclosure_(?P.+?)_temp_\d+$/', $VAL['NAME'], $matches) + || preg_match('/^e(?P.+?)t\d+$/', $VAL['NAME'], $matches) + ) { + $this_id = $matches['id']; - # Long label - $VAL['NAME'] = preg_replace('/^enclosure_.+?_temp_(\d+)$/', 'Probe $1', $VAL['NAME']); + if ($enclosure_id != $this_id) { + $e = 0; + ++$count; + $enclosure_id = $this_id; + } - # Short label - $VAL['NAME'] = preg_replace('/^e.+?t(\d+)$/', 'Probe $1', $VAL['NAME']); + # Long label + $VAL['NAME'] = preg_replace('/^enclosure_.+?_temp_(\d+)$/', 'Probe $1', $VAL['NAME']); - $ds_name[$count] = "Enclosure $enclosure_id Temperatures"; + # Short label + $VAL['NAME'] = preg_replace('/^e.+?t(\d+)$/', 'Probe $1', $VAL['NAME']); - $warnThresh = "INF"; - $critThresh = "INF"; + $ds_name[$count] = "Enclosure $enclosure_id Temperatures"; - if ($VAL['WARN'] != "") { - $warnThresh = $VAL['WARN']; - } - if ($VAL['CRIT'] != "") { - $critThresh = $VAL['CRIT']; - } + $warnThresh = "INF"; + $critThresh = "INF"; - $opt[$count] = "--slope-mode --vertical-label \"Celsius\" --title \"$def_title: Enclosure $enclosure_id Temperatures\" "; + if ($VAL['WARN'] != "") { + $warnThresh = $VAL['WARN']; + } + if ($VAL['CRIT'] != "") { + $critThresh = $VAL['CRIT']; + } - if(isset($def[$count])){ - $def[$count] .= rrd::def("var$KEY", $VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - else { - $def[$count] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - $def[$count] .= rrd::line1("var$KEY","#".$colors[$e++],$VAL['NAME']) ; - $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%6.0lf C"); - } + $opt[$count] = "--slope-mode --vertical-label \"Celsius\" --title \"$def_title: Enclosure $enclosure_id Temperatures\" "; + + if (isset($def[$count])) { + $def[$count] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$count] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } + $def[$count] .= rrd::line1("var$KEY", "#" . $colors[$e++], $VAL['NAME']) ; + $def[$count] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf C"); + } } -} -else { # --new-- - +} else { # --new-- # Loop through the performance data - foreach ($this->DS as $KEY=>$VAL) { - - $label = $VAL['LABEL']; + foreach ($this->DS as $KEY => $VAL) { + $label = $VAL['LABEL']; - # TEMPERATURES (AMBIENT) - if (preg_match('/^T/', $label) && preg_match('/Ambient/', $label)) { + # TEMPERATURES (AMBIENT) + if (preg_match('/^T/', $label) && preg_match('/Ambient/', $label)) { + # Temperature unit and vertical label + list ($unit, $vlabel) = tempunit($VAL['UNIT']); - # Temperature unit and vertical label - list ($unit, $vlabel) = tempunit($VAL['UNIT']); + # Long label + $label = preg_replace('/^T(\d+)_(.+)/', '$2', $label); + $label = preg_replace('/_/', ' ', $label); - # Long label - $label = preg_replace('/^T(\d+)_(.+)/', '$2', $label); - $label = preg_replace('/_/', ' ', $label); + # Short label + $label = preg_replace('/^T(\d+)$/', 'Probe $1', $label); - # Short label - $label = preg_replace('/^T(\d+)$/', 'Probe $1', $label); + $ds_name[$id_temp1] = "Temperatures"; - $ds_name[$id_temp1] = "Temperatures"; + $opt[$id_temp1] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: Ambient Temperature\" "; + if (isset($def[$id_temp1])) { + $def[$id_temp1] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$id_temp1] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } - $opt[$id_temp1] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: Ambient Temperature\" "; - if(isset($def[$id_temp1])){ - $def[$id_temp1] .= rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - else { - $def[$id_temp1] = rrd::def("var$KEY", $VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } + # fancy graphing + $def[$id_temp1] .= rrd::gradient("var$KEY", "#114480", "#1144dc", $label, 10, "50%"); + $def[$id_temp1] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%5.1lf $unit"); - # fancy graphing - $def[$id_temp1] .= rrd::gradient("var$KEY","#114480", "#1144dc", $label, 10, "50%"); - $def[$id_temp1] .= rrd::gprint("var$KEY",array("LAST", "MAX", "AVERAGE"),"%5.1lf $unit"); + # insert extra vertical space if we have thresholds + if ($VAL['WARN'] != "" || $VAL['CRIT'] != "") { + $def[$id_temp1] .= "COMMENT:\\s "; + } - # insert extra vertical space if we have thresholds - if ($VAL['WARN'] != "" || $VAL['CRIT'] != "") { - $def[$id_temp1] .= "COMMENT:\\s "; - } + # warning threshold + if ($VAL['WARN'] != "") { + $warnThresh = $VAL['WARN']; + $def[$id_temp1] .= rrd::cdef("warn$KEY", "var$KEY,$warnThresh,GT,var$KEY,UNKN,IF"); + $def[$id_temp1] .= rrd::gradient("warn$KEY", "#c4c400", "#ffff00", "Above Upper Warning Threshold\: $warnThresh $unit\\l", 10, "50%"); + } - # warning threshold - if ($VAL['WARN'] != "") { - $warnThresh = $VAL['WARN']; - $def[$id_temp1] .= rrd::cdef("warn$KEY", "var$KEY,$warnThresh,GT,var$KEY,UNKN,IF"); - $def[$id_temp1] .= rrd::gradient("warn$KEY","#c4c400", "#ffff00","Above Upper Warning Threshold\: $warnThresh $unit\\l", 10, "50%"); - } - - # critical threshold - if ($VAL['CRIT'] != "") { - $critThresh = $VAL['CRIT']; - $def[$id_temp1] .= rrd::cdef("crit$KEY", "var$KEY,$critThresh,GT,var$KEY,UNKN,IF"); - $def[$id_temp1] .= rrd::gradient("crit$KEY","#800000", "#dc0000","Above Upper Critical Threshold\: $critThresh $unit\\l", 10, "50%"); - } - } + # critical threshold + if ($VAL['CRIT'] != "") { + $critThresh = $VAL['CRIT']; + $def[$id_temp1] .= rrd::cdef("crit$KEY", "var$KEY,$critThresh,GT,var$KEY,UNKN,IF"); + $def[$id_temp1] .= rrd::gradient("crit$KEY", "#800000", "#dc0000", "Above Upper Critical Threshold\: $critThresh $unit\\l", 10, "50%"); + } + } - # TEMPERATURES - if (preg_match('/^T/', $label) && !preg_match('/Ambient/', $label)) { + # TEMPERATURES + if (preg_match('/^T/', $label) && !preg_match('/Ambient/', $label)) { + # Temperature unit and vertical label + list ($unit, $vlabel) = tempunit($VAL['UNIT']); - # Temperature unit and vertical label - list ($unit, $vlabel) = tempunit($VAL['UNIT']); + # Long label + $label = preg_replace('/^T(\d+)_(.+)/', '$2', $label); + $label = preg_replace('/_/', ' ', $label); - # Long label - $label = preg_replace('/^T(\d+)_(.+)/', '$2', $label); - $label = preg_replace('/_/', ' ', $label); + # Short label + $label = preg_replace('/^T(\d+)$/', 'Probe $1', $label); - # Short label - $label = preg_replace('/^T(\d+)$/', 'Probe $1', $label); + $ds_name[$id_temp2] = "Temperatures"; - $ds_name[$id_temp2] = "Temperatures"; + $opt[$id_temp2] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: Chassis Temperatures\" "; + if (isset($def[$id_temp2])) { + $def[$id_temp2] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$id_temp2] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } + $def[$id_temp2] .= rrd::line1("var$KEY", "#" . $colors[$t++], rrd::cut($label, 20)); + $def[$id_temp2] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%4.1lf $unit"); + } - $opt[$id_temp2] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: Chassis Temperatures\" "; - if (isset($def[$id_temp2])) { - $def[$id_temp2] .= rrd::def("var$KEY", $VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - else { - $def[$id_temp2] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - $def[$id_temp2] .= rrd::line1("var$KEY", "#".$colors[$t++], rrd::cut($label,20) ); - $def[$id_temp2] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%4.1lf $unit"); - } + # WATTAGE PROBE + if (preg_match('/^W/', $label)) { + # Long label + $label = preg_replace('/^W(\d+)_(.+)/', '$2', $label); + $label = preg_replace('/_/', ' ', $label); - # WATTAGE PROBE - if (preg_match('/^W/', $label)) { + # Short label + $label = preg_replace('/^W(\d+)$/', 'Probe $1', $label); - # Long label - $label = preg_replace('/^W(\d+)_(.+)/', '$2', $label); - $label = preg_replace('/_/', ' ', $label); + $ds_name[$id_watt] = "Power Consumption"; + $vlabel = "Watt"; - # Short label - $label = preg_replace('/^W(\d+)$/', 'Probe $1', $label); + $title = $ds_name[$id_watt]; - $ds_name[$id_watt] = "Power Consumption"; - $vlabel = "Watt"; + $opt[$id_watt] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; - $title = $ds_name[$id_watt]; + if (isset($def[$id_watt])) { + $def[$id_watt] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$id_watt] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } - $opt[$id_watt] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; - - if(isset($def[$id_watt])){ - $def[$id_watt] .= rrd::def("var$KEY",$VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; - } - else { - $def[$id_watt] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE") ; - } - - # calculate kWh and BTU + # calculate kWh and BTU $def[$id_watt] .= "VDEF:tot$KEY=var$KEY,TOTAL "; - # rrd:vdef is broken in pnp4nagios 0.6.13 # $def[$id_watt] .= rrd::vdef("tot$KEY","var$KEY,TOTAL"); - $def[$id_watt] .= rrd::cdef("kwh$KEY","var$KEY,POP,tot$KEY,1000,/,60,/,60,/"); - $def[$id_watt] .= rrd::cdef("btu$KEY","kwh$KEY,3412.3,*"); + # rrd:vdef is broken in pnp4nagios 0.6.13 # $def[$id_watt] .= rrd::vdef("tot$KEY","var$KEY,TOTAL"); + $def[$id_watt] .= rrd::cdef("kwh$KEY", "var$KEY,POP,tot$KEY,1000,/,60,/,60,/"); + $def[$id_watt] .= rrd::cdef("btu$KEY", "kwh$KEY,3412.3,*"); - # fancy graphing - $def[$id_watt] .= rrd::gradient("var$KEY","#800000","#dc0000","$label", 10, "50%"); + # fancy graphing + $def[$id_watt] .= rrd::gradient("var$KEY", "#800000", "#dc0000", "$label", 10, "50%"); - # print avg, max and min - $def[$id_watt] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%6.0lf W"); + # print avg, max and min + $def[$id_watt] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf W"); - # print kWh and BTU for time period - $def[$id_watt] .= rrd::comment("\\s"); - $def[$id_watt] .= rrd::comment(" Total power used in time period\:"); - $def[$id_watt] .= rrd::gprint("kwh$KEY","AVERAGE","%10.2lf kWh\l"); - $def[$id_watt] .= rrd::comment(" "); - $def[$id_watt] .= rrd::gprint("btu$KEY","AVERAGE","%10.2lf BTU\l"); - } + # print kWh and BTU for time period + $def[$id_watt] .= rrd::comment("\\s"); + $def[$id_watt] .= rrd::comment(" Total power used in time period\:"); + $def[$id_watt] .= rrd::gprint("kwh$KEY", "AVERAGE", "%10.2lf kWh\l"); + $def[$id_watt] .= rrd::comment(" "); + $def[$id_watt] .= rrd::gprint("btu$KEY", "AVERAGE", "%10.2lf BTU\l"); + } - # AMPERAGE PROBE - if (preg_match('/^A/', $label)) { + # AMPERAGE PROBE + if (preg_match('/^A/', $label)) { + $first = 0; + if ($visited_amp == 0) { + $first = 1; + $visited_amp = 1; + } - $first = 0; - if ($visited_amp == 0) { - $first = 1; - $visited_amp = 1; - } + # Long label + $label = preg_replace('/^A(\d+)_(.+)/', '$2', $label); + $label = preg_replace('/_/', ' ', $label); - # Long label - $label = preg_replace('/^A(\d+)_(.+)/', '$2', $label); - $label = preg_replace('/_/', ' ', $label); + # Short label + $label = preg_replace('/^A(\d+)$/', 'Probe $1', $label); - # Short label - $label = preg_replace('/^A(\d+)$/', 'Probe $1', $label); + $ds_name[$id_amp] = "Amperage Probes"; + $vlabel = "Ampere"; - $ds_name[$id_amp] = "Amperage Probes"; - $vlabel = "Ampere"; + $title = $ds_name[$id_amp]; - $title = $ds_name[$id_amp]; + $opt[$id_amp] = "-X0 --lower-limit 0 --slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; + if (isset($def[$id_amp])) { + $def[$id_amp] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + } else { + $def[$id_amp] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + } - $opt[$id_amp] = "-X0 --lower-limit 0 --slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; - if(isset($def[$id_amp])){ - $def[$id_amp] .= rrd::def("var$KEY",$VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - } - else { - $def[$id_amp] = rrd::def("var$KEY",$VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - } + $space = strlen($label) < 16 ? str_repeat(' ', 16 - strlen($label)) : ' '; - $space = strlen($label) < 16 ? str_repeat(' ', 16 - strlen($label)) : ' '; + $def[$id_amp] .= rrd::cdef("tier$KEY", "var$KEY,10,/"); + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "b7::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "bf::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "c7::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "cf::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "d7::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "df::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "e7::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "ef::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "f7::STACK "; + $def[$id_amp] .= "AREA:tier$KEY#" . $colors[$a] . "ff:\"$label$space\":STACK "; + $a++; - $def[$id_amp] .= rrd::cdef("tier$KEY", "var$KEY,10,/"); - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."b7::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."bf::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."c7::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."cf::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."d7::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."df::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."e7::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."ef::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."f7::STACK "; - $def[$id_amp] .= "AREA:tier$KEY#".$colors[$a]."ff:\"$label$space\":STACK "; - $a++; + if ($first) { + $def[$id_amp] .= rrd::cdef("sum$KEY", "var$KEY,0,+"); + } else { + $def[$id_amp] .= rrd::cdef("sum$KEY", "sum" . ($KEY - 1) . ",var$KEY,+"); + } + $def[$id_amp] .= rrd::line1("sum$KEY", "#555555"); + $def[$id_amp] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.1lf A last") ; + } - if ($first) { - $def[$id_amp] .= rrd::cdef("sum$KEY", "var$KEY,0,+"); - } - else { - $def[$id_amp] .= rrd::cdef("sum$KEY", "sum".($KEY-1).",var$KEY,+"); - } - $def[$id_amp] .= rrd::line1("sum$KEY", "#555555"); - $def[$id_amp] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%6.1lf A last") ; - } + # VOLTAGE PROBE + if (preg_match('/^V/', $label)) { + # Long label + $label = preg_replace('/^V(\d+)_(.+)/', '$2', $label); + $label = preg_replace('/_/', ' ', $label); - # VOLTAGE PROBE - if (preg_match('/^V/', $label)) { + # Short label + $label = preg_replace('/^V(\d+)$/', 'Probe $1', $label); - # Long label - $label = preg_replace('/^V(\d+)_(.+)/', '$2', $label); - $label = preg_replace('/_/', ' ', $label); + $ds_name[$id_volt] = "Voltage Probes"; + $vlabel = "Volts"; - # Short label - $label = preg_replace('/^V(\d+)$/', 'Probe $1', $label); - - $ds_name[$id_volt] = "Voltage Probes"; - $vlabel = "Volts"; + $title = $ds_name[$id_volt]; - $title = $ds_name[$id_volt]; + $opt[$id_volt] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; + if (isset($def[$id_volt])) { + $def[$id_volt] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + } else { + $def[$id_volt] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + } + $def[$id_volt] .= rrd::line1("var$KEY", "#" . $colors[$v++], rrd::cut($label, 18)) ; + $def[$id_volt] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%8.2lf A"); + } - $opt[$id_volt] = "--slope-mode --vertical-label \"$vlabel\" --title \"$def_title: $title\" "; - if(isset($def[$id_volt])){ - $def[$id_volt] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'],"AVERAGE"); - } - else { - $def[$id_volt] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'],"AVERAGE"); - } - $def[$id_volt] .= rrd::line1("var$KEY", "#".$colors[$v++], rrd::cut($label,18) ) ; - $def[$id_volt] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%8.2lf A"); - } + # FANS (RPMs) + if (preg_match('/^F/', $label)) { + # Long label + $label = preg_replace('/^F(\d+)_(.+)/', '$2', $label); + $label = preg_replace('/_/', ' ', $label); - # FANS (RPMs) - if (preg_match('/^F/', $label)) { + # Short label + $label = preg_replace('/^F(\d+)$/', 'Probe $1', $label); - # Long label - $label = preg_replace('/^F(\d+)_(.+)/', '$2', $label); - $label = preg_replace('/_/', ' ', $label); + $ds_name[$id_fan] = "Fan Probes"; - # Short label - $label = preg_replace('/^F(\d+)$/', 'Probe $1', $label); + $opt[$id_fan] = "-X0 --slope-mode --vertical-label \"RPMs\" --title \"$def_title: Fan Speeds\" "; + if (isset($def[$id_fan])) { + $def[$id_fan] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$id_fan] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } + $def[$id_fan] .= rrd::line1("var$KEY", "#" . $colors[$f++], rrd::cut($label, 18)) ; + $def[$id_fan] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf RPM"); + } - $ds_name[$id_fan] = "Fan Probes"; + # ENCLOSURE TEMPERATURES (Celsius) + if (preg_match('/^E(?P.+?)_t(emp_)?(?P\d+)/', $label, $matches)) { + $this_id = $matches['encl']; + $probe_index = $matches['probe']; - $opt[$id_fan] = "-X0 --slope-mode --vertical-label \"RPMs\" --title \"$def_title: Fan Speeds\" "; - if(isset($def[$id_fan])){ - $def[$id_fan] .= rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'], "AVERAGE") ; - } - else { - $def[$id_fan] = rrd::def("var$KEY",$VAL['RRDFILE'],$VAL['DS'], "AVERAGE") ; - } - $def[$id_fan] .= rrd::line1("var$KEY", "#".$colors[$f++], rrd::cut($label,18) ) ; - $def[$id_fan] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.0lf RPM"); - } - - # ENCLOSURE TEMPERATURES (Celsius) - if (preg_match('/^E(?P.+?)_t(emp_)?(?P\d+)/', $label, $matches)) { + if ($enclosure_id != $this_id) { + $e = 0; + $id_enc++; + $enclosure_id = $this_id; + } - $this_id = $matches['encl']; - $probe_index = $matches['probe']; + # Label + $label = "Probe $probe_index"; - if ($enclosure_id != $this_id) { - $e = 0; - $id_enc++; - $enclosure_id = $this_id; - } + $ds_name[$id_enc] = "Enclosure $enclosure_id Temperatures"; - # Label - $label = "Probe $probe_index"; + $opt[$id_enc] = "--slope-mode --vertical-label \"Celsius\" --title \"$def_title: Enclosure $enclosure_id Temperatures\" "; - $ds_name[$id_enc] = "Enclosure $enclosure_id Temperatures"; - - $opt[$id_enc] = "--slope-mode --vertical-label \"Celsius\" --title \"$def_title: Enclosure $enclosure_id Temperatures\" "; - - if(isset($def[$id_enc])){ - $def[$id_enc] .= rrd::def("var$KEY", $VAL['RRDFILE'],$VAL['DS'], "AVERAGE") ; - } - else { - $def[$id_enc] = rrd::def("var$KEY", $VAL['RRDFILE'],$VAL['DS'], "AVERAGE") ; - } - $def[$id_enc] .= rrd::line1("var$KEY", "#".$colors[$e++], rrd::cut($label, 14) ); - $def[$id_enc] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"),"%6.1lf C"); - } + if (isset($def[$id_enc])) { + $def[$id_enc] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } else { + $def[$id_enc] = rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE") ; + } + $def[$id_enc] .= rrd::line1("var$KEY", "#" . $colors[$e++], rrd::cut($label, 14)); + $def[$id_enc] .= rrd::gprint("var$KEY", array("LAST", "MAX", "AVERAGE"), "%6.1lf C"); + } } } - -?> diff --git a/share/pnp/templates.dist/check_oracle_connection-time.php b/share/pnp/templates.dist/check_oracle_connection-time.php index a96a383..da00ed5 100644 --- a/share/pnp/templates.dist/check_oracle_connection-time.php +++ b/share/pnp/templates.dist/check_oracle_connection-time.php @@ -1,15 +1,15 @@ +$def[1] .= "GPRINT:var1:LAST:\"%3.2lf %Ss LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%3.2lf %Ss MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%3.2lf %Ss AVERAGE \" "; diff --git a/share/pnp/templates.dist/check_oracle_health.php b/share/pnp/templates.dist/check_oracle_health.php index fd09e98..b2ce747 100644 --- a/share/pnp/templates.dist/check_oracle_health.php +++ b/share/pnp/templates.dist/check_oracle_health.php @@ -1,34 +1,24 @@ diff --git a/share/pnp/templates.dist/check_oracle_health_connection-time.php b/share/pnp/templates.dist/check_oracle_health_connection-time.php index b1438d2..106138f 100644 --- a/share/pnp/templates.dist/check_oracle_health_connection-time.php +++ b/share/pnp/templates.dist/check_oracle_health_connection-time.php @@ -1,15 +1,15 @@ +$def[1] .= "GPRINT:var1:LAST:\"%3.2lf LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%3.2lf MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%3.2lf AVERAGE \" "; diff --git a/share/pnp/templates.dist/check_oracle_health_pga-in-memory-sort-ratio.php b/share/pnp/templates.dist/check_oracle_health_pga-in-memory-sort-ratio.php index a664949..2e31d4d 100644 --- a/share/pnp/templates.dist/check_oracle_health_pga-in-memory-sort-ratio.php +++ b/share/pnp/templates.dist/check_oracle_health_pga-in-memory-sort-ratio.php @@ -1,7 +1,9 @@ +$def[1] .= "GPRINT:var1:LAST:\"%3.2lf %S%% LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%3.2lf %S%% MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%3.2lf %S%% AVERAGE \" "; diff --git a/share/pnp/templates.dist/check_oracle_health_redo-io-traffic.php b/share/pnp/templates.dist/check_oracle_health_redo-io-traffic.php index 7d2fd53..add4a44 100644 --- a/share/pnp/templates.dist/check_oracle_health_redo-io-traffic.php +++ b/share/pnp/templates.dist/check_oracle_health_redo-io-traffic.php @@ -1,7 +1,9 @@ +$def[1] .= "GPRINT:var1:LAST:\"%3.4lf MB/s LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%3.4lf MB/s MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%3.4lf MB/s AVERAGE \" "; diff --git a/share/pnp/templates.dist/check_oracle_health_switch-interval.php b/share/pnp/templates.dist/check_oracle_health_switch-interval.php index c0e6a56..5b6cec8 100644 --- a/share/pnp/templates.dist/check_oracle_health_switch-interval.php +++ b/share/pnp/templates.dist/check_oracle_health_switch-interval.php @@ -1,15 +1,15 @@ +$def[1] .= "GPRINT:var1:LAST:\"%3.1lf s LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%3.1lf s MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%3.1lf s AVERAGE \" "; diff --git a/share/pnp/templates.dist/check_oracle_health_tablespace-usage.php b/share/pnp/templates.dist/check_oracle_health_tablespace-usage.php index acefe8f..ea271c0 100644 --- a/share/pnp/templates.dist/check_oracle_health_tablespace-usage.php +++ b/share/pnp/templates.dist/check_oracle_health_tablespace-usage.php @@ -1,21 +1,22 @@ +$def[2] .= "GPRINT:var1:LAST:\"%6.2lf $UNIT[2] LAST \" "; +$def[2] .= "GPRINT:var1:MAX:\"%6.2lf $UNIT[2] MAX \" "; +$def[2] .= "GPRINT:var1:AVERAGE:\"%6.2lf $UNIT[2] AVERAGE \\n\" "; diff --git a/share/pnp/templates.dist/check_ping.php b/share/pnp/templates.dist/check_ping.php index 09c8458..f8305f0 100644 --- a/share/pnp/templates.dist/check_ping.php +++ b/share/pnp/templates.dist/check_ping.php @@ -1,8 +1,10 @@ diff --git a/share/pnp/templates.dist/check_ping_tick.php b/share/pnp/templates.dist/check_ping_tick.php index f191049..e82e74d 100644 --- a/share/pnp/templates.dist/check_ping_tick.php +++ b/share/pnp/templates.dist/check_ping_tick.php @@ -1,10 +1,12 @@ diff --git a/share/pnp/templates.dist/check_pnp_rrds.php b/share/pnp/templates.dist/check_pnp_rrds.php index 4ccc6ca..8e82734 100644 --- a/share/pnp/templates.dist/check_pnp_rrds.php +++ b/share/pnp/templates.dist/check_pnp_rrds.php @@ -1,8 +1,10 @@ diff --git a/share/pnp/templates.dist/check_smtp.php b/share/pnp/templates.dist/check_smtp.php deleted file mode 120000 index 5093505..0000000 --- a/share/pnp/templates.dist/check_smtp.php +++ /dev/null @@ -1 +0,0 @@ -response.php \ No newline at end of file diff --git a/share/pnp/templates.dist/check_smtp.php b/share/pnp/templates.dist/check_smtp.php new file mode 100644 index 0000000..5e07b15 --- /dev/null +++ b/share/pnp/templates.dist/check_smtp.php @@ -0,0 +1,15 @@ +MACRO['TIMET'] != ""){ - $def[1] .= "VRULE:".$this->MACRO['TIMET']."#000000:\"Last Service Check \\n\" "; +if ($this->MACRO['TIMET'] != "") { + $def[1] .= "VRULE:" . $this->MACRO['TIMET'] . "#000000:\"Last Service Check \\n\" "; } -?> diff --git a/share/pnp/templates.dist/check_snmp_int-full.php b/share/pnp/templates.dist/check_snmp_int-full.php new file mode 100644 index 0000000..69e8c96 --- /dev/null +++ b/share/pnp/templates.dist/check_snmp_int-full.php @@ -0,0 +1,41 @@ +MACRO['TIMET'] != "") { + $def[1] .= "VRULE:" . $this->MACRO['TIMET'] . "#000000:\"Last Service Check \\n\" "; +} diff --git a/share/pnp/templates.dist/check_snmp_int.php b/share/pnp/templates.dist/check_snmp_int.php index 59c9b6f..1ade6da 100644 --- a/share/pnp/templates.dist/check_snmp_int.php +++ b/share/pnp/templates.dist/check_snmp_int.php @@ -1,8 +1,10 @@ MACRO['TIMET'] != ""){ - $def[1] .= "VRULE:".$this->MACRO['TIMET']."#000000:\"Last Service Check \\n\" "; +if ($this->MACRO['TIMET'] != "") { + $def[1] .= "VRULE:" . $this->MACRO['TIMET'] . "#000000:\"Last Service Check \\n\" "; } -?> diff --git a/share/pnp/templates.dist/check_swap.php b/share/pnp/templates.dist/check_swap.php index 2ab5e38..40d7982 100644 --- a/share/pnp/templates.dist/check_swap.php +++ b/share/pnp/templates.dist/check_swap.php @@ -1,26 +1,27 @@ diff --git a/share/pnp/templates.dist/check_tcp.php b/share/pnp/templates.dist/check_tcp.php deleted file mode 120000 index 5093505..0000000 --- a/share/pnp/templates.dist/check_tcp.php +++ /dev/null @@ -1 +0,0 @@ -response.php \ No newline at end of file diff --git a/share/pnp/templates.dist/check_tcp.php b/share/pnp/templates.dist/check_tcp.php new file mode 100644 index 0000000..5e07b15 --- /dev/null +++ b/share/pnp/templates.dist/check_tcp.php @@ -0,0 +1,15 @@ + +$def[1] .= "GPRINT:var1:LAST:\"%.0lf $UNIT[1] LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%.0lf $UNIT[1] MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%.0lf $UNIT[1] AVERAGE \" "; diff --git a/share/pnp/templates.dist/default.php b/share/pnp/templates.dist/default.php index 823ee6a..a612f42 100644 --- a/share/pnp/templates.dist/default.php +++ b/share/pnp/templates.dist/default.php @@ -1,8 +1,9 @@ DS as $KEY=>$VAL) { +foreach ($this->DS as $KEY => $VAL) { + $maximum = ""; + $minimum = ""; + $critical = ""; + $crit_min = ""; + $crit_max = ""; + $warning = ""; + $warn_max = ""; + $warn_min = ""; + $vlabel = " "; + $lower = ""; + $upper = ""; - $maximum = ""; - $minimum = ""; - $critical = ""; - $crit_min = ""; - $crit_max = ""; - $warning = ""; - $warn_max = ""; - $warn_min = ""; - $vlabel = " "; - $lower = ""; - $upper = ""; - - if ($VAL['WARN'] != "" && is_numeric($VAL['WARN']) ){ - $warning = $VAL['WARN']; - } - if ($VAL['WARN_MAX'] != "" && is_numeric($VAL['WARN_MAX']) ) { - $warn_max = $VAL['WARN_MAX']; - } - if ( $VAL['WARN_MIN'] != "" && is_numeric($VAL['WARN_MIN']) ) { - $warn_min = $VAL['WARN_MIN']; - } - if ( $VAL['CRIT'] != "" && is_numeric($VAL['CRIT']) ) { - $critical = $VAL['CRIT']; - } - if ( $VAL['CRIT_MAX'] != "" && is_numeric($VAL['CRIT_MAX']) ) { - $crit_max = $VAL['CRIT_MAX']; - } - if ( $VAL['CRIT_MIN'] != "" && is_numeric($VAL['CRIT_MIN']) ) { - $crit_min = $VAL['CRIT_MIN']; - } - if ( $VAL['MIN'] != "" && is_numeric($VAL['MIN']) ) { - $lower = " --lower-limit=" . $VAL['MIN']; - $minimum = $VAL['MIN']; - } - if ( $VAL['MAX'] != "" && is_numeric($VAL['MAX']) ) { - $maximum = $VAL['MAX']; - } - if ($VAL['UNIT'] == "%%") { - $vlabel = "%"; - $upper = " --upper-limit=101 "; - $lower = " --lower-limit=0 "; - } - else { - $vlabel = $VAL['UNIT']; - } + if ($VAL['WARN'] != "" && is_numeric($VAL['WARN'])) { + $warning = $VAL['WARN']; + } + if ($VAL['WARN_MAX'] != "" && is_numeric($VAL['WARN_MAX'])) { + $warn_max = $VAL['WARN_MAX']; + } + if ($VAL['WARN_MIN'] != "" && is_numeric($VAL['WARN_MIN'])) { + $warn_min = $VAL['WARN_MIN']; + } + if ($VAL['CRIT'] != "" && is_numeric($VAL['CRIT'])) { + $critical = $VAL['CRIT']; + } + if ($VAL['CRIT_MAX'] != "" && is_numeric($VAL['CRIT_MAX'])) { + $crit_max = $VAL['CRIT_MAX']; + } + if ($VAL['CRIT_MIN'] != "" && is_numeric($VAL['CRIT_MIN'])) { + $crit_min = $VAL['CRIT_MIN']; + } + if ($VAL['MIN'] != "" && is_numeric($VAL['MIN'])) { + $lower = " --lower-limit=" . $VAL['MIN']; + $minimum = $VAL['MIN']; + } + if ($VAL['MAX'] != "" && is_numeric($VAL['MAX'])) { + $maximum = $VAL['MAX']; + } + if ($VAL['UNIT'] == "%%") { + $vlabel = "%"; + $upper = " --upper-limit=101 "; + $lower = " --lower-limit=0 "; + } else { + $vlabel = $VAL['UNIT']; + } - $opt[$KEY] = '--vertical-label "' . $vlabel . '" --title "' . $this->MACRO['DISP_HOSTNAME'] . ' / ' . $this->MACRO['DISP_SERVICEDESC'] . '"' . $upper . $lower; - $ds_name[$KEY] = $VAL['LABEL']; - $def[$KEY] = rrd::def ("var1", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$KEY] .= rrd::gradient("var1", "3152A5", "BDC6DE", rrd::cut($VAL['NAME'],16), 20); - $def[$KEY] .= rrd::line1 ("var1", $_LINE ); - $def[$KEY] .= rrd::gprint ("var1", array("LAST","MAX","AVERAGE"), "%3.4lf %S".$VAL['UNIT']); - if ($warning != "") { - $def[$KEY] .= rrd::hrule($warning, $_WARNRULE, "Warning $warning \\n"); - } - if ($warn_min != "") { - $def[$KEY] .= rrd::hrule($warn_min, $_WARNRULE, "Warning (min) $warn_min \\n"); - } - if ($warn_max != "") { - $def[$KEY] .= rrd::hrule($warn_max, $_WARNRULE, "Warning (max) $warn_max \\n"); - } - if ($critical != "") { - $def[$KEY] .= rrd::hrule($critical, $_CRITRULE, "Critical $critical \\n"); - } - if ($crit_min != "") { - $def[$KEY] .= rrd::hrule($crit_min, $_CRITRULE, "Critical (min) $crit_min \\n"); - } - if ($crit_max != "") { - $def[$KEY] .= rrd::hrule($crit_max, $_CRITRULE, "Critical (max) $crit_max \\n"); - } - $def[$KEY] .= rrd::comment("Default Template\\r"); - $def[$KEY] .= rrd::comment("Command " . $VAL['TEMPLATE'] . "\\r"); + if (!is_array($opt)) { + $opt = []; + } + if (!is_array($ds_name)) { + $ds_name = []; + } + if (!is_array($def)) { + $def = []; + } + + $opt[$KEY] = '--vertical-label "' . $vlabel . '" --title "' . $this->MACRO['DISP_HOSTNAME'] . ' / ' . $this->MACRO['DISP_SERVICEDESC'] . '"' . $upper . $lower; + $ds_name[$KEY] = $VAL['LABEL']; + $def[$KEY] = rrd::def("var1", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$KEY] .= rrd::gradient("var1", "3152A5", "BDC6DE", rrd::cut($VAL['NAME'], 16), 20); + $def[$KEY] .= rrd::line1("var1", $_LINE); + $def[$KEY] .= rrd::gprint("var1", array("LAST","MAX","AVERAGE"), "%3.4lf %S" . $VAL['UNIT']); + if ($warning != "") { + $def[$KEY] .= rrd::hrule($warning, $_WARNRULE, "Warning $warning \\n"); + } + if ($warn_min != "") { + $def[$KEY] .= rrd::hrule($warn_min, $_WARNRULE, "Warning (min) $warn_min \\n"); + } + if ($warn_max != "") { + $def[$KEY] .= rrd::hrule($warn_max, $_WARNRULE, "Warning (max) $warn_max \\n"); + } + if ($critical != "") { + $def[$KEY] .= rrd::hrule($critical, $_CRITRULE, "Critical $critical \\n"); + } + if ($crit_min != "") { + $def[$KEY] .= rrd::hrule($crit_min, $_CRITRULE, "Critical (min) $crit_min \\n"); + } + if ($crit_max != "") { + $def[$KEY] .= rrd::hrule($crit_max, $_CRITRULE, "Critical (max) $crit_max \\n"); + } + $def[$KEY] .= rrd::comment("Default Template\\r"); + $def[$KEY] .= rrd::comment("Command " . $VAL['TEMPLATE'] . "\\r"); } -?> diff --git a/share/pnp/templates.dist/icinga.php b/share/pnp/templates.dist/icinga.php index 1a9d423..72cc687 100644 --- a/share/pnp/templates.dist/icinga.php +++ b/share/pnp/templates.dist/icinga.php @@ -1,137 +1,153 @@ DS as $KEY=>$VAL) { - if(preg_match('/^(.*)_latency(.*)$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^(.*)_latency(.*)$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[1])); - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), $label ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), $label); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "Service Stats"'; $ds_name[$graph] = "Service Stats"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^(.*)num_services_(.*)$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^(.*)num_services_(.*)$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[2])); - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,25) ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 25)); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "Host Stats"'; $ds_name[$graph] = "Host Stats"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^(.*)num_hosts_(.*)$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^(.*)num_hosts_(.*)$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[2])); - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,25) ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 25)); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "Check Execution Time" --vertical-label "seconds"'; $ds_name[$graph] = "Execution Time"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^(.*)_execution_time(.*)$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^(.*)_execution_time(.*)$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[1])); - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,25) ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 25)); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "Work Queue Items" --vertical-label "items"'; $ds_name[$graph] = "Work Queue Items"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^api_num_(.*)_queue_items$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^api_num_(.*)_queue_items$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[1])); - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,25) ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 25)); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "Work Queue Rate" --vertical-label "items/s"'; $ds_name[$graph] = "Work Queue Rate"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^api_num_(.*)_queue_item_rate$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^api_num_(.*)_queue_item_rate$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[1])); - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,25) ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 25)); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "Check Rate" --vertical-label "checks/s"'; $ds_name[$graph] = "Check Rate"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^(.*)_checks$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^(.*)_checks$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[1])); - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,25) ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 25)); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "IDO MySQL Queries" --vertical-label "queries/s"'; $ds_name[$graph] = "IDO MySQL Queries"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^(idomysqlconnection_ido-mysql_queries_rate)$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^(idomysqlconnection_ido-mysql_queries_rate)$/', $VAL['NAME'], $matches)) { $i++; $label = "mysql_queries"; - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,15) ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 15)); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -if($i > 0) $graph++; +if ($i > 0) { + $graph++; +} $opt[$graph] = '--title "Endpoints"'; $ds_name[$graph] = "Endpoints"; $def[$graph] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^api_num_(.*)_endpoints$/', $VAL['NAME'], $matches)){ +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^api_num_(.*)_endpoints$/', $VAL['NAME'], $matches)) { $i++; $label = ucfirst(strtolower($matches[1])) . 'ected'; $colorarea = ($label == 'Connected') ? '#2ECC71' : '#E74C3C'; - $def[$graph] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[$graph] .= rrd::area ("var$KEY", $colorarea, rrd::cut($label,25), 'STACK' ); - $def[$graph] .= rrd::gprint ("var$KEY", array("LAST"), "%8.0lf"); + $def[$graph] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[$graph] .= rrd::area("var$KEY", $colorarea, rrd::cut($label, 25), 'STACK'); + $def[$graph] .= rrd::gprint("var$KEY", array("LAST"), "%8.0lf"); } } - -?> diff --git a/share/pnp/templates.dist/integer.php b/share/pnp/templates.dist/integer.php index 9a62c89..e4c4fd5 100644 --- a/share/pnp/templates.dist/integer.php +++ b/share/pnp/templates.dist/integer.php @@ -1,36 +1,38 @@ $VAL ){ - $opt[1] .= "--alt-y-grid -l 0 --vertical-label \"$LABEL[$KEY]\" --title \"$LABEL[$KEY]\" "; - $def[1] .= "DEF:var_float$KEY=$RRDFILE[$KEY]:$DS[$KEY]:MAX " ; - $def[1] .= "CDEF:var$KEY=var_float$KEY,FLOOR " ; - $def[1] .= "LINE1:var$KEY" . getRandomColor() . ":\"$LABEL[$KEY]\" " ; +foreach ($DS as $KEY => $VAL) { + $opt[1] .= "--alt-y-grid -l 0 --vertical-label \"$LABEL[$KEY]\" --title \"$LABEL[$KEY]\" "; + $def[1] .= "DEF:var_float$KEY=$RRDFILE[$KEY]:$DS[$KEY]:MAX " ; + $def[1] .= "CDEF:var$KEY=var_float$KEY,FLOOR " ; + $def[1] .= "LINE1:var$KEY" . getRandomColor() . ":\"$LABEL[$KEY]\" " ; - if ($WARN[$KEY] != "") { - $def[1] .= "HRULE:$WARN[$KEY]#FFFF00 "; - } - if ($CRIT[$KEY] != "") { - $def[1] .= "HRULE:$CRIT[$KEY]#FF0000 "; - } + if ($WARN[$KEY] != "") { + $def[1] .= "HRULE:$WARN[$KEY]#FFFF00 "; + } + if ($CRIT[$KEY] != "") { + $def[1] .= "HRULE:$CRIT[$KEY]#FF0000 "; + } - $def[1] .= "GPRINT:var$KEY:LAST:\"%.0lf $UNIT[$KEY] LAST \" "; - $def[1] .= "GPRINT:var$KEY:MAX:\"%.0lf $UNIT[$KEY] MAX \" "; - $def[1] .= "GPRINT:var$KEY:AVERAGE:\"%.0lf $UNIT[$KEY] AVERAGE \\n\" "; + $def[1] .= "GPRINT:var$KEY:LAST:\"%.0lf $UNIT[$KEY] LAST \" "; + $def[1] .= "GPRINT:var$KEY:MAX:\"%.0lf $UNIT[$KEY] MAX \" "; + $def[1] .= "GPRINT:var$KEY:AVERAGE:\"%.0lf $UNIT[$KEY] AVERAGE \\n\" "; } # thanks to: http://stackoverflow.com/questions/10708965/generate-random-colors -function getRandomColor() { +// phpcs:disable PSR1.Files.SideEffects +function getRandomColor() +{ $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'); - $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)]; + $color = '#' . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)] . $rand[rand(0, 15)]; return $color; } - -?> diff --git a/share/pnp/templates.dist/nagiostats.php b/share/pnp/templates.dist/nagiostats.php index 3a3f64d..2fe4588 100644 --- a/share/pnp/templates.dist/nagiostats.php +++ b/share/pnp/templates.dist/nagiostats.php @@ -1,62 +1,62 @@ DS as $KEY=>$VAL) { - if(preg_match('/(.*)LAT$/', $VAL['NAME'], $matches)){ - $i++; - $label = ucfirst(strtolower($matches[1])); - $def[0] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[0] .= rrd::cdef ("var_sec$KEY", "var$KEY,1000,/"); - $def[0] .= rrd::line1 ("var_sec$KEY", rrd::color($i), rrd::cut($label,10) ); - $def[0] .= rrd::gprint ("var_sec$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/(.*)LAT$/', $VAL['NAME'], $matches)) { + $i++; + $label = ucfirst(strtolower($matches[1])); + $def[0] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[0] .= rrd::cdef("var_sec$KEY", "var$KEY,1000,/"); + $def[0] .= rrd::line1("var_sec$KEY", rrd::color($i), rrd::cut($label, 10)); + $def[0] .= rrd::gprint("var_sec$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } $opt[1] = '--title "Service Stats"'; $ds_name[1] = "Service Stats"; $def[1] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^NUMSVC(.*)$/', $VAL['NAME'], $matches)){ - $i++; - $label = ucfirst(strtolower($matches[1])); - $def[1] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[1] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,10) ); - $def[1] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^NUMSVC(.*)$/', $VAL['NAME'], $matches)) { + $i++; + $label = ucfirst(strtolower($matches[1])); + $def[1] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[1] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 10)); + $def[1] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } $opt[2] = '--title "Host Stats"'; $ds_name[2] = "Host Stats"; $def[2] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/^NUMHST(.*)$/', $VAL['NAME'], $matches)){ - $i++; - $label = ucfirst(strtolower($matches[1])); - $def[2] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[2] .= rrd::line1 ("var$KEY", rrd::color($i), rrd::cut($label,10) ); - $def[2] .= rrd::gprint ("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/^NUMHST(.*)$/', $VAL['NAME'], $matches)) { + $i++; + $label = ucfirst(strtolower($matches[1])); + $def[2] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[2] .= rrd::line1("var$KEY", rrd::color($i), rrd::cut($label, 10)); + $def[2] .= rrd::gprint("var$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } $opt[3] = '--title "Check Execution Time"'; $ds_name[3] = "Execution Time"; $def[3] = ""; $i = 0; -foreach ($this->DS as $KEY=>$VAL) { - if(preg_match('/(.*)EXT$/', $VAL['NAME'], $matches)){ - $i++; - $label = ucfirst(strtolower($matches[1])); - $def[3] .= rrd::def ("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); - $def[3] .= rrd::cdef ("var_sec$KEY", "var$KEY,1000,/"); - $def[3] .= rrd::line1 ("var_sec$KEY", rrd::color($i), rrd::cut($label,10) ); - $def[3] .= rrd::gprint ("var_sec$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); +foreach ($this->DS as $KEY => $VAL) { + if (preg_match('/(.*)EXT$/', $VAL['NAME'], $matches)) { + $i++; + $label = ucfirst(strtolower($matches[1])); + $def[3] .= rrd::def("var$KEY", $VAL['RRDFILE'], $VAL['DS'], "AVERAGE"); + $def[3] .= rrd::cdef("var_sec$KEY", "var$KEY,1000,/"); + $def[3] .= rrd::line1("var_sec$KEY", rrd::color($i), rrd::cut($label, 10)); + $def[3] .= rrd::gprint("var_sec$KEY", array("LAST","MAX","AVERAGE"), "%8.2lf"); } } -?> diff --git a/share/pnp/templates.dist/pnp-runtime.php b/share/pnp/templates.dist/pnp-runtime.php index 21c4ae3..cf9b8a1 100644 --- a/share/pnp/templates.dist/pnp-runtime.php +++ b/share/pnp/templates.dist/pnp-runtime.php @@ -1,10 +1,13 @@ STRUCT['TIMERANGE']['end']; $ds_name[1] = "Runtime"; $def[1] = rrd::def("var1", $RRDFILE[1], $DS[1], "AVERAGE") ; -$def[1] .= rrd::cdef("t_var1","var1,14400,TREND"); +$def[1] .= rrd::cdef("t_var1", "var1,14400,TREND"); if ($WARN[1] != "") { - $def[1] .= rrd::hrule($WARN[1], "#FFFF00"); + $def[1] .= rrd::hrule($WARN[1], "#FFFF00"); } if ($CRIT[1] != "") { - $def[1] .= rrd::hrule($CRIT[1], "#FF0000"); + $def[1] .= rrd::hrule($CRIT[1], "#FF0000"); } -$def[1] .= rrd::gradient("var1", "ffffff", "#33cccc", rrd::cut("Runtime",10)); -$def[1] .= rrd::line1("var1","#339999"); +$def[1] .= rrd::gradient("var1", "ffffff", "#33cccc", rrd::cut("Runtime", 10)); +$def[1] .= rrd::line1("var1", "#339999"); $def[1] .= rrd::gprint("var1", array('LAST', 'MAX', 'AVERAGE'), "%6.2lf$UNIT[1]") ; -$def[1] .= rrd::line1("t_var1", "#ff9999", rrd::cut("4h trend",10)); +$def[1] .= rrd::line1("t_var1", "#ff9999", rrd::cut("4h trend", 10)); $def[1] .= rrd::gprint("t_var1", array('LAST', 'MAX', 'AVERAGE'), "%6.2lf$UNIT[1]") ; # -# Lines processed and RRD errors +# Lines processed and RRD errors # $opt[2] = "--vertical-label \"Counter\" --title \"Number of updates\" "; # @@ -34,9 +37,8 @@ $opt[2] = "--vertical-label \"Counter\" --title \"Number of updates\" "; # $ds_name[2] = "Errors and updates"; $def[2] = ''; -for($i=2; $i <= sizeof($DS); $i++) { -$def[2] .= rrd::def("var$i", $RRDFILE[$i], $DS[$i] , "AVERAGE") ; -$def[2] .= rrd::line1("var$i", rrd::color($i), rrd::cut(ucfirst($LABEL[$i]),12) ); -$def[2] .= rrd::gprint("var$i", array('LAST', 'MAX', 'AVERAGE'), "%4.0lf$UNIT[$i]"); +for ($i = 2; $i <= count($DS); $i++) { + $def[2] .= rrd::def("var$i", $RRDFILE[$i], $DS[$i], "AVERAGE") ; + $def[2] .= rrd::line1("var$i", rrd::color($i), rrd::cut(ucfirst($LABEL[$i]), 12)); + $def[2] .= rrd::gprint("var$i", array('LAST', 'MAX', 'AVERAGE'), "%4.0lf$UNIT[$i]"); } -?> diff --git a/share/pnp/templates.dist/response.php b/share/pnp/templates.dist/response.php index af9dd99..5e07b15 100644 --- a/share/pnp/templates.dist/response.php +++ b/share/pnp/templates.dist/response.php @@ -1,15 +1,15 @@ +$def[1] .= "GPRINT:var1:LAST:\"%3.4lg %s$UNIT[1] LAST \" "; +$def[1] .= "GPRINT:var1:MAX:\"%3.4lg %s$UNIT[1] MAX \" "; +$def[1] .= "GPRINT:var1:AVERAGE:\"%3.4lg %s$UNIT[1] AVERAGE \" "; diff --git a/share/pnp/templates.special/advanced_loop.php-sample b/share/pnp/templates.special/advanced_loop.php-sample index a64fb22..93e6ab4 100644 --- a/share/pnp/templates.special/advanced_loop.php-sample +++ b/share/pnp/templates.special/advanced_loop.php-sample @@ -1,34 +1,44 @@ MACRO['TITLE'] = "Interface Traffic for ETH0"; +$this->MACRO['TITLE'] = "Interface Traffic for ETH0"; $this->MACRO['COMMENT'] = "Inbound Traffc for all Cloud Nodes"; # -# Get a List of Services by regex +# Get a List of Services by regex # Option 1 = 'Host Regex' # Option 2 = 'Service Regex' # -$services = $this->tplGetServices("node","eth0"); +$services = $this->tplGetServices("node", "eth0"); # # The Datasource Name for Graph 0 -$ds_name[0] = "RTA Times"; +if (!is_array($ds_name)) { + $ds_name = []; +} +if (!is_arry($opt)) { + $opt = []; +} +if (!is_array($def)) { + $def = []; +} + +$ds_name[0] = "RTA Times"; $opt[0] = "--title \"Stacked RTA Times\""; $def[0] = ""; # # Iterate through the list of hosts -foreach($services as $key=>$val){ +foreach ($services as $key => $val) { # # get the data for a given Host/Service - $a = $this->tplGetData($val['host'],$val['service']); + $a = $this->tplGetData($val['host'], $val['service']); # # Throw an exception to debug the content of $a # Just to get Infos about the Array Structure # #throw new Kohana_exception(print_r($a,TRUE)); - $def[0] .= rrd::def("a$key" ,$a['DS'][0]['RRDFILE'], $a['DS'][0]['DS'], "AVERAGE"); + $def[0] .= rrd::def("a$key", $a['DS'][0]['RRDFILE'], $a['DS'][0]['DS'], "AVERAGE"); $def[0] .= rrd::area("a$key", rrd::color($key), $a['MACRO']['HOSTNAME'], "STACK"); $def[0] .= rrd::gprint("a$key", array("MIN", "MAX", "LAST"), "%.2lf%s"); } -?> diff --git a/share/pnp/templates.special/loop.php-sample b/share/pnp/templates.special/loop.php-sample index 103ba1c..900ac21 100644 --- a/share/pnp/templates.special/loop.php-sample +++ b/share/pnp/templates.special/loop.php-sample @@ -1,8 +1,18 @@ MACRO['TITLE'] = "The Title"; +$this->MACRO['TITLE'] = "The Title"; $this->MACRO['COMMENT'] = "A Comment"; # # Define the Service we want to graph @@ -12,17 +22,16 @@ $service = '_HOST_'; $hosts = array('localhost','node1','node2'); # # The Datasource Name for Graph 1 ( index 0 ) -$ds_name[0] = "RTA Times"; +$ds_name[0] = "RTA Times"; $opt[0] = "--title \"Stacked RTA Times\""; $def[0] = ""; # # Iterate through the list of hosts -foreach($hosts as $key=>$host){ +foreach ($hosts as $key => $host) { # # get the data for a given Host/Service - $a = $this->tplGetData($host,$service); - $def[0] .= rrd::def("a$key" ,$a['DS'][0]['RRDFILE'], $a['DS'][0]['DS'], "AVERAGE"); + $a = $this->tplGetData($host, $service); + $def[0] .= rrd::def("a$key", $a['DS'][0]['RRDFILE'], $a['DS'][0]['DS'], "AVERAGE"); $def[0] .= rrd::area("a$key", rrd::color($key), $a['MACRO']['HOSTNAME'], "STACK"); $def[0] .= rrd::gprint("a$key", array("MIN", "MAX", "LAST"), "%.2lf%s"); } -?> diff --git a/share/pnp/templates.special/static.php-sample b/share/pnp/templates.special/static.php-sample index 30aac5e..0bc3ecd 100644 --- a/share/pnp/templates.special/static.php-sample +++ b/share/pnp/templates.special/static.php-sample @@ -1,19 +1,28 @@ MACRO['TITLE'] = "All Ping Times for Cluster Nodes"; +# Some Macros +$this->MACRO['TITLE'] = "All Ping Times for Cluster Nodes"; $this->MACRO['COMMENT'] = "This is a comment"; # # The Name of this Datasource (ds) -$ds_name[0] = "RTA Times"; +$ds_name[0] = "RTA Times"; $opt[0] = "--title \"Graph Title\" "; $def[0] = "DEF:var1=/usr/local/pnp4nagios/var/perfdata/node1/_HOST_.rrd:1:AVERAGE "; $def[0] .= "DEF:var2=/usr/local/pnp4nagios/var/perfdata/node2/_HOST_.rrd:1:AVERAGE "; -$def[0] .= "LINE1:var1".rrd::color(1).":\"Localhost \\n\" "; -$def[0] .= "LINE1:var2".rrd::color(2).":\"Node1 \\n\" "; -?> +$def[0] .= "LINE1:var1" . rrd::color(1) . ":\"Localhost \\n\" "; +$def[0] .= "LINE1:var2" . rrd::color(2) . ":\"Node1 \\n\" "; diff --git a/src/.gitignore b/src/.gitignore new file mode 100644 index 0000000..a3f0216 --- /dev/null +++ b/src/.gitignore @@ -0,0 +1,7 @@ +*.o +npcd +pnpsender +utils +Makefile +config.c +npcdmod.c diff --git a/src/Makefile.in b/src/Makefile.in index b4323b4..1eb038e 100644 --- a/src/Makefile.in +++ b/src/Makefile.in @@ -32,7 +32,6 @@ MOD_CFLAGS=@MOD_CFLAGS@ prefix=@prefix@ exec_prefix=@exec_prefix@ LOGDIR=@localstatedir@ -CFGDIR=@sysconfdir@ BINDIR=@bindir@ LIBEXECDIR=@libexecdir@ LIBDIR=@libdir@ @@ -113,6 +112,8 @@ devclean: distclean ############################### # # Install +# leaving out npcdmod.o since +# Nagios changed plugin API # ################################ @@ -124,14 +125,14 @@ install-unstripped: $(MAKE) install-basic install-basic: - $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(BINDIR) + $(INSTALL) -m 755 -d $(DESTDIR)$(BINDIR) $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(LIBDIR) $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(LOGDIR) $(INSTALL) -m 755 $(INSTALL_OPTS) -d $(DESTDIR)$(PERFDATA_DIR) $(INSTALL) -m 775 $(INSTALL_OPTS) -d $(DESTDIR)$(PERFDATA_SPOOL_DIR) - $(INSTALL) -m 754 $(INSTALL_OPTS) @npcd_name@ $(DESTDIR)$(BINDIR) - $(INSTALL) -m 754 $(INSTALL_OPTS) npcdmod.o $(DESTDIR)$(LIBDIR) + $(INSTALL) -m 755 npcd $(DESTDIR)$(BINDIR) + #$(INSTALL) -m 754 $(INSTALL_OPTS) npcdmod.o $(DESTDIR)$(LIBDIR) strip-post-install: - $(STRIP) $(DESTDIR)$(BINDIR)/@npcd_name@ - $(STRIP) $(DESTDIR)$(LIBDIR)/npcdmod.o + $(STRIP) $(DESTDIR)$(BINDIR)/npcd + #$(STRIP) $(DESTDIR)$(LIBDIR)/npcdmod.o diff --git a/src/config.c b/src/config.c.in similarity index 97% rename from src/config.c rename to src/config.c.in index 08183a8..33e3633 100644 --- a/src/config.c +++ b/src/config.c.in @@ -63,10 +63,12 @@ void process_configfile(char *config_file) { while (feof(fh_config_file) == 0) { line_number++; temp = fgets(current_config_line, 1024, fh_config_file); - temp = NULL; - if (current_config_line == NULL) { - printf("Error reading config\n"); - exit(1); + if (temp == NULL) { + if (ferror(fh_config_file) != 0) { + printf("Error reading config\n"); + exit(1); + } + break; } if (current_config_line[0] == '#' || current_config_line[0] == '\n') @@ -554,7 +556,7 @@ int prepare_vars() { if (macro_x[CONFIG_OPT_SCANDIR] != NULL) { directory = macro_x[CONFIG_OPT_SCANDIR]; } else { - directory = "/usr/local/nagios/var/spool/perfdata/"; + directory = "@PERFDATA_SPOOL_DIR@/"; printf( "WARNING - Adapting a hardcoded default perfdata spooldir - '%s'\n", directory); @@ -563,7 +565,7 @@ int prepare_vars() { if (macro_x[CONFIG_OPT_PIDFILE] != NULL) { pidfile = macro_x[CONFIG_OPT_PIDFILE]; } else - pidfile = "/var/run/npcd.pid"; + pidfile = "@piddir@/npcd.pid"; if (macro_x[CONFIG_OPT_LOGLEVEL] != NULL) { loglevel = atoi(macro_x[CONFIG_OPT_LOGLEVEL]); diff --git a/src/npcd.c b/src/npcd.c index d266255..e95ebcb 100644 --- a/src/npcd.c +++ b/src/npcd.c @@ -185,7 +185,7 @@ int main(int argc, char **argv) { strerror(errno)); exit(EXIT_FAILURE); } else { - fprintf(fppid, "%d", getpid()); + fprintf(fppid, "%d\n", getpid()); fclose(fppid); } } @@ -245,7 +245,7 @@ int main(int argc, char **argv) { filecounter, directory); LOG(2, buffer); - for (i = 0, namelist; i < filecounter; i++) { + for (i = 0; i < filecounter; i++) { #ifdef HAVE_GETLOADAVG if (use_load_threshold == TRUE) { @@ -356,7 +356,7 @@ int main(int argc, char **argv) { if (we_should_stop == TRUE) break; - for (i = 0, namelist; i < filecounter; i++) { + for (i = 0; i < filecounter; i++) { free(namelist[i]); } @@ -479,7 +479,7 @@ int process_arguments(int argc, char **argv) { printf("\t\tPath to config file\n"); printf("\n"); printf( - "Visit the Website at http://sourceforge.net/projects/pnp4nagios/ for bug fixes, \n"); + "Visit the Website at https://github.com/pnp4nagios for bug fixes, \n"); printf("new releases, online documentation, FAQs, Mailinglists.\n"); printf("\n"); diff --git a/src/npcdmod.c b/src/npcdmod.c.in similarity index 97% rename from src/npcdmod.c rename to src/npcdmod.c.in index cfd2565..19a8b69 100644 --- a/src/npcdmod.c +++ b/src/npcdmod.c.in @@ -45,9 +45,9 @@ extern int process_performance_data; FILE *fp = NULL; void *npcdmod_module_handle = NULL; -char *perfdata_file = "/usr/local/nagios/var/perfdata"; +char *perfdata_file = "@PERFDATA_DIR@/perf.data"; char *perfdata_spool_filename = "perfdata"; -char *spool_dir = NULL; +char *spool_dir = "@PERFDATA_SPOOL_DIR@"; char *perfdata_file_processing_interval = "15"; void npcdmod_file_roller(); @@ -166,6 +166,14 @@ void npcdmod_file_roller() { /* move the original file */ result = my_rename(perfdata_file, spool_file); + if (result != 0) { + snprintf(temp_buffer, sizeof(temp_buffer) - 1, + "npcdmod: Could not rename perfdata file. %s", strerror(errno)); + temp_buffer[sizeof(temp_buffer) - 1] = '\x0'; + write_to_all_logs(temp_buffer, NSLOG_INFO_MESSAGE); + return; + } + /* open a new file */ if ((fp = fopen(perfdata_file, "a")) == NULL) { diff --git a/src/pnpsender.c b/src/pnpsender.c index ece4b32..b17ce5c 100644 --- a/src/pnpsender.c +++ b/src/pnpsender.c @@ -239,7 +239,7 @@ int process_arguments(int argc, char **argv) { " like \"serviceperfdata\", \"hostperfdata\", \"eventhandler\"\n"); printf("\n\n"); printf( - "Visit the PNP website at http://www.pnp4nagios.org/pnp/ for bug fixes, new\n"); + "Visit the PNP website at https://github.com/pnp4nagios for bug fixes, new\n"); printf( "releases, online documentation, FAQs, information on subscribing to\n"); printf("the mailing lists.\n"); diff --git a/src/utils.c b/src/utils.c index 991d3bd..b8ea1bf 100644 --- a/src/utils.c +++ b/src/utils.c @@ -207,7 +207,7 @@ void check_sig(int signr) { break; default: - snprintf(buffer, sizeof(buffer - 1), + snprintf(buffer, MAX_LOGMESSAGE_SIZE - 1, "Caught the Signal '%d' but don't care about this.\n", signr); LOG(2, buffer); break; diff --git a/subst.in b/subst.in index 9e8685b..0df3979 100755 --- a/subst.in +++ b/subst.in @@ -1,4 +1,4 @@ -#!@PERL@ -w +#!@PERL@ -w -*- perl -*- my ${prefix}="@prefix@"; @@ -23,7 +23,9 @@ if($INSTALL =~ /^\.\//){ $INSTALL =~ s/^\.\//\.\.\//; } my $INSTALL_OPTS="@INSTALL_OPTS@"; -my $DEBUG="@DEBUG@"; +my $DEBUG_LEVEL="@DEBUG_LEVEL@"; +my $SELINUX="@SELINUX@"; +my $PNP_LOGDIR="@PNP_LOGDIR@"; my $PERFDATA_DIR="@PERFDATA_DIR@"; my $PERFDATA_LOG="@PERFDATA_LOG@"; my $PERFDATA_SPOOL_DIR="@PERFDATA_SPOOL_DIR@"; @@ -31,11 +33,13 @@ my $RRDTOOL="@RRDTOOL@"; my $RRDS="@RRDS@"; my $XML_STRUCTURE_VERSION="@XML_STRUCTURE_VERSION@"; my $PKG_REL_DATE="@PKG_REL_DATE@"; -my $PKG_VERSION="@PKG_VERSION@"; -my $PKG_NAME="@PKG_NAME@"; -my $BASE_URL="@BASE_URL@"; -my $HTTPD_CONF="@HTTPD_CONF@"; -my $init_dir="@init_dir@"; +my $PACKAGE_VERSION="@PACKAGE_VERSION@"; +my $PACKAGE_NAME="@PACKAGE_NAME@"; +my $PNP_URL="@PNP_URL@"; +my $NAGIOS_CFG="@NAGIOS_CFG@"; +my $NAGIOS_VER="@NAGIOS_VER@"; +my $HTTP_CONFDIR="@HTTP_CONFDIR@"; +my $initdir="@initdir@"; my $npcd_name="@npcd_name@"; my $pp_pl_name="@pp_pl_name@"; my $nagios_user="@nagios_user@"; @@ -46,6 +50,7 @@ my $KOHANA="@KOHANA@"; my $KOHANA_SYSTEM="@KOHANA_SYSTEM@"; my $libdir="@libdir@"; my $sysconfdir="@sysconfdir@"; +my $pkgsysconfdir="@pkgsysconfdir@"; my $host_os="@host_os@"; my $ac_configure_args="@ac_configure_args@"; @@ -86,7 +91,9 @@ while ($f = shift @ARGV) { s|\@STRIP\@|$STRIP|g; s|\@INSTALL\@|$INSTALL|g; s|\@INSTALL_OPTS\@|$INSTALL_OPTS|g; - s|\@DEBUG\@|$DEBUG|g; + s|\@DEBUG_LEVEL\@|$DEBUG_LEVEL|g; + s|\@SELINUX\@|$SELINUX|g; + s|\@PNP_LOGDIR\@|$PNP_LOGDIR|g; s|\@PERFDATA_DIR\@|$PERFDATA_DIR|g; s|\@PERFDATA_LOG\@|$PERFDATA_LOG|g; s|\@PERFDATA_SPOOL_DIR\@|$PERFDATA_SPOOL_DIR|g; @@ -94,10 +101,12 @@ while ($f = shift @ARGV) { s|\@RRDS\@|$RRDS|g; s|\@XML_STRUCTURE_VERSION\@|$XML_STRUCTURE_VERSION|g; s|\@PKG_REL_DATE\@|$PKG_REL_DATE|g; - s|\@PKG_VERSION\@|$PKG_VERSION|g; - s|\@PKG_NAME\@|$PKG_NAME|g; - s|\@BASE_URL\@|$BASE_URL|g; - s|\@HTTPD_CONF\@|$HTTPD_CONF|g; + s|\@PACKAGE_VERSION\@|$PACKAGE_VERSION|g; + s|\@PACKAGE_NAME\@|$PACKAGE_NAME|g; + s|\@PNP_URL\@|$PNP_URL|g; + s|\@NAGIOS_CFG\@|$NAGIOS_CFG|g; + s|\@NAGIOS_VER\@|$NAGIOS_VER|g; + s|\@HTTP_CONFDIR\@|$HTTP_CONFDIR|g; s|\@npcd_name\@|$npcd_name|g; s|\@pp_pl_name\@|$pp_pl_name|g; s|\@nagios_user\@|$nagios_user|g; @@ -107,8 +116,9 @@ while ($f = shift @ARGV) { s|\@KOHANA\@|$KOHANA|g; s|\@KOHANA_SYSTEM\@|$KOHANA_SYSTEM|g; s|\@libdir\@|$libdir|g; - s|\@init_dir\@|$init_dir|g; + s|\@initdir\@|$initdir|g; s|\@sysconfdir\@|$sysconfdir|g; + s|\@pkgsysconfdir\@|$pkgsysconfdir|g; s|\@datarootdir\@|$datarootdir|g; s|\@datadir\@|$datadir|g; s|\@sbindir\@|$sbindir|g; diff --git a/summary.in b/summary.in index 43b4242..30d6359 100644 --- a/summary.in +++ b/summary.in @@ -1,10 +1,10 @@ -#@PERL@ -w -@PERL_LIB_PATH_CODE@ +#!@PERL@ -w -*- perl -*- +@PERL_LIB_PATH_CODE@ my %conf = ( - VERSION => "@PKG_VERSION@", + VERSION => "@PACKAGE_VERSION@", USE_RRDs => "@RRDS@", - DEBUG_LEVEL => "@DEBUG@", + DEBUG_LEVEL => "@DEBUG_LEVEL@", PERL_LIB_PATH => "@PERL_LIB_PATH@" ); @@ -23,19 +23,24 @@ my $RRD_BINARY = "@RRDTOOL@"; @v = split(/ /,$T[0]); $rrdtool_version = $v[1]; $rrdtool_message = ""; -if($rrdtool_version == ""){ +if($rrdtool_version eq ""){ $rrdtool_message = "WARNING: \"$RRD_BINARY\" does not look like rrdtool"; }else{ $rrdtool_message = "$RRD_BINARY Version $rrdtool_version"; } +$prefix = '' unless defined $prefix; + printf ("\n\n"); -printf ("*** Configuration summary for %s-%s %s ***","@PKG_NAME@","@PKG_VERSION@","@PKG_REL_DATE@"); +printf ("*** Configuration summary for %s-%s %s ***","@PACKAGE_NAME@","@PACKAGE_VERSION@","@PKG_REL_DATE@"); printf ("\n\n"); printf (" General Options:\n"); printf (" ------------------------- -------------------\n"); printf (" Nagios user/group: %s %s\n","@nagios_user@","@nagios_grp@"); printf (" Install directory: %s\n","@prefix@"); +printf (" SELINUX enabled: %s\n","@SELINUX@"); +printf (" Nagios cfg file: %s\n","@NAGIOS_CFG@"); +printf (" Nagios version %s\n","@NAGIOS_VER@"); printf (" HTML Dir: %s\n","@datarootdir@"); printf (" Config Dir: %s\n","@sysconfdir@"); printf (" Location of rrdtool binary: %s\n",$rrdtool_message); @@ -48,8 +53,8 @@ printf (" Perfdata files (NPCD) stored in: %s\n","@PERFDATA_SPOOL_DIR@"); printf ("\n"); printf (" Web Interface Options:\n"); printf (" ------------------------- -------------------\n"); -printf (" HTML URL: %s\n","http://localhost@BASE_URL@"); -printf (" Apache Config File: %s\n","@HTTPD_CONF@/@PKG_NAME@.conf"); +printf (" HTML URL: %s\n","http://localhost@PNP_URL@"); +printf (" HTTP server config File: %s\n","@HTTP_CONFDIR@/@PACKAGE_NAME@.conf"); if( $#ARGV == -1){ printf ("\n\n"); printf (" Review the options above for accuracy. If they look okay,\n"); @@ -70,7 +75,7 @@ if($conf{DEBUG_LEVEL} != 0){ printf ("\n\n"); printf (" Found PERL at: %s\n","@PERL@"); printf (" Found SHELL at: %s\n","@SHELL@"); - printf (" Debug Level: %s\n","@DEBUG@"); + printf (" Debug Level: %s\n","@DEBUG_LEVEL@"); printf (" Libexecdir: %s\n","@libexecdir@"); printf (" localstatedir: %s\n","@localstatedir@"); printf (" libdir: %s\n","@libdir@");