public function action_delete() { if (Session::has('id') && Auth::check() && Input::has('file') && Input::has('listing_id')) { $account = Account::find(Session::get('id')); $listing = Listing::find(Input::get('listing_id')); $location = Location::find($listing->location_id); if ($account->id == $location->account_id) { unlink(Input::get('file')); } else { die("Image does not belogn to user"); } } }
public function order($app) { if (!$app->user->isLoggedIn()) { $app->output->json(array('error' => true, 'message' => 'You must be logged in to order items.'), 400); } $headers = getallheaders(); if (empty($headers['X-CSRFToken']) || strcmp($headers['X-CSRFToken'], $app->user->session->csrf_token) != 0) { unset($_SESSION['order']); $app->logger->log('Invalid CSRFToken on Checkout', 'ERROR', array('provided_token' => $headers['X-CSRFToken'], 'real_token' => $app->user->session->csrf_token), 'user'); $app->output->json(array('error' => true, 'message' => 'It looks like a user was trying to make a request on your behalf. Ensure that your system is secure and relogin.'), 400); } $order = null; $success = false; if (isset($_SESSION['order'])) { /* * Edge case: user has reserved an order already */ try { $order = Order::find($_SESSION['order']); if ($order->status == Order::STATUS_CANCELLED) { throw new ActiveRecord\RecordNotFound(); } $success = true; } catch (ActiveRecord\RecordNotFound $e) { unset($_SESSION['order']); $app->output->json(array('error' => true), 400); } } else { /* * Typical scenario: generate an order from cart listings */ $cart = isset($_SESSION['cart']) ? $_SESSION['cart'] : array('listings' => array(), 'bulk' => array()); if (empty($cart['bulk']) && empty($cart['listings'])) { $app->logger->log('Checkout with Empty Cart', 'ERROR', array(), 'user'); $app->output->json(array('error' => true, 'message' => 'Your cart is empty.'), 400); } $user_id = $app->user->id; $cart = $_SESSION['cart']; $listings = array(); // Grab unique listings first if (!empty($cart['listings'])) { $listings = Listing::find('all', array('conditions' => array('id IN (?)', array_map(function ($item) { return $item['listing']; }, $cart['listings'])), 'include' => 'description')); } // Add in bulk purchases foreach ($cart['bulk'] as $description_id => $item) { if ($item['qty'] < 1) { $app->logger->log('Invalid Quantity error on checkout', 'ERROR', array(), 'user'); $app->output->json(array('error' => true, 'message' => 'You have provided an invalid quantity for your item(s).'), 400); } $bulk_listings = Listing::find('all', array('conditions' => array('stage = ? AND description_id = ?', Listing::STAGE_LIST, $description_id), 'order' => 'price ASC', 'limit' => $item['qty'])); if (count($bulk_listings) != $item['qty']) { throw new Order_ReservationError(); } else { $listings = array_merge($listings, $bulk_listings); } } // Reserving Listings for this user $order = null; $success = Listing::transaction(function () use($listings, $user_id, &$order) { $total = 0.0; foreach ($listings as $idx => &$listing) { if ($listing->stage != Listing::STAGE_LIST) { return false; } $listing->setStage('order'); // If this is a parent listing, replace choose new parent for children $children = $listing->children; if (!empty($children)) { $new_parent = end($children); $listing->parent_listing_id = $new_parent->id; $listing->save(); foreach ($children as $idx => $child_listing) { $child_listing->parent_listing_id = $new_parent->id; $child_listing->save(); } $new_parent->parent_listing_id = null; $new_parent->save(); } $total += $listing->price; } $order = Order::create(['user_id' => $user_id, 'total' => $total]); $order->add($listings); }); } // Initiate checkout via payment gateways try { if (!$success) { throw new Order_ReservationError(); } $request = $app->router->flight->request(); $_SESSION['cart'] = array('listings' => array(), 'bulk' => array()); $_SESSION['order'] = $order->id; if ($request->query->checkout == 'coinbase') { // Checkout with Coinbase $order->provider = 'coinbase'; $order->save(); $coinbase = $app->payment->coinbase_button($order, array('success_url' => '/cart/process?checkout=coinbase', 'cancel_url' => '/cart/cancel')); $app->output->json(array('error' => false, 'url' => 'https://coinbase.com/checkouts/' . $coinbase->button->code)); } else { if ($request->query->checkout == 'stripe') { // Checkout with Stripe $order->provider = 'stripe'; $order->save(); $result = $app->payment->stripe_charge($order, $request->data->stripe_token); $app->output->json(array('error' => false, 'url' => $app->config->get('core.url') . '/cart/process?checkout=stripe&ch=' . $result->id)); } else { // Checkout with PayPal $order->provider = 'paypal'; $order->save(); $checkout_url = $app->payment->paypal_SEC($order, '/cart/process', '/cart/cancel'); $app->output->json(array('error' => false, 'url' => $checkout_url)); } } } catch (Order_ReservationError $e) { $app->logger->log('Checkout failed (' . get_class($e) . ')', 'ERROR', array('pathway' => 'order', 'exception' => $e), 'user'); $app->output->json(array('error' => true, 'message' => 'There was an error ordering the items in your cart. You will be redirected back to your cart shortly.'), 500); } catch (Paypal_CheckoutError $e) { $app->logger->log('Checkout failed (' . get_class($e) . ')', 'ERROR', array('pathway' => 'order', 'exception' => $e), 'user'); $app->output->json(array('error' => true, 'message' => 'There was an error setting up your PayPal Express Checkout. You will be redirected back to your cart shortly.'), 500); } catch (Stripe_CardError $e) { $body = $e->getJsonBody(); $err = $body['error']; $app->logger->log('Checkout failed (' . get_class($e) . ')', 'ERROR', array('pathway' => 'order', 'message' => $err['message']), 'user'); $app->output->json(array('error' => true, 'message' => 'There was an error processing your Stripe Checkout: ' . $err['message'] . ' You will be redirected back to your cart shortly.'), 500); } catch (Stripe_Error $e) { $app->logger->log('Checkout failed (' . get_class($e) . ')', 'ERROR', array('pathway' => 'order', 'exception' => $e), 'user'); $app->output->json(array('error' => true, 'message' => 'There was an internal error processing your Stripe Checkout and has been logged. You will be redirected back to your cart shortly.'), 500); } catch (Exception $e) { $app->output->json(array('error' => true, 'message' => 'There was an internal error processing your checkout and has been logged. You will be redirected back to your cart shortly.'), 500); throw $e; } }
public function feature($app, $listing_id = null) { if (!$app->user->isLoggedIn() || !$app->user->isRank('Senior Support Technician')) { $app->logger->log('Unauthorized access to Admin CP', 'ALERT', array(), 'admin'); $app->output->redirect('/'); } try { $listing = Listing::find($listing_id); $listing->toggleFeatured(); } catch (ActiveRecord\RecordNotFound $e) { } $app->output->redirect('/admin/listings'); }
public function cashout($app) { if (!$app->user->isLoggedIn()) { $app->output->redirect('/account/login'); } try { $cashout = null; CashoutRequest::transaction(function () use($app, &$cashout) { $request = $app->router->flight->request(); $provider_identifier = $request->data->provider_identifier ?: ''; $provider = $request->data->provider ?: 'paypal'; $listings = Listing::find('all', array('conditions' => array('user_id = ? AND stage = ?', $app->user->id, Listing::STAGE_COMPLETE))); if (empty($listings)) { throw new Exception('You have submitted an invalid cashout request. There are no listings to cash out.'); } foreach ($listings as $idx => &$listing) { $listing->setStage('archive'); } $total = 0; $total += array_reduce($listings, function ($carry, $listing) { $carry += $listing->price; return $carry; }); $cashout = CashoutRequest::create(['user_id' => $app->user->id, 'provider' => $provider, 'provider_identifier' => $provider_identifier, 'total' => $total, 'status' => CashoutRequest::STATUS_REQUEST]); if ($cashout->is_invalid()) { throw new Exception('You have submitted an invalid cashout request.'); } $cashout->add($listings); $app->user->last_cashout = $cashout->created_at; $app->user->save(); switch ($cashout->provider) { case 'coinbase': $result = $app->payment->coinbase_generate_address(); $cashout->token = $result->token->address; $cashout->provider_identifier = $result->token->token_id; $cashout->save(); break; case 'stripe': $result = $app->payment->stripe_generate_recipient($cashout); $cashout->token = $result->id; $cashout->save(); break; default: $result = $app->payment->paypal_generate_payment($cashout, '/admin/processCashout?cashout_id=' . $app->hashids->encrypt($cashout->id), '/admin/cashouts'); $cashout->token = $result['PayKey']; $cashout->save(); break; } }); } catch (PayPal_CashoutError $e) { $app->logger->log('Cashout request failed (PayPal_CashoutError)', 'ERROR', array('pathway' => 'paypal', 'exception' => $e), 'user'); $app->output->json(array('error' => true, 'type' => 'warning', 'message' => $app->output->markdown->text('There was an error with processing your PayPal cashout request. Ensure that the PayPal e-mail in your [settings](' . $app->config->get('core.url') . '/account/settings) is valid and refresh this page. This issue has been logged.')), 500); } catch (Coinbase_CashoutError $e) { $app->logger->log('Cashout request failed (Coinbase_CashoutError)', 'ERROR', array('pathway' => 'coinbase', 'exception' => $e), 'user'); $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'There was an error with processing your Coinbase cashout request. This issue has been logged.'), 500); } catch (Stripe_Error $e) { $app->logger->log('Cashout request failed (Stripe_Error)', 'ERROR', array('pathway' => 'stripe', 'exception' => $e), 'user'); $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'There was an error with processing your Stripe cashout request. Ensure that the card that you are entering is a debit card. This issue has been logged.'), 500); } catch (Exception $e) { $app->logger->log('Cashout request failed', 'CRITICAL', array('pathway' => 'unknown', 'exception' => $e), 'user'); $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'There was an error with processing your cashout request. This issue has been logged.'), 500); } }
public function action_flaggedlistings() { if (Auth::check()) { if (Session::has('id')) { if (Session::get('admin') == 1) { $flags = Flag::all(); $listings = array(); foreach ($flags as $flag) { if (array_key_exists($flag->listing_id, $listings)) { $listings[$flag->listing_id]->flags += 1; } else { $listing = Listing::find($flag->listing_id); $listing->flags = 1; $listing->location = $listing->location()->first(); $listing->category = Categorie::find($listing->category_id)->title; $listings[$listing->id] = $listing; } } $view = View::make('account.flagged_listings.index')->with('title', 'Flagged Listings')->with('listings', $listings); return $view; } else { Redirect::to('/account/mylistings'); } } } }
public function action_flag($id) { if (Auth::check() && Session::has('id')) { $flags = Flag::where_listing_id($id)->get(); $size = sizeof($flags); $account = Account::find(Session::get('id')); $flag = Flag::where('listing_id', '=', $id)->where('account_id', '=', $account->id)->get(); if (sizeof($flag) != 0) { $alert = '<div class="alert alert-danger" style="margin-top: 45px; margin-bottom: -45px;"> <strong>Error!</strong> You have already flagged this post.</div>'; Session::put('alert', $alert); return Redirect::to('/listing/' . $id); } else { if ($size < 4) { $flag = new Flag(); $flag->account_id = Session::get('id'); $flag->listing_id = $id; $flag->save(); $alert = '<div class="alert alert-success" style="margin-top: 45px; margin-bottom: -45px;"> <strong>Success! </strong>This listing has been flagged.</div>'; Session::put('alert', $alert); $flagCount = Flag::where('listing_id', '=', $id)->count(); if ($flagCount >= 5) { $listing = Listing::find($id); $location = Location::find($listing->location_id); $account = Account::find($location->account_id); $account->blocked = 1; $account->save(); } } else { // Set up view $listing = Listing::find($id); $imageArray = array(); $listing->images = $imageArray; $loc = $listing->location()->first(); $account = Account::find($loc->account_id); $listing->email = $account->email; $listing->date_available = substr($listing->date_available, 0, 10); $listing->date_unavailable = substr($listing->date_unavailable, 0, 10); // Delete listing $this->action_delete($id); // Show view $alert = '<div class="alert alert-success" style="margin-top: 45px; margin-bottom: -45px;"> <strong>Success! </strong>This listing has been flagged.</div>'; Session::put('alert', $alert); } } } else { $alert = '<div class="alert alert-danger" style="margin-top: 45px; margin-bottom: -45px;"> <strong>Error! </strong>You must be logged in to flag a post.</div>'; Session::put('alert', $alert); } $listing = Listing::find($id); $imageArray = array(); $listing->images = $imageArray; $loc = $listing->location()->first(); $account = Account::find($loc->account_id); $listing->email = $account->email; $listing->date_available = substr($listing->date_available, 0, 10); $listing->date_unavailable = substr($listing->date_unavailable, 0, 10); return Redirect::to('/listing/' . $id); }
public function checkin($app) { $request = $app->router->flight->request(); if ($request->method != 'POST') { $this->error($app, 'Invalid entry'); } $this->authorize($app, $request->data->key, $request->query->sig, $request->data); $item_id = $request->data->item_id; if (empty($item_id)) { $this->error($app, 'Invalid item id'); } $listing = Listing::find('first', array('conditions' => array('stage = ? AND item_id = ?', Listing::STAGE_REVIEW, $item_id), 'order' => 'updated_at DESC')); if (empty($listing)) { $this->error($app, 'Listing does not exist for that item.'); } else { $listing->checkout = 0; $listing->checkout_user_id = null; $listing->save(); } $app->output->json(array('error' => false, 'message' => 'Listing ' . $listing->id . ' has been checked back in.')); }
private function preRenderSetup() { $app =& $this->app; $page = ['alerts' => $this->alerts, 'title' => $this->title, 'activeTab' => $this->activeTab, 'breadcrumbs' => $this->breadcrumbs]; if ($app->user->isSiteDeveloper()) { $page['profiler'] = $app->profiler->fetch(); } $this->twig->addGlobal('page', $page); $this->twig->addFunction(new Twig_SimpleFunction('config', function ($key) use(&$app) { return $app->config->get($key); })); $this->twig->addFunction(new Twig_SimpleFunction('relative_time', function ($time = false, $limit = 86400, $format = 'g:i A M jS') { if (is_object($time)) { $time = $time->format('db'); } if (is_string($time)) { $time = strtotime($time); } $now = time(); $relative = ''; if ($time === $now) { $relative = 'now'; } elseif ($time > $now) { //$relative = 'in the future'; $diff = $time - $now; if ($diff >= $limit) { $relative = date($format, $time); } elseif ($diff < 60) { $relative = 'less than one minute'; } elseif (($minutes = ceil($diff / 60)) < 60) { $relative = $minutes . ' minute' . ((int) $minutes === 1 ? '' : 's'); } else { $hours = ceil($diff / 3600); $relative = 'about ' . $hours . ' hour' . ((int) $hours === 1 ? '' : 's'); } } else { $diff = $now - $time; if ($diff >= $limit) { $relative = date($format, $time); } elseif ($diff < 60) { $relative = 'less than one minute ago'; } elseif (($minutes = ceil($diff / 60)) < 60) { $relative = $minutes . ' minute' . ((int) $minutes === 1 ? '' : 's') . ' ago'; } else { $hours = ceil($diff / 3600); $relative = 'about ' . $hours . ' hour' . ((int) $hours === 1 ? '' : 's') . ' ago'; } } return $relative; })); $this->twig->addFunction(new Twig_SimpleFunction('markdown', function ($data) { return $this->markdown->text($data); })); $this->twig->addFunction(new Twig_SimpleFunction('hashid', function ($id) use(&$app) { return $app->hashids->encrypt($id); })); $this->twig->addFunction(new Twig_SimpleFunction('truncate', function ($text, $limit = 40) { if (strlen($text) < $limit) { return $text; } $text = $text . " "; $text = substr($text, 0, $limit); $text = substr($text, 0, strrpos($text, ' ')); $text = $text . "..."; return $text; })); $this->twig->addFunction(new Twig_SimpleFunction('money_format', function ($amount) { if (!function_exists('money_format')) { sprintf('$%.2f', $amount); } // require_once('./libs/utils/money_format.php'); return money_format('$%.2n', $amount); })); $this->twig->addFunction(new Twig_SimpleFunction('imgur_thumb', function ($link, $type = 'm') { return preg_replace('/(\\.gif|\\.jpg|\\.png)/', $type . '$1', $link); })); $this->twig->addGlobal('user', $app->user); $this->twig->addGlobal('total_users', count(User::find('all'))); $this->twig->addGlobal('total_stock', count(Listing::find('all', array('conditions' => array('stage = ?', Listing::STAGE_LIST))))); $this->twig->addGlobal('total_ordered', count(Listing::find('all', array('conditions' => array('stage IN (?)', array(Listing::STAGE_COMPLETE, Listing::STAGE_ARCHIVE)))))); if ($app->user->isLoggedIn()) { $notification_count = count(Notification::find('all', ['conditions' => ['receiver_id = ? AND seen = ? AND deleted = ?', $app->user->id, 0, 0]])); $this->twig->addGlobal('notification_count', $notification_count); } if (!empty($_SESSION['cart'])) { $cart_count = array_reduce(array_merge($_SESSION['cart']['listings'], $_SESSION['cart']['bulk']), function ($carry, $item) { $carry += $item['qty']; return $carry; }) ?: 0; } else { $cart_count = 0; } $this->twig->addGlobal('cart_count', $cart_count); }
public function get_children() { return Listing::find('all', array('conditions' => array('parent_listing_id = ? AND stage NOT IN (?)', $this->id, array(self::STAGE_ORDER, self::STAGE_COMPLETE, self::STAGE_ARCHIVE)))); }
public function get_recent_offenses() { $listings_cancelled = Listing::find('all', array('conditions' => array('user_id = ? AND stage IN (?)', $this->id, array(Listing::STAGE_DELETE, Listing::STAGE_CANCEL)), 'order' => 'updated_at DESC')); $orders_cancelled = Order::find('all', array('conditions' => array('user_id = ? AND status = ?', $this->id, Order::STATUS_CANCELLED), 'order' => 'updated_at DESC')); // Doing time filter using PHP because all time zone funkiness is handled by server code ;( $now = time(); $oldest = $now - 2592000; // 1 month in seconds $listings_cancelled = array_filter($listings_cancelled, function ($l) use($oldest) { return strtotime($l->updated_at->format('db')) > $oldest; }); $orders_cancelled = array_filter($orders_cancelled, function ($o) use($oldest) { return strtotime($o->updated_at->format('db')) > $oldest; }); if (count($listings_cancelled) + count($orders_cancelled) < self::FLAG_OFFENSE_THRESHOLD) { return array('listings_cancelled' => 0, 'orders_cancelled' => 0, 'total' => 0); } return array('listings_cancelled' => $listings_cancelled, 'orders_cancelled' => $orders_cancelled, 'total' => count($listings_cancelled) + count($orders_cancelled)); }
public function listings($app) { $request = $app->router->flight->request(); $filter = $request->query->getData(); $name = ''; $offset = 0; $tags = array(); // Prepare filtering conditions for listings if (!empty($filter)) { if (isset($filter['name'])) { $name = $filter['name']; unset($filter['name']); } if (isset($filter['offset'])) { $offset = $filter['offset']; unset($filter['offset']); } $tags = array_values($filter); // grab internal_name's $tags = array_filter($tags, function ($tag) { return strcmp($tag, '') != 0; }); } $listings = Listing::find('all', array('conditions' => array('stage = ? AND bot_id IS NOT NULL', Listing::STAGE_LIST), 'include' => 'description')); // Stack listings into groups by description $descriptions = array(); foreach ($listings as $idx => $listing) { // Filter out listings based on search params $matches = $listing->description->checkTags($tags); // Score listings based on similarity to query name $matches += $listing->description->matchName($name); if ($matches > 0 || empty($filter) && $name == '') { $listing->assign_attribute('matches', $matches); } else { continue; } // Stack listings based on flag, else put into separate unique slot if ($listing->description->stackable == 1) { if (empty($descriptions[$listing->description->id])) { $descriptions[$listing->description->id] = array($listing); } else { array_push($descriptions[$listing->description->id], $listing); } } else { array_push($descriptions, array($listing)); } } // Sort all descriptions // First sort listings in each description by price ASC foreach ($descriptions as $idx => $listings) { usort($listings, function ($a, $b) { $diff = $b->matches - $a->matches; if ($diff == 0) { return $a->price - $b->price; } return $diff; }); } // Then sort descriptions by score DESC, lowest price DESC usort($descriptions, function ($a, $b) { $diff = $b[0]->matches - $a[0]->matches; if ($diff == 0) { return $b[0]->price - $a[0]->price; } return $diff; }); $total_descriptions = count($descriptions); $descriptions = array_slice($descriptions, $offset, self::MAX_LISTINGS_SHOWN); $descriptions_json = array(); foreach ($descriptions as $idx => &$d) { $description_json = array('id' => $app->hashids->encrypt($d[0]->id), 'name' => $d[0]->description->name, 'name_st' => $d[0]->description->name, 'price' => money_format('$%.2n', $d[0]->price), 'icon_url' => $d[0]->description->icon_url_large ?: $d[0]->description->icon_url, 'name_color' => $d[0]->description->name_color == 'D2D2D2' ? '000000' : $d[0]->description->name_color, 'qty' => count($d), 'offset' => $idx, 'score' => $d[0]->matches); if ($d[0]->description->stackable == 1) { $description_json['stackable'] = 1; } if ($d[0]->description->is_stattrak) { $description_json['is_stattrak'] = 1; } if ($d[0]->description->exterior) { $description_json['exterior'] = $d[0]->description->exterior; } if ($idx % 4 == 1) { $description_json['text_align'] = 'text-left'; } elseif ($idx % 4 == 0) { $description_json['text_align'] = 'text-right'; } else { $description_json['text_align'] = 'text-center'; } array_push($descriptions_json, $description_json); } $app->output->json(array('descriptions' => $descriptions_json, 'total' => $total_descriptions)); }