croogo /Croogo/View/Helper/LayoutHelper.php

Language PHP Lines 514
MD5 Hash 7ff7a0c50681209b7c08c7d37b3e896c
Repository https://github.com/kareypowell/croogo.git View Raw File View Project SPDX
  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
<?php

App::uses('AppHelper', 'View/Helper');

/**
 * Layout Helper
 *
 * @category Helper
 * @package  Croogo.Croogo.View.Helper
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class LayoutHelper extends AppHelper {

/**
 * Other helpers used by this helper
 *
 * @var array
 * @access public
 */
	public $helpers = array(
		'Croogo.Croogo',
		'Html',
		'Form',
		'Session',
		'Js',
	);

/**
 * Core helpers
 *
 * Extra supported callbacks, like beforeNodeInfo() and afterNodeInfo(),
 * won't be called for these helpers.
 *
 * @var array
 * @access public
 */
	public $coreHelpers = array(
		// CakePHP
		'Ajax',
		'Cache',
		'Form',
		'Html',
		'Javascript',
		'JqueryEngine',
		'Js',
		'MootoolsEngine',
		'Number',
		'Paginator',
		'PrototypeEngine',
		'Rss',
		'Session',
		'Text',
		'Time',
		'Xml',

		// Croogo
		'Filemanager',
		'Image',
		'Layout',
		'Recaptcha',
	);

/**
 * Provides backward compatibility for deprecated methods
 */
	public function __call($method, $params) {
		$mapMethods = array(
			'meta' => array('Meta.Meta', 'meta'),
			'metaField' => array('Meta.Meta', 'field'),
			'blocks' => array('Blocks.Regions', 'blocks'),
			'regionIsEmpty' => array('Blocks.Regions', 'isEmpty'),
			'linkStringToArray' => array('Menus.Menus', 'linkStringToArray'),
			'menu' => array('Menus.Menus', 'menu'),
			'nestedLinks' => array('Menus.Menus', 'nestedLinks'),
			'nestedTerms' => array('Taxonomy.Taxonomies', 'nestedTerms'),
			'vocabulary' => array('Taxonomy.Taxonomies', 'vocabulary'),
			'node' => array('Nodes.Nodes', 'field'),
			'nodeBody' => array('Nodes.Nodes', 'body'),
			'nodeExcerpt' => array('Nodes.Nodes', 'excerpt'),
			'nodeInfo' => array('Nodes.Nodes', 'info'),
			'nodeList' => array('Nodes.Nodes', 'nodeList'),
			'nodeMoreInfo' => array('Nodes.Nodes', 'moreInfo'),
			'setNode' => array('Nodes.Nodes', 'set'),
			'setNodeField' => array('Nodes.Nodes', 'field'),
			'adminRowActions' => array('Croogo', 'adminRowActions'),
			'adminTabs' => array('Croogo', 'adminTabs'),
			'adminMenus' => array('Croogo', 'adminMenus'),
		);

		if (!isset($mapMethods[$method])) {
			trigger_error(__d('croogo', 'Method %1$s::%2$s does not exist', get_class($this), $method), E_USER_WARNING);
			return;
		}

		$mapped = $mapMethods[$method];
		list($helper, $method) = $mapped;
		list($plugin, $helper) = pluginSplit($helper, true);
		if (!$this->{$helper}) {
			if (!$this->_View->Helpers->loaded($helper)) {
				$this->_View->Helpers->load($helper);
			}
			$this->{$helper} = $this->_View->{$helper};
		}
		return call_user_func_array(array($this->{$helper}, $method), $params);
	}

/**
 * Provides backward compatibility for deprecated properties
 */
	public function __get($name) {
		switch ($name) {
			case 'node':
				return $this->_View->Nodes->node;
			default:
				return parent::__get($name);
		}
	}

/**
 * Provides backward compatibility for deprecated properties
 */
	public function __set($name, $val) {
		switch ($name) {
			case 'node':
				return $this->_View->Nodes->node = $val;
			default:
				return parent::__set($name, $val);
		}
	}

/**
 * Javascript variables
 *
 * Shows croogo.js file along with useful information like the applications's basePath, etc.
 *
 * Also merges Configure::read('Js') with the Croogo js variable.
 * So you can set javascript info anywhere like Configure::write('Js.my_var', 'my value'),
 * and you can access it like 'Croogo.my_var' in your javascript.
 *
 * @return string
 */
	public function js() {
		$croogo = array();
		if (isset($this->request->params['locale'])) {
			$croogo['basePath'] = Router::url('/' . $this->request->params['locale'] . '/');
		} else {
			$croogo['basePath'] = Router::url('/');
		}
		$validKeys = array(
			'plugin' => null,
			'controller' => null,
			'action' => null,
			'named' => null,
		);
		$croogo['params'] = array_intersect_key(
			array_merge($validKeys, $this->request->params),
			$validKeys
		);
		if (is_array(Configure::read('Js'))) {
			$croogo = Hash::merge($croogo, Configure::read('Js'));
		}
		return $this->Html->scriptBlock('var Croogo = ' . $this->Js->object($croogo) . ';');
	}

/**
 * Status
 *
 * instead of 0/1, show tick/cross
 *
 * @param integer $value 0 or 1
 * @return string formatted img tag
 */
	public function status($value) {
		if ($value == 1) {
			$icon = 'ok';
			$class = 'green';
		} else {
			$icon = 'remove';
			$class = 'red';
		}
		if (method_exists($this->Html, 'icon')) {
			return $this->Html->icon($icon, compact('class'));
		} else {
			if (empty($this->_View->CroogoHtml)) {
				$this->_View->Helpers->load('Croogo.CroogoHtml');
			}
			return $this->_View->CroogoHtml->icon($icon, compact('class'));
		}
	}

/**
 * Display value from $item array
 *
 * @param $item array of values
 * @param $model string model alias
 * @param $field string field name
 * @param $options array
 * @return string
 */
	public function displayField($item, $model, $field, $options = array()) {
		extract(array_intersect_key($options, array(
			'type' => null,
			'url' => array(),
			'options' => array(),
		)));
		switch ($type) {
			case 'boolean':
				$out = $this->status($item[$model][$field]);
			break;
			default:
				$out = h($item[$model][$field]);
			break;
		}

		if (!empty($url)) {
			if (isset($url['pass'])) {
				$passVars = is_string($url['pass']) ? array($url['pass']) : $url['pass'];
				foreach ($passVars as $passField) {
					$url[] = $item[$model][$passField];
				}
				unset($url['pass']);
			}

			if (isset($url['named'])) {
				$namedVars = is_string($url['named']) ? array($url['named']) : $url['named'];
				foreach ($namedVars as $namedField) {
					$url[$namedField] = $item[$model][$namedField];
				}
				unset($url['named']);
			}

			$out = $this->Html->link($out, $url, $options);
		}
		return $out;
	}

/**
 * Show flash message
 *
 * @return string
 */
	public function sessionFlash() {
		$messages = $this->Session->read('Message');
		$output = '';
		if (is_array($messages)) {
			foreach (array_keys($messages) as $key) {
				$output .= $this->Session->flash($key);
			}
		}
		return $output;
	}

/**
 * isLoggedIn
 *
 * if User is logged in
 *
 * @return boolean
 */
	public function isLoggedIn() {
		if ($this->Session->check('Auth.User.id')) {
			return true;
		} else {
			return false;
		}
	}

/**
 * Feed
 *
 * RSS feeds
 *
 * @param boolean $returnUrl if true, only the URL will be returned
 * @return string
 */
	public function feed($returnUrl = false) {
		if (Configure::read('Site.feed_url')) {
			$url = Configure::read('Site.feed_url');
		} else {
			/*$url = Router::url(array(
				'controller' => 'nodes',
				'action' => 'index',
				'type' => 'blog',
				'ext' => 'rss',
			));*/
			$url = '/promoted.rss';
		}

		if ($returnUrl) {
			$output = $url;
		} else {
			$url = Router::url($url);
			$output = '<link href="' . $url . '" type="application/rss+xml" rel="alternate" title="RSS 2.0" />';
			return $output;
		}

		return $output;
	}

/**
 * Get Role ID
 *
 * @return integer
 */
	public function getRoleId() {
		if ($this->isLoggedIn()) {
			$roleId = $this->Session->read('Auth.User.role_id');
		} else {
			// Public
			$roleId = 3;
		}
		return $roleId;
	}

/**
 * Creates a special type of link for use in admin area.
 *
 * Clicking the link will automatically check a corresponding checkbox
 * where element id is equal to $url parameter and immediately submit the form
 * it's on.  This works in tandem with Admin.processLink() in javascript.
 *
 * @deprecated Will be removed in the future. See CroogoHelper::adminRowAction()
 */
	public function processLink($title, $url = null, $options = array(), $confirmMessage = false) {
		if (!empty($confirmMessage)) {
			$options['data-confirm-message'] = $confirmMessage;
		}
		if (isset($options['icon'])) {
			$options['iconInline'] = true;
		}
		$output = $this->Html->link($title, $url, $options);
		return $output;
	}

/**
 * Filter content
 *
 * Replaces bbcode-like element tags
 *
 * @param string $content content
 * @return string
 */
	public function filter($content, $options = array()) {
		Croogo::dispatchEvent('Helper.Layout.beforeFilter', $this->_View, array(
			'content' => &$content,
			'options' => $options,
		));
		$content = $this->filterElements($content, $options);
		Croogo::dispatchEvent('Helper.Layout.afterFilter', $this->_View, array(
			'content' => &$content,
			'options' => $options,
		));
		return $content;
	}

/**
 * Filter content for elements
 *
 * Original post by Stefan Zollinger: http://bakery.cakephp.org/articles/view/element-helper
 * [element:element_name] or [e:element_name]
 *
 * @param string $content
 * @return string
 */
	public function filterElements($content, $options = array()) {
		preg_match_all('/\[(element|e):([A-Za-z0-9_\-\/]*)(.*?)\]/i', $content, $tagMatches);
		$validOptions = array('plugin', 'cache', 'callbacks');
		for ($i = 0, $ii = count($tagMatches[1]); $i < $ii; $i++) {
			$regex = '/([\w-]+)=[\'"]?((?:.(?![\'"]?\s+(?:\S+)=|[>\'"]))*.)[\'"]?/i';
			preg_match_all($regex, $tagMatches[3][$i], $attributes);
			$element = $tagMatches[2][$i];
			$data = $options = array();
			for ($j = 0, $jj = count($attributes[0]); $j < $jj; $j++) {
				if (in_array($attributes[1][$j], $validOptions)) {
					$options = Hash::merge($options, array($attributes[1][$j] => $attributes[2][$j]));
				} else {
					$data[$attributes[1][$j]] = $attributes[2][$j];
				}
			}
			if (!empty($this->_View->viewVars['block'])) {
				$data['block'] = $this->_View->viewVars['block'];
			}
			$content = str_replace($tagMatches[0][$i], $this->_View->element($element, $data, $options), $content);
		}
		return $content;
	}

/**
 * Hook
 *
 * Used for calling hook methods from other HookHelpers
 *
 * @param string $methodName
 * @return string
 */
	public function hook($methodName) {
		$output = '';
		foreach ($this->_View->helpers as $helper => $settings) {
			if (!is_string($helper) || in_array($helper, $this->coreHelpers)) {
				continue;
			}
			list(, $helper) = pluginSplit($helper);
			if (isset($this->_View->{$helper}) && method_exists($this->_View->{$helper}, $methodName)) {
				$output .= $this->_View->{$helper}->$methodName();
			}
		}
		return $output;
	}

/**
 * Gets a value of view variables based on path
 *
 * @param string $name Variable name to retrieve from View::viewVars
 * @param string $path Extraction path following the Hash path syntax
 * @return array
 */
	public function valueOf($name, $path, $options = array()) {
		if (!isset($this->_View->viewVars[$name])) {
			$this->log(sprintf('Invalid viewVars "%s"', $name));
			return array();
		}
		$result = Hash::extract($this->_View->viewVars[$name], $path);
		$result = isset($result[0]) ? $result[0] : $result;
		return $result;
	}

/**
 * Compute default options for snippet()
 *
 * @param string $type Type
 * @return array Array of options
 */
	private function __snippetDefaults($type) {
		$varName = strtolower(Inflector::pluralize($type)) . '_for_layout';
		$modelAlias = Inflector::classify($type);
		$checkField = 'alias';
		$valueField = 'body';
		$filter = true;
		$format = '{s}.{n}.%s[%s=%s].%s';
		switch ($type) {
			case 'type':
				$valueField = 'description';
				$format = '{s}.%s[%s=%s].%s';
			break;
			case 'vocabulary':
				$valueField = 'title';
				$format = '{s}.%s[%s=%s].%s';
			break;
			case 'menu':
				$valueField = 'title';
				$format = '{s}.%s[%s=%s].%s';
			break;
			case 'node':
				$checkField = 'slug';
			break;
		}
		return compact('checkField', 'filter', 'format', 'modelAlias', 'valueField', 'varName');
	}

/**
 * Simple method to retrieve value from view variables using Hash path format
 *
 * Example:
 *
 *   // display the 'about' block
 *   echo $this->Layout->snippet('about');
 *   // display the 'hello world' node
 *   echo $this->Layout->snippet('hello-world', 'node');
 *
 * You can customize the return value by supplying a custom path:
 *   // display the 'main' menu array
 *   echo $this->Layout->snippet('main', 'menu', array(
 *       'format' => '{s}.%s[%s=%s].%s',
 *   ));
 *   // display the 'main' menu description field
 *   echo $this->Layout->snippet('main', 'menu', array(
 *       'valueField' => 'description',
 *       'format' => '{s}.%s[%s=%s].%s',
 *   ));
 *
 * Options:
 * - checkField Field name that will be checked against $name
 * - filter Filter view data. Defaults to true
 * - format Hash path format
 * - modelAlias Model alias
 * - valueField Field name that will be returned if data is found
 * - varName Variable name as it is stored in viewVars
 *
 * @param string $name Identifier
 * @param string $type String of `block`, `nodes`, `node`
 * @param array $options Options array
 * @return string
 */
	public function snippet($name, $type = 'block', $options = array()) {
		$options = array_merge($this->__snippetDefaults($type), $options);
		extract($options);
		$path = sprintf($format, $modelAlias, $checkField, $name, $valueField);
		$result = $this->valueOf($options['varName'], $path);
		if ($result) {
			if ($options['filter'] === true && is_string($result)) {
				return $this->filter($result, $options);
			} else {
				return $result;
			}
		} else {
			return null;
		}
	}

}
Back to Top