<?php
/*
* Copyright 2008 Blandware (http://www.blandware.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Actions for commodities.
*
* @package AtleapLite
* @author Roman Puchkovskiy
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
/**
*/
require_once "HTTP/Upload.php";
require_once "DB/DataObject/Cast.php";
require_once 'category.php';
// ~ DAO functions
/**
* Loads commodities from DB.
*
* @param array $queryInfo optional query info
* @see loadObjects()
* @return array objects
*/
function loadCommodities($queryInfo = array())
{
$params = $queryInfo['parameters'];
$queryInfo['fields']['category_id'] = $params['categoryId'];
return loadObjects('commodity', getCommodityDescriptor(), 'commoditiesGrid', $queryInfo);
}
/**
* Creates or updates a commodity.
*
* @param int $id ID of commodity to update (ignored when
* creating)
* @param int $categoryId ID of owning category
* @param object $form form object
* @param bool $create if true, commodity is created, else it's updated
* @param int $imageId optional ID of internal image to be assigned to this
* commodity
* @return bool|object false if failed or object
*/
function addOrUpdateCommodity($id, $categoryId, &$form, $create,
$imageId = null) {
global $maxImageWidth, $maxImageHeight, $maxAttributes;
if ($create) {
$dao =& getDao('commodity');
} else {
$dao =& staticGet('commodity', $id);
if (!$dao) {
// no such object
return false;
}
}
formToDao($form, $dao, getCommodityDescriptor());
$dao->category_id = $categoryId;
$deleteImage = false;
if (!$create) {
$deleteImage = $dao->hasImage() && $form->getElementValue('deleteImage');
}
if ($deleteImage) {
deleteInternalImage($dao->image_id);
$dao->image_id = 'null';
} else {
$upload = new HTTP_Upload();
$file = $upload->getFiles("image");
if ($file->isValid()) {
$name = $file->getProp('tmp_name');
$createImage = $create || !$dao->hasImage();
if ($createImage) {
$imageDao =& getDao('internal_image');
} else {
$imageDao =& staticGet('internal_image', $dao->image_id);
}
$resizeData = resizeImageFromFile($name);
$imageDao->data = $resizeData['data'];
$imageDao->type = $resizeData['type'];
$imageDao->width = $resizeData['width'];
$imageDao->height = $resizeData['height'];
$imageDao->data = DB_DataObject_Cast::blob($imageDao->data);
if ($createImage) {
$imageDao->insert();
$dao->image_id = $imageDao->id;
} else {
$imageDao->update();
}
} else if ($create && $imageId !== null) {
$imageDao =& getDao('internal_image');
$srcImage =& staticGet('internal_image', $imageId);
if ($srcImage->id !== null) {
$imageDao->data = $srcImage->data;
$imageDao->type = $srcImage->type;
$imageDao->width = $srcImage->width;
$imageDao->height = $srcImage->height;
$imageDao->data = DB_DataObject_Cast::blob($imageDao->data);
$imageDao->insert();
$dao->image_id = $imageDao->id;
}
}
}
if ($create) {
$dao->pos = getFreeCommodityPos($categoryId);
$dao->insert();
} else {
$dao->update();
}
// attributes
$dao->deleteAttributes();
$number = 0;
for ($i = 0; $i < $maxAttributes; $i++) {
$title = $form->getElementValue("attributeTitle[$i]");
$value = $form->getElementValue("attributeValue[$i]");
if (trim($title) != '') {
$attribute =& getDao('attribute');
$attribute->title = $title;
$attribute->value = $value;
$attribute->commodity_id = $dao->id;
$attribute->number = $number;
$attribute->insert();
$number++;
}
}
return $dao;
}
/**
* Returns position number which is not assigned to any commofity within given
* category.
*
* @param int $categoryId ID of category
*/
function getFreeCommodityPos($categoryId) {
$dao =& getDao('commodity');
return $dao->getFreePos($categoryId);
}
// ~ Actions
/**
* Allows to view commodity properties.
*/
function viewCommodity()
{
global $smarty, $bottomLinks, $maxImageWidth, $maxImageHeight;
$bottomLinks[] = array('link' => getCommodityListUrl('id'),
'text' => getMessage('common.button.ok'),
'permId' => 'listCommodities',
'button' => true);
$dao =& staticGet('commodity', $_GET['id']);
$smarty->assign('viewed', $dao);
$attributes = $dao->getAttributes();
$smarty->assign('attributes', $attributes);
$smarty->assign('attributesAreEmpty', count($attributes) == 0);
$smarty->assign('maxImageWidth', $maxImageWidth);
$smarty->assign('maxImageHeight', $maxImageHeight);
$smarty->assign('template', 'commodity/view.tpl');
$smarty->assign('title', getMessage('commodity.view.title'));
}
/**
* Displays a commodity to user.
*/
function showCommodity() {
global $smarty, $bottomLinks, $maxImageWidth, $maxImageHeight;
if (isset($_GET['id'])) {
$id = $_GET['id'];
$commodity =& staticGet('commodity', $id);
} else {
redirect(buildUrl(null, null, 'category'));
}
$attributes = $commodity->getAttributes();
$smarty->assign('commodity', $commodity);
$smarty->assign('attributes', $attributes);
$smarty->assign('attributesAreEmpty', count($attributes) == 0);
assignCategoryAncestors($smarty, $commodity->category_id);
$smarty->assign('maxImageWidth', $maxImageWidth);
$smarty->assign('maxImageHeight', $maxImageHeight);
$smarty->assign('template', 'commodity/show.tpl');
$smarty->assign('title', htmlspecialchars($commodity->title));
$smarty->setAdminLayout(false);
}
/**
* Creates a commodity form.
*
* @param string $name form name
* @param string $method HTTP method
* @param string $action action
* @param bool $create whether this is for for creation, not for updating
* @param bool $init whether form needs to be initialized from dao
* @param int $id optional commodity ID (for updating)
* @param int $rowsNumber here initial number of rows for attributes in form
* will be stored
* @param int $imageId here ID of image for this commodity will be stored,
* if updating and image exists
* @return object created form
*/
function &createCommodityForm($name, $method, $action, $create, $init,
$id = null, &$rowsNumber, &$imageId) {
global $maxAttributes, $initialAttributes;
// if ID is given, it's not just creation, but cloning
$idGiven = $id !== '' && $id !== null;
$params = array();
if ($idGiven) {
$params['id'] = $id;
}
$categoryId = fromGetOrSession('categoryId');
$params['categoryId'] = $categoryId;
$form = new FormBase($name, $method, buildUrl($action, $params));
$form->addTextElement('title', getMessage('commodity.form.title'));
$form->addTextElement('orderNumber', getMessage('commodity.form.orderNumber'));
$form->addFileElement('image', getMessage('commodity.form.image'));
$form->addRicheditElement('description', getMessage('commodity.form.description'));
$form->addProceedElement($create ? getMessage('common.button.create') : getMessage('common.button.update'));
$form->addCancelElement(getMessage('common.button.cancel'));
if (!$create || $idGiven) {
$dao = staticGet('commodity', $id);
if ((!$create || $idGiven) && $dao->hasImage()) {
$imageId = $dao->image_id;
}
if (!$create && $dao->hasImage()) {
$form->addCheckboxElement('deleteImage', getMessage('commodity.form.deleteImage'));
}
$attributes = $dao->getAttributes();
}
$rowsNumber = ($create && !$idGiven) ? $initialAttributes : max($initialAttributes, count($attributes));
$tabindex = 10;
for ($i = 0; $i < $maxAttributes; $i++) {
$form->addLivesearchElement("attributeTitle[$i]", '',
array('elementId' => 'search' . $i),
array('tabindex' => $tabindex++,
'onkeydown' => "liveHandleKeyDown(this, event, 'qattributeTitle[$i]Result', 'attributeValue[$i]');"));
$form->addTextElement("attributeValue[$i]", '', array('tabindex' => $tabindex++));
}
if (!$create && $init || $create && $init && $idGiven) {
daoToForm($dao, $form, getCommodityDescriptor());
$number = 0;
foreach ($attributes as $attribute) {
$titleElement =& $form->getElement("attributeTitle[$number]");
$valueElement =& $form->getElement("attributeValue[$number]");
$titleElement->setValue($attribute->title);
$valueElement->setValue($attribute->value);
$number++;
}
}
$form->addRequiredRule('title', getMessage('commodity.error.title.required'));
$form->addRequiredRule('orderNumber', getMessage('commodity.error.orderNumber.required'));
$form->addImageRule('image', getMessage('commodity.error.image.image'));
$form->addFormRule($create ? 'validateCreateCommodityForm' : 'validateUpdateCommodityForm');
return $form;
}
/**
* Shows a page with form to create a commodity.
*/
function callCreateCommodity()
{
global $smarty, $bottomLinks, $maxAttributes, $initialAttributes, $maxImageWidth, $maxImageHeight;
$categoryId = fromGetOrSession('categoryId');
if (!isset($categoryId)) {
redirect(getCategoryListUrl('id'));
}
setSystemMenuItemBold('manageCatalogue');
$rowsNumber;
$imageId = null;
$form =& createCommodityForm('createCommodity', 'POST', 'createCommodity', true, true, $_GET['id'], $rowsNumber, $imageId);
$smarty->assign('rowsNumber', $rowsNumber);
$smarty->assign('maxRowsNumber', $maxAttributes);
$smarty->assign('initialRowsNumber', $initialAttributes);
$smarty->assign('formName', 'createCommodity');
$smarty->assign('imageId', $imageId);
$smarty->assign('maxImageWidth', $maxImageWidth);
$smarty->assign('maxImageHeight', $maxImageHeight);
showForm($smarty, $form, 'commodity/createUpdate.tpl', getMessage('commodity.create.title'));
}
/**
* Creates a commodity.
*/
function createCommodity()
{
global $smarty, $bottomLinks, $maxAttributes, $initialAttributes, $maxImageWidth, $maxImageHeight;
if (isCancelled()) {
redirect(getCommodityListUrl('id'));
}
$categoryId = fromGetOrSession('categoryId');
if (!isset($categoryId)) {
redirect(getCategoryListUrl('id'));
}
setSystemMenuItemBold('manageCatalogue');
$rowsNumber;
$imageId = null;
$form =& createCommodityForm('createCommodity', 'POST', 'createCommodity', true, false, $_GET['id'], $rowsNumber, $imageId);
$smarty->assign('rowsNumber', $rowsNumber);
$smarty->assign('maxRowsNumber', $maxAttributes);
$smarty->assign('initialRowsNumber', $initialAttributes);
$smarty->assign('formName', 'createCommodity');
$smarty->assign('imageId', $imageId);
$smarty->assign('maxImageWidth', $maxImageWidth);
$smarty->assign('maxImageHeight', $maxImageHeight);
if ($form->validate()) {
addOrUpdateCommodity(null, $categoryId, $form, true, $imageId);
redirect(getCommodityListUrl());
} else {
showForm($smarty, $form, 'commodity/createUpdate.tpl', getMessage('commodity.create.title'));
}
}
/**
* Shows a page with form to update a commodity.
*/
function callUpdateCommodity()
{
global $smarty, $bottomLinks, $maxAttributes, $initialAttributes, $maxImageWidth, $maxImageHeight;
$categoryId = fromGetOrSession('categoryId');
if (!isset($categoryId)) {
redirect(getCategoryListUrl('id'));
}
setSystemMenuItemBold('manageCatalogue');
$rowsNumber;
$imageId = null;
$form =& createCommodityForm('updateCommodity', 'POST', 'updateCommodity', false, true, $_GET['id'], $rowsNumber, $imageId);
$smarty->assign('rowsNumber', $rowsNumber);
$smarty->assign('maxRowsNumber', $maxAttributes);
$smarty->assign('initialRowsNumber', $initialAttributes);
$smarty->assign('formName', 'createCommodity');
$smarty->assign('formName', 'updateCommodity');
$smarty->assign('imageId', $imageId);
$smarty->assign('maxImageWidth', $maxImageWidth);
$smarty->assign('maxImageHeight', $maxImageHeight);
showForm($smarty, $form, 'commodity/createUpdate.tpl', getMessage('commodity.update.title'));
}
/**
* Updates a commodity.
*/
function updateCommodity()
{
global $smarty, $bottomLinks, $maxAttributes, $initialAttributes, $maxImageWidth, $maxImageHeight;
if (isCancelled()) {
redirect(getCommodityListUrl('id'));
}
$categoryId = fromGetOrSession('categoryId');
if (!isset($categoryId)) {
redirect(getCategoryListUrl('id'));
}
setSystemMenuItemBold('manageCatalogue');
$rowsNumber;
$imageId = null;
$form =& createCommodityForm('updateCommodity', 'POST', 'updateCommodity', false, false, $_GET['id'], $rowsNumber, $imageId);
$smarty->assign('rowsNumber', $rowsNumber);
$smarty->assign('maxRowsNumber', $maxAttributes);
$smarty->assign('initialRowsNumber', $initialAttributes);
$smarty->assign('formName', 'updateCommodity');
$smarty->assign('imageId', $imageId);
$smarty->assign('maxImageWidth', $maxImageWidth);
$smarty->assign('maxImageHeight', $maxImageHeight);
if ($form->validate()) {
addOrUpdateCommodity($_GET['id'], $categoryId, $form, false);
redirect(getCommodityListUrl());
} else {
showForm($smarty, $form, 'commodity/createUpdate.tpl', getMessage('commodity.update.title'));
}
}
/**
* Validates a form which is used to create a commodity.
*
* @param array $fields assoc array from field names to values
* @return bool|array true if form is valid or assoc array with errors
*/
function validateCreateCommodityForm($fields) {
return validateCommodityForm($fields, true);
}
/**
* Validates a form which is used to update a commodity.
*
* @param array $fields assoc array from field names to values
* @return bool|array true if form is valid or assoc array with errors
*/
function validateUpdateCommodityForm($fields) {
return validateCommodityForm($fields, false);
}
/**
* Validates a commodity form.
*
* @param array $fields assoc array from field names to values
* @param bool $create whether this is creation form
* @return bool|array true if form is valid or assoc array with errors
*/
function validateCommodityForm($fields, $create)
{
$errors = array();
if (commodityHasDuplicatesByTitle($fields, $create, $_GET['categoryId'])) {
$errors['title'] = getMessage('commodity.error.duplicate.title');
}
if (commodityHasDuplicatesByOrderNumber($fields, $create)) {
$errors['orderNumber'] = getMessage('commodity.error.duplicate.orderNumber');
}
return count($errors) == 0 ? true : $errors;
}
/**
* Returns whether commodity has duplicates.
*
* @param array $fields assoc array from field names to values
* @param bool $create whether this is creation form being validated
* @param int $categoryId ID of category
* @return bool true if there are duplicates
*/
function commodityHasDuplicatesByTitle($fields, $create, $categoryId) {
$id = $_GET['id'];
$title = $fields['title'];
$dao =& getDao('commodity');
$escapedTitle = $dao->escape($title);
$dao->selectAdd();
$dao->selectAdd('count(*) as _c');
$dao->whereAdd();
$dao->whereAdd("(title = '$escapedTitle')");
$dao->whereAdd("(category_id = $categoryId)");
if (!$create) {
$dao->whereAdd("(id != $id)");
}
$dao->find(true);
return $dao->_c > 0;
}
/**
* Returns whether commodity has duplicates by order number.
*
* @param array $fields assoc array from field names to values
* @param bool $create whether this is creation form being validated
* @return bool true if there are duplicates
*/
function commodityHasDuplicatesByOrderNumber($fields, $create) {
$id = $_GET['id'];
$orderNumber = $fields['orderNumber'];
$dao =& getDao('commodity');
$escapedOrderNumber = $dao->escape($orderNumber);
$dao->selectAdd();
$dao->selectAdd('count(*) as _c');
$dao->whereAdd();
$dao->whereAdd("(order_number = '$escapedOrderNumber')");
if (!$create) {
$dao->whereAdd("(id != $id)");
}
$dao->find(true);
return $dao->_c > 0;
}
/**
* Moves a commodity up one position.
*/
function liftCommodity() {
$id = $_GET['id'];
$dao =& staticGet('commodity', $id);
if ($dao) {
$dao->tryLift();
}
redirect(getCommodityListUrl());
}
/**
* Moves a commodity down one position.
*/
function lowerCommodity() {
$id = $_GET['id'];
$dao =& staticGet('commodity', $id);
if ($dao) {
$dao->tryLower();
}
redirect(getCommodityListUrl());
}
/**
* Deletes a commodity.
*/
function deleteCommodity()
{
global $smarty, $bottomLinks;
setSystemMenuItemBold('manageCatalogue');
$dao =& staticGet('commodity', $_GET['id']);
if (tryDeleteCommodity($dao)) {
redirect(getCommodityListUrl());
} else {
$smarty->assign('template', 'error.tpl');
$smarty->assign('reason', getMessage('commodity.error.cannotDelete'));
$smarty->assign('link', getCommodityListUrl());
}
}
/**
* Deletes several commodities.
*/
function massDeleteCommodities()
{
if (isset($_GET['checked'])) {
foreach ($_GET['checked'] as $id => $on) {
$dao =& staticGet('commodity', $id);
tryDeleteCommodity($dao);
}
}
redirect(getCommodityListUrl());
}
/**
* Tryies to delete a commodity.
*
* @param object $dao object to delete
* @return true if deletion was successful
*/
function tryDeleteCommodity($dao) {
$result = $dao->deleteSubObjects();
if ($result) {
$result = $dao->delete();
}
return $result;
}
/**
* Returns URL to list of commodities.
*
* @param string $colon optional colon by which to sort
* @return URL
*/
function getCommodityListUrl($colon = null) {
if (empty($colon)) {
$colon = $_SESSION['sortColon'];
}
return buildUrl('viewCategory'/*, array('sortColon' => $colon)*/);
}
?>