1<?php
2/**
3 * @package     FrameworkOnFramework
4 * @subpackage  model
5 * @copyright   Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
6 * @license     GNU General Public License version 2 or later; see LICENSE.txt
7 * @note        This file has been modified by the Joomla! Project and no longer reflects the original work of its author.
8 */
9
10// Protect from unauthorized access
11defined('FOF_INCLUDED') or die;
12
13/**
14 * FrameworkOnFramework model behavior class to filter front-end access to items
15 * based on the viewing access levels.
16 *
17 * @package  FrameworkOnFramework
18 * @since    2.1
19 */
20class FOFModelBehaviorAccess extends FOFModelBehavior
21{
22	/**
23	 * This event runs after we have built the query used to fetch a record
24	 * list in a model. It is used to apply automatic query filters.
25	 *
26	 * @param   FOFModel        &$model  The model which calls this event
27	 * @param   FOFDatabaseQuery  &$query  The model which calls this event
28	 *
29	 * @return  void
30	 */
31	public function onAfterBuildQuery(&$model, &$query)
32	{
33		// This behavior only applies to the front-end.
34		if (!FOFPlatform::getInstance()->isFrontend())
35		{
36			return;
37		}
38
39		// Get the name of the access field
40		$table       = $model->getTable();
41		$accessField = $table->getColumnAlias('access');
42
43		// Make sure the field actually exists
44		if (!in_array($accessField, $table->getKnownFields()))
45		{
46			return;
47		}
48
49		$model->applyAccessFiltering(null);
50	}
51
52	/**
53	 * The event runs after FOFModel has called FOFTable and retrieved a single
54	 * item from the database. It is used to apply automatic filters.
55	 *
56	 * @param   FOFModel  &$model   The model which was called
57	 * @param   FOFTable  &$record  The record loaded from the database
58	 *
59	 * @return  void
60	 */
61	public function onAfterGetItem(&$model, &$record)
62	{
63		if ($record instanceof FOFTable)
64		{
65			$fieldName = $record->getColumnAlias('access');
66
67			// Make sure the field actually exists
68			if (!in_array($fieldName, $record->getKnownFields()))
69			{
70				return;
71			}
72
73			// Get the user
74			$user = FOFPlatform::getInstance()->getUser();
75
76			// Filter by authorised access levels
77			if (!in_array($record->$fieldName, $user->getAuthorisedViewLevels()))
78			{
79				$record = null;
80			}
81		}
82	}
83}
84