/** * put your comment there... * * @param mixed $blocks */ protected function getBlocksIterator($blocks) { // Import iterator class file! cssJSToolbox::import('includes:installer:upgrade:0.2:includes:block.class.php'); // Instantiate blocks iterator object! return new CJTInstallerBlocks02($blocks); }
/** * put your comment there... * * @param mixed $blockId */ public function create(&$pin = null) { // Import dependecnes. cssJSToolbox::import('tables:block-pins.php'); // Change metabox status to be created. $this->setState(self::STATE_CREATED); // Add post pin to pins table. $blockPinsTable = new CJTBlockPinsTable($this->dbDriver); // Pin data. $pin = (object) array(); // Import CJTBlockModel class. CJTModel::import('block'); /** @todo Only temporary in version 6.0. Later versions should group all post types by post type name! */ switch ($this->getPost()->post_type) { case 'page': $pin->pin = 'pages'; $pin->flag = CJTBlockModel::PINS_PAGES_CUSTOM_PAGE; break; default: $pin->pin = 'posts'; $pin->flag = CJTBlockModel::PINS_POSTS_CUSTOM_POST; break; } $pin->value = $this->getPost()->ID; // Add pin record. $blockPinsTable->insertRaw($this->getMetaboxId(), array($pin)); // Chains! return $this; }
/** * put your comment there... * */ public function upgrade() { // Save backup in backup table! $backup = $this->current(); // Change 'time' field to 'created'! // Convert formatted date to mysal date! $backup['created'] = $backup['time']; // User author Id instead of name and change 'author' field to 'owner'! $backup['owner'] = get_user_by('login', $backup['author'])->ID; $backup['type'] = 'blocks'; // For now we support only blocks backups! // Load blocks into blocks iterator before destroying deprectaed fields. $blocks = new CJTInstallerBlocks03($backup['data'], CJTInstallerBlocks03::BLOCK_TYPE_BACKUP); // Remove deprecated fields! $backup = array_diff_key($backup, array_flip(array('time', 'author', 'data'))); /// Add backup and get its ID using OLD style table (not xTable)!! // Import dependecneis. cssJSToolbox::import('tables:backups.php'); // Insert backup record. $backupsTable = new CJTBackupsTable(cssJSToolbox::getInstance()->getDBDriver()); $backupsTable->insert($backup); $backupId = $backupsTable->getDBDriver()->processQueue()->getInsertId(); // Insert all blocks! foreach ($blocks as &$block) { // Associate every block with the created backup! $block['backupId'] = $backupId; // Upgrade block! $blocks->upgrade(); $blocks->model->save(); } return $this; }
/** * put your comment there... * * @param mixed $which */ function extra_tablenav($which) { // Import dependencies. cssJSToolbox::import('framework:html:list.php'); // Define filters. $filters = array(); $filters['states'] = 'State'; $filters['types'] = 'Type'; $filters['authors'] = 'Author'; $filters['versions'] = 'Version'; $filters['creation-dates'] = 'Date Created'; $filters['development-states'] = 'Release'; $filters['last-modified-dates'] = 'Last Modified'; // Get the HTML field for each filter antput the result. $filtersName = array(); foreach ($filters as $name => $text) { // Output field markup. $fieldName = "filter_{$name}"; $classes = "filter filter_{$name}"; echo CJTListField::getInstance("template-{$name}", 'templates-manager', $fieldName, isset($_REQUEST[$fieldName]) ? $_REQUEST[$fieldName] : null, null, $classes, null, null, null, cssJSToolbox::getText($text))->getInput(); // Complete list of filters names! $filtersName[] = $fieldName; } if ($which == 'top') { // Output all filter names list! $filtersName = implode(',', $filtersName); echo "<input type='hidden' name='allFiltersName' value='{$filtersName}' />"; } }
/** * put your comment there... * */ protected function enableAction() { // Initializing! $model = $this->model; $cjtWebServer = cssJSToolbox::getCJTWebSiteURL(); $extensions =& CJTPlugin::getInstance()->extensions(); // Get all CJT-Plugins (Include CJT Plugin itself + all its extensions) that has activate // license key! $activeLicenses = $model->getStatedLicenses(); // Import EDD updater Class! cssJSToolbox::import('framework:third-party:easy-digital-download:auto-upgrade.class.php'); // Activate Automatic upgrade for all activated licenses/components! foreach ($activeLicenses as $name => $state) { // Get extension def doc. // Act only if extension has XMl DOC! This might happened i fthe extension // removed while its key still in the database if ($extDef = $extensions->getDefDoc(dirname($state['component']['pluginBase']))) { // Check CJT Server only if updateSrc points to Wordpress Repository $updateSrcServer = (string) $extDef->license->attributes()->updateSrc; if (!$updateSrcServer || $updateSrcServer == 'CJT') { // Initializingn vars for a single state/component! $pluginFile = ABSPATH . PLUGINDIR . '/' . $state['component']['pluginBase']; // Stop using Cached Data as it causes issue, always // get fresh plugin data. $plugin = get_plugin_data($pluginFile); $license =& $state['license']; // Edd API parameter to be send along with he check! $requestParams = array('version' => $plugin['Version'], 'author' => $plugin['AuthorName'], 'license' => $license['key'], 'item_name' => $name); // Set EDD Automatic Updater! $updated = new CJT_EDD_SL_Plugin_Updater($cjtWebServer, $pluginFile, $requestParams); } } } }
/** * put your comment there... * */ public function database() { // Upgrade database tables. cssJSToolbox::import('framework:installer:dbfile.class.php'); CJTDBFileInstaller::getInstance(cssJSToolbox::resolvePath('includes:installer:upgrade:1.0-CE:db:mysql:structure.sql'))->exec(); // Chaining. return $this; }
/** * put your comment there... * */ public function finalize() { // Upgrade database internal version number using // installer class. cssJSToolbox::import('includes:installer:installer:installer.class.php'); CJTInstaller::getInstance()->finalize(); // Chaining. return $this; }
/** * put your comment there... * * @param mixed $blocks * @param mixed $type * @return CJTInstallerBlocks03 */ public function __construct($blocks, $type = null) { // Initialize object! $this->type = $type ? $type : self::BLOCK_TYPE_BLOCK; // Initialize block base iterator. parent::__construct($blocks); // import dependencies. cssJSToolbox::import('tables:blocks.php'); }
/** * put your comment there... * */ public function template() { static $template = null; // Instantiate Template library only when used. if (!$template) { cssJSToolbox::import('framework:developer:lib:template:template.php'); $template = new CJT_Framework_Developer_Lib_Template($this->source); } return $template; }
/** * put your comment there... * */ public function __construct() { // Import dependencies! cssJSToolbox::import('includes:installer:upgrade:block.class.php', 'includes:installer:upgrade:template.class.php'); // Load blocks into installer iterator! $this->blocks = $this->getBlocksIterator(get_option(self::BLOCKS_POINTER)); // Load templates into templates iterator! $driver = cssJSToolbox::getInstance()->getDBDriver(); $templates = $driver->select('SELECT title as `name`, type, `code` FROM ' . self::TEMPLATES_TABLE . ';', ARRAY_A); $this->templates = new CJTInstallerTemplate($templates); }
/** * put your comment there... * */ public static function uninstall() { // For the uninstaller to be run eraseData setting must be enabled. cssJSToolbox::import('models:settings:uninstall.php'); $settings = new CJTSettingsUninstallPage(); if ($settings->eraseData) { // Get the only instance we've for the main access point! $mainAccessPointObject = self::$instance; // Load default controller! $mainAccessPointObject->controllerName = 'default'; $controller = $mainAccessPointObject->route(false)->setAction('uninstall')->_doAction(); } }
/** * put your comment there... * */ public function __construct($type) { // Save type data for later use! $this->type = cssJSToolbox::$config->templates->types[$type]; $this->type->name = $type; // Get which Wordpress queue (wp_script, wp_styles) object to fetch data from. $wpQueueName = self::$typesMap[$type]; /** * @var CJTCouplingModel */ $coupling = CJTModel::getInstance('coupling'); // Initialize ArrayIterator with templates list! parent::__construct($coupling->getQueueObject($wpQueueName)->registered); // Import dependencies! cssJSToolbox::import('framework:db:mysql:xtable.inc.php'); CJTxTable::import('template'); CJTxTable::import('author'); }
/** * Do nothing! * */ public function transit() { // Initialize. $model = CJTModel::getInstance('template'); $node = $this->getNode(); $register = $this->register(); // Prepare object + getting item to be saved into database. $template = $register['packageParser']->getItem($node); // Insert template only if not exists. if (!$model->exists($template['name'])) { // Import template(s) helper. cssJSToolbox::import('includes:templates:templates.class.php'); // Set template revision. $model->inputs['item']['revision']['code'] = $template['code']; unset($template['code']); // Set template main data. $model->inputs['item']['template'] = $template; /** Get template Type! * Get type from external file extension if * the template code was linked to file. * If the template code were inline * then the type must be provided under * TYPE element! */ // If no type specified get it from the external file extension if (!isset($model->inputs['item']['template']['type'])) { // @WARNING: Get locatted file! $codeFileName = (string) $node->code->attributes()->locatted; if ($codeFileName) { // Get type from extension. $fileComponent = pathinfo($codeFileName); $model->inputs['item']['template']['type'] = CJTTemplates::getExtensionType($fileComponent['extension']); } } // Add template. $addedTemplate = $model->save(); // Expose template fields to be by used by other objects. $register['templateId'] = $addedTemplate->templateId; $register['templateFile'] = $addedTemplate->file; } // Chaining. return $this; }
/** * Wordpress do shortcode callback for * CJT Shortcodes ([cjtoolbox ....])! * * This method role is to load the shortcode routines * in order to handle the request. * * It doesn't do anything except deferring the shortcode * codes from loaded until shortcode is really used! * * @param mixed $attributes */ public function shortcode($attributes, $content) { // Instantiate Shortcode handler class. cssJSToolbox::import('controllers:coupling:shortcode:shortcode.php'); $shortcode = new CJT_Controllers_Coupling_Shortcode($attributes, $content); // Return Shortcode replacement! return (string) $shortcode; }
/** * Query Block based on the passed paramaters. * */ public function getBlockBy() { // import dependencies. cssJSToolbox::import('framework:db:mysql:xtable.inc.php'); return CJTxTable::getInstance('block')->set($this->inputs['filter']['field'], $this->inputs['filter']['value'])->load(array($this->inputs['filter']['field']))->getData(); }
/** * Link external Resources (CSS, HTML, JS and PHP) * * The action is to create external link as CJT template * and link it to the target block. */ protected function linkExternalAction() { // Import dependencies. cssJSToolbox::import('includes:templates:templates.class.php'); // Initialize response as successed until error occured! $this->response = array('code' => 0, 'message' => ''); // List of all the external templates records to create! $externalTemplates = array(); // Read inputs. $externals = explode(',', $_REQUEST['externals']); $blockId = (int) $_REQUEST['blockId']; // Add as templates. foreach ($externals as $externalResourceURI) { // Use URI base name as Template Name and the extension as Template Type. $externalPathInfo = pathinfo($externalResourceURI); // Template Item. $item = array(); $item['template']['name'] = $externalPathInfo['basename']; $item['template']['type'] = CJTTemplates::getExtensionType($externalPathInfo['extension']); $item['template']['state'] = 'published'; // Get external URI code! $externalResponse = wp_remote_get($externalResourceURI); if ($error = $externalResponse instanceof WP_Error) { // State an error! $this->response['code'] = $externalResponse->get_error_code(); $this->response['message'] = $externalResponse->get_error_message($this->response['code']); break; } else { // Read code content. $item['revision']['code'] = wp_remote_retrieve_body($externalResponse); // Add to the save list! $externalTemplates[] = $item; } } // Save all templates if no error occured // Single error will halt all the linked externals! They all added as a single transaction. if (!$this->response['code']) { // Instantiate Template Models. $modelLookup = CJTModel::getInstance('templates-lookup'); $modelTemplate = CJTModel::getInstance('template'); $modelBlockTemplates = CJTModel::getInstance('block-templates'); // Add all templates. foreach ($externalTemplates as $item) { // Check existance. $modelTemplate->inputs['filter']['field'] = 'name'; $modelTemplate->inputs['filter']['value'] = $item['template']['name']; if (!($existsItem = $modelTemplate->getTemplateBy()) || !property_exists($existsItem, 'id') || !$existsItem->id) { // Create template. $modelTemplate->inputs['item'] = $item; $item = (array) $modelTemplate->save(); } else { // The returned item has 'id' field not 'templateId'!! $item = array('templateId' => $existsItem->id); } // Link only if not already linked! if (!$modelBlockTemplates->isLinked($blockId, $item['templateId'])) { // Link template to the block. $modelLookup->inputs['templateId'] = $item['templateId']; $modelLookup->inputs['blockId'] = $blockId; $modelLookup->link(); } } } }
<?php /** * */ // Import dependencies. cssJSToolbox::import('framework:html:list.php', 'framework:db:mysql:xtable.inc.php'); /** * */ class CJTTemplateCreationDatesField extends CJTListField { /** * put your comment there... * */ protected function prepareItems() { CJTxTable::import('author'); $internalAuthorsFlag = CJTAuthorTable::FLAG_SYS_AUTHOR; // Query all dates (without time!) or internal authors. $query = " SELECT DISTINCT(DATE(t.creationDate)) `text`\n\t\t\t\t\t\t\t\t\t\t\t\t\tFROM #__cjtoolbox_templates t\n\t\t\t\t\t\t\t\t\t\t\t\t\tLEFT JOIN #__cjtoolbox_authors a\n\t\t\t\t\t\t\t\t\t\t\t\t\tON t.authorId = a.id\n\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE (a.attributes & {$internalAuthorsFlag}) = 0\n\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY `text`;"; $this->items = cssJSToolbox::getInstance()->getDBDriver()->select($query); } } // End class.
/** * put your comment there... * */ public function wordpressTemplates() { // Dependencies! cssJSToolbox::import('framework:db:mysql:xtable.inc.php', 'includes:installer:installer::includes:templates:wordpress-queue.inc.php'); // Install Wordpress build-in templates (scripts shipped out with Wordpress installation)! foreach (array('javascript', 'css') as $type) { $wpTemplates = new CJTInstallerWordpressQueueTemplates($type); foreach ($wpTemplates as $wpTemplate) { // Just install not custom updates needed! $wpTemplates->install(); } } return $this; }
/** * put your comment there... * * @param mixed */ public static function import($type) { // Filtering parameters! extract(self::trigger('CJTxTable.import', compact('type'))); // Implort table file. cssJSToolbox::import("tables:{$type}.php"); }
/** * put your comment there... * */ public function __toString() { // Initialize. $replacement = ''; $model = CJTModel::getInstance('coupling'); // Get shortcode options. $this->options = array_merge($this->options, array_intersect_key($this->attributes, $this->options)); // Get shortcode parameters. $this->parameters = array_diff_key($this->attributes, array_flip(array('force', 'tag', 'name', 'id'))); // Get Block fields to be used to query the block. $blockQueryFields = array_intersect_key($this->attributes, array_flip(array('id', 'name'))); $coupling =& CJTBlocksCouplingController::theInstance(); // Import dependecies. cssJSToolbox::import('framework:db:mysql:xtable.inc.php', 'framework:php:evaluator:evaluator.inc.php'); // Query block. $block = CJTxTable::getInstance('block')->setData($blockQueryFields)->load(array_keys($blockQueryFields)); // Load using Creteria fields. // Get block code if exists and is active block. if ($block->get('id')) { if ($block->get('state') == 'active') { // Get stdCLass copy. $block = $block->getData(); // Output block if 'force="true" or only if it wasn't already in the header/footer! if ($this->options['force'] == 'true' || !in_array($block->id, $coupling->getOnActionIds())) { // Id is being used! $coupling->addOnActionIds((int) $block->id); // Retrieve block code-files. $block->code = $model->getBlockCode($block->id); // Import Executable (PHP and HTML) templates. $block->code = $block->code . $model->getExecTemplatesCode($block->id); // CJT Block Standard Parameters object. $spi = new CJT_Framework_Developer_Interface_Block_Shortcode_Shortcode($block, $this->parameters, $this->content); // Get block code, execute it as PHP! $blockCode = CJTPHPCodeEvaluator::getInstance($block)->exec(array('cb' => $spi))->getOutput(); // CJT Shortcode markup interface (CSMI)! // CSMI is HTML markup to identify the CJT block Shortcode replacement. $replacement = "<{$this->options['tag']} id='{$spi->containerElementId()}' class='csmi csmi-bid-{$block->id} csmi-{$block->name}'>{$this->content}{$blockCode}</{$this->options['tag']}>"; // Get linked templates. $linkedStylesheets = ''; $templates = $model->getLinkedTemplates($block->id); $reverseTypes = array_flip(CJTCouplingModel::$templateTypes); // Enqueue all scripts & Direct Output for all Style Sheets! foreach ($templates as $template) { // Get Template type name. $typeName = $reverseTypes[$template->type]; /** * @var WP_Dependencies */ $queue = $model->getQueueObject($typeName); if (!in_array($template->queueName, $queue->done)) { if (!isset($queue->registered[$template->queueName])) { $queue->add($template->queueName, "/{$template->file}", null, $template->version, 1); } // Enqueue template! $queue->enqueue($template->queueName); } } // Prepend linked Stylesheets to the replacement. if (isset($linkedStylesheets)) { $replacement = "<style type='text/css'>{$linkedStylesheets}</style>{$replacement}"; } } } } else { // Invalid Shortcode block query! $replacement = cssJSToolbox::getText('Could not find block specified! Please check out the Shortcode parameters.'); } // Return shortcode replacement string. return $replacement; }
/** * put your comment there... * */ public function getItemsQuery() { // Import dependencies. cssJSToolbox::import('framework:db:mysql:xtable.inc.php'); CJTxTable::import('template-revision'); CJTxTable::import('author'); // From clause. $query['from'] = ' FROM #__cjtoolbox_templates t LEFT JOIN #__cjtoolbox_template_revisions r ON t.id = r.templateId LEFT JOIN #__cjtoolbox_authors a ON t.authorId = a.id'; // Always get only the last revision. $where[] = '(r.attributes & ' . CJTTemplateRevisionTable::FLAG_LAST_REVISION . ')'; // For version 6 don't display Internal/System (e.g Wordpress, ) Authors templates $where[] = '((a.attributes & ' . CJTAuthorTable::FLAG_SYS_AUTHOR . ') = 0)'; // Build where clause based on the given filters! $filters = array('types' => array('table' => 't', 'name' => 'type'), 'authors' => array('table' => 't', 'name' => 'authorId'), 'version' => array('table' => 'r', 'name' => 'version'), 'creation-dates' => array('name' => 'DATE(creationDate)'), 'last-modified-dates' => array('name' => 'DATE(dateCreated)'), 'states' => array('table' => 't', 'name' => 'state'), 'development-state' => array('table' => 'r', 'name' => 'state')); foreach ($filters as $name => $field) { $filterName = "filter_{$name}"; // Add filter only if there is a value specified. if (!empty($this->inputs[$filterName])) { $value = $this->inputs[$filterName]; if (!is_numeric($value)) { $value = "'{$value}'"; } $field['table'] = isset($field['table']) ? "{$field['table']}." : ''; $where[] = "{$field['table']}{$field['name']} = {$value} "; } } $query['where'] = ' WHERE ' . implode(' AND ', $where); return $query; }
/** * put your comment there... * * @param mixed $blocks * @param mixed $types */ public function getLinkedTemplates($blocks, $types = array('javascript', 'css')) { // Accept single id too! $blocks = (array) $blocks; // Import dependencies! cssJSToolbox::import('framework:db:mysql:xtable.inc.php', 'tables:template-revision.php'); // Initialize vars. $templates = array(); $query['select'] = 'SELECT t.id, t.type, t.queueName, r.version, r.file, bt.blockId'; $query['from'] = 'FROM #__cjtoolbox_block_templates bt LEFT JOIN #__cjtoolbox_templates t ON bt.templateId = t.id LEFT JOIN #__cjtoolbox_template_revisions r ON bt.templateId = r.templateId'; // Filter by blocks ids and getting the last revision of the template! $query['where']['blocks'] = implode(',', $blocks); $query['where']['attributes'] = CJTTemplateRevisionTable::FLAG_LAST_REVISION; // Filter by type. $query['where']['types'] = '"' . implode('","', $types) . '"'; // Where clause. $query['where'] = "WHERE bt.blockId IN ({$query['where']['blocks']}) AND \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t(r.attributes & {$query['where']['attributes']}) AND \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tt.type IN ({$query['where']['types']})"; // Filering! $query = $this->onquerylinkedtemplates($query); $query = "{$query['select']} {$query['from']} {$query['where']}"; $templates = cssJSToolbox::getInstance()->getDBDriver()->select($query); return $templates; }
<?php /** * */ // No direct access. defined('ABSPATH') or die('Access denied'); // Import dependencies. cssJSToolbox::import('framework:mvc:controller-ajax.inc.php'); /** * */ class CJTTinymceBlocksController extends CJTAjaxController { /** * put your comment there... * * @var mixed */ protected $controllerInfo = array('model' => 'tinymce-blocks'); /** * put your comment there... * */ public function __construct($hasView = null, $request = null) { // Initialize parent! parent::__construct($hasView, $request); // Register actions! $this->registryAction('getBlocksList'); $this->registryAction('getShortcode');
/** * put your comment there... * * @param mixed $type * @param mixed $form * @param mixed $name * @param mixed $value * @param mixed $id * @param mixed $classesList * @param mixed $propText * @param mixed $propValue * @param mixed $moreIntoTag */ public static function getInstance($type, $form, $name, $value, $id = null, $classesList = '', $propText = 'text', $propValue = null, $moreIntoTag = null, $optional = null) { /* * @ todo Code to importing file and instantiating class should be in CJTHTMLField class not here!! */ // Import field file. cssJSToolbox::import("models:fields:{$type}.php"); // Create an instance. $type = str_replace(' ', '', ucwords(str_replace(array('-', '_'), ' ', $type))); $className = "CJT{$type}Field"; return new $className($form, $name, $value, $id, $classesList, $propText, $propValue, $moreIntoTag, $optional); }
<?php /** * */ // Disallow direct access. defined('ABSPATH') or die("Access denied"); // Import dependencies. cssJSToolbox::import('framework:db:mysql:table.inc.php'); /** * */ class CJTBackupsTable extends CJTTable { /** * put your comment there... * */ public function __construct($dbDriver) { parent::__construct($dbDriver, cssJSToolbox::$config->database->tables->backups); } /** * put your comment there... * * @param mixed $key */ public function delete($key) { // Where clause filters. $where = '';
/** * Allow executing of a single installation operation! * Both Install and Upgrade operations can be executed throught here * * * @return void */ public function install() { // Initialize. $result = FALSE; // Read input! $rOperation = $this->input['operation']; $type = $rOperation['type']; // Get allowed operations with their state! $operations = (array) get_option(self::INSTALLATION_STATE); $vOperations =& $operations[CJTPlugin::DB_VERSION]; // Invalid operation! if (!isset($vOperations['operations'][$type][$rOperation['name']])) { throw new Exception('Invalid operation'); } else { // Install only if not installed! $operation =& $vOperations['operations'][$type][$rOperation['name']]; if (!isset($operation['state']) || $operation['state'] != self::OPERATION_STATE_INSTALLED) { // Import installer and get installer object! switch ($type) { case 'install': cssJSToolbox::import('includes:installer:installer:installer.class.php'); $installer = CJTInstaller::getInstance(); break; case 'upgrade': $upgrader = $vOperations['upgrader']; cssJSToolbox::import($upgrader['file']); $installer = new $upgrader['class'](); break; } // Execute the requested operation, save state only when succesed! if ($installer->{$rOperation['name']}()) { $operation['state'] = self::OPERATION_STATE_INSTALLED; // Update operations cache to reflect the new state! update_option(self::INSTALLATION_STATE, $operations); // Say OK! $result = array('state' => self::OPERATION_STATE_INSTALLED); } } } return $result; }
/** * put your comment there... * */ public function save() { // import libraries. cssJSToolbox::import('framework:db:mysql:xtable.inc.php'); // Initialize vars. $fSConfig = cssJSToolbox::$config->fileSystem; $currentUser = get_userdata(get_current_user_id()); $dbDriver = cssJSToolbox::getInstance()->getDBDriver(); $saveId = isset($this->inputs['item']['template']['id']) ? $this->inputs['item']['template']['id'] : null; // Load template data is exists (load), change values (setData). $template = CJTxTable::getInstance('template'); if ($saveId) { $template->set('id', $saveId)->load(); } $template->setData($this->inputs['item']['template'])->setQueueName(); $templateDirName = $template->get('queueName'); $templateDir = "wp-content/{$fSConfig->contentDir}/{$fSConfig->templatesDir}/{$templateDirName}"; if (!$template->get('id')) { // Add new Template // Search for author for the current local Wordpress user. // If not created in the Authors table create one! If created get the ID! $author = CJTxTable::getInstance('author', null, "SELECT * FROM #__cjtoolbox_authors \n\t\t\t\t\t\t\t\t\t\t\t\t\t WHERE name = '{$currentUser->user_login}'\n\t\t\t\t\t\t\t\t\t\t\t\t\t AND (attributes & 2);"); // Create Wordpress user in Authors table. if (!$author->get('id')) { $author->setData(array('name' => $currentUser->user_login, 'email' => $currentUser->user_email, 'url' => $currentUser->user_url, 'attributes' => 2))->save(); } // Set template data $template->set('ownerId', $currentUser->ID)->set('creationDate', current_time('mysql'))->set('authorId', $author->get('id')); } // Make sure directory created even if updating templats. // This case is needed when revisioned built-in templates (e.g jquery)!! if (!file_exists(ABSPATH . "/{$templateDir}")) { mkdir(ABSPATH . "/{$templateDir}", 0755); } // Save template. if (!$template->save()->get('id')) { throw new Exception('Error saving template into database!!!'); } /// Always create new revision. /// // Get last used Revision Number! $lastRevisionNo = (int) $dbDriver->getRow("SELECT max(revisionNo) revisionNo\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM #__cjtoolbox_template_revisions\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE templateId = {$template->get('id')}")->revisionNo; // Checki if there is a previous revision and if there is changes!! $lastRevision = CJTxTable::getInstance('template-revision', null, "SELECT * \n\t\t\t FROM #__cjtoolbox_template_revisions \n\t\t\t WHERE templateId = {$template->get('id')} AND revisionNo = {$lastRevisionNo}"); // Only add Revision if it has any field changed! $revisionData = $this->inputs['item']['revision']; $lastRevisionCode = $lastRevision->get('id') ? file_get_contents(ABSPATH . "/{$lastRevision->get('file')}") : null; $revisionHasChanges = $lastRevisionCode !== $revisionData['code'] || $lastRevision->get('state') !== $revisionData['state'] || $lastRevision->get('version') !== $revisionData['version'] || $lastRevision->get('changeLog') !== $revisionData['changeLog']; if ($revisionHasChanges) { $templateType = $template->get('type'); // New added revision number! $revisionNo = $lastRevisionNo + 1; // Get template revision extension. $extension = cssJSToolbox::$config->templates->types[$templateType]->extension; // Remove fields that not part of the revision table! $code = $this->inputs['item']['revision']['code']; unset($this->inputs['item']['revision']['code']); // Creae revision object. $revision = CJTxTable::getInstance('template-revision')->setData($this->inputs['item']['revision'])->set('templateId', $template->get('id'))->set('revisionNo', $revisionNo)->set('dateCreated', current_time('mysql'))->set('attributes', CJTTemplateRevisionTable::FLAG_LAST_REVISION)->set('file', "{$templateDir}/{$revisionNo}.{$extension}")->save(); // Encrypt PHP codes! if ($templateType == 'php') { $code = $this->encryptCode($code); } // Write revision content into Disk File! file_put_contents(ABSPATH . "/{$revision->get('file')}", $code); // Remove FLAG_LAST_REVISION flag from last revision so // our new revision will be the last one!! if ($lastRevision->get('id')) { $flagsOff = $lastRevision->get('attributes') & ~CJTTemplateRevisionTable::FLAG_LAST_REVISION; $lastRevision->set('attributes', $flagsOff)->save(); } } else { // Return last Revision! $revision = $lastRevision; } // Return revision object. return $revision->getData(); }