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