-
Notifications
You must be signed in to change notification settings - Fork 0
/
Data.class.php
executable file
·441 lines (415 loc) · 19 KB
/
Data.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<?php
abstract class Data{
//protected static function performSearch($subject, $predicate);
//protected static function initialize($options);
//static $fields
protected abstract function performLoad($id, $field);
protected abstract function performSave();
//static implementations
public static $empty_field_mode = 'null'; //null, notice, exception
public static $registry = array(); // uuid, integer
public static $core_fields = array('id', 'record_status', 'modification_time', 'creation_time', 'modified_by');
public static $core_options = array(
'id' => array(
'type' => 'integer',
'identifier' => 'true'
),
'record_status',
'modification_time' => array(
'type' => 'instant'
),
'creation_time' => array(
'type' => 'instant'
),
'modified_by' => array(
'type' => 'integer'
)
);
protected static function parseWhere($whereClause){
$results = array();
$inQuote = false;
$quoteChar = '';
$quotation = '';
$result = array();
$quoteChars = array('\'', '"');
$breakingChars = array(' ', '=', '>', '<', '!');
for($lcv=0; $lcv<strlen($whereClause); $lcv++){
if($inQuote){
if($whereClause[$lcv] == $quoteChar){ //close a quote
$result[sizeof($result)-1] .= '\''.$quotation.'\'';
$inQuote = false;
$quotation = '';
}else{
$quotation .= $whereClause[$lcv];
}
}else{
if(!isset($result[0])) $result[0] = ''; //init a new subject if we have nothing
if($whereClause[$lcv] == ' ' ||
(!isset($result[1]) && in_array($whereClause[$lcv], $breakingChars)) ||
(isset($result[1]) && !isset($result[2]) && !in_array($whereClause[$lcv], $breakingChars))
){
if(isset($result[2]) && strtolower(substr($whereClause, $lcv, 4)) == 'and '){
$results[] = $result;
$result = array();
$lcv += 3; //skip the 'and' chars
continue;
}
if(isset($result[0]) && $result[0] == '') continue; //don't advance if we have nothing yet (leading spaces)
if(!isset($result[1])){
$result[1] = '';
}else if(!isset($result[2])){
$result[2] = '';
}
}
if(in_array($whereClause[$lcv], $quoteChars)){ //open a quote
$quoteChar = $whereClause[$lcv];
$inQuote = true;
$quotation = '';
}else{
$result[sizeof($result)-1] .= $whereClause[$lcv];
}
}
}
if($quotation != '') $result[2] = $quotation;
$results[] = $result;
return $results;
}
protected static function convertArrayToSearch($datatype, $query){
return $query;
//todo: implement... not really a priority
}
public static function generateUUID(){
$uuid = array(
'time_low' => 0,
'time_mid' => 0,
'time_hi' => 0,
'clock_seq_hi' => 0,
'clock_seq_low' => 0,
'node' => array()
);
$uuid['time_low'] = mt_rand(0, 0xffff) + (mt_rand(0, 0xffff) << 16);
$uuid['time_mid'] = mt_rand(0, 0xffff);
$uuid['time_hi'] = (4 << 12) | (mt_rand(0, 0x1000));
$uuid['clock_seq_hi'] = (1 << 7) | (mt_rand(0, 128));
$uuid['clock_seq_low'] = mt_rand(0, 255);
for ($i = 0; $i < 6; $i++) {
$uuid['node'][$i] = mt_rand(0, 255);
}
$uuid = sprintf('%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
$uuid['time_low'],
$uuid['time_mid'],
$uuid['time_hi'],
$uuid['clock_seq_hi'],
$uuid['clock_seq_low'],
$uuid['node'][0],
$uuid['node'][1],
$uuid['node'][2],
$uuid['node'][3],
$uuid['node'][4],
$uuid['node'][5]
);
return $uuid;
}
protected function checkInitialization(){
//hacking away
/*if( !isset($this->data[$this->primaryKey]) || empty($this->data[$this->primaryKey]) ){
switch($this->key_type){
//generate a UUID for the object
case 'uuid':
$this->data[$this->primaryKey] = $this->generateUUID();
break;
case 'integer': //AKA autoincrement, implemented in the DB implementation class, not here
//todo: implement me
break;
}
$this->firstSave = true;
}*/
}
public static function search($datatype, $query=null, $fields=array()){
$resultSet = Data::query($datatype, $query, $fields);
$results = array();
foreach($resultSet as $result){
$object = new $datatype();
$object->setData($result);
$object->firstSave = false;
$results[] = $object;
}
return $results;
}
public static function query($datatype, $query=null, $fields=array()){
if(is_string($query)){
$search = Data::parseWhere($query);
}else{
if(is_object($query) && is_a($query, 'Search')){
$search = $query->discriminants;
}else if(is_array($query)){
$search = $query; //Data::convertArrayToSearch($query);
}
}
$dummy = new $datatype();
if(isset($search)){
$resultSet = $datatype::performSearch(array(
'type'=>$datatype,
'object'=>$datatype
), $search, Data::$registry[$dummy->database], $fields);
return $resultSet;
}else{
return array();
}
}
public static function getFieldOptions($field, $object){
($comment = $object->option($field, 'comment'))?$comment:'';
($identifier = $object->option($field, 'identifier'))?true:false;
($required = $object->option($field, 'required'))?($required == 't'||$required == 'true'):false;
($size = (int)$object->option($field, 'size'));
($hidden = $object->option($field, 'hidden'));
($object_type = $object->option($field, 'object_type'));
($query = $object->option($field, 'query'));
($readonly = $object->option($field, 'readonly'));
($type = $object->option($field, 'type'));
$options = array(
'comment' => $comment,
'identifier' => $identifier,
'required' => $required,
'size' => $size,
'hidden' => $hidden,
'readonly' => $readonly,
'object_type' => $object_type,
'query' => $query,
'type' => $type
);
if($position = $object->option($field, 'position')) $options['position'] = $position;
return $options;
}
public static function HTMLField($column, $options, $object){
$description = $options['description'];
$identifier = $options['identifier'];
$default = $options['default'];
$obfuscated = $options['obfuscated'];
$hidden = $options['hidden'];
$readOnly = $options['readonly'];
$required = $options['required'];
$size = $options['size'];
$object_type = $options['object_type']?$options['object_type']:'';
$query = $options['query']?$options['query']:'1';
$class = $options['class'];
$fieldType = strtolower($object->type($column));
switch($fieldType){
case 'binary' :
case 'integer' :
case 'float' :
case 'instant' :
$class = 'date_select';
$type = 'text';
break;
case 'string' :
case 'link' :
$type = 'link';
break;
default :
if($size < 256) $type = 'text';
else $type = 'textarea';
}
if($identifier || $hidden) $type = 'hidden';
$label = ucwords(preg_replace('~_~', ' ', $column));
//no label for readonly...
if($readOnly) return ($object->get($column)?$object->get($column):$default).'<input ro="'.$column.'|'.$object->get($column).'" name="'.$column.'" value="'.($object->get($column)?$object->get($column):$default).'" type="hidden"></input>';
//if($readOnly) return '<label for="'.$column.'">'.$label.'</label>'.($object->get($column) || $default).'<input name="'.$column.'" value="'.($object->get($column) || $default).'" type="hidden"></input>';
if($obfuscated){
$type = 'password';
$html = '<label for="'.$column.'">'.$label.'</label><input name="'.$column.'" type="password"'.
(($size)?' size="'.$size.'"':'').
' class="'.$class.'"></input>';
}else{
$rawValue = (($rawValue = $object->get($column))?$rawValue:($default?$default:''));
$value = ' value="'.$rawValue.'"';
switch($type){
case 'textarea':
$html = '<label for="'.$column.'">'.$label.'</label><textarea name="'.$column.'"'.
(($size)?' size="'.$size.'"':'').
'>'.(($value = $object->get($column))?' value="'.$value.'"':(($default)?' value="'.$default.'"':'')).'</textarea>';
break;
case 'readOnly':
$html = '<label for="'.$column.'">'.$label.'</label>'.($object->get($column) || $default).'<input name="'.$column.'"'.$value.' type="hidden"></input>';
break;
case 'link':
$opts = Data::query($object_type, $query, 'id,name');
$optionText = '';
foreach($opts as $option){
$optionText .= '<option value="'.$option['id'].'" '.($option['id'] == $rawValue?'selected="true"':'').'>'.$option['name'].'</option>';
}
$html = '<label for="'.$column.'">'.$label.'</label><select name="'.$column.'">'.$optionText.'</select><a href=""><div class="icon edit"></div> edit</a>';
break;
default :
$html = ($type != 'hidden'?'<label for="'.$column.'">'.$label.'</label>':'').'<input name="'.$column.'" type="'.$type.'"'. $value.
(($size)?' size="'.$size.'"':'').
' '.(($fieldType == 'instant' && $class)?'class="'.$class.'"':'').'></input>';
}
}
return $html;
}
public static function getSelectionOptions($type, $labelField='name', $conditions=array(), $idFieldName='id'){
}
public static function setMetaFields(&$object, $reason = 'object saved'){
if(is_array($object)){ // it's an old-style array
if($object->isNew) $object['created_at'] = date("Y-m-d H:i:s");
//$object['modification_time'] = date("Y-m-d H:i:s");
//$object['modified_by'] = MySQLData::$user_id;
$object['updated_at'] = date("Y-m-d H:i:s");
//$object['last_update_reason'] = $reason;
}else if(is_object($object)){ // it's a new-style object
if($object->isNew) $object->set('created_at', date("Y-m-d H:i:s"));
//$object->set('modification_time', date("Y-m-d H:i:s"));
//$object->set('modified_by', MySQLData::$user_id);
$object->set('updated_at', date("Y-m-d H:i:s"));
//$object->set('last_update_reason', $reason);
}else{
throw new Exception("object is not an object or array, meta-information cannot be added.");
}
}
public static function isMetaField($name){
if(strtolower($name) != 'id' && in_array(strtolower($name), Data::$core_fields)) return true;
else return false;
}
//instance implementations
public $cache = null;
public $isNew = true;
public $data = array();
public $types = array(); //if not set, assumption is 'string'
public $options = array(); //[type][option_name] = value
public $primaryKey = 'id';
public $firstSave = false;
public $key_type = 'uuid'; // uuid, integer, autoincrement
public function __construct($value, $field=null){
if($value != null && !empty($value)){
$this->data = $this->load($value, $field);
//if(empty())
$class = get_class($this);
Logger::log('Loading '.($class::$name).' '.$value);
}
}
public function type($column){
if($type = $this->types[strtolower($column)]){
return $type;
}else if($type = Data::$core_options[strtolower($column)]['type']){
return $type;
}else return false;
}
public function HTML($separator = '<br/>', $column = false, $action = false){
if($action) $action_string = 'action="'.$action.'"';
if($column){
return Data::HTMLField($column, self::getFieldOptions($field, $this), $this);
}else{
$cn = get_class($this);
$res = '<form class="form_basic" name="'.$cn.'" method="post" '.$action_string.'>';
$unordered = array();
$ordered = array();
foreach(array_merge(Data::$core_fields, $cn::$fields) as $field){
$options = self::getFieldOptions($field, $this);
$fieldHTML = Data::HTMLField($field, $options, $this);
if(array_key_exists('position', $options)){
$ordered[$options['position']] = $fieldHTML;
}else{
$unordered[] = $fieldHTML;
}
}
foreach($ordered as $field){
$res .= $field.$separator;
}
foreach($unordered as $field){
$res .= $field.$separator;
}
$res .= '<input type="hidden" name="form" value="true" /></form>';
return $res;
}
//todo: implement full form
}
public function harvest($prefix='', $suffix=''){
$cn = get_class($this);
$data = array();
foreach(array_merge(Data::$core_fields, $cn::$fields) as $field){
$value = WebApplication::get($prefix.$field.$suffix);
$data[$field] = $value;
if($field == $this->primaryKey){
$this->isNew = false;
}
}
$this->data = $data;
}
public function option($column, $name){
if( ($options = $this->options[strtolower($column)]) && ($option = $options[$name]) ){
return $option;
}
if($option = Data::$core_options[strtolower($column)][$name]){
return $option;
}
return false;
}
public function load($id, $field=null){
$res = $this->performLoad($id, $field);
if($res) $this->isNew = false;
return $res;
}
public function save(){
$this->checkInitialization();
$res = $this->performSave();
$this->isNew = false;
return $res;
}
public function increment($key, $amount=1){
$this->set($key, $this->get($key) + $amount);
}
public function get($key){
//todo: we should shortcut if there's no descention
$parts = explode('.', $key);
$current = $this->data;
$currentPath = array();
foreach($parts as $part){
$currentPath[] = $part;
if(!is_array($current) && !array_key_exists($part, $current)){
$warning_text = 'Value does not exist('.implode('.', $currentPath).')!';
switch($empty_field_mode){
case 'notice': //issues notice then drops through to null return
trigger_error($warning_text, E_USER_NOTICE);
case 'null':
return null;
case 'empty':
return '';
case 'exception':
throw new Exception($warning_text);
}
}else{
$current = &$current[$part];
}
}
return $current;
}
public function getData(){
return $this->data;
}
public function setData($data){
if($data[$this->primaryKey]) $this->isNew = false;
return $this->data = $data;
}
public function set($key, $value){
//todo: we should shortcut if there's no descention
$parts = explode('.', $key);
$parts = array_reverse($parts);
$current = &$this->data;
if(sizeof($parts) == 0) throw new Exception('Cannot set an empty value!');
while(sizeof($parts) > 1){
$thisPart = array_pop($parts);
if(!is_array($current) && !array_key_exists($thisPart, $current)){
$current[$thisPart] = array();
}else{
$current = &$current[$thisPart];
}
}
$thisPart = array_pop($parts);
if($value == null){
unset($current[$thisPart]);
}else{
$current[$thisPart] = $value;
}
}
}