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