From eb07593088e2dcf8a397133e938296e0ae1a69c7 Mon Sep 17 00:00:00 2001
From: Garvin Hicking <blog@garv.in>
Date: Mon, 19 May 2014 11:12:47 +0200
Subject: [PATCH] Change logger to only be instantiated when explicitly enabled
 to not cause unneccessary debugging especially in dev-installations
 References #131

---
 docs/NEWS                            |  4 +--
 include/functions_trackbacks.inc.php | 46 ++++++++++++++--------------
 include/tpl/config_local.inc.php     |  2 +-
 index.php                            |  2 +-
 lang/addlang.txt                     |  7 +----
 serendipity_config.inc.php           | 15 +++------
 6 files changed, 32 insertions(+), 44 deletions(-)

diff --git a/docs/NEWS b/docs/NEWS
index fb8bf088..1efefe40 100644
--- a/docs/NEWS
+++ b/docs/NEWS
@@ -26,8 +26,8 @@ Version 2.0-beta3 ()
       using 2k11 (=default) in the backend.
 
     * Include klogger, call it as $serendipity['logger']->debug/error.
-      The log-level is by default determined automatically, but can also
-      be set in the general configuration.
+      The log-level can be set in the general configuration and is
+      disabled by default.
 
     * Fixed missing s9ymdb ID
 
diff --git a/include/functions_trackbacks.inc.php b/include/functions_trackbacks.inc.php
index 83b244f2..2b8bcf2f 100644
--- a/include/functions_trackbacks.inc.php
+++ b/include/functions_trackbacks.inc.php
@@ -668,14 +668,14 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
     static $old_references = array();
     static $saved_references = array();
     static $saved_urls = array();
-    $serendipity['logger']->debug("serendipity_handle_references");
+    if (is_object($serendipity['logger'])) $serendipity['logger']->debug("serendipity_handle_references");
 
     if ($dry_run) {
         // Store the current list of references. We might need to restore them for later user.
         $old_references = serendipity_db_query("SELECT * FROM {$serendipity['dbPrefix']}references WHERE (type = '' OR type IS NULL) AND entry_id = " . (int)$id, false, 'assoc');
 
         if (is_string($old_references)) {
-            $serendipity['logger']->debug($old_references);
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug($old_references);
         }
 
         if (is_array($old_references) && count($old_references) > 0) {
@@ -686,14 +686,14 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
                 $saved_urls[$old_reference['link']] = true;
             }
         }
-        $serendipity['logger']->debug("Got references in dry run: " . print_r($current_references, true));
+        if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Got references in dry run: " . print_r($current_references, true));
     } else {
         // A dry-run was called previously and restorable references are found. Restore them now.
         $del = serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}references WHERE (type = '' OR type IS NULL) AND entry_id = " . (int)$id);
         if (is_string($del)) {
-            $serendipity['logger']->debug($del);
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug($del);
         }
-        $serendipity['logger']->debug("Deleted references");
+        if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Deleted references");
 
         if (is_array($old_references) && count($old_references) > 0) {
             $current_references = array();
@@ -703,12 +703,12 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
                 $q = serendipity_db_insert('references', $old_reference, 'show');
                 $cr = serendipity_db_query($q);
                 if (is_string($cr)) {
-                    $serendipity['logger']->debug($cr);
+                    if (is_object($serendipity['logger'])) $serendipity['logger']->debug($cr);
                 }
             }
         }
 
-        $serendipity['logger']->debug("Got references in final run:" . print_r($current_references, true));
+        if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Got references in final run:" . print_r($current_references, true));
     }
 
     if (!preg_match_all('@<a[^>]+?href\s*=\s*["\']?([^\'" >]+?)[ \'"][^>]*>(.+?)</a>@i', $text, $matches)) {
@@ -730,13 +730,13 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
     $checked_locations = array();
     serendipity_plugin_api::hook_event('backend_trackbacks', $locations);
     for ($i = 0, $j = count($locations); $i < $j; ++$i) {
-        $serendipity['logger']->debug("Checking {$locations[$i]}...");
+        if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Checking {$locations[$i]}...");
         if ($locations[$i][0] == '/') {
             $locations[$i] = 'http' . (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) != 'off' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $locations[$i];
         }
 
         if (isset($checked_locations[$locations[$i]])) {
-            $serendipity['logger']->debug("Already checked");
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Already checked");
             continue;
         }
 
@@ -757,41 +757,41 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
 
         $row = serendipity_db_query($query, true, 'num');
         if (is_string($row)) {
-            $serendipity['logger']->debug($row);
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug($row);
         }
         
         $names[$i] = strip_tags($names[$i]);
         if (empty($names[$i])) {
-            $serendipity['logger']->debug("Found reference $locations[$i] w/o name. Adding location as name");
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Found reference $locations[$i] w/o name. Adding location as name");
             $names[$i] = $locations[$i];
         }
 
         if ($row[0] > 0 && isset($saved_references[$locations[$i] . $names[$i]])) {
-            $serendipity['logger']->debug("Found references for $id, skipping rest");
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Found references for $id, skipping rest");
             continue;
         }
 
         if (!isset($serendipity['noautodiscovery']) || !$serendipity['noautodiscovery']) {
             if (!$dry_run) {
                 if (!isset($saved_urls[$locations[$i]])){
-                    $serendipity['logger']->debug("Enabling autodiscovery");
+                    if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Enabling autodiscovery");
                     serendipity_reference_autodiscover($locations[$i], $url, $author, $title, serendipity_trackback_excerpt($text));
                 } else {
-                    $serendipity['logger']->debug("This reference was already used before in $id and therefore will not be trackbacked again");
+                    if (is_object($serendipity['logger'])) $serendipity['logger']->debug("This reference was already used before in $id and therefore will not be trackbacked again");
                 }
             } else {
-                $serendipity['logger']->debug("Dry run: Skipping autodiscovery");
+                if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Dry run: Skipping autodiscovery");
             }
             $checked_locations[$locations[$i]] = true; // Store trackbacked link so that no further trackbacks will be sent to the same link
         } else {
-            $serendipity['logger']->debug("Skipping full autodiscovery");
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Skipping full autodiscovery");
         }
     }
     $del = serendipity_db_query("DELETE FROM {$serendipity['dbPrefix']}references WHERE entry_id=" . (int)$id . " AND (type = '' OR type IS NULL)");
     if (is_string($del)) {
-        $serendipity['logger']->debug($del);
+        if (is_object($serendipity['logger'])) $serendipity['logger']->debug($del);
     }
-    $serendipity['logger']->debug("Deleted references again");
+    if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Deleted references again");
 
     if (!is_array($old_references)) {
         $old_references = array();
@@ -812,7 +812,7 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
             $query .= (int)$current_references[$locations[$i] . $names[$i]]['id'] . ", " . (int)$id . ", '" . $i_link . "', '" . $i_location . "')";
             $ins = serendipity_db_query($query);
             if (is_string($ins)) {
-                $serendipity['logger']->debug($ins);
+                if (is_object($serendipity['logger'])) $serendipity['logger']->debug($ins);
             }
             $duplicate_check[$locations[$i] . $names[$i]] = true;
         } else {
@@ -832,11 +832,11 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
             $duplicate_check[$i_location . $i_link] = true;
         }
 
-        $serendipity['logger']->debug("Current lookup for {$locations[$i]}{$names[$i]} is" . print_r($current_references[$locations[$i] . $names[$i]], true));
-        $serendipity['logger']->debug($query);
+        if (is_object($serendipity['logger'])) $serendipity['logger']->debug("Current lookup for {$locations[$i]}{$names[$i]} is" . print_r($current_references[$locations[$i] . $names[$i]], true));
+        if (is_object($serendipity['logger'])) $serendipity['logger']->debug($query);
     }
 
-        $serendipity['logger']->debug(print_r($old_references, true));
+    if (is_object($serendipity['logger'])) $serendipity['logger']->debug(print_r($old_references, true));
 
     // Add citations
     preg_match_all('@<cite[^>]*>([^<]+)</cite>@i', $text, $matches);
@@ -847,7 +847,7 @@ function serendipity_handle_references($id, $author, $title, $text, $dry_run = f
 
         $cite = serendipity_db_query($query);
         if (is_string($cite)) {
-            $serendipity['logger']->debug($cite);
+            if (is_object($serendipity['logger'])) $serendipity['logger']->debug($cite);
         }
     }
 }
diff --git a/include/tpl/config_local.inc.php b/include/tpl/config_local.inc.php
index c37b32c8..fd80ae43 100644
--- a/include/tpl/config_local.inc.php
+++ b/include/tpl/config_local.inc.php
@@ -408,7 +408,7 @@
                                           'title'       => LOG_LEVEL,  
                                           'description' => LOG_LEVEL_DESC,
                                           'type'        => 'list',
-                                          'default'     => array('Automatic' => AUTOMATIC, 'error' => ERROR, 'debug' => DEBUG), # i18n
+                                          'default'     => array('Off' => NO, 'error' => ERROR, 'debug' => DEBUG), # i18n
                                           'permission'  => 'blogConfiguration'),
                             ));
 
diff --git a/index.php b/index.php
index 5694a8be..08e14645 100644
--- a/index.php
+++ b/index.php
@@ -672,6 +672,6 @@ if (!defined('NO_EXIT')) {
     $serendipity['smarty']->display(serendipity_getTemplateFile($serendipity['smarty_file'], 'serendipityPath'));
 }
 
-$serendipity['logger']->debug('Page delivered in '. round(microtime_float()-$time_start,6) .' seconds, '. sizeof(get_included_files()) .' files included');
+if (is_object($serendipity['logger'])) $serendipity['logger']->debug('Page delivered in '. round(microtime_float()-$time_start,6) .' seconds, '. sizeof(get_included_files()) .' files included');
 
 /* vim: set sts=4 ts=4 expandtab : */
diff --git a/lang/addlang.txt b/lang/addlang.txt
index 17675f26..17d48b14 100644
--- a/lang/addlang.txt
+++ b/lang/addlang.txt
@@ -1,10 +1,5 @@
-@define('FRONTEND', 'Frontend');
-@define('BACKEND', 'Backend');
-
 @define('MEDIA_UPLOAD_RESIZE', 'Resize before Upload');
 @define('MEDIA_UPLOAD_RESIZE_DESC', 'Resize images before the upload using Javascript. This will also change the uploader to use Ajax and thus remove the Property-Button');
-
 @define('LOG_LEVEL', 'Log Level');
-@define('LOG_LEVEL_DESC', 'The logger can react to the s9y status and debug in RC-version and smaller, but only log errors in produciton. Or the level can be set manually.');
+@define('LOG_LEVEL_DESC', 'At certain places in the Serendipity code we have placed debugging breakpoints. If this option is set to "Debug", it will write this debug output to templates_c/logs/. You should only enable this option if you are experiencing bugs in those areas, or if you are a developer. Setting this option to "Error" will enable logging PHP errors, overwriting the PHP error_log setting.');
 @define('DEBUG', 'Debug');
-@define('AUTOMATIC', 'Automatisch');
\ No newline at end of file
diff --git a/serendipity_config.inc.php b/serendipity_config.inc.php
index d1bd0b04..6916a1e1 100644
--- a/serendipity_config.inc.php
+++ b/serendipity_config.inc.php
@@ -310,23 +310,16 @@ if (defined('USE_MEMSNAP')) {
 serendipity_load_configuration();
 $serendipity['lang'] = serendipity_getSessionLanguage();
 
-if (! isset($serendipity['logLevel']) || $serendipity['logLevel'] === 'Automatic') {
-    if ($serendipity['production'] != true) {
+if (isset($serendipity['logLevel']) && $serendipity['logLevel'] !== 'Off') {
+    if ($serendipity['logLevel'] == 'debug') {
         $log_level = Psr\Log\LogLevel::DEBUG;
     } else {
         $log_level = Psr\Log\LogLevel::ERROR;
     }
+    
+    $serendipity['logger'] = new Katzgrau\KLogger\Logger($serendipity['serendipityPath'] . '/templates_c/logs', $log_level);
 }
 
-if ($serendipity['logLevel'] == 'error') {
-    $log_level = Psr\Log\LogLevel::ERROR;
-}
-if ($serendipity['logLevel'] == 'debug') {
-    $log_level = Psr\Log\LogLevel::DEBUG;
-}
-
-$serendipity['logger'] = new Katzgrau\KLogger\Logger($serendipity['serendipityPath'] . '/templates_c/logs', $log_level);
-
 if ( (isset($serendipity['autodetect_baseURL']) && serendipity_db_bool($serendipity['autodetect_baseURL'])) ||
      (isset($serendipity['embed']) && serendipity_db_bool($serendipity['embed'])) ) {
     $serendipity['baseURL'] = 'http' . (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . (!strstr($_SERVER['HTTP_HOST'], ':') && !empty($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != '80' && $_SERVER['SERVER_PORT'] != '443' ? ':' . $_SERVER['SERVER_PORT'] : '') . $serendipity['serendipityHTTPPath'];