public function process() { try { $item = $this->getItem(); if (empty($item->id)) { throw new \Exception('Invalid ID'); } // if the task is already locked by another process, fail if (!empty($item->locked_by)) { throw new \Exception('Task locked by another process'); } // lock the task to this process $mongo_id = (string) new \MongoId(); $item->locked_by = $mongo_id; $item->locked_at = time(); $item->store(); // run the task $this->app->call($item->task, $item->parameters); $task = $item->complete(); \Dsc\System::addMessage('Task completed', 'success'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); } $this->app->reroute($this->list_route); }
/** * Parse an existing crontab * * @param Crontab $crontab * * @return CrontabFileHandler */ public function parseExistingCrontab(Crontab $crontab) { $result = exec($this->crontabCommand($crontab) . ' -l', $output, $retval); if (!empty($output)) { //\Dsc\System::addMessage(\Dsc\Debug::dump($output)); foreach ($output as $line) { if (trim($line) == '') { continue; } try { $job = \Dsc\Cron\Job::parse($line); $crontab->addJob($job); } catch (\Exception $e) { \Dsc\System::addMessage('Encountered error (' . $e->getMessage() . ') when parsing cron job: ' . $line, 'error'); } } } /* // parsing cron file $process = new Process($this->crontabCommand($crontab).' -l'); $process->run(); foreach ($this->parseString($process->getOutput()) as $job) { $crontab->addJob($job); } $this->error = $process->getErrorOutput(); */ return $this; }
public function update() { $id = $this->inputfilter->clean($this->app->get('PARAMS.id'), 'cmd'); try { $item = (new \Shop\Models\PaymentMethods())->setState('filter.identifier', $id)->getItem(); if (empty($item->id)) { throw new \Exception('Payment Method not found'); } $enabled = $this->app->get('POST.enabled'); if (strlen($enabled)) { $item->enabled = false; if (!empty($enabled)) { $item->enabled = true; } } if ($settings_array = (array) $this->inputfilter->clean($this->app->get('POST.settings'), 'array')) { $item->settings = $settings_array; } $item->save(); \Dsc\System::addMessage('Settings updated', 'success'); $this->app->reroute('/admin/shop/payment-method/edit/' . $id); } catch (\Exception $e) { \Dsc\System::addMessage("Invalid Payment Method", 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); $this->app->reroute('/admin/shop/payment-methods'); return; } }
protected function displayEdit() { $item = $this->getItem(); if (empty($item) || $item->product_type != 'giftcards') { \Dsc\System::addMessage('Item is not a giftcard', 'error'); $this->app->reroute('/admin/shop/giftcards'); } $f3 = \Base::instance(); $flash = \Dsc\Flash::instance(); $variants = array(); if ($flashed_variants = $flash->old('variants')) { foreach ($flashed_variants as $variant) { $key = implode("-", (array) $variant['attributes']); if (empty($key)) { $key = $variant['id']; } $variants[$key] = $variant; } } $old = array_merge($flash->get('old'), array('variants' => $variants)); $flash->store($old); $model = new \Shop\Models\Categories(); $categories = $model->getList(); \Base::instance()->set('categories', $categories); \Base::instance()->set('selected', 'null'); $all_tags = $this->getModel()->getTags(); \Base::instance()->set('all_tags', $all_tags); $this->app->set('meta.title', 'Edit Gift Card | Shop'); $view = \Dsc\System::instance()->get('theme'); $view->event = $view->trigger('onDisplayShopProductsEdit', array('item' => $this->getItem(), 'tabs' => array(), 'content' => array())); echo $view->render('Shop\\Admin\\Views::giftcards/edit.php'); }
public function beforeRoute() { parent::beforeRoute(); $this->requireIdentity(); //TODO remove this hack, after ACL is finished $user = $this->auth->getIdentity(); //TODO maybe the Role gets stored in the session to avoid one more DB query every load, or maybe none of this makes it to the future if (!empty($user->id) && $this->app->get('safemode.enabled') && $user->id == $this->app->get('safemode.id')) { return; } $role = $user->getRole(); if (empty($role->slug)) { $this->auth->logout(); \Dsc\System::addMessage('Not Authorized'); $this->app->reroute('/admin/login'); } if ($role->slug == 'root') { //root always has access no farther checks needed } elseif (empty($role->adminaccess)) { //if this role is not admin and not given admin permissions $this->auth->logout(); \Dsc\System::addMessage('Not Authorized'); $this->app->reroute('/admin/login'); } }
public function create() { // load the product // is it valid? // is the user logged in? // can the user review this product? // try/catch the save try { $slug = $this->inputfilter->clean($this->app->get('PARAMS.slug'), 'cmd'); $item = $this->model('products')->setState('filter.slug', $slug)->getItem(); if (empty($item->id)) { throw new \Exception(); } } catch (\Exception $e) { if ($this->app->get('AJAX')) { return $this->outputJson($this->getJsonResponse(array('result' => false, 'error' => true, 'message' => 'Invalid Product'))); } else { $this->app->error('404', 'Invalid Product'); return; } } $redirect = '/shop/product/' . $item->slug; if ($custom_redirect = \Dsc\System::instance()->get('session')->get('shop.product_review.redirect')) { $redirect = $custom_redirect; } try { $user = $this->getIdentity(); if (empty($user->id)) { throw new \Exception('Must be logged in to post a review'); } $canReview = \Shop\Models\ProductReviews::canUserReview($user, $item); if ($canReview !== true) { throw new \Exception($canReview); } $post = $this->app->get('POST'); $post['description'] = !empty($post['description']) ? nl2br($post['description']) : null; $review = (new \Shop\Models\ProductReviews($post))->set('product_id', $item->id)->set('user_id', $user->id)->set('user_name', $user->first_name)->set('publication.status', 'draft')->save(); // Add images, using a model method $review->addImages($this->app->get('FILES')); $successMessage = 'Thanks for the review! It will be published following review by our moderators.'; if ($this->app->get('AJAX')) { return $this->outputJson($this->getJsonResponse(array('result' => true, 'message' => $successMessage))); } else { \Dsc\System::addMessage($successMessage, 'success'); $this->app->reroute($redirect); return; } } catch (\Exception $e) { if ($this->app->get('AJAX')) { return $this->outputJson($this->getJsonResponse(array('result' => false, 'error' => true, 'message' => $e->getMessage()))); } else { \Dsc\System::addMessage($e->getMessage(), 'error'); $this->app->reroute($redirect); return; } } }
public function invalidate() { try { $script = $this->input->get('script', '', 'raw'); opcache_invalidate($script, true); \Dsc\System::addMessage('Invalidated ' . $script, 'success'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); } $this->app->reroute('/admin/cache/opcache'); }
/** * Primary entry-point for the report. * Supports GET & POST */ public function index() { $model = (new \Shop\Models\Coupons())->emptyState()->populateState(); try { $paginated = $model->paginate(); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); $this->app->reroute('/admin/shop/reports/' . $this->slug()); return; } $this->app->set('state', $model->getState()); $this->app->set('paginated', $paginated); echo $this->theme->render('Shop/Reports/OrdersByCouponCode/Views::index.php'); }
public function emailSubmit() { // Validate the form inputs // for each email address, send the email // track that this user sent these invitations // redirect back to /invite-friends/email $recip_input = $this->app->split($this->input->get('recipients', null, 'string')); $recipients = array(); foreach ($recip_input as $recip) { $recip = trim(strtolower($recip)); if (!empty($recip) && \Mailer\Factory::instance()->sender()->isEmailAddress($recip)) { $recipients[] = $recip; } } $data = array('sender_name' => $this->input->get('sender_name', null, 'string'), 'sender_email' => trim(strtolower($this->input->get('sender_email', null, 'string'))), 'recipients' => $recipients, 'message' => $this->input->get('message', null, 'string')); try { if (empty($data['sender_email']) || !\Mailer\Factory::instance()->sender()->isEmailAddress($data['sender_email'])) { throw new \Exception('Your email address is invalid'); } if (empty($data['sender_name'])) { throw new \Exception('Your name is invalid'); } if (empty($data['recipients'])) { throw new \Exception('Invalid recipient email(s)'); } if (empty($data['message'])) { throw new \Exception('Invalid message'); } foreach ($data['recipients'] as $key => $recipient) { try { (new \Affiliates\Models\Invites())->bind(array('affiliate_id' => $this->getIdentity()->id, 'sender_email' => $data['sender_email'], 'sender_name' => $data['sender_name'], 'recipient_email' => $recipient, 'message' => $data['message']))->set('__send_email', true)->save(); unset($data['recipients'][$key]); \Dsc\System::addMessage('Invitation sent to ' . $recipient, 'success'); } catch (\Exception $e) { \Dsc\System::addMessage('Invitation not sent to ' . $recipient, 'warning'); \Dsc\System::addMessage($e->getMessage(), 'warning'); } } } catch (\Exception $e) { \Dsc\System::addMessage('Failed to send invitation(s)', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); \Dsc\System::instance()->setUserState('invite_friends.email.flash_filled', true); $this->flash->store($data); $this->app->reroute('/affiliate/invite-friends/email'); } $this->flash->store(array()); $this->app->reroute('/affiliate/invite-friends/email'); }
/** * Purge expired carts * */ public function deleteCart() { $cart_id = $this->app->get('PARAMS.cart_id'); $item = (new \Shop\Models\Carts())->setState('filter.id', $cart_id)->getItem(); if (!empty($item->id)) { try { $item->remove(); \Dsc\System::addMessage('Removed cart', 'success'); } catch (\Exception $e) { \Dsc\System::addMessage('Could not remove cart', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); } } else { \Dsc\System::addMessage('Invalid Cart ID', 'error'); } $this->app->reroute('/admin/shop/reports/' . $this->slug()); }
public function refreshTotals() { $customer = $this->getItem(); if (empty($customer->id)) { \Dsc\System::addMessage('Invalid ID', 'error'); $this->app->reroute('/admin/shop/customers'); } $customer->{'shop.total_spent'} = $customer->totalSpent(true); $customer->{'shop.orders_count'} = $customer->ordersCount(true); try { $customer->save(); $customer->checkCampaigns(); \Dsc\System::addMessage('Totals refreshed', 'success'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); } $this->app->reroute('/admin/shop/customer/read/' . $customer->id); }
public function read() { try { $key = $this->input->get('key', '', 'raw'); if (empty($key) || !apcu_exists($key)) { throw new \Exception('Invalid Key: ' . $key); } $data = apcu_fetch($key, $success); if (!$success) { \Dsc\System::addMessage('Fetching data unsuccessful', 'error'); } $this->app->set('key', $key); $this->app->set('data', $data); echo \Dsc\System::instance()->get('theme')->renderTheme('Admin/Views::cache/apcu_read.php'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); $this->app->reroute('/admin/cache/apcu'); } }
/** * Gets paginated results from a source */ protected function filteredSearch() { $current_source = array('id' => 'invalid', 'title' => ''); $paginated = null; $q = trim($this->input->get('q', null, 'default')); try { if (!empty($q)) { $current_source = \Search\Models\Source::current(); $paginated = \Search\Models\Source::paginate($current_source, $q); \Dsc\Activities::track('Performed Search', array('Search Term' => $q, 'Search Source' => $current_source['title'], 'page_number' => $paginated->current_page, 'app' => 'search')); } } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); } $this->app->set('current_source', $current_source); $this->app->set('paginated', $paginated); $this->app->set('q', $q); $this->app->set('meta.title', trim('Search ' . $current_source['title'])); echo $this->theme->render('Search/Site/Views::search/index.php'); }
public function email() { $f3 = \Base::instance(); $id = $this->inputfilter->clean($f3->get('PARAMS.id'), 'alnum'); $email = $this->inputfilter->clean($f3->get('GET.email'), 'string'); $templateModel = (new \Mailer\Models\Templates())->setState('filter.id', $id); $this->app->set('id', $id); $mailer = \Dsc\System::instance()->get('mailer'); try { $template = $templateModel->getItem(); if (empty($template->id)) { throw new \Exception(); } //get the event $event = (new \Mailer\Models\Events())->setState('filter.id', $template->event_id)->getItem(); $listenerEvent = 'mailerPreview'; $parts = explode('.', $event->event_name); foreach ($parts as $part) { $listenerEvent .= ucfirst($part); } //the preview event should return the variables $results = \Dsc\System::instance()->trigger($listenerEvent); $variables = $results->getArgument('variables'); $view = \Dsc\System::instance()->get('theme'); if (!empty($variables)) { $contents = \Mailer\Factory::getEmailContents($event->event_name, $variables); $mailer->sendEvent($email, $contents); \Dsc\System::addMessage('Sent Email to : ' . $email . '', 'success'); $this->app->set('contents', $contents); echo $view->renderView('Mailer/Admin/Views::preview/index.php'); } else { \Dsc\System::addMessage('No email sent', 'error'); $view = \Dsc\System::instance()->get('theme'); $this->app->set('event', $listenerEvent); echo $view->renderView('Mailer/Admin/Views::preview/notsupported.php'); } } catch (\Exception $e) { \Dsc\System::instance()->addMessage("Invalid Item: " . $e->getMessage(), 'error'); return; } }
public function products() { $model = (new \Shop\Models\Products())->populateState(); $id = $this->inputfilter->clean($this->app->get('PARAMS.id'), 'alnum'); try { $collection = (new \Shop\Models\Collections())->setState('filter.id', $id)->getItem(); if (empty($collection->id)) { throw new \Exception('Invalid Collection'); } $conditions = \Shop\Models\Collections::getProductQueryConditions($collection->id); if (!$model->getState('list.limit')) { $model->setState('list.limit', '100'); } $paginated = $model->setParam('conditions', $conditions)->setState('list.sort', array(array('collections.' . $id . '.ordering' => 1)))->paginate(); $this->app->set('paginated', $paginated); $this->app->set('collection', $collection); $this->app->set('state', $model->getState()); } catch (\Exception $e) { \Dsc\System::addMessage((string) $e, 'error'); $this->app->reroute('/admin/shop/collections'); } $this->app->set('meta.title', 'Manually Sort Products in Collection | Shop'); echo $this->theme->renderTheme('Shop/Admin/Views::collections/products.php'); }
public function initialize() { $f3 = \Base::instance(); $this->setDefaults(array('namespace' => '\\Affiliates\\Site\\Controllers', 'url_prefix' => '/affiliate')); $f3->route('GET /affiliate/@affiliate_id', function ($f3) { \Dsc\System::instance()->get('input')->set('affiliate_id', $f3->get('PARAMS.affiliate_id')); \Affiliates\Models\Referrals::handle(); $identity = \Dsc\System::instance()->get('auth')->getIdentity(); if (empty($identity->id)) { \Dsc\System::addMessage('Please register with us so we can complete the referral. Thanks!'); $f3->reroute('/register'); } $f3->reroute('/'); }); $f3->route('GET /invite/@invite_id', function ($f3) { \Dsc\System::instance()->get('input')->set('invite_id', $f3->get('PARAMS.invite_id')); \Affiliates\Models\Referrals::handle(); $identity = \Dsc\System::instance()->get('auth')->getIdentity(); if (empty($identity->id)) { \Dsc\System::addMessage('Please register with us so we can complete the referral. Thanks!'); $f3->reroute('/register'); } $f3->reroute('/'); }); $f3->route('GET /affiliate/share/thanks', function ($f3) { echo "Thanks!"; }); $this->add('/dashboard', 'GET', array('controller' => 'Dashboard', 'action' => 'index')); $this->add('/invite-friends', 'GET', array('controller' => 'Invite', 'action' => 'index')); $this->add('/invite-friends/email', 'GET', array('controller' => 'Invite', 'action' => 'email')); $this->add('/invite-friends/email', 'POST', array('controller' => 'Invite', 'action' => 'emailSubmit')); $this->add('/invite-friends/link', 'GET', array('controller' => 'Invite', 'action' => 'link')); $this->add('/invite-history', 'GET|POST', array('controller' => 'Invites', 'action' => 'index')); $this->add('/invite-history/page/@page', 'GET', array('controller' => 'Invites', 'action' => 'index')); $this->add('/fp/@id [ajax]', 'GET|POST', array('controller' => 'Fingerprint', 'action' => 'index')); }
public function reverify() { $custom_redirect = \Dsc\System::instance()->get('session')->get('user.reverify.redirect'); $redirect = $custom_redirect ? $custom_redirect : $this->list_route; $user = $this->getItem(); if (!empty($user->id)) { $redirect = $custom_redirect ? $custom_redirect : '/admin/user/edit/' . $user->id; try { $user->sendEmailValidatingEmailAddress(); \Dsc\System::addMessage('Email sent', 'success'); } catch (\Exception $e) { \Dsc\System::addMessage('There was an error sending the email.', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); } } else { \Dsc\System::addMessage('Invalid user.', 'error'); } $this->app->reroute($redirect); }
/** * Import routes from a specified Asset ID * * @throws \Exception */ public function routes() { $message = null; try { $id = $this->inputfilter->clean($this->app->get('PARAMS.id'), 'alnum'); $item = (new \Dsc\Mongo\Collections\Assets())->setState('filter.id', $id)->getItem(); if (empty($item->id)) { throw new \Exception('Invalid Item'); } $file = new \SplTempFileObject(); // TODO Push this to the Assets model switch ($item->storage) { case "s3": $contents = @file_get_contents($item->url); break; case "gridfs": default: $length = $item->length; $chunkSize = $item->chunkSize; $chunks = ceil($length / $chunkSize); $collChunkName = $item->collectionNameGridFS() . ".chunks"; $collChunks = $item->getDb()->{$collChunkName}; $contents = null; for ($i = 0; $i < $chunks; $i++) { $chunk = $collChunks->findOne(array("files_id" => $item->_id, "n" => $i)); $contents .= $chunk["data"]->bin; } break; } $file->fwrite($contents); $reader = new \Ddeboer\DataImport\Reader\CsvReader($file, ","); $reader->setHeaderRowNumber(0); $this->app->set('item', $item); $this->app->set('count', count($reader)); $skipped = 0; $inserted = 0; $updated = 0; $failed = 0; $errors = array(); foreach ($reader as $row) { set_time_limit(0); if (empty($row['Original'])) { $skipped++; continue; } if (strpos($row['Original'], '/') === 0) { $row['Original'] = substr($row['Original'], 1); } if (empty($row['Original'])) { $skipped++; continue; } $redirect = \Redirect\Admin\Models\Routes::findOne(array('url.alias' => $row['Original'])); if (empty($redirect->id)) { // insert $redirect = new \Redirect\Admin\Models\Routes(); $redirect->{'url.alias'} = $row['Original']; $redirect->{'url.redirect'} = $row['Target']; try { $redirect->save(); $inserted++; } catch (\Exception $e) { $failed++; $errors[] = $e->getMessage(); } } else { // update $redirect->{'url.alias'} = $row['Original']; $redirect->{'url.redirect'} = $row['Target']; try { $redirect->save(); $updated++; } catch (\Exception $e) { $failed++; $errors[] = $e->getMessage(); } } } $this->app->set('skipped', $skipped); $this->app->set('inserted', $inserted); $this->app->set('updated', $updated); $this->app->set('failed', $failed); $this->app->set('errors', $errors); $this->app->set('message', $message); echo $this->theme->render('Redirect/Admin/Views::importer/routes_results.php'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); $this->app->reroute('/admin/redirect/import'); return; } }
/** * Checks if the user has access to the requested resource and method pair * * @param unknown $resource * @param unknown $method * @param string $require_identity * @return boolean */ public function checkAccess($resource, $method, $require_identity = true) { $f3 = \Base::instance(); $identity = $this->getIdentity(); if ($require_identity) { $this->requireIdentity(); } // TODO If the user has multiple roles (is that possible) then loop through them if ($hasAccess = \Dsc\System::instance()->get('acl')->isAllowed($identity->role, $resource, $method)) { return $this; } if (\Base::instance()->get('DEBUG')) { \Dsc\System::addMessage(\Dsc\Debug::dump('Debugging is enabled := $role: ' . $identity->role . ", " . '$resource: ' . $resource . ", " . '$method: ' . $method)); } \Dsc\System::addMessage('You do not have access to perform that action.', 'error'); $global_app_name = strtolower($f3->get('APP_NAME')); switch ($global_app_name) { case "admin": \Base::instance()->reroute('/admin'); break; case "site": \Base::instance()->reroute('/'); break; default: throw new \Exception('No access and unkown application'); break; } return false; }
public function save() { try { $request = $this->app->get('REQUEST'); $job = new \Dsc\Cron\Job(); $job->setMinute($request['minute'])->setHour($request['hour'])->setDayOfMonth($request['dayOfMonth'])->setMonth($request['month'])->setDayOfWeek($request['dayOfWeek'])->setCommand($request['command'])->setActive($request['active']); //\Dsc\System::addMessage( \Dsc\Debug::dump($job->cast()) ); $crontab = new \Dsc\Cron\Crontab(); $crontab->addJob($job); $crontab->write(); \Dsc\System::addMessage('Cron job added', 'success'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); } $this->app->reroute('/admin/cron'); }
public function replaceUrl() { $slug = $this->inputfilter->clean($this->app->get('PARAMS.slug'), 'string'); $asset = $this->getModel()->setState('filter.slug', $slug)->getItem(); if (empty($asset->id)) { throw new \Exception('Invalid Asset'); } $url = $this->input->get('upload_url', null, 'default'); $custom_redirect = \Dsc\System::instance()->get('session')->get('assets.handleUrl.redirect'); $redirect = $custom_redirect ? $custom_redirect : $this->create_item_route; if (!empty($url)) { try { $web = \Web::instance(); $request = $web->request($url); if (!empty($request['body'])) { $buffer = $request['body']; } $url_path = parse_url($url, PHP_URL_PATH); $pathinfo = pathinfo($url_path); $filename = $this->inputfilter->clean($url_path); $originalname = str_replace("/", "-", $filename); $values = array('storage' => 'gridfs', 'contentType' => $asset->getMimeType($buffer), 'md5' => md5($filename), "filename" => $filename, "source_url" => $url); $asset = $asset->replace($buffer, $values); \Dsc\System::addMessage('Asset replaced'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); } } $this->app->reroute($redirect); }
/** * Compare the items and shipping from the previously-saved cart. * If they've changed, clear the tax calculations. */ protected function beforeSave() { if (!empty($this->id)) { // If a cart is updated, recalculate coupon values and tax value $cart = (new static())->load(array('_id' => new \MongoId((string) $this->id))); // Compare items, coupons, shipping address, and shipping method. // If changed, empty the taxes // and update coupon & giftcard values if ($cart->items != $this->items || $cart->quantity() != $this->quantity() || $cart->coupons != $this->coupons || $cart->auto_coupons != $this->auto_coupons || $cart->giftcards != $this->giftcards || $cart->shippingMethod() != $this->shippingMethod() || $cart->{'checkout.shipping_address'} != $this->{'checkout.shipping_address'} || $cart->{'checkout.billing_address'} != $this->{'checkout.billing_address'}) { $this->taxes = array(); foreach ((array) $this->coupons as $key => $item) { if (!empty($item['usage_automatic'])) { unset($this->coupons[$key]); continue; } // ensure that the coupon is still valid, removing it if not // and set its value to 0 try { $coupon = (new \Shop\Models\Coupons())->bind($item)->reload(); $coupon->cartValid($this); $this->{'coupons.' . $key . '.amount'} = 0; } catch (\Exception $e) { \Dsc\System::addMessage('Removing coupon: ' . $this->coupons[$key]['code'], 'error'); \Dsc\System::addMessage((string) $e->getMessage(), 'error'); unset($this->coupons[$key]); } } $this->coupons = array_values(array_filter($this->coupons)); // now get all the coupon values foreach ((array) $this->coupons as $key => $item) { $this->{'coupons.' . $key . '.cart_totals_before_calculating_coupon_value'} = $this->totals(); $this->{'coupons.' . $key . '.amount'} = $this->calcCouponValue($item); } // now that user coupons have been validated, ensure the autoCoupons $this->ensureAutoCoupons(); foreach ((array) $this->giftcards as $key => $item) { $this->{'giftcards.' . $key . '.amount'} = $this->calcGiftCardValue($item); } } } // if there is a user_id, delete the session_id if (!empty($this->user_id)) { $this->session_id = null; $this->user_email = $this->user()->email; } $this->quantity = $this->quantity(); $this->items_count = count($this->items); return parent::beforeSave(); }
public function stringsUpdate() { try { $language = $this->getItem(); if (empty($language->id)) { throw new \Exception('Invalid Language'); } // get the strings for the selected language // and add this new key/value pair to it $strings = (new \Dsc\Mongo\Collections\Translations\Strings())->setState('filter.lang_id', $language->id)->getItem(); if (empty($strings->id)) { $strings = new \Dsc\Mongo\Collections\Translations\Strings(); $strings->language_code = $language->code; $strings->language_id = $language->id; } $data = \Base::instance()->get('REQUEST'); $strings->strings = array_filter(array_merge($strings->strings, $data['strings'])); $strings->save(); \Dsc\System::addMessage('Strings updated', 'success'); } catch (\Exception $e) { \Dsc\System::addMessage($e->getMessage(), 'error'); } $this->app->reroute('/admin/language/' . $language->id . '/strings'); }
public function translate() { // using $id and $code, create a clone of the object in the new language $id = $this->app->get('PARAMS.id'); $code = $this->app->get('PARAMS.code'); try { $item = $model = $this->getModel()->setState('filter.id', $id)->getItem(); $clone = $item->set('id', null)->set('_id', null)->setLang($code)->set('type', $item->type())->save(); \Dsc\System::addMessage('Translation created. You are now editing the translation.'); $new_id = $clone->get($this->getItemKey()); $route = str_replace('{id}', $new_id, $this->edit_item_route); $this->app->reroute($route); } catch (\Exception $e) { \Dsc\System::addMessage('Translation failed with the following errors:', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); $route = str_replace('{id}', $id, $this->edit_item_route); $this->app->reroute($route); } }
/** * Step 5 == Finally, submit the password reset */ public function passwordResetSubmit() { $f3 = \Base::instance(); $data = array('new_password' => $this->input->get('new_password', null, 'string'), 'confirm_new_password' => $this->input->get('confirm_new_password', null, 'string')); $id = \Dsc\System::instance()->get('session')->get('user.forgot_password.id'); $user = (new \Users\Models\Users())->setState('filter.id', $id)->getItem(); if (empty($id) || empty($user->id)) { // session value has expired \Dsc\System::addMessage('Unable to process password reset request. Please try again.', 'error'); $f3->reroute('/user/forgot-password'); return; } $user->bind($data); try { $user->save()->sendEmailPasswordResetNotification(); } catch (\Exception $e) { \Dsc\System::addMessage('Password reset failed.', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); \Dsc\System::instance()->get('session')->set('user.forgot_password.id', null); $f3->reroute('/user/forgot-password'); return; } // ok, password reset passed \Dsc\System::addMessage('Password has been reset. You may now login with your new password.'); $f3->reroute('/login'); }
/** * */ public function moveToCart() { $f3 = \Base::instance(); $wishlist_id = $this->inputfilter->clean($f3->get('PARAMS.id'), 'alnum'); $wishlistitem_hash = $this->inputfilter->clean($f3->get('PARAMS.hash'), 'cmd'); $identity = \Dsc\System::instance()->get('auth')->getIdentity(); $session_id = \Dsc\System::instance()->get('session')->id(); $wishlist = (new \Shop\Models\Wishlists())->load(array('_id' => new \MongoId((string) $wishlist_id))); if (empty($wishlist->id)) { if ($f3->get('AJAX')) { return $this->outputJson($this->getJsonResponse(array('result' => false, 'message' => 'Invalid wishlist'))); } else { \Dsc\System::addMessage('Invalid Wishlist', 'error'); $f3->reroute('/shop/wishlist'); return; } } // Validate that this wishlist belongs to the current user if ($identity->id != $wishlist->user_id && $session_id != $wishlist->session_id) { if ($f3->get('AJAX')) { return $this->outputJson($this->getJsonResponse(array('result' => false, 'message' => 'Not your wishlist'))); } else { \Dsc\System::addMessage('Not your wishlist', 'error'); $f3->reroute('/shop/wishlist'); return; } } $cart = \Shop\Models\Carts::fetch(); try { $wishlist->moveToCart($wishlistitem_hash, $cart); } catch (\Exception $e) { if ($f3->get('AJAX')) { return $this->outputJson($this->getJsonResponse(array('result' => false, 'message' => 'Item could not be moved to cart'))); } else { \Dsc\System::addMessage('Item could not be moved to cart', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); $f3->reroute('/shop/wishlist/' . $wishlist->id); return; } } if ($f3->get('AJAX')) { return $this->outputJson($this->getJsonResponse(array('result' => true, 'message' => 'Item moved to cart'))); } else { \Dsc\System::addMessage('Item moved to cart'); $f3->reroute('/shop/wishlist/' . $wishlist->id); } }
public function linkSocialProfile() { $settings = \Users\Models\Settings::fetch(); if (!$settings->isSocialLoginEnabled()) { \Dsc\System::addMessage('Social login is not supported.', 'error'); \Base::instance()->reroute("/user"); } $user = $this->getIdentity(); if (empty($user->id) || !empty($user->__safemode)) { $this->app->reroute('/user'); return; } $provider = strtolower($this->app->get('PARAMS.provider')); if (!$settings->isSocialLoginEnabled($provider)) { \Dsc\System::addMessage('This social profile is not supported.', 'error'); \Base::instance()->reroute("/user"); } $hybridauth_config = \Users\Models\Settings::fetch(); $config = (array) $hybridauth_config->{'social'}; \Dsc\System::instance()->get('session')->set('social_login.failure.redirect', '/user/social-profiles'); if (empty($config['base_url'])) { $config['base_url'] = $this->app->get('SCHEME') . '://' . $this->app->get('HOST') . $this->app->get('BASE') . '/login/social'; } $custom_redirect = \Dsc\System::instance()->get('session')->get('site.login.redirect'); try { // create an instance for Hybridauth with the configuration file path as parameter $hybridauth = new \Hybrid_Auth($config); // try to authenticate the selected $provider $adapter = $hybridauth->authenticate($provider); // grab the user profile $user_profile = $adapter->getUserProfile(); // OK, we have the social identity. // Let's make sure it's unique in our system $filter = 'social.' . $provider . '.profile.identifier'; $found = (new \Users\Models\Users())->setCondition($filter, $user_profile->identifier)->getItem(); if (!empty($found->id) && (string) $found->id != (string) $user->id) { // errrrr, only allow a social ID to be linked to one account at a time \Dsc\System::addMessage('This social profile is already registered with us.', 'error'); // redirect to the requested target, or the default if none requested $redirect = $custom_redirect ? $custom_redirect : '/user'; \Dsc\System::instance()->get('session')->set('site.login.redirect', null); \Base::instance()->reroute($redirect); return; } // add the social id to the user $user->set('social.' . $provider . '.profile', (array) $adapter->getUserProfile()); $user->set('social.' . $provider . '.access_token', (array) $adapter->getAccessToken()); $user->save(); } catch (\Exception $e) { $user_error = null; switch ($e->getCode()) { case 0: $error = "Unspecified error."; break; case 1: $error = "Hybridauth configuration error."; break; case 2: $error = "Provider not properly configured."; break; case 3: $error = "Unknown or disabled provider."; break; case 4: $error = "Missing provider application credentials."; break; case 5: $error = "Authentication failed. The user has canceled the authentication or the provider refused the connection."; $user_error = "Authentication failed."; break; case 6: $error = "User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again."; $user_error = "We were unable to get your profile. Please authenticate again with the profile provider."; $adapter->logout(); break; case 7: $error = "User not connected to the provider."; $user_error = "No profile found with the provider. Missing connection."; $adapter->logout(); break; } if ($this->app->get('DEBUG')) { // if debug mode is enabled, display the full error $error .= "<br /><br /><b>Original error message:</b> " . $e->getMessage(); $error .= "<hr /><pre>Trace:<br />" . $e->getTraceAsString() . "</pre>"; } else { // otherwise, display something simple $error = $user_error; } \Dsc\System::addMessage('Linking failed', 'error'); \Dsc\System::addMessage($error, 'error'); $redirect = $custom_redirect ? $custom_redirect : '/user'; $this->app->reroute($redirect); } // redirect to the requested target, or the default if none requested $redirect = $custom_redirect ? $custom_redirect : '/user'; \Dsc\System::instance()->get('session')->set('site.login.redirect', null); $this->app->reroute($redirect); }
/** * Target for POST to create new record */ public function add() { $f3 = \Base::instance(); $flash = \Dsc\Flash::instance(); $data = \Base::instance()->get('REQUEST'); //\Dsc\System::addMessage( \Dsc\Debug::dump($data) ); if (!$this->canCreate($data)) { throw new \Exception('Not allowed to add record'); } $__customers = explode(",", \Dsc\ArrayHelper::get($data, '__customers')); $__emails = explode(",", \Dsc\ArrayHelper::get($data, '__emails')); $emails = array_filter(array_unique(array_merge(array(), $__customers, $__emails))); if (!empty($emails)) { try { $this->getModel()->issueToEmails($data, $emails); switch ($data['submitType']) { case "save_new": $route = $this->create_item_route; break; case "save_close": default: $route = $this->list_route; break; } $this->setRedirect($route); } catch (\Exception $e) { \Dsc\System::instance()->addMessage('Save failed with the following errors:', 'error'); \Dsc\System::instance()->addMessage($e->getMessage(), 'error'); if (\Base::instance()->get('DEBUG')) { \Dsc\System::instance()->addMessage($e->getTraceAsString(), 'error'); } // redirect back to the create form with the fields pre-populated \Dsc\System::instance()->setUserState('use_flash.' . $this->create_item_route, true); $flash->store($data); $this->setRedirect($this->create_item_route); } } else { // create just a single gift card $this->doAdd($data); } \Dsc\System::addMessage('Gift cards issued'); if ($route = $this->getRedirect()) { \Base::instance()->reroute($route); } return; }
public function revoke() { try { $item = $this->getItem(); if (empty($item->id)) { throw new \Exception('Invalid Item'); } $item->revoke(); \Dsc\System::addMessage('Revoked', 'success'); } catch (\Exception $e) { \Dsc\System::addMessage('Revoke failed.', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); } $id = $this->inputfilter->clean($this->app->get('PARAMS.id'), 'alnum'); $this->app->reroute('/admin/affiliates/commission/read/' . $id); }
public function avatarSubmit() { $user = $this->getIdentity(); try { //TODO Should we delete the previous avatar? if (!empty($_FILES['avatar'])) { //todo move width/height to settings $_FILES['avatar']['name'] = $user->fullName() . "'s Avatar"; $avatar = \Users\Models\Avatars::createFromUpload($_FILES['avatar'], array('width' => 200, 'height' => 200, 'tags' => array($user->id, $user->fullName()))); $user->set('avatar.slug', $avatar->{'slug'}); $user->save(); \Dsc\System::addMessage('Changed avatar.'); } } catch (\Exception $e) { \Dsc\System::addMessage('Saving avatar failed.', 'error'); \Dsc\System::addMessage($e->getMessage(), 'error'); } $this->app->reroute('/user/change-avatar'); }