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 */
8 // Protect from unauthorized access
9 defined('FOF_INCLUDED') or die;
10
11 /**
12 * FrameworkOnFramework model behavior class to filter front-end access to items
13 * based on the viewing access levels.
14 *
15 * @package FrameworkOnFramework
16 * @since 2.1
17 */
18 class FOFModelBehaviorAccess extends FOFModelBehavior
19 {
20 /**
21 * This event runs after we have built the query used to fetch a record
22 * list in a model. It is used to apply automatic query filters.
23 *
24 * @param FOFModel &$model The model which calls this event
25 * @param FOFDatabaseQuery &$query The model which calls this event
26 *
27 * @return void
28 */
29 public function onAfterBuildQuery(&$model, &$query)
30 {
31 // This behavior only applies to the front-end.
32 if (!FOFPlatform::getInstance()->isFrontend())
33 {
34 return;
35 }
36
37 // Get the name of the access field
38 $table = $model->getTable();
39 $accessField = $table->getColumnAlias('access');
40
41 // Make sure the field actually exists
42 if (!in_array($accessField, $table->getKnownFields()))
43 {
44 return;
45 }
46
47 $model->applyAccessFiltering(null);
48 }
49
50 /**
51 * The event runs after FOFModel has called FOFTable and retrieved a single
52 * item from the database. It is used to apply automatic filters.
53 *
54 * @param FOFModel &$model The model which was called
55 * @param FOFTable &$record The record loaded from the databae
56 *
57 * @return void
58 */
59 public function onAfterGetItem(&$model, &$record)
60 {
61 if ($record instanceof FOFTable)
62 {
63 $fieldName = $record->getColumnAlias('access');
64
65 // Make sure the field actually exists
66 if (!in_array($fieldName, $record->getKnownFields()))
67 {
68 return;
69 }
70
71 // Get the user
72 $user = FOFPlatform::getInstance()->getUser();
73
74 // Filter by authorised access levels
75 if (!in_array($record->$fieldName, $user->getAuthorisedViewLevels()))
76 {
77 $record = null;
78 }
79 }
80 }
81 }
82