Content::getLayoutFiles()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/**
4
 * This is the model class for table "content".
5
 *
6
 * The followings are the available columns in table 'content':
7
 * @property integer $id
8
 * @property integer $vid
9
 * @property integer $author_id
10
 * @property string $title
11
 * @property string $content
12
 * @property string $except
13
 * @property integer $status
14
 * @property integer $commentable
15
 * @property integer $category_id
16
 * @property integer $type_id
17
 * @property string $password
18
 * @property integer $like_count
19
 * @property string $slug
20
 * @property string $published
21
 * @property string $created
22
 * @property string $updated
23
 *
24
 * The followings are the available model relations:
25
 * @property Comments[] $comments
26
 * @property Users $author
27
 * @property Content $parent
28
 * @property Content[] $contents
29
 * @property Categories $category
30
 * @property ContentMetadata[] $contentMetadatas
31
 */
32
class Content extends CiiModel
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
33
{
34
	public $pageSize = 9;
35
36
	public $viewFile = 'blog';
37
38
	public $layoutFile = 'blog';
39
40
	public $autosavedata = false;
41
42
	/**
43
	 * Returns the static model of the specified AR class.
44
	 * @param string $className active record class name.
45
	 * @return Content the static model class
46
	 */
47
	public static function model($className=__CLASS__)
48
	{
49
		return parent::model($className);
50
	}
51
52
	/**
53
	 * @return string the associated database table name
54
	 */
55
	public function tableName()
56
	{
57
		return 'content';
58
	}
59
60
	/**
61
	 * @return string[] primary key of the table
62
	 **/
63
	public function primaryKey()
64
	{
65
		return array('id');
66
	}
67
68
	/**
69
	 * @return array validation rules for model attributes.
70
	 */
71
	public function rules()
72
	{
73
		// NOTE: you should only define rules for those attributes that
74
		// will receive user inputs.
75
		return array(
76
			array('vid, author_id, title, content, status, commentable, category_id', 'required'),
77
			array('vid, author_id, status, commentable, category_id, type_id, like_count', 'numerical', 'integerOnly'=>true),
78
			array('title, password, slug', 'length', 'max'=>150),
79
			// The following rule is used by search().
80
			array('id, vid, author_id, title, content, excerpt, status, commentable, category_id, type_id, password, like_count, slug, published, created, updated', 'safe', 'on'=>'search'),
81
		);
82
	}
83
84
	/**
85
	 * @return array relational rules.
86
	 */
87
	public function relations()
88
	{
89
		// NOTE: you may need to adjust the relation name and the related
90
		// class name for the relations automatically generated below.
91
		return array(
92
			'comments' 	=> array(self::HAS_MANY, 'Comments', 'content_id'),
93
			'author' 	=> array(self::BELONGS_TO, 'Users', 'author_id'),
94
			'category' 	=> array(self::BELONGS_TO, 'Categories', 'category_id'),
95
			'metadata' 	=> array(self::HAS_MANY, 'ContentMetadata', 'content_id'),
96
		);
97
	}
98
99
	/**
100
	 * @return array customized attribute labels (name=>label)
101
	 */
102
	public function attributeLabels()
103
	{
104
		return array(
105
			'id' 			=> Yii::t('ciims.models.Content', 'ID'),
106
			'vid' 			=> Yii::t('ciims.models.Content', 'Version'),
107
			'author_id' 	=> Yii::t('ciims.models.Content', 'Author'),
108
			'title' 		=> Yii::t('ciims.models.Content', 'Title'),
109
			'content' 		=> Yii::t('ciims.models.Content', 'Content'),
110
			'excerpt' 		=> Yii::t('ciims.models.Content', 'excerpt'),
111
			'status' 		=> Yii::t('ciims.models.Content', 'Status'),
112
			'commentable' 	=> Yii::t('ciims.models.Content', 'Commentable'),
113
			'category_id' 	=> Yii::t('ciims.models.Content', 'Category'),
114
			'type_id' 		=> Yii::t('ciims.models.Content', 'Type'),
115
			'password' 		=> Yii::t('ciims.models.Content', 'Password'),
116
			'like_count' 	=> Yii::t('ciims.models.Content', 'Likes'),
117
			'tags' 			=> Yii::t('ciims.models.Content', 'Tags'),
118
			'slug' 			=> Yii::t('ciims.models.Content', 'Slug'),
119
			'published' 	=> Yii::t('ciims.models.Content', 'Published'),
120
			'created' 		=> Yii::t('ciims.models.Content', 'Created'),
121
			'updated' 		=> Yii::t('ciims.models.Content', 'Updated'),
122
		);
123
	}
124
125
	/**
126
	 * Returns a safe output to the theme
127
	 * This includes setting nofollow tags on links, forcing them to open in new windows, and safely encoding the text
128
	 * @return string
129
	 */
130
	public function getSafeOutput()
131
	{
132
		$md = new CMarkdownParser;
133
		$dom = new DOMDocument();
134
		$dom->loadHtml('<?xml encoding="UTF-8">'.$md->safeTransform($this->content));
135
		$x = new DOMXPath($dom);
136
137
		foreach ($x->query('//a') as $node)
138
		{
139
			$element = $node->getAttribute('href');
140
			if (isset($element[0]) && $element[0] !== "/")
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal / does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
141
			{
142
				$node->setAttribute('rel', 'nofollow');
143
				$node->setAttribute('target', '_blank');
144
			}
145
		}
146
147
		return $md->safeTransform($dom->saveHtml());
148
	}
149
150
	public function getExtract()
151
	{
152
		Yii::log(Yii::t('ciims.models.Content', 'Use of property "extract" is deprecated in favor of "excerpt"'), 'system.db.ar.CActiveRecord', 'info');
153
		return $this->excerpt;
154
	}
155
156
	/**
157
	 * Correctly retrieves the number of likes for a particular post.
158
	 *
159
	 * This was added to address an issue with the like count changing if an article was updated
160
	 * @return int    The number of likes for this post
161
	 */
162
163
	public function getLikeCount()
164
	{
165
		$meta = ContentMetadata::model()->findByAttributes(array('content_id' => $this->id, 'key' => 'likes'));
166
		if ($meta === NULL)
167
			return 0;
168
169
		return $meta->value;
170
	}
171
172
	/**
173
	 * Gets keyword tags for this entry
174
	 * @return array
175
	 */
176
	public function getTags()
177
	{
178
		$tags = ContentMetadata::model()->findByAttributes(array('content_id' => $this->id, 'key' => 'keywords'));
179
		return $tags === NULL ? array() : json_decode($tags->value, true);
180
	}
181
182
	/**
183
	 * Adds a tag to the model
184
	 * @param string $tag	The tag to add
185
	 * @return bool			If the insert was successful or not
186
	 */
187
	public function addTag($tag)
188
	{
189
		$tags = $this->tags;
190
		if (in_array($tag, $tags)  || $tag == "")
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
191
			return false;
192
193
		$tags[] = $tag;
194
		$tags = json_encode($tags);
195
		$meta = $this->getPrototype('ContentMetadata', array('content_id' => $this->id, 'key' => 'keywords'));
196
197
		$meta->value = $tags;
198
		return $meta->save();
199
	}
200
201
	/**
202
	 * Removes a tag from the model
203
	 * @param string $tag	The tag to remove
204
	 * @return bool			If the removal was successful
205
	 */
206
	public function removeTag($tag)
207
	{
208
		$tags = $this->tags;
209
		if (!in_array($tag, $tags) || $tag == "")
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
210
			return false;
211
212
		$key = array_search($tag, $tags);
213
		unset($tags[$key]);
214
		$tags = json_encode($tags);
215
216
		$meta = $this->getPrototype('ContentMetadata', array('content_id' => $this->id, 'key' => 'keywords'));
217
		$meta->value = $tags;
218
		return $meta->save();
219
	}
220
221
	/**
222
	 * Provides a base criteria for status, uniqueness, and published states
223
	 * @return CDBCriteria
224
	 */
225
	public function getBaseCriteria()
226
	{
227
		$criteria = new CDbCriteria();
228
		return $criteria->addCondition("vid=(SELECT MAX(vid) FROM content WHERE id=t.id)")
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal vid=(SELECT MAX(vid) FROM content WHERE id=t.id) does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
229
					    ->addCondition('status = 1')
230
					    ->addCondition('UNIX_TIMESTAMP() >= published');
231
	}	
232
233
	/**
234
	 * Returns the appropriate status' depending up the user's role
235
	 * @return string[]
236
	 */
237
	public function getStatuses()
238
	{
239
240
		if (Yii::app()->user->role == 5 || Yii::app()->user->role == 7)
241
			return array(0 => Yii::t('ciims.models.Content', 'Draft'));
242
243
		return array(
244
			1 => Yii::t('ciims.models.Content', 'Published'),
245
			2 => Yii::t('ciims.models.Content', 'Ready for Review'),
246
			0 => Yii::t('ciims.models.Content', 'Draft')
247
		);
248
	}
249
250
	/**
251
	 * Determines if an article is published or not
252
	 * @return boolean
253
	 */
254
	public function isPublished()
255
	{
256
		return ($this->status == 1 && ($this->published <= time())) ? true : false;
257
	}
258
259
	/**
260
	 * Determines if a given articled is scheduled or not
261
	 * @return boolean
262
	 */
263
	public function isScheduled()
264
	{
265
		return ($this->status == 1 && ($this->published > time())) ? true : false;
266
	}
267
268
	/**
269
	 * Gets a flattened list of keyword tags for jQuery.tag.js
270
	 * @return string
271
	 */
272
	public function getTagsFlat()
273
	{
274
		return implode(',', $this->tags);
275
	}
276
277
	/**
278
	 * Retrieves the layout used from Metadata
279
	 * We cache this to speed up the viewfile
280
	 */
281
	public function getLayout()
282
	{
283
		$model  = ContentMetadata::model()->findByAttributes(array('content_id' => $this->id, 'key' => 'layout'));
284
		return $model === NULL ? 'blog' : $model->value;
285
	}
286
287
	/**
288
	 * Sets the layout
289
	 * @param string $data  the layout file
290
	 * @return boolean
291
	 */
292
	public function setLayout($data)
293
	{
294
		$meta = $this->getPrototype('ContentMetadata', array('content_id' => $this->id, 'key' => 'layout'));
295
		$meta->value = $data;
296
		return $meta->save();
297
	}
298
299
	/**
300
	 * Sets the view
301
	 * @param string $data  The view file
302
	 * @return boolean
303
	 */
304
	public function setView($data)
305
	{
306
		$meta = $this->getPrototype('ContentMetadata', array('content_id' => $this->id, 'key' => 'view'));
307
		$meta->value = $data;
308
		return $meta->save();
309
	}
310
311
	/**
312
	 * Retrieves the viewfile used from Metadata
313
	 * We cache this to speed up the viewfile
314
	 */
315
	public function getView()
316
	{
317
		$model  = ContentMetadata::model()->findByAttributes(array('content_id' => $this->id, 'key' => 'view'));
318
		return $model === NULL ? 'blog' : $model->value;
319
	}
320
321
	/**
322
	 * Updates the like_count after finding new data
323
	 */
324
	protected function afterFind()
325
	{
326
		parent::afterFind();
327
		$this->like_count = $this->getLikeCount();
328
	}
329
330
	/**
331
	 * Retrieves a list of models based on the current search/filter conditions.
332
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
333
	 */
334
	public function search()
335
	{
336
		$criteria=new CDbCriteria;
337
338
		$criteria->compare('id',$this->id);
339
		$criteria->compare('title',$this->title,true);
340
		$criteria->compare('slug',$this->slug,true);
341
		$criteria->compare('author_id',$this->author_id,true);
342
		$criteria->compare('category_id',$this->category_id,true);
343
		$criteria->compare('content',$this->content,true);
344
		$criteria->compare('password', $this->password, true);
345
		$criteria->compare('created',$this->created,true);
346
		$criteria->compare('updated',$this->updated,true);
347
		$criteria->compare('status', $this->status, true);
348
349
		// Handle publishing with a true/false value simply to do this calculation. Otherwise default to compare
350
		if (is_bool($this->published))
351
		{
352
			if ($this->published)
353
				$criteria->addCondition('published <= UNIX_TIMESTAMP()');
354
			else
355
				$criteria->addCondition('published > UNIX_TIMESTAMP()');
356
		}
357
		else
358
			$criteria->compare('published', $this->published,true);
359
		$criteria->addCondition("vid=(SELECT MAX(vid) FROM content WHERE id=t.id)");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal vid=(SELECT MAX(vid) FROM content WHERE id=t.id) does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
360
361
		// TODO: Figure out how to restore CActiveDataProvidor by getCommentCount
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
362
		return new CActiveDataProvider($this, array(
363
			'criteria' => $criteria,
364
			'sort' => array(
365
				'defaultOrder' => 'published DESC'
366
			),
367
			'pagination' => array(
368
				'pageSize' => $this->pageSize
369
			)
370
		));
371
	}
372
373
	/**
374
	 * Finds all active records with the specified primary keys.
375
	 * Overloaded to support composite primary keys. For our content, we want to find the latest version of that primary key, defined as MAX(vid) WHERE id = pk
376
	 * See {@link find()} for detailed explanation about $condition and $params.
377
	 * @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
378
	 * @param mixed $condition query condition or criteria.
379
	 * @param array $params parameters to be bound to an SQL statement.
380
	 * @return array the records found. An empty array is returned if none is found.
381
	 */
382
	public function findByPk($pk, $condition='', $params=array())
383
	{
384
		// If we do not supply a condition or parameters, use our overwritten method
385
		if ($condition == '' && empty($params) && $pk != null)
386
		{
387
			if (!is_numeric($pk))
388
				throw new CHttpException(400, Yii::t('ciims.models.Content', 'The content ID provided was invalid.'));
389
				
390
			$criteria = new CDbCriteria;
391
			$criteria->addCondition("t.id=:pk");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal t.id=:pk does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
392
			$criteria->addCondition("vid=(SELECT MAX(vid) FROM content WHERE id=:pk)");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal vid=(SELECT MAX(vid) FROM content WHERE id=:pk) does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
393
			$criteria->params = array(
394
				':pk' => $pk
395
			);
396
			return $this->query($criteria);
397
		}
398
399
		return parent::findByPk($pk, $condition, $params);
400
	}
401
402
	/**
403
	 * Lists all revisions in the database for a givenid
404
	 * @param  int $id [description]
405
	 * @return array
406
	 */
407
	public function findRevisions($id)
408
	{
409
		if (!is_numeric($id))
410
			throw new CHttpException(400, Yii::t('ciims.models.Content', 'The content ID provided was invalid.'));
411
				
412
		$criteria = new CDbCriteria;
413
		$criteria->addCondition("id=:id");
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal id=:id does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
414
		$criteria->params = array(
415
			':id' => $id
416
		);
417
		$criteria->order = 'vid DESC';
418
419
		return $this->query($criteria, true);
420
	}
421
422
	/**
423
	 * BeforeValidate
424
	 * @see CActiveRecord::beforeValidate
425
	 */
426
	public function beforeValidate()
427
	{
428
		// Allow publication times to be set automatically
429
		if (empty($this->published))
430
			$this->published = time();
431
432
		if (strlen($this->excerpt) == 0)
433
			$this->excerpt = $this->myTruncate($this->content, 250, '.', '');
434
435
		return parent::beforeValidate();
436
	}
437
438
	/**
439
	 * Saves a prototype copy of the model so that we can get an id back to work with
440
	 * @return boolean 	$model->save(false) without any validation rules
441
	 */
442
	public function savePrototype($author_id)
443
	{
444
		$this->title = '';
445
		$this->content = '';
446
		$this->excerpt = '';
447
		$this->commentable = 1;
448
		$this->status = 0;
449
		$this->category_id = 1;
450
		$this->type_id = 2;
451
		$this->password = null;
452
		$this->created = time();
453
		$this->updated = time();
454
		$this->published = time();
455
		$this->vid = 1;
456
		$this->slug = "";
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
457
		$this->author_id = $author_id;
458
459
		// TODO: Why doesn't Yii return the PK id field? But it does return VID? AutoIncriment bug?
0 ignored issues
show
Coding Style Best Practice introduced by
Comments for TODO tasks are often forgotten in the code; it might be better to use a dedicated issue tracker.
Loading history...
460
		if ($this->save(false))
461
		{
462
			$data = Content::model()->findByAttributes(array('created' => $this->created));
463
			$this->id = $data->id;
464
			return true;
465
		}
466
467
		return false;
468
	}
469
470
	/**
471
	 * BeforeSave
472
	 * Clears caches for rebuilding, creates the end slug that we are going to use
473
	 * @see CActiveRecord::beforeSave();
474
	 */
475
	public function beforeSave()
476
	{
477
		$this->slug = $this->verifySlug($this->slug, $this->title);
478
		Yii::app()->cache->delete('CiiMS::Content::list');
479
		Yii::app()->cache->delete('CiiMS::Routes');
480
481
		Yii::app()->cache->set('content-' . $this->id . '-layout', $this->layoutFile);
482
		Yii::app()->cache->set('content-' . $this->id . '-view', $this->viewFile);
483
484
		return parent::beforeSave();
485
	}
486
487
	/**
488
	 * AfterSave
489
	 * Updates the layout and view if necessary
490
	 * @see CActiveRecord::afterSave()
491
	 */
492
	public function afterSave()
493
	{
494
		// Delete the AutoSave document on update
495
		if ($this->isPublished())
496
		{
497
			$autosaveModel = ContentMetadata::model()->findByAttributes(array('content_id' => $this->id, 'key' => 'autosave'));
498
			if ($autosaveModel != NULL)
499
				$autosaveModel->delete();
500
		}
501
502
		return parent::afterSave();
503
	}
504
505
	/**
506
	 * BeforeDelete
507
	 * Clears caches for rebuilding
508
	 * @see CActiveRecord::beforeDelete
509
	 */
510
	public function beforeDelete()
511
	{
512
		Yii::app()->cache->delete('CiiMS::Content::list');
513
		Yii::app()->cache->delete('CiiMS::Routes');
514
		Yii::app()->cache->delete('content-' . $this->id . '-layout');
515
		Yii::app()->cache->delete('content-' . $this->id . '-view');
516
517
		return parent::beforeDelete();
518
	}
519
520
521
	/**
522
	 * Retrieves the available view files under the current theme
523
	 * @return array    A list of files by name
524
	 */
525
	public function getViewFiles($theme=null)
526
	{
527
		return $this->getFiles($theme, 'views.content');
528
	}
529
530
	/**
531
	 * Retrieves the available layouts under the current theme
532
	 * @return array    A list of files by name
533
	 */
534
	public function getLayoutFiles($theme=null)
535
	{
536
		return $this->getFiles($theme, 'views.layouts');
537
	}
538
539
	/**
540
	 * Retrieves view files for a particular path
541
	 * @param  string $theme  The theme to reference
542
	 * @param  string $type   The view type to lookup
543
	 * @return array $files   An array of files
544
	 */
545
	private function getFiles($theme=null, $type='views')
546
	{
547
		if ($theme === null)
548
			$theme = Cii::getConfig('theme', 'default');
549
550
		$folder = $type;
551
552
		if ($type == 'view')
553
			$folder = 'content';
554
555
		$returnFiles = array();
556
557
		if (!file_exists(YiiBase::getPathOfAlias('base.themes.' . $theme)))
558
			$theme = 'default';
559
560
		$files = Yii::app()->cache->get($theme.'-available-' . $type);
561
562
		if ($files === false)
563
		{
564
			$fileHelper = new CFileHelper;
565
			$files = $fileHelper->findFiles(Yii::getPathOfAlias('base.themes.' . $theme .'.' . $folder), array('fileTypes'=>array('php'), 'level'=>0));
566
			Yii::app()->cache->set($theme.'-available-' . $type, $files);
567
		}
568
569
		foreach ($files as $file)
570
		{
571
			$f = str_replace('content', '', str_replace('/', '', str_replace('.php', '', substr( $file, strrpos( $file, '/' ) + 1 ))));
572
573
			if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
574
				$f = trim(substr($f, strrpos($f, '\\') + 1));
575
576
			if (!in_array($f, array('all', 'password', '_post')))
577
				$returnFiles[$f] = $f;
578
		}
579
580
		return $returnFiles;
581
	}
582
583
	/**
584
	 * Fancy truncate function to help clean up our strings for the excerpt
585
	 * @param string $string    The string we want to apply the text to
586
	 * @param int    $limit     How many characters we want to break into
587
	 * @param string $break     Characters we want to break on if possible
588
	 * @param string $pad       The padding we want to apply
589
	 * @return string           Truncated string
590
	 */
591
	private function myTruncate($string, $limit, $break=".", $pad="...")
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal . does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
Coding Style Comprehensibility introduced by
The string literal ... does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
592
	{
593
		// return with no change if string is shorter than $limit
594
		if(strlen($string) <= $limit)
595
			return $string;
596
597
		// is $break present between $limit and the end of the string?
598
		if(false !== ($breakpoint = strpos($string, $break, $limit)))
599
		{
600
			if($breakpoint < strlen($string) - 1)
601
			{
602
				$string = substr($string, 0, $breakpoint) . $pad;
603
			}
604
		}
605
606
		return $string;
607
	}
608
609
	/**
610
	 * checkSlug - Recursive method to verify that the slug can be used
611
	 * This method is purposfuly declared here to so that Content::findByPk is used instead of CiiModel::findByPk
612
	 * @param string $slug - the slug to be checked
613
	 * @param int $id - the numeric id to be appended to the slug if a conflict exists
614
	 * @return string $slug - the final slug to be used
615
	 */
616
	public function checkSlug($slug, $id=NULL)
617
	{
618
		$category = false;
619
620
		// Find the number of items that have the same slug as this one
621
		$count = $this->countByAttributes(array('slug'=>$slug . $id));
622
623
		// Make sure we don't have a collision with a Category
624
		if ($count == 0)
625
		{
626
			$category = true;
627
			$count = Categories::model()->countByAttributes(array('slug'=>$slug . $id));
628
		}
629
630
		// If we found an item that matched, it's possible that it is the current item (or a previous version of it)
631
		// in which case we don't need to alter the slug
632
		if ($count)
633
		{
634
			// Ensures we don't have a collision on category
635
			if ($category)
636
				return $this->checkSlug($slug, ($id === NULL ? 1 : ($id+1)));
637
638
			// Pull the data that matches
639
			$data = $this->findByPk($this->id);
640
641
			// Check the pulled data id to the current item
642
			if ($data !== NULL && $data->id == $this->id && $data->slug == $this->slug)
643
				return $slug;
644
		}
645
646
		if ($count == 0 && !in_array($slug, $this->forbiddenRoutes))
647
			return $slug . $id;
648
		else
649
			return $this->checkSlug($slug, ($id === NULL ? 1 : ($id+1)));
650
	}
651
}
652