From 0f5437963b5355da4fb3119f7f2014cee127b0b4 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Mon, 10 Feb 2020 14:24:09 +0300 Subject: [PATCH 01/10] * Minor changes. --- modx.ddtools.class.php | 66 +++++++++++++++++++---------------- src/BaseClass/BaseClass.php | 8 ++--- src/FilesTools/FilesTools.php | 6 ++-- 3 files changed, 42 insertions(+), 38 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 5a338bf..2effb6f 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -177,13 +177,13 @@ public static function getInstance(){ * * @desc Convert list of ordered parameters to named. Method is public, but be advised that this is beta-version! * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['paramsList'] {array} — Parameters in ordered list (func_get_args). @required * @param $params['paramsList'][i] {mixed} — Parameter value. @required * @param $params['compliance'] {array} — The order of parameters. @required * @param $params['compliance'][i] {string} — Parameter name. @required * - * @return {array_associative} + * @return {arrayAssociative} */ public static function orderedParamsToNamed($params){ $params = (object) $params; @@ -260,7 +260,7 @@ public static function orderedParamsToNamed($params){ * @param $itemDelimiter {string} — Separator between pairs of key-value. Default: '||'. * @param $keyValDelimiter {string} — Separator between key and value. Default: '::'. * - * @return {array_associative} + * @return {arrayAssociative} */ public static function explodeAssoc( $inputString, @@ -478,7 +478,7 @@ public static function sort2dArray( * * @param $file {string|array} — String of file path or result array of pathinfo() function. @required * - * @return $result {array_associative} — File data. + * @return $result {arrayAssociative} — File data. * @return $result['name'] {string} — File name. * @return $result['version'] {string} — File version. * @return $result['extension'] {string} — File extension. @@ -528,7 +528,7 @@ public static function parseFileNameVersion($file){ * * @desc Makes directory using `$modx->config['new_folder_permissions']`. Nested directories will be created too. Doesn't throw an exception if the folder already exists. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params->path {string} — The directory path. @required * * @return {boolean} — Success status. @@ -754,7 +754,7 @@ public static function encodedStringToArray($inputString){ * * @desc Finds all placeholders' names and returns them as an array. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['text'] {string} — Source string. @required * @param $params['placeholderPrefix'] {string} — Placeholders prefix. Default: '[+'. * @param $params['placeholderSuffix'] {string} — Placeholders suffix. Default: '+]'. @@ -794,7 +794,7 @@ public static function getPlaceholdersFromText($params = []){ * * @desc Add an alert message to the system event log with debug info (backtrace, snippet name, document id, etc). * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['message'] {string} — Message to be logged. Default: ''. * @param $params['source'] {string} — Source of the event (module, snippet name, etc). Default: $modx->currentSnippet || caller. * @param $params['eventId'] {integer} — Event ID. Default: 1. @@ -900,10 +900,10 @@ public static function logEvent($params){ * * @desc Similar to $modx->parseChunk, but takes a text. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['text'] {string} — String to parse. @required - * @param $params['data'] {array_associative|stdClass} — Array of values. Nested arrays are supported too: “['stringPlaceholder' = > 'one', 'arrayPlaceholder' => ['a' => 'one', 'b' => 'two']]” => “[+stringPlaceholder+]”, “[+arrayPlaceholder.a+]”, “[+arrayPlaceholder.b+]”. Default: []. - * @param $params['data'][key] {string|array_associative|stdClass} — Key — placeholder name, value — value. + * @param $params['data'] {arrayAssociative|stdClass} — Array of values. Nested arrays are supported too: “['stringPlaceholder' = > 'one', 'arrayPlaceholder' => ['a' => 'one', 'b' => 'two']]” => “[+stringPlaceholder+]”, “[+arrayPlaceholder.a+]”, “[+arrayPlaceholder.b+]”. Default: []. + * @param $params['data'][key] {string|arrayAssociative|stdClass} — Key — placeholder name, value — value. * @param $params['placeholderPrefix'] {string} — Placeholders prefix. Default: '[+'. * @param $params['placeholderSuffix'] {string} — Placeholders suffix. Default: '+]'. * @param $params['removeEmptyPlaceholders'] {boolean} — Do you need to remove empty placeholders? Default: false. @@ -1011,19 +1011,19 @@ public static function parseSource($source){ * * @desc Prepare document data from single array of fields and TVs: separate them and get TV IDs if needed. * - * @param $params {array_associative|stdClass} — The object of params. @required - * @param $params['data'] {array_associative} — Array of document fields (from table `site_content`) or TVs with values. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required + * @param $params['data'] {arrayAssociative} — Array of document fields (from table `site_content`) or TVs with values. @required * @param $params['data'][key] {mixed} — Field value (optional), when key is field name. The method use only keys, values just will be returned without changes. @required * @param $params['tvAdditionalFieldsToGet'] {array} — Fields of TVs to get if needed (e. g. 'id', 'type'). Default: []. * @param $params['tvAdditionalFieldsToGet'][i] {string} — TV field. * * @return $result {stdClass} - * @return $result->fieldsData {array_associative} — Document fields data (like 'id', 'pagetitle', etc). @required + * @return $result->fieldsData {arrayAssociative} — Document fields data (like 'id', 'pagetitle', etc). @required * @return $result->fieldsData[key] {mixed} — Field value, when key is field name. - * @return $result->tvsData {array_associative} — TVs values. @required + * @return $result->tvsData {arrayAssociative} — TVs values. @required * @return $result->tvsData[key] {mixed} — TV value, when key is TV name. - * @return $result->tvsAdditionalData {array_associative} — TVs additional data, when key is TV name. @required - * @return $result->tvsAdditionalData[key] {array_associative} — TV data, when key is TV name. + * @return $result->tvsAdditionalData {arrayAssociative} — TVs additional data, when key is TV name. @required + * @return $result->tvsAdditionalData[key] {arrayAssociative} — TV data, when key is TV name. * @return $result->tvsAdditionalData[key][item] {string} — TV data. */ public static function prepareDocData($params){ @@ -1102,7 +1102,7 @@ public static function prepareDocData($params){ * * @desc Create a new document. * - * @param $docData {array_associative} — Array of document fields or TVs. Key — name, value — value. @required + * @param $docData {arrayAssociative} — Array of document fields or TVs. Key — name, value — value. @required * @param $docData['pagetitle'] {string} — Document pagetitle. @required * @param $docGroups {array} — Array of document groups id. * @@ -1248,14 +1248,14 @@ public static function createDocument( /** * updateDocument - * @version 1.3.2 (2019-06-22) + * @version 1.3.3 (2020-02-10) * * @desc Update a document. * * @note $docId and/or $where are required. * * @param $docId {integer|array} — Document id(s) to update. @required - * @param $docData {array_associative} — Array of document fields or TVs to update. Key — name, value — value. @required + * @param $docData {arrayAssociative} — Array of document fields or TVs to update. Key — name, value — value. @required * @param $where {string} — SQL WHERE string. Default: ''. * * @return {boolean} — true — если всё хорошо, или false — если такого документа нет, или ещё что-то пошло не так. @@ -1280,10 +1280,14 @@ public static function updateDocument( count($docId) ){ //Обрабатываем массив id - $whereSql .= '`id` IN ("' . implode( - '","', - $docId - ) . '")'; + $whereSql .= + '`id` IN ("' . + implode( + '","', + $docId + ) . + '")' + ; }else if ( is_numeric($docId) && $docId != 0 @@ -2105,12 +2109,12 @@ public static function getDocumentChildrenTVarOutput( * * @see ddRegJsCssLinks snippet (http://code.divandesign.biz/modx/ddregjscsslinks), предназначенный для «правильного» подключения js и css. Даже при «ручном» подключении сниппет регистрирует то, что подключил, используя данный метод. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['name'] {string} — Script name. @required * @param $params['version'] {string} — Script version. Default: '0'. * @param $params['startup'] {boolean} — Is the script connected in the ? Default: false. * - * @return $result {array_associative|''} — empty string if $name is not set or an array of: + * @return $result {arrayAssociative|''} — empty string if $name is not set or an array of: * @return $result['name'] {string} — Script name. * @return $result['version'] {string} — Script version (если был ранее подключен более поздняя версия, вернётся она). * @return $result['useThisVer'] {boolean} — Использовалась ли та версия, что передали. @@ -2302,7 +2306,7 @@ public static function getDocumentIdByUrl($url){ * //After extraction we can safaly use the variables “$docId” and “docField” * ``` * - * @return {array_associative} — An array, in which the correct parameter names are the keys and the parameter values are the values. + * @return {arrayAssociative} — An array, in which the correct parameter names are the keys and the parameter values are the values. */ public static function verifyRenamedParams( $params, @@ -2360,7 +2364,7 @@ public static function verifyRenamedParams( * * @desc Method for sending e-mails. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['to'] {array} — Addresses to mail. @required * @param $params['to'][i] {string_email} — An address. @required * @param $params['text'] {string} — E-mail text. @required @@ -2525,14 +2529,14 @@ public static function screening($str){ * * @desc Explode associative array of fields and TVs in two individual arrays. * - * @param $fields {array_associative} — Array of document fields (from table `site_content`) or TVs with values. @required + * @param $fields {arrayAssociative} — Array of document fields (from table `site_content`) or TVs with values. @required * @param $fields[key] {mixed} — Field value (optional), when key is field name. The method use only keys, values just will be returned without changes. @required * * @return $result {array} - * @return $result[0] {array_associative} — Document fields (like 'id', 'pagetitle', etc). + * @return $result[0] {arrayAssociative} — Document fields (like 'id', 'pagetitle', etc). * @return $result[0][key] {mixed} — Field value, when key is field name. - * @return $result[1] {array_associative} — TVs. - * @return $result[1][key] {array_associative} — TV, when key is TV name. + * @return $result[1] {arrayAssociative} — TVs. + * @return $result[1][key] {arrayAssociative} — TV, when key is TV name. * @return $result[1][key]['id'] {integer} — TV id. * @return $result[1][key]['val'] {mixed} — TV value. */ diff --git a/src/BaseClass/BaseClass.php b/src/BaseClass/BaseClass.php index d18d234..8dcacb9 100644 --- a/src/BaseClass/BaseClass.php +++ b/src/BaseClass/BaseClass.php @@ -8,7 +8,7 @@ class BaseClass { * * @desc Sets existing object properties. * - * @param $params {array_associative|stdClass} — The object properties. @required + * @param $params {arrayAssociative|stdClass} — The object properties. @required * * @return {void} */ @@ -34,7 +34,7 @@ public function setExistingProps($props){ * * @throws \ReflectionException * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params->object {object} — Объект для модификации. @required * @param $params->propName {string} — Имя поля. @required * @param $params->propValue {mixed} — Значение. @required @@ -88,10 +88,10 @@ private function setProp($params){ * * @throws \Exception * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params->parentDir {string} — Directory of the parent file (e. g. __DIR__). @required * @param $params->name {string} — Class name. @required - * @param $params->params {array_associative|stdClass} — Params to be passed to object constructor. Default: []. + * @param $params->params {arrayAssociative|stdClass} — Params to be passed to object constructor. Default: []. * @param $params->capitalizeName {boolean} — Need to capitalize child name? Default: true. * * @return {object} diff --git a/src/FilesTools/FilesTools.php b/src/FilesTools/FilesTools.php index 6069bc6..d7f1b07 100644 --- a/src/FilesTools/FilesTools.php +++ b/src/FilesTools/FilesTools.php @@ -8,7 +8,7 @@ class FilesTools { * * @desc Makes directory using `$modx->config['new_folder_permissions']`. Nested directories will be created too. Doesn't throw an exception if the folder already exists. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params->path {string} — The directory path. @required * * @return {boolean} — Success status. @@ -40,7 +40,7 @@ public static function createDir($params){ * * @desc Copies a required folder with all contents recursively. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['sourcePath'] {string} — Path to the directory, that should copied. @required * @param $params['destinationPath'] {string} — The destination path. @required * @@ -142,7 +142,7 @@ public static function removeDir($path){ * * @desc Делает превьюшку. * - * @param $params {array_associative|stdClass} — The object of params. @required + * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params['sourceFullPathName'] {string} — Адрес оригинального изображения. @required * @param $params['outputFullPathName'] {string} — Адрес результирующего изображения. @required * @param $params['transformMode'] {'resize'|'crop'|'resizeAndCrop'|'resizeAndFill'} — Режим преобразования. @required From 3f1f1a95b0b5306bd19704b6046bfb8dee7c20df Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Mon, 10 Feb 2020 14:43:28 +0300 Subject: [PATCH 02/10] * Minor changes. --- modx.ddtools.class.php | 44 ++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 2effb6f..0ab245e 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1007,7 +1007,7 @@ public static function parseSource($source){ /** * prepareDocData - * @version 2.0.2 (2019-06-22) + * @version 2.0.3 (2020-02-10) * * @desc Prepare document data from single array of fields and TVs: separate them and get TV IDs if needed. * @@ -1082,10 +1082,14 @@ public static function prepareDocData($params){ //From self::$tables['site_tmplvars'], //Where - "`name` IN ('" . implode( - "','", - array_keys($result->tvsData) - ) . "')" + ( + "`name` IN ('" . + implode( + "','", + array_keys($result->tvsData) + ) . + "')" + ) ); while ($row = self::$modx->db->getRow($dbRes)){ @@ -1098,7 +1102,7 @@ public static function prepareDocData($params){ /** * createDocument - * @version 1.2.2 (2019-06-22) + * @version 1.2.3 (2020-02-10) * * @desc Create a new document. * @@ -1113,19 +1117,29 @@ public static function createDocument( $docGroups = false ){ //Если нет хотя бы заголовка, выкидываем - if (!$docData['pagetitle']){return false;} + if (!$docData['pagetitle']){ + return false; + } //Если не передана дата создания документа, ставим текущую - if (!$docData['createdon']){$docData['createdon'] = time();} + if (!$docData['createdon']){ + $docData['createdon'] = time(); + } //Если не передано, кем документ создан, ставим 1 - if (!$docData['createdby']){$docData['createdby'] = 1;} + if (!$docData['createdby']){ + $docData['createdby'] = 1; + } //Если группы заданы, то это приватный документ - if ($docGroups){$docData['privatemgr'] = 1;} + if ($docGroups){ + $docData['privatemgr'] = 1; + } //Если надо публиковать, поставим дату публикации текущей - if ($docData['published'] == 1){$docData['pub_date'] = $docData['createdon'];} + if ($docData['published'] == 1){ + $docData['pub_date'] = $docData['createdon']; + } $docData = self::prepareDocData([ 'data' => $docData, @@ -1141,7 +1155,9 @@ public static function createDocument( self::$tables['site_content'] ); - if (!$docId){return false;} + if (!$docId){ + return false; + } //Если есть хоть одна существующая TV if (count($docData->tvsAdditionalData) > 0){ @@ -1163,11 +1179,13 @@ public static function createDocument( //Добавляем значение TV в базу self::$modx->db->insert( + //Fields [ 'value' => $docData->tvsData[$tvName], 'tmplvarid' => $tvData['id'], 'contentid' => $docId ], + //Table self::$tables['site_tmplvar_contentvalues'] ); } @@ -1181,10 +1199,12 @@ public static function createDocument( $docGroupId ){ self::$modx->db->insert( + //Field [ 'document_group' => $docGroupId, 'document' => $docId ], + //Table self::$tables['document_groups'] ); } From 7f4f8c56b72774d0984d8f1c8252b2f7d83011bc Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 19:32:21 +0300 Subject: [PATCH 03/10] * Minor changes. --- modx.ddtools.class.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 0ab245e..8233ba7 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1438,7 +1438,7 @@ public static function updateDocument( * @param $ids {array} — Documents Ids to get. @required * @param $published {'all'|0|1} — Documents publication status which does not matter if published === 'all'. Default: 'all'. * @param $deleted {'all'|0|1} — Documents removal status which does not matter if deleted === 'all'. Default: 0. - * @param $fields {string_commaSeparated|'*'} — Documents fields to get. Default: '*'. + * @param $fields {stringCommaSeparated|'*'} — Documents fields to get. Default: '*'. * @param $where {string} — SQL WHERE clause. Default: ''. * @param $sort {string} — A field to sort by. Default: 'menuindex'. * @param $dir {'ASC'|'DESC'} — Sorting direction. Default: 'ASC'. @@ -1570,7 +1570,7 @@ public static function getDocuments( * — $deleted parameter can be set as === 'all' to retrieve the documents regardless of their removal status. * * @param $id {integer} — Id of a document which data is being got. @required - * @param $fields {string_commaSeparated|'*'} — Documents fields to get. Default: '*'. + * @param $fields {stringCommaSeparated|'*'} — Documents fields to get. Default: '*'. * @param $published {'all'|0|1} — Document publication status which does not matter if published === 'all'. Default: 'all'. * @param $deleted {'all'|0|1} — Document removal status which does not matter if published === 'all'. Default: 0. * @@ -1633,10 +1633,10 @@ public static function getDocument( * — $published parameter can be set as ==='all' to retrieve the documents regardless of their publication status. * * @param $idnames {array|'*'} — Id, TVs names, or documents fields to get. @required - * @param $fields {string_commaSeparated|'*'} — Fields names in the TV table of MODx database. Default: '*'. + * @param $fields {stringCommaSeparated|'*'} — Fields names in the TV table of MODx database. Default: '*'. * @param $docid {integer|''} — Id of a document to get. Default: Current document. * @param $published {'all'|0|1} — Document publication status which does not matter if published === 'all'. Default: 'all'. - * @param $sort {string_commaSeparated} — Fields of the TV table to sort by. Default: 'rank'. + * @param $sort {stringCommaSeparated} — Fields of the TV table to sort by. Default: 'rank'. * @param $dir {'ASC'|'DESC'} — Sorting direction. Default: 'ASC'. * * @return {array|false} @@ -1887,9 +1887,9 @@ public static function getTemplateVarOutput( * @param $parentid {integer} — Id of parent document. Default: 0. * @param $published {'all'|0|1} — Documents publication status which does not matter if published === 'all'. Default: 1. * @param $deleted {'all'|0|1} — Documents removal status which does not matter if deleted === 'all'. Default: 0. - * @param $fields {string_commaSeparated} — Documents fields to get. Default: '*'. + * @param $fields {stringCommaSeparated} — Documents fields to get. Default: '*'. * @param $where {string} — SQL WHERE clause. Default: ''. - * @param $sort {string|string_commaSeparated} — Transfer a few conditions separated with comma (like SQL) to multiple sort, but param “sortDir” must be '' in this case. Default: 'menuindex'. + * @param $sort {string|stringCommaSeparated} — Transfer a few conditions separated with comma (like SQL) to multiple sort, but param “sortDir” must be '' in this case. Default: 'menuindex'. * @param $dir {'ASC'|'DESC'|''} — Direction for sort. Default: 'ASC'. * @param $limit {string} — SQL LIMIT (without 'LIMIT'). Default: ''. * @@ -2022,7 +2022,7 @@ public static function getDocumentChildren( * @param $parentid {integer} — Id of parent document. Default: 0. * @param $tvidnames {array} — Array of document fields or TVs to get. Default: [$resultKey]. * @param $published {'all'|0|1} — Documents publication status which does not matter if published === 'all'. Default: 1. - * @param $sortBy {string|string_commaSeparated} — Transfer a few conditions separated with comma (like SQL) to multiple sort, but param “sortDir” must be '' in this case. Default: 'menuindex'. + * @param $sortBy {string|stringCommaSeparated} — Transfer a few conditions separated with comma (like SQL) to multiple sort, but param “sortDir” must be '' in this case. Default: 'menuindex'. * @param $sortDir {'ASC'|'DESC'|''} — Direction for sort. Default: 'ASC'. * @param $where {string} — SQL WHERE condition (use only document fields, not TV). Default: ''. * @param $resultKey {string|false} — Field, which values are keys into result array. Use the “false”, that result array keys just will be numbered. Default: 'id'. From 52daba10a6f3bc863de2ac381bf78306f183a205 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 20:37:27 +0300 Subject: [PATCH 04/10] * Attention! (MODX)EvolutionCMS >= 1.1 is required. + `\ddTools::clearCache`. Clears cache of required document(s). --- README.md | 2 +- modx.ddtools.class.php | 62 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 443118c..c12849b 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ A library with various tools facilitating your work. ## # Requires * PHP >= 5.4 -* [(MODX)EvolutionCMS](https://github.com/evolution-cms/evolution) >= 1.0.10 +* [(MODX)EvolutionCMS](https://github.com/evolution-cms/evolution) >= 1.1 * [PHP.libraries.phpThumb](http://phpthumb.sourceforge.net) 1.7.13-201406261000 (included) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 8233ba7..e5c821a 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1005,6 +1005,68 @@ public static function parseSource($source){ return self::$modx->rewriteUrls(self::$modx->parseDocumentSource($source)); } + /** + * clearCache + * @version 1.0 (2020-02-11) + * + * @desc Clears cache of required document(s). + * + * @param $params {arrayAssociative|stdClass} — The object of params. @required + * @param $params->docIds {arrayAssociative|stringCommaSeparated} — Document ID(s). @required + * @param $params->docIds[i] {integer} — Document ID. @required + * + * @return {void} + */ + public static function clearCache($params){ + $params = (object) $params; + + //Comma separated strings support + if (!is_array($params->docIds)){ + $params->docIds = explode( + ',', + $params->docIds + ); + } + + $cacheFilePrefix = + self::$modx->getConfig('base_path') . + self::$modx->getCacheFolder() . + 'docid_' + ; + + $cacheFileSuffix = '.pageCache.php'; + + foreach ( + $params->docIds as + $docId + ){ + //$_GET cache + $cacheFiles = glob( + $cacheFilePrefix . + $docId . + '_*' . + $cacheFileSuffix + ); + //Without $_GET + $cacheFiles[] = + $cacheFilePrefix . + $docId . + $cacheFileSuffix + ; + + foreach ( + $cacheFiles as + $cacheFiles_item + ){ + if (!is_file($cacheFiles_item)){ + continue; + } + + unlink($cacheFiles_item); + } + } + } + /** * prepareDocData * @version 2.0.3 (2020-02-10) From da5a3a343796a27a8063a97d03d4ac5f401d6a50 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 20:42:04 +0300 Subject: [PATCH 05/10] - Completely removed compatibility with (MODX)EvolutionCMS < 1.1. --- modx.ddtools.class.php | 22 ++-------------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index e5c821a..1690116 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -16,8 +16,6 @@ class ddTools { $modx, //Contains names of document fields (`site_content`) $documentFields = [ - //For MODX > 1.0.11 - //alias_visible, 'id', 'type', 'contentType', @@ -25,6 +23,7 @@ class ddTools { 'longtitle', 'description', 'alias', + 'alias_visible', 'link_attributes', 'published', 'pub_date', @@ -113,7 +112,7 @@ class ddTools { /** * __construct - * @version 1.0.2 (2019-06-22) + * @version 1.0.3 (2020-02-11) */ private function __construct(){ global $modx; @@ -129,23 +128,6 @@ private function __construct(){ self::$tables[$tableAlias] = self::$modx->getFullTableName($tableAlias); } - if (method_exists( - self::$modx, - 'getVersionData' - )){ - //В новом MODX в метод можно просто передать 'version' и сразу получить нужный элемент, но не в старом - $modxVersionData = self::$modx->getVersionData(); - - //If version of MODX > 1.0.11 - if (version_compare( - $modxVersionData['version'], - '1.0.11', - '>' - )){ - self::$documentFields[] = 'alias_visible'; - } - } - //We need to include required files if Composer is not used if(!class_exists('\DDTools\FilesTools')){ require_once __DIR__.DIRECTORY_SEPARATOR . 'require.php'; From 268bffff445a8810dad55ec3607ae182235d0009 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 21:01:15 +0300 Subject: [PATCH 06/10] * Minor changes. --- modx.ddtools.class.php | 280 ++++++++++++++++++++++++++++------------- 1 file changed, 196 insertions(+), 84 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 1690116..5a8f02d 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -112,7 +112,7 @@ class ddTools { /** * __construct - * @version 1.0.3 (2020-02-11) + * @version 1.0.4 (2020-02-11) */ private function __construct(){ global $modx; @@ -130,7 +130,11 @@ private function __construct(){ //We need to include required files if Composer is not used if(!class_exists('\DDTools\FilesTools')){ - require_once __DIR__.DIRECTORY_SEPARATOR . 'require.php'; + require_once( + __DIR__ . + DIRECTORY_SEPARATOR . + 'require.php' + ); } } @@ -454,7 +458,7 @@ public static function sort2dArray( /** * parseFileNameVersion - * @version 1.1.3 (2019-06-22) + * @version 1.1.4 (2020-02-11) * * @desc Parses a file path and gets its name, version & extension. * @@ -471,7 +475,11 @@ public static function parseFileNameVersion($file){ //Просто запоминаем его $fileinfo = $file; //А также запоминаем строку - $file = $fileinfo['dirname'] . '/' . $fileinfo['basename']; + $file = + $fileinfo['dirname'] . + '/' . + $fileinfo['basename'] + ; //Если передали строку }else{ //Получаем необходимые данные @@ -732,7 +740,7 @@ public static function encodedStringToArray($inputString){ /** * getPlaceholdersFromText - * @version 1.0.1 (2019-06-22) + * @version 1.0.2 (2020-02-11) * * @desc Finds all placeholders' names and returns them as an array. * @@ -760,7 +768,13 @@ public static function getPlaceholdersFromText($params = []){ $result = []; preg_match_all( - '/' . $params->placeholderPrefix . '(.*?)' . $params->placeholderSuffix . '/', + ( + '/' . + $params->placeholderPrefix . + '(.*?)' . + $params->placeholderSuffix . + '/' + ), $params->text, $result ); @@ -772,7 +786,7 @@ public static function getPlaceholdersFromText($params = []){ /** * logEvent - * @version 1.0.2 (2019-06-22) + * @version 1.0.3 (2020-02-11) * * @desc Add an alert message to the system event log with debug info (backtrace, snippet name, document id, etc). * @@ -821,7 +835,11 @@ public static function logEvent($params){ //Add current document Id to debug info if (!empty(self::$modx->documentIdentifier)){ - $debugInfo[] = '
  • Document id: “' . self::$modx->documentIdentifier . '”;
  • '; + $debugInfo[] = + '
  • Document id: “' . + self::$modx->documentIdentifier . + '”;
  • ' + ; } //Is the code being run in the snippet? @@ -832,21 +850,31 @@ public static function logEvent($params){ $params->source = self::$modx->currentSnippet; }else{ //Add to debug info - $debugInfo[] = '
  • Snippet: “' . self::$modx->currentSnippet . '”;
  • '; + $debugInfo[] = + '
  • Snippet: “' . + self::$modx->currentSnippet . + '”;
  • ' + ; } } - if ($params->source == ''){$params->source = $caller;} + if ($params->source == ''){ + $params->source = $caller; + } //Add debug info to the message $params->message .= '

    Debug info

    '; if (!empty($debugInfo)){ - $params->message .= '
      ' . implode( - '', - $debugInfo - ) . '
    '; + $params->message .= + '
      ' . + implode( + '', + $debugInfo + ) . + '
    ' + ; } //Add backtrace to message @@ -860,11 +888,19 @@ public static function logEvent($params){ 1 )){ //Information - case 'i': $params->eventType = 1; break; + case 'i': + $params->eventType = 1; + break; + //Warning - case 'w': $params->eventType = 2; break; + case 'w': + $params->eventType = 2; + break; + //Error - case 'e': $params->eventType = 3; break; + case 'e': + $params->eventType = 3; + break; } @@ -1051,7 +1087,7 @@ public static function clearCache($params){ /** * prepareDocData - * @version 2.0.3 (2020-02-10) + * @version 2.0.4 (2020-02-11) * * @desc Prepare document data from single array of fields and TVs: separate them and get TV IDs if needed. * @@ -1119,10 +1155,14 @@ public static function prepareDocData($params){ //Получаем id всех необходимых TV $dbRes = self::$modx->db->select( //Fields - '`' . implode( - '`, `', - $params->tvAdditionalFieldsToGet - ) . '`', + ( + '`' . + implode( + '`, `', + $params->tvAdditionalFieldsToGet + ) . + '`' + ), //From self::$tables['site_tmplvars'], //Where @@ -1470,7 +1510,7 @@ public static function updateDocument( /** * getDocuments - * @version 1.2.7 (2019-06-22) + * @version 1.2.8 (2020-02-11) * * @desc Returns required documents (documents fields). * @@ -1539,30 +1579,36 @@ public static function getDocuments( 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( + $fields = + 'sc.' . + implode( ',sc.', array_filter(array_map( 'trim', explode( ',', - $sort + $fields ) )) ) ; + $sort = + $sort == '' ? + '' : + ( + 'sc.' . + implode( + ',sc.', + array_filter(array_map( + 'trim', + explode( + ',', + $sort + ) + )) + ) + ) + ; if ($where != ''){ $where = 'AND ' . $where; } @@ -1579,20 +1625,35 @@ public static function getDocuments( ; $result = self::$modx->db->select( + //Fields 'DISTINCT ' . $fields, + //From self::$tables['site_content'] . ' sc LEFT JOIN ' . self::$tables['document_groups'] . ' dg ON dg.document = sc.id ', - '(sc.id IN (' . implode( - ',', - $ids - ) . ') ' . $published . ' ' . $deleted . ' ' . $where . ') GROUP BY sc.id', + //Where + ( + '(sc.id IN (' . + implode( + ',', + $ids + ) . + ') ' . + $published . + ' ' . + $deleted . + ' ' . + $where . + ') GROUP BY sc.id' + ), + //Order ( $sort ? $sort . ' ' . $dir : '' ), + //Limit $limit ); @@ -1668,7 +1729,7 @@ public static function getDocument( /** * getTemplateVars - * @version 1.3.8 (2019-06-22) + * @version 1.3.9 (2020-02-11) * * @desc Returns the TV and fields array of a document. * @@ -1732,29 +1793,35 @@ public static function getTemplateVars( $fields = $fields == '' ? 'tv.*' : - 'tv.' . implode( - ',tv.', - array_filter(array_map( - 'trim', - explode( - ',', - $fields - ) - )) + ( + 'tv.' . + implode( + ',tv.', + array_filter(array_map( + 'trim', + explode( + ',', + $fields + ) + )) + ) ) ; $sort = $sort == '' ? '' : - 'tv.' . implode( - ',tv.', - array_filter(array_map( - 'trim', - explode( - ',', - $sort - ) - )) + ( + 'tv.' . + implode( + ',tv.', + array_filter(array_map( + 'trim', + explode( + ',', + $sort + ) + )) + ) ) ; @@ -1777,14 +1844,26 @@ public static function getTemplateVars( } $rs = self::$modx->db->select( - $fields . ', IF(tvc.value != "", tvc.value, tv.default_text) as value', + //Fields + ( + $fields . + ', IF(tvc.value != "", tvc.value, tv.default_text) as value' + ), + //From self::$tables['site_tmplvars'] . ' tv INNER JOIN ' . self::$tables['site_tmplvar_templates'] . ' tvtpl ON tvtpl.tmplvarid = tv.id LEFT JOIN ' . self::$tables['site_tmplvar_contentvalues'] . ' tvc ON tvc.tmplvarid=tv.id AND tvc.contentid = "' . $docid . '" ', - $query . ' AND tvtpl.templateid = "' . $docRow['template'] . '"', + //Where + ( + $query . + ' AND tvtpl.templateid = "' . + $docRow['template'] . + '"' + ), + //Order ( $sort ? $sort . ' ' . $dir : @@ -1825,7 +1904,7 @@ public static function getTemplateVars( /** * getTemplateVarOutput - * @version 1.1.7 (2019-06-22) + * @version 1.1.8 (2020-02-11) * * @desc Returns the associative array of fields and TVs of a document. * @@ -1886,9 +1965,19 @@ public static function getTemplateVarOutput( 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'; + $baspath = + MODX_MANAGER_PATH . + 'includes' + ; + + include_once( + $baspath . + '/tmplvars.format.inc.php' + ); + include_once( + $baspath . + '/tmplvars.commands.inc.php' + ); for ( $i= 0; @@ -1919,7 +2008,7 @@ public static function getTemplateVarOutput( /** * getDocumentChildren - * @version 1.2.6 (2019-06-22) + * @version 1.2.7 (2020-02-11) * * @desc Returns the associative array of a document fields. * @@ -1983,30 +2072,36 @@ public static function getDocumentChildren( } // modify field names to use sc. table reference - $fields = 'sc.' . implode( - ',sc.', - array_filter(array_map( - 'trim', - explode( - ',', - $fields - ) - )) - ); - $sort = - $sort == '' ? - '' : - 'sc.' . implode( + $fields = + 'sc.' . + implode( ',sc.', array_filter(array_map( 'trim', explode( ',', - $sort + $fields ) )) ) ; + $sort = + $sort == '' ? + '' : + ( + 'sc.' . + implode( + ',sc.', + array_filter(array_map( + 'trim', + explode( + ',', + $sort + ) + )) + ) + ) + ; // get document groups for current user if ($docgrp = self::$modx->getUserDocGroups()){ @@ -2031,17 +2126,34 @@ public static function getDocumentChildren( ; $result = self::$modx->db->select( + //Fields 'DISTINCT ' . $fields, + //From self::$tables['site_content'] . ' sc LEFT JOIN '.self::$tables['document_groups'] . ' dg ON dg.document = sc.id ', - 'sc.parent = "' . $parentid . '" ' . $published . ' ' . $deleted . ' ' . $where . ' AND (' . $access . ') GROUP BY sc.id', + //Where + ( + 'sc.parent = "' . + $parentid . + '" ' . + $published . + ' ' . + $deleted . + ' ' . + $where . + ' AND (' . + $access . + ') GROUP BY sc.id' + ), + //Order ( $sort ? $sort . ' ' . $dir : '' ), + //Limit $limit ); From eedb5eb68ad2ce560494e0c9d7000d8ec976fb79 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 21:55:05 +0300 Subject: [PATCH 07/10] + `\ddTools::getDocumentParentIds`. Gets the parent ID(s) of the required level. --- modx.ddtools.class.php | 68 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 5a8f02d..bf152a4 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -2412,6 +2412,74 @@ public static function regEmptyClientScript($params = []){ ]; } + /** + * getDocumentParentIds + * @version 1.0 (2020-02-11) + * + * @desc Gets the parent ID(s) of the required level. + * + * @param $params {arrayAssociative|stdClass} — The object of params. Default: —. + * @param $params->docId {integer} — Document Id. Default: $modx->documentIdentifier. + * @param $params->level {integer} — Parent level (1 — the immediate parent; 2 — the parent of the immediate parent; -1 — the last parent; -2 — the parent before the last; etc). Default: 1. + * @param $params->totalResults {integer|'all'} — The number of parents that will be returned. Default: 'all'. + * + * @return $result {array} — Document parent IDs. + * @return $result[i] {integer} — A parent ID. + */ + public static function getDocumentParentIds($params){ + //Defaults + $params = (object) array_merge( + [ + 'docId' => self::$modx->documentIdentifier, + 'level' => 1, + 'totalResults' => 'all' + ], + (array) $params + ); + + //Получаем всех родителей (на самом деле максимум 10, но да ладно) + $result = self::$modx->getParentIds($params->docId); + $resultLen = count($result); + + //Если родители вообще есть + if ($resultLen > 0){ + //Если уровень задали больше, чем в принципе есть родителей, считаем, что нужен последний + if ($params->level > $resultLen){ + $params->level = -1; + } + + //Если уровень задаётся от начала (не от конца), то его надо бы декриминировать (т.к. самого себя в массиве $result не будет) + if ($params->level > 0){ + $params->level--; + } + + //Количество возвращаемых родителей + if ($params->totalResults == 'all'){ + //All parents + $params->totalResults = $resultLen; + }else if (isset($params->totalResults)){ + //Needed number + $params->totalResults = intval($params->totalResults); + }else{ + //Immediate + $params->totalResults = 1; + } + + //Получаем необходимых родителей + $result = array_slice( + $result, + $params->level, + $params->totalResults + ); + + $result = array_reverse($result); + }else{ + $result = [$params->docId]; + } + + return $result; + } + /** * getDocumentIdByUrl * @version 1.1.3 (2019-06-22) From 412e850668e994c3b95f1f4dbba5e29ad005f553 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 22:56:45 +0300 Subject: [PATCH 08/10] * `\ddTools::clearCache`: Added an ability to clear parents cache too (by default). --- modx.ddtools.class.php | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index bf152a4..cfc8971 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1025,18 +1025,25 @@ public static function parseSource($source){ /** * clearCache - * @version 1.0 (2020-02-11) + * @version 1.1 (2020-02-11) * - * @desc Clears cache of required document(s). + * @desc Clears cache of required document(s) and their parents. * * @param $params {arrayAssociative|stdClass} — The object of params. @required * @param $params->docIds {arrayAssociative|stringCommaSeparated} — Document ID(s). @required * @param $params->docIds[i] {integer} — Document ID. @required + * @param $params->clearParentsCache {boolean} — Is need to clear parents cache? Default: true. * * @return {void} */ public static function clearCache($params){ - $params = (object) $params; + //Defaults + $params = (object) array_merge( + [ + 'clearParentsCache' => true, + ], + (array) $params + ); //Comma separated strings support if (!is_array($params->docIds)){ @@ -1082,6 +1089,17 @@ public static function clearCache($params){ unlink($cacheFiles_item); } + + //IF need to clear parents cache too + if ($params->clearParentsCache){ + self::clearCache([ + //Get all parents + 'docIds' => self::getDocumentParentIds([ + 'docId' => $docId + ]), + 'clearParentsCache' => false + ]); + } } } From ecbb1a325fc769d9481db900383bf46c2b37c22b Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 23:35:55 +0300 Subject: [PATCH 09/10] + `\ddTools::updateDocument`: Cache of the updated docs and their parents will be cleared. --- modx.ddtools.class.php | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index cfc8971..7ad7f92 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1370,9 +1370,9 @@ public static function createDocument( /** * updateDocument - * @version 1.3.3 (2020-02-10) + * @version 1.4 (2020-02-11) * - * @desc Update a document. + * @desc Update document(s). Cache of the updated docs and their parents will be cleared. * * @note $docId and/or $where are required. * @@ -1438,6 +1438,11 @@ public static function updateDocument( ); if (self::$modx->db->getRecordCount($docIdsToUpdate_dbRes)){ + $docIdsToUpdate = []; + while ($doc = self::$modx->db->getRow($docIdsToUpdate_dbRes)){ + $docIdsToUpdate[] = $doc['id']; + } + //Разбиваем на поля документа и TV $docData = self::prepareDocData([ 'data' => $docData, @@ -1459,7 +1464,10 @@ public static function updateDocument( //Если есть хоть одна TV if (count($docData->tvsAdditionalData) > 0){ //Обновляем TV всех найденых документов - while ($doc = self::$modx->db->getRow($docIdsToUpdate_dbRes)){ + foreach ( + $docIdsToUpdate as + $docId + ){ //Перебираем массив существующих TV foreach ( $docData->tvsAdditionalData as @@ -1480,7 +1488,7 @@ public static function updateDocument( self::$modx->db->update( '`value` = "' . $docData->tvsData[$tvName] . '"', self::$tables['site_tmplvar_contentvalues'], - '`tmplvarid` = ' . $tvData['id'] . ' AND `contentid` = ' . $doc['id'] + '`tmplvarid` = ' . $tvData['id'] . ' AND `contentid` = ' . $docId ); //Проверяем сколько строк нашлось при обновлении @@ -1510,7 +1518,7 @@ public static function updateDocument( [ 'value' => $docData->tvsData[$tvName], 'tmplvarid' => $tvData['id'], - 'contentid' => $doc['id'] + 'contentid' => $docId ], self::$tables['site_tmplvar_contentvalues'] ); @@ -1519,6 +1527,11 @@ public static function updateDocument( } } + //Clear cache of updated docs + self::clearCache([ + 'docIds' => $docIdsToUpdate + ]); + return true; } From e8e250d2ca0fe869aa10e9919b40ef9c4660e703 Mon Sep 17 00:00:00 2001 From: Ilyas Ronef Date: Tue, 11 Feb 2020 23:41:43 +0300 Subject: [PATCH 10/10] Prerelease --- CHANGELOG.md | 7 +++++++ composer.json | 2 +- modx.ddtools.class.php | 4 ++-- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 890523e..5f28584 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,13 @@ # (MODX)EvolutionCMS.libraries.ddTools changelog +## Version 0.30 (2020-02-11) +* \* Attention! (MODX)EvolutionCMS >= 1.1 is required. +* \+ `\ddTools::getDocumentParentIds`. Gets the parent ID(s) of the required level. +* \+ `\ddTools::clearCache`. Clears cache of required document(s) and their parents. +* \+ `\ddTools::updateDocument`: Cache of the updated docs and their parents will be cleared. + + ## Version 0.29.1 (2019-12-15) * \* `\DDTools\BaseClass::setProp`: Do nothing if property is not exist. diff --git a/composer.json b/composer.json index ce6e57d..831cc47 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dd/modxevo-library-ddtools", "type": "modxevo-library-ddtools", - "version": "0.29.1", + "version": "0.30.0", "description": "A library with various tools facilitating your work.", "keywords": [ "modx", diff --git a/modx.ddtools.class.php b/modx.ddtools.class.php index 7ad7f92..1bc13b7 100644 --- a/modx.ddtools.class.php +++ b/modx.ddtools.class.php @@ -1,11 +1,11 @@