diff --git a/src/Actions.class b/src/Actions.class new file mode 100644 index 00000000..7f3b146a Binary files /dev/null and b/src/Actions.class differ diff --git a/src/Actions.java b/src/Actions.java new file mode 100644 index 00000000..d0c3a26c --- /dev/null +++ b/src/Actions.java @@ -0,0 +1,661 @@ +package com.tekdi.nfta.test; + +import static com.tekdi.nfta.test.NFTADriver.ObjectRepository; +import static io.restassured.RestAssured.*; +import static org.hamcrest.Matchers.*; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.UUID; +import java.util.logging.Logger; + +import org.apache.commons.io.FileUtils; +import org.openqa.selenium.Alert; +import org.openqa.selenium.By; +import org.openqa.selenium.JavascriptExecutor; +import org.openqa.selenium.OutputType; +import org.openqa.selenium.TakesScreenshot; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.firefox.FirefoxDriver; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import com.paulhammant.ngwebdriver.ByAngular; +import com.tekdi.nfta.config.Constant; + +import io.github.bonigarcia.wdm.WebDriverManager; + +public class Actions { + + WebDriver driver; + + Logger logger = Logger.getLogger(Actions.class.getName()); + + /** + * openBrowser will instantiate a new instance of a specified browser + * + * @param locator + * @param data + * @return + */ + + public String openBrowser(String locator, String data) { + try { + if (data.equalsIgnoreCase("Chrome")) { + WebDriverManager.chromedriver().setup(); + driver = new ChromeDriver(); + } else if (data.equalsIgnoreCase("Firefox")) { + WebDriverManager.firefoxdriver().setup(); + driver = new FirefoxDriver(); + } else { + WebDriverManager.chromedriver().setup(); + ChromeOptions options = new ChromeOptions(); + options.addArguments("--headless"); + options.addArguments("--disable-gpu"); + driver = new ChromeDriver(options); + } + driver.manage().window().maximize(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * navigateTo will navigate to a specified destination + * + * @param locator + * @param data + * @return + */ + + public String navigateTo(String locator, String data) { + try { + driver.navigate().to(data); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * enterText to a input field using locator as ID + * + * @param locator + * @param data + * @return + */ + + public String enterTextByID(String locator, String data) { + try { + driver.findElement(By.id(ObjectRepository.getProperty(locator))).sendKeys(data); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * enterText to a input field using locator as Name + * + * @param locator + * @param data + * @return + */ + + public String enterTextByName(String locator, String data) { + try { + driver.findElement(By.name(ObjectRepository.getProperty(locator))).sendKeys(data); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * enterText to a input field using locator as XPath + * + * @param locator + * @param data + * @return + */ + + public String enterTextByXpath(String locator, String data) { + try { + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).sendKeys(data); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * enterText to a input field using locator as CSS Selectors + * + * @param locator + * @param data + * @return + */ + + public String enterTextByCss(String locator, String data) { + + try { + if (data.isEmpty()) { + return "-- No Data is provided --"; + } else { + driver.findElement(By.cssSelector(ObjectRepository.getProperty(locator))).sendKeys(data); + } + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * enterText to a input field using locator as Class Name + * + * @param locator + * @param data + * @return + */ + + public String enterTextByClassName(String locator, String data) { + try { + driver.findElement(By.className(ObjectRepository.getProperty(locator))).sendKeys(data); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String elementToBeClickable(String locator, String data) { + try { + WebDriverWait wait = new WebDriverWait(driver, 30); + wait.until(ExpectedConditions.elementToBeClickable(By.xpath(ObjectRepository.getProperty(locator)))) + .click(); + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * clickButton using locator as ID + * + * @param locator + * @param data + * @return + */ + + public String clickElementByID(String locator, String data) { + try { + driver.findElement(By.id(ObjectRepository.getProperty(locator))).click(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * clickButton using locator as Name + * + * @param locator + * @param data + * @return + */ + + public String clickElementByName(String locator, String data) { + try { + driver.findElement(By.name(ObjectRepository.getProperty(locator))).click(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * clickButton using locator as XPath + * + * @param locator + * @param data + * @return + */ + + public String clickElementByXpath(String locator, String data) { + try { + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * clickButton using locator as CSS Selector + * + * @param locator + * @param data + * @return + */ + + public String clickElementByCss(String locator, String data) { + try { + driver.findElement(By.cssSelector(ObjectRepository.getProperty(locator))).click(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " " + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String acceptAlert(String locator, String data) { + try { + WebDriverWait wait=new WebDriverWait(driver, 70); + wait.until(ExpectedConditions.alertIsPresent()); + driver.switchTo().alert().accept(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + + /* + * public String acceptAlert(String locator, String data) { try { + * + * //driver.switchTo().alert(); // Switching to Alert Alert alert = + * driver.switchTo().alert(); + * + * // Capturing alert message. String alertMessage= + * driver.switchTo().alert().getText(); + * + * // Displaying alert message System.out.println(alertMessage); + * Thread.sleep(5000); + * + * // Accepting alert alert.accept(); } catch (Exception e) { return + * Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + * + * } return Constant.KEYWORD_PASS.getValue(); + * + * } + */ + public String dismissAlert(String locator, String data) { + + try { + driver.switchTo().alert().dismiss(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + + } + return Constant.KEYWORD_PASS.getValue(); + + } + + /** + * clickOnLinkByLinkText allows user to click the link by using the complete + * text present in the link + * + * @param locator + * @param data + * @return + */ + + public String clickOnLinkByLinkText(String locator, String data) { + + try { + driver.findElement(By.linkText(ObjectRepository.getProperty(locator))).click(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + + } + + /** + * clickOnLinkByPartialLinkText allows user to click the link by using the + * partial text present in the link + * + * @param locator + * @param data + * @return + */ + + public String clickOnLinkByPartialLinkText(String locator, String data) { + + try { + driver.findElement(By.partialLinkText(ObjectRepository.getProperty(locator))).click(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + + } + + public String fileupload(String locator, String filePath) { + try { + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))) + .sendKeys(System.getProperty("user.dir") + filePath); + // driver.findElement(By.id(ObjectRepository.getProperty(locator))).sendKeys(System.getProperty("user.dir") + // + filePath); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getStackTrace(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String scorllDown(String locator, String data) { + try { + JavascriptExecutor js = (JavascriptExecutor) driver; + js.executeScript("window.scrollTo(0, document.body.scrollHeight)"); + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String scorllUp(String locator, String data) { + try { + JavascriptExecutor js = (JavascriptExecutor) driver; + js.executeScript("window.scrollTo(document.body.scrollHeight, 0)"); + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String selectCheckBoxByCss(String locator, String data) { + + try { + WebElement element = driver.findElement(By.cssSelector(ObjectRepository.getProperty(locator))); + if (data.equalsIgnoreCase("Yes")) { + element.click(); + } + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * Application specific Keywords + * + */ + + /** + * clickButton using button text + * + * @param locator + * @param data + * @return + */ + + public String clickButtonByText(String locator, String data) { + try { + + driver.findElement(ByAngular.buttonText(ObjectRepository.getProperty(locator))).click(); + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String clickDropdownByXpath(String locator, String data) { + try { + + if (data.isEmpty()) { + return " -- No Data is provided --"; + } else { + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + List options = driver + .findElements(By.xpath(ObjectRepository.getProperty(locator) + "/div/ul/li")); + for (WebElement option : options) { + if (option.getText().equals(data)) { + option.click(); + break; + } + } + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + } + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + + return Constant.KEYWORD_PASS.getValue(); + } + + public String clickDropdowntrashByXpath(String locator, String data) { + try { + + if (data.isEmpty()) { + return " -- No Data is provided --"; + } else { + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + List options = driver + .findElements(By.xpath(ObjectRepository.getProperty(locator) + "/div/ul/li")); + //.findElements(By.xpath(ObjectRepository.getProperty(locator) + "//ul[@class='chzn-results']/li")); + + for (WebElement option : options) { + if (option.getText().equals(data)) { + option.click(); + break; + } + } + //driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + } + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + + return Constant.KEYWORD_PASS.getValue(); + } + + + public String clickDropdownUCM(String locator, String data) { + try { + + if (data.isEmpty()) { + return " -- No Data is provided --"; + } else { + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + List options = driver + .findElements(By.xpath(ObjectRepository.getProperty(locator) + "/div/ul/li")); + for (WebElement option : options) { + if (option.getText().equals(data)) { + option.click(); + break; + } + } + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + } + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + + return Constant.KEYWORD_PASS.getValue(); + } + + + + + + public String verifyPopupMessage(String locator, String data) { + try { + WebDriverWait wait = new WebDriverWait(driver, 10); + WebElement element = wait.until(ExpectedConditions + .visibilityOfElementLocated(By.cssSelector(ObjectRepository.getProperty(locator)))); + System.out.println(element.getText()); + return Constant.KEYWORD_PASS.getValue() + " " + element.getText(); + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + + } + + public String RandomstringCreate(String locator, String data) { + String uuid = UUID.randomUUID().toString(); + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).sendKeys(data); + return Constant.KEYWORD_PASS.getValue(); + } + + public String CheckElementEist(String locator, String data) { + try { + + if (locator.getBytes().equals(data)) { + + return " -- No Data is provided --"; + } else { + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + List options = driver + .findElements(By.xpath(ObjectRepository.getProperty(locator) + "//sui-select-option")); + for (WebElement option : options) { + if (option.getText().equals(data)) { + option.click(); + break; + } + } + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).click(); + } + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + + } + return data; + } + + public String verifyErrorMessage(String locator, String data) { + try { + return driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).getText(); + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + + } + + public String pause(String locator, String data) { + try { + Thread.sleep(2000); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + + } + + public String clickOnRadioByCss(String locator, String data) { + try { + if (data.equalsIgnoreCase("Yes")) { + driver.findElement(By.cssSelector(ObjectRepository.getProperty("openfornominationYes"))).click(); + } else if (data.equalsIgnoreCase("No")) { + driver.findElement(By.cssSelector(ObjectRepository.getProperty("openfornominationNo"))).click(); + } + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + + return Constant.KEYWORD_PASS.getValue(); + + } + + public String VerifyAPICallStatusIs200(String locator, String data) { + + try { + given().log().all().when().header("Authorization", "Bearer " + ObjectRepository.getProperty("apikey")) + .get(data).then().log().all().assertThat().statusCode(equalTo(200)); + + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + + return Constant.KEYWORD_PASS.getValue(); + + } + + public String enterClearTextByXpath(String locator, String data) { + try { + + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).clear(); + driver.findElement(By.xpath(ObjectRepository.getProperty(locator))).sendKeys(data); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String SwitchtoIframe(String locator, String data) { + try { + + driver.switchTo().frame(locator); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + public String SwitchtoDefaultContent(String locator, String data) { + try { + driver.switchTo().defaultContent(); + } catch (Exception e) { + + return Constant.KEYWORD_FAIL.getValue() + e.getMessage(); + } + return Constant.KEYWORD_PASS.getValue(); + } + + + public String quitBrowser(String locator, String data) { + try { + driver.quit(); + } catch (Exception e) { + return Constant.KEYWORD_FAIL.getValue() + " (Cause of Failure >> " + e.getMessage() + " )"; + } + return Constant.KEYWORD_PASS.getValue(); + } + + /** + * Not a keyword + */ + + public void takesScreenshot(String filename, String testStepResult) throws IOException { + File scrFile = null; + if (ObjectRepository.getProperty("takescreeshot_all").equals("Y")) { + try { + scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + FileUtils.copyFile(scrFile, new File(System.getProperty(Constant.PROJECT_ROOT_DIRECTORY.getValue()) + + "/screenshots/" + filename + ".png")); + } catch (Exception e) { + logger.warning(Constant.ERROR_SCREENSHOT.getValue() + driver); + + } + + } else if (testStepResult.startsWith(Constant.KEYWORD_FAIL.getValue()) + && ObjectRepository.getProperty("takescreeshot_failure").equals("Y")) { + try { + scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); + FileUtils.copyFile(scrFile, new File(System.getProperty(Constant.PROJECT_ROOT_DIRECTORY.getValue()) + + "/screenshots/" + filename + ".png")); + } catch (Exception e) { + logger.warning(Constant.ERROR_SCREENSHOT.getValue() + driver); + } + + } + } +} diff --git a/src/TestData.xlsx b/src/TestData.xlsx new file mode 100644 index 00000000..b922853b Binary files /dev/null and b/src/TestData.xlsx differ diff --git a/src/components/com_tjucm/administrator/access.xml b/src/components/com_tjucm/administrator/access.xml index 8f34851d..d634a3f0 100644 --- a/src/components/com_tjucm/administrator/access.xml +++ b/src/components/com_tjucm/administrator/access.xml @@ -14,11 +14,13 @@ + + diff --git a/src/components/com_tjucm/administrator/assets/css/tjucm.css b/src/components/com_tjucm/administrator/assets/css/tjucm.css index 7ae82a71..c323376d 100644 --- a/src/components/com_tjucm/administrator/assets/css/tjucm.css +++ b/src/components/com_tjucm/administrator/assets/css/tjucm.css @@ -1,33 +1,3 @@ -.icon-48-types { -background-image: url(../images/l_types.png); -padding-left:60px!important; -} - -.icon-48-type { -background-image: url(../images/l_types.png); -padding-left:60px!important; -} - -.color-box-types { -float: left;width: 15px;height: 15px;margin-right: 5px;border: 1px solid rgba(0, 0, 0, .2);} - -.icon-48-items { -background-image: url(../images/l_items.png); -padding-left:60px!important; -} - -.icon-48-item { -background-image: url(../images/l_items.png); -padding-left:60px!important; -} - -.color-box-items { -float: left;width: 15px;height: 15px;margin-right: 5px;border: 1px solid rgba(0, 0, 0, .2);} - -.other-filters{ - padding: 0 14px; -} - /* CSS for frontend*/ #item-form .radio input{ margin-left:5px !important; diff --git a/src/components/com_tjucm/administrator/assets/js/tjucm_type.js b/src/components/com_tjucm/administrator/assets/js/tjucm_type.js deleted file mode 100644 index 442914a5..00000000 --- a/src/components/com_tjucm/administrator/assets/js/tjucm_type.js +++ /dev/null @@ -1,3 +0,0 @@ -js = jQuery.noConflict(); -js(document).ready(function () { -}); diff --git a/src/components/com_tjucm/administrator/classes/funlist.php b/src/components/com_tjucm/administrator/classes/funlist.php deleted file mode 100644 index 33c7ffe4..00000000 --- a/src/components/com_tjucm/administrator/classes/funlist.php +++ /dev/null @@ -1,62 +0,0 @@ - - * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. - * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL - */ - -defined('_JEXEC') or die('Restricted access'); -jimport('joomla.form.form'); - -/** - * Extra function list. - * - * @package Joomla.site - * @subpackage com_tjucm - * - * @since 1.0 - */ -class TjucmFunList -{ - /** - * Function to get data - * - * @param STRING $table Name of database table - * @param STRING $selectList Selected value colume name - * @param STRING $where Query where condition - * @param STRING $returnObject Selecting data using JDatabase - link https://docs.joomla.org/Selecting_data_using_JDatabase - * @param STRING $joinType LEFT, RIGHT etc - * @param STRING $joinTable Name of database table - * - * @return true - * - * @since 1.0.0 - */ - public function getDataValues($table, $selectList = "*", $where = "", $returnObject = "", $joinType = "", $joinTable = "") - { - // Ref - link https://docs.joomla.org/Selecting_data_using_JDatabase - - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - - $query->select($selectList); - $query->from($table); - - if ($joinTable) - { - $query->join($joinType, $joinTable); - } - - if ($where) - { - $query->where($where); - } - - $db->setQuery($query); - - return $db->$returnObject(); - } -} diff --git a/src/components/com_tjucm/administrator/config.xml b/src/components/com_tjucm/administrator/config.xml index 0b33201a..0c76c8d1 100644 --- a/src/components/com_tjucm/administrator/config.xml +++ b/src/components/com_tjucm/administrator/config.xml @@ -3,4 +3,10 @@
- \ No newline at end of file +
+ + + + +
+ diff --git a/src/components/com_tjucm/administrator/controllers/types.php b/src/components/com_tjucm/administrator/controllers/types.php index 8fb4ed69..dd832451 100644 --- a/src/components/com_tjucm/administrator/controllers/types.php +++ b/src/components/com_tjucm/administrator/controllers/types.php @@ -320,7 +320,7 @@ public function import() foreach ($options as &$option) { - $fieldOptions['fieldoption'.$optionCount] = array("name" => $option->options, "value" => $option->value); + $fieldOptions['fieldoption' . $optionCount] = array("name" => $option->options, "value" => $option->value); $optionCount++; } } diff --git a/src/components/com_tjucm/administrator/houseKeeping/1.1.0/ucmSubformData.php b/src/components/com_tjucm/administrator/houseKeeping/1.1.0/ucmSubformData.php index dcdc6725..28a9cc9b 100644 --- a/src/components/com_tjucm/administrator/houseKeeping/1.1.0/ucmSubformData.php +++ b/src/components/com_tjucm/administrator/houseKeeping/1.1.0/ucmSubformData.php @@ -128,14 +128,11 @@ public function migrate() // Save ucmSubForm records if (!empty($ucmSubFormDataSet)) { - $itemFormModel = BaseDatabaseModel::getInstance('ItemForm', 'TjucmModel', array('ignore_request' => true)); - // Set ucm type id to check permission in Item form model save() for logged-in user $ucmTypeId = $tjUcmModelType->getTypeId($ucmSubFormClient); - $itemFormModel->setState('ucmType.id', $ucmTypeId); // Call method to save ucmsubform data into new UCM data - $subFormContentIds = $itemFormModel->saveUcmSubFormRecords($validData, $ucmSubFormDataSet); + $subFormContentIds = $this->saveUcmSubFormRecords($validData, $ucmSubFormDataSet, $ucmTypeId); // To update existing ucm subform field value from JSON to subform ucm type name if ($subFormContentIds) @@ -163,4 +160,104 @@ public function migrate() return $result; } + + /** + * Function to save ucmSubForm records + * + * @param ARRAY &$validData Parent record data + * @param ARRAY $ucmSubFormDataSet ucmSubForm records data + * @param ARRAY $ucmTypeId UCM Type Id + * + * @return ARRAY + */ + public function saveUcmSubFormRecords(&$validData, $ucmSubFormDataSet, $ucmTypeId) + { + $db = JFactory::getDbo(); + $subFormContentIds = array(); + $isNew = empty($validData['id']) ? 1 : 0; + + // Delete removed subform details + if (!$isNew) + { + $query = $db->getQuery(true); + $query->select('id'); + $query->from($db->quoteName('#__tj_ucm_data')); + $query->where($db->quoteName('parent_id') . '=' . $validData['id']); + $db->setQuery($query); + $oldSubFormContentIds = $db->loadColumn(); + } + + JLoader::import('components.com_tjfields.tables.fieldsvalue', JPATH_ADMINISTRATOR); + JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); + JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/models'); + $tjUcmModelType = JModelLegacy::getInstance('Type', 'TjucmModel'); + $itemFormModel = BaseDatabaseModel::getInstance('ItemForm', 'TjucmModel', array('ignore_request' => true)); + $itemFormModel->setState('ucmType.id', $ucmTypeId); + + if (!empty($ucmSubFormDataSet)) + { + foreach ($ucmSubFormDataSet as $client => $ucmSubFormTypeData) + { + $validData['client'] = $client; + $validData['type_id'] = $tjUcmModelType->getTypeId($client); + $clientDetail = explode('.', $client); + + // This is an extra field which is used to render the reference of the ucmsubform field on the form (used in case of edit) + $ucmSubformContentIdFieldName = $clientDetail[0] . '_' . $clientDetail[1] . '_' . 'contentid'; + $count = 0; + + foreach ($ucmSubFormTypeData as $ucmSubFormData) + { + $validData['id'] = isset($ucmSubFormData[$ucmSubformContentIdFieldName]) ? (int) $ucmSubFormData[$ucmSubformContentIdFieldName] : 0; + + // Unset extra data + $sfFieldName = $ucmSubFormData['ucmSubformFieldName']; + unset($ucmSubFormData['ucmSubformFieldName']); + $ucmSubformContentFieldElementId = 'jform[' . $sfFieldName . '][' . $sfFieldName . $count . '][' . $ucmSubformContentIdFieldName . ']'; + $count++; + + if ($insertedId = $itemFormModel->save($validData, $ucmSubFormData)) + { + $validData['id'] = $insertedId; + $subFormContentIds[] = array('elementName' => $ucmSubformContentFieldElementId, 'content_id' => $insertedId); + $ucmSubFormData[$ucmSubformContentIdFieldName] = $insertedId; + + // Get field id of contentid field + $fieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); + $fieldTable->load(array('name' => $ucmSubformContentIdFieldName)); + + // Add-Update the value of content id field in the fields value table - start + $fieldsValueTable = JTable::getInstance('Fieldsvalue', 'TjfieldsTable', array('dbo', $db)); + $fieldsValueTable->load(array('field_id' => $fieldTable->id, 'content_id' => $insertedId, 'client' => $validData['client'])); + + if (empty($fieldsValueTable->id)) + { + $fieldsValueTable->field_id = $fieldTable->id; + $fieldsValueTable->value = $fieldsValueTable->content_id = $insertedId; + $fieldsValueTable->client = $validData['client']; + } + + $fieldsValueTable->user_id = JFactory::getUser()->id; + $fieldsValueTable->store(); + + // Add-Update the value of content id field in the fields value table - end + } + } + } + } + + // Delete removed ucmSubForm record from the form + if (!empty($oldSubFormContentIds)) + { + foreach ($oldSubFormContentIds as $oldSubFormContentId) + { + if (array_search($oldSubFormContentId, array_column($subFormContentIds, 'content_id')) === false) + { + $itemFormModel->delete($oldSubFormContentId); + } + } + } + + return $subFormContentIds; + } } diff --git a/src/components/com_tjucm/administrator/houseKeeping/1.2.3/updateClientName.php b/src/components/com_tjucm/administrator/houseKeeping/1.2.3/updateClientName.php new file mode 100644 index 00000000..3cd32a52 --- /dev/null +++ b/src/components/com_tjucm/administrator/houseKeeping/1.2.3/updateClientName.php @@ -0,0 +1,265 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL + */ + +// No direct access +defined('_JEXEC') or die('Restricted access'); + +use Joomla\Registry\Registry; +use Joomla\CMS\Factory; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Filesystem\File; + +/** + * Migration file for TJ-UCM + * + * @since 1.0 + */ +class TjHouseKeepingUpdateClientName extends TjModelHouseKeeping +{ + public $title = "Update Types Name"; + + public $description = 'Update UCM Types name and name of fields in each Type'; + + /** + * Subform migration script + * + * @return void + * + * @since 1.0 + */ + public function migrate() + { + JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_tjucm/tables'); + JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_tjfields/tables'); + JLoader::import('components.com_tjfields.helpers.tjfields', JPATH_ADMINISTRATOR); + + // TJ-Fields helper object + $tjfieldsHelper = new TjfieldsHelper; + + $result = array(); + $ucmSubFormFieldsConfig = array(); + + try + { + // Get all the UCM types + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select('*'); + $query->from($db->qn('#__tj_ucm_types')); + $db->setQuery($query); + $ucmTypes = $db->loadObjectlist(); + + $session = JFactory::getSession(); + $updatedTypes = (empty($session->get('updatedTypes'))) ? array() : $session->get('updatedTypes'); + + if (!empty($ucmTypes)) + { + foreach ($ucmTypes as $ucmType) + { + if (in_array($ucmType->id, $updatedTypes)) + { + continue; + } + + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', $db)); + $ucmTypeTable->load($ucmType->id); + $updatedUniqueIdentifier = 'com_tjucm.' . preg_replace("/[^a-zA-Z0-9]/", "", str_replace('com_tjucm.', '', $ucmTypeTable->unique_identifier)); + $ucmTypeParams = new Registry($ucmType->params); + + // Variable to store the old client of the UCM Type + $oldClientName = $ucmTypeTable->unique_identifier; + $ucmTypeTable->unique_identifier = $updatedUniqueIdentifier; + + if ($ucmTypeTable->store()) + { + // Get all the field groups of the UCM Type + $query = $db->getQuery(true); + $query->select('*'); + $query->from($db->qn('#__tjfields_groups')); + $query->where($db->quoteName('client') . '=' . $db->quote($oldClientName)); + $db->setQuery($query); + $fieldGroups = $db->loadObjectlist(); + + foreach ($fieldGroups as $fieldGroup) + { + $tjfieldsGroupTable = JTable::getInstance('Group', 'TjfieldsTable', array('dbo', $db)); + $tjfieldsGroupTable->load($fieldGroup->id); + $tjfieldsGroupTable->client = $updatedUniqueIdentifier; + + // Update the client of field group in the given UCM Type + if ($tjfieldsGroupTable->store()) + { + $query = $db->getQuery(true); + $query->select('*'); + $query->from($db->qn('#__tjfields_fields')); + $query->where($db->quoteName('client') . '=' . $db->quote($oldClientName)); + $query->where($db->quoteName('group_id') . '=' . $fieldGroup->id); + $db->setQuery($query); + $fields = $db->loadObjectlist(); + + foreach ($fields as $field) + { + $tjfieldsFieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); + $tjfieldsFieldTable->load($field->id); + $tjfieldsFieldTable->client = $updatedUniqueIdentifier; + + if ($tjfieldsFieldTable->type == 'cluster') + { + $tjfieldsFieldTable->name = str_replace('.', '_', $updatedUniqueIdentifier) . '_clusterclusterid'; + } + elseif ($tjfieldsFieldTable->type == 'ownership') + { + $tjfieldsFieldTable->name = str_replace('.', '_', $updatedUniqueIdentifier) . '_ownershipcreatedby'; + } + elseif ($tjfieldsFieldTable->type == 'itemcategory') + { + $tjfieldsFieldTable->name = str_replace('.', '_', $updatedUniqueIdentifier) . '_itemcategoryitemcategory'; + } + else + { + $tjfieldsFieldTable->name = str_replace('.', '_', $updatedUniqueIdentifier) + . '_' . strtolower(preg_replace("/[^a-zA-Z0-9]/", "", $field->label)); + } + + $tjfieldsFieldTable->store(); + + // Check if field name is unique + $isUnique = $tjfieldsHelper->checkIfUniqueName($tjfieldsFieldTable->name); + + // If the name of the field is not unique then update the name by appending count to it + if ($isUnique > 1) + { + $count = 0; + + while ($tjfieldsHelper->checkIfUniqueName($tjfieldsFieldTable->name) > 1) + { + $count++; + $tjfieldsFieldTable->name = $tjfieldsFieldTable->name . $count; + } + + $tjfieldsFieldTable->store(); + } + } + } + } + + // Update client in ucm_data table + $query = $db->getQuery(true); + $fields = array($db->quoteName('client') . ' = ' . $db->quote($updatedUniqueIdentifier)); + $conditions = array($db->quoteName('client') . ' = ' . $db->quote($oldClientName)); + $query->update($db->quoteName('#__tj_ucm_data'))->set($fields)->where($conditions); + $db->setQuery($query); + $db->execute(); + + // Update client in fields_value table + $query = $db->getQuery(true); + $query->update($db->quoteName('#__tjfields_fields_value'))->set($fields)->where($conditions); + $db->setQuery($query); + $db->execute(); + + // Update value of ucmsubform fields in fields_value table + $query = $db->getQuery(true); + $fields = array($db->quoteName('value') . ' = ' . $db->quote($updatedUniqueIdentifier)); + $conditions = array($db->quoteName('value') . ' = ' . $db->quote($oldClientName)); + $query->update($db->quoteName('#__tjfields_fields_value'))->set($fields)->where($conditions); + $db->setQuery($query); + $db->execute(); + + $oldClientParts = explode('.', $oldClientName); + $newClientParts = explode('.', $updatedUniqueIdentifier); + $oldFileName = $oldClientParts[1] . 'form_extra.xml'; + $newFileName = $newClientParts[1] . 'form_extra.xml'; + $oldFileNameAdmin = $oldClientParts[1] . '_extra.xml'; + + // If the UCM type is of subform type then update the link in the respective field + if ($ucmTypeParams->get('is_subform')) + { + $query = $db->getQuery(true); + $query->select('*'); + $query->from($db->qn('#__tjfields_fields')); + $query->where($db->quoteName('params') . ' LIKE ' . $db->quote('%' . $oldFileName . '%')); + $db->setQuery($query); + $ucmSubFormFields = $db->loadObjectlist(); + + foreach ($ucmSubFormFields as $ucmSubFormField) + { + $tjfieldsFieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); + $tjfieldsFieldTable->load($ucmSubFormField->id); + $tjfieldsFieldTable->params = str_replace($oldFileName, $newFileName, $tjfieldsFieldTable->params); + $tjfieldsFieldTable->store(); + } + } + + // If the UCM type is used as data source in related field the we need to update the UCM name in the field params + if ($ucmTypeParams->get('is_subform')) + { + $query = $db->getQuery(true); + $query->select('*'); + $query->from($db->qn('#__tjfields_fields')); + $query->where($db->quoteName('params') . ' LIKE ' . $db->quote('%' . $oldClientName . '%')); + $db->setQuery($query); + $formFields = $db->loadObjectlist(); + + foreach ($formFields as $formField) + { + $tjfieldsFieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); + $tjfieldsFieldTable->load($formField->id); + $fieldParams = new Registry($tjfieldsFieldTable->params); + + if ($fieldParams->get('client') == $oldClientName) + { + $fieldParams->set('client', $updatedUniqueIdentifier); + } + + $tjfieldsFieldTable->params = json_encode($fieldParams); + $tjfieldsFieldTable->store(); + } + } + + // Delete the old XML files for the UCM type + if (File::exists(JPATH_SITE . '/components/com_tjucm/models/forms/' . $oldFileName)) + { + File::delete(JPATH_SITE . '/components/com_tjucm/models/forms/' . $oldFileName); + } + + if (File::exists(JPATH_SITE . '/' . 'administrator/components/com_tjucm/models/forms/' . $oldFileNameAdmin)) + { + File::delete(JPATH_SITE . '/' . 'administrator/components/com_tjucm/models/forms/' . $oldFileNameAdmin); + } + + // Regenerate the XML files + $tjfieldsHelper->generateXml(array('client' => $updatedUniqueIdentifier, 'client_type' => $newClientParts[1])); + } + + $updatedTypes[] = $ucmType->id; + $session->set('updatedTypes', $updatedTypes); + + $result['status'] = ''; + $result['message'] = "Migration in progress"; + + return $result; + } + } + + $session->set('updatedTypes', ''); + + $result['status'] = true; + $result['message'] = "Migration successful"; + } + catch (Exception $e) + { + $result['err_code'] = ''; + $result['status'] = false; + $result['message'] = $e->getMessage(); + } + + return $result; + } +} diff --git a/src/components/com_tjucm/administrator/houseKeeping/1.2.4/updateAlias.php b/src/components/com_tjucm/administrator/houseKeeping/1.2.4/updateAlias.php new file mode 100644 index 00000000..95c61ddc --- /dev/null +++ b/src/components/com_tjucm/administrator/houseKeeping/1.2.4/updateAlias.php @@ -0,0 +1,109 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL + */ + +// No direct access +defined('_JEXEC') or die('Restricted access'); + +/** + * Migration file for TJ-UCM + * + * @since 1.2.4 + */ +class TjHouseKeepingUpdateAlias extends TjModelHouseKeeping +{ + public $title = "Update Types Alias"; + + public $description = 'Update UCM Types alias'; + + /** + * Subform migration script + * + * @return void + * + * @since 1.2.4 + */ + public function migrate() + { + JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_tjucm/tables'); + JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_menus/tables'); + JLoader::import('components.com_tjfields.helpers.tjfields', JPATH_ADMINISTRATOR); + + // TJ-Fields helper object + $tjfieldsHelper = new TjfieldsHelper; + + $result = array(); + + try + { + // Get all the UCM types + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select('*'); + $query->from($db->qn('#__tj_ucm_types')); + $db->setQuery($query); + $ucmTypes = $db->loadObjectlist(); + + if (!empty($ucmTypes)) + { + foreach ($ucmTypes as $ucmType) + { + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', $db)); + $ucmTypeTable->load($ucmType->id); + + // Remove white spaces in alias of UCM types + $updatedAlias = JFilterOutput::stringURLSafe($ucmTypeTable->alias); + $ucmTypeTable->alias = $updatedAlias; + $ucmTypeTable->store(); + } + } + + // Get all the menus of UCM types + $query = $db->getQuery(true); + $query->select('*'); + $query->from($db->quoteName('#__menu')); + $query->where( + $db->quoteName('link') . "=" . $db->quote('index.php?option=com_tjucm&view=itemform') . + "||" . $db->quoteName('link') . "=" . $db->quote('index.php?option=com_tjucm&view=items') + ); + $db->setQuery($query); + $menuItems = $db->loadObjectlist(); + + if (!empty($menuItems)) + { + foreach ($menuItems as $menuItem) + { + $menuItemTable = JTable::getInstance('Menu', 'MenusTable', array('dbo', $db)); + $menuItemTable->load($menuItem->id); + $oldparams = json_decode($menuItemTable->params); + + // Remove white spaces in alias of menus + if (isset($oldparams->ucm_type)) + { + $oldparams->ucm_type = JFilterOutput::stringURLSafe($oldparams->ucm_type); + } + + $menuItemTable->params = json_encode($oldparams); + $menuItemTable->store(); + } + } + + $result['status'] = true; + $result['message'] = "Migration successful"; + } + catch (Exception $e) + { + $result['err_code'] = ''; + $result['status'] = false; + $result['message'] = $e->getMessage(); + } + + return $result; + } +} diff --git a/src/components/com_tjucm/administrator/models/forms/filter_types.xml b/src/components/com_tjucm/administrator/models/forms/filter_types.xml new file mode 100644 index 00000000..6dce3c49 --- /dev/null +++ b/src/components/com_tjucm/administrator/models/forms/filter_types.xml @@ -0,0 +1,19 @@ + +
+ + + + + + + +
\ No newline at end of file diff --git a/src/components/com_tjucm/administrator/models/forms/type.xml b/src/components/com_tjucm/administrator/models/forms/type.xml index 3497a681..499313fc 100644 --- a/src/components/com_tjucm/administrator/models/forms/type.xml +++ b/src/components/com_tjucm/administrator/models/forms/type.xml @@ -1,36 +1,18 @@ - +
- - - - - + - - - - - - - - - - - - - -
diff --git a/src/components/com_tjucm/administrator/models/item.php b/src/components/com_tjucm/administrator/models/item.php index 1a6bf330..9eb0466e 100644 --- a/src/components/com_tjucm/administrator/models/item.php +++ b/src/components/com_tjucm/administrator/models/item.php @@ -45,22 +45,6 @@ class TjucmModelItem extends JModelAdmin // Use imported Trait in model use TjfieldsFilterField; - /** - * Constructor. - * - * @param array $config An optional associative array of configuration settings. - * - * @see JController - * @since 1.6 - */ - public function __construct($config = array()) - { - JLoader::import('components.com_tjucm.classes.funlist', JPATH_ADMINISTRATOR); - $this->common = new TjucmFunList; - - parent::__construct($config); - } - /** * Get an array of data items * @@ -290,7 +274,10 @@ public function save($data, $extra_jform_data = '', $post = '') $input = JFactory::getApplication()->input; $filter = JFilterInput::getInstance(); - $data['type_id'] = $this->common->getDataValues('#__tj_ucm_types', 'id AS type_id', 'unique_identifier = "' . $this->client . '"', 'loadResult'); + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $tjUcmTypeTable = JTable::getInstance('TjucmTableType', 'JTable', array('dbo', JFactory::getDbo())); + $tjUcmTypeTable->load(array('unique_identifier' => $this->client)); + $data['type_id'] = $tjUcmTypeTable->id; if (parent::save($data)) { diff --git a/src/components/com_tjucm/administrator/models/type.php b/src/components/com_tjucm/administrator/models/type.php index 782c53a2..a737298d 100644 --- a/src/components/com_tjucm/administrator/models/type.php +++ b/src/components/com_tjucm/administrator/models/type.php @@ -13,6 +13,8 @@ jimport('joomla.application.component.modeladmin'); +use Joomla\CMS\MVC\Model\BaseDatabaseModel; + /** * Tjucm model. * @@ -48,8 +50,8 @@ class TjucmModelType extends JModelAdmin */ public function __construct($config = array()) { - JLoader::import('components.com_tjucm.classes.funlist', JPATH_ADMINISTRATOR); - $this->common = new TjucmFunList; + $config['event_after_delete'] = 'tjUcmOnAfterTypeDelete'; + $config['event_change_state'] = 'tjUcmOnAfterTypeChangeState'; parent::__construct($config); } @@ -308,44 +310,31 @@ public function save($data) } // Remove white spaces from alias if any - $data['alias'] = str_replace(" ", "_", trim($data['alias'])); + // $data['alias'] = str_replace(" ", "_", trim($data['alias'])); + $data['alias'] = JFilterOutput::stringURLSafe($data['alias']); if (!empty($data['id'])) { $field_group = $this->getGroupCount($data['unique_identifier']); - - // Not able to get count using getTotal method of category model - $field_category = $this->common->getDataValues('#__categories', 'count(*)', 'extension = "' . $data['unique_identifier'] . '"', 'loadResult'); - - // $field_category = $this->getCategoryCount($data['unique_identifier']); + $field_category = $this->getCategoryCount($data['unique_identifier']); if ($field_group == 0 && $field_category == 0) { - $data['unique_identifier'] = 'com_tjucm.' . $data['alias']; + $data['unique_identifier'] = 'com_tjucm.' . preg_replace("/[^a-zA-Z0-9]/", "", $data['alias']); } } else { - $data['unique_identifier'] = 'com_tjucm.' . $data['alias']; + $data['unique_identifier'] = 'com_tjucm.' . preg_replace("/[^a-zA-Z0-9]/", "", $data['alias']); } - $params = array(); - $params['is_subform'] = $data['is_subform']; - $params['allow_draft_save'] = $data['allow_draft_save']; - $params['allow_auto_save'] = $data['allow_auto_save']; - $params['publish_items'] = $data['publish_items']; - $params['allowed_count'] = $data['allowed_count']; - $params['layout'] = $data['layout']; - $params['details_layout'] = $data['details_layout']; - $params['list_layout'] = $data['list_layout']; - // If UCM type is a subform then need to add content_id as hidden field in the form - For flat subform storage JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); $db = JFactory::getDbo(); $tjfieldsFieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); $tjfieldsFieldTable->load(array('name' => str_replace('.', '_', $data['unique_identifier']) . '_contentid')); - if ($params['is_subform'] == 1 && empty($tjfieldsFieldTable->id)) + if ($data['params']['is_subform'] == 1 && empty($tjfieldsFieldTable->id)) { JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjfields/models'); $fieldGroup = array("name" => "hidden", "title" => "hidden", "client" => $data['unique_identifier'], "state" => 1); @@ -365,22 +354,27 @@ public function save($data) $input->post->set('client_type', ''); } - // If UCM type is a subform then it cant be saved as draft and auto save is also disabled - if ($params['is_subform'] == 1) + // Check the params 'Group' of fields & UCM type is a subform then it cant be saved as draft and auto save is also disabled + if ($data['params']['is_subform'] == 1) { - $params['allow_draft_save'] = $params['allow_auto_save'] = $params['allowed_count'] = 0; + $data['params']['allow_draft_save'] = $data['params']['allow_auto_save'] = $data['params']['allowed_count'] = 0; } // If auto save is enabled then draft save is enabled by default - if ($params['allow_auto_save'] == 1) + if ($data['params']['allow_auto_save'] == 1) { - $params['allow_draft_save'] = 1; + $data['params']['allow_draft_save'] = 1; } - $data['params'] = json_encode($params); - if (parent::save($data)) { + $id = (int) $this->getState($this->getName() . '.id'); + $data['typeId'] = $id; + $dispatcher = JDispatcher::getInstance(); + JPluginHelper::importPlugin('actionlog', 'tjucm'); + $isNew = ($data['id'] != 0) ? false : true; + $dispatcher->trigger('tjUcmOnAfterTypeSave', array($data, $isNew)); + return true; } @@ -417,10 +411,10 @@ public function getGroupCount($client) public function getCategoryCount($client) { JLoader::import('components.com_categories.models.categories', JPATH_ADMINISTRATOR); - $categories_model = JModelLegacy::getInstance('Categories', 'CategoriesModel'); - $categories_model->setState('filter.extension', $client); + $categoryModel = JModelLegacy::getInstance('Categories', 'CategoriesModel', array('ignore_request' => true)); + $categoryModel->setState('filter.extension', $client); - return $categories_model->getTotal(); + return $categoryModel->getTotal(); } /** @@ -543,11 +537,75 @@ public function delete(&$pks) // Delete UCM type if (!parent::delete($pk)) - { + { return false; } } return true; } + + /** + * Method to validation before copy items + * + * @param object $sourceClient Source client. + * @param object $targetClient Tareget client. + * + * @return Boolean + * + * @since __DEPLOY_VERSION__ + */ + public function getCompatibleUcmTypes($sourceClient, $targetClient) + { + $validUcmType = array(); + + if (!$sourceClient && !$targetClient) + { + return false; + } + + // Get the source ucm type and target ucm type fields list + BaseDatabaseModel::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjfields/models'); + $tjFieldsFieldsModel = BaseDatabaseModel::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); + + // Get source UCM Type fields + $tjFieldsFieldsModel->setState('filter.client', $sourceClient); + $sourceFields = $tjFieldsFieldsModel->getItems(); + + // Get destination UCM Type fields + $tjFieldsFieldsModel = BaseDatabaseModel::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); + $tjFieldsFieldsModel->setState('filter.client', $targetClient); + $targetFields = $tjFieldsFieldsModel->getItems(); + + $count = 0; + + if (count($sourceFields) == count($targetFields)) + { + foreach ($sourceFields as $sourceField) + { + $prefix = str_replace(".", "_", $sourceClient); + $sourceFieldName = explode($prefix . "_", $sourceField->name); + + foreach ($targetFields as $targetField) + { + $prefix = str_replace(".", "_", $targetClient); + $targetFieldName = explode($prefix . "_", $targetField->name); + + // Check source and destination field name and field types are equal + if ($sourceFieldName == $targetFieldName && $sourceField->type == $targetField->type) + { + $count ++; + continue; + } + } + } + } + + if (count($sourceFields) == $count) + { + return true; + } + + return false; + } } diff --git a/src/components/com_tjucm/administrator/tjucm.php b/src/components/com_tjucm/administrator/tjucm.php index 0bfd57c3..fd288f3f 100644 --- a/src/components/com_tjucm/administrator/tjucm.php +++ b/src/components/com_tjucm/administrator/tjucm.php @@ -20,15 +20,6 @@ // Include dependancies jimport('joomla.application.component.controller'); -$path = JPATH_COMPONENT_ADMINISTRATOR . '/classes/' . 'funlist.php'; - -if (!class_exists('TjucmFunList')) -{ - // Require_once $path; - JLoader::register('TjucmFunList', $path); - JLoader::load('TjucmFunList'); -} - // Load backend helper $path = JPATH_ADMINISTRATOR . '/components/com_tjucm/helpers/tjucm.php'; diff --git a/src/components/com_tjucm/administrator/views/item/view.html.php b/src/components/com_tjucm/administrator/views/item/view.html.php index e5ccfae0..b6b01f4c 100644 --- a/src/components/com_tjucm/administrator/views/item/view.html.php +++ b/src/components/com_tjucm/administrator/views/item/view.html.php @@ -96,7 +96,7 @@ protected function addToolbar() $canDo = TjucmHelper::getActions(); - JToolBarHelper::title(JText::_('COM_TJUCM_TITLE_ITEM'), 'item.png'); + JToolBarHelper::title(JText::_('COM_TJUCM_TITLE_ITEM'), 'icon-pencil'); // If not checked out, can save the item. if (!$checkedOut && ($canDo->get('core.edit') || ($canDo->get('core.create')))) diff --git a/src/components/com_tjucm/administrator/views/items/view.html.php b/src/components/com_tjucm/administrator/views/items/view.html.php index 7df465d5..89810a12 100644 --- a/src/components/com_tjucm/administrator/views/items/view.html.php +++ b/src/components/com_tjucm/administrator/views/items/view.html.php @@ -78,7 +78,7 @@ protected function addToolbar() $state = $this->get('State'); $canDo = TjucmHelper::getActions(); - JToolBarHelper::title(JText::_('COM_TJUCM_TITLE_ITEMS'), 'items.png'); + JToolBarHelper::title(JText::_('COM_TJUCM_TITLE_ITEMS'), 'list'); // Check if the form exists before showing the add/edit buttons $formPath = JPATH_COMPONENT_ADMINISTRATOR . '/views/item'; diff --git a/src/components/com_tjucm/administrator/views/type/tmpl/edit.php b/src/components/com_tjucm/administrator/views/type/tmpl/edit.php index 21ec84bd..c861509a 100644 --- a/src/components/com_tjucm/administrator/views/type/tmpl/edit.php +++ b/src/components/com_tjucm/administrator/views/type/tmpl/edit.php @@ -14,15 +14,8 @@ JHtml::_('behavior.formvalidation'); JHtml::_('formbehavior.chosen', 'select'); JHtml::_('behavior.keepalive'); - -JHtml::script(JUri::root() . 'administrator/components/com_tjucm/assets/js/tjucm_type.js'); ?> -extra_sidebar)) -{ - $this->sidebar .= $this->extra_sidebar; -} -?> + - sidebar)): ?> + sidebar)): ?>
sidebar; ?>
-
-
- +
- - + $this)); ?>
pagination->getLimitBox(); ?>
@@ -160,7 +144,7 @@
diff --git a/src/components/com_tjucm/administrator/views/types/view.html.php b/src/components/com_tjucm/administrator/views/types/view.html.php index 41e0f94e..8fcb032e 100644 --- a/src/components/com_tjucm/administrator/views/types/view.html.php +++ b/src/components/com_tjucm/administrator/views/types/view.html.php @@ -41,6 +41,8 @@ public function display($tpl = null) $this->state = $this->get('State'); $this->items = $this->get('Items'); $this->pagination = $this->get('Pagination'); + $this->filterForm = $this->get('FilterForm'); + $this->activeFilters = $this->get('ActiveFilters'); // Check for errors. if (count($errors = $this->get('Errors'))) @@ -67,8 +69,8 @@ protected function addToolbar() { $state = $this->get('State'); $canDo = TjucmHelper::getActions(); - - JToolBarHelper::title(JText::_('COM_TJUCM_TITLE_TYPES'), 'types.png'); + $component_title = JText::_('COM_TJUCM_COMPONENT'); + JToolBarHelper::title($component_title . " : " . JText::_('COM_TJUCM_TITLE_TYPES'), 'list'); // Check if the form exists before showing the add/edit buttons $formPath = JPATH_COMPONENT_ADMINISTRATOR . '/views/type'; @@ -138,20 +140,6 @@ protected function addToolbar() { JToolBarHelper::preferences('com_tjucm'); } - - // Set sidebar action - New in 3.0 - JHtmlSidebar::setAction('index.php?option=com_tjucm&view=types'); - - $this->extra_sidebar = ''; - JHtmlSidebar::addFilter( - - JText::_('JOPTION_SELECT_PUBLISHED'), - - 'filter_published', - - JHtml::_('select.options', JHtml::_('jgrid.publishedOptions'), "value", "text", $this->state->get('filter.state'), true) - - ); } /** diff --git a/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.ini b/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.ini index ed8ac522..b95375a3 100644 --- a/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.ini +++ b/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.ini @@ -1,178 +1,205 @@ -COM_TJUCM="TJ - UCM" -COM_TJUCM_COMPONENT_LABEL="Tjucm" -COM_TJUCM_CONFIGURATION="Tjucm Configuration" -COM_TJUCM_ACCESS_HEADING="Access" -COM_TJUCM_COMPONENT_DESC="TJ Universal Content Manager test" -COM_TJUCM_N_ITEMS_ARCHIVED="%d items successfully archived" -COM_TJUCM_N_ITEMS_ARCHIVED_1="%d item successfully archived" -COM_TJUCM_N_ITEMS_CHECKED_IN_0="No item successfully checked in" -COM_TJUCM_N_ITEMS_CHECKED_IN_1="%d item successfully checked in" -COM_TJUCM_N_ITEMS_CHECKED_IN_MORE="%d items successfully checked in" -COM_TJUCM_N_ITEMS_DELETED="%d items successfully deleted" -COM_TJUCM_N_ITEMS_DELETED_1="%d item successfully deleted" -COM_TJUCM_N_ITEMS_PUBLISHED="%d items successfully published" -COM_TJUCM_N_ITEMS_PUBLISHED_1="%d item successfully published" -COM_TJUCM_N_ITEMS_TRASHED="%d items successfully trashed" -COM_TJUCM_N_ITEMS_TRASHED_1="%d item successfully trashed" -COM_TJUCM_N_ITEMS_UNPUBLISHED="%d items successfully unpublished" -COM_TJUCM_N_ITEMS_UNPUBLISHED_1="%d item successfully unpublished" -COM_TJUCM_NO_ITEM_SELECTED="No items selected" -COM_TJUCM_SAVE_SUCCESS="Item successfully saved" -COM_TJUCM_ITEM_ID_SELECT_LABEL="Select the item ID" -COM_TJUCM_SELECT_UCM_TYPE_LBL="UCM Type" -COM_TJUCM_SELECT_UCM_TYPE_DESC="Select UCM Type" -COM_TJUCM_FIELDSET_UCM_TYPE_SELECT_LABEL="UCM Config" -COM_TJUCM_FILTER_SELECT_LABEL=" - Select %s - " -COM_TJUCM_TEST_LABEL="Test label" -COM_TJUCM_FIELDSET_RULES="Permissions" -COM_TJUCM_FROM_FILTER="From %s" -COM_TJUCM_TO_FILTER="To %s" -COM_TJUCM_VIEW_FILE="[View File]" -COM_TJUCM_ITEMS_SUCCESS_DUPLICATED="Items successfully duplicated" -COM_TJUCM_SOMETHING_WENT_WRONG="Something went wrong" - -COM_TJUCM_TYPE_EXPORT="Export" -COM_TJUCM_TYPE_IMPORT="Import" -COM_TJUCM_TYPE_DELETE_CONFIRMATION="All the field groups, fields and the data related to selected UCM type(s) will be deleted. Are you sure that you want to delete the selected UCM type(s)?" -COM_TJUCM_TITLE_TYPES="Types" -COM_TJUCM_TYPES_ID="ID" -COM_TJUCM_TYPES_ORDERING="Order" -COM_TJUCM_TYPES_TITLE="Title" -COM_TJUCM_TYPES_ALIAS="Alias" -COM_TJUCM_TYPES_STATE="State" -COM_TJUCM_TYPES_TYPE_DESCRIPTION="Type Description" -COM_TJUCM_TYPES_UNIQUE_IDENTIFIER="Unique Identifier" -COM_TJUCM_TYPES_PARAMS="Params" -COM_TJUCM_TYPES_CHECKED_OUT="N/A" -COM_TJUCM_TYPES_CHECKED_OUT_TIME="N/A" -COM_TJUCM_TYPES_CREATED_BY="Created by" -COM_TJUCM_TYPES_CREATED_DATE="Created Date" -COM_TJUCM_TYPES_MODIFIED_BY="Modified by" -COM_TJUCM_TYPES_MODIFIED_DATE="Modified Date" -COM_TJUCM_TYPES_IMPORT="Import UCM Types" -COM_TJUCM_TYPES_IMPORT_TYPES_JSON="Import UCM Types" -COM_TJUCM_IMPORT="Import" -COM_TJUCM_TYPE_IMPORT_INVALID_FILE_UPLOAD_ERROR="Uploaded file is invalid" -COM_TJUCM_TYPE_IMPORT_FILE_UPLOAD_ERROR="Unable to upload the file" -COM_TJUCM_TYPE_IMPORT_INVALID_FILE_CONTENT_ERROR="File content is invalid" -COM_TJUCM_TYPE_IMPORT_SUCCESS_MSG="UCM type(s) imported successfully" -COM_TJUCM_DUPLICATE_TYPE_ERROR="UCM type already exists" - -COM_TJUCM_TITLE_ITEMS="Items" -COM_TJUCM_ITEMS_ID="ID" -COM_TJUCM_ITEMS_ORDERING="Order" -COM_TJUCM_ITEMS_STATE="State" -COM_TJUCM_ITEMS_CATEGORY_ID="Category Id" -COM_TJUCM_ITEMS_TYPE_ID="Type Id" -COM_TJUCM_ITEMS_CHECKED_OUT="N/A" -COM_TJUCM_ITEMS_CHECKED_OUT_TIME="N/A" -COM_TJUCM_ITEMS_CREATED_BY="Created by" -COM_TJUCM_ITEMS_CREATED_DATE="Created Date" -COM_TJUCM_ITEMS_MODIFIED_BY="Modified by" -COM_TJUCM_ITEMS_MODIFIED_DATE="Modified Date" -COM_TJUCM_TITLE_TYPE="Type" -COM_TJUCM_LEGEND_TYPE="Type" -COM_TJUCM_FORM_LBL_TYPE_ID="ID" -COM_TJUCM_FORM_DESC_TYPE_ID="" -COM_TJUCM_FORM_LBL_TYPE_ORDERING="Order" -COM_TJUCM_FORM_DESC_TYPE_ORDERING="" -COM_TJUCM_FORM_LBL_TYPE_TITLE="Title" -COM_TJUCM_FORM_DESC_TYPE_TITLE="Enter title" -COM_TJUCM_FORM_LBL_TYPE_ALIAS="Alias" -COM_TJUCM_FORM_DESC_TYPE_ALIAS="Enter alias for this UCM type" -COM_TJUCM_FORM_LBL_TYPE_STATE="State" -COM_TJUCM_FORM_DESC_TYPE_STATE="Select the UCM type state" -COM_TJUCM_FORM_LBL_TYPE_ALLOWED_COUNT="Allowed Count" -COM_TJUCM_FORM_DESC_TYPE_ALLOWED_COUNT="Enter how many times one user can add item for this UCM type" -COM_TJUCM_FORM_LBL_TYPE_ALLOW_DRAFT_SAVE="Allow Draft Save" -COM_TJUCM_FORM_DESC_TYPE_ALLOW_DRAFT_SAVE="Set to 'YES' if you want to allow partial submission of item" -COM_TJUCM_FORM_LBL_TYPE_ALLOW_AUTO_SAVE="Allow Auto Save" -COM_TJUCM_FORM_DESC_TYPE_ALLOW_AUTO_SAVE="Set to 'YES' if you want to allow auto save of item" -COM_TJUCM_FORM_LBL_TYPE_TYPE_DESCRIPTION="Description" -COM_TJUCM_FORM_DESC_TYPE_TYPE_DESCRIPTION="Enter description" -COM_TJUCM_FORM_LBL_TYPE_UNIQUE_IDENTIFIER="Unique Identifier" -COM_TJUCM_FORM_DESC_TYPE_UNIQUE_IDENTIFIER="Enter unique identifier for this UCM type" -COM_TJUCM_FORM_LBL_TYPE_PARAMS="Params" -COM_TJUCM_FORM_DESC_TYPE_PARAMS="" -COM_TJUCM_FORM_LBL_TYPE_CHECKED_OUT="N/A" -COM_TJUCM_FORM_DESC_TYPE_CHECKED_OUT="" -COM_TJUCM_FORM_LBL_TYPE_CHECKED_OUT_TIME="N/A" -COM_TJUCM_FORM_DESC_TYPE_CHECKED_OUT_TIME="" -COM_TJUCM_FORM_LBL_TYPE_CREATED_BY="Created by" -COM_TJUCM_FORM_DESC_TYPE_CREATED_BY="" -COM_TJUCM_FORM_LBL_TYPE_CREATED_DATE="Created Date" -COM_TJUCM_FORM_DESC_TYPE_CREATED_DATE="" -COM_TJUCM_FORM_LBL_TYPE_MODIFIED_BY="Modified by" -COM_TJUCM_FORM_DESC_TYPE_MODIFIED_BY="" -COM_TJUCM_FORM_LBL_TYPE_MODIFIED_DATE="Modified Date" -COM_TJUCM_FORM_DESC_TYPE_MODIFIED_DATE="" -COM_TJUCM_TITLE_ITEM="Item" -COM_TJUCM_LEGEND_ITEM="Item" -COM_TJUCM_FORM_LBL_ITEM_ID="ID" -COM_TJUCM_FORM_DESC_ITEM_ID="" -COM_TJUCM_FORM_LBL_ITEM_ORDERING="Order" -COM_TJUCM_FORM_DESC_ITEM_ORDERING="" -COM_TJUCM_FORM_LBL_ITEM_STATE="State" -COM_TJUCM_FORM_DESC_ITEM_STATE="" -COM_TJUCM_FORM_LBL_ITEM_CATEGORY_ID="Category Id" -COM_TJUCM_FORM_DESC_ITEM_CATEGORY_ID="" -COM_TJUCM_FORM_LBL_ITEM_TYPE_ID="Type Id" -COM_TJUCM_FORM_DESC_ITEM_TYPE_ID="" -COM_TJUCM_FORM_LBL_ITEM_CHECKED_OUT="N/A" -COM_TJUCM_FORM_DESC_ITEM_CHECKED_OUT="" -COM_TJUCM_FORM_LBL_ITEM_CHECKED_OUT_TIME="N/A" -COM_TJUCM_FORM_DESC_ITEM_CHECKED_OUT_TIME="" -COM_TJUCM_FORM_LBL_ITEM_CREATED_BY="Created by" -COM_TJUCM_FORM_DESC_ITEM_CREATED_BY="" -COM_TJUCM_FORM_LBL_ITEM_CREATED_DATE="Created Date" -COM_TJUCM_FORM_DESC_ITEM_CREATED_DATE="" -COM_TJUCM_FORM_LBL_ITEM_MODIFIED_BY="Modified by" -COM_TJUCM_FORM_DESC_ITEM_MODIFIED_BY="" -COM_TJUCM_FORM_LBL_ITEM_MODIFIED_DATE="Modified Date" -COM_TJUCM_FORM_DESC_ITEM_MODIFIED_DATE="" -COM_TJUCM_TITLE_LIST_VIEW_ITEMS="Items" -COM_TJUCM_TITLE_LIST_VIEW_ITEMS_DESC="Show list of Items" -COM_TJUCM_TITLE_ITEM_VIEW_ITEM="Single Item" -COM_TJUCM_TITLE_ITEM_VIEW_ITEM_DESC="Show specific Item" -COM_TJUCM_TITLE_FORM_VIEW_ITEM="ItemForm" -COM_TJUCM_TITLE_FORM_VIEW_ITEM_DESC="Show a form to add or edit an Item" -COM_TJUCM_SAVE_WARNING="Alias already existed so a number was added at the end. You can re-edit the article to customise the alias." -COM_TJUCM_TYPES_MANAGER="Manage" -COM_TJUCM_TYPES_CATEGORY_URL="Category" -COM_TJUCM_TYPES_FIELD_GROUP_URL="Field Group" -COM_TJUCM_TYPES_FIELDS_URL="Fields" -COM_TJUCM_TYPES_DATA_URL="Items" -COM_TJUCM_TYPES_ADD_NEW_DATA_URL="Create Item" -COM_TJUCM_NO_FIELDS_TO_SHOW_ON_LIST_VIEW="Please set 'Show on list view' to 'yes' for at least one field of this UCM type" -COM_TJUCM_NO_DATA_FOUND="No Data Found" -COM_TJUCM_TITLE_FIX_DATABASE="Fix Database" -COM_TJUCM_PERMISSION_VIEW="View" -COM_TJUCM_PERMISSION_TYPE_ITEM_CREATE="Create Item" -COM_TJUCM_PERMISSION_TYPE_ITEM_CREATE_DESC="Allows users in the group to create item in this UCM type." -COM_TJUCM_PERMISSION_TYPE_ITEM_VIEW="View All Items" -COM_TJUCM_PERMISSION_TYPE_ITEM_VIEW_DESC="Allows users in the group to view items created by any user in this UCM type." -COM_TJUCM_PERMISSION_TYPE_ITEM_EDIT="Edit All Items" -COM_TJUCM_PERMISSION_TYPE_ITEM_EDIT_DESC="Allows users in the group to edit items created by any user in this UCM type." -COM_TJUCM_PERMISSION_TYPE_ITEM_EDITSTATE="Edit All Item State" -COM_TJUCM_PERMISSION_TYPE_ITEM_EDITSTATE_DESC="Allows users in the group to edit state of any item created by any user in this UCM type." -COM_TJUCM_PERMISSION_TYPE_ITEM_EDITOWN="Edit Own Item" -COM_TJUCM_PERMISSION_TYPE_ITEM_EDITOWN_DESC="Allows users in the group to edit own items in this UCM type." -COM_TJUCM_PERMISSION_TYPE_ITEM_DELETE="Delete All Items" -COM_TJUCM_PERMISSION_TYPE_ITEM_DELETE_DESC="Allows users in the group to delete items created by any user in this UCM type." -COM_TJUCM_FORM_LBL_TYPE_IS_SUBFORM="Is Subform" -COM_TJUCM_FORM_DESC_TYPE_IS_SUBFORM="Set whether this UCM type is a subform. If you select YES then you can create a field of this UCM type as a subform field in any other UCM type." -COM_TJUCM_FORM_LBL_TYPE_LAYOUT="Form Layout" -COM_TJUCM_FORM_DESC_TYPE_LAYOUT="Select the layout to be used for this UCM type form view" -COM_TJUCM_DETAILS_LBL_TYPE_LAYOUT="Details Layout" -COM_TJUCM_DETAILS_DESC_TYPE_LAYOUT="Select the layout to be used for this UCM type details view" -COM_TJUCM_LIST_LBL_TYPE_LAYOUT="List Layout" -COM_TJUCM_LIST_DESC_TYPE_LAYOUT="Select the layout to be used for this UCM type list view" -COM_TJUCM_FORM_LBL_TYPE_PUBLISH_ITEMS_BY_DEFAULT="Publish items by default" -COM_TJUCM_FORM_DESC_TYPE_PUBLISH_ITEMS_BY_DEFAULT="Publish items by default" - -; Added in version 1.1 -COM_TJUCM_FIX_DATABASE="Fix Database" - -; Added in version 1.2.0 -COM_TJUCM_PERMISSION_TYPE_ITEM_DELETEOWN="Delete Own Item" -COM_TJUCM_PERMISSION_TYPE_ITEM_DELETEOWN_DESC="Allows users in the group to delete own items in this UCM type." +COM_TJUCM="TJ - UCM" +COM_TJUCM_COMPONENT_LABEL="Tjucm" +COM_TJUCM_CONFIGURATION="Tjucm Configuration" +COM_TJUCM_ACCESS_HEADING="Access" +COM_TJUCM_COMPONENT_DESC="TJ Universal Content Manager test" +COM_TJUCM_N_ITEMS_ARCHIVED="%d items successfully archived" +COM_TJUCM_N_ITEMS_ARCHIVED_1="%d item successfully archived" +COM_TJUCM_N_ITEMS_CHECKED_IN_0="No item successfully checked in" +COM_TJUCM_N_ITEMS_CHECKED_IN_1="%d item successfully checked in" +COM_TJUCM_N_ITEMS_CHECKED_IN_MORE="%d items successfully checked in" +COM_TJUCM_N_ITEMS_DELETED="%d items successfully deleted" +COM_TJUCM_N_ITEMS_DELETED_1="%d item successfully deleted" +COM_TJUCM_N_ITEMS_PUBLISHED="%d items successfully published" +COM_TJUCM_N_ITEMS_PUBLISHED_1="%d item successfully published" +COM_TJUCM_N_ITEMS_TRASHED="%d items successfully trashed" +COM_TJUCM_N_ITEMS_TRASHED_1="%d item successfully trashed" +COM_TJUCM_N_ITEMS_UNPUBLISHED="%d items successfully unpublished" +COM_TJUCM_N_ITEMS_UNPUBLISHED_1="%d item successfully unpublished" +COM_TJUCM_NO_ITEM_SELECTED="No items selected" +COM_TJUCM_SAVE_SUCCESS="Item successfully saved" +COM_TJUCM_ITEM_ID_SELECT_LABEL="Select the item ID" +COM_TJUCM_SELECT_UCM_TYPE_LBL="UCM Type" +COM_TJUCM_SELECT_UCM_TYPE_DESC="Select UCM Type" +COM_TJUCM_FIELDSET_UCM_TYPE_SELECT_LABEL="UCM Config" +COM_TJUCM_FILTER_SELECT_LABEL=" - Select %s - " +COM_TJUCM_TEST_LABEL="Test label" +COM_TJUCM_FIELDSET_RULES="Permissions" +COM_TJUCM_FROM_FILTER="From %s" +COM_TJUCM_TO_FILTER="To %s" +COM_TJUCM_VIEW_FILE="[View File]" +COM_TJUCM_ITEMS_SUCCESS_DUPLICATED="Items successfully duplicated" +COM_TJUCM_SOMETHING_WENT_WRONG="Something went wrong" +COM_TYPE_PAGE_ADD_TYPE="Types: New" +COM_TYPE_PAGE_EDIT_TYPE="Types: Edit" +COM_TJUCM_TYPE_EXPORT="Export" +COM_TJUCM_TYPE_IMPORT="Import" +COM_TJUCM_TYPE_DELETE_CONFIRMATION="All the field groups, fields and the data related to selected UCM type(s) will be deleted. Are you sure that you want to delete the selected UCM type(s)?" +COM_TJUCM_TITLE_TYPES="Types" +COM_TJUCM_TYPES_ID="ID" +COM_TJUCM_TYPES_ORDERING="Order" +COM_TJUCM_TYPES_TITLE="Title" +COM_TJUCM_TYPES_ALIAS="Alias" +COM_TJUCM_TYPES_STATE="State" +COM_TJUCM_TYPES_TYPE_DESCRIPTION="Type Description" +COM_TJUCM_TYPES_UNIQUE_IDENTIFIER="Unique Identifier" +COM_TJUCM_TYPES_PARAMS="Params" +COM_TJUCM_TYPES_CHECKED_OUT="N/A" +COM_TJUCM_TYPES_CHECKED_OUT_TIME="N/A" +COM_TJUCM_TYPES_CREATED_BY="Created by" +COM_TJUCM_TYPES_CREATED_DATE="Created Date" +COM_TJUCM_TYPES_MODIFIED_BY="Modified by" +COM_TJUCM_TYPES_MODIFIED_DATE="Modified Date" +COM_TJUCM_TYPES_IMPORT="Import UCM Types" +COM_TJUCM_TYPES_IMPORT_TYPES_JSON="Import UCM Types" +COM_TJUCM_IMPORT="Import" +COM_TJUCM_TYPE_IMPORT_INVALID_FILE_UPLOAD_ERROR="Uploaded file is invalid" +COM_TJUCM_TYPE_IMPORT_FILE_UPLOAD_ERROR="Unable to upload the file" +COM_TJUCM_TYPE_IMPORT_INVALID_FILE_CONTENT_ERROR="File content is invalid" +COM_TJUCM_TYPE_IMPORT_SUCCESS_MSG="UCM type(s) imported successfully" +COM_TJUCM_DUPLICATE_TYPE_ERROR="UCM type already exists" + +COM_TJLMS_COMPONENT="LMS" +COM_JTICKETING_COMPONENT="Ticketing" +COM_TJUCM_COMPONENT="UCM" +COM_TJUCM_TITLE_TYPES="Types" + +COM_TJUCM_PAGE_ADD_TYPE="Types - New" +COM_TJUCM_PAGE_EDIT_TYPE="Types - Edit" + +COM_TJUCM_TITLE_ITEMS="Items" +COM_TJUCM_ITEMS_ID="ID" +COM_TJUCM_ITEMS_ORDERING="Order" +COM_TJUCM_ITEMS_STATE="State" +COM_TJUCM_ITEMS_CATEGORY_ID="Category Id" +COM_TJUCM_ITEMS_TYPE_ID="Type Id" +COM_TJUCM_ITEMS_CHECKED_OUT="N/A" +COM_TJUCM_ITEMS_CHECKED_OUT_TIME="N/A" +COM_TJUCM_ITEMS_CREATED_BY="Created by" +COM_TJUCM_ITEMS_CREATED_DATE="Created Date" +COM_TJUCM_ITEMS_MODIFIED_BY="Modified by" +COM_TJUCM_ITEMS_MODIFIED_DATE="Modified Date" +COM_TJUCM_TITLE_TYPE="Type" +COM_TJUCM_LEGEND_TYPE="Type" +COM_TJUCM_FORM_LBL_TYPE_ID="ID" +COM_TJUCM_FORM_DESC_TYPE_ID="" +COM_TJUCM_FORM_LBL_TYPE_ORDERING="Order" +COM_TJUCM_FORM_DESC_TYPE_ORDERING="" +COM_TJUCM_FORM_LBL_TYPE_TITLE="Title" +COM_TJUCM_FORM_DESC_TYPE_TITLE="Enter title" +COM_TJUCM_FORM_LBL_TYPE_ALIAS="Alias" +COM_TJUCM_FORM_DESC_TYPE_ALIAS="Enter alias for this UCM type" +COM_TJUCM_FORM_LBL_TYPE_STATE="State" +COM_TJUCM_FORM_DESC_TYPE_STATE="Select the UCM type state" +COM_TJUCM_FORM_LBL_TYPE_ALLOWED_COUNT="Allowed Count" +COM_TJUCM_FORM_DESC_TYPE_ALLOWED_COUNT="Enter how many times one user can add item for this UCM type" +COM_TJUCM_FORM_LBL_TYPE_ALLOW_DRAFT_SAVE="Allow Draft Save" +COM_TJUCM_FORM_DESC_TYPE_ALLOW_DRAFT_SAVE="Set to 'YES' if you want to allow partial submission of item" +COM_TJUCM_FORM_LBL_TYPE_ALLOW_AUTO_SAVE="Allow Auto Save" +COM_TJUCM_FORM_DESC_TYPE_ALLOW_AUTO_SAVE="Set to 'YES' if you want to allow auto save of item" +COM_TJUCM_FORM_LBL_TYPE_TYPE_DESCRIPTION="Description" +COM_TJUCM_FORM_DESC_TYPE_TYPE_DESCRIPTION="Enter description" +COM_TJUCM_FORM_LBL_TYPE_UNIQUE_IDENTIFIER="Unique Identifier" +COM_TJUCM_FORM_DESC_TYPE_UNIQUE_IDENTIFIER="Enter unique identifier for this UCM type" +COM_TJUCM_FORM_LBL_TYPE_PARAMS="Params" +COM_TJUCM_FORM_DESC_TYPE_PARAMS="" +COM_TJUCM_FORM_LBL_TYPE_CHECKED_OUT="N/A" +COM_TJUCM_FORM_DESC_TYPE_CHECKED_OUT="" +COM_TJUCM_FORM_LBL_TYPE_CHECKED_OUT_TIME="N/A" +COM_TJUCM_FORM_DESC_TYPE_CHECKED_OUT_TIME="" +COM_TJUCM_FORM_LBL_TYPE_CREATED_BY="Created by" +COM_TJUCM_FORM_DESC_TYPE_CREATED_BY="" +COM_TJUCM_FORM_LBL_TYPE_CREATED_DATE="Created Date" +COM_TJUCM_FORM_DESC_TYPE_CREATED_DATE="" +COM_TJUCM_FORM_LBL_TYPE_MODIFIED_BY="Modified by" +COM_TJUCM_FORM_DESC_TYPE_MODIFIED_BY="" +COM_TJUCM_FORM_LBL_TYPE_MODIFIED_DATE="Modified Date" +COM_TJUCM_FORM_DESC_TYPE_MODIFIED_DATE="" +COM_TJUCM_TITLE_ITEM="Item" +COM_TJUCM_LEGEND_ITEM="Item" +COM_TJUCM_FORM_LBL_ITEM_ID="ID" +COM_TJUCM_FORM_DESC_ITEM_ID="" +COM_TJUCM_FORM_LBL_ITEM_ORDERING="Order" +COM_TJUCM_FORM_DESC_ITEM_ORDERING="" +COM_TJUCM_FORM_LBL_ITEM_STATE="State" +COM_TJUCM_FORM_DESC_ITEM_STATE="" +COM_TJUCM_FORM_LBL_ITEM_CATEGORY_ID="Category Id" +COM_TJUCM_FORM_DESC_ITEM_CATEGORY_ID="" +COM_TJUCM_FORM_LBL_ITEM_TYPE_ID="Type Id" +COM_TJUCM_FORM_DESC_ITEM_TYPE_ID="" +COM_TJUCM_FORM_LBL_ITEM_CHECKED_OUT="N/A" +COM_TJUCM_FORM_DESC_ITEM_CHECKED_OUT="" +COM_TJUCM_FORM_LBL_ITEM_CHECKED_OUT_TIME="N/A" +COM_TJUCM_FORM_DESC_ITEM_CHECKED_OUT_TIME="" +COM_TJUCM_FORM_LBL_ITEM_CREATED_BY="Created by" +COM_TJUCM_FORM_DESC_ITEM_CREATED_BY="" +COM_TJUCM_FORM_LBL_ITEM_CREATED_DATE="Created Date" +COM_TJUCM_FORM_DESC_ITEM_CREATED_DATE="" +COM_TJUCM_FORM_LBL_ITEM_MODIFIED_BY="Modified by" +COM_TJUCM_FORM_DESC_ITEM_MODIFIED_BY="" +COM_TJUCM_FORM_LBL_ITEM_MODIFIED_DATE="Modified Date" +COM_TJUCM_FORM_DESC_ITEM_MODIFIED_DATE="" +COM_TJUCM_TITLE_LIST_VIEW_ITEMS="Items" +COM_TJUCM_TITLE_LIST_VIEW_ITEMS_DESC="Show list of Items" +COM_TJUCM_TITLE_ITEM_VIEW_ITEM="Single Item" +COM_TJUCM_TITLE_ITEM_VIEW_ITEM_DESC="Show specific Item" +COM_TJUCM_TITLE_FORM_VIEW_ITEM="ItemForm" +COM_TJUCM_TITLE_FORM_VIEW_ITEM_DESC="Show a form to add or edit an Item" +COM_TJUCM_SAVE_WARNING="Alias already existed so a number was added at the end. You can re-edit the article to customise the alias." +COM_TJUCM_TYPES_MANAGER="Manage" +COM_TJUCM_TYPES_CATEGORY_URL="Category" +COM_TJUCM_TYPES_FIELD_GROUP_URL="Field Group" +COM_TJUCM_TYPES_FIELDS_URL="Fields" +COM_TJUCM_TYPES_DATA_URL="Items" +COM_TJUCM_TYPES_ADD_NEW_DATA_URL="Create Item" +COM_TJUCM_NO_FIELDS_TO_SHOW_ON_LIST_VIEW="Please set 'Show on list view' to 'yes' for at least one field of this UCM type" +COM_TJUCM_NO_DATA_FOUND="No Data Found" +COM_TJUCM_TITLE_FIX_DATABASE="Fix Database" +COM_TJUCM_PERMISSION_VIEW="View" +COM_TJUCM_PERMISSION_TYPE_ITEM_CREATE="Create Item" +COM_TJUCM_PERMISSION_TYPE_ITEM_CREATE_DESC="Allows users in the group to create item in this UCM type." +COM_TJUCM_PERMISSION_TYPE_ITEM_VIEW="View All Items" +COM_TJUCM_PERMISSION_TYPE_ITEM_VIEW_DESC="Allows users in the group to view items created by any user in this UCM type." +COM_TJUCM_PERMISSION_TYPE_ITEM_EDIT="Edit All Items" +COM_TJUCM_PERMISSION_TYPE_ITEM_EDIT_DESC="Allows users in the group to edit items created by any user in this UCM type." +COM_TJUCM_PERMISSION_TYPE_ITEM_EDITSTATE="Edit All Item State" +COM_TJUCM_PERMISSION_TYPE_ITEM_EDITSTATE_DESC="Allows users in the group to edit state of any item created by any user in this UCM type." +COM_TJUCM_PERMISSION_TYPE_ITEM_EDITOWN="Edit Own Item" +COM_TJUCM_PERMISSION_TYPE_ITEM_EDITOWN_DESC="Allows users in the group to edit own items in this UCM type." +COM_TJUCM_PERMISSION_TYPE_ITEM_DELETE="Delete All Items" +COM_TJUCM_PERMISSION_TYPE_ITEM_DELETE_DESC="Allows users in the group to delete items created by any user in this UCM type." +COM_TJUCM_PERMISSION_TYPE_ITEM_IMPORT="Import Items" +COM_TJUCM_PERMISSION_TYPE_ITEM_IMPORT_DESC="Allows users in the group to import the items from CSV file.
NOTE:- This will only work if a user has the permission to add item in the UCM type." +COM_TJUCM_FORM_LBL_TYPE_IS_SUBFORM="Is Subform" +COM_TJUCM_FORM_DESC_TYPE_IS_SUBFORM="Set whether this UCM type is a subform. If you select YES then you can create a field of this UCM type as a subform field in any other UCM type." +COM_TJUCM_FORM_LBL_TYPE_LAYOUT="Form Layout" +COM_TJUCM_FORM_DESC_TYPE_LAYOUT="Select the layout to be used for this UCM type form view" +COM_TJUCM_DETAILS_LBL_TYPE_LAYOUT="Details Layout" +COM_TJUCM_DETAILS_DESC_TYPE_LAYOUT="Select the layout to be used for this UCM type details view" +COM_TJUCM_LIST_LBL_TYPE_LAYOUT="List Layout" +COM_TJUCM_LIST_DESC_TYPE_LAYOUT="Select the layout to be used for this UCM type list view" +COM_TJUCM_FORM_LBL_TYPE_PUBLISH_ITEMS_BY_DEFAULT="Publish items by default" +COM_TJUCM_FORM_DESC_TYPE_PUBLISH_ITEMS_BY_DEFAULT="Publish items by default" + +; Added in version 1.1 +COM_TJUCM_FIX_DATABASE="Fix Database" + +; Added in version 1.2.0 +COM_TJUCM_PERMISSION_TYPE_ITEM_DELETEOWN="Delete Own Item" +COM_TJUCM_PERMISSION_TYPE_ITEM_DELETEOWN_DESC="Allows users in the group to delete own items in this UCM type." + +;Added in version 1.2.4 +COM_TJUCM_FORM_LBL_TYPE_ALLOW_BITRATE_ON="Enable timely autosave?" +COM_TJUCM_FORM_DESC_LBL_TYPE_ALLOW_BITRATE_ON="Set to 'YES' if you want to allow submission of item after specified interval of time. Note:If you have used editor field in your UCM type then you should enable this configuration" +COM_TJUCM_FORM_LBL_TYPE_BITRATE_SECONDS="Autosave Interval (seconds)" +COM_TJUCM_FORM_DESC_LBL_TYPE_BITRATE_SECONDS="Enter time in seconds to save data repeatedly for this ucm type" +COM_TJUCM_SEARCH_FILTER_SUBMIT="Search" + +; Added in version 1.2.4 +COM_TJUCM_PERMISSION_TYPE_ITEM_COPYITEM="Copy Item" +COM_TJUCM_PERMISSION_TYPE_ITEM_COPYITEM_DESC="Copy Item from one UCM to another UCM or same UCM type" +COM_TJUCM_COPY_ITEM_SETTING_LABEL="Copy Item" +COM_TJUCM_USE_TJQUEUE_WHILE_COPY_ITEM="Use TjQueue While Copy Item" +COM_TJUCM_USE_TJQUEUE_WHILE_COPY_ITEM_DESC="Set to 'Yes' if you want to use TjQueue while copying items" +COM_TJUCM_YES="Yes" +COM_TJUCM_NO="No" diff --git a/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.sys.ini b/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.sys.ini index 743d4656..7024f544 100644 --- a/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.sys.ini +++ b/src/components/com_tjucm/languages/administrator/en-GB/en-GB.com_tjucm.sys.ini @@ -5,4 +5,7 @@ COM_TJUCM_TITLE_ITEMS="Items" COM_TJUCM_TITLE_FORM_VIEW_ITEM="ItemForm" COM_TJUCM_TITLE_FORM_VIEW_ITEM_DESC="Show a form to add or edit a Item" COM_TJUCM_TITLE_LIST_VIEW_ITEMS="Items" -COM_TJUCM_TITLE_LIST_VIEW_ITEMS_DESC="Show a list of Items" \ No newline at end of file +COM_TJUCM_TITLE_LIST_VIEW_ITEMS_DESC="Show a list of Items" +COM_TJUCM_TITLE_FORM_VIEW_ITEMFORM="One line one input" +COM_TJUCM_DEFAULT_TITLE_IN_OPTION="Two input in a row" +COM_TJUCM_GRID_TITLE_IN_OPTION="One input in a row" \ No newline at end of file diff --git a/src/components/com_tjucm/languages/site/en-GB/en-GB.com_tjucm.ini b/src/components/com_tjucm/languages/site/en-GB/en-GB.com_tjucm.ini index 811f4bea..e51f8b45 100644 --- a/src/components/com_tjucm/languages/site/en-GB/en-GB.com_tjucm.ini +++ b/src/components/com_tjucm/languages/site/en-GB/en-GB.com_tjucm.ini @@ -7,6 +7,7 @@ COM_TJUCM_ITEM_NOT_LOADED="Could not load the item" COM_TJUCM_VIEW_FILE="[View File]" COM_TJUCM_VIEW_RECORD="View" COM_TJUCM_ADD_ITEM="Add" +COM_TJUCM_IMPORT_ITEM="Import Records" COM_TJUCM_EDIT_ITEM="Edit" COM_TJUCM_DELETE_ITEM="Delete" COM_TJUCM_DELETE_MESSAGE="Are you sure that you want delete this item?" @@ -41,7 +42,6 @@ COM_TJUCM_NO_ITEM_SELECTED="No items selected" COM_TJUCM_SAVE_SUCCESS="Item successfully saved" COM_TJUCM_ITEM_ID_SELECT_LABEL="Select the item ID" COM_TJUCM_SELECT_UCM_TYPE_LBL="UCM Type" -COM_TJUCM_SELECT_UCM_TYPE_DESC="Select UCM Type" COM_TJUCM_FIELDSET_UCM_TYPE_SELECT_LABEL="UCM Config" COM_TJUCM_FILTER_SELECT_LABEL=" - Select %s - " COM_TJUCM_TEST_LABEL="Test label" @@ -150,14 +150,16 @@ COM_TJUCM_TYPES_ADD_NEW_DATA_URL="Create Item" COM_TJUCM_NEXT_BUTTON="Next" COM_TJUCM_PREVIOUS_BUTTON="Previous" COM_TJUCM_CANCEL_BUTTON="Cancel" -COM_TJUCM_SAVE_ITEM="Submit Section" -COM_TJUCM_SAVE_AS_DRAFT_ITEM="Save Section Progress" +COM_TJUCM_SAVE_ITEM="Submit" +COM_TJUCM_SAVE_AS_DRAFT_ITEM="Save Progress" COM_TJUCM_NOTE_ON_FORM="Please make sure you have filled all the fields before you submit the form" COM_TJUCM_MSG_ON_SAVED_FORM="Data saved successfully." -COM_TJUCM_MSG_ON_DRAFT_FORM="Section saved as draft successfully" +COM_TJUCM_MSG_ON_DRAFT_FORM="Saved as draft successfully" COM_TJUCM_ALLOWED_COUNT_LIMIT="You are allowed to fill this form upto %d time(s) only" +COM_TJUCM_SUBFORM_NOT_ALLOWED_WITH_OUT_PARENT_ID="You can not save child form's record without parent form's record ID" +COM_TJUCM_INVALID_PARENT_ID="Parent form's record ID (parent_id) is invalid." COM_TJUCM_NO_FIELDS_TO_SHOW_ON_LIST_VIEW="Please set 'Show on list view' to 'yes' for at least one field of this UCM type" -COM_TJUCM_ITEMFORM_SUBMIT_ALERT="Are you sure you want to submit this section?"; +COM_TJUCM_ITEMFORM_SUBMIT_ALERT="Are you sure you want to submit this form?"; COM_TJUCM_NO_ACTIVITIES="There are no activities here yet" COM_TJUCM_SAVE_FAILED="Save failed: %s" COM_TJUCM_DELETE_FAILED="Delete failed: %s" @@ -171,6 +173,9 @@ COM_TJUCM_FILE_DELETE_ERROR="Sorry the file could not be deleted, please try aga COM_TJUCM_FILE_DELETE_CONFIRM="Are you sure you want to delete this file?" COM_TJUCM_MSG_FOR_AUTOSAVE_FEATURE_DISABLED="Your changes will be lost if you don’t save them. Submit the form to update your changes."; COM_TJUCM_NO_FORM_DATA="No data to save"; +COM_TJUCM_FORM_LIST="LIST" +COM_TJUCM_EDIT_FORM="EDIT" + ; Since 1.2.1 COM_TJUCM_FORM_VALIDATATION_FAILED="Provided data is not valid" @@ -179,3 +184,42 @@ COM_TJUCM_FORM_SAVE_FAILED_CLIENT_REQUIRED="Unable to process the request as cli COM_TJUCM_FORM_SAVE_FAILED_RECORD_ID_REQUIRED="Unable to process the request as record id is not provided" COM_TJUCM_FORM_SAVE_FAILED_FIELD_DATA_REQUIRED="Unable to process the request as field data is not provided" COM_TJUCM_FORM_SAVE_FAILED_AUTHORIZATION_ERROR="You are not authorized to perform this operation." + +; Since 1.2.3 +COM_TJUCM_COPY_ITEM="Copy" +COM_TJUCM_COPY_ITEM_TO_OTHER="Copy to Other" +COM_TJUCM_ITEM_COPY_SUCCESSFULLY="Item successfully copied as draft" + +; Since 1.2.2 +COM_TJUCM_SOMETHING_WENT_WRONG="Something went wrong" + +; Since 1.2.3 +COM_TJUCM_DATA_STATUS_DRAFT="Draft" +COM_TJUCM_DATA_STATUS_SAVE="Saved" +COM_TJUCM_DATA_STATUS="Status" +COM_TJUCM_DATA_STATUS_SELECT_OPTION="Select item status" + +; Since 1.2.4 +COM_TJUCM_ITEMS_UPLOAD_CSV_FILE_HELP="Note: To import records using CSV file for this form you should have CSV file in the following format. %s to download sample CSV file" +COM_TJUCM_ITEMS_CSV_FILE_UPLOAD_ERROR="Error in uploading the CSV file" +COM_TJUCM_ITEMS_INVALID_CSV_FILE="Selected file is invalid" +COM_TJUCM_ITEMS_INVALID_CSV_FILE_REQUIRED_COLUMN_MISSING="Some required column(s) are missing in the uploaded CSV file" +COM_TJUCM_ITEMS_UPLOAD_CSV_FILE="Choose CSV File" +COM_TJUCM_CLICK_HERE="Click Here" +COM_TJUCM_ITEMS_IMPORTED_SCUUESSFULLY="%d record(s) imported successfully" +COM_TJUCM_ITEMS_IMPORT_REJECTED_RECORDS="%d invalid record(s) were not imported" +COM_TJUCM_ITEMS_NO_RECORDS_TO_IMPORT="No records found to import" +COM_TJUCM_ITEMS_IMPORTING_MSG="Please wait, Records are being imported..." +COM_TJUCM_LOGIN_MSG="Please login" +COM_TJUCM_SELECT_SOURCE_FORM="Select data source" +COM_TJUCM_PROCESS_DATA="Process" +COM_TJUCM_CANCEL_COPY="Cancel" + +COM_TJUCM_COPY_ITEMS="Copy Items" +COM_TJUCM_COPY_ITEMS_SELECT_UCM_TYPE="Select Copy To" +COM_TJUCM_COPY_ITEMS_BUTTON="Process" +COM_TJUCM_COPY_ITEMS_SELECT_CLUSTER="Select Cluster" +COM_TJUCM_ITEM_COPY_TO_QUEUE_SUCCESSFULLY="Item Successfully saved to queue for copy" + +; Since 1.2.5 +COM_TJUCM_FILTER_SELECT_CATEGORY_LABEL="Select Category" diff --git a/src/components/com_tjucm/media/css/.htaccess b/src/components/com_tjucm/media/css/.htaccess new file mode 100755 index 00000000..79a12fe2 --- /dev/null +++ b/src/components/com_tjucm/media/css/.htaccess @@ -0,0 +1,3 @@ + + Allow from All + \ No newline at end of file diff --git a/src/components/com_tjucm/media/css/index.html b/src/components/com_tjucm/media/css/index.html new file mode 100644 index 00000000..2efb97f3 --- /dev/null +++ b/src/components/com_tjucm/media/css/index.html @@ -0,0 +1 @@ + diff --git a/src/components/com_tjucm/media/css/tjucm.css b/src/components/com_tjucm/media/css/tjucm.css new file mode 100644 index 00000000..325dc8f4 --- /dev/null +++ b/src/components/com_tjucm/media/css/tjucm.css @@ -0,0 +1,33 @@ +/* CSS for frontend*/ +#item-form .radio input{ +margin-left:5px !important; +} + +#item-form .chzn-container{ +width:200px !important; +} + +#item-form .field-calendar input{ + display: inline !important; +} + #item-form textarea{ + height: inherit !important; +} + +#item-form .minicolors-theme-bootstrap .hex { + width: 100px !important; + height: auto; +} + +.tjucm-wrapper .tj-wordwrap{ +word-break: break-word; +} + +#item-form #tjucm_loader{ + height:auto; + position:absolute; + top:45%; + left:45%; + opacity: 0.5; + display:none; +} diff --git a/src/components/com_tjucm/media/gif/.htaccess b/src/components/com_tjucm/media/gif/.htaccess new file mode 100755 index 00000000..79a12fe2 --- /dev/null +++ b/src/components/com_tjucm/media/gif/.htaccess @@ -0,0 +1,3 @@ + + Allow from All + \ No newline at end of file diff --git a/src/components/com_tjucm/media/gif/loading.gif b/src/components/com_tjucm/media/gif/loading.gif new file mode 100644 index 00000000..b8e5a75f Binary files /dev/null and b/src/components/com_tjucm/media/gif/loading.gif differ diff --git a/src/components/com_tjucm/media/js/com_tjucm.min.js b/src/components/com_tjucm/media/js/com_tjucm.min.js new file mode 100755 index 00000000..1c0a5a22 --- /dev/null +++ b/src/components/com_tjucm/media/js/com_tjucm.min.js @@ -0,0 +1 @@ +window.com_tjucm={};var Services=function(){};var UI=function(){};window.com_tjucm.Services=new Services;window.com_tjucm.UI=new UI;Services=undefined;UI=undefined; \ No newline at end of file diff --git a/src/components/com_tjucm/media/js/core/base.js b/src/components/com_tjucm/media/js/core/base.js index dae0116e..bdc362f4 100755 --- a/src/components/com_tjucm/media/js/core/base.js +++ b/src/components/com_tjucm/media/js/core/base.js @@ -44,6 +44,7 @@ com_tjucm.Services.Base = Class.extend({ config.contentType = typeof config.contentType != "undefined" ? config.contentType : 'application/x-www-form-urlencoded; charset=UTF-8'; config.processData = typeof config.processData != "undefined" ? config.processData : true; + config.async = typeof config.async != "undefined" ? config.async : true; return jQuery.ajax({ type: "POST", @@ -51,6 +52,7 @@ com_tjucm.Services.Base = Class.extend({ data: data, contentType: config.contentType, processData: config.processData, + async: config.async, headers: config.headers, beforeSend: function () { }, @@ -94,4 +96,4 @@ com_tjucm.Services.Base = Class.extend({ } }); } -}); \ No newline at end of file +}); diff --git a/src/components/com_tjucm/media/js/core/base.min.js b/src/components/com_tjucm/media/js/core/base.min.js new file mode 100755 index 00000000..70264bff --- /dev/null +++ b/src/components/com_tjucm/media/js/core/base.min.js @@ -0,0 +1 @@ +"use strict";com_tjucm.Services.Base=Class.extend({get:function(e,n,t){if((n=n||{}).headers=n.headers||{},"function"!=typeof t)throw"base expects callback to be function";return jQuery.ajax({type:"GET",url:e,headers:n.headers,beforeSend:function(){},success:function(e){t(null,e)},error:function(e){t(e,null)}})},post:function(e,n,t,c){if(n=n||{},(t=t||{}).headers=t.headers||{},"function"!=typeof c)throw"base expects callback to be function";return t.contentType=void 0!==t.contentType?t.contentType:"application/x-www-form-urlencoded; charset=UTF-8",t.processData=void 0===t.processData||t.processData,t.async=void 0===t.async||t.async,jQuery.ajax({type:"POST",url:e,data:n,contentType:t.contentType,processData:t.processData,async:t.async,headers:t.headers,beforeSend:function(){},success:function(e){c(null,e)},error:function(e){c(e,null)}})},patch:function(e,n,t,c){if(n=n||{},(t=t||{}).headers=t.headers||{},"function"!=typeof c)throw"base expects callback to be function";return"object"==typeof n&&(n=JSON.stringify(n)),jQuery.ajax({type:"PATCH",url:e,data:n,headers:t.headers,beforeSend:function(){},success:function(e){c(null,e)},error:function(e){c(e,null)}})}}); diff --git a/src/components/com_tjucm/media/js/core/class.min.js b/src/components/com_tjucm/media/js/core/class.min.js new file mode 100755 index 00000000..331a9a29 --- /dev/null +++ b/src/components/com_tjucm/media/js/core/class.min.js @@ -0,0 +1 @@ +(function(){var initializing=false,fnTest=/xyz/.test(function(){xyz})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(prop){var _super=this.prototype;initializing=true;var prototype=new this;initializing=false;for(var name in prop){prototype[name]=typeof prop[name]=="function"&&typeof _super[name]=="function"&&fnTest.test(prop[name])?function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);this._super=tmp;return ret}}(name,prop[name]):prop[name]}function Class(){if(!initializing&&this.init)this.init.apply(this,arguments)}Class.prototype=prototype;Class.prototype.constructor=Class;Class.extend=arguments.callee;return Class}})(); \ No newline at end of file diff --git a/src/components/com_tjucm/media/js/form.js b/src/components/com_tjucm/media/js/form.js deleted file mode 100644 index b530b0a7..00000000 --- a/src/components/com_tjucm/media/js/form.js +++ /dev/null @@ -1,19 +0,0 @@ -function getScript(url, success) { - var script = document.createElement('script'); - script.src = url; - var head = document.getElementsByTagName('head')[0], - done = false; - // Attach handlers for all browsers - script.onload = script.onreadystatechange = function() { - if (!done && (!this.readyState - || this.readyState == 'loaded' - || this.readyState == 'complete')) { - done = true; - success(); - script.onload = script.onreadystatechange = null; - head.removeChild(script); - } - }; - head.appendChild(script); -} - diff --git a/src/components/com_tjucm/media/js/index.html b/src/components/com_tjucm/media/js/index.html new file mode 100644 index 00000000..2efb97f3 --- /dev/null +++ b/src/components/com_tjucm/media/js/index.html @@ -0,0 +1 @@ + diff --git a/src/components/com_tjucm/media/js/load_js.php b/src/components/com_tjucm/media/js/load_js.php deleted file mode 100755 index b7007e06..00000000 --- a/src/components/com_tjucm/media/js/load_js.php +++ /dev/null @@ -1,23 +0,0 @@ - - * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. - * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL - */ - -// No direct access -defined('_JEXEC') or die('Restricted access'); - -$doc = JFactory::getDocument(); - -// Add Javascript vars in array -$doc->addScriptOptions('tjucm', array()); - -// Load JS files -JHtml::script(JUri::root() . 'media/com_tjucm/js/core/class.js'); -JHtml::script(JUri::root() . 'media/com_tjucm/js/com_tjucm.js'); -JHtml::script(JUri::root() . 'media/com_tjucm/js/core/base.js'); -JHtml::script(Juri::root() . 'media/com_tjucm/js/services/item.js'); diff --git a/src/components/com_tjucm/media/js/services/item.js b/src/components/com_tjucm/media/js/services/item.js index d287e809..5cb2f6c6 100755 --- a/src/components/com_tjucm/media/js/services/item.js +++ b/src/components/com_tjucm/media/js/services/item.js @@ -11,6 +11,7 @@ com_tjucm.Services.Item = new (com_tjucm.Services.Base.extend({ saveFormDataUrl: window.tjSiteRoot + "index.php?option=com_tjucm&format=json&task=itemform.saveFormData", autoSaveFieldDataUrl: window.tjSiteRoot + "index.php?option=com_tjucm&format=json&task=itemform.saveFieldData", getRelatedFieldUpdatedOptionsUrl: window.tjSiteRoot + "index.php?option=com_tjucm&format=json&task=itemform.getRelatedFieldOptions", + getUpdatedRelatedFieldOptions: window.tjSiteRoot + "index.php?option=com_tjucm&format=json&task=itemform.getUpdatedRelatedFieldOptions", config: { headers: {} }, @@ -21,6 +22,7 @@ com_tjucm.Services.Item = new (com_tjucm.Services.Base.extend({ create: function (ucmTypeData, callback){ this.config.processData = false; this.config.contentType = false; + this.config.async = false; this.post(this.createNewRecordUrl, ucmTypeData, this.config, callback); }, saveFieldData: function (ucmFormData, callback) { @@ -31,6 +33,11 @@ com_tjucm.Services.Item = new (com_tjucm.Services.Base.extend({ getUpdatedRelatedFieldsOptions: function (tjUcmItemFormData, callback){ this.post(this.getRelatedFieldUpdatedOptionsUrl, tjUcmItemFormData, this.config, callback); }, + getRelatedFieldOptions: function (tjUcmItemFormData, callback){ + this.config.processData = false; + this.config.contentType = false; + this.post(this.getUpdatedRelatedFieldOptions, tjUcmItemFormData, this.config, callback); + }, saveFormData: function (ucmFormData, callback) { this.config.processData = false; this.config.contentType = false; diff --git a/src/components/com_tjucm/media/js/services/item.min.js b/src/components/com_tjucm/media/js/services/item.min.js new file mode 100755 index 00000000..48391c84 --- /dev/null +++ b/src/components/com_tjucm/media/js/services/item.min.js @@ -0,0 +1 @@ +'use strict';com_tjucm.Services.Item=new(com_tjucm.Services.Base.extend({createNewRecordUrl:window.tjSiteRoot+"index.php?option=com_tjucm&format=json&task=itemform.save",saveFormDataUrl:window.tjSiteRoot+"index.php?option=com_tjucm&format=json&task=itemform.saveFormData",autoSaveFieldDataUrl:window.tjSiteRoot+"index.php?option=com_tjucm&format=json&task=itemform.saveFieldData",getRelatedFieldUpdatedOptionsUrl:window.tjSiteRoot+"index.php?option=com_tjucm&format=json&task=itemform.getRelatedFieldOptions",getUpdatedRelatedFieldOptions:window.tjSiteRoot+"index.php?option=com_tjucm&format=json&task=itemform.getUpdatedRelatedFieldOptions",config:{headers:{}},response:{success:"",message:""},create:function(a,b){this.config.processData=!1,this.config.contentType=!1,this.config.async=!1,this.post(this.createNewRecordUrl,a,this.config,b)},saveFieldData:function(a,b){this.config.processData=!1,this.config.contentType=!1,this.post(this.autoSaveFieldDataUrl,a,this.config,b)},getUpdatedRelatedFieldsOptions:function(a,b){this.post(this.getRelatedFieldUpdatedOptionsUrl,a,this.config,b)},getRelatedFieldOptions:function(a,b){this.config.processData=!1,this.config.contentType=!1,this.post(this.getUpdatedRelatedFieldOptions,a,this.config,b)},saveFormData:function(a,b){this.config.processData=!1,this.config.contentType=!1,this.post(this.saveFormDataUrl,a,this.config,b)}})); diff --git a/src/components/com_tjucm/media/js/services/items.js b/src/components/com_tjucm/media/js/services/items.js new file mode 100755 index 00000000..ac24491b --- /dev/null +++ b/src/components/com_tjucm/media/js/services/items.js @@ -0,0 +1,35 @@ +/* + * @package TJ-UCM + * @author Techjoomla + * @copyright Copyright (c) 2009-2019 TechJoomla. All rights reserved + * @license GNU General Public License version 2, or later + */ +'use strict'; +/** global: com_tjucm */ +com_tjucm.Services.Items = new (com_tjucm.Services.Base.extend({ + checkCompatibilityUrl: window.tjSiteRoot + "index.php?option=com_tjucm&task=type.getCompatibleUcmTypes", + copyItemUrl: window.tjSiteRoot + "index.php?option=com_tjucm&format=json&task=itemform.copyItem", + getClusterFieldUrl: window.tjSiteRoot + "index.php?option=com_tjucm&&task=type.getClusterFieldOptions", + config: { + headers: {} + }, + response: { + "success": "", + "message": "" + }, + chekCompatibility: function (currentUcmType, callback){ + this.config.processData = false; + this.config.contentType = false; + this.post(this.checkCompatibilityUrl, currentUcmType, this.config, callback); + }, + getClusterFieldOptions: function (currentUcmType, callback){ + this.config.processData = false; + this.config.contentType = false; + this.post(this.getClusterFieldUrl, currentUcmType, this.config, callback); + }, + copyItem: function (copyItemData, callback){ + this.config.processData = false; + this.config.contentType = 'application/x-www-form-urlencoded; charset=UTF-8'; + this.post(this.copyItemUrl, copyItemData, this.config, callback); + } +})); diff --git a/src/components/com_tjucm/media/js/services/items.min.js b/src/components/com_tjucm/media/js/services/items.min.js new file mode 100644 index 00000000..378b0d6f --- /dev/null +++ b/src/components/com_tjucm/media/js/services/items.min.js @@ -0,0 +1 @@ +"use strict";com_tjucm.Services.Items=new(com_tjucm.Services.Base.extend({checkCompatibilityUrl:window.tjSiteRoot+"index.php?option=com_tjucm&task=type.getCompatibleUcmTypes",copyItemUrl:window.tjSiteRoot+"index.php?option=com_tjucm&format=json&task=itemform.copyItem",getClusterFieldUrl:window.tjSiteRoot+"index.php?option=com_tjucm&&task=type.getClusterFieldOptions",config:{headers:{}},response:{success:"",message:""},chekCompatibility:function(t,i){this.config.processData=!1,this.config.contentType=!1,this.post(this.checkCompatibilityUrl,t,this.config,i)},getClusterFieldOptions:function(t,i){this.config.processData=!1,this.config.contentType=!1,this.post(this.getClusterFieldUrl,t,this.config,i)},copyItem:function(t,i){this.config.processData=!1,this.config.contentType="application/x-www-form-urlencoded; charset=UTF-8",this.post(this.copyItemUrl,t,this.config,i)}})); diff --git a/src/components/com_tjucm/media/js/ui/item.js b/src/components/com_tjucm/media/js/ui/item.js new file mode 100644 index 00000000..d085dbed --- /dev/null +++ b/src/components/com_tjucm/media/js/ui/item.js @@ -0,0 +1,12 @@ +/* confirmation message before item deletion */ + jQuery(window).ready(function () { + jQuery('.delete-button').click(deleteItem); + }); + + function deleteItem() + { + if (!confirm(Joomla.JText._('COM_TJUCM_DELETE_MESSAGE'))) + { + return false; + } + } diff --git a/src/components/com_tjucm/media/js/ui/item.min.js b/src/components/com_tjucm/media/js/ui/item.min.js new file mode 100644 index 00000000..5db4df2c --- /dev/null +++ b/src/components/com_tjucm/media/js/ui/item.min.js @@ -0,0 +1 @@ +function deleteItem(){if(!confirm(Joomla.JText._("COM_TJUCM_DELETE_MESSAGE")))return!1}jQuery(window).ready(function(){jQuery(".delete-button").click(deleteItem)}); \ No newline at end of file diff --git a/src/components/com_tjucm/administrator/assets/js/itemform.js b/src/components/com_tjucm/media/js/ui/itemform.js similarity index 68% rename from src/components/com_tjucm/administrator/assets/js/itemform.js rename to src/components/com_tjucm/media/js/ui/itemform.js index 7fdae20f..0e7d84c5 100644 --- a/src/components/com_tjucm/administrator/assets/js/itemform.js +++ b/src/components/com_tjucm/media/js/ui/itemform.js @@ -1,6 +1,6 @@ /*Variable to store the updated options of related field*/ var tjucmRelatedFieldUpdatedOptions = ''; -/*Variable to store the data of editor field*/ +/*Variable to store the data of tinyMCE editor field*/ var tjUcmTinyMCEFieldIds = new Array(); /*Variable to store if the next button is clicked*/ var tjUcmClickedOnNext = 0; @@ -10,6 +10,14 @@ var tjUcmClickedOnPrev = 0; var tjUcmCurrentAutoSaveState = 0; /*Variable to store if form is submited for final save*/ var tjUcmFormFinalSave = 0; +/*Variable to store the data of JCE editor field*/ +var tjUcmJCEFieldIds = new Array(); +/*Variable to store if form is saved once using bit rate config*/ +var tjUcmFormSavedByBitRateConfig = 0; +/*Variable to store if save call is from bitrate*/ +var tjUcmSaveFormInDraftWithNoMsg = undefined; +/*Variable to store id of button from which the save is initiated*/ +var tjUcmFormSubmitCallingButtonId = ''; /* This function executes for autosave form */ jQuery(window).load(function() @@ -17,11 +25,23 @@ jQuery(window).load(function() /*Code to get item state*/ var tjUcmCurrentDraftSaveState = Number(jQuery('#itemState').val()); + /*value of bitrate on button*/ + var tjUcmAllowBitrate = jQuery('#item-form #tjucm-bitrate').val(); + + /*value of bitrate seconds on button*/ + var tjUcmBitrateSeconds = jQuery('#item-form #tjucm-bitrate_seconds').val(); + /* If record is submitted and no longet in the draft state then dont allow autosave to work*/ if (tjUcmCurrentDraftSaveState === 1) { var tjUcmAllowAutoSave = jQuery('#item-form #tjucm-autosave').val(); + /*value of bitrate button*/ + var tjUcmAllowBitrate = jQuery('#item-form #tjucm-bitrate').val(); + + /*value of bitrate seconds on button*/ + var tjUcmBitrateSeconds = jQuery('#item-form #tjucm-bitrate_seconds').val(); + /*Check if auto save is enabled for UCM type*/ if (tjUcmAllowAutoSave == 1) { @@ -37,58 +57,121 @@ jQuery(window).load(function() /* To save calendar field value */ jQuery("#item-form .field-calendar input:text").blur(function(){ - if (jQuery('#item-form').hasClass('dirty')) + if (tjUcmCurrentAutoSaveState) { - if (tjUcmCurrentAutoSaveState) - { - tjUcmItemForm.onUcmFormChange(this); - } + tjUcmItemForm.onUcmFormChange(this); } }); - var tjUcmTinyMCE = Joomla.getOptions("plg_editor_tinymce"); - - /* Get the value of editor fields*/ - if (tjUcmTinyMCE != undefined) + /*function to get iframe id of tinyMCE editor*/ + if(jQuery("#item-form .js-editor-tinymce").length > 0) { - jQuery.each(tjUcmTinyMCE.tinyMCE, function(index, value){ - if (jQuery("#item-form #jform_"+index).length) - { - var tjUcmEditorFieldContent = jQuery("#jform_"+index+"_ifr").contents().find('body').html(); - tjUcmTinyMCEFieldIds[index] = tjUcmEditorFieldContent; - } - else if ((jQuery("#item-form #jform_"+index).length == 0) && (index != 'default')) + var tjUcmTinyMCE = Joomla.getOptions("plg_editor_tinymce"); + if (tjUcmTinyMCE != undefined) + { + jQuery.each(tjUcmTinyMCE.tinyMCE, function(index, value) { - var tjUcmSubFormEditorFields = jQuery("textarea[id$='__"+index+"']"); - - if (tjUcmSubFormEditorFields.length) + if (jQuery("#item-form #jform_"+index).length) { - jQuery.each(tjUcmSubFormEditorFields, function(findex, fvalue){ - var tjUcmEditorFieldContentId = jQuery(fvalue).attr('id'); - var tjUcmEditorFieldContent = jQuery("#"+tjUcmEditorFieldContentId+"_ifr").contents().find('body').html(); - var tjucmTempIndex = tjUcmEditorFieldContentId.replace("jform_", ""); - tjUcmTinyMCEFieldIds[tjucmTempIndex] = tjUcmEditorFieldContent; - }); + var tjUcmEditorFieldContent = jQuery("#jform_"+index+"_ifr").contents().find('body').html(); + tjUcmTinyMCEFieldIds[index] = tjUcmEditorFieldContent; } - } - }); + else if ((jQuery("#item-form #jform_"+index).length == 0) && (index != 'default')) + { + var tjUcmSubFormEditorFields = jQuery("textarea[id$='__"+index+"']"); + + if (tjUcmSubFormEditorFields.length) + { + jQuery.each(tjUcmSubFormEditorFields, function(findex, fvalue) + { + var tjUcmEditorFieldContentId = jQuery(fvalue).attr('id'); + var tjUcmEditorFieldContent = jQuery("#"+tjUcmEditorFieldContentId+"_ifr").contents().find('body').html(); + var tjucmTempIndex = tjUcmEditorFieldContentId.replace("jform_", ""); + tjUcmTinyMCEFieldIds[tjucmTempIndex] = tjUcmEditorFieldContent; + }); + } + } + }); + } + } + + /*function to get iframe id of JCE editor*/ + if(jQuery("#item-form .wf-editor-container").length > 0) + { + /*function to get iframe id of JCE editor*/ + setTimeout(function(){ + jQuery("#item-form .mceIframeContainer iframe").each(function (){ + + var iframeId=jQuery(this).attr('id'); + var tjucmIframeIndex = iframeId.replace("jform_", ""); + var tjucmJceIframeIndex = tjucmIframeIndex.replace("_ifr", ""); + var iframeContent=jQuery("#"+iframeId).contents().find('body').html(); + + tjUcmJCEFieldIds[tjucmJceIframeIndex]=iframeContent;});},2000); + } - /* Check after some time if the content of editor is changed and if so then save it in DB*/ - setInterval(function () { - for (var key in tjUcmTinyMCEFieldIds) { - if (tjUcmTinyMCEFieldIds.hasOwnProperty(key)) { - var tjUcmEditorFieldContent = jQuery("#jform_"+key+"_ifr").contents().find('body').html(); + /* Auto save form as per configured bit rate*/ + if (tjUcmAllowAutoSave == 1 && tjUcmAllowBitrate == 1 && tjUcmBitrateSeconds !== undefined) + { + if (jQuery("#item-form #tjUcmSectionDraftSave").length >= 1) + { + setInterval(function(){ + if(jQuery('#item-form').hasClass('dirty') || tjUcmFormSavedByBitRateConfig === 0) + { + /* Once the form is saved using the bit rate config mark the flag*/ + tjUcmFormSavedByBitRateConfig = 1; + + jQuery("#tjUcmSectionDraftSave").click(); + } - if (tjUcmTinyMCEFieldIds[key] != tjUcmEditorFieldContent) + //For saving data of Jce editor. + if("#item-form .wf-editor-container") + { + for (var key in tjUcmJCEFieldIds) { - var tjUcmTempFieldObj = jQuery("#jform_"+key); - tjUcmTempFieldObj.val(tjUcmEditorFieldContent); - tjUcmTinyMCEFieldIds[key] = tjUcmEditorFieldContent; - tjUcmItemForm.onUcmFormChange(tjUcmTempFieldObj); + if (tjUcmJCEFieldIds.hasOwnProperty(key)) + { + var iframeContent = jQuery("#jform_"+key+"_ifr").contents().find('body').html(); + if (tjUcmJCEFieldIds[key] != iframeContent) + { + var tjUcmTempFieldObj1 = jQuery("#jform_"+key); + + if (tjUcmTempFieldObj1.length) + { + tjUcmTempFieldObj1.val(iframeContent); + tjUcmJCEFieldIds[key] = iframeContent; + tjUcmItemForm.onUcmFormChange(tjUcmTempFieldObj1); + } + } + } } } - } - },7000); + + //For saving data of tinyMce editor + if(jQuery("#item-form .js-editor-tinymce").length > 0) + { + for (var key in tjUcmTinyMCEFieldIds) + { + if (tjUcmTinyMCEFieldIds.hasOwnProperty(key)) + { + var tjUcmEditorFieldContent = jQuery("#jform_"+key+"_ifr").contents().find('body').html(); + + if (tjUcmTinyMCEFieldIds[key] != tjUcmEditorFieldContent) + { + var tjUcmTempFieldObj = jQuery("#jform_"+key); + + if (tjUcmTempFieldObj.length) + { + tjUcmTempFieldObj.val(tjUcmEditorFieldContent); + tjUcmTinyMCEFieldIds[key] = tjUcmEditorFieldContent; + tjUcmItemForm.onUcmFormChange(tjUcmTempFieldObj); + } + } + } + } + + } }, tjUcmBitrateSeconds*1000); + } } } } @@ -135,6 +218,19 @@ jQuery(window).load(function() } } + /* If there is any editor field in sub-form then add its reference in variable tjUcmJCEFieldIds*/ + if (jQuery(row).find('.wf-editor-container textarea')) + { + var tjUcmIdOfEditorFieldInSubForm = jQuery(row).find('.wf-editor-container textarea').attr('id'); + + if (tjUcmIdOfEditorFieldInSubForm) + { + var tjUcmSubFormEditorFieldContent = jQuery("#"+tjUcmIdOfEditorFieldInSubForm+"_ifr").contents().find('body').html(); + tjUcmIdOfEditorFieldInSubForm = tjUcmIdOfEditorFieldInSubForm.replace('jform_', ''); + tjUcmTinyMCEFieldIds[tjUcmIdOfEditorFieldInSubForm] = tjUcmSubFormEditorFieldContent; + } + } + /* Update options of related fields*/ jQuery.each(tjucmRelatedFieldUpdatedOptions, function(index, value) { if (value.templateId) @@ -206,7 +302,7 @@ jQuery(window).load(function() tjUcmClickedOnPrev = 0; } - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); } } else @@ -238,7 +334,7 @@ jQuery(window).load(function() tjUcmClickedOnPrev = 0; } - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); } }); }); @@ -367,11 +463,20 @@ var tjUcmItemForm = { /* Save the ucm-subform field data*/ var afterAddFieldValueForUcmSubFormField = function (err, rsp){ - var tjUcmIsMultiSelect = (jQuery(fieldObj).attr('name').slice(-2) == '[]') ? '[]' : ''; + var fieldName = jQuery(fieldObj).attr('name'); + var tjUcmIsMultiSelect = (fieldName.slice(-2) == '[]') ? '[]' : ''; var tjUcmUpdatedSubFormFieldName = 'jform['+jQuery(fieldObj).attr('id').split('__').pop()+']'+tjUcmIsMultiSelect; + + if (jQuery(fieldObj).attr('type') == 'radio') + { + var tjUcmUpdatedSubFormFieldName = 'jform['+jQuery(fieldObj).attr('name').split('][').pop(); + } + jQuery(fieldObj).attr('name', tjUcmUpdatedSubFormFieldName); tjUcmItemForm.saveUcmFormFieldData(tjucmClient, response.data.id, fieldObj); + + jQuery(fieldObj).attr('name', fieldName); } /* Add entry for ucm-subform-field in field_value table for the parent record*/ @@ -394,14 +499,30 @@ var tjUcmItemForm = { } else if (jQuery.isNumeric(tjucmRecordId) && tjucmRecordId != 0) { - var tjUcmIsMultiSelect = (jQuery(fieldObj).attr('name').slice(-2) == '[]') ? '[]' : ''; + var fieldName = jQuery(fieldObj).attr('name'); + var tjUcmIsMultiSelect = (fieldName.slice(-2) == '[]') ? '[]' : ''; var tjUcmUpdatedSubFormFieldName = 'jform['+jQuery(fieldObj).attr('id').split('__').pop()+']'+tjUcmIsMultiSelect; + + if (jQuery(fieldObj).attr('type') == 'radio') + { + var tjUcmUpdatedSubFormFieldName = 'jform['+jQuery(fieldObj).attr('name').split('][').pop(); + } + jQuery(fieldObj).attr('name', tjUcmUpdatedSubFormFieldName); tjUcmItemForm.saveUcmFormFieldData(tjucmClient, tjucmRecordId, fieldObj); + jQuery(fieldObj).attr('name', fieldName); + return true; } + else if (tjucmRecordId == undefined) + { + /* In case of subform onchange save the entire form*/ + tjUcmSaveFormInDraftWithNoMsg = 1; + tjUcmFormSubmitCallingButtonId = 'tjUcmSectionDraftSave'; + jQuery("#tjUcmSectionDraftSave").click(); + } return false; } @@ -434,20 +555,68 @@ var tjUcmItemForm = { tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), 0); } } - else if (jQuery(fieldObj).attr('type') != 'file') + else if(jQuery(fieldObj).hasClass('tjfieldTjList')) + { + /* This condition used for tjlist option actial values updated - This is used for single & multiple values*/ + if (jQuery(fieldObj).val() !='' && jQuery(fieldObj).val() != undefined) + { + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery(fieldObj).val()); + } + else + { + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), ''); + } + + /* Check other options multiple values exist and its not empty */ + if (jQuery('input#'+jQuery(fieldObj).attr('id')).val() !='' && jQuery('input#'+jQuery(fieldObj).attr('id')).val() != undefined) + { + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery('input#'+jQuery(fieldObj).attr('id')).val()); + } + } + else if(jQuery('input#'+jQuery(fieldObj).attr('id')).data('role') == "tagsinput") + { + /* This condition used for tjlist Other option multiple values textbox */ + + if (jQuery('#'+jQuery(fieldObj).attr('id')).val() !='' && jQuery('#'+jQuery(fieldObj).attr('id')).val() != undefined) + { + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery('#'+jQuery(fieldObj).attr('id')).val()); + } + + /* Check other options multiple values exist and its not empty */ + if (jQuery(fieldObj).val() !='' && jQuery(fieldObj).val() != undefined) + { + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery(fieldObj).val()); + } + } + else if (jQuery(fieldObj).attr('type') == 'file') { - tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery(fieldObj).val()); + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery(fieldObj)[0].files[0]); } else { - tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery(fieldObj)[0].files[0]); + if (jQuery(fieldObj).val() == null) + { + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), ''); + } + else + { + tjUcmItemFieldFormData.append(jQuery(fieldObj).attr('name'), jQuery(fieldObj).val()); + } } - com_tjucm.Services.Item.saveFieldData(tjUcmItemFieldFormData, tjUcmItemForm.afterDataSave); + // Call function if field name exist in request data + if (jQuery(fieldObj).attr('name') !='' && jQuery(fieldObj).attr('name') != undefined) + { + com_tjucm.Services.Item.saveFieldData(tjUcmItemFieldFormData, tjUcmItemForm.afterDataSave); + } return true; }, afterDataSave: function (error, response){ + + /* Hide loader when record is saved*/ + jQuery("#item-form #tjucm_loader").hide(); + response = JSON.parse(response); /* Remove the dirty class fromt the form once the field data is saved*/ jQuery('#item-form').removeClass('dirty'); @@ -520,7 +689,7 @@ var tjUcmItemForm = { Joomla.renderMessages({'error':[response.message]}); } - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); } if (response.messages !== null) @@ -531,7 +700,7 @@ var tjUcmItemForm = { Joomla.renderMessages({'error':[value]}); }); - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); } } } @@ -572,23 +741,41 @@ var tjUcmItemForm = { saveUcmFormData: function(){ /* Disable the action buttons before performing the action*/ jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', true); - var tjUcmFormSubmitCallingButtonId = event.target.id; - var tjUcmSaveRecordAsDraft = 1; - if (tjUcmFormSubmitCallingButtonId == 'tjUcmSectionFinalSave') + /* In case of save through bitrate setting event will be undefined*/ + if (event === undefined) { - if(!confirm(Joomla.JText._("COM_TJUCM_ITEMFORM_SUBMIT_ALERT"))) + tjUcmFormSubmitCallingButtonId = 'tjUcmSectionDraftSave'; + tjUcmSaveFormInDraftWithNoMsg = 1; + } + else + { + if (event.target.id == 'tjUcmSectionDraftSave' || event.target.id == 'tjUcmSectionFinalSave') { - jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', false); - - return false; + tjUcmFormSubmitCallingButtonId = event.target.id; + } + else + { + tjUcmFormSubmitCallingButtonId = 'tjUcmSectionDraftSave'; } + } + var tjUcmSaveRecordAsDraft = 1; + + if (tjUcmFormSubmitCallingButtonId == 'tjUcmSectionFinalSave') + { if (document.formvalidator.isValid(document.getElementById('item-form'))) { + if(!confirm(Joomla.JText._("COM_TJUCM_ITEMFORM_SUBMIT_ALERT"))) + { + jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', false); + + return false; + } + /* Clear the error messages first if any before processing the data*/ jQuery("#system-message-container").html(""); - + /* Disable the save button till the record is saved*/ jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', true); } @@ -596,19 +783,28 @@ var tjUcmItemForm = { { tjUcmItemForm.setVisibilityOfNavigationButtons(); jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', false); - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); - + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); + return false; } tjUcmSaveRecordAsDraft = 0; } - /* For AJAX save need to assign values to the editor field containers*/ + /* For AJAX save need to assign values to the editor field containers of tinyMCE editor*/ jQuery("#item-form .toggle-editor a").each(function(index) { this.click(); }); + /* For AJAX save need to assign values to the editor field containers of JCE editor*/ + jQuery("#item-form .wf-editor-toggle").each(function(index) { + this.click(); + }); + + /* Show loader when record is saved*/ + jQuery("#item-form #tjucm_loader").show(); + jQuery("html, body").animate({scrollTop: jQuery("#item-form #tjucm_loader").position().top}, "slow"); + tjUcmItemForm.getUcmParentRecordId(tjUcmSaveRecordAsDraft, function (){ var tjUcmForm = document.getElementById('item-form'); var tjUcmItemFormData = new FormData(tjUcmForm); @@ -634,24 +830,46 @@ var tjUcmItemForm = { tjUcmFormFinalSave = 1; } - jQuery('input[type="checkbox"]').each(function (){ - if (jQuery(this).prop('checked') == true) - { - tjUcmItemFormData.append(jQuery(this).attr('name'), 1); - } - else - { - tjUcmItemFormData.append(jQuery(this).attr('name'), 0); - } + /* Reset the variable*/ + tjUcmFormSubmitCallingButtonId = ''; + + jQuery('#item-form input[type="checkbox"]').each(function (){ + if (jQuery(this).prop('checked') == true) + { + tjUcmItemFormData.append(jQuery(this).attr('name'), 1); + } + else + { + tjUcmItemFormData.append(jQuery(this).attr('name'), 0); + } + }); + + jQuery('#item-form select').each(function (){ + if (jQuery(this).val() == null) + { + tjUcmItemFormData.append(jQuery(this).attr('name'), ''); + } }); + /* Do not show draft save msg if the save is triggered as per bitrate config*/ + if (tjUcmSaveFormInDraftWithNoMsg !== undefined) + { + tjUcmSaveFormInDraftWithNoMsg = undefined; + tjUcmItemFormData.append('showDraftMessage', 0); + } + com_tjucm.Services.Item.saveFormData(tjUcmItemFormData, tjUcmItemForm.afterDataSave); }); - /* Once data is assigned to the textarea toggle the editors*/ + /* Once data is assigned to the textarea toggle the tinyMCE editors*/ jQuery("#item-form .toggle-editor a").each(function(index) { this.click(); }); + + /* Once data is assigned to the textarea toggle the Jce editors*/ + jQuery("#item-form .wf-editor-toggle").each(function(index) { + this.click(); + }); }, saveSectionData: function (tabId){ /* Disable the action buttons before performing the action*/ @@ -704,7 +922,6 @@ var tjUcmItemForm = { /* Disable the save button till the record is saved*/ jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', true); - tjUcmItemForm.getUcmParentRecordId(1, function (){ tjUcmSectionFormData.delete('task'); tjUcmSectionFormData.delete('option'); @@ -724,7 +941,7 @@ var tjUcmItemForm = { } else { - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); return false; } @@ -779,7 +996,7 @@ var tjUcmItemForm = { { jQuery("#next_button").attr('disabled', true); } - + if (jQuery(tjUcmCurrentFormTab).prev('li').length) { jQuery("#previous_button").attr('disabled', false); @@ -789,6 +1006,52 @@ var tjUcmItemForm = { jQuery("#previous_button").attr('disabled', true); } } + }, + getRelatedFieldOptions: function (relatedFieldId, fieldId, clusterId) { + var tjUcmItemFormData = new FormData(); + var FieldsData = {fieldId: fieldId}; + + var tjUcmUpdateRelatedFieldsOptions = function (error, response){ + response = JSON.parse(response); + tjucmRelatedFieldUpdatedOptions = response.data; + + if(tjucmRelatedFieldUpdatedOptions == '') + { + return false; + } + + var selectOption = ''; + var op = ''; + var data = response.data; + + for(var index = 0; index < data.length; ++index) + { + selectOption = ''; + if(FieldsData.SelectedValues !== null && typeof FieldsData.SelectedValues !== 'undefined' && FieldsData.SelectedValues.length > 0) + { + if (FieldsData.SelectedValues.includes(data[index].value)) + { + selectOption = ' selected="selected" '; + } + } + + op="" ; + jQuery('#'+relatedFieldId).append(op); + } + + // Update to chz-done selects*/ + jQuery('#'+relatedFieldId).trigger("liszt:updated"); + }; + + FieldsData.SelectedValues = jQuery('#'+relatedFieldId).val(); + + if (jQuery.trim(fieldId) != '' && fieldId != 'undefined') + { + jQuery('#'+relatedFieldId+', .chzn-results').empty(); + tjUcmItemFormData.append('fieldId', fieldId); + tjUcmItemFormData.append('clusterId', clusterId); + com_tjucm.Services.Item.getRelatedFieldOptions(tjUcmItemFormData, tjUcmUpdateRelatedFieldsOptions); + } } }; @@ -809,23 +1072,23 @@ function steppedFormSave(form_id, status, showDraftSuccessMsg) if ('save' == status) { - if(confirm(Joomla.JText._("COM_TJUCM_ITEMFORM_SUBMIT_ALERT"))) + if (document.formvalidator.isValid('#item-form')) { - /* code to remove the class added by are-you-sure alert box */ - jQuery('#item-form').removeClass('dirty'); - - if (!document.formvalidator.isValid('#item-form')) + if(!confirm(Joomla.JText._("COM_TJUCM_ITEMFORM_SUBMIT_ALERT"))) { jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', false); - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); return false; } + + /* code to remove the class added by are-you-sure alert box */ + jQuery('#item-form').removeClass('dirty'); } else { jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr('disabled', false); - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); return false; } @@ -847,7 +1110,7 @@ function steppedFormSave(form_id, status, showDraftSuccessMsg) Joomla.renderMessages({'error':[value]}); }); - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); } } @@ -855,7 +1118,7 @@ function steppedFormSave(form_id, status, showDraftSuccessMsg) { Joomla.renderMessages({'info':[returnedData.message]}); - jQuery("html, body").animate({scrollTop: jQuery("#item-form").position().top}, "slow"); + jQuery("html, body").animate({scrollTop: jQuery("#system-message-container").position().top}, "slow"); } if (returnedData.data !== null) @@ -963,7 +1226,6 @@ function itemformactions(tab_id, navDirection) jQuery('#tjucm_myTabTabs > .active').next('li').prev('a').trigger('click'); } - var nextTabName = jQuery('ul#' + getTabId).find('li.active').next('li').children('a').attr('href'); var prevTabName = jQuery('ul#' + getTabId).find('li.active').prev('li').children('a').attr('href'); diff --git a/src/components/com_tjucm/media/js/ui/itemform.min.js b/src/components/com_tjucm/media/js/ui/itemform.min.js new file mode 100644 index 00000000..92ba2a21 --- /dev/null +++ b/src/components/com_tjucm/media/js/ui/itemform.min.js @@ -0,0 +1 @@ +var tjucmRelatedFieldUpdatedOptions="",tjUcmTinyMCEFieldIds=[],tjUcmClickedOnNext=0,tjUcmClickedOnPrev=0,tjUcmCurrentAutoSaveState=0,tjUcmFormFinalSave=0,tjUcmJCEFieldIds=[],tjUcmFormSavedByBitRateConfig=0,tjUcmSaveFormInDraftWithNoMsg=void 0,tjUcmFormSubmitCallingButtonId="";jQuery(window).load(function(){var a=+jQuery("#itemState").val(),b=jQuery("#item-form #tjucm-bitrate").val(),c=jQuery("#item-form #tjucm-bitrate_seconds").val();if(1==a){var d=jQuery("#item-form #tjucm-autosave").val(),b=jQuery("#item-form #tjucm-bitrate").val(),c=jQuery("#item-form #tjucm-bitrate_seconds").val();if(1==d){if(tjUcmCurrentAutoSaveState=1,jQuery("#item-form").on("change select",":input",function(){tjUcmCurrentAutoSaveState&&tjUcmItemForm.onUcmFormChange(this)}),jQuery("#item-form .field-calendar input:text").blur(function(){tjUcmCurrentAutoSaveState&&tjUcmItemForm.onUcmFormChange(this)}),0"+c.text+"")}),jQuery(b).find("#"+e).trigger("liszt:updated")}})}),jQuery("#next_button, #previous_button").on("click",function(){if("next_button"==jQuery(this).attr("id")?tjUcmClickedOnNext=1:tjUcmClickedOnPrev=1,!jQuery("#item-form").hasClass("dirty")){var a=jQuery(jQuery("#tjucm_myTabTabs > .active a").attr("href")).find("input, textarea, select, fieldset");tjUcmItemForm.validateSection(a)?(jQuery("#system-message-container").html(""),tjUcmClickedOnNext&&(tjUcmClickedOnNext=0,jQuery("#tjucm_myTabTabs > .active").next("li").find("a").trigger("click"),tjUcmItemForm.setVisibilityOfNavigationButtons()),tjUcmClickedOnPrev&&(tjUcmClickedOnPrev=0,jQuery("#tjucm_myTabTabs > .active").prev("li").find("a").trigger("click"),tjUcmItemForm.setVisibilityOfNavigationButtons())):(tjUcmClickedOnNext=0,tjUcmClickedOnPrev=0),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow")}else if(tjUcmCurrentAutoSaveState){var a=jQuery(jQuery("#tjucm_myTabTabs > .active a").attr("href")).find("input, textarea, select, fieldset");tjUcmItemForm.validateSection(a)?tjUcmItemForm.saveSectionData(jQuery("#tjucm_myTabTabs > .active a").attr("href")):(tjUcmClickedOnNext=0,tjUcmClickedOnPrev=0)}else{var a=jQuery(jQuery("#tjucm_myTabTabs > .active a").attr("href")).find("input, textarea, select, fieldset");tjUcmItemForm.validateSection(a)?(jQuery("#system-message-container").html(""),tjUcmClickedOnNext&&(tjUcmClickedOnNext=0,jQuery("#tjucm_myTabTabs > .active").next("li").find("a").trigger("click"),tjUcmItemForm.setVisibilityOfNavigationButtons()),tjUcmClickedOnPrev&&(tjUcmClickedOnPrev=0,jQuery("#tjucm_myTabTabs > .active").prev("li").find("a").trigger("click"),tjUcmItemForm.setVisibilityOfNavigationButtons())):(tjUcmClickedOnNext=0,tjUcmClickedOnPrev=0),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow")}})});var tjUcmItemForm={getUcmParentRecordId:function(a,b){var c=jQuery("#item-form").find("input[name='jform[client]']").val(),d=new Promise(function(b,d){var e=jQuery("#item-form").find("input[name='jform[id]']").val();if(""==e){var f=new FormData;""!=c&&f.append("client",c),f.append(Joomla.getOptions("csrf.token"),1);var g=function(a,c){if(c=JSON.parse(c),null==a)if(null!==c.data&&jQuery.isNumeric(c.data.id)){jQuery("#item-form").find("input[name='jform[id]']").val(c.data.id);var e=window.location.href.split("#")[0],f=-1===e.indexOf("?")?"?":"&",g="id="+c.data.id;0<=e.indexOf(g)||(e+=f+g),history.pushState(null,null,e),b(c.data.id)}else d(c)};f.append("draft",a),com_tjucm.Services.Item.create(f,g)}else jQuery.isNumeric(e)&&0!=e&&b(e)});d.then(function(a){b(a)}).catch(function(a){return console.log(a),!1})},onUcmFormChange:function(a){jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!0),tjUcmItemForm.getUcmParentRecordId(1,function(b){var c=jQuery("#item-form").find("input[name='jform[client]']").val();tjUcmItemForm.initUcmFormFieldDataSave(a,c,b)})},initUcmFormFieldDataSave:function(a,b,c){jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!0);var d="",e=new FormData;if(e.append(Joomla.getOptions("csrf.token"),1),void 0!==jQuery(a).parent().parent().parent().attr("data-base-name")||void 0!==jQuery(a).parent().parent().parent().parent().attr("data-base-name")){var f=jQuery(a).parent().parent().parent().attr("data-base-name");null==f&&(f=jQuery(a).parent().parent().parent().parent().attr("data-base-name"));var g=jQuery(a).attr("id");d=g.replace(g.split("_").pop(),"contentid");var h="com_tjucm."+d.split("__").pop().replace("_contentid","").replace("com_tjucm_",""),i=jQuery("#"+d).val();if(""==i){var j=function(g,i){if(i=JSON.parse(i),null==g){null!==i.data&&jQuery.isNumeric(i.data.id)&&jQuery("#"+d).val(i.data.id);var j=function(){var b=jQuery(a).attr("name"),c="[]"==b.slice(-2)?"[]":"",d="jform["+jQuery(a).attr("id").split("__").pop()+"]"+c;if("radio"==jQuery(a).attr("type"))var d="jform["+jQuery(a).attr("name").split("][").pop();jQuery(a).attr("name",d),tjUcmItemForm.saveUcmFormFieldData(h,i.data.id,a),jQuery(a).attr("name",b)};return e.append("jform["+f+"]",h),e.append("client",b),e.append("recordid",c),com_tjucm.Services.Item.saveFieldData(e,j),!0}};e.append("parent_id",c),e.append("client",h),e.append("draft",1),com_tjucm.Services.Item.create(e,j)}else{if(jQuery.isNumeric(i)&&0!=i){var k=jQuery(a).attr("name"),l="[]"==k.slice(-2)?"[]":"",m="jform["+jQuery(a).attr("id").split("__").pop()+"]"+l;if("radio"==jQuery(a).attr("type"))var m="jform["+jQuery(a).attr("name").split("][").pop();return jQuery(a).attr("name",m),tjUcmItemForm.saveUcmFormFieldData(h,i,a),jQuery(a).attr("name",k),!0}null==i&&(tjUcmSaveFormInDraftWithNoMsg=1,tjUcmFormSubmitCallingButtonId="tjUcmSectionDraftSave",jQuery("#tjUcmSectionDraftSave").click())}return!1}return tjUcmItemForm.saveUcmFormFieldData(b,c,a),!0},saveUcmFormFieldData:function(a,b,c){jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!0);var d=new FormData;return d.append(Joomla.getOptions("csrf.token"),1),d.append("client",a),d.append("recordid",b),"checkbox"==jQuery(c).attr("type")?!0==jQuery(c).prop("checked")?d.append(jQuery(c).attr("name"),1):d.append(jQuery(c).attr("name"),0):jQuery(c).hasClass("tjfieldTjList")?(""!=jQuery(c).val()&&null!=jQuery(c).val()?d.append(jQuery(c).attr("name"),jQuery(c).val()):d.append(jQuery(c).attr("name"),""),""!=jQuery("input#"+jQuery(c).attr("id")).val()&&null!=jQuery("input#"+jQuery(c).attr("id")).val()&&d.append(jQuery(c).attr("name"),jQuery("input#"+jQuery(c).attr("id")).val())):"tagsinput"==jQuery("input#"+jQuery(c).attr("id")).data("role")?(""!=jQuery("#"+jQuery(c).attr("id")).val()&&null!=jQuery("#"+jQuery(c).attr("id")).val()&&d.append(jQuery(c).attr("name"),jQuery("#"+jQuery(c).attr("id")).val()),""!=jQuery(c).val()&&null!=jQuery(c).val()&&d.append(jQuery(c).attr("name"),jQuery(c).val())):"file"==jQuery(c).attr("type")?d.append(jQuery(c).attr("name"),jQuery(c)[0].files[0]):null==jQuery(c).val()?d.append(jQuery(c).attr("name"),""):d.append(jQuery(c).attr("name"),jQuery(c).val()),""!=jQuery(c).attr("name")&&null!=jQuery(c).attr("name")&&com_tjucm.Services.Item.saveFieldData(d,tjUcmItemForm.afterDataSave),!0},afterDataSave:function(a,b){if(jQuery("#item-form #tjucm_loader").hide(),b=JSON.parse(b),jQuery("#item-form").removeClass("dirty"),null==b)return!1;if(jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!1),null!=b.data&&b.data.childContentIds&&jQuery.each(b.data.childContentIds,function(a,b){jQuery("#"+a).val(b)}),b.data&&tjUcmFormFinalSave&&(jQuery("#tjucm-auto-save-disabled-msg").show(),jQuery("#itemState").val(0),jQuery("#tjUcmSectionDraftSave").remove(),tjUcmCurrentAutoSaveState=0,tjUcmFormFinalSave=0),tjUcmClickedOnNext&&(tjUcmClickedOnNext=0,jQuery("#tjucm_myTabTabs > .active").next("li").find("a").trigger("click")),tjUcmClickedOnPrev&&(tjUcmClickedOnPrev=0,jQuery("#tjucm_myTabTabs > .active").prev("li").find("a").trigger("click")),tjUcmItemForm.setVisibilityOfNavigationButtons(),b.data){var c=jQuery("#item-form").find("input[name='jform[client]']").val(),d=jQuery("#item-form").find("input[name='jform[id]']").val();tjUcmItemForm.updateRelatedFieldsOptions(c,d)}tjUcmItemForm.renderResponseMessages(b)},renderResponseMessages:function(a){null!=a&&(null!==a.message&&(a.data?Joomla.renderMessages({success:[a.message]}):Joomla.renderMessages({error:[a.message]}),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow")),null!==a.messages&&null!==a.messages.error&&(jQuery.each(a.messages.error,function(a,b){Joomla.renderMessages({error:[b]})}),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow")))},updateRelatedFieldsOptions:function(a,b){var c=new FormData,d=function(a,b){return b=JSON.parse(b),tjucmRelatedFieldUpdatedOptions=b.data,""!=tjucmRelatedFieldUpdatedOptions&&void jQuery.each(b.data,function(a,b){jQuery("#"+b.elementId).html(""),jQuery.each(b.options,function(a,c){var d="";"1"==c.selected&&(d=" selected=\"selected\" "),jQuery("#"+b.elementId).append("")}),jQuery("#"+b.elementId).trigger("liszt:updated")})};c.append("client",a),c.append("content_id",b),com_tjucm.Services.Item.getUpdatedRelatedFieldsOptions(c,d)},saveUcmFormData:function(){jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!0),event===void 0?(tjUcmFormSubmitCallingButtonId="tjUcmSectionDraftSave",tjUcmSaveFormInDraftWithNoMsg=1):"tjUcmSectionDraftSave"==event.target.id||"tjUcmSectionFinalSave"==event.target.id?tjUcmFormSubmitCallingButtonId=event.target.id:tjUcmFormSubmitCallingButtonId="tjUcmSectionDraftSave";var a=1;if("tjUcmSectionFinalSave"==tjUcmFormSubmitCallingButtonId){if(document.formvalidator.isValid(document.getElementById("item-form"))){if(!confirm(Joomla.JText._("COM_TJUCM_ITEMFORM_SUBMIT_ALERT")))return jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!1),!1;jQuery("#system-message-container").html(""),jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!0)}else return tjUcmItemForm.setVisibilityOfNavigationButtons(),jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!1),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow"),!1;a=0}jQuery("#item-form .toggle-editor a").each(function(){this.click()}),jQuery("#item-form .wf-editor-toggle").each(function(){this.click()}),jQuery("#item-form #tjucm_loader").show(),jQuery("html, body").animate({scrollTop:jQuery("#item-form #tjucm_loader").position().top},"slow"),tjUcmItemForm.getUcmParentRecordId(a,function(){var a=document.getElementById("item-form"),b=new FormData(a);b.delete("task"),b.delete("option"),b.delete("view"),b.delete("layout");var c=jQuery("#item-form").find("input[name='jform[client]']").val(),d=jQuery("#item-form").find("input[name='jform[id]']").val();b.append(Joomla.getOptions("csrf.token"),1),b.append("client",c),b.append("recordid",d),"tjUcmSectionDraftSave"==tjUcmFormSubmitCallingButtonId&&b.append("draft",1),"tjUcmSectionFinalSave"==tjUcmFormSubmitCallingButtonId&&(tjUcmFormFinalSave=1),tjUcmFormSubmitCallingButtonId="",jQuery("#item-form input[type=\"checkbox\"]").each(function(){!0==jQuery(this).prop("checked")?b.append(jQuery(this).attr("name"),1):b.append(jQuery(this).attr("name"),0)}),jQuery("#item-form select").each(function(){null==jQuery(this).val()&&b.append(jQuery(this).attr("name"),"")}),tjUcmSaveFormInDraftWithNoMsg!==void 0&&(tjUcmSaveFormInDraftWithNoMsg=void 0,b.append("showDraftMessage",0)),com_tjucm.Services.Item.saveFormData(b,tjUcmItemForm.afterDataSave)}),jQuery("#item-form .toggle-editor a").each(function(){this.click()}),jQuery("#item-form .wf-editor-toggle").each(function(){this.click()})},saveSectionData:function(a){jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!0);var b=new FormData,c=jQuery(a).find("input, textarea, select, fieldset");return tjUcmItemForm.validateSection(c)?void(jQuery("#system-message-container").html(""),jQuery("#item-form .toggle-editor a").each(function(){this.click()}),c.length&&c.each(function(){"file"==jQuery(this).attr("type")?null!=jQuery(this)[0].files[0]&&b.append(jQuery(this).attr("name"),jQuery(this)[0].files[0]):"checkbox"==jQuery(this).attr("type")?!0==jQuery(this).prop("checked")?jQuery(this).val(1):jQuery(this).val(0):null!=jQuery(this).val()&&b.append(jQuery(this).attr("name"),jQuery(this).val())}),jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!0),tjUcmItemForm.getUcmParentRecordId(1,function(){b.delete("task"),b.delete("option"),b.delete("view"),b.delete("layout");var c=jQuery("#item-form").find("input[name='jform[client]']").val(),d=jQuery("#item-form").find("input[name='jform[id]']").val();b.append(Joomla.getOptions("csrf.token"),1),b.append("client",c),b.append("recordid",d),b.append("tjUcmFormSection",jQuery("a[href='"+a+"']").html()),com_tjucm.Services.Item.saveFormData(b,tjUcmItemForm.afterDataSave)})):(jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow"),!1)},validateSection:function(a){var b,c,d,e,f,g=!0,h=[];for(e=0,f=a.length;e "+g[h].text+"",jQuery("#"+a).append(f);jQuery("#"+a).trigger("liszt:updated")};e.SelectedValues=jQuery("#"+a).val(),""!=jQuery.trim(b)&&"undefined"!=b&&(jQuery("#"+a+", .chzn-results").empty(),d.append("fieldId",b),d.append("clusterId",c),com_tjucm.Services.Item.getRelatedFieldOptions(d,f))}};function steppedFormSave(a,b,c){window.onbeforeunload=null,jQuery("#item-form .toggle-editor a").each(function(){this.click()});var d=jQuery("#"+a),e=!1;if(jQuery("#form_status").val(b),"save"==b)if(document.formvalidator.isValid("#item-form")){if(!confirm(Joomla.JText._("COM_TJUCM_ITEMFORM_SUBMIT_ALERT")))return jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!1),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow"),!1;jQuery("#item-form").removeClass("dirty")}else return jQuery(".form-actions button[type='button'], .form-actions input[type='button']").attr("disabled",!1),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow"),!1;return d&&jQuery(d).ajaxSubmit({datatype:"JSON",async:!1,success:function(a){var d=JSON.parse(a);if(null!==d.messages&&null!==d.messages.error&&(jQuery.each(d.messages.error,function(a,b){Joomla.renderMessages({error:[b]})}),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow")),null!==d.message&&""!=d.message&&(Joomla.renderMessages({info:[d.message]}),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").position().top},"slow")),null!==d.data){jQuery("#recordId").val(d.data.id),"save"==b?(jQuery("#tjUcmSectionFinalSave").attr("disabled","disabled"),Joomla.renderMessages({success:[Joomla.JText._("COM_TJUCM_MSG_ON_SAVED_FORM")]}),jQuery("html, body").animate({scrollTop:jQuery("#system-message-container").offset().top-40},"slow")):(e=!0,"1"===c&&(jQuery("#draft_msg").show(),setTimeout(function(){jQuery("#draft_msg").hide()},5e3)));var f=window.location.href.split("#")[0],g=-1===f.indexOf("?")?"?":"&",h="id="+d.data.id;jQuery.each(d.data.childContentIds,function(a,b){jQuery("input[name='"+b.elementName+"']").val(b.content_id)}),tjucmRelatedFieldUpdatedOptions=d.data.relatedFieldOptions,jQuery.each(d.data.relatedFieldOptions,function(a,b){jQuery("#"+b.elementId).html(""),jQuery.each(b.options,function(a,c){var d="";"1"==c.selected&&(d=" selected=\"selected\" "),jQuery("#"+b.elementId).append("")}),jQuery("#"+b.elementId).trigger("liszt:updated")}),0<=f.indexOf(h)||(f+=g+h),history.pushState(null,null,f)}jQuery("#tjUcmSectionDraftSave").attr("disabled",!1),jQuery("#tjUcmSectionFinalSave").attr("disabled",!1),jQuery("#item-form .toggle-editor a").each(function(){this.click()})}}),e}function itemformactions(a,b){var c=jQuery("ul#tjucm_myTabTabs").find("li.active a");jQuery(c).next("li")==null?jQuery("#previous_button").attr("disabled",!0):jQuery("#previous_button").attr("disabled",!1),jQuery(c).prev("li")==null?jQuery("#next_button").attr("disabled",!0):jQuery("#next_button").attr("disabled",!1),next?jQuery("#tjucm_myTabTabs > .active").next("li").find("a").trigger("click"):jQuery("#tjucm_myTabTabs > .active").next("li").prev("a").trigger("click");var d=jQuery("ul#"+getTabId).find("li.active").next("li").children("a").attr("href"),e=jQuery("ul#"+getTabId).find("li.active").prev("li").children("a").attr("href");d==null?jQuery("#next_button").attr("disabled",!0):jQuery("#next_button").attr("disabled",!1),e==null?jQuery("#previous_button").attr("disabled",!0):jQuery("#previous_button").attr("disabled",!1),steppedFormSave("item-form","draft",1),"next"==b&&jQuery("#"+getTabId+" > .active").next("li").find("a").trigger("click"),"prev"==b&&jQuery("#"+getTabId+" > .active").prev("li").find("a").trigger("click")} diff --git a/src/components/com_tjucm/media/js/ui/items.js b/src/components/com_tjucm/media/js/ui/items.js new file mode 100644 index 00000000..e852e282 --- /dev/null +++ b/src/components/com_tjucm/media/js/ui/items.js @@ -0,0 +1,71 @@ +jQuery(window).load(function() +{ + var client = jQuery('#client').val(); + + var currentUcmType = new FormData(); + currentUcmType.append('client', client); + var afterCheckCompatibilityOfUcmType = function(error, response){ + response = JSON.parse(response); + + if (response.data) + { + jQuery.each(response.data, function(key, value) { + jQuery('#target_ucm').append(jQuery('').attr('value',value.value).text(value.text)); + jQuery('#target_ucm').trigger('liszt:updated'); + }); + } + else + { + jQuery('.ucmListField').addClass('hide'); + } + }; + + // Code to check ucm type compatibility to copy item + com_tjucm.Services.Items.chekCompatibility(currentUcmType, afterCheckCompatibilityOfUcmType); + + var afterGetClusterField = function(error, response){ + response = JSON.parse(response); + if (response.data != null) + { + jQuery.each(response.data, function(key, value) { + jQuery('#cluster_list').append(jQuery('').attr('value',value.value).text(value.text)); + jQuery('#cluster_list').trigger('liszt:updated'); + }); + } + else + { + jQuery('.clusterListField').addClass('hide'); + } + }; + + // To get the cluster fields options + com_tjucm.Services.Items.getClusterFieldOptions(currentUcmType, afterGetClusterField); +}); + +// Method to Copy items +var tjUcmItems = { + copyItem : function() + { + var afterCopyItem = function(error, response){ + jQuery("#item-form #tjucm_loader").show(); + jQuery("html, body").animate({scrollTop: jQuery("#item-form #tjucm_loader").position().top}, "slow"); + + response = JSON.parse(response); + + sessionStorage.setItem('message', response.message); + if(response.data !== null) + { + sessionStorage.setItem('class', 'alert alert-success'); + } + else + { + sessionStorage.setItem('class', 'alert alert-danger'); + } + } + + var copyItemData = jQuery('#adminForm').serialize(); + + // Code to copy item to ucm type + com_tjucm.Services.Items.copyItem(copyItemData, afterCopyItem); + } +} diff --git a/src/components/com_tjucm/media/js/ui/items.min.js b/src/components/com_tjucm/media/js/ui/items.min.js new file mode 100644 index 00000000..f93d7843 --- /dev/null +++ b/src/components/com_tjucm/media/js/ui/items.min.js @@ -0,0 +1 @@ +jQuery(window).load(function(){var e=jQuery("#client").val(),t=new FormData;t.append("client",e);com_tjucm.Services.Items.chekCompatibility(t,function(e,t){(t=JSON.parse(t)).data?jQuery.each(t.data,function(e,t){jQuery("#target_ucm").append(jQuery("").attr("value",t.value).text(t.text)),jQuery("#target_ucm").trigger("liszt:updated")}):jQuery(".ucmListField").addClass("hide")});com_tjucm.Services.Items.getClusterFieldOptions(t,function(e,t){null!=(t=JSON.parse(t)).data?jQuery.each(t.data,function(e,t){jQuery("#cluster_list").append(jQuery("").attr("value",t.value).text(t.text)),jQuery("#cluster_list").trigger("liszt:updated")}):jQuery(".clusterListField").addClass("hide")})});var tjUcmItems={copyItem:function(){var e=jQuery("#adminForm").serialize();com_tjucm.Services.Items.copyItem(e,function(e,t){jQuery("#item-form #tjucm_loader").show(),jQuery("html, body").animate({scrollTop:jQuery("#item-form #tjucm_loader").position().top},"slow"),t=JSON.parse(t),sessionStorage.setItem("message",t.message),null!==t.data?sessionStorage.setItem("class","alert alert-success"):sessionStorage.setItem("class","alert alert-danger")})}}; diff --git a/src/components/com_tjucm/administrator/assets/js/jquery.are-you-sure.js b/src/components/com_tjucm/media/js/vendor/jquery/jquery.are-you-sure.js similarity index 100% rename from src/components/com_tjucm/administrator/assets/js/jquery.are-you-sure.js rename to src/components/com_tjucm/media/js/vendor/jquery/jquery.are-you-sure.js diff --git a/src/components/com_tjucm/administrator/assets/js/jquery.form.js b/src/components/com_tjucm/media/js/vendor/jquery/jquery.form.js similarity index 100% rename from src/components/com_tjucm/administrator/assets/js/jquery.form.js rename to src/components/com_tjucm/media/js/vendor/jquery/jquery.form.js diff --git a/src/components/com_tjucm/administrator/assets/js/ays-beforeunload-shim.js b/src/components/com_tjucm/media/js/vendor/shim/ays-beforeunload-shim.js similarity index 100% rename from src/components/com_tjucm/administrator/assets/js/ays-beforeunload-shim.js rename to src/components/com_tjucm/media/js/vendor/shim/ays-beforeunload-shim.js diff --git a/src/components/com_tjucm/site/controllers/item.php b/src/components/com_tjucm/site/controllers/item.php index bfca6a61..29b0e21d 100644 --- a/src/components/com_tjucm/site/controllers/item.php +++ b/src/components/com_tjucm/site/controllers/item.php @@ -30,6 +30,34 @@ public function __construct() $this->client = JFactory::getApplication()->input->get('client'); $this->created_by = JFactory::getApplication()->input->get('created_by'); + // If client is empty then get client from menu params + if (empty($this->client)) + { + // Get the active item + $menuitem = $app->getMenu()->getActive(); + + // Get the params + $this->menuparams = $menuitem->params; + + if (!empty($this->menuparams)) + { + $this->ucm_type = $this->menuparams->get('ucm_type'); + + if (!empty($this->ucm_type)) + { + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $this->ucm_type)); + $this->client = $ucmTypeTable->unique_identifier; + } + } + } + + // Get UCM type id from uniquue identifier + JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/models'); + $tjUcmModelType = JModelLegacy::getInstance('Type', 'TjucmModel'); + $this->ucmTypeId = $tjUcmModelType->getTypeId($this->client); + $this->appendUrl = ""; if (!empty($this->created_by)) @@ -42,11 +70,6 @@ public function __construct() $this->appendUrl .= "&client=" . $this->client; } - // Get UCM type id from uniquue identifier - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/models'); - $tjUcmModelType = JModelLegacy::getInstance('Type', 'TjucmModel'); - $this->ucmTypeId = $tjUcmModelType->getTypeId($this->client); - parent::__construct(); } @@ -106,19 +129,18 @@ public function publish() // Initialise variables. $app = JFactory::getApplication(); + $id = $app->input->getInt('id'); $tjUcmFrontendHelper = new TjucmHelpersTjucm; // Checking if the user can remove object - $user = JFactory::getUser(); - $canEdit = $user->authorise('core.type.edititem', 'com_tjucm.type.edititem' . $this->ucmTypeId); - $canChange = $user->authorise('core.type.edititemstate', 'com_tjucm.type.' . $this->ucmTypeId); + $canEdit = TjucmAccess::canEdit($this->ucmTypeId, $id); + $canEditState = TjucmAccess::canEditState($this->ucmTypeId, $id); - if ($canEdit || $canChange) + if ($canEdit || $canEditState) { $model = $this->getModel('Item', 'TjucmModel'); // Get the user data. - $id = $app->input->getInt('id'); $state = $app->input->getInt('state'); // Attempt to save the data. @@ -140,8 +162,12 @@ public function publish() $this->setMessage(JText::_('COM_TJUCM_ITEM_SAVED_SUCCESSFULLY')); // If there isn't any menu item active, redirect to list view - $itemId = $tjUcmFrontendHelper->getItemId('index.php?option=com_tjucm&view=items' . $this->appendUrl); + $itemId = $tjUcmFrontendHelper->getItemId('index.php?option=com_tjucm&view=items' . $this->client); $this->setRedirect(JRoute::_('index.php?option=com_tjucm&view=items' . $this->appendUrl . '&Itemid=' . $itemId, false)); + + // Call trigger on after publish/unpublish the record + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnAfterStateChangeItem', array($id, $state)); } else { @@ -167,17 +193,16 @@ public function remove() // Initialise variables. $app = JFactory::getApplication(); + // Get the user data. + $id = $app->input->getInt('id', 0); + // Checking if the user can remove object - $user = JFactory::getUser(); - $canDelete = $user->authorise('core.type.deleteitem', 'com_tjucm.type.' . $this->ucmTypeId); + $canDelete = TjucmAccess::canDelete($this->ucmTypeId, $id); if ($canDelete) { $model = $this->getModel('Item', 'TjucmModel'); - // Get the user data. - $id = $app->input->getInt('id', 0); - // Attempt to save the data. $return = $model->delete($id); diff --git a/src/components/com_tjucm/site/controllers/itemform.json.php b/src/components/com_tjucm/site/controllers/itemform.json.php index f5f3a285..e523cff3 100644 --- a/src/components/com_tjucm/site/controllers/itemform.json.php +++ b/src/components/com_tjucm/site/controllers/itemform.json.php @@ -16,6 +16,11 @@ use Joomla\CMS\Session\Session; use Joomla\CMS\Router\Route; use Joomla\Registry\Registry; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Plugin\PluginHelper; +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\Response\JsonResponse; +use Joomla\CMS\Component\ComponentHelper; jimport('joomla.filesystem.file'); @@ -63,52 +68,6 @@ public function __construct() parent::__construct(); } - /** - * Method to check if you can add a new record. - * - * Extended classes can override this if necessary. - * - * @param array $data An array of input data. - * - * @return boolean - * - * @since 12.2 - */ - protected function allowAdd($data = array()) - { - $user = Factory::getUser(); - - return $user->authorise('core.type.createitem', 'com_tjucm.type.' . $this->ucmTypeId); - } - - /** - * Method to check if you can edit an existing record. - * - * Extended classes can override this if necessary. - * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key; default is id. - * - * @return boolean - * - * @since 12.2 - */ - protected function allowEdit($data = array(), $key = 'id') - { - $user = Factory::getUser(); - $edit = $user->authorise('core.type.edititem', 'com_tjucm.type.' . $this->ucmTypeId); - $editOwn = $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $this->ucmTypeId); - - if ($edit || $editOwn) - { - return true; - } - else - { - return false; - } - } - /** * Function to save ucm data item * @@ -141,12 +100,6 @@ public function save($key = null, $urlVar = null) $app->close(); } - // Set the state of record as per UCM type config - $typeTable = $model->getTable('type'); - $typeTable->load(array('unique_identifier' => $client)); - $typeParams = new Registry($typeTable->params); - $data['state'] = $typeParams->get('publish_items', 0); - $data['client'] = $client; } @@ -167,10 +120,22 @@ public function save($key = null, $urlVar = null) $app->close(); } + $isNew = (empty($data['id'])) ? 1 : 0; + + // Plugin trigger on before item save + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnBeforeSaveItem', array($data, $isNew)); + if ($model->save($data)) { $result['id'] = $model->getState($model->getName() . '.id'); + // Plugin trigger on after item save + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnafterSaveItem', array($data, $isNew)); + echo new JResponseJson($result, Text::_('COM_TJUCM_ITEM_SAVED_SUCCESSFULLY')); $app->close(); } @@ -246,8 +211,18 @@ public function saveFieldData() $fieldData['client'] = $client; $fieldData['created_by'] = $table->created_by; + // Plugin trigger on before item date save + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnBeforeSaveItemData', array($recordId, $client, $data)); + // If data is valid then save the data into DB - $response = $model->saveExtraFields($fieldData); + $response = $model->saveFieldsData($fieldData); + + // Plugin trigger on after item data save + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnAfterSaveItemData', array($recordId, $client, $data)); echo new JResponseJson($response); $app->close(); @@ -270,15 +245,16 @@ public function saveFormData() { JSession::checkToken() or jexit(Text::_('JINVALID_TOKEN')); - $app = Factory::getApplication(); - $post = $app->input->post; - $recordId = $post->get('recordid', 0, 'INT'); - $client = $post->get('client', '', 'STRING'); - $formData = $post->get('jform', array(), 'ARRAY'); - $filesData = $app->input->files->get('jform', array(), 'ARRAY'); - $formData = array_merge_recursive($formData, $filesData); - $section = $post->get('tjUcmFormSection', '', 'STRING'); - $draft = $post->get('draft', 0, 'INT'); + $app = Factory::getApplication(); + $post = $app->input->post; + $recordId = $post->get('recordid', 0, 'INT'); + $client = $post->get('client', '', 'STRING'); + $formData = $post->get('jform', array(), 'ARRAY'); + $filesData = $app->input->files->get('jform', array(), 'ARRAY'); + $formData = array_merge_recursive($formData, $filesData); + $section = $post->get('tjUcmFormSection', '', 'STRING'); + $showDraftMsg = $post->get('showDraftMessage', 1, 'INT'); + $draft = $post->get('draft', 0, 'INT'); if (empty($formData) || empty($client)) { @@ -292,7 +268,6 @@ public function saveFormData() // Create JForm object for the field $model = $this->getModel('itemform'); $formData['client'] = $client; - $form = $model->getTypeForm($formData); if (!empty($section)) { @@ -308,7 +283,38 @@ public function saveFormData() // Validate field data $data = $model->validate($form, $formData); - if ($data == false) + // Validate UCM subform data - start + $fieldSets = $form->getFieldsets(); + + foreach ($fieldSets as $fieldset) + { + foreach ($form->getFieldset($fieldset->name) as $field) + { + if ($field->type == 'Ucmsubform') + { + $subForm = $field->loadSubForm(); + $subFormFieldName = str_replace('jform[', '', $field->name); + $subFormFieldName = str_replace(']', '', $subFormFieldName); + + if (!empty($formData[$subFormFieldName])) + { + foreach ($formData[$subFormFieldName] as $ucmSubFormData) + { + $ucmSubFormData = $model->validate($subForm, $ucmSubFormData); + + if ($ucmSubFormData === false) + { + $data = false; + } + } + } + } + } + } + + // Validate UCM subform data - end + + if ($data === false) { $errors = $model->getErrors(); $this->processErrors($errors); @@ -326,24 +332,53 @@ public function saveFormData() $formData['client'] = $client; $formData['created_by'] = $table->created_by; + // Plugin trigger on before item date save + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnBeforeSaveItemData', array($recordId, $client, $data)); + // If data is valid then save the data into DB - $response = $model->saveExtraFields($formData); + $response = $model->saveFieldsData($formData); + + // Plugin trigger on before item date save + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnAfterSaveItemData', array($recordId, $client, $data)); + $msg = null; if ($response && empty($section)) { if ($draft) { - $msg = ($response) ? Text::_("COM_TJUCM_ITEM_DRAFT_SAVED_SUCCESSFULLY") : Text::_("COM_TJUCM_FORM_SAVE_FAILED"); + if ($showDraftMsg) + { + $msg = ($response) ? Text::_("COM_TJUCM_ITEM_DRAFT_SAVED_SUCCESSFULLY") : Text::_("COM_TJUCM_FORM_SAVE_FAILED"); + } } else { $msg = ($response) ? Text::_("COM_TJUCM_ITEM_SAVED_SUCCESSFULLY") : Text::_("COM_TJUCM_FORM_SAVE_FAILED"); } - // Disable the draft mode of the item if full f)orm is submitted + // Disable the draft mode of the item if full form is submitted + $table->load($recordId); $table->draft = $draft; + $table->modified_date = Factory::getDate()->toSql(); $table->store(); + + // Perform actions (redirection or trigger call) after final submit + if (!$draft) + { + // TJ-ucm plugin trigger after save + $dispatcher = JEventDispatcher::getInstance(); + PluginHelper::importPlugin("content"); + $dispatcher->trigger('onUcmItemAfterSave', array($table->getProperties(), $data)); + } + } + else + { + $msg = Text::_("COM_TJUCM_FORM_SAVE_FAILED_AUTHORIZATION_ERROR"); } echo new JResponseJson($response, $msg); @@ -455,7 +490,7 @@ private function processErrors($errors) $msg = array(); // Push up to three validation messages out to the user. - for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) + for ($i = 0; $i < count($errors); $i++) { if ($errors[$i] instanceof Exception) { @@ -468,10 +503,17 @@ private function processErrors($errors) } } - $app->enqueueMessage(implode("\n", $msg), 'error'); + $app->enqueueMessage(implode("
", $msg), 'error'); } } + /** + * Method to get updated list of options for related field + * + * @return void + * + * @since 1.2.1 + */ public function getRelatedFieldOptions() { JSession::checkToken() or jexit(Text::_('JINVALID_TOKEN')); @@ -495,4 +537,313 @@ public function getRelatedFieldOptions() echo new JResponseJson($updatedOptionsForRelatedField); $app->close(); } + + /** + * Method to copy item + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + public function copyItem() + { + // Check for request forgeries. + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); + + $app = Factory::getApplication(); + $post = $app->input->post; + + $sourceClient = $app->input->get('client', '', 'string'); + $filter = $app->input->get('filter', '', 'ARRAY'); + $targetClient = $filter['target_ucm']; + + if (!$targetClient) + { + $targetClient = $sourceClient; + } + + $clusterId = $filter['cluster_list']; + + JLoader::import('components.com_tjucm.models.type', JPATH_ADMINISTRATOR); + $typeModel = BaseDatabaseModel::getInstance('Type', 'TjucmModel'); + + if ($sourceClient != $targetClient) + { + // Server side Validation for source and UCM Type + $result = $typeModel->getCompatibleUcmTypes($sourceClient, $targetClient); + } + else + { + $result = true; + } + + if ($result) + { + $copyIds = $app->input->get('cid'); + JLoader::import('components.com_tjfields.helpers.tjfields', JPATH_SITE); + $tjFieldsHelper = new TjfieldsHelper; + + if (count($copyIds)) + { + $model = $this->getModel('itemform'); + $ucmConfigs = ComponentHelper::getParams('com_tjucm'); + $useTjQueue = $ucmConfigs->get('tjqueue_copy_items'); + + if ($useTjQueue) + { + foreach ($copyIds as $cid) + { + $response = $model->queueItemCopy($cid, $sourceClient, $targetClient, Factory::getuser()->id, $clusterId); + + $msg = ($response) ? Text::_("COM_TJUCM_ITEM_COPY_TO_QUEUE_SUCCESSFULLY") : Text::_("COM_TJUCM_FORM_SAVE_FAILED"); + } + } + else + { + $model->setClient($targetClient); + + foreach ($copyIds as $cid) + { + $ucmOldData = array(); + $ucmOldData['clientComponent'] = 'com_tjucm'; + $ucmOldData['content_id'] = $cid; + $ucmOldData['layout'] = 'edit'; + $ucmOldData['client'] = $sourceClient; + $fileFieldArray = array(); + + // Get the field values + $extraFieldsData = $model->loadFormDataExtra($ucmOldData); + + // Code to replace source field name with destination field name + foreach ($extraFieldsData as $fieldKey => $fieldValue) + { + $prefixSourceClient = str_replace(".", "_", $sourceClient); + $fieldName = explode($prefixSourceClient . "_", $fieldKey); + $prefixTargetClient = str_replace(".", "_", $targetClient); + $targetFieldName = $prefixTargetClient . '_' . $fieldName[1]; + $tjFieldsTable = $tjFieldsHelper->getFieldData($targetFieldName); + $fieldId = $tjFieldsTable->id; + $fieldType = $tjFieldsTable->type; + $fielParams = json_decode($tjFieldsTable->params); + $sourceTjFieldsTable = $tjFieldsHelper->getFieldData($fieldKey); + $sourceFieldParams = json_decode($sourceTjFieldsTable->params); + $subFormData = array(); + + if ($tjFieldsTable->type == 'ucmsubform' || $tjFieldsTable->type == 'subform') + { + $params = json_decode($tjFieldsTable->params)->formsource; + $subFormClient = explode('components/com_tjucm/models/forms/', $params); + $subFormClient = explode('form_extra.xml', $subFormClient[1]); + $subFormClient = 'com_tjucm.' . $subFormClient[0]; + + $params = $sourceFieldParams->formsource; + $subFormSourceClient = explode('components/com_tjucm/models/forms/', $params); + $subFormSourceClient = explode('form_extra.xml', $subFormSourceClient[1]); + $subFormSourceClient = 'com_tjucm.' . $subFormSourceClient[0]; + + $subFormData = (array) json_decode($fieldValue); + } + + if ($subFormData) + { + foreach ($subFormData as $keyData => $data) + { + $prefixSourceClient = str_replace(".", "_", $sourceClient); + $fieldName = explode($prefixSourceClient . "_", $keyData); + $prefixTargetClient = str_replace(".", "_", $targetClient); + $subTargetFieldName = $prefixTargetClient . '_' . $fieldName[1]; + $data = (array) $data; + + foreach ((array) $data as $key => $d) + { + $prefixSourceClient = str_replace(".", "_", $subFormSourceClient); + $fieldName = explode($prefixSourceClient . "_", $key); + $prefixTargetClient = str_replace(".", "_", $subFormClient); + $subFieldName = $prefixTargetClient . '_' . $fieldName[1]; + + JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjfields/tables'); + $fieldTable = JTable::getInstance('field', 'TjfieldsTable'); + + $fieldTable->load(array('name' => $key)); + + if ($fieldName[1] == 'contentid') + { + $d = ''; + } + + $temp = array(); + unset($data[$key]); + + if (is_array($d)) + { + // TODO Temprary used switch case need to modify code + switch ($fieldTable->type) + { + case 'multi_select': + foreach ($d as $option) + { + $temp[] = $option->value; + } + + if (!empty($temp)) + { + $data[$subFieldName] = $temp; + } + break; + + case 'tjlist': + case 'related': + foreach ($d as $option) + { + $data[$subFieldName][] = $option; + } + break; + + default: + foreach ($d as $option) + { + $data[$subFieldName] = $option->value; + } + break; + } + } + elseif($fieldTable->type == 'file' || $fieldTable->type == 'image') + { + JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjfields/tables'); + $subDestionationFieldTable = JTable::getInstance('field', 'TjfieldsTable'); + + $subDestionationFieldTable->load(array('name' => $subFieldName)); + + $subformFileData = array(); + $subformFileData['value'] = $d; + $subformFileData['copy'] = true; + $subformFileData['type'] = $fieldTable->type; + $subformFileData['sourceClient'] = $subFormSourceClient; + $subformFileData['sourceFieldUploadPath'] = json_decode($fieldTable->params)->uploadpath; + $subformFileData['destFieldUploadPath'] = json_decode($subDestionationFieldTable->params)->uploadpath; + $subformFileData['user_id'] = Factory::getUser()->id; + $data[$subFieldName] = $subformFileData; + } + elseif ($fieldTable->type == 'cluster') + { + $data[$subFieldName] = $clusterId; + } + else + { + $data[$subFieldName] = $d; + } + } + + unset($subFormData[$keyData]); + $subFormData[$subTargetFieldName] = $data; + } + + unset($extraFieldsData[$fieldKey]); + $extraFieldsData[$targetFieldName] = $subFormData; + } + else + { + unset($extraFieldsData[$fieldKey]); + + if ($fieldType == 'file' || $fieldType == 'image') + { + $fileData = array(); + $fileData['value'] = $fieldValue; + $fileData['copy'] = true; + $fileData['type'] = $fieldType; + $fileData['sourceClient'] = $sourceClient; + $fileData['sourceFieldUploadPath'] = $sourceFieldParams->uploadpath; + $fileData['destFieldUploadPath'] = $fielParams->uploadpath; + $fileData['user_id'] = Factory::getUser()->id; + $extraFieldsData[$targetFieldName] = $fileData; + } + elseif($fieldType == 'cluster') + { + $extraFieldsData[$targetFieldName] = $clusterId; + } + else + { + $extraFieldsData[$targetFieldName] = $fieldValue; + } + } + } + + $ucmData = array(); + $ucmData['id'] = 0; + $ucmData['client'] = $targetClient; + $ucmData['parent_id'] = 0; + $ucmData['state'] = 0; + $ucmData['draft'] = 1; + + if ($clusterId) + { + $ucmData['cluster_id'] = $clusterId; + } + + // Save data into UCM data table + $result = $model->save($ucmData); + $recordId = $model->getState($model->getName() . '.id'); + + if ($recordId) + { + $formData = array(); + $formData['content_id'] = $recordId; + $formData['fieldsvalue'] = $extraFieldsData; + $formData['client'] = $targetClient; + + // If data is valid then save the data into DB + $response = $model->saveExtraFields($formData); + + $msg = ($response) ? Text::_("COM_TJUCM_ITEM_COPY_SUCCESSFULLY") : Text::_("COM_TJUCM_FORM_SAVE_FAILED"); + } + } + } + + echo new JResponseJson($response, $msg); + $app->close(); + } + } + } + + /** + * Method to get Related Field Options for the field. + * + * @return null + * + * @since 1.0.0 + */ + public function getUpdatedRelatedFieldOptions() + { + $app = Factory::getApplication(); + $fieldId = $app->input->get('fieldId', '', 'STRING'); + $clusterId = $app->input->get('clusterId', 0, 'STRING'); + + // Set Cluster ID + if ($clusterId) + { + $app->input->set('cluster_id', $clusterId); + } + + // Check for request forgeries. + if (!Session::checkToken()) + { + echo new JsonResponse(null, Text::_('JINVALID_TOKEN'), true); + $app->close(); + } + + // Get object of TJ-Fields field model + JLoader::import('components.com_tjfields.models.field', JPATH_ADMINISTRATOR); + $tjFieldsModelField = JModelLegacy::getInstance('Field', 'TjfieldsModel'); + $options = $tjFieldsModelField->getRelatedFieldOptions($fieldId); + + $relatedFieldOptions = array(); + + foreach ($options as $option) + { + $relatedFieldOptions[] = HTMLHelper::_('select.option', trim($option['value']), trim($option['text'])); + } + + echo new JsonResponse($relatedFieldOptions); + $app->close(); + } } diff --git a/src/components/com_tjucm/site/controllers/itemform.php b/src/components/com_tjucm/site/controllers/itemform.php index 0517aa72..f0817729 100644 --- a/src/components/com_tjucm/site/controllers/itemform.php +++ b/src/components/com_tjucm/site/controllers/itemform.php @@ -18,8 +18,6 @@ jimport('joomla.filesystem.file'); -require_once JPATH_SITE . "/components/com_tjfields/filterFields.php"; - /** * Item controller class. * @@ -27,9 +25,6 @@ */ class TjucmControllerItemForm extends JControllerForm { - // Use imported Trait in model - use TjfieldsFilterField; - /** * Constructor * @@ -63,7 +58,10 @@ public function __construct() if (!empty($this->ucm_type)) { - $this->client = 'com_tjucm.' . $this->ucm_type; + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $this->ucm_type)); + $this->client = $ucmTypeTable->unique_identifier; } } } @@ -90,66 +88,6 @@ public function __construct() parent::__construct(); } - /** - * Method to add a new record. - * - * @return boolean True if the record can be added, false if not. - * - * @since 12.2 - */ - public function add() - { - $app = Factory::getApplication(); - $context = "$this->option.edit.$this->context"; - - $tjUcmFrontendHelper = new TjucmHelpersTjucm; - - // Access check. - if (!$this->allowAdd()) - { - // Set the internal error and also the redirect error. - $this->setError(Text::_('JLIB_APPLICATION_ERROR_CREATE_RECORD_NOT_PERMITTED')); - $this->setMessage($this->getError(), 'error'); - - $link = 'index.php?option=com_tjucm&view=items' . $this->appendUrl; - $itemId = $tjUcmFrontendHelper->getItemId($link); - - $this->setRedirect(Route::_($link . '&Itemid=' . $itemId . $this->getRedirectToListAppend(), false)); - - return false; - } - - // Clear the record edit information from the session. - $app->setUserState($context . '.data', null); - - $clusterId = $app->input->getInt('cluster_id', 0); - $cluster = ''; - - // Check cluster exist - if ($clusterId) - { - $cluster = '&cluster_id=' . $clusterId; - } - - // Redirect to the edit screen. - $link = 'index.php?option=com_tjucm&view=itemform&client=' . $this->client; - $itemId = $tjUcmFrontendHelper->getItemId($link); - - $this->setRedirect(Route::_($link . '&Itemid=' . $itemId . $cluster . $this->getRedirectToItemAppend(), false)); - - return true; - } - - /** - * Function to apply field data changes - * - * @return void - */ - public function apply() - { - $this->save(); - } - /** * Method to check out an item for editing and redirect to the edit form. * @@ -197,338 +135,6 @@ public function edit($key = null, $urlVar = null) $this->setRedirect(Route::_('index.php?option=com_tjucm&view=itemform' . $recordId . '&Itemid=' . $itemId, false)); } - /** - * Method to save a record. - * - * @param string $key The name of the primary key of the URL variable. - * @param string $urlVar The name of the URL variable if different from the primary key (sometimes required to avoid router collisions). - * - * @return boolean True if successful, false otherwise. - * - * @since 12.2 - */ - public function save($key = null, $urlVar = null) - { - // Check for request forgeries. - Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); - $app = Factory::getApplication(); - $lang = Factory::getLanguage(); - $model = $this->getModel(); - $task = $this->getTask(); - $formStatus = $app->input->get('form_status', '', 'STRING'); - - // Set client value - $model->setClient($this->client); - - $table = $model->getTable(); - - // Get the user data. - $data = $app->input->get('jform', array(), 'array'); - $data['id'] = empty($data['id']) ? 0 : (int) $data['id']; - $all_jform_data = $data; - - // Get file information - $files = $app->input->files->get('jform'); - - // Jform tweak - Get all posted data. - $post = $app->input->post; - - // Populate the row id from the session. - - // $data[$key] = $recordId; - - // The save2copy task needs to be handled slightly differently. - if ($task == 'save2copy') - { - // Check-in the original row. - if ($checkin && $model->checkin($data[$key]) === false) - { - // Check-in failed. Go back to the item and display a notice. - $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError())); - $this->setMessage($this->getError(), 'error'); - - echo new JResponseJson(null); - jexit(); - } - - // Reset the ID, the multilingual associations and then treat the request as for Apply. - $data[$key] = 0; - $data['associations'] = array(); - $task = 'apply'; - } - - // Access check. - if (!$this->allowSave($data, $key)) - { - $this->setError(Text::_('JLIB_APPLICATION_ERROR_SAVE_NOT_PERMITTED')); - $this->setMessage($this->getError(), 'error'); - - echo new JResponseJson(null); - jexit(); - } - - // Validate the posted data. - // Sometimes the form needs some posted data, such as for plugins and modules. - $form = $model->getForm($data, false); - - if (!$form) - { - $app->enqueueMessage($model->getError(), 'error'); - - echo new JResponseJson(null); - jexit(); - } - - // Test whether the data is valid. - $validData = $model->validate($form, $data); - - // Check for validation errors. - if ($validData === false) - { - // Get the validation messages. - $errors = $model->getErrors(); - - // Push up to three validation messages out to the user. - for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) - { - if ($errors[$i] instanceof Exception) - { - $app->enqueueMessage($errors[$i]->getMessage(), 'error'); - } - else - { - $app->enqueueMessage($errors[$i], 'error'); - } - } - - echo new JResponseJson(null); - jexit(); - } - - // Jform tweaking - get data for extra fields jform. - $extra_jform_data = array_diff_key($all_jform_data, $validData); - - // Check if form file is present. - jimport('joomla.filesystem.file'); - /* Explode client 1. Componet name 2.type */ - $client = explode(".", $this->client); - /* End */ - - $filePath = JPATH_ADMINISTRATOR . '/components/com_tjucm/models/forms/' . $client[1] . '_extra.xml'; - - if (JFile::exists($filePath)) - { - // Validate the posted data. - $formExtra = $model->getFormExtra( - array( - "category" => isset($data['category_id']) ? $data['category_id'] : '', - "clientComponent" => 'com_tjucm', - "client" => $this->client, - "view" => $client[1], - "layout" => 'edit', ) - ); - - if (!$formExtra) - { - JError::raiseWarning(500, $model->getError()); - - return false; - } - - if (!empty($formExtra)) - { - // Remove required attribute from fields if data is stored in draft mode - if ($formStatus == 'draft') - { - $validData['draft'] = 1; - $fieldSets = $formExtra->getFieldsets(); - - foreach ($fieldSets as $fieldset) - { - foreach ($formExtra->getFieldset($fieldset->name) as $field) - { - $formExtra->setFieldAttribute($field->fieldname, 'required', false); - $formExtra->setFieldAttribute($field->fieldname, 'validate', ''); - } - } - } - else - { - $validData['draft'] = 0; - } - - // Remove the fields having empty value from both the array before merge - if (is_array($data)) - { - $data = array_filter($data); - } - - if (is_array($files)) - { - $files = array_filter($files); - } - - /* If file field is required then in the validation method return false - * * so that we will mearge $data and $ files array using array_merge function - * * and pass to the validation funcation.*/ - - if (!empty($files)) - { - $extra_jform_data = array_merge_recursive($data, $files); - } - - // Validate the posted extra data. - $extra_jform_data = $model->validateExtra($formExtra, $extra_jform_data); - } - - // Check for errors. - if ($extra_jform_data === false) - { - // Get the validation messages. - $errors = $model->getErrors(); - - // Push up to three validation messages out to the user. - for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) - { - if ($errors[$i] instanceof Exception) - { - $app->enqueueMessage($errors[$i]->getMessage(), 'error'); - } - else - { - $app->enqueueMessage($errors[$i], 'error'); - } - } - - echo new JResponseJson(null); - jexit(); - } - } - - if (!isset($validData['tags'])) - { - $validData['tags'] = null; - } - - $response = ''; - - try - { - $status_title = $app->input->get('form_status'); - $validData['status'] = $status_title; - - if (!empty($files)) - { - $extra_jform_data['tjFieldFileField'] = $files; - } - - // If no data send then dont add any entry in item form table - start - $allow = 0; - - foreach ($extra_jform_data as $extra_data) - { - if ($extra_data != '') - { - $allow = 1; - - break; - } - } - - if (empty($allow)) - { - $app->enqueueMessage(Text::_("COM_TJUCM_NO_FORM_DATA"), 'error'); - - echo new JResponseJson(null); - jexit(); - } - - // Set cluster values to store in core UCM table values - $model->setClusterData($validData, $data); - - // Get sorted dataset of submitted ucmsubform records as per their client - $ucmSubFormDataSet = $model->getFormattedUcmSubFormRecords($validData, $extra_jform_data); - - $isNew = empty($validData['id']) ? 1 : 0; - - // Save parent form record - $recordId = $model->save($validData, $extra_jform_data); - $validData['parent_id'] = $recordId; - - // Save ucmSubForm records - if (!empty($ucmSubFormDataSet)) - { - $subFormContentIds = $model->saveUcmSubFormRecords($validData, $ucmSubFormDataSet); - } - - // Get updated options for related fields - $app->input->set('id', $recordId); - $updatedRelatedFieldsOptions = $model->getUdatedRelatedFieldOptions($recordId); - - if ($recordId === false) - { - echo new JResponseJson(null); - jexit(); - } - - if ($recordId) - { - $validData['id'] = $recordId; - - $dispatcher = JEventDispatcher::getInstance(); - JPluginHelper::importPlugin("system", "jlike_tjucm"); - $dispatcher->trigger('jlike_tjucmOnAfterSave', array($recordId, $validData)); - - // TJ-ucm plugin trigger after save - $dispatcher = JEventDispatcher::getInstance(); - JPluginHelper::importPlugin("content"); - $dispatcher->trigger('onUcmItemAfterSave', array($validData, $extra_jform_data, $isNew)); - - $response = $recordId; - $redirect_url = ''; - $redirect_msg = ''; - } - } - catch (Exception $e) - { - $response = $e; - $redirect_url = ''; - $redirect_msg = $e->getMessage(); - } - - if ($this->isajax) - { - if (!empty($response)) - { - $response = array('id' => $response); - - // Add subform record ids in the response - if (isset($subFormContentIds) && !empty($subFormContentIds)) - { - $response['childContentIds'] = $subFormContentIds; - } - - // Add updated options of related fields in the response - if (!empty($updatedRelatedFieldsOptions)) - { - $response['relatedFieldOptions'] = $updatedRelatedFieldsOptions; - } - } - - echo new JResponseJson($response); - jexit(); - } - else - { - $app->redirect($redirect_url, $redirect_msg); - } - - // Invoke the postSave method to allow for the child class to access the model. - $this->postSaveHook($model, $validData); - - return true; - } - /** * Method to cancel an edit. * @@ -665,58 +271,12 @@ public function redirectToListView($typeId, $allowedCount) Factory::getApplication()->redirect($link, sprintf(Text::_('COM_TJUCM_ALLOWED_COUNT_LIMIT'), $allowedCount), "Warning"); } - /** - * Method to check if you can add a new record. - * - * Extended classes can override this if necessary. - * - * @param array $data An array of input data. - * - * @return boolean - * - * @since 12.2 - */ - protected function allowAdd($data = array()) - { - $user = Factory::getUser(); - - return $user->authorise('core.type.createitem', 'com_tjucm.type.' . $this->ucmTypeId); - } - - /** - * Method to check if you can edit an existing record. - * - * Extended classes can override this if necessary. - * - * @param array $data An array of input data. - * @param string $key The name of the key for the primary key; default is id. - * - * @return boolean - * - * @since 12.2 - */ - protected function allowEdit($data = array(), $key = 'id') - { - $user = Factory::getUser(); - $edit = $user->authorise('core.type.edititem', 'com_tjucm.type.' . $this->ucmTypeId); - $editOwn = $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $this->ucmTypeId); - - if ($edit || $editOwn) - { - return true; - } - else - { - return false; - } - } - /** * Method to check out an item for copying and redirect to the edit form. * * @return void * - * @since __DEPLOY_VERSION__ + * @since 1.2.1 */ public function prepareForCopy() { diff --git a/src/components/com_tjucm/site/controllers/items.php b/src/components/com_tjucm/site/controllers/items.php index 697c3dbe..0eb6fa14 100644 --- a/src/components/com_tjucm/site/controllers/items.php +++ b/src/components/com_tjucm/site/controllers/items.php @@ -11,6 +11,15 @@ // No direct access. defined('_JEXEC') or die; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Session\Session; +use Joomla\CMS\Filesystem\File; +use Joomla\Registry\Registry; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Table\Table; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Factory; + /** * Items list controller class. * @@ -35,4 +44,372 @@ public function &getModel($name = 'Items', $prefix = 'TjucmModel', $config = arr return $model; } + + /** + * Function to import records in specifed UCM type from CSV. + * + * @return null + * + * @since 1.2.4 + */ + public function importCsv() + { + Session::checkToken() or die('Invalid Token'); + + $app = Factory::getApplication(); + $importFile = $app->input->files->get('csv-file-upload'); + + $client = $app->input->get("client", '', 'STRING'); + + if (empty($client)) + { + $app->enqueueMessage(Text::_('COM_TJUCM_SOMETHING_WENT_WRONG'), 'error'); + $app->redirect(Uri::root() . 'index.php?option=com_tjucm&view=items&layout=importitems&tmpl=component'); + } + + // Check if the file is a CSV file + if (!in_array($importFile['type'], array('application/vnd.ms-excel', 'text/plain', 'text/csv', 'text/tsv'))) + { + $app->enqueueMessage(Text::_('COM_TJUCM_ITEMS_INVALID_CSV_FILE'), 'error'); + $app->redirect(Uri::root() . 'index.php?option=com_tjucm&view=items&layout=importitems&tmpl=component&client=' . $client); + } + + // Load required files + JLoader::import('components.com_tjucm.models.itemform', JPATH_SITE); + JLoader::import('components.com_tjfields.models.fields', JPATH_ADMINISTRATOR); + JLoader::import('components.com_tjfields.models.options', JPATH_ADMINISTRATOR); + + $uploadPath = Factory::getConfig()->get('tmp_path') . '/' . File::makeSafe($importFile['name']); + + // Upload the JSON file + if (!File::upload($importFile['tmp_name'], $uploadPath)) + { + $app->enqueueMessage(Text::_('COM_TJUCM_ITEMS_CSV_FILE_UPLOAD_ERROR'), 'error'); + $app->redirect(Uri::root() . 'index.php?option=com_tjucm&view=items&layout=importitems&tmpl=component&client=' . $client); + } + + // Get all fields in the given UCM type + $tjFieldsFieldsModel = BaseDatabaseModel::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); + $tjFieldsFieldsModel->setState("filter.client", $client); + $tjFieldsFieldsModel->setState("filter.state", 1); + $tjFieldsFieldsModel->setState('list.ordering', 'a.ordering'); + $tjFieldsFieldsModel->setState('list.direction', 'asc'); + $fields = $tjFieldsFieldsModel->getItems(); + + // Map the field names as per field labels in the uploaded CSV file + $fieldsArray = array(); + $requiredFieldsName = array(); + $requiredFieldsLabel = array(); + $fieldsName = array_column($fields, 'name'); + $fieldsLabel = array_column($fields, 'label'); + $fieldHeaders = array_combine($fieldsName, $fieldsLabel); + + foreach ($fields as $field) + { + // Get the required fields for the UCM type + if ($field->required == 1) + { + $requiredFieldsName[$field->name] = $field->name; + $requiredFieldsLabel[] = $field->label; + } + + // Add options data the radio and list type fields + if (in_array($field->type, array('radio', 'single_select', 'multi_select', 'tjlist'))) + { + $tjFieldsOptionsModel = BaseDatabaseModel::getInstance('Options', 'TjfieldsModel', array('ignore_request' => true)); + $tjFieldsOptionsModel->setState("filter.field_id", $field->id); + $field->options = $tjFieldsOptionsModel->getItems(); + } + + $fieldsArray[$field->name] = $field; + } + + // Read the CSV file + $file = fopen($uploadPath, 'r'); + $headerRow = true; + $invalidRows = 0; + $validRows = 0; + $errors = array(); + + // Loop through the uploaded file + while (($data = fgetcsv($file)) !== false) + { + if ($headerRow) + { + $headers = $data; + $headerRow = false; + + // Check if all the required fields headers are present in the CSV file to be imported + $isValid = (count(array_intersect($requiredFieldsLabel, $headers)) == count($requiredFieldsLabel)); + + if (!$isValid) + { + $app->enqueueMessage(Text::_('COM_TJUCM_ITEMS_INVALID_CSV_FILE_REQUIRED_COLUMN_MISSING'), 'error'); + $app->redirect(Uri::root() . 'index.php?option=com_tjucm&view=items&layout=importitems&tmpl=component&client=' . $client); + } + } + elseif (count($headers) == count($data)) + { + $itemData = array(); + $parentId = 0; + $categoryId = 0; + + // Prepare item data for item creation + foreach ($data as $key => $value) + { + if ($headers[$key] === 'parent_id') + { + $parentId = $value; + continue; + } + + $fieldName = array_search($headers[$key], $fieldHeaders); + $value = trim($value); + + if ($fieldName !== false && $value != '') + { + if (isset($fieldsArray[$fieldName]->options) && !empty($fieldsArray[$fieldName]->options)) + { + $fieldParams = new Registry($fieldsArray[$fieldName]->params); + $fieldOptions = array_column($fieldsArray[$fieldName]->options, 'options'); + + // If there are multiple values for a field then we need to send those as array + if (strpos($value, '||') !== false && $fieldParams->get('multiple')) + { + $optionValue = array_map('trim', explode("||", $value)); + $multiSelectValues = array(); + $otherOptionsValues = array(); + + foreach ($optionValue as $option) + { + if (in_array($option, $fieldOptions)) + { + $multiSelectValues[] = $option; + } + else + { + if ($fieldParams->get('other')) + { + $otherOptionsValues[] = $option; + } + } + } + + if (!empty($otherOptionsValues)) + { + $multiSelectValues[] = 'tjlistothervalue'; + $multiSelectValues[] = implode(',', $otherOptionsValues); + } + + $itemData[$fieldName] = $multiSelectValues; + } + else + { + if (in_array($value, $fieldOptions)) + { + $itemData[$fieldName] = $value; + } + else + { + if ($fieldParams->get('other')) + { + $itemData[$fieldName] = array('tjlistothervalue', $value); + } + } + } + } + elseif ($fieldsArray[$fieldName]->type == 'cluster') + { + if (JLoader::import('components.com_cluster.tables.clusters', JPATH_ADMINISTRATOR)) + { + $clusterTable = Table::getInstance('Clusters', 'ClusterTable'); + $clusterTable->load(array("name" => $value)); + $itemData[$fieldName] = $clusterTable->id; + } + } + elseif ($fieldsArray[$fieldName]->type == 'itemcategory') + { + if (JLoader::import('components.com_categories.tables.category', JPATH_ADMINISTRATOR)) + { + $categoryTable = Table::getInstance('Category', 'CategoriesTable'); + $categoryTable->load(array('title' => $value, 'extension' => $client, 'published' => 1)); + + if (property_exists($categoryTable, 'id')) + { + $itemData[$fieldName] = $categoryId = $categoryTable->id; + } + } + } + else + { + $itemData[$fieldName] = trim($value); + } + } + } + + // Check if all the required values are present in the row + $isValid = (count(array_intersect_key($itemData, $requiredFieldsName)) == count($requiredFieldsName)); + + if (!$isValid || empty($itemData)) + { + $invalidRows++; + } + else + { + $tjucmItemFormModel = BaseDatabaseModel::getInstance('ItemForm', 'TjucmModel'); + + $fieldsData = array(); + $fieldsData['client'] = $client; + + $form = $tjucmItemFormModel->getTypeForm($fieldsData); + $data = $tjucmItemFormModel->validate($form, $itemData); + + if ($data !== false) + { + // Save the record in UCM + if ($tjucmItemFormModel->save(array('client' => $client, 'parent_id' => $parentId, 'category_id' => $categoryId))) + { + $contentId = (int) $tjucmItemFormModel->getState($tjucmItemFormModel->getName() . '.id'); + + $fieldsData['content_id'] = $contentId; + $fieldsData['fieldsvalue'] = $data; + + if ($tjucmItemFormModel->saveFieldsData($fieldsData)) + { + $validRows++; + + continue; + } + } + } + + $invalidRows++; + + $errors = array_merge($errors, $tjucmItemFormModel->getErrors()); + } + } + else + { + $invalidRows++; + } + } + + if (!empty($errors)) + { + $this->processErrors($errors); + } + + if ($validRows) + { + $app->enqueueMessage(Text::sprintf('COM_TJUCM_ITEMS_IMPORTED_SCUUESSFULLY', $validRows), 'success'); + } + + if ($invalidRows) + { + $app->enqueueMessage(Text::sprintf('COM_TJUCM_ITEMS_IMPORT_REJECTED_RECORDS', $invalidRows), 'warning'); + } + + if (empty($validRows) && empty($invalidRows)) + { + $app->enqueueMessage(Text::_('COM_TJUCM_ITEMS_NO_RECORDS_TO_IMPORT'), 'error'); + } + + $app->redirect(Uri::root() . 'index.php?option=com_tjucm&view=items&layout=importitems&tmpl=component&client=' . $client); + } + + /** + * Function to generate schema of CSV file for importing the records in specifed UCM type. + * + * @return null + * + * @since 1.2.4 + */ + public function getCsvImportFormat() + { + Session::checkToken('get') or die('Invalid Token'); + + $app = Factory::getApplication(); + $client = $app->input->get("client", '', 'STRING'); + + if (empty($client)) + { + $app->enqueueMessage(Text::_('COM_TJUCM_SOMETHING_WENT_WRONG'), 'error'); + $app->redirect(Uri::root() . 'index.php?option=com_tjucm&view=items&layout=importitems&tmpl=component'); + } + + // Get UCM Type data + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = Table::getInstance('Type', 'TjucmTable'); + $ucmTypeTable->load(array("unique_identifier" => $client)); + + // Check if UCM type is subform + $ucmTypeParams = new Registry($ucmTypeTable->params); + $isSubform = $ucmTypeParams->get('is_subform'); + + // Get fields in the given UCM type + JLoader::import('components.com_tjfields.models.fields', JPATH_ADMINISTRATOR); + $tjFieldsFieldsModel = BaseDatabaseModel::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); + $tjFieldsFieldsModel->setState("filter.client", $client); + $tjFieldsFieldsModel->setState("filter.state", 1); + $tjFieldsFieldsModel->setState('list.ordering', 'a.ordering'); + $tjFieldsFieldsModel->setState('list.direction', 'asc'); + $fields = $tjFieldsFieldsModel->getItems(); + $fieldsLabel = array_column($fields, 'label'); + + if ($isSubform) + { + // Add parentid in colunm + array_push($fieldsLabel, 'parent_id'); + } + + // Generate schema CSV file with CSV headers as label of the fields for given UCM type and save it in temp folder + $fileName = preg_replace('/[^A-Za-z0-9\-]/', '', $ucmTypeTable->title) . '.csv'; + $csvFileTmpPath = Factory::getConfig()->get('tmp_path') . '/' . $fileName; + $output = fopen($csvFileTmpPath, 'w'); + fputcsv($output, $fieldsLabel); + fclose($output); + + // Download the CSV file + header("Content-type: text/csv"); + header("Content-disposition: attachment; filename = " . $fileName); + readfile($csvFileTmpPath); + + jexit(); + } + + /** + * Method to procees errors + * + * @param ARRAY $errors ERRORS + * + * @return void + * + * @since 1.0 + */ + private function processErrors($errors) + { + $app = Factory::getApplication(); + + if (!empty($errors)) + { + $code = 500; + $msg = array(); + + // Push up to three validation messages out to the user. + for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) + { + if ($errors[$i] instanceof Exception) + { + $code = $errors[$i]->getCode(); + $msg[] = $errors[$i]->getMessage(); + } + else + { + $msg[] = $errors[$i]; + } + } + + $app->enqueueMessage(implode("
", $msg), 'error'); + } + } } diff --git a/src/components/com_tjucm/site/controllers/type.php b/src/components/com_tjucm/site/controllers/type.php new file mode 100644 index 00000000..8c711cc2 --- /dev/null +++ b/src/components/com_tjucm/site/controllers/type.php @@ -0,0 +1,191 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL + */ + +// No direct access +defined('_JEXEC') or die; + +use Joomla\CMS\Session\Session; +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Table\Table; + +/** + * Type controller class. + * + * @since __DEPLOY_VERSION__ + */ +class TjucmControllerType extends JControllerForm +{ + /** + * Constructor + * + * @throws Exception + */ + public function __construct() + { + $this->view_list = 'types'; + parent::__construct(); + } + + /** + * Method to check the compatibility between ucm types + * + * @return mixed + * + * @since __DEPLOY_VERSION__ + */ + public function getCompatibleUcmTypes() + { + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); + + $app = Factory::getApplication(); + $post = $app->input->post; + $client = $post->get('client', '', 'STRING'); + + if (empty($client)) + { + echo new JResponseJson(null); + $app->close(); + } + + JLoader::import('components.com_tjucm.models.types', JPATH_ADMINISTRATOR); + $typesModel = BaseDatabaseModel::getInstance('Types', 'TjucmModel'); + $typesModel->setState('filter.state', 1); + $ucmTypes = $typesModel->getItems(); + + JLoader::import('components.com_tjucm.models.type', JPATH_ADMINISTRATOR); + $typeModel = BaseDatabaseModel::getInstance('Type', 'TjucmModel'); + + $validUcmType = array(); + $validUcmType[0]['value'] = ""; + $validUcmType[0]['text'] = Text::_('COM_TJUCM_COPY_ITEMS_SELECT_UCM_TYPE'); + + foreach ($ucmTypes as $key => $type) + { + if ($type->unique_identifier != $client) + { + $result = $typeModel->getCompatibleUcmTypes($client, $type->unique_identifier); + + if ($result) + { + $validUcmType[$key + 1]['value'] = $type->unique_identifier; + $validUcmType[$key + 1]['text'] = $type->title; + } + } + } + + if (count($validUcmType) <= 1) + { + $validUcmType = false; + } + + echo new JResponseJson($validUcmType); + $app->close(); + } + + /** + * Method to get Cluster field + * + * @return boolean + * + * @since __DEPLOY_VERSION__ + */ + public function getClusterFieldOptions() + { + // Check for request forgeries. + Session::checkToken() or jexit(Text::_('JINVALID_TOKEN')); + + $app = Factory::getApplication(); + + $lang = Factory::getLanguage(); + $lang->load('com_tjfields', JPATH_SITE); + + $post = $app->input->post; + $client = $post->get('client', '', 'STRING'); + + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $typeTable = Table::getInstance('type', 'TjucmTable'); + $typeTable->load(array('unique_identifier' => $client)); + + if (empty($client)) + { + echo new JResponseJson(null); + $app->close(); + } + + // Show records belonging to users cluster if com_cluster is installed and enabled - start + $clusterExist = ComponentHelper::getComponent('com_cluster', true)->enabled; + + if (empty($clusterExist)) + { + echo new JResponseJson(null); + $app->close(); + } + + JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); + $fieldTable = Table::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); + $fieldTable->load(array('client' => $client, 'type' => 'cluster')); + + if (!$fieldTable->id) + { + echo new JResponseJson(null); + $app->close(); + } + + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + JLoader::import("/components/com_cluster/includes/cluster", JPATH_ADMINISTRATOR); + $clustersModel = ClusterFactory::model('Clusters', array('ignore_request' => true)); + $clusters = $clustersModel->getItems(); + + // Get list of clusters with data in UCM type + $db = Factory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->quoteName('cluster_id')); + $query->from($db->quoteName('#__tj_ucm_data')); + $query->where($db->quoteName('client') . '=' . $db->quote($client)); + $query->group($db->quoteName('cluster_id')); + $db->setQuery($query); + $clustersWithData = $db->loadColumn(); + + $usersClusters = array(); + + $clusterObj = new stdclass; + $clusterObj->text = Text::_("COM_TJFIELDS_OWNERSHIP_CLUSTER"); + $clusterObj->value = ""; + + $usersClusters[] = $clusterObj; + + if (!empty($clusters)) + { + foreach ($clusters as $clusterList) + { + if (RBACL::check(Factory::getUser()->id, 'com_cluster', 'core.viewitem.' . $typeTable->id, $clusterList->id) || RBACL::check(Factory::getUser()->id, 'com_cluster', 'core.viewallitem.' . $typeTable->id)) + { + if (!empty($clusterList->id)) + { + if (in_array($clusterList->id, $clustersWithData)) + { + $clusterObj = new stdclass; + $clusterObj->text = $clusterList->name; + $clusterObj->value = $clusterList->id; + + $usersClusters[] = $clusterObj; + } + } + } + } + } + + echo new JResponseJson($usersClusters); + $app->close(); + } +} diff --git a/src/components/com_tjucm/site/helpers/tjucm.php b/src/components/com_tjucm/site/helpers/tjucm.php index 830226a4..bd958cc6 100644 --- a/src/components/com_tjucm/site/helpers/tjucm.php +++ b/src/components/com_tjucm/site/helpers/tjucm.php @@ -76,6 +76,8 @@ public static function getLanguageConstantForJs() Text::script('COM_TJUCM_FIELDS_VALIDATION_ERROR_DATE', true); Text::script('COM_TJUCM_FIELDS_VALIDATION_ERROR_NUMBER', true); Text::script('COM_TJUCM_MSG_ON_SAVED_FORM', true); + Text::script('COM_TJUCM_ITEMS_INVALID_CSV_FILE', true); + Text::script('JLIB_HTML_PLEASE_MAKE_A_SELECTION_FROM_THE_LIST', true); } /** diff --git a/src/components/com_tjucm/site/includes/access.php b/src/components/com_tjucm/site/includes/access.php new file mode 100644 index 00000000..822c4b94 --- /dev/null +++ b/src/components/com_tjucm/site/includes/access.php @@ -0,0 +1,282 @@ + + * @copyright Copyright (C) 2009 - 2020 Techjoomla. All rights reserved. + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +defined('_JEXEC') or die(); + +use Joomla\CMS\Factory; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Table\Table; +use Joomla\String\StringHelper; + +require_once JPATH_SITE . '/components/com_tjucm/includes/defines.php'; + +/** + * Tjucm factory class. + * + * This class perform the helpful operation required to Tjucm package + * + * @since __DEPLOY_VERSION__ + */ +class TjucmAccess +{ + public static function canCreate($ucmTypeId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + + return RBACL::check($user->id, 'com_cluster', 'core.createitem.' . $ucmTypeId); + } + } + else + { + return $user->authorise('core.type.createitem', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function canImport($ucmTypeId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + + return RBACL::check($user->id, 'com_cluster', 'core.importitem.' . $ucmTypeId) && RBACL::check(JFactory::getUser()->id, 'com_cluster', 'core.createtitem.' . $ucmTypeId); + } + } + else + { + return $user->authorise('core.type.importitem', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function canView($ucmTypeId, $contentId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); + $itemTable = JTable::getInstance('Item', 'TjucmTable', array('dbo', JFactory::getDbo())); + $itemTable->load($contentId); + + if ($user->id == $itemTable->created_by) + { + return true; + } + + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + if (RBACL::check($user->id, 'com_cluster', 'core.viewallitem.' . $ucmTypeId)) + { + return true; + } + + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + return RBACL::check($user->id, 'com_cluster', 'core.viewitem.' . $ucmTypeId, $itemTable->cluster_id); + } + } + else + { + return $user->authorise('core.type.viewitem', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function canEdit($ucmTypeId, $contentId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + + if (RBACL::check($user->id, 'com_cluster', 'core.editallitem.' . $ucmTypeId)) + { + return true; + } + + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); + $itemTable = JTable::getInstance('Item', 'TjucmTable', array('dbo', JFactory::getDbo())); + $itemTable->load($contentId); + + return RBACL::check($user->id, 'com_cluster', 'core.edititem.' . $ucmTypeId, $itemTable->cluster_id); + } + } + else + { + return $user->authorise('core.type.edititem', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function canEditState($ucmTypeId, $contentId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + JLoader::import("components.com_subusers.includes.rbacl", JPATH_ADMINISTRATOR); + + if (RBACL::check($user->id, 'com_cluster', 'core.editallitemstate.' . $ucmTypeId)) + { + return true; + } + + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); + $itemTable = JTable::getInstance('Item', 'TjucmTable', array('dbo', JFactory::getDbo())); + $itemTable->load($contentId); + + return RBACL::check($user->id, 'com_cluster', 'core.edititemstate.' . $ucmTypeId, $itemTable->cluster_id); + } + } + else + { + return $user->authorise('core.type.edititemstate', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function canEditOwn($ucmTypeId, $contentId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); + $itemTable = JTable::getInstance('Item', 'TjucmTable', array('dbo', JFactory::getDbo())); + $itemTable->load($contentId); + + return RBACL::check($user->id, 'com_cluster', 'core.editownitem.' . $ucmTypeId, $itemTable->cluster_id); + } + } + else + { + return $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function canDelete($ucmTypeId, $contentId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + + if (RBACL::check($user->id, 'com_cluster', 'core.deleteallitem.' . $ucmTypeId)) + { + return true; + } + + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); + $itemTable = JTable::getInstance('Item', 'TjucmTable', array('dbo', JFactory::getDbo())); + $itemTable->load($contentId); + + return RBACL::check($user->id, 'com_cluster', 'core.deleteitem.' . $ucmTypeId, $itemTable->cluster_id); + } + } + else + { + return $user->authorise('core.type.deleteitem', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function canDeleteOwn($ucmTypeId, $contentId, $userId = 0) + { + $user = empty($userId) ? Factory::getUser() : Factory::getUser($userId); + + if (TjucmAccess::hasCluster($ucmTypeId)) + { + // Get com_subusers component status + $subUserExist = ComponentHelper::getComponent('com_subusers', true)->enabled; + + // Check user have permission to edit record of assigned cluster + if ($subUserExist) + { + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); + $itemTable = JTable::getInstance('Item', 'TjucmTable', array('dbo', JFactory::getDbo())); + $itemTable->load($contentId); + + return RBACL::check($user->id, 'com_cluster', 'core.deleteownitem.' . $ucmTypeId, $itemTable->cluster_id); + } + } + else + { + return $user->authorise('core.type.deleteownitem', 'com_tjucm.type.' . $ucmTypeId); + } + } + + public static function hasCluster($ucmTypeId) + { + if (ComponentHelper::getComponent('com_cluster', true)->enabled) + { + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $typeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $typeTable->load($ucmTypeId); + + JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); + $fieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', JFactory::getDbo())); + $fieldTable->load(array('client' => $typeTable->unique_identifier, 'type' => 'cluster', 'state' => 1)); + + if ($fieldTable->id) + { + return true; + } + } + + return false; + } +} diff --git a/src/components/com_tjucm/site/includes/defines.php b/src/components/com_tjucm/site/includes/defines.php new file mode 100644 index 00000000..e6485254 --- /dev/null +++ b/src/components/com_tjucm/site/includes/defines.php @@ -0,0 +1,23 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +if (defined('COM_TJUCM_SITE_DEFINE_FILE')) +{ + return; +} + +define('COM_TJUCM_ITEM_STATE_PUBLISHED', 1); +define('COM_TJUCM_ITEM_STATE_UNPUBLISHED', 0); +define('COM_TJUCM_ITEM_STATE_ARCHIVED', 2); +define('COM_TJUCM_ITEM_STATE_TRASHED', -2); +define('COM_TJUCM_ITEM_STATE_DRAFT', -1); + +// Need this constant for performance purpose Always define this at the end of file +define('COM_TJUCM_SITE_DEFINE_FILE', true); diff --git a/src/components/com_tjucm/site/includes/item.php b/src/components/com_tjucm/site/includes/item.php new file mode 100644 index 00000000..806d9fcf --- /dev/null +++ b/src/components/com_tjucm/site/includes/item.php @@ -0,0 +1,316 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +defined('_JEXEC') or die(); + +use Joomla\CMS\Object\CMSObject; + +/** + * Tjucm item class. + * + * @since __DEPLOY_VERSION__ + */ +class TjucmItem extends CMSObject +{ + /** + * The auto incremental primary key of the item + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $id = 0; + + /** + * In case of UCM-Subform parent_id is used to point to the parent record of the UCM-Subform records + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $parent_id = 0; + + /** + * Id of assets table for the item + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $asset_id = 0; + + /** + * Defines ordering of the item - Not Used As Of Now + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $ordering = 0; + + /** + * State of item + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $state = COM_TJUCM_ITEM_STATE_UNPUBLISHED; + + /** + * Category of the item - Category from the categories created for UCM type + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $category_id = ''; + + /** + * Id of UCM type to which the item belongs + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $type_id = 0; + + /** + * Unique identifier of the UCM type + * + * @var string + * @since __DEPLOY_VERSION__ + */ + public $client = ''; + + /** + * Cluster id to which the item belongs + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $cluster_id = ''; + + /** + * Joomla user id by whom the record is being checked out + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $checked_out = ''; + + /** + * Joomla user id by whom the record is created + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $created_by = ''; + + /** + * Joomla user id by whom the record is modified + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $modified_by = ''; + + /** + * Flag to mark if the item is a draft + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + public $draft = ''; + + /** + * Date time when the item was last checked out + * + * @var datetime + * @since __DEPLOY_VERSION__ + */ + public $checked_out_time = ''; + + /** + * Date time when the item was created + * + * @var datetime + * @since __DEPLOY_VERSION__ + */ + public $created_date = ''; + + /** + * Date time when the item was last modified + * + * @var datetime + * @since __DEPLOY_VERSION__ + */ + public $modified_date = ''; + + /** + * holds the already loaded instances of the Item + * + * @var array + * @since __DEPLOY_VERSION__ + */ + protected static $itemObj = array(); + + /** + * Holds the fields values in the item + * + * @var array + * @since __DEPLOY_VERSION__ + */ + private $fieldsValues = array(); + + /** + * Constructor activating the default information of the item + * + * @param int $id The unique item key to load. + * + * @since __DEPLOY_VERSION__ + */ + public function __construct($id = 0) + { + if (!empty($id)) + { + $this->load($id); + } + } + + /** + * Returns the item object + * + * @param integer $id The primary key of the item to load (optional). + * + * @return TjucmItem The item object. + * + * @since __DEPLOY_VERSION__ + */ + public static function getInstance($id = 0) + { + if (!$id) + { + return new TjucmItem; + } + + if (empty(self::$itemObj[$id])) + { + self::$itemObj[$id] = new TjucmItem($id); + } + + return self::$itemObj[$id]; + } + + /** + * Method to load a item properties + * + * @param int $id The item id + * + * @return boolean True on success + * + * @since __DEPLOY_VERSION__ + */ + public function load($id) + { + $table = Tjucm::table("item"); + + if ($table->load($id)) + { + $this->setProperties($table->getProperties()); + + // Load field values for the item + // $this->setFieldsValues($table->id); + + return true; + } + + return false; + } + + /** + * Method to save the Item object to the database + * + * @return boolean True on success + * + * @since __DEPLOY_VERSION__ + */ + public function save() + { + $isNew = $this->isNew(); + + // Create the item table object + $table = Tjucm::table('item'); + + // Allow an exception to be thrown. + try + { + $table->bind(get_object_vars($this)); + + // Check and store the object. + if (!$table->check()) + { + $this->setError($table->getError()); + + return false; + } + + // Store the item data in the database + $result = $table->store(); + + // Set the id for the item object in case we created a new item. + if ($result && $isNew) + { + $this->load($table->get('id')); + $item = Tjucm::model('item'); + $this->item_id = $item->generateItemID($this->id); + + return $this->save(); + } + elseif ($result && !$isNew) + { + return $this->load($this->id); + } + } + catch (\Exception $e) + { + $this->setError($e->getMessage()); + + return false; + } + + return $result; + } + + /** + * Method to check is item new or not + * + * @return boolean True on success + * + * @since __DEPLOY_VERSION__ + */ + private function isNew() + { + return $this->id < 1; + } + + /** + * Returns a property of the object or the default value if the property is not set. + * + * @param string $property The name of the property. + * @param mixed $default The default value. + * + * @return mixed The value of the property. + * + * @since __DEPLOY_VERSION__ + */ + public function get($property, $default = null) + { + if (isset($this->$property)) + { + return $this->$property; + } + + return $default; + } +} diff --git a/src/components/com_tjucm/site/includes/tjucm.php b/src/components/com_tjucm/site/includes/tjucm.php new file mode 100644 index 00000000..0671cbfb --- /dev/null +++ b/src/components/com_tjucm/site/includes/tjucm.php @@ -0,0 +1,215 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +defined('_JEXEC') or die(); + +use Joomla\CMS\Factory; +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Table\Table; +use Joomla\String\StringHelper; + +require_once JPATH_SITE . '/components/com_tjucm/includes/defines.php'; + +/** + * Tjucm factory class. + * + * This class perform the helpful operation required to Tjucm package + * + * @since __DEPLOY_VERSION__ + */ +class TJUCM +{ + /** + * Holds the record of the loaded Tjucm classes + * + * @var array + * @since __DEPLOY_VERSION__ + */ + private static $loadedClass = array(); + + /** + * Holds the record of the component config + * + * @var Joomla\Registry\Registry + * @since __DEPLOY_VERSION__ + */ + private static $config = null; + + /** + * Retrieves a table from the table folder + * + * @param string $name The table file name + * @param array $config Configuration array for model. Optional. + * + * @return Table|boolean object or false on failure + * + * @since __DEPLOY_VERSION__ + **/ + public static function table($name, $config = array()) + { + Table::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/tables'); + $table = Table::getInstance($name, 'TjucmTable', $config); + + return $table; + } + + /** + * Retrieves a model from the model folder + * + * @param string $name The model name + * @param array $config Configuration array for model. Optional. + * + * @return BaseDatabaseModel|boolean object or false on failure + * + * @since __DEPLOY_VERSION__ + **/ + public static function model($name, $config = array()) + { + JLoader::import('components.com_tjucm.models.type', JPATH_ADMINISTRATOR); + JLoader::import('components.com_tjucm.models.types', JPATH_ADMINISTRATOR); + BaseDatabaseModel::addIncludePath(JPATH_SITE . '/components/com_tjucm/models', 'TjucmModel'); + $model = BaseDatabaseModel::getInstance($name, 'TjucmModel', $config); + + return $model; + } + + /** + * Magic method to create instance of Tjucm library + * + * @param string $name The name of the class + * @param mixed $arguments Arguments of class + * + * @return mixed return the Object of the respective class if exist OW return false + * + * @since __DEPLOY_VERSION__ + **/ + public static function __callStatic($name, $arguments) + { + self::loadClass($name); + + $className = 'Tjucm' . StringHelper::ucfirst($name); + + if (class_exists($className)) + { + if (method_exists($className, 'getInstance')) + { + return call_user_func_array(array($className, 'getInstance'), $arguments); + } + + return new $className; + } + + return false; + } + + /** + * Load the class library if not loaded + * + * @param string $className The name of the class which required to load + * + * @return boolean True on success + * + * @since __DEPLOY_VERSION__ + **/ + public static function loadClass($className) + { + if (! isset(self::$loadedClass[$className])) + { + $className = (string) StringHelper::strtolower($className); + + $path = JPATH_SITE . '/components/com_tjucm/includes/' . $className . '.php'; + + include_once $path; + + self::$loadedClass[$className] = true; + } + + return self::$loadedClass[$className]; + } + + /** + * Load the component configuration + * + * @return Joomla\Registry\Registry A Registry object. + */ + public static function config() + { + if (empty(self::$config)) + { + self::$config = ComponentHelper::getParams('com_tjucm'); + } + + return self::$config; + } + + /** + * Initializes the css, js and necessary dependencies + * + * @param string $location The location where the assets needs to load + * + * @return void + * + * @since __DEPLOY_VERSION__ + */ + public static function init($location = 'site') + { + static $loaded = null; + $docType = Factory::getDocument()->getType(); + $versionClass = self::Version(); + + if (! $loaded[$location] && ($docType == 'html')) + { + if (file_exists(JPATH_ROOT . '/media/techjoomla_strapper/tjstrapper.php')) + { + JLoader::register('TjStrapper', JPATH_ROOT . '/media/techjoomla_strapper/tjstrapper.php'); + TjStrapper::loadTjAssets(); + } + + $version = '2.0'; + $input = Factory::getApplication()->input; + $view = $input->get('view', '', 'STRING'); + + try + { + $version = $versionClass->getMediaVersion(); + } + catch (Exception $e) + { + // Silence is peace :) + } + + $options = array("version" => $version); + + if ($view == 'itemform' || $view == 'items') + { + HTMLHelper::script('media/com_tjucm/js/com_tjucm.min.js', $options); + HTMLHelper::script('media/com_tjucm/js/core/class.min.js', $options); + HTMLHelper::script('media/com_tjucm/js/core/base.min.js', $options); + HTMLHelper::script('media/com_tjucm/js/services/item.min.js', $options); + HTMLHelper::script('media/com_tjucm/js/vendor/jquery/jquery.form.js', $options); + HTMLHelper::script('media/com_tjucm/js/ui/itemform.min.js', $options); + HTMLHelper::script('media/com_tjucm/js/services/items.min.js', $options); + HTMLHelper::script('media/com_tjucm/js/ui/items.min.js', $options); + + HTMLHelper::StyleSheet('media/com_tjucm/css/tjucm.css', $options); + } + + if ($view == 'item') + { + HTMLHelper::script('media/com_tjucm/js/ui/item.js'); + HTMLHelper::StyleSheet('media/com_tjucm/css/tjucm.css', $options); + } + + $loaded[$location] = true; + } + } +} diff --git a/src/components/com_tjucm/site/includes/version.php b/src/components/com_tjucm/site/includes/version.php new file mode 100644 index 00000000..9abf6f8d --- /dev/null +++ b/src/components/com_tjucm/site/includes/version.php @@ -0,0 +1,106 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL + */ +use Joomla\CMS\Factory; +defined('_JEXEC') or die(); +/** + * Version information class for the TJVendors. + * + * @since __DEPLOY_VERSION__ + */ +class TjUcmVersion +{ + /** + * Product name. + * + * @var string + * @since __DEPLOY_VERSION__ + */ + const PRODUCT = 'TJUCM'; + /** + * Major release version. + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + const MAJOR_VERSION = 2; + /** + * Minor release version. + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + const MINOR_VERSION = 0; + /** + * Patch release version. + * + * @var integer + * @since __DEPLOY_VERSION__ + */ + const PATCH_VERSION = 0; + /** + * Release date. + * + * @var string + * @since __DEPLOY_VERSION__ + */ + const RELDATE = '20-August-2019'; + /** + * Gets a "PHP standardized" version string for the current TJVendors. + * + * @return string Version string. + * + * @since __DEPLOY_VERSION__ + */ + public function getShortVersion() + { + return self::MAJOR_VERSION . '.' . self::MINOR_VERSION . '.' . self::PATCH_VERSION; + } + + /** + * Gets a version string for the current TJVendors with all release information. + * + * @return string Complete version string. + * + * @since __DEPLOY_VERSION__ + */ + public function getLongVersion() + { + return self::PRODUCT . ' ' . $this->getShortVersion() . ' ' . self::RELDATE; + } + + /** + * Generate a media version string for assets + * Public to allow third party developers to use it + * + * @return string + * + * @since __DEPLOY_VERSION__ + */ + public function generateMediaVersion() + { + return md5($this->getLongVersion() . Factory::getConfig()->get('secret')); + } + + /** + * Gets a media version which is used to append to TJVendors core media files. + * + * This media version is used to append to TJVendors core media in order to trick browsers into + * reloading the CSS and JavaScript, because they think the files are renewed. + * The media version is renewed after TJVendors core update, install, discover_install and uninstallation. + * + * @return string The media version. + * + * @since __DEPLOY_VERSION__ + */ + public function getMediaVersion() + { + return $this->generateMediaVersion(); + } +} diff --git a/src/components/com_tjucm/site/layouts/detail/fields.php b/src/components/com_tjucm/site/layouts/detail/fields.php index 38b6dfda..ec6b29cf 100644 --- a/src/components/com_tjucm/site/layouts/detail/fields.php +++ b/src/components/com_tjucm/site/layouts/detail/fields.php @@ -1,10 +1,10 @@ + * @package TJ-UCM + * + * @author TechJoomla * @copyright Copyright (c) 2009-2019 TechJoomla. All rights reserved. - * @license GNU General Public License version 2 or later; see LICENSE.txt + * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access @@ -20,8 +20,9 @@ // Layout for field types $fieldLayout = array(); -$fieldLayout['File'] = $fieldLayout['Image'] = "file"; +$fieldLayout['File'] = $fieldLayout['Image'] = $fieldLayout['Captureimage'] = "file"; $fieldLayout['Checkbox'] = "checkbox"; +$fieldLayout['Color'] = "color"; $fieldLayout['multi_select'] = $fieldLayout['single_select'] = $fieldLayout['Radio'] = $fieldLayout['List'] = $fieldLayout['tjlist'] = "list"; $fieldLayout['Itemcategory'] = "itemcategory"; $fieldLayout['Video'] = $fieldLayout['Audio'] = $fieldLayout['Url'] = "link"; @@ -30,6 +31,7 @@ $fieldLayout['Related'] = $fieldLayout['SQL'] = "sql"; $fieldLayout['Subform'] = "subform"; $fieldLayout['Ownership'] = "ownership"; +$fieldLayout['Editor'] = "editor"; // Load the tj-fields helper JLoader::import('components.com_tjfields.helpers.tjfields', JPATH_SITE); @@ -61,6 +63,7 @@ $count++; $fieldCount = 0; ?> +
getFieldset($fieldset->name) as $field) @@ -96,7 +99,6 @@
label; ?>:
render(array('fieldXml' => $xmlField, 'field' => $field)); - echo $output; + + // To align text, textarea, textareacounter, editor and tjlist fields properly + if ($field->type == 'Textarea'|| $field->type == 'Textareacounter'|| $field->type == 'Text' || $field->type == 'Editor' || $field->type == 'tjlist') + { + ?> +
+ +
+
@@ -186,5 +201,6 @@ } ?>
+
+ * @package TJ-UCM + * + * @author TechJoomla * @copyright Copyright (c) 2009-2019 TechJoomla. All rights reserved. - * @license GNU General Public License version 2 or later; see LICENSE.txt + * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('_JEXEC') or die('Restricted access'); +use Joomla\CMS\Factory; +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Router\Route; +use Joomla\CMS\Session\Session; + if (!key_exists('itemsData', $displayData)) { return; } $fieldsData = $displayData['fieldsData']; - -$app = JFactory::getApplication(); -$user = JFactory::getUser(); +$app = Factory::getApplication(); +$user = Factory::getUser(); // Layout for field types $fieldLayout = array(); -$fieldLayout['File'] = $fieldLayout['Image'] = "file"; +$fieldLayout['File'] = $fieldLayout['Image'] = $fieldLayout['Captureimage'] = "file"; $fieldLayout['Checkbox'] = "checkbox"; -$fieldLayout['tjlist'] = $fieldLayout['Radio'] = $fieldLayout['List'] = $fieldLayout['Single_select'] = $fieldLayout['Multi_select'] = "list"; +$fieldLayout['Color'] = "color"; +$fieldLayout['Tjlist'] = $fieldLayout['Radio'] = $fieldLayout['List'] = $fieldLayout['Single_select'] = $fieldLayout['Multi_select'] = "list"; $fieldLayout['Itemcategory'] = "itemcategory"; $fieldLayout['Video'] = $fieldLayout['Audio'] = $fieldLayout['Url'] = "link"; $fieldLayout['Calendar'] = "calendar"; $fieldLayout['Cluster'] = "cluster"; $fieldLayout['Related'] = $fieldLayout['Sql'] = "sql"; +$fieldLayout['Subform'] = "subform"; $fieldLayout['Ownership'] = "ownership"; +$fieldLayout['Editor'] = "editor"; // Load the tj-fields helper JLoader::import('components.com_tjfields.helpers.tjfields', JPATH_SITE); $TjfieldsHelper = new TjfieldsHelper; +// Load itemForm model +JLoader::import('components.com_tjucm.models.itemform', JPATH_SITE); +$tjucmItemFormModel = JModelLegacy::getInstance('ItemForm', 'TjucmModel'); + // Get JLayout data $item = $displayData['itemsData']; $created_by = $displayData['created_by']; @@ -43,15 +55,19 @@ $xmlFormObject = $displayData['xmlFormObject']; $formObject = $displayData['formObject']; $ucmTypeId = $displayData['ucmTypeId']; +$allowDraftSave = $displayData['ucmTypeParams']->allow_draft_save; +$i = isset($displayData['key']) ? $displayData['key'] : ''; $appendUrl = ''; -$csrf = "&" . JSession::getFormToken() . '=1'; +$csrf = "&" . Session::getFormToken() . '=1'; + +$canEditOwn = TjucmAccess::canEditOwn($ucmTypeId, $item->id); +$canDeleteOwn = TjucmAccess::canDeleteOwn($ucmTypeId, $item->id); +$canEditState = TjucmAccess::canEditState($ucmTypeId, $item->id); +$canEdit = TjucmAccess::canEdit($ucmTypeId, $item->id); +$canDelete = TjucmAccess::canDelete($ucmTypeId, $item->id); -$canEditOwn = $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $ucmTypeId); -$canDeleteOwn = $user->authorise('core.type.deleteownitem', 'com_tjucm.type.' . $ucmTypeId); -$canChange = $user->authorise('core.type.edititemstate', 'com_tjucm.type.' . $ucmTypeId); -$canEdit = $user->authorise('core.type.edititem', 'com_tjucm.type.' . $ucmTypeId); -$canDelete = $user->authorise('core.type.deleteitem', 'com_tjucm.type.' . $ucmTypeId); +$canCopyItem = $user->authorise('core.type.copyitem', 'com_tjucm.type.' . $ucmTypeId); if (!empty($created_by)) { @@ -67,37 +83,47 @@ $tjUcmFrontendHelper = new TjucmHelpersTjucm; $itemId = $tjUcmFrontendHelper->getItemId($link); -$link = JRoute::_('index.php?option=com_tjucm&view=item&id=' . $item->id . "&client=" . $client . '&Itemid=' . $itemId, false); +$link = Route::_('index.php?option=com_tjucm&view=item&id=' . $item->id . "&client=" . $client . '&Itemid=' . $itemId, false); $editown = false; if ($canEditOwn) { - $editown = (JFactory::getUser()->id == $item->created_by ? true : false); + $editown = (Factory::getUser()->id == $item->created_by ? true : false); } $deleteOwn = false; if ($canDeleteOwn) { - $deleteOwn = (JFactory::getUser()->id == $item->created_by ? true : false); + $deleteOwn = (Factory::getUser()->id == $item->created_by ? true : false); } + ?> +
+ + + + id); ?> + + state)) { - $class = ($canChange) ? 'active' : 'disabled'; ?> + $class = ($canEditState) ? 'active' : 'disabled'; ?> - + state == 1) { - ?> @@ -106,62 +132,168 @@ } ?> - + escape($item->id); ?> field_values)) + if ($allowDraftSave) { - foreach ($item->field_values as $key => $fieldValue) + ?> + draft) ? Text::_('COM_TJUCM_DATA_STATUS_DRAFT') : Text::_('COM_TJUCM_DATA_STATUS_SAVE'); ?> + $fieldValue) { - $tjFieldsFieldTable = $fieldsData[$key]; + if (array_key_exists($key, $displayData['listcolumn'])) + { + $tjFieldsFieldTable = $fieldsData[$key]; - $canView = false; + $canView = false; - if ($user->authorise('core.field.viewfieldvalue', 'com_tjfields.group.' . $tjFieldsFieldTable->group_id)) - { - $canView = $user->authorise('core.field.viewfieldvalue', 'com_tjfields.field.' . $tjFieldsFieldTable->id); - } + if ($user->authorise('core.field.viewfieldvalue', 'com_tjfields.group.' . $tjFieldsFieldTable->group_id)) + { + $canView = $user->authorise('core.field.viewfieldvalue', 'com_tjfields.field.' . $tjFieldsFieldTable->id); + } - $fieldXml = $formObject->getFieldXml($tjFieldsFieldTable->name); - ?> - - created_by == $user->id)) - { - $field = $formObject->getField($tjFieldsFieldTable->name); - $field->setValue($fieldValue); - $layoutToUse = (array_key_exists(ucfirst($tjFieldsFieldTable->type), $fieldLayout)) ? $fieldLayout[ucfirst($tjFieldsFieldTable->type)] : 'field'; - $layout = new JLayoutFile($layoutToUse, JPATH_ROOT . '/components/com_tjfields/layouts/fields'); - $output = $layout->render(array('fieldXml' => $fieldXml, 'field' => $field)); - echo $output; - } + $fieldXml = $formObject->getFieldXml($tjFieldsFieldTable->name); ?> - "> + created_by == $user->id)) + { + $field = $formObject->getField($tjFieldsFieldTable->name); + $field->setValue($fieldValue); + + if ($field->type == 'Ucmsubform' && $fieldValue) + { + $ucmSubFormData = json_decode($tjucmItemFormModel->getUcmSubFormFieldDataJson($item->id, $field)); + $field->setValue($ucmSubFormData); + ?> +
+
label; ?>:
+
+ getFieldData($field->getAttribute('name')); + + $ucmSubFormFieldParams = json_decode($fieldData->params); + $ucmSubFormFormSource = explode('/', $ucmSubFormFieldParams->formsource); + $ucmSubFormClient = $ucmSubFormFormSource[1] . '.' . str_replace('form_extra.xml', '', $ucmSubFormFormSource[4]); + $view = explode('.', $ucmSubFormClient); + $ucmSubFormData = (array) $ucmSubFormData; + + if (!empty($ucmSubFormData)) + { + $count = 0; + + foreach ($ucmSubFormData as $subFormData) + { + $count++; + $contentIdFieldname = str_replace('.', '_', $ucmSubFormClient) . '_contentid'; + + $ucmSubformFormObject = $tjucmItemModel->getFormExtra( + array( + "clientComponent" => 'com_tjucm', + "client" => $ucmSubFormClient, + "view" => $view[1], + "layout" => 'default', + "content_id" => $subFormData->$contentIdFieldname) + ); + + $ucmSubFormFormXml = simplexml_load_file($field->formsource); + + $ucmSubFormCount = 0; + + foreach ($ucmSubFormFormXml as $ucmSubFormXmlFieldSet) + { + $ucmSubFormXmlFieldSets[$ucmSubFormCount] = $ucmSubFormXmlFieldSet; + $ucmSubFormCount++; + } + + $ucmSubFormRecordData = $tjucmItemModel->getData($subFormData->$contentIdFieldname); + + // Call the JLayout recursively to render fields of ucmsubform + $layout = new JLayoutFile('fields', JPATH_ROOT . '/components/com_tjucm/layouts/detail'); + echo $layout->render(array('xmlFormObject' => $ucmSubFormXmlFieldSets, 'formObject' => $ucmSubformFormObject, 'itemData' => $ucmSubFormRecordData, 'isSubForm' => 1)); + + if (count($ucmSubFormData) > $count) + { + echo "
"; + } + } + } + ?> +
+
+ type), $fieldLayout + ) + ) ? $fieldLayout[ucfirst($tjFieldsFieldTable->type)] : 'field'; + $layout = new JLayoutFile($layoutToUse, JPATH_ROOT . '/components/com_tjfields/layouts/fields'); + $output = $layout->render(array('fieldXml' => $fieldXml, 'field' => $field)); + + // To align text, textarea, textareacounter, editor and tjlist fields properly + if ($field->type == 'Textarea'|| $field->type == 'Textareacounter'|| $field->type == 'Text' || $field->type == 'Editor' || $field->type == 'tjlist') + { + ?> +
+ +
+ + + + + + - - + | - - - - - - id . $appendUrl . $csrf; ?>" + class="delete-button" type="button" + title=""> | + + + + +
diff --git a/src/components/com_tjucm/site/models/item.php b/src/components/com_tjucm/site/models/item.php index 02e31596..60ea055d 100644 --- a/src/components/com_tjucm/site/models/item.php +++ b/src/components/com_tjucm/site/models/item.php @@ -17,6 +17,7 @@ require_once JPATH_SITE . "/components/com_tjfields/filterFields.php"; use Joomla\Utilities\ArrayHelper; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; /** * Tjucm model. @@ -44,7 +45,6 @@ class TjucmModelItem extends JModelAdmin protected function populateState() { $app = JFactory::getApplication('com_tjucm'); - $user = JFactory::getUser(); // Load state from the request. $id = $app->input->getInt('id'); @@ -68,7 +68,10 @@ protected function populateState() if (!empty($ucm_type)) { - $ucmType = 'com_tjucm.' . $ucm_type; + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $ucm_type)); + $ucmType = $ucmTypeTable->unique_identifier; } } } @@ -80,9 +83,7 @@ protected function populateState() $this->setState('ucmType.id', $ucmId); // Check published state - if ((!$user->authorise('core.type.edititem', 'com_tjucm.type.' . $ucmId)) - && (!$user->authorise('core.type.editownitem', 'com_tjucm.type.' . $ucmId)) - && (!$user->authorise('core.type.edititemstate', 'com_tjucm.type.' . $ucmId))) + if ((!TjucmAccess::canEdit($ucmId, $id)) && (!TjucmAccess::canEditOwn($ucmId, $id)) && (!TjucmAccess::canEditState($ucmId, $id))) { $this->setState('filter.published', 1); $this->setState('fileter.archived', 2); @@ -170,8 +171,6 @@ public function getItem($pk = null) */ public function &getData($id = null) { - $user = JFactory::getUser(); - $this->item = false; if (empty($id)) @@ -181,7 +180,7 @@ public function &getData($id = null) // Get UCM type id (Get if user is autorised to edit the items for this UCM type) $ucmTypeId = $this->getState('ucmType.id'); - $canView = $user->authorise('core.type.viewitem', 'com_tjucm.type.' . $ucmTypeId); + $canView = TjucmAccess::canView($ucmTypeId, $id); // Get a level row instance. $table = $this->getTable(); @@ -211,7 +210,7 @@ public function &getData($id = null) if (!empty($this->item->id)) { - if ($canView || ($this->item->created_by == $user->id)) + if ($canView || ($this->item->created_by == JFactory::getUser()->id)) { $this->item->params->set('access-view', true); } @@ -242,124 +241,47 @@ public function getTable($type = 'Item', $prefix = 'TjucmTable', $config = array } /** - * Get the id of an item by alias + * Publish the element * - * @param string $alias Item alias + * @param int &$id Item id + * @param int $state Publish state * - * @return mixed + * @return boolean */ - public function getItemIdByAlias($alias) + public function publish(&$id, $state = 1) { $table = $this->getTable(); + $table->load($id); + $table->state = $state; - $table->load(array('alias' => $alias)); - - return $table->id; - } - - /** - * Method to check in an item. - * - * @param integer $id The id of the row to check out. - * - * @return boolean True on success, false on failure. - * - * @since 1.6 - */ - public function checkin($id = null) - { - // Get the id. - $id = (!empty($id)) ? $id : (int) $this->getState('item.id'); - - if ($id) + // Only if item is published + if ($state == 1) { - // Initialise the table - $table = $this->getTable(); - - // Attempt to check the row in. - if (method_exists($table, 'checkin')) - { - if (!$table->checkin($id)) - { - return false; - } - } + $table->draft = 0; } - return true; - } - - /** - * Method to check out an item for editing. - * - * @param integer $id The id of the row to check out. - * - * @return boolean True on success, false on failure. - * - * @since 1.6 - */ - public function checkout($id = null) - { - // Get the user id. - $id = (!empty($id)) ? $id : (int) $this->getState('item.id'); - - if ($id) + if ($table->store()) { - // Initialise the table - $table = $this->getTable(); - - // Get the current user object. - $user = JFactory::getUser(); + JLoader::import('components.com_tjucm.models.items', JPATH_SITE); + $itemsModel = BaseDatabaseModel::getInstance('Items', 'TjucmModel', array('ignore_request' => true)); + $itemsModel->setState("parent_id", $id); + $children = $itemsModel->getItems(); - // Attempt to check the row out. - if (method_exists($table, 'checkout')) + foreach ($children as $child) { - if (!$table->checkout($user->get('id'), $id)) + $childTable = $this->getTable(); + $childTable->load($child->id); + $childTable->state = $state; + + // Only if item is published + if ($state == 1) { - return false; + $childTable->draft = 0; } + + $childTable->store(); } } - - return true; - } - - /** - * Get the name of a category by id - * - * @param int $id Category id - * - * @return Object|null Object if success, null in case of failure - */ - public function getCategoryName($id) - { - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query - ->select('title') - ->from('#__categories') - ->where('id = ' . $id); - $db->setQuery($query); - - return $db->loadObject(); - } - - /** - * Publish the element - * - * @param int &$id Item id - * @param int $state Publish state - * - * @return boolean - */ - public function publish(&$id, $state = 1) - { - $table = $this->getTable(); - $table->load($id); - $table->draft = $state == 1 ? 0 : 1; - $table->state = $state; - - return $table->store(); } /** @@ -374,8 +296,7 @@ public function delete(&$id) $app = JFactory::getApplication('com_tjucm'); $ucmTypeId = $this->getState('ucmType.id'); - $user = JFactory::getUser(); - $canDelete = $user->authorise('core.type.deleteitem', 'com_tjucm.type.' . $ucmTypeId); + $canDelete = TjucmAccess::canDelete($ucmTypeId, $id); if ($canDelete) { @@ -390,38 +311,4 @@ public function delete(&$id) return false; } } - - /** - * Method to getAliasFieldNameByView - * - * @param array $view An array of record primary keys. - * - * @return boolean True if successful, false if an error occurs. - * - * @since 1.0 - */ - public function getAliasFieldNameByView($view) - { - switch ($view) - { - case 'type': - case 'typeform': - return 'alias'; - break; - } - } - - /** - * Method to check if a user has permissions to view ucm items of given type - * - * @param int $typeId Type Id - * - * @return boolean - */ - public function canView($typeId) - { - $user = JFactory::getUser(); - - return $user->authorise('core.type.viewitem', 'com_tjucm.type.' . $typeId); - } } diff --git a/src/components/com_tjucm/site/models/itemform.php b/src/components/com_tjucm/site/models/itemform.php index 32175e0a..e71f4405 100644 --- a/src/components/com_tjucm/site/models/itemform.php +++ b/src/components/com_tjucm/site/models/itemform.php @@ -15,18 +15,26 @@ jimport('joomla.event.dispatcher'); require_once JPATH_SITE . "/components/com_tjfields/filterFields.php"; -require_once JPATH_ADMINISTRATOR . '/components/com_tjucm/classes/funlist.php'; use Joomla\CMS\Table\Table; use Joomla\Utilities\ArrayHelper; use Joomla\CMS\Factory; use Joomla\CMS\Component\ComponentHelper; use Joomla\Registry\Registry; +use Joomla\CMS\Language\Text; +use TJQueue\Admin\TJQueueProduce; + +if (ComponentHelper::getComponent('com_tjqueue', true)->enabled) +{ + jimport('tjqueueproduce', JPATH_SITE . '/administrator/components/com_tjqueue/libraries'); +} + +JLoader::register('TjucmAccess', JPATH_SITE . '/components/com_tjucm/includes/access.php'); /** * Tjucm model. * - * @since 1.6 + * @since 1.0 */ class TjucmModelItemForm extends JModelAdmin { @@ -34,7 +42,7 @@ class TjucmModelItemForm extends JModelAdmin /** * @var string The prefix to use with controller messages. - * @since 1.6 + * @since 1.0 */ protected $text_prefix = 'COM_TJUCM'; @@ -49,22 +57,6 @@ class TjucmModelItemForm extends JModelAdmin // Use imported Trait in model use TjfieldsFilterField; - /** - * Constructor. - * - * @param array $config An optional associative array of configuration settings. - * - * @see JController - * @since 1.6 - */ - public function __construct($config = array()) - { - JLoader::import('components.com_tjucm.classes.funlist', JPATH_ADMINISTRATOR); - $this->common = new TjucmFunList; - - parent::__construct($config); - } - /** * Method to auto-populate the model state. * @@ -72,7 +64,7 @@ public function __construct($config = array()) * * @return void * - * @since 1.6 + * @since 1.0 */ protected function populateState() { @@ -104,7 +96,10 @@ protected function populateState() if (!empty($ucm_type)) { - $ucmType = 'com_tjucm.' . $ucm_type; + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $ucm_type)); + $ucmType = $ucmTypeTable->unique_identifier; } } } @@ -116,9 +111,7 @@ protected function populateState() $this->setState('ucmType.id', $ucmId); // Check published state - if ((!$user->authorise('core.type.edititem', 'com_tjucm.type.' . $ucmId)) - && (!$user->authorise('core.type.editownitem', 'com_tjucm.type.' . $ucmId)) - && (!$user->authorise('core.type.edititemstate', 'com_tjucm.type.' . $ucmId))) + if ((!TjucmAccess::canEdit($ucmId, $id)) && (!TjucmAccess::canEditOwn($ucmId, $id)) && (!TjucmAccess::canEditState($ucmId, $id))) { $this->setState('filter.published', 1); $this->setState('fileter.archived', 2); @@ -158,9 +151,9 @@ public function &getData($id = null) // Get UCM type id (Get if user is autorised to edit the items for this UCM type) $ucmTypeId = $this->getState('ucmType.id'); - $canEdit = $user->authorise('core.type.edititem', 'com_tjucm.type.' . $ucmTypeId); - $canEditOwn = $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $ucmTypeId); - $canCreate = $user->authorise('core.type.createitem', 'com_tjucm.type.' . $ucmTypeId); + $canEdit = TjucmAccess::canEdit($ucmTypeId, $id); + $canEditOwn = TjucmAccess::canEditOwn($ucmTypeId, $id); + $canCreate = TjucmAccess::canCreate($ucmTypeId); // Get a level row instance. $table = $this->getTable(); @@ -232,7 +225,7 @@ public function &getData($id = null) * * @return JTable A database object * - * @since 1.6 + * @since 1.0 */ public function getTable($type = 'Item', $prefix = 'TjucmTable', $config = array()) { @@ -241,93 +234,10 @@ public function getTable($type = 'Item', $prefix = 'TjucmTable', $config = array return JTable::getInstance($type, $prefix, $config); } - /** - * Get an item by alias - * - * @param string $alias Alias string - * - * @return int Element id - */ - public function getItemIdByAlias($alias) - { - $table = $this->getTable(); - - $table->load(array('alias' => $alias)); - - return $table->id; - } - - /** - * Method to check in an item. - * - * @param integer $id The id of the row to check out. - * - * @return boolean True on success, false on failure. - * - * @since 1.6 - */ - public function checkin($id = null) - { - // Get the id. - $id = (!empty($id)) ? $id : (int) $this->getState('item.id'); - - if ($id) - { - // Initialise the table - $table = $this->getTable(); - - // Attempt to check the row in. - if (method_exists($table, 'checkin')) - { - if (!$table->checkin($id)) - { - return false; - } - } - } - - return true; - } - - /** - * Method to check out an item for editing. - * - * @param integer $id The id of the row to check out. - * - * @return boolean True on success, false on failure. - * - * @since 1.6 - */ - public function checkout($id = null) - { - // Get the user id. - $id = (!empty($id)) ? $id : (int) $this->getState('item.id'); - - if ($id) - { - // Initialise the table - $table = $this->getTable(); - - // Get the current user object. - $user = JFactory::getUser(); - - // Attempt to check the row out. - if (method_exists($table, 'checkout')) - { - if (!$table->checkout($user->get('id'), $id)) - { - return false; - } - } - } - - return true; - } - /** * Get an array of data items * - * @param string $client client value + * @param string $client client * * @return mixed Array of data items on success, false on failure. */ @@ -336,16 +246,6 @@ public function setClient($client) $this->client = $client; } - /** - * Get an client value - * - * @return mixed Array of data items on success, false on failure. - */ - public function getClient() - { - return $this->client; - } - /** * Method to get the record form. * @@ -354,7 +254,7 @@ public function getClient() * * @return JForm A JForm object on success, false on failure * - * @since 1.6 + * @since 1.0 */ public function getForm($data = array(), $loadData = true) { @@ -382,7 +282,7 @@ public function getForm($data = array(), $loadData = true) * * @return JForm A JForm object on success, false on failure * - * @since 1.6 + * @since 1.2.2 */ public function getFieldForm($data = array(), $loadData = true) { @@ -430,21 +330,31 @@ public function getFieldForm($data = array(), $loadData = true) return $form; } + /** + * Method to get the type form object. + * + * @param array $data An optional array of data for the form to interogate. + * @param boolean $loadData True if the form is to load its own data (default case), false if not. + * + * @return JForm A JForm object on success, false on failure + * + * @since 1.2.2 + */ public function getTypeForm($data = array(), $loadData = true) { $draft = isset($data['draft']) ? $data['draft'] : 0; - $clientPart = explode(".", $data['client']); + $client = $data['client']; + $contentId = empty($data['id']) ? '' : $data['id']; + $clientPart = explode(".", $client); - // Path of empty form XML to create form object dynamically - $formPath = JPATH_SITE . '/components/com_tjucm/models/forms/' . $clientPart[1] . 'form_extra.xml'; + $data = array(); + $data['clientComponent'] = $clientPart[0]; + $data['view'] = $clientPart[1]; + $data['client'] = $client; + $data['content_id'] = $contentId; + $data['layout'] = 'edit'; - // Get the form. - $form = $this->loadForm( - $data['client'], $formPath, - array('control' => 'jform', - 'load_data' => $loadData, - ) - ); + $form = $this->getFormObject($data); // If data is being saved in draft mode then dont check if the fields are required if ($draft) @@ -455,6 +365,21 @@ public function getTypeForm($data = array(), $loadData = true) { foreach ($form->getFieldset($fieldset->name) as $field) { + // Remove required attribute from the subform fields in case of draft save + if ($field->type == 'Subform' || $field->type == 'Ucmsubform') + { + $subForm = $field->loadSubForm(); + $subFormFieldSets = $subForm->getFieldsets(); + + foreach ($subFormFieldSets as $subFormFieldSet) + { + foreach ($subForm->getFieldset($subFormFieldSet->name) as $subFormField) + { + $subForm->setFieldAttribute($subFormField->fieldname, 'required', false); + } + } + } + $form->setFieldAttribute($field->fieldname, 'required', false); } } @@ -468,6 +393,16 @@ public function getTypeForm($data = array(), $loadData = true) return $form; } + /** + * Method to get the type section form object. + * + * @param array $data An optional array of data for the form to interogate. + * @param boolean $loadData True if the form is to load its own data (default case), false if not. + * + * @return JForm A JForm object on success, false on failure + * + * @since 1.2.2 + */ public function getSectionForm($data = array(), $loadData = true) { if (empty($data['client']) || empty($data['section'])) @@ -475,25 +410,25 @@ public function getSectionForm($data = array(), $loadData = true) return false; } + $section = $data['section']; + $client = $data['client']; + $clientPart = explode(".", $client); + + $data = array(); + $data['clientComponent'] = $clientPart[0]; + $data['view'] = $clientPart[1]; + $data['client'] = $client; + $data['layout'] = 'edit'; + + $parentForm = $this->getFormObject($data); + // Create xml with the fieldset of provided section $newXML = new SimpleXMLElement(''); $newXmlFilePath = JPATH_SITE . '/components/com_tjucm/models/forms/tempfieldsetform.xml'; - // Get path of parent UCM type XML - $fieldNamePart = explode('.', $data['client']); - $parentFormPath = JPATH_SITE . "/administrator/components/com_tjucm/models/forms/" . $fieldNamePart[1] . "_extra.xml"; - - // Get parent form. - $parentForm = $this->loadForm( - 'com_tjucm.itemform', $parentFormPath, - array('control' => 'jform', - 'load_data' => false, - ) - ); - // Get the fieldset XML from parent form $formXml = $parentForm->getXml(); - $fieldsetXml = $formXml->xpath('//fieldset[@name="' . $data['section'] . '" and not(ancestor::field/form/*)]'); + $fieldsetXml = $formXml->xpath('//fieldset[@name="' . $section . '" and not(ancestor::field/form/*)]'); if ($fieldsetXml[0] instanceof \SimpleXMLElement) { @@ -539,7 +474,7 @@ public function getSectionForm($data = array(), $loadData = true) * * @return mixed The data for the form. * - * @since 1.6 + * @since 1.0 */ protected function loadFormData() { @@ -566,11 +501,11 @@ protected function loadFormData() * * @return boolean True on success. * - * @since 1.6 + * @since 1.0 */ public function save($data) { - $user = JFactory::getUser(); + $user = empty($data['created_by']) ? Factory::getUser() : Factory::getUser($data['created_by']); // Guest users are not allowed to add the records if (empty($user->id)) @@ -580,6 +515,15 @@ public function save($data) return false; } + if (empty($data['id'])) + { + // Set the state of record as per UCM type config + $typeTable = $this->getTable('type'); + $typeTable->load(array('unique_identifier' => $data['client'])); + $typeParams = new Registry($typeTable->params); + $data['state'] = $typeParams->get('publish_items', 0); + } + // Get instance of UCM type table JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); $tjUcmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', Factory::getDbo())); @@ -607,13 +551,39 @@ public function save($data) $ucmTypeParams = new Registry($tjUcmTypeTable->params); + // Check if UCM type is subform + $isSubform = $ucmTypeParams->get('is_subform'); + + if ($isSubform) + { + if ($data['parent_id']) + { + $tableParentData = $this->getTable(); + $tableParentData->load(array('id' => $data['parent_id'])); + + if (!property_exists($tableParentData->id) && (!$tableParentData->id)) + { + $this->setError(Text::_('COM_TJUCM_INVALID_PARENT_ID')); + + return false; + } + } + + if (!$data['parent_id']) + { + $this->setError(Text::_('COM_TJUCM_SUBFORM_NOT_ALLOWED_WITH_OUT_PARENT_ID')); + + return false; + } + } + // Check if user is allowed to add/edit the record if (empty($data['id'])) { $allowedCount = $ucmTypeParams->get('allowed_count', 0, 'INT'); // Check if the user is allowed to add record for given UCM type - $canAdd = $user->authorise('core.type.createitem', 'com_tjucm.type.' . $data['type_id']); + $canAdd = TjucmAccess::canCreate($data['type_id'], $data['created_by']); if (!$canAdd) { @@ -638,8 +608,8 @@ public function save($data) else { // Check if the user can edit this record - $canEdit = $user->authorise('core.type.edititem', 'com_tjucm.type.' . $data['type_id']); - $canEditOwn = $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $data['type_id']); + $canEdit = TjucmAccess::canEdit($data['type_id'], $data['id']); + $canEditOwn = TjucmAccess::canEditOwn($data['type_id'], $data['id']); $itemTable = $this->getTable(); $itemTable->load(array('id' => $data['id'])); @@ -673,16 +643,18 @@ public function save($data) * * @since 1.2.1 */ - public function saveExtraFields($fieldData) + public function saveFieldsData($fieldData) { // If the data contain data related to cluster field or ownership field then update the ucm_data table accordingly if (!empty($fieldData['fieldsvalue']) && !empty($fieldData['content_id'])) { $clusterFieldName = str_replace('.', '_', $fieldData['client']) . '_clusterclusterid'; $ownerShipFieldName = str_replace('.', '_', $fieldData['client']) . '_ownershipcreatedby'; - $itemCategoryFieldName = str_replace('.', '_', $fieldData['client']) . '_itemcategory'; + $itemCategoryFieldName = str_replace('.', '_', $fieldData['client']) . '_itemcategoryitemcategory'; - if (array_key_exists($clusterFieldName, $fieldData['fieldsvalue']) || array_key_exists($ownerShipFieldName, $fieldData['fieldsvalue']) || array_key_exists($itemCategoryFieldName, $fieldData['fieldsvalue'])) + if (array_key_exists($clusterFieldName, $fieldData['fieldsvalue']) + || array_key_exists($ownerShipFieldName, $fieldData['fieldsvalue']) + || array_key_exists($itemCategoryFieldName, $fieldData['fieldsvalue'])) { JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); $ucmItemTable = JTable::getInstance('Item', 'TjucmTable', array('dbo', JFactory::getDbo())); @@ -694,280 +666,29 @@ public function saveExtraFields($fieldData) } if (!empty($fieldData['fieldsvalue'][$ownerShipFieldName])) - { - $ucmItemTable->created_by = $fieldData['fieldsvalue'][$ownerShipFieldName]; - } - - if (!empty($fieldData['fieldsvalue'][$itemCategoryFieldName])) - { - $ucmItemTable->category_id = $fieldData['fieldsvalue'][$itemCategoryFieldName]; - } - - $ucmItemTable->store(); - } - } - - return TjfieldsFilterField::saveExtraFields($fieldData); - } - - /** - * Method to save the form data. - * - * @param array $data The form data. - * @param array $extra_jform_data Exra field data. - * - * @return boolean - * - * @since 1.6 - */ - public function saveTOBEDELETED($data, $extra_jform_data = '') - { - $app = JFactory::getApplication(); - $user = JFactory::getUser(); - $status_title = $app->input->get('form_status'); - $ucmTypeId = $this->getState('ucmType.id'); - $typeItemId = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('item.id'); - $authorised = false; - - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/models'); - $tjUcmModelType = JModelLegacy::getInstance('Type', 'TjucmModel'); - - if (empty($ucmTypeId)) - { - // Get UCM type id from uniquue identifier - $ucmTypeId = $tjUcmModelType->getTypeId($data['client']); - } - - if ($ucmTypeId) - { - // Check if user is allowed to save the content - $typeData = $tjUcmModelType->getItem($ucmTypeId); - $allowedCount = $typeData->allowed_count; - - // 0 : add unlimited records against this UCM type - $allowedCount = empty($allowedCount) ? 0 : $allowedCount; - $userId = $user->id; - $allowedToAdd = $this->allowedToAddTypeData($userId, $data['client'], $allowedCount); - - if (!$allowedToAdd && $typeItemId == 0) - { - $message = JText::sprintf('COM_TJUCM_ALLOWED_COUNT_LIMIT', $allowedCount); - $app->enqueueMessage($message, 'warning'); - - return false; - } - - if ($typeItemId) - { - // Check the user can edit this item - $canEdit = $user->authorise('core.type.edititem', 'com_tjucm.type.' . $ucmTypeId); - $canEditOwn = $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $ucmTypeId); - - // Get the UCM item details - Table::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/tables'); - $itemDetails = Table::getInstance('Item', 'TjucmTable'); - $itemDetails->load(array('id' => $typeItemId)); - - // If there is ownership field in form and the field is assigned some value then update created_by for the record - $client = explode(".", $itemDetails->client); - $ownershipField = $client[0] . '_' . $client[1] . '_ownershipcreatedby'; - - if (isset($extra_jform_data[$ownershipField]) && !empty($extra_jform_data[$ownershipField])) { JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); - $ownershipFieldData = Table::getInstance('Field', 'TjfieldsTable'); - $ownershipFieldData->load(array('name' => $ownershipField)); - $ownershipFieldParams = json_decode($ownershipFieldData->params); + $fieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', JFactory::getDbo())); + $fieldTable->load(array('name' => $ownerShipFieldName)); + $fieldParams = new Registry($fieldTable->params); - if ($ownershipFieldParams->ucmItemOwner == 1) + // If enabled then the selected user will be set as creator of the UCM type item + if ($fieldParams->get('ucmItemOwner')) { - $data['created_by'] = $extra_jform_data[$ownershipField]; + $ucmItemTable->created_by = $fieldData['fieldsvalue'][$ownerShipFieldName]; } } - else - { - $data['created_by'] = $itemDetails->created_by; - } - - if ($canEdit) - { - $authorised = true; - } - elseif (($canEditOwn) && ($itemDetails->created_by == $user->id)) - { - if (!empty($data['created_by']) && $itemDetails->created_by == $data['created_by']) - { - $authorised = true; - } - } - } - else - { - // Check the user can create new items in this section - $authorised = $user->authorise('core.type.createitem', 'com_tjucm.type.' . $ucmTypeId); - } - } - - if ($authorised !== true) - { - throw new Exception(JText::_('COM_TJUCM_ERROR_MESSAGE_NOT_AUTHORISED'), 403); - - return false; - } - - $ucmTypeData = $this->common->getDataValues('#__tj_ucm_types', 'id AS type_id, params', 'unique_identifier = "' - . $data['client'] . '"', 'loadAssoc'); - - $data['type_id'] = empty($data['type_id']) ? $ucmTypeData['type_id'] : $data['type_id']; - - $ucmTypeParams = json_decode($ucmTypeData['params']); - - $table = $this->getTable(); - - if (isset($ucmTypeParams->publish_items) && $ucmTypeParams->publish_items == 0) - { - $data['state'] = 0; - } - else - { - $data['state'] = 1; - } - - // To store fields value in TJ-Fields - $data_extra = array(); - - if (!empty($extra_jform_data)) - { - $data_extra['client'] = $data['client']; - $data_extra['fieldsvalue'] = $extra_jform_data; - } - - $isNew = empty($typeItemId) ? 1 : 0; - - // OnBefore UCM record save trigger. - JPluginHelper::importPlugin('tjucm'); - $dispatcher = JDispatcher::getInstance(); - $dispatcher->trigger('tjucmOnBeforeSaveItem', array(&$data, &$data_extra, $isNew)); - - // Load TJ-Fields tables - Table::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjfields/tables'); - - // If item category field is added in the type then save item category agains the item record - foreach ($extra_jform_data as $fieldName => $fieldData) - { - $fieldTable = Table::getInstance('Field', 'TjfieldsTable'); - $fieldTable->load(array('name' => $fieldName)); - - if ($fieldTable->type == 'itemcategory') - { - $data['category_id'] = $fieldData; - - break; - } - } - - if ($table->save($data) === true) - { - if (!empty($extra_jform_data)) - { - $data_extra['content_id'] = $table->id; - - // Save extra fields data. - $this->saveExtraFields($data_extra); - } - - $data['id'] = $table->id; - - // OnAfter UCM record save trigger. - $dispatcher->trigger('tjucmOnAfterSaveItem', array($data, $data_extra)); - - return $table->id; - } - else - { - throw new Exception($table->getError()); - } - } - - /** - * Method to duplicate an Item - * - * @param array &$pks An array of primary key IDs. - * - * @return boolean True if successful. - * - * @throws Exception - */ - public function duplicate(&$pks) - { - $user = JFactory::getUser(); - $ucmTypeId = $this->getState('ucmType.id'); - - // Access checks. - if (!$user->authorise('core.type.createitem', 'com_tjucm.type.' . $ucmTypeId)) - { - throw new Exception(JText::_('JERROR_CORE_CREATE_NOT_PERMITTED')); - return false; - } - - $dispatcher = JEventDispatcher::getInstance(); - $context = $this->option . '.' . $this->name; - - // Include the plugins for the save events. - JPluginHelper::importPlugin($this->events_map['save']); - - $table = $this->getTable(); - - foreach ($pks as $pk) - { - if ($table->load($pk, true)) - { - // Reset the id to create a new record. - $table->id = 0; - - if (!$table->check()) - { - throw new Exception($table->getError()); - - return false; - } - - if (!empty($table->type_id)) - { - if (is_array($table->type_id)) - { - $table->type_id = implode(',', $table->type_id); - } - } - else - { - $table->type_id = ''; - } - - // Trigger the before save event. - $result = $dispatcher->trigger($this->event_before_save, array($context, &$table, true)); - - if (in_array(false, $result, true) || !$table->store()) + if (!empty($fieldData['fieldsvalue'][$itemCategoryFieldName])) { - throw new Exception($table->getError()); + $ucmItemTable->category_id = $fieldData['fieldsvalue'][$itemCategoryFieldName]; } - // Trigger the after save event. - $dispatcher->trigger($this->event_after_save, array($context, &$table, true)); - } - else - { - throw new Exception($table->getError()); - - return false; + $ucmItemTable->store(); } } - // Clean cache - $this->cleanCache(); - - return true; + return $this->saveExtraFields($fieldData); } /** @@ -985,8 +706,8 @@ public function delete(&$contentId) $user = JFactory::getUser(); $table = $this->getTable(); $table->load($contentId); - $canDelete = $user->authorise('core.type.deleteitem', 'com_tjucm.type.' . $table->type_id); - $canDeleteown = $user->authorise('core.type.deleteownitem', 'com_tjucm.type.' . $table->type_id); + $canDelete = TjucmAccess::canDelete($table->type_id, $contentId); + $canDeleteown = TjucmAccess::canDeleteOwn($table->type_id, $contentId); $deleteOwn = false; @@ -1021,9 +742,19 @@ public function delete(&$contentId) { $table->load($subFormContentId); + // Plugin trigger on before item delete + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnBeforeDeleteItem', array($subFormContentId, $table->client)); + if ($table->delete($subFormContentId) === true) { $this->deleteExtraFieldsData($subFormContentId, $table->client); + + // Plugin trigger on after item delete + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnAfterDeleteItem', array($subFormContentId, $table->client)); } } } @@ -1031,10 +762,20 @@ public function delete(&$contentId) // Delete parent record $table->load($id); + // Plugin trigger on before item delete + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnBeforeDeleteItem', array($id, $table->client)); + if ($table->delete($id) === true) { $this->deleteExtraFieldsData($id, $table->client); + // Plugin trigger on after item delete + JPluginHelper::importPlugin('actionlog'); + $dispatcher = JDispatcher::getInstance(); + $dispatcher->trigger('tjUcmOnAfterDeleteItem', array($id, $table->client)); + return $id; } else @@ -1050,38 +791,6 @@ public function delete(&$contentId) } } - /** - * Check if data can be saved - * - * @return bool - */ - public function getCanSave() - { - $table = $this->getTable(); - - return $table !== false; - } - - /** - * Method to getAliasFieldNameByView - * - * @param array $view An array of record primary keys. - * - * @return boolean True if successful, false if an error occurs. - * - * @since 1.0 - */ - public function getAliasFieldNameByView($view) - { - switch ($view) - { - case 'type': - case 'typeform': - return 'alias'; - break; - } - } - /** * Check if user is submit new type data or not * @@ -1125,263 +834,6 @@ public function allowedToAddTypeData($userId, $client, $allowedCount) } } - /** - * Method to set cluster data in posted data. - * - * @param array &$validData The validated data. - * - * @param array $data UCM form data. - * - * @return null - * - * @since 1.6 - */ - public function setClusterData(&$validData, $data) - { - $clusterField = $ownershipField = ''; - - // To get type of UCM - if (!empty($this->client)) - { - $client = explode(".", $this->client); - $clusterField = $client[0] . '_' . $client[1] . '_clusterclusterid'; - $ownershipField = $client[0] . '_' . $client[1] . '_ownershipcreatedby'; - } - - JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); - $ownershipFieldData = Table::getInstance('Field', 'TjfieldsTable'); - $ownershipFieldData->load(array('name' => $ownershipField)); - $ownershipFieldParams = json_decode($ownershipFieldData->params); - - // Save created_by field by ownership user field (To save form on behalf of someone) - if (!empty($data[$ownershipField]) && empty($data[$clusterField]) && ($ownershipFieldParams->ucmItemOwner == 1)) - { - $validData['created_by'] = $data[$ownershipField]; - } - - // Cluster Id store in UCM data - $clusterExist = ComponentHelper::getComponent('com_cluster', true)->enabled; - - if (!empty($data[$clusterField]) && $clusterExist) - { - $user = Factory::getUser(); - $isSuperUser = $user->authorise('core.admin'); - - JLoader::import("/components/com_cluster/includes/cluster", JPATH_ADMINISTRATOR); - $ClusterModel = ClusterFactory::model('ClusterUsers', array('ignore_request' => true)); - $ClusterModel->setState('list.group_by_user_id', 1); - $ClusterModel->setState('filter.published', 1); - $ClusterModel->setState('filter.cluster_id', (int) $data[$clusterField]); - - if (!$isSuperUser && !$user->authorise('core.manageall', 'com_cluster')) - { - $ClusterModel->setState('filter.user_id', $user->id); - } - - // Get all assigned cluster entries - $clusters = $ClusterModel->getItems(); - - if (!empty($clusters)) - { - $validData['cluster_id'] = $data[$clusterField]; - - if (!empty($data[$ownershipField])) - { - $clusterUsers = array(); - - foreach ($clusters as $cluster) - { - $clusterUsers[] = $cluster->user_id; - } - - if (in_array($data[$ownershipField], $clusterUsers) && ($ownershipFieldParams->ucmItemOwner == 1)) - { - $validData['created_by'] = $data[$ownershipField]; - } - } - } - } - } - - /** - * Function to get formatted data to be added of ucmsubform records - * - * @param ARRAY $validData Parent record data - * @param ARRAY &$extra_jform_data form data - * - * @return ARRAY - */ - public function getFormattedUcmSubFormRecords($validData, &$extra_jform_data) - { - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/models'); - $tjUcmModelType = JModelLegacy::getInstance('Type', 'TjucmModel'); - - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjfields/models'); - $tjFieldsFieldsModel = JModelLegacy::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); - $tjFieldsFieldsModel->setState('filter.client', $validData['client']); - $tjFieldsFieldsModel->setState('filter.type', 'ucmsubform'); - - // Get list of ucmsubform fields in the parent form - $ucmSubFormFields = $tjFieldsFieldsModel->getItems(); - - // Variable to store ucmsubform records posted in the form - $ucmSubFormDataSet = array(); - - // Sort all the ucmsubform records as per client - foreach ($ucmSubFormFields as $ucmSubFormField) - { - if (!isset($extra_jform_data[$ucmSubFormField->name])) - { - continue; - } - - $subformRecords = $extra_jform_data[$ucmSubFormField->name]; - - if (!empty($subformRecords)) - { - $ucmSubFormData = array(); - - foreach ($subformRecords as $key => $subformRecord) - { - // Append file data to the ucmSubForm data - if (array_key_exists('tjFieldFileField', $extra_jform_data)) - { - if (isset($extra_jform_data['tjFieldFileField'][$ucmSubFormField->name][$key])) - { - $subformRecord['tjFieldFileField'] = $extra_jform_data['tjFieldFileField'][$ucmSubFormField->name][$key]; - } - } - - $subformRecord = array_filter($subformRecord); - - if (!empty($subformRecord)) - { - // Add ucmSubFormFieldName in the data to pass data to JS - $subformRecord['ucmSubformFieldName'] = $ucmSubFormField->name; - - $ucmSubFormData[] = $subformRecord; - } - } - - if (!empty($ucmSubFormData)) - { - $ucmSubFormFieldParams = json_decode($ucmSubFormField->params); - $ucmSubFormFormSource = explode('/', $ucmSubFormFieldParams->formsource); - $ucmSubFormClient = $ucmSubFormFormSource[1] . '.' . str_replace('form_extra.xml', '', $ucmSubFormFormSource[4]); - $ucmSubFormDataSet[$ucmSubFormClient] = $ucmSubFormData; - $extra_jform_data[$ucmSubFormField->name] = $ucmSubFormClient; - } - } - } - - // Remove empty records - $ucmSubFormDataSet = array_filter($ucmSubFormDataSet); - - return $ucmSubFormDataSet; - } - - /** - * Function to save ucmSubForm records - * - * @param ARRAY &$validData Parent record data - * @param ARRAY $ucmSubFormDataSet ucmSubForm records data - * - * @return ARRAY - */ - public function saveUcmSubFormRecords(&$validData, $ucmSubFormDataSet) - { - $db = JFactory::getDbo(); - $subFormContentIds = array(); - - $isNew = empty($validData['id']) ? 1 : 0; - - // Delete removed subform details - if (!$isNew) - { - $query = $db->getQuery(true); - $query->select('id'); - $query->from($db->quoteName('#__tj_ucm_data')); - $query->where($db->quoteName('parent_id') . '=' . $validData['id']); - $db->setQuery($query); - $oldSubFormContentIds = $db->loadColumn(); - } - - JLoader::import('components.com_tjfields.tables.fieldsvalue', JPATH_ADMINISTRATOR); - JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/models'); - $tjUcmModelType = JModelLegacy::getInstance('Type', 'TjucmModel'); - - if (!empty($ucmSubFormDataSet)) - { - foreach ($ucmSubFormDataSet as $client => $ucmSubFormTypeData) - { - $validData['client'] = $client; - $validData['type_id'] = $tjUcmModelType->getTypeId($client); - - $clientDetail = explode('.', $client); - - // This is an extra field which is used to render the reference of the ucmsubform field on the form (used in case of edit) - $ucmSubformContentIdFieldName = $clientDetail[0] . '_' . $clientDetail[1] . '_' . 'contentid'; - - $count = 0; - - foreach ($ucmSubFormTypeData as $ucmSubFormData) - { - $validData['id'] = isset($ucmSubFormData[$ucmSubformContentIdFieldName]) ? (int) $ucmSubFormData[$ucmSubformContentIdFieldName] : 0; - - // Unset extra data - $sfFieldName = $ucmSubFormData['ucmSubformFieldName']; - unset($ucmSubFormData['ucmSubformFieldName']); - - $ucmSubformContentFieldElementId = 'jform[' . $sfFieldName . '][' . $sfFieldName . $count . '][' . $ucmSubformContentIdFieldName . ']'; - $count++; - - if ($insertedId = $this->save($validData, $ucmSubFormData)) - { - $validData['id'] = $insertedId; - $subFormContentIds[] = array('elementName' => $ucmSubformContentFieldElementId, 'content_id' => $insertedId); - - $ucmSubFormData[$ucmSubformContentIdFieldName] = $insertedId; - - // Get field id of contentid field - $fieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); - $fieldTable->load(array('name' => $ucmSubformContentIdFieldName)); - - // Add-Update the value of content id field in the fields value table - start - $fieldsValueTable = JTable::getInstance('Fieldsvalue', 'TjfieldsTable', array('dbo', $db)); - $fieldsValueTable->load(array('field_id' => $fieldTable->id, 'content_id' => $insertedId, 'client' => $validData['client'])); - - if (empty($fieldsValueTable->id)) - { - $fieldsValueTable->field_id = $fieldTable->id; - $fieldsValueTable->value = $fieldsValueTable->content_id = $insertedId; - $fieldsValueTable->client = $validData['client']; - } - - $fieldsValueTable->user_id = JFactory::getUser()->id; - $fieldsValueTable->store(); - - // Add-Update the value of content id field in the fields value table - end - } - } - } - } - - // Delete removed ucmSubForm record from the form - if (!empty($oldSubFormContentIds)) - { - foreach ($oldSubFormContentIds as $oldSubFormContentId) - { - if (array_search($oldSubFormContentId, array_column($subFormContentIds, 'content_id')) === false) - { - $this->delete($oldSubFormContentId); - } - } - } - - return $subFormContentIds; - } - /** * Function to save ucmSubForm records * @@ -1392,6 +844,11 @@ public function saveUcmSubFormRecords(&$validData, $ucmSubFormDataSet) */ public function getUcmSubFormFieldDataJson($parentRecordId, $efd) { + if (is_array($efd->value)) + { + $efd->value = $efd->value[0]; + } + $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('id'); @@ -1418,7 +875,53 @@ public function getUcmSubFormFieldDataJson($parentRecordId, $efd) foreach ($ucmSubFormFieldValues as $ucmSubFormFieldValue) { $ucmSubFormFieldName = $ucmSubFormFieldValue->name; - $subFormData->$ucmSubFormFieldName = $ucmSubFormFieldValue->value; + + $value = ''; + $temp = array(); + + switch ($ucmSubFormFieldValue->type) + { + case 'radio': + if (is_array($ucmSubFormFieldValue->value) || is_object($ucmSubFormFieldValue->value)) + { + if (isset($ucmSubFormFieldValue->value[0])) + { + $value = $ucmSubFormFieldValue->value[0]->value; + } + } + else + { + $value = $ucmSubFormFieldValue->value; + } + break; + case 'tjlist': + case 'related': + case 'multi_select': + + if (is_array($ucmSubFormFieldValue->value) || is_object($ucmSubFormFieldValue->value)) + { + foreach ($ucmSubFormFieldValue->value as $option) + { + $temp[] = $option->value; + } + + if (!empty($temp)) + { + $value = $temp; + } + } + else + { + $value = $ucmSubFormFieldValue->value; + } + + break; + + default: + $value = $ucmSubFormFieldValue->value; + } + + $subFormData->$ucmSubFormFieldName = $value; } $client = explode('.', $recordData['client']); @@ -1426,6 +929,16 @@ public function getUcmSubFormFieldDataJson($parentRecordId, $efd) $subFormData->$ucmSubformContentIdFieldName = $contentId; $concat = $efd->name . $key; + + // Check if any field has value for the subform entry and if there is no value in subform then dont show it + $subFormDataArray = (array) $subFormData; + unset($subFormDataArray[$ucmSubformContentIdFieldName]); + + if (empty($subFormDataArray)) + { + continue; + } + $ucmSubFormFieldData->$concat = $subFormData; } @@ -1435,7 +948,9 @@ public function getUcmSubFormFieldDataJson($parentRecordId, $efd) /** * Function to updated related field options * - * @param INT $contentId parent content id + * @param INT $client client + * + * @param INT $contentId Content id * * @return ARRAY */ @@ -1624,4 +1139,57 @@ public function getUdatedRelatedFieldOptions($client, $contentId) return $returnData; } + + /** + * Method to push data in queue. + * + * @param string $ucmId Ucm id + * @param string $sourceClient Source client + * @param array $targetClient Target client + * @param Object $userId User id who wants to copy item + * @param Object $clusterId Cluster id + * + * @return boolean value. + * + * @since __DEPLOY_VERSION__ + */ + public static function queueItemCopy($ucmId, $sourceClient, $targetClient, $userId, $clusterId=0) + { + $return = []; + + $messageBody = new stdClass; + $messageBody->ucmId = $ucmId; + $messageBody->sourceClient = $sourceClient; + $messageBody->targetClient = $targetClient; + $messageBody->userId = $userId; + + if ($clusterId) + { + $messageBody->clusterId = $clusterId; + } + + try + { + $TJQueueProduce = new TJQueueProduce; + + // Set message body + $TJQueueProduce->message->setBody(json_encode($messageBody)); + + // @Params client, value + $TJQueueProduce->message->setProperty('client', 'core.copyitem'); + $TJQueueProduce->produce(); + } + catch (Exception $e) + { + $return['success'] = 0; + $return['message'] = $e->getMessage(); + + return $return; + } + + $return['success'] = 1; + $return['message'] = ''; + + return $return; + } } diff --git a/src/components/com_tjucm/site/models/items.php b/src/components/com_tjucm/site/models/items.php index bcda4f90..33366386 100644 --- a/src/components/com_tjucm/site/models/items.php +++ b/src/components/com_tjucm/site/models/items.php @@ -13,6 +13,8 @@ jimport('joomla.application.component.modellist'); use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Table\Table; /** * Methods supporting a list of Tjucm records. @@ -21,8 +23,6 @@ */ class TjucmModelItems extends JModelList { - private $client; - /** * Constructor. * @@ -46,6 +46,9 @@ public function __construct($config = array()) ); } + $this->fields = array(); + $this->specialSortableFields = array(); + parent::__construct($config); } @@ -69,34 +72,31 @@ protected function populateState($ordering = "a.id", $direction = "DESC") $user = JFactory::getUser(); $db = JFactory::getDbo(); - // Load the filter state. - $search = $app->getUserStateFromRequest($this->context . '.filter.search', 'filter_search', '', 'STRING'); - $this->setState('filter.search', $search); - JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_tjucm/models'); $tjUcmModelType = JModelLegacy::getInstance('Type', 'TjucmModel'); - $typeId = $app->input->get('id', "", "INT"); + $typeId = $app->input->get('id', 0, "INT"); + $ucmType = $app->input->get('client', '', "STRING"); - JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_tjucm/tables'); - $typeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', $db)); - $typeTable->load(array('id' => $typeId)); - $ucmType = $typeTable->unique_identifier; + if (empty($typeId) || empty($ucmType)) + { + JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_tjucm/tables'); + $typeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', $db)); - // Set state for field filters - JLoader::import('components.com_tjfields.models.fields', JPATH_ADMINISTRATOR); - $fieldsModel = JModelLegacy::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); - $fieldsModel->setState('filter.client', $this->client); - $fieldsModel->setState('filter.filterable', 1); - $fields = $fieldsModel->getItems(); + if ($typeId && empty($ucmType)) + { + $typeTable->load(array('id' => $typeId)); + $ucmType = $typeTable->unique_identifier; + } - foreach ($fields as $field) - { - $filterValue = $app->getUserStateFromRequest($this->context . '.' . $field->name, $field->name, '', 'STRING'); - $this->setState('filter.field.' . $field->name, $filterValue); + if ($ucmType && empty($typeId)) + { + $typeTable->load(array('unique_identifier' => $ucmType)); + $typeId = $typeTable->id; + } } - if (empty($ucmType)) + if (empty($ucmType) && empty($typeId)) { // Get the active item $menuitem = $app->getMenu()->getActive(); @@ -106,45 +106,88 @@ protected function populateState($ordering = "a.id", $direction = "DESC") if (!empty($this->menuparams)) { - $this->ucm_type = $this->menuparams->get('ucm_type'); + $ucmTypeAlias = $this->menuparams->get('ucm_type'); - if (!empty($this->ucm_type)) + if (!empty($ucmTypeAlias)) { - $ucmType = 'com_tjucm.' . $this->ucm_type; + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $ucmTypeAlias)); + $ucmType = $ucmTypeTable->unique_identifier; + $typeId = $ucmTypeTable->id; } } } - if (empty($ucmType)) + // Load the filter state. + $search = $app->getUserStateFromRequest($this->context . '.' . $ucmType . '.filter.search', 'filter_search', '', 'STRING'); + $this->setState($ucmType . '.filter.search', $search); + + // Set state for field filters + JLoader::import('components.com_tjfields.models.fields', JPATH_ADMINISTRATOR); + $fieldsModel = JModelLegacy::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); + $fieldsModel->setState('filter.client', $ucmType); + $fieldsModel->setState('filter.filterable', 1); + $fields = $fieldsModel->getItems(); + + foreach ($fields as $field) { - // Get UCM type id from uniquue identifier - $ucmType = $app->input->get('client', '', 'STRING'); + $filterValue = $app->getUserStateFromRequest($this->context . '.' . $field->name, $field->name, '', 'STRING'); + $this->setState('filter.field.' . $field->name, $filterValue); } - if (empty($typeId)) + $clusterId = $app->getUserStateFromRequest($this->context . '.' . $ucmType . '.cluster', 'cluster'); + + if ($clusterId) { - $typeId = $tjUcmModelType->getTypeId($ucmType); + $this->setState($ucmType . '.filter.cluster_id', $clusterId); } - $clusterId = $app->getUserStateFromRequest($this->context . '.cluster', 'cluster'); + $categoryId = $app->getUserStateFromRequest($this->context . '.' . $ucmType . '.itemcategory', 'itemcategory'); - if ($clusterId) + if ($categoryId) { - $this->setState('filter.cluster_id', $clusterId); + $this->setState($ucmType . '.filter.category_id', $categoryId); } + $draft = $app->getUserStateFromRequest($this->context . '.draft', 'draft'); + $this->setState('filter.draft', $draft); + $this->setState('ucm.client', $ucmType); $this->setState("ucmType.id", $typeId); $createdBy = $app->input->get('created_by', "", "INT"); - $canView = $user->authorise('core.type.viewitem', 'com_tjucm.type.' . $typeId); + $this->setState("created_by", $createdBy); - if (!$canView) + if ($this->getUserStateFromRequest($this->context . $ucmType . '.filter.order', 'filter_order', '', 'string')) { - $createdBy = $user->id; + $ordering = $this->getUserStateFromRequest($this->context . $ucmType . '.filter.order', 'filter_order', '', 'string'); } - $this->setState("created_by", $createdBy); + if ($this->getUserStateFromRequest($this->context . $ucmType . '.filter.order_Dir', 'filter_order_Dir', '', 'string')) + { + $direction = $this->getUserStateFromRequest($this->context . $ucmType . '.filter.order_Dir', 'filter_order_Dir', '', 'string'); + } + + $fromDate = $this->getUserStateFromRequest($this->context . '.fromDate', 'fromDate', '', 'STRING'); + $toDate = $this->getUserStateFromRequest($this->context . '.toDate', 'toDate', '', 'STRING'); + + if (!empty($fromDate) || !empty($toDate)) + { + $fromDate = empty($fromDate) ? JFactory::getDate('now -1 month')->toSql() : JFactory::getDate($fromDate)->toSql(); + $toDate = empty($toDate) ? JFactory::getDate('now')->toSql() : JFactory::getDate($toDate)->toSql(); + + // If from date is less than to date then swipe the dates + if ($fromDate > $toDate) + { + $tmpDate = $fromDate; + $fromDate = $toDate; + $toDate = $tmpDate; + } + + $this->setState($ucmType . ".filter.fromDate", $fromDate); + $this->setState($ucmType . ".filter.toDate", $toDate); + } // List state information. parent::populateState($ordering, $direction); @@ -159,47 +202,62 @@ protected function populateState($ordering = "a.id", $direction = "DESC") */ protected function getListQuery() { - $this->fields = $this->getFields(); + // Call function to initialise fields lists + $this->getFields(); // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. - $query->select( - $this->getState( - 'list.select', 'DISTINCT ' . $db->quoteName('a.id') . ', ' - . $db->quoteName('a.state') . ', ' - . $db->quoteName('a.cluster_id') . ', ' - . $db->quoteName('a.created_by') - ) - ); + $query->select('a.*'); - $query->from($db->quoteName('#__tj_ucm_data', 'a')); + foreach ($this->fields as $fieldId => $field) + { + if ($field->type == 'number') + { + $query->select('CAST(MAX(CASE WHEN fv.field_id=' . $fieldId . ' THEN value END) AS SIGNED) `' . $fieldId . '`'); + } + else + { + $query->select('MAX(CASE WHEN fv.field_id=' . $fieldId . ' THEN value END) `' . $fieldId . '`'); + } + } - // Join over the users for the checked out user - $query->select($db->quoteName('uc.name', 'uEditor')); - $query->join("LEFT", $db->quoteName('#__users', 'uc') . ' ON (' . $db->quoteName('uc.id') . ' = ' . $db->quoteName('a.checked_out') . ')'); + $query->from($db->qn('#__tj_ucm_data', 'a')); - $this->client = $this->getState('ucm.client'); + // Join over fields value table + $query->join( + "LEFT", $db->qn('#__tjfields_fields_value', 'fv') . ' ON (' . $db->qn('fv.content_id') . ' = ' . $db->qn('a.id') . ')' + ); - if (!empty($this->client)) + $client = $this->getState('ucm.client'); + + if (!empty($client)) { - $query->where($db->quoteName('a.client') . ' = ' . $db->quote($db->escape($this->client))); + $query->where($db->qn('a.client') . ' = ' . $db->q($db->escape($client))); } - $ucmType = $this->getState('ucmType.id', '', 'INT'); + $ucmTypeId = $this->getState('ucmType.id', '', 'INT'); - if (!empty($ucmType)) + if (!empty($ucmTypeId)) { - $query->where($db->quoteName('a.type_id') . ' = ' . (INT) $ucmType); + $query->where($db->qn('a.type_id') . ' = ' . (INT) $ucmTypeId); } $createdBy = $this->getState('created_by', '', 'INT'); if (!empty($createdBy)) { - $query->where($db->quoteName('a.created_by') . ' = ' . (INT) $createdBy); + $query->where($db->qn('a.created_by') . ' = ' . (INT) $createdBy); + } + + // Filter for parent record + $parentId = $this->getState('parent_id'); + + if (is_numeric($parentId)) + { + $query->where($db->qn('a.parent_id') . ' = ' . $parentId); } // Show records belonging to users cluster if com_cluster is installed and enabled - start @@ -209,45 +267,61 @@ protected function getListQuery() { JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); $fieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); - $fieldTable->load(array('client' => $this->client, 'type' => 'cluster')); + $fieldTable->load(array('client' => $client, 'type' => 'cluster', 'state' => '1')); if ($fieldTable->id) { - JFormHelper::addFieldPath(JPATH_ADMINISTRATOR . '/components/com_tjfields/models/fields/'); - $cluster = JFormHelper::loadFieldType('cluster', false); - $clusterList = $cluster->getOptionsExternally(); + JLoader::import("/components/com_cluster/includes/cluster", JPATH_ADMINISTRATOR); + $clustersModel = ClusterFactory::model('Clusters', array('ignore_request' => true)); + $clusters = $clustersModel->getItems(); + $usersClusters = array(); - if (!empty($clusterList)) + if (!empty($clusters)) { - $usersClusters = array(); - - foreach ($clusterList as $clusterList) + foreach ($clusters as $clusterList) { - if (!empty($clusterList->value)) + if (!empty($clusterList->id)) { - $usersClusters[] = $clusterList->value; + if (TjucmAccess::canView($ucmTypeId, $clusterList->id)) + { + $usersClusters[] = $clusterList->id; + } } } } - $query->where($db->quoteName('a.cluster_id') . ' IN (' . implode(",", $usersClusters) . ')'); + // If cluster array empty then we set 0 in whereclause query + if (empty($usersClusters)) + { + $usersClusters[] = 0; + } + + $query->where($db->qn('a.cluster_id') . ' IN (' . implode(",", $usersClusters) . ')'); } } // Filter by published state - $published = $this->getState('filter.state'); + $published = $this->getState('filter.state', ''); if (is_numeric($published)) { - $query->where($db->quoteName('a.state') . ' = ' . (INT) $published); + $query->where($db->qn('a.state') . ' = ' . (INT) $published); } elseif ($published === '') { - $query->where(($db->quoteName('(a.state) ') . ' IN (0, 1)')); + $query->where(($db->qn('a.state') . ' IN (0, 1)')); + } + + // Filter by draft status + $draft = $this->getState('filter.draft'); + + if (in_array($draft, array('0', '1'))) + { + $query->where($db->qn('a.draft') . ' = ' . $draft); } // Search by content id - $search = $this->getState('filter.search'); + $search = $this->getState($client . '.filter.search'); if (!empty($search)) { @@ -255,96 +329,219 @@ protected function getListQuery() if (stripos($search, 'id:') === 0) { - $query->where($db->quoteName('a.id') . ' = ' . (int) str_replace('id:', '', $search)); + $query->where($db->qn('a.id') . ' = ' . (int) str_replace('id:', '', $search)); } } - // Search on fields data - $filteredItemIds = $this->filterContent(); + $fromDate = $this->getState($client . '.filter.fromDate'); + $toDate = $this->getState($client . '.filter.toDate'); - if (is_array($filteredItemIds)) + if (!empty($fromDate) || !empty($toDate)) { - if (!empty($filteredItemIds)) - { - $filteredItemIds = implode(',', $filteredItemIds); - $query->where($db->quoteName('a.id') . ' IN (' . $filteredItemIds . ')'); - } - else - { - // If no search results found then do not return any record - $query->where($db->quoteName('a.id') . '=0'); - } + $query->where('DATE(' . $db->qn('a.created_date') . ') ' . ' BETWEEN ' . $db->q($fromDate) . ' AND ' . $db->q($toDate)); } + // Search on fields data + $this->filterContent($client, $query); + // Filter by cluster - $clusterId = (int) $this->getState('filter.cluster_id'); + $clusterId = (int) $this->getState($client . '.filter.cluster_id'); if ($clusterId) { - $query->where($db->quoteName('a.cluster_id') . ' = ' . $clusterId); + $query->where($db->qn('a.cluster_id') . ' = ' . $clusterId); } + // Filter by category + $categoryId = (int) $this->getState($client . '.filter.category_id'); + + if ($categoryId) + { + $query->where($db->qn('a.category_id') . ' = ' . $categoryId); + } + + $query->group($db->qn('a.id')); + + // Sort data + $this->sortContent($query); + + return $query; + } + + /** + * Get list items + * + * @return ARRAY + * + * @since 1.6 + */ + public function getItems() + { + $items = parent::getItems(); + + // Get id of multi-select fields + $contentIds = array_column($items, 'id'); + $client = $this->getState('ucm.client'); + + if (!empty($contentIds) && !empty($client)) + { + // Get fields which can have multiple values + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->qn('id')); + $query->from($db->qn('#__tjfields_fields')); + $query->where($db->qn('client') . ' = ' . $db->q($client)); + $query->where('(' . $db->qn('params') . ' LIKE ' . $db->q('%multiple":"true%') . ' OR ' . $db->qn('params') . ' LIKE ' . $db->q('%multiple":"1%') . ')'); + $db->setQuery($query); + $fieldsList = $db->loadColumn(); + + if (!empty($fieldsList)) + { + // Get fields which can have multiple values + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->qn(array('content_id', 'field_id', 'value'))); + $query->from($db->qn('#__tjfields_fields_value')); + $query->where($db->qn('content_id') . ' IN(' . implode(', ', $contentIds) . ')'); + $query->where($db->qn('field_id') . ' IN(' . implode(', ', $fieldsList) . ')'); + $db->setQuery($query); + $multiSelectValues = $db->loadObjectList(); + + $mappedData = array(); + + foreach ($multiSelectValues as $multiSelectValue) + { + $mappedData[$multiSelectValue->content_id][$multiSelectValue->field_id][] = $multiSelectValue->value; + } + + foreach ($items as $k => &$item) + { + $item = (ARRAY) $item; + + foreach ($mappedData as $contentId => $mappedContentData) + { + if ($contentId == $item['id']) + { + foreach ($mappedContentData as $fieldId => $value) + { + $item[$fieldId] = $value; + } + + unset($mappedContentData[$contentId]); + } + } + + $item = (OBJECT) $item; + } + + } + } + + return $items; + } + + /** + * Function to sort content as per field values + * + * @param OBJECT &$query query object + * + * @return VOID + * + * @since 1.2.1 + */ + private function sortContent(&$query) + { + $db = JFactory::getDbo(); + // Add the list ordering clause. $orderCol = $this->state->get('list.ordering'); $orderDirn = $this->state->get('list.direction'); - if ($orderCol && $orderDirn) + if ($orderCol && $orderDirn && (!is_numeric($orderCol) || array_key_exists($orderCol, $this->fields))) { - $query->order($db->escape($orderCol . ' ' . $orderDirn)); - } + if ($this->specialSortableFields[$orderCol]->type == 'itemcategory') + { + $query->select($db->qn('c.title', 'itemcategorytitle')); - return $query; + // Join over category table + $query->join( + "LEFT", $db->qn('#__categories', 'c') . ' ON (' . $db->qn('a.category_id') . ' = ' . $db->qn('c.id') . ')' + ); + + $query->order($db->escape($db->qn('itemcategorytitle') . ' ' . $orderDirn)); + } + elseif ($this->specialSortableFields[$orderCol]->type == 'cluster') + { + $query->select($db->qn('cl.name', 'clustertitle')); + + // Join over cluster table + $query->join( + "LEFT", $db->qn('#__tj_clusters', 'cl') . ' ON (' . $db->qn('a.cluster_id') . ' = ' . $db->qn('cl.id') . ')' + ); + + $query->order($db->escape($db->qn('clustertitle') . ' ' . $orderDirn)); + } + elseif ($this->specialSortableFields[$orderCol]->type == 'ownership') + { + $query->select($db->qn('u.username', 'ownershiptitle')); + + // Join over user table + $query->join( + "LEFT", $db->qn('#__users', 'u') . ' ON (' . $db->qn('a.created_by') . ' = ' . $db->qn('u.id') . ')' + ); + + $query->order($db->escape($db->qn('ownershiptitle') . ' ' . $orderDirn)); + } + else + { + $query->order($db->escape($db->qn($orderCol) . ' ' . $orderDirn)); + } + } } /** * Function to filter content as per field values * - * @return Array Content Ids + * @param string $client Client + * + * @param OBJECT &$query query object + * + * @return VOID * * @since 1.2.1 */ - private function filterContent() + private function filterContent($client, &$query) { + $db = $this->getDbo(); + $subQuery = $db->getQuery(true); + $subQuery->select(1); + $subQuery->from($db->qn('#__tjfields_fields_value', 'v')); + // Flag to mark if field specific search is done from the search box $filterFieldFound = 0; - // Flag to mark if any filter is applied or not - $filterApplied = 0; - // Variable to store count of the self joins on the fields_value table $filterFieldsCount = 0; - // Apply search filter - $db = JFactory::getDbo(); - $query = $db->getQuery(true); - $query->select('fv1.content_id'); - $query->from($db->quoteName('#__tjfields_fields_value', 'fv1')); - $query->join('INNER', $db->qn('#__tjfields_fields', 'f') . ' ON (' . $db->qn('fv1.field_id') . ' = ' . $db->qn('f.id') . ')'); - $query->where($db->quoteName('f.state') . ' =1'); - $query->where($db->quoteName('f.client') . ' = ' . $db->quote($this->client)); - // Filter by field value - $search = $this->getState('filter.search'); + $search = $this->getState($client . '.filter.search'); if (!empty($this->fields) && (stripos($search, 'id:') !== 0)) { foreach ($this->fields as $fieldId => $field) { // For field specific search - if (stripos($search, $field . ':') === 0) + if (stripos($search, $field->label . ':') === 0) { $filterFieldsCount++; - if ($filterFieldsCount > 1) - { - $query->join('LEFT', $db->qn('#__tjfields_fields_value', 'fv' . $filterFieldsCount) . ' ON (' . $db->qn('fv' . ($filterFieldsCount-1).'.content_id') . ' = ' . $db->qn('fv'.$filterFieldsCount.'.content_id') . ')'); - } + $subQuery->join('LEFT', $db->qn('#__tjfields_fields_value', 'v' . $filterFieldsCount) . ' ON (' . $db->qn('v' . + '.content_id') . ' = ' . $db->qn('v' . $filterFieldsCount . '.content_id') . ')'); - $search = trim(str_replace($field . ':', '', $search)); - $query->where($db->qn('fv'.$filterFieldsCount.'.field_id') . ' = ' . $fieldId); - $query->where($db->qn('fv'.$filterFieldsCount.'.value') . ' LIKE ' . $db->q('%' . $search . '%')); + $search = trim(str_replace($field->label . ':', '', $search)); + $subQuery->where($db->qn('v' . $filterFieldsCount . '.field_id') . ' = ' . $fieldId); + $subQuery->where($db->qn('v' . $filterFieldsCount . '.value') . ' LIKE ' . $db->q('%' . $search . '%')); $filterFieldFound = 1; - $filterApplied = 1; break; } @@ -356,53 +553,55 @@ private function filterContent() { $filterFieldsCount++; - if ($filterFieldsCount > 1) - { - $query->join('LEFT', $db->qn('#__tjfields_fields_value', 'fv' . $filterFieldsCount) . ' ON (' . $db->qn('fv' . ($filterFieldsCount-1).'.content_id') . ' = ' . $db->qn('fv'.$filterFieldsCount.'.content_id') . ')'); - } - - $query->where($db->quoteName('fv'.$filterFieldsCount.'.value') . ' LIKE ' . $db->q('%' . $search . '%')); - $filterApplied = 1; - } + $subQuery->join('LEFT', $db->qn('#__tjfields_fields_value', 'v' . $filterFieldsCount) . ' ON (' . $db->qn('v' . + '.content_id') . ' = ' . $db->qn('v' . $filterFieldsCount . '.content_id') . ')'); + $subQuery->where($db->qn('v' . $filterFieldsCount . '.value') . ' LIKE ' . $db->q('%' . $search . '%')); + } // For filterable fields JLoader::import('components.com_tjfields.models.fields', JPATH_ADMINISTRATOR); $fieldsModel = JModelLegacy::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); - $fieldsModel->setState('filter.client', $this->client); + $fieldsModel->setState('filter.client', $client); $fieldsModel->setState('filter.filterable', 1); $fields = $fieldsModel->getItems(); foreach ($fields as $field) { $filterValue = $this->getState('filter.field.' . $field->name); + $filteroptionId = $this->getState('filter.field.' . $field->name . '.optionId'); - if ($filterValue != '') + if ($filterValue != '' || $filteroptionId) { $filterFieldsCount++; - if ($filterFieldsCount > 1) + $subQuery->join('LEFT', $db->qn('#__tjfields_fields_value', 'v' . $filterFieldsCount) . ' ON (' . $db->qn('v' . + '.content_id') . ' = ' . $db->qn('v' . $filterFieldsCount . '.content_id') . ')'); + $subQuery->where($db->qn('v' . $filterFieldsCount . '.field_id') . ' = ' . $field->id); + + if ($filteroptionId) { - $query->join('LEFT', $db->qn('#__tjfields_fields_value', 'fv' . $filterFieldsCount) . ' ON (' . $db->qn('fv' . ($filterFieldsCount-1).'.content_id') . ' = ' . $db->qn('fv'.$filterFieldsCount.'.content_id') . ')'); + // Check option id blank or null + if ($filteroptionId == 'other') + { + $subQuery->where('(' . $db->qn('v' . $filterFieldsCount . '.option_id') . + ' is null OR ' . $db->qn('v' . $filterFieldsCount . '.option_id') . ' = 0 )'); + } + else + { + $subQuery->where($db->qn('v' . $filterFieldsCount . '.option_id') . ' = ' . $db->q($filteroptionId)); + } + } + else + { + $subQuery->where($db->qn('v' . $filterFieldsCount . '.value') . ' = ' . $db->q($filterValue)); } - - $query->where($db->qn('fv'.$filterFieldsCount.'.field_id') . ' = ' . $field->id); - $query->where($db->qn('fv'.$filterFieldsCount.'.value') . ' = ' . $db->q($filterValue)); - $filterApplied = 1; } } - $query->setLimit($this->getState('list.limit')); - - // If there is any filter applied then only execute the query - if ($filterApplied) + if ($filterFieldsCount > 0) { - $db->setQuery($query); - - return $db->loadColumn(); - } - else - { - return false; + $subQuery->where($db->qn('v.content_id') . '=' . $db->qn('a.id')); + $query->where("EXISTS (" . $subQuery . ")"); } } @@ -418,108 +617,29 @@ public function getFields() $fieldsModel = JModelLegacy::getInstance('Fields', 'TjfieldsModel', array('ignore_request' => true)); $fieldsModel->setState('filter.showonlist', 1); $fieldsModel->setState('filter.state', 1); - $this->client = $this->getState('ucm.client'); + $fieldsModel->setState('filter.showonlist', 1); + $fieldsModel->setState('list.ordering', 'ordering'); + $fieldsModel->setState('list.direction', 'ASC'); + $client = $this->getState('ucm.client'); - if (!empty($this->client)) + if (!empty($client)) { - $fieldsModel->setState('filter.client', $this->client); + $fieldsModel->setState('filter.client', $client); } $items = $fieldsModel->getItems(); - $data = array(); - foreach ($items as $item) { - $data[$item->id] = $item->label; - } - - return $data; - } - - /** - * Get an array of data items - * - * @return mixed Array of data items on success, false on failure. - */ - public function getItems() - { - $typeId = $this->getState('ucmType.id'); - $createdBy = $this->getState('created_by', ''); - - JLoader::import('components.com_tjucm.models.item', JPATH_SITE); - $itemModel = new TjucmModelItem; - $canView = $itemModel->canView($typeId); - $user = JFactory::getUser(); - - // If user is not allowed to view the records and if the created_by is not the logged in user then do not show the records - if (!$canView) - { - if (!empty($createdBy) && $createdBy == $user->id) + if (in_array($item->type, array('itemcategory', 'cluster', 'ownership'))) { - $canView = true; + $this->specialSortableFields[$item->id] = $item; } - } - if (!$canView) - { - return false; + $this->fields[$item->id] = $item; } - $items = parent::getItems(); - $itemsArray = (array) $items; - $contentIds = array_column($itemsArray, 'id'); - $fieldValues = $this->getFieldsData($contentIds); - - foreach ($items as &$item) - { - $item->field_values = array(); - - foreach ($fieldValues as $key => &$fieldValue) - { - if ($item->id == $fieldValue->content_id) - { - if (isset($item->field_values[$fieldValue->field_id])) - { - if (is_array($item->field_values[$fieldValue->field_id])) - { - $item->field_values[$fieldValue->field_id] = array_merge($item->field_values[$fieldValue->field_id], array($fieldValue->value)); - } - else - { - $item->field_values[$fieldValue->field_id] = array_merge(array($item->field_values[$fieldValue->field_id]), array($fieldValue->value)); - } - } - else - { - $item->field_values[$fieldValue->field_id] = $fieldValue->value; - } - - unset($fieldValues[$key]); - } - } - } - - foreach ($items as &$item) - { - $fieldValues = array(); - - foreach ($this->fields as $fieldId => $fieldValue) - { - if (!array_key_exists($fieldId, $item->field_values)) - { - $fieldValues[$fieldId] = ""; - } - else - { - $fieldValues[$fieldId] = $item->field_values[$fieldId]; - } - } - - $item->field_values = $fieldValues; - } - - return $items; + return $this->fields; } /** @@ -543,7 +663,7 @@ private function getFieldsData($contentIds) $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('*'); - $query->from($db->quoteName('#__tjfields_fields_value', 'fv')); + $query->from($db->qn('#__tjfields_fields_value', 'fv')); $query->join('INNER', $db->qn('#__tjfields_fields', 'f') . ' ON (' . $db->qn('f.id') . ' = ' . $db->qn('fv.field_id') . ')'); $query->where($db->qn('f.state') . '=1'); $query->where($db->qn('fv.content_id') . ' IN (' . $contentIds . ')'); @@ -552,86 +672,6 @@ private function getFieldsData($contentIds) return $db->loadObjectList(); } - /** - * Overrides the default function to check Date fields format, identified by - * "_dateformat" suffix, and erases the field if it's not correct. - * - * @return void - */ - protected function loadFormData() - { - $app = JFactory::getApplication(); - $filters = $app->getUserState($this->context . '.filter', array()); - $error_dateformat = false; - - foreach ($filters as $key => $value) - { - if (strpos($key, '_dateformat') && !empty($value) && $this->isValidDate($value) == null) - { - $filters[$key] = ''; - $error_dateformat = true; - } - } - - if ($error_dateformat) - { - $app->enqueueMessage(JText::_("COM_TJUCM_SEARCH_FILTER_DATE_FORMAT"), "warning"); - $app->setUserState($this->context . '.filter', $filters); - } - - return parent::loadFormData(); - } - - /** - * Checks if a given date is valid and in a specified format (YYYY-MM-DD) - * - * @param string $date Date to be checked - * - * @return bool - */ - private function isValidDate($date) - { - $date = str_replace('/', '-', $date); - - return (date_create($date)) ? JFactory::getDate($date)->format("Y-m-d") : null; - } - - /** - * Method to getAliasFieldNameByView - * - * @param array $view An array of record primary keys. - * - * @return boolean True if successful, false if an error occurs. - * - * @since 12.2 - */ - public function getAliasFieldNameByView($view) - { - switch ($view) - { - case 'items': - return 'alias'; - break; - } - } - - /** - * Get an item by alias - * - * @param string $alias Alias string - * - * @return int Element id - */ - public function getItemIdByAlias($alias) - { - $db = JFactory::getDbo(); - $table = JTable::getInstance('type', 'TjucmTable', array('dbo', $db)); - - $table->load(array('alias' => $alias)); - - return $table->id; - } - /** * Check if there are fields to show in list view * @@ -645,10 +685,10 @@ public function showListCheck($client) { $db = JFactory::getDbo(); $query = $db->getQuery(true); - $query->select("count(" . $db->quoteName('id') . ")"); - $query->from($db->quoteName('#__tjfields_fields')); - $query->where($db->quoteName('client') . '=' . $db->quote($client)); - $query->where($db->quoteName('showonlist') . '=1'); + $query->select("count(" . $db->qn('id') . ")"); + $query->from($db->qn('#__tjfields_fields')); + $query->where($db->qn('client') . '=' . $db->q($client)); + $query->where($db->qn('showonlist') . '=1'); $db->setQuery($query); $result = $db->loadResult(); @@ -660,4 +700,50 @@ public function showListCheck($client) return false; } } + + /** + * Method to check the compatibility between ucm types + * + * @param string $client Client + * + * @return mixed + * + * @since __DEPLOY_VERSION__ + */ + public function canCopyToSameUcmType($client) + { + JLoader::import('components.com_tjucm.models.types', JPATH_ADMINISTRATOR); + $typesModel = BaseDatabaseModel::getInstance('Types', 'TjucmModel'); + $typesModel->setState('filter.state', 1); + $ucmTypes = $typesModel->getItems(); + + JLoader::import('components.com_tjucm.models.type', JPATH_ADMINISTRATOR); + $typeModel = BaseDatabaseModel::getInstance('Type', 'TjucmModel'); + + $checkUcmCompatability = false; + + foreach ($ucmTypes as $key => $type) + { + if ($client != $type->unique_identifier) + { + $result = $typeModel->getCompatibleUcmTypes($client, $type->unique_identifier); + + if ($result) + { + $checkUcmCompatability = true; + } + } + } + + JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); + $fieldTable = Table::getInstance('Field', 'TjfieldsTable', array('dbo', JFactory::getDbo())); + $fieldTable->load(array('client' => $client, 'type' => 'cluster', 'state' => '1')); + + if (!$checkUcmCompatability && !$fieldTable->id) + { + return true; + } + + return false; + } } diff --git a/src/components/com_tjucm/site/router.php b/src/components/com_tjucm/site/router.php index 0eb0898f..f1fc2a97 100644 --- a/src/components/com_tjucm/site/router.php +++ b/src/components/com_tjucm/site/router.php @@ -148,12 +148,15 @@ public function parse(&$segments) if ($count >= 1) { - $ucmTypeTable = Table::getInstance('Type', 'TjucmTable', array('dbo', $db)); - $ucmTypeTable->load(array('alias' => $segments[1])); - - if ($ucmTypeTable->id) + if (isset($segments[1])) { - $vars['client'] = $ucmTypeTable->unique_identifier; + $ucmTypeTable = Table::getInstance('Type', 'TjucmTable', array('dbo', $db)); + $ucmTypeTable->load(array('alias' => $segments[1])); + + if ($ucmTypeTable->id) + { + $vars['client'] = $ucmTypeTable->unique_identifier; + } } } diff --git a/src/components/com_tjucm/site/tjucm.php b/src/components/com_tjucm/site/tjucm.php index 3f7b4c4e..118757ed 100644 --- a/src/components/com_tjucm/site/tjucm.php +++ b/src/components/com_tjucm/site/tjucm.php @@ -16,6 +16,11 @@ JLoader::registerPrefix('Tjucm', JPATH_COMPONENT); JLoader::register('TjucmController', JPATH_COMPONENT . '/controller.php'); +// Load tj-fields language files +$lang = JFactory::getLanguage(); +$lang->load('com_tjfields', JPATH_ADMINISTRATOR); +$lang->load('com_tjfields', JPATH_SITE); + // Load backend helper $path = JPATH_ADMINISTRATOR . '/components/com_tjucm/helpers/tjucm.php'; @@ -29,33 +34,15 @@ JLoader::load('TjucmHelper'); } -// Load required JS files -//JLoader::import('media.com_tjucm.js.load_js', JPATH_SITE); -require_once JPATH_SITE . '/media/com_tjucm/js/load_js.php'; - -$path = JPATH_COMPONENT_ADMINISTRATOR . '/classes/' . 'funlist.php'; - -if (!class_exists('TjucmFunList')) -{ - // Require_once $path; - JLoader::register('TjucmFunList', $path); - JLoader::load('TjucmFunList'); -} - -// Load tjassets -jimport('joomla.filesystem.file'); -$tjStrapperPath = JPATH_SITE . '/media/techjoomla_strapper/tjstrapper.php'; - -if (JFile::exists($tjStrapperPath)) -{ - require_once $tjStrapperPath; - TjStrapper::loadTjAssets(); -} - JLoader::register('TjucmHelpersTjucm', JPATH_SITE . '/components/com_tjucm/helpers/tjucm.php'); JLoader::load('TjucmHelpersTjucm'); TjucmHelpersTjucm::getLanguageConstantForJs(); +// Initialise UCM +JLoader::register('TjucmAccess', JPATH_SITE . '/components/com_tjucm/includes/access.php'); +JLoader::register('TJUCM', JPATH_SITE . '/components/com_tjucm/includes/tjucm.php'); +TJUCM::init(); + // Execute the task. $controller = JControllerLegacy::getInstance('Tjucm'); diff --git a/src/components/com_tjucm/site/views/item/tmpl/default.php b/src/components/com_tjucm/site/views/item/tmpl/default.php index 00fc4663..a1e30e63 100644 --- a/src/components/com_tjucm/site/views/item/tmpl/default.php +++ b/src/components/com_tjucm/site/views/item/tmpl/default.php @@ -1,19 +1,33 @@ + * @package TJ-UCM + * @author TechJoomla * @copyright Copyright (c) 2009-2019 TechJoomla. All rights reserved. - * @license GNU General Public License version 2 or later; see LICENSE.txt + * @license GNU General Public License version 2 or later; see LICENSE.txt */ // No direct access defined('_JEXEC') or die; +/*To load language constant of js file*/ +JText::script('COM_TJUCM_DELETE_MESSAGE'); + $user = JFactory::getUser(); +$tjUcmFrontendHelper = new TjucmHelpersTjucm; if ($this->form_extra) { + if (isset($this->title)) + { + ?> + +
authorise('core.type.edititem', 'com_tjucm.type.' . $this->ucmTypeId)) || ($user->authorise('core.type.editownitem', 'com_tjucm.type.' . $this->ucmTypeId) && JFactory::getUser()->id == $this->item->created_by)) + if ((TjucmAccess::canEdit($this->ucmTypeId, $this->item->id)) || (TjucmAccess::canEditOwn($this->ucmTypeId, $this->item->id) && JFactory::getUser()->id == $this->item->created_by)) { $redirectURL = JRoute::_('index.php?option=com_tjucm&task=item.edit&id=' . $this->item->id . '&client=' . $this->client, false); ?> @@ -50,18 +64,22 @@ $deleteOwn = false; - if ($user->authorise('core.type.deleteownitem', 'com_tjucm.type.' . $this->ucmTypeId)) + if (TjucmAccess::canDeleteOwn($this->ucmTypeId, $this->item->id)) { $deleteOwn = (JFactory::getUser()->id == $this->item->created_by ? true : false); } - if ($user->authorise('core.type.deleteitem', 'com_tjucm.type.' . $this->ucmTypeId) || $deleteOwn) + if (TjucmAccess::canDelete($this->ucmTypeId, $this->item->id) || $deleteOwn) { $redirectURL = JRoute::_('index.php?option=com_tjucm&task=itemform.remove&id=' . $this->item->id . '&client=' . $this->client . "&" . JSession::getFormToken() . '=1', false); ?> - + client; + $itemId = $tjUcmFrontendHelper->getItemId($link); ?> +
-
+
\ No newline at end of file diff --git a/src/components/com_tjucm/site/views/item/view.html.php b/src/components/com_tjucm/site/views/item/view.html.php index 8cc78723..4921e994 100644 --- a/src/components/com_tjucm/site/views/item/view.html.php +++ b/src/components/com_tjucm/site/views/item/view.html.php @@ -41,6 +41,16 @@ public function display($tpl = null) { $app = JFactory::getApplication(); + if (!JFactory::getUser()->id) + { + $msg = JText::_('COM_TJUCM_LOGIN_MSG'); + + // Get current url. + $current = JUri::getInstance()->toString(); + $url = base64_encode($current); + JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_users&view=login&return=' . $url, false), $msg); + } + // Load tj-fields language file $lang = JFactory::getLanguage(); $lang->load('com_tjfields', JPATH_SITE); @@ -91,7 +101,10 @@ public function display($tpl = null) if (!empty($this->ucm_type)) { - $this->client = 'com_tjucm.' . $this->ucm_type; + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $this->ucm_type)); + $this->client = $ucmTypeTable->unique_identifier; } } } @@ -119,6 +132,7 @@ public function display($tpl = null) $typeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); $typeTable->load(array('unique_identifier' => $this->client)); $typeParams = json_decode($typeTable->params); + $this->title = $typeTable->title; if (isset($typeParams->details_layout) && !empty($typeParams->details_layout)) { diff --git a/src/components/com_tjucm/site/views/itemform/tmpl/default.php b/src/components/com_tjucm/site/views/itemform/tmpl/default.php index 89f2358d..744fe6db 100644 --- a/src/components/com_tjucm/site/views/itemform/tmpl/default.php +++ b/src/components/com_tjucm/site/views/itemform/tmpl/default.php @@ -10,38 +10,38 @@ // No direct access defined('_JEXEC') or die; -JHtml::_('behavior.keepalive'); -JHtml::_('behavior.tooltip'); -JHtml::_('behavior.formvalidation'); -JHtml::_('formbehavior.chosen', 'select'); -JHtml::_('jquery.token'); +use Joomla\CMS\HTML\HTMLHelper; -// Load admin language file -$lang = JFactory::getLanguage(); -$lang->load('com_tjucm', JPATH_SITE); -$doc = JFactory::getDocument(); -$doc->addScript(JUri::root() . 'administrator/components/com_tjucm/assets/js/jquery.form.js'); -$doc->addScript(JUri::root() . 'administrator/components/com_tjucm/assets/js/itemform.js'); -$doc->addScript(JUri::root() . 'administrator/components/com_tjfields/assets/js/tjfields.js'); -JHtml::_('stylesheet', 'administrator/components/com_tjucm/assets/css/tjucm.css'); +HTMLHelper::_('behavior.keepalive'); +HTMLHelper::_('behavior.tooltip'); +HTMLHelper::_('behavior.formvalidation'); +HTMLHelper::_('formbehavior.chosen', 'select'); +HTMLHelper::_('jquery.token'); /* - * Script to show alert box if form changes are made and user is closing/refreshing/navigating the tab - * without saving the content - */ -$doc->addScript(JUri::root() . 'administrator/components/com_tjucm/assets/js/jquery.are-you-sure.js'); +* Script to show alert box if form changes are made and user is closing/refreshing/navigating the tab +* without saving the content +*/ +HTMLHelper::script('media/com_tjucm/js/vendor/jquery/jquery.are-you-sure.js'); /* - * Script to show alert box if form changes are made and user is closing/refreshing/navigating the tab - * without saving the content on iphone|ipad|ipod|opera - */ -$doc->addScript(JUri::root() . 'administrator/components/com_tjucm/assets/js/ays-beforeunload-shim.js'); +* Script to show alert box if form changes are made and user is closing/refreshing/navigating the tab +* without saving the content on iphone|ipad|ipod|opera +*/ +HTMLHelper::script('media/com_tjucm/js/vendor/shim/ays-beforeunload-shim.js'); + +HTMLHelper::script('administrator/components/com_tjfields/assets/js/tjfields.js'); + +// Load admin language file +$lang = JFactory::getLanguage(); +$lang->load('com_tjucm', JPATH_SITE); $jinput = JFactory::getApplication(); $editRecordId = $jinput->input->get("id", '', 'INT'); $baseUrl = $jinput->input->server->get('REQUEST_URI', '', 'STRING'); $calledFrom = (strpos($baseUrl, 'administrator')) ? 'backend' : 'frontend'; $layout = ($calledFrom == 'frontend') ? 'default' : 'edit'; +$dynamicLayout = $this->setLayout($this->layout); $fieldsets_counter_deafult = 0; $setnavigation = false; @@ -116,17 +116,42 @@
form_extra) - { - ?> -
- loadTemplate('extrafields'); - ?> -
- form_extra) + { + if ($this->id != '0') + { + ?> + + + +
+ loadTemplate('extrafields'); + } + else + { + echo $this->loadTemplate('grid'); + } + ?> +
+ allow_draft_save)) - { - ?> - - - + + + + + allow_auto_save || $this->allow_draft_save) && $itemState) { ?> @@ -190,13 +215,20 @@ ?> " id="tjUcmSectionFinalSave" onclick="tjUcmItemForm.saveUcmFormData();" /> + " onclick="Joomla.submitbutton('itemform.cancel');" /> + +
+ +
- + + + diff --git a/src/components/com_tjucm/site/views/itemform/tmpl/default.xml b/src/components/com_tjucm/site/views/itemform/tmpl/default.xml index ec0402d1..9e725678 100644 --- a/src/components/com_tjucm/site/views/itemform/tmpl/default.xml +++ b/src/components/com_tjucm/site/views/itemform/tmpl/default.xml @@ -1,6 +1,6 @@ - + diff --git a/src/components/com_tjucm/site/views/itemform/tmpl/default_grid.php b/src/components/com_tjucm/site/views/itemform/tmpl/default_grid.php new file mode 100644 index 00000000..0ee9d6b6 --- /dev/null +++ b/src/components/com_tjucm/site/views/itemform/tmpl/default_grid.php @@ -0,0 +1,138 @@ + + * @package Com_Tjucm + * @author Techjoomla + * @copyright Copyright (c) 2009-2017 TechJoomla. All rights reserved. + * @license GNU General Public License version 2 or later. + */ + +// No direct access +defined('_JEXEC') or die; + +$fieldsets_counter = 0; +$layout = JFactory::getApplication()->input->get('layout'); + + +if ($this->form_extra) +{ + // Iterate through the normal form fieldsets and display each one + $fieldSets = $this->form_extra->getFieldsets(); + + foreach ($fieldSets as $fieldset) + { + if (count($fieldSets) > 1) + { + if ($fieldsets_counter == 0) + { + echo JHtml::_('bootstrap.startTabSet', 'tjucm_myTab'); + } + + $fieldsets_counter++; + + if (count($this->form_extra->getFieldset($fieldset->name))) + { + foreach ($this->form_extra->getFieldset($fieldset->name) as $field) + { + if (!$field->hidden) + { + $tabName = JFilterOutput::stringURLUnicodeSlug(trim($fieldset->name)); + echo JHtml::_("bootstrap.addTab", "tjucm_myTab", $tabName, $fieldset->name); + break; + } + } + } + } + ?> +
+ form_extra->getFieldset($fieldset->name) as $field) + { + if (!$field->hidden) + { + if($field->type=="Checkbox") + { + ?> +
+
+
+ label; ?> +
+
+ input; ?> +
+
+
+
+ label; ?> +
+
+ input; ?> +
+ type == 'File') + { + ?> + + +
+
+ +
+ 1) + { + if (count($this->form_extra->getFieldset($fieldset->name))) + { + foreach ($this->form_extra->getFieldset($fieldset->name) as $field) + { + if (!$field->hidden) + { + echo JHtml::_("bootstrap.endTab"); + break; + } + } + } + } + } + + if (count($fieldSets) > 1) + { + echo JHtml::_('bootstrap.endTabSet'); + } +} +else +{ + ?> +
+ +
+ + + + + + +
+ + +
+
+
diff --git a/src/components/com_tjucm/site/views/itemform/view.html.php b/src/components/com_tjucm/site/views/itemform/view.html.php index 693e3754..b7eb4b54 100644 --- a/src/components/com_tjucm/site/views/itemform/view.html.php +++ b/src/components/com_tjucm/site/views/itemform/view.html.php @@ -18,6 +18,7 @@ use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; +use Joomla\CMS\Component\ComponentHelper; /** * View to edit @@ -79,6 +80,15 @@ class TjucmViewItemform extends JViewLegacy */ protected $copyRecId; + /** + * The Title of view + * + * @var String + * + * @since 1.2.4 + */ + protected $title; + /** * Display the view * @@ -93,6 +103,17 @@ public function display($tpl = null) $app = Factory::getApplication(); $input = $app->input; $user = Factory::getUser(); + + if (!$user->id) + { + $msg = JText::_('COM_TJUCM_LOGIN_MSG'); + + // Get current url. + $current = JUri::getInstance()->toString(); + $url = base64_encode($current); + JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_users&view=login&return=' . $url, false), $msg); + } + $this->state = $this->get('State'); $this->id = $input->getInt('id', $input->getInt('content_id', 0)); @@ -115,6 +136,7 @@ public function display($tpl = null) if ($this->id && !$clusterId) { $input->set('cluster_id', $this->item->cluster_id); + $clusterId = $this->item->cluster_id; } // Get a copy record id @@ -155,7 +177,10 @@ public function display($tpl = null) if (!empty($this->ucm_type)) { - $this->client = 'com_tjucm.' . $this->ucm_type; + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $this->ucm_type)); + $this->client = $ucmTypeTable->unique_identifier; } } } @@ -167,6 +192,19 @@ public function display($tpl = null) return; } + if (empty($this->title)) + { + // Get the active item + $menuItem = $app->getMenu()->getActive(); + + // Get the params + $this->menuparams = $menuItem->params; + + if (!empty($this->menuparams)) + { + $this->title = $this->menuparams->get('ucm_type'); + } + } // Check the view access to the itemform (the model has already computed the values). if ($this->item->params->get('access-view') == false) @@ -183,6 +221,17 @@ public function display($tpl = null) $typeTable->load(array('unique_identifier' => $this->client)); $typeParams = json_decode($typeTable->params); + if ($this->item->id) + { + if (!TjucmAccess::canEdit($typeTable->id, $this->item->id) && !TjucmAccess::canEditOwn($typeTable->id, $this->item->id)) + { + $app->enqueueMessage(Text::_('JERROR_ALERTNOAUTHOR'), 'error'); + $app->setHeader('status', 403, true); + + return; + } + } + // Check if the UCM type is unpublished if ($typeTable->state == "0") { @@ -193,7 +242,7 @@ public function display($tpl = null) } // Set Layout to type view - $layout = isset($typeParams->layout) ? $typeParams->layout : ''; + $this->layout = isset($typeParams->layout) ? $typeParams->layout : ''; if (isset($typeParams->layout) && !empty($typeParams->layout)) { @@ -235,14 +284,13 @@ public function display($tpl = null) $this->allow_auto_save = (isset($typeParams->allow_auto_save) && empty($typeParams->allow_auto_save)) ? 0 : 1; $this->allow_draft_save = (isset($typeParams->allow_draft_save) && !empty($typeParams->allow_draft_save)) ? 1 : 0; + $this->allow_bit_rate = (isset($typeParams->bitrate_on) && !empty($typeParams->bitrate_on)) ? 1 : 0; + $this->allow_bit_rate_seconds = $typeParams->bitrate_seconds; // Check for errors. if (count($errors = $this->get('Errors'))) { - foreach ($errors as $error) - { - $app->enqueueMessage($error, 'error'); - } + $app->enqueueMessage(Text::_("COM_TJUCM_SOMETHING_WENT_WRONG"), 'error'); return false; } @@ -268,7 +316,7 @@ protected function _prepareDocument() { $app = Factory::getApplication(); $menus = $app->getMenu(); - $title = null; + $this->title = null; // Because the application sets a default page title, // we need to get it from the menu item itself @@ -283,22 +331,22 @@ protected function _prepareDocument() $this->params->def('page_heading', Text::_('COM_TJUCM_DEFAULT_PAGE_TITLE')); } - $title = $this->params->get('page_title', ''); + $this->title = $this->params->get('page_title', ''); - if (empty($title)) + if (empty($this->title)) { - $title = $app->get('sitename'); + $this->title = $app->get('sitename'); } elseif ($app->get('sitename_pagetitles', 0) == 1) { - $title = Text::sprintf('JPAGETITLE', $app->get('sitename'), $title); + $this->title = Text::sprintf('JPAGETITLE', $app->get('sitename'), $this->title); } elseif ($app->get('sitename_pagetitles', 0) == 2) { - $title = Text::sprintf('JPAGETITLE', $title, $app->get('sitename')); + $this->title = Text::sprintf('JPAGETITLE', $this->title, $app->get('sitename')); } - $this->document->setTitle($title); + $this->document->setTitle($this->title); if ($this->params->get('menu-meta_description')) { diff --git a/src/components/com_tjucm/site/views/items/tmpl/default.php b/src/components/com_tjucm/site/views/items/tmpl/default.php index 2db9ffdb..d1d0b39f 100644 --- a/src/components/com_tjucm/site/views/items/tmpl/default.php +++ b/src/components/com_tjucm/site/views/items/tmpl/default.php @@ -12,14 +12,28 @@ JHtml::addIncludePath(JPATH_COMPONENT . '/helpers/html'); JHtml::_('bootstrap.tooltip'); +JHtml::_('behavior.keepalive'); +JHtml::_('behavior.formvalidation'); JHtml::_('behavior.multiselect'); +JHtml::_('behavior.modal'); JHtml::_('formbehavior.chosen', 'select'); +JHtml::_('jquery.token'); + +$importItemsPopUpUrl = JUri::root() . '/index.php?option=com_tjucm&view=items&layout=importitems&tmpl=component&client=' . $this->client; +$copyItemPopupUrl = JUri::root() . 'index.php?option=com_tjucm&view=items&layout=copyitems&tmpl=component&client=' . $this->client; +JFactory::getDocument()->addScriptDeclaration(' + jQuery(document).ready(function(){ + jQuery("#adminForm #import-items").click(function() { + SqueezeBox.open("' . $importItemsPopUpUrl . '" ,{handler: "iframe", size: {x: window.innerWidth-250, y: window.innerHeight-150}}); + }); + }); +'); $user = JFactory::getUser(); $userId = $user->get('id'); $tjUcmFrontendHelper = new TjucmHelpersTjucm; -$listOrder = $this->state->get('list.ordering'); -$listDirn = $this->state->get('list.direction'); +$listOrder = $this->escape($this->state->get('list.ordering')); +$listDirn = $this->escape($this->state->get('list.direction')); $appendUrl = ''; $csrf = "&" . JSession::getFormToken() . '=1'; @@ -33,16 +47,118 @@ $appendUrl .= "&client=" . $this->client; } -$tmpListColumn = $this->listcolumn; -reset($tmpListColumn); -$firstListColumn = key($tmpListColumn); - $link = 'index.php?option=com_tjucm&view=items' . $appendUrl; $itemId = $tjUcmFrontendHelper->getItemId($link); $fieldsData = array(); + +JFactory::getDocument()->addScriptDeclaration(" + function copySameUcmTypeItem() + { + var afterCopyItem = function(error, response){ + jQuery('#item-form #tjucm_loader').hide(); + jQuery('html, body').animate({scrollTop: jQuery('#item-form #tjucm_loader').position().top}, 'slow'); + response = JSON.parse(response); + + sessionStorage.setItem('message', response.message); + if(response.data !== null) + { + window.parent.location.reload(); + sessionStorage.setItem('class', 'alert alert-success'); + } + else + { + sessionStorage.setItem('class', 'alert alert-danger'); + } + } + + var copyItemData = jQuery('#adminForm').serialize(); + + // Code to copy item to ucm type + com_tjucm.Services.Items.copyItem(copyItemData, afterCopyItem); + } +"); + +$statusColumnWidth = 0; + ?> -
- loadTemplate('filters'); ?> + + +
+ +
+items)) + { + ?> + loadTemplate('filters'); + ?> +
+ allowedToAdd) + { + ?> + + + + canImport) + { + ?> + + + + canCopyItem) + { + if ($this->canCopyToSameUcmType) + {?> + + + + + + + + JText::_('COM_TJUCM_COPY_ITEMS'), + ), + $this->loadTemplate('copyitems') + ); ?> + +
+
 
+
 
+
+
+ canCopyItem) { ?> + + + items[0]->state)) { ?> - + + - - listcolumn)) - { - JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_tjfields/tables'); - $tjFieldsFieldTable = JTable::getInstance('field', 'TjfieldsTable'); + if (!empty($this->ucmTypeParams->allow_draft_save) && $this->ucmTypeParams->allow_draft_save == 1) + { + $statusColumnWidth = 2; + ?> + + listcolumn as $fieldId => $col_name) { @@ -79,46 +206,38 @@ } else { + JTable::addIncludePath(JPATH_ROOT . '/administrator/components/com_tjfields/tables'); $tjFieldsFieldTable = JTable::getInstance('field', 'TjfieldsTable'); $tjFieldsFieldTable->load($fieldId); $fieldsData[$fieldId] = $tjFieldsFieldTable; } - ?> - - canEdit || $this->canDelete) - { + if (in_array($col_name->type, $this->sortableFields)) + { + ?> + + + + - - - - - - items)) - { - ?> - - - - - - + + + showList)) @@ -143,8 +262,21 @@ foreach ($this->items as $i => $item) { // Call the JLayout to render the fields in the details view - $layout = new JLayoutFile('list', JPATH_ROOT . '/components/com_tjucm/layouts/list'); - echo $layout->render(array('itemsData' => $item, 'created_by' => $this->created_by, 'client' => $this->client, 'xmlFormObject' => $formXml, 'ucmTypeId' => $this->ucmTypeId, 'fieldsData' => $fieldsData, 'formObject' => $formObject)); + $layout = new JLayoutFile('list.list', JPATH_ROOT . '/components/com_tjucm/'); + echo $layout->render( + array( + 'itemsData' => $item, + 'created_by' => $this->created_by, + 'client' => $this->client, + 'xmlFormObject' => $formXml, + 'ucmTypeId' => $this->ucmTypeId, + 'ucmTypeParams' => $this->ucmTypeParams, + 'fieldsData' => $fieldsData, + 'formObject' => $formObject, + 'statusColumnWidth' => $statusColumnWidth, + 'listcolumn' => $this->listcolumn + ) + ); } } else @@ -163,39 +295,50 @@ ?>
+ + + + + - - + + - - + label, ENT_COMPAT, 'UTF-8'), $fieldId, $listDirn, $listOrder); ?> + + label; ?> + +
- pagination->getListFooter(); ?> -
+
+items)) + { + echo $this->pagination->getPagesLinks(); + } +?> +
allowedToAdd) { ?> - - + + + - + -canDelete) -{ - ?> - - diff --git a/src/components/com_tjucm/site/views/items/tmpl/default_copyitems.php b/src/components/com_tjucm/site/views/items/tmpl/default_copyitems.php new file mode 100755 index 00000000..663ee83f --- /dev/null +++ b/src/components/com_tjucm/site/views/items/tmpl/default_copyitems.php @@ -0,0 +1,39 @@ + + * @copyright Copyright (c) 2009-2019 TechJoomla. All rights reserved. + * @license GNU General Public License version 2 or later; see LICENSE.txt + */ + +// No direct access +defined('_JEXEC') or die; + +use Joomla\CMS\Factory; +use Joomla\CMS\Language\Text; + +?> +
+ + +
+ diff --git a/src/components/com_tjucm/site/views/items/tmpl/default_filters.php b/src/components/com_tjucm/site/views/items/tmpl/default_filters.php index 769b7066..5dd97792 100644 --- a/src/components/com_tjucm/site/views/items/tmpl/default_filters.php +++ b/src/components/com_tjucm/site/views/items/tmpl/default_filters.php @@ -11,44 +11,144 @@ defined('_JEXEC') or die; use Joomla\CMS\Component\ComponentHelper; +use Joomla\Registry\Registry; + +$tmpListColumn = $this->listcolumn; +reset($tmpListColumn); +$firstListColumn = key($tmpListColumn); ?>
-
- - -
+
+ + +
+ enabled) { JLoader::import('components.com_tjfields.tables.field', JPATH_ADMINISTRATOR); $fieldTable = JTable::getInstance('Field', 'TjfieldsTable', array('dbo', $db)); - $fieldTable->load(array('client' => $this->client, 'type' => 'cluster')); + $fieldTable->load(array('client' => $this->client, 'type' => 'cluster', 'state' => '1')); if ($fieldTable->id) { - JFormHelper::addFieldPath(JPATH_ADMINISTRATOR . '/components/com_tjfields/models/fields/'); - $cluster = JFormHelper::loadFieldType('cluster', false); - $this->clusterList = $cluster->getOptionsExternally(); + JLoader::import("/components/com_subusers/includes/rbacl", JPATH_ADMINISTRATOR); + JLoader::import("/components/com_cluster/includes/cluster", JPATH_ADMINISTRATOR); + $clustersModel = ClusterFactory::model('Clusters', array('ignore_request' => true)); + $clusters = $clustersModel->getItems(); + + // Get list of clusters with data in UCM type + $db = JFactory::getDbo(); + $query = $db->getQuery(true); + $query->select($db->quoteName('cluster_id')); + $query->from($db->quoteName('#__tj_ucm_data')); + $query->where($db->quoteName('client') . '=' . $db->quote($this->client)); + $query->group($db->quoteName('cluster_id')); + $db->setQuery($query); + $clustersWithData = $db->loadColumn(); + + $usersClusters = array(); + + $clusterObj = new stdclass; + $clusterObj->text = JText::_("COM_TJFIELDS_OWNERSHIP_CLUSTER"); + $clusterObj->value = ""; + + $usersClusters[] = $clusterObj; + + if (!empty($clusters)) + { + foreach ($clusters as $clusterList) + { + if (RBACL::check(JFactory::getUser()->id, 'com_cluster', 'core.viewitem.' . $this->ucmTypeId, $clusterList->id) || RBACL::check(JFactory::getUser()->id, 'com_cluster', 'core.viewallitem.' . $this->ucmTypeId)) + { + if (!empty($clusterList->id)) + { + if (in_array($clusterList->id, $clustersWithData)) + { + $clusterObj = new stdclass; + $clusterObj->text = $clusterList->name; + $clusterObj->value = $clusterList->id; + + $usersClusters[] = $clusterObj; + } + } + } + } + } ?> load(array('client' => $this->client, 'type' => 'itemcategory', 'state' => '1')); + + if ($fieldTable->id) + { + $fieldParams = new Registry($fieldTable->params); + $stateFilter = $fieldParams->get('published', '1'); + + if (strpos($stateFilter, ',')) + { + $stateFilter = explode(',', $stateFilter); + } + else + { + $stateFilter = (ARRAY) $stateFilter; + } + + $selectCategory = new stdClass; + $selectCategory->value = ''; + $selectCategory->text = JText::_("COM_TJUCM_FILTER_SELECT_CATEGORY_LABEL"); + + $categoryOptions = JHtml::_('category.options', $this->client, $config = array('filter.published' => $stateFilter)); + $categoryOptions = array_merge(array($selectCategory), $categoryOptions); + ?> + + true)); $tjFieldsOptionsModel->setState('filter.field_id', $field->id); + $tjFieldsOptionsModel->setState('list.ordering', 'ordering'); + $tjFieldsOptionsModel->setState('list.direction', 'ASC'); + $options = $tjFieldsOptionsModel->getItems(); if (!empty($options)) @@ -73,7 +176,11 @@ ?>
-

\ No newline at end of file +

diff --git a/src/components/com_tjucm/site/views/items/tmpl/importitems.php b/src/components/com_tjucm/site/views/items/tmpl/importitems.php new file mode 100644 index 00000000..f420b43e --- /dev/null +++ b/src/components/com_tjucm/site/views/items/tmpl/importitems.php @@ -0,0 +1,95 @@ + + * @copyright Copyright (C) 2009 - 2019 Techjoomla. All rights reserved. + * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL + */ + +// No direct access +defined('_JEXEC') or die; + +use Joomla\CMS\HTML\HTMLHelper; +use Joomla\CMS\Factory; +use Joomla\CMS\Uri\Uri; +use Joomla\CMS\Language\Text; +use Joomla\CMS\Session\Session; + +HTMLHelper::_('bootstrap.tooltip'); + +Factory::getDocument()->addScriptDeclaration(' + jQuery(document).ready(function(){ + jQuery("#uploadForm #upload-submit").click(function() { + if (jQuery("#uploadForm #csv-file-upload").val() == "") + { + jQuery("#uploadForm #csv-file-upload").css("border-color", "red"); + + return false; + } + else + { + var tjUcmUploadFileName = jQuery("#uploadForm #csv-file-upload").val(); + var tjUcmUploadFileExtension = tjUcmUploadFileName.substr((tjUcmUploadFileName.lastIndexOf(".") +1)); + + if (tjUcmUploadFileExtension === "csv") + { + jQuery("#uploadForm #records-import-msg").show(); + jQuery("#uploadForm #upload-submit").attr("disabled", "disabled"); + jQuery("#uploadForm #csv-file-upload").css("border-color", ""); + document.getElementById("uploadForm").submit(); + } + else + { + jQuery("#uploadForm #csv-file-upload").css("border-color", "red"); + jQuery("#system-message-container").html(); + Joomla.renderMessages({"error":[Joomla.JText._("COM_TJUCM_ITEMS_INVALID_CSV_FILE")]}); + + return false; + } + } + + return false; + }); + }); +'); +?> +
+

+ +

+
+
+
+ + +
+
+
 
+ +
+
 
+
+ +
+
+
+ +
+
+ + + + +
diff --git a/src/components/com_tjucm/site/views/items/view.html.php b/src/components/com_tjucm/site/views/items/view.html.php index 6869b808..92c51550 100644 --- a/src/components/com_tjucm/site/views/items/view.html.php +++ b/src/components/com_tjucm/site/views/items/view.html.php @@ -38,15 +38,7 @@ class TjucmViewItems extends JViewLegacy protected $canCreate; - protected $canView; - - protected $canEdit; - - protected $canChange; - - protected $canEditOwn; - - protected $canDelete; + protected $canImport; protected $menuparams; @@ -56,6 +48,12 @@ class TjucmViewItems extends JViewLegacy protected $created_by; + protected $ucmTypeParams; + + protected $title; + + protected $draft; + /** * Display the view * @@ -70,6 +68,16 @@ public function display($tpl = null) $app = JFactory::getApplication(); $user = JFactory::getUser(); + if (!$user->id) + { + $msg = JText::_('COM_TJUCM_LOGIN_MSG'); + + // Get current url. + $current = JUri::getInstance()->toString(); + $url = base64_encode($current); + JFactory::getApplication()->redirect(JRoute::_('index.php?option=com_users&view=login&return=' . $url, false), $msg); + } + // Check the view access to the items. if (!$user->id) { @@ -88,13 +96,13 @@ public function display($tpl = null) $model = $this->getModel("Items"); $this->ucmTypeId = $id = $model->getState('ucmType.id'); $this->client = $model->getState('ucm.client'); - $this->canCreate = $user->authorise('core.type.createitem', 'com_tjucm.type.' . $this->ucmTypeId); - $this->canView = $user->authorise('core.type.viewitem', 'com_tjucm.type.' . $this->ucmTypeId); - $this->canEdit = $user->authorise('core.type.edititem', 'com_tjucm.type.' . $this->ucmTypeId); - $this->canChange = $user->authorise('core.type.edititemstate', 'com_tjucm.type.' . $this->ucmTypeId); - $this->canEditOwn = $user->authorise('core.type.editownitem', 'com_tjucm.type.' . $this->ucmTypeId); - $this->canDelete = $user->authorise('core.type.deleteitem', 'com_tjucm.type.' . $this->ucmTypeId); - $this->canDeleteOwn = $user->authorise('core.type.deleteownitem', 'com_tjucm.type.' . $this->ucmTypeId); + $this->canCreate = TjucmAccess::canCreate($this->ucmTypeId); + $this->canImport = TjucmAccess::canImport($this->ucmTypeId); + $this->draft = array("" => JText::_('COM_TJUCM_DATA_STATUS_SELECT_OPTION'), + "0" => JText::_("COM_TJUCM_DATA_STATUS_SAVE"), "1" => JText::_('COM_TJUCM_DATA_STATUS_DRAFT')); + $this->canCopyItem = $user->authorise('core.type.copyitem', 'com_tjucm.type.' . $this->ucmTypeId); + $this->canCopyToSameUcmType = $model->canCopyToSameUcmType($this->client); + $this->sortableFields = array('text', 'number', 'checkbox', 'textarea', 'textareacounter', 'calendar', 'email', 'radio', 'single_select', 'itemcategory', 'cluster', 'ownership'); // If did not get the client from url then get if from menu param if (empty($this->client)) @@ -111,11 +119,24 @@ public function display($tpl = null) if (!empty($this->ucm_type)) { - $this->client = 'com_tjucm.' . $this->ucm_type; + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('alias' => $this->ucm_type)); + $this->client = $ucmTypeTable->unique_identifier; + $this->title = $ucmTypeTable->title; } } } + // To get title of list as per the ucm type + if (!isset($this->title)) + { + JLoader::import('components.com_tjfields.tables.type', JPATH_ADMINISTRATOR); + $ucmTypeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); + $ucmTypeTable->load(array('unique_identifier' => $this->client)); + $this->title = $ucmTypeTable->title; + } + // If there are no fields column to show in list view then dont allow to show data $this->showList = $model->showListCheck($this->client); @@ -133,11 +154,11 @@ public function display($tpl = null) JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); $typeTable = JTable::getInstance('Type', 'TjucmTable', array('dbo', JFactory::getDbo())); $typeTable->load(array('unique_identifier' => $this->client)); - $typeParams = json_decode($typeTable->params); + $this->ucmTypeParams = json_decode($typeTable->params); - if (isset($typeParams->list_layout) && !empty($typeParams->list_layout)) + if (isset($this->ucmTypeParams->list_layout) && !empty($this->ucmTypeParams->list_layout)) { - $this->setLayout($typeParams->list_layout); + $this->setLayout($this->ucmTypeParams->list_layout); } $allowedCount = (!empty($typeTable->allowed_count))?$typeTable->allowed_count:'0'; @@ -151,11 +172,6 @@ public function display($tpl = null) } } - if ($this->created_by == $userId) - { - $this->canView = true; - } - // Check for errors. if (count($errors = $this->get('Errors'))) { diff --git a/src/components/com_tjucm/tjucm.xml b/src/components/com_tjucm/tjucm.xml index 6adf1a51..84b8bb21 100644 --- a/src/components/com_tjucm/tjucm.xml +++ b/src/components/com_tjucm/tjucm.xml @@ -6,8 +6,8 @@ Techjoomla extensions@techjoomla.com https://techjoomla.com - 25th Oct 2019 - 1.2.2 + 2nd Dec 2019 + 1.2.3 TJ-UCM - Universal Content Manager]]> script.php @@ -36,9 +36,12 @@ layouts controllers helpers + includes js + css + gif en-GB/en-GB.com_tjucm.ini @@ -53,7 +56,6 @@ tjucm.php controllers assets - classes helpers models houseKeeping diff --git a/src/objectrepository.properties b/src/objectrepository.properties new file mode 100644 index 00000000..cdfaa69f --- /dev/null +++ b/src/objectrepository.properties @@ -0,0 +1,134 @@ +#Screenshot config +takescreeshot_all=Y +takescreeshot_failure=Y +environment=live +release=3.2 +#Locators for login +username=#mod-login-username +password=#mod-login-password +Login=//button[@class='btn btn-primary btn-block btn-large login-button'] + +clickoncomponent=//a[contains(text(),'Components')] +SelectUCM=//a[contains(text(),'TJ - UCM')] +NewType=//div[@id='toolbar-new'] +ErrorMessage=//div[@class="alert alert-error alert-danger"] +Cancel=toolbar-cancel + +SearchBox= //input[@id='filter_search'] +SearchIcon=//button[@class='btn hasTooltip'] +Checkbox= //input[@name='checkall-toggle'] +Trash=//div[@id='toolbar-trash'] +Searchtool=//div[@class="btn-wrapper hidden-phone"] +SelectStatus=//*[@id="filter_state_chzn"] +SelectStatusTrash=//div[@id="filter_state_chzn"] +EmptyTrash=//div[@id='toolbar-delete'] +SelectAllcheckbox=//*[@id="typeList"]/thead/tr/th[2]/input +Clear=//button[contains(text(),'Clear')] + +newType=button[class='btn btn-small button-new btn-success'] +titlename=jform[title] +SaveNClose= toolbar-save + +Unpublished=toolbar-unpublish +Published=toolbar-publish +Trashed= toolbar-trash +SelectRecord=//input[@id='cb0'] +MessageContainer=//*[@id="system-message-container"]/div + +FieldGroup = //*[@id="typeList"]/tbody/tr[1]/td[7]/a[2] +NewButton=//*[@id="toolbar-new"]/button +EnterName=//*[@id="jform_name"] +SavenClose=//div[@id='toolbar-save'] + +GroupRecord=//*[@id="cb0"] +Cancel=toolbar-cancel + +FieldClick=//*[@id="typeList"]/tbody/tr/td[7]/a[3] +DropdownFields=//*[@id="jform_type_chzn"] +SelectList=//*[@id="jform_type_chzn"]/div/ul/li[4] +label=//*[@id="jform_label"] +name=//*[@id="jform_name"] +clickonType=//*[@id="submenu"] +TextData=//*[@id="jform_fieldoption__fieldoption0__name"] +ValueData=//*[@id="jform_fieldoption__fieldoption0__value"] +TextNextData=//*[@id="jform_fieldoption__fieldoption1__name"] +ValueNextData=//*[@id="jform_fieldoption__fieldoption1__value"] +ClickPlus=//tbody/tr[1]/td[4]/div[1]/a[1] + +Height=//*[@id="jform_params_height"] +width=//*[@id="jform_params_width"] +Autoplay =//fieldset[@id='jform_params_autoplay']/label[@class='btn active btn-danger'] +Muted=//fieldset[@id='jform_params_muted']/label[@class='btn active btn-danger'] + +StatusDropdown=//*[@id="jform_state_chzn"] +RequiredYes=//fieldset[@id='jform_required']//label[@class='btn'] +RequiredNo=//fieldset[@id='jform_required']//label[@class='btn active btn-danger'] +ReadOnlyYes=//fieldset[@id='jform_readonly']//label[@class='btn'] +ReadOnlyNo=//fieldset[@id='jform_readonly']//label[@class='btn active btn-danger'] +showOnListNo=//fieldset[@id='jform_showonlist']//label[@class='btn'] +showOnListYes=//fieldset[@id='jform_showonlist']//label[@class='btn active btn-success'] + +VideoHeight= //*[@id="jform_params_height"] +VideoWidth= //*[@id="jform_params_width"] +VideoLabel=//*[@id="jform_label"] +VideoName=//*[@id="jform_name"] +dropdownArrow=//*[@id="jform_type_chzn"]/a/div/b +Autoplay=//fieldset[@id='jform_params_autoplay']//label[@class='btn'] +DisplayStyle=//fieldset[@id='jform_params_display_video']//label[@class='btn'] +VimeoNo=//fieldset[@id='jform_params_vimeo']//label[2] +FacebookNo=//fieldset[@id='jform_params_Facebook']//label[@class='btn'] +TwitchNo=//fieldset[@id='jform_params_twitch']//label[@class='btn'] +DailyMotionNo=//fieldset[@id='jform_params_dailymotion']//label[@class='btn'] +soundcloudNo=//fieldset[@id='jform_params_soundcloud']/label[2] + +imageHeight=//*[@id="jform_params_height"] +imageWidth=//*[@id="jform_params_width"] +SizeUpload=//*[@id="jform_params_size"] + +OwnershipYes=//fieldset[@id="jform_params_ucmItemOwner"]//label[@class='btn'] +IsSubformYes=//fieldset[@id="jform_params_is_subform"]/label[@class='btn'] +SelectTypeforGroup=//*[@id="typeList"]/tbody/tr[2]/td[7]/a[3] +FormSource =//*[@id="jform_params_formsource_chzn"] + +MenuClick=//div[@class='nav-collapse collapse']//a[text()='Menus '] +AllMenu=//a[@class='no-dropdown menu-allmenu'][text()='All Menu Items'] +NewButton=//button[@class='btn btn-small button-new btn-success'] +MenuTitle=//input[@id='jform_title'] +MenuDropdown=//div[@id='jform_menutype_chzn'] +SelectedDropdown=//ul[@class='chzn-results']/li[text()='Main Menu'] + +SelectButton=//button[@class='btn btn-primary'] +iframe=Menu Item Type +SelectUcm=//a[contains(text(),'TJ - UCM')] +ItemForm=//*[@id="collapse11"]/div/ul/li[1] +items=//*[@id="collapse11"]/div/ul/li[2] +UCMConfig=//a[text()='UCM Config'] +SelectUCMType=//div[@id='jform_params_ucm_type_chzn'] + +selectMainMenu= + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/pkg_tjucm.xml b/src/pkg_tjucm.xml index b326c6a7..3073b049 100644 --- a/src/pkg_tjucm.xml +++ b/src/pkg_tjucm.xml @@ -6,13 +6,14 @@ TJUCM - Universal Content Manager Package Copyright (c) 2009-2019 Techjoomla. All rights reserved. http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL - 25th Oct 2019 + 2nd Dec 2019 ucm - 1.2.2 + 1.2.3 Techjoomla Team script.pkg_tjucm.php - - com_tjucm.zip - com_tjfields.zip + + components/com_tjucm.zip + components/com_tjfields.zip + plugins/actionlog/tjucm.zip diff --git a/src/plugins/actionlog/tjucm/index.html b/src/plugins/actionlog/tjucm/index.html new file mode 100644 index 00000000..2efb97f3 --- /dev/null +++ b/src/plugins/actionlog/tjucm/index.html @@ -0,0 +1 @@ + diff --git a/src/plugins/actionlog/tjucm/language/en-GB/en-GB.plg_actionlog_tjucm.ini b/src/plugins/actionlog/tjucm/language/en-GB/en-GB.plg_actionlog_tjucm.ini new file mode 100644 index 00000000..a4f8ceff --- /dev/null +++ b/src/plugins/actionlog/tjucm/language/en-GB/en-GB.plg_actionlog_tjucm.ini @@ -0,0 +1,39 @@ +; @package TJUCM +; @subpackage Actionlog.TJUCM +; @copyright Copyright (C) 2009 - 2018 Techjoomla. All rights reserved. +; @license GNU General Public License version 2 or later +; Note: All ini files need to be saved as UTF-8 + +PLG_ACTIONLOG_TJUCM="Action Log - TJUCM" +PLG_ACTIONLOG_TJUCM_XML_DESCRIPTION="Record the actions of users on the site for extension TJUCM so they can be reviewed if required." +PLG_ACTIONLOG_TJUCM_LOG_ACTION_TYPE_SAVE="Log action for type creation?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_TYPE_DELETE="Log action for type delete?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_TYPE_UPDATE="Log action for type update?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_TYPE_STATE_CHANGE="Log action for type state change?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_TYPE_IMPORT="Log action for type import?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_TYPE_EXPORT="Log action for type Export?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_TYPE_TRASH="Log action for type Trash?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_ITEM_DELETE="Log action for item delete?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_ITEM_SAVE="Log action for item creation?" +PLG_ACTIONLOG_TJUCM_LOG_ACTION_ITEM_DATA_SAVE="Log action for item data add/update?" + +PLG_ACTIONLOG_TJUCM_TYPE_ADDED="{username} added a new UCM type {title} " +PLG_ACTIONLOG_TJUCM_TYPE_UPDATED="{username} updated the UCM type {title} " +PLG_ACTIONLOG_TJUCM_TYPE_DELETED="{username} deleted the UCM type \"{title}\"" +PLG_ACTIONLOGS_TJUCM_TYPE_UNPUBLISHED="{username} unpublished the UCM type {title} " +PLG_ACTIONLOGS_TJUCM_TYPE_PUBLISHED="{username} published the UCM type {title} " +PLG_ACTIONLOGS_TJUCM_TYPE_ARCHIVED="{username} archived the UCM type {title} of client \"{identifier}\"" +PLG_ACTIONLOGS_TJUCM_TYPE_TRASHED="{username} trashed the UCM type {title}" +PLG_ACTIONLOG_TJUCM_TYPE_EXPORTED="{username} exported the UCM type {title}" +PLG_ACTIONLOG_TJUCM_TYPE_IMPORTED="{username} imported the UCM type {title}" + +PLG_ACTIONLOG_TJUCM_ITEM_DELETED="{username} has deleted a record from {title}" +PLG_ACTIONLOG_TJUCM_ITEM_ADDED="{username} has added a record in {title}" +PLG_ACTIONLOG_TJUCM_ITEM_DATA_ADDED="{username} has added a record in {title}" +PLG_ACTIONLOG_TJUCM_ITEM_DATA_EDIT="{username} has updated a record in {title}" +PLG_ACTIONLOG_TJUCM_CLUSTER_ITEM_DATA_EDIT="{username} from {cluster_title} has updated a record in {title}" +PLG_ACTIONLOG_TJUCM_CLUSTER_ITEM_DATA_ADDED="{username} from {cluster_title} has added a record in {title}" +PLG_ACTIONLOG_TJUCM_CLUSTER_ITEM_DELETED="{username} from {cluster_title} has deleted a record from {title}" +PLG_ACTIONLOG_TJUCM_OTHER_CLUSTER_ITEM_DATA_EDIT="{username} from {cluster_title} has updated a record in {title} for {owner_cluster_title}" +PLG_ACTIONLOG_TJUCM_OTHER_CLUSTER_ITEM_DATA_ADDED="{username} from {cluster_title} has added a record in {title} for {owner_cluster_title}" +PLG_ACTIONLOG_TJUCM_OTHER_CLUSTER_ITEM_DELETED="{username} from {cluster_title} has deleted a record from {title} for {owner_cluster_title}" diff --git a/src/plugins/actionlog/tjucm/language/en-GB/en-GB.plg_actionlog_tjucm.sys.ini b/src/plugins/actionlog/tjucm/language/en-GB/en-GB.plg_actionlog_tjucm.sys.ini new file mode 100644 index 00000000..faa6bead --- /dev/null +++ b/src/plugins/actionlog/tjucm/language/en-GB/en-GB.plg_actionlog_tjucm.sys.ini @@ -0,0 +1,8 @@ +; @package TJUCM +; @subpackage Actionlog.TJUCM +; @copyright Copyright (C) 2009 - 2018 Techjoomla. All rights reserved. +; @license GNU General Public License version 2 or later +; Note: All ini files need to be saved as UTF-8 + +PLG_ACTIONLOG_TJUCM="Action Log - TJUCM" +PLG_ACTIONLOG_TJUCM_XML_DESCRIPTION="Record the actions of users on the site for extension TJUCM so they can be reviewed if required." \ No newline at end of file diff --git a/src/plugins/actionlog/tjucm/tjucm.php b/src/plugins/actionlog/tjucm/tjucm.php new file mode 100644 index 00000000..cd422570 --- /dev/null +++ b/src/plugins/actionlog/tjucm/tjucm.php @@ -0,0 +1,495 @@ + + * @copyright Copyright (c) 2009-2019 Techjoomla. All rights reserved. + * @license GNU General Public License version 2 or later. + */ + +// No direct access. +defined('_JEXEC') or die(); + +JLoader::register('ActionlogsHelper', JPATH_ADMINISTRATOR . '/components/com_actionlogs/helpers/actionlogs.php'); + +use Joomla\CMS\Component\ComponentHelper; +use Joomla\CMS\Plugin\CMSPlugin; +use Joomla\CMS\Factory; +use Joomla\CMS\MVC\Model\BaseDatabaseModel; +use Joomla\CMS\Table\Table; + +/** + * UCM Actions Logging Plugin. + * + * @since __DEPLOY__VERSION__ + */ +class PlgActionlogTjUcm extends CMSPlugin +{ + /** + * Application object. + * + * @var JApplicationCms + * @since __DEPLOY__VERSION__ + */ + protected $app; + + /** + * Database object. + * + * @var JDatabaseDriver + * @since __DEPLOY__VERSION__ + */ + protected $db; + + /** + * Load plugin language file automatically so that it can be used inside component + * + * @var boolean + * @since __DEPLOY__VERSION__ + */ + protected $autoloadLanguage = true; + + /** + * Proxy for ActionlogsModelUserlog addLog method + * + * This method adds a record to #__action_logs contains (message_language_key, message, date, context, user) + * + * @param array $messages The contents of the messages to be logged + * @param string $messageLanguageKey The language key of the message + * @param string $context The context of the content passed to the plugin + * @param int $userId ID of user perform the action, usually ID of current logged in user + * + * @return void + * + * @since __DEPLOY__VERSION__ + */ + protected function addLog($messages, $messageLanguageKey, $context, $userId = null) + { + JLoader::register('ActionlogsModelActionlog', JPATH_ADMINISTRATOR . '/components/com_actionlogs/models/actionlog.php'); + + $model = BaseDatabaseModel::getInstance('Actionlog', 'ActionlogsModel'); + $model->addLog($messages, $messageLanguageKey, $context, $userId); + } + + /** + * On saving UCM type data - logging method + * + * Method is called when ucm type is to be stored in the database. + * This method logs who created/edited any data of UCM type + * + * @param Array $type Holds the ucm type data + * @param Boolean $isNew True if a new type is stored. + * + * @return void + * + * @since __DEPLOY__VERSION__ + */ + public function tjUcmOnAfterTypeSave($type, $isNew) + { + if ($isNew) + { + if (!$this->params->get('logActionForTypeSave', 1)) + { + return; + } + + $messageLanguageKey = 'PLG_ACTIONLOG_TJUCM_TYPE_ADDED'; + $action = 'add'; + } + else + { + if (!$this->params->get('logActionForTypeUpdate', 1)) + { + return; + } + + $messageLanguageKey = 'PLG_ACTIONLOG_TJUCM_TYPE_UPDATED'; + $action = 'update'; + } + + $context = Factory::getApplication()->input->get('option'); + $user = Factory::getUser(); + + $message = array( + 'action' => $action, + 'id' => $type['typeId'], + 'title' => $type['title'], + 'userid' => $user->id, + 'username' => ucfirst($user->username), + 'accountlink' => 'index.php?option=com_users&task=user.edit&id=' . $user->id, + 'typelink' => 'index.php?option=com_tjucm&view=type&layout=edit&id=' . $type['typeId'], + ); + + $this->addLog(array($message), $messageLanguageKey, $context, $user->id); + } + + /** + * On deleting UCM type data - logging method + * + * Method is called after ucm type is deleted in the database. + * + * @param String $context com_tjucm + * @param Object $table Holds the coupon data. + * + * @return void + * + * @since __DEPLOY__VERSION__ + */ + public function tjUcmOnAfterTypeDelete($context, $table) + { + if (!$this->params->get('logActionForTypeDelete', 1)) + { + return; + } + + $context = Factory::getApplication()->input->get('option'); + $user = Factory::getUser(); + + $messageLanguageKey = 'PLG_ACTIONLOG_TJUCM_TYPE_DELETED'; + $message = array( + 'action' => 'delete', + 'id' => $table->id, + 'title' => $table->title, + 'identifier' => $table->unique_identifier, + 'userid' => $user->id, + 'username' => ucfirst($user->username), + 'accountlink' => 'index.php?option=com_users&task=user.edit&id=' . $user->id, + ); + + $this->addLog(array($message), $messageLanguageKey, $context, $user->id); + } + + /** + * On changing state of UCM Type - logging method + * + * Method is called after user data is stored in the database. + * This method logs who changed state of UCM type + * + * @param String $context com_tjucm + * @param Array $pks Holds array of primary key. + * @param Int $value Switch case value. + * + * @return void + * + * @since __DEPLOY__VERSION__ + */ + public function tjUcmOnAfterTypeChangeState($context, $pks, $value) + { + if (!$this->params->get('logActionForTypeStateChange', 1)) + { + return; + } + + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $tjucmTableType = Table::getInstance('type', 'TjucmTable', array()); + + $context = Factory::getApplication()->input->get('option'); + $jUser = Factory::getUser(); + $userId = $jUser->id; + $userName = ucfirst($jUser->username); + + switch ($value) + { + case 0: + $messageLanguageKey = 'PLG_ACTIONLOGS_TJUCM_TYPE_UNPUBLISHED'; + $action = 'unpublish'; + break; + case 1: + $messageLanguageKey = 'PLG_ACTIONLOGS_TJUCM_TYPE_PUBLISHED'; + $action = 'publish'; + break; + case 2: + $messageLanguageKey = 'PLG_ACTIONLOGS_TJUCM_TYPE_ARCHIVED'; + $action = 'archive'; + break; + case -2: + $messageLanguageKey = 'PLG_ACTIONLOGS_TJUCM_TYPE_TRASHED'; + $action = 'trash'; + break; + default: + $messageLanguageKey = ''; + $action = ''; + break; + } + + foreach ($pks as $pk) + { + $tjucmTableType->load(array('id' => $pk)); + + $message = array( + 'action' => $action, + 'id' => $tjucmTableType->id, + 'title' => $tjucmTableType->title, + 'identifier' => $tjucmTableType->unique_identifier, + 'itemlink' => 'index.php?option=com_tjucm&view=type&layout=edit&id=' . $tjucmTableType->id, + 'userid' => $userId, + 'username' => $userName, + 'accountlink' => 'index.php?option=com_users&task=user.edit&id=' . $userId, + ); + + $this->addLog(array($message), $messageLanguageKey, $context, $userId); + } + } + + /** + * On saving UCM item data - logging method + * + * Method is called when ucm item is to be stored in the database. + * This method logs who created/edited any data of UCM item + * + * @param Integer $item Holds the ucm item id + * + * @param Integer $isNew Flag to mark new records + * + * @return void + * + * @since __DEPLOY__VERSION__ + */ + public function tjucmOnAfterSaveItem($item, $isNew) + { + if (!$this->params->get('tjucmOnAfterSaveItem', 1)) + { + return; + } + + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $tjucmTableType = Table::getInstance('type', 'TjucmTable', array()); + $tjucmTableType->load(array('unique_identifier' => $item['client'])); + + $context = Factory::getApplication()->input->get('option'); + $user = Factory::getUser(); + + $messageLanguageKey = 'PLG_ACTIONLOG_TJUCM_ITEM_ADDED'; + $message = array( + 'action' => 'add', + 'id' => $item['id'], + 'title' => $tjucmTableType->title, + 'userid' => $user->id, + 'username' => ucfirst($user->username), + 'accountlink' => 'index.php?option=com_users&task=user.edit&id=' . $user->id, + ); + + $this->addLog(array($message), $messageLanguageKey, $context, $user->id); + } + + /** + * On saving UCM item data - logging method + * + * Method is called when ucm item is to be stored in the database. + * This method logs who created/edited any data of UCM item + * + * @param Integer $recordId Holds the ucm item id + * + * @param Integer $client UCM client + * + * @param Integer $data fields value + * + * @return void + * + * @since __DEPLOY__VERSION__ + */ + public function tjucmOnBeforeSaveItemData($recordId, $client, $data) + { + if (!$this->params->get('tjucmOnAfterSaveItemData', 1) || empty($recordId)) + { + return; + } + + $context = Factory::getApplication()->input->get('option'); + $user = Factory::getUser(); + + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $tjucmTableType = Table::getInstance('type', 'TjucmTable', array()); + $tjucmTableType->load(array('unique_identifier' => $client)); + + JLoader::import('components.com_tjfields.tables.fieldsvalue', JPATH_ADMINISTRATOR); + $fieldValue = Table::getInstance('FieldsValue', 'TjfieldsTable', array()); + $fieldValue->load(array('content_id' => $recordId, 'client' => $client)); + + $clusterId = ""; + $clusterTitle = ""; + $ownerClusterId = ""; + $ownerClusterTitle = ""; + + if (ComponentHelper::getComponent('com_cluster', true)->enabled) + { + $clusterField = str_replace(".", "_", $client) . '_clusterclusterid'; + + JLoader::import('components.com_cluster.models.clusteruser', JPATH_ADMINISTRATOR); + $clusterUserModel = JModelLegacy::getInstance('ClusterUser', 'ClusterModel'); + $usersClusters = $clusterUserModel->getUsersClusters($user->id); + + if ($data[$clusterField]) + { + $editingRecordOfOtherCluster = true; + + // Check if user belongs to the cluster who has created the record or not + foreach ($usersClusters as $usersCluster) + { + if ($usersCluster->cluster_id == $data[$clusterField]) + { + // If user is not part of cluster who owns the record then he is editing record on behalf or other cluster + $editingRecordOfOtherCluster = false; + + break; + } + } + + JLoader::import('components.com_cluster.tables.clusters', JPATH_ADMINISTRATOR); + $clusterTable = Table::getInstance('Clusters', 'ClusterTable', array()); + + if ($editingRecordOfOtherCluster) + { + $clusterTable->load($usersClusters[0]->cluster_id); + $clusterId = $usersClusters[0]->cluster_id; + $clusterTitle = $clusterTable->name; + + $clusterTable->load($data[$clusterField]); + $ownerClusterId = $data[$clusterField]; + $ownerClusterTitle = $clusterTable->name; + + $messageLanguageKey = ($fieldValue->id) ? 'PLG_ACTIONLOG_TJUCM_OTHER_CLUSTER_ITEM_DATA_EDIT' : 'PLG_ACTIONLOG_TJUCM_OTHER_CLUSTER_ITEM_DATA_ADDED'; + } + else + { + $clusterTable->load($data[$clusterField]); + $clusterId = $tjucmTableItem->cluster_id; + $clusterTitle = $clusterTable->name; + + $messageLanguageKey = ($fieldValue->id) ? 'PLG_ACTIONLOG_TJUCM_CLUSTER_ITEM_DATA_EDIT' : 'PLG_ACTIONLOG_TJUCM_CLUSTER_ITEM_DATA_ADDED'; + } + } + } + else + { + $messageLanguageKey = ($fieldValue->id) ? 'PLG_ACTIONLOG_TJUCM_ITEM_DATA_EDIT' : 'PLG_ACTIONLOG_TJUCM_ITEM_DATA_ADDED'; + } + + JLoader::import('components.com_tjucm.helpers.tjucm', JPATH_SITE); + $tjUcmFrontendHelper = new TjucmHelpersTjucm; + $link = 'index.php?option=com_tjucm&view=item&client=' . $client . '&id=' . $recordId; + $itemId = $tjUcmFrontendHelper->getItemId($link); + $link = JRoute::_($link . '&Itemid=' . $itemId, false); + + $message = array( + 'action' => 'add', + 'id' => $recordId, + 'title' => $tjucmTableType->title, + 'cluster_id' => $clusterId, + 'cluster_title' => $clusterTitle, + 'owner_cluster_id' => $ownerClusterId, + 'owner_cluster_title' => $ownerClusterTitle, + 'userid' => $user->id, + 'username' => ucfirst($user->name), + 'accountlink' => 'index.php?option=com_users&task=user.edit&id=' . $user->id, + 'item_link' => $link, + ); + + $this->addLog(array($message), $messageLanguageKey, $context, $user->id); + } + + /** + * On deleting UCM item data - logging method + * + * Method is called after ucm item is deleted in the database. + * + * @param Object $item Holds the item obj. + * + * @param Object $client UCM type + * + * @return void + * + * @since __DEPLOY__VERSION__ + */ + public function tjUcmOnBeforeDeleteItem($item, $client) + { + if (!$this->params->get('TjUcmOnAfterItemDelete', 1)) + { + return; + } + + JLoader::import('components.com_tjucm.tables.type', JPATH_ADMINISTRATOR); + $tjucmTableType = Table::getInstance('type', 'TjucmTable', array()); + $tjucmTableType->load(array('unique_identifier' => $client)); + + $context = Factory::getApplication()->input->get('option'); + $user = Factory::getUser(); + + $clusterId = ""; + $clusterTitle = ""; + $ownerClusterId = ""; + $ownerClusterTitle = ""; + + if (ComponentHelper::getComponent('com_cluster', true)->enabled) + { + JLoader::import('components.com_tjucm.tables.item', JPATH_ADMINISTRATOR); + $tjucmTableItem = Table::getInstance('Item', 'TjucmTable', array()); + $tjucmTableItem->load($item); + + JLoader::import('components.com_cluster.models.clusteruser', JPATH_ADMINISTRATOR); + $clusterUserModel = JModelLegacy::getInstance('ClusterUser', 'ClusterModel'); + $usersClusters = $clusterUserModel->getUsersClusters($user->id); + + $deletingRecordOfOtherCluster = true; + + // Check if user belongs to the cluster who has created the record or not + foreach ($usersClusters as $usersCluster) + { + if ($usersCluster->cluster_id == $tjucmTableItem->cluster_id) + { + // If user is not part of cluster who owns the record then he is editing record on behalf or other cluster + $deletingRecordOfOtherCluster = false; + + break; + } + } + + if ($tjucmTableItem->cluster_id) + { + JLoader::import('components.com_cluster.tables.clusters', JPATH_ADMINISTRATOR); + $clusterTable = Table::getInstance('Clusters', 'ClusterTable', array()); + + if ($deletingRecordOfOtherCluster) + { + $clusterTable->load($usersClusters[0]->cluster_id); + $clusterId = $usersClusters[0]->cluster_id; + $clusterTitle = $clusterTable->name; + + $clusterTable->load($tjucmTableItem->cluster_id); + $ownerClusterId = $tjucmTableItem->cluster_id; + $ownerClusterTitle = $clusterTable->name; + + $messageLanguageKey = 'PLG_ACTIONLOG_TJUCM_OTHER_CLUSTER_ITEM_DELETED'; + } + else + { + $clusterTable->load($tjucmTableItem->cluster_id); + $clusterId = $tjucmTableItem->cluster_id; + $clusterTitle = $clusterTable->name; + + $messageLanguageKey = 'PLG_ACTIONLOG_TJUCM_CLUSTER_ITEM_DELETED'; + } + } + } + else + { + $messageLanguageKey = 'PLG_ACTIONLOG_TJUCM_ITEM_DELETED'; + } + + $message = array( + 'action' => 'delete', + 'id' => $item, + 'title' => $tjucmTableType->title, + 'cluster_id' => $clusterId, + 'cluster_title' => $clusterTitle, + 'owner_cluster_id' => $ownerClusterId, + 'owner_cluster_title' => $ownerClusterTitle, + 'userid' => $user->id, + 'username' => ucfirst($user->name), + 'accountlink' => 'index.php?option=com_users&task=user.edit&id=' . $user->id, + ); + + $this->addLog(array($message), $messageLanguageKey, $context, $user->id); + } +} diff --git a/src/plugins/actionlog/tjucm/tjucm.xml b/src/plugins/actionlog/tjucm/tjucm.xml new file mode 100644 index 00000000..34c13553 --- /dev/null +++ b/src/plugins/actionlog/tjucm/tjucm.xml @@ -0,0 +1,54 @@ + + + plg_actionlog_tjucm + Techjoomla + 19th March 2020 + Copyright (C) 2009 - 2020 Techjoomla. All rights reserved. + http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL + extensions@techjoomla.com + https://techjoomla.com + 1.2.4 + PLG_ACTIONLOG_TJUCM_XML_DESCRIPTION + + tjucm.php + index.html + + + en-GB/en-GB.plg_actionlog_tjucm.ini + en-GB/en-GB.plg_actionlog_tjucm.sys.ini + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
diff --git a/src/components/com_tjucm/plugins/api/tjucm/tjucm.php b/src/plugins/api/tjucm/tjucm.php similarity index 100% rename from src/components/com_tjucm/plugins/api/tjucm/tjucm.php rename to src/plugins/api/tjucm/tjucm.php diff --git a/src/components/com_tjucm/plugins/api/tjucm/tjucm.xml b/src/plugins/api/tjucm/tjucm.xml similarity index 100% rename from src/components/com_tjucm/plugins/api/tjucm/tjucm.xml rename to src/plugins/api/tjucm/tjucm.xml diff --git a/src/components/com_tjucm/plugins/api/tjucm/tjucm/item.php b/src/plugins/api/tjucm/tjucm/item.php similarity index 100% rename from src/components/com_tjucm/plugins/api/tjucm/tjucm/item.php rename to src/plugins/api/tjucm/tjucm/item.php diff --git a/src/components/com_tjucm/plugins/api/tjucm/tjucm/type.php b/src/plugins/api/tjucm/tjucm/type.php similarity index 100% rename from src/components/com_tjucm/plugins/api/tjucm/tjucm/type.php rename to src/plugins/api/tjucm/tjucm/type.php