model.php 15.3 KB
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
<?php
// namespace administrator\components\com_jmap\framework\model;
/**
 *
 * @package JMAP::FRAMEWORK::administrator::components::com_jmap
 * @subpackage framework 
 * @subpackage model 
 * @author Joomla! Extensions Store
 * @copyright (C) 2015 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 */
defined ( '_JEXEC' ) or die ( 'Restricted access' );
jimport ( 'joomla.application.component.model' );

/**
 * Base model responsibilities
 *
 * @package JMAP::FRAMEWORK::administrator::components::com_jmap
 * @subpackage framework
 * @subpackage model
 * @since 2.0
 */
interface IJMapModel {
	/**
	 * Main get data method
	 *
	 * @access public
	 * @return Object[]
	 */
	public function getData();
	
	/**
	 * Counter result set
	 *
	 * @access public
	 * @return int
	 */
	public function getTotal();
	
	/**
	 * Load entity from ORM table
	 *
	 * @access public
	 * @param int $id        	
	 * @return Object&
	 */
	public function loadEntity($id);
	
	/**
	 * Cancel editing entity
	 *
	 * @param int $id        	
	 * @access public
	 * @return boolean
	 */
	public function cancelEntity($id);
	
	/**
	 * Delete entity
	 *
	 * @param array $ids        	
	 * @access public
	 * @return boolean
	 */
	public function deleteEntity($ids);
	
	/**
	 * Storing entity by ORM table
	 *
	 * @access public
	 * @return mixed
	 */
	public function storeEntity();
	
	/**
	 * Publishing state changer for entities
	 *
	 * @access public
	 * @param int $idEntity        	
	 * @param string $state        	
	 * @return boolean
	 */
	public function publishEntities($idEntity, $state);
	
	/**
	 * Change entities ordering
	 *
	 * @access public
	 * @param int $idEntity        	
	 * @param string $state        	
	 * @return boolean
	 */
	public function changeOrder($idEntity, $direction);
	
	/**
	 * Method to move and reorder
	 *
	 * @access public
	 * @return boolean on success
	 * @since 1.5
	 */
	function saveOrder($cid = array(), $order);
	
	/**
	 * Copy existing entity
	 *
	 * @param int $id        	
	 * @access public
	 * @return boolean
	 */
	public function copyEntity($ids);
	
	/**
	 * Return select lists used as filter for listEntities
	 *
	 * @access public
	 * @return array
	 */
	public function getFilters();
	
	/**
	 * Return select lists used as filter for editEntity
	 *
	 * @access public
	 * @param Object $record        	
	 * @return array
	 */
	public function getLists($record = null);
}

/**
 * Base concrete model for business logic
 *
 * @package JMAP::FRAMEWORK::administrator::components::com_jmap
 * @subpackage framework
 * @subpackage model
 * @since 2.0
 */
class JMapModel extends JModelLegacy implements IJMapModel {
	/**
	 * Application reference
	 *
	 * @access protected
	 * @var Object
	 */
	protected $app;
	
	/**
	 * Component params with view override
	 *
	 * @access protected
	 * @var Object
	 */
	protected $componentParams;
	
	/**
	 * Variables in request array
	 *
	 * @access protected
	 * @var Object
	 */
	protected $requestArray;
	
	/**
	 * Variables in request array name
	 *
	 * @access protected
	 * @var Object
	 */
	protected $requestName;
	
	/**
	 * Get a cache object specific for this extension models
	 * already configured and independant from global config
	 * The cache handler is always callback to cache functions operations
	 * and SQL database queries
	 *
	 * @access protected
	 * @return object JCache
	 */
	protected function getExtensionCache() {
		jimport ( 'joomla.cache.cache' );
		// Static cache instance
		static $cache;
		if (is_object ( $cache )) {
			return $cache;
		}
		
		$conf = JFactory::getConfig ();
		$componentParams = JComponentHelper::getParams ( $this->option );
		$options = array (
				'defaultgroup' => $this->option,
				'cachebase' => $conf->get ( 'cache_path', JPATH_CACHE ),
				'lifetime' => ( int ) $componentParams->get ( 'cache_lifetime', 24 ) * 60, // hours to minutes (core cache multiplies by 60 secs), default 24 hours
				'language' => $conf->get ( 'language', 'en-GB' ),
				'storage' => $conf->get ( 'cache_handler', 'file' ) 
		);
		
		$cache = JCache::getInstance ( 'callback', $options );
		$cache->setCaching ( $componentParams->get ( 'enable_callback_cache', false ) );
		return $cache;
	}
	
	/**
	 * Main get data method
	 *
	 * @access public
	 * @return Object[]
	 */
	public function getData() {
		// Build query
		$query = $this->buildListQuery ();
		$this->_db->setQuery ( $query, $this->getState ( 'limitstart' ), $this->getState ( 'limit' ) );
		try {
			$result = $this->_db->loadObjectList ();
			if ($this->_db->getErrorNum ()) {
				throw new JMapException ( JText::sprintf ( 'COM_JMAP_ERROR_RECORDS', $this->_db->getErrorMsg () ), 'error' );
			}
		} catch ( JMapException $e ) {
			$this->app->enqueueMessage ( $e->getMessage (), $e->getErrorLevel () );
			$result = array ();
		} catch ( Exception $e ) {
			$jmapException = new JMapException ( $e->getMessage (), 'error' );
			$this->app->enqueueMessage ( $jmapException->getMessage (), $jmapException->getErrorLevel () );
			$result = array ();
		}
		return $result;
	}
	
	/**
	 * Counter result set
	 *
	 * @access public
	 * @return int
	 */
	public function getTotal() {
		// Build query
		$query = $this->buildListQuery ();
		$this->_db->setQuery ( $query );
		$result = count ( $this->_db->loadColumn () );
		
		return $result;
	}
	
	/**
	 * Load entity from ORM table
	 *
	 * @access public
	 * @param int $id        	
	 * @return Object&
	 */
	public function loadEntity($id) {
		// load table record
		$table = $this->getTable ();
		
		// Check for previously set post data after errors
		$context = implode ( '.', array (
				$this->getState ( 'option' ),
				$this->getName (),
				'errordataload' 
		) );
		$sessionData = $this->app->getUserState ( $context );
		
		try {
			// Give priority to session recovered data
			if (! $sessionData) {
				// Load normally from database
				if (! $table->load ( $id )) {
					throw new JMapException ( $this->_db->getErrorMsg (), 'error' );
				}
			} else {
				// Recover and bind/load from session
				if (! $table->bind ( $sessionData, false, true )) {
					throw new JMapException ( $this->_db->getErrorMsg (), 'error' );
				}
				// Delete session data for next request
				$this->app->setUserState ( $context, null );
			}
		} catch ( JMapException $e ) {
			$this->setError ( $e );
			return false;
		} catch ( Exception $e ) {
			$jmapException = new JMapException ( $e->getMessage (), 'error' );
			$this->setError ( $jmapException );
			return false;
		}
		return $table;
	}
	
	/**
	 * Cancel editing entity
	 *
	 * @param int $id        	
	 * @access public
	 * @return boolean
	 */
	public function cancelEntity($id) {
		// New record - do null e return true subito
		if (! $id) {
			return true;
		}
		
		$table = $this->getTable ();
		try {
			if (! $table->load ( $id )) {
				throw new JMapException ( $table->getError (), 'error' );
			}
			if (! $table->checkin ()) {
				throw new JMapException ( $table->getError (), 'error' );
			}
		} catch ( JMapException $e ) {
			$this->setError ( $e );
			return false;
		} catch ( Exception $e ) {
			$jmapException = new JMapException ( $e->getMessage (), 'error' );
			$this->setError ( $jmapException );
			return false;
		}
		
		return true;
	}
	
	/**
	 * Delete entity
	 *
	 * @param array $ids        	
	 * @access public
	 * @return boolean
	 */
	public function deleteEntity($ids) {
		$table = $this->getTable ();
		
		// Ciclo su ogni entity da cancellare
		if (is_array ( $ids ) && count ( $ids )) {
			foreach ( $ids as $id ) {
				try {
					if (! $table->delete ( $id )) {
						throw new JMapException ( $table->getError (), 'error' );
					}
					// Only if table supports ordering
					if (property_exists ( $table, 'ordering' )) {
						$table->reorder ();
					}
				} catch ( JMapException $e ) {
					$this->setError ( $e );
					return false;
				} catch ( Exception $e ) {
					$jmapException = new JMapException ( $e->getMessage (), 'error' );
					$this->setError ( $jmapException );
					return false;
				}
			}
		}
		
		return true;
	}
	
	/**
	 * Storing entity by ORM table
	 *
	 * @access public
	 * @return mixed
	 */
	public function storeEntity() {
		$table = $this->getTable ();
		try {
			// Bind override aware, supports true as second param to distinguish when bind is store/load, has not side effect on original ignore array
			if (! $table->bind ( $this->requestArray[$this->requestName], true )) {
				throw new JMapException ( $table->getError (), 'error' );
			}
			
			// Run validation server side
			if (! $table->check ()) {
				throw new JMapException ( $table->getError (), 'error' );
			}
			
			// By default, never update nulls
			if (! $table->store ( false )) {
				throw new JMapException ( $table->getError (), 'error' );
			}
			// Only if table supports ordering
			if (property_exists ( $table, 'ordering' )) {
				$where = null;
				$catidOrdering = property_exists ( $table, 'catid' );
				if ($catidOrdering) {
					$where = 'catid = ' . $table->catid;
				}
				$table->reorder ( $where );
			}
		} catch ( JMapException $e ) {
			$this->setError ( $e );
			return false;
		} catch ( Exception $e ) {
			$jmapException = new JMapException ( $e->getMessage (), 'error' );
			$this->setError ( $jmapException );
			return false;
		}
		return $table;
	}
	
	/**
	 * Publishing state changer for entities
	 *
	 * @access public
	 * @param int $idEntity        	
	 * @param string $state        	
	 * @return boolean
	 */
	public function publishEntities($idEntity, $state) {
		// Table load
		$table = $this->getTable ( $this->getName (), 'Table' );
		
		if (isset ( $idEntity ) && $idEntity) {
			try {
				// Ensure treat as array
				if (! is_array ( $idEntity )) {
					$idEntity = array (
							$idEntity 
					);
				}
				$state = $state == 'unpublish' ? 0 : 1;
				if (! $table->publish ( $idEntity, $state )) {
					throw new JMapException ( $table->getError (), 'notice' );
				}
			} catch ( JMapException $e ) {
				$this->setError ( $e );
				return false;
			} catch ( Exception $e ) {
				$jmapException = new JMapException ( $e->getMessage (), 'notice' );
				$this->setError ( $jmapException );
				return false;
			}
		}
		return true;
	}
	
	/**
	 * Change entities ordering
	 *
	 * @access public
	 * @param int $idEntity        	
	 * @param int $direction        	
	 * @return boolean
	 */
	public function changeOrder($idEntity, $direction) {
		$where = null;
		if (isset ( $idEntity ) && $idEntity) {
			try {
				$table = $this->getTable ();
				$table->load ( ( int ) $idEntity );
				// Check if ordering where by cats is required
				if (property_exists ( $table, 'catid' )) {
					$where = 'catid = ' . $table->catid;
				}
				if (! $table->move ( $direction, $where )) {
					throw new JMapException ( $table->getError (), 'notice' );
				}
			} catch ( JMapException $e ) {
				$this->setError ( $e );
				return false;
			} catch ( Exception $e ) {
				$jmapException = new JMapException ( $e->getMessage (), 'notice' );
				$this->setError ( $jmapException );
				return false;
			}
		}
		return true;
	}
	
	/**
	 * Method to move and reorder
	 *
	 * @access public
	 * @param array $cid        	
	 * @param array $order        	
	 * @return boolean on success
	 * @since 1.5
	 */
	public function saveOrder($cid = array(), $order) {
		if (is_array ( $cid ) && count ( $cid )) {
			try {
				$table = $this->getTable ();
				$singleReorder = ! (property_exists ( $table, 'catid' ));
				// If JTableNested demand to table class the saveorder algo
				if ($table instanceof JTableNested) {
					if (! $table->saveorder ( $cid, $order )) {
						throw new JMapException ( $table->getError (), 'notice' );
					}
				} else {
					// update ordering values
					$conditions = array();
					for($i = 0; $i < count ( $cid ); $i ++) {
						$table->load ( ( int ) $cid [$i] );
						if ($table->ordering != $order [$i]) {
							$table->ordering = $order [$i];
							if (! $table->store ()) {
								throw new JMapException ( $table->getError (), 'notice' );
							}
						}
						// Remember to reorder within position and client_id
						$condition = 'catid = ' . $table->catid;
						$found = false;
						
						foreach ( $conditions as $cond ) {
							if ($cond [1] == $condition) {
								$found = true;
								break;
							}
						}
						
						if (! $found) {
							$key = $table->getKeyName ();
							$conditions [] = array (
									$table->$key,
									$condition 
							);
						}
					}
				}
			} catch ( JMapException $e ) {
				$this->setError ( $e );
				return false;
			} catch ( Exception $e ) {
				$jmapException = new JMapException ( $e->getMessage (), 'notice' );
				$this->setError ( $jmapException );
				return false;
			}
			
			// All went well
			if (! $table instanceof JTableNested && ! $singleReorder) {
				// Execute reorder for each category.
				foreach ( $conditions as $cond ) {
					$table->load ( $cond [0] );
					$table->reorder ( $cond [1] );
				}
			} elseif (! $table instanceof JTableNested && $singleReorder) {
				$table->reorder ();
			}
		}
		return true;
	}
	
	/**
	 * Copy existing entity
	 *
	 * @param int $id        	
	 * @access public
	 * @return boolean
	 */
	public function copyEntity($ids) {
		if (is_array ( $ids ) && count ( $ids )) {
			$table = $this->getTable ();
			try {
				foreach ( $ids as $id ) {
					if ($table->load ( ( int ) $id )) {
						$table->id = 0;
						$table->name = JText::_ ( 'COM_JMAP_COPYOF' ) . $table->name;
						$table->published = 0;
						$table->params = $table->params->toString ();
						if (! $table->store ()) {
							throw new JMapException ( $table->getError (), 'error' );
						}
					} else {
						throw new JMapException ( $table->getError (), 'error' );
					}
				}
				$table->reorder ();
			} catch ( JMapException $e ) {
				$this->setError ( $e );
				return false;
			} catch ( Exception $e ) {
				$jmapException = new JMapException ( $e->getMessage (), 'error' );
				$this->setError ( $jmapException );
				return false;
			}
		}
		return true;
	}
	
	/**
	 * Return select lists used as filter for listEntities
	 *
	 * @access public
	 * @return array
	 */
	public function getFilters() {
		$filters ['state'] = JHtml::_ ( 'grid.state', $this->getState ( 'state' ) );
		
		return $filters;
	}
	
	/**
	 * Return select lists used as filter for editEntity
	 *
	 * @access public
	 * @param Object $record        	
	 * @return array
	 */
	public function getLists($record = null) {
		$lists = array ();
		// Grid states
		$lists ['published'] = JHtml::_ ( 'select.booleanlist', 'published', null, $record->published );
		
		return $lists;
	}
	
	/**
	 * Get the component params width view override/merge
	 * 
	 * @access public
	 * @return Object
	 */
	public function getComponentParams() {
		if (is_object ( $this->componentParams )) {
			return $this->componentParams;
		}
		
		// Manage Site and Admin application instance to call params with view overrides when needed
		if ($this->app instanceof JApplicationSite && $this->option == 'com_jmap') {
			$this->componentParams = $this->app->getParams ( 'com_jmap' );
		} else {
			$this->componentParams = JComponentHelper::getParams ( 'com_jmap' );
		}
		
		return $this->componentParams;
	}
	
	/**
	 * Class constructor
	 *
	 * @access public
	 * @param $config array        	
	 * @return Object&
	 */
	public function __construct($config = array()) {
		parent::__construct ( $config );
		$this->app = JFactory::getApplication ();
		$this->requestArray = &$GLOBALS;
		$this->requestName = '_' . strtoupper('post');
	}
}