1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20:
21: App::uses('AclNode', 'Model');
22: App::uses('Hash', 'Utility');
23:
24: 25: 26: 27: 28: 29: 30: 31:
32: class AclBehavior extends ModelBehavior {
33:
34: 35: 36: 37: 38:
39: protected $_typeMaps = array('requester' => 'Aro', 'controlled' => 'Aco', 'both' => array('Aro', 'Aco'));
40:
41: 42: 43: 44: 45: 46: 47:
48: public function setup(Model $model, $config = array()) {
49: if (isset($config[0])) {
50: $config['type'] = $config[0];
51: unset($config[0]);
52: }
53: $this->settings[$model->name] = array_merge(array('type' => 'controlled'), $config);
54: $this->settings[$model->name]['type'] = strtolower($this->settings[$model->name]['type']);
55:
56: $types = $this->_typeMaps[$this->settings[$model->name]['type']];
57:
58: if (!is_array($types)) {
59: $types = array($types);
60: }
61: foreach ($types as $type) {
62: $model->{$type} = ClassRegistry::init($type);
63: }
64: if (!method_exists($model, 'parentNode')) {
65: trigger_error(__d('cake_dev', 'Callback parentNode() not defined in %s', $model->alias), E_USER_WARNING);
66: }
67: }
68:
69: 70: 71: 72: 73: 74: 75: 76: 77:
78: public function node(Model $model, $ref = null, $type = null) {
79: if (empty($type)) {
80: $type = $this->_typeMaps[$this->settings[$model->name]['type']];
81: if (is_array($type)) {
82: trigger_error(__d('cake_dev', 'AclBehavior is setup with more then one type, please specify type parameter for node()'), E_USER_WARNING);
83: return null;
84: }
85: }
86: if (empty($ref)) {
87: $ref = array('model' => $model->name, 'foreign_key' => $model->id);
88: }
89: return $model->{$type}->node($ref);
90: }
91:
92: 93: 94: 95: 96: 97: 98:
99: public function afterSave(Model $model, $created) {
100: $types = $this->_typeMaps[$this->settings[$model->name]['type']];
101: if (!is_array($types)) {
102: $types = array($types);
103: }
104: foreach ($types as $type) {
105: $parent = $model->parentNode();
106: if (!empty($parent)) {
107: $parent = $this->node($model, $parent, $type);
108: }
109: $data = array(
110: 'parent_id' => isset($parent[0][$type]['id']) ? $parent[0][$type]['id'] : null,
111: 'model' => $model->name,
112: 'foreign_key' => $model->id
113: );
114: if (!$created) {
115: $node = $this->node($model, null, $type);
116: $data['id'] = isset($node[0][$type]['id']) ? $node[0][$type]['id'] : null;
117: }
118: $model->{$type}->create();
119: $model->{$type}->save($data);
120: }
121: }
122:
123: 124: 125: 126: 127: 128:
129: public function afterDelete(Model $model) {
130: $types = $this->_typeMaps[$this->settings[$model->name]['type']];
131: if (!is_array($types)) {
132: $types = array($types);
133: }
134: foreach ($types as $type) {
135: $node = Hash::extract($this->node($model, null, $type), "0.{$type}.id");
136: if (!empty($node)) {
137: $model->{$type}->delete($node);
138: }
139: }
140: }
141:
142: }
143: