1<?php
2/**
3 * Extension of the Horde_Permission class for storing permission
4 * information in the SQL driver.
5 *
6 * Copyright 2008-2017 Horde LLC (http://www.horde.org/)
7 *
8 * See the enclosed file COPYING for license information (LGPL). If you
9 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
10 *
11 * @author   Duck <duck@obala.net>
12 * @category Horde
13 * @package  Perms
14 */
15class Horde_Perms_Permission_Sql extends Horde_Perms_Permission
16{
17    /**
18     * The string permission id.
19     *
20     * @var string
21     */
22    protected $_id;
23
24    /**
25     * Cache object.
26     *
27     * @var Horde_Cache
28     */
29    protected $_cache;
30
31    /**
32     * Database handle for saving changes.
33     *
34     * @var Horde_Db_Adapter
35     */
36    protected $_db;
37
38    /**
39     * Tasks to run on serialize().
40     *
41     * @return array  Parameters that are stored.
42     */
43    public function __sleep()
44    {
45        return array_diff(array_keys(get_class_vars(__CLASS__)), array('_cache', '_db'));
46    }
47
48    /**
49     * Sets the helper functions within the object.
50     *
51     * @param Horde_Cache $cache    The cache object.
52     * @param Horde_Db_Adapter $db  The database object.
53     */
54    public function setObs(Horde_Cache $cache, Horde_Db_Adapter $db)
55    {
56        $this->_cache = $cache;
57        $this->_db = $db;
58    }
59
60    /**
61     * Get permission ID.
62     *
63     * @return TODO
64     */
65    public function getId()
66    {
67        return $this->_id;
68    }
69
70    /**
71     * Set permission id.
72     *
73     * @param string $id  Permission ID.
74     */
75    public function setId($id)
76    {
77        $this->_id = $id;
78    }
79
80    /**
81     * Saves any changes to this object to the backend permanently. New
82     * objects are added instead.
83     *
84     * @throws Horde_Perms_Exception
85     */
86    public function save()
87    {
88        if (!isset($this->_db)) {
89            throw new Horde_Perms_Exception('Cannot save because the DB instances has not been set in this object.');
90        }
91
92        $name = $this->getName();
93        if (empty($name)) {
94            throw new Horde_Perms_Exception('Permission names must be non-empty');
95        }
96
97        $query = 'UPDATE horde_perms SET perm_data = ? WHERE perm_id = ?';
98        $params = array(serialize($this->data), $this->getId());
99
100        try {
101            $this->_db->update($query, $params);
102        } catch (Horde_Db_Exception $e) {
103            throw new Horde_Perms_Exception($e);
104        }
105
106        $this->_cache->expire('perm_sql_' . $this->_cacheVersion . $name);
107        $this->_cache->expire('perm_sql_exists_' . $this->_cacheVersion . $name);
108    }
109
110}
111