basercms /baser/plugins/blog/models/blog_post.php

Language PHP Lines 584
MD5 Hash 8b7ef3ef357f8f2abae31ba2edeb5558
Repository https://github.com/hashing/basercms.git View Raw File
  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
<?php
/* SVN FILE: $Id$ */
/**
 * 記事モデル
 *
 * PHP versions 5
 *
 * baserCMS :  Based Website Development Project <http://basercms.net>
 * Copyright 2008 - 2012, baserCMS Users Community <http://sites.google.com/site/baserusers/>
 *
 * @copyright		Copyright 2008 - 2012, baserCMS Users Community
 * @link			http://basercms.net baserCMS Project
 * @package			baser.plugins.blog.models
 * @since			baserCMS v 0.1.0
 * @version			$Revision$
 * @modifiedby		$LastChangedBy$
 * @lastmodified	$Date$
 * @license			http://basercms.net/license/index.html
 */
/**
 * Include files
 */
/**
 * 記事モデル
 *
 * @package baser.plugins.blog.models
 */
class BlogPost extends BlogAppModel {
/**
 * クラス名
 *
 * @var string
 * @access public
 */
	var $name = 'BlogPost';
/**
 * ビヘイビア
 *
 * @var array
 * @access public
 */
	var $actsAs = array('BcContentsManager', 'BcCache');
/**
 * belongsTo
 *
 * @var array
 * @access public
 */
	var $belongsTo = array(
			'BlogCategory' =>   array(  'className'=>'Blog.BlogCategory',
							'foreignKey'=>'blog_category_id'),
			'User' =>           array(  'className'=>'User',
							'foreignKey'=>'user_id'),
			'BlogContent' =>    array(  'className'=>'Blog.BlogContent',
							'foreignKey'=>'blog_content_id')
	);
/**
 * hasMany
 *
 * @var array
 * @access public
 */
	var $hasMany = array('BlogComment'=>
			array('className'=>'Blog.BlogComment',
							'order'=>'created',
							'foreignKey'=>'blog_post_id',
							'dependent'=>true,
							'exclusive'=>false,
							'finderQuery'=>''));
/**
 * HABTM
 * 
 * @var array
 * @access public
 */
	var $hasAndBelongsToMany = array(
			'BlogTag' => array(
				'className'				=> 'Blog.BlogTag',
				'joinTable'				=> 'blog_posts_blog_tags',
				'foreignKey'			=> 'blog_post_id',
				'associationForeignKey'	=> 'blog_tag_id',
				'conditions'			=> '',
				'order'					=> '',
				'limit'					=> '',
				'unique'				=> true,
				'finderQuery'			=> '',
				'deleteQuery'			=> ''
		));
/**
 * validate
 *
 * @var array
 * @access public
 */
	var $validate = array(
		'name' => array(
			array(  'rule'		=> array('notEmpty'),
					'message'	=> 'タイトルを入力してください。',
					'required'	=> true),
			array(	'rule'		=> array('maxLength', 255),
					'message'	=> 'タイトルは255文字以内で入力してください。')
		),
		'posts_date' => array(
			array(	'rule'		=> array('notEmpty'),
					'message'	=> '投稿日を入力してください。',
					'required'	=> true)
		),
		'user_id' => array(
			array(	'rule'		=> array('notEmpty'),
					'message'	=> '投稿者を選択してください。')
		)
	);
/**
 * 初期値を取得する
 *
 * @return array $authUser 初期値データ
 * @access public
 */
	function getDefaultValue($authUser) {
		
		$data[$this->name]['user_id'] = $authUser['User']['id'];
		$data[$this->name]['posts_date'] = date('Y/m/d H:i:s');
		$data[$this->name]['status'] = 0;
		return $data;
		
	}
/**
 * ブログの月別一覧を取得する
 *
 * @param array $blogContentId
 * @param array $options
 * @return array 月別リストデータ
 * @access public
 */
	function getPostedDates($blogContentId, $options) {

		$options = array_merge(array(
			'category'	=> false,
			'limit'		=> false, 
			'viewCount'	=> false, 
			'type'		=> 'month'	// month Or year
		), $options);
		
		extract($options);
		$conditions = array('BlogPost.blog_content_id'=>$blogContentId);
		$conditions = am($conditions, $this->getConditionAllowPublish());
		// TODO CSVDBではGROUP BYが実装されていない為、取り急ぎPHPで処理
		/*$dates = $this->find('all',array('fields'=>array('YEAR(posts_date) as year','MONTH(posts_date) as month','COUNT(id)' as count),
                                          $conditions,
                                          'group'=>array('YEAR(posts_date)','MONTH(posts_date)'))));*/
		
		if($category) {
			$recursive = 1;
			$this->unbindModel(array(
				'belongsTo'				=> array('User', 'BlogContent'),
				'hasAndBelongsToMany'	=> array('BlogTag')
			));
		} else {
			$recursive = -1;
		}
		
		// 毎秒抽出条件が違うのでキャッシュしない
		$posts = $this->find('all',array(
			'conditions'=> $conditions, 
			'order'		=> 'BlogPost.posts_date DESC', 
			'recursive' => $recursive,
			'cache'		=> false
		));

		$dates = array();
		$counter = 0;

		foreach($posts as $post) {
			
			$exists = false;
			$_date = array();
			$year = date('Y',strtotime($post['BlogPost']['posts_date']));
			$month = date('m',strtotime($post['BlogPost']['posts_date']));
			$categoryId = $post['BlogPost']['blog_category_id'];
			
			foreach($dates as $key => $date) {
				
				if(!$category || $date['BlogCategory']['id'] == $categoryId) {
					if($type == 'year' && $date['year'] == $year) {
						$exists = true;
					}
					if($type == 'month' && $date['year'] == $year && $date['month'] == $month) {				
						$exists = true;
					}
				}
				
				if($exists) {				
					if($viewCount) {
						$dates[$key]['count']++;
					}
					break;
				}
				
			}
			
			if(!$exists) {
				if($type == 'year') {
					$_date['year'] = $year;
				} elseif($type == 'month') {
					$_date['year'] = $year;
					$_date['month'] = $month;
				}
				if($category) {
					$_date['BlogCategory']['id'] = $categoryId;
					$_date['BlogCategory']['name'] = $post['BlogCategory']['name'];
					$_date['BlogCategory']['title'] = $post['BlogCategory']['title'];
				}
				if($viewCount) {
					$_date['count'] = 1;
				}
				$dates[] = $_date;
				$counter++;
			}
			
			if($limit !== false && $limit <= $counter) {
				break;
			}
			
		}
		
		return $dates;

	}
/**
 * カレンダー用に指定した月で記事の投稿がある日付のリストを取得する
 * 
 * @param int $contentId
 * @param int $year
 * @param int $month
 * @return array
 * @access public
 */
	function getEntryDates($contentId,$year,$month) {

		$entryDates = $this->find('all', array(
			'fields'	=> array('BlogPost.posts_date'),
			'conditions'=> $this->_getEntryDatesConditions($contentId,$year,$month), 
			'recursive'	=> -1,
			'cache'		=> false
		));
		$entryDates = Set::extract('/BlogPost/posts_date',$entryDates);
		foreach($entryDates as $key => $entryDate) {
			$entryDates[$key] = date('Y-m-d',strtotime($entryDate));
		}
		return $entryDates;

	}
/**
 * 指定した月の記事が存在するかチェックする
 *
 * @param	int $contentId
 * @param	int $year
 * @param	int $month
 * @return	boolean
 */
	function existsEntry($contentId,$year,$month) {
		
		if($this->find('first', array(
			'fields'	=> array('BlogPost.id'),
			'conditions'=> $this->_getEntryDatesConditions($contentId,$year,$month), 
			'recursive'	=> -1,
			'cache'		=> false
		))) {
			return true;
		} else {
			return false;
		}
		
	}
/**
 * 年月を指定した検索条件を生成
 * データベースごとに構文が違う
 * 
 * @param int $contentId
 * @param int $year
 * @param int $month
 * @return string
 * @access private
 */
	function _getEntryDatesConditions($contentId,$year,$month) {

		$dbConfig = new DATABASE_CONFIG();
		$driver = preg_replace('/^bc_/', '', $dbConfig->plugin['driver']);

		switch($driver) {
			case 'mysql':
			case 'csv':
				if(!empty($year)) {
					$conditions["YEAR(`BlogPost`.`posts_date`)"] = $year;
				}else {
					$conditions["YEAR(`BlogPost`.`posts_date`)"] = date('Y');
				}
				if(!empty($month)) {
					$conditions["MONTH(`BlogPost`.`posts_date`)"] = $month;
				}else {
					$conditions["MONTH(`BlogPost`.`posts_date`)"] = date('m');
				}
				break;

			case 'postgres':
				if(!empty($year)) {
					$conditions["date_part('year', \"BlogPost\".\"posts_date\")"] = $year;
				}else {
					$conditions["date_part('year', \"BlogPost\".\"posts_date\")"] = date('Y');
				}
				if(!empty($month)) {
					$conditions["date_part('month', \"BlogPost\".\"posts_date\")"] = $month;
				}else {
					$conditions["date_part('month', \"BlogPost\".\"posts_date\")"] = date('m');
				}
				break;

			case 'sqlite':
			case 'sqlite3':
				if(!empty($year)) {
					$conditions["strftime('%Y',BlogPost.posts_date)"] = $year;
				}else {
					$conditions["strftime('%Y',BlogPost.posts_date)"] = date('Y');
				}
				if(!empty($month)) {
					$conditions["strftime('%m',BlogPost.posts_date)"] = sprintf('%02d',$month);
				}else {
					$conditions["strftime('%m',BlogPost.posts_date)"] = date('m');
				}
				break;

		}

		$conditions = am($conditions,  array('BlogPost.blog_content_id'=>$contentId), $this->getConditionAllowPublish());
		return $conditions;
		
	}
/**
 * コントロールソースを取得する
 *
 * @param string $field フィールド名
 * @param	array	$options
 * @return	array	コントロールソース
 * @access	public
 */
	function getControlSource($field, $options = array()) {

		switch ($field) {
			case 'blog_category_id':
				
				extract($options);
				$catOption = array('blogContentId' => $blogContentId);
				$isSuperAdmin = false;

				if(!empty($userGroupId)) {
					
					if(!isset($blogCategoryId)) {
						$blogCategoryId = '';
					}

					if($userGroupId == 1) {
						$isSuperAdmin = true;
					}

					// 現在のページが編集不可の場合、現在表示しているカテゴリも取得する
					if(!$postEditable && $blogCategoryId) {
						$catOption['conditions'] = array('OR' => array('BlogCategory.id' => $blogCategoryId));
					}

					// super admin でない場合は、管理許可のあるカテゴリのみ取得
					if(!$isSuperAdmin) {
						$catOption['ownerId'] = $userGroupId;
					}
				
					if($postEditable && !$rootEditable && !$isSuperAdmin) {
						unset($empty);
					}
				
				}
				
				$categories = $this->BlogCategory->getControlSource('parent_id', $catOption);
				
				// 「指定しない」追加
				if(isset($empty)) {
					if($categories) {
						$categories = array('' => $empty) + $categories;
					} else {
						$categories = array('' => $empty);
					}
				}
				
				$controlSources['blog_category_id'] = $categories;
				
				break;
			case 'user_id':
				$controlSources['user_id'] = $this->User->getUserList($options);
				break;
			case 'blog_tag_id':
				$controlSources['blog_tag_id'] = $this->BlogTag->find('list');
				break;
		}
		if(isset($controlSources[$field])) {
			return $controlSources[$field];
		}else {
			return false;
		}

	}
/**
 * 公開状態を取得する
 *
 * @param array データリスト
 * @return boolean 公開状態
 * @access public
 */
	function allowPublish($data){

		if(isset($data['BlogPost'])){
			$data = $data['BlogPost'];
		}

		$allowPublish = (int)$data['status'];

		if($data['publish_begin'] == '0000-00-00 00:00:00') {
			$data['publish_begin'] = NULL;
		}
		if($data['publish_end'] == '0000-00-00 00:00:00') {
			$data['publish_end'] = NULL;
		}

		// 期限を設定している場合に条件に該当しない場合は強制的に非公開とする
		if(($data['publish_begin'] && $data['publish_begin'] >= date('Y-m-d H:i:s')) ||
				($data['publish_end'] && $data['publish_end'] <= date('Y-m-d H:i:s'))){
			$allowPublish = false;
		}

		return $allowPublish;

	}
/**
 * 公開済の conditions を取得
 * 
 * @return array
 * @access public 
 */
	function getConditionAllowPublish() {
		
		$conditions[$this->alias.'.status'] = true;
		$conditions[] = array('or'=> array(array($this->alias.'.publish_begin <=' => date('Y-m-d H:i:s')),
										array($this->alias.'.publish_begin' => NULL),
										array($this->alias.'.publish_begin' => '0000-00-00 00:00:00')));
		$conditions[] = array('or'=> array(array($this->alias.'.publish_end >=' => date('Y-m-d H:i:s')),
										array($this->alias.'.publish_end' => NULL),
										array($this->alias.'.publish_end' => '0000-00-00 00:00:00')));
		return $conditions;
		
	}
/**
 * 公開状態の記事を取得する
 *
 * @param array $options
 * @return array
 * @access public
 */
	function getPublishes ($options) {

		if(!empty($options['conditions'])) {
			$options['conditions'] = array_merge($this->getConditionAllowPublish(), $options['conditions']);
		} else {
			$options['conditions'] = $this->getConditionAllowPublish();
		}
		// 毎秒抽出条件が違うのでキャッシュしない
		$options['cache'] = false;
		$datas = $this->find('all', $options);
		return $datas;

	}
/**
 * afterSave
 *
 * @param boolean $created
 * @return boolean
 * @access public
 */
	function afterSave($created) {

		// 検索用テーブルへの登録・削除
		if(!$this->data['BlogPost']['exclude_search']) {
			$this->saveContent($this->createContent($this->data));
		} else {
			$this->deleteContent($this->data['BlogPost']['id']);
		}
		
	}
/**
 * 検索用データを生成する
 *
 * @param array $data
 * @return array
 * @access public
 */
	function createContent($data) {

		if(isset($data['BlogPost'])) {
			$data = $data['BlogPost'];
		}

		$_data = array();
		$_data['Content']['type'] = 'ブログ';
		$_data['Content']['model_id'] = $this->id;
		$_data['Content']['category'] = '';
		if(!empty($data['blog_category_id'])) {
			$BlogCategory = ClassRegistry::init('Blog.BlogCategory');
			$categoryPath = $BlogCategory->getPath($data['blog_category_id'], array('title'));
			if($categoryPath) {
				$_data['Content']['category'] = $categoryPath[0]['BlogCategory']['title'];
			}
		}
		$_data['Content']['title'] = $data['name'];
		$_data['Content']['detail'] = $data['content'].' '.$data['detail'];
		$PluginContent = ClassRegistry::init('PluginContent');
		$_data['Content']['url'] = '/'.$PluginContent->field('name', array('PluginContent.content_id' => $data['blog_content_id'], 'plugin' => 'blog')).'/archives/'.$data['no'];
		$_data['Content']['status'] = $this->allowPublish($data);

		return $_data;

	}
/**
 * beforeDelete
 *
 * @return boolean
 * @access public
 */
	function beforeDelete() {

		return $this->deleteContent($this->id);

	}
/**
 * コピーする
 * 
 * @param int $id
 * @param array $data
 * @return mixed page Or false
 */
	function copy($id = null, $data = array()) {
		
		$data = array();
		if($id) {
			$data = $this->find('first', array('conditions' => array('BlogPost.id' => $id), 'recursive' => 1));
		}
		if(!empty($_SESSION['Auth']['User'])) {
			$data['BlogPost']['user_id'] = $_SESSION['Auth']['User']['id'];
		}
		
		$data['BlogPost']['name'] .= '_copy';
		$data['BlogPost']['no'] = $this->getMax('no', array('BlogPost.blog_content_id' => $data['BlogPost']['blog_content_id']))+1;
		$data['BlogPost']['status'] = false;
		
		unset($data['BlogPost']['id']);
		unset($data['BlogPost']['created']);
		unset($data['BlogPost']['modified']);
		if(!empty($data['BlogTag'])) {
			foreach($data['BlogTag'] as $key => $tag) {
				$data['BlogTag'][$key] = $tag['id'];
			}
		}
		
		$this->create($data);
		$result = $this->save();
		if($result) {
			return $result;
		} else {
			if(isset($this->validationErrors['name'])) {
				return $this->copy(null, $data);
			} else {
				return false;
			}
		}
		
	}
	
}
?>
Back to Top