PageRenderTime 82ms CodeModel.GetById 5ms RepoModel.GetById 0ms app.codeStats 1ms

/app/models/ca_sets.php

https://bitbucket.org/Sinfin/pawtucket
PHP | 1506 lines | 955 code | 149 blank | 402 comment | 192 complexity | 498eea2f5af808109f4ae06115983930 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /** ---------------------------------------------------------------------
  3. * app/models/ca_sets.php : table access class for table ca_sets
  4. * ----------------------------------------------------------------------
  5. * CollectiveAccess
  6. * Open-source collections management software
  7. * ----------------------------------------------------------------------
  8. *
  9. * Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
  10. * Copyright 2009-2011 Whirl-i-Gig
  11. *
  12. * For more information visit http://www.CollectiveAccess.org
  13. *
  14. * This program is free software; you may redistribute it and/or modify it under
  15. * the terms of the provided license as published by Whirl-i-Gig
  16. *
  17. * CollectiveAccess is distributed in the hope that it will be useful, but
  18. * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  20. *
  21. * This source code is free and modifiable under the terms of
  22. * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
  23. * the "license.txt" file for details, or visit the CollectiveAccess web site at
  24. * http://www.CollectiveAccess.org
  25. *
  26. * @package CollectiveAccess
  27. * @subpackage models
  28. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3
  29. *
  30. * ----------------------------------------------------------------------
  31. */
  32. /**
  33. *
  34. */
  35. require_once(__CA_LIB_DIR__."/ca/IBundleProvider.php");
  36. require_once(__CA_LIB_DIR__."/ca/BundlableLabelableBaseModelWithAttributes.php");
  37. require_once(__CA_APP_DIR__.'/models/ca_set_items.php');
  38. require_once(__CA_APP_DIR__.'/models/ca_users.php');
  39. require_once(__CA_APP_DIR__.'/helpers/htmlFormHelpers.php');
  40. define('__CA_SET_NO_ACCESS__', 0);
  41. define('__CA_SET_READ_ACCESS__', 1);
  42. define('__CA_SET_EDIT_ACCESS__', 2);
  43. BaseModel::$s_ca_models_definitions['ca_sets'] = array(
  44. 'NAME_SINGULAR' => _t('set'),
  45. 'NAME_PLURAL' => _t('sets'),
  46. 'FIELDS' => array(
  47. 'set_id' => array(
  48. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_HIDDEN,
  49. 'IDENTITY' => true, 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
  50. 'IS_NULL' => false,
  51. 'DEFAULT' => '',
  52. 'LABEL' => _t('CollectiveAccess id'), 'DESCRIPTION' => _t('Unique numeric identifier used by CollectiveAccess internally to identify this set')
  53. ),
  54. 'parent_id' => array(
  55. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_OMIT,
  56. 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
  57. 'IS_NULL' => true,
  58. 'DEFAULT' => '',
  59. 'LABEL' => 'Parent id', 'DESCRIPTION' => 'Identifier of parent set; is null if set is root of hierarchy.'
  60. ),
  61. 'hier_set_id' => array(
  62. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_OMIT,
  63. 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
  64. 'IS_NULL' => false,
  65. 'DEFAULT' => '',
  66. 'LABEL' => 'Set hierarchy', 'DESCRIPTION' => 'Identifier of set that is root of the set hierarchy.'
  67. ),
  68. 'user_id' => array(
  69. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_OMIT,
  70. 'DISPLAY_WIDTH' => 40, 'DISPLAY_HEIGHT' => 1,
  71. 'IS_NULL' => true,
  72. 'DISPLAY_FIELD' => array('ca_users.lname', 'ca_users.fname'),
  73. 'DEFAULT' => '',
  74. 'LABEL' => _t('User'), 'DESCRIPTION' => _t('The user who created the set.')
  75. ),
  76. 'table_num' => array(
  77. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_SELECT,
  78. 'DISPLAY_WIDTH' => 40, 'DISPLAY_HEIGHT' => 1,
  79. 'DONT_USE_AS_BUNDLE' => true,
  80. 'IS_NULL' => false,
  81. 'DEFAULT' => '',
  82. 'LABEL' => _t('Set content'), 'DESCRIPTION' => _t('Determines what kind of items (objects, entities, places, etc.) are stored by the set.'),
  83. 'BOUNDS_CHOICE_LIST' => array(
  84. _t('Objects') => 57,
  85. _t('Object lots') => 51,
  86. _t('Entities') => 20,
  87. _t('Places') => 72,
  88. _t('Occurrences') => 67,
  89. _t('Collections') => 13,
  90. _t('Storage locations') => 89,
  91. _t('Object representations') => 56
  92. ),
  93. 'BOUNDS_LENGTH' => array(1,100)
  94. ),
  95. 'type_id' => array(
  96. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_SELECT,
  97. 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
  98. 'IS_NULL' => false,
  99. 'DEFAULT' => '',
  100. 'LIST_CODE' => 'set_types',
  101. 'LABEL' => _t('Type'), 'DESCRIPTION' => _t('The type of the set determines what sorts of information the set and each item in the set can have associated with them.')
  102. ),
  103. 'set_code' => array(
  104. 'FIELD_TYPE' => FT_TEXT, 'DISPLAY_TYPE' => DT_FIELD,
  105. 'DISPLAY_WIDTH' => 40, 'DISPLAY_HEIGHT' => 1,
  106. 'IS_NULL' => true,
  107. 'DEFAULT' => '',
  108. 'LABEL' => _t('Set code'), 'DESCRIPTION' => _t('A unique alphanumeric code for this set. You will need to specify this if you are using this set in a special context (on a web front-end, for example) in which the set must be unambiguously identified.'),
  109. 'BOUNDS_LENGTH' => array(0, 100),
  110. 'UNIQUE_WITHIN' => array()
  111. ),
  112. 'access' => array(
  113. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_SELECT,
  114. 'DISPLAY_WIDTH' => 40, 'DISPLAY_HEIGHT' => 1,
  115. 'IS_NULL' => false,
  116. 'DEFAULT' => 0,
  117. 'BOUNDS_CHOICE_LIST' => array(
  118. _t('Not accessible to public') => 0,
  119. _t('Accessible to public') => 1
  120. ),
  121. 'LIST' => 'access_statuses',
  122. 'LABEL' => _t('Access'), 'DESCRIPTION' => _t('Indicates if object is accessible to the public or not. ')
  123. ),
  124. 'status' => array(
  125. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_SELECT,
  126. 'DISPLAY_WIDTH' => 40, 'DISPLAY_HEIGHT' => 1,
  127. 'IS_NULL' => false,
  128. 'DEFAULT' => 0,
  129. 'BOUNDS_CHOICE_LIST' => array(
  130. _t('Newly created') => 0,
  131. _t('Editing in progress') => 1,
  132. _t('Editing complete - pending review') => 2,
  133. _t('Review in progress') => 3,
  134. _t('Completed') => 4
  135. ),
  136. 'LIST' => 'workflow_statuses',
  137. 'LABEL' => _t('Status'), 'DESCRIPTION' => _t('Indicates the current state of the object record.')
  138. ),
  139. 'hier_left' => array(
  140. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_OMIT,
  141. 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
  142. 'IS_NULL' => false,
  143. 'DEFAULT' => '',
  144. 'LABEL' => 'Hierarchical index - left bound', 'DESCRIPTION' => 'Left-side boundary for nested set-style hierarchical indexing; used to accelerate search and retrieval of hierarchical record sets.'
  145. ),
  146. 'hier_right' => array(
  147. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_OMIT,
  148. 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
  149. 'IS_NULL' => false,
  150. 'DEFAULT' => '',
  151. 'LABEL' => 'Hierarchical index - right bound', 'DESCRIPTION' => 'Right-side boundary for nested set-style hierarchical indexing; used to accelerate search and retrieval of hierarchical record sets.'
  152. ),
  153. 'rank' => array(
  154. 'FIELD_TYPE' => FT_NUMBER, 'DISPLAY_TYPE' => DT_FIELD,
  155. 'DISPLAY_WIDTH' => 10, 'DISPLAY_HEIGHT' => 1,
  156. 'IS_NULL' => false,
  157. 'DEFAULT' => '',
  158. 'LABEL' => _t('Sort order'), 'DESCRIPTION' => _t('Sort order'),
  159. )
  160. )
  161. );
  162. class ca_sets extends BundlableLabelableBaseModelWithAttributes implements IBundleProvider {
  163. # ---------------------------------
  164. # --- Object attribute properties
  165. # ---------------------------------
  166. # Describe structure of content object's properties - eg. database fields and their
  167. # associated types, what modes are supported, et al.
  168. #
  169. # ------------------------------------------------------
  170. # --- Basic object parameters
  171. # ------------------------------------------------------
  172. # what table does this class represent?
  173. protected $TABLE = 'ca_sets';
  174. # what is the primary key of the table?
  175. protected $PRIMARY_KEY = 'set_id';
  176. # ------------------------------------------------------
  177. # --- Properties used by standard editing scripts
  178. #
  179. # These class properties allow generic scripts to properly display
  180. # records from the table represented by this class
  181. #
  182. # ------------------------------------------------------
  183. # Array of fields to display in a listing of records from this table
  184. protected $LIST_FIELDS = array('user_id');
  185. # When the list of "list fields" above contains more than one field,
  186. # the LIST_DELIMITER text is displayed between fields as a delimiter.
  187. # This is typically a comma or space, but can be any string you like
  188. protected $LIST_DELIMITER = ' ';
  189. # What you'd call a single record from this table (eg. a "person")
  190. protected $NAME_SINGULAR;
  191. # What you'd call more than one record from this table (eg. "people")
  192. protected $NAME_PLURAL;
  193. # List of fields to sort listing of records by; you can use
  194. # SQL 'ASC' and 'DESC' here if you like.
  195. protected $ORDER_BY = array('user_id');
  196. # Maximum number of record to display per page in a listing
  197. protected $MAX_RECORDS_PER_PAGE = 20;
  198. # How do you want to page through records in a listing: by number pages ordered
  199. # according to your setting above? Or alphabetically by the letters of the first
  200. # LIST_FIELD?
  201. protected $PAGE_SCHEME = 'alpha'; # alpha [alphabetical] or num [numbered pages; default]
  202. # If you want to order records arbitrarily, add a numeric field to the table and place
  203. # its name here. The generic list scripts can then use it to order table records.
  204. protected $RANK = 'rank';
  205. # ------------------------------------------------------
  206. # Hierarchical table properties
  207. # ------------------------------------------------------
  208. protected $HIERARCHY_TYPE = __CA_HIER_TYPE_ADHOC_MONO__;
  209. protected $HIERARCHY_LEFT_INDEX_FLD = 'hier_left';
  210. protected $HIERARCHY_RIGHT_INDEX_FLD = 'hier_right';
  211. protected $HIERARCHY_PARENT_ID_FLD = 'parent_id';
  212. protected $HIERARCHY_DEFINITION_TABLE = 'ca_sets';
  213. protected $HIERARCHY_ID_FLD = 'hier_set_id';
  214. protected $HIERARCHY_POLY_TABLE = null;
  215. # ------------------------------------------------------
  216. # Change logging
  217. # ------------------------------------------------------
  218. protected $UNIT_ID_FIELD = null;
  219. protected $LOG_CHANGES_TO_SELF = true;
  220. protected $LOG_CHANGES_USING_AS_SUBJECT = array(
  221. "FOREIGN_KEYS" => array(
  222. ),
  223. "RELATED_TABLES" => array(
  224. )
  225. );
  226. # ------------------------------------------------------
  227. # Group-based access control
  228. # ------------------------------------------------------
  229. protected $USERS_RELATIONSHIP_TABLE = 'ca_sets_x_users';
  230. protected $USER_GROUPS_RELATIONSHIP_TABLE = 'ca_sets_x_user_groups';
  231. # ------------------------------------------------------
  232. # Labels
  233. # ------------------------------------------------------
  234. protected $LABEL_TABLE_NAME = 'ca_set_labels';
  235. # ------------------------------------------------------
  236. # Attributes
  237. # ------------------------------------------------------
  238. protected $ATTRIBUTE_TYPE_ID_FLD = 'type_id'; // name of type field for this table - attributes system uses this to determine via ca_metadata_type_restrictions which attributes are applicable to rows of the given type
  239. protected $ATTRIBUTE_TYPE_LIST_CODE = 'set_types'; // list code (ca_lists.list_code) of list defining types for this table
  240. # ------------------------------------------------------
  241. # ID numbering
  242. # ------------------------------------------------------
  243. protected $ID_NUMBERING_ID_FIELD = 'set_code'; // name of field containing user-defined identifier
  244. protected $ID_NUMBERING_SORT_FIELD = null; // name of field containing version of identifier for sorting (is normalized with padding to sort numbers properly)
  245. protected $ID_NUMBERING_CONTEXT_FIELD = null; // name of field to use value of for "context" when checking for duplicate identifier values; if not set identifer is assumed to be global in scope; if set identifer is checked for uniqueness (if required) within the value of this field
  246. # ------------------------------------------------------
  247. # $FIELDS contains information about each field in the table. The order in which the fields
  248. # are listed here is the order in which they will be returned using getFields()
  249. protected $FIELDS;
  250. # cache for haveAccessToSet()
  251. static $s_have_access_to_set_cache = array();
  252. # ------------------------------------------------------
  253. # --- Constructor
  254. #
  255. # This is a function called when a new instance of this object is created. This
  256. # standard constructor supports three calling modes:
  257. #
  258. # 1. If called without parameters, simply creates a new, empty objects object
  259. # 2. If called with a single, valid primary key value, creates a new objects object and loads
  260. # the record identified by the primary key value
  261. #
  262. # ------------------------------------------------------
  263. public function __construct($pn_id=null) {
  264. // Filter list of tables set can be used for to those enabled in current config
  265. BaseModel::$s_ca_models_definitions['ca_sets']['FIELDS']['table_num']['BOUNDS_CHOICE_LIST'] = caFilterTableList(BaseModel::$s_ca_models_definitions['ca_sets']['FIELDS']['table_num']['BOUNDS_CHOICE_LIST']);
  266. parent::__construct($pn_id); # call superclass constructor
  267. }
  268. # ------------------------------------------------------
  269. /**
  270. *
  271. */
  272. protected function initLabelDefinitions() {
  273. parent::initLabelDefinitions();
  274. $this->BUNDLES['ca_users'] = array('type' => 'special', 'repeating' => true, 'label' => _t('User access'));
  275. $this->BUNDLES['ca_user_groups'] = array('type' => 'special', 'repeating' => true, 'label' => _t('Group access'));
  276. $this->BUNDLES['ca_set_items'] = array('type' => 'special', 'repeating' => true, 'label' => _t('Set items'));
  277. }
  278. # ------------------------------------------------------
  279. /**
  280. * Overrides default implementation with code to ensure consistency of set contents
  281. */
  282. public function update($pa_options=null) {
  283. if ($vn_rc = parent::update($pa_options)) {
  284. // make sure all items have the same type as the set
  285. $this->getDb()->query("
  286. UPDATE ca_set_items
  287. SET type_id = ?
  288. WHERE
  289. set_id = ?
  290. ", (int)$this->get('type_id'), (int)$this->getPrimaryKey());
  291. }
  292. return $vn_rc;
  293. }
  294. # ------------------------------------------------------
  295. /**
  296. * Override set() to reject changes to user_id for existing rows
  297. */
  298. public function set($pa_fields, $pm_value="", $pa_options=null) {
  299. if ($this->getPrimaryKey()) {
  300. if (is_array($pa_fields)) {
  301. if (isset($pa_fields['user_id'])) { unset($pa_fields['user_id']); }
  302. if (isset($pa_fields['table_num'])) { unset($pa_fields['table_num']); }
  303. } else {
  304. if ($pa_fields === 'user_id') { return false; }
  305. if ($pa_fields === 'table_num') { return false; }
  306. }
  307. }
  308. return parent::set($pa_fields, $pm_value, $pa_options);
  309. }
  310. # ------------------------------------------------------
  311. /**
  312. * @param array $pa_options
  313. * duplicate_subitems
  314. */
  315. public function duplicate($pa_options=null) {
  316. $vb_we_set_transaction = false;
  317. if (!$this->inTransaction()) {
  318. $this->setTransaction($o_t = new Transaction($this->getDb()));
  319. $vb_we_set_transaction = true;
  320. } else {
  321. $o_t = $this->getTransaction();
  322. }
  323. if ($t_dupe = parent::duplicate($pa_options)) {
  324. $vb_duplicate_subitems = isset($pa_options['duplicate_subitems']) && $pa_options['duplicate_subitems'];
  325. if ($vb_duplicate_subitems) {
  326. // Try to dupe related ca_set_items rows
  327. $o_db = $this->getDb();
  328. $qr_res = $o_db->query("
  329. SELECT *
  330. FROM ca_set_items
  331. WHERE set_id = ?
  332. ", (int)$this->getPrimaryKey());
  333. $va_items = array();
  334. while($qr_res->nextRow()) {
  335. $va_items[$qr_res->get('item_id')] = $qr_res->getRow();
  336. }
  337. foreach($va_items as $vn_item_id => $va_item) {
  338. $t_item = new ca_set_items();
  339. $t_item->setMode(ACCESS_WRITE);
  340. $va_item['set_id'] = $t_dupe->getPrimaryKey();
  341. $t_item->set($va_item);
  342. $t_item->insert();
  343. if ($t_item->numErrors()) {
  344. $this->errors = $t_item->errors;
  345. if ($vb_we_set_transaction) { $this->removeTransaction(false);}
  346. return false;
  347. }
  348. }
  349. }
  350. }
  351. if ($vb_we_set_transaction) { $this->removeTransaction(true);}
  352. return $t_dupe;
  353. }
  354. # ------------------------------------------------------
  355. # Set lists
  356. # ------------------------------------------------------
  357. /**
  358. * Returns list of sets subject to options
  359. *
  360. * @param array $pa_options Array of options. Supported options are:
  361. * table - if set, list is restricted to sets that can contain the specified item. You can pass a table name or number. If omitted sets containing any content will be returned.
  362. * setType - Restricts returned sets to those of the specified type. You can pass a type_id or list item code for the set type. If omitted sets are returned regardless of type.
  363. * user_id - Restricts returned sets to those accessible by the current user. If omitted then all sets, regardless of access are returned.
  364. * access - Restricts returned sets to those with at least the specified access level for the specified user. If user_id is omitted then this option has no effect. If user_id is set and this option is omitted, then sets where the user has at least read access will be returned.
  365. * checkAccess - Restricts returned sets to those with an public access level with the specified values. If omitted sets are returned regardless of public access (ca_sets.access) value. Can be a single value or array if you wish to filter on multiple public access values.
  366. * row_id = if set to an integer only sets containing the specified row are returned
  367. * setIDsOnly = if set to true only set_id values are returned, in a simple array
  368. * @return array A list of sets keyed by set_id and then locale_id. Keys for the per-locale value array include: set_id, set_code, status, public access, owner user_id, content table_num, set type_id, set name, number of items in the set (item_count), set type name for display and set content type name for display. If setIDsOnly option is set then a simple array of set_id values is returned instead.
  369. */
  370. public function getSets($pa_options=null) {
  371. if (!is_array($pa_options)) { $pa_options = array(); }
  372. $pm_table_name_or_num = isset($pa_options['table']) ? $pa_options['table'] : null;
  373. $pm_type = isset($pa_options['setType']) ? $pa_options['setType'] : null;
  374. $pn_user_id = isset($pa_options['user_id']) ? (int)$pa_options['user_id'] : null;
  375. $pn_access = isset($pa_options['access']) ? $pa_options['access'] : null;
  376. $pb_set_ids_only = isset($pa_options['setIDsOnly']) ? (bool)$pa_options['setIDsOnly'] : false;
  377. $pn_row_id = (isset($pa_options['row_id']) && ((int)$pa_options['row_id'])) ? (int)$pa_options['row_id'] : null;
  378. $pa_public_access = isset($pa_options['checkAccess']) ? $pa_options['checkAccess'] : null;
  379. if ($pa_public_access && is_numeric($pa_public_access) && !is_array($pa_public_access)) {
  380. $pa_public_access = array($pa_public_access);
  381. }
  382. for($vn_i=0; $vn_i < sizeof($pa_public_access); $vn_i++) { $pa_public_access[$vn_i] = intval($pa_public_access[$vn_i]); }
  383. if ($pm_table_name_or_num && !($vn_table_num = $this->_getTableNum($pm_table_name_or_num))) { return null; }
  384. $va_extra_joins = array();
  385. $o_db = $this->getDb();
  386. $va_sql_wheres = array();
  387. if ($vn_table_num) {
  388. $va_sql_wheres[] = "(cs.table_num = ".intval($vn_table_num).")";
  389. }
  390. if ($pb_set_ids_only) {
  391. $va_sql_selects = array('cs.set_id');
  392. } else {
  393. $va_sql_selects = array(
  394. 'cs.set_id', 'cs.set_code', 'cs.status', 'cs.access', 'cs.user_id', 'cs.table_num', 'cs.type_id',
  395. 'csl.label_id', 'csl.name', 'csl.locale_id', 'l.language', 'l.country', 'u.fname', 'u.lname', 'u.email'
  396. );
  397. }
  398. if ($pn_user_id) {
  399. $o_dm = $this->getAppDatamodel();
  400. $t_user = $o_dm->getInstanceByTableName('ca_users', true);
  401. $t_user->load($pn_user_id);
  402. if ($t_user->getPrimaryKey()) {
  403. $vs_access_sql = ($pn_access > 0) ? " AND (access >= ".intval($pn_access).")" : "";
  404. if (is_array($va_groups = $t_user->getUserGroups()) && sizeof($va_groups)) {
  405. $vs_sql = "(
  406. (cs.user_id = ".intval($pn_user_id).") OR
  407. (cs.set_id IN (
  408. SELECT set_id
  409. FROM ca_sets_x_user_groups
  410. WHERE
  411. group_id IN (".join(',', array_keys($va_groups)).") {$vs_access_sql}
  412. AND
  413. (
  414. (sdatetime IS NULL AND edatetime IS NULL)
  415. OR
  416. (
  417. sdatetime <= ".time()." AND edatetime >= ".time()."
  418. )
  419. )
  420. )
  421. )
  422. )";
  423. } else {
  424. $vs_sql = "(cs.user_id = {$pn_user_id})";
  425. }
  426. $vs_sql .= " OR (cs.set_id IN (
  427. SELECT set_id
  428. FROM ca_sets_x_users
  429. WHERE
  430. user_id = {$pn_user_id} {$vs_access_sql}
  431. AND
  432. (
  433. (sdatetime IS NULL AND edatetime IS NULL)
  434. OR
  435. (
  436. sdatetime <= ".time()." AND edatetime >= ".time()."
  437. )
  438. )
  439. )
  440. )";
  441. $va_sql_wheres[] = "({$vs_sql})";
  442. }
  443. }
  444. if (!is_null($pa_public_access) && is_array($pa_public_access) && sizeof($pa_public_access)) {
  445. $va_sql_wheres[] = "(cs.access IN (".join(', ', $pa_public_access)."))";
  446. }
  447. if (isset($pm_type) && $pm_type) {
  448. if(is_numeric($pm_type)){
  449. $va_sql_wheres[] = "(cs.type_id = ".intval($pm_type).")";
  450. }else{
  451. # --- look up code of set type
  452. $t_list = new ca_lists();
  453. $vn_type_id = $t_list->getItemIDFromList("set_types", $pm_type);
  454. if($vn_type_id){
  455. $va_sql_wheres[] = "(cs.type_id = {$vn_type_id})";
  456. }
  457. }
  458. }
  459. if ($pn_row_id > 0) {
  460. $va_sql_wheres[] = "((csi.row_id = {$pn_row_id}) AND (csi.table_num = {$vn_table_num}))";
  461. $va_extra_joins[] = "INNER JOIN ca_set_items AS csi ON cs.set_id = csi.set_id";
  462. $va_sql_selects[] = 'csi.item_id';
  463. }
  464. if (!$pb_set_ids_only) {
  465. // get set item counts
  466. $qr_res = $o_db->query("
  467. SELECT cs.set_id, count(*) item_count
  468. FROM ca_sets cs
  469. INNER JOIN ca_set_items AS csi ON cs.set_id = csi.set_id
  470. ".(sizeof($va_sql_wheres) ? 'WHERE ' : '')."
  471. ".join(' AND ', $va_sql_wheres)."
  472. GROUP BY cs.set_id
  473. ");
  474. $va_item_counts = array();
  475. while($qr_res->nextRow()) {
  476. $va_item_counts[(int)$qr_res->get('set_id')] = (int)$qr_res->get('item_count');
  477. }
  478. // get sets
  479. $qr_res = $o_db->query("
  480. SELECT ".join(', ', $va_sql_selects)."
  481. FROM ca_sets cs
  482. LEFT JOIN ca_set_labels AS csl ON cs.set_id = csl.set_id
  483. LEFT JOIN ca_locales AS l ON csl.locale_id = l.locale_id
  484. INNER JOIN ca_users AS u ON cs.user_id = u.user_id
  485. ".join("\n", $va_extra_joins)."
  486. ".(sizeof($va_sql_wheres) ? 'WHERE ' : '')."
  487. ".join(' AND ', $va_sql_wheres)."
  488. ORDER BY csl.name
  489. ");
  490. $va_sets = array();
  491. $o_dm = $this->getAppDatamodel();
  492. $va_type_name_cache = array();
  493. $t_list = new ca_lists();
  494. while($qr_res->nextRow()) {
  495. $vn_table_num = $qr_res->get('table_num');
  496. if (!isset($va_type_name_cache[$vn_table_num]) || !($vs_set_type = $va_type_name_cache[$vn_table_num])) {
  497. $vs_set_type = $va_type_name_cache[$vn_table_num] = $this->getSetContentTypeName($vn_table_num, array('number' => 'plural'));
  498. }
  499. $vs_type = $t_list->getItemFromListForDisplayByItemID('set_types', $qr_res->get('type_id'));
  500. $va_sets[$qr_res->get('set_id')][$qr_res->get('locale_id')] = array_merge($qr_res->getRow(), array('item_count' => intval($va_item_counts[$qr_res->get('set_id')]), 'set_content_type' => $vs_set_type, 'set_type' => $vs_type));
  501. }
  502. return $va_sets;
  503. } else {
  504. // get sets
  505. $qr_res = $o_db->query("
  506. SELECT ".join(', ', $va_sql_selects)."
  507. FROM ca_sets cs
  508. INNER JOIN ca_users AS u ON cs.user_id = u.user_id
  509. ".join("\n", $va_extra_joins)."
  510. ".(sizeof($va_sql_wheres) ? 'WHERE ' : '')."
  511. ".join(' AND ', $va_sql_wheres)."
  512. ");
  513. return $qr_res->getAllFieldValues("set_id");
  514. }
  515. }
  516. # ------------------------------------------------------
  517. /**
  518. * Returns list of sets to which the item (as specified by $pm_table_name_or_num and $pn_row_id) can be associated and is not already part of.
  519. *
  520. * @param mixed $pm_table_name_or_num Name or number of table
  521. * @param int $pn_row_id ID of row in table specified by $pm_table_name_or_num to check for
  522. * @param array $pa_options Optional list of options. Supported options are the same as those for ca_sets::getSets() and ca_sets::getSetsForItem()
  523. * @return array A list of sets keyed by set_id and then locale_id. Keys for the per-locale value array include: set_id, set_code, status, public access, owner user_id, content table_num, set type_id, set name, number of items in the set (item_count), set type name for display and set content type name for display. This is the same format as returned by ca_sets::getSets().
  524. */
  525. public function getAvailableSetsForItem($pm_table_name_or_num, $pn_row_id, $pa_options=null) {
  526. if (!is_array($pa_options)) { $pa_options = array(); }
  527. if (!($va_full_set_list = $this->getSets(array_merge(array('table' => $pm_table_name_or_num), $pa_options)))) { return null; }
  528. if (!($va_current_set_list = $this->getSetsForItem($pm_table_name_or_num, $pn_row_id, $pa_options))) { return null; }
  529. $va_available_sets = array();
  530. foreach($va_full_set_list as $vn_set_id => $va_set_info_by_locale) {
  531. if (isset($va_current_set_list[$vn_set_id]) && $va_current_set_list[$vn_set_id]) { continue;}
  532. $va_available_sets[$vn_set_id] = $va_set_info_by_locale;
  533. }
  534. return $va_available_sets;
  535. }
  536. # ------------------------------------------------------
  537. /**
  538. * Returns list of sets in which the specified item is a member
  539. *
  540. * @param mixed $pm_table_name_or_num Name or number of table
  541. * @param int $pn_row_id ID of row in table specified by $pm_table_name_or_num to check for
  542. * @param array $pa_options Optional list of options. Supported options are the same as those for ca_sets::getSets() and ca_sets::getSetsForItem()
  543. * @return array A list of sets keyed by set_id and then locale_id. Keys for the per-locale value array include: set_id, set_code, status, public access, owner user_id, content table_num, set type_id, set name, number of items in the set (item_count), set type name for display and set content type name for display. This is the same format as returned by ca_sets::getSets().
  544. */
  545. public function getSetsForItem($pm_table_name_or_num, $pn_row_id, $pa_options=null) {
  546. if (!is_array($pa_options)) { $pa_options = array(); }
  547. if (!$pn_row_id) { return array(); }
  548. return $this->getSets(array_merge($pa_options, array('table' => $pm_table_name_or_num, 'row_id' => $pn_row_id)));
  549. }
  550. # ------------------------------------------------------
  551. /**
  552. * Returns list of set_ids of sets in which the specified item is a member
  553. *
  554. * @param mixed $pm_table_name_or_num Name or number of table
  555. * @param int $pn_row_id ID of row in table specified by $pm_table_name_or_num to check for
  556. * @param array $pa_options Optional list of options. Supported options are the same as those for ca_sets::getSets() and ca_sets::getSetsForItem()
  557. * @return array A list of set_ids, or null if parameters are invalid
  558. */
  559. public function getSetIDsForItem($pm_table_name_or_num, $pn_row_id, $pa_options=null) {
  560. if (is_array($va_sets = $this->getSetsForItem($pm_table_name_or_num, $pn_row_id, $pa_options))) {
  561. return array_keys($va_sets);
  562. }
  563. return null;
  564. }
  565. # ------------------------------------------------------
  566. /**
  567. * Checks if a row of a table is in a set.
  568. *
  569. * @param mixed $pm_table_name_or_num Name or number of table
  570. * @param int $pn_row_id ID of row in table specified by $pm_table_name_or_num to check for
  571. * @param mixed $pm_set_code_or_id Set code or set_id of set to check for item
  572. * @return bool True if row is in set, false if now. If the table or set are invalid null will be returned.
  573. */
  574. public function isInSet($pm_table_name_or_num, $pn_row_id, $pm_set_code_or_id) {
  575. if (!($vn_table_num = $this->_getTableNum($pm_table_name_or_num))) { return null; }
  576. if (!($vn_set_id = $this->_getSetID($pm_set_code_or_id))) { return null; }
  577. $o_db = $this->getDb();
  578. $qr_res = $o_db->query("
  579. SELECT cs.set_id
  580. FROM ca_sets cs
  581. INNER JOIN ca_set_items AS csi ON cs.set_id = csi.set_id
  582. WHERE
  583. (cs.set_id = ?) AND (csi.row_id = ?) AND (cs.table_num = ?)
  584. ", (int)$vn_set_id, (int)$pn_row_id, (int)$vn_table_num);
  585. if ($qr_res->numRows() > 0) {
  586. return true;
  587. }
  588. return false;
  589. }
  590. # ------------------------------------------------------
  591. /**
  592. * Returns a random set_id from a group defined by specified options. These options are the same as those for ca_sets::getSets()
  593. *
  594. * @param array $pa_options Array of options. Supported options are:
  595. * table - if set, list is restricted to sets that can contain the specified item. You can pass a table name or number. If omitted sets containing any content will be returned.
  596. * setType - Restricts returned sets to those of the specified type. You can pass a type_id or list item code for the set type. If omitted sets are returned regardless of type.
  597. * user_id - Restricts returned sets to those accessible by the current user. If omitted then all sets, regardless of access are returned.
  598. * access - Restricts returned sets to those with at least the specified access level for the specified user. If user_id is omitted then this option has no effect. If user_id is set and this option is omitted, then sets where the user has at least read access will be returned.
  599. * checkAccess - Restricts returned sets to those with an public access level with the specified values. If omitted sets are returned regardless of public access (ca_sets.access) value. Can be a single value or array if you wish to filter on multiple public access values.
  600. * row_id = if set to an integer only sets containing the specified row are returned
  601. * @return int A randomly selected set_id value
  602. */
  603. public function getRandomSetID($pa_options=null) {
  604. $va_set_ids = $this->getSets(array_merge($pa_options, array('setIDsOnly' => true)));
  605. return $va_set_ids[rand(0, sizeof($va_set_ids) - 1)];
  606. }
  607. # ------------------------------------------------------
  608. /**
  609. * Determines if user has access to a set at a specified access level.
  610. *
  611. * @param int $pn_user_id user_id of user to check set access for
  612. * @param int $pn_access type of access required. Use __CA_SET_READ_ACCESS__ for read-only access or __CA_SET_EDIT_ACCESS__ for editing (full) access
  613. * @param int $pn_set_id The id of the set to check. If omitted then currently loaded set will be checked.
  614. * @return bool True if user has access, false if not
  615. */
  616. public function haveAccessToSet($pn_user_id, $pn_access, $pn_set_id=null) {
  617. if ($pn_set_id) {
  618. $vn_set_id = $pn_set_id;
  619. $t_set = new ca_sets($vn_set_id);
  620. $vn_set_user_id = $t_set->get('user_id');
  621. } else {
  622. $vn_set_user_id = $this->get('user_id');
  623. }
  624. if(!$vn_set_id && !($vn_set_id = $this->getPrimaryKey())) {
  625. return true; // new set
  626. }
  627. if (isset(ca_sets::$s_have_access_to_set_cache[$vn_set_id.'/'.$pn_user_id.'/'.$pn_access])) {
  628. return ca_sets::$s_have_access_to_set_cache[$vn_set_id.'/'.$pn_user_id.'/'.$pn_access];
  629. }
  630. if (($vn_set_user_id == $pn_user_id)) { // owners have all access
  631. return ca_sets::$s_have_access_to_set_cache[$vn_set_id.'/'.$pn_user_id.'/'.$pn_access] = true;
  632. }
  633. if (($this->get('access') > 0) && ($pn_access == __CA_SET_READ_ACCESS__)) { // public sets are readable by all
  634. return ca_sets::$s_have_access_to_set_cache[$vn_set_id.'/'.$pn_user_id.'/'.$pn_access] = true;
  635. }
  636. $o_db = $this->getDb();
  637. $qr_res = $o_db->query($vs_sql="
  638. SELECT sxg.set_id
  639. FROM ca_sets_x_user_groups sxg
  640. INNER JOIN ca_user_groups AS ug ON sxg.group_id = ug.group_id
  641. INNER JOIN ca_users_x_groups AS uxg ON uxg.group_id = ug.group_id
  642. WHERE
  643. (sxg.access >= ?) AND (uxg.user_id = ?) AND (sxg.set_id = ?)
  644. AND
  645. (
  646. (sxg.sdatetime <= ".time()." AND sxg.edatetime >= ".time().")
  647. OR
  648. (sxg.sdatetime IS NULL and sxg.edatetime IS NULL)
  649. )
  650. ", (int)$pn_access, (int)$pn_user_id, (int)$vn_set_id);
  651. if ($qr_res->numRows() > 0) { return ca_sets::$s_have_access_to_set_cache[$vn_set_id.'/'.$pn_user_id.'/'.$pn_access] = true; }
  652. $qr_res = $o_db->query("
  653. SELECT sxu.set_id
  654. FROM ca_sets_x_users sxu
  655. INNER JOIN ca_users AS u ON sxu.user_id = u.user_id
  656. WHERE
  657. (sxu.access >= ?) AND (u.user_id = ?) AND (sxu.set_id = ?)
  658. AND
  659. (
  660. (sxu.sdatetime <= ".time()." AND sxu.edatetime >= ".time().")
  661. OR
  662. sxu.sdatetime IS NULL and sxu.edatetime IS NULL
  663. )
  664. ", (int)$pn_access, (int)$pn_user_id, (int)$vn_set_id);
  665. if ($qr_res->numRows() > 0) { return ca_sets::$s_have_access_to_set_cache[$vn_set_id.'/'.$pn_user_id.'/'.$pn_access] = true; }
  666. return ca_sets::$s_have_access_to_set_cache[$vn_set_id.'/'.$pn_user_id.'/'.$pn_access] = false;
  667. }
  668. # ------------------------------------------------------
  669. /**
  670. *
  671. *
  672. * @param int $pn_user_id user_id of user to check set access for
  673. * @param int $pn_access type of access required. Use __CA_SET_READ_ACCESS__ for read-only access or __CA_SET_EDIT_ACCESS__ for editing (full) access
  674. * @param int $pa_set_ids The ids of the sets to check. If omitted then currently loaded set will be checked. Can also be set to a single integer.
  675. * @return int
  676. */
  677. public function getAccessExpirationDates($pn_user_id, $pn_access, $pa_set_ids=null, $pa_options=null) {
  678. if (!is_array($pa_set_ids)) {
  679. if (!$pa_set_ids) { $pa_set_ids = $this->get('set_id'); }
  680. if(!$pa_set_ids) { return null; }
  681. $pa_set_ids = array($pa_set_ids);
  682. }
  683. foreach($pa_set_ids as $vn_i => $vn_set_id) {
  684. $pa_set_ids[$vn_i] = (int)$vn_set_id;
  685. }
  686. $o_db = $this->getDb();
  687. $qr_res = $o_db->query("
  688. SELECT sxg.set_id, sxg.sdatetime, sxg.edatetime, s.user_id
  689. FROM ca_sets_x_user_groups sxg
  690. INNER JOIN ca_user_groups AS ug ON sxg.group_id = ug.group_id
  691. INNER JOIN ca_users_x_groups AS uxg ON uxg.group_id = ug.group_id
  692. INNER JOIN ca_sets AS s ON s.set_id = sxg.set_id
  693. WHERE
  694. (sxg.access >= ?) AND (uxg.user_id = ?) AND (sxg.set_id IN (?))
  695. AND
  696. (
  697. sxg.sdatetime <= ".time()." AND sxg.edatetime >= ".time()."
  698. )
  699. ", (int)$pn_access, (int)$pn_user_id, $pa_set_ids);
  700. $o_tep = new TimeExpressionParser();
  701. $va_expiration_times = array();
  702. while($qr_res->nextRow()) {
  703. if ($qr_res->get('user_id') == $pn_user_id) {
  704. $va_expiration_times[$vn_set_id] = -1;
  705. continue;
  706. }
  707. $vn_set_id = $qr_res->get('set_id');
  708. $vn_exp = $qr_res->get('edatetime');
  709. if (!isset($va_expiration_times[$vn_set_id]) || ($va_expiration_times[$vn_set_id] < $vn_exp)) {
  710. $o_tep->setUnixTimestamps($vn_exp, $vn_exp);
  711. $vs_text = $o_tep->getText();
  712. $va_expiration_times[$vn_set_id] = $vs_text;
  713. }
  714. }
  715. $qr_res = $o_db->query("
  716. SELECT sxu.set_id, sxu.sdatetime, sxu.edatetime, s.user_id
  717. FROM ca_sets_x_users sxu
  718. INNER JOIN ca_users AS u ON sxu.user_id = u.user_id
  719. INNER JOIN ca_sets AS s ON s.set_id = sxu.set_id
  720. WHERE
  721. (sxu.access >= ?) AND (u.user_id = ?) AND (sxu.set_id IN (?))
  722. AND
  723. (
  724. sxu.sdatetime <= ".time()." AND sxu.edatetime >= ".time()."
  725. )
  726. ", (int)$pn_access, (int)$pn_user_id, $pa_set_ids);
  727. while($qr_res->nextRow()) {
  728. if ($qr_res->get('user_id') == $pn_user_id) {
  729. $va_expiration_times[$vn_set_id] = -1;
  730. continue;
  731. }
  732. $vn_set_id = $qr_res->get('set_id');
  733. $vn_exp = $qr_res->get('edatetime');
  734. if (!isset($va_expiration_times[$vn_set_id]) || ($va_expiration_times[$vn_set_id] < $vn_exp)) {
  735. $o_tep->setUnixTimestamps($vn_exp, $vn_exp);
  736. $vs_text = $o_tep->getText();
  737. $va_expiration_times[$vn_set_id] = $vs_text;
  738. }
  739. }
  740. return $va_expiration_times;
  741. }
  742. # ------------------------------------------------------
  743. # Set maintenance
  744. # ------------------------------------------------------
  745. /**
  746. * Add item to currently loaded set
  747. *
  748. * @param int $pn_row_id The row_id to add to the set. Assumed to be a key to a record in the sets's content type's table.
  749. * @param array $pa_labels An array of ca_set_item label values to create. The array is keyed on locale_id; each value is an array with keys set to ca_set_item_labels fields with associated values.
  750. * @param int $pn_user_id user_id of user adding the item. Used to check if the user has editing access to the set. If omitted no checking of access is done.
  751. * @param int $pn_rank position in the set of the newly added item
  752. * @return int Returns item_id of newly created set item entry. The item_id is a unique identifier for the row_id in the city at the specified position (rank). It is *not* the same as the row_id.
  753. */
  754. public function addItem($pn_row_id, $pa_labels=null, $pn_user_id=null, $pn_rank=null) {
  755. if(!($vn_set_id = $this->getPrimaryKey())) { return null; }
  756. if ($pn_user_id && (!$this->haveAccessToSet($pn_user_id, __CA_SET_EDIT_ACCESS__))) { return false; }
  757. $vn_table_num = $this->get('table_num');
  758. // Verify existance of row before adding to set
  759. $t_instance = $this->getAppDatamodel()->getInstanceByTableNum($vn_table_num, true);
  760. if (!$t_instance->load($pn_row_id)) {
  761. $this->postError(750, _t('Item does not exist'), 'ca_sets->addItem()');
  762. return false;
  763. }
  764. // Add it to the set
  765. $t_item = new ca_set_items();
  766. $t_item->setMode(ACCESS_WRITE);
  767. $t_item->set('set_id', $this->getPrimaryKey());
  768. $t_item->set('table_num', $vn_table_num);
  769. $t_item->set('row_id', $pn_row_id);
  770. $t_item->set('type_id', $this->get('type_id'));
  771. $t_item->insert();
  772. if (!is_null($pn_rank)) {
  773. $t_item->set('rank', $pn_rank);
  774. $t_item->update();
  775. }
  776. if ($t_item->numErrors()) {
  777. $this->errors = $t_item->errors;
  778. return false;
  779. }
  780. if (is_array($pa_labels) && sizeof($pa_labels)) {
  781. foreach($pa_labels as $vn_locale_id => $va_label) {
  782. if (!isset($va_label['caption']) || !trim($va_label['caption'])) { continue; }
  783. $t_item->addLabel(
  784. $va_label, $vn_locale_id
  785. );
  786. if ($t_item->numErrors()) {
  787. $this->errors = $t_item->errors;
  788. return false;
  789. }
  790. }
  791. }
  792. return (int)$t_item->getPrimaryKey();
  793. }
  794. # ------------------------------------------------------
  795. /**
  796. * Removes all instances of the specified item from the set as specified by the row_id
  797. *
  798. * @param int $pn_row_id The row_id of the item to remove
  799. * @param int $pn_user_id Option user_id of user to check set access for; if no user_id is specified then no access checking is done
  800. * @return bool True on success, false if an error occurred
  801. */
  802. public function removeItem($pn_row_id, $pn_user_id=null) {
  803. if(!($vn_set_id = $this->getPrimaryKey())) { return null; }
  804. if ($pn_user_id && (!$this->haveAccessToSet($pn_user_id, __CA_SET_EDIT_ACCESS__))) { return false; }
  805. $t_item = new ca_set_items();
  806. $t_item->setMode(ACCESS_WRITE);
  807. while ($t_item->load(array('set_id' => $this->getPrimaryKey(), 'row_id' => $pn_row_id))) {
  808. $t_item->delete(true);
  809. if ($t_item->numErrors()) {
  810. $this->errors = $t_item->errors;
  811. return false;
  812. }
  813. }
  814. return true;
  815. }
  816. # ------------------------------------------------------
  817. /**
  818. * Removes the specified item from the set as specified by the item_id
  819. *
  820. * @param int $pn_item_id The item_id of the ca_set_items row in the set
  821. * @param int $pn_user_id Option user_id of user to check set access for; if no user_id is specified then no access checking is done
  822. * @return bool True on success, false if an error occurred
  823. */
  824. public function removeItemByItemID($pn_item_id, $pn_user_id=null) {
  825. if(!($vn_set_id = $this->getPrimaryKey())) { return null; }
  826. if (!$this->haveAccessToSet($pn_user_id, __CA_SET_EDIT_ACCESS__)) { return false; }
  827. $t_item = new ca_set_items();
  828. $t_item->setMode(ACCESS_WRITE);
  829. if ($t_item->load($pn_item_id)) {
  830. $t_item->delete(true);
  831. if ($t_item->numErrors()) {
  832. $this->errors = $t_item->errors;
  833. return false;
  834. }
  835. return true;
  836. }
  837. return true;
  838. }
  839. # ------------------------------------------------------
  840. /**
  841. * Returns a list of item_ids for the current set with ranks for each, in rank order
  842. *
  843. * @param array $pa_options An optional array of options. Supported options are:
  844. * user_id = the user_id of the current user; used to determine which sets the user has access to
  845. * @return array Array keyed on item_id with values set to ranks for each item
  846. */
  847. public function getItemRanks($pa_options=null) {
  848. if(!($vn_set_id = $this->getPrimaryKey())) { return null; }
  849. if (!$this->haveAccessToSet($pa_options['user_id'], __CA_SET_READ_ACCESS__)) { return false; }
  850. $va_items = caExtractValuesByUserLocale($this->getItems($pa_options));
  851. $va_ranks = array();
  852. foreach($va_items as $vn_item_id => $va_item) {
  853. $va_ranks[$vn_item_id] = $va_item['rank'];
  854. }
  855. return $va_ranks;
  856. }
  857. # ------------------------------------------------------
  858. /**
  859. * Returns a list of row_ids for the current set with ranks for each, in rank order
  860. *
  861. * @param array $pa_options An optional array of options. Supported options are:
  862. * user_id = the user_id of the current user; used to determine which sets the user has access to
  863. * @return array Array keyed on row_id with values set to ranks for each item. If the set contains duplicate row_ids then the list will only have the largest rank. If you have sets with duplicate rows use getItemRanks() instead
  864. */
  865. public function getRowIDRanks($pa_options=null) {
  866. if(!($vn_set_id = $this->getPrimaryKey())) { return null; }
  867. if (!$this->haveAccessToSet($pa_options['user_id'], __CA_SET_READ_ACCESS__)) { return false; }
  868. $va_items = caExtractValuesByUserLocale($this->getItems($pa_options));
  869. $va_ranks = array();
  870. foreach($va_items as $vn_item_id => $va_item) {
  871. $va_ranks[$va_item['row_id']] = $va_item['rank'];
  872. }
  873. return $va_ranks;
  874. }
  875. # ------------------------------------------------------
  876. /**
  877. * Sets order of items in the currently loaded set to the order of row_ids as set in $pa_row_ids
  878. *
  879. * @param array $pa_row_ids A list of row_ids in the set, in the order in which they should be displayed in the set
  880. * @param array $pa_options An optional array of options. Supported options include:
  881. * user_id = the user_id of the current user; used to determine which sets the user has access to
  882. * @return array An array of errors. If the array is empty then no errors occurred
  883. */
  884. public function reorderItems($pa_row_ids, $pa_options=null) {
  885. if (!($vn_set_id = $this->getPrimaryKey())) {
  886. return null;
  887. }
  888. $vn_user_id = isset($pa_options['user_id']) ? (int)$pa_options['user_id'] : null;
  889. // does user have edit access to set?
  890. if ($vn_user_id && !$this->haveAccessToSet($vn_user_id, __CA_SET_EDIT_ACCESS__)) {
  891. return false;
  892. }
  893. $va_row_ranks = $this->getRowIDRanks($pa_options); // get current ranks
  894. $vn_i = 0;
  895. $o_trans = new Transaction();
  896. $t_set_item = new ca_set_items();
  897. $t_set_item->setTransaction($o_trans);
  898. $t_set_item->setMode(ACCESS_WRITE);
  899. $va_errors = array();
  900. // delete rows not present in $pa_row_ids
  901. $va_to_delete = array();
  902. foreach($va_row_ranks as $vn_row_id => $va_rank) {
  903. if (!in_array($vn_row_id, $pa_row_ids)) {
  904. if ($t_set_item->load(array('set_id' => $vn_set_id, 'row_id' => $vn_row_id))) {
  905. $t_set_item->delete(true);
  906. }
  907. }
  908. }
  909. // rewrite ranks
  910. foreach($pa_row_ids as $vn_rank => $vn_row_id) {
  911. if (isset($va_row_ranks[$vn_row_id]) && $t_set_item->load(array('set_id' => $vn_set_id, 'row_id' => $vn_row_id))) {
  912. if ($va_row_ranks[$vn_row_id] != $vn_rank) {
  913. $t_set_item->set('rank', $vn_rank);
  914. $t_set_item->update();
  915. if ($t_set_item->numErrors()) {
  916. $va_errors[$vn_row_id] = _t('Could not reorder item %1: %2', $vn_row_id, join('; ', $t_set_item->getErrors()));
  917. }
  918. }
  919. } else {
  920. // add item to set
  921. $this->addItem($vn_row_id, null, $vn_user_id, $vn_rank);
  922. }
  923. }
  924. if(sizeof($va_errors)) {
  925. $o_trans->rollback();
  926. } else {
  927. $o_trans->commit();
  928. }
  929. return $va_errors;
  930. }
  931. # ------------------------------------------------------
  932. /**
  933. * Returns row_ids on items in set, in order of appearance in set
  934. * unless 'shuffle' option is set, in which case row_ids are returned
  935. * in a randomized order
  936. *
  937. * @param array $pa_options Optional list of options.
  938. * @return array List of row_ids
  939. */
  940. public function getItemRowIDs($pa_options=null) {
  941. if (!is_array($pa_options)) { $pa_options = array(); }
  942. $pa_options['returnRowIdsOnly'] = true;
  943. $va_row_ids = $this->getItems($pa_options);
  944. if (isset($pa_options['shuffle']) && $pa_options['shuffle'] && isset($va_row_ids) && is_array($va_row_ids)) {
  945. $va_row_ids = array_keys($va_row_ids);
  946. shuffle($va_row_ids);
  947. $va_row_ids = array_flip($va_row_ids);
  948. }
  949. return $va_row_ids;
  950. }
  951. # ------------------------------------------------------
  952. /**
  953. * Returns information on items in current set
  954. *
  955. * @param array $pa_options Optional array of options. Supported options are:
  956. * user_id = user_id of the current user; used to determine paintings may be shown
  957. * thumbnailVersions = A list of of a media versions to return with each item. Only used if the set content type is ca_objects.
  958. * thumbnailVersion = Same as 'thumbnailVersions' except it is a single value. (Maintained for compatibility with older code.)
  959. * limit = Limits the total number of records to be returned
  960. * checkAccess = An array of row-level access values to check set members for, often produced by the caGetUserAccessValues() helper. Set members with access values not in the list will be omitted. If this option is not set or left null no access checking is done.
  961. * returnRowIdsOnly = If true a simple array of row_ids (keys of the set members) for members of the set is returned rather than full item-level info for each set member.
  962. * returnItemIdsOnly = If true a simple array of item_ids (keys for the ca_set_items rows themselves) is returned rather than full item-level info for each set member.
  963. * returnItemAttributes = A list of attribute element codes for the ca_set_item record to return values for.
  964. * @return array An array of items. The format varies depending upon the options set. If returnRowIdsOnly or returnItemIdsOnly are set then the returned array is a
  965. * simple list of ids. The full return array is key'ed on ca_set_items.item_id and then on locale_id. The values are arrays with keys set to a number of fields including:
  966. * set_id, item_id, row_id, rank, label_id, locale_id, caption (from the ca_set_items label), all instrinsic field content from the row_id, the display label of the row
  967. * as 'set_item_label'.
  968. * If 'thumbnailVersion' is set then additional keys will be available for the selected media version:
  969. * representation_tag, representation_url, representation_width and representation_height (the HTML tag, URL, pixel width and pixel height of the representation respectively)
  970. * If 'thumbnailVersions' is set then additional keys will be available for the selected media versions:
  971. * representation_tag_<version_name>, representation_url_<version_name>, representation_width_<version_name> and representation_height_<version_name> (the HTML tag, URL, pixel width and pixel height of the representation respectively)
  972. * If 'returnItemAttributes' is set then there will be an additional key for each element_code prefixed with 'ca_attribute_' to ensure it doesn't conflict with any other key in the array.
  973. *
  974. */
  975. public function getItems($pa_options=null) {
  976. if(!($vn_set_id = $this->getPrimaryKey())) { return null; }
  977. if (!is_array($pa_options)) { $pa_options = array(); }
  978. if ($pa_options['user_id'] && !$this->haveAccessToSet($pa_options['user_id'], __CA_SET_READ_ACCESS__)) { return false; }
  979. $o_db = $this->getDb();
  980. $o_dm = $this->getAppDatamodel();
  981. $t_rel_label_table = null;
  982. if (!($t_rel_table = $o_dm->getInstanceByTableNum($this->get('table_num'), true))) { return null; }
  983. if (method_exists($t_rel_table, 'getLabelTableName')) {
  984. if ($vs_label_table_name = $t_rel_table->getLabelTableName()) {
  985. $t_rel_label_table = $o_dm->getInstanceByTableName($vs_label_table_name, true);
  986. }
  987. }
  988. $vs_label_join_sql = '';
  989. if ($t_rel_label_table) {
  990. $vs_label_join_sql = "LEFT JOIN ".$t_rel_label_table->tableName()." AS rel_label ON rel.".$t_rel_table->primaryKey()." = rel_label.".$t_rel_table->primaryKey()."\n";
  991. }
  992. $vs_rep_join_sql = $vs_rep_where_sql = $vs_rep_select = '';
  993. if (($t_rel_table->tableName() === 'ca_objects') && (isset($pa_options['thumbnailVersion']) || isset($pa_options['thumbnailVersions']))) {
  994. $vs_rep_join_sql = "LEFT JOIN ca_objects_x_object_representations AS coxor ON rel.object_id = coxor.object_id
  995. LEFT JOIN ca_object_representations AS cor ON coxor.representation_id = cor.representation_id\n";
  996. $vs_rep_where_sql = " AND (coxor.is_primary = 1 OR coxor.is_primary IS NULL)";
  997. $vs_rep_select = ', coxor.*, cor.media, cor.access rep_access';
  998. }
  999. $vs_limit_sql = '';
  1000. if (isset($pa_options['limit']) && ($pa_options['limit'] > 0)) {
  1001. $vs_limit_sql = "LIMIT ".$pa_options['limit'];
  1002. }
  1003. // get set items
  1004. $vs_access_sql = '';
  1005. if (isset($pa_options['checkAccess']) && is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && $t_rel_table->hasField('access')) {
  1006. $vs_access_sql = ' AND rel.access IN ('.join(',', $pa_options['checkAccess']).')';
  1007. }
  1008. $vs_deleted_sql = '';
  1009. if ($t_rel_table->hasField('deleted')) {
  1010. $vs_deleted_sql = ' AND rel.deleted = 0';
  1011. }
  1012. // get row labels
  1013. $qr_res = $o_db->query("
  1014. SELECT
  1015. casi.set_id, casi.item_id, casi.row_id, casi.rank,
  1016. rel_label.".$t_rel_label_table->getDisplayField().", rel_label.locale_id
  1017. FROM ca_set_items casi
  1018. INNER JOIN ".$t_rel_table->tableName()." AS rel ON rel.".$t_rel_table->primaryKey()." = casi.row_id
  1019. {$vs_label_join_sql}
  1020. WHERE
  1021. casi.set_id = ? {$vs_access_sql} {$vs_deleted_sql}
  1022. ORDER BY
  1023. casi.rank ASC
  1024. {$vs_limit_sql}
  1025. ", (int)$vn_set_id);
  1026. $va_labels = array();
  1027. while($qr_res->nextRow()) {
  1028. $va_labels[$qr_res->get('row_id')][$qr_res->get('locale_id')] = $qr_res->getRow();
  1029. }
  1030. $va_labels = caExtractValuesByUserLocale($va_labels);
  1031. // get set items
  1032. $vs_access_sql = '';
  1033. if (isset($pa_options['checkAccess']) && is_array($pa_options['c…

Large files files are truncated, but you can click here to view the full file