public function execute()
 {
     $view = $this->getView();
     $fac = new ModelFactory('PageModel');
     if ($this->getSetting('blog')) {
         $fac->where('parenturl = /blog/view/' . $this->getSetting('blog'));
     }
     $fac->where('parenturl LIKE /blog/view/%');
     $fac->where('published_status = published');
     $fac->where('published <= ' . \Core\Date\DateTime::NowGMT());
     $fac->limit($this->getSetting('count'));
     switch ($this->getSetting('sort')) {
         case 'newest':
             $fac->order('published DESC');
             break;
         case 'popular':
             $fac->order('popularity DESC');
             break;
         case 'random':
             $fac->order('RAND()');
             break;
     }
     if (!$fac->count()) {
         // If there are no results found, then do not display the widget.
         return '';
     }
     $view->assign('count', $this->getSetting('count'));
     $view->assign('sort', $this->getSetting('sort'));
     $view->assign('title', $this->getSetting('title'));
     // The template is expecting an array, if count is 1, only a single Model is returned from the factory.
     $view->assign('links', $this->getSetting('count') == 1 ? [$fac->get()] : $fac->get());
 }
示例#2
0
 public function execute()
 {
     $view = $this->getView();
     $fac = new ModelFactory('PageModel');
     $fac->where('baseurl LIKE /blog/view/%');
     $fac->where('published_status = published');
     $fac->where('published <= ' . \Core\Date\DateTime::NowGMT());
     $fac->limit($this->getSetting('count'));
     switch ($this->getSetting('sort')) {
         case 'newest':
             $fac->order('published DESC');
             break;
         case 'popular':
             $fac->order('popularity DESC');
             break;
         case 'random':
             $fac->order('RAND()');
             break;
     }
     if (!$fac->count()) {
         // If there are no results found, then do not display the widget.
         return '';
     }
     $view->assign('sort', $this->getSetting('sort'));
     $view->assign('title', $this->getSetting('title'));
     $view->assign('links', $fac->get());
 }
	public function index(){

		$view = $this->getView();

		$permissionmanager = \Core\user()->checkAccess('p:/user/permissions/manage');

		$factory = new ModelFactory('UserGroupModel');

		if(Core::IsComponentAvailable('multisite') && MultiSiteHelper::IsEnabled()){
			if(MultiSiteHelper::GetCurrentSiteID()){
				// Child site, only display global and site-specific sites.
				$w = new \Core\Datamodel\DatasetWhereClause();
				$w->setSeparator('or');
				$w->addWhere('site = ' . MultiSiteHelper::GetCurrentSiteID());
				$w->addWhere('site = -1');
				$factory->where($w);

				$displayglobal = true;
				$multisite = false;
			}
			else {
				// Root site, display all groups across all sites.
				$factory->where('site != -2');
				$displayglobal = false;
				$multisite = true;
			}
			$site = MultiSiteHelper::GetCurrentSiteID();
		}
		else{
			$displayglobal = false;
			$multisite = false;
			$site = null;
		}

		$factory->order('name');
		$groups = $factory->get();

		$view->title = 'User Group Administration';
		$view->assign('groups', $groups);
		$view->assign('permissionmanager', $permissionmanager);
		$view->assign('display_global', $displayglobal);
		$view->assign('site', $site);
		$view->assign('multisite', $multisite);
		$view->addControl('Add Group', '/usergroupadmin/create', 'add');
	}
示例#4
0
 /**
  * The hook catch for the "/core/admin/view" hook.
  */
 public static function AdminHook()
 {
     // If this user doesn't have access to manage crons, just continue.
     if (!\Core\user()->checkAccess('p:/cron/viewlog')) {
         return;
     }
     $suffixtext = 'This could be a problem if you have scripts relying on it!  <a href="' . \Core\resolve_link('/cron/howto') . '">Read how to resolve this issue</a>.';
     // Lookup and make sure that the cron hooks have ran recently enough!
     $checks = [['cron' => 'hourly', 'modify' => '-1 hour', 'label' => 'hour'], ['cron' => 'daily', 'modify' => '-1 day', 'label' => 'day'], ['cron' => 'weekly', 'modify' => '-1 week', 'label' => 'week'], ['cron' => 'monthly', 'modify' => '-1 month', 'label' => 'month']];
     foreach ($checks as $check) {
         $time = new CoreDateTime();
         $cronfac = new ModelFactory('CronLogModel');
         $cronfac->where('cron = ' . $check['cron']);
         $time->modify($check['modify']);
         $cronfac->where('created >= ' . $time->getFormatted('U', Time::TIMEZONE_GMT));
         $count = $cronfac->count();
         if ($count == 0) {
             \Core\set_message('Your ' . $check['cron'] . ' cron has not run in the last ' . $check['label'] . '!  ' . $suffixtext, 'error');
             // Only complain to the admin once per view.
             return;
         }
     }
 }
 /**
  * Page to display and manage all gallery widgets.
  */
 public function admin()
 {
     $view = $this->getView();
     $request = $this->getPageRequest();
     if (!\Core\user()->checkAccess('p:/gallery/manage_all')) {
         return View::ERROR_ACCESSDENIED;
     }
     $factory = new ModelFactory('WidgetModel');
     $factory->where('baseurl LIKE /gallery/view/%');
     $factory->order('title');
     $widgets = $factory->get();
     $view->title = 'Gallery Widgets';
     $view->assign('can_manage_theme', \Core\user()->checkAccess('g:admin'));
     $view->assign('widgets', $widgets);
     $view->addControl('Create Gallery Widget', '/gallerywidget/update', 'add');
 }
示例#6
0
 public function view()
 {
     $view = $this->getView();
     $factory = new ModelFactory('GalleryImageModel');
     if ($this->getSetting('order') == 'random') {
         $factory->order('RAND()');
     } else {
         $factory->order($this->getSetting('order'));
     }
     if ($this->getSetting('album')) {
         $factory->where('albumid = ' . $this->getSetting('album'));
         $album = GalleryAlbumModel::Construct($this->getSetting('album'));
         $link = $album->get('baseurl');
     } else {
         $link = null;
     }
     $factory->limit($this->getSetting('count'));
     $images = $factory->get();
     $view->assign('images', $images);
     $view->assign('dimensions', $this->getSetting('dimensions'));
     $view->assign('link', $link);
     $view->assign('uselightbox', $this->getSetting('uselightbox') && Core::IsComponentAvailable('jquery-lightbox'));
 }
示例#7
0
 /**
  * The view for the admin dashboard.  Gets the last executed crons and displays that to the admin.
  */
 public function dashboard()
 {
     // This dashboard has no effect if the user can't view crons.
     if (!\Core\user()->checkAccess('p:/cron/viewlog')) {
         return '';
     }
     $view = $this->getView();
     // Get the latest cron and its execution information and display that to the dashboard.
     $checks = [['cron' => 'hourly', 'modify' => '-1 hour', 'label' => 'hour'], ['cron' => 'daily', 'modify' => '-1 day', 'label' => 'day'], ['cron' => 'weekly', 'modify' => '-1 week', 'label' => 'week'], ['cron' => 'monthly', 'modify' => '-1 month', 'label' => 'month']];
     $crons = array();
     foreach ($checks as $k => $check) {
         $time = new CoreDateTime();
         $cronfac = new ModelFactory('CronLogModel');
         $cronfac->limit(1);
         $cronfac->where('cron = ' . $check['cron']);
         $cronfac->order('created desc');
         $c = $cronfac->get();
         if ($c) {
             $crons[] = $c;
         }
     }
     $view->title = 't:STRING_LATEST_CRON_RESULTS';
     $view->assign('crons', $crons);
 }
示例#8
0
	public function  __construct($atts = null) {
		error_log(__CLASS__ . ' is candidate for immediate removal, please change this code!', E_USER_DEPRECATED);

		// Defaults
		$this->_attributes['name']    = 'page';

		if ($atts instanceof PageModel) {
			parent::__construct(array('name' => 'page'));

			$page = $atts;
		}
		else {
			if(isset($atts['model']) && $atts['model'] instanceof PageModel){
				// Everything is based off the page.
				$page = $atts['model'];
				unset($atts['model']);

				parent::__construct($atts);
			}
			else{
				parent::__construct($atts);

				// BaseURL needs to be set for this to work.
				//if(!$this->get('baseurl')) return null;

				// Everything is based off the page.
				$page = new PageModel($this->get('baseurl'));
			}
		}

		$this->_attributes['baseurl'] = $page->get('baseurl');
		$name = $this->_attributes['name'];

		// I need to get a list of pages to offer as a dropdown for selecting the "parent" page.
		$f = new ModelFactory('PageModel');
		if ($this->get('baseurl')) $f->where('baseurl != ' . $this->get('baseurl'));
		$opts = PageModel::GetPagesAsOptions($f, '-- No Parent Page --');

		$this->addElement(
			'pageparentselect',
			array(
				'name'    => $name . "[parenturl]",
				'title'   => 'Parent Page',
				'value'   => strtolower($page->get('parenturl')),
				'options' => $opts
			)
		);

		// Title
		$this->addElement(
			'text', array(
				      'name'        => $name . "[title]",
				      'title'       => 'Title',
				      'value'       => $page->get('title'),
				      'description' => 'Every page needs a title to accompany it, this should be short but meaningful.',
				      'required'    => true
			      )
		);

		// Rewrite url.
		$this->addElement(
			'pagerewriteurl', array(
				                'name'        => $name . "[rewriteurl]",
				                'title'       => 'Page URL',
				                'value'       => $page->get('rewriteurl'),
				                'description' => 'Starts with a "/", omit ' . ROOT_URL,
				                'required'    => true
			                )
		);

		$this->addElement(
			'access', array(
				        'name'  => $name . "[access]",
				        'title' => 'Access Permissions',
				        'value' => $page->get('access')
			        )
		);

		$this->addElement(
			'pagemetas',
			array(
				'name' => $name . '_meta',
				'model' => $page,
			)
		);

		// Give me all the skins available on the current theme.
		$skins = array('' => '-- Site Default Skin --');
		foreach(ThemeHandler::GetTheme(null)->getSkins() as $s){
			$n = ($s['title']) ? $s['title'] : $s['file'];
			if($s['default']) $n .= ' (default)';
			$skins[$s['file']] = $n;
		}
		if(sizeof($skins) > 2){
			$this->addElement(
				'select', array(
					        'name'    => $name . "[theme_template]",
					        'title'   => 'Theme Skin',
					        'value'   => $page->get('theme_template'),
					        'options' => $skins
				        )
			);
		}
	}
	/**
	 * Given all the user defined filter, sort, and what not, apply those values to the ModelFactory if possible.
	 *
	 * @since 2.4.0
	 * @param ModelFactory $factory
	 */
	public function applyToFactory(ModelFactory $factory){
		if($this->hassort){
			$factory->order($this->getOrder());
		}

		if($this->haspagination){
			// Determine the starting count if the page is requested.
			if($this->_currentpage > 1){
				$startat = $this->_limit * ($this->_currentpage - 1);
				$factory->limit($startat . ', ' . $this->_limit);
			}
			else{
				$factory->limit($this->_limit);
			}
		}

		foreach($this->_elements as $el){
			/** @var $el FormElement */
			$name = $el->get('name');
			$idxname = $name;

			if(strpos($name, 'filter[') === 0){
				$name = substr($name, 7, -1);
			}

			// If this element is not in the index of elements, skip to the next element.
			if(!isset($this->_elementindexes[$idxname])){
				continue;
			}

			// If this doesn't have a link attribute, just skip.
			if(!$el->get('link')){
				continue;
			}

			// No value, just skip.
			if($el->get('value') === '' || $el->get('value') === null){
				continue;
			}

			// If there is a "" option, interpret that as empty and allow "0" to be used.
			if($el->get('value') === '0'){
				if($el->get('options') && isset($el->get('options')[''])){
					// '' is set... proceed.
				}
				else{
					continue;
				}
			}

			$value = $el->get('value');

			// Was there a prefix and/or suffix requested?
			if($el->get('linkvalueprefix')){
				$value = $el->get('linkvalueprefix') . $value;
			}
			if($el->get('linkvaluesuffix')){
				$value = $value . $el->get('linkvaluesuffix');
			}

			// If this link is a date object, convert a date string to its unix timestamp representation.
			if($el instanceof FormDateInput || $el->get('dateformat')){
				// Default to a unix timestamp, but allow the user to override this.
				// This is useful for saving a date in the datastore as a human-readable format.
				$format = $el->get('dateformat') ? $el->get('dateformat') : 'U';
				$date = new CoreDateTime($value);
				$value = $date->getFormatted($format, Time::TIMEZONE_GMT);
			}

			if($el->get('linkname')){
				$name = $el->get('linkname');
			}

			// New support for multiple link names!
			if(!is_array($name)){
				$name = [$name];
			}
			$statements = [];

			foreach($name as $n){
				switch($el->get('link')){
					case FilterForm::LINK_TYPE_STANDARD:
					case FilterForm::LINK_TYPE_GT:
					case FilterForm::LINK_TYPE_GE:
					case FilterForm::LINK_TYPE_LT:
					case FilterForm::LINK_TYPE_LE:
						$statements[] = $n . $el->get('link') . $value;
						break;
					case FilterForm::LINK_TYPE_STARTSWITH:
						$statements[] = $n . ' LIKE ' . $value . '%';
						break;
					case FilterForm::LINK_TYPE_CONTAINS:
						$statements[] = $n . ' LIKE %' . $value . '%';
						break;
				}
			}

			if(sizeof($statements) > 1){
				// Create a sub where clause for these.
				$subwhere = new \Core\Datamodel\DatasetWhereClause();
				$subwhere->setSeparator('OR');
				foreach($statements as $s){
					$subwhere->addWhere($s);
				}
				// Add this sub clause to the main where clause.
				$factory->where($subwhere);
			}
			else{
				// A single command just gets added to the main clause.
				$factory->where($statements[0]);
			}
		}

		// Might as well update the count now, it can always be updated later.
		$this->setTotalCount($factory->count());
	}
示例#10
0
 /**
  * Method to cleanup expired IP addresses from the database.
  *
  * @return bool
  */
 public static function CleanupHook()
 {
     $factory = new \ModelFactory('IpBlacklistModel');
     $factory->where('expires > 0');
     // If they're set not to be deleted, don't purge them...
     $factory->where('expires <= ' . \CoreDateTime::Now('U', \Time::TIMEZONE_GMT));
     // DELETE!
     $count = $factory->count();
     if (!$count) {
         echo 'No records purged.';
         return true;
     }
     foreach ($factory->get() as $record) {
         /** @var $record \IpBlacklistModel */
         $record->delete();
     }
     echo "Purged " . $count . ' record' . ($count > 1 ? 's' : '') . ' successfully.';
     return true;
 }
	/**
	 * Form Handler for logging in.
	 *
	 * @static
	 *
	 * @param \Form $form
	 *
	 * @return bool|null|string
	 */
	public static function LoginHandler(\Form $form){
		/** @var \FormElement $e */
		$e = $form->getElement('email');
		/** @var \FormElement $p */
		$p = $form->getElement('pass');


		/** @var \UserModel $u */
		$u = \UserModel::Find(array('email' => $e->get('value')), 1);

		if(!$u){
			// Log this as a login attempt!
			$logmsg = 'Failed Login. Email not registered' . "\n" . 'Email: ' . $e->get('value') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg);
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_EMAIL_NOT_FOUND');
			return false;
		}

		if($u->get('active') == 0){
			// The model provides a quick cut-off for active/inactive users.
			// This is the control managed with in the admin.
			$logmsg = 'Failed Login. User tried to login before account activation' . "\n" . 'User: '******'email') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id'));
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_NOT_ACTIVE');
			return false;
		}
		elseif($u->get('active') == -1){
			// The model provides a quick cut-off for active/inactive users.
			// This is the control managed with in the admin.
			$logmsg = 'Failed Login. User tried to login after account deactivation.' . "\n" . 'User: '******'email') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login', $logmsg, null, $u->get('id'));
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_ACCOUNT_DEACTIVATED');
			return false;
		}

		try{
			/** @var \Core\User\AuthDrivers\datastore $auth */
			$auth = $u->getAuthDriver('datastore');
		}
		catch(Exception $e){
			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_PASSWORD_AUTH_DISABLED');
			return false;
		}


		// This is a special case if the password isn't set yet.
		// It can happen with imported users or if a password is invalidated.
		if($u->get('password') == ''){
			// Use the Nonce system to generate a one-time key with this user's data.
			$nonce = \NonceModel::Generate(
				'20 minutes',
				['type' => 'password-reset', 'user' => $u->get('id')]
			);

			$link = '/datastoreauth/forgotpassword?e=' . urlencode($u->get('email')) . '&n=' . $nonce;

			$email = new \Email();
			$email->setSubject('Initial Password Request');
			$email->to($u->get('email'));
			$email->assign('link', \Core\resolve_link($link));
			$email->assign('ip', REMOTE_IP);
			$email->templatename = 'emails/user/initialpassword.tpl';
			try{
				$email->send();
				\SystemLogModel::LogSecurityEvent('/user/initialpassword/send', 'Initial password request sent successfully', null, $u->get('id'));

				\Core\set_message('t:MESSAGE_INFO_USER_LOGIN_MUST_SET_NEW_PASSWORD_INSTRUCTIONS_HAVE_BEEN_EMAILED');
				return true;
			}
			catch(\Exception $e){
				\Core\ErrorManagement\exception_handler($e);
				\Core\set_message('t:MESSAGE_ERROR_USER_LOGIN_MUST_SET_NEW_PASSWORD_UNABLE_TO_SEND_EMAIL');
				return false;
			}
		}


		if(!$auth->checkPassword($p->get('value'))){

			// Log this as a login attempt!
			$logmsg = 'Failed Login. Invalid password' . "\n" . 'Email: ' . $e->get('value') . "\n";
			\SystemLogModel::LogSecurityEvent('/user/login/failed_password', $logmsg, null, $u->get('id'));

			// Also, I want to look up and see how many login attempts there have been in the past couple minutes.
			// If there are too many, I need to start slowing the attempts.
			$time = new \CoreDateTime();
			$time->modify('-5 minutes');

			$securityfactory = new \ModelFactory('SystemLogModel');
			$securityfactory->where('code = /user/login/failed_password');
			$securityfactory->where('datetime > ' . $time->getFormatted(\Time::FORMAT_EPOCH, \Time::TIMEZONE_GMT));
			$securityfactory->where('ip_addr = ' . REMOTE_IP);

			$attempts = $securityfactory->count();
			if($attempts > 4){
				// Start slowing down the response.  This should help deter brute force attempts.
				// (x+((x-7)/4)^3)-4
				sleep( ($attempts+(($attempts-7)/4)^3)-4 );
				// This makes a nice little curve with the following delays:
				// 5th  attempt: 0.85
				// 6th  attempt: 2.05
				// 7th  attempt: 3.02
				// 8th  attempt: 4.05
				// 9th  attempt: 5.15
				// 10th attempt: 6.52
				// 11th attempt: 8.10
				// 12th attempt: 10.05
			}

			$e->setError('t:MESSAGE_ERROR_USER_LOGIN_INCORRECT_PASSWORD');
			$p->set('value', '');
			return false;
		}


		if($form->getElementValue('redirect')){
			// The page was set via client-side javascript on the login page.
			// This is the most reliable option.
			$url = $form->getElementValue('redirect');
		}
		elseif(REL_REQUEST_PATH == '/user/login'){
			// If the user came from the registration page, get the page before that.
			$url = $form->referrer;
		}
		else{
			// else the registration link is now on the same page as the 403 handler.
			$url = REL_REQUEST_PATH;
		}

		// Well, record this too!
		\SystemLogModel::LogSecurityEvent('/user/login', 'Login successful (via password)', null, $u->get('id'));

		// yay...
		$u->set('last_login', \CoreDateTime::Now('U', \Time::TIMEZONE_GMT));
		$u->save();
		\Core\Session::SetUser($u);

		// Allow an external script to override the redirecting URL.
		$overrideurl = \HookHandler::DispatchHook('/user/postlogin/getredirecturl');
		if($overrideurl){
			$url = $overrideurl;
		}

		return $url;
	}
<?php

/**
 * Upgrade file to migrate the existing navigation widgets to the new schema, (edit and delete URLs)
 * 
 * @author Charlie Powell <*****@*****.**>
 * @date 20140228.1049
 * @package Blog
 */
$fac = new ModelFactory('WidgetModel');
$fac->where('baseurl LIKE /navigation/view/%');
foreach ($fac->get() as $model) {
    /** @var WidgetModel $model */
    $id = substr($model->get('baseurl'), 17);
    $model->set('baseurl', '/navigation/view/' . $id);
    $model->set('editurl', '/navigation/edit/' . $id);
    $model->set('deleteurl', '/navigation/delete/' . $id);
    $model->save();
}
示例#13
0
 /**
  * View controller for a blog article listing page.
  * This will only display articles under this same blog.
  *
  * @param BlogModel $blog
  */
 private function _viewBlog(BlogModel $blog)
 {
     $view = $this->getView();
     $page = $blog->getLink('Page');
     $request = $this->getPageRequest();
     $manager = \Core\user()->checkAccess('p:/blog/manage_all');
     $editor = \Core\user()->checkAccess($blog->get('manage_articles_permission ')) || $manager;
     $viewer = \Core\user()->checkAccess($blog->get('access')) || $editor;
     // Get the latest published article's update date.  This will be used for the blog updated timestamp.
     // (This doesn't have a whole lot of benefit above the ModelFactory, simply illustrating a different way to query data).
     $latest = \Core\Datamodel\Dataset::Init()->select('*')->table('page')->where('parenturl = ' . $blog->get('baseurl'))->where('published_status = published')->order('published DESC')->limit(1)->current();
     $filters = new FilterForm();
     $filters->haspagination = true;
     // Allow different type of requests to come in here.
     switch ($request->ctype) {
         case 'application/atom+xml':
             $view->templatename = 'pages/blog/view-blog.atom.tpl';
             $view->contenttype = $request->ctype;
             $view->mastertemplate = false;
             $filters->setLimit(200);
             break;
         case 'application/rss+xml':
             $view->templatename = 'pages/blog/view-blog.rss.tpl';
             $view->contenttype = $request->ctype;
             $view->mastertemplate = false;
             $filters->setLimit(200);
             break;
         default:
             $view->templatename = 'pages/blog/view-blog.tpl';
             $filters->setLimit(20);
             break;
     }
     $filters->load($this->getPageRequest());
     $factory = new ModelFactory('PageModel');
     if ($request->getParameter('q')) {
         $query = $request->getParameter('q');
         $factory->where(\Core\Search\Helper::GetWhereClause($request->getParameter('q')));
     } else {
         $query = null;
     }
     $factory->where('parenturl = ' . $blog->get('baseurl'));
     $factory->order('published DESC');
     if (!$editor) {
         // Limit these to published articles.
         $factory->where('published_status = published');
         // And where the published date is >= now.
         $factory->where('published <= ' . CoreDateTime::Now('U', Time::TIMEZONE_GMT));
     }
     $filters->applyToFactory($factory);
     $articles = $factory->get();
     $view->mode = View::MODE_PAGEORAJAX;
     $view->assign('blog', $blog);
     $view->assign('articles', $articles);
     $view->assign('page', $page);
     $view->assign('filters', $filters);
     $view->assign('canonical_url', \Core\resolve_link($blog->get('baseurl')));
     $view->assign('last_updated', $latest ? $latest['updated'] : 0);
     $view->assign('servername', SERVERNAME_NOSSL);
     $view->assign('editor', $editor);
     $view->assign('add_article_link', '/content/create?page_template=blog-article.tpl&parenturl=' . $blog->get('baseurl'));
     // Add the extra view types for this page
     $view->addHead('<link rel="alternate" type="application/atom+xml" title="' . $page->get('title') . ' Atom Feed" href="' . \Core\resolve_link($blog->get('baseurl')) . '.atom"/>');
     $view->addHead('<link rel="alternate" type="application/rss+xml" title="' . $page->get('title') . ' RSS Feed" href="' . \Core\resolve_link($blog->get('baseurl')) . '.rss"/>');
     if ($editor) {
         if ($blog->get('type') == 'remote') {
             $view->addControl('Import Feed', '/blog/import/' . $blog->get('id'), 'exchange');
         } else {
             $view->addControl('Add Article', '/content/create?page_template=blog-article.tpl&parenturl=' . $blog->get('baseurl'), 'add');
         }
     }
     if ($manager) {
         $view->addControl('Edit Blog', '/blog/update/' . $blog->get('id'), 'edit');
         $view->addControl('All Articles', '/admin/pages/?filter[parenturl]=' . $blog->get('baseurl'), 'tasks');
     }
     $view->addControl('RSS Feed', \Core\resolve_link($blog->get('baseurl')) . '.rss', 'rss');
     //$view->addControl('Atom Feed', \Core\resolve_link($blog->get('baseurl')) . '.atom', 'rss');
 }
示例#14
0
	/**
	 * Admin listing of all the users
	 *
	 * @return null|int
	 */
	public function admin(){
		$view = $this->getView();
		$request = $this->getPageRequest();

		if(!\Core\user()->checkAccess('p:/user/users/manage')){
			return View::ERROR_ACCESSDENIED;
		}

		$filters = new FilterForm();
		$filters->setName('user-admin');
		$filters->haspagination = true;
		$filters->hassort = true;
		$filters->setSortkeys(array('email', 'active', 'created','last_login'));
		$filters->addElement(
			'text',
			array(
				'title' => 'Email',
				'name' => 'email',
				'link' => FilterForm::LINK_TYPE_CONTAINS
			)
		);
		$filters->addElement(
			'select',
			array(
				'title' => 'Active',
				'name' => 'active',
				'options' => array('' => '-- All --', '0' => 'Inactive', '1' => 'Active'),
				'link' => FilterForm::LINK_TYPE_STANDARD,
			)
		);
		$filters->addElement(
			'select',
			array(
				'title' => 'Ever logged in?',
				'name' => 'last_login',
				'options' => array('' => 'Both', '1' => 'No', '2' => 'Yes'),
			)
		);

		$filters->load($request);
		$factory = new ModelFactory('UserModel');

		if($filters->get('last_login') == 1) {
			$factory->where('last_login = 0');
		}
		elseif($filters->get('last_login') == 2) {
			$factory->where('last_login > 0');
		}

		$filters->applyToFactory($factory);

		$users = $factory->get();

		$view->title = 'User Administration';
		$view->assign('enableavatar', (\ConfigHandler::Get('/user/enableavatar')));
		$view->assign('users', $users);
		$view->assign('filters', $filters);
		$view->addControl('Add User', '/user/register', 'add');
		$view->addControl('Import Users', '/user/import', 'upload-alt');

		return null;
	}
示例#15
0
	/**
	 * Display a listing of all widgets registered in the system.
	 */
	public function admin(){
		$view = $this->getView();
		$request = $this->getPageRequest();

		$viewer = \Core\user()->checkAccess('p:/core/widgets/manage');
		$manager = \Core\user()->checkAccess('p:/core/widgets/manage');
		if(!($viewer || $manager)){
			return View::ERROR_ACCESSDENIED;
		}

		// Build a list of create pages for all registered components.
		$components    = Core::GetComponents();
		$pages         = [];
		$skins         = [];
		$selected      = null;
		$selectedtype  = null;
		$baseurl       = null;
		$selectoptions = [];
		$links         = [];
		$theme         = ThemeHandler::GetTheme();
		$formtheme     = null;
		$formskin      = null;
		$formtemplate  = null;

		foreach($components as $c){
			/** @var Component_2_1 $c */

			$viewdir = $c->getViewSearchDir();
			if($viewdir){
				$dirlen = strlen($viewdir);
				$component = $c->getName();

				$dh = \Core\Filestore\Factory::Directory($viewdir);
				//$pagetplfiles = $dh->ls('tpl', true);
				$pagetplfiles = $dh->ls(null, true);

				// not sure why getFilename(path) isn't working as expected, but this works too.
				foreach($pagetplfiles as $obj){

					// I don't want directories.
					if($obj instanceof \Core\Filestore\Directory) continue;

					/** @var $obj \Core\Filestore\File */
					$file = substr($obj->getFilename(), $dirlen);

					// Since this is a template, it may actually be in a different location than where the package maintainer put it.
					// ie: user template user/templates/pages/user/view.tpl may be installed to themes/myawesometheme/pages/user/view.tpl instead.
					$tpl = Core\Templates\Template::Factory($file);

					if($tpl->hasWidgetAreas()){
						$pagetitle = $file;
						if(strpos($pagetitle, 'pages/') === 0){
							$pagetitle = substr($pagetitle, 6);
						}
						// Replace directory slashes with a space
						$pagetitle = str_replace(['/', '-'], ' ', $pagetitle);
						// Capitalize them
						$pagetitle = ucwords($pagetitle);
						// And trim off the ".tpl" suffix.
						$pagetitle = substr($pagetitle, 0, -4);
						$pages[$file] = $pagetitle;
					}
				}
			}

			foreach($c->getXML()->getElements('/widgets/widgetcreate') as $node){
				/** @var DOMElement $node */

				if($node->getAttribute('baseurl')){
					$nodebaseurl = $node->getAttribute('baseurl');
					$image = '';
				}
				elseif($node->getAttribute('class')){
					/** @var Widget_2_1 $obj */
					$obj = Widget_2_1::Factory($node->getAttribute('class'));
					$nodebaseurl = '/widget/create?class=' . $node->getAttribute('class');
					if($obj){
						$image = $obj->getPreviewImage();
					}
					else{
						\Core\set_message('Invalid "widgetcreate" found in ' .$node->getAttribute('class') . ', ' . $node->getAttribute('title'), 'error');
						$image = '';
					}
				}
				else{
					\Core\set_message('Invalid "widgetcreate" found in ' . $c->getName() . ', ' . $node->getAttribute('title'), 'error');
					continue;
				}

				$links[] = [
					'baseurl' => $nodebaseurl,
					'title' => $node->getAttribute('title'),
				    'preview' => $image,
				];
			}
		}

		// Build the array of skins for the current theme
		$themeskins  = $theme->getSkins();
		$defaultskin = null;
		foreach($themeskins as $dat){

			$skins[ 'skins/' . $dat['file'] ] = $dat['title'];

			if($dat['default']){
				$defaultskin = 'skins/' . $dat['file'];
			}
		}

		// Now that the various templates have been loaded into a flat array, I need to sort them.
		asort($pages);
		asort($skins);

		foreach($skins as $k => $v){
			$selectoptions[ $k ] = 'Skin: ' . $v;
		}
		foreach($pages as $k => $v){
			$selectoptions[ $k ] = 'Page: ' . $v;
		}

		if($request->getParameter('baseurl')){
			// It's a URL-specific request, lookup which template that page used last.
			$baseurl  = $request->getParameter('baseurl');
			$page     = PageModel::Construct($baseurl);

			if(!isset($pages[ $page->get('last_template') ])){
				\Core\set_message('Requested page template does not seem to contain any widget areas.', 'error');
				\Core\go_back();
			}

			$selected = $page->get('last_template');
			$selectedtype = 'url';
			$formtemplate = $selected;
		}
		elseif($request->getParameter('template')){
			$selected = $request->getParameter('template');

			if(isset($pages[ $selected ])){
				$selectedtype = 'page';
				$formtemplate = $selected;
			}
			else{
				$selectedtype = 'skin';
				$formtheme = $theme->getKeyName();
				$formskin  = $selected;
			}
		}
		else{
			// Just use the default theme skin.
			$selected = $defaultskin;
			$selectedtype = 'skin';$formtheme = $theme->getKeyName();
			$formskin  = $selected;
		}

		$template     = \Core\Templates\Template::Factory($selected);
		$areas        = $template->getWidgetAreas();
		$installables = [0 => ''];

		foreach($areas as $k => $dat){
			// Ensure that each area has a widgets array, (even if it's empty)
			$areas[$k]['widgets'] = [];
			$installables[] = $dat['installable'];
		}
		$installables = array_unique($installables);

		$factory = new ModelFactory('WidgetInstanceModel');
		$factory->order('weight');
		if(Core::IsComponentAvailable('multisite') && MultiSiteHelper::IsEnabled()){
			$factory->whereGroup('or', ['site = -1', 'site = ' . MultiSiteHelper::GetCurrentSiteID()]);
		}

		if($selectedtype == 'skin'){
			// First, the skin-level where clause.
			$skinwhere = new Core\Datamodel\DatasetWhereClause();
			$skinwhere->setSeparator('AND');
			//$skinwhere->addWhere('theme = ' . $theme->getKeyName());
			$skinwhere->addWhere('template = ' . $selected);
			$factory->where($skinwhere);
		}
		elseif($selectedtype == 'page'){
			$factory->where('template = ' . $selected);
		}
		elseif($selectedtype == 'url'){
			$factory->where('page_baseurl = ' . $baseurl);
		}
		else{
			\Core\set_message('Invalid/unknown template type', 'error');
			\Core\go_back();
		}


		foreach($factory->get() as $wi){
			/** @var $wi WidgetInstanceModel */

			$a = $wi->get('widgetarea');
			$areas[$a]['widgets'][] = $wi;
		}

		$available = WidgetModel::Find(['installable IN ' . implode(', ', $installables)]);

		/*
		$table = new Core\ListingTable\Table();
		$table->setName('/admin/widgets');
		$table->setModelName('WidgetModel');
		// Add in all the columns for this listing table.
		$table->addColumn('Title', 'title');
		if(Core::IsComponentAvailable('enterprise') && MultiSiteHelper::IsEnabled() && \Core\user()->checkAccess('g:admin')){
			$table->addColumn('Site', 'site', false);
			$ms = true;
		}
		else{
			$ms = false;
		}
		$table->getModelFactory()->where('installable IN ' . implode(', ', $installables));
		$table->addColumn('Base URL', 'baseurl');
		$table->addColumn('Installable', 'installable');
		$table->addColumn('Created', 'created');

		$table->loadFiltersFromRequest();
		*/

		$view->mastertemplate = 'admin';
		$view->title = 'All Widgets';
		//$view->assign('table', $table);
		$view->assign('available_widgets', $available);
		$view->assign('links', $links);
		$view->assign('manager', $manager);
		$view->assign('theme', $formtheme);
		$view->assign('skin', $formskin);
		$view->assign('template', $selected);
		$view->assign('page_template', $formtemplate);
		$view->assign('page_baseurl', $baseurl);
		$view->assign('options', $selectoptions);
		$view->assign('selected', $selected);
		$view->assign('areas', $areas);
		//$view->assign('multisite', $ms);
	}
示例#16
0
<?php

/**
 * Upgrade file to add control links for content pages.
 * 
 * @author Charlie Powell <*****@*****.**>
 * @date 20140228.1049
 * @package Content
 */
$fac = new ModelFactory('PageModel');
$fac->where('baseurl LIKE /content/view/%');
foreach ($fac->get() as $model) {
    /** @var PageModel $model */
    $base = '/content/view/';
    $id = substr($model->get('baseurl'), strlen($base));
    $model->set('component', 'content');
    $model->set('baseurl', '/content/view/' . $id);
    $model->set('editurl', '/content/edit/' . $id);
    $model->set('deleteurl', '/content/delete/' . $id);
    $model->save();
}
示例#17
0
<?php

/**
 * Upgrade file to add control links for blogs and to migrated the blog articles to the content application.
 * 
 * @author Charlie Powell <*****@*****.**>
 * @date 20140228.1049
 * @package Blog
 */
$fac = new ModelFactory('PageModel');
$fac->where('baseurl LIKE /blog/view/%');
foreach ($fac->get() as $model) {
    /** @var PageModel $model */
    $model->set('component', 'blog');
    $model->set('editurl', str_replace('/blog/view/', '/blog/update/', $model->get('baseurl')));
    $model->set('deleteurl', str_replace('/blog/view/', '/blog/delete/', $model->get('baseurl')));
    $model->save();
}
//
// This is how to update all pages and their necessary values, (useful for a template for other components)
//
//$fac = new ModelFactory('PageModel');
//$fac->where('baseurl LIKE /blog/article/view/%');
//foreach($fac->get() as $model){
//	/** @var PageModel $model */
//	$model->set('component', 'blog');
//	$model->set('editurl', str_replace('/blog/article/view/', '/blog/article/update/', $model->get('baseurl')));
//	$model->set('deleteurl', str_replace('/blog/article/view/', '/blog/article/delete/', $model->get('baseurl')));
//	$model->save();
//}
$fac = new ModelFactory('BlogArticleModel');
示例#18
0
	public function sitemap(){
		$view  = $this->getView();
		$req   = $this->getPageRequest();

		// Give me every registered (public) page!
		$factory = new ModelFactory('PageModel');
		$factory->where('indexable = 1');
		$factory->order('title');
		// Multisite?
		if(Core::IsComponentAvailable('multisite') && MultiSiteHelper::IsEnabled()){
			$factory->whereGroup(
				'OR',
				array(
					'site = ' . MultiSiteHelper::GetCurrentSiteID(),
					'site = -1'
				)
			);
			$site = MultiSiteHelper::GetCurrentSiteID();
		}
		else{
			$site = null;
		}

		// Run this through the streamer, just in case there are a lot of pages...
		$stream = new \Core\Datamodel\DatasetStream($factory->getDataset());

		$user = \Core\user();
		$toshow = array();
		while(($record = $stream->getRecord())){
			if(!$user->checkAccess( $record['access'] )){
				// Skip any further operations if the user does not have access to this page
				continue;
			}

			if($record['published_status'] != 'published'){
				// Skip any further operations if the page isn't even marked as published.
				continue;
			}

			$page = new PageModel();
			$page->_loadFromRecord($record);

			if(!$page->isPublished()){
				// Skip out if the page is not marked as published.
				// This has extended checks other than simply if the status is set as "published",
				// such as publish date and expiration date.
				continue;
			}

			$toshow[] = $page;
		}

		// Anything else?
		$extra = HookHandler::DispatchHook('/sitemap/getlisting');
		$toshow = array_merge($toshow, $extra);

		// This page allows for a few content types.
		switch($req->ctype){
			case View::CTYPE_XML:
				$view->contenttype = View::CTYPE_XML;
				break;
			case View::CTYPE_HTML:
				$view->contenttype = View::CTYPE_HTML;
				break;
		}

		$view->title = 'Sitemap';
		$view->assign('pages', $toshow);
		$view->assign('site', $site);
	}
示例#19
0
<?php
/**
 * Upgrade script to convert all the JSON-encoded user groups and transpose them to the new UserUserGroup object.
 *
 * @package Core
 */

$fac = new ModelFactory('UserModel');
$fac->where('groups != ');

while(($user = $fac->getNext())){
	/** @var UserModel $user */
	// datamodel backed users have the groups listed in their column "groups".
	$g = json_decode($user->get('groups'), true);
	if(!$g) $g = array();

	$gids = [];

	foreach($g as $gid){
		if(is_array($gid)){
			$gids = array_merge($gids, $gid);
		}
		else{
			$gids[] = $gid;
		}
	}
	$gids = array_unique($gids);

	$user->setGroups($gids);
	$user->save();
}
示例#20
0
	/**
	 * Perform a model search on the records of this Model.
	 *
	 * @param string $query The base query to search
	 * @param array $where  Any additional where parameters to add onto the factory
	 *
	 * @return array An array of ModelResult objects.
	 */
	public static function Search($query, $where = []){
		$ret = [];

		// If this object does not support searching, simply return an empty array.
		$ref = new ReflectionClass(get_called_class());

		if(!$ref->getProperty('HasSearch')->getValue()){
			return $ret;
		}

		$fac = new ModelFactory(get_called_class());

		if(sizeof($where)){
			$fac->where($where);
		}

		if($ref->getProperty('HasDeleted')->getValue()){
			$fac->where('deleted = 0');
		}

		$fac->where(\Core\Search\Helper::GetWhereClause($query));
		foreach($fac->get() as $m){
			/** @var Model $m */
			$sr = new \Core\Search\ModelResult($query, $m);

			// This may happen since the where clause can be a little open-ended.
			if($sr->relevancy < 1) continue;
			$sr->title = $m->getLabel();
			$sr->link  = $m->get('baseurl');

			$ret[] = $sr;
		}

		// Sort the results before returning them.
		// Because otherwise, what's the point of a search algorithm?!?
		usort($ret, function($a, $b) {
			/** @var $a Core\Search\ModelResult */
			/** @var $b Core\Search\ModelResult */
			return $a->relevancy < $b->relevancy;
		});

		return $ret;
	}
示例#21
0
	/**
	 * Get the page model for the current page.
	 *
	 * @return PageModel
	 */
	public function getPageModel() {
		if ($this->_pagemodel === null) {
			$uri = $this->uriresolved;


			$pagefac = new ModelFactory('PageModel');
			$pagefac->where('rewriteurl = ' . $uri);
			//$pagefac->where('fuzzy = 0');
			$pagefac->limit(1);
			if(Core::IsComponentAvailable('multisite') && MultiSiteHelper::IsEnabled()){
				$pagefac->whereGroup('OR', array('site = -1', 'site = ' . MultiSiteHelper::GetCurrentSiteID()));
			}

			$p = $pagefac->get();

			// Split this URL, it'll be used somewhere.
			$pagedat = $this->splitParts();

			if ($p) {
				// :) Found it
				$this->_pagemodel = $p;
			}
			elseif ($pagedat && isset($pagedat['baseurl'])) {
				// Is this even a valid controller?
				// This will allow a page to be called with it being in the pages database.
				$p = new PageModel($pagedat['baseurl']);
				if(!$p->exists()){
					$p->set('rewriteurl', $pagedat['rewriteurl']);
				}
				$this->_pagemodel = $p;
			}
			else {
				// No page in the database and no valid controller... sigh
				$this->_pagemodel = new PageModel();
			}

			//var_dump($p); die();

			// Make sure all the parameters from both standard GET and core parameters are tacked on.
			if ($pagedat && $pagedat['parameters']) {
				foreach ($pagedat['parameters'] as $k => $v) {
					$this->_pagemodel->setParameter($k, $v);
				}
			}
			if (is_array($_GET)) {
				foreach ($_GET as $k => $v) {
					if (is_numeric($k)) continue;
					$this->_pagemodel->setParameter($k, $v);
				}
			}
		}

		return $this->_pagemodel;
	}
/**
 * @todo Finish documentation of smarty_function_widgetarea
 * @param array  $params  Associative (and/or indexed) array of smarty parameters passed in from the template
 * @param Smarty_Internal_Template $smarty  Parent Smarty template object
 *
 * @return string|void
 */
function smarty_function_widgetarea($params, $smarty) {
	// Get all widgets set to load in this area.

	$body     = '';
	$baseurl  = PageRequest::GetSystemRequest()->getBaseURL();
	$template = $smarty->template_resource;
	$tmpl     = $smarty->getTemplateVars('__core_template');
	$topview  = ($tmpl instanceof \Core\Templates\TemplateInterface) ? $tmpl->getView() : \Core\view();

	$parameters  = [];
	$name        = null;
	$installable = null;
	$assign      = null;
	foreach($params as $k => $v){
		switch($k){
			case 'name':
				$name = $v;
				break;
			case 'installable':
				$installable = $v;
				break;
			case 'assign':
				$assign = $v;
				break;
			default:
				$parameters[$k] = $v;
				break;
		}
	}

	// I need to resolve the page template down to the base version in order for the lookup to work.
	foreach(Core\Templates\Template::GetPaths() as $base){
		if(strpos($template, $base) === 0){
			$template = substr($template, strlen($base));
			break;
		}
	}

	// Given support for page-level widgets, this logic gets slightly more difficult...
	$factory = new ModelFactory('WidgetInstanceModel');
	$factory->order('weight');
	if(Core::IsComponentAvailable('multisite') && MultiSiteHelper::IsEnabled()){
		$factory->whereGroup('or', ['site = -1', 'site = ' . MultiSiteHelper::GetCurrentSiteID()]);
	}

	$subwhere = new Core\Datamodel\DatasetWhereClause();
	$subwhere->setSeparator('OR');

	// First, the skin-level where clause.
	$skinwhere = new Core\Datamodel\DatasetWhereClause();
	$skinwhere->setSeparator('AND');
	$skinwhere->addWhere('template = ' . $template);
	$skinwhere->addWhere('widgetarea = ' . $name);
	$subwhere->addWhere($skinwhere);

	// And second, the page-level where clause.
	if($baseurl){
		$pagewhere = new Core\Datamodel\DatasetWhereClause();
		$pagewhere->setSeparator('AND');
		$pagewhere->addWhere('page_baseurl = ' . $baseurl);
		$pagewhere->addWhere('widgetarea = ' . $name);
		$subwhere->addWhere($pagewhere);
	}

	$factory->where($subwhere);


	$widgetcount = 0;
	try{
		$widgets = $factory->get();
	}
	catch(Exception $e){
		if(DEVELOPMENT_MODE){
			$body .= '<p class="message-error">Exception while trying to load widget area ' . $name . '!</p>';
			$body .= '<pre class="xdebug-var-dump">' . $e->getMessage() . '</pre>';
		}
		else{
			\Core\ErrorManagement\exception_handler($e, false);
		}
		$widgets = [];
		++$widgetcount;
	}


	foreach ($widgets as $wi) {
		/** @var $wi WidgetInstanceModel */
		// User cannot access this widget? Don't display it...
		if(!\Core\user()){
			continue;
		}
		if (!\Core\user()->checkAccess($wi->get('access'))){
			continue;
		}

		if($installable){
			$wi->set('installable', $installable);
		}
		$view = $wi->execute($parameters);

		// Some widgets may return simply a blank string.  Those should just be ignored.
		if ($view == ''){
			continue;
		}

		// If it's just a string, return that.
		if (is_string($view)) {
			$contents = $view;
		}
		elseif($view->error == View::ERROR_NOERROR){
			// Ensure that the widget's View knows it's linked to a parent!
			$view->parent = $topview;

			$contents = $view->fetch();
		}
		else{
			$contents = 'Error displaying widget [' . $wi->get('baseurl') . '], returned error [' . $view->error . ']';
		}
		++$widgetcount;
		
		// Does this widget have controls attached to it?
		$widget = $wi->getWidget();
		if($widget->controls instanceof ViewControls && $widget->controls->hasLinks()){
			$contents = '<div class="widget-controls-wrapper">' .
				'<menu id="widget-controls-' . $wi->get('id') . '">' . 
				$widget->controls->fetch() . 
				'</menu>' . 
				'</div>' .
				$contents;
		}

		$body .= '<div class="widget">' . $contents . '</div>';
	}

	// Do some sanitizing for the css data
	$class = 'widgetarea-' . strtolower(str_replace(' ', '', $name));

	$html = '<div class="widgetarea ' . $class . '" widgetarea="' . $name . '">' . $body . '</div>';

	// No widgets, no inner content!
	if($widgetcount == 0){
		$html = '';
	}

	if($assign){
		$smarty->assign($assign, $html);
	}
	else{
		return $html;
	}
}