Plugin Directory

Changeset 3253666


Ignore:
Timestamp:
03/11/2025 02:16:18 AM (12 months ago)
Author:
ivankomlev
Message:

Table Management / Create/Copy/Rename reworked. Same class used for Joomla and WP.

Location:
customtables/trunk
Files:
5 edited

Legend:

Unmodified
Added
Removed
  • customtables/trunk/inc/admin/class-admin-table-edit.php

    r3252718 r3253666  
    5050
    5151            try {
    52                 $this->helperListOfTables->save($this->tableId);
     52                $this->helperListOfTables->save($this->tableId ?? 0);
    5353            } catch (Exception $e) {
    5454                common::enqueueMessage($e->getMessage());
  • customtables/trunk/libraries/ct-database-wp.php

    r3252718 r3253666  
    650650        elseif ($type == 'native')
    651651            $realTableName_safe = $tableName;
     652        elseif ($type == 'table')
     653            $realTableName_safe = $wpdb->prefix . 'customtables_table_' . $tableName_safe;
    652654        else
    653655            $realTableName_safe = $wpdb->prefix . 'customtables_' . $tableName_safe;
  • customtables/trunk/libraries/customtables/helpers/TableHelper.php

    r3247449 r3253666  
    155155     * @since 3.2.2
    156156     */
    157     public static function renameTableIfNeeded($tableid, $tablename): void
     157    public static function renameTableIfNeeded(int $tableid, string $tablename): void
    158158    {
    159159        $old_tablename = self::getTableName($tableid);
     
    172172     * @since 3.2.2
    173173     */
    174     public static function getTableName($tableid = 0): ?string
     174    public static function getTableName(int $tableid = 0): ?string
    175175    {
    176176        if ($tableid == 0)
     
    178178
    179179        $whereClause = new MySQLWhereClause();
    180         $whereClause->addCondition('id', (int)$tableid);
     180        $whereClause->addCondition('id', $tableid);
    181181        $rows = database::loadObjectList('#__customtables_tables AS s', ['tablename'], $whereClause, null, null, 1);
    182182        if (count($rows) != 1)
     
    198198            return false;
    199199
    200         //Add third-party fields
    201         $whereClause = new MySQLWhereClause();
    202 
     200        // Add third-party fields
     201        $whereClause = new MySQLWhereClause();
    203202        $serverType = database::getServerType();
    204203
     
    219218            $whereClause->addCondition('table_schema', $database);
    220219        }
     220
    221221        $whereClause->addCondition('table_name', $realtablename);
    222222        $fields = database::loadObjectList('information_schema.columns', $selects, $whereClause);
     
    224224        $primary_key_column = '';
    225225        $primary_key_column_type = '';
    226         $primary_key_column_type_is_nullable = null;
    227226        $ordering = 1;
     227
    228228        foreach ($fields as $field) {
    229             if ($primary_key_column == '' and strtolower($field->column_key) == 'pri') {
     229            if ($primary_key_column == '' && strtolower($field->column_key) == 'pri') {
     230                if (strtolower($field->is_nullable) == 'yes') {
     231                    throw new Exception('Primary key column "' . $field->column_name . '" cannot be NULL.');
     232                }
    230233                $primary_key_column = $field->column_name;
    231234                $primary_key_column_type = $field->column_type;
    232                 $primary_key_column_type_is_nullable = $field->is_nullable;
    233235            } else {
    234236                $ct_field_type = Fields::convertMySQLFieldTypeToCT($field->column_type);
    235237
    236                 //TODO: check how it works
    237 
    238                 if ($ct_field_type['type'] === null)
     238                if ($ct_field_type['type'] === null) {
     239                    error_log('Unknown MySQL field type: ' . print_r($field, true));
    239240                    throw new Exception('Add Third-Party Table Fields: third-party table field type "' . $field->data_type . '" is unknown.');
    240 
    241                 $data['tableid'] = $ct->Table->tableid;
    242                 $data['fieldname'] = $field->column_name;
    243                 $data['fieldtitle'] = ucwords(strtolower($field->column_name));
    244                 $data['type'] = $ct_field_type['type'];
    245 
    246                 if (key_exists('typeparams', $ct_field_type))
     241                }
     242
     243                $data = [
     244                    'tableid' => $ct->Table->tableid,
     245                    'fieldname' => $field->column_name,
     246                    'fieldtitle' => str_replace('_', ' ', ucwords(strtolower($field->column_name), '_')),
     247                    'type' => $ct_field_type['type'],
     248                    'ordering' => $ordering,
     249                    'defaultvalue' => isset($field->column_default) ? $field->column_default : null,
     250                    'description' => isset($field->column_comment) && $field->column_comment !== '' ? $field->column_comment : null,
     251                    'isrequired' => (strtolower($field->is_nullable) == 'no') ? 1 : 0
     252                ];
     253
     254                if (key_exists('typeparams', $ct_field_type)) {
    247255                    $data['typeparams'] = $ct_field_type['typeparams'];
    248 
    249                 $data['ordering'] = $ordering;
    250                 $data['defaultvalue'] = $field->column_default != '' ? $field->column_default : null;
    251                 $data['description'] = $field->column_comment != '' ? $field->column_comment : null;
    252                 //$data['customfieldname'] = $field->column_name;
    253                 $data['isrequired'] = 0;
     256                }
    254257
    255258                database::insert('#__customtables_fields', $data);
     
    259262
    260263        if ($primary_key_column != '') {
    261             //Update primary key column
    262 
     264            // Update primary key column
    263265            $data = [
    264266                'customidfield' => $primary_key_column,
    265                 'customidfieldtype' => $primary_key_column_type . ($primary_key_column_type_is_nullable ? ' NULL' : ' NOT NULL'), //TODO Add more details
     267                'customidfieldtype' => $primary_key_column_type . ' NOT NULL',
    266268                'customfieldprefix' => null
    267269            ];
     270
    268271            $whereClauseUpdate = new MySQLWhereClause();
    269272            $whereClauseUpdate->addCondition('id', $ct->Table->tableid);
     
    371374
    372375        $rows = database::loadAssocList('#__customtables_fields', ['*'], $whereClause);
    373 
    374         if (count($rows) == 0)
    375             die('Original table has no fields.');
    376376
    377377        foreach ($rows as $row) {
  • customtables/trunk/libraries/customtables/integrity/coretables.php

    r3248073 r3253666  
    376376            'comment' => 'Custom Tables Categories'];
    377377    }
     378
     379    public static function addMultilingualTablesFields($LanguageList): void
     380    {
     381        $moreThanOneLanguage = false;
     382        $fields = Fields::getListOfExistingFields('#__customtables_tables', false);
     383        foreach ($LanguageList as $lang) {
     384            $id_title = 'tabletitle';
     385            $id_desc = 'description';
     386            if ($moreThanOneLanguage) {
     387                $id_title .= '_' . $lang->sef;
     388                $id_desc .= '_' . $lang->sef;
     389            }
     390
     391            try {
     392                if (!in_array($id_title, $fields))
     393                    Fields::addLanguageField('#__customtables_tables', $id_title, $id_title, 'null');
     394
     395                if (!in_array($id_desc, $fields))
     396                    Fields::addLanguageField('#__customtables_tables', $id_desc, $id_desc, 'null');
     397            } catch (Exception $e) {
     398                throw new Exception($e->getMessage());
     399            }
     400
     401            $moreThanOneLanguage = true; //More than one language installed
     402        }
     403    }
    378404}
  • customtables/trunk/libraries/customtables/views/admin-listoftables.php

    r3248111 r3253666  
    1414if (!defined('ABSPATH')) exit;
    1515
     16use CustomTables\Integrity\IntegrityCoreTables;
    1617use Exception;
    1718
     
    102103    }
    103104
    104     /**
    105      * @throws Exception
    106      * @since 3.2.2
    107      */
    108     function save(?int $tableId): void
    109     {
    110         $data = [];
     105
     106    /**
     107     * @throws Exception
     108     * @since 3.5.8
     109     */
     110    function save(int $tableId): void
     111    {
    111112        // Check if running in WordPress context
    112113        if (defined('WPINC')) {
     
    118119        }
    119120
    120         // Get database name and prefix
    121         $database = database::getDataBaseName();
    122         $dbPrefix = database::getDBPrefix();
    123 
    124         // Initialize variables
    125         $moreThanOneLanguage = false;
    126         $fields = Fields::getListOfExistingFields('#__customtables_tables', false);
    127         $tableTitle = null;
    128 
    129         // Process table name
    130         if (function_exists("transliterator_transliterate"))
    131             $newTableName = transliterator_transliterate("Any-Latin; Latin-ASCII; Lower()", common::inputPostString('tablename', null, 'create-edit-table'));
    132         else
    133             $newTableName = common::inputPostString('tablename', null, 'create-edit-table');
    134 
    135         $newTableName = strtolower(trim(preg_replace("/\W/", "", $newTableName)));
    136 
     121        $data = [];
     122        $data['tablename'] = common::inputPostString('tablename', null, 'create-edit-table');
    137123        $data ['customphp'] = common::inputPostString('customphp', null, 'create-edit-table');
    138         $customTableName = common::inputPostString('customtablename', null, 'create-edit-table');
    139         $data ['customtablename'] = $customTableName;
     124        $data ['customtablename'] = common::inputPostString('customtablename', null, 'create-edit-table');
    140125        $data ['customidfield'] = common::inputPostString('customidfield', null, 'create-edit-table');
    141126        $data ['customidfieldtype'] = common::inputPostString('customidfieldtype', null, 'create-edit-table');
     
    143128        $data ['customfieldprefix'] = common::inputPostString('customfieldprefix', null, 'create-edit-table');
    144129
    145         if ($newTableName == "")
    146             throw new Exception('Please provide the table name.');
    147 
    148         // Save as Copy
    149         $old_tablename = '';
    150         if (common::inputPostCmd('task', null, 'create-edit-table') === 'save2copy') {
    151             $originalTableId = common::inputPostInt('originaltableid', null, 'create-edit-table');
    152             if ($originalTableId !== null) {
    153                 $old_tablename = TableHelper::getTableName($originalTableId);
    154 
    155                 // Handle copy table name
    156                 $copyTableName = $newTableName;
    157                 if ($old_tablename == $newTableName)
    158                     $copyTableName = 'copy_of_' . $newTableName;
    159 
    160                 while (TableHelper::getTableID($newTableName) != 0) {
    161                     $copyTableName = 'copy_of_' . $newTableName;
    162                 }
    163 
    164                 $tableId = null;
    165                 $newTableName = $copyTableName;
    166             }
    167         }
     130        $task = 'save';//common::inputPostCmd('task', null, 'create-edit-table');
    168131
    169132        // Process multilingual fields
     133        $moreThanOneLanguage = false;
     134
    170135        foreach ($this->ct->Languages->LanguageList as $lang) {
    171136            $id_title = 'tabletitle';
     
    174139                $id_title .= '_' . $lang->sef;
    175140                $id_desc .= '_' . $lang->sef;
    176             } else {
    177                 $tableTitle = common::inputPostString($id_title, null, 'create-edit-table');
    178             }
    179 
    180             if (!in_array($id_title, $fields)) {
    181                 Fields::addLanguageField('#__customtables_tables', $id_title, $id_title, 'null');
    182             }
    183 
    184             if (!in_array($id_desc, $fields))
    185                 Fields::addLanguageField('#__customtables_tables', $id_desc, $id_desc, 'null');
    186 
    187             $tableTitleValue = common::inputPostString($id_title, null, 'create-edit-table');
    188             if ($tableTitleValue !== null)
    189                 $data [$id_title] = $tableTitleValue;
    190 
    191             $tableDescription = common::inputPostString($id_desc, null, 'create-edit-table');
    192             if ($tableDescription !== null)
    193                 $data [$id_desc] = $tableDescription;
     141            }
     142
     143            $data [$id_title] = common::inputPostString($id_title, null, 'create-edit-table');
     144            $data [$id_desc] = common::inputPostString($id_desc, null, 'create-edit-table');
    194145            $moreThanOneLanguage = true; //More than one language installed
    195146        }
    196147
     148        $this->saveWithData($tableId, $data, $task);
     149    }
     150
     151    /**
     152     * @throws Exception
     153     * @since 3.2.2
     154     */
     155
     156    function saveWithData(int $tableId, array $data, string $task): int
     157    {
     158        // Get database name and prefix
     159        $database = database::getDataBaseName();
     160        $dbPrefix = database::getDBPrefix();
     161
     162        // Process table name
     163        if (function_exists("transliterator_transliterate"))
     164            $newTableName = transliterator_transliterate("Any-Latin; Latin-ASCII; Lower()", $data['tablename']);
     165        else
     166            $newTableName = $data['tablename'];
     167
     168        $newTableName = strtolower(trim(preg_replace("/\W/", "", $newTableName)));
     169
     170        if ($newTableName == "")
     171            throw new Exception('Please provide the table name.');
     172
     173        $data ['primarykeypattern'] = stripcslashes($data ['primarykeypattern']);
     174
     175        $old_tablename = null;
     176
     177        //If it's a new table, check if field name is unique or add number "_1" if it's not.
     178        if ($tableId === 0) {
     179            $newTableName = TableHelper::checkTableName($newTableName);
     180        } else {
     181
     182            $originalTableId = common::inputPostInt('originaltableid', null, 'create-edit-table');
     183            if (!empty($originalTableId)) {
     184                $old_tablename = TableHelper::getTableName($originalTableId);
     185            }
     186            // Save as Copy
     187            if ($task === 'save2copy') {
     188
     189                if (!empty($originalTableId)) {
     190
     191                    // Handle copy table name
     192                    $copyTableName = $newTableName;
     193                    if ($old_tablename == $newTableName)
     194                        $copyTableName = 'copy_of_' . $newTableName;
     195
     196                    while (TableHelper::getTableID($newTableName) != 0) {
     197                        $copyTableName = 'copy_of_' . $newTableName;
     198                    }
     199
     200                    $tableId = 0;
     201                    $newTableName = $copyTableName;
     202                }
     203            }
     204        }
     205
     206        if (defined('_JEXEC'))
     207            $data['tablecategory'] = (int)$data['tablecategory'];
     208
     209        if ($data['customidfield'] === null)
     210            $data['customidfield'] = 'id';
     211
     212        if ($data['customidfieldtype'] === null)
     213            $data['customidfieldtype'] = 'int UNSIGNED NOT NULL AUTO_INCREMENT';
     214
     215        $customFieldPrefix = trim(preg_replace("/[^a-zA-Z-_\d]/", "_", ($data['customfieldprefix'] ?? null)));
     216        if ($customFieldPrefix === "")
     217            $customFieldPrefix = null;
     218
     219        $data['customfieldprefix'] = $customFieldPrefix;
     220
     221        IntegrityCoreTables::addMultilingualTablesFields($this->ct->Languages->LanguageList);
     222
    197223        // If it's a new table, check if field name is unique or add number "_1" if it's not.
    198         if ($tableId === null) {
    199             $already_exists = TableHelper::getTableID($newTableName);
    200             if ($already_exists == 0) {
    201                 $data ['tablename'] = $newTableName;
    202             } else {
    203                 throw new Exception('Table with this name already exists.');
    204             }
    205 
     224        if ($tableId === 0) {
    206225            try {
    207                 database::insert('#__customtables_tables', $data);
     226                $tableId = database::insert('#__customtables_tables', $data);
    208227            } catch (Exception $e) {
    209228                throw new Exception($e->getMessage());
     229            }
     230
     231            if ($data['customtablename'] == '-new-') {
     232
     233                // Case: Creating a new third-party table
     234                TableHelper::createTableIfNotExists($dbPrefix, $newTableName, $data['tabletitle'], $newTableName);
     235
     236                //Add fields if it's a third-party table and no fields added yet.
     237                //TableHelper::addThirdPartyTableFieldsIfNeeded($database, $newTableName, $newTableName);
     238            } elseif (empty($data['customtablename'])) {
     239
     240                $originalTableId = common::inputPostInt('originaltableid', 0, 'create-edit-table');
     241                if ($originalTableId != 0 and $old_tablename != '' and $task === 'save2copy') {
     242                    // Copying an existing table
     243                    TableHelper::copyTable($this->ct, $originalTableId, $newTableName, $old_tablename, $data['customtablename']);
     244                } else {
     245                    // Creating a new custom table (without copying)
     246                    TableHelper::createTableIfNotExists($dbPrefix, $newTableName, $data['tabletitle'], $data['customtablename'] ?? '');
     247
     248
     249                }
     250
     251                // Creating a new custom table (without copying)
     252                //TableHelper::createTableIfNotExists($dbPrefix, $newTableName, $data['tabletitle'], $data['customtablename'] ?? '');
    210253            }
    211254
     
    220263            }
    221264
    222             if (empty($customTableName))//do not rename real table if it's a third-party table - not part of the Custom Tables
     265            if (empty($data['customtablename']))//do not rename real table if it's a third-party table - not part of the Custom Tables
    223266            {
    224267                //This function will find the old Table Name of existing table and rename MySQL table.
     
    230273                $whereClauseUpdate = new MySQLWhereClause();
    231274                $whereClauseUpdate->addCondition('id', $tableId);
     275
    232276                database::update('#__customtables_tables', $data, $whereClauseUpdate);
    233277            } catch (Exception $e) {
    234278                throw new Exception($e->getMessage());
    235279            }
    236         }
    237 
    238         //Create MySQLTable
    239         if ($customTableName == '-new-') {
    240             // Case: Creating a new third-party table
    241             $customTableName = $newTableName;
    242             TableHelper::createTableIfNotExists($dbPrefix, $newTableName, $tableTitle, $customTableName);
    243 
    244             //Add fields if it's a third-party table and no fields added yet.
    245             TableHelper::addThirdPartyTableFieldsIfNeeded($database, $newTableName, $customTableName);
    246         } else {
     280
    247281            // Case: Updating an existing table or creating a new custom table
    248             $originalTableId = common::inputPostInt('originaltableid', 0, 'create-edit-table');
    249 
    250             if ($originalTableId != 0 and $old_tablename != '') {
    251                 // Copying an existing table
    252                 TableHelper::copyTable($this->ct, $originalTableId, $newTableName, $old_tablename, $customTableName);
    253             } else {
    254                 // Creating a new custom table (without copying)
    255                 TableHelper::createTableIfNotExists($dbPrefix, $newTableName, $tableTitle, $customTableName ?? '');
    256 
    257                 //Add fields if it's a third-party table and no fields added yet.
    258                 if (!empty($customTableName)) {
    259                     TableHelper::addThirdPartyTableFieldsIfNeeded($database, $newTableName, $customTableName);
    260                 }
    261             }
    262         }
     282
     283
     284            //echo '$originalTableId:' . $originalTableId . '<br/>';
     285            //echo '$old_tablename:' . $old_tablename . '<br/>';
     286            //echo '$task:' . $task . '<br/>';
     287            //die;
     288
     289
     290        }
     291
     292        //Add fields if it's a third-party table and no fields added yet.
     293        if (!empty($data['customtablename']) and $data['customtablename'] !== '-new-') {
     294            TableHelper::addThirdPartyTableFieldsIfNeeded($database, $newTableName, $data['customtablename']);
     295        }
     296
     297        return $tableId;
    263298    }
    264299}
Note: See TracChangeset for help on using the changeset viewer.