PageRenderTime 31ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/ww.plugins/products/api.php

http://kv-webme.googlecode.com/
PHP | 650 lines | 427 code | 43 blank | 180 comment | 44 complexity | 7804c5ee4085ade69c33265a7911b84c MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, BSD-3-Clause, BSD-2-Clause, Apache-2.0, MIT, LGPL-2.1
  1. <?php
  2. /**
  3. * API for Products plugin
  4. *
  5. * PHP version 5.2
  6. *
  7. * @category None
  8. * @package None
  9. * @author Kae Verens <kae@kvsites.ie>
  10. * @license GPL 2.0
  11. * @link http://kvsites.ie/
  12. */
  13. // { Products_arrayToCSV
  14. /**
  15. * convert an array to a CSV row
  16. *
  17. * @param array $row row data
  18. * @param string $delimiter what to separate the fields by
  19. * @param string $enclosure how should strings be enclosed
  20. * @param string $eol what end-of-line character to use
  21. *
  22. * @return string the CSV row
  23. */
  24. function Products_arrayToCSV(
  25. $row, $delimiter = ',', $enclosure = '"', $eol = "\n"
  26. ) {
  27. static $fp = false;
  28. if ($fp === false) {
  29. $fp = fopen('php://temp', 'r+');
  30. }
  31. else {
  32. rewind($fp);
  33. }
  34. if (fputcsv($fp, $row, $delimiter, $enclosure) === false) {
  35. return false;
  36. }
  37. rewind($fp);
  38. $csv = fgets($fp);
  39. if ($eol != PHP_EOL) {
  40. $csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
  41. }
  42. return $csv;
  43. }
  44. // }
  45. // { Products_categoriesOptionsGet
  46. /**
  47. * show a list of categories
  48. *
  49. * @return null
  50. */
  51. function Products_categoriesOptionsGet() {
  52. $selected=$_REQUEST['selected'];
  53. $rs=dbAll('select id,name from products_categories where enabled order by name');
  54. $arr=array();
  55. foreach ($rs as $r) {
  56. $arr[$r['id']]=$r['name'];
  57. }
  58. return $arr;
  59. }
  60. // }
  61. // { Products_categoriesGetFull
  62. /**
  63. * return a list of categories and ids, named in full
  64. *
  65. * @return array
  66. */
  67. function Products_categoriesGetFull() {
  68. $pid=(int)$_REQUEST['pid'];
  69. /**
  70. * getFull
  71. *
  72. * @param int $pid parent ID
  73. * @param string $prefix prefix
  74. *
  75. * @return array
  76. */
  77. function getFull($pid, $prefix='') {
  78. $rs=dbAll('select name,id from products_categories where parent_id='.$pid);
  79. $cats=array();
  80. foreach ($rs as $r) {
  81. $cats[$prefix.$r['name']]=$r['id'];
  82. $cats=array_merge($cats, getFull($r['id'], $prefix.$r['name'].' - '));
  83. }
  84. return $cats;
  85. }
  86. return getFull($pid);
  87. }
  88. // }
  89. // { Products_categoryUnwatch
  90. /**
  91. * unwatch this category
  92. *
  93. * @return null
  94. */
  95. function Products_categoryUnwatch() {
  96. $cid=(int)$_REQUEST['cid'];
  97. $uid=(int)$_SESSION['userdata']['id'];
  98. if (!$uid || !$cid) {
  99. return array('error'=>'no category selected or not logged in');
  100. }
  101. dbQuery(
  102. 'delete from products_watchlists where user_id='.$uid
  103. .' and category_id='.$cid
  104. );
  105. return array('ok'=>1);
  106. }
  107. // }
  108. // { Products_categoryWatch
  109. /**
  110. * watch this category
  111. *
  112. * @return null
  113. */
  114. function Products_categoryWatch() {
  115. $cid=(int)$_REQUEST['cid'];
  116. $uid=(int)$_SESSION['userdata']['id'];
  117. if (!$uid || !$cid) {
  118. return array('error'=>'no category selected or not logged in');
  119. }
  120. Products_categoryUnwatch();
  121. dbQuery(
  122. 'insert into products_watchlists set user_id='.$uid.', category_id='.$cid
  123. );
  124. return array('ok'=>1);
  125. }
  126. // }
  127. // { Products_categoryWatches
  128. /**
  129. * get list of watches
  130. *
  131. * DEPRECATED: Kae to find all uses of this and replace with
  132. * Products_watchlistsGet then remove this function
  133. *
  134. * @return null
  135. */
  136. function Products_categoryWatches() {
  137. $uid=(int)$_SESSION['userdata']['id'];
  138. if (!$uid) {
  139. return array('error'=>'not logged in');
  140. }
  141. $rs=dbAll(
  142. 'select category_id from products_watchlists where user_id='.$uid
  143. );
  144. $arr=array();
  145. foreach ($rs as $r) {
  146. $arr[]=$r['category_id'];
  147. }
  148. return $arr;
  149. }
  150. // }
  151. // { Products_getImgs
  152. /**
  153. * get a list of images
  154. *
  155. * @return list of images
  156. */
  157. function Products_getImgs() {
  158. $pid=(int)$_REQUEST['id'];
  159. $product=Product::getInstance($pid);
  160. $dir=USERBASE.'/f'.$product->vals['images_directory'];
  161. $imgs=array();
  162. if (file_exists($dir)) {
  163. $dir=new DirectoryIterator($dir);
  164. foreach ($dir as $file) {
  165. if ($file->isDot()) {
  166. continue;
  167. }
  168. $imgs[]='/f'.$product->vals['images_directory'].'/'.$file->getFilename();
  169. }
  170. }
  171. return $imgs;
  172. }
  173. // }
  174. // { Products_getProductMainDetails
  175. /**
  176. * utility function to return an array of common product details
  177. *
  178. * @param object $p product
  179. *
  180. * @return array
  181. */
  182. function Products_getProductMainDetails($p) {
  183. $parr=array(
  184. 'id'=>$p->id,
  185. 'name'=>__FromJson($p->name)
  186. );
  187. if ($p->vals['online-store']) {
  188. $o=$p->vals['online-store'];
  189. $parr['_price']=$p->getPriceBase();
  190. $sale_price=$p->getPriceSale();
  191. if ($sale_price) {
  192. $parr['_sale_price']=$sale_price;
  193. }
  194. if ($o['_bulk_price']) {
  195. $parr['_bulk_price']=$o['_bulk_price'];
  196. }
  197. if ($o['_bulk_amount']) {
  198. $parr['_bulk_amount']=$o['_bulk_amount'];
  199. }
  200. if ($o['_sold_amt']) {
  201. $parr['_sold_amt']=$o['_sold_amt'];
  202. }
  203. if ($o['_stock_amt']) {
  204. $parr['_stock_amt']=$o['_stock_amt'];
  205. }
  206. }
  207. $parr['link']=$p->getRelativeUrl();
  208. return $parr;
  209. }
  210. // }
  211. // { Products_getProductOwnersByCoords
  212. /**
  213. * get a list of users with active products using map coordinates
  214. *
  215. * @return array of product IDs
  216. */
  217. function Products_getProductOwnersByCoords() {
  218. $coords=$_REQUEST['coords'];
  219. // { sanitise coords
  220. $x1=(float)$coords[0];
  221. $x2=(float)$coords[2];
  222. $y1=(float)$coords[1];
  223. $y2=(float)$coords[3];
  224. if ($x2<$x1) {
  225. $t=$x1;
  226. $x1=$x2;
  227. $x2=$t;
  228. }
  229. if ($y2<$y1) {
  230. $t=$y1;
  231. $y1=$y2;
  232. $y2=$t;
  233. }
  234. // }
  235. // { get list of relevant users
  236. $users=dbAll(
  237. "select id,location_lat, location_lng from user_accounts where
  238. location_lat>$x1 and location_lat<$x2
  239. and location_lng>$y1 and location_lng<$y2 and active limit 1000",
  240. 'id'
  241. );
  242. if (!count($users)) {
  243. return array();
  244. }
  245. $users2=dbAll(
  246. 'select distinct user_id from products where enabled and user_id in ('
  247. .join(',', array_keys($users)).')'
  248. );
  249. foreach ($users2 as $k=>$v) {
  250. $users2[$k]=$users[$v['user_id']];
  251. }
  252. return $users2;
  253. // }
  254. }
  255. // }
  256. // { Products_getProductsByUser
  257. /**
  258. * get a list of products (id, name, relativeUrl) owned by a user
  259. *
  260. * @return array of products
  261. */
  262. function Products_getProductsByUser() {
  263. $user_id=(int)$_REQUEST['user_id'];
  264. $products=array();
  265. $rs=dbAll('select id from products where user_id='.$user_id.' and enabled');
  266. foreach ($rs as $r) {
  267. $p=Product::getInstance($r['id']);
  268. $products[]=array(
  269. 'id'=>$p->id,
  270. 'name'=>__FromJson($p->name),
  271. 'url'=>$p->getRelativeUrl()
  272. );
  273. }
  274. return $products;
  275. }
  276. // }
  277. // { Products_getProduct
  278. /**
  279. * return a single product's main details
  280. *
  281. * @return array
  282. */
  283. function Products_getProduct() {
  284. $p=Product::getInstance((int)$_REQUEST['id']);
  285. if (!$p || !$p->id) {
  286. return false;
  287. }
  288. $mainDetails=Products_getProductMainDetails($p);
  289. if ($p->vals['stockcontrol_details']) {
  290. $mainDetails['stockcontrol']=json_decode(
  291. $p->vals['stockcontrol_details'], true
  292. );
  293. }
  294. else {
  295. $mainDetails['stockcontrol']=false;
  296. }
  297. return $mainDetails;
  298. }
  299. // }
  300. // { Products_getRelatedProducts
  301. /**
  302. * return a list of products by relation
  303. *
  304. * @return array
  305. */
  306. function Products_getRelatedProducts() {
  307. $pid=(int)$_REQUEST['id'];
  308. $rs=dbAll(
  309. 'select * from products_relations where from_id='.$pid.' or to_id='.$pid
  310. );
  311. $related=array();
  312. $rtypes=array();
  313. foreach ($rs as $r) {
  314. $rid=(int)$r['relation_id'];
  315. if (!isset($rtypes[$rid])) {
  316. $rtypes[$rid]=dbOne(
  317. 'select one_way from products_relation_types where id='.$rid, 'one_way'
  318. );
  319. }
  320. if ($rtypes[$rid]!=1) {
  321. $related[]=$r['from_id']==$pid?$r['to_id']:$r['from_id'];
  322. }
  323. elseif ($r['from_id']==$pid) {
  324. $related[]=$r['to_id'];
  325. }
  326. }
  327. $related=array_unique($related);
  328. $products=array();
  329. foreach ($related as $pid) {
  330. $p=Product::getInstance($pid);
  331. if (!$p || !$p->id) {
  332. continue;
  333. }
  334. $products[]=Products_getProductMainDetails($p);
  335. }
  336. return $products;
  337. }
  338. // }
  339. // { Products_reviewDelete
  340. /**
  341. * remove a review
  342. *
  343. * @return null
  344. */
  345. function Products_reviewDelete() {
  346. $id = (int)$_REQUEST['id'];
  347. $productid= (int)$_REQUEST['productid'];
  348. $userid = (int)dbOne(
  349. 'select user_id from products_reviews where id='.$id,
  350. 'user_id'
  351. );
  352. $user= $_SESSION['userdata']['id'];
  353. if (!Core_isAdmin() || $user!=$userid) {
  354. die('You do not have permission to delete this review');
  355. }
  356. dbQuery('delete from products_reviews where id='.$id);
  357. if (dbOne('select id from products_reviews where id='.$id, 'id')) {
  358. return array('status'=>0);
  359. }
  360. $numReviews= (int) dbOne(
  361. 'select count(id)
  362. from products_reviews
  363. where product_id='.$productid,
  364. 'count(id)'
  365. );
  366. $average = (int) dbOne(
  367. 'select avg(rating)
  368. from products_reviews
  369. where product_id='.$productid
  370. .' group by product_id',
  371. 'avg(rating)'
  372. );
  373. return array(
  374. 'status'=>1,
  375. 'id'=>$id,
  376. 'user'=>$user,
  377. 'userid'=>$userid,
  378. 'num'=>$numReviews,
  379. 'avg'=>$average,
  380. 'product'=>$productid
  381. );
  382. }
  383. // }
  384. // { Products_reviewUpdate
  385. /**
  386. * Updates a review, calculates the new total and average
  387. *
  388. * @return array the updated review
  389. */
  390. function Products_reviewUpdate() {
  391. $id= (int)$_REQUEST['id'];
  392. $loggedInUser= $_SESSION['userdata']['id'];
  393. $userWhoLeftReview
  394. = dbOne(
  395. 'select user_id from products_reviews where id='.$id,
  396. 'user_id'
  397. );
  398. if (!(Core_isAdmin()||$loggedInUser==$userWhoLeftReview)) {
  399. die('You do not have sufficent privileges to edit this review');
  400. }
  401. $timeExpired
  402. = dbOne(
  403. 'select now()>
  404. date_add("'.$_REQUEST['cdate'].'", interval 15 minute) as can_edit',
  405. 'can_edit'
  406. );
  407. if ($timeExpired) {
  408. return array('status'=>0, 'message'=>'time has expired');
  409. }
  410. $body = addslashes($_REQUEST['text']);
  411. $rating = (int)$_REQUEST['rating'];
  412. if (($rating<1||$rating>5)||$id<=0) {
  413. return array('status'=>0, 'message'=>'Invalid Rating');
  414. }
  415. dbQuery(
  416. 'update products_reviews set body="'.$body.'", rating='.$rating
  417. .' where id='.$id
  418. );
  419. $productid=dbOne(
  420. 'select product_id from products_reviews where id='.$id,
  421. 'product_id'
  422. );
  423. $average=dbOne(
  424. 'select avg(rating) from products_reviews where product_id='
  425. .$productid.' group by product_id',
  426. 'avg(rating)'
  427. );
  428. $total=dbOne(
  429. 'select count(id) from products_reviews where product_id='.$productid,
  430. 'count(id)'
  431. );
  432. $review=dbRow(
  433. 'select rating,body,cdate from products_reviews where id = '.$id
  434. );
  435. $rating = $review['rating'];
  436. $body = $review['body'];
  437. $date = $review['cdate'];
  438. $name=dbOne(
  439. 'select name from user_accounts where id='.$userWhoLeftReview,
  440. 'name'
  441. );
  442. return array(
  443. 'status'=>1,
  444. 'id'=>$id,
  445. 'product'=>$productid,
  446. 'user_id'=>$userWhoLeftReview,
  447. 'user'=>$name,
  448. 'date'=>$date,
  449. 'rating'=>$rating,
  450. 'body'=>$body,
  451. 'avg'=>$average,
  452. 'total'=>$total
  453. );
  454. }
  455. // }
  456. // { Products_showDefaultImg
  457. /**
  458. * show the default image of a product
  459. *
  460. * @return null
  461. */
  462. function Products_showDefaultImg() {
  463. $id=(int)$_REQUEST['id'];
  464. $product=Product::getInstance($id);
  465. $w=(int)@$_REQUEST['w'];
  466. $h=(int)@$_REQUEST['h'];
  467. if ($product) {
  468. $iid=$product->getDefaultImage();
  469. if ($iid) {
  470. header('Location: /a/f=getImg/w='.$w.'/h='.$h.'/'.$iid);
  471. Core_quit();
  472. }
  473. }
  474. header('Location: /i/blank.gif');
  475. }
  476. // }
  477. // { Products_showQrCode
  478. /**
  479. * show an image of a QR code leading to a product
  480. *
  481. * @return null
  482. */
  483. function Products_showQrCode() {
  484. $pid=(int)$_REQUEST['pid'];
  485. $product=Product::getInstance($pid);
  486. if (!$product) {
  487. redirect('/i/blank.gif');
  488. }
  489. $fname=USERBASE.'/ww.cache/products/qr'.$pid;
  490. if (!file_exists($fname)) {
  491. require_once SCRIPTBASE.'/ww.incs/phpqrcode.php';
  492. @mkdir(USERBASE.'/ww.cache/products');
  493. QRcode::png(
  494. 'http://'.$_SERVER['HTTP_HOST'].$product->getRelativeUrl(),
  495. $fname
  496. );
  497. }
  498. header('Content-type: image/png');
  499. header('Cache-Control: max-age=2592000, public');
  500. header('Expires-Active: On');
  501. header('Expires: Fri, 1 Jan 2500 01:01:01 GMT');
  502. header('Pragma:');
  503. header('Content-Length: ' . filesize($fname));
  504. readfile($fname);
  505. Core_quit();
  506. }
  507. // }
  508. // { Products_typeGet
  509. /**
  510. * get details about a specific product type
  511. *
  512. * @return array the product type details
  513. */
  514. function Products_typeGet() {
  515. $id=(int)@$_REQUEST['id'];
  516. $r=Core_cacheLoad('products', 'productTypeDetails_'.$id, -1);
  517. if ($r===-1) {
  518. $r=dbRow("select * from products_types where id=$id");
  519. $r['default_category_name']=dbOne(
  520. 'select name from products_categories where id='.$r['default_category'],
  521. 'name'
  522. );
  523. $r['data_fields']=json_decode($r['data_fields']);
  524. Core_cacheSave('products', 'productTypeDetails_'.$id, $r);
  525. }
  526. return $r;
  527. }
  528. // }
  529. // { Products_typesGet
  530. /**
  531. * get a list of product types
  532. *
  533. * @return array list of product types, in DataTables format
  534. */
  535. function Products_typesGet() {
  536. $rs=dbAll('select name,id from products_types order by name');
  537. $count=count($rs);
  538. $result=array(
  539. 'sEcho'=>intval(@$_REQUEST['sEcho']),
  540. 'iTotalRecords'=>$count,
  541. 'iTotalDisplayRecords'=>$count,
  542. 'aaData'=>array()
  543. );
  544. foreach ($rs as $r) {
  545. $result['aaData'][]=array(
  546. $r['name'],
  547. $r['id'],
  548. 0
  549. );
  550. }
  551. return $result;
  552. }
  553. // }
  554. // { Products_typesTemplatesGet
  555. /**
  556. * get a list of pre-created product type templates
  557. *
  558. * @return array list of types
  559. */
  560. function Products_typesTemplatesGet() {
  561. $dir=new DirectoryIterator(dirname(__FILE__).'/templates');
  562. $templates=array();
  563. foreach ($dir as $file) {
  564. if ($file->isDot() || !preg_match('/\.json$/', $file->getFilename())) {
  565. continue;
  566. }
  567. $templates[]=str_replace('.json', '', $file->getFilename());
  568. }
  569. return $templates;
  570. }
  571. // }
  572. // { Products_watchlistsGet
  573. /**
  574. * retrieve a user's watchlists
  575. *
  576. * @return array
  577. */
  578. function Products_watchlistsGet() {
  579. if (!isset($_SESSION['userdata']['id'])) {
  580. return array('error'=>__('not logged in'));
  581. }
  582. $uid=(int)$_SESSION['userdata']['id'];
  583. return dbAll('select * from products_watchlists where user_id='.$uid);
  584. }
  585. // }
  586. // { Products_watchlistsSave
  587. /**
  588. * update a user's watchlists
  589. *
  590. * @return array
  591. */
  592. function Products_watchlistsSave() {
  593. if (!isset($_SESSION['userdata']['id'])) {
  594. return array('error'=>__('not logged in'));
  595. }
  596. $uid=(int)$_SESSION['userdata']['id'];
  597. dbQuery('delete from products_watchlists where user_id='.$uid);
  598. foreach ($_REQUEST['watchlists'] as $w) {
  599. dbQuery(
  600. 'insert into products_watchlists set category_id='
  601. .((int)$w['category_id']).', location_id='.((int)$w['location_id'])
  602. .', user_id='.$uid
  603. );
  604. }
  605. return dbAll('select * from products_watchlists where user_id='.$uid);
  606. }
  607. // }