8745fdb7a6bb8180e74230e2b38f5c6d03dcbb43
[racktables] / inc / database.php
1 <?php
2 /*
3 *
4 * This file is a library of database access functions for RackTables.
5 *
6 */
7
8 $SQLSchema = array
9 (
10 'object' => array
11 (
12 'table' => 'RackObject',
13 'columns' => array
14 (
15 'id' => 'id',
16 'name' => 'name',
17 'label' => 'label',
18 'barcode' => 'barcode',
19 'asset_no' => 'asset_no',
20 'objtype_id' => 'objtype_id',
21 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
22 'Rack_name' => '(select name from Rack where id = rack_id)',
23 'row_id' => '(select row_id from Rack where id = rack_id)',
24 'Row_name' => '(select name from RackRow where id = row_id)',
25 'objtype_name' => '(select dict_value from Dictionary where dict_key = objtype_id)',
26 ),
27 'keycolumn' => 'id',
28 'ordcolumns' => array ('name'),
29 ),
30 'user' => array
31 (
32 'table' => 'UserAccount',
33 'columns' => array
34 (
35 'user_id' => 'user_id',
36 'user_name' => 'user_name',
37 'user_password_hash' => 'user_password_hash',
38 'user_realname' => 'user_realname',
39 ),
40 'keycolumn' => 'user_id',
41 'ordcolumns' => array ('user_name'),
42 ),
43 'ipv4net' => array
44 (
45 'table' => 'IPv4Network',
46 'columns' => array
47 (
48 'id' => 'id',
49 'ip' => 'INET_NTOA(IPv4Network.ip)',
50 'mask' => 'mask',
51 'name' => 'name',
52 ),
53 'keycolumn' => 'id',
54 'ordcolumns' => array ('ip', 'mask'),
55 ),
56 'file' => array
57 (
58 'table' => 'File',
59 'columns' => array
60 (
61 'id' => 'id',
62 'name' => 'name',
63 'type' => 'type',
64 'size' => 'size',
65 'ctime' => 'ctime',
66 'mtime' => 'mtime',
67 'atime' => 'atime',
68 'comment' => 'comment',
69 ),
70 'keycolumn' => 'id',
71 'ordcolumns' => array ('name'),
72 ),
73 'ipv4vs' => array
74 (
75 'table' => 'IPv4VS',
76 'columns' => array
77 (
78 'id' => 'id',
79 'vip' => 'INET_NTOA(vip)',
80 'vport' => 'vport',
81 'proto' => 'proto',
82 'name' => 'name',
83 'vsconfig' => 'vsconfig',
84 'rsconfig' => 'rsconfig',
85 'poolcount' => '(select count(vs_id) from IPv4LB where vs_id = id)',
86 'dname' => 'CONCAT_WS("/", CONCAT_WS(":", INET_NTOA(vip), vport), proto)',
87 ),
88 'keycolumn' => 'id',
89 'ordcolumns' => array ('vip', 'proto', 'vport'),
90 ),
91 'ipv4rspool' => array
92 (
93 'table' => 'IPv4RSPool',
94 'columns' => array
95 (
96 'id' => 'id',
97 'name' => 'name',
98 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
99 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
100 'vsconfig' => 'vsconfig',
101 'rsconfig' => 'rsconfig',
102 ),
103 'keycolumn' => 'id',
104 'ordcolumns' => array ('name', 'id'),
105 ),
106 'rack' => array
107 (
108 'table' => 'Rack',
109 'columns' => array
110 (
111 'id' => 'id',
112 'name' => 'name',
113 'height' => 'height',
114 'comment' => 'comment',
115 'row_id' => 'row_id',
116 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
117 ),
118 'keycolumn' => 'id',
119 'ordcolumns' => array ('row_id', 'name'),
120 'pidcolumn' => 'row_id',
121 ),
122 );
123
124 function isInnoDBSupported ($dbh = FALSE) {
125 global $dbxlink;
126
127 // sometimes db handle isn't available globally, must be passed
128 if (!$dbxlink)
129 $dbxlink = $dbh;
130
131 // create a temp table
132 $dbxlink->query("CREATE TABLE `innodb_test` (`id` int) ENGINE=InnoDB");
133 $row = $dbxlink->query("SHOW TABLE STATUS LIKE 'innodb_test'")->fetch(PDO::FETCH_ASSOC);
134 $dbxlink->query("DROP TABLE `innodb_test`");
135 if ($row['Engine'] == 'InnoDB')
136 return TRUE;
137
138 return FALSE;
139 }
140
141 function escapeString ($value, $do_db_escape = TRUE)
142 {
143 $ret = htmlspecialchars ($value, ENT_QUOTES, 'UTF-8');
144 if ($do_db_escape)
145 {
146 global $dbxlink;
147 $ret = substr ($dbxlink->quote ($ret), 1, -1);
148 }
149 return $ret;
150 }
151
152 // Return detailed information about one rack row.
153 function getRackRowInfo ($rackrow_id)
154 {
155 $query =
156 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
157 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
158 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
159 "where RackRow.id = ${rackrow_id} " .
160 "group by RackRow.id";
161 $result = useSelectBlade ($query, __FUNCTION__);
162 if ($row = $result->fetch (PDO::FETCH_ASSOC))
163 return $row;
164 else
165 return NULL;
166 }
167
168 function getRackRows ()
169 {
170 $query = "select id, name from RackRow ";
171 $result = useSelectBlade ($query, __FUNCTION__);
172 $rows = array();
173 while ($row = $result->fetch (PDO::FETCH_ASSOC))
174 $rows[$row['id']] = parseWikiLink ($row['name'], 'o');
175 $result->closeCursor();
176 asort ($rows);
177 return $rows;
178 }
179
180 function commitAddRow($rackrow_name)
181 {
182 return useInsertBlade('RackRow', array('name'=>"'$rackrow_name'"));
183 }
184
185 function commitUpdateRow($rackrow_id, $rackrow_name)
186 {
187 global $dbxlink;
188 $query = "update RackRow set name = '${rackrow_name}' where id=${rackrow_id}";
189 $result = $dbxlink->query ($query);
190 if ($result == NULL)
191 {
192 showError ("SQL query '${query}' failed", __FUNCTION__);
193 return FALSE;
194 }
195 $result->closeCursor();
196 return TRUE;
197 }
198
199 function commitDeleteRow($rackrow_id)
200 {
201 global $dbxlink;
202 $query = "select count(*) from Rack where row_id=${rackrow_id}";
203 $result = $dbxlink->query ($query);
204 if (($result!=NULL) && ($row = $result->fetch(PDO::FETCH_NUM)) )
205 {
206 if ($row[0] == 0)
207 {
208 $query = "delete from RackRow where id=${rackrow_id}";
209 $result = $dbxlink->query ($query);
210 if ($result == NULL)
211 {
212 showError ("SQL query '${query}' failed", __FUNCTION__);
213 return FALSE;
214 }
215 }
216 }
217 else
218 {
219 showError ("SQL query '${query}' failed", __FUNCTION__);
220 return FALSE;
221 }
222 $result->closeCursor();
223 return TRUE;
224 }
225
226 // This function returns id->name map for all object types. The map is used
227 // to build <select> input for objects.
228 function getObjectTypeList ()
229 {
230 return readChapter ('RackObjectType');
231 }
232
233 // Return a simple object list w/o related information, so that the returned value
234 // can be directly used by printSelect(). An optional argument is the name of config
235 // option with constraint in RackCode.
236 function getNarrowObjectList ($varname = '')
237 {
238 $ret = array();
239 global $dbxlink;
240 $query =
241 "select RackObject.id as id, RackObject.name as name, dict_value as objtype_name, " .
242 "objtype_id from " .
243 "RackObject inner join Dictionary on objtype_id=dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
244 "where Chapter.name = 'RackObjectType' " .
245 "order by objtype_id, name";
246 $result = useSelectBlade ($query, __FUNCTION__);
247 // Fetch everything at once to unblock result buffer and enable
248 // loadEntityTags(), which will be called soon.
249 $buffer = $result->fetchAll (PDO::FETCH_ASSOC);
250 unset ($result);
251 foreach ($buffer as $row)
252 $ret[$row['id']] = displayedName ($row);
253 if (strlen ($varname) and strlen (getConfigVar ($varname)))
254 {
255 global $parseCache;
256 if (!isset ($parseCache[$varname]))
257 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
258 if ($parseCache[$varname]['result'] != 'ACK')
259 return array();
260 $ret = filterEntityList ($ret, 'object', $parseCache[$varname]['load']);
261 }
262 return $ret;
263 }
264
265 // For a given realm return a list of entity records, each with
266 // enough information for judgeEntityRecord() to execute.
267 function listCells ($realm, $parent_id = 0)
268 {
269 global $SQLSchema;
270 if (!isset ($SQLSchema[$realm]))
271 {
272 showError ('invalid arg', __FUNCTION__);
273 return NULL;
274 }
275 $SQLinfo = $SQLSchema[$realm];
276 $query = 'SELECT tag_id';
277 foreach ($SQLinfo['columns'] as $alias => $expression)
278 // Automatically prepend table name to each single column, but leave all others intact.
279 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
280 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = '${realm}' and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
281 if (isset ($SQLinfo['pidcolumn']) and $parent_id)
282 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ${parent_id}";
283 $query .= " ORDER BY ";
284 foreach ($SQLinfo['ordcolumns'] as $oc)
285 $query .= "${SQLinfo['table']}.${oc}, ";
286 $query .= " tag_id";
287 $result = useSelectBlade ($query, __FUNCTION__);
288 $ret = array();
289 global $taglist;
290 // Index returned result by the value of key column.
291 while ($row = $result->fetch (PDO::FETCH_ASSOC))
292 {
293 $entity_id = $row[$SQLinfo['keycolumn']];
294 // Init the first record anyway, but store tag only if there is one.
295 if (!isset ($ret[$entity_id]))
296 {
297 $ret[$entity_id] = array ('realm' => $realm);
298 foreach (array_keys ($SQLinfo['columns']) as $alias)
299 $ret[$entity_id][$alias] = $row[$alias];
300 $ret[$entity_id]['etags'] = array();
301 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
302 $ret[$entity_id]['etags'][] = array
303 (
304 'id' => $row['tag_id'],
305 'tag' => $taglist[$row['tag_id']]['tag'],
306 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
307 );
308 }
309 elseif (isset ($taglist[$row['tag_id']]))
310 // Meeting existing key later is always more tags on existing list.
311 $ret[$entity_id]['etags'][] = array
312 (
313 'id' => $row['tag_id'],
314 'tag' => $taglist[$row['tag_id']]['tag'],
315 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
316 );
317 }
318 // Add necessary finish to the list before returning it.
319 foreach (array_keys ($ret) as $entity_id)
320 {
321 $ret[$entity_id]['itags'] = getImplicitTags ($ret[$entity_id]['etags']);
322 $ret[$entity_id]['atags'] = generateEntityAutoTags ($realm, $entity_id);
323 switch ($realm)
324 {
325 case 'object':
326 $ret[$entity_id]['dname'] = displayedName ($ret[$entity_id]);
327 break;
328 default:
329 break;
330 }
331 }
332 return $ret;
333 }
334
335 // Very much like listCells(), but return only one record requested (or NULL,
336 // if it does not exist).
337 function spotEntity ($realm, $id)
338 {
339 global $SQLSchema;
340 if (!isset ($SQLSchema[$realm]))
341 {
342 showError ('invalid arg', __FUNCTION__);
343 return NULL;
344 }
345 $SQLinfo = $SQLSchema[$realm];
346 $query = 'SELECT tag_id';
347 foreach ($SQLinfo['columns'] as $alias => $expression)
348 // Automatically prepend table name to each single column, but leave all others intact.
349 $query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
350 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = '${realm}' and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
351 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ${id}";
352 $query .= " ORDER BY tag_id";
353 $result = useSelectBlade ($query, __FUNCTION__);
354 $ret = array();
355 global $taglist;
356 while ($row = $result->fetch (PDO::FETCH_ASSOC))
357 if (!isset ($ret['realm']))
358 {
359 $ret = array ('realm' => $realm);
360 foreach (array_keys ($SQLinfo['columns']) as $alias)
361 $ret[$alias] = $row[$alias];
362 $ret['etags'] = array();
363 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
364 $ret['etags'][] = array
365 (
366 'id' => $row['tag_id'],
367 'tag' => $taglist[$row['tag_id']]['tag'],
368 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
369 );
370 }
371 elseif (isset ($taglist[$row['tag_id']]))
372 $ret['etags'][] = array
373 (
374 'id' => $row['tag_id'],
375 'tag' => $taglist[$row['tag_id']]['tag'],
376 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
377 );
378 unset ($result);
379 if (!isset ($ret['realm'])) // no rows were returned
380 return NULL;
381 $ret['itags'] = getImplicitTags ($ret['etags']);
382 $ret['atags'] = generateEntityAutoTags ($realm, $id);
383 switch ($realm)
384 {
385 case 'object':
386 $ret['dname'] = displayedName ($ret);
387 break;
388 default:
389 break;
390 }
391 return $ret;
392 }
393
394 // This function can be used with array_walk().
395 function amplifyCell (&$record, $dummy = NULL)
396 {
397 switch ($record['realm'])
398 {
399 case 'object':
400 $record['ports'] = getObjectPortsAndLinks ($record['id']);
401 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
402 $record['nat4'] = getNATv4ForObject ($record['id']);
403 $record['ipv4rspools'] = getRSPoolsForObject ($record['id']);
404 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
405 break;
406 case 'ipv4net':
407 $record['ip_bin'] = ip2long ($record['ip']);
408 $record['parent_id'] = getIPv4AddressNetworkId ($record['ip'], $record['mask']);
409 break;
410 case 'file':
411 $record['links'] = getFileLinks ($record['id']);
412 break;
413 case 'ipv4rspool':
414 $record['lblist'] = array();
415 $query = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
416 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
417 "where rspool_id = ${record['id']} order by object_id, vip, vport";
418 $result = useSelectBlade ($query, __FUNCTION__);
419 while ($row = $result->fetch (PDO::FETCH_ASSOC))
420 $record['lblist'][$row['object_id']][$row['vs_id']] = array
421 (
422 'rsconfig' => $row['rsconfig'],
423 'vsconfig' => $row['vsconfig'],
424 );
425 unset ($result);
426 $record['rslist'] = array();
427 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
428 "IPv4RS where rspool_id = ${record['id']} order by IPv4RS.rsip, rsport";
429 $result = useSelectBlade ($query, __FUNCTION__);
430 while ($row = $result->fetch (PDO::FETCH_ASSOC))
431 $record['rslist'][$row['id']] = array
432 (
433 'inservice' => $row['inservice'],
434 'rsip' => $row['rsip'],
435 'rsport' => $row['rsport'],
436 'rsconfig' => $row['rsconfig'],
437 );
438 unset ($result);
439 break;
440 case 'ipv4vs':
441 // Get the detailed composition of a particular virtual service, namely the list
442 // of all pools, each shown with the list of objects servicing it. VS/RS configs
443 // will be returned as well.
444 $record['rspool'] = array();
445 $query = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
446 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
447 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
448 "where vs_id = ${record['id']} order by pool.name, object_id";
449 $result = useSelectBlade ($query, __FUNCTION__);
450 while ($row = $result->fetch (PDO::FETCH_ASSOC))
451 {
452 if (!isset ($record['rspool'][$row['id']]))
453 $record['rspool'][$row['id']] = array
454 (
455 'name' => $row['name'],
456 'vsconfig' => $row['vsconfig'],
457 'rsconfig' => $row['rsconfig'],
458 'lblist' => array(),
459 );
460 if ($row['object_id'] == NULL)
461 continue;
462 $record['rspool'][$row['id']]['lblist'][$row['object_id']] = array
463 (
464 'vsconfig' => $row['lb_vsconfig'],
465 'rsconfig' => $row['lb_rsconfig'],
466 );
467 }
468 unset ($result);
469 break;
470 case 'rack':
471 $record['mountedObjects'] = array();
472 // start with default rackspace
473 for ($i = $record['height']; $i > 0; $i--)
474 for ($locidx = 0; $locidx < 3; $locidx++)
475 $record[$i][$locidx]['state'] = 'F';
476 // load difference
477 $query =
478 "select unit_no, atom, state, object_id " .
479 "from RackSpace where rack_id = ${record['id']} and " .
480 "unit_no between 1 and " . $record['height'] . " order by unit_no";
481 $result = useSelectBlade ($query, __FUNCTION__);
482 global $loclist;
483 $mounted_objects = array();
484 while ($row = $result->fetch (PDO::FETCH_ASSOC))
485 {
486 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
487 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
488 if ($row['state'] == 'T' and $row['object_id'] != NULL)
489 $mounted_objects[$row['object_id']] = TRUE;
490 }
491 $record['mountedObjects'] = array_keys ($mounted_objects);
492 unset ($result);
493 break;
494 default:
495 }
496 }
497
498 // This is a popular helper.
499 function getObjectInfo ($object_id = 0, $set_dname = TRUE)
500 {
501 $query =
502 "select RackObject.id as id, RackObject.name as name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
503 "RackObject inner join Dictionary on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
504 "where RackObject.id = '${object_id}' and Chapter.name = 'RackObjectType'";
505 $result = useSelectBlade ($query, __FUNCTION__);
506 if (($ret = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
507 {
508 showError ('Query succeeded, but returned no data', __FUNCTION__);
509 return NULL;
510 }
511 $result->closeCursor();
512 // It's safe now to run subsequent queries.
513 if ($set_dname)
514 $ret['dname'] = displayedName ($ret);
515 return $ret;
516 }
517
518 function getPortTypes ()
519 {
520 return readChapter ('PortType');
521 }
522
523 function getObjectPortsAndLinks ($object_id)
524 {
525 // prepare decoder
526 $ptd = readChapter ('PortType');
527 $query = "select id, name, label, l2address, type as type_id, reservation_comment from Port where object_id = ${object_id}";
528 // list and decode all ports of the current object
529 $result = useSelectBlade ($query, __FUNCTION__);
530 $ret=array();
531 while ($row = $result->fetch (PDO::FETCH_ASSOC))
532 {
533 $row['type'] = $ptd[$row['type_id']];
534 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
535 $row['remote_id'] = NULL;
536 $row['remote_name'] = NULL;
537 $row['remote_object_id'] = NULL;
538 $row['remote_object_name'] = NULL;
539 $ret[] = $row;
540 }
541 unset ($result);
542 // now find and decode remote ends for all locally terminated connections
543 // FIXME: can't this data be extracted in one pass with sub-queries?
544 foreach (array_keys ($ret) as $tmpkey)
545 {
546 $portid = $ret[$tmpkey]['id'];
547 $remote_id = NULL;
548 $query = "select porta, portb from Link where porta = {$portid} or portb = ${portid}";
549 $result = useSelectBlade ($query, __FUNCTION__);
550 if ($row = $result->fetch (PDO::FETCH_ASSOC))
551 {
552 if ($portid != $row['porta'])
553 $remote_id = $row['porta'];
554 elseif ($portid != $row['portb'])
555 $remote_id = $row['portb'];
556 }
557 unset ($result);
558 if ($remote_id) // there's a remote end here
559 {
560 $query = "select Port.name as port_name, Port.type as port_type, object_id, RackObject.name as object_name " .
561 "from Port left join RackObject on Port.object_id = RackObject.id " .
562 "where Port.id = ${remote_id}";
563 $result = useSelectBlade ($query, __FUNCTION__);
564 if ($row = $result->fetch (PDO::FETCH_ASSOC))
565 {
566 $ret[$tmpkey]['remote_name'] = $row['port_name'];
567 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
568 $ret[$tmpkey]['remote_object_name'] = $row['object_name'];
569 }
570 $ret[$tmpkey]['remote_id'] = $remote_id;
571 unset ($result);
572 // only call displayedName() when necessary
573 if (empty ($ret[$tmpkey]['remote_object_name']) and !empty ($ret[$tmpkey]['remote_object_id']))
574 {
575 $oi = getObjectInfo ($ret[$tmpkey]['remote_object_id']);
576 $ret[$tmpkey]['remote_object_name'] = $oi['dname'];
577 }
578 }
579 }
580 return $ret;
581 }
582
583 function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
584 {
585 if ($row_id <= 0 or $height <= 0 or empty ($name))
586 return FALSE;
587 $result = useInsertBlade
588 (
589 'Rack',
590 array
591 (
592 'row_id' => $row_id,
593 'name' => "'${name}'",
594 'height' => $height,
595 'comment' => "'${comment}'"
596 )
597 );
598 if ($result == NULL)
599 {
600 showError ('useInsertBlade() failed', __FUNCTION__);
601 return FALSE;
602 }
603 $last_insert_id = lastInsertID();
604 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', "id = ${last_insert_id}");
605 }
606
607 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
608 {
609 global $dbxlink;
610 // Maintain UNIQUE INDEX for common names and asset tags by
611 // filtering out empty strings (not NULLs).
612 $result1 = useInsertBlade
613 (
614 'RackObject',
615 array
616 (
617 'name' => empty ($new_name) ? 'NULL' : "'${new_name}'",
618 'label' => "'${new_label}'",
619 'barcode' => empty ($new_barcode) ? 'NULL' : "'${new_barcode}'",
620 'objtype_id' => $new_type_id,
621 'asset_no' => empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'"
622 )
623 );
624 if ($result1 == NULL)
625 {
626 showError ("SQL query #1 failed", __FUNCTION__);
627 return FALSE;
628 }
629 $last_insert_id = lastInsertID();
630 // Do AutoPorts magic
631 executeAutoPorts ($last_insert_id, $new_type_id);
632 // Now tags...
633 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
634 if ($error != '')
635 {
636 showError ("Error adding tags for the object: ${error}");
637 return FALSE;
638 }
639 return recordHistory ('RackObject', "id = ${last_insert_id}");
640 }
641
642 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
643 {
644 if ($object_id == 0 || $new_type_id == 0)
645 {
646 showError ('Not all required args are present.', __FUNCTION__);
647 return FALSE;
648 }
649 global $dbxlink;
650 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
651 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
652 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
653 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
654 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
655 "where id='${object_id}' limit 1";
656 $result = $dbxlink->query ($query);
657 if ($result == NULL)
658 {
659 showError ("SQL query '${query}' failed", __FUNCTION__);
660 return FALSE;
661 }
662 $result->closeCursor();
663 return recordHistory ('RackObject', "id = ${object_id}");
664 }
665
666 // There are times when you want to delete all traces of an object
667 function commitDeleteObject ($object_id = 0)
668 {
669 if ($object_id <= 0)
670 {
671 showError ('Invalid args', __FUNCTION__);
672 die;
673 }
674 global $dbxlink;
675 $dbxlink->query("DELETE FROM AttributeValue WHERE object_id = ${object_id}");
676 $dbxlink->query("DELETE FROM File WHERE id IN (SELECT file_id FROM FileLink WHERE entity_id = 'object' AND entity_id = ${object_id})");
677 $dbxlink->query("DELETE FROM IPv4LB WHERE object_id = ${object_id}");
678 $dbxlink->query("DELETE FROM IPv4Allocation WHERE object_id = ${object_id}");
679 $dbxlink->query("DELETE FROM Port WHERE object_id = ${object_id}");
680 $dbxlink->query("DELETE FROM IPv4NAT WHERE object_id = ${object_id}");
681 $dbxlink->query("DELETE FROM RackSpace WHERE object_id = ${object_id}");
682 $dbxlink->query("DELETE FROM TagStorage WHERE entity_realm = 'object' and entity_id = ${object_id}");
683 $dbxlink->query("DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ${object_id})");
684 $dbxlink->query("DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ${object_id})");
685 $dbxlink->query("DELETE FROM MountOperation WHERE object_id = ${object_id}");
686 $dbxlink->query("DELETE FROM RackObjectHistory WHERE id = ${object_id}");
687 $dbxlink->query("DELETE FROM RackObject WHERE id = ${object_id}");
688
689 return '';
690 }
691
692 function commitDeleteRack($rack_id)
693 {
694 global $dbxlink;
695 $query = "delete from RackSpace where rack_id = '${rack_id}'";
696 $dbxlink->query ($query);
697 $query = "delete from TagStorage where entity_realm='rack' and entity_id='${rack_id}'";
698 $dbxlink->query ($query);
699 $query = "delete from RackHistory where id = '${rack_id}'";
700 $dbxlink->query ($query);
701 $query = "delete from Rack where id = '${rack_id}'";
702 $dbxlink->query ($query);
703 return TRUE;
704 }
705
706 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
707 {
708 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
709 {
710 showError ('Not all required args are present.', __FUNCTION__);
711 return FALSE;
712 }
713 global $dbxlink;
714
715 // Can't shrink a rack if rows being deleted contain mounted objects
716 $check_sql = "SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = '${rack_id}' AND unit_no > '{$new_height}'";
717 $check_result = $dbxlink->query($check_sql);
718 $check_row = $check_result->fetch (PDO::FETCH_ASSOC);
719 if ($check_row['count'] > 0) {
720 showError ('Cannot shrink rack, objects are still mounted there', __FUNCTION__);
721 return FALSE;
722 }
723
724 $update_sql = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
725 "where id='${rack_id}' limit 1";
726 $update_result = $dbxlink->query ($update_sql);
727 if ($update_result->rowCount() != 1)
728 {
729 showError ('Error updating rack information', __FUNCTION__);
730 return FALSE;
731 }
732 return recordHistory ('Rack', "id = ${rack_id}");
733 }
734
735 // This function accepts rack data returned by amplifyCell(), validates and applies changes
736 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
737 // correspond to current rack ID.
738 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
739 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
740 // The function returns the modified rack upon success.
741 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
742 {
743 global $loclist, $dbxlink;
744 $rack_id = $rackData['id'];
745 $rack_name = $rackData['name'];
746 $rackchanged = FALSE;
747 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
748 {
749 for ($locidx = 0; $locidx < 3; $locidx++)
750 {
751 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
752 continue;
753 // detect a change
754 $state = $rackData[$unit_no][$locidx]['state'];
755 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
756 $newstate = $checked_state;
757 else
758 $newstate = $unchecked_state;
759 if ($state == $newstate)
760 continue;
761 $rackchanged = TRUE;
762 // and validate
763 $atom = $loclist[$locidx];
764 // The only changes allowed are those introduced by checkbox grid.
765 if
766 (
767 !($state == $checked_state && $newstate == $unchecked_state) &&
768 !($state == $unchecked_state && $newstate == $checked_state)
769 )
770 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
771 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
772 // anyway and then looking for probable need of INSERT.
773 $query =
774 "delete from RackSpace where rack_id = ${rack_id} and " .
775 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
776 $r = $dbxlink->query ($query);
777 if ($r == NULL)
778 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
779 if ($newstate != 'F')
780 {
781 $query =
782 "insert into RackSpace(rack_id, unit_no, atom, state) " .
783 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
784 $r = $dbxlink->query ($query);
785 if ($r == NULL)
786 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
787 }
788 if ($newstate == 'T' and $object_id != 0)
789 {
790 // At this point we already have a record in RackSpace.
791 $query =
792 "update RackSpace set object_id=${object_id} " .
793 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
794 $r = $dbxlink->query ($query);
795 if ($r->rowCount() == 1)
796 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
797 else
798 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
799 }
800 }
801 }
802 if ($rackchanged)
803 {
804 resetThumbCache ($rack_id);
805 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
806 }
807 else
808 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
809 }
810
811 // This function builds a list of rack-unit-atom records, which are assigned to
812 // the requested object.
813 function getMoleculeForObject ($object_id = 0)
814 {
815 if ($object_id == 0)
816 {
817 showError ("object_id == 0", __FUNCTION__);
818 return NULL;
819 }
820 $query =
821 "select rack_id, unit_no, atom from RackSpace " .
822 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
823 $result = useSelectBlade ($query, __FUNCTION__);
824 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
825 $result->closeCursor();
826 return $ret;
827 }
828
829 // This function builds a list of rack-unit-atom records for requested molecule.
830 function getMolecule ($mid = 0)
831 {
832 if ($mid == 0)
833 {
834 showError ("mid == 0", __FUNCTION__);
835 return NULL;
836 }
837 $query =
838 "select rack_id, unit_no, atom from Atom " .
839 "where molecule_id=${mid}";
840 $result = useSelectBlade ($query, __FUNCTION__);
841 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
842 $result->closeCursor();
843 return $ret;
844 }
845
846 // returns exactly what is's named after
847 function lastInsertID ()
848 {
849 if (NULL == ($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)))
850 {
851 showError ('SQL query failed!', __FUNCTION__);
852 die;
853 }
854 $row = $result->fetch (PDO::FETCH_NUM);
855 return $row[0];
856 }
857
858 // This function creates a new record in Molecule and number of linked
859 // R-U-A records in Atom.
860 function createMolecule ($molData)
861 {
862 global $dbxlink;
863 $query = "insert into Molecule values()";
864 $result1 = $dbxlink->query ($query);
865 if ($result1->rowCount() != 1)
866 {
867 showError ('Error inserting into Molecule', __FUNCTION__);
868 return NULL;
869 }
870 $molecule_id = lastInsertID();
871 foreach ($molData as $rua)
872 {
873 $rack_id = $rua['rack_id'];
874 $unit_no = $rua['unit_no'];
875 $atom = $rua['atom'];
876 $query =
877 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
878 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
879 $result3 = $dbxlink->query ($query);
880 if ($result3 == NULL or $result3->rowCount() != 1)
881 {
882 showError ('Error inserting into Atom', __FUNCTION__);
883 return NULL;
884 }
885 }
886 return $molecule_id;
887 }
888
889 // History logger. This function assumes certain table naming convention and
890 // column design:
891 // 1. History table name equals to dictionary table name plus 'History'.
892 // 2. History table must have the same row set (w/o keys) plus one row named
893 // 'ctime' of type 'timestamp'.
894 function recordHistory ($tableName, $whereClause)
895 {
896 global $dbxlink, $remote_username;
897 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
898 $result = $dbxlink->query ($query);
899 if ($result == NULL or $result->rowCount() != 1)
900 {
901 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
902 return FALSE;
903 }
904 return TRUE;
905 }
906
907 function getRackspaceHistory ()
908 {
909 $query =
910 "select mo.id as mo_id, ro.id as ro_id, ro.name, mo.ctime, mo.comment, dict_value as objtype_name, user_name from " .
911 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
912 "inner join Dictionary on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
913 "where Chapter.name = 'RackObjectType' order by ctime desc";
914 $result = useSelectBlade ($query, __FUNCTION__);
915 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
916 $result->closeCursor();
917 return $ret;
918 }
919
920 // This function is used in renderRackspaceHistory()
921 function getOperationMolecules ($op_id = 0)
922 {
923 if ($op_id <= 0)
924 {
925 showError ("Missing argument", __FUNCTION__);
926 return;
927 }
928 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
929 $result = useSelectBlade ($query, __FUNCTION__);
930 // We expect one row.
931 $row = $result->fetch (PDO::FETCH_ASSOC);
932 if ($row == NULL)
933 {
934 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
935 return;
936 }
937 $omid = $row['old_molecule_id'];
938 $nmid = $row['new_molecule_id'];
939 $result->closeCursor();
940 return array ($omid, $nmid);
941 }
942
943 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
944 {
945 if ($object_id <= 0)
946 {
947 showError ('Invalid object_id', __FUNCTION__);
948 return;
949 }
950 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
951 $result = useSelectBlade ($query, __FUNCTION__);
952 $rows = $result->fetchAll (PDO::FETCH_NUM);
953 unset ($result);
954 $ret = array();
955 foreach ($rows as $row)
956 {
957 if (!$fetch_rackdata)
958 {
959 $ret[$row[0]] = $row[0];
960 continue;
961 }
962 if (NULL == ($rackData = spotEntity ('rack', $row[0])))
963 {
964 showError ('Rack not found', __FUNCTION__);
965 return NULL;
966 }
967 amplifyCell ($rackData);
968 $ret[$row[0]] = $rackData;
969 }
970 return $ret;
971 }
972
973 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
974 {
975 if ($object_id <= 0)
976 {
977 showError ('Invalid object_id', __FUNCTION__);
978 return;
979 }
980 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
981 return "Invalid L2 address ${port_l2address}";
982 $result = useInsertBlade
983 (
984 'Port',
985 array
986 (
987 'name' => "'${port_name}'",
988 'object_id' => "'${object_id}'",
989 'label' => "'${port_label}'",
990 'type' => "'${port_type_id}'",
991 'l2address' => ($db_l2address === '') ? 'NULL' : "'${db_l2address}'"
992 )
993 );
994 if ($result)
995 return '';
996 else
997 return 'SQL query failed';
998 }
999
1000 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
1001 // string value. In case it is omitted, we just assign it its current value.
1002 // It would be nice to simplify this semantics later.
1003 function commitUpdatePort ($port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
1004 {
1005 global $dbxlink;
1006 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
1007 return "Invalid L2 address ${port_l2address}";
1008 $query =
1009 "update Port set name='$port_name', type=$port_type_id, label='$port_label', " .
1010 "reservation_comment = ${port_reservation_comment}, l2address=" .
1011 (($db_l2address === '') ? 'NULL' : "'${db_l2address}'") .
1012 " where id='$port_id'";
1013 $result = $dbxlink->exec ($query);
1014 if ($result == 1)
1015 return '';
1016 $errorInfo = $dbxlink->errorInfo();
1017 // We could update nothing.
1018 if ($errorInfo[0] == '00000')
1019 return '';
1020 return $errorInfo[2];
1021 }
1022
1023 function delObjectPort ($port_id)
1024 {
1025 if (unlinkPort ($port_id) != '')
1026 return __FUNCTION__ . ': unlinkPort() failed';
1027 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
1028 return __FUNCTION__ . ': useDeleteBlade() failed';
1029 return '';
1030 }
1031
1032 function getAllIPv4Allocations ()
1033 {
1034 $query =
1035 "select object_id as object_id, ".
1036 "RackObject.name as object_name, ".
1037 "IPv4Allocation.name as name, ".
1038 "INET_NTOA(ip) as ip ".
1039 "from IPv4Allocation join RackObject on id=object_id ";
1040 $result = useSelectBlade ($query, __FUNCTION__);
1041 $ret = array();
1042 $count=0;
1043 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1044 {
1045 $ret[$count]['object_id']=$row['object_id'];
1046 $ret[$count]['object_name']=$row['object_name'];
1047 $ret[$count]['name']=$row['name'];
1048 $ret[$count]['ip']=$row['ip'];
1049 $count++;
1050 }
1051 $result->closeCursor();
1052 return $ret;
1053 }
1054
1055 function getEmptyPortsOfType ($type_id)
1056 {
1057 $query =
1058 "select distinct Port.id as Port_id, ".
1059 "Port.object_id as Port_object_id, ".
1060 "RackObject.name as Object_name, ".
1061 "Port.name as Port_name, ".
1062 "Port.type as Port_type_id, ".
1063 "dict_value as Port_type_name ".
1064 "from ( ".
1065 " ( ".
1066 " Port inner join Dictionary on Port.type = dict_key join Chapter on Chapter.id = Dictionary.chapter_id ".
1067 " ) ".
1068 " join RackObject on Port.object_id = RackObject.id ".
1069 ") ".
1070 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
1071 "inner join PortCompat on Port.type = PortCompat.type2 ".
1072 "where Chapter.name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
1073 "and Port.reservation_comment is null order by Object_name, Port_name";
1074 $result = useSelectBlade ($query, __FUNCTION__);
1075 $ret = array();
1076 $count=0;
1077 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1078 {
1079 $ret[$count]['Port_id']=$row['Port_id'];
1080 $ret[$count]['Port_object_id']=$row['Port_object_id'];
1081 $ret[$count]['Object_name']=$row['Object_name'];
1082 $ret[$count]['Port_name']=$row['Port_name'];
1083 $ret[$count]['Port_type_id']=$row['Port_type_id'];
1084 $ret[$count]['Port_type_name']=$row['Port_type_name'];
1085 $count++;
1086 }
1087 $result->closeCursor();
1088 return $ret;
1089 }
1090
1091 function linkPorts ($porta, $portb)
1092 {
1093 if ($porta == $portb)
1094 return "Ports can't be the same";
1095 if ($porta > $portb)
1096 {
1097 $tmp = $porta;
1098 $porta = $portb;
1099 $portb = $tmp;
1100 }
1101 global $dbxlink;
1102 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
1103 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
1104 // FIXME: who cares about the return value?
1105 $result = $dbxlink->exec ($query1);
1106 $result = $dbxlink->exec ($query2);
1107 return '';
1108 }
1109
1110 function unlinkPort ($port)
1111 {
1112 global $dbxlink;
1113 $query =
1114 "delete from Link where porta='$port' or portb='$port'";
1115 $result = $dbxlink->exec ($query);
1116 return '';
1117 }
1118
1119 // Return all IPv4 addresses allocated to the objects. Attach detailed
1120 // info about address to each alocation records. Index result by dotted-quad
1121 // address.
1122 function getObjectIPv4Allocations ($object_id = 0)
1123 {
1124 $ret = array();
1125 $query = 'select name as osif, type, inet_ntoa(ip) as dottedquad from IPv4Allocation ' .
1126 "where object_id = ${object_id} " .
1127 'order by ip';
1128 $result = useSelectBlade ($query, __FUNCTION__);
1129 // don't spawn a sub-query with unfetched buffer, it may fail
1130 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1131 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1132 unset ($result);
1133 foreach (array_keys ($ret) as $dottedquad)
1134 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
1135 return $ret;
1136 }
1137
1138 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
1139 function constructIPv4Address ($dottedquad = NULL)
1140 {
1141 $ret = array
1142 (
1143 'name' => '',
1144 'reserved' => 'no',
1145 'outpf' => array(),
1146 'inpf' => array(),
1147 'rslist' => array(),
1148 'allocs' => array(),
1149 'lblist' => array()
1150 );
1151 if ($dottedquad != NULL)
1152 $ret['ip'] = $dottedquad;
1153 return $ret;
1154 }
1155
1156 // Check the range requested for meaningful IPv4 records, build them
1157 // into a list and return. Return an empty list if nothing matched.
1158 // Both arguments are expected in signed int32 form. The resulting list
1159 // is keyed by uint32 form of each IP address, items aren't sorted.
1160 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
1161 function scanIPv4Space ($pairlist)
1162 {
1163 $ret = array();
1164 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
1165 return $ret;;
1166 $dnamechache = array();
1167 // FIXME: this is a copy-and-paste prototype
1168 $or = '';
1169 $whereexpr1 = '(';
1170 $whereexpr2 = '(';
1171 $whereexpr3 = '(';
1172 $whereexpr4 = '(';
1173 $whereexpr5a = '(';
1174 $whereexpr5b = '(';
1175 foreach ($pairlist as $tmp)
1176 {
1177 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
1178 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
1179 $whereexpr1 .= $or . "ip between ${db_first} and ${db_last}";
1180 $whereexpr2 .= $or . "ip between ${db_first} and ${db_last}";
1181 $whereexpr3 .= $or . "vip between ${db_first} and ${db_last}";
1182 $whereexpr4 .= $or . "rsip between ${db_first} and ${db_last}";
1183 $whereexpr5a .= $or . "remoteip between ${db_first} and ${db_last}";
1184 $whereexpr5b .= $or . "localip between ${db_first} and ${db_last}";
1185 $or = ' or ';
1186 }
1187 $whereexpr1 .= ')';
1188 $whereexpr2 .= ')';
1189 $whereexpr3 .= ')';
1190 $whereexpr4 .= ')';
1191 $whereexpr5a .= ')';
1192 $whereexpr5b .= ')';
1193
1194 // 1. collect labels and reservations
1195 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
1196 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1197 $result = useSelectBlade ($query, __FUNCTION__);
1198 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1199 {
1200 $ip_bin = ip2long ($row['ip']);
1201 if (!isset ($ret[$ip_bin]))
1202 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1203 $ret[$ip_bin]['name'] = $row['name'];
1204 $ret[$ip_bin]['reserved'] = $row['reserved'];
1205 }
1206 unset ($result);
1207
1208 // 2. check for allocations
1209 $query =
1210 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
1211 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
1212 "dict_value as objtype_name from " .
1213 "IPv4Allocation as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
1214 "left join Dictionary on objtype_id=dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
1215 "where ${whereexpr2} " .
1216 "and Chapter.name = 'RackObjectType'" .
1217 "order by ipb.type, object_name";
1218 $result = useSelectBlade ($query, __FUNCTION__);
1219 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1220 {
1221 $ip_bin = ip2long ($row['ip']);
1222 if (!isset ($ret[$ip_bin]))
1223 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1224 if (!isset ($dnamecache[$row['object_id']]))
1225 {
1226 $quasiobject['id'] = $row['object_id'];
1227 $quasiobject['name'] = $row['object_name'];
1228 $quasiobject['objtype_id'] = $row['objtype_id'];
1229 $quasiobject['objtype_name'] = $row['objtype_name'];
1230 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1231 }
1232 $tmp = array();
1233 foreach (array ('object_id', 'type', 'name') as $cname)
1234 $tmp[$cname] = $row[$cname];
1235 $tmp['object_name'] = $dnamecache[$row['object_id']];
1236 $ret[$ip_bin]['allocs'][] = $tmp;
1237 }
1238 unset ($result);
1239
1240 // 3. look for virtual services and related LB
1241 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
1242 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
1243 "IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1244 "inner join RackObject as ro on lb.object_id = ro.id " .
1245 "left join Dictionary on objtype_id=dict_key " .
1246 "join Chapter on Chapter.id = Dictionary.chapter_id " .
1247 "where ${whereexpr3} " .
1248 "and Chapter.name = 'RackObjectType'" .
1249 "order by vport, proto, ro.name, object_id";
1250 $result = useSelectBlade ($query, __FUNCTION__);
1251 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1252 {
1253 $ip_bin = ip2long ($row['ip']);
1254 if (!isset ($ret[$ip_bin]))
1255 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1256 if (!isset ($dnamecache[$row['object_id']]))
1257 {
1258 $quasiobject['name'] = $row['object_name'];
1259 $quasiobject['objtype_id'] = $row['objtype_id'];
1260 $quasiobject['objtype_name'] = $row['objtype_name'];
1261 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1262 }
1263 $tmp = array();
1264 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
1265 $tmp[$cname] = $row[$cname];
1266 $tmp['object_name'] = $dnamecache[$row['object_id']];
1267 $tmp['vip'] = $row['ip'];
1268 $ret[$ip_bin]['lblist'][] = $tmp;
1269 }
1270 unset ($result);
1271
1272 // 4. don't forget about real servers along with pools
1273 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1274 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
1275 "where ${whereexpr4} " .
1276 "order by ip, rsport, rspool_id";
1277 $result = useSelectBlade ($query, __FUNCTION__);
1278 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1279 {
1280 $ip_bin = ip2long ($row['ip']);
1281 if (!isset ($ret[$ip_bin]))
1282 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1283 $tmp = array();
1284 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1285 $tmp[$cname] = $row[$cname];
1286 $ret[$ip_bin]['rslist'][] = $tmp;
1287 }
1288 unset ($result);
1289
1290 // 5. add NAT rules, part 1
1291 $query =
1292 "select " .
1293 "proto, " .
1294 "INET_NTOA(localip) as localip, " .
1295 "localport, " .
1296 "INET_NTOA(remoteip) as remoteip, " .
1297 "remoteport, " .
1298 "description " .
1299 "from IPv4NAT " .
1300 "where ${whereexpr5a} " .
1301 "order by localip, localport, remoteip, remoteport, proto";
1302 $result = useSelectBlade ($query, __FUNCTION__);
1303 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1304 {
1305 $remoteip_bin = ip2long ($row['remoteip']);
1306 if (!isset ($ret[$remoteip_bin]))
1307 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1308 $ret[$remoteip_bin]['inpf'][] = $row;
1309 }
1310 unset ($result);
1311 // 5. add NAT rules, part 2
1312 $query =
1313 "select " .
1314 "proto, " .
1315 "INET_NTOA(localip) as localip, " .
1316 "localport, " .
1317 "INET_NTOA(remoteip) as remoteip, " .
1318 "remoteport, " .
1319 "description " .
1320 "from IPv4NAT " .
1321 "where ${whereexpr5b} " .
1322 "order by localip, localport, remoteip, remoteport, proto";
1323 $result = useSelectBlade ($query, __FUNCTION__);
1324 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1325 {
1326 $localip_bin = ip2long ($row['localip']);
1327 if (!isset ($ret[$localip_bin]))
1328 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1329 $ret[$localip_bin]['outpf'][] = $row;
1330 }
1331 unset ($result);
1332 return $ret;
1333 }
1334
1335 // Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
1336 function getIPv4NetworkInfo ($id = 0)
1337 {
1338 if ($id <= 0)
1339 {
1340 showError ('Invalid arg', __FUNCTION__);
1341 return NULL;
1342 }
1343 $query = "select INET_NTOA(ip) as ip, mask, name ".
1344 "from IPv4Network where id = $id";
1345 $result = useSelectBlade ($query, __FUNCTION__);
1346 $ret = $result->fetch (PDO::FETCH_ASSOC);
1347 if ($ret == NULL)
1348 return NULL;
1349 unset ($result);
1350 $ret['id'] = $id;
1351 $ret['ip_bin'] = ip2long ($ret['ip']);
1352 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1353 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1354 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
1355 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
1356 return $ret;
1357 }
1358
1359 function getIPv4Address ($dottedquad = '')
1360 {
1361 if ($dottedquad == '')
1362 {
1363 showError ('Invalid arg', __FUNCTION__);
1364 return NULL;
1365 }
1366 $i32 = ip2long ($dottedquad); // signed 32 bit
1367 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1368 if (!isset ($scanres[$i32]))
1369 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1370 return constructIPv4Address ($dottedquad);
1371 markupIPv4AddrList ($scanres);
1372 return $scanres[$i32];
1373 }
1374
1375 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1376 {
1377 $result = useInsertBlade
1378 (
1379 'IPv4Allocation',
1380 array
1381 (
1382 'ip' => "INET_ATON('$ip')",
1383 'object_id' => "'${object_id}'",
1384 'name' => "'${name}'",
1385 'type' => "'${type}'"
1386 )
1387 );
1388 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
1389 }
1390
1391 // Return the id of the smallest IPv4 network containing the given IPv4 address
1392 // or NULL, if nothing was found. When finding the covering network for
1393 // another network, it is important to filter out matched records with longer
1394 // masks (they aren't going to be the right pick).
1395 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1396 {
1397 // N.B. To perform the same for IPv6 address and networks, some pre-requisites
1398 // are necessary and a different query. IPv6 addresses are 128 bit long, which
1399 // is too much for both PHP and MySQL data types. These values must be split
1400 // into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1401 // Then each network must have its 128-bit netmask split same way and either
1402 // stored right in its record or JOINed from decoder and accessible as m_u32_0,
1403 // m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1404 // covering the given address would look as follows:
1405 // $query = 'select id from IPv6Network as n where ' .
1406 // "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1407 // "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1408 // "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1409 // "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1410 // "mask < ${masklen} " .
1411 // 'order by mask desc limit 1';
1412
1413 $query = 'select id from IPv4Network where ' .
1414 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1415 "and mask < ${masklen} " .
1416 'order by mask desc limit 1';
1417 $result = useSelectBlade ($query, __FUNCTION__);
1418 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1419 return $row['id'];
1420 return NULL;
1421 }
1422
1423 function updateRange ($id=0, $name='')
1424 {
1425 global $dbxlink;
1426 $query =
1427 "update IPv4Network set name='$name' where id='$id'";
1428 $result = $dbxlink->exec ($query);
1429 return '';
1430 }
1431
1432 // This function is actually used not only to update, but also to create records,
1433 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1434 // (MySQL 4.0 workaround).
1435 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1436 {
1437 // DELETE may safely fail.
1438 $r = useDeleteBlade ('IPv4Address', 'ip', "INET_ATON('${ip}')");
1439 // INSERT may appear not necessary.
1440 if ($name == '' and $reserved == 'no')
1441 return '';
1442 if (useInsertBlade ('IPv4Address', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1443 return '';
1444 else
1445 return __FUNCTION__ . '(): useInsertBlade() failed';
1446 }
1447
1448 function updateBond ($ip='', $object_id=0, $name='', $type='')
1449 {
1450 global $dbxlink;
1451
1452 $query =
1453 "update IPv4Allocation set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1454 $result = $dbxlink->exec ($query);
1455 return '';
1456 }
1457
1458 function unbindIpFromObject ($ip='', $object_id=0)
1459 {
1460 global $dbxlink;
1461
1462 $query =
1463 "delete from IPv4Allocation where ip=INET_ATON('$ip') and object_id='$object_id'";
1464 $result = $dbxlink->exec ($query);
1465 return '';
1466 }
1467
1468 function searchByl2address ($port_l2address)
1469 {
1470 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
1471 return NULL; // Don't complain, other searches may return own data.
1472 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1473 "where l2address = '${db_l2address}'";
1474 $result = useSelectBlade ($query, __FUNCTION__);
1475 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1476 $result->closeCursor();
1477 if (count ($rows) == 0) // No results.
1478 return NULL;
1479 if (count ($rows) == 1) // Target found.
1480 return $rows[0];
1481 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
1482 return NULL;
1483 }
1484
1485 function getIPv4PrefixSearchResult ($terms)
1486 {
1487 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPv4Network where ";
1488 $or = '';
1489 foreach (explode (' ', $terms) as $term)
1490 {
1491 $query .= $or . "name like '%${term}%'";
1492 $or = ' or ';
1493 }
1494 $result = useSelectBlade ($query, __FUNCTION__);
1495 $ret = array();
1496 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1497 $ret[] = $row;
1498 return $ret;
1499 }
1500
1501 function getIPv4AddressSearchResult ($terms)
1502 {
1503 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1504 $or = '';
1505 foreach (explode (' ', $terms) as $term)
1506 {
1507 $query .= $or . "name like '%${term}%'";
1508 $or = ' or ';
1509 }
1510 $result = useSelectBlade ($query, __FUNCTION__);
1511 $ret = array();
1512 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1513 $ret[] = $row;
1514 return $ret;
1515 }
1516
1517 function getIPv4RSPoolSearchResult ($terms)
1518 {
1519 $query = "select id as pool_id, name from IPv4RSPool where ";
1520 $or = '';
1521 foreach (explode (' ', $terms) as $term)
1522 {
1523 $query .= $or . "name like '%${term}%'";
1524 $or = ' or ';
1525 }
1526 $result = useSelectBlade ($query, __FUNCTION__);
1527 $ret = array();
1528 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1529 $ret[] = $row;
1530 return $ret;
1531 }
1532
1533 function getIPv4VServiceSearchResult ($terms)
1534 {
1535 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPv4VS where ";
1536 $or = '';
1537 foreach (explode (' ', $terms) as $term)
1538 {
1539 $query .= $or . "name like '%${term}%'";
1540 $or = ' or ';
1541 }
1542 $result = useSelectBlade ($query, __FUNCTION__);
1543 $ret = array();
1544 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1545 $ret[] = $row;
1546 return $ret;
1547 }
1548
1549 function getAccountSearchResult ($terms)
1550 {
1551 $byUsername = getSearchResultByField
1552 (
1553 'UserAccount',
1554 array ('user_id', 'user_name', 'user_realname'),
1555 'user_name',
1556 $terms,
1557 'user_name'
1558 );
1559 $byRealname = getSearchResultByField
1560 (
1561 'UserAccount',
1562 array ('user_id', 'user_name', 'user_realname'),
1563 'user_realname',
1564 $terms,
1565 'user_name'
1566 );
1567 // Filter out dupes.
1568 foreach ($byUsername as $res1)
1569 foreach (array_keys ($byRealname) as $key2)
1570 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1571 {
1572 unset ($byRealname[$key2]);
1573 continue 2;
1574 }
1575 $ret = array_merge ($byUsername, $byRealname);
1576 // Set realm, so it's renderable.
1577 foreach (array_keys ($ret) as $key)
1578 $ret[$key]['realm'] = 'user';
1579 return $ret;
1580 }
1581
1582 function getFileSearchResult ($terms)
1583 {
1584 $byFilename = getSearchResultByField
1585 (
1586 'File',
1587 array ('id', 'name', 'comment', 'type', 'size'),
1588 'name',
1589 $terms,
1590 'name'
1591 );
1592 $byComment = getSearchResultByField
1593 (
1594 'File',
1595 array ('id', 'name', 'comment', 'type', 'size'),
1596 'comment',
1597 $terms,
1598 'name'
1599 );
1600 // Filter out dupes.
1601 foreach ($byFilename as $res1)
1602 foreach (array_keys ($byComment) as $key2)
1603 if ($res1['id'] == $byComment[$key2]['id'])
1604 {
1605 unset ($byComment[$key2]);
1606 continue 2;
1607 }
1608 return array_merge ($byFilename, $byComment);
1609 }
1610
1611 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1612 {
1613 $pfx = '';
1614 $query = 'select ';
1615 foreach ($rcolumns as $col)
1616 {
1617 $query .= $pfx . $col;
1618 $pfx = ', ';
1619 }
1620 $pfx = '';
1621 $query .= " from ${tname} where ";
1622 foreach (explode (' ', $terms) as $term)
1623 {
1624 $query .= $pfx . "${scolumn} like '%${term}%'";
1625 $pfx = ' or ';
1626 }
1627 if ($ocolumn != '')
1628 $query .= " order by ${ocolumn}";
1629 $result = useSelectBlade ($query, __FUNCTION__);
1630 $ret = array();
1631 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1632 $ret[] = $row;
1633 return $ret;
1634 }
1635
1636 // This function returns either port ID or NULL for specified arguments.
1637 function getPortID ($object_id, $port_name)
1638 {
1639 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1640 $result = useSelectBlade ($query, __FUNCTION__);
1641 $rows = $result->fetchAll (PDO::FETCH_NUM);
1642 if (count ($rows) != 1)
1643 return NULL;
1644 $ret = $rows[0][0];
1645 $result->closeCursor();
1646 return $ret;
1647 }
1648
1649 function commitCreateUserAccount ($username, $realname, $password)
1650 {
1651 return useInsertBlade
1652 (
1653 'UserAccount',
1654 array
1655 (
1656 'user_name' => "'${username}'",
1657 'user_realname' => "'${realname}'",
1658 'user_password_hash' => "'${password}'"
1659 )
1660 );
1661 }
1662
1663 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1664 {
1665 global $dbxlink;
1666 $query =
1667 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1668 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1669 $result = $dbxlink->query ($query);
1670 if ($result == NULL)
1671 {
1672 showError ('SQL query failed', __FUNCTION__);
1673 die;
1674 }
1675 return TRUE;
1676 }
1677
1678 // This function returns an array of all port type pairs from PortCompat table.
1679 function getPortCompat ()
1680 {
1681 $query =
1682 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1683 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1684 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1685 "inner join Chapter as c1 on d1.chapter_id = c1.id " .
1686 "inner join Chapter as c2 on d2.chapter_id = c2.id " .
1687 "where c1.name = 'PortType' and c2.name = 'PortType'";
1688 $result = useSelectBlade ($query, __FUNCTION__);
1689 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1690 $result->closeCursor();
1691 return $ret;
1692 }
1693
1694 function removePortCompat ($type1 = 0, $type2 = 0)
1695 {
1696 global $dbxlink;
1697 if ($type1 == 0 or $type2 == 0)
1698 {
1699 showError ('Invalid arguments', __FUNCTION__);
1700 die;
1701 }
1702 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1703 $result = $dbxlink->query ($query);
1704 if ($result == NULL)
1705 {
1706 showError ('SQL query failed', __FUNCTION__);
1707 die;
1708 }
1709 return TRUE;
1710 }
1711
1712 function addPortCompat ($type1 = 0, $type2 = 0)
1713 {
1714 if ($type1 <= 0 or $type2 <= 0)
1715 {
1716 showError ('Invalid arguments', __FUNCTION__);
1717 die;
1718 }
1719 return useInsertBlade
1720 (
1721 'PortCompat',
1722 array ('type1' => $type1, 'type2' => $type2)
1723 );
1724 }
1725
1726 // This function returns the dictionary as an array of trees, each tree
1727 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1728 // and 'word' keys with the latter holding all the words within the chapter.
1729 // FIXME: there's a lot of excess legacy code in this function, it's reasonable
1730 // to merge it with readChapter().
1731 function getDict ($parse_links = FALSE)
1732 {
1733 $query1 =
1734 "select Chapter.name as chapter_name, Chapter.id as chapter_no, dict_key, dict_value, sticky from " .
1735 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id order by Chapter.name, dict_value";
1736 $result = useSelectBlade ($query1, __FUNCTION__);
1737 $dict = array();
1738 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1739 {
1740 $chapter_no = $row['chapter_no'];
1741 if (!isset ($dict[$chapter_no]))
1742 {
1743 $dict[$chapter_no]['no'] = $chapter_no;
1744 $dict[$chapter_no]['name'] = $row['chapter_name'];
1745 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1746 $dict[$chapter_no]['word'] = array();
1747 }
1748 if ($row['dict_key'] != NULL)
1749 {
1750 $dict[$chapter_no]['word'][$row['dict_key']] = ($parse_links or $row['dict_key'] <= MAX_DICT_KEY) ?
1751 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1752 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1753 }
1754 }
1755 $result->closeCursor();
1756 unset ($result);
1757 // Find the list of all assigned values of dictionary-addressed attributes, each with
1758 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1759 // of the returned disctionary words.
1760 $query2 = "select a.id as attr_id, am.chapter_id as chapter_no, uint_value, count(object_id) as refcnt " .
1761 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1762 "inner join AttributeValue as av on a.id = av.attr_id " .
1763 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
1764 "where a.type = 'dict' group by a.id, am.chapter_id, uint_value " .
1765 "order by a.id, am.chapter_id, uint_value";
1766 $result = useSelectBlade ($query2, __FUNCTION__);
1767 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1768 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1769 $result->closeCursor();
1770 return $dict;
1771 }
1772
1773 function getDictStats ()
1774 {
1775 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25);
1776 $query =
1777 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
1778 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id";
1779 $result = useSelectBlade ($query, __FUNCTION__);
1780 $tc = $tw = $uc = $uw = 0;
1781 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1782 {
1783 $tc++;
1784 $tw += $row['wc'];;
1785 if (in_array ($row['chapter_no'], $stock_chapters))
1786 continue;
1787 $uc++;
1788 $uw += $row['wc'];;
1789 }
1790 $result->closeCursor();
1791 unset ($result);
1792 $query = "select count(id) as attrc from RackObject as ro left join " .
1793 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1794 $result = useSelectBlade ($query, __FUNCTION__);
1795 $to = $ta = $so = 0;
1796 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1797 {
1798 $to++;
1799 if ($row['attrc'] != 0)
1800 {
1801 $so++;
1802 $ta += $row['attrc'];
1803 }
1804 }
1805 $result->closeCursor();
1806 $ret = array();
1807 $ret['Total chapters in dictionary'] = $tc;
1808 $ret['Total words in dictionary'] = $tw;
1809 $ret['User chapters'] = $uc;
1810 $ret['Words in user chapters'] = $uw;
1811 $ret['Total objects'] = $to;
1812 $ret['Objects with stickers'] = $so;
1813 $ret['Total stickers attached'] = $ta;
1814 return $ret;
1815 }
1816
1817 function getIPv4Stats ()
1818 {
1819 $ret = array();
1820 $subject = array();
1821 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1822 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1823 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1824 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1825 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1826 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1827 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1828 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
1829
1830 foreach ($subject as $item)
1831 {
1832 $result = useSelectBlade ($item['q'], __FUNCTION__);
1833 $row = $result->fetch (PDO::FETCH_NUM);
1834 $ret[$item['txt']] = $row[0];
1835 $result->closeCursor();
1836 unset ($result);
1837 }
1838 return $ret;
1839 }
1840
1841 function getRackspaceStats ()
1842 {
1843 $ret = array();
1844 $subject = array();
1845 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
1846 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1847 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1848 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1849
1850 foreach ($subject as $item)
1851 {
1852 $result = useSelectBlade ($item['q'], __FUNCTION__);
1853 $row = $result->fetch (PDO::FETCH_NUM);
1854 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
1855 $result->closeCursor();
1856 unset ($result);
1857 }
1858 return $ret;
1859 }
1860
1861 function renderTagStats ()
1862 {
1863 global $taglist, $root;
1864 $query = "select id, tag, count(tag_id) as refcnt from " .
1865 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1866 "group by tag_id order by refcnt desc limit 50";
1867 // The same data is already present in pre-loaded tag list, but not in
1868 // the form we need. So let's ask the DB server for cooked top list and
1869 // use the cooked tag list to break it down.
1870 $result = useSelectBlade ($query, __FUNCTION__);
1871 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1872 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
1873 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th><th>files</th></tr>';
1874 $pagebyrealm = array
1875 (
1876 'file' => 'files&tab=default',
1877 'ipv4net' => 'ipv4space&tab=default',
1878 'ipv4vs' => 'ipv4vslist&tab=default',
1879 'ipv4rspool' => 'ipv4rsplist&tab=default',
1880 'object' => 'depot&tab=default',
1881 'rack' => 'rackspace&tab=default',
1882 'user' => 'userlist&tab=default'
1883 );
1884 foreach ($refc as $ref)
1885 {
1886 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
1887 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user', 'file') as $realm)
1888 {
1889 echo '<td>';
1890 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1891 echo '&nbsp;';
1892 else
1893 {
1894 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&cft[]=${ref['id']}'>";
1895 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1896 }
1897 echo '</td>';
1898 }
1899 echo '</tr>';
1900 }
1901 echo '</table>';
1902 }
1903
1904 /*
1905
1906 The following allows figuring out records in TagStorage, which refer to non-existing entities:
1907
1908 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1909 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1910 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1911 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1912 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1913 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1914 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
1915
1916 Accordingly, these are the records, which refer to non-existent tags:
1917
1918 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1919
1920 */
1921
1922 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1923 {
1924 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1925 {
1926 showError ('Invalid args', __FUNCTION__);
1927 die;
1928 }
1929 global $dbxlink;
1930 $query =
1931 "update Dictionary set dict_value = '${dict_value}' where chapter_id=${chapter_no} " .
1932 "and dict_key=${dict_key} limit 1";
1933 $result = $dbxlink->query ($query);
1934 if ($result == NULL)
1935 {
1936 showError ('SQL query failed', __FUNCTION__);
1937 die;
1938 }
1939 return TRUE;
1940 }
1941
1942 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1943 {
1944 if ($chapter_no <= 0 or empty ($dict_value))
1945 {
1946 showError ('Invalid args', __FUNCTION__);
1947 die;
1948 }
1949 return useInsertBlade
1950 (
1951 'Dictionary',
1952 array ('chapter_id' => $chapter_no, 'dict_value' => "'${dict_value}'")
1953 );
1954 }
1955
1956 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1957 {
1958 if ($chapter_no <= 0 or $dict_key <= 0)
1959 {
1960 showError ('Invalid args', __FUNCTION__);
1961 die;
1962 }
1963 global $dbxlink;
1964 $query =
1965 "delete from Dictionary where chapter_id=${chapter_no} " .
1966 "and dict_key=${dict_key} limit 1";
1967 $result = $dbxlink->query ($query);
1968 if ($result == NULL)
1969 {
1970 showError ('SQL query failed', __FUNCTION__);
1971 die;
1972 }
1973 return TRUE;
1974 }
1975
1976 function commitAddChapter ($chapter_name = '')
1977 {
1978 if (empty ($chapter_name))
1979 {
1980 showError ('Invalid args', __FUNCTION__);
1981 die;
1982 }
1983 return useInsertBlade
1984 (
1985 'Chapter',
1986 array ('name' => "'${chapter_name}'")
1987 );
1988 }
1989
1990 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1991 {
1992 if ($chapter_no <= 0 or empty ($chapter_name))
1993 {
1994 showError ('Invalid args', __FUNCTION__);
1995 die;
1996 }
1997 global $dbxlink;
1998 $query =
1999 "update Chapter set name = '${chapter_name}' where id = ${chapter_no} " .
2000 "and sticky = 'no' limit 1";
2001 $result = $dbxlink->query ($query);
2002 if ($result == NULL)
2003 {
2004 showError ('SQL query failed', __FUNCTION__);
2005 die;
2006 }
2007 return TRUE;
2008 }
2009
2010 function commitDeleteChapter ($chapter_no = 0)
2011 {
2012 if ($chapter_no <= 0)
2013 {
2014 showError ('Invalid args', __FUNCTION__);
2015 die;
2016 }
2017 global $dbxlink;
2018 $query =
2019 "delete from Chapter where id = ${chapter_no} and sticky = 'no' limit 1";
2020 $result = $dbxlink->query ($query);
2021 if ($result == NULL)
2022 {
2023 showError ('SQL query failed', __FUNCTION__);
2024 die;
2025 }
2026 return TRUE;
2027 }
2028
2029 // This is a dictionary accessor. We perform link rendering, so the user sees
2030 // nice <select> drop-downs.
2031 function readChapter ($chapter_name = '')
2032 {
2033 if (empty ($chapter_name))
2034 {
2035 showError ('invalid argument', __FUNCTION__);
2036 return NULL;
2037 }
2038 $query =
2039 "select dict_key, dict_value from Dictionary join Chapter on Chapter.id = Dictionary.chapter_id " .
2040 "where Chapter.name = '${chapter_name}'";
2041 $result = useSelectBlade ($query, __FUNCTION__);
2042 $chapter = array();
2043 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2044 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
2045 $result->closeCursor();
2046 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2047 asort ($chapter);
2048 return $chapter;
2049 }
2050
2051 function getAttrMap ()
2052 {
2053 $query =
2054 "select a.id as attr_id, a.type as attr_type, a.name as attr_name, am.objtype_id, " .
2055 "d.dict_value as objtype_name, am.chapter_id, c2.name as chapter_name from " .
2056 "Attribute as a left join AttributeMap as am on a.id = am.attr_id " .
2057 "left join Dictionary as d on am.objtype_id = d.dict_key " .
2058 "left join Chapter as c1 on d.chapter_id = c1.id " .
2059 "left join Chapter as c2 on am.chapter_id = c2.id " .
2060 "where c1.name = 'RackObjectType' or c1.name is null " .
2061 "order by a.name";
2062 $result = useSelectBlade ($query, __FUNCTION__);
2063 $ret = array();
2064 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2065 {
2066 $attr_id = $row['attr_id'];
2067 if (!isset ($ret[$attr_id]))
2068 {
2069 $ret[$attr_id]['id'] = $attr_id;
2070 $ret[$attr_id]['type'] = $row['attr_type'];
2071 $ret[$attr_id]['name'] = $row['attr_name'];
2072 $ret[$attr_id]['application'] = array();
2073 }
2074 if ($row['objtype_id'] == '')
2075 continue;
2076 $application['objtype_id'] = $row['objtype_id'];
2077 $application['objtype_name'] = $row['objtype_name'];
2078 if ($row['attr_type'] == 'dict')
2079 {
2080 $application['chapter_no'] = $row['chapter_id'];
2081 $application['chapter_name'] = $row['chapter_name'];
2082 }
2083 $ret[$attr_id]['application'][] = $application;
2084 }
2085 $result->closeCursor();
2086 return $ret;
2087 }
2088
2089 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2090 {
2091 if ($attr_id <= 0 or empty ($attr_name))
2092 {
2093 showError ('Invalid args', __FUNCTION__);
2094 die;
2095 }
2096 global $dbxlink;
2097 $query =
2098 "update Attribute set name = '${attr_name}' " .
2099 "where id = ${attr_id} limit 1";
2100 $result = $dbxlink->query ($query);
2101 if ($result == NULL)
2102 {
2103 showError ("SQL query '${query}' failed", __FUNCTION__);
2104 die;
2105 }
2106 return TRUE;
2107 }
2108
2109 function commitAddAttribute ($attr_name = '', $attr_type = '')
2110 {
2111 if (empty ($attr_name))
2112 {
2113 showError ('Invalid args', __FUNCTION__);
2114 die;
2115 }
2116 switch ($attr_type)
2117 {
2118 case 'uint':
2119 case 'float':
2120 case 'string':
2121 case 'dict':
2122 break;
2123 default:
2124 showError ('Invalid args', __FUNCTION__);
2125 die;
2126 }
2127 return useInsertBlade
2128 (
2129 'Attribute',
2130 array ('name' => "'${attr_name}'", 'type' => "'${attr_type}'")
2131 );
2132 }
2133
2134 function commitDeleteAttribute ($attr_id = 0)
2135 {
2136 if ($attr_id <= 0)
2137 {
2138 showError ('Invalid args', __FUNCTION__);
2139 die;
2140 }
2141 return useDeleteBlade ('Attribute', 'id', $attr_id);
2142 }
2143
2144 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2145 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2146 {
2147 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
2148 {
2149 showError ('Invalid args', __FUNCTION__);
2150 die;
2151 }
2152 return useInsertBlade
2153 (
2154 'AttributeMap',
2155 array
2156 (
2157 'attr_id' => $attr_id,
2158 'objtype_id' => $objtype_id,
2159 'chapter_id' => $chapter_no
2160 )
2161 );
2162 }
2163
2164 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2165 {
2166 if ($attr_id <= 0 or $objtype_id <= 0)
2167 {
2168 showError ('Invalid args', __FUNCTION__);
2169 die;
2170 }
2171 global $dbxlink;
2172 $query =
2173 "delete from AttributeMap where attr_id=${attr_id} " .
2174 "and objtype_id=${objtype_id} limit 1";
2175 $result = $dbxlink->query ($query);
2176 if ($result == NULL)
2177 {
2178 showError ('SQL query failed', __FUNCTION__);
2179 die;
2180 }
2181 return TRUE;
2182 }
2183
2184 // This function returns all optional attributes for requested object
2185 // as an array of records. NULL is returned on error and empty array
2186 // is returned, if there are no attributes found.
2187 function getAttrValues ($object_id, $strip_optgroup = FALSE)
2188 {
2189 if ($object_id <= 0)
2190 {
2191 showError ('Invalid argument', __FUNCTION__);
2192 return NULL;
2193 }
2194 $ret = array();
2195 $query =
2196 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2197 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2198 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2199 "inner join Attribute as A on AM.attr_id = A.id " .
2200 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2201 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2202 "left join Chapter as C on AM.chapter_id = C.id " .
2203 "where RO.id = ${object_id} order by A.type, A.name";
2204 $result = useSelectBlade ($query, __FUNCTION__);
2205 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2206 {
2207 $record = array();
2208 $record['id'] = $row['attr_id'];
2209 $record['name'] = $row['attr_name'];
2210 $record['type'] = $row['attr_type'];
2211 switch ($row['attr_type'])
2212 {
2213 case 'uint':
2214 case 'float':
2215 case 'string':
2216 $record['value'] = $row[$row['attr_type'] . '_value'];
2217 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2218 break;
2219 case 'dict':
2220 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2221 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
2222 $record['chapter_name'] = $row['chapter_name'];
2223 $record['key'] = $row['uint_value'];
2224 break;
2225 default:
2226 $record['value'] = NULL;
2227 break;
2228 }
2229 $ret[$row['attr_id']] = $record;
2230 }
2231 $result->closeCursor();
2232 return $ret;
2233 }
2234
2235 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2236 {
2237 if ($object_id <= 0 or $attr_id <= 0)
2238 {
2239 showError ('Invalid arguments', __FUNCTION__);
2240 die;
2241 }
2242 global $dbxlink;
2243 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2244 $result = $dbxlink->query ($query);
2245 if ($result == NULL)
2246 {
2247 showError ('SQL query failed', __FUNCTION__);
2248 die;
2249 }
2250 return TRUE;
2251 }
2252
2253 // FIXME: don't share common code with use commitResetAttrValue()
2254 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2255 {
2256 if ($object_id <= 0 or $attr_id <= 0)
2257 {
2258 showError ('Invalid arguments', __FUNCTION__);
2259 die;
2260 }
2261 if (empty ($value))
2262 return commitResetAttrValue ($object_id, $attr_id);
2263 global $dbxlink;
2264 $query1 = "select type as attr_type from Attribute where id = ${attr_id}";
2265 $result = $dbxlink->query ($query1);
2266 if ($result == NULL)
2267 {
2268 showError ('SQL query #1 failed', __FUNCTION__);
2269 die;
2270 }
2271 $row = $result->fetch (PDO::FETCH_NUM);
2272 if ($row == NULL)
2273 {
2274 showError ('SQL query #1 returned no results', __FUNCTION__);
2275 die;
2276 }
2277 $attr_type = $row[0];
2278 $result->closeCursor();
2279 switch ($attr_type)
2280 {
2281 case 'uint':
2282 case 'float':
2283 case 'string':
2284 $column = $attr_type . '_value';
2285 break;
2286 case 'dict':
2287 $column = 'uint_value';
2288 break;
2289 default:
2290 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
2291 die;
2292 }
2293 $query2 =
2294 "delete from AttributeValue where " .
2295 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2296 $result = $dbxlink->query ($query2);
2297 if ($result == NULL)
2298 {
2299 showError ('SQL query #2 failed', __FUNCTION__);
2300 die;
2301 }
2302 // We know $value isn't empty here.
2303 $query3 =
2304 "insert into AttributeValue set ${column} = '${value}', " .
2305 "object_id = ${object_id}, attr_id = ${attr_id} ";
2306 $result = $dbxlink->query ($query3);
2307 if ($result == NULL)
2308 {
2309 showError ('SQL query #3 failed', __FUNCTION__);
2310 die;
2311 }
2312 return TRUE;
2313 }
2314
2315 function commitUseupPort ($port_id = 0)
2316 {
2317 if ($port_id <= 0)
2318 {
2319 showError ("Invalid argument", __FUNCTION__);
2320 die;
2321 }
2322 global $dbxlink;
2323 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2324 $result = $dbxlink->exec ($query);
2325 if ($result == NULL)
2326 {
2327 showError ("SQL query failed", __FUNCTION__);
2328 die;
2329 }
2330 return TRUE;
2331
2332 }
2333
2334 // This is a swiss-knife blade to insert a record into a table.
2335 // The first argument is table name.
2336 // The second argument is an array of "name" => "value" pairs.
2337 // The function returns either TRUE or FALSE (we expect one row
2338 // to be inserted).
2339 function useInsertBlade ($tablename, $values)
2340 {
2341 global $dbxlink;
2342 $namelist = $valuelist = '';
2343 foreach ($values as $name => $value)
2344 {
2345 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2346 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2347 }
2348 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2349 $result = $dbxlink->exec ($query);
2350 if ($result != 1)
2351 return FALSE;
2352 return TRUE;
2353 }
2354
2355 // This swiss-knife blade deletes one record from the specified table
2356 // using the specified key name and value.
2357 function useDeleteBlade ($tablename, $keyname, $keyvalue)
2358 {
2359 global $dbxlink;
2360 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
2361 }
2362
2363 function useSelectBlade ($query, $caller = 'N/A')
2364 {
2365 global $dbxlink;
2366 $result = $dbxlink->query ($query);
2367 if ($result == NULL)
2368 {
2369 $ei = $dbxlink->errorInfo();
2370 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
2371 debug_print_backtrace();
2372 return NULL;
2373 }
2374 return $result;
2375 }
2376
2377 function loadConfigCache ()
2378 {
2379 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
2380 $result = useSelectBlade ($query, __FUNCTION__);
2381 $cache = array();
2382 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2383 $cache[$row['varname']] = $row;
2384 $result->closeCursor();
2385 return $cache;
2386 }
2387
2388 // setConfigVar() is expected to perform all necessary filtering
2389 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2390 {
2391 global $dbxlink;
2392 if (empty ($varname) || $varvalue === NULL)
2393 {
2394 showError ('Invalid arguments', __FUNCTION__);
2395 return FALSE;
2396 }
2397 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2398 $result = $dbxlink->query ($query);
2399 if ($result == NULL)
2400 {
2401 showError ("SQL query '${query}' failed", __FUNCTION__);
2402 return FALSE;
2403 }
2404 $rc = $result->rowCount();
2405 $result->closeCursor();
2406 if ($rc == 0 or $rc == 1)
2407 return TRUE;
2408 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
2409 return FALSE;
2410 }
2411
2412 // Database version detector. Should behave corretly on any
2413 // working dataset a user might have.
2414 function getDatabaseVersion ()
2415 {
2416 global $dbxlink;
2417 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2418 $result = $dbxlink->query ($query);
2419 if ($result == NULL)
2420 {
2421 $errorInfo = $dbxlink->errorInfo();
2422 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2423 return '0.14.4';
2424 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2425 }
2426 $rows = $result->fetchAll (PDO::FETCH_NUM);
2427 if (count ($rows) != 1 || empty ($rows[0][0]))
2428 {
2429 $result->closeCursor();
2430 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2431 }
2432 $ret = $rows[0][0];
2433 $result->closeCursor();
2434 return $ret;
2435 }
2436
2437 // Return an array of virtual services. For each of them list real server pools
2438 // with their load balancers and other stats.
2439 function getSLBSummary ()
2440 {
2441 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2442 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2443 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2444 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2445 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2446 'group by vs.id, object_id order by vs.vip, object_id';
2447 $result = useSelectBlade ($query, __FUNCTION__);
2448 $ret = array();
2449 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2450 {
2451 $vsid = $row['vsid'];
2452 $object_id = $row['object_id'];
2453 if (!isset ($ret[$vsid]))
2454 {
2455 $ret[$vsid] = array();
2456 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2457 $ret[$vsid][$cname] = $row[$cname];
2458 $ret[$vsid]['lblist'] = array();
2459 }
2460 // There's only one assigned RS pool possible for each LB-VS combination.
2461 $ret[$vsid]['lblist'][$row['object_id']] = array
2462 (
2463 'id' => $row['rspool_id'],
2464 'size' => $row['rscount'],
2465 'name' => $row['pool_name']
2466 );
2467 }
2468 $result->closeCursor();
2469 return $ret;
2470 }
2471
2472 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2473 {
2474 if ($pool_id <= 0)
2475 {
2476 showError ('Invalid arguments', __FUNCTION__);
2477 die;
2478 }
2479 if (empty ($rsport) or $rsport == 0)
2480 $rsport = 'NULL';
2481 return useInsertBlade
2482 (
2483 'IPv4RS',
2484 array
2485 (
2486 'rsip' => "inet_aton('${rsip}')",
2487 'rsport' => $rsport,
2488 'rspool_id' => $pool_id,
2489 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2490 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2491 )
2492 );
2493 }
2494
2495 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2496 {
2497 if (empty ($vip) or $vport <= 0 or empty ($proto))
2498 return __FUNCTION__ . ': invalid arguments';
2499 if (!useInsertBlade
2500 (
2501 'IPv4VS',
2502 array
2503 (
2504 'vip' => "inet_aton('${vip}')",
2505 'vport' => $vport,
2506 'proto' => "'${proto}'",
2507 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2508 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2509 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2510 )
2511 ))
2512 return __FUNCTION__ . ': SQL insertion failed';
2513 return produceTagsForLastRecord ('ipv4vs', $taglist);
2514 }
2515
2516 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2517 {
2518 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2519 {
2520 showError ('Invalid arguments', __FUNCTION__);
2521 die;
2522 }
2523 return useInsertBlade
2524 (
2525 'IPv4LB',
2526 array
2527 (
2528 'object_id' => $object_id,
2529 'rspool_id' => $pool_id,
2530 'vs_id' => $vs_id,
2531 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2532 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2533 )
2534 );
2535 }
2536
2537 function commitDeleteRS ($id = 0)
2538 {
2539 if ($id <= 0)
2540 return FALSE;
2541 return useDeleteBlade ('IPv4RS', 'id', $id);
2542 }
2543
2544 function commitDeleteVS ($id = 0)
2545 {
2546 if ($id <= 0)
2547 return FALSE;
2548 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
2549 }
2550
2551 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2552 {
2553 global $dbxlink;
2554 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2555 return FALSE;
2556 $query = "delete from IPv4LB where object_id = ${object_id} and " .
2557 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2558 $result = $dbxlink->exec ($query);
2559 if ($result === NULL)
2560 return FALSE;
2561 elseif ($result != 1)
2562 return FALSE;
2563 else
2564 return TRUE;
2565 }
2566
2567 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2568 {
2569 if ($rsid <= 0)
2570 {
2571 showError ('Invalid args', __FUNCTION__);
2572 die;
2573 }
2574 if (long2ip (ip2long ($rsip)) !== $rsip)
2575 {
2576 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2577 die;
2578 }
2579 if (empty ($rsport) or $rsport == 0)
2580 $rsport = 'NULL';
2581 global $dbxlink;
2582 $query =
2583 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2584 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2585 " where id = ${rsid} limit 1";
2586 $result = $dbxlink->query ($query);
2587 if ($result == NULL)
2588 {
2589 showError ("SQL query '${query}' failed", __FUNCTION__);
2590 die;
2591 }
2592 return TRUE;
2593 }
2594
2595 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2596 {
2597 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2598 {
2599 showError ('Invalid args', __FUNCTION__);
2600 die;
2601 }
2602 global $dbxlink;
2603 $query =
2604 "update IPv4LB set vsconfig = " .
2605 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2606 ', rsconfig = ' .
2607 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2608 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2609 "and vs_id = ${vs_id} limit 1";
2610 $result = $dbxlink->exec ($query);
2611 if ($result === NULL)
2612 return FALSE;
2613 else
2614 return TRUE;
2615 }
2616
2617 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2618 {
2619 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2620 {
2621 showError ('Invalid args', __FUNCTION__);
2622 die;
2623 }
2624 global $dbxlink;
2625 $query = "update IPv4VS set " .
2626 "vip = inet_aton('${vip}'), " .
2627 "vport = ${vport}, " .
2628 "proto = '${proto}', " .
2629 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2630 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2631 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2632 " where id = ${vsid} limit 1";
2633 $result = $dbxlink->exec ($query);
2634 if ($result === NULL)
2635 return FALSE;
2636 else
2637 return TRUE;
2638 }
2639
2640 function loadThumbCache ($rack_id = 0)
2641 {
2642 $ret = NULL;
2643 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2644 $result = useSelectBlade ($query, __FUNCTION__);
2645 $row = $result->fetch (PDO::FETCH_ASSOC);
2646 if ($row)
2647 $ret = base64_decode ($row['thumb_data']);
2648 $result->closeCursor();
2649 return $ret;
2650 }
2651
2652 function saveThumbCache ($rack_id = 0, $cache = NULL)
2653 {
2654 global $dbxlink;
2655 if ($rack_id == 0 or $cache == NULL)
2656 {
2657 showError ('Invalid arguments', __FUNCTION__);
2658 return;
2659 }
2660 $data = base64_encode ($cache);
2661 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2662 $result = $dbxlink->exec ($query);
2663 }
2664
2665 function resetThumbCache ($rack_id = 0)
2666 {
2667 global $dbxlink;
2668 if ($rack_id == 0)
2669 {
2670 showError ('Invalid argument', __FUNCTION__);
2671 return;
2672 }
2673 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2674 $result = $dbxlink->exec ($query);
2675 }
2676
2677 // Return the list of attached RS pools for the given object. As long as we have
2678 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2679 // by vs_id, because there will be only one RS pool listed for each VS of the
2680 // current object.
2681 function getRSPoolsForObject ($object_id = 0)
2682 {
2683 if ($object_id <= 0)
2684 {
2685 showError ('Invalid object_id', __FUNCTION__);
2686 return NULL;
2687 }
2688 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2689 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2690 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2691 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2692 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2693 "where lb.object_id = ${object_id} " .
2694 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2695 $result = useSelectBlade ($query, __FUNCTION__);
2696 $ret = array ();
2697 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2698 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2699 $ret[$row['vs_id']][$cname] = $row[$cname];
2700 $result->closeCursor();
2701 return $ret;
2702 }
2703
2704 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2705 {
2706 if (empty ($name))
2707 return __FUNCTION__ . ': invalid arguments';
2708 if (!useInsertBlade
2709 (
2710 'IPv4RSPool',
2711 array
2712 (
2713 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2714 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2715 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2716 )
2717 ))
2718 return __FUNCTION__ . ': SQL insertion failed';
2719 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2720 }
2721
2722 function commitDeleteRSPool ($pool_id = 0)
2723 {
2724 global $dbxlink;
2725 if ($pool_id <= 0)
2726 return FALSE;
2727 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2728 }
2729
2730 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2731 {
2732 if ($pool_id <= 0)
2733 {
2734 showError ('Invalid arg', __FUNCTION__);
2735 die;
2736 }
2737 global $dbxlink;
2738 $query = "update IPv4RSPool set " .
2739 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2740 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2741 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2742 " where id = ${pool_id} limit 1";
2743 $result = $dbxlink->exec ($query);
2744 if ($result === NULL)
2745 return FALSE;
2746 elseif ($result != 1)
2747 return FALSE;
2748 else
2749 return TRUE;
2750 }
2751
2752 function getRSList ()
2753 {
2754 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2755 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
2756 $result = useSelectBlade ($query, __FUNCTION__);
2757 $ret = array ();
2758 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2759 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2760 $ret[$row['id']][$cname] = $row[$cname];
2761 $result->closeCursor();
2762 return $ret;
2763 }
2764
2765 // Return the list of all currently configured load balancers with their pool count.
2766 function getLBList ()
2767 {
2768 $query = "select object_id, count(rspool_id) as poolcount " .
2769 "from IPv4LB group by object_id order by object_id";
2770 $result = useSelectBlade ($query, __FUNCTION__);
2771 $ret = array ();
2772 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2773 $ret[$row['object_id']] = $row['poolcount'];
2774 $result->closeCursor();
2775 return $ret;
2776 }
2777
2778 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2779 // attached (each with vsconfig/rsconfig in turn), each with the list of
2780 // virtual services terminating the pool. Each pool also lists all real
2781 // servers with rsconfig.
2782 function getSLBConfig ($object_id)
2783 {
2784 if ($object_id <= 0)
2785 {
2786 showError ('Invalid arg', __FUNCTION__);
2787 return NULL;
2788 }
2789 $ret = array();
2790 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2791 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2792 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2793 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2794 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2795 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2796 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2797 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2798 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2799 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2800 $result = useSelectBlade ($query, __FUNCTION__);
2801 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2802 {
2803 $vs_id = $row['vs_id'];
2804 if (!isset ($ret[$vs_id]))
2805 {
2806 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name') as $c)
2807 $ret[$vs_id][$c] = $row[$c];
2808 $ret[$vs_id]['rslist'] = array();
2809 }
2810 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2811 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2812 }
2813 $result->closeCursor();
2814 return $ret;
2815 }
2816
2817 function commitSetInService ($rs_id = 0, $inservice = '')
2818 {
2819 if ($rs_id <= 0 or empty ($inservice))
2820 {
2821 showError ('Invalid args', __FUNCTION__);
2822 return NULL;
2823 }
2824 global $dbxlink;
2825 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
2826 $result = $dbxlink->exec ($query);
2827 if ($result === NULL)
2828 return FALSE;
2829 elseif ($result != 1)
2830 return FALSE;
2831 else
2832 return TRUE;
2833 }
2834
2835 function executeAutoPorts ($object_id = 0, $type_id = 0)
2836 {
2837 if ($object_id == 0 or $type_id == 0)
2838 {
2839 showError ('Invalid arguments', __FUNCTION__);
2840 die;
2841 }
2842 $ret = TRUE;
2843 foreach (getAutoPorts ($type_id) as $autoport)
2844 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2845 return $ret;
2846 }
2847
2848 // Return only implicitly listed tags, the rest of the chain will be
2849 // generated/deducted later at higher levels.
2850 // Result is a chain: randomly indexed taginfo list.
2851 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2852 {
2853 $ret = array();
2854 if (!in_array ($entity_realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2855 return $ret;
2856 $query = "select tt.id, tag from " .
2857 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2858 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
2859 "order by tt.tag";
2860 $result = useSelectBlade ($query, __FUNCTION__);
2861 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2862 $ret[$row['id']] = $row;
2863 $result->closeCursor();
2864 return getExplicitTagsOnly ($ret);
2865 }
2866
2867 // Return a tag chain with all DB tags on it.
2868 function getTagList ()
2869 {
2870 $ret = array();
2871 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2872 "from TagTree left join TagStorage on id = tag_id " .
2873 "group by id, entity_realm order by tag";
2874 $result = useSelectBlade ($query, __FUNCTION__);
2875 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2876 // which is utf8_general_ci for UTF-8.
2877 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2878 {
2879 if (!isset ($ret[$row['id']]))
2880 $ret[$row['id']] = array
2881 (
2882 'id' => $row['id'],
2883 'tag' => $row['tag'],
2884 'ci' => $ci++,
2885 'parent_id' => $row['parent_id'],
2886 'refcnt' => array()
2887 );
2888 if ($row['realm'])
2889 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2890 }
2891 $result->closeCursor();
2892 return $ret;
2893 }
2894
2895 function commitCreateTag ($tagname = '', $parent_id = 0)
2896 {
2897 if ($tagname == '' or $parent_id === 0)
2898 return "Invalid args to " . __FUNCTION__;
2899 $result = useInsertBlade
2900 (
2901 'TagTree',
2902 array
2903 (
2904 'tag' => "'${tagname}'",
2905 'parent_id' => $parent_id
2906 )
2907 );
2908 global $dbxlink;
2909 if ($result)
2910 return '';
2911 elseif ($dbxlink->errorCode() == 23000)
2912 return "name '${tag_name}' is already used";
2913 else
2914 return "SQL query failed in " . __FUNCTION__;
2915 }
2916
2917 function commitDestroyTag ($tagid = 0)
2918 {
2919 if ($tagid == 0)
2920 return 'Invalid arg to ' . __FUNCTION__;
2921 if (useDeleteBlade ('TagTree', 'id', $tagid))
2922 return '';
2923 else
2924 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2925 }
2926
2927 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2928 {
2929 if ($parent_id == 0)
2930 $parent_id = 'NULL';
2931 global $dbxlink;
2932 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2933 "where id = ${tag_id} limit 1";
2934 $result = $dbxlink->exec ($query);
2935 if ($result !== FALSE)
2936 return '';
2937 elseif ($dbxlink->errorCode() == 23000)
2938 return "name '${tag_name}' is already used";
2939 else
2940 return 'SQL query failed in ' . __FUNCTION__;
2941 }
2942
2943 // Drop the whole chain stored.
2944 function destroyTagsForEntity ($entity_realm, $entity_id)
2945 {
2946 global $dbxlink;
2947 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
2948 $result = $dbxlink->exec ($query);
2949 if ($result === NULL)
2950 return FALSE;
2951 else
2952 return TRUE;
2953 }
2954
2955 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2956 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2957 {
2958 global $dbxlink;
2959 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
2960 $result = $dbxlink->exec ($query);
2961 if ($result === NULL)
2962 return FALSE;
2963 else
2964 return TRUE;
2965 }
2966
2967 // Push a record into TagStorage unconditionally.
2968 function addTagForEntity ($realm = '', $entity_id, $tag_id)
2969 {
2970 if (empty ($realm))
2971 return FALSE;
2972 return useInsertBlade
2973 (
2974 'TagStorage',
2975 array
2976 (
2977 'entity_realm' => "'${realm}'",
2978 'entity_id' => $entity_id,
2979 'tag_id' => $tag_id,
2980 )
2981 );
2982 }
2983
2984 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2985 // on the implicit list already). Then remove any other records, which
2986 // appear on the "implicit" side of the chain. This will make sure,
2987 // that both the tag base is still minimal and all requested tags appear on
2988 // the resulting tag chain.
2989 // Return TRUE, if any changes were committed.
2990 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2991 {
2992 // Put the current explicit sub-chain into a buffer and merge all tags from
2993 // the extra chain, which aren't there yet.
2994 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2995 foreach ($extrachain as $extratag)
2996 if (!tagOnChain ($extratag, $newchain))
2997 $newchain[] = $extratag;
2998 // Then minimize the working buffer and check if it differs from the original
2999 // chain we started with. If it is so, save the work and signal the upper layer.
3000 $newchain = getExplicitTagsOnly ($newchain);
3001 if (tagChainCmp ($oldchain, $newchain))
3002 {
3003 destroyTagsForEntity ($realm, $entity_id);
3004 foreach ($newchain as $taginfo)
3005 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3006 return TRUE;
3007 }
3008 return FALSE;
3009 }
3010
3011 // Presume, that the target record has no tags attached.
3012 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3013 {
3014 if (!count ($tagidlist))
3015 return '';
3016 if (!$last_insert_id)
3017 $last_insert_id = lastInsertID();
3018 $errcount = 0;
3019 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
3020 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
3021 $errcount++;
3022 if (!$errcount)
3023 return '';
3024 else
3025 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3026 }
3027
3028 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3029 {
3030 // $range is in x.x.x.x/x format, split into ip/mask vars
3031 $rangeArray = explode('/', $range);
3032 if (count ($rangeArray) != 2)
3033 return "Invalid IPv4 prefix '${range}'";
3034 $ip = $rangeArray[0];
3035 $mask = $rangeArray[1];
3036
3037 if (empty ($ip) or empty ($mask))
3038 return "Invalid IPv4 prefix '${range}'";
3039 $ipL = ip2long($ip);
3040 $maskL = ip2long($mask);
3041 if ($ipL == -1 || $ipL === FALSE)
3042 return 'Bad IPv4 address';
3043 if ($mask < 32 && $mask > 0)
3044 $maskL = $mask;
3045 else
3046 {
3047 $maskB = decbin($maskL);
3048 if (strlen($maskB)!=32)
3049 return 'Invalid netmask';
3050 $ones=0;
3051 $zeroes=FALSE;
3052 foreach( str_split ($maskB) as $digit)
3053 {
3054 if ($digit == '0')
3055 $zeroes = TRUE;
3056 if ($digit == '1')
3057 {
3058 $ones++;
3059 if ($zeroes == TRUE)
3060 return 'Invalid netmask';
3061 }
3062 }
3063 $maskL = $ones;
3064 }
3065 $binmask = binMaskFromDec($maskL);
3066 $ipL = $ipL & $binmask;
3067 $result = useInsertBlade
3068 (
3069 'IPv4Network',
3070 array
3071 (
3072 'ip' => sprintf ('%u', $ipL),
3073 'mask' => "'${maskL}'",
3074 'name' => "'${name}'"
3075 )
3076 );
3077 if ($result != TRUE)
3078 return "Could not add ${range} (already exists?).";
3079
3080 if ($is_bcast and $maskL < 31)
3081 {
3082 $network_addr = long2ip ($ipL);
3083 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3084 updateAddress ($network_addr, 'network', 'yes');
3085 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3086 }
3087 return produceTagsForLastRecord ('ipv4net', $taglist);
3088 }
3089
3090 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
3091 function destroyIPv4Prefix ($id = 0)
3092 {
3093 if ($id <= 0)
3094 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
3095 if (!useDeleteBlade ('IPv4Network', 'id', $id))
3096 return __FUNCTION__ . ': SQL query #1 failed';
3097 if (!destroyTagsForEntity ('ipv4net', $id))
3098 return __FUNCTION__ . ': SQL query #2 failed';
3099 return '';
3100 }
3101
3102 function loadScript ($name)
3103 {
3104 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3105 $row = $result->fetch (PDO::FETCH_NUM);
3106 if ($row !== FALSE)
3107 return $row[0];
3108 else
3109 return NULL;
3110 }
3111
3112 function saveScript ($name, $text)
3113 {
3114 if (empty ($name))
3115 {
3116 showError ('Invalid argument');
3117 return FALSE;
3118 }
3119 // delete regardless of existence
3120 useDeleteBlade ('Script', 'script_name', "'${name}'");
3121 return useInsertBlade
3122 (
3123 'Script',
3124 array
3125 (
3126 'script_name' => "'${name}'",
3127 'script_text' => "'${text}'"
3128 )
3129 );
3130 }
3131
3132 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3133 {
3134 if (NULL === getIPv4AddressNetworkId ($localip))
3135 return "$localip: Non existant ip";
3136 if (NULL === getIPv4AddressNetworkId ($localip))
3137 return "$remoteip: Non existant ip";
3138 if ( ($localport <= 0) or ($localport >= 65536) )
3139 return "$localport: invaild port";
3140 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3141 return "$remoteport: invaild port";
3142
3143 $result = useInsertBlade
3144 (
3145 'IPv4NAT',
3146 array
3147 (
3148 'object_id' => $object_id,
3149 'localip' => "INET_ATON('${localip}')",
3150 'remoteip' => "INET_ATON('$remoteip')",
3151 'localport' => $localport,
3152 'remoteport' => $remoteport,
3153 'proto' => "'${proto}'",
3154 'description' => "'${description}'",
3155 )
3156 );
3157 if ($result)
3158 return '';
3159 else
3160 return __FUNCTION__ . ': Failed to insert the rule.';
3161 }
3162
3163 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3164 {
3165 global $dbxlink;
3166
3167 $query =
3168 "delete from IPv4NAT where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3169 $result = $dbxlink->exec ($query);
3170 return '';
3171 }
3172
3173 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3174 {
3175 global $dbxlink;
3176
3177 $query =
3178 "update IPv4NAT set description='$description' where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3179 $result = $dbxlink->exec ($query);
3180 return '';
3181 }
3182
3183 function getNATv4ForObject ($object_id)
3184 {
3185 $ret = array();
3186 $ret['out'] = array();
3187 $ret['in'] = array();
3188 $query =
3189 "select ".
3190 "proto, ".
3191 "INET_NTOA(localip) as localip, ".
3192 "localport, ".
3193 "INET_NTOA(remoteip) as remoteip, ".
3194 "remoteport, ".
3195 "ipa1.name as local_addr_name, " .
3196 "ipa2.name as remote_addr_name, " .
3197 "description ".
3198 "from IPv4NAT ".
3199 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3200 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
3201 "where object_id='$object_id' ".
3202 "order by localip, localport, proto, remoteip, remoteport";
3203 $result = useSelectBlade ($query, __FUNCTION__);
3204 $count=0;
3205 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3206 {
3207 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3208 $ret['out'][$count][$cname] = $row[$cname];
3209 $count++;
3210 }
3211 $result->closeCursor();
3212 unset ($result);
3213
3214 $query =
3215 "select ".
3216 "proto, ".
3217 "INET_NTOA(localip) as localip, ".
3218 "localport, ".
3219 "INET_NTOA(remoteip) as remoteip, ".
3220 "remoteport, ".
3221 "IPv4NAT.object_id as object_id, ".
3222 "RackObject.name as object_name, ".
3223 "description ".
3224 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3225 "where IPv4Allocation.object_id='$object_id' ".
3226 "order by remoteip, remoteport, proto, localip, localport";
3227 $result = useSelectBlade ($query, __FUNCTION__);
3228 $count=0;
3229 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3230 {
3231 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3232 $ret['in'][$count][$cname] = $row[$cname];
3233 $count++;
3234 }
3235 $result->closeCursor();
3236
3237 return $ret;
3238 }
3239
3240 // This function performs search and then calculates score for each result.
3241 // Given previous search results in $objects argument, it adds new results
3242 // to the array and updates score for existing results, if it is greater than
3243 // existing score.
3244 function mergeSearchResults (&$objects, $terms, $fieldname)
3245 {
3246 global $dbxlink;
3247 $query =
3248 "select ro.name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3249 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3250 "on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id where Chapter.name = 'RackObjectType' and ";
3251 $count = 0;
3252 foreach (explode (' ', $terms) as $term)
3253 {
3254 if ($count) $query .= ' or ';
3255 $query .= "ro.${fieldname} like '%$term%'";
3256 $count++;
3257 }
3258 $query .= " order by ${fieldname}";
3259 $result = useSelectBlade ($query, __FUNCTION__);
3260 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3261 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3262 {
3263 foreach ($clist as $cname)
3264 $object[$cname] = $row[$cname];
3265 $object['score'] = 0;
3266 $object['dname'] = displayedName ($object);
3267 unset ($object['objtype_id']);
3268 foreach (explode (' ', $terms) as $term)
3269 if (strstr ($object['name'], $term))
3270 $object['score'] += 1;
3271 unset ($object['name']);
3272 if (!isset ($objects[$row['id']]))
3273 $objects[$row['id']] = $object;
3274 elseif ($objects[$row['id']]['score'] < $object['score'])
3275 $objects[$row['id']]['score'] = $object['score'];
3276 }
3277 return $objects;
3278 }
3279
3280 function getLostIPv4Addresses ()
3281 {
3282 dragon();
3283 }
3284
3285 // Return a list of files which are not linked to the specified record. This list
3286 // will be used by printSelect().
3287 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3288 {
3289 if ($entity_type == NULL || $entity_id == 0)
3290 {
3291 showError ('Invalid parameters', __FUNCTION__);
3292 return NULL;
3293 }
3294 global $dbxlink;
3295 $sql =
3296 'SELECT id, name FROM File ' .
3297 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
3298 'ORDER BY name, id';
3299 $query = $dbxlink->prepare($sql);
3300 $query->bindParam(1, $entity_type);
3301 $query->bindParam(2, $entity_id);
3302 $query->execute();
3303 $ret=array();
3304 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3305 $ret[$row['id']] = $row['name'];
3306 return $ret;
3307 }
3308
3309 function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3310 {
3311 if ($entity_type == NULL || $entity_id == 0)
3312 {
3313 showError ('Invalid parameters', __FUNCTION__);
3314 return NULL;
3315 }
3316 global $dbxlink;
3317 $sql =
3318 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3319 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3320 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3321 $query = $dbxlink->prepare($sql);
3322 $query->bindParam(1, $entity_type);
3323 $query->bindParam(2, $entity_id);
3324 $query->execute();
3325 $ret = array();
3326 while ($row = $query->fetch (PDO::FETCH_ASSOC))
3327 $ret[$row['file_id']] = array (
3328 'id' => $row['file_id'],
3329 'link_id' => $row['link_id'],
3330 'name' => $row['name'],
3331 'type' => $row['type'],
3332 'size' => $row['size'],
3333 'ctime' => $row['ctime'],
3334 'mtime' => $row['mtime'],
3335 'atime' => $row['atime'],
3336 'comment' => $row['comment'],
3337 );
3338 return $ret;
3339 }
3340
3341 function getFile ($file_id = 0)
3342 {
3343 if ($file_id == 0)
3344 {
3345 showError ('Invalid file_id', __FUNCTION__);
3346 return NULL;
3347 }
3348 global $dbxlink;
3349 $query = $dbxlink->prepare('SELECT * FROM File WHERE id = ?');
3350 $query->bindParam(1, $file_id);
3351 $query->execute();
3352 if (($row = $query->fetch (PDO::FETCH_ASSOC)) == NULL)
3353 {
3354 showError ('Query succeeded, but returned no data', __FUNCTION__);
3355 $ret = NULL;
3356 }
3357 else
3358 {
3359 $ret = array();
3360 $ret['id'] = $row['id'];
3361 $ret['name'] = $row['name'];
3362 $ret['type'] = $row['type'];
3363 $ret['size'] = $row['size'];
3364 $ret['ctime'] = $row['ctime'];
3365 $ret['mtime'] = $row['mtime'];
3366 $ret['atime'] = $row['atime'];
3367 $ret['contents'] = $row['contents'];
3368 $ret['comment'] = $row['comment'];
3369 $query->closeCursor();
3370
3371 // Someone accessed this file, update atime