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 * craeted by the currently logged in user only.
14 *
15 * @package FrameworkOnFramework
16 * @since 2.1
17 */
18 class FOFModelBehaviorPrivate 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 $createdField = $table->getColumnAlias('created_by');
40
41 // Make sure the access field actually exists
42 if (!in_array($createdField, $table->getKnownFields()))
43 {
44 return;
45 }
46
47 // Get the current user's id
48 $user_id = FOFPlatform::getInstance()->getUser()->id;
49
50 // And filter the query output by the user id
51 $db = FOFPlatform::getInstance()->getDbo();
52
53 $alias = $model->getTableAlias();
54 $alias = $alias ? $db->qn($alias) . '.' : '';
55
56 $query->where($alias . $db->qn($createdField) . ' = ' . $db->q($user_id));
57 }
58
59 /**
60 * The event runs after FOFModel has called FOFTable and retrieved a single
61 * item from the database. It is used to apply automatic filters.
62 *
63 * @param FOFModel &$model The model which was called
64 * @param FOFTable &$record The record loaded from the databae
65 *
66 * @return void
67 */
68 public function onAfterGetItem(&$model, &$record)
69 {
70 if ($record instanceof FOFTable)
71 {
72 $keyName = $record->getKeyName();
73 if ($record->$keyName === null)
74 {
75 return;
76 }
77
78 $fieldName = $record->getColumnAlias('created_by');
79
80 // Make sure the field actually exists
81 if (!in_array($fieldName, $record->getKnownFields()))
82 {
83 return;
84 }
85
86 $user_id = FOFPlatform::getInstance()->getUser()->id;
87
88 if ($record->$fieldName != $user_id)
89 {
90 $record = null;
91 }
92 }
93 }
94 }
95