Example #1
0
 /**
  * @Route(methods="POST", defaults={"_maintenance" = true})
  * @Request({"credentials": "array", "_remember_me": "boolean"})
  */
 public function authenticateAction($credentials, $remember = false)
 {
     $isXml = App::request()->isXmlHttpRequest();
     try {
         if (!App::csrf()->validate()) {
             throw new AuthException(__('Invalid token. Please try again.'));
         }
         App::auth()->authorize($user = App::auth()->authenticate($credentials, false));
         if (!$isXml) {
             return App::auth()->login($user, $remember);
         } else {
             App::auth()->setUser($user, $remember);
             return ['success' => true];
         }
     } catch (BadCredentialsException $e) {
         $error = __('Invalid username or password.');
     } catch (AuthException $e) {
         $error = $e->getMessage();
     }
     if (!$isXml) {
         App::message()->error($error);
         return App::redirect(App::url()->previous());
     } else {
         App::abort(400, $error);
     }
 }
 /**
  * @Route("/admin/login", defaults={"_maintenance"=true})
  */
 public function loginAction()
 {
     if (App::user()->isAuthenticated()) {
         return App::redirect('@system');
     }
     return ['$view' => ['title' => __('Login'), 'name' => 'system/theme:views/login.php', 'layout' => false], 'last_username' => App::session()->get(Auth::LAST_USERNAME), 'redirect' => App::request()->get('redirect') ?: App::url('@system', [], true), 'remember_me_param' => Auth::REMEMBER_ME_PARAM];
 }
 /**
  * @Request({"email": "string"})
  */
 public function requestAction($email)
 {
     try {
         if (App::user()->isAuthenticated()) {
             return App::redirect();
         }
         if (!App::csrf()->validate()) {
             throw new Exception(__('Invalid token. Please try again.'));
         }
         if (empty($email)) {
             throw new Exception(__('Enter a valid email address.'));
         }
         if (!($user = User::findByEmail($email))) {
             throw new Exception(__('Unknown email address.'));
         }
         if ($user->isBlocked()) {
             throw new Exception(__('Your account has not been activated or is blocked.'));
         }
         $user->activation = App::get('auth.random')->generateString(32);
         $url = App::url('@user/resetpassword/confirm', ['user' => $user->username, 'key' => $user->activation], 0);
         try {
             $mail = App::mailer()->create();
             $mail->setTo($user->email)->setSubject(__('Reset password for %site%.', ['%site%' => App::module('system/site')->config('title')]))->setBody(App::view('system/user:mails/reset.php', compact('user', 'url', 'mail')), 'text/html')->send();
         } catch (\Exception $e) {
             throw new Exception(__('Unable to send confirmation link.'));
         }
         $user->save();
         return ['message' => __('Check your email for the confirmation link.')];
     } catch (Exception $e) {
         App::abort(400, $e->getMessage());
     }
 }
 /**
  * @param FieldValueBase $fieldValue
  * @return array
  */
 public function uploadAction(FieldValueBase $fieldValue)
 {
     try {
         if (!($path = $this->getPath($fieldValue->field->get('path')))) {
             return $this->error(__('Invalid path.'));
         }
         if (!is_dir($path) || !App::user()->hasAccess('system: manage storage | bixframework: upload files')) {
             return $this->error(__('Permission denied.'));
         }
         $fileInfo = [];
         $files = App::request()->files->get('files');
         if (!$files) {
             return $this->error(__('No files uploaded.'));
         }
         /** @var UploadedFile $file */
         foreach ($files as $file) {
             if (!$file->isValid()) {
                 return $this->error(sprintf(__('Uploaded file invalid. (%s)'), $file->getErrorMessage()));
             }
             if (!($ext = $file->guessExtension()) or !in_array($ext, $fieldValue->field->get('allowed', []))) {
                 return $this->error(__('File extension not allowed.'));
             }
             if (!($size = $file->getClientSize()) or $size > $fieldValue->field->get('max_size', 0) * 1024 * 1024) {
                 return $this->error(__('File is too large.'));
             }
             //give file unique name
             $localFile = $file->move($path, sprintf('%d%d-%s', microtime(true) * 10000, rand(), preg_replace("/[^a-zA-Z0-9\\.]/", "-", $file->getClientOriginalName())));
             $fileInfo[] = ['name' => $file->getClientOriginalName(), 'size' => $localFile->getSize(), 'path' => str_replace(App::path(), '', $localFile->getPathname()), 'url' => ltrim(App::url()->getStatic($localFile->getPathname(), [], 'base'), '/')];
         }
         return ['message' => __('Upload complete.'), 'files' => $fileInfo];
     } catch (\Exception $e) {
         return $this->error(__('Unable to upload.'));
     }
 }
Example #5
0
 /**
  * @Request({"path"})
  */
 public function indexAction($path)
 {
     if (!($dir = $this->getPath())) {
         return $this->error(__('Invalid path.'));
     }
     if (!is_dir($dir) || '-' === ($mode = $this->getMode($dir))) {
         throw new ForbiddenException(__('Permission denied.'));
     }
     $data = array_fill_keys(['items'], []);
     $data['mode'] = $mode;
     $finder = App::finder();
     $finder->sort(function ($a, $b) {
         return $b->getRealpath() > $a->getRealpath() ? -1 : 1;
     });
     foreach ($finder->depth(0)->in($dir) as $file) {
         if ('-' === ($mode = $this->getMode($file->getPathname()))) {
             continue;
         }
         $info = ['name' => $file->getFilename(), 'mime' => 'application/' . ($file->isDir() ? 'folder' : 'file'), 'path' => $this->normalizePath($path . '/' . $file->getFilename()), 'url' => ltrim(App::url()->getStatic($file->getPathname(), [], 'base'), '/'), 'writable' => $mode == 'w'];
         if (!$file->isDir()) {
             $info = array_merge($info, ['size' => $this->formatFileSize($file->getSize()), 'lastmodified' => date(\DateTime::ISO8601, $file->getMTime())]);
         }
         $data['items'][] = $info;
     }
     return $data;
 }
Example #6
0
 public function getFormUrl()
 {
     if (!$this->id) {
         return '';
     }
     return App::url('@formmaker/form/front', ['id' => $this->id]);
 }
Example #7
0
 /**
  * @Route(methods="POST", defaults={"_maintenance" = true})
  * @Request({"credentials": "array", "remember_me": "boolean", "redirect": "string"})
  */
 public function authenticateAction($credentials, $remember = false, $redirect = '')
 {
     try {
         if (!App::csrf()->validate()) {
             throw new CsrfException(__('Invalid token. Please try again.'));
         }
         App::auth()->authorize($user = App::auth()->authenticate($credentials, false));
         if (($event = App::auth()->login($user, $remember)) && $event->hasResponse()) {
             return $event->getResponse();
         }
         if (App::request()->isXmlHttpRequest()) {
             return App::response()->json(['csrf' => App::csrf()->generate()]);
         } else {
             return App::redirect(preg_replace('#(https?:)?//[^/]+#', '', $redirect));
         }
     } catch (CsrfException $e) {
         if (App::request()->isXmlHttpRequest()) {
             return App::response()->json(['csrf' => App::csrf()->generate()], 401);
         }
         $error = $e->getMessage();
     } catch (BadCredentialsException $e) {
         $error = __('Invalid username or password.');
     } catch (AuthException $e) {
         $error = $e->getMessage();
     }
     if (App::request()->isXmlHttpRequest()) {
         App::abort(401, $error);
     } else {
         App::message()->error($error);
         return App::redirect(preg_replace('#(https?:)?//[^/]+#', '', App::url()->previous()));
     }
 }
Example #8
0
 /**
  * @Route("/admin/login", defaults={"_maintenance"=true})
  * @Request({"redirect": "string", "message": "string"})
  */
 public function loginAction($redirect = '', $message = '')
 {
     if (App::user()->isAuthenticated()) {
         return App::redirect('@system');
     }
     return ['$view' => ['title' => __('Login'), 'name' => 'system/theme:views/login.php', 'layout' => false], 'last_username' => App::session()->get(Auth::LAST_USERNAME), 'redirect' => $redirect ?: App::url('@system'), 'message' => $message];
 }
 public function indexAction()
 {
     $user = App::user();
     if (!$user->isAuthenticated()) {
         return App::redirect('@user/login', ['redirect' => App::url()->current()]);
     }
     return ['$view' => ['title' => __('Your Profile'), 'name' => 'system/user/profile.php'], '$data' => ['user' => ['name' => $user->name, 'email' => $user->email]]];
 }
Example #10
0
 /**
  * @param int        $category_id
  * @param bool|false $base
  * @return string|bool
  */
 public function getUrl($category_id = 0, $base = false)
 {
     $category_id = $category_id ?: $this->get('primary_category', 0);
     if (!$category_id || App::config('bixie/download')->get('routing') == 'item') {
         return App::url('@download/id', ['id' => $this->id ?: 0], $base);
     } else {
         return App::url('@download/category/file/' . $category_id, ['id' => $this->id ?: 0], $base);
     }
 }
Example #11
0
 /**
  * Filter the response content.
  */
 public function onResponse($event, $request, $response)
 {
     if (!is_string($content = $response->getContent())) {
         return;
     }
     $response->setContent(preg_replace_callback(self::REGEX_URL, function ($matches) {
         return sprintf(' %s="%s"', $matches['attr'], App::url($matches['url']));
     }, $content));
 }
 public function indexAction()
 {
     $user = App::user();
     $userprofile = App::module('bixie/userprofile');
     if (!$user->isAuthenticated()) {
         return App::redirect('@user/login', ['redirect' => App::url()->current()]);
     }
     return ['$view' => ['title' => __('Your Profile'), 'name' => 'bixie/userprofile/profile.php'], '$data' => ['config' => $userprofile->config('default'), 'fields' => Field::getProfileFields(), 'profilevalues' => Profilevalue::getUserProfilevalues($user), 'user' => ['id' => $user->id, 'username' => $user->username, 'name' => $user->name, 'email' => $user->email]]];
 }
 /**
  * main profile edit page
  * @Route("/", methods="GET")
  */
 public function indexAction()
 {
     $user = App::user();
     $userprofile = App::module('bixie/userprofile');
     if (!$user->isAuthenticated()) {
         return App::redirect('@user/login', ['redirect' => App::url()->current()]);
     }
     $profileUser = ProfileUser::load($user);
     return ['$view' => ['title' => __('Your Profile'), 'name' => 'bixie/userprofile/profile-edit.php'], '$data' => ['config' => $userprofile->config(), 'user' => ['id' => $user->id, 'username' => $user->username, 'name' => $user->name, 'email' => $user->email]], 'profileUser' => $profileUser];
 }
Example #14
0
 /**
  * @Route("/{id}", name="view", requirements={"id"="\d+"})
  */
 public function viewAction($id)
 {
     $artist = Artist::query()->where('id = ?', [$id])->related('album')->first();
     $request = App::request();
     if (is_null($artist)) {
         $request->getSession()->getFlashBag()->add('error', __('Tried to view an non-existing Artist'));
         return App::response()->redirect('@shoutzor/artist/index');
     }
     $topTracks = $artist->getTopMedia();
     return ['$view' => ['title' => 'Artist: ' . $artist->name, 'name' => 'shoutzor:views/artist/view.php'], 'image' => is_null($artist->image) || empty($artist->image) ? App::url()->getStatic('shoutzor:assets/images/profile-placeholder.png') : App::url()->getStatic('shoutzor:' . App::module('shoutzor')->config('shoutzor')['imageDir'] . '/' . $artist->image), 'summary' => empty($artist->summary) ? __('No summary for this artist is available') : $artist->summary, 'artist' => $artist, 'topTracks' => $topTracks, 'albums' => $artist->getAlbums()];
 }
 /**
  * @Route(methods="POST", defaults={"_maintenance" = true})
  * @Request({"credentials": "array"})
  */
 public function authenticateAction($credentials)
 {
     try {
         if (!App::csrf()->validate()) {
             throw new AuthException(__('Invalid token. Please try again.'));
         }
         App::auth()->authorize($user = App::auth()->authenticate($credentials, false));
         return App::auth()->login($user, App::request()->get(Auth::REMEMBER_ME_PARAM));
     } catch (BadCredentialsException $e) {
         App::message()->error(__('Invalid username or password.'));
     } catch (AuthException $e) {
         App::message()->error($e->getMessage());
     }
     return App::redirect(App::url()->previous());
 }
Example #16
0
 public function extensionsAction()
 {
     $packages = array_values(App::package()->all('pagekit-extension'));
     foreach ($packages as $package) {
         if ($module = App::module($package->get('module'))) {
             if ($settings = $module->get('settings') and $settings[0] === '@') {
                 $settings = App::url($settings);
             }
             $package->set('enabled', true);
             $package->set('settings', $settings);
             $package->set('config', $module->config);
             $package->set('permissions', (bool) $module->get('permissions'));
         }
     }
     return ['$view' => ['title' => __('Extensions'), 'name' => 'installer:views/extensions.php'], '$data' => ['api' => App::get('system.api'), 'packages' => $packages]];
 }
Example #17
0
 /**
  * Adds a menu item.
  *
  * @param string $id
  * @param array  $item
  */
 public function addItem($id, array $item)
 {
     $meta = App::user()->get('admin.menu', []);
     $route = App::request()->attributes->get('_route');
     $item = new ArrObject($item, ['id' => $id, 'label' => $id, 'parent' => 'root', 'priority' => 0]);
     if (!App::user()->hasAccess($item['access'])) {
         return;
     }
     if (isset($meta[$id])) {
         $item['priority'] = $meta[$id];
     }
     if ($item['icon']) {
         $item['icon'] = App::url()->getStatic($item['icon']);
     }
     $item['active'] = (bool) preg_match('#^' . str_replace('*', '.*', $item['active'] ?: $item['url']) . '$#', $route);
     $item['url'] = App::url($item['url']);
     $this->items[$id] = $item;
 }
Example #18
0
 /**
  * @Route("/{id}", name="id")
  */
 public function postAction($id = 0)
 {
     if (!($post = Post::where(['id = ?', 'status = ?', 'date < ?'], [$id, Post::STATUS_PUBLISHED, new \DateTime()])->related('user')->first())) {
         App::abort(404, __('Post not found!'));
     }
     if (!$post->hasAccess(App::user())) {
         App::abort(403, __('Insufficient User Rights.'));
     }
     $post->excerpt = App::content()->applyPlugins($post->excerpt, ['post' => $post, 'markdown' => $post->get('markdown')]);
     $post->content = App::content()->applyPlugins($post->content, ['post' => $post, 'markdown' => $post->get('markdown')]);
     $user = App::user();
     $description = $post->get('meta.og:description');
     if (!$description) {
         $description = strip_tags($post->excerpt ?: $post->content);
         $description = rtrim(mb_substr($description, 0, 150), " \t\n\r\v.,") . '...';
     }
     return ['$view' => ['title' => __($post->title), 'name' => 'blog/post.php', 'og:type' => 'article', 'article:published_time' => $post->date->format(\DateTime::ATOM), 'article:modified_time' => $post->modified->format(\DateTime::ATOM), 'article:author' => $post->user->name, 'og:title' => $post->get('meta.og:title') ?: $post->title, 'og:description' => $description, 'og:image' => $post->get('image.src') ? App::url()->getStatic($post->get('image.src'), [], 0) : false], '$comments' => ['config' => ['post' => $post->id, 'enabled' => $post->isCommentable(), 'requireinfo' => $this->blog->config('comments.require_email'), 'max_depth' => $this->blog->config('comments.max_depth'), 'user' => ['name' => $user->name, 'isAuthenticated' => $user->isAuthenticated(), 'canComment' => $user->hasAccess('blog: post comments'), 'skipApproval' => $user->hasAccess('blog: skip comment approval')]]], 'blog' => $this->blog, 'post' => $post];
 }
 /**
  * @Route("/feed")
  * @Route("/feed/{type}")
  */
 public function feedAction($type = '')
 {
     if (!App::node()->hasAccess(App::user())) {
         App::abort(403, __('Insufficient User Rights.'));
     }
     // fetch locale and convert to ISO-639 (en_US -> en-us)
     $locale = App::module('system')->config('site.locale');
     $locale = str_replace('_', '-', strtolower($locale));
     $site = App::module('system/site');
     $feed = App::feed()->create($type ?: $this->blog->config('feed.type'), ['title' => $site->config('title'), 'link' => App::url('@blog', [], true), 'description' => $site->config('description'), 'element' => ['language', $locale], 'selfLink' => App::url('@blog/feed', [], true)]);
     if ($last = Post::where(['status = ?', 'date < ?'], [Post::STATUS_PUBLISHED, new \DateTime()])->limit(1)->orderBy('modified', 'DESC')->first()) {
         $feed->setDate($last->modified);
     }
     foreach (Post::where(['status = ?', 'date < ?'], [Post::STATUS_PUBLISHED, new \DateTime()])->related('user')->limit($this->blog->config('feed.limit'))->orderBy('date', 'DESC')->get() as $post) {
         $url = App::url('@blog/id', ['id' => $post->id], true);
         $feed->addItem($feed->createItem(['title' => $post->title, 'link' => $url, 'description' => App::content()->applyPlugins($post->content, ['post' => $post, 'markdown' => $post->get('markdown'), 'readmore' => true]), 'date' => $post->date, 'author' => [$post->user->name, $post->user->email], 'id' => $url]));
     }
     return App::response($feed->output(), 200, ['Content-Type' => $feed->getMIMEType() . '; charset=' . $feed->getEncoding()]);
 }
 /**
  * @Request({"user": "******"})
  */
 public function registerAction($data)
 {
     $message = '';
     try {
         if (App::user()->isAuthenticated() || $this->module->config('registration') == 'admin') {
             return App::redirect();
         }
         if (!App::csrf()->validate()) {
             throw new Exception(__('Invalid token. Please try again.'));
         }
         $password = @$data['password'];
         if (trim($password) != $password || strlen($password) < 6) {
             throw new Exception(__('Password must be 6 characters or longer.'));
         }
         $user = User::create(['registered' => new \DateTime(), 'name' => @$data['name'], 'username' => @$data['username'], 'email' => @$data['email'], 'password' => App::get('auth.password')->hash($password), 'status' => User::STATUS_BLOCKED]);
         $token = App::get('auth.random')->generateString(32);
         $admin = $this->module->config('registration') == 'approval';
         if ($verify = $this->module->config('require_verification')) {
             $user->activation = $token;
         } elseif ($admin) {
             $user->activation = $token;
             $user->set('verified', true);
         } else {
             $user->status = User::STATUS_ACTIVE;
         }
         $user->validate();
         $user->save();
         if ($verify) {
             $this->sendVerificationMail($user);
             $message = __('Complete your registration by clicking the link provided in the mail that has been sent to you.');
         } elseif ($admin) {
             $this->sendApproveMail($user);
             $message = __('Your user account has been created and is pending approval by the site administrator.');
         } else {
             $this->sendWelcomeEmail($user);
             $message = __('Your user account has been created.');
         }
     } catch (Exception $e) {
         App::abort(400, $e->getMessage());
     }
     App::message()->success($message);
     return ['message' => $message, 'redirect' => App::url('@user/login', [], true)];
 }
Example #21
0
 /**
  * Loads a package from data.
  *
  * @param  string|array $data
  * @return Package
  */
 public function load($data)
 {
     if (is_string($data) && strpos($data, '{') !== 0) {
         $path = strtr(dirname($data), '\\', '/');
         $data = @file_get_contents($data);
     }
     if (is_string($data)) {
         $data = @json_decode($data, true);
     }
     if (is_array($data) && isset($data['name'])) {
         if (!isset($data['module'])) {
             $data['module'] = basename($data['name']);
         }
         if (isset($path)) {
             $data['path'] = $path;
             $data['url'] = App::url()->getStatic($path);
         }
         return new Package($data);
     }
 }
Example #22
0
 public function getRedirect()
 {
     return $this->form->get('afterSubmit') == 'redirect' ? App::url($this->form->get('redirect'), [], true) : false;
 }
Example #23
0
 /**
  * Gets the category URL.
  *
  * @param  mixed  $referenceType
  * @return string|bool
  */
 public function getUrl($referenceType = false)
 {
     return App::url('@download/category/' . $this->id, [], $referenceType);
 }
Example #24
0
 /**
  * {@inheritdoc}
  */
 public function jsonSerialize()
 {
     $data = ['url' => App::url('@portfolio/id', ['id' => $this->id ?: 0], 'base')];
     return $this->toArray($data);
 }
Example #25
0
 /**
  * @Route("api/site/link", name="api/link")
  * @Request({"link"})
  * @Access("site: manage site")
  */
 public function linkAction($link)
 {
     return ['message' => 'success', 'url' => App::url($link, [], 'base') ?: $link];
 }
Example #26
0
 /**
  * {@inheritdoc}
  */
 public function jsonSerialize()
 {
     $data = $this->toArray([], []);
     $data['url'] = App::url('@shoutzor/artist/view', ['id' => $this->id]);
     return $data;
 }
Example #27
0
 /**
  * @param int  $width
  * @param int  $height
  * @return string
  */
 public function getAvatar($width = 280, $height = 280)
 {
     $config = App::module('bixie/userprofile')->config();
     $this->getProfile();
     if ($avatar_field = $config['avatar_field'] and $fieldValue = $this->fieldValues[$avatar_field]) {
         $files = $fieldValue->getValuedata();
         $file = reset($files);
         if ($file['url']) {
             return sprintf('<img height="%d" width="%d" alt="%s" src="%s">', $height, $width, $this->get('username'), $file['url']);
         }
     }
     if ($config['use_gravatar']) {
         return sprintf('<img height="%d" width="%d" alt="%s" v-gravatar.literal="%s">', $height, $width, $this->get('username'), $this->get('email'));
     }
     $fallback = $config['fallback_image_src'] ?: 'packages/bixie/pk-framework/assets/noimage.jpg';
     return sprintf('<img height="%d" width="%d" alt="%s" src="%s">', $height, $width, $this->get('username'), App::url()->getStatic($fallback, [], 'base'));
 }
 /**
  * Checks for the "system: access admin area" and redirects to login.
  */
 public function onRequest($event, $request)
 {
     if (App::auth()->getUser() or !in_array('system: access admin area', $request->attributes->get('_access', []))) {
         return;
     }
     $params = [];
     // redirect to default URL for POST requests and don't explicitly redirect the default URL
     if ('POST' !== $request->getMethod() && $request->attributes->get('_route') != '@system') {
         $params['redirect'] = App::url()->current(true);
     }
     $event->setResponse(App::response()->redirect('@system/login', $params));
 }
Example #29
0
 public function getFormUrl()
 {
     return App::url('@formmaker/form', ['id' => $this->id]);
 }
Example #30
0
 /**
  * Gets the node URL.
  *
  * @param  mixed  $referenceType
  * @return string
  */
 public function getUrl($referenceType = false)
 {
     return App::url($this->link, [], $referenceType);
 }