PageRenderTime 119ms CodeModel.GetById 77ms app.highlight 34ms RepoModel.GetById 1ms app.codeStats 1ms

/assets/snippets/evogallery/classes/gallery.class.inc.php

https://github.com/good-web-master/modx.evo.custom
PHP | 442 lines | 350 code | 50 blank | 42 comment | 93 complexity | f924e04763343d715e3a68b42fcbf5f7 MD5 | raw file
  1<?php
  2/*---------------------------------------------------------------------------
  3* Gallery - Contains functions for generating a listing of gallery thumbanils
  4*                   while controlling various display aspects.
  5*--------------------------------------------------------------------------*/
  6class Gallery
  7{
  8	var $config;  // Array containing snippet configuration values
  9
 10	/**
 11	* Class constructor, set configuration parameters
 12	*/
 13	function Gallery($params)
 14	{
 15		global $modx;
 16
 17		$this->config = $params;
 18
 19		$this->galleriesTable = 'portfolio_galleries';
 20	}
 21
 22	/**
 23	* Determine what action was requested and process request
 24	*/
 25	function execute()
 26	{
 27		$output = '';
 28
 29		$this->config['type'] = isset($this->config['type']) ? $this->config['type'] : 'simple-list';
 30
 31		if ($this->config['includeAssets'])
 32			$this->getConfig($this->config['type']);
 33
 34		if ($this->config['display'] == 'galleries')
 35			$output = $this->renderGalleries();
 36		elseif ($this->config['display'] == 'single')
 37			$output = $this->renderSingle();
 38        else
 39			$output = $this->renderImages();
 40
 41		return $output;
 42	}
 43
 44	/**
 45	* Generate a listing of document galleries
 46	*/
 47	function renderGalleries()
 48	{
 49		global $modx;
 50
 51		// Retrieve chunks/default templates from disk
 52		$tpl = ($this->config['tpl'] == '') ? file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.default.txt') : $modx->getChunk($this->config['tpl']);
 53		$item_tpl = ($this->config['itemTpl'] == '') ? file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.default.txt') : $modx->getChunk($this->config['itemTpl']);
 54		$item_tpl_first = ($this->config['itemTplFirst'] == '') ? @file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.first.txt') : $modx->getChunk($this->config['itemTplFirst']);
 55		$item_tpl_alt = ($this->config['itemTplAlt'] == '') ? @file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.alt.txt') : $modx->getChunk($this->config['itemTplAlt']);
 56		$item_tpl_last = ($this->config['itemTplLast'] == '') ? @file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.last.txt') : $modx->getChunk($this->config['itemTplLast']);
 57
 58		// Hide/show docs based on configuration
 59		$docSelect = '';
 60		if ($this->config['docId'] != '*' && !empty($this->config['docId']))
 61		{
 62			if (strpos($this->config['docId'], ',') !== false)
 63			{
 64				$docSelect = 'parent IN ('.$this->config['docId'].')';
 65			}
 66			else
 67				$docSelect = 'parent = ' . $this->config['docId'];
 68		}
 69		if ($this->config['excludeDocs'] > 0)
 70		{
 71			$excludeDocs = '';
 72			if (strpos($this->config['excludeDocs'], ',') !== false)
 73			{
 74				$excludeDocs = 'parent NOT IN ('.$this->config['excludeDocs'].')';
 75			}
 76			else
 77				$excludeDocs .= 'parent != ' . $this->config['excludeDocs'];
 78			if (!empty($docSelect))
 79				$docSelect.= ' AND ';
 80			$docSelect.= $excludeDocs;
 81		}
 82
 83		$phx = new PHxParser();  // Instantiate PHx
 84
 85		$items = '';
 86
 87		// Retrieve list of documents under the requested id
 88		$filter = " WHERE deleted = '0' AND published = '1' AND type = 'document' AND hidemenu <= '" . $this->config['ignoreHidden'] . "'";
 89		if (!empty($docSelect))
 90			$filter.=' AND '.$docSelect;
 91	
 92		if ($this->config['paginate']) {
 93			//Retrieve total records
 94			$totalRows = $modx->db->getValue('select count(*) from '.$modx->getFullTableName('site_content').$filter);
 95			if (!empty($this->config['limit']) && $totalRows>$this->config['limit'])
 96				$totalRows = $this->config['limit'];
 97			$limit = $this->paginate($totalRows);
 98			if (!empty($limit))
 99				$limit = ' limit '.$limit;
100		} else
101			$limit = !empty($this->config['limit']) ? ' limit '.$this->config['limit'] : "";
102		$result = $modx->db->query("select id, pagetitle, longtitle, description, alias, pub_date, introtext, editedby, editedon, publishedon, publishedby, menutitle from " . $modx->getFullTableName('site_content') . $filter. ' order by '. $this->config['gallerySortBy'] . ' ' . $this->config['gallerySortDir'] . $limit);
103		$recordCount = $modx->db->getRecordCount($result);
104		if ($recordCount > 0)
105		{
106		    $count = 1;
107			while ($row = $modx->fetchRow($result))
108			{
109				$item_phx = new PHxParser();
110
111				// Get total number of images for total placeholder
112				$total_result = $modx->db->select("filename", $modx->getFullTableName($this->galleriesTable), "content_id = '" . $row['id'] . "'");
113                $total = $modx->db->getRecordCount($total_result);
114
115				// Fetch first image for each gallery, using the image sort order/direction
116				$image_result = $modx->db->select("filename", $modx->getFullTableName($this->galleriesTable), "content_id = '" . $row['id'] . "'", $this->config['sortBy'] . ' ' . $this->config['sortDir'], '1');
117				if ($modx->db->getRecordCount($image_result) > 0)
118				{
119					$image = $modx->fetchRow($image_result);
120					foreach ($image as $name => $value)
121						if ($name=='filename')
122							$item_phx->setPHxVariable($name, rawurlencode(trim($value)));
123						else
124							$item_phx->setPHxVariable($name, trim($value));
125					$item_phx->setPHxVariable('images_dir', $this->config['galleriesUrl'] . $row['id'] . '/');
126					$item_phx->setPHxVariable('thumbs_dir', $this->config['galleriesUrl'] . $row['id'] . '/thumbs/');
127					$item_phx->setPHxVariable('original_dir', $this->config['galleriesUrl'] . $row['id'] . '/original/');
128					$item_phx->setPHxVariable('plugin_dir', $this->config['snippetUrl'] . $this->config['type'] . '/');
129
130					foreach ($row as $name => $value)
131						$item_phx->setPHxVariable($name, trim($value));
132                    
133                    // Get template variable output for row and set variables as needed
134                    $row_tvs = $modx->getTemplateVarOutput('*',$row['id']);
135					foreach ($row_tvs as $name => $value)
136						$item_phx->setPHxVariable($name, trim($value));
137
138					$item_phx->setPHxVariable('total', $total);
139
140    				if(!empty($item_tpl_first) && $count == 1){
141        				$items .= $item_phx->Parse($item_tpl_first);
142    				} else if(!empty($item_tpl_last) && $count == $recordCount){
143        				$items .= $item_phx->Parse($item_tpl_last);
144    				} else if(!empty($item_tpl_alt) && $count % $this->config['itemAltNum'] == 0){
145        				$items .= $item_phx->Parse($item_tpl_alt);
146    				} else {
147        				$items .= $item_phx->Parse($item_tpl);
148    				}
149
150				}
151				$count++;
152			}
153		}
154
155		$phx->setPHxVariable('items', $items);
156		$phx->setPHxVariable('plugin_dir', $this->config['snippetUrl'] . $this->config['type'] . '/');
157
158		return $phx->Parse($tpl);  // Pass through PHx;
159	}
160
161	/**
162	* Generate a listing of thumbnails/images for gallery/slideshow display
163	*/
164	function renderImages()
165	{
166		global $modx;
167
168		// Retrieve chunks/default templates from disk
169		$tpl = ($this->config['tpl'] == '') ? file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.default.txt') : $modx->getChunk($this->config['tpl']);
170		$item_tpl = ($this->config['itemTpl'] == '') ? file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.default.txt') : $modx->getChunk($this->config['itemTpl']);
171		$item_tpl_first = ($this->config['itemTplFirst'] == '') ? @file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.first.txt') : $modx->getChunk($this->config['itemTplFirst']);
172		$item_tpl_alt = ($this->config['itemTplAlt'] == '') ? @file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.alt.txt') : $modx->getChunk($this->config['itemTplAlt']);
173		$item_tpl_last = ($this->config['itemTplLast'] == '') ? @file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.last.txt') : $modx->getChunk($this->config['itemTplLast']);
174
175		$docSelect = '';
176		if ($this->config['docId'] != '*' && !empty($this->config['docId']))
177		{
178			if (strpos($this->config['docId'], ',') !== false)
179			{
180				$docSelect = 'content_id IN ('.$this->config['docId'].')';
181			}
182			else
183				$docSelect = 'content_id = ' . $this->config['docId'];
184		}
185		if ($this->config['excludeDocs'] > 0)
186		{
187			$excludeDocs = '';
188			if (strpos($this->config['excludeDocs'], ',') !== false)
189			{
190				$excludeDocs = 'content_id NOT IN ('.$this->config['excludeDocs'].')';
191			}
192			else
193				$excludeDocs .= 'content_id != ' . $this->config['excludeDocs'];
194			if (!empty($docSelect))
195				$docSelect.= ' AND ';
196			$docSelect.= $excludeDocs;
197		}
198
199		if (!empty($this->config['tags']))
200		{
201            $mode = (!empty($this->config['tagMode']) ? $this->config['tagMode'] : 'AND');
202            foreach (explode(',', $this->config['tags']) as $tag) {
203            	$tagSelect .= "keywords LIKE '%" . trim($tag) . "%' ".$mode." ";
204            }
205            $tagSelect = rtrim($tagSelect, ' '.$mode.' ');
206			if (!empty($docSelect))
207				$docSelect.=' AND ';
208            $docSelect .= "(".$tagSelect.")";
209		}
210
211		$phx = new PHxParser();  // Instantiate PHx
212
213		$items = '';
214		$limit = '';
215		$where = !empty($docSelect)?' WHERE '.$docSelect.' ':'';
216		if ($this->config['paginate']) {
217			//Retrieve total records
218			$totalRows = $modx->db->getValue('select count(*) from '.$modx->getFullTableName($this->galleriesTable).$where.(!empty($this->config['limit']) ? ' limit '.$this->config['limit'] : ""));
219			$limit = $this->paginate($totalRows);
220			if (!empty($limit))
221				$limit = ' limit '.$limit;
222		} else
223			$limit = !empty($this->config['limit']) ? ' limit '.$this->config['limit'] : "";
224		// Retrieve photos from the database table
225		$result = $modx->db->query("select * from ". $modx->getFullTableName($this->galleriesTable). $where. ' order by '. $this->config['sortBy'] . ' ' . $this->config['sortDir']. $limit);
226        $recordCount = $modx->db->getRecordCount($result);
227		if ($recordCount > 0)
228		{
229            $count = 1;		    
230			while ($row = $modx->fetchRow($result))
231			{
232				$item_phx = new PHxParser();
233				foreach ($row as $name => $value)
234					if ($name=='filename')
235						$item_phx->setPHxVariable($name, rawurlencode(trim($value)));
236					else
237						$item_phx->setPHxVariable($name, trim($value));
238				$imgsize = getimagesize($this->config['galleriesPath'] . $row['content_id'] . '/' . $row['filename']); 
239				$item_phx->setPHxVariable('width',$imgsize[0]); 
240				$item_phx->setPHxVariable('height',$imgsize[1]); 
241				$item_phx->setPHxVariable('image_withpath', $this->config['galleriesUrl'] . $row['content_id'] . '/' . $row['filename']);
242				$item_phx->setPHxVariable('images_dir', $this->config['galleriesUrl'] . $row['content_id'] . '/');
243				$item_phx->setPHxVariable('thumbs_dir', $this->config['galleriesUrl'] . $row['content_id'] . '/thumbs/');
244				$item_phx->setPHxVariable('original_dir', $this->config['galleriesUrl'] . $row['content_id'] . '/original/');
245				$item_phx->setPHxVariable('plugin_dir', $this->config['snippetUrl'] . $this->config['type'] . '/');
246				if(!empty($item_tpl_first) && $count == 1){
247    				$items .= $item_phx->Parse($item_tpl_first);
248				} else if(!empty($item_tpl_last) && $count == $recordCount){
249    				$items .= $item_phx->Parse($item_tpl_last);
250				} else if(!empty($item_tpl_alt) && $count % $this->config['itemAltNum'] == 0){
251    				$items .= $item_phx->Parse($item_tpl_alt);
252				} else {
253    				$items .= $item_phx->Parse($item_tpl);
254				}
255				$count++;
256			}
257		}
258		$phx->setPHxVariable('items', $items);
259		$phx->setPHxVariable('plugin_dir', $this->config['snippetUrl'] . $this->config['type'] . '/');
260
261		return $phx->Parse($tpl);  // Pass through PHx;
262	}
263
264	/**
265	* Generate a listing of a single thumbnail/image for gallery/slideshow display
266	*/
267	function renderSingle()
268	{
269		global $modx;
270
271		// Retrieve chunks/default templates from disk
272		$tpl = ($this->config['tpl'] == '') ? file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.default.txt') : $modx->getChunk($this->config['tpl']);
273		$item_tpl = ($this->config['itemTpl'] == '') ? file_get_contents($this->config['snippetPath'] . $this->config['type'] . '/tpl.item.default.txt') : $modx->getChunk($this->config['itemTpl']);
274
275		$picSelect = '';
276		if ($this->config['picId'] != '*' && !empty($this->config['picId']))
277		{
278				$picSelect = "id = '" . $this->config['picId'] . "'";
279		}
280
281		$phx = new PHxParser();  // Instantiate PHx
282
283		$items = '';
284
285		// Retrieve photos from the database table
286	    $result = $modx->db->select("*", $modx->getFullTableName($this->galleriesTable), $picSelect);
287		if ($modx->db->getRecordCount($result) > 0)
288		{
289			while ($row = $modx->fetchRow($result))
290			{
291				$item_phx = new PHxParser();
292				foreach ($row as $name => $value)
293					if ($name=='filename')
294						$item_phx->setPHxVariable($name, rawurlencode(trim($value)));
295					else
296						$item_phx->setPHxVariable($name, trim($value));
297				$item_phx->setPHxVariable('images_dir', $this->config['galleriesUrl'] . $row['content_id'] . '/');
298				$item_phx->setPHxVariable('thumbs_dir', $this->config['galleriesUrl'] . $row['content_id'] . '/thumbs/');
299				$item_phx->setPHxVariable('original_dir', $this->config['galleriesUrl'] . $row['content_id'] . '/original/');
300				$item_phx->setPHxVariable('plugin_dir', $this->config['snippetUrl'] . $this->config['type'] . '/');
301				$items .= $item_phx->Parse($item_tpl);
302			}
303		}
304
305		$phx->setPHxVariable('items', $items);
306		$phx->setPHxVariable('plugin_dir', $this->config['snippetUrl'] . $this->config['type'] . '/');
307
308		return $phx->Parse($tpl);  // Pass through PHx;
309	}
310
311	/**
312	* Get configuration settings for the selected gallery/slideshow type
313	*/
314	function getConfig($type)
315	{
316		global $modx;
317
318		if (file_exists($this->config['snippetPath'] . $type . '/tpl.config.txt'))
319		{
320			$register = 0;
321
322			$config = file($this->config['snippetPath'] . $type . '/tpl.config.txt');
323			foreach ($config as $line)
324			{
325				$line = trim($line);
326
327				if ($line == '')
328					$register = 0;
329				elseif (strpos($line, '@SCRIPT') === 0)
330					$register = 1;
331				elseif (strpos($line, '@CSS') === 0)
332					$register = 2;
333				elseif (strpos($line, '@EXTSCRIPT') === 0)
334					$register = 3;
335				elseif (strpos($line, '@EXTCSS') === 0)
336					$register = 4;
337				else
338				{
339					switch ($register)
340					{
341						case 1:
342							$modx->regClientStartupScript($this->config['snippetUrl'] . $type . '/' . $line);
343							break;
344						case 2:
345							$modx->regClientCSS($this->config['snippetUrl'] . $type . '/' . $line);
346							break;
347						case 3:
348							$modx->regClientStartupScript($line);
349							break;
350						case 4:
351							$modx->regClientCSS($line);
352							break;
353					}
354				}
355			}
356		}
357	}
358
359	/**
360	* Replace placeholders in template
361	*/
362	function processTemplate($tpl, $params)
363	{
364		//Parse placeholders
365		foreach($params as $key=>$value)
366		{
367			$tpl = str_replace('[+'.$key.'+]', $value, $tpl);
368		}
369		return $tpl;
370	}
371
372	/**
373	*  Set pagination's placeholders
374	*  Return string with limit values for SQL query
375	*/
376	function paginate($totalRows) {
377		global $modx;
378		if (!$this->config['paginate'])
379			return "";
380
381		$pageUrl = !empty($this->config['id'])?$this->config['id'].'_page':'page';
382		$page = isset($_GET[$pageUrl])?intval($_GET[$pageUrl]):1;
383		$rowsPerPage = $this->config['show'];
384		$totalPages = ceil($totalRows/$rowsPerPage);
385		$previous = $page - 1;
386		$next = $page + 1;
387		$start = ($page-1)*$rowsPerPage;
388		if ($start<0)
389			$start = 0;
390		$stop = $start + $rowsPerPage - 1;
391		if ($stop>=$totalRows)
392			$stop = $totalRows - 1;
393
394		$split = "";
395		if ($previous > 0 && $next <= $totalPages)
396			$split = $paginateSplitterCharacter;
397
398		$previoustpl = '';
399		$previousplaceholder = '';
400		if ($previous > 0)
401			$previoustpl = 'tplPaginatePrevious';
402		elseif ($this->config['paginateAlwaysShowLinks'])
403			$previoustpl = 'tplPaginatePreviousOff';
404		if (!empty($previoustpl))
405			$previousplaceholder = $this->processTemplate($this->config[$previoustpl],
406															array('url'=>$modx->makeUrl($modx->documentIdentifier,'',($previous!=1?"$pageUrl=$previous":"")),
407																'PaginatePreviousText'=>$this->config['paginatePreviousText']));			
408		$nexttpl = '';
409		$nextplaceholder = '';
410		if ($next <= $totalPages)
411			$nexttpl = 'tplPaginateNext';
412		elseif ($this->config['paginateAlwaysShowLinks'])
413			$nexttpl = 'tplPaginateNextOff';
414		if (!empty($nexttpl))
415			$nextplaceholder = $this->processTemplate($this->config[$nexttpl],
416														array('url'=>$modx->makeUrl($modx->documentIdentifier,'',($next!=1?"$pageUrl=$next":"")),
417																'PaginateNextText'=>$this->config['paginateNextText']));			
418
419		$pages = '';
420		for ($i=1;$i<=$totalPages;$i++) {
421			if ($i != $page) {
422				$pages .= $this->processTemplate($this->config['tplPaginatePage'],
423												array('url'=>$modx->makeUrl($modx->documentIdentifier,'',($i!=1?"$pageUrl=$i":"")),'page'=>$i));
424			} else {
425				$modx->setPlaceholder($this->config['id']."currentPage", $i);
426				$pages .= $this->processTemplate($this->config['tplPaginateCurrentPage'], array('page'=>$i));
427			}
428		}
429		$modx->setPlaceholder($this->config['id']."next", $nextplaceholder);
430		$modx->setPlaceholder($this->config['id']."previous", $previousplaceholder);
431		$modx->setPlaceholder($this->config['id']."splitter", $split);
432		$modx->setPlaceholder($this->config['id']."start", $start+1);
433		$modx->setPlaceholder($this->config['id']."stop", $stop+1);
434		$modx->setPlaceholder($this->config['id']."total", $totalRows);
435		$modx->setPlaceholder($this->config['id']."pages", $pages);
436		$modx->setPlaceholder($this->config['id']."perPage", $rowsPerPage);
437		$modx->setPlaceholder($this->config['id']."totalPages", $totalPages);
438		return $start.','.($stop-$start+1);
439	}	
440
441}
442?>