From 9da4e321f853a291808349753f9f41cd766b014a Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 6 Jan 2023 11:25:53 +0900 Subject: [PATCH 01/49] Code cleanup --- assets/plugins/qm/qm.inc.php | 316 +++++++++++++++++++---------------- 1 file changed, 171 insertions(+), 145 deletions(-) diff --git a/assets/plugins/qm/qm.inc.php b/assets/plugins/qm/qm.inc.php index 3fff247f90..607762b2b1 100755 --- a/assets/plugins/qm/qm.inc.php +++ b/assets/plugins/qm/qm.inc.php @@ -13,38 +13,66 @@ class Qm { var $modx; //_______________________________________________________ - function __construct(&$modx, $jqpath='', $loadmanagerjq='', $loadfrontendjq='', $noconflictjq='', $loadfa='', $loadtb='', $tbwidth='', $tbheight='', $hidefields='', $hidetabs='', $hidesections='', $addbutton='', $tpltype='', $tplid='', $custombutton='', $managerbutton='', $logout='', $autohide='', $position='', $editbuttons='', $editbclass='', $newbuttons='', $newbclass='', $tvbuttons='', $tvbclass='', $buttonStyle='', $removeBg='') { + function __construct(&$modx, + $jqpath = '', + $loadmanagerjq = '', + $loadfrontendjq = '', + $noconflictjq = '', + $loadfa = '', + $loadtb = '', + $tbwidth = '', + $tbheight = '', + $hidefields = '', + $hidetabs = '', + $hidesections = '', + $addbutton = '', + $tpltype = '', + $tplid = '', + $custombutton = '', + $managerbutton = '', + $logout = '', + $autohide = '', + $position = '', + $editbuttons = '', + $editbclass = '', + $newbuttons = '', + $newbclass = '', + $tvbuttons = '', + $tvbclass = '', + $buttonStyle = '', + $removeBg = '') + { $this->modx = $modx; // Get plugin parameters - $this->jqpath = $jqpath; - $this->loadmanagerjq = $loadmanagerjq; + $this->jqpath = $jqpath; + $this->loadmanagerjq = $loadmanagerjq; $this->loadfrontendjq = $loadfrontendjq; - $this->noconflictjq = $noconflictjq; - $this->loadfa = $loadfa; - $this->loadtb = $loadtb; - $this->tbwidth = $tbwidth; - $this->tbheight = $tbheight; - $this->usemm = null; - $this->hidefields = $hidefields; - $this->hidetabs = $hidetabs; - $this->hidesections = $hidesections; - $this->addbutton = $addbutton; - $this->tpltype = $tpltype; - $this->tplid = $tplid; - $this->custombutton = $custombutton; - $this->managerbutton = $managerbutton; - $this->logout = $logout; - $this->autohide = $autohide; - $this->position = $position; - $this->editbuttons = $editbuttons; - $this->editbclass = $editbclass; - $this->newbuttons = $newbuttons; - $this->newbclass = $newbclass; - $this->tvbuttons = $tvbuttons; - $this->tvbclass = $tvbclass; - $this->buttonStyle = $buttonStyle; - $this->removeBg = $removeBg; + $this->noconflictjq = $noconflictjq; + $this->loadfa = $loadfa; + $this->loadtb = $loadtb; + $this->tbwidth = $tbwidth; + $this->tbheight = $tbheight; + $this->usemm = null; + $this->hidefields = $hidefields; + $this->hidetabs = $hidetabs; + $this->hidesections = $hidesections; + $this->addbutton = $addbutton; + $this->tpltype = $tpltype; + $this->tplid = $tplid; + $this->custombutton = $custombutton; + $this->managerbutton = $managerbutton; + $this->logout = $logout; + $this->autohide = $autohide; + $this->position = $position; + $this->editbuttons = $editbuttons; + $this->editbclass = $editbclass; + $this->newbuttons = $newbuttons; + $this->newbclass = $newbclass; + $this->tvbuttons = $tvbuttons; + $this->tvbclass = $tvbclass; + $this->buttonStyle = $buttonStyle; + $this->removeBg = $removeBg; // Includes include_once($this->modx->config['base_path'].'assets/plugins/qm/mcc.class.php'); @@ -63,7 +91,9 @@ function Run() { $manager_language = $this->modx->config['manager_language']; // Individual user language setting (if set) - if (isset($_SESSION['mgrUsrConfigSet']['manager_language'])) $manager_language = $_SESSION['mgrUsrConfigSet']['manager_language']; + if (isset($_SESSION['mgrUsrConfigSet']['manager_language'])) { + $manager_language = $_SESSION['mgrUsrConfigSet']['manager_language']; + } // Include_once the language file if(!isset($manager_language) || !file_exists(MODX_MANAGER_PATH."includes/lang/".$manager_language.".inc.php")) { @@ -73,7 +103,7 @@ function Run() { include_once MODX_MANAGER_PATH."includes/lang/english.inc.php"; // Include user language - if($manager_language!="english" && file_exists(MODX_MANAGER_PATH."includes/lang/".$manager_language.".inc.php")) { + if($manager_language !== 'english' && file_exists(MODX_MANAGER_PATH."includes/lang/".$manager_language.".inc.php")) { include_once MODX_MANAGER_PATH."includes/lang/".$manager_language.".inc.php"; } @@ -87,7 +117,7 @@ function Run() { case 'OnDocFormSave': // Saving process for Qm only - if(intval($_REQUEST['quickmanager']) == 1) { + if((int)$_REQUEST['quickmanager'] == 1) { $id = $e->params['id']; $key = $id; @@ -95,19 +125,19 @@ function Run() { // Normal saving document procedure stops to redirect => Before redirecting secure documents and clear cache // Secure web documents - flag as private (code from: processors/save_content.processor.php) - include $this->modx->config['site_manager_path']."includes/secure_web_documents.inc.php"; - secureWebDocument($key); + include $this->modx->config['site_manager_path']."includes/secure_web_documents.inc.php"; + secureWebDocument($key); // Secure manager documents - flag as private (code from: processors/save_content.processor.php) - include $this->modx->config['site_manager_path']."includes/secure_mgr_documents.inc.php"; - secureMgrDocument($key); + include $this->modx->config['site_manager_path']."includes/secure_mgr_documents.inc.php"; + secureMgrDocument($key); // Clear cache $this->modx->clearCache('full'); // Different doc to be refreshed than the one we are editing? if (isset($_POST['qmrefresh'])) { - $id = intval($_POST['qmrefresh']); + $id = (int)$_POST['qmrefresh']; } // Redirect to clearer page which refreshes parent window and closes modal box frame @@ -151,7 +181,7 @@ function Run() { } // QM+ TV edit - if(intval($_GET['quickmanagertv'] == 1) && $_GET['tvname'] != '' && $this->tvbuttons == 'true') { + if((int)($_GET['quickmanagertv'] == 1) && $_GET['tvname'] != '' && $this->tvbuttons == 'true') { $tvName = ''; $locked = FALSE; @@ -165,7 +195,7 @@ function Run() { include_once(MODX_MANAGER_PATH.'includes/tmplvars.format.inc.php'); // Get save status - if (isset($_POST['save'])) $save = intval($_POST['save']); + if (isset($_POST['save'])) $save = (int)$_POST['save']; // Get TV name if (preg_match('/^([^\\"\'\(\)<>!?]+)/i', $_GET['tvname'])) $tvName = $_GET['tvname']; @@ -184,7 +214,9 @@ function Run() { } // Check TV access - if (!$access) { $access = $this->checkTvAccess($tv['id']); } + if (!$access) { + $access = $this->checkTvAccess($tv['id']); + } // User can access TV if ($access) { @@ -193,13 +225,14 @@ function Run() { if ($save == 0) { // Check is document locked? Someone else is editing the document... //$_lang['lock_msg'] - if ($this->checkLocked()) $locked = TRUE; - - // Set document locked - else $this->setLocked(1); + if ($this->checkLocked()) { + $locked = TRUE; + } else { + $this->setLocked(1); + } // Handle RTE - if($tv['type'] == 'richtext') { + if($tv['type'] === 'richtext') { // Invoke OnRichTextEditorInit event $eventOutput = $this->modx->invokeEvent("OnRichTextEditorInit", array('editor'=>$this->modx->config['which_editor'], 'elements'=>array('tv'.$tvName))); @@ -212,12 +245,12 @@ function Run() { $tvHtml = renderFormElement($tv['type'], $tv['name'], $tv['default_text'], $tv['elements'], $tv['value']); // Get jQuery conflict mode - if ($this->noconflictjq == 'true') $jq_mode = '$j'; - else $jq_mode = '$'; - } - - // Save TV - else { + if ($this->noconflictjq == 'true') { + $jq_mode = '$j'; + } else { + $jq_mode = '$'; + } + } else { // Remove document locked $this->setLocked(0); @@ -255,7 +288,7 @@ function Run() { // Normal form else { // Image preview - if ($tv['type'] == 'image') { + if ($tv['type'] === 'image') { $imagePreview = '
@@ -330,7 +363,7 @@ function Run() { // QM+ with toolbar else { - if(isset($_SESSION['mgrValidated']) && $_REQUEST['z'] != 'manprev') { + if(isset($_SESSION['mgrValidated']) && $_REQUEST['z'] !== 'manprev') { // If logout break here if(isset($_REQUEST['logout'])) { @@ -341,7 +374,7 @@ function Run() { $userID = $_SESSION['mgrInternalKey']; // Add ID - $controls .= '
  • ID: '.$docID.'
  • '; + $controls = '
  • ID: '.$docID.'
  • '; // Go to Manager button if ($this->managerbutton == 'true') { $managerButton = ' @@ -374,7 +407,9 @@ function Run() { '; // Does user have permissions to add document - if($this->modx->hasPermission('new_document')) $controls .= $addButton; + if($this->modx->hasPermission('new_document')) { + $controls .= $addButton; + } } // Custom add buttons if not empty and enough permissions @@ -406,9 +441,7 @@ function Run() { // Button visible for all if ($buttonParams[4] == '') { $showButton = TRUE; - } - // Button is visible for specific user roles - else { + } else { $showButton = FALSE; // Get user roles the button is visible for @@ -455,8 +488,6 @@ function Run() { } } - - // Logout button $logout = $this->modx->config['site_manager_url'].'index.php?a=8&quickmanager=logout&logoutid='.$docID; $logoutButton = ' @@ -472,7 +503,7 @@ function Run() { $editor = '
    -
    +
    • @@ -482,7 +513,7 @@ function Run() {
    • '.$controls.'
    -
    '; +
    '; $MGR_DIR = $this->modx->getManagerPath( ); $css = ' @@ -499,7 +530,7 @@ function Run() { '; } // Buttons Styles - if ($this->buttonStyle == 'actionButtons') { + if ($this->buttonStyle === 'actionButtons') { $css .= ' '; @@ -511,7 +542,7 @@ function Run() { '; } // Top toolbar Autohide false - if (($this->autohide == 'false') && ($this->position == 'top')) { + if (($this->autohide == 'false') && ($this->position === 'top')) { $css .= ' '; @@ -701,7 +732,7 @@ function Run() { if (($this->removeBg == 'yes') && ($this->buttonStyle == 'navButtons')) { $css .= ' - - ' . $str . ''; + + + + + ' . $str . ''; } else { echo 'Error'; @@ -6648,17 +6665,17 @@ public function getHiddenIdFromAlias($parentid, $alias) `children`.`id` AS `child_id`, children.alias AS `child_alias`, COUNT(`grandsons`.`id`) AS `grandsons_count` - FROM " . $table ." AS `sc` - JOIN " . $table . " AS `children` ON `children`.`parent` = `sc`.`id` - LEFT JOIN " . $table . " AS `grandsons` ON `grandsons`.`parent` = `children`.`id` - WHERE `sc`.`parent` = '" . (int)$parentid . "' AND `sc`.`alias_visible` = '0' - GROUP BY `children`.`id`"); + FROM " . $table ." AS `sc` + JOIN " . $table . " AS `children` ON `children`.`parent` = `sc`.`id` + LEFT JOIN " . $table . " AS `grandsons` ON `grandsons`.`parent` = `children`.`id` + WHERE `sc`.`parent` = '" . (int)$parentid . "' AND `sc`.`alias_visible` = '0' + GROUP BY `children`.`id`"); while ($child = $this->db->getRow($query)) { if ($child['child_alias'] == $alias || $child['child_id'] == $alias) { $out = $child['child_id']; break; - } else if ($child['grandsons_count'] > 0 && ($id = $this->getHiddenIdFromAlias($child['hidden_id'], $alias))) { + } elseif ($child['grandsons_count'] > 0 && ($id = $this->getHiddenIdFromAlias($child['hidden_id'], $alias))) { $out = $id; break; } From af194ff92d60739990877bf2f5c7c806bdfa1ae1 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 6 Jan 2023 11:31:13 +0900 Subject: [PATCH 03/49] refactor $modx->sendRedirect() --- manager/includes/document.parser.class.inc.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index b8583e01ab..f97311b852 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -326,6 +326,10 @@ public function sendRedirect($url, $count_attempts = false, $type = 'REDIRECT_HE if (empty ($url)) { return false; } + if (strpos($url, "\n") !== false) { + $this->messageQuit('No newline allowed in redirect url.'); + exit; + } if ($count_attempts) { // append the redirect count string to the url $currentNumberOfRedirects = $_GET['err'] ?? 0; @@ -364,10 +368,6 @@ public function sendRedirect($url, $count_attempts = false, $type = 'REDIRECT_HE header($responseCode); } - if (strpos($url, "\n") !== false) { - $this->messageQuit('No newline allowed in redirect url.'); - exit; - } if (strpos($url, MODX_BASE_URL) === 0) { $url = MODX_SITE_URL . substr($url, strlen(MODX_BASE_URL)); } From 9f4478722df1d0d2aebda7ca502f2137a1370748 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 6 Jan 2023 11:31:34 +0900 Subject: [PATCH 04/49] refactor qm --- assets/plugins/qm/qm.inc.php | 123 ++++++++++++++++++++--------------- 1 file changed, 71 insertions(+), 52 deletions(-) diff --git a/assets/plugins/qm/qm.inc.php b/assets/plugins/qm/qm.inc.php index 607762b2b1..368bb67605 100755 --- a/assets/plugins/qm/qm.inc.php +++ b/assets/plugins/qm/qm.inc.php @@ -141,12 +141,9 @@ function Run() { } // Redirect to clearer page which refreshes parent window and closes modal box frame - if ($this->modx->config['friendly_urls'] == 1){ - $this->modx->sendRedirect($this->modx->makeUrl($id).'?quickmanagerclose=1', 0, 'REDIRECT_HEADER', 'HTTP/1.1 301 Moved Permanently'); - }else{ - $this->modx->sendRedirect($this->modx->makeUrl($id).'&quickmanagerclose=1', 0, 'REDIRECT_HEADER', 'HTTP/1.1 301 Moved Permanently'); - } - + $this->modx->sendRedirect( + $this->modx->makeUrl($id,null,'quickmanagerclose=1'), null, 'REDIRECT_JS' + ); } break; @@ -198,19 +195,31 @@ function Run() { if (isset($_POST['save'])) $save = (int)$_POST['save']; // Get TV name - if (preg_match('/^([^\\"\'\(\)<>!?]+)/i', $_GET['tvname'])) $tvName = $_GET['tvname']; + if (preg_match('/^([^"\'()<>!?]+)/i', $_GET['tvname'])) $tvName = $_GET['tvname']; // Get TV array $tv = $this->modx->getTemplateVar($tvName, '*', $docID); // Handle default TVs switch ($tvName) { - case 'pagetitle' : $tv['type'] = 'text'; $tv['caption'] = $this->getDefaultTvCaption($tvName); $access = TRUE; break; - case 'longtitle' : $tv['type'] = 'text'; $tv['caption'] = $this->getDefaultTvCaption($tvName); $access = TRUE; break; - case 'description' : $tv['type'] = 'text'; $tv['caption'] = $this->getDefaultTvCaption($tvName); $access = TRUE; break; - case 'content' : $tv['type'] = 'richtext'; $tv['caption'] = $this->getDefaultTvCaption($tvName); $access = TRUE; break; - case 'menutitle' : $tv['type'] = 'text'; $tv['caption'] = $this->getDefaultTvCaption($tvName); $access = TRUE; break; - case 'introtext' : $tv['type'] = 'textarea'; $tv['caption'] = $this->getDefaultTvCaption($tvName); $access = TRUE; break; + case 'longtitle': + case 'description': + case 'menutitle': + case 'pagetitle' : + $tv['type'] = 'text'; + $tv['caption'] = $this->getDefaultTvCaption($tvName); + $access = TRUE; + break; + case 'content' : + $tv['type'] = 'richtext'; + $tv['caption'] = $this->getDefaultTvCaption($tvName); + $access = TRUE; + break; + case 'introtext' : + $tv['type'] = 'textarea'; + $tv['caption'] = $this->getDefaultTvCaption($tvName); + $access = TRUE; + break; } // Check TV access @@ -1077,43 +1086,40 @@ function updateMODXsession() { // Check if user has manager access permissions to current document //_______________________________________________________ function checkAccess() { - $access = FALSE; - - // If user is admin (role = 1) - if ($_SESSION['mgrRole'] == 1) $access = TRUE; - - else { - $docID = $this->modx->documentIdentifier; - - // Database table - $table= $this->modx->getFullTableName("document_groups"); + if ($_SESSION['mgrRole'] == 1) { + return TRUE; + } - // Check if current document is assigned to one or more doc groups - $result = $this->modx->db->select('count(id)', $table, "document='{$docID}'"); - $rowCount= $this->modx->db->getValue($result); + $docID = $this->modx->documentIdentifier; - // If document is assigned to one or more doc groups, check access - if ($rowCount >= 1) { + // Database table + $table= $this->modx->getFullTableName("document_groups"); - // Get document groups for current user - $mrgDocGroups = $_SESSION['mgrDocgroups']; - if (!empty($mrgDocGroups)) { - $docGroup = implode(",", $mrgDocGroups); + // Check if current document is assigned to one or more doc groups + $result = $this->modx->db->select('count(id)', $table, "document='{$docID}'"); + $rowCount= $this->modx->db->getValue($result); - // Check if user has access to current document - $result = $this->modx->db->select('count(id)', $table, "document = '{$docID}' AND document_group IN ({$docGroup})"); - $rowCount = $this->modx->db->getValue($result); + // If document is assigned to one or more doc groups, check access + if ($rowCount < 1) { + return TRUE; + } + $mrgDocGroups = $_SESSION['mgrDocgroups']; + if (empty($mrgDocGroups)) { + return FALSE; + } - if ($rowCount >= 1) $access = TRUE; - } + $docGroup = implode(",", $mrgDocGroups); - else $access = FALSE; - } + // Check if user has access to current document + $rowCount = $this->modx->db->getValue( + $this->modx->db->select('count(id)', $table, "document = '{$docID}' AND document_group IN ({$docGroup})") + ); - else $access = TRUE; + if ($rowCount >= 1) { + return TRUE; } - return $access; + return FALSE; } // Function from: processors/cache_sync.class.processor.php @@ -1156,10 +1162,18 @@ function createTvButtons($matches) { } // Return TV button link if access - if ($access && $caption != '') { - $amp = ($this->modx->config['friendly_urls'] == 1) ? '?' : '&'; - return ''.$caption.''; + if (!$access || $caption == '') { + return null; } + $amp = ($this->modx->config['friendly_urls'] == 1) ? '?' : '&'; + return sprintf( + '%s', + $this->tvbclass, + $this->modx->makeUrl($docID), + $amp, + $matches[1], + $caption + ); } // Check user access to TV @@ -1245,8 +1259,8 @@ function saveTv($tvName) { $pageId = $this->modx->documentIdentifier; $time = time(); $user = $_SESSION['mgrInternalKey']; - $tvId = isset($_POST['tvid']) ? intval($_POST['tvid']) : ''; - $tvContent = isset($_POST['tv'.$tvName]) ? $_POST['tv'.$tvName] : ''; + $tvId = isset($_POST['tvid']) ? (int)$_POST['tvid'] : ''; + $tvContent = $_POST['tv' . $tvName] ?? ''; $tvContentTemp = ''; // Escape TV content @@ -1267,15 +1281,20 @@ function saveTv($tvName) { 'contentid' => $pageId, 'value' => $tvContent, ); - $result = $this->modx->db->select('count(id)', $tmplvarContentValuesTable, "tmplvarid = '{$fields['tmplvarid']}' AND contentid = '{$fields['contentid']}'"); + $result = $this->modx->db->select( + 'count(id)', + $tmplvarContentValuesTable, + sprintf("tmplvarid='%s' AND contentid='%s'", $fields['tmplvarid'], $fields['contentid']) + ); // TV exists, update TV if($this->modx->db->getValue($result)) { - $this->modx->db->update($fields, $tmplvarContentValuesTable, "tmplvarid = '{$fields['tmplvarid']}' AND contentid = '{$fields['contentid']}'"); - } - - // TV does not exist, create new TV - else { + $this->modx->db->update( + $fields, + $tmplvarContentValuesTable, + sprintf("tmplvarid='%s' AND contentid='%s'", $fields['tmplvarid'], $fields['contentid']) + ); + } else { $this->modx->db->insert($fields, $tmplvarContentValuesTable); } From ab2dcc0afafaa019e2e193d326faab09a6b4f0ea Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 6 Jan 2023 11:32:28 +0900 Subject: [PATCH 05/49] refactor $modx->sendForward() --- .../includes/document.parser.class.inc.php | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index f97311b852..41037052e5 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -385,20 +385,19 @@ public function sendRedirect($url, $count_attempts = false, $type = 'REDIRECT_HE */ public function sendForward($id, $responseCode = '') { - if ($this->forwards > 0) { - $this->forwards = $this->forwards - 1; - $this->documentIdentifier = $id; - $this->documentMethod = 'id'; - if ($responseCode) { - header($responseCode); - } - $this->prepareResponse(); - exit(); - } else { + if ($this->forwards <= 0) { $this->messageQuit("Internal Server Error id={$id}"); header('HTTP/1.0 500 Internal Server Error'); die('

    ERROR: Too many forward attempts!

    The request could not be completed due to too many unsuccessful forward attempts.

    '); } + $this->forwards--; + $this->documentIdentifier = $id; + $this->documentMethod = 'id'; + if ($responseCode) { + header($responseCode); + } + $this->prepareResponse(); + exit(); } /** From 00945ff3d4fafa2b6439827ca7da8b5db1f240e8 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 6 Jan 2023 11:33:20 +0900 Subject: [PATCH 06/49] refactor $modx->getSettings() --- manager/includes/document.parser.class.inc.php | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 41037052e5..23f3abd953 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -460,9 +460,21 @@ public function getSettings() $this->config['valid_hostnames'] = MODX_SITE_HOSTNAMES; $this->config['site_manager_url'] = MODX_MANAGER_URL; $this->config['site_manager_path'] = MODX_MANAGER_PATH; - $this->error_reporting = isset($this->config['error_reporting']) ? $this->config['error_reporting'] : 0; - $this->config['filemanager_path'] = str_replace('[(base_path)]', MODX_BASE_PATH, (isset($this->config['filemanager_path']) ? $this->config['filemanager_path'] : '')); - $this->config['rb_base_dir'] = str_replace('[(base_path)]', MODX_BASE_PATH, (isset($this->config['rb_base_dir']) ? $this->config['rb_base_dir'] : '')); + $this->error_reporting = $this->config['error_reporting'] ?? 0; + if(strpos($this->config['filemanager_path'], '[(base_path)]')!==false) { + $this->config['filemanager_path'] = str_replace( + '[(base_path)]', + MODX_BASE_PATH, + $this->config['filemanager_path'] + ); + } + if(strpos($this->config['rb_base_dir'],'[(base_path)]')!==false) { + $this->config['rb_base_dir'] = str_replace( + '[(base_path)]', + MODX_BASE_PATH, + $this->config['rb_base_dir'] + ); + } if (!isset($this->config['session_timeout'])) { $this->config['session_timeout'] = 15; From ad1070c9f793716404fe02bb80dc59eb1cd967c6 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 6 Jan 2023 11:34:02 +0900 Subject: [PATCH 07/49] refactor $modx->getUserSettings() --- .../includes/document.parser.class.inc.php | 42 +++++++++++-------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 23f3abd953..d9f0b870d9 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -560,9 +560,6 @@ private function recoverySiteCache() */ public function getUserSettings() { - $tbl_web_user_settings = $this->getFullTableName('web_user_settings'); - $tbl_user_settings = $this->getFullTableName('user_settings'); - // load user setting if user is logged in $usrSettings = []; if ($id = $this->getLoginUserID()) { @@ -579,20 +576,16 @@ public function getUserSettings() if (isset ($_SESSION[$usrType . 'UsrConfigSet'])) { $usrSettings = &$_SESSION[$usrType . 'UsrConfigSet']; } else { - if ($usrType == 'web') { - $from = $tbl_web_user_settings; - $where = "webuser='{$id}'"; - } else { - $from = $tbl_user_settings; - $where = "user='{$id}'"; - } - - $which_browser_default = $this->configGlobal['which_browser'] ? $this->configGlobal['which_browser'] : $this->config['which_browser']; - - $result = $this->db->select('setting_name, setting_value', $from, $where); + $result = $this->db->select( + 'setting_name, setting_value', + ($usrType === 'web') + ? $this->getFullTableName('web_user_settings') + : $this->getFullTableName('user_settings'), + ($usrType === 'web') ? "webuser='" . $id . "'" : "user='" . $id . "'" + ); while ($row = $this->db->getRow($result)) { if ($row['setting_name'] === 'which_browser' && $row['setting_value'] === 'default') { - $row['setting_value'] = $which_browser_default; + $row['setting_value'] = $this->configGlobal['which_browser'] ?: $this->config['which_browser']; } $usrSettings[$row['setting_name']] = $row['setting_value']; } @@ -606,7 +599,12 @@ public function getUserSettings() if (isset ($_SESSION['mgrUsrConfigSet'])) { $musrSettings = &$_SESSION['mgrUsrConfigSet']; } else { - if ($result = $this->db->select('setting_name, setting_value', $tbl_user_settings, "user='{$mgrid}'")) { + $result = $this->db->select( + 'setting_name, setting_value', + $this->getFullTableName('user_settings'), + "user='" . $mgrid . "'" + ); + if ($result) { while ($row = $this->db->getRow($result)) { $musrSettings[$row['setting_name']] = $row['setting_value']; } @@ -625,8 +623,16 @@ public function getUserSettings() } $this->config = array_merge($this->config, $usrSettings); - $this->config['filemanager_path'] = str_replace('[(base_path)]', MODX_BASE_PATH, $this->config['filemanager_path']); - $this->config['rb_base_dir'] = str_replace('[(base_path)]', MODX_BASE_PATH, $this->config['rb_base_dir']); + $this->config['filemanager_path'] = str_replace( + '[(base_path)]', + MODX_BASE_PATH, + $this->config['filemanager_path'] + ); + $this->config['rb_base_dir'] = str_replace( + '[(base_path)]', + MODX_BASE_PATH, + $this->config['rb_base_dir'] + ); return $usrSettings; } From fc63f2843c91c260d61a871bf3bb21b42e664733 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 6 Jan 2023 11:34:50 +0900 Subject: [PATCH 08/49] refacto $modx->cleanDocumentIdentifier() --- .../includes/document.parser.class.inc.php | 64 ++++++++++++++----- 1 file changed, 49 insertions(+), 15 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index d9f0b870d9..2db7842e7a 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -766,27 +766,61 @@ public function cleanDocumentIdentifier($qOrig) $this->virtualDir = ''; } - if (preg_match('@^[1-9][0-9]*$@', $q) && !isset($this->documentListing[$q])) { /* we got an ID returned, check to make sure it's not an alias */ - /* FS#476 and FS#308: check that id is valid in terms of virtualDir structure */ - if ($this->config['use_alias_path'] == 1) { - if (($this->virtualDir != '' && !isset($this->documentListing[$this->virtualDir . '/' . $q]) || ($this->virtualDir == '' && !isset($this->documentListing[$q]))) && (($this->virtualDir != '' && isset($this->documentListing[$this->virtualDir]) && in_array($q, $this->getChildIds($this->documentListing[$this->virtualDir], 1))) || ($this->virtualDir == '' && in_array($q, $this->getChildIds(0, 1))))) { - $this->documentMethod = 'id'; - return $q; - } else { /* not a valid id in terms of virtualDir, treat as alias */ - $this->documentMethod = 'alias'; - return $q; - } - } else { - $this->documentMethod = 'id'; - return $q; - } - } else { /* we didn't get an ID back, so instead we assume it's an alias */ + if (!preg_match('@^[1-9][0-9]*$@', $q) || isset($this->documentListing[$q])) { if ($this->config['friendly_alias_urls'] != 1) { $q = $qOrig; } $this->documentMethod = 'alias'; return $q; } + + if ($this->config['use_alias_path'] != 1) { + $this->documentMethod = 'id'; + return $q; + } + + if ($this->virtualDir == '' && isset($this->documentListing[$q])) { + $this->documentMethod = 'alias'; + return $q; + } + + if ($this->virtualDir != '' && isset($this->documentListing[$this->virtualDir . '/' . $q])) { + $this->documentMethod = 'alias'; + return $q; + } + + if ($this->virtualDir == '' && !in_array($q, $this->getChildIds(0, 1))) { + $this->documentMethod = 'id'; + return $q; + } + + if($this->virtualDir != '' && !isset($this->documentListing[$this->virtualDir])) { + $this->documentMethod = 'id'; + return $q; + } + if ( + $this->virtualDir == '' && !in_array($q, $this->getChildIds(0, 1)) + ) { + $this->documentMethod = 'id'; + return $q; + } + + if ( + $this->virtualDir != '' && !in_array($q, $this->getChildIds($this->documentListing[$this->virtualDir], 1)) + ) { + $this->documentMethod = 'id'; + return $q; + } + + if ( + $this->virtualDir == '' && !in_array($q, $this->getChildIds(0, 1)) + ) { + $this->documentMethod = 'id'; + return $q; + } + + $this->documentMethod = 'id'; + return $q; } /** From c2dd9abcf4489873b444e9084b41d824d88e5f77 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Sat, 7 Jan 2023 17:02:08 +0900 Subject: [PATCH 09/49] refactor - QuickManager --- assets/plugins/qm/qm.inc.php | 30 +++++++----------------------- 1 file changed, 7 insertions(+), 23 deletions(-) diff --git a/assets/plugins/qm/qm.inc.php b/assets/plugins/qm/qm.inc.php index 368bb67605..38856f2b78 100755 --- a/assets/plugins/qm/qm.inc.php +++ b/assets/plugins/qm/qm.inc.php @@ -10,7 +10,7 @@ if(!class_exists('Qm')) { class Qm { - var $modx; + private $modx; //_______________________________________________________ function __construct(&$modx, @@ -543,9 +543,7 @@ function Run() { $css .= ' '; - } - else - if ($this->buttonStyle == 'navButtons') { + } elseif ($this->buttonStyle === 'navButtons') { $css .= ' '; @@ -617,10 +615,7 @@ function Run() { } '; - } - else - // Bottom toolbar Autohide true - if (($this->autohide == 'true') && ($this->position == 'bottom')) { + } elseif (($this->autohide == 'true') && ($this->position === 'bottom')) { $css .= ' '; - } - else - // Bottom toolbar Autohide false - if (($this->autohide == 'false') && ($this->position == 'bottom')) { + } elseif (($this->autohide == 'false') && ($this->position === 'bottom')) { $css .= ' '; - } - else - // Left toolbar Autohide false - if (($this->autohide == 'false') && ($this->position == 'left')) { + } elseif ($this->autohide == 'false' && $this->position === 'left') { $css .= ' '; - } - else - // Right toolbar Autohide false - if (($this->autohide == 'false') && ($this->position == 'right')) { + } elseif (($this->autohide == 'false') && ($this->position == 'right')) { $css .= ' '; - } - else - if (($this->removeBg == 'yes') && ($this->buttonStyle == 'navButtons')) { + } elseif (($this->removeBg === 'yes') && ($this->buttonStyle === 'navButtons')) { $css .= ' - '; + + '; + } + else + // Top toolbar Autohide true + if (($this->autohide == 'true') && ($this->position === 'top')) { + $css .= ' + - '; + @media only screen + and (min-device-width: 768px) + and (max-device-width: 1024px) + and (orientation: portrait) + and (-webkit-min-device-pixel-ratio: 1) { + .butttext {display:none} + .butticon {display:inline!important} } - else + + '; + } else + if ($this->position === 'before') { // Top toolbar Relative - if ($this->position === 'before') { - $css .= ' - - '; - } elseif (($this->autohide == 'true') && ($this->position === 'bottom')) { - $css .= ' - - '; - } elseif (($this->autohide == 'false') && ($this->position === 'bottom')) { - $css .= ' - - '; + $css .= ' + - '; - } elseif ($this->autohide == 'false' && $this->position === 'left') { - $css .= ' - - '; + @media only screen + and (min-device-width: 768px) + and (max-device-width: 1024px) + and (orientation: portrait) + and (-webkit-min-device-pixel-ratio: 1) { + .butttext {display:none} + .butticon {display:inline!important} } - // Right toolbar Autohide true - if (($this->autohide == 'true') && ($this->position == 'right')) { - $css .= ' - - '; - } elseif (($this->autohide == 'false') && ($this->position == 'right')) { - $css .= ' - - '; + + '; + } elseif (($this->autohide == 'true') && ($this->position === 'bottom')) { + $css .= ' + - '; - } elseif (($this->removeBg === 'yes') && ($this->buttonStyle === 'navButtons')) { - $css .= ' - - '; + @media only screen + and (min-device-width: 768px) + and (max-device-width: 1024px) + and (orientation: portrait) + and (-webkit-min-device-pixel-ratio: 1) { + .butttext {display:none} + .butticon {display:inline!important} } - // Insert jQuery and ColorBox in head if needed - $head = ''; - if ($this->loadfrontendjq == 'true') { - $head .= ''; + + '; + } elseif (($this->autohide == 'false') && ($this->position === 'bottom')) { + $css .= ' + - - - '; + @media only screen + and (min-device-width: 768px) + and (max-device-width: 1024px) + and (orientation: portrait) + and (-webkit-min-device-pixel-ratio: 1) { + .butttext {display:none} + .butticon {display:inline!important} } + + '; + } + // Left toolbar Autohide true + if ($this->autohide == 'true' && $this->position === 'left') { + $css .= ' + + '; + } elseif ($this->autohide == 'false' && $this->position === 'left') { + $css .= ' + + '; + } + // Right toolbar Autohide true + if (($this->autohide == 'true') && ($this->position == 'right')) { + $css .= ' + + '; + } elseif (($this->autohide == 'false') && ($this->position == 'right')) { + $css .= ' + + '; + } + // Remove background + if (($this->removeBg === 'yes') && ($this->buttonStyle === 'actionButtons')) { + $css .= ' + + '; + } elseif (($this->removeBg === 'yes') && ($this->buttonStyle === 'navButtons')) { + $css .= ' + + '; + } + // Insert jQuery and ColorBox in head if needed + $head = ''; + if ($this->loadfrontendjq == 'true') { + $head .= ''; + } + if ($this->loadtb == 'true') { + $head .= ' + + + + + + '; + } - // Insert ColorBox jQuery definitions for QuickManager+ + // Insert ColorBox jQuery definitions for QuickManager+ + $head .= ' + - '; + // Hide QM+ + $'.$jvar.'(".qmClose").click(function () { + $'.$jvar.'("#qmEditor").hide("normal"); + $'.$jvar.'("#qmEditorClosed").show("normal"); + document.cookie = "hideQM=1; path=/;"; + }); - $head .= " - - "; - - // Insert QM+ css in head - $head .= $css; + }); - // Place QM+ head information in head, just before tag - $output = preg_replace('~()~i', $head . '\1', $output); + }); - // Insert editor toolbar right after tag - $output = preg_replace('~(]*>)~i', '\1' . $editor, $output); + function getCookie(cookieName) + { + var results = document.cookie.match ( "(^|;) ?" + cookieName + "=([^;]*)(;|$)" ); - // Search and create edit buttons in to the content - if ($this->editbuttons == 'true' && $access) { - $output = preg_replace('//', '$2', $output); + if (results) return (unescape(results[2])); + else return null; } - // Search and create new document buttons in to the content - if ($this->newbuttons == 'true' && $access) { - $output = preg_replace('//', '$3', $output); + + '; + + $head .= " + + "; - // Search and create new document buttons in to the content - if ($this->tvbuttons == 'true' && $access) { - // Set and get user doc groups for TV permissions - $this->docGroup = ''; - $mrgDocGroups = $_SESSION['mgrDocgroups']; - if (!empty($mrgDocGroups)) $this->docGroup = implode(",", $mrgDocGroups); + // Insert QM+ css in head + $head .= $css; - // Create TV buttons and check TV permissions - $output = preg_replace_callback('//', array(&$this, 'createTvButtons'), $output); - } + // Place QM+ head information in head, just before tag + $output = preg_replace('~()~i', $head . '\1', $output); + + // Insert editor toolbar right after tag + $output = preg_replace('~(]*>)~i', '\1' . $editor, $output); + + // Search and create edit buttons in to the content + if ($this->editbuttons == 'true' && $access) { + $output = preg_replace('//', '$2', $output); + } + + // Search and create new document buttons in to the content + if ($this->newbuttons == 'true' && $access) { + $output = preg_replace('//', '$3', $output); + } + + // Search and create new document buttons in to the content + if ($this->tvbuttons == 'true' && $access) { + // Set and get user doc groups for TV permissions + $this->docGroup = ''; + $mrgDocGroups = $_SESSION['mgrDocgroups']; + if (!empty($mrgDocGroups)) $this->docGroup = implode(",", $mrgDocGroups); + + // Create TV buttons and check TV permissions + $output = preg_replace_callback('//', array(&$this, 'createTvButtons'), $output); } } From 2df331d467995c8a7f441bf37e991fb4a8467409 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:02:28 +0900 Subject: [PATCH 21/49] refactor $modx->getDocumentIdentifier() --- .../includes/document.parser.class.inc.php | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index d3a2fd36e9..318bb257d0 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -648,17 +648,21 @@ public function getDocumentIdentifier($method) return $this->db->escape($_REQUEST['q']); } - $id_ = filter_input(INPUT_GET, 'id'); - if ($id_) { - if (preg_match('@^[1-9][0-9]*$@', $id_)) { - return $id_; + $id = filter_input(INPUT_GET, 'id'); + if ($id) { + if (!preg_match('@^[1-9][0-9]*$@', $id)) { + $this->sendErrorPage(); + exit; } + return $id; + } + + if (strpos($_SERVER['REQUEST_URI'], 'index.php/') !== false) { $this->sendErrorPage(); - } elseif (strpos($_SERVER['REQUEST_URI'], 'index.php/') !== false) { - $this->sendErrorPage(); - } else { - return $this->config['site_start']; + exit; } + + return $this->config['site_start']; } /** From ad727c743a4b9a3f4aa41f4b3eb96d90a25521ec Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:04:03 +0900 Subject: [PATCH 22/49] refactor - $modx->isLoggedIn() --- manager/includes/document.parser.class.inc.php | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 318bb257d0..53529cf3f3 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -673,17 +673,13 @@ public function getDocumentIdentifier($method) */ public function isLoggedIn($context = 'mgr') { - if (strpos($context, 'm') === 0) { - $_ = 'mgrValidated'; - } else { - $_ = 'webValidated'; - } + $_ = strpos($context, 'm') === 0 ? 'mgrValidated' : 'webValidated'; - if (!MODX_CLI && (!isset($_SESSION[$_]) || empty($_SESSION[$_]))) { - return false; + if (MODX_CLI || !empty($_SESSION[$_])) { + return true; } - return true; + return false; } /** From 1d10fc9b4c0bf7d7e855b7cdd3f9e892be6a7811 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:04:50 +0900 Subject: [PATCH 23/49] refactor $modx->getDocumentObjectFromCache() --- manager/includes/document.parser.class.inc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 53529cf3f3..a48251b1e8 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -915,7 +915,7 @@ public function getDocumentObjectFromCache($id, $loading = false) $docGrps = explode(',', $docObj['__MODxDocGroups__']); // check is user has access to doc groups if (is_array($usrGrps)) { - foreach ($usrGrps as $k => $v) { + foreach ($usrGrps as $v) { if (!in_array($v, $docGrps)) { continue; } From 67cdbdcc19db90bcbef6e5c879e57aa1d065805a Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:09:05 +0900 Subject: [PATCH 24/49] new - $modx->docAccessConditions() (private method) --- .../includes/document.parser.class.inc.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index a48251b1e8..8cbce0f849 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4069,6 +4069,25 @@ public function getDocuments($ids = [], $published = 1, $deleted = 0, $fields = } } + private function docAccessConditions() { + $docgrp = $this->getUserDocGroups(); + if ($docgrp) { + $docgrp = implode(',', $docgrp); + } + + if($this->isBackend()) { + if($_SESSION['mgrRole']==1) { + return ''; + } + return $docgrp + ? 'sc.privatemgr=0 OR dg.document_group IN (' . $docgrp . ')' + : 'sc.privatemgr=0'; + } + return $docgrp + ? 'sc.privateweb=0 OR dg.document_group IN (' . $docgrp . ')' + : 'sc.privateweb=0'; + } + /** * getDocument * @version 1.0.1 (2014-02-19) From 86a041684ede852cd4581eda1ffaefd9f3a07598 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:10:37 +0900 Subject: [PATCH 25/49] refactor $modx->getDocumentObject() --- .../includes/document.parser.class.inc.php | 71 ++++++++++--------- 1 file changed, 37 insertions(+), 34 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 8cbce0f849..bc395a83f5 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -2719,13 +2719,10 @@ public function getDocumentObject($method, $identifier, $isPrepareResponse = fal return $cache[$cacheKey]; } - $tblsc = $this->getFullTableName("site_content"); - $tbldg = $this->getFullTableName("document_groups"); - // allow alias to be full path if ($method === 'alias') { - $identifier = $this->cleanDocumentIdentifier($identifier); $method = $this->documentMethod; + $identifier = $this->cleanDocumentIdentifier($identifier); } if ($method === 'alias' && $this->config['use_alias_path'] && array_key_exists($identifier, $this->documentListing)) { $method = 'id'; @@ -2736,32 +2733,25 @@ public function getDocumentObject($method, $identifier, $isPrepareResponse = fal if (is_array($out) && is_array($out[0])) { $cache[$cacheKey] = $out[0]; return $out[0]; - } - - // get document groups for current user - if ($docgrp = $this->getUserDocGroups()) { - $docgrp = implode(",", $docgrp); - } - // get document - if ($this->isFrontend()) { - if (!$docgrp) { - $access = "sc.privateweb=0"; - } else { - $access = sprintf("sc.privateweb=0 OR dg.document_group IN (%s)", $docgrp); - } - } elseif ($_SESSION['mgrRole'] != 1) { - if (!$docgrp) { - $access = 'sc.privatemgr=0'; - } else { - $access = sprintf("sc.privatemgr=0 OR dg.document_group IN (%s)", $docgrp); - } - } else { - $access = ''; } + + $access = $this->docAccessConditions(); + $rs = $this->db->select( 'sc.*', - $tblsc . " sc - LEFT JOIN " . $tbldg . " dg ON dg.document = sc.id", "sc." . $method . " = '" . $identifier . "' AND (" . $access . ")", "", 1); + [ + sprintf('%s sc', $this->getFullTableName('site_content')), + sprintf('LEFT JOIN %s dg ON dg.document=sc.id', $this->getFullTableName('document_groups')), + ], + sprintf( + "sc.%s='%s' AND (%s)", + $method, + $identifier, + $access + ), + '', + 1 + ); if ($this->db->getRecordCount($rs) < 1) { $seclimit = 0; if ($this->config['unauthorized_page']) { @@ -2771,8 +2761,8 @@ public function getDocumentObject($method, $identifier, $isPrepareResponse = fal 'count(dg.id)', sprintf( "%s as dg, %s as sc", - $tbldg, - $tblsc + $this->getFullTableName('document_groups'), + $this->getFullTableName('site_content') ), "dg.document = sc.id AND sc.alias = '" . $identifier . "'", '', 1 @@ -2780,8 +2770,10 @@ public function getDocumentObject($method, $identifier, $isPrepareResponse = fal } else { $secrs = $this->db->select( 'count(id)', - $tbldg, - "document = '" . $identifier . "'", '', 1 + $this->getFullTableName('document_groups'), + sprintf("document='%s'", $identifier), + '', + 1 ); } // check if file is not public @@ -2809,9 +2801,20 @@ public function getDocumentObject($method, $identifier, $isPrepareResponse = fal // load TVs and merge with document - Orig by Apodigm - Docvars $rs = $this->db->select( "tv.*, IF(tvc.value!='',tvc.value,tv.default_text) as value", - $this->getFullTableName("site_tmplvars") . " tv - INNER JOIN " . $this->getFullTableName("site_tmplvar_templates") . " tvtpl ON tvtpl.tmplvarid = tv.id - LEFT JOIN " . $this->getFullTableName("site_tmplvar_contentvalues") . " tvc ON tvc.tmplvarid=tv.id AND tvc.contentid = '{$documentObject['id']}'", "tvtpl.templateid = '{$documentObject['template']}'"); + [ + sprintf('%s tv', $this->getFullTableName("site_tmplvars")), + sprintf( + 'INNER JOIN %s tvtpl ON tvtpl.tmplvarid=tv.id', + $this->getFullTableName('site_tmplvar_templates') + ), + sprintf( + "LEFT JOIN %s tvc ON tvc.tmplvarid=tv.id AND tvc.contentid='%s'", + $this->getFullTableName('site_tmplvar_contentvalues'), + $documentObject['id'] + ) + ], + sprintf("tvtpl.templateid='%s'", $documentObject['template']) + ); $tmplvars = []; while ($row = $this->db->getRow($rs)) { $tmplvars[$row['name']] = array( From 8102371bf8ea750af577c9e445db8e50d31f9443 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:11:13 +0900 Subject: [PATCH 26/49] refactor $modx->getAllChildren() --- .../includes/document.parser.class.inc.php | 50 ++++++++++++------- 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index bc395a83f5..ac54fca4c8 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -3883,30 +3883,42 @@ public function isFrontend() * @param string $fields Default: id, pagetitle, description, parent, alias, menutitle * @return array */ - public function getAllChildren($id = 0, $sort = 'menuindex', $dir = 'ASC', $fields = 'id, pagetitle, description, parent, alias, menutitle') + public function getAllChildren($id = 0, + $sort = 'menuindex', + $dir = 'ASC', + $fields = 'id, pagetitle, description, parent, alias, menutitle') { + static $cache = null; $cacheKey = md5(print_r(func_get_args(), true)); - if (isset($this->tmpCache[__FUNCTION__][$cacheKey])) { - return $this->tmpCache[__FUNCTION__][$cacheKey]; + if (isset($cache[$cacheKey])) { + return $cache[$cacheKey]; } - $tblsc = $this->getFullTableName("site_content"); - $tbldg = $this->getFullTableName("document_groups"); - // modify field names to use sc. table reference - $fields = 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $fields)))); - $sort = 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $sort)))); - // get document groups for current user - if ($docgrp = $this->getUserDocGroups()) { - $docgrp = implode(",", $docgrp); - } - // build query - $access = ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") . (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)"); - $result = $this->db->select("DISTINCT {$fields}", "{$tblsc} sc - LEFT JOIN {$tbldg} dg on dg.document = sc.id", "sc.parent = '{$id}' AND ({$access}) GROUP BY sc.id", "{$sort} {$dir}"); - $resourceArray = $this->db->makeArray($result); - $this->tmpCache[__FUNCTION__][$cacheKey] = $resourceArray; - return $resourceArray; + $result = $this->db->select( + 'DISTINCT sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $fields)))), + [ + sprintf('%s sc', $this->getFullTableName('site_content')), + sprintf('LEFT JOIN %s dg on dg.document=sc.id', $this->getFullTableName('document_groups')) + ], + sprintf( + "sc.parent='%s' AND (%s) GROUP BY sc.id", + $id, + $this->docAccessConditions() + ), + sprintf( + 'sc.%s %s', + implode( + ',sc.', + array_filter( + array_map('trim', explode(',', $sort)) + ) + ), + $dir + ) + ); + $cache[$cacheKey] = $this->db->makeArray($result); + return $cache[$cacheKey]; } /** From cfbaf4f43abd72db8f7db231a3b5bddae157b74a Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:11:47 +0900 Subject: [PATCH 27/49] refactor $modx->getActiveChildren() --- .../includes/document.parser.class.inc.php | 51 +++++++++++-------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index ac54fca4c8..51ab87437c 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -3932,32 +3932,41 @@ public function getAllChildren($id = 0, * @param string $fields Default: id, pagetitle, description, parent, alias, menutitle * @return array */ - public function getActiveChildren($id = 0, $sort = 'menuindex', $dir = 'ASC', $fields = 'id, pagetitle, description, parent, alias, menutitle') + public function getActiveChildren($id = 0, + $sort = 'menuindex', + $dir = 'ASC', + $fields = 'id, pagetitle, description, parent, alias, menutitle') { + static $cache = null; $cacheKey = md5(print_r(func_get_args(), true)); - if (isset($this->tmpCache[__FUNCTION__][$cacheKey])) { - return $this->tmpCache[__FUNCTION__][$cacheKey]; - } - - $tblsc = $this->getFullTableName("site_content"); - $tbldg = $this->getFullTableName("document_groups"); - - // modify field names to use sc. table reference - $fields = 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $fields)))); - $sort = 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $sort)))); - // get document groups for current user - if ($docgrp = $this->getUserDocGroups()) { - $docgrp = implode(",", $docgrp); + if (isset($cache[$cacheKey])) { + return $cache[$cacheKey]; } - // build query - $access = ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") . (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)"); - $result = $this->db->select("DISTINCT {$fields}", "{$tblsc} sc - LEFT JOIN {$tbldg} dg on dg.document = sc.id", "sc.parent = '{$id}' AND sc.published=1 AND sc.deleted=0 AND ({$access}) GROUP BY sc.id", "{$sort} {$dir}"); - $resourceArray = $this->db->makeArray($result); - $this->tmpCache[__FUNCTION__][$cacheKey] = $resourceArray; + $result = $this->db->select( + 'DISTINCT sc.' . implode( + ',sc.', + array_filter( + array_map('trim', explode(',', $fields)) + ) + ), + [ + sprintf('%s sc', $this->getFullTableName('site_content')), + sprintf( + 'LEFT JOIN %s dg on dg.document=sc.id', + $this->getFullTableName('document_groups') + ) + ], + sprintf( + "sc.parent='%s' AND sc.published=1 AND sc.deleted=0 AND (%s) GROUP BY sc.id", + $id, + $this->docAccessConditions() + ), + sprintf("sc.%s %s", implode(',sc.', array_filter(array_map('trim', explode(',', $sort)))), $dir) + ); - return $resourceArray; + $cache[$cacheKey] = $this->db->makeArray($result); + return $cache[$cacheKey]; } /** From f3309384e9bee5f67ae548ecb4e2faa9a5d4cc1e Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:12:21 +0900 Subject: [PATCH 28/49] refactor $modx->getDocumentChildren() --- .../includes/document.parser.class.inc.php | 75 +++++++++++-------- 1 file changed, 45 insertions(+), 30 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 51ab87437c..85c4b5cebf 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -3986,44 +3986,59 @@ public function getActiveChildren($id = 0, * * @return {array; false} - Result array, or false. */ - public function getDocumentChildren($parentid = 0, $published = 1, $deleted = 0, $fields = '*', $where = '', $sort = 'menuindex', $dir = 'ASC', $limit = '') + public function getDocumentChildren($parentid = 0, + $published = 1, + $deleted = 0, + $fields = '*', + $where = '', + $sort = 'menuindex', + $dir = 'ASC', + $limit = '') { + static $cache = null; $cacheKey = md5(print_r(func_get_args(), true)); - if (isset($this->tmpCache[__FUNCTION__][$cacheKey])) { - return $this->tmpCache[__FUNCTION__][$cacheKey]; - } - - $published = ($published !== 'all') ? 'AND sc.published = ' . $published : ''; - $deleted = ($deleted !== 'all') ? 'AND sc.deleted = ' . $deleted : ''; - - if ($where != '') { - $where = 'AND ' . $where; + if (isset($cache[$cacheKey])) { + return $cache[$cacheKey]; } // modify field names to use sc. table reference - $fields = 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $fields)))); - $sort = ($sort == '') ? '' : 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $sort)))); - - // get document groups for current user - if ($docgrp = $this->getUserDocGroups()) { - $docgrp = implode(',', $docgrp); - } - - // build query - $access = ($this->isFrontend() ? 'sc.privateweb=0' : '1="' . $_SESSION['mgrRole'] . '" OR sc.privatemgr=0') . (!$docgrp ? '' : ' OR dg.document_group IN (' . $docgrp . ')'); - - $tblsc = $this->getFullTableName('site_content'); - $tbldg = $this->getFullTableName('document_groups'); - - $result = $this->db->select("DISTINCT {$fields}", "{$tblsc} sc - LEFT JOIN {$tbldg} dg on dg.document = sc.id", "sc.parent = '{$parentid}' {$published} {$deleted} {$where} AND ({$access}) GROUP BY sc.id", ($sort ? "{$sort} {$dir}" : ""), $limit); - $resourceArray = $this->db->makeArray($result); - - $this->tmpCache[__FUNCTION__][$cacheKey] = $resourceArray; + $result = $this->db->select( + 'DISTINCT sc.' . implode( + ',sc.', + array_filter( + array_map('trim', explode(',', $fields)) + ) + ), + [ + sprintf('%s sc', $this->getFullTableName('site_content')), + sprintf('LEFT JOIN %s dg on dg.document=sc.id', $this->getFullTableName('document_groups')) + ], + sprintf( + "sc.parent='%s' %s %s %s AND (%s) GROUP BY sc.id", + $parentid, + $published !== 'all' ? 'AND sc.published = ' . $published : '', + $deleted !== 'all' ? 'AND sc.deleted = ' . $deleted : '', + $where ? 'AND ' . $where : '', + $this->docAccessConditions() + ), + $sort + ? sprintf( + 'sc.%s %s', + implode( + ',sc.', + array_filter(array_map('trim', explode(',', $sort))) + ), + $dir + ) + : '' + , + $limit + ); - return $resourceArray; + $cache[$cacheKey] = $this->db->makeArray($result); + return $cache[$cacheKey]; } /** From b2089b50063257e7551b1856c416eb9a37b1b48b Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:12:52 +0900 Subject: [PATCH 29/49] refactor $modx->getDocuments() --- .../includes/document.parser.class.inc.php | 58 +++++++++---------- 1 file changed, 27 insertions(+), 31 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 85c4b5cebf..cf529e299c 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4060,10 +4060,11 @@ public function getDocumentChildren($parentid = 0, */ public function getDocuments($ids = [], $published = 1, $deleted = 0, $fields = '*', $where = '', $sort = 'menuindex', $dir = 'ASC', $limit = '') { + static $cache = null; $cacheKey = md5(print_r(func_get_args(), true)); - if (isset($this->tmpCache[__FUNCTION__][$cacheKey])) { - return $this->tmpCache[__FUNCTION__][$cacheKey]; + if (isset($cache[$cacheKey])) { + return $cache[$cacheKey]; } if (is_string($ids)) { @@ -4073,39 +4074,34 @@ public function getDocuments($ids = [], $published = 1, $deleted = 0, $fields = $ids = array($ids); } } - if (count($ids) == 0) { - $this->tmpCache[__FUNCTION__][$cacheKey] = false; + if (!$ids) { + $cache[$cacheKey] = false; return false; - } else { - // modify field names to use sc. table reference - $fields = 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $fields)))); - $sort = ($sort == '') ? '' : 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $sort)))); - if ($where != '') { - $where = 'AND ' . $where; - } - - $published = ($published !== 'all') ? "AND sc.published = '{$published}'" : ''; - $deleted = ($deleted !== 'all') ? "AND sc.deleted = '{$deleted}'" : ''; - - // get document groups for current user - if ($docgrp = $this->getUserDocGroups()) { - $docgrp = implode(',', $docgrp); - } - - $access = ($this->isFrontend() ? 'sc.privateweb=0' : '1="' . $_SESSION['mgrRole'] . '" OR sc.privatemgr=0') . (!$docgrp ? '' : ' OR dg.document_group IN (' . $docgrp . ')'); - - $tblsc = $this->getFullTableName('site_content'); - $tbldg = $this->getFullTableName('document_groups'); - - $result = $this->db->select("DISTINCT {$fields}", "{$tblsc} sc - LEFT JOIN {$tbldg} dg on dg.document = sc.id", "(sc.id IN (" . implode(',', $ids) . ") {$published} {$deleted} {$where}) AND ({$access}) GROUP BY sc.id", ($sort ? "{$sort} {$dir}" : ""), $limit); + } - $resourceArray = $this->db->makeArray($result); + $result = $this->db->select( + sprintf('DISTINCT sc.%s', implode(',sc.', array_filter(array_map('trim', explode(',', $fields))))), + [ + sprintf("%s sc", $this->getFullTableName('site_content')), + sprintf("LEFT JOIN %s dg on dg.document=sc.id", $this->getFullTableName('document_groups')) + ], + sprintf( + "(sc.id IN (%s) %s %s %s) AND (%s) GROUP BY sc.id", + implode(',', $ids), + $published === 'all' ? '' : sprintf("AND sc.published='%s'", $published), + $deleted === 'all' ? '' : sprintf("AND sc.deleted='%s'", $deleted), + $where ? 'AND ' . $where : '', + $this->docAccessConditions() + ), + $sort + ? sprintf('sc.%s %s', implode(',sc.', array_filter(array_map('trim', explode(',', $sort)))), $dir) + : '', + $limit + ); - $this->tmpCache[__FUNCTION__][$cacheKey] = $resourceArray; + $cache[$cacheKey] = $this->db->makeArray($result); - return $resourceArray; - } + return $cache[$cacheKey]; } private function docAccessConditions() { From c716c9575fa4439593b5ffbe801a0fc88e1d30e1 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:13:25 +0900 Subject: [PATCH 30/49] refactor $modx->getDocument() --- manager/includes/document.parser.class.inc.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index cf529e299c..afac7bc139 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4142,17 +4142,17 @@ private function docAccessConditions() { */ public function getDocument($id = 0, $fields = '*', $published = 1, $deleted = 0) { - if ($id == 0) { + if (!$id) { return false; - } else { - $docs = $this->getDocuments(array($id), $published, $deleted, $fields, '', '', '', 1); + } - if ($docs != false) { - return $docs[0]; - } else { - return false; - } + $docs = $this->getDocuments(array($id), $published, $deleted, $fields, '', '', '', 1); + + if (!$docs) { + return false; } + + return $docs[0]; } /** From df5ba6d24d16ca6e23e0cc4613da6c78b198a317 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:14:02 +0900 Subject: [PATCH 31/49] refactor $modx->getField() --- manager/includes/document.parser.class.inc.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index afac7bc139..4afb824e15 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4166,7 +4166,8 @@ public function getField($field = 'content', $docid = '') if (!$docid) { $docid = $this->documentIdentifier ?? null; - } elseif (!preg_match('@^[0-9]+$@', $docid)) { + } + if (!preg_match('@^[1-9][0-9]*$@', $docid)) { $docid = $this->getIdFromAlias($docid); } From 8223a05cad7021ccc935ff242bc008418b953cc3 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:14:31 +0900 Subject: [PATCH 32/49] refactor $modx->getPageInfo() --- .../includes/document.parser.class.inc.php | 44 ++++++++++--------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 4afb824e15..f967dd920a 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4203,34 +4203,36 @@ public function getField($field = 'content', $docid = '') * Default: id, pagetitle, description, alias * @return boolean|array */ - public function getPageInfo($pageid = -1, $active = 1, $fields = 'id, pagetitle, description, alias') + public function getPageInfo($pageid = null, $active = 1, $fields = 'id, pagetitle, description, alias') { + static $cache = null; $cacheKey = md5(print_r(func_get_args(), true)); - if (isset($this->tmpCache[__FUNCTION__][$cacheKey])) { - return $this->tmpCache[__FUNCTION__][$cacheKey]; + if (isset($cache[$cacheKey])) { + return $cache[$cacheKey]; } - if ($pageid == 0) { + if (!$pageid) { return false; - } else { - $tblsc = $this->getFullTableName("site_content"); - $tbldg = $this->getFullTableName("document_groups"); - $activeSql = $active == 1 ? "AND sc.published=1 AND sc.deleted=0" : ""; - // modify field names to use sc. table reference - $fields = 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $fields)))); - // get document groups for current user - if ($docgrp = $this->getUserDocGroups()) { - $docgrp = implode(",", $docgrp); - } - $access = ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") . (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)"); - $result = $this->db->select($fields, "{$tblsc} sc LEFT JOIN {$tbldg} dg on dg.document = sc.id", "(sc.id='{$pageid}' {$activeSql}) AND ({$access})", "", 1); - $pageInfo = $this->db->getRow($result); - - $this->tmpCache[__FUNCTION__][$cacheKey] = $pageInfo; - - return $pageInfo; } + + $result = $this->db->select( + 'sc.' . implode(',sc.', array_filter(array_map('trim', explode(',', $fields)))), + [ + sprintf('%s sc', $this->getFullTableName('site_content')), + sprintf('LEFT JOIN %s dg on dg.document = sc.id', $this->getFullTableName('document_groups')) + ], + sprintf( + "(sc.id='%s' %s) AND (%s)", + $pageid, + $active == 1 ? "AND sc.published=1 AND sc.deleted=0" : '', + $this->docAccessConditions() + ), + '', + 1 + ); + $cache[$cacheKey] = $this->db->getRow($result); + return $cache[$cacheKey]; } /** From 91166e82a2802f66a4a425cee894d68f33d5b1cf Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:15:06 +0900 Subject: [PATCH 33/49] refactor $modx->getDocumentChildrenTVars() --- .../includes/document.parser.class.inc.php | 87 ++++++++++--------- 1 file changed, 47 insertions(+), 40 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index f967dd920a..1fae7f1e2c 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4851,61 +4851,68 @@ public function toTimeStamp($str) * Default: ASC * @return array|bool */ - public function getDocumentChildrenTVars($parentid = 0, $tvidnames = [], $published = 1, $docsort = "menuindex", $docsortdir = "ASC", $tvfields = "*", $tvsort = "rank", $tvsortdir = "ASC") + public function getDocumentChildrenTVars($parentid = 0, + $tvidnames = [], + $published = 1, + $docsort = "menuindex", + $docsortdir = "ASC", + $tvfields = "*", + $tvsort = "rank", + $tvsortdir = "ASC") { $docs = $this->getDocumentChildren($parentid, $published, 0, '*', '', $docsort, $docsortdir); if (!$docs) { return false; - } else { - $result = []; - // get user defined template variables - if ($tvfields) { - $_ = array_filter(array_map('trim', explode(',', $tvfields))); - foreach ($_ as $i => $v) { - if ($v === 'value') { - unset($_[$i]); - } else { - $_[$i] = 'tv.' . $v; - } + } + + $result = []; + // get user defined template variables + if ($tvfields) { + $_ = array_filter(array_map('trim', explode(',', $tvfields))); + foreach ($_ as $i => $v) { + if ($v === 'value') { + unset($_[$i]); + } else { + $_[$i] = 'tv.' . $v; } - $fields = implode(',', $_); - } else { - $fields = "tv.*"; } + $fields = implode(',', $_); + } else { + $fields = "tv.*"; + } - if ($tvsort != '') { - $tvsort = 'tv.' . implode(',tv.', array_filter(array_map('trim', explode(',', $tvsort)))); - } - if ($tvidnames == "*") { - $query = "tv.id<>0"; - } else { - $query = (is_numeric($tvidnames[0]) ? "tv.id" : "tv.name") . " IN ('" . implode("','", $tvidnames) . "')"; - } + if ($tvsort != '') { + $tvsort = 'tv.' . implode(',tv.', array_filter(array_map('trim', explode(',', $tvsort)))); + } + if ($tvidnames == "*") { + $query = "tv.id<>0"; + } else { + $query = (is_numeric($tvidnames[0]) ? "tv.id" : "tv.name") . " IN ('" . implode("','", $tvidnames) . "')"; + } - $this->getUserDocGroups(); + $this->getUserDocGroups(); - foreach ($docs as $doc) { + foreach ($docs as $doc) { - $docid = $doc['id']; + $docid = $doc['id']; - $rs = $this->db->select("{$fields}, IF(tvc.value!='',tvc.value,tv.default_text) as value ", "[+prefix+]site_tmplvars tv - INNER JOIN [+prefix+]site_tmplvar_templates tvtpl ON tvtpl.tmplvarid = tv.id - LEFT JOIN [+prefix+]site_tmplvar_contentvalues tvc ON tvc.tmplvarid=tv.id AND tvc.contentid='{$docid}'", "{$query} AND tvtpl.templateid = '{$doc['template']}'", ($tvsort ? "{$tvsort} {$tvsortdir}" : "")); - $tvs = $this->db->makeArray($rs); + $rs = $this->db->select("{$fields}, IF(tvc.value!='',tvc.value,tv.default_text) as value ", "[+prefix+]site_tmplvars tv + INNER JOIN [+prefix+]site_tmplvar_templates tvtpl ON tvtpl.tmplvarid = tv.id + LEFT JOIN [+prefix+]site_tmplvar_contentvalues tvc ON tvc.tmplvarid=tv.id AND tvc.contentid='{$docid}'", "{$query} AND tvtpl.templateid = '{$doc['template']}'", ($tvsort ? "{$tvsort} {$tvsortdir}" : "")); + $tvs = $this->db->makeArray($rs); - // get default/built-in template variables - ksort($doc); - foreach ($doc as $key => $value) { - if ($tvidnames == '*' || in_array($key, $tvidnames)) { - $tvs[] = array('name' => $key, 'value' => $value); - } - } - if (is_array($tvs) && count($tvs)) { - $result[] = $tvs; + // get default/built-in template variables + ksort($doc); + foreach ($doc as $key => $value) { + if ($tvidnames === '*' || in_array($key, $tvidnames)) { + $tvs[] = array('name' => $key, 'value' => $value); } } - return $result; + if (is_array($tvs) && count($tvs)) { + $result[] = $tvs; + } } + return $result; } /** From 5f5cf345baefa06fadd815f06b9239947426c66c Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:15:43 +0900 Subject: [PATCH 34/49] refactor $modx->getDocumentChildrenTVarOutput() --- .../includes/document.parser.class.inc.php | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 1fae7f1e2c..46d9fe0acf 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4944,41 +4944,41 @@ public function getDocumentChildrenTVarOutput($parentid = 0, $tvidnames = [], $p if (!$docs) { return false; - } else { - $result = []; + } + + $result = []; - $unsetResultKey = false; + $unsetResultKey = false; - if ($resultKey !== false) { - if (is_array($tvidnames)) { - if (count($tvidnames) != 0 && !in_array($resultKey, $tvidnames)) { - $tvidnames[] = $resultKey; - $unsetResultKey = true; - } - } elseif ($tvidnames != '*' && $tvidnames != $resultKey) { - $tvidnames = array($tvidnames, $resultKey); + if ($resultKey !== false) { + if (is_array($tvidnames)) { + if (count($tvidnames) != 0 && !in_array($resultKey, $tvidnames)) { + $tvidnames[] = $resultKey; $unsetResultKey = true; } + } elseif ($tvidnames !== '*' && $tvidnames != $resultKey) { + $tvidnames = array($tvidnames, $resultKey); + $unsetResultKey = true; } + } - for ($i = 0; $i < count($docs); $i++) { - $tvs = $this->getTemplateVarOutput($tvidnames, $docs[$i]['id'], $published); + for ($i = 0; $i < count($docs); $i++) { + $tvs = $this->getTemplateVarOutput($tvidnames, $docs[$i]['id'], $published); - if ($tvs) { - if ($resultKey !== false && array_key_exists($resultKey, $tvs)) { - $result[$tvs[$resultKey]] = $tvs; + if ($tvs) { + if ($resultKey !== false && array_key_exists($resultKey, $tvs)) { + $result[$tvs[$resultKey]] = $tvs; - if ($unsetResultKey) { - unset($result[$tvs[$resultKey]][$resultKey]); - } - } else { - $result[] = $tvs; + if ($unsetResultKey) { + unset($result[$tvs[$resultKey]][$resultKey]); } + } else { + $result[] = $tvs; } } - - return $result; } + + return $result; } /** From ea6ac68b68143c4dc90e61f66519ccbcc264a325 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:16:19 +0900 Subject: [PATCH 35/49] refactor $modx->getTemplateVar() --- manager/includes/document.parser.class.inc.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 46d9fe0acf..18a7ddb7dd 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -5000,10 +5000,10 @@ public function getTemplateVar($idname = "", $fields = "*", $docid = "", $publis { if ($idname == "") { return false; - } else { - $result = $this->getTemplateVars(array($idname), $fields, $docid, $published, "", ""); //remove sorting for speed - return ($result != false) ? $result[0] : false; } + + $result = $this->getTemplateVars(array($idname), $fields, $docid, $published, "", ""); //remove sorting for speed + return ($result != false) ? $result[0] : false; } /** From 78228018ace52f4213117b265483f766d0ab9b3f Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:17:00 +0900 Subject: [PATCH 36/49] refactor $modx->getUserDocGroups() --- .../includes/document.parser.class.inc.php | 44 ++++++++++++------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 18a7ddb7dd..c9d6aa3fc0 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -5415,32 +5415,42 @@ public function getUserDocGroups($resolveIds = false) { if ($this->isFrontend() && isset($_SESSION['webDocgroups']) && isset($_SESSION['webValidated'])) { $dg = $_SESSION['webDocgroups']; - $dgn = isset($_SESSION['webDocgrpNames']) ? $_SESSION['webDocgrpNames'] : false; + $dgn = $_SESSION['webDocgrpNames'] ?? false; } elseif ($this->isBackend() && isset($_SESSION['mgrDocgroups']) && isset($_SESSION['mgrValidated'])) { $dg = $_SESSION['mgrDocgroups']; - $dgn = isset($_SESSION['mgrDocgrpNames']) ? $_SESSION['mgrDocgrpNames'] : false; + $dgn = $_SESSION['mgrDocgrpNames'] ?? false; } else { $dg = ''; } if (!$resolveIds) { return $dg; - } elseif (is_array($dgn)) { - return $dgn; - } elseif (is_array($dg)) { - // resolve ids to names - $dgn = []; - $ds = $this->db->select('name', $this->getFullTableName("documentgroup_names"), "id IN (" . implode(",", $dg) . ")"); - while ($row = $this->db->getRow($ds)) { - $dgn[] = $row['name']; - } - // cache docgroup names to session - if ($this->isFrontend()) { - $_SESSION['webDocgrpNames'] = $dgn; - } else { - $_SESSION['mgrDocgrpNames'] = $dgn; - } + } + + if (is_array($dgn)) { return $dgn; } + + if (!is_array($dg)) { + return []; + } + + // resolve ids to names + $dgn = []; + $ds = $this->db->select( + 'name', + $this->getFullTableName("documentgroup_names"), + sprintf('id IN (%s)', implode(',', $dg)) + ); + while ($row = $this->db->getRow($ds)) { + $dgn[] = $row['name']; + } + // cache docgroup names to session + if ($this->isFrontend()) { + $_SESSION['webDocgrpNames'] = $dgn; + } else { + $_SESSION['mgrDocgrpNames'] = $dgn; + } + return $dgn; } /** From 1e12499cef3018f4c2198928eb1750bd4201c596 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:18:03 +0900 Subject: [PATCH 37/49] refactor $modx->getIdFromAlias() --- .../includes/document.parser.class.inc.php | 66 +++++++++++-------- 1 file changed, 40 insertions(+), 26 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index c9d6aa3fc0..99eab40241 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -6866,7 +6866,7 @@ public function getHiddenIdFromAlias($parentid, $alias) } /** - * @param $alias + * @param string $alias * @return bool|int */ public function getIdFromAlias($alias) @@ -6876,36 +6876,50 @@ public function getIdFromAlias($alias) } $tbl_site_content = $this->getFullTableName('site_content'); - if ($this->config['use_alias_path'] == 1) { - if ($alias == '.') { - return 0; + if (!$this->config['use_alias_path']) { + $rs = $this->db->select( + 'id', + $tbl_site_content, + "deleted=0 and alias='" . $alias . "'", + 'parent, menuindex' + ); + $id = $this->db->getValue($rs); + if (!$id) { + $id = false; } + return $id; + } - if (strpos($alias, '/') !== false) { - $_a = explode('/', $alias); - } else { - $_a[] = $alias; - } - $id = 0; + if ($alias === '.') { + return 0; + } - foreach ($_a as $alias) { - if ($id === false) { - break; - } - $alias = $this->db->escape($alias); - $rs = $this->db->select('id', $tbl_site_content, "deleted=0 and parent='{$id}' and alias='{$alias}'"); - if ($this->db->getRecordCount($rs) == 0) { - $rs = $this->db->select('id', $tbl_site_content, "deleted=0 and parent='{$id}' and id='{$alias}'"); - } - $next = $this->db->getValue($rs); - $id = !$next ? $this->getHiddenIdFromAlias($id, $alias) : $next; - } + if (strpos($alias, '/') !== false) { + $_a = explode('/', $alias); } else { - $rs = $this->db->select('id', $tbl_site_content, "deleted=0 and alias='{$alias}'", 'parent, menuindex'); - $id = $this->db->getValue($rs); - if (!$id) { - $id = false; + $_a[] = $alias; + } + $id = 0; + + foreach ($_a as $alias) { + if ($id === false) { + break; + } + $alias = $this->db->escape($alias); + $rs = $this->db->select( + 'id', + $tbl_site_content, + "deleted=0 and parent='" . $id . "' and alias='" . $alias . "'" + ); + if ($this->db->getRecordCount($rs) == 0) { + $rs = $this->db->select( + 'id', + $tbl_site_content, + "deleted=0 and parent='" . $id . "' and id='" . $alias . "'" + ); } + $next = $this->db->getValue($rs); + $id = $next ?: $this->getHiddenIdFromAlias($id, $alias); } return $id; } From 382c13cab4eca99f77284b7a7f6c1f634ff5ffde Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:18:40 +0900 Subject: [PATCH 38/49] refactor $modx->atBindInclude() --- .../includes/document.parser.class.inc.php | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 99eab40241..0a4e90be25 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -6937,18 +6937,24 @@ public function atBindInclude($str = '') $str = substr($str, 0, strpos("\n", $str)); } - $str = substr($str, 9); - $str = trim($str); - $str = str_replace('\\', '/', $str); - $str = ltrim($str, '/'); + $str = ltrim( + str_replace( + '\\', + '/', + trim(substr($str, 9)) + ), + '/' + ); $tpl_dir = 'assets/templates/'; if (strpos($str, MODX_MANAGER_PATH) === 0) { return false; - } elseif (is_file(MODX_BASE_PATH . $str)) { + } + + if (is_file(MODX_BASE_PATH . $str)) { $file_path = MODX_BASE_PATH . $str; - } elseif (is_file(MODX_BASE_PATH . "{$tpl_dir}{$str}")) { + } elseif (is_file(MODX_BASE_PATH . $tpl_dir . $str)) { $file_path = MODX_BASE_PATH . $tpl_dir . $str; } else { return false; @@ -6966,7 +6972,7 @@ public function atBindInclude($str = '') } $content = ob_get_clean(); if (!$content && $result) { - $content = $result; + return $result; } return $content; } From 19912679c9178d9475d932b81065fd0e6bb58314 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:19:10 +0900 Subject: [PATCH 39/49] refactor $modx->isJson() --- manager/includes/document.parser.class.inc.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 0a4e90be25..f4cdf4db95 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -6999,7 +6999,10 @@ public function htmlspecialchars($str, $flags = ENT_COMPAT, $encode = '') public function isJson($string, $returnData = false) { $data = json_decode($string, true); - return (json_last_error() == JSON_ERROR_NONE) ? ($returnData ? $data : true) : false; + if (json_last_error() != JSON_ERROR_NONE) { + return false; + } + return ($returnData ? $data : true); } /** From 2e6966ce0f982741d7882c5c420ddb52233c4422 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:19:37 +0900 Subject: [PATCH 40/49] refactor $modx->splitKeyAndFilter() --- .../includes/document.parser.class.inc.php | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index f4cdf4db95..d52188d3b1 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -7006,23 +7006,25 @@ public function isJson($string, $returnData = false) } /** - * @param $key + * @param $str * @return array */ - public function splitKeyAndFilter($key) + public function splitKeyAndFilter($str) { - if (isset($this->config['enable_filter']) && $this->config['enable_filter'] == 1 && strpos($key, ':') !== false && stripos($key, '@FILE') !== 0) { - list($key, $modifiers) = explode(':', $key, 2); - } else { - $modifiers = false; + if (empty($this->config['enable_filter'])) { + return [trim($str), false]; } - $key = trim($key); - if ($modifiers !== false) { - $modifiers = trim($modifiers); + if (strpos($str, ':') === false) { + return [trim($str), false]; + } + + if (stripos($str, '@FILE') === 0) { + return [trim($str), false]; } - return array($key, $modifiers); + list($key, $modifiers) = explode(':', $str, 2); + return [trim($key), trim($modifiers)]; } /** From 05fbe05762faa3e3705524d897dbcce640d7de26 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:20:06 +0900 Subject: [PATCH 41/49] refactor $modx->applyFilter() --- manager/includes/document.parser.class.inc.php | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index d52188d3b1..c5fe518efb 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -7035,15 +7035,12 @@ public function splitKeyAndFilter($str) */ public function applyFilter($value = '', $modifiers = false, $key = '') { - if ($modifiers === false || $modifiers == 'raw') { + if ($modifiers === false || $modifiers === 'raw') { return $value; } - if ($modifiers !== false) { - $modifiers = trim($modifiers); - } $this->loadExtension('MODIFIERS'); - return $this->filter->phxFilter($key, $value, $modifiers); + return $this->filter->phxFilter($key, $value, trim($modifiers)); } // End of class. From f23e3e76f21adb08c04ebf4a6cbc4da136dce176 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:20:34 +0900 Subject: [PATCH 42/49] refactor $modx->_getCleanQueryString() --- manager/includes/document.parser.class.inc.php | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index c5fe518efb..5144595278 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -7054,22 +7054,21 @@ public function applyFilter($value = '', $modifiers = false, $key = '') */ private static function _getCleanQueryString() { - $q = MODX_CLI ? null : (isset($_GET['q']) ? $_GET['q'] : ''); + if (MODX_CLI) { + return null; + } + + $q = $_GET['q'] ?? ''; //Return null if the query doesn't exist if (empty($q)) { return null; } - //If we have a string, return it - if (is_string($q)) { - return $q; - } - - //If we have an array, return the first element if (is_array($q)) { return $q[0]; } + return $q; } /** From 238bce7d9669957b760367507b141164dff6969f Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:21:07 +0900 Subject: [PATCH 43/49] refactor $modx->addLog() --- manager/includes/document.parser.class.inc.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 5144595278..747a9a0bae 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -7078,15 +7078,17 @@ private static function _getCleanQueryString() */ public function addLog($title = 'no title', $msg = '', $type = 1) { - if ($title === '') { - $title = 'no title'; - } if (is_array($msg)) { $msg = '
    ' . print_r($msg, true) . '
    '; } elseif ($msg === '') { $msg = $_SERVER['REQUEST_URI']; } - $this->logEvent(0, $type, $msg, $title); + $this->logEvent( + 0, + $type, + $msg, + $title ?: 'no title' + ); } /** From 44a4a8cf96dd13339f0d5aab350bd5f2ef84e275 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Wed, 11 Jan 2023 23:22:54 +0900 Subject: [PATCH 44/49] separate SystemEvent class --- .../includes/document.parser.class.inc.php | 121 +----------------- manager/includes/system_event.class.inc.php | 120 +++++++++++++++++ 2 files changed, 121 insertions(+), 120 deletions(-) create mode 100644 manager/includes/system_event.class.inc.php diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 747a9a0bae..a32100d969 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -11,6 +11,7 @@ define('E_USER_DEPRECATED', 16384); } +include_once __DIR__ . '/system_event.class.inc.php'; class DocumentParser { /** @@ -7194,123 +7195,3 @@ public function getMail($reload = false) return $this->mail; } } - -/** - * System Event Class - */ -class SystemEvent -{ - public $name = ''; - public $_propagate = true; - /** - * @deprecated use setOutput(), getOutput() - * @var string - */ - public $_output; - public $activated = false; - public $activePlugin = ''; - public $params = []; - - /** - * Previous event object - * @var SystemEvent - */ - private $previousEvent; - - /** - * @param string $name Name of the event - */ - public function __construct($name = "") - { - $this->_resetEventObject(); - $this->name = $name; - } - - /** - * Display a message to the user - * - * @global array $SystemAlertMsgQueque - * @param string $msg The message - */ - public function alert($msg) - { - global $SystemAlertMsgQueque; - if ($msg == "") { - return; - } - if (is_array($SystemAlertMsgQueque)) { - $title = ''; - if ($this->name && $this->activePlugin) { - $title = "
    " . $this->activePlugin . " - " . $this->name . "
    "; - } - $SystemAlertMsgQueque[] = "$title
    $msg
    "; - } - } - - /** - * Output - * - * @param string $msg - * @deprecated see addOutput - */ - public function output($msg) - { - $this->addOutput($msg); - } - - /** - * @param mixed $data - */ - public function addOutput($data) - { - if(\is_scalar($data)) { - $this->_output .= $data; - } - } - - /** - * @param mixed $data - */ - public function setOutput($data) - { - $this->_output = $data; - } - - /** - * @return mixed - */ - public function getOutput() - { - return $this->_output; - } - - /** - * Stop event propogation - */ - public function stopPropagation() - { - $this->_propagate = false; - } - - public function _resetEventObject() - { - unset ($this->returnedValues); - $this->name = ""; - $this->setOutput(null); - $this->_propagate = true; - $this->activated = false; - } - - /** - * @param SystemEvent $event - */ - public function setPreviousEvent($event) - { - $this->previousEvent = $event; - } - - public function getPreviousEvent() - { - return $this->previousEvent; - } -} diff --git a/manager/includes/system_event.class.inc.php b/manager/includes/system_event.class.inc.php new file mode 100644 index 0000000000..3d906aeecd --- /dev/null +++ b/manager/includes/system_event.class.inc.php @@ -0,0 +1,120 @@ +_resetEventObject(); + $this->name = $name; + } + + /** + * Display a message to the user + * + * @global array $SystemAlertMsgQueque + * @param string $msg The message + */ + public function alert($msg) + { + global $SystemAlertMsgQueque; + if ($msg == "") { + return; + } + if (is_array($SystemAlertMsgQueque)) { + $title = ''; + if ($this->name && $this->activePlugin) { + $title = "
    " . $this->activePlugin . " - " . $this->name . "
    "; + } + $SystemAlertMsgQueque[] = "$title
    $msg
    "; + } + } + + /** + * Output + * + * @param string $msg + * @deprecated see addOutput + */ + public function output($msg) + { + $this->addOutput($msg); + } + + /** + * @param mixed $data + */ + public function addOutput($data) + { + if(\is_scalar($data)) { + $this->_output .= $data; + } + } + + /** + * @param mixed $data + */ + public function setOutput($data) + { + $this->_output = $data; + } + + /** + * @return mixed + */ + public function getOutput() + { + return $this->_output; + } + + /** + * Stop event propogation + */ + public function stopPropagation() + { + $this->_propagate = false; + } + + public function _resetEventObject() + { + unset ($this->returnedValues); + $this->name = ""; + $this->setOutput(null); + $this->_propagate = true; + $this->activated = false; + } + + /** + * @param SystemEvent $event + */ + public function setPreviousEvent($event) + { + $this->previousEvent = $event; + } + + public function getPreviousEvent() + { + return $this->previousEvent; + } +} From 3ba3fd0e7a244af9b3fa688aa288dc4b13786001 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Thu, 12 Jan 2023 10:44:24 +0900 Subject: [PATCH 45/49] refactor $mmdx->getDocuments() --- manager/includes/document.parser.class.inc.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index a32100d969..7c0f7c3237 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4059,7 +4059,14 @@ public function getDocumentChildren($parentid = 0, * * @return {array; false} - Result array with documents, or false. */ - public function getDocuments($ids = [], $published = 1, $deleted = 0, $fields = '*', $where = '', $sort = 'menuindex', $dir = 'ASC', $limit = '') + public function getDocuments($ids = [], + $published = 1, + $deleted = 0, + $fields = '*', + $where = '', + $sort = 'menuindex', + $dir = 'ASC', + $limit = '') { static $cache = null; From 0df1027556c922ac1ca675aea38851206c427226 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Thu, 12 Jan 2023 10:45:41 +0900 Subject: [PATCH 46/49] refactor $modx->getTemplateVars() --- .../includes/document.parser.class.inc.php | 80 ++++++++++++------- 1 file changed, 50 insertions(+), 30 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 7c0f7c3237..ed67d9c14e 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -5031,7 +5031,12 @@ public function getTemplateVar($idname = "", $fields = "*", $docid = "", $publis * * @return array|bool Result array, or false. */ - public function getTemplateVars($idnames = [], $fields = '*', $docid = '', $published = 1, $sort = 'rank', $dir = 'ASC') + public function getTemplateVars($idnames = [], + $fields = '*', + $docid = '', + $published = 1, + $sort = 'rank', + $dir = 'ASC') { static $cache = null; $cacheKey = md5(print_r(func_get_args(), true)); @@ -5039,55 +5044,70 @@ public function getTemplateVars($idnames = [], $fields = '*', $docid = '', $publ return $cache[$cacheKey]; } - if (($idnames !== '*' && !is_array($idnames)) || empty($idnames) ) { + if (!$idnames ) { + return false; + } + if (!is_array($idnames) && $idnames !== '*') { return false; } - // get document record - if (empty($docid)) { + if (!$docid) { $docid = $this->documentIdentifier; $docRow = $this->documentObject; } else { $docRow = $this->getDocument($docid, '*', $published); - if (!$docRow) { $cache[$cacheKey] = false; return false; } } - // get user defined template variables - if (!empty($fields) && (is_scalar($fields) || \is_array($fields))) { - if(\is_scalar($fields)) { - $fields = explode(',', $fields); - } - $fields = array_filter(array_map('trim', $fields), function($value) { - return $value !== 'value'; - }); - $fields = 'tv.' . implode(',tv.', $fields); - } else { + if (!$fields || (!is_scalar($fields) && !is_array($fields))) { $fields = 'tv.*'; - } - - if ($idnames === '*') { - $query = 'tv.id<>0'; } else { - $query = (is_numeric($idnames[0]) ? 'tv.id' : 'tv.name') . " IN ('" . implode("','", $idnames) . "')"; + if (is_scalar($fields)) { + $fields = explode(',', $fields); + } + $fields = sprintf( + 'tv.%s', + implode( + ',tv.', + array_filter(array_map('trim', $fields), static function ($value) { + return $value !== 'value'; + }) + ) + ); } $rs = $this->db->select( $fields . ", IF(tvc.value != '', tvc.value, tv.default_text) as value", - $this->getFullTableName('site_tmplvars') . ' tv ' . - 'INNER JOIN ' . $this->getFullTableName('site_tmplvar_templates') . ' tvtpl ON tvtpl.tmplvarid = tv.id ' . - 'LEFT JOIN ' . $this->getFullTableName('site_tmplvar_contentvalues') . " tvc ON tvc.tmplvarid = tv.id AND tvc.contentid = '" . $docid . "'", - $query . " AND tvtpl.templateid = '" . $docRow['template'] . "'", + [ + sprintf('%s tv', $this->getFullTableName('site_tmplvars')), + sprintf( + 'INNER JOIN %s tvtpl ON tvtpl.tmplvarid=tv.id ', + $this->getFullTableName('site_tmplvar_templates') + ), + sprintf( + "LEFT JOIN %s tvc ON tvc.tmplvarid=tv.id AND tvc.contentid='%s'", + $this->getFullTableName('site_tmplvar_contentvalues'), + $docid + ) + ], + $idnames === '*' + ? 'tv.id!=0' + : sprintf( + "%s IN ('%s') AND tvtpl.templateid='%s'", + is_numeric($idnames[0]) ? 'tv.id' : 'tv.name', + implode("','", $idnames), + $docRow['template'] + ), $sort - ? sprintf( - 'tv.%s %s', - implode(',tv.', array_filter(array_map('trim', explode(',', $sort)))), - $dir - ) - : '' + ? sprintf( + 'tv.%s %s', + implode(',tv.', array_filter(array_map('trim', explode(',', $sort)))), + $dir + ) + : '' ); $result = $this->db->makeArray($rs); From f3175d1307c9dab23c947f96d4a990e7df504e51 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Thu, 12 Jan 2023 10:46:44 +0900 Subject: [PATCH 47/49] refactor $modx->getTemplateVarOutput() --- .../includes/document.parser.class.inc.php | 61 ++++++++++--------- 1 file changed, 33 insertions(+), 28 deletions(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index ed67d9c14e..2dc74e8d25 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -5131,10 +5131,6 @@ public function getTemplateVars($idnames = [], /** * getTemplateVarOutput - * @version 1.0.1 (2014-02-19) - * - * @desc Returns an associative array containing TV rendered output values. - * * @param array $idnames {array; '*'} * - Which TVs to fetch - Can relate to the TV ids in the db (array elements should be numeric only) or the TV names (array elements should be names only). @required * @param string $docid {integer; ''} @@ -5143,41 +5139,50 @@ public function getTemplateVars($idnames = [], * - Document publication status. Once the parameter equals 'all', the result will be returned regardless of whether the ducuments are published or they are not. Default: 1. * @param string $sep {string} * - Separator that is used while concatenating in getTVDisplayFormat(). Default: ''. - * @return array {array; false} - Result array, or false. + * @return array|false * - Result array, or false. + *@version 1.0.1 (2014-02-19) + * + * @desc Returns an associative array containing TV rendered output values. + * */ public function getTemplateVarOutput($idnames = [], $docid = '', $published = 1, $sep = '') { - if (is_array($idnames) && empty($idnames) ) { + if (!$idnames) { return false; - } else { - $output = []; - $vars = ($idnames == '*' || is_array($idnames)) ? $idnames : array($idnames); - - $docid = (int)$docid > 0 ? (int)$docid : $this->documentIdentifier; - // remove sort for speed - $result = $this->getTemplateVars($vars, '*', $docid, $published, '', ''); + } - if ($result == false) { - return false; - } else { - $baspath = MODX_MANAGER_PATH . 'includes'; - include_once $baspath . '/tmplvars.format.inc.php'; - include_once $baspath . '/tmplvars.commands.inc.php'; + if (!preg_match('/^[1-9][0-9]*$/', $docid)) { + $docid = $this->documentIdentifier; + } - for ($i = 0; $i < count($result); $i++) { - $row = $result[$i]; + $result = $this->getTemplateVars( + (is_array($idnames) || $idnames === '*') ? $idnames : array($idnames), + '*', + $docid, + $published, + '', + '' + ); + if (!$result) { + return false; + } - if (!isset($row['id']) or !$row['id']) { - $output[$row['name']] = $row['value']; - } else { - $output[$row['name']] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'], $docid, $sep); - } - } + include_once __DIR__ . '/tmplvars.format.inc.php'; + include_once __DIR__ . '/tmplvars.commands.inc.php'; - return $output; + $output = []; + foreach ($result as $row) { + if (empty($row['id'])) { + $output[$row['name']] = $row['value']; + continue; } + $output[$row['name']] = getTVDisplayFormat( + $row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'], $docid, $sep + ); } + + return $output; } /** From d76f9b77193cdadccce8c777a8a8a346a291b181 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Thu, 12 Jan 2023 10:47:45 +0900 Subject: [PATCH 48/49] fix - $modx->getField() --- manager/includes/document.parser.class.inc.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/manager/includes/document.parser.class.inc.php b/manager/includes/document.parser.class.inc.php index 2dc74e8d25..5435b75224 100755 --- a/manager/includes/document.parser.class.inc.php +++ b/manager/includes/document.parser.class.inc.php @@ -4189,7 +4189,7 @@ public function getField($field = 'content', $docid = '') $doc = $this->getDocumentObject('id', $docid); if (is_array($doc[$field])) { - $tvs = $this->getTemplateVarOutput($field, $docid, 1); + $tvs = $this->getTemplateVarOutput($field, $docid, 'all'); $cache[$field][$docid] = $tvs[$field]; } else { $cache[$field][$docid] = $doc[$field]; From ebb3898ca948fb14083b5fcce3806c69343368c4 Mon Sep 17 00:00:00 2001 From: Yamamoto Date: Fri, 13 Jan 2023 00:09:24 +0900 Subject: [PATCH 49/49] update require php version 5.6 => 7.0 --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index a9800b1840..49ec2ff6b2 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,7 @@ "vendor-dir": "vendor" }, "require": { - "php": ">=5.6", + "php": ">=7.0", "ext-json": "*" }, "minimum-stability": "dev",