/
article_service.js
executable file
·719 lines (630 loc) · 25.7 KB
/
article_service.js
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
/*
Copyright (C) 2015 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//dependencies
var async = require('async');
var util = require('../../util.js');
/**
* Reusable service classes to be called from controllers
*
* @module Services
*/
module.exports = function ArticleServiceModule(pb) {
/**
* Retrieves articles and pages
*
* @class ArticleService
* @constructor
*
*/
function ArticleService(){
this.object_type = ARTICLE_TYPE;
}
/**
*
* @private
* @static
* @readonly
* @property ARTICLE_TYPE
* @type {String}
*/
var ARTICLE_TYPE = 'article'
/**
*
* @private
* @static
* @readonly
* @property PAGE_TYPE
* @type {String}
*/
var PAGE_TYPE = 'page';
/**
* Rerieves the content type
*
* @method getContentType
* @return {String} Content type
*/
ArticleService.prototype.getContentType = function() {
return this.object_type;
};
/**
* Sets the content type (article, page)
*
* @method setContentType
* @param {String} type The content type
*/
ArticleService.prototype.setContentType = function(type) {
this.object_type = type;
};
/**
* Finds an article or page by Id
*
* @method findById
* @param {String} articleId The article's object Id
* @param {Function} cb Callback function
*/
ArticleService.prototype.findById = function(articleId, cb) {
this.find(pb.DAO.getIdWhere(articleId), cb);
};
/**
* Finds articles by section
*
* @method findBySection
* @param {String} sectionId The section's object Id
* @param {Function} cb Callback function
*/
ArticleService.prototype.findBySection = function(sectionId, cb) {
this.find({article_sections: sectionId}, cb);
};
/**
* Finds articles and pages by topic
*
* @method findByTopic
* @param {[type]} topicId The topic's object Id
* @param {Function} cb Callback function
*/
ArticleService.prototype.findByTopic = function(topicId, cb) {
this.find({article_topics: topicId}, cb);
};
/**
* Finds articles and pages matching criteria
*
* @method find
* @param {Object} where Defines the where clause for the article search
* @param {Object} options The options object that can provide query control
* parameters
* @param {Array} [options.order] The order that the results will be returned
* in. The default is publish date descending and created descending
* @param {Object} [options.select] The fields that will be returned for each
* article that matches the criteria
* @param {Integer} [options.limit] The number of results to return
* @param {Integer} [options.offset] The number of articles to skip before
* returning results
* @param {Function} cb Callback function that takes two parameters: the first
* is an error, if occurred. The second is an array of articles or possibly
* null if an error occurs.
*/
ArticleService.prototype.find = function(where, options, cb) {
if (util.isFunction(options)) {
cb = options;
options = {};
}
else if (!options) {
options = {};
}
//verify the where is valid
if (!util.isObject(where)) {
return cb(new Error('The where clause must be an object'));
}
//build out query
if(!where.publish_date) {
where.publish_date = {$lt: new Date()};
}
if(!where.draft) {
where.draft = {$ne: 1};
}
//build out the ordering
var order;
if (options.order) {
order = options.order;
}
else {
order = [{'publish_date': pb.DAO.DESC}, {'created': pb.DAO.DESC}];
}
//build out select
var select;
if (util.isObject(options.select)) {
select = options.select;
}
else {
select = pb.DAO.SELECT_ALL;
}
//build out the limit (must be a valid integer)
var limit = undefined;
if (pb.validation.isInt(options.limit, true, true)) {
limit = options.limit;
}
//build out the limit (must be a valid integer)
var offset = 0;
if (pb.validation.isInt(options.offset, true, true)) {
offset = options.offset;
}
var self = this;
var dao = new pb.DAO();
dao.q(this.getContentType(), {where: where, select: select, order: order, limit: limit, offset: offset}, function(err, articles) {
if (util.isError(err)) {
return cb(err, []);
}
else if (articles.length === 0) {
return cb(null, []);
}
//get authors
self.getArticleAuthors(articles, function(err, authors) {
var contentService = new pb.ContentService();
contentService.getSettings(function(err, contentSettings) {
var tasks = util.getTasks(articles, function(articles, i) {
return function(callback) {
self.processArticleForDisplay(articles[i], articles.length, authors, contentSettings, function(){
callback(null, null);
});
};
});
async.series(tasks, function(err, results) {
cb(err, articles);
});
});
});
});
};
/**
* Updates articles
*
* @param {String} articleId id of article
* @param {Object} fields fields to update
* @param {Object} options
* @param {Function} cb Callback function
*/
ArticleService.prototype.update = function(articleId, fields, options, cb) {
if(!util.isObject(fields)){
return cb(new Error('The fields parameter is required'));
}
var where = pb.DAO.getIdWhere(articleId);
var content_type = this.getContentType();
var dao = new pb.DAO();
dao.updateFields(content_type, where, fields, options, cb);
};
/**
* Retrieves data necessary for displaying an articles and appends it to the
* article object
*
* @method processArticleForDisplay
* @param {Object} article The artice to process
* @param {Number} articleCount The total number of articles
* @param {Array} authors Available authors retrieved from the database
* @param {Object} contentSettings Content settings to use for processing
* @param {Function} cb Callback function
*/
ArticleService.prototype.processArticleForDisplay = function(article, articleCount, authors, contentSettings, cb) {
var self = this;
if (this.getContentType() === ARTICLE_TYPE) {
if(contentSettings.display_bylines) {
for(var j = 0; j < authors.length; j++) {
if(pb.DAO.areIdsEqual(authors[j][pb.DAO.getIdField()], article.author)) {
if(authors[j].photo && contentSettings.display_author_photo) {
article.author_photo = authors[j].photo;
article.media_body_style = '';
}
article.author_name = pb.users.getFormattedName(authors[j]);
article.author_position = (authors[j].position && contentSettings.display_author_position) ? authors[j].position : '';
break;
}
}
}
if(contentSettings.display_timestamp ) {
article.timestamp = pb.ContentService.getTimestampTextFromSettings(
article.publish_date,
contentSettings
);
}
if(article.article_layout.indexOf('^read_more^') > -1) {
if(articleCount > 1) {
article.article_layout = article.article_layout.substr(0, article.article_layout.indexOf('^read_more^')) + ' <a href="' + pb.config.siteRoot + '/article/' + article.url + '">' + contentSettings.read_more_text + '...</a>';
}
else {
article.article_layout = article.article_layout.split('^read_more^').join('');
}
}
else if(articleCount > 1 && contentSettings.auto_break_articles) {
var breakString = '<br>';
var tempLayout;
// Firefox uses br and Chrome uses div in content editables.
// We need to see which one is being used
var brIndex = article.article_layout.indexOf('<br>');
if(brIndex === -1) {
brIndex = article.article_layout.indexOf('<br />');
breakString = '<br />';
}
var divIndex = article.article_layout.indexOf('</div>');
// Temporarily replace double breaks with a directive so we don't mess up the count
if(divIndex === -1 || (brIndex > -1 && divIndex > -1 && brIndex < divIndex)) {
tempLayout = article.article_layout.split(breakString + breakString).join(breakString + '^dbl_pgf_break^');
}
else {
breakString = '</div>';
tempLayout = article.article_layout.split('<div><br></div>').join(breakString + '^dbl_pgf_break^')
.split('<div><br /></div>').join(breakString + '^dbl_pgf_break^');
}
// Split the layout by paragraphs and remove any empty indices
var tempLayoutArray = tempLayout.split(breakString);
for(var i = 0; i < tempLayoutArray.length; i++) {
if(!tempLayoutArray[i].length) {
tempLayoutArray.splice(i, 1);
i--;
}
}
// Only continue if we have more than 1 paragraph
if(tempLayoutArray.length > 1) {
var newLayout = '';
// Cutoff the article at the right number of paragraphs
for(i = 0; i < tempLayoutArray.length && i < contentSettings.auto_break_articles; i++) {
if(i === contentSettings.auto_break_articles -1 && i != tempLayoutArray.length - 1) {
newLayout += tempLayoutArray[i] + ' <a href="' + pb.config.siteRoot + '/article/' + article.url + '">' + contentSettings.read_more_text + '...</a>' + breakString;
continue;
}
newLayout += tempLayoutArray[i] + breakString;
}
if(breakString === '</div>') {
breakString = '<div><br /></div>';
}
// Replace the double breaks
newLayout = newLayout.split('^dbl_pgf_break^').join(breakString);
article.article_layout = newLayout;
}
}
}
article.layout = article.article_layout;
var mediaLoader = new MediaLoader();
mediaLoader.start(article[this.getContentType()+'_layout'], function(err, newLayout) {
article.layout = newLayout;
delete article.article_layout;
if (self.getContentType() === ARTICLE_TYPE && ArticleService.allowComments(contentSettings, article)) {
var opts = {
where: {
article: article[pb.DAO.getIdField()].toString()
},
order: {
created: pb.DAO.ASC
}
};
var dao = new pb.DAO();
dao.q('comment', opts, function(err, comments) {
if(util.isError(err) || comments.length == 0) {
return cb(null, null);
}
self.getCommenters(comments, contentSettings, function(err, commentsWithCommenters) {
article.comments = commentsWithCommenters;
cb(null, null);
});
});
}
else {
cb(null, null);
}
});
};
/**
* Retrieves the authors of an array of articles
*
* @method getArticleAuthors
* @param {Array} articles Array of article objects
* @param {Function} cb Callback function
*/
ArticleService.prototype.getArticleAuthors = function(articles, cb) {
//gather all author IDs
var dao = new pb.DAO();
dao.q('user', {where: pb.DAO.getIdInWhere(articles, 'author')}, cb);
};
/**
* Retrieves the commenters for an array of comments
*
* @method getCommenters
* @param {Array} comments Array of comment objects
* @param {Object} contentSettings Content settings to use for processing
* @param {Function} cb Callback function
*/
ArticleService.prototype.getCommenters = function(comments, contentSettings, cb) {
//callback for iteration to handle setting the commenter attributes
var processComment = function(comment, commenter) {
comment.commenter_name = 'Anonymous';
comment.timestamp = pb.ContentService.getTimestampTextFromSettings(comment.created, contentSettings);
if (commenter) {
comment.commenter_name = pb.users.getFormattedName(commenter);
if(commenter.photo) {
comment.commenter_photo = commenter.photo;
}
if(commenter.position) {
comment.commenter_position = commenter.position;
}
}
};
var processedComments = [];
var users = {};
var tasks = util.getTasks(comments, function(comments, i) {
return function(callback) {
var comment = comments[i];
if (!comment.commenter || users[comment.commenter]) {
//user already commented so pull locally
processComment(comment, users[comment.commenter]);
processedComments.push(comment);
callback(null, true);
return;
}
//user has not already commented so load
var dao = new pb.DAO();
dao.loadById(comment.commenter, 'user', function(err, commenter) {
if(util.isError(err) || commenter == null) {
callback(null, false);
return;
}
//process the comment
users[commenter[pb.DAO.getIdField()].toString()] = commenter;
processComment(comment, commenter);
processedComments.push(comment);
callback(null, true);
});
};
});
async.series(tasks, function(err, result) {
cb(err, processedComments);
});
};
/**
* Retrieves the article and byline templates
*
* @method getTemplates
* @param {Function} cb Callback function
*/
ArticleService.prototype.getTemplates = function(cb) {
var ts = new pb.TemplateService();
ts.load('elements/article', function(err, articleTemplate) {
ts.load('elements/article/byline', function(err, bylineTemplate) {
cb(articleTemplate, bylineTemplate);
});
});
};
/**
* Retrieves the SEO metadata for the specified content.
* @method getMetaInfo
* @param {Object} article The article to retrieve information for
* @param {Function} cb A callback that takes two parameters. The first is
* an Error, if occurred. The second is an object that contains 4
* properties:
* title - the SEO title,
* description - the SEO description,
* keywords - an array of SEO keywords that describe the content,
* thumbnail - a URI path to the thumbnail image
*/
ArticleService.prototype.getMetaInfo = function(article, cb) {
if (util.isNullOrUndefined(article)) {
return cb(
new Error('The article parameter cannot be null'),
//provided for backward compatibility
{
title: '',
description: '',
thumbnail: '',
keywords: []
}
);
}
//compile the tasks necessary to gather the meta info
var tasks = {
//figure out SEO title
title: function(callback) {
var title;
if (pb.ValidationService.isNonEmptyStr(article.seo_title, true)) {
title = article.seo_title;
}
else {
title = article.headline;
}
callback(null, title);
},
//figure out the description by taking the explicit meta
//description or stripping all HTML formatting from the body and
//using it.
description: function(callback) {
var description = '';
if(util.isString(article.meta_desc)) {
description = article.meta_desc;
}
else if(pb.ValidationService.isNonEmptyStr(article.layout, true)) {
description = article.layout.replace(/<\/?[^>]+(>|$)/g, '').substr(0, 155);
}
callback(null, description);
},
keywords: function(callback) {
var keywords = util.arrayToHash(article.meta_keywords || []);
var topics = article.article_topics || article.page_topics;
if (!util.isArray(topics) || topics.length <= 0) {
return callback(null, Object.keys(keywords));
}
//we know there are topics we need to retrieve them to set the
//meta keywords
var opts = {
select: {
name: 1
},
where: pb.DAO.getIdInWhere(article.article_topics || article.page_topics)
};
var topicService = new pb.TopicService();
topicService.getAll(opts, function(err, topics) {
if (util.isError(err)) {
return callback(err);
}
//add to the key word hash. It is ok if we overwrite an existing
//value since it is a hash. We just want a unique set.
topics.forEach(function(topic) {
keywords[topic.name] = true;
});
callback(null, Object.keys(keywords));
});
},
thumbnail: function(callback) {
//no media so skip
if (!pb.ValidationService.isNonEmptyStr(article.thumbnail, true)) {
return callback(null, '');
}
//media should exists so go get it
var mOpts = {
select: {
location: 1
},
where: pb.DAO.getIdWhere(article.thumbnail)
};
var mediaService = new pb.MediaService();
mediaService.get(mOpts, function(err, media) {
callback(err, util.isNullOrUndefined(media) ? '' : media.location);
});
}
};
async.parallel(tasks, cb);
};
/**
* Retrieves the meta info for an article or page
* @deprecated Since 0.4.1
* @method getMetaInfo
* @param {Object} article An article or page object
* @param {Function} cb Callback function
*/
ArticleService.getMetaInfo = function(article, cb) {
if(util.isNullOrUndefined(article)) {
return cb('', '', '');
}
//log deprecation
pb.log.warn('ArticleService: ArticleService.getMetaInfo is deprecated and will be removed 0.5.0. Use the prototype function getMetaInfo instead');
//all wrapped up to ensure we can be multi-threaded here for backwards
//compatibility
(function(cb) {
var articleService = new ArticleService();
articleService.getMetaInfo(article, function(err, meta) {
if (util.isError(err)) {
return cb('', '', '');
}
cb(meta.keywords, meta.description, meta.title, meta.thumbnail);
});
})(cb);
};
/**
* Provided the content descriptor and the content settings object the
* function indicates if comments should be allowed within the given
* context of the content.
* @param {Object} contentSettings The settings object retrieved from the
* content service
* @param {Object} content The page or article that should or should not
* have associated comments.
* @return {Boolean}
*/
ArticleService.allowComments = function(contentSettings, content) {
return contentSettings.allow_comments && content.allow_comments;
};
/**
* Handles retrieval and injection of media in articles and pages
*
* @module Services
* @class MediaLoader
* @constructor
* @submodule Entities
*/
function MediaLoader() {};
/**
* Processes an article or page to insert media
*
* @method start
* @param {String} articleLayout The HTML layout of the article or page
* @param {Function} cb [description]
*/
MediaLoader.prototype.start = function(articleLayout, cb) {
var self = this;
var ts = new pb.TemplateService();
ts.load('elements/media', function(err, mediaTemplate) {
async.whilst(
function() {return articleLayout.indexOf('^media_display_') >= 0;},
function(callback) {
self.replaceMediaTag(articleLayout, mediaTemplate, function(err, newArticleLayout) {
articleLayout = newArticleLayout;
callback();
});
},
function(err) {
cb(err, articleLayout);
}
);
});
};
/**
* Replaces an article or page layout's ^media_display^ tag with a media embed
* @param {String} layout The HTML layout of the article or page
* @param {String} mediaTemplate The template of the media embed
* @param {Function} cb Callback function
*/
MediaLoader.prototype.replaceMediaTag = function(layout, mediaTemplate, cb) {
var flag = pb.MediaService.extractNextMediaFlag(layout);
if (!flag) {
return cb(null, layout);
}
var mediaStyleString = flag.style;
var dao = new pb.DAO();
dao.loadById(flag.id, 'media', function(err, data) {
if(util.isError(err)) {
return cb(err);
}
else if (!data) {
pb.log.warn("ArticleService: Content contains reference to missing media [%s].", flag.id);
return cb(null, layout.replace(flag.flag, ''));
}
//ensure the max height is set if explicity set for media replacement
var options = {
view: 'post',
style: {
},
attrs: {
frameborder: "0",
allowfullscreen: ""
}
};
if (flag.style.maxHeight) {
options.style['max-height'] = flag.style.maxHeight;
}
var ms = new pb.MediaService();
ms.render(data, options, function(err, html) {
if (util.isError(err)) {
return cb(err);
}
//get the style for the container
var containerStyleStr = pb.MediaService.getStyleForPosition(flag.style.position) || '';
//finish up replacements
var mediaEmbed = mediaTemplate.split('^media^').join(html);
mediaEmbed = mediaEmbed.split('^caption^').join(data.caption);
mediaEmbed = mediaEmbed.split('^display_caption^').join(data.caption ? '' : 'display: none');
mediaEmbed = mediaEmbed.split('^container_style^').join(containerStyleStr);
cb(null, layout.replace(flag.flag, mediaEmbed));
});
});
};
//exports
return {
ArticleService: ArticleService,
MediaLoader: MediaLoader
};
};