1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
|
<?php
/**
* The DataTree_sql:: class provides an SQL implementation of the Horde
* DataTree system.
*
* Required parameters:<pre>
* 'phptype' The database type (ie. 'pgsql', 'mysql', etc.).
* 'charset' The charset used by the database.</pre>
*
* Optional parameters:<pre>
* 'table' The name of the data table in 'database'.
* DEFAULT: 'horde_datatree'</pre>
*
* Required by some database implementations:<pre>
* 'database' The name of the database.
* 'username' The username with which to connect to the database.
* 'password' The password associated with 'username'.
* 'hostspec' The hostname of the database server.
* 'protocol' The communication protocol ('tcp', 'unix', etc.).
* 'options' Additional options to pass to the database.
* 'port' The port on which to connect to the database.
* 'tty' The TTY on which to connect to the database.</pre>
*
* The table structure for the DataTree system is in
* scripts/sql/horde_datatree.sql.
*
* $Horde: framework/DataTree/DataTree/sql.php,v 1.156.2.30 2006/07/13 09:04:20 jan Exp $
*
* Copyright 1999-2006 Stephane Huther <shuther@bigfoot.com>
* Copyright 2001-2006 Chuck Hagenbuch <chuck@horde.org>
* Copyright 2005-2006 Jan Schneider <jan@horde.org>
*
* See the enclosed file COPYING for license information (LGPL). If
* you did not receive this file, see
* http://www.fsf.org/copyleft/lgpl.html.
*
* @author Chuck Hagenbuch <chuck@horde.org>
* @author Jan Schneider <jan@horde.org>
* @author Stephane Huther <shuther@bigfoot.com>
* @since Horde 2.1
* @package Horde_DataTree
*/
class DataTree_sql extends DataTree {
/**
* Handle for the current database connection.
*
* @var DB
*/
var $_db;
/**
* The number of copies of the horde_datatree_attributes table
* that we need to join on in the current query.
*
* @var integer
*/
var $_tableCount = 1;
/**
* Constructs a new SQL DataTree object.
*
* @param array $params A hash containing connection parameters.
*/
function DataTree_sql($params)
{
parent::DataTree($params);
$this->_connect();
}
/**
* Returns a list of all groups (root nodes) of the data tree.
*
* @return array The the group IDs
*/
function getGroups()
{
$query = 'SELECT DISTINCT group_uid FROM ' . $this->_params['table'];
Horde::logMessage('SQL Query by DataTree_sql::getGroups(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
return $this->_db->getCol($query);
}
/**
* Loads (a subset of) the datatree into the $_data array.
*
* @access private
*
* @param string $root Which portion of the tree to load.
* Defaults to all of it.
* @param boolean $loadTree Load a tree starting at $root, or just the
* requested level and direct parents?
* Defaults to single level.
* @param boolean $reload Re-load already loaded values?
* @param string $sortby_name Attribute name to use for sorting.
* @param string $sortby_key Attribute key to use for sorting.
* @param integer $direction Sort direction:
* 0 - ascending
* 1 - descending
*
* @return mixed True on success or a PEAR_Error on failure.
*/
function _load($root = DATATREE_ROOT, $loadTree = false, $reload = false,
$sortby_name = null, $sortby_key = null, $direction = 0)
{
/* Do NOT use DataTree::exists() here; that would cause an infinite
* loop. */
if (!$reload &&
(in_array($root, $this->_nameMap) ||
(count($this->_data) && $root == DATATREE_ROOT)) ||
(!is_null($this->_sortHash) &&
isset($this->_data[$root]['sorter'][$this->_sortHash]))) {
return true;
}
$query = $this->_buildLoadQuery($root,
$loadTree,
DATATREE_BUILD_SELECT,
$sortby_name,
$sortby_key,
$direction);
if (is_a($query, 'PEAR_Error')) {
return $query;
}
if (empty($query)) {
return true;
}
Horde::logMessage('SQL Query by DataTree_sql::_load(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$data = $this->_db->getAll($query);
if (is_a($data, 'PEAR_Error')) {
return $data;
}
return $this->set($data, $this->_params['charset']);
}
/**
* Counts (a subset of) the datatree which would be loaded into the $_data
* array if _load() is called with the same value of $root.
*
* @access private
*
* @param string $root Which portion of the tree to load. Defaults to all
* of it.
*
* @return integer Number of objects
*/
function _count($root = DATATREE_ROOT)
{
$query = $this->_buildLoadQuery($root, true, DATATREE_BUILD_COUNT);
if (is_a($query, 'PEAR_Error')) {
return $query;
}
if (empty($query)) {
return 0;
}
Horde::logMessage('SQL Query by DataTree_sql::_count(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
return (int)$this->_db->getOne($query);
}
/**
* Loads (a subset of) the datatree into the $_data array.
*
* @access private
*
* @param string $root Which portion of the tree to load.
* Defaults to all of it.
* @param boolean $loadTree Load a tree starting at $root, or just the
* requested level and direct parents?
* Defaults to single level.
* @param integer $operation Type of query to build
* @param string $sortby_name Attribute name to use for sorting.
* @param string $sortby_key Attribute key to use for sorting.
* @param integer $direction Sort direction:
* 0 - ascending
* 1 - descending
*
* @return mixed True on success or a PEAR_Error on failure.
*/
function _buildLoadQuery($root = DATATREE_ROOT, $loadTree = false,
$operation = DATATREE_BUILD_SELECT,
$sortby_name = null, $sortby_key = null,
$direction = 0)
{
$sorted = false;
$where = sprintf('c.group_uid = %s ', $this->_db->quote($this->_params['group']));
if (!empty($root) && $root != DATATREE_ROOT) {
$parent_where = $this->_buildParentIds($root, $loadTree, 'c.');
if (!empty($parent_where) && !is_a($parent_where, 'PEAR_Error')) {
$where = sprintf('%s AND (%s)', $where, $parent_where);
}
}
if (!is_null($sortby_name)) {
$where = sprintf('%s AND a.attribute_name = %s ', $where, $this->_db->quote($sortby_name));
$sorted = true;
}
if (!is_null($sortby_key)) {
$where = sprintf('%s AND a.attribute_key = %s ', $where, $this->_db->quote($sortby_key));
$sorted = true;
}
switch ($operation) {
case DATATREE_BUILD_COUNT:
$what = 'COUNT(*)';
break;
default:
$what = 'c.datatree_id, c.datatree_name, c.datatree_parents, c.datatree_order';
break;
}
if ($sorted) {
$query = sprintf('SELECT %s FROM %s c LEFT JOIN %s a ON (c.datatree_id = a.datatree_id OR c.datatree_name=%s) '.
'WHERE %s GROUP BY c.datatree_id, c.datatree_name, c.datatree_parents, c.datatree_order ORDER BY a.attribute_value %s',
$what,
$this->_params['table'],
$this->_params['table_attributes'],
$this->_db->quote($root),
$where,
($direction == 1) ? 'DESC' : 'ASC');
} else {
$query = sprintf('SELECT %s FROM %s c WHERE %s',
$what,
$this->_params['table'],
$where);
}
return $query;
}
/**
* Builds parent ID string for selecting trees.
*
* @access private
*
* @param string $root Which portion of the tree to load.
* @param boolean $loadTree Load a tree starting at $root, or just the
* requested level and direct parents?
* Defaults to single level.
* @param string $join_name Table join name
*
* @return string Id list.
*/
function _buildParentIds($root, $loadTree = false, $join_name = '')
{
if (strpos($root, ':') !== false) {
$parts = explode(':', $root);
$root = array_pop($parts);
}
$root = (string)$root;
$query = 'SELECT datatree_id, datatree_parents' .
' FROM ' . $this->_params['table'] .
' WHERE datatree_name = ? AND group_uid = ?' .
' ORDER BY datatree_id';
$values = array($root,
$this->_params['group']);
Horde::logMessage('SQL Query by DataTree_sql::_buildParentIds(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$root = $this->_db->getAssoc($query, false, $values);
if (is_a($root, 'PEAR_Error') || !count($root)) {
return '';
}
$where = '';
$first_time = true;
foreach ($root as $object_id => $object_parents) {
$pstring = $object_parents . ':' . $object_id . '%';
$pquery = '';
if (!empty($object_parents)) {
$ids = substr($object_parents, 1);
$pquery = ' OR ' . $join_name . 'datatree_id IN (' . str_replace(':', ', ', $ids) . ')';
}
if ($loadTree) {
$pquery .= ' OR ' . $join_name . 'datatree_parents = ' . $this->_db->quote(substr($pstring, 0, -2));
}
if (!$first_time) {
$where .= ' OR ';
}
$where .= sprintf($join_name . 'datatree_parents LIKE %s OR ' . $join_name . 'datatree_id = %s%s',
$this->_db->quote($pstring),
$object_id,
$pquery);
$first_time = false;
}
return $where;
}
/**
* Loads a set of objects identified by their unique IDs, and their
* parents, into the $_data array.
*
* @access private
*
* @param mixed $cids The unique ID of the object to load, or an array of
* object ids.
*
* @return mixed True on success or a PEAR_Error on failure.
*/
function _loadById($cids)
{
/* Make sure we have an array. */
if (!is_array($cids)) {
$cids = array((int)$cids);
} else {
array_walk($cids, 'intval');
}
/* Bail out now if there's nothing to load. */
if (!count($cids)) {
return true;
}
/* Don't load any that are already loaded. Also, make sure that
* everything in the $ids array that we are building is an integer. */
$ids = array();
foreach ($cids as $cid) {
/* Do NOT use DataTree::exists() here; that would cause an
* infinite loop. */
if (!isset($this->_data[$cid])) {
$ids[] = (int)$cid;
}
}
/* If there are none left to load, return. */
if (!count($ids)) {
return true;
}
$in = array_search(DATATREE_ROOT, $ids) === false ? sprintf('datatree_id IN (%s) AND ', implode(', ', $ids)) : '';
$query = sprintf('SELECT datatree_id, datatree_parents FROM %s' .
' WHERE %sgroup_uid = %s' .
' ORDER BY datatree_id',
$this->_params['table'],
$in,
$this->_db->quote($this->_params['group']));
Horde::logMessage('SQL Query by DataTree_sql::_loadById(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$parents = $this->_db->getAssoc($query);
if (is_a($parents, 'PEAR_Error')) {
return $parents;
}
if (empty($parents)) {
return PEAR::raiseError(_("Not found."), null, null, null, 'DataTree ids ' . implode(', ', $ids) . ' not found.');
}
$ids = array();
foreach ($parents as $cid => $parent) {
$ids[(int)$cid] = (int)$cid;
$pids = explode(':', substr($parent, 1));
foreach ($pids as $pid) {
$pid = (int)$pid;
if (!isset($this->_data[$pid])) {
$ids[$pid] = $pid;
}
}
}
/* If $ids is empty, we have nothing to load. */
if (!count($ids)) {
return true;
}
$query = 'SELECT datatree_id, datatree_name, datatree_parents, datatree_order' .
' FROM ' . $this->_params['table'] .
' WHERE datatree_id IN (?' . str_repeat(', ?', count($ids) - 1) . ')' .
' AND group_uid = ? ORDER BY datatree_id';
$values = array_merge($ids, array($this->_params['group']));
Horde::logMessage('SQL Query by DataTree_sql::_loadById(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$data = $this->_db->getAll($query, $values);
if (is_a($data, 'PEAR_Error')) {
return $data;
}
return $this->set($data, $this->_params['charset']);
}
/**
* Returns a tree sorted by the specified attribute name and/or key.
*
* @since Horde 3.1
*
* @param string $root Which portion of the tree to sort.
* Defaults to all of it.
* @param boolean $loadTree Sort the tree starting at $root, or just the
* requested level and direct parents?
* Defaults to single level.
* @param string $sortby_name Attribute name to use for sorting.
* @param string $sortby_key Attribute key to use for sorting.
* @param integer $direction Sort direction:
* 0 - ascending
* 1 - descending
*/
function getSortedTree($root, $loadTree = false, $sortby_name = null,
$sortby_key = null, $direction = 0)
{
$query = $this->_buildLoadQuery($root,
$loadTree,
DATATREE_BUILD_SELECT,
$sortby_name,
$sortby_key,
$direction);
return $this->_db->getAll($query);
}
/**
* Adds an object.
*
* @param mixed $object The object to add (string or
* DataTreeObject).
* @param boolean $id_as_name Whether the object ID is to be used as
* object name. Used in situations where
* there is no available unique input for
* object name.
*/
function add($object, $id_as_name = false)
{
$attributes = false;
if (is_a($object, 'DataTreeObject')) {
$fullname = $object->getName();
$order = $object->order;
/* We handle data differently if we can map it to the
* horde_datatree_attributes table. */
if (method_exists($object, '_toAttributes')) {
$data = '';
$ser = null;
/* Set a flag for later so that we know to insert the
* attribute rows. */
$attributes = true;
} else {
require_once 'Horde/Serialize.php';
$ser = SERIALIZE_UTF7_BASIC;
$data = Horde_Serialize::serialize($object->getData(), $ser, NLS::getCharset());
}
} else {
$fullname = $object;
$order = null;
$data = '';
$ser = null;
}
/* Get the next unique ID. */
$id = $this->_db->nextId($this->_params['table']);
if (is_a($id, 'PEAR_Error')) {
Horde::logMessage($id, __FILE__, __LINE__, PEAR_LOG_ERR);
return $id;
}
if (strpos($fullname, ':') !== false) {
$parts = explode(':', $fullname);
$parents = '';
$pstring = '';
if ($id_as_name) {
/* Requested use of ID as name, so discard current name. */
array_pop($parts);
/* Set name to ID. */
$name = $id;
/* Modify fullname to reflect new name. */
$fullname = implode(':', $parts) . ':' . $id;
if (is_a($object, 'DataTreeObject')) {
$object->setName($fullname);
} else {
$object = $fullname;
}
} else {
$name = array_pop($parts);
}
foreach ($parts as $par) {
$pstring .= (empty($pstring) ? '' : ':') . $par;
$pid = $this->getId($pstring);
if (is_a($pid, 'PEAR_Error')) {
/* Auto-create parents. */
$pid = $this->add($pstring);
if (is_a($pid, 'PEAR_Error')) {
return $pid;
}
}
$parents .= ':' . $pid;
}
} else {
if ($id_as_name) {
/* Requested use of ID as name, set fullname and name to ID. */
$fullname = $id;
$name = $id;
if (is_a($object, 'DataTreeObject')) {
$object->setName($fullname);
} else {
$object = $fullname;
}
} else {
$name = $fullname;
}
$parents = '';
$pid = DATATREE_ROOT;
}
if (parent::exists($fullname)) {
return PEAR::raiseError(_("Already exists"));
}
$query = 'INSERT INTO ' . $this->_params['table'] .
' (datatree_id, group_uid, datatree_name, datatree_order,' .
' datatree_data, user_uid, datatree_serialized,' .
' datatree_parents)' .
' VALUES (?, ?, ?, ?, ?, ?, ?, ?)';
$values = array((int)$id,
$this->_params['group'],
String::convertCharset($name, NLS::getCharset(), $this->_params['charset']),
is_null($order) ? NULL : (int)$order,
$data,
(string)Auth::getAuth(),
(int)$ser,
$parents);
Horde::logMessage('SQL Query by DataTree_sql::add(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
if (is_a($result, 'PEAR_Error')) {
Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
return $result;
}
$reorder = $this->reorder($parents, $order, $id);
if (is_a($reorder, 'PEAR_Error')) {
Horde::logMessage($reorder, __FILE__, __LINE__, PEAR_LOG_ERR);
return $reorder;
}
$result = parent::_add($fullname, $id, $pid, $order);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
/* If we succesfully inserted the object and it supports
* being mapped to the attributes table, do that now: */
if (!empty($attributes)) {
$result = $this->updateData($object);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
}
return $id;
}
/**
* Changes the order of the children of an object.
*
* @param string $parent The full id path of the parent object.
* @param mixed $order If an array it specifies the new positions for
* all child objects.
* If an integer and $cid is specified, the position
* where the child specified by $cid is inserted. If
* $cid is not specified, the position gets deleted,
* causing the following positions to shift up.
* @param integer $cid See $order.
*/
function reorder($parent, $order = null, $cid = null)
{
if (!$parent || is_a($parent, 'PEAR_Error')) {
// Abort immediately if the parent string is empty; we
// cannot safely reorder all top-level elements.
return;
}
$pquery = '';
if (!is_array($order) && !is_null($order)) {
/* Single update (add/del). */
if (is_null($cid)) {
/* No object id given so shuffle down. */
$direction = '-';
} else {
/* We have an object id so shuffle up. */
$direction = '+';
/* Leaving the newly inserted object alone. */
$pquery = sprintf(' AND datatree_id != %s', (int)$cid);
}
$query = sprintf('UPDATE %s SET datatree_order = datatree_order %s 1 WHERE group_uid = %s AND datatree_parents = %s AND datatree_order >= %s',
$this->_params['table'],
$direction,
$this->_db->quote($this->_params['group']),
$this->_db->quote($parent),
is_null($order) ? 'NULL' : (int)$order) . $pquery;
Horde::logMessage('SQL Query by DataTree_sql::reorder(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query);
} elseif (is_array($order)) {
/* Multi update. */
$query = 'SELECT COUNT(datatree_id)' .
' FROM ' . $this->_params['table'] .
' WHERE group_uid = ? AND datatree_parents = ?' .
' GROUP BY datatree_parents';
$values = array($this->_params['group'],
$parent);
Horde::logMessage('SQL Query by DataTree_sql::reorder(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->getOne($query, $values);
if (is_a($result, 'PEAR_Error')) {
return $result;
} elseif (count($order) != $result) {
return PEAR::raiseError(_("Cannot reorder, number of entries supplied for reorder does not match number stored."));
}
$o_key = 0;
foreach ($order as $o_cid) {
$query = 'UPDATE ' . $this->_params['table'] .
' SET datatree_order = ? WHERE datatree_id = ?';
$values = array($o_key, is_null($o_cid) ? NULL : (int)$o_cid);
Horde::logMessage('SQL Query by DataTree_sql::reorder(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
$o_key++;
}
$pid = $this->getId($parent);
/* Re-order our cache. */
return $this->_reorder($pid, $order);
}
}
/**
* Explicitly set the order for a datatree object.
*
* @param integer $id The datatree object id to change.
* @param integer $order The new order.
*/
function setOrder($id, $order)
{
$query = 'UPDATE ' . $this->_params['table'] .
' SET datatree_order = ? WHERE datatree_id = ?';
$values = array(is_null($order) ? NULL : (int)$order,
(int)$id);
Horde::logMessage('SQL Query by DataTree_sql::setOrder(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
return $this->_db->query($query, $values);
}
/**
* Removes an object.
*
* @param mixed $object The object to remove.
* @param boolean $force Force removal of every child object?
*/
function remove($object, $force = false)
{
$id = $this->getId($object);
$order = $this->getOrder($object);
$query = 'SELECT datatree_id FROM ' . $this->_params['table'] .
' WHERE group_uid = ? AND datatree_parents LIKE ?' .
' ORDER BY datatree_id';
$values = array($this->_params['group'],
'%:' . (int)$id . '');
Horde::logMessage('SQL Query by DataTree_sql::remove(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$children = $this->_db->getAll($query, $values, DB_FETCHMODE_ASSOC);
if (count($children)) {
if ($force) {
foreach ($children as $child) {
$cat = $this->getName($child['datatree_id']);
$result = $this->remove($cat, true);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
}
} else {
return PEAR::raiseError(sprintf(_("Cannot remove, %d children exist."), count($children)));
}
}
/* Remove attributes for this object. */
$query = 'DELETE FROM ' . $this->_params['table_attributes'] .
' WHERE datatree_id = ?';
$values = array((int)$id);
Horde::logMessage('SQL Query by DataTree_sql::remove(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
$query = 'DELETE FROM ' . $this->_params['table'] .
' WHERE datatree_id = ?';
$values = array((int)$id);
Horde::logMessage('SQL Query by DataTree_sql::remove(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
$parents = $this->getParentIdString($object);
if (is_a($parents, 'PEAR_Error')) {
return $parents;
}
$reorder = $this->reorder($parents, $order);
if (is_a($reorder, 'PEAR_Error')) {
return $reorder;
}
return is_a(parent::remove($object), 'PEAR_Error') ? $id : true;
}
/**
* Removes one or more objects by id.
*
* This function does *not* do the validation, reordering, etc. that
* remove() does. If you need to check for children, re-do ordering, etc.,
* then you must remove() objects one-by-one. This is for code that knows
* it's dealing with single (non-parented) objects and needs to delete a
* batch of them quickly.
*
* @param array $ids The objects to remove.
*/
function removeByIds($ids)
{
/* Sanitize input. */
if (!is_array($ids)) {
$ids = array((int)$ids);
} else {
array_walk($ids, 'intval');
}
/* Removing zero objects always succeeds. */
if (!$ids) {
return true;
}
/* Remove attributes for $ids. */
$query = 'DELETE FROM ' . $this->_params['table_attributes'] .
' WHERE datatree_id IN (?' . str_repeat(', ?', count($ids) - 1) . ')';
$values = $ids;
Horde::logMessage('SQL Query by DataTree_sql::removeByIds(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
$query = 'DELETE FROM ' . $this->_params['table'] .
' WHERE datatree_id IN (?' . str_repeat(', ?', count($ids) - 1) . ')';
$values = $ids;
Horde::logMessage('SQL Query by DataTree_sql::removeByIds(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
return $this->_db->query($query, $values);
}
/**
* Removes one or more objects by name.
*
* This function does *not* do the validation, reordering, etc. that
* remove() does. If you need to check for children, re-do ordering, etc.,
* then you must remove() objects one-by-one. This is for code that knows
* it's dealing with single (non-parented) objects and needs to delete a
* batch of them quickly.
*
* @param array $names The objects to remove.
*/
function removeByNames($names)
{
if (!is_array($names)) {
$names = array($names);
}
/* Removing zero objects always succeeds. */
if (!$names) {
return true;
}
$query = 'SELECT datatree_id FROM ' . $this->_params['table'] .
' WHERE datatree_name IN (?' . str_repeat(', ?', count($names) - 1) . ')';
$values = $names;
Horde::logMessage('SQL Query by DataTree_sql::removeByNames(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$ids = $this->_db->getCol($query, 0, $values);
if (is_a($ids, 'PEAR_Error')) {
return $ids;
}
return $this->removeByIds($ids);
}
/**
* Move an object to a new parent.
*
* @param mixed $object The object to move.
* @param string $newparent The new parent object. Defaults to the root.
*/
function move($object, $newparent = null)
{
$old_parent_path = $this->getParentIdString($object);
$result = parent::move($object, $newparent);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
$id = $this->getId($object);
$new_parent_path = $this->getParentIdString($object);
/* Fetch the object being moved and all of its children, since
* we also need to update their parent paths to avoid creating
* orphans. */
$query = 'SELECT datatree_id, datatree_parents' .
' FROM ' . $this->_params['table'] .
' WHERE datatree_parents = ? OR datatree_parents LIKE ?' .
' OR datatree_id = ?';
$values = array($old_parent_path . ':' . $id,
$old_parent_path . ':' . $id . ':%',
(int)$id);
Horde::logMessage('SQL Query by DataTree_sql::move(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$rowset = $this->_db->query($query, $values);
if (is_a($rowset, 'PEAR_Error')) {
return $rowset;
}
/* Update each object, replacing the old parent path with the
* new one. */
while ($row = $rowset->fetchRow(DB_FETCHMODE_ASSOC)) {
if (is_a($row, 'PEAR_Error')) {
return $row;
}
$oquery = '';
if ($row['datatree_id'] == $id) {
$oquery = ', datatree_order = 0 ';
}
/* Do str_replace() only if this is not a first level
* object. */
if (!empty($row['datatree_parents'])) {
$ppath = str_replace($old_parent_path, $new_parent_path, $row['datatree_parents']);
} else {
$ppath = $new_parent_path;
}
$query = sprintf('UPDATE %s SET datatree_parents = %s' . $oquery . ' WHERE datatree_id = %s',
$this->_params['table'],
$this->_db->quote($ppath),
(int)$row['datatree_id']);
Horde::logMessage('SQL Query by DataTree_sql::move(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
}
$order = $this->getOrder($object);
/* Shuffle down the old order positions. */
$reorder = $this->reorder($old_parent_path, $order);
/* Shuffle up the new order positions. */
$reorder = $this->reorder($new_parent_path, 0, $id);
return true;
}
/**
* Change an object's name.
*
* @param mixed $old_object The old object.
* @param string $new_object_name The new object name.
*/
function rename($old_object, $new_object_name)
{
/* Do the cache renaming first */
$result = parent::rename($old_object, $new_object_name);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
/* Get the object id and set up the sql query. */
$id = $this->getId($old_object);
$query = 'UPDATE ' . $this->_params['table'] .
' SET datatree_name = ? WHERE datatree_id = ?';
$values = array(String::convertCharset($new_object_name, NLS::getCharset(), $this->_params['charset']),
(int)$id);
Horde::logMessage('SQL Query by DataTree_sql::rename(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
return is_a($result, 'PEAR_Error') ? $result : true;
}
/**
* Retrieves data for an object from the datatree_data field.
*
* @param integer $cid The object id to fetch, or an array of object ids.
*/
function getData($cid)
{
require_once 'Horde/Serialize.php';
if (is_array($cid)) {
if (!count($cid)) {
return array();
}
$query = sprintf('SELECT datatree_id, datatree_data, datatree_serialized FROM %s WHERE datatree_id IN (%s)',
$this->_params['table'],
implode(', ', $cid));
Horde::logMessage('SQL Query by DataTree_sql::getData(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->getAssoc($query);
if (is_a($result, 'PEAR_Error')) {
Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
return $result;
}
$data = array();
foreach ($result as $id => $row) {
$data[$id] = Horde_Serialize::unserialize($row[0], $row[1],
NLS::getCharset());
/* Convert old data to the new format. */
if ($row[1] == SERIALIZE_BASIC) {
$data[$id] = String::convertCharset($data[$id],
NLS::getCharset(true));
}
$data[$id] = (is_null($data[$id]) || !is_array($data[$id]))
? array()
: $data[$id];
}
return $data;
} else {
$query = 'SELECT datatree_data, datatree_serialized' .
' FROM ' . $this->_params['table'] .
' WHERE datatree_id = ?';
$values = array((int)$cid);
Horde::logMessage('SQL Query by DataTree_sql::getData(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$row = $this->_db->getRow($query, $values, DB_FETCHMODE_ASSOC);
$data = Horde_Serialize::unserialize($row['datatree_data'],
$row['datatree_serialized'],
NLS::getCharset());
/* Convert old data to the new format. */
if ($row['datatree_serialized'] == SERIALIZE_BASIC) {
$data = String::convertCharset($data, NLS::getCharset(true));
}
return (is_null($data) || !is_array($data)) ? array() : $data;
}
}
/**
* Retrieves data for an object from the horde_datatree_attributes table.
*
* @param integer|array $cid The object id to fetch, or an array of
* object ids.
* @param array $keys The attributes keys to fetch.
*
* @return array A hash of attributes, or a multi-level hash of object
* ids => their attributes.
*/
function getAttributes($cid, $keys = false)
{
if (empty($cid)) {
return array();
}
if ($keys) {
$filter = sprintf(' AND attribute_key IN (\'%s\')',
implode("', '", $keys));
} else {
$filter = '';
}
if (is_array($cid)) {
$query = sprintf('SELECT datatree_id, attribute_name AS name, attribute_key AS "key", attribute_value AS value FROM %s WHERE datatree_id IN (%s)%s',
$this->_params['table_attributes'],
implode(', ', $cid),
$filter);
Horde::logMessage('SQL Query by DataTree_sql::getAttributes(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$rows = $this->_db->getAll($query, DB_FETCHMODE_ASSOC);
if (is_a($rows, 'PEAR_Error')) {
return $rows;
}
$data = array();
foreach ($rows as $row) {
if (empty($data[$row['datatree_id']])) {
$data[$row['datatree_id']] = array();
}
$data[$row['datatree_id']][] = array('name' => $row['name'],
'key' => $row['key'],
'value' => String::convertCharset($row['value'], $this->_params['charset'], NLS::getCharset()));
}
return $data;
} else {
$query = sprintf('SELECT attribute_name AS name, attribute_key AS "key", attribute_value AS value FROM %s WHERE datatree_id = %s%s',
$this->_params['table_attributes'],
(int)$cid,
$filter);
Horde::logMessage('SQL Query by DataTree_sql::getAttributes(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$rows = $this->_db->getAll($query, DB_FETCHMODE_ASSOC);
for ($i = 0; $i < count($rows); $i++) {
$rows[$i]['value'] = String::convertCharset($rows[$i]['value'],
$this->_params['charset'],
NLS::getCharset());
}
return $rows;
}
}
/**
* Returns the number of objects matching a set of attribute criteria.
*
* @see buildAttributeQuery()
*
* @param array $criteria The array of criteria.
* @param string $parent The parent node to start searching from.
* @param boolean $allLevels Return all levels, or just the direct
* children of $parent? Defaults to all levels.
* @param string $restrict Only return attributes with the same
* attribute_name or attribute_id.
*/
function countByAttributes($criteria, $parent = DATATREE_ROOT,
$allLevels = true, $restrict = 'name')
{
if (!count($criteria)) {
return 0;
}
$aq = $this->buildAttributeQuery($criteria,
$parent,
$allLevels,
$restrict,
DATATREE_BUILD_COUNT);
if (is_a($aq, 'PEAR_Error')) {
return $aq;
}
list($query, $values) = $aq;
Horde::logMessage('SQL Query by DataTree_sql::countByAttributes(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
if (is_a($result, 'PEAR_Error')) {
Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
return $result;
}
$row = &$result->fetchRow();
if (is_a($row, 'PEAR_Error')) {
Horde::logMessage($row, __FILE__, __LINE__, PEAR_LOG_ERR);
return $row;
}
return $row[0];
}
/**
* Returns a set of object ids based on a set of attribute criteria.
*
* @see buildAttributeQuery()
*
* @param array $criteria The array of criteria.
* @param string $parent The parent node to start searching from.
* @param boolean $allLevels Return all levels, or just the direct
* children of $parent? Defaults to all levels.
* @param string $restrict Only return attributes with the same
* attribute_name or attribute_id.
* @param integer $from The object to start to fetching
* @param integer $count The number of objects to fetch
* @param string $sortby_name Attribute name to use for sorting.
* @param string $sortby_key Attribute key to use for sorting.
* @param integer $direction Sort direction:
* 0 - ascending
* 1 - descending
*/
function getByAttributes($criteria, $parent = DATATREE_ROOT,
$allLevels = true, $restrict = 'name', $from = 0,
$count = 0, $sortby_name = null,
$sortby_key = null, $direction = 0)
{
if (!count($criteria)) {
return PEAR::raiseError('no criteria');
}
$aq = $this->buildAttributeQuery($criteria,
$parent,
$allLevels,
$restrict,
DATATREE_BUILD_SELECT,
$sortby_name,
$sortby_key,
$direction);
if (is_a($aq, 'PEAR_Error')) {
return $aq;
}
list($query, $values) = $aq;
Horde::logMessage('SQL Query by DataTree_sql::getByAttributes(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
if ($count) {
$result = $this->_db->limitQuery($query, $from, $count, $values);
} else {
$result = $this->_db->query($query, $values);
}
if (is_a($result, 'PEAR_Error')) {
Horde::logMessage($result, __FILE__, __LINE__, PEAR_LOG_ERR);
return $result;
}
$rows = array();
while ($row = &$result->fetchRow()) {
$rows[$row[0]] = String::convertCharset($row[1], $this->_params['charset']);
}
return $rows;
}
/**
* Sorts IDs by attribute values. IDs without attributes will be added to
* the end of the sorted list.
*
* @param array $unordered_ids Array of ids to sort.
* @param array $sortby_name Attribute name to use for sorting.
* @param array $sortby_key Attribute key to use for sorting.
* @param array $direction Sort direction:
* 0 - ascending
* 1 - descending
*
* @return array Sorted ids.
*/
function sortByAttributes($unordered_ids, $sortby_name = null,
$sortby_key = null, $direction = 0)
{
/* Select ids ordered by attribute value. */
$where = '';
if (!is_null($sortby_name)) {
$where = sprintf(' AND attribute_name = %s ',
$this->_db->quote($sortby_name));
}
if (!is_null($sortby_key)) {
$where = sprintf('%s AND attribute_key = %s ',
$where,
$this->_db->quote($sortby_key));
}
$query = sprintf('SELECT datatree_id FROM %s WHERE datatree_id IN (%s) %s ORDER BY attribute_value %s',
$this->_params['table_attributes'],
implode(',', $unordered_ids),
$where,
($direction == 1) ? 'DESC' : 'ASC');
Horde::logMessage('SQL Query by DataTree_sql::sortByAttributes(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$ordered_ids = $this->_db->getCol($query);
/* Make sure that some ids didn't get lost because has no such
* attribute name/key. Append them to the end. */
if (count($ordered_ids) != count($unordered_ids)) {
$ordered_ids = array_unique(array_merge($ordered_ids, $unordered_ids));
}
return $ordered_ids;
}
/**
* Returns a list of all of the available values of the given attribute
* name/key combination. Either attribute_name or attribute_key MUST be
* supplied, and both MAY be supplied.
*
* @param string $attribute_name The name of the attribute.
* @param string $attribute_key The key value of the attribute.
* @param string $parent The parent node to start searching from.
* @param boolean $allLevels Return all levels, or just the direct
* children of $parent? Defaults to all
* levels.
*
* @return array An array of all of the available values.
*/
function getAttributeValues($attribute_name = null, $attribute_key = null,
$parent = DATATREE_ROOT, $allLevels = true)
{
// Build the name/key filter.
$where = '';
if (!is_null($attribute_name)) {
$where .= 'a.attribute_name = ' . $this->_db->quote($attribute_name);
}
if (!is_null($attribute_key)) {
if ($where) {
$where .= ' AND ';
}
$where .= 'a.attribute_key = ' . $this->_db->quote($attribute_key);
}
// Return if we have no criteria.
if (!$where) {
return PEAR::raiseError('no criteria');
}
// Add filtering by parent, and for one or all levels.
$levelQuery = '';
if ($parent != DATATREE_ROOT) {
$parts = explode(':', $parent);
$parents = '';
$pstring = '';
foreach ($parts as $part) {
$pstring .= (empty($pstring) ? '' : ':') . $part;
$pid = $this->getId($pstring);
if (is_a($pid, 'PEAR_Error')) {
return $pid;
}
$parents .= ':' . $pid;
}
if ($allLevels) {
$levelQuery = sprintf('AND (datatree_parents = %s OR datatree_parents LIKE %s)',
$this->_db->quote($parents),
$this->_db->quote($parents . ':%'));
} else {
$levelQuery = sprintf('AND datatree_parents = %s',
$this->_db->quote($parents));
}
} elseif (!$allLevels) {
$levelQuery = "AND datatree_parents = ''";
}
// Build the FROM/JOIN clauses.
$joins = 'LEFT JOIN ' . $this->_params['table'] .
' c ON a.datatree_id = c.datatree_id';
$query = sprintf('SELECT DISTINCT a.attribute_value FROM %s a %s WHERE c.group_uid = %s AND %s %s',
$this->_params['table_attributes'],
$joins,
$this->_db->quote($this->_params['group']),
$where,
$levelQuery);
Horde::logMessage('SQL Query by DataTree_sql::getAttributeValues(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$rows = $this->_db->getCol($query);
if (is_a($rows, 'PEAR_Error')) {
Horde::logMessage($rows, __FILE__, __LINE__, PEAR_LOG_ERR);
}
return $rows;
}
/**
* Builds an attribute query. Here is an example $criteria array:
*
* <code>
* $criteria['OR'] = array(
* array('AND' => array(
* array('field' => 'name',
* 'op' => '=',
* 'test' => 'foo'),
* array('field' => 'key',
* 'op' => '=',
* 'test' => 'abc'))),
* array('AND' => array(
* array('field' => 'name',
* 'op' => '=',
* 'test' => 'bar'),
* array('field' => 'key',
* 'op' => '=',
* 'test' => 'xyz'))));
* </code>
*
* This would fetch all object ids where attribute name is "foo" AND key
* is "abc", OR "bar" AND "xyz".
*
* @param array $criteria The array of criteria.
* @param string $parent The parent node to start searching from.
* @param boolean $allLevels Return all levels, or just the direct
* children of $parent? Defaults to all levels.
* @param string $restrict Only return attributes with the same
* attribute_name or attribute_id.
* @param integer $operation Type of query to build
* @param string $sortby_name Attribute name to use for sorting.
* @param string $sortby_key Attribute key to use for sorting.
* @param integer $direction Sort direction:
* 0 - ascending
* 1 - descending
*
* @return array An SQL query and a list of values suitable for binding
* as an array.
*/
function buildAttributeQuery($criteria, $parent = DATATREE_ROOT,
$allLevels = true, $restrict = 'name',
$operation = DATATREE_BUILD_SELECT,
$sortby_name = null, $sortby_key = null,
$direction = 0)
{
if (!count($criteria)) {
return array('', array());
}
/* Build the query. */
$this->_tableCount = 1;
$query = '';
$values = array();
foreach ($criteria as $key => $vals) {
if ($key == 'OR' || $key == 'AND') {
if (!empty($query)) {
$query .= ' ' . $key . ' ';
}
$binds = $this->_buildAttributeQuery($key, $vals);
$query .= '(' . $binds[0] . ')';
$values += $binds[1];
}
}
// Add filtering by parent, and for one or all levels.
$levelQuery = '';
$levelValues = array();
if ($parent != DATATREE_ROOT) {
$parts = explode(':', $parent);
$parents = '';
$pstring = '';
foreach ($parts as $part) {
$pstring .= (empty($pstring) ? '' : ':') . $part;
$pid = $this->getId($pstring);
if (is_a($pid, 'PEAR_Error')) {
return $pid;
}
$parents .= ':' . $pid;
}
if ($allLevels) {
$levelQuery = 'AND (datatree_parents = ? OR datatree_parents LIKE ?)';
$levelValues = array($parents, $parents . ':%');
} else {
$levelQuery = 'AND datatree_parents = ?';
$levelValues = array($parents);
}
} elseif (!$allLevels) {
$levelQuery = "AND datatree_parents = ''";
}
// Build the FROM/JOIN clauses.
$joins = array();
$pairs = array();
for ($i = 1; $i <= $this->_tableCount; $i++) {
$joins[] = 'LEFT JOIN ' . $this->_params['table_attributes'] .
' a' . $i . ' ON a' . $i . '.datatree_id = c.datatree_id';
if ($i != 1) {
if ($restrict == 'name') {
$pairs[] = 'AND a1.attribute_name = a' . $i . '.attribute_name';
} elseif ($restrict == 'id') {
$pairs[] = 'AND a1.datatree_id = a' . $i . '.datatree_id';
}
}
}
// Override sorting.
$sort = array();
if (!is_null($sortby_name) || !is_null($sortby_key)) {
$order_table = 'a' . $i;
$joins[] = 'LEFT JOIN ' . $this->_params['table_attributes'] .
' ' . $order_table . ' ON ' . $order_table .
'.datatree_id = c.datatree_id';
if (!is_null($sortby_name)) {
$pairs[] = sprintf('AND %s.attribute_name = ? ', $order_table);
$sort[] = $sortby_name;
}
if (!is_null($sortby_key)) {
$pairs[] = sprintf('AND %s.attribute_key = ? ', $order_table);
$sort[] = $sortby_key;
}
$order = sprintf('%s.attribute_value %s',
$order_table,
($direction == 1) ? 'DESC' : 'ASC');
$group_by = 'c.datatree_id, c.datatree_name, c.datatree_order, ' .
$order_table . '.attribute_value';
} else {
$order = 'c.datatree_order, c.datatree_name, c.datatree_id';
$group_by = 'c.datatree_id, c.datatree_name, c.datatree_order';
}
$joins = implode(' ', $joins);
$pairs = implode(' ', $pairs);
$tail = sprintf('GROUP BY %s ORDER BY %s', $group_by, $order);
switch ($operation) {
case DATATREE_BUILD_COUNT:
$what = 'COUNT(DISTINCT c.datatree_id)';
$tail = '';
break;
default:
$what = 'c.datatree_id, c.datatree_name';
break;
}
return array(sprintf('SELECT %s FROM %s c %s WHERE c.group_uid = ? AND %s %s %s %s',
$what,
$this->_params['table'],
$joins,
$query,
$levelQuery,
$pairs,
$tail),
array_merge(array($this->_params['group']),
$values,
$levelValues,
$sort));
}
/**
* Builds a piece of an attribute query.
*
* @param string $glue The glue to join the criteria (OR/AND).
* @param array $criteria The array of criteria.
* @param boolean $join Should we join on a clean
* horde_datatree_attributes table? Defaults to
* false.
*
* @return array An SQL fragment and a list of values suitable for binding
* as an array.
*/
function _buildAttributeQuery($glue, $criteria, $join = false)
{
require_once 'Horde/SQL.php';
// Initialize the clause that we're building.
$clause = '';
$values = array();
// Get the table alias to use for this set of criteria.
$alias = $this->_getAlias($join);
foreach ($criteria as $key => $vals) {
if (!empty($clause)) {
$clause .= ' ' . $glue . ' ';
}
if (!empty($vals['OR']) || !empty($vals['AND'])) {
$binds = $this->_buildAttributeQuery($glue, $vals);
$clause .= '(' . $binds[0] . ')';
$values = array_merge($values, $binds[1]);
} elseif (!empty($vals['JOIN'])) {
$binds = $this->_buildAttributeQuery($glue, $vals['JOIN'], true);
$clause .= $binds[0];
$values = array_merge($values, $binds[1]);
} else {
if (isset($vals['field'])) {
$binds = Horde_SQL::buildClause($this->_db, $alias . '.attribute_' . $vals['field'], $vals['op'], $vals['test'], true);
$clause .= $binds[0];
$values = array_merge($values, $binds[1]);
} else {
$binds = $this->_buildAttributeQuery($key, $vals);
$clause .= $binds[0];
$values = array_merge($values, $binds[1]);
}
}
}
return array($clause, $values);
}
/**
* Get an alias to horde_datatree_attributes, incrementing it if
* necessary.
*
* @param boolean $increment Increment the alias count? Defaults to no.
*/
function _getAlias($increment = false)
{
static $seen = array();
if ($increment && !empty($seen[$this->_tableCount])) {
$this->_tableCount++;
}
$seen[$this->_tableCount] = true;
return 'a' . $this->_tableCount;
}
/**
* Update the data in an object. Does not change the object's
* parent or name, just serialized data or attributes.
*
* @param DataTree $object A DataTree object.
*/
function updateData($object)
{
if (!is_a($object, 'DataTreeObject')) {
/* Nothing to do for non objects. */
return true;
}
/* Get the object id. */
$id = $this->getId($object->getName());
if (is_a($id, 'PEAR_Error')) {
return $id;
}
/* See if we can break the object out to datatree_attributes table. */
if (method_exists($object, '_toAttributes')) {
/* If we can, clear out the datatree_data field to make sure it
* doesn't get picked up by getData(). Intentionally don't check
* for errors here in case datatree_data goes away in the
* future. */
$query = 'UPDATE ' . $this->_params['table'] .
' SET datatree_data = ? WHERE datatree_id = ?';
$values = array(NULL, (int)$id);
Horde::logMessage('SQL Query by DataTree_sql::updateData(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$this->_db->query($query, $values);
/* Start a transaction. */
$this->_db->autoCommit(false);
/* Delete old attributes. */
$query = 'DELETE FROM ' . $this->_params['table_attributes'] .
' WHERE datatree_id = ?';
$values = array((int)$id);
Horde::logMessage('SQL Query by DataTree_sql::updateData(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
if (is_a($result, 'PEAR_Error')) {
$this->_db->rollback();
$this->_db->autoCommit(true);
return $result;
}
/* Get the new attribute set, and insert each into the DB. If
* anything fails in here, rollback the transaction, return the
* relevant error, and bail out. */
$attributes = $object->_toAttributes();
$query = 'INSERT INTO ' . $this->_params['table_attributes'] .
' (datatree_id, attribute_name, attribute_key, attribute_value)' .
' VALUES (?, ?, ?, ?)';
$statement = $this->_db->prepare($query);
foreach ($attributes as $attr) {
$values = array((int)$id,
$attr['name'],
$attr['key'],
String::convertCharset($attr['value'], NLS::getCharset(), $this->_params['charset']));
Horde::logMessage('SQL Query by DataTree_sql::updateData(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->execute($statement, $values);
if (is_a($result, 'PEAR_Error')) {
$this->_db->rollback();
$this->_db->autoCommit(true);
return $result;
}
}
/* Commit the transaction, and turn autocommit back on. */
$result = $this->_db->commit();
$this->_db->autoCommit(true);
return is_a($result, 'PEAR_Error') ? $result : true;
} else {
/* Write to the datatree_data field. */
require_once 'Horde/Serialize.php';
$ser = SERIALIZE_UTF7_BASIC;
$data = Horde_Serialize::serialize($object->getData(), $ser, NLS::getCharset());
$query = 'UPDATE ' . $this->_params['table'] .
' SET datatree_data = ?, datatree_serialized = ?' .
' WHERE datatree_id = ?';
$values = array($data,
(int)$ser,
(int)$id);
Horde::logMessage('SQL Query by DataTree_sql::updateData(): ' . $query, __FILE__, __LINE__, PEAR_LOG_DEBUG);
$result = $this->_db->query($query, $values);
return is_a($result, 'PEAR_Error') ? $result : true;
}
}
/**
* Attempts to open a connection to the SQL server.
*
* @return boolean True.
*/
function _connect()
{
Horde::assertDriverConfig($this->_params, 'storage',
array('phptype', 'charset'),
'DataTree SQL');
if (!isset($this->_params['database'])) {
$this->_params['database'] = '';
}
if (!isset($this->_params['username'])) {
$this->_params['username'] = '';
}
if (!isset($this->_params['password'])) {
$this->_params['password'] = '';
}
if (!isset($this->_params['hostspec'])) {
$this->_params['hostspec'] = '';
}
if (!isset($this->_params['table'])) {
$this->_params['table'] = 'horde_datatree';
}
if (!isset($this->_params['table_attributes'])) {
$this->_params['table_attributes'] = 'horde_datatree_attributes';
}
/* Connect to the SQL server using the supplied parameters. */
require_once 'DB.php';
$this->_db = &DB::connect($this->_params,
array('persistent' => !empty($this->_params['persistent'])));
if (is_a($this->_db, 'PEAR_Error')) {
Horde::fatal($this->_db, __FILE__, __LINE__);
}
// Set DB portability options
switch ($this->_db->phptype) {
case 'mssql':
$this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS | DB_PORTABILITY_RTRIM);
break;
default:
$this->_db->setOption('portability', DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_ERRORS);
}
return true;
}
}
|