Listing.php 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681
  1. <?php
  2. /**
  3. *
  4. * PHP Pro Bid $Id$ yWmrd6SsYKr+Ju1kqDkgXtlajw1PaVMT9T2YTgnUX0c=
  5. *
  6. * @link http://www.phpprobid.com
  7. * @copyright Copyright (c) 2017 Online Ventures Software & CodeCube SRL
  8. * @license http://www.phpprobid.com/license Commercial License
  9. *
  10. * @version 7.10 [rev.7.10.03]
  11. */
  12. /**
  13. * listings table row object model
  14. */
  15. namespace Ppb\Db\Table\Row;
  16. use Ppb\Service,
  17. Cube\Controller\Front,
  18. Cube\Db\Table,
  19. Cube\Db\Expr,
  20. Ppb\Model\Shipping as ShippingModel,
  21. Ppb\Db\Table\Rowset;
  22. class Listing extends AbstractRow
  23. {
  24. /**
  25. * listing statuses
  26. */
  27. const OPEN = 'open';
  28. const CLOSED = 'closed';
  29. const SCHEDULED = 'scheduled';
  30. /**
  31. * custom fields tables "type" column
  32. */
  33. const CUSTOM_FIELDS_TYPE = 'item';
  34. /**
  35. * unlimited quantity flag
  36. */
  37. const UNLIMITED_QUANTITY = -1;
  38. /**
  39. *
  40. * relist type
  41. * 'same' -> same listing
  42. * 'new' -> new listing
  43. */
  44. const RELIST_SAME = 'same';
  45. const RELIST_NEW = 'new';
  46. /**
  47. * last count operation flags
  48. */
  49. const COUNT_OP_NONE = 'none';
  50. const COUNT_OP_ADD = 'add';
  51. const COUNT_OP_SUBTRACT = 'subtract';
  52. /**
  53. * operations
  54. */
  55. const ADD = 'add';
  56. const SUBTRACT = 'subtract';
  57. /**
  58. * max chars for the short description method
  59. */
  60. const SHORT_DESC_MAX_CHARS = 255;
  61. /**
  62. *
  63. * serializable fields
  64. *
  65. * @var array
  66. */
  67. protected $_serializable = array('postage_settings', 'offline_payment', 'direct_payment');
  68. /**
  69. *
  70. * array of available relist methods
  71. *
  72. * @var array
  73. */
  74. protected $_relistMethods = array(
  75. self::RELIST_SAME,
  76. self::RELIST_NEW,
  77. );
  78. /**
  79. *
  80. * relist method to be used
  81. *
  82. * @var string
  83. */
  84. protected $_relistMethod;
  85. /**
  86. *
  87. * bids rowset
  88. * contains all bids placed on this listing
  89. *
  90. * @var \Ppb\Db\Table\Rowset\Bids
  91. */
  92. protected $_bids = null;
  93. /**
  94. *
  95. * offers rowset
  96. * contains all offers posted on this listing
  97. *
  98. * @var \Ppb\Db\Table\Rowset\Offers
  99. */
  100. protected $_offers = null;
  101. /**
  102. *
  103. * sales rowset
  104. * contains all sales transactions
  105. *
  106. * @var \Ppb\Db\Table\Rowset\Sales
  107. */
  108. protected $_sales = null;
  109. /**
  110. *
  111. * bid increments table service
  112. *
  113. * @var \Ppb\Service\Table\BidIncrements
  114. */
  115. protected $_bidIncrements;
  116. /**
  117. *
  118. * custom fields and custom fields data tables service
  119. *
  120. * @var \Ppb\Service\CustomFields
  121. */
  122. protected $_customFields;
  123. /**
  124. *
  125. * sales listings table service
  126. *
  127. * @var \Ppb\Service\Table\SalesListings
  128. */
  129. protected $_salesListings;
  130. /**
  131. *
  132. * custom fields data table service
  133. *
  134. * @var \Ppb\Service\CustomFieldsData
  135. */
  136. protected $_customFieldsData;
  137. /**
  138. *
  139. * categories table service
  140. *
  141. * @var \Ppb\Service\Table\Relational\Categories
  142. */
  143. protected $_categories;
  144. /**
  145. *
  146. * listing media rowset
  147. *
  148. * @var \Cube\Db\Table\Rowset\AbstractRowset
  149. */
  150. protected $_listingsMedia;
  151. /**
  152. *
  153. * the id of a sale that was created as a result of a purchase
  154. * (buy out or assign winner)
  155. *
  156. * @var int
  157. */
  158. protected $_saleId;
  159. /**
  160. *
  161. * tax type object that applies to the listing
  162. * or null if no tax will apply
  163. *
  164. * @var \Ppb\Db\Table\Row\TaxType|null
  165. */
  166. protected $_taxType = null;
  167. /**
  168. *
  169. * closed flag
  170. *
  171. * @var bool
  172. */
  173. protected $_closedFlag = false;
  174. /**
  175. *
  176. * class constructor
  177. *
  178. * @param array $data
  179. */
  180. public function __construct(array $data = array())
  181. {
  182. if (!isset($data['data']['id'])) {
  183. $data['data']['id'] = 0;
  184. }
  185. parent::__construct($data);
  186. }
  187. /**
  188. *
  189. * get bids rowset ordered from the highest to the lowest
  190. *
  191. * @return \Ppb\Db\Table\Rowset\Bids
  192. */
  193. public function getBids()
  194. {
  195. if (!$this->_bids instanceof Rowset\Bids) {
  196. $select = $this->getTable()->select()
  197. ->order(array('amount DESC', 'id DESC'));
  198. $this->_bids = $this->findDependentRowset('\Ppb\Db\Table\Bids', null, $select);
  199. }
  200. return $this->_bids;
  201. }
  202. /**
  203. *
  204. * clear bids rowset
  205. *
  206. * @return $this
  207. */
  208. public function clearBids()
  209. {
  210. $this->_bids = null;
  211. return $this;
  212. }
  213. /**
  214. *
  215. * get offers rowset
  216. *
  217. * @return \Ppb\Db\Table\Rowset\Offers
  218. */
  219. public function getOffers()
  220. {
  221. if (!$this->_offers instanceof Rowset\Offers) {
  222. $select = $this->getTable()->select()
  223. ->order(array('id DESC'));
  224. $this->_offers = $this->findDependentRowset('\Ppb\Db\Table\Offers', null, $select);
  225. }
  226. return $this->_offers;
  227. }
  228. /**
  229. *
  230. * clear offers rowset
  231. *
  232. * @return $this
  233. */
  234. public function clearOffers()
  235. {
  236. $this->_offers = null;
  237. return $this;
  238. }
  239. /**
  240. *
  241. * get sales listings table rowset
  242. *
  243. * @return \Ppb\Db\Table\Rowset\Sales
  244. */
  245. public function getSales()
  246. {
  247. if (!$this->_sales instanceof Rowset\Sales) {
  248. $service = new Service\Sales();
  249. $select = $service->getTable()->getAdapter()->select()
  250. ->from(array('l' => 'sales_listings'))
  251. ->joinLeft(array('s' => 'sales'), 'l.sale_id = s.id', 's.buyer_id')
  252. ->where('l.listing_id = ?', intval($this->getData('id')))
  253. ->where('s.pending = ?', 0)
  254. ->order(array('l.id DESC'));
  255. $this->_sales = $service->fetchAll($select);
  256. }
  257. return $this->_sales;
  258. }
  259. /**
  260. *
  261. * clear sales rowset
  262. *
  263. * @return $this
  264. */
  265. public function clearSales()
  266. {
  267. $this->_sales = null;
  268. return $this;
  269. }
  270. /**
  271. *
  272. * get bid increments table service
  273. *
  274. * @return \Ppb\Service\Table\BidIncrements
  275. */
  276. public function getBidIncrements()
  277. {
  278. if (!$this->_bidIncrements instanceof Service\Table\BidIncrements) {
  279. $this->setBidIncrements(
  280. new Service\Table\BidIncrements());
  281. }
  282. return $this->_bidIncrements;
  283. }
  284. /**
  285. *
  286. * set bid increments table service
  287. *
  288. * @param \Ppb\Service\Table\BidIncrements $bidIncrements
  289. *
  290. * @return $this
  291. */
  292. public function setBidIncrements(Service\Table\BidIncrements $bidIncrements)
  293. {
  294. $this->_bidIncrements = $bidIncrements;
  295. return $this;
  296. }
  297. /**
  298. *
  299. * get custom fields table service
  300. *
  301. * @return \Ppb\Service\CustomFields
  302. */
  303. public function getCustomFieldsService()
  304. {
  305. if (!$this->_customFields instanceof Service\CustomFields) {
  306. $this->setCustomFieldsService(
  307. new Service\CustomFields());
  308. }
  309. return $this->_customFields;
  310. }
  311. /**
  312. *
  313. * set custom fields table service
  314. *
  315. * @param \Ppb\Service\CustomFields $customFields
  316. *
  317. * @return $this
  318. */
  319. public function setCustomFieldsService(Service\CustomFields $customFields)
  320. {
  321. $this->_customFields = $customFields;
  322. return $this;
  323. }
  324. /**
  325. *
  326. * set sales listings table service
  327. *
  328. * @param \Ppb\Service\Table\SalesListings $salesListings
  329. *
  330. * @return $this
  331. */
  332. public function setSalesListings($salesListings)
  333. {
  334. $this->_salesListings = $salesListings;
  335. return $this;
  336. }
  337. /**
  338. * @return \Ppb\Service\Table\SalesListings
  339. */
  340. public function getSalesListings()
  341. {
  342. if (!$this->_salesListings instanceof Service\Table\SalesListings) {
  343. $this->setSalesListings(
  344. new Service\Table\SalesListings());
  345. }
  346. return $this->_salesListings;
  347. }
  348. /**
  349. *
  350. * get categories table service
  351. *
  352. * @return \Ppb\Service\Table\Relational\Categories
  353. */
  354. public function getCategories()
  355. {
  356. if (!$this->_categories instanceof Service\Table\Relational\Categories) {
  357. $this->setCategories(
  358. new Service\Table\Relational\Categories());
  359. }
  360. return $this->_categories;
  361. }
  362. /**
  363. *
  364. * set categories table service
  365. *
  366. * @param \Ppb\Service\Table\Relational\Categories $categories
  367. *
  368. * @return $this
  369. */
  370. public function setCategories(Service\Table\Relational\Categories $categories)
  371. {
  372. $this->_categories = $categories;
  373. return $this;
  374. }
  375. /**
  376. *
  377. * set sale id
  378. *
  379. * @param int $saleId
  380. *
  381. * @return $this
  382. */
  383. public function setSaleId($saleId)
  384. {
  385. $this->_saleId = $saleId;
  386. return $this;
  387. }
  388. /**
  389. *
  390. * get sale id
  391. *
  392. * @return int
  393. */
  394. public function getSaleId()
  395. {
  396. return $this->_saleId;
  397. }
  398. /**
  399. *
  400. * get custom fields data service
  401. *
  402. * @return \Ppb\Service\CustomFieldsData
  403. */
  404. public function getCustomFieldsData()
  405. {
  406. if (!$this->_customFieldsData instanceof Service\CustomFieldsData) {
  407. $this->setCustomFieldsData(
  408. new Service\CustomFieldsData());
  409. }
  410. return $this->_customFieldsData;
  411. }
  412. /**
  413. *
  414. * set custom fields data service
  415. *
  416. * @param \Ppb\Service\CustomFieldsData $customFieldsData
  417. *
  418. * @return $this
  419. */
  420. public function setCustomFieldsData(Service\CustomFieldsData $customFieldsData)
  421. {
  422. $this->_customFieldsData = $customFieldsData;
  423. return $this;
  424. }
  425. /**
  426. *
  427. * get closed flag
  428. *
  429. * @return bool
  430. */
  431. public function getClosedFlag()
  432. {
  433. return $this->_closedFlag;
  434. }
  435. /**
  436. *
  437. * retrieve the listing's selected media types or all if $types = null
  438. * if the listing has not been created yet, then use the $_data array,
  439. * otherwise get data from the listings_media table
  440. *
  441. * @param string|array|null $types
  442. *
  443. * @return array|\Ppb\Db\Table\Rowset\ListingsMedia
  444. */
  445. public function getMedia($types = null)
  446. {
  447. $media = array();
  448. if ($types !== null) {
  449. if (!is_array($types)) {
  450. $types = array($types);
  451. }
  452. }
  453. else {
  454. $types = Service\ListingsMedia::getTypes();
  455. }
  456. // if we are creating a listing, we will use the $_data array
  457. if (!$this->getData('id')) {
  458. foreach ($types as $type) {
  459. $files = $this->getData($type);
  460. if ($files !== null) {
  461. if (!is_array($files)) {
  462. $this->addData($type, \Ppb\Utility::unserialize($files));
  463. }
  464. $data = array_filter((array)$this->getData($type));
  465. foreach ($data as $value) {
  466. $media[] = array(
  467. 'id' => null,
  468. 'value' => $value,
  469. 'type' => $type,
  470. );
  471. }
  472. }
  473. }
  474. }
  475. else {
  476. /** @var \Ppb\Db\Table\Rowset\ListingsMedia $media */
  477. $media = $this->findDependentRowset('\Ppb\Db\Table\ListingsMedia', null,
  478. $this->getTable()->select()->where('type IN (?)', $types)
  479. ->order('order_id ASC'));
  480. }
  481. return $media;
  482. }
  483. /**
  484. *
  485. * retrieve the listing's main image
  486. *
  487. * @param bool $absolutePath if true, return the full path of the image
  488. *
  489. * @return string|null
  490. */
  491. public function getMainImage($absolutePath = false)
  492. {
  493. $images = $this->getMedia('image');
  494. $image = null;
  495. if (count($images) > 0) {
  496. $image = $images[0]['value'];
  497. if ($absolutePath === true) {
  498. if (!preg_match('#^http(s)?://(.*)+$#i', $image)) {
  499. $settings = $this->getSettings();
  500. $uploadsPath = $settings['site_path'] . \Ppb\Utility::URI_DELIMITER . \Ppb\Utility::getFolder('uploads');
  501. $image = $uploadsPath . \Ppb\Utility::URI_DELIMITER . $image;
  502. }
  503. }
  504. }
  505. return $image;
  506. }
  507. /**
  508. *
  509. * get listing status (open/closed/scheduled)
  510. *
  511. * @return string
  512. */
  513. public function getStatus()
  514. {
  515. if ($this->getData('start_time') > date('Y-m-d H:i:s', time())) {
  516. return self::SCHEDULED;
  517. }
  518. else if ($this->getData('closed')) {
  519. return self::CLOSED;
  520. }
  521. else {
  522. return self::OPEN;
  523. }
  524. }
  525. /**
  526. *
  527. * check if listing is active (and not a draft)
  528. *
  529. * @return bool
  530. */
  531. public function isActive()
  532. {
  533. if (
  534. $this->isDraft() === false &&
  535. $this->getData('active') == 1 &&
  536. $this->getData('approved') == 1 &&
  537. $this->getData('deleted') != 1
  538. ) {
  539. return true;
  540. }
  541. return false;
  542. }
  543. /**
  544. *
  545. * check if listing is open
  546. *
  547. * @return bool
  548. */
  549. public function isOpen()
  550. {
  551. return ($this->getStatus() == self::OPEN) ? true : false;
  552. }
  553. /**
  554. *
  555. * check if listing is scheduled
  556. *
  557. * @return bool
  558. */
  559. public function isScheduled()
  560. {
  561. return ($this->getStatus() == self::SCHEDULED) ? true : false;
  562. }
  563. /**
  564. *
  565. * check if listing is closed
  566. *
  567. * @return bool
  568. */
  569. public function isClosed()
  570. {
  571. return ($this->getStatus() == self::CLOSED) ? true : false;
  572. }
  573. /**
  574. *
  575. * generate the meta description of the listing.
  576. *
  577. * it will be something like: {title} in {category}
  578. *
  579. * @return string
  580. */
  581. public function getMetaDescription()
  582. {
  583. $breadcrumbs = implode(' > ', $this->getCategories()->getBreadcrumbs(
  584. $this->getData('category_id')));
  585. return sprintf('%s in %s', $this->getData('name'), $breadcrumbs);
  586. }
  587. /**
  588. *
  589. * get relist method
  590. *
  591. * @return string
  592. */
  593. public function getRelistMethod()
  594. {
  595. if (!$this->_relistMethod) {
  596. $settings = $this->getSettings();
  597. $this->setRelistMethod(
  598. (isset($settings['relist_method'])) ? $settings['relist_method'] : null);
  599. }
  600. return $this->_relistMethod;
  601. }
  602. /**
  603. *
  604. * set relist method
  605. *
  606. * @param string $relistMethod
  607. *
  608. * @return $this
  609. */
  610. public function setRelistMethod($relistMethod = null)
  611. {
  612. if (!in_array($relistMethod, $this->_relistMethods)) {
  613. $relistMethod = array_shift(
  614. array_values($this->_relistMethods));
  615. }
  616. $this->_relistMethod = $relistMethod;
  617. return $this;
  618. }
  619. /**
  620. *
  621. * get the available quantity for this listing
  622. * this is calculated based on the quantity field minus and pending sales that have the listing added
  623. * if quantity = -1 - we have an unlimited quantity of items for the listing
  624. *
  625. * @param int|null $quantity initial quantity
  626. * @param array|null $productAttributes the product attributes for which to check stock levels
  627. *
  628. * @return int|true true if we have unlimited quantity
  629. */
  630. public function getAvailableQuantity($quantity = null, $productAttributes = null)
  631. {
  632. $stockLevels = \Ppb\Utility::unserialize($this->getData('stock_levels'));
  633. $quantityAvailable = 0;
  634. if (!empty($stockLevels) && is_array($stockLevels) && $this->getData('listing_type') == 'product') {
  635. foreach ($stockLevels as $stockLevel) {
  636. if (is_array($stockLevel)) {
  637. if (array_key_exists('options', $stockLevel)) {
  638. $selected = \Ppb\Utility::unserialize($stockLevel['options']);
  639. if ($selected == $productAttributes) {
  640. $quantityAvailable = $stockLevel['quantity'];
  641. }
  642. }
  643. }
  644. }
  645. }
  646. else {
  647. $quantityAvailable = $this->getData('quantity');
  648. }
  649. if ($quantityAvailable == self::UNLIMITED_QUANTITY) {
  650. return true;
  651. }
  652. $settings = $this->getSettings();
  653. if ($settings['pending_sales_listings_expire_hours']) {
  654. $quantity += $quantityAvailable;
  655. $salesListings = $this->findDependentRowset('\Ppb\Db\Table\SalesListings');
  656. /** @var \Ppb\Db\Table\Row\SaleListing $saleListing */
  657. foreach ($salesListings as $saleListing) {
  658. $sale = $saleListing->findParentRow('\Ppb\Db\Table\Sales');
  659. if ($sale['pending']) {
  660. $quantity -= $saleListing['quantity'];
  661. }
  662. }
  663. }
  664. else {
  665. $quantity = $quantityAvailable;
  666. }
  667. return ($quantity > 0) ? $quantity : 0;
  668. }
  669. /**
  670. *
  671. * returns the time left in seconds or 0 for time left or if this doesnt apply for the listing
  672. *
  673. * @return int
  674. */
  675. public function getTimeLeft()
  676. {
  677. $timeLeft = strtotime($this->getData('end_time')) - time();
  678. return ($timeLeft > 0) ? $timeLeft : 0;
  679. }
  680. /**
  681. *
  682. * get the tax type but only if it applies to the selected buyer
  683. *
  684. * @param \Ppb\Db\Table\Row\User $buyer buyer user model
  685. * @param int $billingAddressId billing address id, needed for a sale model
  686. * @param string $country country override
  687. * @param string $state state override
  688. *
  689. * @return bool|\Ppb\Db\Table\Row\TaxType
  690. */
  691. public function getTaxType(User $buyer = null, $billingAddressId = null, $country = null, $state = null)
  692. {
  693. if (!$this->getData('apply_tax')) {
  694. $this->_taxType = false;
  695. }
  696. else if ($this->_taxType === null) {
  697. /** @var \Ppb\Db\Table\Row\User $seller */
  698. $seller = $this->findParentRow('\Ppb\Db\Table\Users');
  699. $taxType = false;
  700. if (($taxTypeId = $seller->canApplyTax()) != false) {
  701. $taxTypeService = new Service\Table\TaxTypes();
  702. $taxTypeModel = $taxTypeService->findBy('id', $taxTypeId);
  703. if ($taxTypeModel instanceof TaxType) {
  704. $locationsIds = \Ppb\Utility::unserialize($taxTypeModel->getData('locations_ids'));
  705. if ($country === null && $state === null) {
  706. if ($buyer === null) {
  707. $buyer = $this->getUser();
  708. }
  709. if ($buyer instanceof User) {
  710. $address = $buyer->getAddress($billingAddressId);
  711. if (isset($address['country']) && isset($address['state'])) {
  712. $country = $address['country'];
  713. $state = $address['state'];
  714. }
  715. }
  716. }
  717. if (in_array($country, $locationsIds) || in_array($state, $locationsIds)
  718. ) {
  719. $taxType = $taxTypeModel;
  720. }
  721. }
  722. }
  723. $this->_taxType = $taxType;
  724. }
  725. return $this->_taxType;
  726. }
  727. /**
  728. *
  729. * get listing owner
  730. *
  731. * @return \Ppb\Db\Table\Row\User|null
  732. */
  733. public function getOwner()
  734. {
  735. /** @var \Ppb\Db\Table\Row\User $owner */
  736. $owner = $this->findParentRow('\Ppb\Db\Table\Users');
  737. return $owner;
  738. }
  739. /**
  740. *
  741. * get the maximum bid from an array of bids
  742. *
  743. * @param bool $current if set to true, include start_price in the array,
  744. * will display the current bid or start price
  745. *
  746. * @return float
  747. */
  748. public function currentBid($current = false)
  749. {
  750. $amounts = array(0);
  751. if ($current === true) {
  752. $amounts[] = $this->getData('start_price');
  753. }
  754. $bids = $this->getBids();
  755. foreach ($bids as $bid) {
  756. $amounts[] = $bid['amount'];
  757. }
  758. return max($amounts);
  759. }
  760. /**
  761. *
  762. * get the latest bid for the selected user (normally for the logged in user)
  763. *
  764. * @param $userId
  765. *
  766. * @return \Ppb\Db\Table\Row\Bid|null
  767. */
  768. public function yourBid($userId)
  769. {
  770. $bids = $this->getBids();
  771. foreach ($bids as $bid) {
  772. if ($bid['user_id'] == $userId) {
  773. return $bid;
  774. }
  775. }
  776. return null;
  777. }
  778. /**
  779. *
  780. * return the minimum amount that can be bid on the listing
  781. *
  782. * @param bool $amount if set to true, it will calculate the minimum bid that will
  783. * need to be set, based on the amount input
  784. * the variable will always be higher than $bidAmount
  785. *
  786. * @return float
  787. */
  788. public function minimumBid($amount = null)
  789. {
  790. $settings = $this->getSettings();
  791. $bidAmount = $this->getData('start_price');
  792. $this->clearBids();
  793. if ($this->countDependentRowset('\Ppb\Db\Table\Bids') > 0) {
  794. $maximumBid = $this->currentBid();
  795. $bidIncrement = $this->getData('bid_increment');
  796. if ($bidIncrement > 0) {
  797. $bidAmount = $maximumBid + $bidIncrement;
  798. }
  799. else {
  800. $incrementsTable = $this->getBidIncrements()->getTable();
  801. $incrementAmount = $incrementsTable->fetchRow(
  802. $incrementsTable->select('amount')
  803. ->where('tier_from <= ?', $maximumBid)
  804. ->where('tier_to > ?', $maximumBid)
  805. );
  806. $bidAmount = $maximumBid + $incrementAmount['amount'];
  807. }
  808. }
  809. if ($amount !== null) {
  810. if ($amount < $bidAmount) {
  811. $amount = $bidAmount;
  812. }
  813. $reservePrice = $this->getData('reserve_price');
  814. if ($bidAmount < $reservePrice) {
  815. $bidAmount = min(array(
  816. $reservePrice, $amount));
  817. }
  818. if (!$settings['proxy_bidding']) {
  819. $bidAmount = $amount;
  820. }
  821. }
  822. return $bidAmount;
  823. }
  824. /**
  825. *
  826. * get payment methods available for the listing
  827. * convert old gateways field to new serialized field
  828. *
  829. * @param string $type type of payment methods to retrieve ('direct', 'offline' or null for all)
  830. *
  831. * @return array
  832. */
  833. public function getPaymentMethods($type = null)
  834. {
  835. $result = array();
  836. if (in_array($type, array(null, 'direct'))) {
  837. $paymentGatewaysService = new Service\Table\PaymentGateways();
  838. $directPayment = \Ppb\Utility::unserialize($this->getData('direct_payment'));
  839. if (!is_array($directPayment)) {
  840. $directPayment = @explode(',', $directPayment);
  841. if (is_array($directPayment)) {
  842. $this->save(array(
  843. 'direct_payment' => serialize($directPayment),
  844. ));
  845. }
  846. }
  847. $directPaymentMethods = array_filter((array)$directPayment);
  848. if (count($directPaymentMethods) > 0) {
  849. // check if the direct payment gateway is still enabled by the seller
  850. $userId = $this->getData('user_id');
  851. $rows = $paymentGatewaysService->getData($userId, $directPaymentMethods, true);
  852. foreach ($rows as $row) {
  853. $className = '\\Ppb\\Model\\PaymentGateway\\' . $row['name'];
  854. if (class_exists($className)) {
  855. /** @var \Ppb\Model\PaymentGateway\AbstractPaymentGateway $gatewayModel */
  856. $gatewayModel = new $className($userId);
  857. if ($gatewayModel->enabled()) {
  858. $result[] = array(
  859. 'id' => $row['id'],
  860. 'type' => 'direct',
  861. 'name' => $row['name'],
  862. 'logo' => $row['logo_path'],
  863. );
  864. }
  865. }
  866. }
  867. }
  868. }
  869. if (in_array($type, array(null, 'offline'))) {
  870. $offlinePaymentMethodsService = new Service\Table\OfflinePaymentMethods();
  871. $offlinePayment = \Ppb\Utility::unserialize($this->getData('offline_payment'));
  872. if (!is_array($offlinePayment)) {
  873. $offlinePayment = @explode(',', $offlinePayment);
  874. if (is_array($offlinePayment)) {
  875. $this->save(array(
  876. 'offline_payment' => serialize($offlinePayment),
  877. ));
  878. }
  879. }
  880. $offlinePaymentMethods = array_filter((array)$offlinePayment);
  881. if (count($offlinePaymentMethods) > 0) {
  882. $select = $offlinePaymentMethodsService->getTable()->select()
  883. ->where('id IN (?)', new Expr(implode(', ', $offlinePaymentMethods)));
  884. $rows = $offlinePaymentMethodsService->fetchAll($select, array('order_id ASC', 'name ASC'));
  885. foreach ($rows as $row) {
  886. $result[] = array(
  887. 'id' => $row['id'],
  888. 'type' => 'offline',
  889. 'name' => $row['name'],
  890. 'logo' => $row['logo'],
  891. );
  892. }
  893. }
  894. }
  895. return $result;
  896. }
  897. /**
  898. *
  899. * create an array of key => value from the custom fields and custom fields data tables
  900. * the custom fields data is available in the listing object when its created
  901. *
  902. * @param string $type
  903. *
  904. * @return array
  905. */
  906. public function getCustomFields($type = self::CUSTOM_FIELDS_TYPE)
  907. {
  908. $result = array();
  909. $categoryId = $this->getData('category_id');
  910. $addlCategoryId = $this->getData('addl_category_id');
  911. $categoriesFilter = array(0);
  912. if ($categoryId) {
  913. $categoriesFilter = array_merge($categoriesFilter, array_keys(
  914. $this->getCategories()->getBreadcrumbs($categoryId)));
  915. }
  916. if ($addlCategoryId) {
  917. $categoriesFilter = array_merge($categoriesFilter, array_keys(
  918. $this->getCategories()->getBreadcrumbs($addlCategoryId)));
  919. }
  920. $customFields = $this->getCustomFieldsService()->getFields(array(
  921. 'type' => $type,
  922. 'active' => 1,
  923. 'category_ids' => $categoriesFilter,
  924. ));
  925. $listingsService = new Service\Listings();
  926. $customFieldsData = $listingsService->getCustomFieldsData($this->getData('id'));
  927. foreach ($customFields as $row) {
  928. foreach ($row as $key => $value) {
  929. if (($array = @unserialize($value)) !== false) {
  930. $row[$key] = $array;
  931. }
  932. }
  933. $customFieldValuePost = $this->getData('custom_field_' . $row['id']);
  934. if (!empty($customFieldValuePost)) {
  935. $row['value'] = $customFieldValuePost;
  936. }
  937. else if (!empty($customFieldsData[$row['id']])) {
  938. $row['value'] = $customFieldsData[$row['id']];
  939. }
  940. else {
  941. $row['value'] = null;
  942. }
  943. $row['value'] = \Ppb\Utility::unserialize($row['value']);
  944. $rowDisplay = array();
  945. $isMultiOptions = false;
  946. if (!empty($row['multiOptions'])) {
  947. if (count(array_filter($row['multiOptions']['key']))) {
  948. $isMultiOptions = true;
  949. }
  950. }
  951. if ($isMultiOptions === true) {
  952. foreach ((array)$row['value'] as $customFldValue) {
  953. if (($customFldKey = array_search($customFldValue, $row['multiOptions']['key'])) !== false) {
  954. $customFldValue = trim($row['prefix'] . ' ' . $row['multiOptions']['value'][$customFldKey] . ' ' . $row['suffix']);
  955. }
  956. if (!empty($customFldValue)) {
  957. $rowDisplay[] = $customFldValue;
  958. }
  959. }
  960. }
  961. else if (is_string($row['value'])) {
  962. $rowDisplay[] = trim($row['prefix'] . ' ' . $row['value'] . ' ' . $row['suffix']);
  963. }
  964. $row['display'] = $rowDisplay;
  965. $result[] = $row;
  966. }
  967. return $result;
  968. }
  969. /**
  970. *
  971. * returns an array used by the url view helper to generate the listing details page uri
  972. *
  973. * @return array
  974. */
  975. public function link()
  976. {
  977. return array(
  978. 'module' => 'listings',
  979. 'controller' => 'listing',
  980. 'action' => 'details',
  981. 'id' => $this->getData('id'),
  982. 'name' => $this->getData('name')
  983. );
  984. }
  985. /**
  986. *
  987. * check if the listing exists
  988. * should return false if it doesnt exist or if it is marked deleted and a user other
  989. * than its owner access the method, or if its inactive
  990. *
  991. * @param bool $extended if set to true, it will return false if the item is marked deleted or inactive
  992. * otherwise it will return false only if the item doesnt exist in the database
  993. *
  994. * @return bool
  995. */
  996. public function exists($extended = true)
  997. {
  998. $listing = $this->getData();
  999. if (isset($listing['id'])) {
  1000. unset($listing['id']);
  1001. }
  1002. if (empty($listing)) {
  1003. return false;
  1004. }
  1005. if ($extended) {
  1006. $user = $this->getUser();
  1007. $userId = (isset($user['id'])) ? $user['id'] : null;
  1008. if ($userId !== $listing['user_id'] &&
  1009. ($listing['deleted'] || ($listing['active'] != 1) || !$listing['approved'])
  1010. ) {
  1011. return false;
  1012. }
  1013. }
  1014. return true;
  1015. }
  1016. /**
  1017. *
  1018. * check if the listing exists and if the logged in / specified user is the owner of the listing
  1019. *
  1020. * @param \Ppb\Db\Table\Row\User $user
  1021. *
  1022. * @return bool
  1023. */
  1024. public function isOwner(User $user = null)
  1025. {
  1026. $exists = $this->exists(false);
  1027. if ($exists === true) {
  1028. if ($user === null) {
  1029. $user = $this->getUser();
  1030. }
  1031. $userId = (isset($user['id'])) ? $user['id'] : null;
  1032. if ($userId !== $this->getData('user_id')) {
  1033. return false;
  1034. }
  1035. }
  1036. return $exists;
  1037. }
  1038. /**
  1039. *
  1040. * check if the listing exists and if the logged in / specified user has added it to the watch list
  1041. *
  1042. * @param \Ppb\Db\Table\Row\User $user
  1043. *
  1044. * @return bool
  1045. */
  1046. public function isWatched(User $user = null)
  1047. {
  1048. $exists = $this->exists(false);
  1049. if ($exists === true) {
  1050. if ($user === null) {
  1051. $user = $this->getUser();
  1052. }
  1053. $bootstrap = Front::getInstance()->getBootstrap();
  1054. $session = $bootstrap->getResource('session');
  1055. $userToken = strval($session->getCookie(User::USER_TOKEN));
  1056. $userId = (isset($user['id'])) ? $user['id'] : null;
  1057. $select = $this->getTable()->select();
  1058. if ($userId !== null) {
  1059. $select->where('user_token = "' . $userToken . '" OR user_id = "' . $userId . '"');
  1060. }
  1061. else {
  1062. $select->where('user_token = ?', $userToken);
  1063. }
  1064. $countWatched = $this->countDependentRowset('\Ppb\Db\Table\ListingsWatch', null, $select);
  1065. if ($countWatched) {
  1066. return true;
  1067. }
  1068. }
  1069. return false;
  1070. }
  1071. /**
  1072. *
  1073. * get the number of users watching the listing
  1074. *
  1075. * @return int
  1076. */
  1077. public function countWatchers()
  1078. {
  1079. return $this->countDependentRowset('\Ppb\Db\Table\ListingsWatch');
  1080. }
  1081. /**
  1082. *
  1083. * count the total number of bids and offers the logged in user has posted on the listing
  1084. *
  1085. * @return int
  1086. */
  1087. public function getNbBidsOffers()
  1088. {
  1089. $user = $this->getUser();
  1090. $select = $this->getTable()->select()
  1091. ->where('user_id = ?', $user['id'])
  1092. ->group('maximum_bid');
  1093. $nbBids = $this->countDependentRowset('\Ppb\Db\Table\Bids', null, $select);
  1094. $select = $this->getTable()->select()
  1095. ->where('user_id = ?', $user['id']);
  1096. $nbOffers = $this->countDependentRowset('\Ppb\Db\Table\Offers', null, $select);
  1097. return ($nbBids + $nbOffers);
  1098. }
  1099. /**
  1100. *
  1101. * check if a purchase action can be validated, return true if valid or
  1102. * an error message string otherwise
  1103. *
  1104. * @param string $type the type of purchase action requested to be validated (bid, buy, offer)
  1105. *
  1106. * @return bool|string
  1107. */
  1108. public function canPurchase($type = 'bid')
  1109. {
  1110. $user = $this->getUser();
  1111. $translate = $this->getTranslate();
  1112. if (empty($user)) {
  1113. return $translate->_('Please log in to access the purchase confirmation page.');
  1114. }
  1115. else if ($user['id'] == $this->getData('user_id')) {
  1116. return $translate->_('You are the owner of the listing.');
  1117. }
  1118. else if (!$this->isActiveAndOpen()) {
  1119. return $translate->_('The listing is closed.');
  1120. }
  1121. else if (($blockMessage = $this->_isBlockedUserPurchasing()) !== false) {
  1122. return $blockMessage;
  1123. }
  1124. $limitBidsOffersPerUser = $this->findParentRow('\Ppb\Db\Table\Users')
  1125. ->getGlobalSettings('limit_bids_per_user');
  1126. switch ($type) {
  1127. case 'bid':
  1128. if ($this->getData('listing_type') == 'product') {
  1129. return $translate->_('This listing is a product. No bids can be placed.');
  1130. }
  1131. else if ($limitBidsOffersPerUser > 0) {
  1132. if ($this->getNbBidsOffers() >= $limitBidsOffersPerUser) {
  1133. $sentence = $translate->_('You have reached the maximum allowed number of bids/offers per user (%s).');
  1134. return sprintf($sentence, $limitBidsOffersPerUser);
  1135. }
  1136. }
  1137. break;
  1138. case 'buy':
  1139. if ($this->isBuyOut() === false) {
  1140. return $translate->_('Buy Out is disabled for this listing.');
  1141. }
  1142. else if ($this->canAddToCart() === true) {
  1143. return $translate->_('The product can only be purchased through a shopping cart.');
  1144. }
  1145. break;
  1146. case 'offer':
  1147. if ($this->isMakeOffer() === false) {
  1148. return $translate->_('Make Offer is disabled for this listing.');
  1149. }
  1150. else if ($limitBidsOffersPerUser > 0) {
  1151. if ($this->getNbBidsOffers() >= $limitBidsOffersPerUser) {
  1152. $sentence = $translate->_('You have reached the maximum allowed number of bids/offers per user (%s).');
  1153. return sprintf($sentence, $limitBidsOffersPerUser);
  1154. }
  1155. }
  1156. break;
  1157. }
  1158. return true;
  1159. }
  1160. /**
  1161. *
  1162. * check if the listing can be added to the shopping cart
  1163. * or return an error message otherwise
  1164. *
  1165. * the owner can add his own products to the shopping cart, but check out is not allowed.
  1166. *
  1167. * @param int|null $quantity if quantity is set, check by quantity as well
  1168. * @param array|null $productAttributes the product attributes for which to check stock levels
  1169. *
  1170. * @return bool|string
  1171. */
  1172. public function canAddToCart($quantity = null, $productAttributes = null)
  1173. {
  1174. $settings = $this->getSettings();
  1175. $translate = $this->getTranslate();
  1176. if (!$settings['enable_shopping_cart']) {
  1177. return $translate->_('The shopping cart module is disabled.');
  1178. }
  1179. else if ($this->getData('listing_type') != 'product') {
  1180. return $translate->_('Only products can be added to a shopping cart.');
  1181. }
  1182. else if (!$this->isActiveAndOpen()) {
  1183. return $translate->_('The listing is closed.');
  1184. }
  1185. else if (($blockMessage = $this->_isBlockedUserPurchasing()) !== false) {
  1186. return $blockMessage;
  1187. }
  1188. else {
  1189. /** @var \Ppb\Db\Table\Row\User $seller */
  1190. $seller = $this->findParentRow('\Ppb\Db\Table\Users');
  1191. switch ($settings['shopping_cart_applies']) {
  1192. case 'store_owners':
  1193. if (!$seller->storeStatus(true)) {
  1194. return $translate->_("The seller's store is disabled.");
  1195. }
  1196. break;
  1197. case 'store_listings':
  1198. if (!$seller->storeStatus(true) || $this->getData('list_in') == 'site') {
  1199. return $translate->_('Only products listed in store can be added to the shopping cart.');
  1200. }
  1201. break;
  1202. }
  1203. if ($quantity !== null) {
  1204. $availableQuantity = $this->getAvailableQuantity(null, $productAttributes);
  1205. if ($availableQuantity < $quantity) {
  1206. return $translate->_('Cannot add to cart - not enough quantity available.');
  1207. }
  1208. }
  1209. }
  1210. return true;
  1211. }
  1212. /**
  1213. *
  1214. * check if a pending offer can be accepted on a listing
  1215. *
  1216. * @param int $quantity
  1217. * @param array|null $productAttributes the product attributes for which to check stock levels
  1218. *
  1219. * @return bool
  1220. */
  1221. public function canAcceptOffer($quantity = 1, $productAttributes = null)
  1222. {
  1223. if ($this->isMakeOffer()) {
  1224. $availableQuantity = $this->getAvailableQuantity(null, $productAttributes);
  1225. if ($quantity <= $availableQuantity) {
  1226. return true;
  1227. }
  1228. }
  1229. return false;
  1230. }
  1231. /**
  1232. *
  1233. * drafts can be edited always
  1234. * @7.10 scheduled listings can always be edited, just like drafts
  1235. *
  1236. * active open listings can be edited, if:
  1237. * - for auctions:
  1238. * no activity (bids, offers, sale).
  1239. * the remaining duration needs to be greater than the minimum limit set in admin
  1240. * - for products:
  1241. * there can be activity, but in this case only selected fields can be edited
  1242. *
  1243. * @return bool
  1244. */
  1245. public function canEdit()
  1246. {
  1247. if ($this->isDraft() || $this->isScheduled()) {
  1248. return true;
  1249. }
  1250. $startTime = strtotime($this->getData('start_time'));
  1251. if (!$this->isClosed() && $this->getData('active')) {
  1252. // auctions ending time limit setting
  1253. if ($this->isOpen() && $this->getData('listing_type') == 'auction') {
  1254. $settings = $this->getSettings();
  1255. // the below snippet is needed for when checking if the listing can be edited right on the Listing\Create action
  1256. $endTime = strtotime($this->getData('end_time'));
  1257. if (!$endTime) {
  1258. $endTime = $startTime + $this->getData('duration') * 86400;
  1259. }
  1260. $timeRemaining = $endTime - time();
  1261. if ($timeRemaining < $settings['auctions_editing_hours'] * 3600) {
  1262. return false;
  1263. }
  1264. }
  1265. return ($this->getData('listing_type') == 'product') ? true : !$this->hasActivity();
  1266. }
  1267. return false;
  1268. }
  1269. /**
  1270. *
  1271. * check if the poster can close an open listing
  1272. * products can be closed at any time, while auctions can be closed depending on the
  1273. * close auction before end time setting
  1274. *
  1275. * @return bool
  1276. */
  1277. public function canClose()
  1278. {
  1279. if ($this->isOpen()) {
  1280. $settings = $this->getSettings();
  1281. if ($this->getData('listing_type') == 'auction') {
  1282. if ($settings['close_auctions_end_time'] || !$this->hasActivity()) {
  1283. return true;
  1284. }
  1285. }
  1286. else {
  1287. return true;
  1288. }
  1289. }
  1290. return false;
  1291. }
  1292. /**
  1293. *
  1294. * a listing can be deleted if not scheduled/closed or for auctions if there is no activity
  1295. *
  1296. * @return bool
  1297. */
  1298. public function canDelete()
  1299. {
  1300. if ($this->isOpen()) {
  1301. if ($this->getData('listing_type') == 'auction' && $this->hasActivity()) {
  1302. return false;
  1303. }
  1304. }
  1305. return true;
  1306. }
  1307. /**
  1308. *
  1309. * check if there was any activity on the listing (bidding, offers, purchasing)
  1310. *
  1311. * @return bool
  1312. */
  1313. public function hasActivity()
  1314. {
  1315. return (count($this->getBids()) ||
  1316. count($this->getOffers()) ||
  1317. count($this->getSales())
  1318. ) ? true : false;
  1319. }
  1320. /**
  1321. *
  1322. * check if buy out is enabled for the listing
  1323. *
  1324. * @return bool
  1325. */
  1326. public function isBuyOut()
  1327. {
  1328. if ($this->getData('listing_type') == 'product') {
  1329. return true;
  1330. }
  1331. else {
  1332. $buyoutPrice = $this->getData('buyout_price');
  1333. if ($buyoutPrice > 0) {
  1334. $settings = $this->getSettings();
  1335. if ($settings['enable_buyout']) {
  1336. $maximumBid = $this->currentBid();
  1337. if ($settings['always_show_buyout'] && $maximumBid < $buyoutPrice) {
  1338. return true;
  1339. }
  1340. else if (!$this->countDependentRowset('\Ppb\Db\Table\Bids') || $maximumBid < $this->getData('reserve_price')) {
  1341. return true;
  1342. }
  1343. }
  1344. }
  1345. }
  1346. return false;
  1347. }
  1348. /**
  1349. *
  1350. * check if the make offer feature is enabled for the listing
  1351. *
  1352. * @return bool
  1353. */
  1354. public function isMakeOffer()
  1355. {
  1356. $settings = $this->getSettings();
  1357. if ($settings['enable_make_offer'] && $this->getData('enable_make_offer')) {
  1358. return true;
  1359. }
  1360. return false;
  1361. }
  1362. /**
  1363. *
  1364. * check if the listing is active and open
  1365. *
  1366. * @return bool
  1367. */
  1368. public function isActiveAndOpen()
  1369. {
  1370. if ($this->isActive() && $this->isOpen()) {
  1371. return true;
  1372. }
  1373. return false;
  1374. }
  1375. /**
  1376. *
  1377. * determine and set the 'approved' flag for the listing
  1378. *
  1379. * @param int|null $value
  1380. *
  1381. * @return $this
  1382. */
  1383. public function updateApproved($value = null)
  1384. {
  1385. $settings = $this->getSettings();
  1386. if ($value !== null) {
  1387. $data['approved'] = $value;
  1388. }
  1389. else {
  1390. if ($settings['enable_listings_approval']) {
  1391. $data['approved'] = 0;
  1392. $mail = new \Admin\Model\Mail\Admin();
  1393. $mail->listingApproval($this)->send();
  1394. }
  1395. else {
  1396. $data['approved'] = 1;
  1397. }
  1398. }
  1399. $this->save($data);
  1400. return $this;
  1401. }
  1402. /**
  1403. *
  1404. * update listing quantity field
  1405. *
  1406. * @param int $quantity
  1407. * @param mixed $productAttributes
  1408. * @param string $operation
  1409. *
  1410. * @return int remaining quantity (for stock levels it will return -1)
  1411. */
  1412. public function updateQuantity($quantity, $productAttributes = null, $operation = self::SUBTRACT)
  1413. {
  1414. $stockLevels = \Ppb\Utility::unserialize($this->getData('stock_levels'));
  1415. $productAttributes = \Ppb\Utility::unserialize($productAttributes);
  1416. $quantityRemaining = self::UNLIMITED_QUANTITY;
  1417. if (!empty($stockLevels) && $this->getData('listing_type') == 'product') {
  1418. foreach ($stockLevels as $key => $stockLevel) {
  1419. if ($stockLevel['options'] == $productAttributes) {
  1420. $quantityAvailable = $stockLevel['quantity'];
  1421. if ($quantityAvailable != self::UNLIMITED_QUANTITY) {
  1422. $stockLevels[$key]['quantity']
  1423. = $this->_quantityOperator($quantityAvailable, $quantity, $operation);
  1424. }
  1425. }
  1426. }
  1427. $this->save(array(
  1428. 'stock_levels' => serialize($stockLevels),
  1429. ));
  1430. }
  1431. else {
  1432. $quantityAvailable = $this->getData('quantity');
  1433. if ($quantityAvailable != self::UNLIMITED_QUANTITY) {
  1434. $quantityRemaining
  1435. = $this->_quantityOperator($quantityAvailable, $quantity, $operation);
  1436. $this->save(array(
  1437. 'quantity' => $quantityRemaining,
  1438. ));
  1439. }
  1440. }
  1441. return $quantityRemaining;
  1442. }
  1443. /**
  1444. *
  1445. * apply operations to the quantity field
  1446. *
  1447. * @param int $quantityAvailable
  1448. * @param int $quantity
  1449. * @param string $operation
  1450. *
  1451. * @return int
  1452. */
  1453. protected function _quantityOperator($quantityAvailable, $quantity, $operation = self::ADD)
  1454. {
  1455. if ($quantityAvailable != self::UNLIMITED_QUANTITY) {
  1456. return ($operation == self::ADD) ?
  1457. ($quantityAvailable + $quantity) : ($quantityAvailable - $quantity);
  1458. }
  1459. return self::UNLIMITED_QUANTITY;
  1460. }
  1461. /**
  1462. *
  1463. * determine and set the 'active' flag for the listing
  1464. *
  1465. * @param int $active
  1466. *
  1467. * @return $this
  1468. */
  1469. public function updateActive($active = 1)
  1470. {
  1471. $this->save(array(
  1472. 'active' => (int)$active,
  1473. ));
  1474. return $this;
  1475. }
  1476. /**
  1477. *
  1478. * close a listing
  1479. * when the cron closes the listing, the end time will not be modified.
  1480. *
  1481. * @param bool $automatic whether the listing is closed automatically (by the cron job) or not
  1482. *
  1483. * @return $this
  1484. */
  1485. public function close($automatic = false)
  1486. {
  1487. $data = array();
  1488. if (strtotime($this->getData('start_time')) < time() && $this->getData('closed') == 0) {
  1489. $data['closed'] = 1;
  1490. if ($automatic === false) {
  1491. $data['end_time'] = new Expr('now()');
  1492. }
  1493. $this->save($data);
  1494. $this->_closedFlag = true;
  1495. }
  1496. return $this;
  1497. }
  1498. /**
  1499. *
  1500. * relist a listing
  1501. *
  1502. * - the quantity field is calculated from the quantity sum in the sales listings table
  1503. * and the listing quantity field
  1504. *
  1505. * @7.9 if duration === null => custom end time; else duration - if 0 = unlimited
  1506. *
  1507. * @param bool $autoRelist auto relist flag
  1508. *
  1509. * @return int the id of the new listing
  1510. */
  1511. public function relist($autoRelist = false)
  1512. {
  1513. // calculate quantity
  1514. $service = $this->getSalesListings();
  1515. if (!$this->getData('stock_levels')) {
  1516. $quantity = $this->getTable()->getAdapter()->fetchOne(
  1517. $service->getTable()->select(array('Qty' => new Expr('sum(quantity)')))
  1518. ->where('listing_id = ?', $this->getData('id'))
  1519. );
  1520. $quantity += $this->getData('quantity');
  1521. }
  1522. else {
  1523. $quantity = 0;
  1524. }
  1525. // by default all relisted listings are activated [admin default]
  1526. // for the front end, we will run the method that will charge setup fees and set the approval flag
  1527. $params = array(
  1528. 'start_time_type' => 0,
  1529. 'closed' => 0,
  1530. 'is_relisted' => 1,
  1531. 'end_time_type' => 0,
  1532. 'active' => 1,
  1533. 'approved' => 1,
  1534. 'deleted' => 0,
  1535. 'nb_clicks' => 0,
  1536. 'draft' => 0,
  1537. 'counted_at' => new Expr('null'),
  1538. 'last_count_operation' => self::COUNT_OP_NONE,
  1539. 'quantity' => $quantity,
  1540. );
  1541. $duration = $this->getData('duration');
  1542. if ($duration === null) {
  1543. $difference = strtotime($this->getData('end_time')) - strtotime($this->getData('start_time'));
  1544. $params['end_time_type'] = 1;
  1545. $params['end_time'] = date('Y-m-d H:i:s',
  1546. time() + (($difference < 86400) ? 86400 : $difference)); // minimum 1 day duration
  1547. }
  1548. else {
  1549. $endTime = ($duration > 0) ? time() + $duration * 86400 : null;
  1550. $params['end_time'] = ($endTime) ? date('Y-m-d H:i:s', $endTime) : new Expr('null');
  1551. }
  1552. if ($autoRelist !== false) {
  1553. $nbRelists = $this->getData('nb_relists') - 1;
  1554. if ($nbRelists > 0) {
  1555. $params['nb_relists'] = $nbRelists;
  1556. }
  1557. else {
  1558. $params['nb_relists'] = 0;
  1559. $params['auto_relist_sold'] = 0;
  1560. }
  1561. }
  1562. $listingsService = new Service\Listings();
  1563. $listingsService->setUser(
  1564. $this->findParentRow('\Ppb\Db\Table\Users'));
  1565. $listingId = null;
  1566. switch ($this->getRelistMethod()) {
  1567. case 'new':
  1568. $listing = $listingsService->findBy('id', $this->getData('id'), true, true);
  1569. $data = $listing->getData();
  1570. unset($data['id']);
  1571. if (!$autoRelist || !$this->getData('auto_relist_sold')) {
  1572. $this->delete();
  1573. }
  1574. // need to also copy custom fields and
  1575. $listingId = $listingsService->save(array_merge($data, $params));
  1576. break;
  1577. case 'same':
  1578. $params['start_time'] = date('Y-m-d H:i:s', time());
  1579. $tableColumns = $this->getTable()->info(Table\AbstractTable::COLS);
  1580. $params = array_intersect_key($params, array_flip(array_values($tableColumns)));
  1581. $this->save($params);
  1582. // delete all data from the bids, offers and sales_listings tables
  1583. $dependentTables = array(
  1584. '\Ppb\Db\Table\Bids',
  1585. '\Ppb\Db\Table\Offers',
  1586. );
  1587. if (!$autoRelist || !$this->getData('auto_relist_sold')) {
  1588. $dependentTables[] = '\Ppb\Db\Table\SalesListings';
  1589. }
  1590. foreach ($dependentTables as $dependentTable) {
  1591. $rowset = $this->findDependentRowset($dependentTable);
  1592. /** @var \Cube\Db\Table\Row $row */
  1593. foreach ($rowset as $row) {
  1594. $row->delete();
  1595. }
  1596. }
  1597. $listingId = $this->getData('id');
  1598. break;
  1599. }
  1600. return $listingId;
  1601. }
  1602. /**
  1603. *
  1604. * processes post listing setup actions:
  1605. * charges listing setup fees in account mode
  1606. * activates and approves listing based on different settings
  1607. *
  1608. * @param \Ppb\Db\Table\Row\Listing $savedListing in case we edit a listing
  1609. *
  1610. * @return string returns any related output messages
  1611. */
  1612. public function processPostSetupActions(Listing $savedListing = null)
  1613. {
  1614. /** @var \Cube\View $view */
  1615. $view = Front::getInstance()->getBootstrap()->getResource('view');
  1616. $message = null;
  1617. /** @var \Ppb\Db\Table\Row\User $user */
  1618. $user = $this->findParentRow('\Ppb\Db\Table\Users');
  1619. $listingSetupService = new Service\Fees\ListingSetup(
  1620. $this, $user);
  1621. // apply listing setup voucher if available
  1622. if ($voucherCode = $this->getData('voucher_code')) {
  1623. $listingSetupService->setVoucher($voucherCode);
  1624. $voucher = $listingSetupService->getVoucher();
  1625. if ($voucher instanceof Voucher) {
  1626. $voucher->updateUses();
  1627. }
  1628. }
  1629. if ($savedListing instanceof Listing) {
  1630. $listingSetupService->setSavedListing($savedListing);
  1631. }
  1632. $listingFees = $listingSetupService->calculate();
  1633. // apply listing setup fee
  1634. $totalAmount = $listingSetupService->getTotalAmount();
  1635. $userPaymentMode = $user->userPaymentMode();
  1636. if ($totalAmount > 0 && $userPaymentMode == 'live') {
  1637. $this->updateActive(0);
  1638. }
  1639. else {
  1640. $this->updateActive();
  1641. if ($totalAmount > 0) {
  1642. $user->updateBalance($totalAmount);
  1643. $accountingService = new Service\Accounting();
  1644. $accountingService->setListingId($this->getData('id'))
  1645. ->setUserId($user['id'])
  1646. ->saveMultiple($listingFees);
  1647. if ($view->isHelper('amount')) {
  1648. $translate = $this->getTranslate();
  1649. $sentence = $translate->_('The amount of %s has been debited from your account balance.');
  1650. $message = sprintf($sentence, $view->amount($totalAmount));
  1651. }
  1652. }
  1653. }
  1654. $this->updateApproved();
  1655. return $message;
  1656. }
  1657. /**
  1658. *
  1659. * process category counter for the listing object
  1660. * will work based on the counted_at and last_count_operation flags and will be called by the cron job
  1661. *
  1662. * @param bool|string $force force count
  1663. *
  1664. * @return bool true if counted, false if unmodified
  1665. */
  1666. public function processCategoryCounter($force = false)
  1667. {
  1668. $counted = false;
  1669. $operation = self::COUNT_OP_ADD;
  1670. if ($force === false) {
  1671. if ($this->isActiveAndOpen()) {
  1672. $operation = self::COUNT_OP_ADD;
  1673. }
  1674. else if ($this->getData('list_in') != 'store') {
  1675. $operation = self::COUNT_OP_SUBTRACT;
  1676. }
  1677. }
  1678. $lastCountOperation = $this->getData('last_count_operation');
  1679. if (
  1680. $force === true ||
  1681. ($operation == self::COUNT_OP_ADD && $lastCountOperation != self::COUNT_OP_ADD) ||
  1682. ($operation == self::COUNT_OP_SUBTRACT && $lastCountOperation == self::COUNT_OP_ADD)
  1683. ) {
  1684. $this->countCategoriesCounter($operation);
  1685. $counted = true;
  1686. }
  1687. $this->save(array(
  1688. 'last_count_operation' => $operation,
  1689. 'counted_at' => date('Y-m-d H:i:s', time()),
  1690. ));
  1691. return $counted;
  1692. }
  1693. /**
  1694. *
  1695. * do the requested category counting operation
  1696. * 7.2 - added a fix which was causing this method to loop indefinitely if a category that was to be counted didn't exist
  1697. * 7.7 - only count the additional category if the setting is enabled in admin
  1698. *
  1699. * @param $operation
  1700. *
  1701. * @return $this
  1702. */
  1703. public function countCategoriesCounter($operation)
  1704. {
  1705. $settings = $this->getSettings();
  1706. $ids = array(
  1707. $this->getData('category_id'),
  1708. );
  1709. if ($settings['addl_category_listing']) {
  1710. $ids[] = $this->getData('addl_category_id');
  1711. }
  1712. foreach ($ids as $id) {
  1713. if ($id > 0) {
  1714. do {
  1715. /** @var \Ppb\Db\Table\Row\Category $category */
  1716. $category = $this->getCategories()->findBy('id', $id);
  1717. $id = 0;
  1718. if (count($category) > 0) {
  1719. if ($operation == self::COUNT_OP_SUBTRACT) {
  1720. $category->subtractCounter($this->getData('listing_type'));
  1721. }
  1722. else if ($operation == self::COUNT_OP_ADD) {
  1723. $category->addCounter($this->getData('listing_type'));
  1724. }
  1725. $id = $category['parent_id'];
  1726. }
  1727. } while ($id > 0);
  1728. }
  1729. }
  1730. return $this;
  1731. }
  1732. /**
  1733. *
  1734. * The method will post a bid, an offer or create a sale if the buy out method is used
  1735. *
  1736. * @param array $data place bid related data
  1737. * @param string $type the type of purchase action (bid|buy|offer)
  1738. * @param int $userId force user id
  1739. *
  1740. * @return string return message that is to be output
  1741. */
  1742. public function placeBid(array $data, $type = 'bid', $userId = null)
  1743. {
  1744. $bootstrap = Front::getInstance()->getBootstrap();
  1745. if ($userId === null) {
  1746. $user = $bootstrap->getResource('user');
  1747. $userId = $user['id'];
  1748. }
  1749. $view = $bootstrap->getResource('view');
  1750. $translate = $this->getTranslate();
  1751. $message = null;
  1752. switch ($type) {
  1753. case 'bid':
  1754. $service = new Service\Bids();
  1755. $data['user_id'] = $userId;
  1756. $data['listing_id'] = $this->getData('id');
  1757. $service->save($data);
  1758. $message = $service->getMessage();
  1759. $usersService = new Service\Users();
  1760. $user = $usersService->findBy('id', $userId);
  1761. $mail = new \Listings\Model\Mail\OwnerNotification();
  1762. $mail->newBid($this->getData('id'), $user, $data['amount'])->send();
  1763. break;
  1764. case 'buy':
  1765. $service = new Service\Sales();
  1766. $quantity = 1;
  1767. if (isset($data['quantity'])) {
  1768. $quantity = ($data['quantity'] > 0) ? $data['quantity'] : $quantity;
  1769. }
  1770. $price = $this->getProductPrice($data['product_attributes']);
  1771. $data = array(
  1772. 'buyer_id' => $userId,
  1773. 'seller_id' => $this->getData('user_id'),
  1774. 'postage_id' => (int)$data['postage_id'],
  1775. 'shipping_address_id' => $data['shipping_address_id'],
  1776. 'apply_insurance' => (bool)$data['apply_insurance'],
  1777. 'voucher_details' => $data['voucher_details'],
  1778. 'listings' => array(
  1779. array(
  1780. 'listing_id' => $this->getData('id'),
  1781. 'price' => $price,
  1782. 'quantity' => $quantity,
  1783. 'product_attributes' => $data['product_attributes'],
  1784. )
  1785. ),
  1786. );
  1787. $service->save($data);
  1788. $message = sprintf($translate->_('You have successfully purchased this item - price: %s, quantity purchased: %s.'),
  1789. $view->amount($price, $this->getData('currency')), $quantity);
  1790. $this->setSaleId(
  1791. $service->getSaleId());
  1792. break;
  1793. case 'offer':
  1794. $service = new Service\Offers();
  1795. $data['user_id'] = $userId;
  1796. $data['type'] = 'offer';
  1797. if (empty($data['receiver_id'])) {
  1798. $data['receiver_id'] = $this->getData('user_id');
  1799. }
  1800. $data['listing_id'] = $this->getData('id');
  1801. $quantity = 1;
  1802. if (isset($data['quantity'])) {
  1803. $quantity = ($data['quantity'] > 0) ? $data['quantity'] : $quantity;
  1804. }
  1805. $data['quantity'] = $quantity;
  1806. $id = $service->save($data);
  1807. $message = sprintf($translate->_('Your offer, in the amount of %s, has been posted successfully.'),
  1808. $view->amount($data['amount'], $this->getData('currency')));
  1809. /** @var \Ppb\Db\Table\Row\Offer $row */
  1810. $row = $service->findBy('id', $id);
  1811. $mail = new \Listings\Model\Mail\UserNotification();
  1812. $mail->newOffer($this, $row)->send();
  1813. break;
  1814. }
  1815. return $message;
  1816. }
  1817. /**
  1818. *
  1819. * get the price of the product based on the selected product attributes and their price variations
  1820. *
  1821. * @param mixed $productAttributes
  1822. *
  1823. * @return float
  1824. */
  1825. public function getProductPrice($productAttributes = null)
  1826. {
  1827. $price = $this->getData('buyout_price');
  1828. $stockLevels = \Ppb\Utility::unserialize($this->getData('stock_levels'));
  1829. $productAttributes = \Ppb\Utility::unserialize($productAttributes);
  1830. if (!empty($stockLevels) && $this->getData('listing_type') == 'product') {
  1831. foreach ($stockLevels as $key => $stockLevel) {
  1832. if ($stockLevel['options'] == $productAttributes) {
  1833. $price += $stockLevel['price'];
  1834. break;
  1835. }
  1836. }
  1837. }
  1838. return $price;
  1839. }
  1840. /**
  1841. *
  1842. * this method assigns a set bid as a winning bid on a listing, or it assigns it automatically when:
  1843. * - we have a standard auction with a high bid greater or equal to the reserve price
  1844. * (fixed in V7.3, before it required the bid amount to be greater than the reserve)
  1845. * - we have a first bidder auction (later)
  1846. *
  1847. * @param \Ppb\Db\Table\Row\Bid $bid the bid that should be assigned as winning bid, or null if the bid should be selected automatically
  1848. *
  1849. * @throws \RuntimeException
  1850. * @return int|false the id of the resulted sale or false if no winner has been assigned
  1851. */
  1852. public function assignWinner(Bid $bid = null)
  1853. {
  1854. if ($bid !== null) {
  1855. if ($bid['listing_id'] !== $this->getData('id')) {
  1856. throw new \RuntimeException("The listing id of the bid object inserted in the assignWinner() method is invalid");
  1857. }
  1858. }
  1859. else {
  1860. $this->clearBids();
  1861. $bids = $this->getBids();
  1862. if (count($bids) > 0) {
  1863. switch ($this->getData('listing_type')) {
  1864. case 'auction':
  1865. $highBid = $bids[0];
  1866. if ($highBid['amount'] >= $this->getData('reserve_price')) {
  1867. $bid = $highBid;
  1868. }
  1869. break;
  1870. }
  1871. }
  1872. }
  1873. if ($bid instanceof Bid) {
  1874. $service = new Service\Sales();
  1875. $data = array(
  1876. 'buyer_id' => $bid['user_id'],
  1877. 'seller_id' => $this->getData('user_id'),
  1878. 'listings' => array(
  1879. array(
  1880. 'listing_id' => $this->getData('id'),
  1881. 'price' => $bid['amount'],
  1882. 'quantity' => 1,
  1883. )
  1884. ),
  1885. );
  1886. $service->save($data);
  1887. $this->setSaleId(
  1888. $service->getSaleId());
  1889. return $this->getSaleId();
  1890. }
  1891. return false;
  1892. }
  1893. /**
  1894. *
  1895. * add a new click to the listing
  1896. *
  1897. * @7.9: do not purge the queries cache - as such do not use the save() method
  1898. *
  1899. * @return $this
  1900. */
  1901. public function addClick()
  1902. {
  1903. $nbClicks = $this->_data['nb_clicks'];
  1904. $table = $this->getTable();
  1905. $tableName = $table->getPrefix() . $table->getName();
  1906. $table->getAdapter()->update($tableName, array(
  1907. 'nb_clicks' => new Expr('nb_clicks + 1')
  1908. ), $this->_getWhereQuery());
  1909. $this->_data['nb_clicks'] = $nbClicks + 1;
  1910. return $this;
  1911. }
  1912. /**
  1913. *
  1914. * add the product to the shopping cart
  1915. * first we check if a shopping cart is active and if it is, add the item to the existing shopping cart
  1916. *
  1917. * the user id, insurance and postage are only saved when updating the shopping cart or checking out
  1918. *
  1919. * carts need to match the exact same fields like when combining invoices:
  1920. *
  1921. * @param int|null $quantity
  1922. * @param array|null $productAttributes
  1923. *
  1924. * @return $this
  1925. */
  1926. public function addToCart($quantity = null, $productAttributes = null)
  1927. {
  1928. $quantity = ($quantity < 1) ? 1 : $quantity;
  1929. $bootstrap = Front::getInstance()->getBootstrap();
  1930. $session = $bootstrap->getResource('session');
  1931. $userToken = strval($session->getCookie(User::USER_TOKEN));
  1932. $salesService = new Service\Sales();
  1933. $select = $salesService->getTable()->select()
  1934. ->where('user_token = ?', $userToken)
  1935. ->where('seller_id = ?', $this->getData('user_id'))
  1936. ->where('sale_data REGEXP \'"currency";s:[[:digit:]]+:"' . $this->getData('currency') . '"\'')
  1937. ->where('sale_data REGEXP \'"country";s:[[:digit:]]+:"' . $this->getData('country') . '"\'')
  1938. ->where('sale_data REGEXP \'"state";s:[[:digit:]]+:"' . $this->getData('state') . '"\'')
  1939. ->where('sale_data REGEXP \'"address";s:[[:digit:]]+:"' . $this->getData('address') . '"\'')
  1940. ->where('sale_data REGEXP \'"apply_tax";s:[[:digit:]]+:"' . $this->getData('apply_tax') . '"\'')
  1941. ->where('pending = ?', 1);
  1942. if ($pickupOptions = $this->getData('pickup_options')) {
  1943. $select->where('sale_data REGEXP \'"pickup_options";s:[[:digit:]]+:"' . $pickupOptions . '"\'');
  1944. }
  1945. else {
  1946. $select->where('sale_data REGEXP \'"pickup_options";N\'');
  1947. }
  1948. $row = $salesService->fetchAll($select)->getRow(0);
  1949. $data = array(
  1950. 'user_token' => $userToken,
  1951. 'seller_id' => $this->getData('user_id'),
  1952. 'quantity' => (int)$quantity,
  1953. 'pending' => 1,
  1954. 'listings' => array(
  1955. array(
  1956. 'listing_id' => $this->getData('id'),
  1957. 'price' => $this->getProductPrice($productAttributes),
  1958. 'quantity' => (int)$quantity,
  1959. 'product_attributes' => (count($productAttributes) > 0) ? serialize($productAttributes) : null,
  1960. )
  1961. ),
  1962. );
  1963. if ($row !== null) {
  1964. $data['id'] = $row->getData('id');
  1965. }
  1966. $salesService->save($data);
  1967. return $this;
  1968. }
  1969. /**
  1970. *
  1971. * save the recently viewed listing in the table
  1972. *
  1973. * @return $this
  1974. */
  1975. public function addRecentlyViewedListing()
  1976. {
  1977. $settings = $this->getSettings();
  1978. if ($settings['enable_recently_viewed_listings']) {
  1979. $bootstrap = Front::getInstance()->getBootstrap();
  1980. $session = $bootstrap->getResource('session');
  1981. $user = $this->getUser();
  1982. $userId = (isset($user['id'])) ? $user['id'] : null;
  1983. $userToken = strval($session->getCookie(User::USER_TOKEN));
  1984. if (!empty($userToken)) {
  1985. $recentlyViewedListingsService = new Service\RecentlyViewedListings();
  1986. $select = $recentlyViewedListingsService->getTable()->select()
  1987. ->where('user_token = ?', $userToken)
  1988. ->where('listing_id = ?', $this->getData('id'));
  1989. $row = $recentlyViewedListingsService->fetchAll($select)->getRow(0);
  1990. $data = array(
  1991. 'user_token' => $userToken,
  1992. 'listing_id' => $this->getData('id'),
  1993. 'user_id' => $userId,
  1994. );
  1995. if ($row !== null) {
  1996. $data['id'] = $row->getData('id');
  1997. }
  1998. $recentlyViewedListingsService->save($data);
  1999. }
  2000. }
  2001. return $this;
  2002. }
  2003. /**
  2004. *
  2005. * save the updated row in the table
  2006. * add updated_at flag unless already set and if not saving the whole data array
  2007. *
  2008. * 7.7 - whenever we use the save method on a listing, if the listing was active and open
  2009. * before the save operation, we basically remove the counter and ask the cron to count the item again
  2010. * (code duplicated from the listings service save() method)
  2011. *
  2012. * @param array $data partial data to be saved
  2013. * the complete row is saved if this parameter is null
  2014. *
  2015. * @return $this
  2016. */
  2017. public function save(array $data = null)
  2018. {
  2019. if ($data === null) {
  2020. $data = $this->_data;
  2021. }
  2022. if (!array_key_exists('updated_at', $data)) {
  2023. $data['updated_at'] = date('Y-m-d H:i:s', time());
  2024. }
  2025. if (!array_key_exists('last_count_operation', $data)) {
  2026. if (
  2027. $this->isActiveAndOpen() &&
  2028. $this->getData('list_in') != 'store' &&
  2029. $this->getdata('last_count_operation') == self::COUNT_OP_ADD
  2030. ) {
  2031. $this->countCategoriesCounter(self::COUNT_OP_SUBTRACT);
  2032. $data['last_count_operation'] = self::COUNT_OP_NONE;
  2033. }
  2034. }
  2035. parent::save($data);
  2036. return $this;
  2037. }
  2038. /**
  2039. *
  2040. * delete or mark a listing as deleted
  2041. * drafts are also deleted directly, rather than just being marked deleted
  2042. * also subtract the listing from the category counters if it wasn't already subtracted
  2043. *
  2044. * 7.7 - for a pending cart, delete related rows from the sales listings table
  2045. *
  2046. * @param bool $admin if true - admin delete (delete all related files as well)
  2047. *
  2048. * @return bool|integer returns true if marked deleted, or number of affected rows if using admin delete
  2049. */
  2050. public function delete($admin = false)
  2051. {
  2052. $this->addData('deleted', 1)
  2053. ->processCategoryCounter();
  2054. $salesListings = $this->findDependentRowset('\Ppb\Db\Table\SalesListings');
  2055. /** @var \Ppb\Db\Table\Row\SaleListing $saleListing */
  2056. foreach ($salesListings as $saleListing) {
  2057. $sale = $saleListing->findParentRow('\Ppb\Db\Table\Sales');
  2058. if ($sale['pending']) {
  2059. $saleListing->delete();
  2060. }
  2061. }
  2062. if ($admin === true || $this->getData('draft')) {
  2063. $this->findDependentRowset('\Ppb\Db\Table\ListingsMedia')
  2064. ->delete();
  2065. $this->getCustomFieldsData()
  2066. ->delete(self::CUSTOM_FIELDS_TYPE, $this->getData('id'));
  2067. return parent::delete();
  2068. }
  2069. else {
  2070. $user = $this->getUser();
  2071. if (isset($user['id'])) {
  2072. $this->save(array(
  2073. 'deleted' => 1,
  2074. ));
  2075. return true;
  2076. }
  2077. }
  2078. return false;
  2079. }
  2080. /**
  2081. *
  2082. * check if the seller has checked the must pick-up option for the listing
  2083. *
  2084. * @return bool
  2085. */
  2086. public function pickUpOnly()
  2087. {
  2088. $settings = $this->getSettings();
  2089. if ($this->isShipping() && $settings['enable_pickups'] &&
  2090. $this->getData(ShippingModel::FLD_PICKUP_OPTIONS) == ShippingModel::MUST_PICKUP
  2091. ) {
  2092. return true;
  2093. }
  2094. return false;
  2095. }
  2096. /**
  2097. *
  2098. * check if shipping is enabled for the listing (global setting)
  2099. *
  2100. * @return bool
  2101. */
  2102. public function isShipping()
  2103. {
  2104. $settings = $this->getSettings();
  2105. if ($settings['enable_shipping']) {
  2106. return true;
  2107. }
  2108. return false;
  2109. }
  2110. /**
  2111. *
  2112. * check if listing is listed in an adult category
  2113. *
  2114. * @return bool
  2115. */
  2116. public function isAdult()
  2117. {
  2118. $ruleKeys = array('Category', 'AddlCategory');
  2119. foreach ($ruleKeys as $ruleKey) {
  2120. $category = $this->findParentRow('\Ppb\Db\Table\Categories', $ruleKey);
  2121. if ($category instanceof Category) {
  2122. if ($category->getData('adult')) {
  2123. return true;
  2124. }
  2125. }
  2126. }
  2127. return false;
  2128. }
  2129. /**
  2130. *
  2131. * generate a short description for the listing, from the description field
  2132. *
  2133. * @param int $maxChars
  2134. *
  2135. * @return string
  2136. */
  2137. public function shortDescription($maxChars = null)
  2138. {
  2139. /** @var \Cube\View $view */
  2140. $view = Front::getInstance()->getBootstrap()->getResource('view');
  2141. $description = strip_tags($view->renderHtml($this->getData('description')));
  2142. $length = strlen($description);
  2143. $maxChars = ($maxChars === null) ? self::SHORT_DESC_MAX_CHARS : $maxChars;
  2144. return substr($description, 0, $maxChars) . (($length > $maxChars) ? ' ... ' : '');
  2145. }
  2146. /**
  2147. *
  2148. * returns an array used by the url view helper to generate the purchase link for the listing
  2149. * it can be a link to the buy out confirm page, or a link to the add to cart action
  2150. *
  2151. * @return array
  2152. */
  2153. public function purchaseLink()
  2154. {
  2155. if ($this->canAddToCart() === true) {
  2156. return array(
  2157. 'module' => 'listings',
  2158. 'controller' => 'cart',
  2159. 'action' => 'add',
  2160. 'id' => $this->getData('id'),
  2161. );
  2162. }
  2163. return array(
  2164. 'module' => 'listings',
  2165. 'controller' => 'purchase',
  2166. 'action' => 'confirm',
  2167. 'type' => 'buy',
  2168. 'id' => $this->getData('id'),
  2169. );
  2170. }
  2171. /**
  2172. *
  2173. * check if free shipping is offered for the listing
  2174. *
  2175. * this will work if:
  2176. * - free postage is offered and free postage amount <= current bid
  2177. * - item based postage > there is at least one option that has the price set to 0
  2178. * - flat rates > the first item value is set to 0
  2179. *
  2180. * @return bool
  2181. */
  2182. public function isFreeShipping()
  2183. {
  2184. /** @var \Ppb\Db\Table\Row\User $owner */
  2185. $owner = $this->findParentRow('\Ppb\Db\Table\Users');
  2186. if ($owner->getPostageSettings(ShippingModel::SETUP_FREE_POSTAGE) &&
  2187. $owner->getPostageSettings(ShippingModel::SETUP_FREE_POSTAGE_AMOUNT) <= $this->currentBid(true)
  2188. ) {
  2189. return true;
  2190. }
  2191. if ($owner->getPostageSettings(ShippingModel::SETUP_POSTAGE_TYPE) == ShippingModel::POSTAGE_TYPE_ITEM) {
  2192. $postage = $this->getData(ShippingModel::FLD_POSTAGE);
  2193. if (isset($postage['price'])) {
  2194. foreach ($postage['price'] as $key => $value) {
  2195. if ($value == 0) {
  2196. return true;
  2197. }
  2198. }
  2199. }
  2200. }
  2201. else if ($owner->getPostageSettings(ShippingModel::SETUP_POSTAGE_TYPE) == ShippingModel::POSTAGE_TYPE_FLAT) {
  2202. if ($owner->getPostageSettings(ShippingModel::SETUP_POSTAGE_FLAT_FIRST) <= 0) {
  2203. return true;
  2204. }
  2205. }
  2206. return false;
  2207. }
  2208. /**
  2209. *
  2210. * check if the listing is a draft
  2211. *
  2212. * @return bool
  2213. */
  2214. public function isDraft()
  2215. {
  2216. return (bool)$this->getData('draft');
  2217. }
  2218. /**
  2219. *
  2220. * check if the logged in user is blocked from purchasing by the seller or admin
  2221. * and return the block message if true
  2222. *
  2223. * @return string|false
  2224. */
  2225. protected function _isBlockedUserPurchasing()
  2226. {
  2227. $user = $this->getUser();
  2228. $dataToBlock = array(
  2229. 'ip' => $_SERVER['REMOTE_ADDR'],
  2230. );
  2231. if (!empty($user)) {
  2232. $dataToBlock['username'] = $user['username'];
  2233. $dataToBlock['email'] = $user['email'];
  2234. }
  2235. $blockedUsersService = new Service\BlockedUsers();
  2236. $blockedUser = $blockedUsersService->check(
  2237. BlockedUser::ACTION_PURCHASE, $dataToBlock, $this->getData('user_id'));
  2238. if ($blockedUser !== null) {
  2239. $view = Front::getInstance()->getBootstrap()->getResource('view');
  2240. return $view->blockStatus($blockedUser)->blockMessage();
  2241. }
  2242. return false;
  2243. }
  2244. /**
  2245. *
  2246. * call magic method, used for retrieving dependent data
  2247. *
  2248. * @param string $name the name of the method from the \Cube\Db\Table\Row\AbstractRow method
  2249. * @param array $arguments the arguments accepted by the method
  2250. *
  2251. * @return mixed
  2252. */
  2253. public function __call($name, $arguments)
  2254. {
  2255. $listing = $this;
  2256. return call_user_func_array(
  2257. array($listing, $name), $arguments);
  2258. }
  2259. }