diff --git a/Action/CommentAction.php b/Action/CommentAction.php new file mode 100644 index 0000000..0706928 --- /dev/null +++ b/Action/CommentAction.php @@ -0,0 +1,614 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Comment\Action; + +use Comment\Comment as CommentModule; +use Comment\Events\CommentAbuseEvent; +use Comment\Events\CommentChangeStatusEvent; +use Comment\Events\CommentCheckOrderEvent; +use Comment\Events\CommentComputeRatingEvent; +use Comment\Events\CommentCreateEvent; +use Comment\Events\CommentDefinitionEvent; +use Comment\Events\CommentDeleteEvent; +use Comment\Events\CommentEvents; +use Comment\Events\CommentReferenceGetterEvent; +use Comment\Events\CommentUpdateEvent; +use Comment\Exception\InvalidDefinitionException; +use Comment\Model\Comment; +use Comment\Model\CommentQuery; +use Comment\Model\Map\CommentTableMap; +use DateInterval; +use DateTime; +use Propel\Runtime\ActiveQuery\Criteria; +use Propel\Runtime\ActiveQuery\Join; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\Translation\TranslatorInterface; +use Thelia\Core\Template\ParserInterface; +use Thelia\Log\Tlog; +use Thelia\Mailer\MailerFactory; +use Thelia\Model\ConfigQuery; +use Thelia\Model\ContentQuery; +use Thelia\Model\CustomerQuery; +use Thelia\Model\Map\OrderProductTableMap; +use Thelia\Model\Map\OrderTableMap; +use Thelia\Model\Map\ProductSaleElementsTableMap; +use Thelia\Model\MessageQuery; +use Thelia\Model\MetaData; +use Thelia\Model\MetaDataQuery; +use Thelia\Model\OrderProductQuery; +use Thelia\Model\ProductQuery; +use Thelia\Tools\URL; + +/** + * + * CommentAction class where all actions are managed + * + * Class CommentAction + * @package Comment\Action + * @author Michaël Espeche + */ +class CommentAction implements EventSubscriberInterface +{ + /** @var null|TranslatorInterface */ + protected $translator = null; + + /** @var null|ParserInterface */ + protected $parser = null; + + /** @var null|MailerFactory */ + protected $mailer = null; + + public function __construct(TranslatorInterface $translator, ParserInterface $parser, MailerFactory $mailer) + { + $this->translator = $translator; + $this->parser = $parser; + $this->mailer = $mailer; + } + + public function create(CommentCreateEvent $event) + { + $comment = new Comment(); + + $comment + ->setRef($event->getRef()) + ->setRefId($event->getRefId()) + ->setCustomerId($event->getCustomerId()) + ->setUsername($event->getUsername()) + ->setEmail($event->getEmail()) + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->setContent($event->getContent()) + ->setStatus($event->getStatus()) + ->setVerified($event->isVerified()) + ->setRating($event->getRating()) + ->setAbuse($event->getAbuse()) + ->save(); + + $event->setComment($comment); + + if (Comment::ACCEPTED === $comment->getStatus()) { + $this->dispatchRatingCompute( + $event->getDispatcher(), + $comment->getRef(), + $comment->getRefId() + ); + } + } + + public function update(CommentUpdateEvent $event) + { + if (null !== $comment = CommentQuery::create()->findPk($event->getId())) { + $comment + ->setRef($event->getRef()) + ->setRefId($event->getRefId()) + ->setCustomerId($event->getCustomerId()) + ->setUsername($event->getUsername()) + ->setEmail($event->getEmail()) + ->setLocale($event->getLocale()) + ->setTitle($event->getTitle()) + ->setContent($event->getContent()) + ->setStatus($event->getStatus()) + ->setVerified($event->isVerified()) + ->setRating($event->getRating()) + ->setAbuse($event->getAbuse()) + ->save(); + $event->setComment($comment); + + $this->dispatchRatingCompute( + $event->getDispatcher(), + $comment->getRef(), + $comment->getRefId() + ); + } + } + + public function delete(CommentDeleteEvent $event) + { + if (null !== $comment = CommentQuery::create()->findPk($event->getId())) { + $comment->delete(); + + $event->setComment($comment); + + if (Comment::ACCEPTED === $comment->getStatus()) { + $this->dispatchRatingCompute( + $event->getDispatcher(), + $comment->getRef(), + $comment->getRefId() + ); + } + } + } + + public function abuse(CommentAbuseEvent $event) + { + if (null !== $comment = CommentQuery::create()->findPk($event->getId())) { + $comment->setAbuse($comment->getAbuse() + 1); + $comment->save(); + + $event->setComment($comment); + } + } + + public function statusChange(CommentChangeStatusEvent $event) + { + $changed = false; + + if (null !== $comment = CommentQuery::create()->findPk($event->getId())) { + if ($comment->getStatus() !== $event->getNewStatus()) { + $comment->setStatus($event->getNewStatus()); + $comment->save(); + + $event->setComment($comment); + + $this->dispatchRatingCompute( + $event->getDispatcher(), + $comment->getRef(), + $comment->getRefId() + ); + } + } + } + + public function productRatingCompute(CommentComputeRatingEvent $event) + { + if ('product' === $event->getRef()) { + + $product = ProductQuery::create()->findPk($event->getRefId()); + if (null !== $product) { + + $query = CommentQuery::create() + ->filterByRef('product') + ->filterByRefId($product->getId()) + ->filterByStatus(Comment::ACCEPTED) + ->withColumn("AVG(RATING)", 'AVG_RATING') + ->select('AVG_RATING'); + + $rating = $query->findOne(); + + if (null !== $rating) { + $rating = round($rating, 2); + + $event->setRating($rating); + + MetaDataQuery::setVal( + Comment::META_KEY_RATING, + MetaData::PRODUCT_KEY, + $product->getId(), + $rating + ); + } + } + } + } + + /** + * Dispatch an event to compute an average rating + * + * @param string $ref + * @param int $refId + */ + protected function dispatchRatingCompute($dispatcher, $ref, $refId) + { + $ratingEvent = new CommentComputeRatingEvent(); + + $ratingEvent + ->setRef($ref) + ->setRefId($refId); + + $dispatcher->dispatch( + CommentEvents::COMMENT_RATING_COMPUTE, + $ratingEvent + ); + } + + public function getRefrence(CommentReferenceGetterEvent $event) + { + if ('product' === $event->getRef()) { + $product = ProductQuery::create()->findPk($event->getRefId()); + if (null !== $product) { + $event->setTitle($product->getTitle()); + $event->setViewUrl($product->getUrl($event->getLocale())); + $event->setEditUrl( + URL::getInstance()->absoluteUrl( + '/admin/products/update', + ['product_id' => $product->getId()] + ) + ); + $event->setObject($product); + } + } elseif ('content' === $event->getRef()) { + $content = ContentQuery::create()->findPk($event->getRefId()); + if (null !== $content) { + $event->setTitle($content->getTitle()); + $event->setViewUrl($content->getUrl($event->getLocale())); + $event->setEditUrl( + URL::getInstance()->absoluteUrl( + '/admin/contents/update', + ['product_id' => $content->getId()] + ) + ); + $event->setObject($content); + } + } + } + + public function getDefinition(CommentDefinitionEvent $event) + { + $config = $event->getConfig(); + + if (!in_array($event->getRef(), $config['ref_allowed'])) { + throw new InvalidDefinitionException( + $this->translator->trans( + "Reference %ref is not allowed", + ['%ref' => $event->getRef()], + CommentModule::MESSAGE_DOMAIN + ) + ); + } + + $eventName = CommentEvents::COMMENT_GET_DEFINITION . "." . $event->getRef(); + $event->getDispatcher()->dispatch($eventName, $event); + + // is only customer is authorized to publish + if ($config['only_customer'] && null === $event->getCustomer()) { + throw new InvalidDefinitionException( + $this->translator->trans( + "Only customer are allowed to publish comment", + [], + CommentModule::MESSAGE_DOMAIN + ), + false + ); + } + + if (null !== $event->getCustomer()) { + // is customer already have published something + $comment = CommentQuery::create() + ->filterByCustomerId($event->getCustomer()->getId()) + ->filterByRef($event->getRef()) + ->filterByRefId($event->getRefId()) + ->findOne(); + + if (null !== $comment) { + $event->setComment($comment); + } + } + } + + + public function getProductDefinition(CommentDefinitionEvent $event) + { + $config = $event->getConfig(); + + $event->setRating(true); + + $product = ProductQuery::create()->findPk($event->getRefId()); + if (null === $product) { + throw new InvalidDefinitionException( + $this->translator->trans( + "Product %id does not exist", + ['%ref' => $event->getRef()], + CommentModule::MESSAGE_DOMAIN + ) + ); + } + + // is comment is authorized on this product + $commentProductActivated = MetaDataQuery::getVal( + Comment::META_KEY_ACTIVATED, + \Thelia\Model\MetaData::PRODUCT_KEY, + $product->getId() + ); + + // not defined, get the global config + if ("1" !== $commentProductActivated) { + if ("0" === $commentProductActivated || false === $config['activated']) { + throw new InvalidDefinitionException( + $this->translator->trans( + "Comment not activated on this element.", + ['%ref' => $event->getRef()], + CommentModule::MESSAGE_DOMAIN + ) + ); + } + } + + $verified = false; + if (null !== $event->getCustomer()) { + // customer has bought the product + $productBoughtCount = OrderProductQuery::getSaleStats( + $product->getRef(), + null, + null, + [2, 3, 4], + $event->getCustomer()->getId() + ); + + if ($config['only_verified']) { + if (0 === $productBoughtCount) { + throw new InvalidDefinitionException( + $this->translator->trans( + "Only customers who have bought this product can publish comment", + [], + CommentModule::MESSAGE_DOMAIN + ), + false + ); + } + } + + $verified = 0 !== $productBoughtCount; + } else { + $verified = false; + } + + $event->setVerified($verified); + } + + public function getContentDefinition(CommentDefinitionEvent $event) + { + $config = $event->getConfig(); + + $event->setVerified(true); + $event->setRating(false); + + // is comment is authorized on this product + $commentProductActivated = MetaDataQuery::getVal( + Comment::META_KEY_ACTIVATED, + \Thelia\Model\MetaData::CONTENT_KEY, + $event->getRefId() + ); + + // not defined, get the global config + if ("1" !== $commentProductActivated) { + if ("0" === $commentProductActivated || false === $config['activated']) { + throw new InvalidDefinitionException( + $this->translator->trans( + "Comment not activated on this element.", + ['%ref' => $event->getRef()], + CommentModule::MESSAGE_DOMAIN + ) + ); + } + } + } + + public function requestCustomerDemand(CommentCheckOrderEvent $event) + { + $config = \Comment\Comment::getConfig(); + $nbDays = $config["request_customer_ttl"]; + + if (0 !== $nbDays) { + + $endDate = new DateTime('NOW'); + $endDate->setTime(0, 0, 0); + $endDate->sub(new DateInterval('P' . $nbDays . 'D')); + + $startDate = clone $endDate; + $startDate->sub(new DateInterval('P1D')); + + + $pseJoin = new Join( + OrderProductTableMap::PRODUCT_SALE_ELEMENTS_ID, + ProductSaleElementsTableMap::ID, + Criteria::INNER_JOIN + ); + + $products = OrderProductQuery::create() + ->useOrderQuery() + ->filterByInvoiceDate($startDate, Criteria::GREATER_EQUAL) + ->filterByInvoiceDate($endDate, Criteria::LESS_THAN) + ->addAsColumn('customerId', OrderTableMap::CUSTOMER_ID) + ->addAsColumn('orderId', OrderTableMap::ID) + ->endUse() + ->addJoinObject($pseJoin) + ->addAsColumn('pseId', OrderProductTableMap::PRODUCT_SALE_ELEMENTS_ID) + ->addAsColumn('productId', ProductSaleElementsTableMap::PRODUCT_ID) + ->select( + [ + 'customerId', + 'orderId', + 'pseId', + 'productId' + ] + ) + ->find() + ->toArray(); + + if (empty($products)) { + return; + } + + $reduce = array_reduce( + $products, + function ($result, $item) { + + if (!array_key_exists($item['customerId'], $result)) { + $result[$item['customerId']] = []; + } + if (!in_array($item['productId'], $result[$item['customerId']])) { + $result[$item['customerId']][] = $item['productId']; + } + + return $result; + }, + [] + ); + + $customerIds = array_keys($reduce); + // check if comments already exists + $comments = CommentQuery::create() + ->filterByCustomerId($customerIds) + ->filterByRef(MetaData::PRODUCT_KEY) + ->addAsColumn('customerId', CommentTableMap::CUSTOMER_ID) + ->addAsColumn('productId', CommentTableMap::REF_ID) + ->select( + [ + 'customerId', + 'productId' + ] + ) + ->find() + ->toArray(); + + $commentReduce = array_reduce( + $comments, + function ($result, $item) { + + if (!array_key_exists($item['customerId'], $result)) { + $result[$item['customerId']] = []; + } + $result[$item['customerId']][] = $item['productId']; + + return $result; + }, + [] + ); + + foreach ($customerIds as $customerId) { + $send = false; + + if (!array_key_exists($customerId, $commentReduce)) { + $send = true; + } else { + if (empty(array_intersect($commentReduce[$customerId], $reduce[$customerId]))) { + // No commments + $send = true; + } + } + + if ($send) { + try { + $this->sendMail($customerId, $reduce[$customerId]); + } catch (\Exception $ex) { + Tlog::getInstance()->error($ex->getMessage()); + } + } + } + } + } + + protected function sendMail($customerId, array $productIds) + { + $contact_email = ConfigQuery::getStoreEmail(); + + if ($contact_email) { + $message = MessageQuery::create() + ->filterByName('comment_request_customer') + ->findOne(); + + if (null === $message) { + throw new \Exception("Failed to load message 'comment_request_customer'."); + } + + $customer = CustomerQuery::create()->findPk($customerId); + + if (null === $customer) { + throw new \Exception( + sprintf("Failed to load customer '%s'.", $customerId) + ); + } + + $parser = $this->parser; + + $locale = $customer->getCustomerLang()->getLocale(); + + $parser->assign('customer_id', $customer->getId()); + $parser->assign('product_ids', $productIds); + $parser->assign('lang_id', $customer->getCustomerLang()->getId()); + + $message->setLocale($locale); + + $instance = \Swift_Message::newInstance() + ->addTo($customer->getEmail(), $customer->getFirstname() . " " . $customer->getLastname()) + ->addFrom($contact_email, ConfigQuery::getStoreName()); + + // Build subject and body + $message->buildMessage($parser, $instance); + + $this->mailer->send($instance); + + Tlog::getInstance()->debug( + "Message sent to customer " . $customer->getEmail() + ); + } + } + + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * array('eventName' => 'methodName') + * * array('eventName' => array('methodName', $priority)) + * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) + * + * @return array The event names to listen to + * + * @api + */ + public static function getSubscribedEvents() + { + return [ + CommentEvents::COMMENT_CREATE => ['create', 128], + CommentEvents::COMMENT_DELETE => ['delete', 128], + CommentEvents::COMMENT_UPDATE => ['update', 128], + CommentEvents::COMMENT_ABUSE => ['abuse', 128], + CommentEvents::COMMENT_STATUS_UPDATE => ['statusChange', 128], + CommentEvents::COMMENT_RATING_COMPUTE => ['productRatingCompute', 128], + CommentEvents::COMMENT_REFERENCE_GETTER => ['getRefrence', 128], + CommentEvents::COMMENT_CUSTOMER_DEMAND => ['requestCustomerDemand', 128], + CommentEvents::COMMENT_GET_DEFINITION => ['getDefinition', 128], + CommentEvents::COMMENT_GET_DEFINITION_PRODUCT => ['getProductDefinition', 128], + CommentEvents::COMMENT_GET_DEFINITION_CONTENT => ['getContentDefinition', 128], + ]; + } +} \ No newline at end of file diff --git a/Comment.php b/Comment.php new file mode 100755 index 0000000..ba1a1ec --- /dev/null +++ b/Comment.php @@ -0,0 +1,147 @@ + + * @author Julien Chanséaume + */ +class Comment extends BaseModule +{ + const MESSAGE_DOMAIN = "comment"; + + /** Use comment */ + const CONFIG_ACTIVATED = 1; + + /** Use moderation */ + const CONFIG_MODERATE = 1; + + /** Allowed ref */ + const CONFIG_REF_ALLOWED = 'product,content'; + + /** Only customers are abled to post comment */ + const CONFIG_ONLY_CUSTOMER = 1; + + /** Allow only verified customer (for product, customers that have bought the product) */ + const CONFIG_ONLY_VERIFIED = 1; + + /** request customer comment, x days after an order */ + const CONFIG_REQUEST_CUSTOMMER_TTL = 15; + + + public function postActivation(ConnectionInterface $con = null) + { + // Config + if (null === ConfigQuery::read('comment_activated')) { + ConfigQuery::write('comment_activated', Comment::CONFIG_ACTIVATED); + } + + if (null === ConfigQuery::read('comment_moderate')) { + ConfigQuery::write('comment_moderate', Comment::CONFIG_MODERATE); + } + + if (null === ConfigQuery::read('comment_ref_allowed')) { + ConfigQuery::write('comment_ref_allowed', Comment::CONFIG_REF_ALLOWED); + } + + if (null === ConfigQuery::read('comment_only_customer')) { + ConfigQuery::write('comment_only_customer', Comment::CONFIG_ONLY_CUSTOMER); + } + + if (null === ConfigQuery::read('comment_only_verified')) { + ConfigQuery::write('comment_only_verified', Comment::CONFIG_ONLY_VERIFIED); + } + + if (null === ConfigQuery::read('comment_request_customer_ttl')) { + ConfigQuery::write('comment_request_customer_ttl', Comment::CONFIG_REQUEST_CUSTOMMER_TTL); + } + + // Schema + try { + CommentQuery::create()->findOne(); + } catch (\Exception $ex) { + $database = new Database($con->getWrappedConnection()); + $database->insertSql(null, [__DIR__ . DS . 'Config' . DS . 'thelia.sql']); + } + + // create new message + if (null === MessageQuery::create()->findOneByName('comment_request_customer')) { + + $message = new Message(); + $message + ->setName('comment_request_customer') + ->setHtmlTemplateFileName('request-customer-comment.html') + ->setHtmlLayoutFileName('') + ->setTextTemplateFileName('request-customer-comment.txt') + ->setTextLayoutFileName('') + ->setSecured(0); + + $languages = LangQuery::create()->find(); + + foreach ($languages as $language) { + $locale = $language->getLocale(); + + $message->setLocale($locale); + + $message->setTitle( + Translator::getInstance()->trans('Request customer comment', [], self::MESSAGE_DOMAIN) + ); + $message->setSubject( + Translator::getInstance()->trans('', [], self::MESSAGE_DOMAIN) + ); + } + + $message->save(); + } + } + + public static function getConfig() + { + $config = [ + 'activated' => ( + intval(ConfigQuery::read('comment_activated', self::CONFIG_ACTIVATED)) === 1 + ), + 'moderate' => ( + intval(ConfigQuery::read('comment_moderate', self::CONFIG_MODERATE)) === 1 + ), + 'ref_allowed' => explode( + ',', + ConfigQuery::read('comment_ref_allowed', self::CONFIG_REF_ALLOWED) + ), + 'only_customer' => ( + intval(ConfigQuery::read('comment_only_customer', self::CONFIG_ONLY_CUSTOMER)) === 1 + ), + 'only_verified' => ( + intval(ConfigQuery::read('comment_only_verified', self::CONFIG_ONLY_VERIFIED)) === 1 + ), + 'request_customer_ttl' => ( + intval(ConfigQuery::read('comment_request_customer_ttl', self::CONFIG_REQUEST_CUSTOMMER_TTL)) + ) + ]; + + return $config; + } +} diff --git a/Config/config.xml b/Config/config.xml new file mode 100755 index 0000000..5e42070 --- /dev/null +++ b/Config/config.xml @@ -0,0 +1,71 @@ + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Config/module.xml b/Config/module.xml new file mode 100755 index 0000000..b674022 --- /dev/null +++ b/Config/module.xml @@ -0,0 +1,24 @@ + + + Comment\Comment + + Comment system + + + Système de commentaire + + + en_US + fr_FR + + 0.1 + + Julien Chanséaume + jchanseaume@openstudio.fr + + classic + 2.1.0 + alpha + \ No newline at end of file diff --git a/Config/routing.xml b/Config/routing.xml new file mode 100755 index 0000000..85a25e1 --- /dev/null +++ b/Config/routing.xml @@ -0,0 +1,69 @@ + + + + + + + + Comment\Controller\Front\CommentController::getAction + + + + Comment\Controller\Front\CommentController::createAction + + + + Comment\Controller\Front\CommentController::deleteAction + \d+ + + + + Comment\Controller\Front\CommentController::abuseAction + + + + + Comment\Controller\Back\CommentController::saveConfiguration + + + + + + Comment\Controller\Back\CommentController::defaultAction + + + + Comment\Controller\Back\CommentController::createAction + + + + Comment\Controller\Back\CommentController::updateAction + \d+ + + + + Comment\Controller\Back\CommentController::processUpdateAction + \d+ + + + + Comment\Controller\Back\CommentController::deleteAction + + + + Comment\Controller\Back\CommentController::changeStatusAction + + + + Comment\Controller\Back\CommentController::activationAction + .* + \d+ + + + + Comment\Controller\Back\CommentController::requestCustomerCommentAction + + + diff --git a/Config/schema.xml b/Config/schema.xml new file mode 100755 index 0000000..e6668bd --- /dev/null +++ b/Config/schema.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + + + + + + +
+ + +
diff --git a/Config/thelia.sql b/Config/thelia.sql new file mode 100755 index 0000000..c3e1bd5 --- /dev/null +++ b/Config/thelia.sql @@ -0,0 +1,39 @@ + +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +-- --------------------------------------------------------------------- +-- comment +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `comment`; + +CREATE TABLE `comment` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `username` VARCHAR(255), + `customer_id` INTEGER, + `ref` VARCHAR(255), + `ref_id` INTEGER, + `email` VARCHAR(255), + `title` VARCHAR(255), + `content` LONGTEXT, + `rating` TINYINT, + `status` TINYINT DEFAULT 0, + `verified` TINYINT, + `abuse` INTEGER, + `locale` VARCHAR(10), + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `idx_comment_user_id` (`customer_id`), + CONSTRAINT `fk_comment_customer_id` + FOREIGN KEY (`customer_id`) + REFERENCES `customer` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + +# This restores the fkey checks, after having unset them earlier +SET FOREIGN_KEY_CHECKS = 1; diff --git a/Controller/Back/CommentController.php b/Controller/Back/CommentController.php new file mode 100644 index 0000000..ad09eb2 --- /dev/null +++ b/Controller/Back/CommentController.php @@ -0,0 +1,435 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Comment\Controller\Back; + +use Comment\Comment; +use Comment\Events\CommentChangeStatusEvent; +use Comment\Events\CommentCheckOrderEvent; +use Comment\Events\CommentCreateEvent; +use Comment\Events\CommentDeleteEvent; +use Comment\Events\CommentEvent; +use Comment\Events\CommentEvents; +use Comment\Events\CommentUpdateEvent; +use Comment\Form\CommentCreationForm; +use Comment\Form\CommentModificationForm; +use Comment\Model\CommentQuery; +use Exception; +use Symfony\Component\HttpFoundation\RedirectResponse; +use Thelia\Controller\Admin\AbstractCrudController; +use Thelia\Core\Security\AccessManager; +use Thelia\Core\Security\Resource\AdminResources; +use Thelia\Model\ConfigQuery; +use Thelia\Model\MetaDataQuery; +use Thelia\Tools\URL; + +/** + * Class CommentController + * @package Comment\Controller\Back + * @author Julien Chanséaume + */ +class CommentController extends AbstractCrudController +{ + + protected $currentRouter = "router.comment"; + + public function __construct() + { + parent::__construct( + 'comment', + 'created_reverse', + 'order', + AdminResources::CONFIG, + CommentEvents::COMMENT_CREATE, + CommentEvents::COMMENT_UPDATE, + CommentEvents::COMMENT_DELETE, + null, // No visibility toggle + null, // no position change + Comment::getModuleCode() + ); + } + + /** + * Return the creation form for this object + */ + protected function getCreationForm() + { + return new CommentCreationForm($this->getRequest()); + } + + /** + * Return the update form for this object + */ + protected function getUpdateForm() + { + return new CommentModificationForm($this->getRequest()); + } + + /** + * Hydrate the update form for this object, before passing it to the update template + * + * @param \Comment\Model\Comment $object + */ + protected function hydrateObjectForm($object) + { + // Prepare the data that will hydrate the form + $data = [ + 'id' => $object->getId(), + 'ref' => $object->getRef(), + 'ref_id' => $object->getRefId(), + 'customer_id' => $object->getCustomerId(), + 'username' => $object->getUsername(), + 'email' => $object->getEmail(), + 'locale' => $object->getLocale(), + 'title' => $object->getTitle(), + 'content' => $object->getContent(), + 'status' => $object->getStatus(), + 'verified' => $object->getVerified(), + 'rating' => $object->getRating() + ]; + + // Setup the object form + return new CommentModificationForm($this->getRequest(), "form", $data); + } + + /** + * Creates the creation event with the provided form data + * + * @param unknown $formData + */ + protected function getCreationEvent($formData) + { + $event = $this->bindFormData( + new CommentCreateEvent(), + $formData + ); + + return $event; + } + + /** + * Creates the update event with the provided form data + * + * @param unknown $formData + */ + protected function getUpdateEvent($formData) + { + $event = $this->bindFormData( + new CommentUpdateEvent(), + $formData + ); + + $event->setId($formData['id']); + + return $event; + } + + protected function bindFormData($event, $formData) + { + $event->setRef($formData['ref']); + $event->setRefId($formData['ref_id']); + $event->setCustomerId($formData['customer_id']); + $event->setUsername($formData['username']); + $event->setEmail($formData['email']); + $event->setLocale($formData['locale']); + $event->setTitle($formData['title']); + $event->setContent($formData['content']); + $event->setStatus($formData['status']); + $event->setVerified($formData['verified']); + $event->setRating($formData['rating']); + + return $event; + } + + /** + * Creates the delete event with the provided form data + */ + protected function getDeleteEvent() + { + $event = new CommentDeleteEvent(); + + $event->setId($this->getRequest()->get('comment_id')); + + return $event; + } + + /** + * Return true if the event contains the object, e.g. the action has updated the object in the event. + * + * @param CommentEvent $event + */ + protected function eventContainsObject($event) + { + return null !== $event->getComment(); + } + + /** + * Get the created object from an event. + * + * @param CommentEvent $event + * + * @return \Comment\Model\Comment + */ + protected function getObjectFromEvent($event) + { + return $event->getComment(); + } + + /** + * Load an existing object from the database + */ + protected function getExistingObject() + { + + $comment_id = $this->getRequest()->get('comment_id'); + if (null === $comment_id) { + $comment_id = $this->getRequest()->attributes('comment_id'); + } + + return CommentQuery::create()->findPk($comment_id); + } + + /** + * Returns the object label form the object event (name, title, etc.) + * + * @param \Comment\Model\Comment $object + */ + protected function getObjectLabel($object) + { + $object->getTitle(); + } + + /** + * Returns the object ID from the object + * + * @param \Comment\Model\Comment $object + */ + protected function getObjectId($object) + { + $object->getId(); + } + + /** + * Render the main list template + * + * @param string $currentOrder , if any, null otherwise. + */ + protected function renderListTemplate($currentOrder) + { + return $this->render('comments', ['order' => $currentOrder]); + } + + /** + * Render the edition template + */ + protected function renderEditionTemplate() + { + return $this->render( + 'comment-edit', + [ + 'comment_id' => $this->getRequest()->get('comment_id') + ] + ); + } + + /** + * Must return a RedirectResponse instance + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + protected function redirectToEditionTemplate() + { + return $this->generateRedirectFromRoute( + "admin.comment.comments.update", + [], + ['comment_id' => $this->getRequest()->get('comment_id')] + ); + } + + /** + * Must return a RedirectResponse instance + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + protected function redirectToListTemplate() + { + return $this->generateRedirectFromRoute('admin.comment.comments.default'); + } + + + public function changeStatusAction() + { + if (null !== $response = $this->checkAuth([], ['comment'], AccessManager::UPDATE) + ) { + return $response; + } + + $message = [ + "success" => false, + ]; + + $id = $this->getRequest()->request->get('id'); + $status = $this->getRequest()->request->get('status'); + + if (null !== $id && null !== $status) { + try { + $event = new CommentChangeStatusEvent(); + $event + ->setId($id) + ->setNewStatus($status); + + $this->dispatch( + CommentEvents::COMMENT_STATUS_UPDATE, + $event + ); + + $message = [ + "success" => true, + "data" => [ + 'id' => $id, + 'status' => $event->getComment()->getStatus() + ] + ]; + } catch (\Exception $ex) { + $message["error"] = $ex->getMessage(); + } + } else { + $message["error"] = $this->getTranslator()->trans('Missing parameters', [], Comment::MESSAGE_DOMAIN); + } + + return $this->jsonResponse(json_encode($message)); + } + + public function activationAction($ref, $refId) + { + if (null !== $response = $this->checkAuth([], ['comment'], AccessManager::UPDATE) + ) { + return $response; + } + + $message = [ + "success" => false, + ]; + + $status = $this->getRequest()->request->get('status'); + + switch ($status) { + case "0": + case "1": + MetaDataQuery::setVal(\Comment\Model\Comment::META_KEY_ACTIVATED, $ref, $refId, $status); + $message['success'] = true; + break; + case "-1": + $deleted = MetaDataQuery::create() + ->filterByMetaKey(\Comment\Model\Comment::META_KEY_ACTIVATED) + ->filterByElementKey($ref) + ->filterByElementId($refId) + ->delete(); + if ($deleted === 1) { + $message['success'] = true; + } + break; + } + + $message['status'] = MetaDataQuery::getVal(\Comment\Model\Comment::META_KEY_ACTIVATED, $ref, $refId, "-1"); + + return $this->jsonResponse(json_encode($message)); + } + + + /** + * Save comment module configuration + * + * @return \Symfony\Component\HttpFoundation\RedirectResponse + */ + public function saveConfiguration() + { + + if (null !== $response = $this->checkAuth([AdminResources::MODULE], ['comment'], AccessManager::UPDATE) + ) { + return $response; + } + + $form = new \Comment\Form\ConfigurationForm($this->getRequest()); + $message = ""; + + $response = null; + + try { + $vform = $this->validateForm($form); + $data = $vform->getData(); + + ConfigQuery::write( + 'comment_activated', + $data['activated'] ? '1' : '0' + ); + ConfigQuery::write( + 'comment_moderate', + $data['moderate'] ? '1' : '0' + ); + ConfigQuery::write('comment_ref_allowed', $data['ref_allowed']); + ConfigQuery::write( + 'comment_only_customer', + $data['only_customer'] ? '1' : '0' + ); + ConfigQuery::write( + 'comment_only_verified', + $data['only_verified'] ? '1' : '0' + ); + ConfigQuery::write( + 'comment_request_customer_ttl', + $data['request_customer_ttl'] + ); + } catch (\Exception $e) { + $message = $e->getMessage(); + } + if ($message) { + $form->setErrorMessage($message); + $this->getParserContext()->addForm($form); + $this->getParserContext()->setGeneralError($message); + + return $this->render( + "module-configure", + ["module_code" => Comment::getModuleCode()] + ); + } + + return RedirectResponse::create( + URL::getInstance()->absoluteUrl("/admin/module/" . Comment::getModuleCode()) + ); + } + + public function requestCustomerCommentAction() + { + // We do not check auth, as the related route may be invoked from a cron + try { + $this->dispatch( + CommentEvents::COMMENT_CUSTOMER_DEMAND, + new CommentCheckOrderEvent() + ); + } catch (\Exception $ex) { + // Any error + return $this->errorPage($ex); + } + + return $this->redirectToListTemplate(); + } +} diff --git a/Controller/Front/CommentController.php b/Controller/Front/CommentController.php new file mode 100644 index 0000000..4d48332 --- /dev/null +++ b/Controller/Front/CommentController.php @@ -0,0 +1,293 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Comment\Controller\Front; + +use Comment\Comment; +use Comment\Events\CommentAbuseEvent; +use Comment\Events\CommentCreateEvent; +use Comment\Events\CommentDefinitionEvent; +use Comment\Events\CommentDeleteEvent; +use Comment\Events\CommentEvents; +use Comment\Exception\InvalidDefinitionException; +use Comment\Model\CommentQuery; +use Exception; +use Thelia\Controller\Front\BaseFrontController; + +/** + * Class CommentController + * @package Comment\Controller\Admin + * @author Michaël Espeche + * @author Julien Chanséaume + */ +class CommentController extends BaseFrontController +{ + const DEFAULT_VISIBLE = 0; + + protected $useFallbackTemplate = true; + + public function getAction() + { + // only ajax + $this->checkXmlHttpRequest(); + + $definition = null; + + try { + $definition = $this->getDefinition( + $this->getRequest()->get('ref', null), + $this->getRequest()->get('ref_id', null) + ); + } catch (InvalidDefinitionException $ex) { + if ($ex->isSilent()) { + // Comment not authorized on this resource + $this->accessDenied(); + } + } + + return $this->render( + "ajax-comments", + [ + 'ref' => $this->getRequest()->get('ref'), + 'ref_id' => $this->getRequest()->get('ref_id'), + 'start' => $this->getRequest()->get('start', 0), + 'count' => $this->getRequest()->get('count', 10), + ] + ); + } + + public function abuseAction() + { + // only ajax + $this->checkXmlHttpRequest(); + + $abuseForm = $this->createForm('comment.abuse.form'); + + $messageData = [ + "success" => false + ]; + + try { + $form = $this->validateForm($abuseForm); + + $comment_id = $form->get("id")->getData(); + + $event = new CommentAbuseEvent(); + $event->setId($comment_id); + + $this->dispatch(CommentEvents::COMMENT_ABUSE, $event); + + $messageData["success"] = true; + $messageData["message"] = $this->getTranslator()->trans( + "Your request has been registered. Thank you.", + [], + Comment::MESSAGE_DOMAIN + ); + } catch (\Exception $ex) { + // all errors + $messageData["message"] = $this->getTranslator()->trans( + "Your request could not be validated. Try it later", + [], + Comment::MESSAGE_DOMAIN + ); + } + + return $this->jsonResponse(json_encode($messageData)); + } + + + public function createAction() + { + // only ajax + $this->checkXmlHttpRequest(); + + $responseData = []; + /** @var CommentDefinitionEvent $definition */ + $definition = null; + + try { + $params = $this->getRequest()->get('admin_add_comment'); + $definition = $this->getDefinition( + $params['ref'], + $params['ref_id'] + ); + } catch (InvalidDefinitionException $ex) { + if ($ex->isSilent()) { + // Comment not authorized on this resource + $this->accessDenied(); + } else { + // The customer does not have minimum requirement to post comment + $responseData = [ + "success" => false, + "messages" => [$ex->getMessage()] + ]; + return $this->jsonResponse(json_encode($responseData)); + } + } + + $customer = $definition->getCustomer(); + + $validationGroups = [ + 'Default' + ]; + + if (null === $customer) { + $validationGroups[] = 'anonymous'; + } + if (!$definition->hasRating()) { + $validationGroups[] = 'rating'; + } + + $commentForm = $this->createForm( + 'comment.add.form', + 'form', + [], + ['validation_groups' => $validationGroups] + ); + + try { + $form = $this->validateForm($commentForm); + + $event = new CommentCreateEvent(); + $event->bindForm($form); + + $event->setVerified($definition->isVerified()); + + if (null !== $customer) { + $event->setCustomerId($customer->getId()); + } + + if (!$definition->getConfig()['moderate']) { + $event->setStatus(\Comment\Model\Comment::ACCEPTED); + } else { + $event->setStatus(\Comment\Model\Comment::PENDING); + } + + $event->setLocale($this->getRequest()->getLocale()); + + $this->dispatch(CommentEvents::COMMENT_CREATE, $event); + + if (null !== $event->getComment()) { + $responseData = [ + "success" => true, + "messages" => [ + $this->getTranslator()->trans( + "Thank you for submitting your comment.", + [], + Comment::MESSAGE_DOMAIN + ), + ] + ]; + if ($definition->getConfig()['moderate']) { + $responseData['messages'][] = $this->getTranslator()->trans( + "Your comment will be put online once verified.", + [], + Comment::MESSAGE_DOMAIN + ); + } + } else { + $responseData = [ + "success" => false, + "messages" => [ + $this->getTranslator()->trans( + "Sorry, an unknown error occurred. Please try again.", + [], + Comment::MESSAGE_DOMAIN + ) + ] + ]; + } + } catch (Exception $ex) { + $responseData = [ + "success" => false, + "messages" => [$ex->getMessage()] + ]; + } + + return $this->jsonResponse(json_encode($responseData)); + } + + protected function getDefinition($ref, $refId) + { + $eventDefinition = new CommentDefinitionEvent(); + $eventDefinition + ->setRef($ref) + ->setRefId($refId) + ->setCustomer($this->getSecurityContext()->getCustomerUser()) + ->setConfig(Comment::getConfig()); + + $this->dispatch( + CommentEvents::COMMENT_GET_DEFINITION, + $eventDefinition + ); + + return $eventDefinition; + } + + public function deleteAction($commentId) + { + // only ajax + $this->checkXmlHttpRequest(); + + $messageData = [ + "success" => false + ]; + + try { + $customer = $this->getSecurityContext()->getCustomerUser(); + + // find the comment + $comment = CommentQuery::create()->findPk($commentId); + + if (null !== $comment) { + if ($comment->getCustomerId() === $customer->getId()) { + $event = new CommentDeleteEvent(); + $event->setId($commentId); + + $this->dispatch(CommentEvents::COMMENT_DELETE, $event); + + if (null !== $event->getComment()) { + $messageData["success"] = true; + $messageData["message"] = $this->getTranslator()->trans( + "Your comment has been deleted.", + [], + Comment::MESSAGE_DOMAIN + ); + } + } + } + } catch (\Exception $ex) { + ; + } + + if (false === $messageData["success"]) { + $messageData["message"] = $this->getTranslator()->trans( + "Comment could not be removed. Please try later.", + [], + Comment::MESSAGE_DOMAIN + ); + } + + return $this->jsonResponse(json_encode($messageData)); + } +} diff --git a/Events/CommentAbuseEvent.php b/Events/CommentAbuseEvent.php new file mode 100644 index 0000000..a6daac0 --- /dev/null +++ b/Events/CommentAbuseEvent.php @@ -0,0 +1,23 @@ + + */ +class CommentAbuseEvent extends CommentEvent +{ +} diff --git a/Events/CommentChangeStatusEvent.php b/Events/CommentChangeStatusEvent.php new file mode 100644 index 0000000..39026e0 --- /dev/null +++ b/Events/CommentChangeStatusEvent.php @@ -0,0 +1,43 @@ + + */ +class CommentChangeStatusEvent extends CommentEvent +{ + /** @var int */ + protected $newStatus; + + /** + * @return int + */ + public function getNewStatus() + { + return $this->newStatus; + } + + /** + * @param int $newStatus + */ + public function setNewStatus($newStatus) + { + $this->newStatus = $newStatus; + + return $this; + } +} diff --git a/Events/CommentCheckOrderEvent.php b/Events/CommentCheckOrderEvent.php new file mode 100644 index 0000000..abe1797 --- /dev/null +++ b/Events/CommentCheckOrderEvent.php @@ -0,0 +1,26 @@ + + */ +class CommentCheckOrderEvent extends ActionEvent +{ + +} diff --git a/Events/CommentComputeRatingEvent.php b/Events/CommentComputeRatingEvent.php new file mode 100644 index 0000000..e6b4c93 --- /dev/null +++ b/Events/CommentComputeRatingEvent.php @@ -0,0 +1,85 @@ + + */ +class CommentComputeRatingEvent extends ActionEvent +{ + /** @var string */ + protected $ref; + + /** @var int */ + protected $refId; + + /** @var float */ + protected $rating; + + /** + * @return string + */ + public function getRef() + { + return $this->ref; + } + + /** + * @param string $ref + */ + public function setRef($ref) + { + $this->ref = $ref; + return $this; + } + + /** + * @return int + */ + public function getRefId() + { + return $this->refId; + } + + /** + * @param int $refId + */ + public function setRefId($refId) + { + $this->refId = $refId; + return $this; + } + + /** + * @return float + */ + public function getRating() + { + return $this->rating; + } + + /** + * @param float $rating + */ + public function setRating($rating) + { + $this->rating = $rating; + + return $this; + } +} diff --git a/Events/CommentCreateEvent.php b/Events/CommentCreateEvent.php new file mode 100644 index 0000000..491c893 --- /dev/null +++ b/Events/CommentCreateEvent.php @@ -0,0 +1,270 @@ + + * + * + */ +class CommentCreateEvent extends CommentEvent +{ + /** @var string */ + protected $ref; + + /** @var int */ + protected $refId; + + /** @var int */ + protected $customerId; + + /** @var string */ + protected $username; + + /** @var string */ + protected $email; + + /** @var string */ + protected $locale; + + /** @var string */ + protected $title; + + /** @var string */ + protected $content; + + /** @var int */ + protected $status; + + /** @var boolean */ + protected $verified; + + /** @var int */ + protected $rating; + + /** @var int */ + protected $abuse; + + /** + * @return int + */ + public function getAbuse() + { + return $this->abuse; + } + + /** + * @param int $abuse + */ + public function setAbuse($abuse) + { + $this->abuse = $abuse; + + return $this; + } + + /** + * @return string + */ + public function getContent() + { + return $this->content; + } + + /** + * @param string $content + */ + public function setContent($content) + { + $this->content = $content; + } + + /** + * @return int + */ + public function getCustomerId() + { + return $this->customerId; + } + + /** + * @param int $customerId + */ + public function setCustomerId($customerId) + { + $this->customerId = $customerId; + } + + /** + * @return string + */ + public function getEmail() + { + return $this->email; + } + + /** + * @param string $email + */ + public function setEmail($email) + { + $this->email = $email; + } + + /** + * @return string + */ + public function getLocale() + { + return $this->locale; + } + + /** + * @param string $locale + */ + public function setLocale($locale) + { + $this->locale = $locale; + + return $this; + } + + /** + * @return int + */ + public function getRating() + { + return $this->rating; + } + + /** + * @param int $rating + */ + public function setRating($rating) + { + $this->rating = $rating; + + return $this; + } + + /** + * @return string + */ + public function getRef() + { + return $this->ref; + } + + /** + * @param string $ref + */ + public function setRef($ref) + { + $this->ref = $ref; + + return $this; + } + + /** + * @return int + */ + public function getRefId() + { + return $this->refId; + } + + /** + * @param int $refId + */ + public function setRefId($refId) + { + $this->refId = $refId; + + return $this; + } + + /** + * @return int + */ + public function getStatus() + { + return $this->status; + } + + /** + * @param int $status + */ + public function setStatus($status) + { + $this->status = $status; + + return $this; + } + + /** + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * @param string $title + */ + public function setTitle($title) + { + $this->title = $title; + + return $this; + } + + /** + * @return string + */ + public function getUsername() + { + return $this->username; + } + + /** + * @param string $username + */ + public function setUsername($username) + { + $this->username = $username; + + return $this; + } + + /** + * @return boolean + */ + public function isVerified() + { + return $this->verified; + } + + /** + * @param boolean $verified + */ + public function setVerified($verified) + { + $this->verified = $verified; + + return $this; + } +} diff --git a/Events/CommentDefinitionEvent.php b/Events/CommentDefinitionEvent.php new file mode 100644 index 0000000..cb4e5a4 --- /dev/null +++ b/Events/CommentDefinitionEvent.php @@ -0,0 +1,166 @@ + + */ +class CommentDefinitionEvent extends CommentEvent +{ + /** @var string */ + protected $ref; + + /** @var int */ + protected $ref_id; + + /** @var array */ + protected $config = []; + + /** @var \Thelia\Model\Customer */ + protected $customer = null; + + /** @var bool */ + protected $verified = false; + + /** @var bool */ + protected $rating = false; + + /** @var bool */ + protected $valid = false; + + public function __construct() + { + } + + /** + * @return string + */ + public function getRef() + { + return $this->ref; + } + + /** + * @param string $ref + */ + public function setRef($ref) + { + $this->ref = $ref; + return $this; + } + + /** + * @return int + */ + public function getRefId() + { + return $this->ref_id; + } + + /** + * @param int $ref_id + */ + public function setRefId($ref_id) + { + $this->ref_id = $ref_id; + return $this; + } + + /** + * @return array + */ + public function getConfig() + { + return $this->config; + } + + /** + * @param array $config + */ + public function setConfig($config) + { + $this->config = $config; + return $this; + } + + /** + * @return \Thelia\Model\Customer + */ + public function getCustomer() + { + return $this->customer; + } + + /** + * @param \Thelia\Model\Customer $customer + */ + public function setCustomer($customer) + { + $this->customer = $customer; + return $this; + } + + /** + * @return boolean + */ + public function isVerified() + { + return $this->verified; + } + + /** + * @param boolean $verified + */ + public function setVerified($verified) + { + $this->verified = $verified; + return $this; + } + + /** + * @return boolean + */ + public function hasRating() + { + return $this->rating; + } + + /** + * @param boolean $rating + */ + public function setRating($rating) + { + $this->rating = $rating; + return $this; + } + + /** + * @return boolean + */ + public function isValid() + { + return $this->valid; + } + + /** + * @param boolean $valid + */ + public function setValid($valid) + { + $this->valid = $valid; + return $this; + } +} diff --git a/Events/CommentDeleteEvent.php b/Events/CommentDeleteEvent.php new file mode 100644 index 0000000..6ef440e --- /dev/null +++ b/Events/CommentDeleteEvent.php @@ -0,0 +1,23 @@ + + */ +class CommentDeleteEvent extends CommentEvent +{ +} diff --git a/Events/CommentEvent.php b/Events/CommentEvent.php new file mode 100644 index 0000000..1b44878 --- /dev/null +++ b/Events/CommentEvent.php @@ -0,0 +1,87 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace Comment\Events; + +use Comment\Model\Comment; +use Thelia\Core\Event\ActionEvent; + +/** + * + * This class contains all Comment events identifiers used by Comment Core + * + * @author Michaël Espeche + * @author Julien Chanséaume + * + */ +class CommentEvent extends ActionEvent +{ + /** @var int */ + protected $id = null; + + /** @var Comment */ + protected $comment = null; + + /** + * Constructor + */ + public function __construct() + { + } + + /** + * @return int + */ + public function getId() + { + return $this->id; + } + + /** + * @param int $id + */ + public function setId($id) + { + $this->id = $id; + + return $this; + } + + /** + * @return Comment|null + */ + public function getComment() + { + return $this->comment; + } + + /** + * @param Comment $comment + */ + public function setComment(Comment $comment) + { + $this->comment = $comment; + + return $this; + } +} diff --git a/Events/CommentEvents.php b/Events/CommentEvents.php new file mode 100644 index 0000000..d825de8 --- /dev/null +++ b/Events/CommentEvents.php @@ -0,0 +1,36 @@ + + */ +class CommentEvents +{ + const COMMENT_CREATE = "action.comment.create"; + const COMMENT_UPDATE = "action.comment.update"; + const COMMENT_DELETE = "action.comment.delete"; + const COMMENT_STATUS_UPDATE = "action.comment.status.update"; + const COMMENT_ABUSE = "action.comment.abuse"; + const COMMENT_RATING_COMPUTE = "action.comment.rating.compute"; + const COMMENT_REFERENCE_GETTER = "action.comment.reference.getter"; + const COMMENT_CUSTOMER_DEMAND = "action.comment.customer.demand"; + // + const COMMENT_GET_DEFINITION = "action.comment.definition"; + const COMMENT_GET_DEFINITION_PRODUCT = "action.comment.definition.product"; + const COMMENT_GET_DEFINITION_CONTENT = "action.comment.definition.content"; +} diff --git a/Events/CommentReferenceGetterEvent.php b/Events/CommentReferenceGetterEvent.php new file mode 100644 index 0000000..e553320 --- /dev/null +++ b/Events/CommentReferenceGetterEvent.php @@ -0,0 +1,172 @@ + + */ +class CommentReferenceGetterEvent extends ActionEvent +{ + /** @var string */ + protected $ref; + /** @var int */ + protected $refId; + /** @var string */ + protected $locale; + /** @var mixed */ + protected $object; + /** @var string */ + protected $title; + /** @var string */ + protected $viewUrl; + /** @var string */ + protected $editUrl; + + public function __construct($ref, $refId, $locale) + { + $this->ref = $ref; + $this->refId = $refId; + $this->locale = $locale; + } + + + /** + * @return string + */ + public function getEditUrl() + { + return $this->editUrl; + } + + /** + * @param string $editUrl + */ + public function setEditUrl($editUrl) + { + $this->editUrl = $editUrl; + + return $this; + } + + /** + * @return string + */ + + public function getLocale() + { + return $this->locale; + } + + /** + * @param string $locale + */ + public function setLocale($locale) + { + $this->locale = $locale; + } + + /** + * @return mixed + */ + public function getObject() + { + return $this->object; + } + + /** + * @param mixed $object + */ + public function setObject($object) + { + $this->object = $object; + + return $this; + } + + /** + * @return string + */ + public function getRef() + { + return $this->ref; + } + + /** + * @param string $ref + */ + public function setRef($ref) + { + $this->ref = $ref; + + return $this; + } + + /** + * @return int + */ + public function getRefId() + { + return $this->refId; + } + + /** + * @param int $refId + */ + public function setRefId($refId) + { + $this->refId = $refId; + + return $this; + } + + /** + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * @param string $title + */ + public function setTitle($title) + { + $this->title = $title; + + return $this; + } + + /** + * @return string + */ + public function getViewUrl() + { + return $this->viewUrl; + } + + /** + * @param string $viewUrl + */ + public function setViewUrl($viewUrl) + { + $this->viewUrl = $viewUrl; + + return $this; + } +} diff --git a/Events/CommentUpdateEvent.php b/Events/CommentUpdateEvent.php new file mode 100644 index 0000000..f1161a8 --- /dev/null +++ b/Events/CommentUpdateEvent.php @@ -0,0 +1,23 @@ + + */ +class CommentUpdateEvent extends CommentCreateEvent +{ +} diff --git a/Exception/InvalidDefinitionException.php b/Exception/InvalidDefinitionException.php new file mode 100644 index 0000000..611d79e --- /dev/null +++ b/Exception/InvalidDefinitionException.php @@ -0,0 +1,49 @@ + + */ +class InvalidDefinitionException extends \RuntimeException +{ + + protected $silent = true; + + public function __construct($message, $silent = true) + { + $this->silent = $silent; + + parent::__construct($message); + } + + /** + * @return boolean + */ + public function isSilent() + { + return $this->silent; + } + + /** + * @param boolean $silent + */ + public function setSilent($silent) + { + $this->silent = $silent; + } +} diff --git a/Form/AddCommentForm.php b/Form/AddCommentForm.php new file mode 100644 index 0000000..20afc1b --- /dev/null +++ b/Form/AddCommentForm.php @@ -0,0 +1,119 @@ +. */ +/* */ +/*************************************************************************************/ +namespace Comment\Form; + +use Comment\Comment; +use Symfony\Component\Validator\Constraints\Email; +use Symfony\Component\Validator\Constraints\GreaterThan; +use Symfony\Component\Validator\Constraints\GreaterThanOrEqual; +use Symfony\Component\Validator\Constraints\LessThanOrEqual; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Form\BaseForm; + +class AddCommentForm extends BaseForm +{ + protected function trans($id, array $parameters = []) + { + return $this->translator->trans($id, $parameters, Comment::MESSAGE_DOMAIN); + } + + protected function buildForm() + { + $this->formBuilder + ->add('username', 'text', [ + 'constraints' => [ + new NotBlank(['groups' => ['anonymous']]) + ], + 'label' => $this->trans('Username'), + 'label_attr' => [ + 'for' => 'comment_username' + ] + ]) + ->add('email', 'email', [ + 'constraints' => [ + new NotBlank(['groups' => ['anonymous']]), + new Email(['groups' => ['anonymous']]) + ], + 'label' => $this->trans('Email'), + 'label_attr' => [ + 'for' => 'comment_mail' + ] + ]) + ->add('title', 'text', [ + 'constraints' => [ + new NotBlank() + ], + 'label' => $this->trans('Title'), + 'label_attr' => [ + 'for' => 'title' + ] + ]) + ->add('content', 'text', [ + 'constraints' => [ + new NotBlank() + ], + 'label' => $this->trans('Content'), + 'label_attr' => [ + 'for' => 'content' + ] + ]) + ->add('ref', 'text', [ + 'constraints' => [ + new NotBlank() + ], + 'label' => $this->trans('Ref'), + 'label_attr' => [ + 'for' => 'ref' + ] + ]) + ->add('ref_id', 'text', [ + 'constraints' => [ + new GreaterThan(['value' => 0]) + ], + 'label' => $this->trans('Ref Id'), + 'label_attr' => [ + 'for' => 'ref_id' + ] + ]) + ->add('rating', 'text', [ + 'constraints' => [ + new GreaterThanOrEqual(['value' => 0, 'groups' => ['rating']]), + new LessThanOrEqual(['value' => 5, 'groups' => ['rating']]) + ], + 'label' => $this->trans('Rating'), + 'label_attr' => [ + 'for' => 'rating' + ] + ]); + } + + /* + protected function getDefinition() { + $this->form->get('success_url'); + } +*/ + public function getName() + { + return 'admin_add_comment'; + } +} diff --git a/Form/CommentAbuseForm.php b/Form/CommentAbuseForm.php new file mode 100644 index 0000000..2c22ea8 --- /dev/null +++ b/Form/CommentAbuseForm.php @@ -0,0 +1,48 @@ + + */ +class CommentAbuseForm extends BaseForm +{ + protected function trans($id, array $parameters = []) + { + return $this->translator->trans($id, $parameters, Comment::MESSAGE_DOMAIN); + } + + protected function buildForm() + { + $this + ->formBuilder + ->add( + 'id', + 'comment_id' + ); + } + + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return 'comment_abuse'; + } +} diff --git a/Form/CommentCreationForm.php b/Form/CommentCreationForm.php new file mode 100644 index 0000000..653dbea --- /dev/null +++ b/Form/CommentCreationForm.php @@ -0,0 +1,168 @@ + + */ +class CommentCreationForm extends BaseForm +{ + + protected function trans($id, array $parameters = []) + { + return $this->translator->trans($id, $parameters, Comment::MESSAGE_DOMAIN); + } + + protected function buildForm() + { + $this + ->formBuilder + ->add( + 'customer_id', + 'integer', + [ + 'required' => false, + 'label' => $this->trans('Customer'), + 'label_attr' => [ + 'for' => 'customer_id' + ] + ] + ) + ->add('username', 'text', [ + 'required' => false, + 'constraints' => [ + new Length(['min' => 2]) + ], + 'label' => $this->trans('Username'), + 'label_attr' => [ + 'for' => 'comment_username' + ] + ]) + ->add('email', 'email', [ + 'required' => false, + 'constraints' => [ + new Email() + ], + 'label' => $this->trans('Email'), + 'label_attr' => [ + 'for' => 'comment_mail' + ] + ]) + ->add( + 'locale', + 'text', + [ + 'label' => $this->trans('Locale'), + 'label_attr' => [ + 'for' => 'locale' + ] + ] + ) + ->add('title', 'text', [ + 'constraints' => [ + new NotBlank() + ], + 'label' => $this->trans('Title'), + 'label_attr' => [ + 'for' => 'title' + ] + ]) + ->add('content', 'text', [ + 'constraints' => [ + new NotBlank() + ], + 'label' => $this->trans('Content'), + 'label_attr' => [ + 'for' => 'content' + ] + ]) + ->add('ref', 'text', [ + 'constraints' => [ + new NotBlank() + ], + 'label' => $this->trans('Ref'), + 'label_attr' => [ + 'for' => 'ref' + ] + ]) + ->add('ref_id', 'integer', [ + 'constraints' => [ + new GreaterThanOrEqual(['value' => 0]) + ], + 'label' => $this->trans('Ref Id'), + 'label_attr' => [ + 'for' => 'ref_id' + ] + ]) + ->add('rating', 'integer', [ + 'required' => false, + 'constraints' => [ + new GreaterThanOrEqual(['value' => 0]), + new LessThanOrEqual(['value' => 5]) + ], + 'label' => $this->trans('Rating'), + 'label_attr' => [ + 'for' => 'rating' + ] + ]) + ->add( + 'status', + 'integer', + [ + 'label' => $this->trans('Status'), + 'label_attr' => [ + 'for' => 'status' + ] + ] + ) + ->add( + 'verified', + 'integer', + [ + 'label' => $this->trans('Verified'), + 'label_attr' => [ + 'for' => 'verified' + ] + ] + ) + ->add( + 'abuse', + 'integer', + [ + 'label' => $this->trans('Abuse'), + 'label_attr' => [ + 'for' => 'abuse' + ] + ] + ); + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return 'admin_comment_creation'; + } +} diff --git a/Form/CommentModificationForm.php b/Form/CommentModificationForm.php new file mode 100644 index 0000000..21f9c41 --- /dev/null +++ b/Form/CommentModificationForm.php @@ -0,0 +1,60 @@ + + */ +class CommentModificationForm extends CommentCreationForm +{ + protected function trans($id, array $parameters = []) + { + return $this->translator->trans($id, $parameters, Comment::MESSAGE_DOMAIN); + } + + protected function buildForm() + { + parent::buildForm(); + + $this + ->formBuilder + ->add( + 'id', + 'integer', + [ + 'constraints' => [ + new NotBlank() + ], + 'label' => $this->trans('Id'), + 'label_attr' => [ + 'for' => 'id' + ] + ] + ); + } + + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return 'admin_comment_modification'; + } +} diff --git a/Form/ConfigurationForm.php b/Form/ConfigurationForm.php new file mode 100644 index 0000000..7305937 --- /dev/null +++ b/Form/ConfigurationForm.php @@ -0,0 +1,129 @@ + + */ +class ConfigurationForm extends BaseForm +{ + protected function trans($id, array $parameters = []) + { + return $this->translator->trans($id, $parameters, Comment::MESSAGE_DOMAIN); + } + + protected function buildForm() + { + $form = $this->formBuilder; + + $config = Comment::getConfig(); + + $form + ->add( + "activated", + "checkbox", + [ + 'data' => $config['activated'], + 'label' => $this->trans("Activated"), + 'label_attr' => [ + 'for' => "activated", + 'help' => $this->trans( + "Global activation of comments. You can control activation by product, content." + ) + ], + ] + ) + ->add( + "moderate", + "checkbox", + [ + 'data' => $config['moderate'], + 'label' => $this->trans("Moderate"), + 'label_attr' => [ + 'for' => "moderate", + 'help' => $this->trans("Comments are not validated automatically.") + ], + ] + ) + ->add( + "ref_allowed", + "text", + [ + 'constraints' => [ + new NotBlank() + ], + 'data' => implode(',', $config['ref_allowed']), + 'label' => $this->trans("Allowed references"), + 'label_attr' => [ + 'for' => "back_office_path", + 'help' => $this->trans("which elements could use comments") + ], + ] + ) + ->add( + "only_customer", + "checkbox", + [ + 'data' => $config['only_customer'], + 'label' => $this->trans("Only customer"), + 'label_attr' => [ + 'for' => "only_customer", + 'help' => $this->trans("Only registered customers can post comments.") + ], + ] + ) + ->add( + "only_verified", + "checkbox", + [ + 'data' => $config['only_verified'], + 'label' => $this->trans("Only verified"), + 'label_attr' => [ + 'for' => "only_verified", + 'help' => $this->trans( + "For product comments. Only customers that bought the product can post comments." + ) + ], + ] + ) + ->add( + "request_customer_ttl", + "number", + [ + 'data' => $config['request_customer_ttl'], + 'label' => $this->trans("Request customer"), + 'label_attr' => [ + 'for' => "request_customer_ttl", + 'help' => $this->trans( + "Send an email to request customer comments, x days after a paid order (0 = no request sent)." + ) + ], + ] + ); + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return "comment-configuration-form"; + } +} diff --git a/Form/Field/CommentIdType.php b/Form/Field/CommentIdType.php new file mode 100644 index 0000000..ce6bd00 --- /dev/null +++ b/Form/Field/CommentIdType.php @@ -0,0 +1,45 @@ + + */ +class CommentIdType extends AbstractIdType +{ + /** + * @return \Propel\Runtime\ActiveQuery\ModelCriteria + * + * Get the model query to check + */ + protected function getQuery() + { + return new CommentQuery(); + } + + /** + * Returns the name of this type. + * + * @return string The name of this type + */ + public function getName() + { + return "comment_id"; + } +} diff --git a/Hook/BackHook.php b/Hook/BackHook.php new file mode 100644 index 0000000..b4cc225 --- /dev/null +++ b/Hook/BackHook.php @@ -0,0 +1,83 @@ + + */ +class BackHook extends BaseHook +{ + + public function onModuleConfiguration(HookRenderEvent $event) + { + $event->add($this->render("configuration.html")); + } + + /** + * Add a new entry in the admin tools menu + * + * should add to event a fragment with fields : id,class,url,title + * + * @param HookRenderBlockEvent $event + */ + public function onMainTopMenuTools(HookRenderBlockEvent $event) + { + $event->add( + [ + 'id' => 'tools_menu_comment', + 'class' => '', + 'url' => URL::getInstance()->absoluteUrl('/admin/module/comments'), + 'title' => $this->trans('Comments', [], Comment::MESSAGE_DOMAIN) + ] + ); + } + + public function onProductTabContent(HookRenderEvent $event) + { + $this->onTabContent($event, 'product'); + } + + public function onContentTabContent(HookRenderEvent $event) + { + $this->onTabContent($event, 'content'); + } + + protected function onTabContent(HookRenderEvent $event, $ref) + { + $event->add( + $this->render( + 'tab-content.html', + [ + 'ref' => $ref, + 'id' => $event->getArgument('id') + ] + ) + ); + } + + public function onJsTabContent(HookRenderEvent $event) + { + $event->add( + $this->addJS('assets/js/comment.js') + ); + } +} diff --git a/Hook/FrontHook.php b/Hook/FrontHook.php new file mode 100644 index 0000000..faf97d4 --- /dev/null +++ b/Hook/FrontHook.php @@ -0,0 +1,161 @@ + + */ +class FrontHook extends BaseHook +{ + protected $parserContext = null; + + public function __construct() + { + } + + public function onShowComment(HookRenderEvent $event) + { + $data = $this->showComment($event); + + if (null !== $data) { + $event->add($data); + } + } + + public function onShowBlockComment(HookRenderBlockEvent $event) + { + $data = $this->showComment($event); + + if (null !== $data) { + $event->add( + [ + 'id' => 'comment', + 'title' => $this->trans("Comments", [], Comment::MESSAGE_DOMAIN), + 'content' => $data + ] + ); + } + } + + protected function showComment(BaseHookRenderEvent $event) + { + list($ref, $refId) = $this->getParams($event); + + $eventDefinition = new CommentDefinitionEvent(); + $eventDefinition + ->setRef($ref) + ->setRefId($refId) + ->setCustomer($this->getCustomer()) + ->setConfig(Comment::getConfig()); + $message = ''; + + try { + $this->dispatcher->dispatch( + CommentEvents::COMMENT_GET_DEFINITION, + $eventDefinition + ); + $eventDefinition->setValid(true); + } catch (InvalidDefinitionException $ex) { + if ($ex->isSilent()) { + return null; + } + $eventDefinition->setValid(false); + $message = $ex->getMessage(); + } catch (\Exception $ex) { + Tlog::getInstance()->debug($ex->getMessage()); + return null; + } + + return $this->render( + "comment.html", + [ + 'definition' => $eventDefinition, + 'message' => $message + ] + ); + } + + /** + * Add the javascript script to manage comments + * + * @param HookRenderEvent $event + */ + public function jsComment(HookRenderEvent $event) + { + $allowedRef = explode( + ',', + ConfigQuery::read('comment_ref_allowed', Comment::CONFIG_REF_ALLOWED) + ); + + if (in_array($this->getView(), $allowedRef)) { + + list($ref, $refId) = $this->getParams($event); + + $event->add( + $this->render( + "js.html", + [ + 'ref' => $ref, + 'ref_id' => $refId + ] + ) + ); + + $event->add( + $this->addJS('assets/js/comment.js') + ); + } + } + + protected function getParams(BaseHookRenderEvent $event) + { + $ref = $event->getArgument('ref') + ? $event->getArgument('ref') + : $this->getView(); + + $refId = 0; + + if ($event->getArgument('ref_id')) { + $refId = $event->getArgument('ref_id'); + } else { + if ($this->getRequest()->attributes->has('id')) { + $refId = intval($this->getRequest()->attributes->get('id')); + } elseif ($this->getRequest()->query->has($ref . '_id')) { + $refId = intval($this->getRequest()->query->get($ref . '_id')); + } + } + + if (null === $ref || 0 === $refId) { + throw new InvalidArgumentException( + $this->trans("Reference not found", [], Comment::MESSAGE_DOMAIN) + ); + } + + return [$ref, $refId]; + } +} diff --git a/I18n/backOffice/default/en_US.php b/I18n/backOffice/default/en_US.php new file mode 100644 index 0000000..93903fe --- /dev/null +++ b/I18n/backOffice/default/en_US.php @@ -0,0 +1,53 @@ + 'Abused', + 'Accepted' => 'Accepted', + 'Actions' => 'Actions', + 'Activated for this element' => 'Activated for this element', + 'Add a new comment' => 'Add a new comment', + 'All' => 'All', + 'Author' => 'Author', + 'Change this comment' => 'Change this comment', + 'Comment' => 'Comment', + 'Comment configuration.' => 'Comment configuration.', + 'Comment created on %date_create. Last modification: %date_change' => 'Comment created on %date_create. Last modification: %date_change', + 'Comments' => 'Comments', + 'Comments activation.' => 'Comments activation.', + 'Comments management' => 'Comments management', + 'Create a new comment' => 'Create a new comment', + 'Create this comment' => 'Create this comment', + 'Deactivated for this element' => 'Deactivated for this element', + 'Delete comment' => 'Delete comment', + 'Delete this comment' => 'Delete this comment', + 'Do you really want to delete this comment ?' => 'Do you really want to delete this comment ?', + 'Edit comment' => 'Edit comment', + 'Edit comment %name' => 'Edit comment %name', + 'Editing comment "%name"' => 'Editing comment "%name"', + 'Error' => 'Error', + 'Filter' => 'Filter', + 'Home' => 'Home', + 'ID' => 'ID', + 'Impossible to change status.' => 'Impossible to change status.', + 'Impossible to delete comment.' => 'Impossible to delete comment.', + 'Next' => 'Next', + 'Pagination' => 'Pagination', + 'Pending' => 'Pending', + 'Please contact your administrator or try later' => 'Please contact your administrator or try later', + 'Posted: ' => 'Posted: ', + 'Previous' => 'Previous', + 'Reference' => 'Reference', + 'Refused' => 'Refused', + 'Save' => 'Save', + 'Sorry, comment ID=%id was not found.' => 'Sorry, comment ID=%id was not found.', + 'Status' => 'Status', + 'Status :' => 'Status :', + 'Unknow customer %id' => 'Unknow customer %id', + 'Use global configuration' => 'Use global configuration', + 'View' => 'View', + 'no' => 'no', + 'not a customer' => 'not a customer', + 'rating: ' => 'rating: ', + 'verified: ' => 'verified: ', + 'yes' => 'yes', +); diff --git a/I18n/backOffice/default/fr_FR.php b/I18n/backOffice/default/fr_FR.php new file mode 100644 index 0000000..3a5ccbf --- /dev/null +++ b/I18n/backOffice/default/fr_FR.php @@ -0,0 +1,53 @@ + 'Abusif', + 'Accepted' => 'Accepté', + 'Actions' => 'Actions', + 'Activated for this element' => 'Activé pour cet élément', + 'Add a new comment' => 'Ajouter un nouveau commentaires', + 'All' => 'Tous', + 'Author' => 'Auteur', + 'Change this comment' => 'Modifier ce commentaire', + 'Comment' => 'Commentaire', + 'Comment configuration.' => 'Configuration des commentaires.', + 'Comment created on %date_create. Last modification: %date_change' => 'Commentaire créé le %date_create. Dernière modification: %date_change ', + 'Comments' => 'Commentaires', + 'Comments activation.' => 'Activation des commentaires.', + 'Comments management' => 'Gestion des commentaires', + 'Create a new comment' => 'Créer un nouveau commentaire', + 'Create this comment' => 'Créer ce commentaire', + 'Deactivated for this element' => 'Désactivé pour cet élément', + 'Delete comment' => 'Supprimer le commentaire', + 'Delete this comment' => 'Supprimer ce commentaire', + 'Do you really want to delete this comment ?' => 'Voulez-vous vraiment supprimer ce commentaire ?', + 'Edit comment' => 'Modifier le commentaire', + 'Edit comment %name' => 'Modifier le commentaire %name', + 'Editing comment "%name"' => 'Edition du commentaire "%name"', + 'Error' => 'Erreur', + 'Filter' => 'Filtrer', + 'Home' => 'Accueil', + 'ID' => 'ID', + 'Impossible to change status.' => 'Changement de statut impossible.', + 'Impossible to delete comment.' => 'Suppression du commentaire impossible', + 'Next' => 'Suivant', + 'Pagination' => 'Pagination', + 'Pending' => 'En attente', + 'Please contact your administrator or try later' => 'Veuillez contacter l\'administrateur ou ré-essayer plus tard', + 'Posted: ' => 'Posté :', + 'Previous' => 'Précédent', + 'Reference' => 'Référence', + 'Refused' => 'Refiusé', + 'Save' => 'Enregistrer', + 'Sorry, comment ID=%id was not found.' => 'Désolé, le commentaire ID=%id n\'a pas été trouvé.', + 'Status' => 'Statut', + 'Status :' => 'Statut :', + 'Unknow customer %id' => 'Client inconnu %id', + 'Use global configuration' => 'Utiliser la configuration globale', + 'View' => 'Voir', + 'no' => 'non', + 'not a customer' => 'pas un client', + 'rating: ' => 'note :', + 'verified: ' => 'vérifié :', + 'yes' => 'oui', +); diff --git a/I18n/en_US.php b/I18n/en_US.php new file mode 100755 index 0000000..abab2d0 --- /dev/null +++ b/I18n/en_US.php @@ -0,0 +1,42 @@ + 'Abuse', + 'Activated' => 'Activated', + 'Allowed references' => 'Allowed references', + 'Comment could not be removed. Please try later.' => 'Comment could not be removed. Please try later.', + 'Comment not activated on this element.' => 'Comment not activated on this element.', + 'Comments' => 'Comments', + 'Comments are not validated automatically.' => 'Comments are not validated automatically.', + 'Content' => 'Content', + 'Customer' => 'Customer', + 'Email' => 'Email', + 'For product comments. Only customers that bought the product can post comments.' => 'For product comments. Only customers that bought the product can post comments.', + 'Global activation of comments. You can control activation by product, content.' => 'Global activation of comments. You can control activation by product, content.', + 'Id' => 'Id', + 'If \'ref\' argument is specified, \'ref_id\' argument should be specified' => 'If \'ref\' argument is specified, \'ref_id\' argument should be specified', + 'Locale' => 'Locale', + 'Missing parameters' => 'Missing parameters', + 'Moderate' => 'Moderate', + 'Only customer' => 'Only customer', + 'Only customer are allowed to publish comment' => 'Only customer are allowed to publish comment', + 'Only customers who have bought this product can publish comment' => 'Only customers who have bought this product can publish comment', + 'Only registered customers can post comments.' => 'Only registered customers can post comments.', + 'Only verified' => 'Only verified', + 'Product %id does not exist' => 'Product %id does not exist', + 'Rating' => 'Rating', + 'Ref' => 'Ref', + 'Ref Id' => 'Ref Id', + 'Reference %ref is not allowed' => 'Reference %ref is not allowed', + 'Sorry, an unknown error occurred. Please try again.' => 'Sorry, an unknown error occurred. Please try again.', + 'Status' => 'Status', + 'Thank you for submitting your comment.' => 'Thank you for submitting your comment.', + 'Title' => 'Title', + 'Username' => 'Username', + 'Verified' => 'Verified', + 'Your comment has been deleted.' => 'Your comment has been deleted.', + 'Your comment will be put online once verified.' => 'Your comment will be put online once verified.', + 'Your request could not be validated. Try it later' => 'Your request could not be validated. Try it later', + 'Your request has been registered. Thank you.' => 'Your request has been registered. Thank you.', + 'which elements could use comments' => 'which elements could use comments', +); diff --git a/I18n/fr_FR.php b/I18n/fr_FR.php new file mode 100755 index 0000000..3b76a8e --- /dev/null +++ b/I18n/fr_FR.php @@ -0,0 +1,43 @@ + 'Abus', + 'Activated' => 'Activé', + 'Allowed references' => 'Références autorisées', + 'Comment could not be removed. Please try later.' => 'Le commentaire n\'a pas pu être supprimé. Veuillez ré-essayer plus tard.', + 'Comment not activated on this element.' => 'Les commentaires ne sont pas autorisés sur cet élément. ', + 'Comments' => 'Commentaires', + 'Comments are not validated automatically.' => 'Les commentaires ne sont pas validés automatiquement.', + 'Content' => 'Message', + 'Customer' => 'Client', + 'Email' => 'Email', + 'For product comments. Only customers that bought the product can post comments.' => 'Pour les commentaires produits. Seuls les clients ayant achetés le produit peuvent publier des commentaires.', + 'Global activation of comments. You can control activation by product, content.' => 'Activation globale des commentaires. Vous pouvez contrôler l\'activation par produit, contenu.', + 'Id' => 'Id', + 'If \'ref\' argument is specified, \'ref_id\' argument should be specified' => 'si l\'argument \'ref\' est renseigné, l\'argument \'ref_id\' est nécessaire.', + 'Locale' => 'Langue', + 'Missing parameters' => 'Paramètres manquants', + 'Moderate' => 'Modération', + 'Only customer' => 'Seuls les clients', + 'Only customer are allowed to publish comment' => 'Seul les clients sont autorisés à publier des commentaires', + 'Only customers who have bought this product can publish comment' => 'Seuls les clients ayant achetés ce produit peuvent publier des commentaires', + 'Only registered customers can post comments.' => 'Seuls les clients enregistrés peuvent publier des commentaires.', + 'Only verified' => 'Uniquement vérifié', + 'Product %id does not exist' => 'Le produit %id n\'existe pas', + 'Rating' => 'Note', + 'Ref' => 'Réf', + 'Ref Id' => 'Réf id', + 'Reference %ref is not allowed' => 'La référence %ref n\'est pas autorisée', + 'Reference not found' => 'Référence inconnue', + 'Sorry, an unknown error occurred. Please try again.' => 'Désolé, une erreur non gérée est apparue. Veuillez ré-essayer.', + 'Status' => 'Statut', + 'Thank you for submitting your comment.' => 'Merci pour votre commentaire.', + 'Title' => 'Titre', + 'Username' => 'Nom', + 'Verified' => 'Vérifié', + 'Your comment has been deleted.' => 'Votre commentaire a été supprimé.', + 'Your comment will be put online once verified.' => 'Votre commentaire sera mis en ligne une fois vérifié.', + 'Your request could not be validated. Try it later' => 'Votre demande ne peux pas être validé. Essayer plus tard.', + 'Your request has been registered. Thank you.' => 'Votre demande a été enregistré. Merci.', + 'which elements could use comments' => 'Indique les éléments pouvant utiliser es commentaires', +); diff --git a/I18n/frontOffice/default/en_US.php b/I18n/frontOffice/default/en_US.php new file mode 100644 index 0000000..0e3cd7d --- /dev/null +++ b/I18n/frontOffice/default/en_US.php @@ -0,0 +1,16 @@ + 'Add your comment', + 'Anonymous' => 'Anonymous', + 'Are you sure ?' => 'Are you sure ?', + 'By %username' => 'By %username', + 'Comments' => 'Comments', + 'Delete' => 'Delete', + 'Load more comments...' => 'Load more comments...', + 'Mark as inappropriate' => 'Mark as inappropriate', + 'No more comments' => 'No more comments', + 'Send' => 'Send', + 'There are no comments yet' => 'There are no comments yet', + 'Verified' => 'Verified', +); diff --git a/I18n/frontOffice/default/fr_FR.php b/I18n/frontOffice/default/fr_FR.php new file mode 100644 index 0000000..3e08460 --- /dev/null +++ b/I18n/frontOffice/default/fr_FR.php @@ -0,0 +1,16 @@ + 'Ajouter votre commentaire', + 'Anonymous' => 'Anonyme', + 'Are you sure ?' => 'Etes-vous certain ?', + 'By %username' => 'Par %username', + 'Comments' => 'Les commentaires', + 'Delete' => 'Supprimer', + 'Load more comments...' => 'Montrer plus de commentaires...', + 'Mark as inappropriate' => 'Marquer comme inaproprié', + 'No more comments' => 'Plus de commentaire', + 'Send' => 'Envoyer', + 'There are no comments yet' => 'Il n\'y a pas encore de commentaire', + 'Verified' => 'Vérifié', +); diff --git a/Loop/CommentLoop.php b/Loop/CommentLoop.php new file mode 100644 index 0000000..48f57e2 --- /dev/null +++ b/Loop/CommentLoop.php @@ -0,0 +1,263 @@ + + */ +class CommentLoop extends BaseLoop implements PropelSearchLoopInterface +{ + protected $timestampable = true; + + protected $cacheRef = []; + + /** + * Definition of loop arguments + * + * @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createIntListTypeArgument('id'), + Argument::createIntListTypeArgument('customer'), + Argument::createAnyTypeArgument('ref'), + Argument::createIntListTypeArgument('ref_id'), + Argument::createIntListTypeArgument('status'), + Argument::createBooleanOrBothTypeArgument('verified', BooleanOrBothType::ANY), + Argument::createAnyTypeArgument('locale'), + Argument::createAnyTypeArgument('load_ref', 0), + new Argument( + 'order', + new Type\TypeCollection( + new Type\EnumListType( + [ + 'id', + 'id_reverse', + 'status', + 'status_reverse', + 'verified', + 'verified_reverse', + 'abuse', + 'abuse_reverse', + 'created', + 'created_reverse', + 'updated', + 'updated_reverse' + ] + ) + ), + 'manual' + ) + ); + } + + /** + * this method returns a Propel ModelCriteria + * + * @return \Propel\Runtime\ActiveQuery\ModelCriteria + */ + public function buildModelCriteria() + { + $search = CommentQuery::create(); + + $id = $this->getId(); + if (null !== $id) { + $search->filterById($id, Criteria::IN); + } + + $customer = $this->getCustomer(); + if (null !== $customer) { + $search->filterByCustomerId($customer, Criteria::IN); + } + + $ref = $this->getRef(); + $refId = $this->getRefId(); + if (null !== $ref || null !== $refId) { + if (null === $ref || null === $refId) { + throw new \InvalidArgumentException( + $this->translator->trans( + "If 'ref' argument is specified, 'ref_id' argument should be specified", + [], + Comment::MESSAGE_DOMAIN + ) + ); + } + + $search->filterByRef($ref); + $search->filterByRefId($refId, Criteria::IN); + } + + $status = $this->getStatus(); + if ($status !== null) { + $search->filterByStatus($status); + } + + $verified = $this->getVerified(); + if ($verified !== BooleanOrBothType::ANY) { + $search->filterByVerified($verified ? 1 : 0); + } + + $locale = $this->getLocale(); + if (null !== $locale) { + $search->filterByLocale($locale); + } + + $orders = $this->getOrder(); + if (null !== $orders) { + foreach ($orders as $order) { + switch ($order) { + case "id": + $search->orderById(Criteria::ASC); + break; + case "id_reverse": + $search->orderById(Criteria::DESC); + break; + case "visible": + $search->orderByStatus(Criteria::ASC); + break; + case "visible_reverse": + $search->orderByStatus(Criteria::DESC); + break; + case "verified": + $search->orderByVerified(Criteria::ASC); + break; + case "verified_reverse": + $search->orderByVerified(Criteria::DESC); + break; + case "abuse": + $search->orderByAbuse(Criteria::ASC); + break; + case "abuse_reverse": + $search->orderByAbuse(Criteria::DESC); + break; + case "rating": + $search->orderByRating(Criteria::ASC); + break; + case "rating_reverse": + $search->orderByRating(Criteria::DESC); + break; + case "created": + $search->addAscendingOrderByColumn('created_at'); + break; + case "created_reverse": + $search->addDescendingOrderByColumn('created_at'); + break; + case "updated": + $search->addAscendingOrderByColumn('updated_at'); + break; + case "updated_reverse": + $search->addDescendingOrderByColumn('updated_at'); + break; + } + } + } + + return $search; + } + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + /** @var \Comment\Model\Comment $comment */ + foreach ($loopResult->getResultDataCollection() as $comment) { + $loopResultRow = new LoopResultRow($comment); + + $loopResultRow + ->set('ID', $comment->getId()) + ->set('USERNAME', $comment->getUsername()) + ->set('EMAIL', $comment->getEmail()) + ->set('CUSTOMER_ID', $comment->getCustomerId()) + ->set('REF', $comment->getRef()) + ->set('REF_ID', $comment->getRefId()) + ->set('TITLE', $comment->getTitle()) + ->set('CONTENT', $comment->getContent()) + ->set('RATING', $comment->getRating()) + ->set('STATUS', $comment->getStatus()) + ->set('VERIFIED', $comment->getVerified()) + ->set('ABUSE', $comment->getAbuse()); + + if (1 == $this->getLoadRef()) { + // dispatch event to get the reference element + $this->getReference( + $loopResultRow, + $comment->getRef(), + $comment->getRefId() + ); + } + + $this->addOutputFields($loopResultRow, $comment); + + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } + + /** + * @param LoopResultRow $loopResultRow + * @param string $ref + * @param int $refId + */ + protected function getReference(LoopResultRow &$loopResultRow, $ref, $refId) + { + $key = sprintf('%s:%s', $ref, $refId); + $data = [ + 'REF_OBJECT' => null, + 'REF_TITLE' => null, + 'REF_EDIT_URL' => null, + 'REF_VIEW_URL' => null + ]; + + if (!array_key_exists($key, $this->cacheRef)) { + $event = new CommentReferenceGetterEvent($ref, $refId, $this->request->getLocale()); + + $this->dispatcher->dispatch( + CommentEvents::COMMENT_REFERENCE_GETTER, + $event + ); + + $data['REF_OBJECT'] = $event->getObject(); + $data['REF_TITLE'] = $event->getTitle(); + $data['REF_EDIT_URL'] = $event->getEditUrl(); + $data['REF_VIEW_URL'] = $event->getViewUrl(); + } else { + $data = $this->cacheRef[$key]; + } + + foreach ($data as $k => $v) { + $loopResultRow->set($k, $v); + } + } +} diff --git a/Model/Base/Comment.php b/Model/Base/Comment.php new file mode 100755 index 0000000..91c0337 --- /dev/null +++ b/Model/Base/Comment.php @@ -0,0 +1,2020 @@ +status = 0; + } + + /** + * Initializes internal state of Comment\Model\Base\Comment object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another Comment instance. If + * obj is an instance of Comment, delegates to + * equals(Comment). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return Comment The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return Comment The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [username] column value. + * + * @return string + */ + public function getUsername() + { + + return $this->username; + } + + /** + * Get the [customer_id] column value. + * + * @return int + */ + public function getCustomerId() + { + + return $this->customer_id; + } + + /** + * Get the [ref] column value. + * + * @return string + */ + public function getRef() + { + + return $this->ref; + } + + /** + * Get the [ref_id] column value. + * + * @return int + */ + public function getRefId() + { + + return $this->ref_id; + } + + /** + * Get the [email] column value. + * + * @return string + */ + public function getEmail() + { + + return $this->email; + } + + /** + * Get the [title] column value. + * + * @return string + */ + public function getTitle() + { + + return $this->title; + } + + /** + * Get the [content] column value. + * + * @return string + */ + public function getContent() + { + + return $this->content; + } + + /** + * Get the [rating] column value. + * + * @return int + */ + public function getRating() + { + + return $this->rating; + } + + /** + * Get the [status] column value. + * + * @return int + */ + public function getStatus() + { + + return $this->status; + } + + /** + * Get the [verified] column value. + * + * @return int + */ + public function getVerified() + { + + return $this->verified; + } + + /** + * Get the [abuse] column value. + * + * @return int + */ + public function getAbuse() + { + + return $this->abuse; + } + + /** + * Get the [locale] column value. + * + * @return string + */ + public function getLocale() + { + + return $this->locale; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at instanceof \DateTime ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at instanceof \DateTime ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[CommentTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [username] column. + * + * @param string $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setUsername($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->username !== $v) { + $this->username = $v; + $this->modifiedColumns[CommentTableMap::USERNAME] = true; + } + + + return $this; + } // setUsername() + + /** + * Set the value of [customer_id] column. + * + * @param int $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setCustomerId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->customer_id !== $v) { + $this->customer_id = $v; + $this->modifiedColumns[CommentTableMap::CUSTOMER_ID] = true; + } + + if ($this->aCustomer !== null && $this->aCustomer->getId() !== $v) { + $this->aCustomer = null; + } + + + return $this; + } // setCustomerId() + + /** + * Set the value of [ref] column. + * + * @param string $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setRef($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->ref !== $v) { + $this->ref = $v; + $this->modifiedColumns[CommentTableMap::REF] = true; + } + + + return $this; + } // setRef() + + /** + * Set the value of [ref_id] column. + * + * @param int $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setRefId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->ref_id !== $v) { + $this->ref_id = $v; + $this->modifiedColumns[CommentTableMap::REF_ID] = true; + } + + + return $this; + } // setRefId() + + /** + * Set the value of [email] column. + * + * @param string $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setEmail($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->email !== $v) { + $this->email = $v; + $this->modifiedColumns[CommentTableMap::EMAIL] = true; + } + + + return $this; + } // setEmail() + + /** + * Set the value of [title] column. + * + * @param string $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setTitle($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->title !== $v) { + $this->title = $v; + $this->modifiedColumns[CommentTableMap::TITLE] = true; + } + + + return $this; + } // setTitle() + + /** + * Set the value of [content] column. + * + * @param string $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setContent($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->content !== $v) { + $this->content = $v; + $this->modifiedColumns[CommentTableMap::CONTENT] = true; + } + + + return $this; + } // setContent() + + /** + * Set the value of [rating] column. + * + * @param int $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setRating($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->rating !== $v) { + $this->rating = $v; + $this->modifiedColumns[CommentTableMap::RATING] = true; + } + + + return $this; + } // setRating() + + /** + * Set the value of [status] column. + * + * @param int $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setStatus($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->status !== $v) { + $this->status = $v; + $this->modifiedColumns[CommentTableMap::STATUS] = true; + } + + + return $this; + } // setStatus() + + /** + * Set the value of [verified] column. + * + * @param int $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setVerified($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->verified !== $v) { + $this->verified = $v; + $this->modifiedColumns[CommentTableMap::VERIFIED] = true; + } + + + return $this; + } // setVerified() + + /** + * Set the value of [abuse] column. + * + * @param int $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setAbuse($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->abuse !== $v) { + $this->abuse = $v; + $this->modifiedColumns[CommentTableMap::ABUSE] = true; + } + + + return $this; + } // setAbuse() + + /** + * Set the value of [locale] column. + * + * @param string $v new value + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setLocale($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->locale !== $v) { + $this->locale = $v; + $this->modifiedColumns[CommentTableMap::LOCALE] = true; + } + + + return $this; + } // setLocale() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[CommentTableMap::CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \Comment\Model\Comment The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[CommentTableMap::UPDATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->status !== 0) { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : CommentTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : CommentTableMap::translateFieldName('Username', TableMap::TYPE_PHPNAME, $indexType)]; + $this->username = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : CommentTableMap::translateFieldName('CustomerId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->customer_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : CommentTableMap::translateFieldName('Ref', TableMap::TYPE_PHPNAME, $indexType)]; + $this->ref = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : CommentTableMap::translateFieldName('RefId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->ref_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : CommentTableMap::translateFieldName('Email', TableMap::TYPE_PHPNAME, $indexType)]; + $this->email = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : CommentTableMap::translateFieldName('Title', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : CommentTableMap::translateFieldName('Content', TableMap::TYPE_PHPNAME, $indexType)]; + $this->content = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : CommentTableMap::translateFieldName('Rating', TableMap::TYPE_PHPNAME, $indexType)]; + $this->rating = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : CommentTableMap::translateFieldName('Status', TableMap::TYPE_PHPNAME, $indexType)]; + $this->status = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : CommentTableMap::translateFieldName('Verified', TableMap::TYPE_PHPNAME, $indexType)]; + $this->verified = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : CommentTableMap::translateFieldName('Abuse', TableMap::TYPE_PHPNAME, $indexType)]; + $this->abuse = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : CommentTableMap::translateFieldName('Locale', TableMap::TYPE_PHPNAME, $indexType)]; + $this->locale = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : CommentTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 14 + $startcol : CommentTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 15; // 15 = CommentTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \Comment\Model\Comment object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aCustomer !== null && $this->customer_id !== $this->aCustomer->getId()) { + $this->aCustomer = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(CommentTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildCommentQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCustomer = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see Comment::setDeleted() + * @see Comment::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildCommentQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(CommentTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(CommentTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(CommentTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + CommentTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCustomer !== null) { + if ($this->aCustomer->isModified() || $this->aCustomer->isNew()) { + $affectedRows += $this->aCustomer->save($con); + } + $this->setCustomer($this->aCustomer); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[CommentTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . CommentTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(CommentTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(CommentTableMap::USERNAME)) { + $modifiedColumns[':p' . $index++] = 'USERNAME'; + } + if ($this->isColumnModified(CommentTableMap::CUSTOMER_ID)) { + $modifiedColumns[':p' . $index++] = 'CUSTOMER_ID'; + } + if ($this->isColumnModified(CommentTableMap::REF)) { + $modifiedColumns[':p' . $index++] = 'REF'; + } + if ($this->isColumnModified(CommentTableMap::REF_ID)) { + $modifiedColumns[':p' . $index++] = 'REF_ID'; + } + if ($this->isColumnModified(CommentTableMap::EMAIL)) { + $modifiedColumns[':p' . $index++] = 'EMAIL'; + } + if ($this->isColumnModified(CommentTableMap::TITLE)) { + $modifiedColumns[':p' . $index++] = 'TITLE'; + } + if ($this->isColumnModified(CommentTableMap::CONTENT)) { + $modifiedColumns[':p' . $index++] = 'CONTENT'; + } + if ($this->isColumnModified(CommentTableMap::RATING)) { + $modifiedColumns[':p' . $index++] = 'RATING'; + } + if ($this->isColumnModified(CommentTableMap::STATUS)) { + $modifiedColumns[':p' . $index++] = 'STATUS'; + } + if ($this->isColumnModified(CommentTableMap::VERIFIED)) { + $modifiedColumns[':p' . $index++] = 'VERIFIED'; + } + if ($this->isColumnModified(CommentTableMap::ABUSE)) { + $modifiedColumns[':p' . $index++] = 'ABUSE'; + } + if ($this->isColumnModified(CommentTableMap::LOCALE)) { + $modifiedColumns[':p' . $index++] = 'LOCALE'; + } + if ($this->isColumnModified(CommentTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = 'CREATED_AT'; + } + if ($this->isColumnModified(CommentTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = 'UPDATED_AT'; + } + + $sql = sprintf( + 'INSERT INTO comment (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'USERNAME': + $stmt->bindValue($identifier, $this->username, PDO::PARAM_STR); + break; + case 'CUSTOMER_ID': + $stmt->bindValue($identifier, $this->customer_id, PDO::PARAM_INT); + break; + case 'REF': + $stmt->bindValue($identifier, $this->ref, PDO::PARAM_STR); + break; + case 'REF_ID': + $stmt->bindValue($identifier, $this->ref_id, PDO::PARAM_INT); + break; + case 'EMAIL': + $stmt->bindValue($identifier, $this->email, PDO::PARAM_STR); + break; + case 'TITLE': + $stmt->bindValue($identifier, $this->title, PDO::PARAM_STR); + break; + case 'CONTENT': + $stmt->bindValue($identifier, $this->content, PDO::PARAM_STR); + break; + case 'RATING': + $stmt->bindValue($identifier, $this->rating, PDO::PARAM_INT); + break; + case 'STATUS': + $stmt->bindValue($identifier, $this->status, PDO::PARAM_INT); + break; + case 'VERIFIED': + $stmt->bindValue($identifier, $this->verified, PDO::PARAM_INT); + break; + case 'ABUSE': + $stmt->bindValue($identifier, $this->abuse, PDO::PARAM_INT); + break; + case 'LOCALE': + $stmt->bindValue($identifier, $this->locale, PDO::PARAM_STR); + break; + case 'CREATED_AT': + $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case 'UPDATED_AT': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = CommentTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getUsername(); + break; + case 2: + return $this->getCustomerId(); + break; + case 3: + return $this->getRef(); + break; + case 4: + return $this->getRefId(); + break; + case 5: + return $this->getEmail(); + break; + case 6: + return $this->getTitle(); + break; + case 7: + return $this->getContent(); + break; + case 8: + return $this->getRating(); + break; + case 9: + return $this->getStatus(); + break; + case 10: + return $this->getVerified(); + break; + case 11: + return $this->getAbuse(); + break; + case 12: + return $this->getLocale(); + break; + case 13: + return $this->getCreatedAt(); + break; + case 14: + return $this->getUpdatedAt(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['Comment'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['Comment'][$this->getPrimaryKey()] = true; + $keys = CommentTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getUsername(), + $keys[2] => $this->getCustomerId(), + $keys[3] => $this->getRef(), + $keys[4] => $this->getRefId(), + $keys[5] => $this->getEmail(), + $keys[6] => $this->getTitle(), + $keys[7] => $this->getContent(), + $keys[8] => $this->getRating(), + $keys[9] => $this->getStatus(), + $keys[10] => $this->getVerified(), + $keys[11] => $this->getAbuse(), + $keys[12] => $this->getLocale(), + $keys[13] => $this->getCreatedAt(), + $keys[14] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aCustomer) { + $result['Customer'] = $this->aCustomer->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = CommentTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setUsername($value); + break; + case 2: + $this->setCustomerId($value); + break; + case 3: + $this->setRef($value); + break; + case 4: + $this->setRefId($value); + break; + case 5: + $this->setEmail($value); + break; + case 6: + $this->setTitle($value); + break; + case 7: + $this->setContent($value); + break; + case 8: + $this->setRating($value); + break; + case 9: + $this->setStatus($value); + break; + case 10: + $this->setVerified($value); + break; + case 11: + $this->setAbuse($value); + break; + case 12: + $this->setLocale($value); + break; + case 13: + $this->setCreatedAt($value); + break; + case 14: + $this->setUpdatedAt($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = CommentTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setUsername($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setCustomerId($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setRef($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setRefId($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setEmail($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setTitle($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setContent($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setRating($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setStatus($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setVerified($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setAbuse($arr[$keys[11]]); + if (array_key_exists($keys[12], $arr)) $this->setLocale($arr[$keys[12]]); + if (array_key_exists($keys[13], $arr)) $this->setCreatedAt($arr[$keys[13]]); + if (array_key_exists($keys[14], $arr)) $this->setUpdatedAt($arr[$keys[14]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(CommentTableMap::DATABASE_NAME); + + if ($this->isColumnModified(CommentTableMap::ID)) $criteria->add(CommentTableMap::ID, $this->id); + if ($this->isColumnModified(CommentTableMap::USERNAME)) $criteria->add(CommentTableMap::USERNAME, $this->username); + if ($this->isColumnModified(CommentTableMap::CUSTOMER_ID)) $criteria->add(CommentTableMap::CUSTOMER_ID, $this->customer_id); + if ($this->isColumnModified(CommentTableMap::REF)) $criteria->add(CommentTableMap::REF, $this->ref); + if ($this->isColumnModified(CommentTableMap::REF_ID)) $criteria->add(CommentTableMap::REF_ID, $this->ref_id); + if ($this->isColumnModified(CommentTableMap::EMAIL)) $criteria->add(CommentTableMap::EMAIL, $this->email); + if ($this->isColumnModified(CommentTableMap::TITLE)) $criteria->add(CommentTableMap::TITLE, $this->title); + if ($this->isColumnModified(CommentTableMap::CONTENT)) $criteria->add(CommentTableMap::CONTENT, $this->content); + if ($this->isColumnModified(CommentTableMap::RATING)) $criteria->add(CommentTableMap::RATING, $this->rating); + if ($this->isColumnModified(CommentTableMap::STATUS)) $criteria->add(CommentTableMap::STATUS, $this->status); + if ($this->isColumnModified(CommentTableMap::VERIFIED)) $criteria->add(CommentTableMap::VERIFIED, $this->verified); + if ($this->isColumnModified(CommentTableMap::ABUSE)) $criteria->add(CommentTableMap::ABUSE, $this->abuse); + if ($this->isColumnModified(CommentTableMap::LOCALE)) $criteria->add(CommentTableMap::LOCALE, $this->locale); + if ($this->isColumnModified(CommentTableMap::CREATED_AT)) $criteria->add(CommentTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(CommentTableMap::UPDATED_AT)) $criteria->add(CommentTableMap::UPDATED_AT, $this->updated_at); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(CommentTableMap::DATABASE_NAME); + $criteria->add(CommentTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \Comment\Model\Comment (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setUsername($this->getUsername()); + $copyObj->setCustomerId($this->getCustomerId()); + $copyObj->setRef($this->getRef()); + $copyObj->setRefId($this->getRefId()); + $copyObj->setEmail($this->getEmail()); + $copyObj->setTitle($this->getTitle()); + $copyObj->setContent($this->getContent()); + $copyObj->setRating($this->getRating()); + $copyObj->setStatus($this->getStatus()); + $copyObj->setVerified($this->getVerified()); + $copyObj->setAbuse($this->getAbuse()); + $copyObj->setLocale($this->getLocale()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \Comment\Model\Comment Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildCustomer object. + * + * @param ChildCustomer $v + * @return \Comment\Model\Comment The current object (for fluent API support) + * @throws PropelException + */ + public function setCustomer(ChildCustomer $v = null) + { + if ($v === null) { + $this->setCustomerId(NULL); + } else { + $this->setCustomerId($v->getId()); + } + + $this->aCustomer = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCustomer object, it will not be re-added. + if ($v !== null) { + $v->addComment($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCustomer object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCustomer The associated ChildCustomer object. + * @throws PropelException + */ + public function getCustomer(ConnectionInterface $con = null) + { + if ($this->aCustomer === null && ($this->customer_id !== null)) { + $this->aCustomer = CustomerQuery::create()->findPk($this->customer_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCustomer->addComments($this); + */ + } + + return $this->aCustomer; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->username = null; + $this->customer_id = null; + $this->ref = null; + $this->ref_id = null; + $this->email = null; + $this->title = null; + $this->content = null; + $this->rating = null; + $this->status = null; + $this->verified = null; + $this->abuse = null; + $this->locale = null; + $this->created_at = null; + $this->updated_at = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCustomer = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(CommentTableMap::DEFAULT_STRING_FORMAT); + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildComment The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[CommentTableMap::UPDATED_AT] = true; + + return $this; + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/Model/Base/CommentQuery.php b/Model/Base/CommentQuery.php new file mode 100755 index 0000000..8c3a718 --- /dev/null +++ b/Model/Base/CommentQuery.php @@ -0,0 +1,1057 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildComment|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = CommentTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(CommentTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildComment A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, USERNAME, CUSTOMER_ID, REF, REF_ID, EMAIL, TITLE, CONTENT, RATING, STATUS, VERIFIED, ABUSE, LOCALE, CREATED_AT, UPDATED_AT FROM comment WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildComment(); + $obj->hydrate($row); + CommentTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildComment|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(CommentTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(CommentTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(CommentTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(CommentTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the username column + * + * Example usage: + * + * $query->filterByUsername('fooValue'); // WHERE username = 'fooValue' + * $query->filterByUsername('%fooValue%'); // WHERE username LIKE '%fooValue%' + * + * + * @param string $username The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByUsername($username = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($username)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $username)) { + $username = str_replace('*', '%', $username); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CommentTableMap::USERNAME, $username, $comparison); + } + + /** + * Filter the query on the customer_id column + * + * Example usage: + * + * $query->filterByCustomerId(1234); // WHERE customer_id = 1234 + * $query->filterByCustomerId(array(12, 34)); // WHERE customer_id IN (12, 34) + * $query->filterByCustomerId(array('min' => 12)); // WHERE customer_id > 12 + * + * + * @see filterByCustomer() + * + * @param mixed $customerId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByCustomerId($customerId = null, $comparison = null) + { + if (is_array($customerId)) { + $useMinMax = false; + if (isset($customerId['min'])) { + $this->addUsingAlias(CommentTableMap::CUSTOMER_ID, $customerId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($customerId['max'])) { + $this->addUsingAlias(CommentTableMap::CUSTOMER_ID, $customerId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::CUSTOMER_ID, $customerId, $comparison); + } + + /** + * Filter the query on the ref column + * + * Example usage: + * + * $query->filterByRef('fooValue'); // WHERE ref = 'fooValue' + * $query->filterByRef('%fooValue%'); // WHERE ref LIKE '%fooValue%' + * + * + * @param string $ref The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByRef($ref = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($ref)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $ref)) { + $ref = str_replace('*', '%', $ref); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CommentTableMap::REF, $ref, $comparison); + } + + /** + * Filter the query on the ref_id column + * + * Example usage: + * + * $query->filterByRefId(1234); // WHERE ref_id = 1234 + * $query->filterByRefId(array(12, 34)); // WHERE ref_id IN (12, 34) + * $query->filterByRefId(array('min' => 12)); // WHERE ref_id > 12 + * + * + * @param mixed $refId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByRefId($refId = null, $comparison = null) + { + if (is_array($refId)) { + $useMinMax = false; + if (isset($refId['min'])) { + $this->addUsingAlias(CommentTableMap::REF_ID, $refId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($refId['max'])) { + $this->addUsingAlias(CommentTableMap::REF_ID, $refId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::REF_ID, $refId, $comparison); + } + + /** + * Filter the query on the email column + * + * Example usage: + * + * $query->filterByEmail('fooValue'); // WHERE email = 'fooValue' + * $query->filterByEmail('%fooValue%'); // WHERE email LIKE '%fooValue%' + * + * + * @param string $email The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByEmail($email = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($email)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $email)) { + $email = str_replace('*', '%', $email); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CommentTableMap::EMAIL, $email, $comparison); + } + + /** + * Filter the query on the title column + * + * Example usage: + * + * $query->filterByTitle('fooValue'); // WHERE title = 'fooValue' + * $query->filterByTitle('%fooValue%'); // WHERE title LIKE '%fooValue%' + * + * + * @param string $title The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByTitle($title = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($title)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $title)) { + $title = str_replace('*', '%', $title); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CommentTableMap::TITLE, $title, $comparison); + } + + /** + * Filter the query on the content column + * + * Example usage: + * + * $query->filterByContent('fooValue'); // WHERE content = 'fooValue' + * $query->filterByContent('%fooValue%'); // WHERE content LIKE '%fooValue%' + * + * + * @param string $content The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByContent($content = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($content)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $content)) { + $content = str_replace('*', '%', $content); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CommentTableMap::CONTENT, $content, $comparison); + } + + /** + * Filter the query on the rating column + * + * Example usage: + * + * $query->filterByRating(1234); // WHERE rating = 1234 + * $query->filterByRating(array(12, 34)); // WHERE rating IN (12, 34) + * $query->filterByRating(array('min' => 12)); // WHERE rating > 12 + * + * + * @param mixed $rating The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByRating($rating = null, $comparison = null) + { + if (is_array($rating)) { + $useMinMax = false; + if (isset($rating['min'])) { + $this->addUsingAlias(CommentTableMap::RATING, $rating['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($rating['max'])) { + $this->addUsingAlias(CommentTableMap::RATING, $rating['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::RATING, $rating, $comparison); + } + + /** + * Filter the query on the status column + * + * Example usage: + * + * $query->filterByStatus(1234); // WHERE status = 1234 + * $query->filterByStatus(array(12, 34)); // WHERE status IN (12, 34) + * $query->filterByStatus(array('min' => 12)); // WHERE status > 12 + * + * + * @param mixed $status The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByStatus($status = null, $comparison = null) + { + if (is_array($status)) { + $useMinMax = false; + if (isset($status['min'])) { + $this->addUsingAlias(CommentTableMap::STATUS, $status['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($status['max'])) { + $this->addUsingAlias(CommentTableMap::STATUS, $status['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::STATUS, $status, $comparison); + } + + /** + * Filter the query on the verified column + * + * Example usage: + * + * $query->filterByVerified(1234); // WHERE verified = 1234 + * $query->filterByVerified(array(12, 34)); // WHERE verified IN (12, 34) + * $query->filterByVerified(array('min' => 12)); // WHERE verified > 12 + * + * + * @param mixed $verified The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByVerified($verified = null, $comparison = null) + { + if (is_array($verified)) { + $useMinMax = false; + if (isset($verified['min'])) { + $this->addUsingAlias(CommentTableMap::VERIFIED, $verified['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($verified['max'])) { + $this->addUsingAlias(CommentTableMap::VERIFIED, $verified['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::VERIFIED, $verified, $comparison); + } + + /** + * Filter the query on the abuse column + * + * Example usage: + * + * $query->filterByAbuse(1234); // WHERE abuse = 1234 + * $query->filterByAbuse(array(12, 34)); // WHERE abuse IN (12, 34) + * $query->filterByAbuse(array('min' => 12)); // WHERE abuse > 12 + * + * + * @param mixed $abuse The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByAbuse($abuse = null, $comparison = null) + { + if (is_array($abuse)) { + $useMinMax = false; + if (isset($abuse['min'])) { + $this->addUsingAlias(CommentTableMap::ABUSE, $abuse['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($abuse['max'])) { + $this->addUsingAlias(CommentTableMap::ABUSE, $abuse['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::ABUSE, $abuse, $comparison); + } + + /** + * Filter the query on the locale column + * + * Example usage: + * + * $query->filterByLocale('fooValue'); // WHERE locale = 'fooValue' + * $query->filterByLocale('%fooValue%'); // WHERE locale LIKE '%fooValue%' + * + * + * @param string $locale The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByLocale($locale = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($locale)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $locale)) { + $locale = str_replace('*', '%', $locale); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(CommentTableMap::LOCALE, $locale, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(CommentTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(CommentTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(CommentTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(CommentTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(CommentTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Comment\Model\Thelia\Model\Customer object + * + * @param \Comment\Model\Thelia\Model\Customer|ObjectCollection $customer The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function filterByCustomer($customer, $comparison = null) + { + if ($customer instanceof \Comment\Model\Thelia\Model\Customer) { + return $this + ->addUsingAlias(CommentTableMap::CUSTOMER_ID, $customer->getId(), $comparison); + } elseif ($customer instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(CommentTableMap::CUSTOMER_ID, $customer->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCustomer() only accepts arguments of type \Comment\Model\Thelia\Model\Customer or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Customer relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function joinCustomer($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Customer'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Customer'); + } + + return $this; + } + + /** + * Use the Customer relation Customer object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Comment\Model\Thelia\Model\CustomerQuery A secondary query class using the current class as primary query + */ + public function useCustomerQuery($relationAlias = null, $joinType = Criteria::LEFT_JOIN) + { + return $this + ->joinCustomer($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Customer', '\Comment\Model\Thelia\Model\CustomerQuery'); + } + + /** + * Exclude object from result + * + * @param ChildComment $comment Object to remove from the list of results + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function prune($comment = null) + { + if ($comment) { + $this->addUsingAlias(CommentTableMap::ID, $comment->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the comment table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + CommentTableMap::clearInstancePool(); + CommentTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildComment or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildComment object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(CommentTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + CommentTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + CommentTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(CommentTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(CommentTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(CommentTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(CommentTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(CommentTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildCommentQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(CommentTableMap::CREATED_AT); + } + +} // CommentQuery diff --git a/Model/Comment.php b/Model/Comment.php new file mode 100755 index 0000000..aa25e78 --- /dev/null +++ b/Model/Comment.php @@ -0,0 +1,16 @@ + array('Id', 'Username', 'CustomerId', 'Ref', 'RefId', 'Email', 'Title', 'Content', 'Rating', 'Status', 'Verified', 'Abuse', 'Locale', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'username', 'customerId', 'ref', 'refId', 'email', 'title', 'content', 'rating', 'status', 'verified', 'abuse', 'locale', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(CommentTableMap::ID, CommentTableMap::USERNAME, CommentTableMap::CUSTOMER_ID, CommentTableMap::REF, CommentTableMap::REF_ID, CommentTableMap::EMAIL, CommentTableMap::TITLE, CommentTableMap::CONTENT, CommentTableMap::RATING, CommentTableMap::STATUS, CommentTableMap::VERIFIED, CommentTableMap::ABUSE, CommentTableMap::LOCALE, CommentTableMap::CREATED_AT, CommentTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'USERNAME', 'CUSTOMER_ID', 'REF', 'REF_ID', 'EMAIL', 'TITLE', 'CONTENT', 'RATING', 'STATUS', 'VERIFIED', 'ABUSE', 'LOCALE', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'username', 'customer_id', 'ref', 'ref_id', 'email', 'title', 'content', 'rating', 'status', 'verified', 'abuse', 'locale', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Username' => 1, 'CustomerId' => 2, 'Ref' => 3, 'RefId' => 4, 'Email' => 5, 'Title' => 6, 'Content' => 7, 'Rating' => 8, 'Status' => 9, 'Verified' => 10, 'Abuse' => 11, 'Locale' => 12, 'CreatedAt' => 13, 'UpdatedAt' => 14, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'username' => 1, 'customerId' => 2, 'ref' => 3, 'refId' => 4, 'email' => 5, 'title' => 6, 'content' => 7, 'rating' => 8, 'status' => 9, 'verified' => 10, 'abuse' => 11, 'locale' => 12, 'createdAt' => 13, 'updatedAt' => 14, ), + self::TYPE_COLNAME => array(CommentTableMap::ID => 0, CommentTableMap::USERNAME => 1, CommentTableMap::CUSTOMER_ID => 2, CommentTableMap::REF => 3, CommentTableMap::REF_ID => 4, CommentTableMap::EMAIL => 5, CommentTableMap::TITLE => 6, CommentTableMap::CONTENT => 7, CommentTableMap::RATING => 8, CommentTableMap::STATUS => 9, CommentTableMap::VERIFIED => 10, CommentTableMap::ABUSE => 11, CommentTableMap::LOCALE => 12, CommentTableMap::CREATED_AT => 13, CommentTableMap::UPDATED_AT => 14, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'USERNAME' => 1, 'CUSTOMER_ID' => 2, 'REF' => 3, 'REF_ID' => 4, 'EMAIL' => 5, 'TITLE' => 6, 'CONTENT' => 7, 'RATING' => 8, 'STATUS' => 9, 'VERIFIED' => 10, 'ABUSE' => 11, 'LOCALE' => 12, 'CREATED_AT' => 13, 'UPDATED_AT' => 14, ), + self::TYPE_FIELDNAME => array('id' => 0, 'username' => 1, 'customer_id' => 2, 'ref' => 3, 'ref_id' => 4, 'email' => 5, 'title' => 6, 'content' => 7, 'rating' => 8, 'status' => 9, 'verified' => 10, 'abuse' => 11, 'locale' => 12, 'created_at' => 13, 'updated_at' => 14, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('comment'); + $this->setPhpName('Comment'); + $this->setClassName('\\Comment\\Model\\Comment'); + $this->setPackage('Comment.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('USERNAME', 'Username', 'VARCHAR', false, 255, null); + $this->addForeignKey('CUSTOMER_ID', 'CustomerId', 'INTEGER', 'customer', 'ID', false, null, null); + $this->addColumn('REF', 'Ref', 'VARCHAR', false, 255, null); + $this->addColumn('REF_ID', 'RefId', 'INTEGER', false, null, null); + $this->addColumn('EMAIL', 'Email', 'VARCHAR', false, 255, null); + $this->addColumn('TITLE', 'Title', 'VARCHAR', false, 255, null); + $this->addColumn('CONTENT', 'Content', 'CLOB', false, null, null); + $this->addColumn('RATING', 'Rating', 'TINYINT', false, null, null); + $this->addColumn('STATUS', 'Status', 'TINYINT', false, null, 0); + $this->addColumn('VERIFIED', 'Verified', 'TINYINT', false, null, null); + $this->addColumn('ABUSE', 'Abuse', 'INTEGER', false, null, null); + $this->addColumn('LOCALE', 'Locale', 'VARCHAR', false, 10, null); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Customer', '\\Comment\\Model\\Thelia\\Model\\Customer', RelationMap::MANY_TO_ONE, array('customer_id' => 'id', ), 'CASCADE', 'RESTRICT'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? CommentTableMap::CLASS_DEFAULT : CommentTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (Comment object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = CommentTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = CommentTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + CommentTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = CommentTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + CommentTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = CommentTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = CommentTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + CommentTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(CommentTableMap::ID); + $criteria->addSelectColumn(CommentTableMap::USERNAME); + $criteria->addSelectColumn(CommentTableMap::CUSTOMER_ID); + $criteria->addSelectColumn(CommentTableMap::REF); + $criteria->addSelectColumn(CommentTableMap::REF_ID); + $criteria->addSelectColumn(CommentTableMap::EMAIL); + $criteria->addSelectColumn(CommentTableMap::TITLE); + $criteria->addSelectColumn(CommentTableMap::CONTENT); + $criteria->addSelectColumn(CommentTableMap::RATING); + $criteria->addSelectColumn(CommentTableMap::STATUS); + $criteria->addSelectColumn(CommentTableMap::VERIFIED); + $criteria->addSelectColumn(CommentTableMap::ABUSE); + $criteria->addSelectColumn(CommentTableMap::LOCALE); + $criteria->addSelectColumn(CommentTableMap::CREATED_AT); + $criteria->addSelectColumn(CommentTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.USERNAME'); + $criteria->addSelectColumn($alias . '.CUSTOMER_ID'); + $criteria->addSelectColumn($alias . '.REF'); + $criteria->addSelectColumn($alias . '.REF_ID'); + $criteria->addSelectColumn($alias . '.EMAIL'); + $criteria->addSelectColumn($alias . '.TITLE'); + $criteria->addSelectColumn($alias . '.CONTENT'); + $criteria->addSelectColumn($alias . '.RATING'); + $criteria->addSelectColumn($alias . '.STATUS'); + $criteria->addSelectColumn($alias . '.VERIFIED'); + $criteria->addSelectColumn($alias . '.ABUSE'); + $criteria->addSelectColumn($alias . '.LOCALE'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(CommentTableMap::DATABASE_NAME)->getTable(CommentTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(CommentTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(CommentTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new CommentTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a Comment or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or Comment object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \Comment\Model\Comment) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(CommentTableMap::DATABASE_NAME); + $criteria->add(CommentTableMap::ID, (array) $values, Criteria::IN); + } + + $query = CommentQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { CommentTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { CommentTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the comment table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return CommentQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a Comment or Criteria object. + * + * @param mixed $criteria Criteria or Comment object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from Comment object + } + + if ($criteria->containsKey(CommentTableMap::ID) && $criteria->keyContainsValue(CommentTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.CommentTableMap::ID.')'); + } + + + // Set the correct dbName + $query = CommentQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // CommentTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +CommentTableMap::buildTableMap(); diff --git a/README.md b/README.md new file mode 100644 index 0000000..d5b655a --- /dev/null +++ b/README.md @@ -0,0 +1,95 @@ +# Module Comment + +The module **Comment** allows customer to add comments on different elements of the website : product, content, ... + +A comment is composed of a : + +- title +- message +- rating +- is related to a customer + +The message can be moderated by a administrator before being displayed on the website (recommended). + +Only registered and logged in customer can post comment on the website. You can also only authorized customers to post +comment on products that they have bought. Customers will receive an email after 15 days (by default) to encourage them +to post comment. + +If the comment has been accepted the customer can edit or delete it. + +This module is compatible with Thelia version 2.1 or greater. + +## Installation + +### Manually + +* Copy the module into ```/local/modules/``` directory and be sure that the name of the module is Comment. +* Activate it in your thelia administration panel + +### Composer + +Add it in your main thelia composer.json file + +``` +composer require your-vendor/comment-module:~1.0 +``` + +## Usage + +In back-office, the configuration page allows you to configure the module. + +In the tools menu, a new page displays comments and let you manage them. + +In the front office, an integration is provided for the default template. It uses hooks, so it's activated by default. + +You can override these smarty templates in the current template. You have to put your templates files in this directory + (with default template) : `template/frontOffice/default/modules/Comment/` + +## Loop + +The module provides a new loop : **comment** + +### Input arguments + +|Argument |Description | +|--- |--- | +|**id** | the comment id | +|**customer** | the customer id | +|**ref** | the reference key. eg : product | +|**ref_id** | the reference id. (the product id) | +|**status** | the status of the comment : 0 = pending, 1 = accepted | +|**verified** | the customer has bought the product | +|**locale** | the locale of the comment : fr_FR | +|**load_ref** | load or not the reference object. default = 0 | + +### Output arguments + +|Variable |Description | +|--- |--- | +|$ID | the comment id | +|$USERNAME | the username | +|$EMAIL | the email | +|$CUSTOMER_ID | the customer id | +|$REF | the reference key | +|$REF_ID | the reference id | +|$TITLE | the title | +|$CONTENT | the content | +|$RATING | the rating | +|$STATUS | the status : : 0 = pending, 1 = accepted | +|$VERIFIED | 0 : not verified / not applicable, 1 = the customer has bought the product | +|$ABUSE | an abuse counter. | + +## how to get the rating of a product + +Ratings are stored in the meta_data table. to retrieve the rating, you can use the smarty function `meta` like this : + +```smarty +{$rating={meta meta="COMMENT_RATING" key="product" id="10"}} +{if $rating} + + rating: {$rating} + +{/if} +``` + + diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..b3f1a8c --- /dev/null +++ b/composer.json @@ -0,0 +1,11 @@ +{ + "name": "thelia/comment-module", + "license": "LGPL-3.0+", + "type": "thelia-module", + "require": { + "thelia/installer": "~1.1" + }, + "extra": { + "installer-name": "Comment" + } +} \ No newline at end of file diff --git a/templates/backOffice/default/assets/js/comment.js b/templates/backOffice/default/assets/js/comment.js new file mode 100644 index 0000000..8c812a1 --- /dev/null +++ b/templates/backOffice/default/assets/js/comment.js @@ -0,0 +1,30 @@ +;(function($) { + $(document).ready(function(){ + + $('#comment-save').on('click', function(){ + + var $link, $form, $list; + + $link = $(this); + $form = $link.parents('form').first(); + $list = $form.find('#comment-status').first(); + + $.ajax({ + type: "POST", + dataType: 'json', + data: {status: $list.val()}, + url: $form.attr('action') + }).done(function(data, textStatus, jqXHR){ + if (data.success) { + $list.val(data.status); + } else { + $list.val(data.status); + } + }).fail(function(jqXHR, textStatus, errorThrown){ + + }); + + }); + + }); +})(jQuery); diff --git a/templates/backOffice/default/comment-edit.html b/templates/backOffice/default/comment-edit.html new file mode 100644 index 0000000..b34333f --- /dev/null +++ b/templates/backOffice/default/comment-edit.html @@ -0,0 +1,178 @@ +{extends file="admin-layout.tpl"} + +{block name="no-return-functions"} +{$admin_current_location = 'configuration'} +{/block} + +{block name="page-title"}{intl d='comment.bo.default' l='Edit comment'}{/block} + +{block name="check-module"}comment{/block} +{block name="check-access"}update{/block} + +{block name="main-content"} + +{include file="commons.html" scope="parent"} +
+ +
+ + {loop name="comment_edit" type="comment" hidden="*" id="$comment_id" backend_context="1" limit="1"} + + + +
+
+
+ +
+ {intl d='comment.bo.default' l="Edit comment %name" name={$ID}} +
+ +
+
+ {form name="admin.comment.modification.form" blo=1} + +
+ {* Be sure to get the comment ID, even if the form could not be validated *} + + + {include file="includes/inner-form-toolbar.html" close_url="{url path='/admin/module/comments'}"} + + {form_hidden_fields form=$form} + + {form_field form=$form field='success_url'} + + {/form_field} + + {form_field form=$form field='id'} + + {/form_field} + + {if $form_error}
{$form_error_message}
{/if} + + {form_field form=$form field="ref"} + + {/form_field} + + {form_field form=$form field="ref_id"} + + {/form_field} + + {form_field form=$form field="status"} +
+ + +
+ {/form_field} + + {if $CUSTOMER_ID } + {form_field form=$form field="customer_id"} +
+ + + {loop type="customer" name="customer" id="{$CUSTOMER_ID}" current="no" backend_context="1"} + + {$FIRSTNAME} {$LASTNAME} + + {/loop} + {elseloop rel="customer"} + {intl d='comment.bo.default' l="Unknow customer %id" id="{$CUSTOMER_ID}" } + {/elseloop} +
+ {/form_field} + {else} + {form_field form=$form field="username"} +
+ + +
+ {/form_field} + + {form_field form=$form field="email"} +
+ + +
+ {/form_field} + {/if} + + {form_field form=$form field="locale"} +
+ + +
+ {/form_field} + + {form_field form=$form field="title"} +
+ + +
+ {/form_field} + + {form_field form=$form field="content"} +
+ + +
+ {/form_field} + + {form_field form=$form field='verified'} +
+ +
+ {/form_field} + + {form_field form=$form field="rating"} +
+ + +
+ {/form_field} + +
+
+

{intl d='comment.bo.default' l='Comment created on %date_create. Last modification: %date_change' date_create="{format_date date=$CREATE_DATE}" date_change="{format_date date=$UPDATE_DATE}"}

+
+
+ +
+ + {/form} +
+
+
+
+ +
+ + {/loop} + + {elseloop rel="comment_edit"} +
+
+
+ {intl d='comment.bo.default' l="Sorry, comment ID=%id was not found." id={$comment_id}} +
+
+
+ {/elseloop} + +
+
+{/block} + +{block name="javascript-last-call"} +{hook name="comment.edit-js" location="comment-edit-js" } +{/block} \ No newline at end of file diff --git a/templates/backOffice/default/comments.html b/templates/backOffice/default/comments.html new file mode 100644 index 0000000..b42fa24 --- /dev/null +++ b/templates/backOffice/default/comments.html @@ -0,0 +1,449 @@ +{extends file="admin-layout.tpl"} + +{block name="no-return-functions"} +{$admin_current_location = 'configuration'} +{/block} + +{block name="page-title"}{intl d='comment.bo.default' l='Comments'}{/block} + +{block name="check-module"}comment{/block} +{block name="check-access"}view{/block} + +{block name="main-content"} + +{include file="commons.html" scope="parent"} + +
+ +
+ + + + {hook name="comments.top" location="comments_top" } + + {if $error_message} +
+
+
+ {$error_message} +
+
+
+ {/if} + + {* Loop Filter *} + {$loop_limit={$smarty.get.loop_limit|default:20}} + {$loop_page={$smarty.get.page|default:1}} + {$loop_order={$smarty.get.loop_order|default:'created_reverse'}} + {$loop_status={$smarty.get.loop_status|default:''}} + + {assign var="amount" value={count type="comment" status=$loop_status order=$loop_order backend_context="1"}} + {if $amount < $loop_limit * $loop_page} + {$loop_page=1} + {/if} + +
+
+
+
+ + + + + + + + + + + + + {loop type="comment" name="comment.list" status=$loop_status order=$loop_order page=$loop_page limit=$loop_limit load_ref="1" backend_context="1"} + + + + {* Author *} + + + {* Comment *} + + + {* Reference *} + + + + + {/loop} + + + + + + +
+ {intl d='comment.bo.default' l="Comments management"} + + {* No create action for now + {loop type="auth" name="can_create" role="ADMIN" module="comment" access="CREATE"} + + + + {/loop} + *} + + {intl d='comment.bo.default' l='Send email to customer'} + + +
+ +
+
+ + +
+
+
+ +
+ +
+ +
{intl d='comment.bo.default' l="ID"}{intl d='comment.bo.default' l="Author"}{intl d='comment.bo.default' l="Comment"}{intl d='comment.bo.default' l="Reference"}{intl d='comment.bo.default' l="Actions"}
{$ID} + {if $CUSTOMER_ID} + {loop type="customer" name="customer" id="{$CUSTOMER_ID}" current="no" backend_context="1"} + +
+ {$FIRSTNAME} {$LASTNAME} +
+ {/loop} + {elseloop rel="customer"} + {intl d='comment.bo.default' l="Unknow customer %id" id="{$CUSTOMER_ID}" } + {/elseloop} + {else} + {intl d='comment.bo.default' l="not a customer"}
+ +
+ {$USERNAME} +
+ {/if} +
+

{$TITLE}

+

{$CONTENT}

+
    +
  • {intl d='comment.bo.default' l="Posted: "} {format_date date={$CREATED} output="datetime"}
  • +
  • {intl d='comment.bo.default' l="rating: "} {$RATING}
  • +
  • {intl d='comment.bo.default' l="verified: "} {if $VERIFIED}{intl d='comment.bo.default' l='yes'}{else}{intl d='comment.bo.default' l='no'}{/if}
  • +
+
+ {if $REF_VIEW_URL} + + {/if} + {if $REF_TITLE}{$REF_TITLE} {/if} + ({$REF}: {$REF_ID}) + {if $REF_VIEW_URL} + + {/if} + + + + +
+ {include + file = "includes/pagination.html" + + loop_ref = "comment.list" + max_page_count = $loop_limit + page_url = "{url path={navigate to="current"} product_order=$loop_page}" + } + +
+ {* + {if $amount > $limit} +
+ {intl d='comment.bo.default' l="Pagination"} +
    + + + {pageloop rel="comment.list" limit=$loop_limit} + {$PAGE} + {if $PAGE eq $LAST} + + {/if} + {/pageloop} +
+
+ {/if} + *} + + +
+
+ +
+ + {hook name="comments.bottom" location="comments_bottom" } + +
+
+ + + +{* +{form name="thelia.lang.create"} + + +{* Capture the dialog body, to pass it to the generic dialog *} +{* todo create comment +{capture "creation_dialog"} + +{/capture} + +{include + file = "includes/generic-create-dialog.html" + + dialog_id = "creation_dialog" + dialog_title = {intl d='comment.bo.default' l="Create a new comment"} + dialog_body = {$smarty.capture.creation_dialog nofilter} + + dialog_ok_label = {intl d='comment.bo.default' l="Create this comment"} + + form_action = {url path='/admin/configuration/comments/add'} + form_enctype = {form_enctype form=$form} + form_error_message = $form_error_message +} +{/form} +*} + +{* Delete confirmation dialog *} + +{capture "delete_dialog"} + + {hook name="comments.delete-form" location="comments_delete_form" } +{/capture} + +{include + file = "includes/generic-confirm-dialog.html" + + dialog_id = "delete_dialog" + dialog_title = {intl d='comment.bo.default' l="Delete comment"} + dialog_message = {intl d='comment.bo.default' l="Do you really want to delete this comment ?"} + + form_action = {token_url path='/admin/module/comment/delete'} + form_content = {$smarty.capture.delete_dialog nofilter} + form_error_message = $error_delete_message +} + +
+ + + + + +{/block} + +{block name="javascript-initialization"} + +{javascripts file='assets/js/main.js'} + +{/javascripts} + + +{/block} + +{block name="javascript-last-call"} +{hook name="comments.js" location="comments-js" } +{/block} \ No newline at end of file diff --git a/templates/backOffice/default/commons.html b/templates/backOffice/default/commons.html new file mode 100644 index 0000000..87fe4b6 --- /dev/null +++ b/templates/backOffice/default/commons.html @@ -0,0 +1,9 @@ +{* Status *} + +{$comment_status=[]} +{$comment_status['0']=['label' => {intl d='comment.bo.default' l="Pending"}, 'css' => 'default']} +{$comment_status['1']=['label' => {intl d='comment.bo.default' l="Accepted"}, 'css' => 'success']} +{$comment_status['2']=['label' => {intl d='comment.bo.default' l="Refused"}, 'css' => 'danger']} +{$comment_status['3']=['label' => {intl d='comment.bo.default' l="Abused"}, 'css' => 'warning']} + + \ No newline at end of file diff --git a/templates/backOffice/default/configuration.html b/templates/backOffice/default/configuration.html new file mode 100644 index 0000000..3e1c7e8 --- /dev/null +++ b/templates/backOffice/default/configuration.html @@ -0,0 +1,80 @@ +
+
+ +
+ {intl d='comment.bo.default' l='Comment configuration.'} +
+ +
+
+ + {form name="comment.configuration.form"} +
+ + {if $form_error_message}
{$form_error_message}
{/if} + + {form_hidden_fields form=$form} + + {form_field form=$form field='activated'} +
+ + {$label_attr.help} +
+ {/form_field} + + {form_field form=$form field='moderate'} +
+ + {$label_attr.help} +
+ {/form_field} + + {form_field form=$form field='ref_allowed'} +
+ + + {$label_attr.help} +
+ {/form_field} + + {form_field form=$form field='only_customer'} +
+ + {$label_attr.help} +
+ {/form_field} + + {form_field form=$form field='only_verified'} +
+ + {$label_attr.help} +
+ {/form_field} + + {form_field form=$form field='request_customer_ttl'} +
+ + + {$label_attr.help} +
+ {/form_field} + + + +
+ {/form} + +
+ +
+ +
+
\ No newline at end of file diff --git a/templates/backOffice/default/tab-content.html b/templates/backOffice/default/tab-content.html new file mode 100644 index 0000000..8399adc --- /dev/null +++ b/templates/backOffice/default/tab-content.html @@ -0,0 +1,38 @@ +{$activated={meta meta="COMMENT_ACTIVATED" key=$ref id=$id}} +{if $activated === null} + {$activated = "-1"} +{/if} + +
+
+ +
+ {intl d='comment.bo.default' l='Comments activation.'} +
+ +
+
+ +
+ +
+ + +
+ + + +
+ +
+ +
+ +
+
diff --git a/templates/email/default/request-customer-comment.html b/templates/email/default/request-customer-comment.html new file mode 100644 index 0000000..1d4a07b --- /dev/null +++ b/templates/email/default/request-customer-comment.html @@ -0,0 +1,17 @@ +{default_translation_domain domain="comment.email.default"} + +{loop type="customer" name="customer.order" current="false" id=$customer_id backend_context="1"} +

{intl l="Dear" } {$LASTNAME} {$FIRSTNAME},

+{/loop} + +

{intl l="Thank you for your order on our online store %store_name" store_name={config key="store_name"}}

+

{intl l="It would be great to share your thoughts on products with other customers."}

+

{intl l="You can post comments on this products: "}

+
    +{loop name="products" type="product" id={','|implode:$product_ids} lang=$lang_id} +
  • {$TITLE}
  • +{/loop} +
+

{intl l="Feel free to contact us for any further information"}

+ +

{intl l="Best Regards."}

\ No newline at end of file diff --git a/templates/email/default/request-customer-comment.txt b/templates/email/default/request-customer-comment.txt new file mode 100644 index 0000000..cd2ef77 --- /dev/null +++ b/templates/email/default/request-customer-comment.txt @@ -0,0 +1,16 @@ +{default_translation_domain domain="comment.email.default"} + +{loop type="customer" name="customer.order" current="false" id=$customer_id backend_context="1"} +{intl l="Dear" } {$LASTNAME} {$FIRSTNAME}, +{/loop} + +{intl l="Thank you for your order on our online store %store_name" store_name={config key="store_name"}} +{intl l="It would be great to share your thoughts on products with other customers."} +{intl l="You can post comments on this products: "} +{loop name="products" type="product" id={','|implode:$product_ids} lang={$lang}} + - {$TITLE} : {$URL} +{/loop} + +{intl l="Feel free to contact us for any further information"} + +{intl l="Best Regards."} \ No newline at end of file diff --git a/templates/frontOffice/default/ajax-comments.html b/templates/frontOffice/default/ajax-comments.html new file mode 100644 index 0000000..162b212 --- /dev/null +++ b/templates/frontOffice/default/ajax-comments.html @@ -0,0 +1,91 @@ +{default_translation_domain domain='comment.fo.default'} +{$locale={lang attr="locale"}} +{$customer_id={customer attr="id"}} + +{ifloop rel="comments"} + + {function name=comment_stars empty=1} + {$star=''} + {$star_empty=''} + + {for $foo=0 to 4} + {if $value > $foo} + {$star nofilter} + {elseif $empty == 1} + {$star_empty nofilter} + {/if} + {/for} + {/function} + + + {loop name="comments" type="comment" ref="{$ref}" ref_id="{$ref_id}" status="1" order="created_reverse" + offset="{$start}" limit="{$count}" } + + {if $CUSTOMER_ID} + {loop name="customer" type="customer" id="{$CUSTOMER_ID}" current="false" limit="1"} + {$username="{$FIRSTNAME} {$LASTNAME|truncate:2:"...":false}"} + {$image="http://www.gravatar.com/avatar/{$EMAIL|trim|strtolower|md5}?d=mm&s=64"} + {/loop} + {elseloop rel="customer"} + {$username={intl l="Anonymous"} } + {$image={image file='assets/img/avatar.png'}} + {/elseloop} + {else} + {$username=$USERNAME} + {$image="http://www.gravatar.com/avatar/{$EMAIL|trim|strtolower|md5}?d=mm&s=64"} + {/if} + +
+ +
+

+ {intl l="By %username" username={$username}} + {if $RATING}{comment_stars value=$RATING}{/if} +

+

{$TITLE}

+ +

{$CONTENT}

+ +
    +
  • {format_date date="{$CREATED}" output="date"}
  • + {if $VERIFIED} +
  • {intl l="Verified"}
  • + {else} +
  • {intl l="Verified"}
  • + {/if} + {if $customer_id && $customer_id == $CUSTOMER_ID} +
  • {intl l="Delete"}
  • + {else} +
  • + {form name="comment.abuse.form"} +
    + {form_hidden_fields form=$form} + {form_field form=$form field="id"} + + {intl l="Mark as inappropriate"} + {/form_field} +
    + {/form} +
  • + {/if} +
+
+
+ + {/loop} + + {if {count type="comment" ref="{$ref}" ref_id="{$ref_id}" status="1" } > $start + $count } + + {/if} +{/ifloop} +{elseloop rel="comments"} +
+ {if $start == 0 } + {intl l="There are no comments yet"} + {else} + {intl l="No more comments"} + {/if} +
+{/elseloop} diff --git a/templates/frontOffice/default/assets/img/avatar.png b/templates/frontOffice/default/assets/img/avatar.png new file mode 100644 index 0000000..5ce8620 Binary files /dev/null and b/templates/frontOffice/default/assets/img/avatar.png differ diff --git a/templates/frontOffice/default/assets/js/comment.js b/templates/frontOffice/default/assets/js/comment.js new file mode 100644 index 0000000..94427aa --- /dev/null +++ b/templates/frontOffice/default/assets/js/comment.js @@ -0,0 +1,159 @@ +;(function($) { + + $(document).ready(function () { + + var $commentTop = $('#comment-top'), + $commentMessage = $('#comment-top-message'), + $commentList = $('#comment-list'), + $commentCustomer = $('#comment-customer'), + $commentForm = $('#form-add-comment'); + + var displayMessage = function displayMessage($element, cssClass, messages, timeout){ + $element.slideUp('fast', function(){ + var i = 0, + domP; + if (messages.length > 0) { + $element.html(""); + $element + .removeClass('alert-success alert-info alert-warning alert-danger hidden') + .addClass('alert-' + cssClass) + ; + for ( ; i < messages.length ; i++ ) { + domP = document.createElement( "p" ); + $element.append( $(domP).html(messages[i]) ); + } + $element.slideDown('slow'); + + if (timeout) { + setTimeout(function(){$element.slideUp();}, timeout); + } + } + }); + }; + + var loadComments = function loadComments(start, count) { + + $.ajax({ + type: "GET", + data: { + 'ref': commentConfig['ref'], + 'ref_id': commentConfig['id'], + 'start': start, + 'count': count + }, + url: commentConfig['get'] + }).done(function(data){ + $commentList.append(data); + }).fail(function(jqXHR, textStatus, errorThrown){ + displayMessage($commentMessage, 'danger', [textStatus]); + }); + + }; + + var abuseComment = function abuseComment(ev) { + + var $link, $form, $alert; + + $link = $(ev.currentTarget); + $form = $link.parents('form').first(); + $alert = $form.parents('.comment-item').first().find('.comment-alert'); + + $.ajax({ + type: "POST", + dataType: 'json', + data: $form.serialize(), + url: $form.attr('action') + }).done(function(data, textStatus, jqXHR){ + if (data.success) { + displayMessage($alert, 'success', [data.message], 5000); + $form.parents('.comment-abuse').first().remove(); + } else { + displayMessage($alert, 'danger', [data.message]); + } + }).fail(function(jqXHR, textStatus, errorThrown){ + displayMessage($alert, 'danger', [textStatus]); + }); + + }; + + var deleteComment = function deleteComment($btn) { + + var $form, $alert; + + $form = $btn.parents('form').first(); + $alert = $form.parents('.comment-item').first().find('.comment-alert'); + + $.ajax({ + type: "GET", + url: $btn.attr('href') + }).done(function(data){ + if (data.success) { + displayMessage($alert, 'success', [data.message], 5000); + $('#comment-customer').remove(); + } else { + displayMessage($alert, 'danger', [data.message]); + } + }).fail(function(jqXHR, textStatus, errorThrown){ + displayMessage($commentMessage, 'danger', [textStatus]); + }); + + }; + + $commentForm.on('submit', function (ev) { + + ev.preventDefault(); + + $.ajax({ + type: "POST", + dataType: 'json', + data: $(this).serialize(), + url: commentConfig['post'] + }).done(function(data, textStatus, jqXHR){ + if (data.success) { + displayMessage($commentMessage, 'success', data.messages); + $commentForm.slideUp(function(){ + $commentForm.remove(); + }); + } else { + displayMessage($commentMessage, 'warning', data.messages); + } + }).fail(function(jqXHR, textStatus, errorThrown){ + displayMessage($commentMessage, 'danger', [textStatus]); + }); + + }); + + loadComments(commentConfig['start'], commentConfig['count']); + + $commentList.on( "click", ".comments-more-link", function(ev) { + ev.preventDefault(); + + commentConfig['start'] += commentConfig['count']; + loadComments(commentConfig['start'], commentConfig['count']); + + $(ev.currentTarget).parents('.comments-more').first().remove(); + }); + + $commentList.on( "click", ".abuse-trigger", function(ev) { + ev.preventDefault(); + + abuseComment(ev); + }); + + $commentList.on( "click", ".delete-trigger", function(ev) { + ev.preventDefault(); + + $trigger = $(ev.currentTarget); + + if ($trigger.data("confirmed") == "1") { + deleteComment($trigger); + } else { + $trigger.data("confirmed", "1"); + $trigger.html($trigger.data("message")); + } + + }); + + }); + +})(jQuery); diff --git a/templates/frontOffice/default/assets/js/images/cancel-off.png b/templates/frontOffice/default/assets/js/images/cancel-off.png new file mode 100755 index 0000000..a3031f0 Binary files /dev/null and b/templates/frontOffice/default/assets/js/images/cancel-off.png differ diff --git a/templates/frontOffice/default/assets/js/images/cancel-on.png b/templates/frontOffice/default/assets/js/images/cancel-on.png new file mode 100755 index 0000000..08f2493 Binary files /dev/null and b/templates/frontOffice/default/assets/js/images/cancel-on.png differ diff --git a/templates/frontOffice/default/assets/js/images/star-half.png b/templates/frontOffice/default/assets/js/images/star-half.png new file mode 100755 index 0000000..3c19e90 Binary files /dev/null and b/templates/frontOffice/default/assets/js/images/star-half.png differ diff --git a/templates/frontOffice/default/assets/js/images/star-off.png b/templates/frontOffice/default/assets/js/images/star-off.png new file mode 100755 index 0000000..956fa7c Binary files /dev/null and b/templates/frontOffice/default/assets/js/images/star-off.png differ diff --git a/templates/frontOffice/default/assets/js/images/star-on.png b/templates/frontOffice/default/assets/js/images/star-on.png new file mode 100755 index 0000000..975fe7f Binary files /dev/null and b/templates/frontOffice/default/assets/js/images/star-on.png differ diff --git a/templates/frontOffice/default/assets/js/jquery.raty.css b/templates/frontOffice/default/assets/js/jquery.raty.css new file mode 100755 index 0000000..00be54f --- /dev/null +++ b/templates/frontOffice/default/assets/js/jquery.raty.css @@ -0,0 +1,46 @@ +.cancel-on-png, .cancel-off-png, .star-on-png, .star-off-png, .star-half-png { + font-size: 2em; +} + +@font-face { + font-family: "raty"; + font-style: normal; + font-weight: normal; + src: url("fonts/raty.eot"); + src: url("fonts/raty.eot?#iefix") format("embedded-opentype"); + src: url("fonts/raty.svg#raty") format("svg"); + src: url("fonts/raty.ttf") format("truetype"); + src: url("fonts/raty.woff") format("woff"); +} + +.cancel-on-png, .cancel-off-png, .star-on-png, .star-off-png, .star-half-png { + -moz-osx-font-smoothing: grayscale; + -webkit-font-smoothing: antialiased; + font-family: "raty"; + font-style: normal; + font-variant: normal; + font-weight: normal; + line-height: 1; + speak: none; + text-transform: none; +} + +.cancel-on-png:before { + content: "\e600"; +} + +.cancel-off-png:before { + content: "\e601"; +} + +.star-on-png:before { + content: "\f005"; +} + +.star-off-png:before { + content: "\f006"; +} + +.star-half-png:before { + content: "\f123"; +} diff --git a/templates/frontOffice/default/assets/js/jquery.raty.js b/templates/frontOffice/default/assets/js/jquery.raty.js new file mode 100755 index 0000000..c583651 --- /dev/null +++ b/templates/frontOffice/default/assets/js/jquery.raty.js @@ -0,0 +1,760 @@ +/*! + * jQuery Raty - A Star Rating Plugin + * + * The MIT License + * + * @author : Washington Botelho + * @doc : http://wbotelhos.com/raty + * @version : 2.7.0 + * + */ + +; +(function($) { + 'use strict'; + + var methods = { + init: function(options) { + return this.each(function() { + this.self = $(this); + + methods.destroy.call(this.self); + + this.opt = $.extend(true, {}, $.fn.raty.defaults, options); + + methods._adjustCallback.call(this); + methods._adjustNumber.call(this); + methods._adjustHints.call(this); + + this.opt.score = methods._adjustedScore.call(this, this.opt.score); + + if (this.opt.starType !== 'img') { + methods._adjustStarType.call(this); + } + + methods._adjustPath.call(this); + methods._createStars.call(this); + + if (this.opt.cancel) { + methods._createCancel.call(this); + } + + if (this.opt.precision) { + methods._adjustPrecision.call(this); + } + + methods._createScore.call(this); + methods._apply.call(this, this.opt.score); + methods._setTitle.call(this, this.opt.score); + methods._target.call(this, this.opt.score); + + if (this.opt.readOnly) { + methods._lock.call(this); + } else { + this.style.cursor = 'pointer'; + + methods._binds.call(this); + } + }); + }, + + _adjustCallback: function() { + var options = ['number', 'readOnly', 'score', 'scoreName', 'target']; + + for (var i = 0; i < options.length; i++) { + if (typeof this.opt[options[i]] === 'function') { + this.opt[options[i]] = this.opt[options[i]].call(this); + } + } + }, + + _adjustedScore: function(score) { + if (!score) { + return score; + } + + return methods._between(score, 0, this.opt.number); + }, + + _adjustHints: function() { + if (!this.opt.hints) { + this.opt.hints = []; + } + + if (!this.opt.halfShow && !this.opt.half) { + return; + } + + var steps = this.opt.precision ? 10 : 2; + + for (var i = 0; i < this.opt.number; i++) { + var group = this.opt.hints[i]; + + if (Object.prototype.toString.call(group) !== '[object Array]') { + group = [group]; + } + + this.opt.hints[i] = []; + + for (var j = 0; j < steps; j++) { + var + hint = group[j], + last = group[group.length - 1]; + + if (last === undefined) { + last = null; + } + + this.opt.hints[i][j] = hint === undefined ? last : hint; + } + } + }, + + _adjustNumber: function() { + this.opt.number = methods._between(this.opt.number, 1, this.opt.numberMax); + }, + + _adjustPath: function() { + this.opt.path = this.opt.path || ''; + + if (this.opt.path && this.opt.path.charAt(this.opt.path.length - 1) !== '/') { + this.opt.path += '/'; + } + }, + + _adjustPrecision: function() { + this.opt.half = true; + }, + + _adjustStarType: function() { + var replaces = ['cancelOff', 'cancelOn', 'starHalf', 'starOff', 'starOn']; + + this.opt.path = ''; + + for (var i = 0; i < replaces.length; i++) { + this.opt[replaces[i]] = this.opt[replaces[i]].replace('.', '-'); + } + }, + + _apply: function(score) { + methods._fill.call(this, score); + + if (score) { + if (score > 0) { + this.score.val(score); + } + + methods._roundStars.call(this, score); + } + }, + + _between: function(value, min, max) { + return Math.min(Math.max(parseFloat(value), min), max); + }, + + _binds: function() { + if (this.cancel) { + methods._bindOverCancel.call(this); + methods._bindClickCancel.call(this); + methods._bindOutCancel.call(this); + } + + methods._bindOver.call(this); + methods._bindClick.call(this); + methods._bindOut.call(this); + }, + + _bindClick: function() { + var that = this; + + that.stars.on('click.raty', function(evt) { + var + execute = true, + score = (that.opt.half || that.opt.precision) ? that.self.data('score') : (this.alt || $(this).data('alt')); + + if (that.opt.click) { + execute = that.opt.click.call(that, +score, evt); + } + + if (execute || execute === undefined) { + if (that.opt.half && !that.opt.precision) { + score = methods._roundHalfScore.call(that, score); + } + + methods._apply.call(that, score); + } + }); + }, + + _bindClickCancel: function() { + var that = this; + + that.cancel.on('click.raty', function(evt) { + that.score.removeAttr('value'); + + if (that.opt.click) { + that.opt.click.call(that, null, evt); + } + }); + }, + + _bindOut: function() { + var that = this; + + that.self.on('mouseleave.raty', function(evt) { + var score = +that.score.val() || undefined; + + methods._apply.call(that, score); + methods._target.call(that, score, evt); + methods._resetTitle.call(that); + + if (that.opt.mouseout) { + that.opt.mouseout.call(that, score, evt); + } + }); + }, + + _bindOutCancel: function() { + var that = this; + + that.cancel.on('mouseleave.raty', function(evt) { + var icon = that.opt.cancelOff; + + if (that.opt.starType !== 'img') { + icon = that.opt.cancelClass + ' ' + icon; + } + + methods._setIcon.call(that, this, icon); + + if (that.opt.mouseout) { + var score = +that.score.val() || undefined; + + that.opt.mouseout.call(that, score, evt); + } + }); + }, + + _bindOver: function() { + var that = this, + action = that.opt.half ? 'mousemove.raty' : 'mouseover.raty'; + + that.stars.on(action, function(evt) { + var score = methods._getScoreByPosition.call(that, evt, this); + + methods._fill.call(that, score); + + if (that.opt.half) { + methods._roundStars.call(that, score, evt); + methods._setTitle.call(that, score, evt); + + that.self.data('score', score); + } + + methods._target.call(that, score, evt); + + if (that.opt.mouseover) { + that.opt.mouseover.call(that, score, evt); + } + }); + }, + + _bindOverCancel: function() { + var that = this; + + that.cancel.on('mouseover.raty', function(evt) { + var + starOff = that.opt.path + that.opt.starOff, + icon = that.opt.cancelOn; + + if (that.opt.starType === 'img') { + that.stars.attr('src', starOff); + } else { + icon = that.opt.cancelClass + ' ' + icon; + + that.stars.attr('class', starOff); + } + + methods._setIcon.call(that, this, icon); + methods._target.call(that, null, evt); + + if (that.opt.mouseover) { + that.opt.mouseover.call(that, null); + } + }); + }, + + _buildScoreField: function() { + return $('', { name: this.opt.scoreName, type: 'hidden' }).appendTo(this); + }, + + _createCancel: function() { + var icon = this.opt.path + this.opt.cancelOff, + cancel = $('<' + this.opt.starType + ' />', { title: this.opt.cancelHint, 'class': this.opt.cancelClass }); + + if (this.opt.starType === 'img') { + cancel.attr({ src: icon, alt: 'x' }); + } else { + // TODO: use $.data + cancel.attr('data-alt', 'x').addClass(icon); + } + + if (this.opt.cancelPlace === 'left') { + this.self.prepend(' ').prepend(cancel); + } else { + this.self.append(' ').append(cancel); + } + + this.cancel = cancel; + }, + + _createScore: function() { + var score = $(this.opt.targetScore); + + this.score = score.length ? score : methods._buildScoreField.call(this); + }, + + _createStars: function() { + for (var i = 1; i <= this.opt.number; i++) { + var + name = methods._nameForIndex.call(this, i), + attrs = { alt: i, src: this.opt.path + this.opt[name] }; + + if (this.opt.starType !== 'img') { + attrs = { 'data-alt': i, 'class': attrs.src }; // TODO: use $.data. + } + + attrs.title = methods._getHint.call(this, i); + + $('<' + this.opt.starType + ' />', attrs).appendTo(this); + + if (this.opt.space) { + this.self.append(i < this.opt.number ? ' ' : ''); + } + } + + this.stars = this.self.children(this.opt.starType); + }, + + _error: function(message) { + $(this).text(message); + + $.error(message); + }, + + _fill: function(score) { + var hash = 0; + + for (var i = 1; i <= this.stars.length; i++) { + var + icon, + star = this.stars[i - 1], + turnOn = methods._turnOn.call(this, i, score); + + if (this.opt.iconRange && this.opt.iconRange.length > hash) { + var irange = this.opt.iconRange[hash]; + + icon = methods._getRangeIcon.call(this, irange, turnOn); + + if (i <= irange.range) { + methods._setIcon.call(this, star, icon); + } + + if (i === irange.range) { + hash++; + } + } else { + icon = this.opt[turnOn ? 'starOn' : 'starOff']; + + methods._setIcon.call(this, star, icon); + } + } + }, + + _getFirstDecimal: function(number) { + var + decimal = number.toString().split('.')[1], + result = 0; + + if (decimal) { + result = parseInt(decimal.charAt(0), 10); + + if (decimal.slice(1, 5) === '9999') { + result++; + } + } + + return result; + }, + + _getRangeIcon: function(irange, turnOn) { + return turnOn ? irange.on || this.opt.starOn : irange.off || this.opt.starOff; + }, + + _getScoreByPosition: function(evt, icon) { + var score = parseInt(icon.alt || icon.getAttribute('data-alt'), 10); + + if (this.opt.half) { + var + size = methods._getWidth.call(this), + percent = parseFloat((evt.pageX - $(icon).offset().left) / size); + + score = score - 1 + percent; + } + + return score; + }, + + _getHint: function(score, evt) { + if (score !== 0 && !score) { + return this.opt.noRatedMsg; + } + + var + decimal = methods._getFirstDecimal.call(this, score), + integer = Math.ceil(score), + group = this.opt.hints[(integer || 1) - 1], + hint = group, + set = !evt || this.move; + + if (this.opt.precision) { + if (set) { + decimal = decimal === 0 ? 9 : decimal - 1; + } + + hint = group[decimal]; + } else if (this.opt.halfShow || this.opt.half) { + decimal = set && decimal === 0 ? 1 : decimal > 5 ? 1 : 0; + + hint = group[decimal]; + } + + return hint === '' ? '' : hint || score; + }, + + _getWidth: function() { + var width = this.stars[0].width || parseFloat(this.stars.eq(0).css('font-size')); + + if (!width) { + methods._error.call(this, 'Could not get the icon width!'); + } + + return width; + }, + + _lock: function() { + var hint = methods._getHint.call(this, this.score.val()); + + this.style.cursor = ''; + this.title = hint; + + this.score.prop('readonly', true); + this.stars.prop('title', hint); + + if (this.cancel) { + this.cancel.hide(); + } + + this.self.data('readonly', true); + }, + + _nameForIndex: function(i) { + return this.opt.score && this.opt.score >= i ? 'starOn' : 'starOff'; + }, + + _resetTitle: function(star) { + for (var i = 0; i < this.opt.number; i++) { + this.stars[i].title = methods._getHint.call(this, i + 1); + } + }, + + _roundHalfScore: function(score) { + var integer = parseInt(score, 10), + decimal = methods._getFirstDecimal.call(this, score); + + if (decimal !== 0) { + decimal = decimal > 5 ? 1 : 0.5; + } + + return integer + decimal; + }, + + _roundStars: function(score, evt) { + var + decimal = (score % 1).toFixed(2), + name ; + + if (evt || this.move) { + name = decimal > 0.5 ? 'starOn' : 'starHalf'; + } else if (decimal > this.opt.round.down) { // Up: [x.76 .. x.99] + name = 'starOn'; + + if (this.opt.halfShow && decimal < this.opt.round.up) { // Half: [x.26 .. x.75] + name = 'starHalf'; + } else if (decimal < this.opt.round.full) { // Down: [x.00 .. x.5] + name = 'starOff'; + } + } + + if (name) { + var + icon = this.opt[name], + star = this.stars[Math.ceil(score) - 1]; + + methods._setIcon.call(this, star, icon); + } // Full down: [x.00 .. x.25] + }, + + _setIcon: function(star, icon) { + star[this.opt.starType === 'img' ? 'src' : 'className'] = this.opt.path + icon; + }, + + _setTarget: function(target, score) { + if (score) { + score = this.opt.targetFormat.toString().replace('{score}', score); + } + + if (target.is(':input')) { + target.val(score); + } else { + target.html(score); + } + }, + + _setTitle: function(score, evt) { + if (score) { + var + integer = parseInt(Math.ceil(score), 10), + star = this.stars[integer - 1]; + + star.title = methods._getHint.call(this, score, evt); + } + }, + + _target: function(score, evt) { + if (this.opt.target) { + var target = $(this.opt.target); + + if (!target.length) { + methods._error.call(this, 'Target selector invalid or missing!'); + } + + var mouseover = evt && evt.type === 'mouseover'; + + if (score === undefined) { + score = this.opt.targetText; + } else if (score === null) { + score = mouseover ? this.opt.cancelHint : this.opt.targetText; + } else { + if (this.opt.targetType === 'hint') { + score = methods._getHint.call(this, score, evt); + } else if (this.opt.precision) { + score = parseFloat(score).toFixed(1); + } + + var mousemove = evt && evt.type === 'mousemove'; + + if (!mouseover && !mousemove && !this.opt.targetKeep) { + score = this.opt.targetText; + } + } + + methods._setTarget.call(this, target, score); + } + }, + + _turnOn: function(i, score) { + return this.opt.single ? (i === score) : (i <= score); + }, + + _unlock: function() { + this.style.cursor = 'pointer'; + this.removeAttribute('title'); + + this.score.removeAttr('readonly'); + + this.self.data('readonly', false); + + for (var i = 0; i < this.opt.number; i++) { + this.stars[i].title = methods._getHint.call(this, i + 1); + } + + if (this.cancel) { + this.cancel.css('display', ''); + } + }, + + cancel: function(click) { + return this.each(function() { + var self = $(this); + + if (self.data('readonly') !== true) { + methods[click ? 'click' : 'score'].call(self, null); + + this.score.removeAttr('value'); + } + }); + }, + + click: function(score) { + return this.each(function() { + if ($(this).data('readonly') !== true) { + score = methods._adjustedScore.call(this, score); + + methods._apply.call(this, score); + + if (this.opt.click) { + this.opt.click.call(this, score, $.Event('click')); + } + + methods._target.call(this, score); + } + }); + }, + + destroy: function() { + return this.each(function() { + var self = $(this), + raw = self.data('raw'); + + if (raw) { + self.off('.raty').empty().css({ cursor: raw.style.cursor }).removeData('readonly'); + } else { + self.data('raw', self.clone()[0]); + } + }); + }, + + getScore: function() { + var score = [], + value ; + + this.each(function() { + value = this.score.val(); + + score.push(value ? +value : undefined); + }); + + return (score.length > 1) ? score : score[0]; + }, + + move: function(score) { + return this.each(function() { + var + integer = parseInt(score, 10), + decimal = methods._getFirstDecimal.call(this, score); + + if (integer >= this.opt.number) { + integer = this.opt.number - 1; + decimal = 10; + } + + var + width = methods._getWidth.call(this), + steps = width / 10, + star = $(this.stars[integer]), + percent = star.offset().left + steps * decimal, + evt = $.Event('mousemove', { pageX: percent }); + + this.move = true; + + star.trigger(evt); + + this.move = false; + }); + }, + + readOnly: function(readonly) { + return this.each(function() { + var self = $(this); + + if (self.data('readonly') !== readonly) { + if (readonly) { + self.off('.raty').children('img').off('.raty'); + + methods._lock.call(this); + } else { + methods._binds.call(this); + methods._unlock.call(this); + } + + self.data('readonly', readonly); + } + }); + }, + + reload: function() { + return methods.set.call(this, {}); + }, + + score: function() { + var self = $(this); + + return arguments.length ? methods.setScore.apply(self, arguments) : methods.getScore.call(self); + }, + + set: function(options) { + return this.each(function() { + $(this).raty($.extend({}, this.opt, options)); + }); + }, + + setScore: function(score) { + return this.each(function() { + if ($(this).data('readonly') !== true) { + score = methods._adjustedScore.call(this, score); + + methods._apply.call(this, score); + methods._target.call(this, score); + } + }); + } + }; + + $.fn.raty = function(method) { + if (methods[method]) { + return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); + } else if (typeof method === 'object' || !method) { + return methods.init.apply(this, arguments); + } else { + $.error('Method ' + method + ' does not exist!'); + } + }; + + $.fn.raty.defaults = { + cancel : false, + cancelClass : 'raty-cancel', + cancelHint : 'Cancel this rating!', + cancelOff : 'cancel-off.png', + cancelOn : 'cancel-on.png', + cancelPlace : 'left', + click : undefined, + half : false, + halfShow : true, + hints : ['bad', 'poor', 'regular', 'good', 'gorgeous'], + iconRange : undefined, + mouseout : undefined, + mouseover : undefined, + noRatedMsg : 'Not rated yet!', + number : 5, + numberMax : 20, + path : undefined, + precision : false, + readOnly : false, + round : { down: 0.25, full: 0.6, up: 0.76 }, + score : undefined, + scoreName : 'score', + single : false, + space : true, + starHalf : 'star-half.png', + starOff : 'star-off.png', + starOn : 'star-on.png', + starType : 'img', + target : undefined, + targetFormat : '{score}', + targetKeep : false, + targetScore : undefined, + targetText : '', + targetType : 'hint' + }; + +})(jQuery); diff --git a/templates/frontOffice/default/comment.html b/templates/frontOffice/default/comment.html new file mode 100644 index 0000000..3685f97 --- /dev/null +++ b/templates/frontOffice/default/comment.html @@ -0,0 +1,129 @@ +{default_translation_domain domain='comment.fo.default'} +{function name=comment_stars empty=1} + {$star=''} + {$star_empty=''} + + {for $foo=0 to 4} + {if $value > $foo} + {$star nofilter} + {elseif $empty == 1} + {$star_empty nofilter} + {/if} + {/for} +{/function} + +
+ +
+ +
+ {intl l="Add your comment"} +
+ + + + {if $definition->isValid()} + {form name="comment.add.form"} +
+ + {form_hidden_fields form=$form} + + {form_field form=$form field="ref"} + + {/form_field} + + {form_field form=$form field="ref_id"} + + {/form_field} + + {if ! $definition->getCustomer()} + {form_field form=$form field="username"} +
+ + +
+ {/form_field} + + {form_field form=$form field="email"} +
+ + +
+ {/form_field} + {/if} + + {form_field form=$form field="title"} +
+ + +
+ {/form_field} + + {form_field form=$form field="content"} +
+ + +
+ {/form_field} + + {if $definition->hasRating()} + + {form_field form=$form field="rating"} +
+ {$label} +
+ + + + + + +
+
+ {/form_field} + {/if} + +
+ +
+
+ {/form} + {else} +
{$message}
+ {/if} +
+ +
+
+ {intl l="Comments"} + {if $definition->hasRating()} + {$rating={meta meta="COMMENT_RATING" key="{$definition->getRef()}" id="{$definition->getRefId()}"}} + {if $rating} + + rating: {comment_stars value=$rating} + + {/if} + {/if} +
+ +
+
+
\ No newline at end of file diff --git a/templates/frontOffice/default/includes/stars.html b/templates/frontOffice/default/includes/stars.html new file mode 100644 index 0000000..cb00c64 --- /dev/null +++ b/templates/frontOffice/default/includes/stars.html @@ -0,0 +1,17 @@ + +{* + A function inside an included file seems not working in smarty +*} + +{function name=comment_stars empty=1} + {$star=''} + {$star_empty=''} + + {for $foo=0 to 4} + {if $value > $foo} + {$star nofilter} + {elseif $empty == 1} + {$star_empty nofilter} + {/if} + {/for} +{/function} diff --git a/templates/frontOffice/default/js.html b/templates/frontOffice/default/js.html new file mode 100644 index 0000000..349724c --- /dev/null +++ b/templates/frontOffice/default/js.html @@ -0,0 +1,15 @@ +