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