82266441e1832b7021d07e33eb17754ad98982b8
4 * This file is a library of database access functions for RackTables.
8 function isInnoDBSupported ($dbh = FALSE) {
11 // sometimes db handle isn't available globally, must be passed
15 // create a temp table
16 $dbxlink->query("CREATE TABLE `innodb_test` (`id` int) ENGINE=InnoDB");
17 $row = $dbxlink->query("SHOW TABLE STATUS LIKE 'innodb_test'")->fetch(PDO
::FETCH_ASSOC
);
18 $dbxlink->query("DROP TABLE `innodb_test`");
19 if ($row['Engine'] == 'InnoDB')
25 function escapeString ($value, $do_db_escape = TRUE)
27 $ret = htmlspecialchars ($value, ENT_QUOTES
, 'UTF-8');
31 $ret = substr ($dbxlink->quote ($ret), 1, -1);
36 // Return detailed information about one rack row.
37 function getRackRowInfo ($rackrow_id)
40 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
41 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
42 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
43 "where RackRow.id = ${rackrow_id} " .
44 "group by RackRow.id";
45 $result = useSelectBlade ($query, __FUNCTION__
);
46 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
52 function getRackRows ()
54 $query = "select id, name from RackRow ";
55 $result = useSelectBlade ($query, __FUNCTION__
);
57 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
58 $rows[$row['id']] = parseWikiLink ($row['name'], 'o');
59 $result->closeCursor();
64 function commitAddRow($rackrow_name)
66 return useInsertBlade('RackRow', array('name'=>"'$rackrow_name'"));
69 function commitUpdateRow($rackrow_id, $rackrow_name)
72 $query = "update RackRow set name = '${rackrow_name}' where id=${rackrow_id}";
73 $result = $dbxlink->query ($query);
76 showError ("SQL query '${query}' failed", __FUNCTION__
);
79 $result->closeCursor();
83 function commitDeleteRow($rackrow_id)
86 $query = "select count(*) from Rack where row_id=${rackrow_id}";
87 $result = $dbxlink->query ($query);
88 if (($result!=NULL) && ($row = $result->fetch(PDO
::FETCH_NUM
)) )
92 $query = "delete from RackRow where id=${rackrow_id}";
93 $result = $dbxlink->query ($query);
96 showError ("SQL query '${query}' failed", __FUNCTION__
);
103 showError ("SQL query '${query}' failed", __FUNCTION__
);
106 $result->closeCursor();
110 // This function returns id->name map for all object types. The map is used
111 // to build <select> input for objects.
112 function getObjectTypeList ()
114 return readChapter ('RackObjectType');
117 // Return a simple object list w/o related information, so that the returned value
118 // can be directly used by printSelect(). An optional argument is the name of config
119 // option with constraint in RackCode.
120 function getNarrowObjectList ($varname = '')
125 "select RackObject.id as id, RackObject.name as name, dict_value as objtype_name, " .
127 "RackObject inner join Dictionary on objtype_id=dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
128 "where Chapter.name = 'RackObjectType' " .
129 "order by objtype_id, name";
130 $result = useSelectBlade ($query, __FUNCTION__
);
131 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
132 $ret[$row['id']] = displayedName ($row);
133 if (strlen ($varname) and strlen (getConfigVar ($varname)))
136 if (!isset ($parseCache[$varname]))
137 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
138 if ($parseCache[$varname]['result'] != 'ACK')
140 $ret = filterEntityList ($ret, 'object', $parseCache[$varname]['load']);
145 // For a given realm return a list of entity records, each with
146 // enough information for judgeEntityRecord() to execute.
147 function listCells ($realm, $parent_id = 0)
152 $table = 'RackObject';
158 'barcode' => 'barcode',
159 'asset_no' => 'asset_no',
160 'objtype_id' => 'objtype_id',
161 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
162 'Rack_name' => '(select name from Rack where id = rack_id)',
163 'row_id' => '(select row_id from Rack where id = rack_id)',
164 'Row_name' => '(select name from RackRow where id = row_id)',
165 'objtype_name' => '(select dict_value from Dictionary where dict_key = objtype_id)',
168 $ordcolumns = array ('name');
171 $table= 'UserAccount';
174 'user_id' => 'user_id',
175 'user_name' => 'user_name',
176 'user_password_hash' => 'user_password_hash',
177 'user_realname' => 'user_realname',
179 $keycolumn = 'user_id';
180 $ordcolumns = array ('user_name');
183 $table = 'IPv4Network';
187 'ip' => 'INET_NTOA(IPv4Network.ip)',
192 $ordcolumns = array ('ip', 'mask');
205 'comment' => 'comment',
208 $ordcolumns = array ('name');
215 'vip' => 'INET_NTOA(vip)',
219 'vsconfig' => 'vsconfig',
220 'rsconfig' => 'rsconfig',
221 'poolcount' => '(select count(vs_id) from IPv4LB where vs_id = id)',
222 'dname' => 'CONCAT_WS("/", CONCAT_WS(":", INET_NTOA(vip), vport), proto)',
225 $ordcolumns = array ('vip', 'proto', 'vport');
228 $table = 'IPv4RSPool';
233 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
234 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
235 'vsconfig' => 'vsconfig',
236 'rsconfig' => 'rsconfig',
239 $ordcolumns = array ('name', 'id');
247 'height' => 'height',
248 'comment' => 'comment',
249 'row_id' => 'row_id',
250 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
253 $ordcolumns = array ('row_id', 'name');
254 $pidcolumn = 'row_id';
257 showError ('invalid arg', __FUNCTION__
);
260 $query = 'SELECT tag_id';
261 foreach ($columns as $alias => $expression)
262 // Automatically prepend table name to each single column, but leave all others intact.
263 $query .= ', ' . ($alias == $expression ?
"${table}.${alias}" : "${expression} as ${alias}");
264 $query .= " FROM ${table} LEFT JOIN TagStorage on entity_realm = '${realm}' and entity_id = ${table}.${keycolumn}";
265 if (isset ($pidcolumn) and $parent_id)
266 $query .= " WHERE ${table}.${pidcolumn} = ${parent_id}";
267 $query .= " ORDER BY ";
268 foreach ($ordcolumns as $oc)
269 $query .= "${table}.${oc}, ";
271 $result = useSelectBlade ($query, __FUNCTION__
);
274 // Index returned result by the value of key column.
275 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
277 $entity_id = $row[$keycolumn];
278 // Init the first record anyway, but store tag only if there is one.
279 if (!isset ($ret[$entity_id]))
281 $ret[$entity_id] = array ('realm' => $realm);
282 foreach (array_keys ($columns) as $alias)
283 $ret[$entity_id][$alias] = $row[$alias];
284 $ret[$entity_id]['etags'] = array();
285 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
286 $ret[$entity_id]['etags'][] = array
288 'id' => $row['tag_id'],
289 'tag' => $taglist[$row['tag_id']]['tag'],
290 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
294 // Meeting existing key later is always more tags on existing list.
295 $ret[$entity_id]['etags'][] = array
297 'id' => $row['tag_id'],
298 'tag' => $taglist[$row['tag_id']]['tag'],
299 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
302 // Add necessary finish to the list before returning it.
303 foreach (array_keys ($ret) as $entity_id)
305 $ret[$entity_id]['itags'] = getImplicitTags ($ret[$entity_id]['etags']);
306 $ret[$entity_id]['atags'] = generateEntityAutoTags ($realm, $entity_id);
310 $ret[$entity_id]['dname'] = displayedName ($ret[$entity_id]);
319 // This function can be used with array_walk().
320 function amplifyCell (&$record, $dummy = NULL)
322 switch ($record['realm'])
325 $record['ports'] = getObjectPortsAndLinks ($record['id']);
326 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
327 $record['nat4'] = getNATv4ForObject ($record['id']);
328 $record['ipv4rspools'] = getRSPoolsForObject ($record['id']);
329 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
332 $record['ip_bin'] = ip2long ($record['ip']);
333 $record['parent_id'] = getIPv4AddressNetworkId ($record['ip'], $record['mask']);
336 $record['links'] = getFileLinks ($record['id']);
342 // This is a popular helper for getting information about
343 // a particular rack and its rackspace at once.
344 function getRackData ($rack_id = 0, $silent = FALSE)
348 if ($silent == FALSE)
349 showError ('Invalid rack_id', __FUNCTION__
);
353 "select Rack.id, Rack.name, row_id, height, Rack.comment, RackRow.name as row_name from " .
354 "Rack left join RackRow on Rack.row_id = RackRow.id " .
355 "where Rack.id='${rack_id}'";
356 $result = useSelectBlade ($query, __FUNCTION__
);
357 if (($row = $result->fetch (PDO
::FETCH_ASSOC
)) == NULL)
359 if ($silent == FALSE)
360 showError ('Query #1 succeded, but returned no data', __FUNCTION__
);
374 foreach ($clist as $cname)
375 $rack[$cname] = $row[$cname];
376 $result->closeCursor();
379 // start with default rackspace
380 for ($i = $rack['height']; $i > 0; $i--)
381 for ($locidx = 0; $locidx < 3; $locidx++
)
382 $rack[$i][$locidx]['state'] = 'F';
386 "select unit_no, atom, state, object_id " .
387 "from RackSpace where rack_id = ${rack_id} and " .
388 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
389 $result = useSelectBlade ($query, __FUNCTION__
);
391 $mounted_objects = array();
392 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
394 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
395 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
396 if ($row['state'] == 'T' and $row['object_id']!=NULL)
397 $mounted_objects[$row['object_id']] = TRUE;
399 $rack['mountedObjects'] = array_keys($mounted_objects);
400 $result->closeCursor();
404 // This is a popular helper.
405 function getObjectInfo ($object_id = 0, $set_dname = TRUE)
408 "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 " .
409 "RackObject inner join Dictionary on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
410 "where RackObject.id = '${object_id}' and Chapter.name = 'RackObjectType'";
411 $result = useSelectBlade ($query, __FUNCTION__
);
412 if (($ret = $result->fetch (PDO
::FETCH_ASSOC
)) == NULL)
414 showError ('Query succeeded, but returned no data', __FUNCTION__
);
417 $result->closeCursor();
418 // It's safe now to run subsequent queries.
420 $ret['dname'] = displayedName ($ret);
424 function getPortTypes ()
426 return readChapter ('PortType');
429 function getObjectPortsAndLinks ($object_id = 0)
433 showError ('Invalid object_id', __FUNCTION__
);
437 $ptd = readChapter ('PortType');
438 $query = "select id, name, label, l2address, type as type_id, reservation_comment from Port where object_id = ${object_id}";
439 // list and decode all ports of the current object
440 $result = useSelectBlade ($query, __FUNCTION__
);
442 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
444 $row['type'] = $ptd[$row['type_id']];
445 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
446 $row['remote_id'] = NULL;
447 $row['remote_name'] = NULL;
448 $row['remote_object_id'] = NULL;
449 $row['remote_object_name'] = NULL;
453 // now find and decode remote ends for all locally terminated connections
454 foreach (array_keys ($ret) as $tmpkey)
456 $portid = $ret[$tmpkey]['id'];
458 $query = "select porta, portb from Link where porta = {$portid} or portb = ${portid}";
459 $result = useSelectBlade ($query, __FUNCTION__
);
460 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
462 if ($portid != $row['porta'])
463 $remote_id = $row['porta'];
464 elseif ($portid != $row['portb'])
465 $remote_id = $row['portb'];
468 if ($remote_id) // there's a remote end here
470 $query = "select Port.name as port_name, Port.type as port_type, object_id, RackObject.name as object_name " .
471 "from Port left join RackObject on Port.object_id = RackObject.id " .
472 "where Port.id = ${remote_id}";
473 $result = useSelectBlade ($query, __FUNCTION__
);
474 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
476 $ret[$tmpkey]['remote_name'] = $row['port_name'];
477 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
478 $ret[$tmpkey]['remote_object_name'] = $row['object_name'];
480 $ret[$tmpkey]['remote_id'] = $remote_id;
482 // only call displayedName() when necessary
483 if (empty ($ret[$tmpkey]['remote_object_name']) and !empty ($ret[$tmpkey]['remote_object_id']))
485 $oi = getObjectInfo ($ret[$tmpkey]['remote_object_id']);
486 $ret[$tmpkey]['remote_object_name'] = $oi['dname'];
493 function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
495 if ($row_id <= 0 or $height <= 0 or empty ($name))
497 $result = useInsertBlade
503 'name' => "'${name}'",
505 'comment' => "'${comment}'"
510 showError ('useInsertBlade() failed', __FUNCTION__
);
513 $last_insert_id = lastInsertID();
514 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', "id = ${last_insert_id}");
517 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
520 // Maintain UNIQUE INDEX for common names and asset tags by
521 // filtering out empty strings (not NULLs).
522 $result1 = useInsertBlade
527 'name' => empty ($new_name) ?
'NULL' : "'${new_name}'",
528 'label' => "'${new_label}'",
529 'barcode' => empty ($new_barcode) ?
'NULL' : "'${new_barcode}'",
530 'objtype_id' => $new_type_id,
531 'asset_no' => empty ($new_asset_no) ?
'NULL' : "'${new_asset_no}'"
534 if ($result1 == NULL)
536 showError ("SQL query #1 failed", __FUNCTION__
);
539 $last_insert_id = lastInsertID();
540 // Do AutoPorts magic
541 executeAutoPorts ($last_insert_id, $new_type_id);
543 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
546 showError ("Error adding tags for the object: ${error}");
549 return recordHistory ('RackObject', "id = ${last_insert_id}");
552 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
554 if ($object_id == 0 ||
$new_type_id == 0)
556 showError ('Not all required args are present.', __FUNCTION__
);
560 $new_asset_no = empty ($new_asset_no) ?
'NULL' : "'${new_asset_no}'";
561 $new_barcode = empty ($new_barcode) ?
'NULL' : "'${new_barcode}'";
562 $new_name = empty ($new_name) ?
'NULL' : "'${new_name}'";
563 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
564 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
565 "where id='${object_id}' limit 1";
566 $result = $dbxlink->query ($query);
569 showError ("SQL query '${query}' failed", __FUNCTION__
);
572 $result->closeCursor();
573 return recordHistory ('RackObject', "id = ${object_id}");
576 // There are times when you want to delete all traces of an object
577 function commitDeleteObject ($object_id = 0)
581 showError ('Invalid args', __FUNCTION__
);
585 $dbxlink->query("DELETE FROM AttributeValue WHERE object_id = ${object_id}");
586 $dbxlink->query("DELETE FROM File WHERE id IN (SELECT file_id FROM FileLink WHERE entity_id = 'object' AND entity_id = ${object_id})");
587 $dbxlink->query("DELETE FROM IPv4LB WHERE object_id = ${object_id}");
588 $dbxlink->query("DELETE FROM IPv4Allocation WHERE object_id = ${object_id}");
589 $dbxlink->query("DELETE FROM Port WHERE object_id = ${object_id}");
590 $dbxlink->query("DELETE FROM IPv4NAT WHERE object_id = ${object_id}");
591 $dbxlink->query("DELETE FROM RackSpace WHERE object_id = ${object_id}");
592 $dbxlink->query("DELETE FROM TagStorage WHERE entity_realm = 'object' and entity_id = ${object_id}");
593 $dbxlink->query("DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ${object_id})");
594 $dbxlink->query("DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ${object_id})");
595 $dbxlink->query("DELETE FROM MountOperation WHERE object_id = ${object_id}");
596 $dbxlink->query("DELETE FROM RackObjectHistory WHERE id = ${object_id}");
597 $dbxlink->query("DELETE FROM RackObject WHERE id = ${object_id}");
602 function commitDeleteRack($rack_id)
605 $query = "delete from RackSpace where rack_id = '${rack_id}'";
606 $dbxlink->query ($query);
607 $query = "delete from TagStorage where entity_realm='rack' and entity_id='${rack_id}'";
608 $dbxlink->query ($query);
609 $query = "delete from RackHistory where id = '${rack_id}'";
610 $dbxlink->query ($query);
611 $query = "delete from Rack where id = '${rack_id}'";
612 $dbxlink->query ($query);
616 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
618 if (empty ($rack_id) ||
empty ($new_name) ||
empty ($new_height))
620 showError ('Not all required args are present.', __FUNCTION__
);
625 // Can't shrink a rack if rows being deleted contain mounted objects
626 $check_sql = "SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = '${rack_id}' AND unit_no > '{$new_height}'";
627 $check_result = $dbxlink->query($check_sql);
628 $check_row = $check_result->fetch (PDO
::FETCH_ASSOC
);
629 if ($check_row['count'] > 0) {
630 showError ('Cannot shrink rack, objects are still mounted there', __FUNCTION__
);
634 $update_sql = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
635 "where id='${rack_id}' limit 1";
636 $update_result = $dbxlink->query ($update_sql);
637 if ($update_result->rowCount() != 1)
639 showError ('Error updating rack information', __FUNCTION__
);
642 return recordHistory ('Rack', "id = ${rack_id}");
645 // This function accepts rack data returned by getRackData(), validates and applies changes
646 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
647 // correspond to current rack ID.
648 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
649 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
650 // The function returns the modified rack upon success.
651 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
653 global $loclist, $dbxlink;
654 $rack_id = $rackData['id'];
655 $rack_name = $rackData['name'];
656 $rackchanged = FALSE;
657 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
659 for ($locidx = 0; $locidx < 3; $locidx++
)
661 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
664 $state = $rackData[$unit_no][$locidx]['state'];
665 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
666 $newstate = $checked_state;
668 $newstate = $unchecked_state;
669 if ($state == $newstate)
673 $atom = $loclist[$locidx];
674 // The only changes allowed are those introduced by checkbox grid.
677 !($state == $checked_state && $newstate == $unchecked_state) &&
678 !($state == $unchecked_state && $newstate == $checked_state)
680 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
681 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
682 // anyway and then looking for probable need of INSERT.
684 "delete from RackSpace where rack_id = ${rack_id} and " .
685 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
686 $r = $dbxlink->query ($query);
688 return array ('code' => 500, 'message' => __FUNCTION__
. ": ${rack_name}: SQL DELETE query failed");
689 if ($newstate != 'F')
692 "insert into RackSpace(rack_id, unit_no, atom, state) " .
693 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
694 $r = $dbxlink->query ($query);
696 return array ('code' => 500, 'message' => __FUNCTION__
. ": ${rack_name}: SQL INSERT query failed");
698 if ($newstate == 'T' and $object_id != 0)
700 // At this point we already have a record in RackSpace.
702 "update RackSpace set object_id=${object_id} " .
703 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
704 $r = $dbxlink->query ($query);
705 if ($r->rowCount() == 1)
706 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
708 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
714 resetThumbCache ($rack_id);
715 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
718 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
721 // This function builds a list of rack-unit-atom records, which are assigned to
722 // the requested object.
723 function getMoleculeForObject ($object_id = 0)
727 showError ("object_id == 0", __FUNCTION__
);
731 "select rack_id, unit_no, atom from RackSpace " .
732 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
733 $result = useSelectBlade ($query, __FUNCTION__
);
734 $ret = $result->fetchAll (PDO
::FETCH_ASSOC
);
735 $result->closeCursor();
739 // This function builds a list of rack-unit-atom records for requested molecule.
740 function getMolecule ($mid = 0)
744 showError ("mid == 0", __FUNCTION__
);
748 "select rack_id, unit_no, atom from Atom " .
749 "where molecule_id=${mid}";
750 $result = useSelectBlade ($query, __FUNCTION__
);
751 $ret = $result->fetchAll (PDO
::FETCH_ASSOC
);
752 $result->closeCursor();
756 // returns exactly what is's named after
757 function lastInsertID ()
759 if (NULL == ($result = useSelectBlade ('select last_insert_id()', __FUNCTION__
)))
761 showError ('SQL query failed!', __FUNCTION__
);
764 $row = $result->fetch (PDO
::FETCH_NUM
);
768 // This function creates a new record in Molecule and number of linked
769 // R-U-A records in Atom.
770 function createMolecule ($molData)
773 $query = "insert into Molecule values()";
774 $result1 = $dbxlink->query ($query);
775 if ($result1->rowCount() != 1)
777 showError ('Error inserting into Molecule', __FUNCTION__
);
780 $molecule_id = lastInsertID();
781 foreach ($molData as $rua)
783 $rack_id = $rua['rack_id'];
784 $unit_no = $rua['unit_no'];
785 $atom = $rua['atom'];
787 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
788 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
789 $result3 = $dbxlink->query ($query);
790 if ($result3 == NULL or $result3->rowCount() != 1)
792 showError ('Error inserting into Atom', __FUNCTION__
);
799 // History logger. This function assumes certain table naming convention and
801 // 1. History table name equals to dictionary table name plus 'History'.
802 // 2. History table must have the same row set (w/o keys) plus one row named
803 // 'ctime' of type 'timestamp'.
804 function recordHistory ($tableName, $whereClause)
806 global $dbxlink, $remote_username;
807 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
808 $result = $dbxlink->query ($query);
809 if ($result == NULL or $result->rowCount() != 1)
811 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__
);
817 function getRackspaceHistory ()
820 "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 " .
821 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
822 "inner join Dictionary on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
823 "where Chapter.name = 'RackObjectType' order by ctime desc";
824 $result = useSelectBlade ($query, __FUNCTION__
);
825 $ret = $result->fetchAll(PDO
::FETCH_ASSOC
);
826 $result->closeCursor();
830 // This function is used in renderRackspaceHistory()
831 function getOperationMolecules ($op_id = 0)
835 showError ("Missing argument", __FUNCTION__
);
838 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
839 $result = useSelectBlade ($query, __FUNCTION__
);
840 // We expect one row.
841 $row = $result->fetch (PDO
::FETCH_ASSOC
);
844 showError ("SQL query succeded, but returned no results.", __FUNCTION__
);
847 $omid = $row['old_molecule_id'];
848 $nmid = $row['new_molecule_id'];
849 $result->closeCursor();
850 return array ($omid, $nmid);
853 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
857 showError ('Invalid object_id', __FUNCTION__
);
860 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
861 $result = useSelectBlade ($query, __FUNCTION__
);
862 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
863 $result->closeCursor();
865 foreach ($rows as $row)
867 if (!$fetch_rackdata)
869 $ret[$row[0]] = $row[0];
872 $rackData = getRackData ($row[0]);
873 if ($rackData == NULL)
875 showError ('getRackData() failed', __FUNCTION__
);
878 $ret[$row[0]] = $rackData;
880 $result->closeCursor();
884 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
888 showError ('Invalid object_id', __FUNCTION__
);
891 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
892 return "Invalid L2 address ${port_l2address}";
893 $result = useInsertBlade
898 'name' => "'${port_name}'",
899 'object_id' => "'${object_id}'",
900 'label' => "'${port_label}'",
901 'type' => "'${port_type_id}'",
902 'l2address' => ($db_l2address === '') ?
'NULL' : "'${db_l2address}'"
908 return 'SQL query failed';
911 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
912 // string value. In case it is omitted, we just assign it its current value.
913 // It would be nice to simplify this semantics later.
914 function commitUpdatePort ($port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
917 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
918 return "Invalid L2 address ${port_l2address}";
920 "update Port set name='$port_name', type=$port_type_id, label='$port_label', " .
921 "reservation_comment = ${port_reservation_comment}, l2address=" .
922 (($db_l2address === '') ?
'NULL' : "'${db_l2address}'") .
923 " where id='$port_id'";
924 $result = $dbxlink->exec ($query);
927 $errorInfo = $dbxlink->errorInfo();
928 // We could update nothing.
929 if ($errorInfo[0] == '00000')
931 return $errorInfo[2];
934 function delObjectPort ($port_id)
936 if (unlinkPort ($port_id) != '')
937 return __FUNCTION__
. ': unlinkPort() failed';
938 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
939 return __FUNCTION__
. ': useDeleteBlade() failed';
943 function getAllIPv4Allocations ()
946 "select object_id as object_id, ".
947 "RackObject.name as object_name, ".
948 "IPv4Allocation.name as name, ".
949 "INET_NTOA(ip) as ip ".
950 "from IPv4Allocation join RackObject on id=object_id ";
951 $result = useSelectBlade ($query, __FUNCTION__
);
954 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
956 $ret[$count]['object_id']=$row['object_id'];
957 $ret[$count]['object_name']=$row['object_name'];
958 $ret[$count]['name']=$row['name'];
959 $ret[$count]['ip']=$row['ip'];
962 $result->closeCursor();
966 function getEmptyPortsOfType ($type_id)
969 "select distinct Port.id as Port_id, ".
970 "Port.object_id as Port_object_id, ".
971 "RackObject.name as Object_name, ".
972 "Port.name as Port_name, ".
973 "Port.type as Port_type_id, ".
974 "dict_value as Port_type_name ".
977 " Port inner join Dictionary on Port.type = dict_key join Chapter on Chapter.id = Dictionary.chapter_id ".
979 " join RackObject on Port.object_id = RackObject.id ".
981 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
982 "inner join PortCompat on Port.type = PortCompat.type2 ".
983 "where Chapter.name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
984 "and Port.reservation_comment is null order by Object_name, Port_name";
985 $result = useSelectBlade ($query, __FUNCTION__
);
988 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
990 $ret[$count]['Port_id']=$row['Port_id'];
991 $ret[$count]['Port_object_id']=$row['Port_object_id'];
992 $ret[$count]['Object_name']=$row['Object_name'];
993 $ret[$count]['Port_name']=$row['Port_name'];
994 $ret[$count]['Port_type_id']=$row['Port_type_id'];
995 $ret[$count]['Port_type_name']=$row['Port_type_name'];
998 $result->closeCursor();
1002 function linkPorts ($porta, $portb)
1004 if ($porta == $portb)
1005 return "Ports can't be the same";
1006 if ($porta > $portb)
1013 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
1014 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
1015 // FIXME: who cares about the return value?
1016 $result = $dbxlink->exec ($query1);
1017 $result = $dbxlink->exec ($query2);
1021 function unlinkPort ($port)
1025 "delete from Link where porta='$port' or portb='$port'";
1026 $result = $dbxlink->exec ($query);
1030 // Return all IPv4 addresses allocated to the objects. Attach detailed
1031 // info about address to each alocation records. Index result by dotted-quad
1033 function getObjectIPv4Allocations ($object_id = 0)
1036 $query = 'select name as osif, type, inet_ntoa(ip) as dottedquad from IPv4Allocation ' .
1037 "where object_id = ${object_id} " .
1039 $result = useSelectBlade ($query, __FUNCTION__
);
1040 // don't spawn a sub-query with unfetched buffer, it may fail
1041 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1042 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1044 foreach (array_keys ($ret) as $dottedquad)
1045 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
1049 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
1050 function constructIPv4Address ($dottedquad = NULL)
1058 'rslist' => array(),
1059 'allocs' => array(),
1062 if ($dottedquad != NULL)
1063 $ret['ip'] = $dottedquad;
1067 // Check the range requested for meaningful IPv4 records, build them
1068 // into a list and return. Return an empty list if nothing matched.
1069 // Both arguments are expected in signed int32 form. The resulting list
1070 // is keyed by uint32 form of each IP address, items aren't sorted.
1071 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
1072 function scanIPv4Space ($pairlist)
1075 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
1077 $dnamechache = array();
1078 // FIXME: this is a copy-and-paste prototype
1086 foreach ($pairlist as $tmp)
1088 $db_first = sprintf ('%u', 0x00000000 +
$tmp['i32_first']);
1089 $db_last = sprintf ('%u', 0x00000000 +
$tmp['i32_last']);
1090 $whereexpr1 .= $or . "ip between ${db_first} and ${db_last}";
1091 $whereexpr2 .= $or . "ip between ${db_first} and ${db_last}";
1092 $whereexpr3 .= $or . "vip between ${db_first} and ${db_last}";
1093 $whereexpr4 .= $or . "rsip between ${db_first} and ${db_last}";
1094 $whereexpr5a .= $or . "remoteip between ${db_first} and ${db_last}";
1095 $whereexpr5b .= $or . "localip between ${db_first} and ${db_last}";
1102 $whereexpr5a .= ')';
1103 $whereexpr5b .= ')';
1105 // 1. collect labels and reservations
1106 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
1107 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1108 $result = useSelectBlade ($query, __FUNCTION__
);
1109 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1111 $ip_bin = ip2long ($row['ip']);
1112 if (!isset ($ret[$ip_bin]))
1113 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1114 $ret[$ip_bin]['name'] = $row['name'];
1115 $ret[$ip_bin]['reserved'] = $row['reserved'];
1119 // 2. check for allocations
1121 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
1122 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
1123 "dict_value as objtype_name from " .
1124 "IPv4Allocation as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
1125 "left join Dictionary on objtype_id=dict_key join Chapter on Chapter.id = Dictionary.chapter_id " .
1126 "where ${whereexpr2} " .
1127 "and Chapter.name = 'RackObjectType'" .
1128 "order by ipb.type, object_name";
1129 $result = useSelectBlade ($query, __FUNCTION__
);
1130 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1132 $ip_bin = ip2long ($row['ip']);
1133 if (!isset ($ret[$ip_bin]))
1134 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1135 if (!isset ($dnamecache[$row['object_id']]))
1137 $quasiobject['id'] = $row['object_id'];
1138 $quasiobject['name'] = $row['object_name'];
1139 $quasiobject['objtype_id'] = $row['objtype_id'];
1140 $quasiobject['objtype_name'] = $row['objtype_name'];
1141 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1144 foreach (array ('object_id', 'type', 'name') as $cname)
1145 $tmp[$cname] = $row[$cname];
1146 $tmp['object_name'] = $dnamecache[$row['object_id']];
1147 $ret[$ip_bin]['allocs'][] = $tmp;
1151 // 3. look for virtual services and related LB
1152 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
1153 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
1154 "IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1155 "inner join RackObject as ro on lb.object_id = ro.id " .
1156 "left join Dictionary on objtype_id=dict_key " .
1157 "join Chapter on Chapter.id = Dictionary.chapter_id " .
1158 "where ${whereexpr3} " .
1159 "and Chapter.name = 'RackObjectType'" .
1160 "order by vport, proto, ro.name, object_id";
1161 $result = useSelectBlade ($query, __FUNCTION__
);
1162 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1164 $ip_bin = ip2long ($row['ip']);
1165 if (!isset ($ret[$ip_bin]))
1166 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1167 if (!isset ($dnamecache[$row['object_id']]))
1169 $quasiobject['name'] = $row['object_name'];
1170 $quasiobject['objtype_id'] = $row['objtype_id'];
1171 $quasiobject['objtype_name'] = $row['objtype_name'];
1172 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1175 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
1176 $tmp[$cname] = $row[$cname];
1177 $tmp['object_name'] = $dnamecache[$row['object_id']];
1178 $tmp['vip'] = $row['ip'];
1179 $ret[$ip_bin]['lblist'][] = $tmp;
1183 // 4. don't forget about real servers along with pools
1184 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1185 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
1186 "where ${whereexpr4} " .
1187 "order by ip, rsport, rspool_id";
1188 $result = useSelectBlade ($query, __FUNCTION__
);
1189 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1191 $ip_bin = ip2long ($row['ip']);
1192 if (!isset ($ret[$ip_bin]))
1193 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1195 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1196 $tmp[$cname] = $row[$cname];
1197 $ret[$ip_bin]['rslist'][] = $tmp;
1201 // 5. add NAT rules, part 1
1205 "INET_NTOA(localip) as localip, " .
1207 "INET_NTOA(remoteip) as remoteip, " .
1211 "where ${whereexpr5a} " .
1212 "order by localip, localport, remoteip, remoteport, proto";
1213 $result = useSelectBlade ($query, __FUNCTION__
);
1214 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1216 $remoteip_bin = ip2long ($row['remoteip']);
1217 if (!isset ($ret[$remoteip_bin]))
1218 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1219 $ret[$remoteip_bin]['inpf'][] = $row;
1222 // 5. add NAT rules, part 2
1226 "INET_NTOA(localip) as localip, " .
1228 "INET_NTOA(remoteip) as remoteip, " .
1232 "where ${whereexpr5b} " .
1233 "order by localip, localport, remoteip, remoteport, proto";
1234 $result = useSelectBlade ($query, __FUNCTION__
);
1235 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1237 $localip_bin = ip2long ($row['localip']);
1238 if (!isset ($ret[$localip_bin]))
1239 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1240 $ret[$localip_bin]['outpf'][] = $row;
1246 // Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
1247 function getIPv4NetworkInfo ($id = 0)
1251 showError ('Invalid arg', __FUNCTION__
);
1254 $query = "select INET_NTOA(ip) as ip, mask, name ".
1255 "from IPv4Network where id = $id";
1256 $result = useSelectBlade ($query, __FUNCTION__
);
1257 $ret = $result->fetch (PDO
::FETCH_ASSOC
);
1262 $ret['ip_bin'] = ip2long ($ret['ip']);
1263 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1264 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1265 $ret['db_first'] = sprintf ('%u', 0x00000000 +
$ret['ip_bin'] & $ret['mask_bin']);
1266 $ret['db_last'] = sprintf ('%u', 0x00000000 +
$ret['ip_bin'] |
($ret['mask_bin_inv']));
1270 function getIPv4Address ($dottedquad = '')
1272 if ($dottedquad == '')
1274 showError ('Invalid arg', __FUNCTION__
);
1277 $i32 = ip2long ($dottedquad); // signed 32 bit
1278 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1279 if (!isset ($scanres[$i32]))
1280 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1281 return constructIPv4Address ($dottedquad);
1282 markupIPv4AddrList ($scanres);
1283 return $scanres[$i32];
1286 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1288 $result = useInsertBlade
1293 'ip' => "INET_ATON('$ip')",
1294 'object_id' => "'${object_id}'",
1295 'name' => "'${name}'",
1296 'type' => "'${type}'"
1299 return $result ?
'' : (__FUNCTION__
. '(): useInsertBlade() failed');
1302 // Return the id of the smallest IPv4 network containing the given IPv4 address
1303 // or NULL, if nothing was found. When finding the covering network for
1304 // another network, it is important to filter out matched records with longer
1305 // masks (they aren't going to be the right pick).
1306 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1308 // N.B. To perform the same for IPv6 address and networks, some pre-requisites
1309 // are necessary and a different query. IPv6 addresses are 128 bit long, which
1310 // is too much for both PHP and MySQL data types. These values must be split
1311 // into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1312 // Then each network must have its 128-bit netmask split same way and either
1313 // stored right in its record or JOINed from decoder and accessible as m_u32_0,
1314 // m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1315 // covering the given address would look as follows:
1316 // $query = 'select id from IPv6Network as n where ' .
1317 // "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1318 // "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1319 // "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1320 // "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1321 // "mask < ${masklen} " .
1322 // 'order by mask desc limit 1';
1324 $query = 'select id from IPv4Network where ' .
1325 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1326 "and mask < ${masklen} " .
1327 'order by mask desc limit 1';
1328 $result = useSelectBlade ($query, __FUNCTION__
);
1329 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1334 function updateRange ($id=0, $name='')
1338 "update IPv4Network set name='$name' where id='$id'";
1339 $result = $dbxlink->exec ($query);
1343 // This function is actually used not only to update, but also to create records,
1344 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1345 // (MySQL 4.0 workaround).
1346 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1348 // DELETE may safely fail.
1349 $r = useDeleteBlade ('IPv4Address', 'ip', "INET_ATON('${ip}')");
1350 // INSERT may appear not necessary.
1351 if ($name == '' and $reserved == 'no')
1353 if (useInsertBlade ('IPv4Address', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1356 return __FUNCTION__
. '(): useInsertBlade() failed';
1359 function updateBond ($ip='', $object_id=0, $name='', $type='')
1364 "update IPv4Allocation set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1365 $result = $dbxlink->exec ($query);
1369 function unbindIpFromObject ($ip='', $object_id=0)
1374 "delete from IPv4Allocation where ip=INET_ATON('$ip') and object_id='$object_id'";
1375 $result = $dbxlink->exec ($query);
1379 function searchByl2address ($port_l2address)
1381 if (NULL === ($db_l2address = l2addressForDatabase ($port_l2address)))
1382 return NULL; // Don't complain, other searches may return own data.
1383 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1384 "where l2address = '${db_l2address}'";
1385 $result = useSelectBlade ($query, __FUNCTION__
);
1386 $rows = $result->fetchAll (PDO
::FETCH_ASSOC
);
1387 $result->closeCursor();
1388 if (count ($rows) == 0) // No results.
1390 if (count ($rows) == 1) // Target found.
1392 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__
);
1396 function getIPv4PrefixSearchResult ($terms)
1398 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPv4Network where ";
1400 foreach (explode (' ', $terms) as $term)
1402 $query .= $or . "name like '%${term}%'";
1405 $result = useSelectBlade ($query, __FUNCTION__
);
1407 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1412 function getIPv4AddressSearchResult ($terms)
1414 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1416 foreach (explode (' ', $terms) as $term)
1418 $query .= $or . "name like '%${term}%'";
1421 $result = useSelectBlade ($query, __FUNCTION__
);
1423 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1428 function getIPv4RSPoolSearchResult ($terms)
1430 $query = "select id as pool_id, name from IPv4RSPool where ";
1432 foreach (explode (' ', $terms) as $term)
1434 $query .= $or . "name like '%${term}%'";
1437 $result = useSelectBlade ($query, __FUNCTION__
);
1439 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1444 function getIPv4VServiceSearchResult ($terms)
1446 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPv4VS where ";
1448 foreach (explode (' ', $terms) as $term)
1450 $query .= $or . "name like '%${term}%'";
1453 $result = useSelectBlade ($query, __FUNCTION__
);
1455 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1460 function getAccountSearchResult ($terms)
1462 $byUsername = getSearchResultByField
1465 array ('user_id', 'user_name', 'user_realname'),
1470 $byRealname = getSearchResultByField
1473 array ('user_id', 'user_name', 'user_realname'),
1478 // Filter out dupes.
1479 foreach ($byUsername as $res1)
1480 foreach (array_keys ($byRealname) as $key2)
1481 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1483 unset ($byRealname[$key2]);
1486 $ret = array_merge ($byUsername, $byRealname);
1487 // Set realm, so it's renderable.
1488 foreach (array_keys ($ret) as $key)
1489 $ret[$key]['realm'] = 'user';
1493 function getFileSearchResult ($terms)
1495 $byFilename = getSearchResultByField
1498 array ('id', 'name', 'comment', 'type', 'size'),
1503 $byComment = getSearchResultByField
1506 array ('id', 'name', 'comment', 'type', 'size'),
1511 // Filter out dupes.
1512 foreach ($byFilename as $res1)
1513 foreach (array_keys ($byComment) as $key2)
1514 if ($res1['id'] == $byComment[$key2]['id'])
1516 unset ($byComment[$key2]);
1519 return array_merge ($byFilename, $byComment);
1522 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1526 foreach ($rcolumns as $col)
1528 $query .= $pfx . $col;
1532 $query .= " from ${tname} where ";
1533 foreach (explode (' ', $terms) as $term)
1535 $query .= $pfx . "${scolumn} like '%${term}%'";
1539 $query .= " order by ${ocolumn}";
1540 $result = useSelectBlade ($query, __FUNCTION__
);
1542 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1547 // This function returns either port ID or NULL for specified arguments.
1548 function getPortID ($object_id, $port_name)
1550 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1551 $result = useSelectBlade ($query, __FUNCTION__
);
1552 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
1553 if (count ($rows) != 1)
1556 $result->closeCursor();
1560 function commitCreateUserAccount ($username, $realname, $password)
1562 return useInsertBlade
1567 'user_name' => "'${username}'",
1568 'user_realname' => "'${realname}'",
1569 'user_password_hash' => "'${password}'"
1574 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1578 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1579 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1580 $result = $dbxlink->query ($query);
1581 if ($result == NULL)
1583 showError ('SQL query failed', __FUNCTION__
);
1589 // This function returns an array of all port type pairs from PortCompat table.
1590 function getPortCompat ()
1593 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1594 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1595 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1596 "inner join Chapter as c1 on d1.chapter_id = c1.id " .
1597 "inner join Chapter as c2 on d2.chapter_id = c2.id " .
1598 "where c1.name = 'PortType' and c2.name = 'PortType'";
1599 $result = useSelectBlade ($query, __FUNCTION__
);
1600 $ret = $result->fetchAll (PDO
::FETCH_ASSOC
);
1601 $result->closeCursor();
1605 function removePortCompat ($type1 = 0, $type2 = 0)
1608 if ($type1 == 0 or $type2 == 0)
1610 showError ('Invalid arguments', __FUNCTION__
);
1613 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1614 $result = $dbxlink->query ($query);
1615 if ($result == NULL)
1617 showError ('SQL query failed', __FUNCTION__
);
1623 function addPortCompat ($type1 = 0, $type2 = 0)
1625 if ($type1 <= 0 or $type2 <= 0)
1627 showError ('Invalid arguments', __FUNCTION__
);
1630 return useInsertBlade
1633 array ('type1' => $type1, 'type2' => $type2)
1637 // This function returns the dictionary as an array of trees, each tree
1638 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1639 // and 'word' keys with the latter holding all the words within the chapter.
1640 // FIXME: there's a lot of excess legacy code in this function, it's reasonable
1641 // to merge it with readChapter().
1642 function getDict ($parse_links = FALSE)
1645 "select Chapter.name as chapter_name, Chapter.id as chapter_no, dict_key, dict_value, sticky from " .
1646 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id order by Chapter.name, dict_value";
1647 $result = useSelectBlade ($query1, __FUNCTION__
);
1649 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1651 $chapter_no = $row['chapter_no'];
1652 if (!isset ($dict[$chapter_no]))
1654 $dict[$chapter_no]['no'] = $chapter_no;
1655 $dict[$chapter_no]['name'] = $row['chapter_name'];
1656 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ?
TRUE : FALSE;
1657 $dict[$chapter_no]['word'] = array();
1659 if ($row['dict_key'] != NULL)
1661 $dict[$chapter_no]['word'][$row['dict_key']] = ($parse_links or $row['dict_key'] <= MAX_DICT_KEY
) ?
1662 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1663 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1666 $result->closeCursor();
1668 // Find the list of all assigned values of dictionary-addressed attributes, each with
1669 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1670 // of the returned disctionary words.
1671 $query2 = "select a.id as attr_id, am.chapter_id as chapter_no, uint_value, count(object_id) as refcnt " .
1672 "from Attribute as a inner join AttributeMap as am on a.id = am.attr_id " .
1673 "inner join AttributeValue as av on a.id = av.attr_id " .
1674 "inner join Dictionary as d on am.chapter_id = d.chapter_id and av.uint_value = d.dict_key " .
1675 "where a.type = 'dict' group by a.id, am.chapter_id, uint_value " .
1676 "order by a.id, am.chapter_id, uint_value";
1677 $result = useSelectBlade ($query2, __FUNCTION__
);
1678 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1679 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1680 $result->closeCursor();
1684 function getDictStats ()
1686 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25);
1688 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
1689 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id";
1690 $result = useSelectBlade ($query, __FUNCTION__
);
1691 $tc = $tw = $uc = $uw = 0;
1692 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1696 if (in_array ($row['chapter_no'], $stock_chapters))
1701 $result->closeCursor();
1703 $query = "select count(id) as attrc from RackObject as ro left join " .
1704 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1705 $result = useSelectBlade ($query, __FUNCTION__
);
1706 $to = $ta = $so = 0;
1707 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1710 if ($row['attrc'] != 0)
1713 $ta +
= $row['attrc'];
1716 $result->closeCursor();
1718 $ret['Total chapters in dictionary'] = $tc;
1719 $ret['Total words in dictionary'] = $tw;
1720 $ret['User chapters'] = $uc;
1721 $ret['Words in user chapters'] = $uw;
1722 $ret['Total objects'] = $to;
1723 $ret['Objects with stickers'] = $so;
1724 $ret['Total stickers attached'] = $ta;
1728 function getIPv4Stats ()
1732 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1733 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1734 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1735 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1736 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1737 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1738 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1739 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
1741 foreach ($subject as $item)
1743 $result = useSelectBlade ($item['q'], __FUNCTION__
);
1744 $row = $result->fetch (PDO
::FETCH_NUM
);
1745 $ret[$item['txt']] = $row[0];
1746 $result->closeCursor();
1752 function getRackspaceStats ()
1756 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
1757 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1758 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1759 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1761 foreach ($subject as $item)
1763 $result = useSelectBlade ($item['q'], __FUNCTION__
);
1764 $row = $result->fetch (PDO
::FETCH_NUM
);
1765 $ret[$item['txt']] = empty ($row[0]) ?
0 : $row[0];
1766 $result->closeCursor();
1772 function renderTagStats ()
1774 global $taglist, $root;
1775 $query = "select id, tag, count(tag_id) as refcnt from " .
1776 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1777 "group by tag_id order by refcnt desc limit 50";
1778 // The same data is already present in pre-loaded tag list, but not in
1779 // the form we need. So let's ask the DB server for cooked top list and
1780 // use the cooked tag list to break it down.
1781 $result = useSelectBlade ($query, __FUNCTION__
);
1782 $refc = $result->fetchAll (PDO
::FETCH_ASSOC
);
1783 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
1784 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th><th>files</th></tr>';
1785 $pagebyrealm = array
1787 'file' => 'files&entity_type=all',
1788 'ipv4net' => 'ipv4space&tab=default',
1789 'ipv4vs' => 'ipv4vslist&tab=default',
1790 'ipv4rspool' => 'ipv4rsplist&tab=default',
1791 'object' => 'objgroup&group_id=0',
1792 'rack' => 'rackspace&tab=default',
1793 'user' => 'userlist&tab=default'
1795 foreach ($refc as $ref)
1797 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
1798 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user', 'file') as $realm)
1801 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1805 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&cft[]=${ref['id']}'>";
1806 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1817 The following allows figuring out records in TagStorage, which refer to non-existing entities:
1819 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1820 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1821 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1822 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1823 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1824 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1825 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
1827 Accordingly, these are the records, which refer to non-existent tags:
1829 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1833 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1835 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1837 showError ('Invalid args', __FUNCTION__
);
1842 "update Dictionary set dict_value = '${dict_value}' where chapter_id=${chapter_no} " .
1843 "and dict_key=${dict_key} limit 1";
1844 $result = $dbxlink->query ($query);
1845 if ($result == NULL)
1847 showError ('SQL query failed', __FUNCTION__
);
1853 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1855 if ($chapter_no <= 0 or empty ($dict_value))
1857 showError ('Invalid args', __FUNCTION__
);
1860 return useInsertBlade
1863 array ('chapter_id' => $chapter_no, 'dict_value' => "'${dict_value}'")
1867 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1869 if ($chapter_no <= 0 or $dict_key <= 0)
1871 showError ('Invalid args', __FUNCTION__
);
1876 "delete from Dictionary where chapter_id=${chapter_no} " .
1877 "and dict_key=${dict_key} limit 1";
1878 $result = $dbxlink->query ($query);
1879 if ($result == NULL)
1881 showError ('SQL query failed', __FUNCTION__
);
1887 function commitAddChapter ($chapter_name = '')
1889 if (empty ($chapter_name))
1891 showError ('Invalid args', __FUNCTION__
);
1894 return useInsertBlade
1897 array ('name' => "'${chapter_name}'")
1901 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1903 if ($chapter_no <= 0 or empty ($chapter_name))
1905 showError ('Invalid args', __FUNCTION__
);
1910 "update Chapter set name = '${chapter_name}' where id = ${chapter_no} " .
1911 "and sticky = 'no' limit 1";
1912 $result = $dbxlink->query ($query);
1913 if ($result == NULL)
1915 showError ('SQL query failed', __FUNCTION__
);
1921 function commitDeleteChapter ($chapter_no = 0)
1923 if ($chapter_no <= 0)
1925 showError ('Invalid args', __FUNCTION__
);
1930 "delete from Chapter where id = ${chapter_no} and sticky = 'no' limit 1";
1931 $result = $dbxlink->query ($query);
1932 if ($result == NULL)
1934 showError ('SQL query failed', __FUNCTION__
);
1940 // This is a dictionary accessor. We perform link rendering, so the user sees
1941 // nice <select> drop-downs.
1942 function readChapter ($chapter_name = '')
1944 if (empty ($chapter_name))
1946 showError ('invalid argument', __FUNCTION__
);
1950 "select dict_key, dict_value from Dictionary join Chapter on Chapter.id = Dictionary.chapter_id " .
1951 "where Chapter.name = '${chapter_name}'";
1952 $result = useSelectBlade ($query, __FUNCTION__
);
1954 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1955 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
1956 $result->closeCursor();
1957 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1962 function getAttrMap ()
1965 "select a.id as attr_id, a.type as attr_type, a.name as attr_name, am.objtype_id, " .
1966 "d.dict_value as objtype_name, am.chapter_id, c2.name as chapter_name from " .
1967 "Attribute as a left join AttributeMap as am on a.id = am.attr_id " .
1968 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1969 "left join Chapter as c1 on d.chapter_id = c1.id " .
1970 "left join Chapter as c2 on am.chapter_id = c2.id " .
1971 "where c1.name = 'RackObjectType' or c1.name is null " .
1973 $result = useSelectBlade ($query, __FUNCTION__
);
1975 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1977 $attr_id = $row['attr_id'];
1978 if (!isset ($ret[$attr_id]))
1980 $ret[$attr_id]['id'] = $attr_id;
1981 $ret[$attr_id]['type'] = $row['attr_type'];
1982 $ret[$attr_id]['name'] = $row['attr_name'];
1983 $ret[$attr_id]['application'] = array();
1985 if ($row['objtype_id'] == '')
1987 $application['objtype_id'] = $row['objtype_id'];
1988 $application['objtype_name'] = $row['objtype_name'];
1989 if ($row['attr_type'] == 'dict')
1991 $application['chapter_no'] = $row['chapter_id'];
1992 $application['chapter_name'] = $row['chapter_name'];
1994 $ret[$attr_id]['application'][] = $application;
1996 $result->closeCursor();
2000 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
2002 if ($attr_id <= 0 or empty ($attr_name))
2004 showError ('Invalid args', __FUNCTION__
);
2009 "update Attribute set name = '${attr_name}' " .
2010 "where id = ${attr_id} limit 1";
2011 $result = $dbxlink->query ($query);
2012 if ($result == NULL)
2014 showError ("SQL query '${query}' failed", __FUNCTION__
);
2020 function commitAddAttribute ($attr_name = '', $attr_type = '')
2022 if (empty ($attr_name))
2024 showError ('Invalid args', __FUNCTION__
);
2035 showError ('Invalid args', __FUNCTION__
);
2038 return useInsertBlade
2041 array ('name' => "'${attr_name}'", 'type' => "'${attr_type}'")
2045 function commitDeleteAttribute ($attr_id = 0)
2049 showError ('Invalid args', __FUNCTION__
);
2052 return useDeleteBlade ('Attribute', 'id', $attr_id);
2055 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2056 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2058 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
2060 showError ('Invalid args', __FUNCTION__
);
2063 return useInsertBlade
2068 'attr_id' => $attr_id,
2069 'objtype_id' => $objtype_id,
2070 'chapter_id' => $chapter_no
2075 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2077 if ($attr_id <= 0 or $objtype_id <= 0)
2079 showError ('Invalid args', __FUNCTION__
);
2084 "delete from AttributeMap where attr_id=${attr_id} " .
2085 "and objtype_id=${objtype_id} limit 1";
2086 $result = $dbxlink->query ($query);
2087 if ($result == NULL)
2089 showError ('SQL query failed', __FUNCTION__
);
2095 // This function returns all optional attributes for requested object
2096 // as an array of records. NULL is returned on error and empty array
2097 // is returned, if there are no attributes found.
2098 function getAttrValues ($object_id, $strip_optgroup = FALSE)
2100 if ($object_id <= 0)
2102 showError ('Invalid argument', __FUNCTION__
);
2107 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2108 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2109 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2110 "inner join Attribute as A on AM.attr_id = A.id " .
2111 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2112 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2113 "left join Chapter as C on AM.chapter_id = C.id " .
2114 "where RO.id = ${object_id} order by A.type, A.name";
2115 $result = useSelectBlade ($query, __FUNCTION__
);
2116 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2119 $record['id'] = $row['attr_id'];
2120 $record['name'] = $row['attr_name'];
2121 $record['type'] = $row['attr_type'];
2122 switch ($row['attr_type'])
2127 $record['value'] = $row[$row['attr_type'] . '_value'];
2128 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2131 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2132 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
2133 $record['chapter_name'] = $row['chapter_name'];
2134 $record['key'] = $row['uint_value'];
2137 $record['value'] = NULL;
2140 $ret[$row['attr_id']] = $record;
2142 $result->closeCursor();
2146 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2148 if ($object_id <= 0 or $attr_id <= 0)
2150 showError ('Invalid arguments', __FUNCTION__
);
2154 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2155 $result = $dbxlink->query ($query);
2156 if ($result == NULL)
2158 showError ('SQL query failed', __FUNCTION__
);
2164 // FIXME: don't share common code with use commitResetAttrValue()
2165 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2167 if ($object_id <= 0 or $attr_id <= 0)
2169 showError ('Invalid arguments', __FUNCTION__
);
2173 return commitResetAttrValue ($object_id, $attr_id);
2175 $query1 = "select type as attr_type from Attribute where id = ${attr_id}";
2176 $result = $dbxlink->query ($query1);
2177 if ($result == NULL)
2179 showError ('SQL query #1 failed', __FUNCTION__
);
2182 $row = $result->fetch (PDO
::FETCH_NUM
);
2185 showError ('SQL query #1 returned no results', __FUNCTION__
);
2188 $attr_type = $row[0];
2189 $result->closeCursor();
2195 $column = $attr_type . '_value';
2198 $column = 'uint_value';
2201 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__
);
2205 "delete from AttributeValue where " .
2206 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2207 $result = $dbxlink->query ($query2);
2208 if ($result == NULL)
2210 showError ('SQL query #2 failed', __FUNCTION__
);
2213 // We know $value isn't empty here.
2215 "insert into AttributeValue set ${column} = '${value}', " .
2216 "object_id = ${object_id}, attr_id = ${attr_id} ";
2217 $result = $dbxlink->query ($query3);
2218 if ($result == NULL)
2220 showError ('SQL query #3 failed', __FUNCTION__
);
2226 function commitUseupPort ($port_id = 0)
2230 showError ("Invalid argument", __FUNCTION__
);
2234 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2235 $result = $dbxlink->exec ($query);
2236 if ($result == NULL)
2238 showError ("SQL query failed", __FUNCTION__
);
2245 // This is a swiss-knife blade to insert a record into a table.
2246 // The first argument is table name.
2247 // The second argument is an array of "name" => "value" pairs.
2248 // The function returns either TRUE or FALSE (we expect one row
2250 function useInsertBlade ($tablename, $values)
2253 $namelist = $valuelist = '';
2254 foreach ($values as $name => $value)
2256 $namelist = $namelist . ($namelist == '' ?
"(${name}" : ", ${name}");
2257 $valuelist = $valuelist . ($valuelist == '' ?
"(${value}" : ", ${value}");
2259 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2260 $result = $dbxlink->exec ($query);
2266 // This swiss-knife blade deletes one record from the specified table
2267 // using the specified key name and value.
2268 function useDeleteBlade ($tablename, $keyname, $keyvalue)
2271 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
2274 function useSelectBlade ($query, $caller = 'N/A')
2277 $result = $dbxlink->query ($query);
2278 if ($result == NULL)
2280 $ei = $dbxlink->errorInfo();
2281 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
2287 function loadConfigCache ()
2289 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
2290 $result = useSelectBlade ($query, __FUNCTION__
);
2292 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2293 $cache[$row['varname']] = $row;
2294 $result->closeCursor();
2298 // setConfigVar() is expected to perform all necessary filtering
2299 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2302 if (empty ($varname) ||
$varvalue === NULL)
2304 showError ('Invalid arguments', __FUNCTION__
);
2307 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2308 $result = $dbxlink->query ($query);
2309 if ($result == NULL)
2311 showError ("SQL query '${query}' failed", __FUNCTION__
);
2314 $rc = $result->rowCount();
2315 $result->closeCursor();
2316 if ($rc == 0 or $rc == 1)
2318 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__
);
2322 // Database version detector. Should behave corretly on any
2323 // working dataset a user might have.
2324 function getDatabaseVersion ()
2327 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2328 $result = $dbxlink->query ($query);
2329 if ($result == NULL)
2331 $errorInfo = $dbxlink->errorInfo();
2332 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2334 die (__FUNCTION__
. ': SQL query #1 failed with error ' . $errorInfo[2]);
2336 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
2337 if (count ($rows) != 1 ||
empty ($rows[0][0]))
2339 $result->closeCursor();
2340 die (__FUNCTION__
. ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2343 $result->closeCursor();
2347 // Return an array of virtual services. For each of them list real server pools
2348 // with their load balancers and other stats.
2349 function getSLBSummary ()
2351 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2352 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2353 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2354 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2355 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2356 'group by vs.id, object_id order by vs.vip, object_id';
2357 $result = useSelectBlade ($query, __FUNCTION__
);
2359 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2361 $vsid = $row['vsid'];
2362 $object_id = $row['object_id'];
2363 if (!isset ($ret[$vsid]))
2365 $ret[$vsid] = array();
2366 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2367 $ret[$vsid][$cname] = $row[$cname];
2368 $ret[$vsid]['lblist'] = array();
2370 // There's only one assigned RS pool possible for each LB-VS combination.
2371 $ret[$vsid]['lblist'][$row['object_id']] = array
2373 'id' => $row['rspool_id'],
2374 'size' => $row['rscount'],
2375 'name' => $row['pool_name']
2378 $result->closeCursor();
2382 // Get the detailed composition of a particular virtual service, namely the list
2383 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2384 // will be returned as well.
2385 function getVServiceInfo ($vsid = 0)
2387 $query1 = "select id, inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2388 "from IPv4VS where id = ${vsid}";
2389 $result = useSelectBlade ($query1, __FUNCTION__
);
2391 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2394 foreach (array ('id', 'vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2395 $vsinfo[$cname] = $row[$cname];
2396 $vsinfo['rspool'] = array();
2397 $result->closeCursor();
2399 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2400 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2401 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
2402 "where vs_id = ${vsid} order by pool.name, object_id";
2403 $result = useSelectBlade ($query2, __FUNCTION__
);
2404 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2406 if (!isset ($vsinfo['rspool'][$row['id']]))
2408 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2409 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2410 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2411 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2413 if ($row['object_id'] == NULL)
2415 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2417 'vsconfig' => $row['lb_vsconfig'],
2418 'rsconfig' => $row['lb_rsconfig']
2421 $result->closeCursor();
2425 // Collect and return the following info about the given real server pool:
2426 // basic information
2427 // parent virtual service information
2428 // load balancers list (each with a list of VSes)
2429 // real servers list
2431 function getRSPoolInfo ($id = 0)
2433 $query1 = "select id, name, vsconfig, rsconfig from " .
2434 "IPv4RSPool where id = ${id}";
2435 $result = useSelectBlade ($query1, __FUNCTION__
);
2437 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2440 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2441 $ret[$c] = $row[$c];
2442 $result->closeCursor();
2444 $ret['lblist'] = array();
2445 $ret['rslist'] = array();
2446 $query2 = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
2447 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
2448 "where rspool_id = ${id} order by object_id, vip, vport";
2449 $result = useSelectBlade ($query2, __FUNCTION__
);
2450 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2451 foreach (array ('vsconfig', 'rsconfig') as $c)
2452 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2453 $result->closeCursor();
2455 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2456 "IPv4RS where rspool_id = ${id} order by IPv4RS.rsip, rsport";
2457 $result = useSelectBlade ($query3, __FUNCTION__
);
2458 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2459 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2460 $ret['rslist'][$row['id']][$c] = $row[$c];
2461 $result->closeCursor();
2465 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2469 showError ('Invalid arguments', __FUNCTION__
);
2472 if (empty ($rsport) or $rsport == 0)
2474 return useInsertBlade
2479 'rsip' => "inet_aton('${rsip}')",
2480 'rsport' => $rsport,
2481 'rspool_id' => $pool_id,
2482 'inservice' => ($inservice == 'yes' ?
"'yes'" : "'no'"),
2483 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2488 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2490 if (empty ($vip) or $vport <= 0 or empty ($proto))
2491 return __FUNCTION__
. ': invalid arguments';
2497 'vip' => "inet_aton('${vip}')",
2499 'proto' => "'${proto}'",
2500 'name' => (empty ($name) ?
'NULL' : "'${name}'"),
2501 'vsconfig' => (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'"),
2502 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2505 return __FUNCTION__
. ': SQL insertion failed';
2506 return produceTagsForLastRecord ('ipv4vs', $taglist);
2509 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2511 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2513 showError ('Invalid arguments', __FUNCTION__
);
2516 return useInsertBlade
2521 'object_id' => $object_id,
2522 'rspool_id' => $pool_id,
2524 'vsconfig' => (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'"),
2525 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2530 function commitDeleteRS ($id = 0)
2534 return useDeleteBlade ('IPv4RS', 'id', $id);
2537 function commitDeleteVS ($id = 0)
2541 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
2544 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2547 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2549 $query = "delete from IPv4LB where object_id = ${object_id} and " .
2550 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2551 $result = $dbxlink->exec ($query);
2552 if ($result === NULL)
2554 elseif ($result != 1)
2560 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2564 showError ('Invalid args', __FUNCTION__
);
2567 if (long2ip (ip2long ($rsip)) !== $rsip)
2569 showError ("Invalid IP address '${rsip}'", __FUNCTION__
);
2572 if (empty ($rsport) or $rsport == 0)
2576 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2577 (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2578 " where id = ${rsid} limit 1";
2579 $result = $dbxlink->query ($query);
2580 if ($result == NULL)
2582 showError ("SQL query '${query}' failed", __FUNCTION__
);
2588 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2590 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2592 showError ('Invalid args', __FUNCTION__
);
2597 "update IPv4LB set vsconfig = " .
2598 (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'") .
2600 (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2601 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2602 "and vs_id = ${vs_id} limit 1";
2603 $result = $dbxlink->exec ($query);
2604 if ($result === NULL)
2610 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2612 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2614 showError ('Invalid args', __FUNCTION__
);
2618 $query = "update IPv4VS set " .
2619 "vip = inet_aton('${vip}'), " .
2620 "vport = ${vport}, " .
2621 "proto = '${proto}', " .
2622 'name = ' . (empty ($name) ?
'NULL,' : "'${name}', ") .
2623 'vsconfig = ' . (empty ($vsconfig) ?
'NULL,' : "'${vsconfig}', ") .
2624 'rsconfig = ' . (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2625 " where id = ${vsid} limit 1";
2626 $result = $dbxlink->exec ($query);
2627 if ($result === NULL)
2633 function loadThumbCache ($rack_id = 0)
2636 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2637 $result = useSelectBlade ($query, __FUNCTION__
);
2638 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2640 $ret = base64_decode ($row['thumb_data']);
2641 $result->closeCursor();
2645 function saveThumbCache ($rack_id = 0, $cache = NULL)
2648 if ($rack_id == 0 or $cache == NULL)
2650 showError ('Invalid arguments', __FUNCTION__
);
2653 $data = base64_encode ($cache);
2654 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2655 $result = $dbxlink->exec ($query);
2658 function resetThumbCache ($rack_id = 0)
2663 showError ('Invalid argument', __FUNCTION__
);
2666 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2667 $result = $dbxlink->exec ($query);
2670 // Return the list of attached RS pools for the given object. As long as we have
2671 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2672 // by vs_id, because there will be only one RS pool listed for each VS of the
2674 function getRSPoolsForObject ($object_id = 0)
2676 if ($object_id <= 0)
2678 showError ('Invalid object_id', __FUNCTION__
);
2681 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2682 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2683 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2684 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2685 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2686 "where lb.object_id = ${object_id} " .
2687 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2688 $result = useSelectBlade ($query, __FUNCTION__
);
2690 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2691 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2692 $ret[$row['vs_id']][$cname] = $row[$cname];
2693 $result->closeCursor();
2697 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2700 return __FUNCTION__
. ': invalid arguments';
2706 'name' => (empty ($name) ?
'NULL' : "'${name}'"),
2707 'vsconfig' => (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'"),
2708 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2711 return __FUNCTION__
. ': SQL insertion failed';
2712 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2715 function commitDeleteRSPool ($pool_id = 0)
2720 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2723 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2727 showError ('Invalid arg', __FUNCTION__
);
2731 $query = "update IPv4RSPool set " .
2732 'name = ' . (empty ($name) ?
'NULL,' : "'${name}', ") .
2733 'vsconfig = ' . (empty ($vsconfig) ?
'NULL,' : "'${vsconfig}', ") .
2734 'rsconfig = ' . (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2735 " where id = ${pool_id} limit 1";
2736 $result = $dbxlink->exec ($query);
2737 if ($result === NULL)
2739 elseif ($result != 1)
2745 function getRSList ()
2747 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2748 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
2749 $result = useSelectBlade ($query, __FUNCTION__
);
2751 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2752 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2753 $ret[$row['id']][$cname] = $row[$cname];
2754 $result->closeCursor();
2758 // Return the list of all currently configured load balancers with their pool count.
2759 function getLBList ()
2761 $query = "select object_id, count(rspool_id) as poolcount " .
2762 "from IPv4LB group by object_id order by object_id";
2763 $result = useSelectBlade ($query, __FUNCTION__
);
2765 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2766 $ret[$row['object_id']] = $row['poolcount'];
2767 $result->closeCursor();
2771 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2772 // attached (each with vsconfig/rsconfig in turn), each with the list of
2773 // virtual services terminating the pool. Each pool also lists all real
2774 // servers with rsconfig.
2775 function getSLBConfig ($object_id)
2777 if ($object_id <= 0)
2779 showError ('Invalid arg', __FUNCTION__
);
2783 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2784 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2785 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2786 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2787 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2788 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2789 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2790 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2791 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2792 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2793 $result = useSelectBlade ($query, __FUNCTION__
);
2794 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2796 $vs_id = $row['vs_id'];
2797 if (!isset ($ret[$vs_id]))
2799 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)
2800 $ret[$vs_id][$c] = $row[$c];
2801 $ret[$vs_id]['rslist'] = array();
2803 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2804 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2806 $result->closeCursor();
2810 function commitSetInService ($rs_id = 0, $inservice = '')
2812 if ($rs_id <= 0 or empty ($inservice))
2814 showError ('Invalid args', __FUNCTION__
);
2818 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
2819 $result = $dbxlink->exec ($query);
2820 if ($result === NULL)
2822 elseif ($result != 1)
2828 function executeAutoPorts ($object_id = 0, $type_id = 0)
2830 if ($object_id == 0 or $type_id == 0)
2832 showError ('Invalid arguments', __FUNCTION__
);
2836 foreach (getAutoPorts ($type_id) as $autoport)
2837 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2841 // Return only implicitly listed tags, the rest of the chain will be
2842 // generated/deducted later at higher levels.
2843 // Result is a chain: randomly indexed taginfo list.
2844 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2847 if (!in_array ($entity_realm, array ('file', 'ipv4net', 'ipv4vs', 'ipv4rspool', 'object', 'rack', 'user')))
2849 $query = "select tt.id, tag from " .
2850 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2851 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
2853 $result = useSelectBlade ($query, __FUNCTION__
);
2854 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2855 $ret[$row['id']] = $row;
2856 $result->closeCursor();
2857 return getExplicitTagsOnly ($ret);
2860 // Return a tag chain with all DB tags on it.
2861 function getTagList ()
2864 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2865 "from TagTree left join TagStorage on id = tag_id " .
2866 "group by id, entity_realm order by tag";
2867 $result = useSelectBlade ($query, __FUNCTION__
);
2868 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2869 // which is utf8_general_ci for UTF-8.
2870 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2872 if (!isset ($ret[$row['id']]))
2873 $ret[$row['id']] = array
2876 'tag' => $row['tag'],
2878 'parent_id' => $row['parent_id'],
2882 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2884 $result->closeCursor();
2888 function commitCreateTag ($tagname = '', $parent_id = 0)
2890 if ($tagname == '' or $parent_id === 0)
2891 return "Invalid args to " . __FUNCTION__
;
2892 $result = useInsertBlade
2897 'tag' => "'${tagname}'",
2898 'parent_id' => $parent_id
2904 elseif ($dbxlink->errorCode() == 23000)
2905 return "name '${tag_name}' is already used";
2907 return "SQL query failed in " . __FUNCTION__
;
2910 function commitDestroyTag ($tagid = 0)
2913 return 'Invalid arg to ' . __FUNCTION__
;
2914 if (useDeleteBlade ('TagTree', 'id', $tagid))
2917 return 'useDeleteBlade() failed in ' . __FUNCTION__
;
2920 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2922 if ($parent_id == 0)
2923 $parent_id = 'NULL';
2925 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2926 "where id = ${tag_id} limit 1";
2927 $result = $dbxlink->exec ($query);
2928 if ($result !== FALSE)
2930 elseif ($dbxlink->errorCode() == 23000)
2931 return "name '${tag_name}' is already used";
2933 return 'SQL query failed in ' . __FUNCTION__
;
2936 // Drop the whole chain stored.
2937 function destroyTagsForEntity ($entity_realm, $entity_id)
2940 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
2941 $result = $dbxlink->exec ($query);
2942 if ($result === NULL)
2948 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2949 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2952 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
2953 $result = $dbxlink->exec ($query);
2954 if ($result === NULL)
2960 // Push a record into TagStorage unconditionally.
2961 function addTagForEntity ($realm = '', $entity_id, $tag_id)
2965 return useInsertBlade
2970 'entity_realm' => "'${realm}'",
2971 'entity_id' => $entity_id,
2972 'tag_id' => $tag_id,
2977 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2978 // on the implicit list already). Then remove any other records, which
2979 // appear on the "implicit" side of the chain. This will make sure,
2980 // that both the tag base is still minimal and all requested tags appear on
2981 // the resulting tag chain.
2982 // Return TRUE, if any changes were committed.
2983 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2985 // Put the current explicit sub-chain into a buffer and merge all tags from
2986 // the extra chain, which aren't there yet.
2987 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2988 foreach ($extrachain as $extratag)
2989 if (!tagOnChain ($extratag, $newchain))
2990 $newchain[] = $extratag;
2991 // Then minimize the working buffer and check if it differs from the original
2992 // chain we started with. If it is so, save the work and signal the upper layer.
2993 $newchain = getExplicitTagsOnly ($newchain);
2994 if (tagChainCmp ($oldchain, $newchain))
2996 destroyTagsForEntity ($realm, $entity_id);
2997 foreach ($newchain as $taginfo)
2998 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3004 // Presume, that the target record has no tags attached.
3005 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3007 if (!count ($tagidlist))
3009 if (!$last_insert_id)
3010 $last_insert_id = lastInsertID();
3012 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
3013 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
3018 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3021 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3023 // $range is in x.x.x.x/x format, split into ip/mask vars
3024 $rangeArray = explode('/', $range);
3025 if (count ($rangeArray) != 2)
3026 return "Invalid IPv4 prefix '${range}'";
3027 $ip = $rangeArray[0];
3028 $mask = $rangeArray[1];
3030 if (empty ($ip) or empty ($mask))
3031 return "Invalid IPv4 prefix '${range}'";
3032 $ipL = ip2long($ip);
3033 $maskL = ip2long($mask);
3034 if ($ipL == -1 ||
$ipL === FALSE)
3035 return 'Bad IPv4 address';
3036 if ($mask < 32 && $mask > 0)
3040 $maskB = decbin($maskL);
3041 if (strlen($maskB)!=32)
3042 return 'Invalid netmask';
3045 foreach( str_split ($maskB) as $digit)
3052 if ($zeroes == TRUE)
3053 return 'Invalid netmask';
3058 $binmask = binMaskFromDec($maskL);
3059 $ipL = $ipL & $binmask;
3060 $result = useInsertBlade
3065 'ip' => sprintf ('%u', $ipL),
3066 'mask' => "'${maskL}'",
3067 'name' => "'${name}'"
3070 if ($result != TRUE)
3071 return "Could not add ${range} (already exists?).";
3073 if ($is_bcast and $maskL < 31)
3075 $network_addr = long2ip ($ipL);
3076 $broadcast_addr = long2ip ($ipL |
binInvMaskFromDec ($maskL));
3077 updateAddress ($network_addr, 'network', 'yes');
3078 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3080 return produceTagsForLastRecord ('ipv4net', $taglist);
3083 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
3084 function destroyIPv4Prefix ($id = 0)
3087 return __FUNCTION__
. ': Invalid IPv4 prefix ID';
3088 if (!useDeleteBlade ('IPv4Network', 'id', $id))
3089 return __FUNCTION__
. ': SQL query #1 failed';
3090 if (!destroyTagsForEntity ('ipv4net', $id))
3091 return __FUNCTION__
. ': SQL query #2 failed';
3095 function loadScript ($name)
3097 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3098 $row = $result->fetch (PDO
::FETCH_NUM
);
3105 function saveScript ($name, $text)
3109 showError ('Invalid argument');
3112 // delete regardless of existence
3113 useDeleteBlade ('Script', 'script_name', "'${name}'");
3114 return useInsertBlade
3119 'script_name' => "'${name}'",
3120 'script_text' => "'${text}'"
3125 function saveUserPassword ($user_id, $newp)
3127 $newhash = sha1 ($newp);
3128 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
3131 function objectIsPortless ($id = 0)
3135 showError ('Invalid argument', __FUNCTION__
);
3138 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__
)) == NULL)
3140 showError ('SQL query failed', __FUNCTION__
);
3143 $row = $result->fetch (PDO
::FETCH_NUM
);
3145 $result->closeCursor();
3147 return $count === '0';
3150 function recordExists ($id = 0, $realm = 'object')
3156 'object' => 'RackObject',
3157 'ipv4net' => 'IPv4Network',
3158 'user' => 'UserAccount',
3164 'user' => 'user_id',
3166 $query = 'select count(*) from ' . $table[$realm] . ' where ' . $idcol[$realm] . ' = ' . $id;
3167 if (($result = useSelectBlade ($query, __FUNCTION__
)) == NULL)
3169 showError ('SQL query failed', __FUNCTION__
);
3172 $row = $result->fetch (PDO
::FETCH_NUM
);
3174 $result->closeCursor();
3176 return $count === '1';
3179 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3181 if (NULL === getIPv4AddressNetworkId ($localip))
3182 return "$localip: Non existant ip";
3183 if (NULL === getIPv4AddressNetworkId ($localip))
3184 return "$remoteip: Non existant ip";
3185 if ( ($localport <= 0) or ($localport >= 65536) )
3186 return "$localport: invaild port";
3187 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3188 return "$remoteport: invaild port";
3190 $result = useInsertBlade
3195 'object_id' => $object_id,
3196 'localip' => "INET_ATON('${localip}')",
3197 'remoteip' => "INET_ATON('$remoteip')",
3198 'localport' => $localport,
3199 'remoteport' => $remoteport,
3200 'proto' => "'${proto}'",
3201 'description' => "'${description}'",
3207 return __FUNCTION__
. ': Failed to insert the rule.';
3210 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3215 "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'";
3216 $result = $dbxlink->exec ($query);
3220 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3225 "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'";
3226 $result = $dbxlink->exec ($query);
3230 function getNATv4ForObject ($object_id)
3233 $ret['out'] = array();
3234 $ret['in'] = array();
3238 "INET_NTOA(localip) as localip, ".
3240 "INET_NTOA(remoteip) as remoteip, ".
3242 "ipa1.name as local_addr_name, " .
3243 "ipa2.name as remote_addr_name, " .
3246 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3247 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
3248 "where object_id='$object_id' ".
3249 "order by localip, localport, proto, remoteip, remoteport";
3250 $result = useSelectBlade ($query, __FUNCTION__
);
3252 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3254 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3255 $ret['out'][$count][$cname] = $row[$cname];
3258 $result->closeCursor();
3264 "INET_NTOA(localip) as localip, ".
3266 "INET_NTOA(remoteip) as remoteip, ".
3268 "IPv4NAT.object_id as object_id, ".
3269 "RackObject.name as object_name, ".
3271 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3272 "where IPv4Allocation.object_id='$object_id' ".
3273 "order by remoteip, remoteport, proto, localip, localport";
3274 $result = useSelectBlade ($query, __FUNCTION__
);
3276 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3278 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3279 $ret['in'][$count][$cname] = $row[$cname];
3282 $result->closeCursor();
3287 // This function performs search and then calculates score for each result.
3288 // Given previous search results in $objects argument, it adds new results
3289 // to the array and updates score for existing results, if it is greater than
3291 function mergeSearchResults (&$objects, $terms, $fieldname)
3295 "select ro.name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3296 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3297 "on objtype_id = dict_key join Chapter on Chapter.id = Dictionary.chapter_id where Chapter.name = 'RackObjectType' and ";
3299 foreach (explode (' ', $terms) as $term)
3301 if ($count) $query .= ' or ';
3302 $query .= "ro.${fieldname} like '%$term%'";
3305 $query .= " order by ${fieldname}";
3306 $result = useSelectBlade ($query, __FUNCTION__
);
3307 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3308 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3310 foreach ($clist as $cname)
3311 $object[$cname] = $row[$cname];
3312 $object['score'] = 0;
3313 $object['dname'] = displayedName ($object);
3314 unset ($object['objtype_id']);
3315 foreach (explode (' ', $terms) as $term)
3316 if (strstr ($object['name'], $term))
3317 $object['score'] +
= 1;
3318 unset ($object['name']);
3319 if (!isset ($objects[$row['id']]))
3320 $objects[$row['id']] = $object;
3321 elseif ($objects[$row['id']]['score'] < $object['score'])
3322 $objects[$row['id']]['score'] = $object['score'];
3327 function getLostIPv4Addresses ()
3332 // Return a list of files which are not linked to the specified record. This list
3333 // will be used by printSelect().
3334 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3336 if ($entity_type == NULL ||
$entity_id == 0)
3338 showError ('Invalid parameters', __FUNCTION__
);
3343 'SELECT id, name FROM File ' .
3344 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .
3345 'ORDER BY name, id';
3346 $query = $dbxlink->prepare($sql);
3347 $query->bindParam(1, $entity_type);
3348 $query->bindParam(2, $entity_id);
3351 while ($row = $query->fetch (PDO
::FETCH_ASSOC
))
3352 $ret[$row['id']] = $row['name'];
3356 function getFilesOfEntity ($entity_type = NULL, $entity_id = 0)
3358 if ($entity_type == NULL ||
$entity_id == 0)
3360 showError ('Invalid parameters', __FUNCTION__
);
3365 'SELECT FileLink.file_id, FileLink.id AS link_id, name, type, size, ctime, mtime, atime, comment ' .
3366 'FROM FileLink LEFT JOIN File ON FileLink.file_id = File.id ' .
3367 'WHERE FileLink.entity_type = ? AND FileLink.entity_id = ? ORDER BY name';
3368 $query = $dbxlink->prepare($sql);
3369 $query->bindParam(1, $entity_type);
3370 $query->bindParam(2, $entity_id);
3373 while ($row = $query->fetch (PDO
::FETCH_ASSOC
))
3374 $ret[$row['file_id']] = array (
3375 'id' => $row['file_id'],
3376 'link_id' => $row['link_id'],
3377 'name' => $row['name'],
3378 'type' => $row['type'],
3379 'size' => $row['size'],
3380 'ctime' => $row['ctime'],
3381 'mtime' => $row['mtime'],
3382 'atime' => $row['atime'],
3383 'comment' => $row['comment'],