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 * that are enabled.
14 *
15 * @package FrameworkOnFramework
16 * @since 2.1
17 */
18 class FOFModelBehaviorEnabled 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 enabled field
38 $table = $model->getTable();
39 $enabledField = $table->getColumnAlias('enabled');
40
41 // Make sure the field actually exists
42 if (!in_array($enabledField, $table->getKnownFields()))
43 {
44 return;
45 }
46
47 // Filter by enabled fields only
48 $db = FOFPlatform::getInstance()->getDbo();
49
50 // Alias
51 $alias = $model->getTableAlias();
52 $alias = $alias ? $db->qn($alias) . '.' : '';
53
54 $query->where($alias . $db->qn($enabledField) . ' = ' . $db->q(1));
55 }
56
57 /**
58 * The event runs after FOFModel has called FOFTable and retrieved a single
59 * item from the database. It is used to apply automatic filters.
60 *
61 * @param FOFModel &$model The model which was called
62 * @param FOFTable &$record The record loaded from the databae
63 *
64 * @return void
65 */
66 public function onAfterGetItem(&$model, &$record)
67 {
68 if ($record instanceof FOFTable)
69 {
70 $fieldName = $record->getColumnAlias('enabled');
71
72 // Make sure the field actually exists
73 if (!in_array($fieldName, $record->getKnownFields()))
74 {
75 return;
76 }
77
78 if ($record->$fieldName != 1)
79 {
80 $record = null;
81 }
82 }
83 }
84 }
85