-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCourses.php
More file actions
381 lines (326 loc) · 12.2 KB
/
Copy pathCourses.php
File metadata and controls
381 lines (326 loc) · 12.2 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
<?php defined('SYSPATH') or die('No Direct Script Access');
/**
* Модель курсов, имеет поля, соответствующие полям в базе данных и статические методы для получения
* контеста и массива контестов по некоторым признакам.
*
* @author Alexander Menshikov
*/
class Model_Courses extends Model
{
public $id = 0;
public $uri;
public $title;
public $text;
public $description;
public $cover;
public $is_big_cover;
public $course_articles = [];
public $course_authors = [];
public $dt_publish;
public $dt_create;
public $dt_update;
public $is_removed;
public $is_published;
public $marked;
const FEED_PREFIX = 'course';
/**
* Пустой конструктор для модели курсов, если нужно получить курс из хранилища, нужно пользоваться статическими
* методами
*/
public function __construct()
{
}
/**
* Добавляет текущий объект в базу данных и присваивает ему ID.
*
* @throws Kohana_Exception
*/
public function insert()
{
$idAndRowAffected = Dao_Courses::insert()
->set('uri', $this->uri)
->set('title', $this->title)
->set('text', $this->text)
->set('description', $this->description)
->set('cover', $this->cover)
->set('is_big_cover', $this->is_big_cover)
->set('is_removed', $this->is_removed)
->set('is_published', $this->is_published)
->set('marked', $this->marked)
->clearcache('courses_list')
->execute();
if ($idAndRowAffected) {
$course = Dao_Courses::select()
->where('id', '=', $idAndRowAffected)
->limit(1)
->cached(10*Date::MINUTE)
->execute();
$this->fillByRow($course);
}
return $idAndRowAffected;
}
/**
* Заполняет текущий объект строкой из базы данных.
*
* @param $course_row array строка из базы данных с создаваемым курсом
* @return Model_Courses модель, заполненная полями из курса, либо пустая модель, если была передана пустая строка.
*/
private function fillByRow($course_row)
{
if (empty($course_row['id'])) {
return $this;
}
foreach ($course_row as $fieldname => $value) {
if (property_exists($this, $fieldname)) {
$this->$fieldname = $value;
}
}
$this->course_articles = self::getArticles($this->id);
$this->course_authors = $this->getUniqueCourseAuthors();
return $this;
}
/**
* Удаляет курс, представленный в модели.
*
* @param $user_id Number идентификатор пользователя, для проверки прав на удаление курса
*/
public function remove()
{
if ($this->id != 0) {
Dao_Courses::update()->where('id', '=', $this->id)
->set('is_removed', 1)
->set('is_published', 0)
->clearcache('courses_list')
->execute();
// Курс удален
$this->id = 0;
}
}
/**
* Обновляет курс, сохраняя поля модели.
*/
public function update()
{
Dao_Courses::update()->where('id', '=', $this->id)
->set('uri', $this->uri)
->set('title', $this->title)
->set('text', $this->text)
->set('description', $this->description)
->set('cover', $this->cover)
->set('is_big_cover', $this->is_big_cover)
->set('dt_publish', $this->dt_publish)
->set('dt_update', $this->dt_update)
->set('is_removed', $this->is_removed)
->set('is_published', $this->is_published)
->set('marked', $this->marked)
->clearcache($this->id)
->execute();
}
/**
* Добавляет статью к курсу.
* @param $article_id
* @param $course_id
* @return Dao_CoursesArticles::insert
*/
public static function addArticle($article_id, $course_id)
{
$article = Model_Article::get($article_id);
if (!$article->id) {
return false;
}
$course = Model_Courses::get($course_id);
if (!$course->id) {
return false;
}
return Dao_CoursesArticles::insert()
->set('course_id', $course_id)
->set('article_id', $article_id)
->set('article_index', 0)
->execute();
}
/**
* Получить список курсов, в которые включена данная статья.
* @param $article
* @return bool|array
*/
public static function getCoursesByArticleId($article)
{
if (!$article) {
return false;
}
$selectedCourses = Dao_CoursesArticles::select('course_id')
->where('article_id', '=', $article->id)
->execute('course_id');
return $selectedCourses ? array_keys($selectedCourses) : array();
}
/**
* Открепляет статью от курсов.
*
* @param int $article_id
* @param {int|array} $courses_ids - если передан, то открепляет статью от указанных курсов, иначе ото всех
* @return Dao_CoursesArticles:remove
*/
public static function deleteArticles($article_id, $courses_ids = 0)
{
$deleteQuery = Dao_CoursesArticles::delete()->where('article_id', '=', $article_id);
if ($courses_ids === 0) {
return $deleteQuery->execute();
}
return $deleteQuery->where_in('course_id', $courses_ids)->execute();
}
/**
* Возвращает курс из базы данных с указанным идентификатором, иначе возвращает пустой курс с ID=0.
*
* @param int $id идентификатор курса в базе
* @return Model_Courses экземпляр модели с указанным идентификатором и заполненными полями, если найден в базе или
* пустую модель с ID=0.
*/
public static function get($id = 0, $needClearCache = false)
{
$course = Dao_Courses::select()
->where('id', '=', $id)
->limit(1);
if ($needClearCache) {
$course->clearcache($id);
} else {
$course->cached(Date::MINUTE * 5, $id);
}
$course = $course->execute();
$model = new Model_Courses();
return $model->fillByRow($course);
}
/**
* Return
* a) All published courses to output them on Article editing page
* b) All published courses, containing at least one Article to show in feed
*
* @return Model_Courses[] - array of Model_Courses
*/
public static function getActiveCourses($clearCache = false, $excludeCoursesWithoutArticles = false)
{
$active_courses = Model_Courses::getCourses(false, false, !$clearCache ? Date::MINUTE * 5 : null);
$courses_with_articles = array();
if ($excludeCoursesWithoutArticles) {
foreach ($active_courses as $course) {
if (self::getArticles($course->id)) {
$courses_with_articles[] = $course;
}
}
return $courses_with_articles;
} else {
return $active_courses;
}
}
/**
* Получить все неудалённые курсы в порядке убывания ID.
*/
public static function getAllCourses()
{
return Model_Courses::getCourses(true, false);
}
public static function getActiveCoursesNames()
{
$courses = Model_Courses::getActiveCourses();
$list = array();
foreach ($courses as $course) {
$list []= array('id' => $course->id, 'name' => $course->title);
}
return $list;
}
/**
* Получить список курсов с указанными условиями.
*
* @param $add_removed boolean добавлять ли удалённые курсы в получаемый список курсов
* @param $add_not_published boolean
* @return array ModelCourses массив моделей, удовлетворяющих запросу
*/
private static function getCourses($add_not_published = false, $add_removed = false, $cachedTime = null)
{
$coursesQuery = Dao_Courses::select()->limit(200); // TODO add pagination.
if (!$add_removed) {
$coursesQuery->where('is_removed', '=', 0);
}
if (!$add_not_published) {
$coursesQuery->where('is_published', '=', 1);
}
if ($cachedTime) {
$coursesQuery->cached($cachedTime, 'courses_list');
}
$course_rows = $coursesQuery->order_by('dt_create', 'DESC')->execute();
return self::rowsToModels($course_rows);
}
private static function rowsToModels($course_rows)
{
$courses = array();
if (!empty($course_rows)) {
foreach ($course_rows as $course_row) {
$course = new Model_Courses();
$course->fillByRow($course_row);
array_push($courses, $course);
}
}
return $courses;
}
/**
* Get Articles from Course
* @param [int] $courseId - ID of Course
* @return Model_Article[] - Array of Articles
*/
public static function getArticles($course_id)
{
if (!$course_id) {
return false;
}
$articles_ids = Dao_CoursesArticles::select('article_id')->where('course_id', '=', $course_id)->execute();
/** $articleList - empty array. Needs to fill by article ids */
$articleList = array();
/**
* If Course has Articles
*/
if ($articles_ids) {
foreach ($articles_ids as $article) {
$course_article = Model_Article::get($article['article_id']);
/**
* Show only published Articles in Course
*/
if ($course_article->is_published) {
$articleList[] = $course_article;
}
}
/** Get Articles with Coauthors to display on Course Page */
foreach ($articleList as $article) {
$coauthorship = new Model_Coauthors($article->id);
$article->coauthor = Model_User::get($coauthorship->user_id);
}
}
return $articleList;
}
/**
* Checks whether or not course contains any articles
* @param $course_id - course's id
* @return bool
*/
public static function containsArticles(int $course_id) {
return (bool) self::getArticles($course_id);
}
/**
* Return unique article authors from the Course
* @param Model_Article[] - Articles included in specific Course
* @return Model_User[] - Array of unique Course authors
*/
public function getUniqueCourseAuthors()
{
$course_articles = self::getArticles($this->id);
$course_authors_ids = array();
$course_authors = array();
foreach ($course_articles as $article) {
$author_id = $article->author->id;
if (!in_array($author_id, $course_authors_ids))
{
$course_authors_ids[] = $author_id;
$course_authors[] = Model_User::get($author_id);
}
}
return $course_authors;
}
}