pages.js 33.8 KB
Newer Older
1
const Model = require('objection').Model
2
const _ = require('lodash')
3 4 5 6
const JSBinType = require('js-binary').Type
const pageHelper = require('../helpers/page')
const path = require('path')
const fs = require('fs-extra')
Nick's avatar
Nick committed
7
const yaml = require('js-yaml')
8 9
const striptags = require('striptags')
const emojiRegex = require('emoji-regex')
10
const he = require('he')
11
const CleanCSS = require('clean-css')
NGPixel's avatar
NGPixel committed
12 13 14
const TurndownService = require('turndown')
const turndownPluginGfm = require('@joplin/turndown-plugin-gfm').gfm
const cheerio = require('cheerio')
15

16 17
/* global WIKI */

Nick's avatar
Nick committed
18 19
const frontmatterRegex = {
  html: /^(<!-{2}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{2}>)?(?:\n|\r)*([\w\W]*)*/,
20
  legacy: /^(<!-- TITLE: ?([\w\W]+?) ?-{2}>)?(?:\n|\r)?(<!-- SUBTITLE: ?([\w\W]+?) ?-{2}>)?(?:\n|\r)*([\w\W]*)*/i,
Nick's avatar
Nick committed
21 22 23
  markdown: /^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})?(?:\n|\r)*([\w\W]*)*/
}

24
const punctuationRegex = /[!,:;/\\_+\-=()&#@<>$~%^*[\]{}"'|]+|(\.\s)|(\s\.)/ig
25
// const htmlEntitiesRegex = /(&#[0-9]{3};)|(&#x[a-zA-Z0-9]{2};)/ig
26

27 28 29 30 31 32 33 34 35 36 37 38 39 40
/**
 * Pages model
 */
module.exports = class Page extends Model {
  static get tableName() { return 'pages' }

  static get jsonSchema () {
    return {
      type: 'object',
      required: ['path', 'title'],

      properties: {
        id: {type: 'integer'},
        path: {type: 'string'},
41
        hash: {type: 'string'},
42 43 44
        title: {type: 'string'},
        description: {type: 'string'},
        isPublished: {type: 'boolean'},
45
        privateNS: {type: 'string'},
46 47 48
        publishStartDate: {type: 'string'},
        publishEndDate: {type: 'string'},
        content: {type: 'string'},
49
        contentType: {type: 'string'},
50 51 52 53 54 55 56

        createdAt: {type: 'string'},
        updatedAt: {type: 'string'}
      }
    }
  }

NGPixel's avatar
NGPixel committed
57 58 59 60
  static get jsonAttributes() {
    return ['extra']
  }

61 62 63 64 65 66 67 68 69 70 71 72 73 74
  static get relationMappings() {
    return {
      tags: {
        relation: Model.ManyToManyRelation,
        modelClass: require('./tags'),
        join: {
          from: 'pages.id',
          through: {
            from: 'pageTags.pageId',
            to: 'pageTags.tagId'
          },
          to: 'tags.id'
        }
      },
75
      links: {
Nick's avatar
Nick committed
76 77
        relation: Model.HasManyRelation,
        modelClass: require('./pageLinks'),
78 79
        join: {
          from: 'pages.id',
Nick's avatar
Nick committed
80
          to: 'pageLinks.pageId'
81 82
        }
      },
83 84 85 86 87 88 89 90
      author: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./users'),
        join: {
          from: 'pages.authorId',
          to: 'users.id'
        }
      },
91 92 93 94 95 96 97 98
      creator: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./users'),
        join: {
          from: 'pages.creatorId',
          to: 'users.id'
        }
      },
NGPixel's avatar
NGPixel committed
99 100 101 102 103 104 105 106
      editor: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./editors'),
        join: {
          from: 'pages.editorKey',
          to: 'editors.key'
        }
      },
107 108 109 110
      locale: {
        relation: Model.BelongsToOneRelation,
        modelClass: require('./locales'),
        join: {
NGPixel's avatar
NGPixel committed
111
          from: 'pages.localeCode',
112 113 114 115 116 117 118 119 120 121 122 123 124
          to: 'locales.code'
        }
      }
    }
  }

  $beforeUpdate() {
    this.updatedAt = new Date().toISOString()
  }
  $beforeInsert() {
    this.createdAt = new Date().toISOString()
    this.updatedAt = new Date().toISOString()
  }
125 126 127 128 129 130 131 132 133
  /**
   * Solving the violates foreign key constraint using cascade strategy
   * using static hooks
   * @see https://vincit.github.io/objection.js/api/types/#type-statichookarguments
   */
  static async beforeDelete({ asFindQuery }) {
    const page = await asFindQuery().select('id')
    await WIKI.models.comments.query().delete().where('pageId', page[0].id)
  }
134 135 136
  /**
   * Cache Schema
   */
137 138
  static get cacheSchema() {
    return new JSBinType({
Nicolas Giard's avatar
Nicolas Giard committed
139
      id: 'uint',
140 141 142 143 144 145
      authorId: 'uint',
      authorName: 'string',
      createdAt: 'string',
      creatorId: 'uint',
      creatorName: 'string',
      description: 'string',
NGPixel's avatar
NGPixel committed
146
      editorKey: 'string',
147 148 149 150 151
      isPrivate: 'boolean',
      isPublished: 'boolean',
      publishEndDate: 'string',
      publishStartDate: 'string',
      render: 'string',
152 153 154 155 156 157
      tags: [
        {
          tag: 'string',
          title: 'string'
        }
      ],
NGPixel's avatar
NGPixel committed
158 159 160 161
      extra: {
        js: 'string',
        css: 'string'
      },
162
      title: 'string',
163
      toc: 'string',
164 165
      updatedAt: 'string'
    })
166 167
  }

168 169
  /**
   * Inject page metadata into contents
170 171
   *
   * @returns {string} Page Contents with Injected Metadata
172 173
   */
  injectMetadata () {
174
    return pageHelper.injectPageMetadata(this)
175 176
  }

177 178
  /**
   * Get the page's file extension based on content type
179 180
   *
   * @returns {string} File Extension
181 182
   */
  getFileExtension() {
Nick's avatar
Nick committed
183
    return pageHelper.getFileExtension(this.contentType)
184 185
  }

Nick's avatar
Nick committed
186 187 188 189 190
  /**
   * Parse injected page metadata from raw content
   *
   * @param {String} raw Raw file contents
   * @param {String} contentType Content Type
191
   * @returns {Object} Parsed Page Metadata with Raw Content
Nick's avatar
Nick committed
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
   */
  static parseMetadata (raw, contentType) {
    let result
    switch (contentType) {
      case 'markdown':
        result = frontmatterRegex.markdown.exec(raw)
        if (result[2]) {
          return {
            ...yaml.safeLoad(result[2]),
            content: result[3]
          }
        } else {
          // Attempt legacy v1 format
          result = frontmatterRegex.legacy.exec(raw)
          if (result[2]) {
            return {
              title: result[2],
              description: result[4],
              content: result[5]
            }
          }
        }
        break
      case 'html':
        result = frontmatterRegex.html.exec(raw)
        if (result[2]) {
          return {
            ...yaml.safeLoad(result[2]),
            content: result[3]
          }
        }
        break
    }
    return {
      content: raw
    }
  }

230 231 232 233 234 235
  /**
   * Create a New Page
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise of the Page Model Instance
   */
236
  static async createPage(opts) {
NGPixel's avatar
NGPixel committed
237
    // -> Validate path
238
    if (opts.path.includes('.') || opts.path.includes(' ') || opts.path.includes('\\') || opts.path.includes('//')) {
239 240 241
      throw new WIKI.Error.PageIllegalPath()
    }

242
    // -> Remove trailing slash
NGPixel's avatar
NGPixel committed
243
    if (opts.path.endsWith('/')) {
244 245 246
      opts.path = opts.path.slice(0, -1)
    }

247 248 249 250 251
    // -> Remove starting slash
    if (opts.path.startsWith('/')) {
      opts.path = opts.path.slice(1)
    }

NGPixel's avatar
NGPixel committed
252 253 254 255 256 257 258 259 260
    // -> Check for page access
    if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
      locale: opts.locale,
      path: opts.path
    })) {
      throw new WIKI.Error.PageDeleteForbidden()
    }

    // -> Check for duplicate
Nick's avatar
Nick committed
261 262 263 264 265
    const dupCheck = await WIKI.models.pages.query().select('id').where('localeCode', opts.locale).where('path', opts.path).first()
    if (dupCheck) {
      throw new WIKI.Error.PageDuplicateCreate()
    }

NGPixel's avatar
NGPixel committed
266
    // -> Check for empty content
Nick's avatar
Nick committed
267 268 269 270
    if (!opts.content || _.trim(opts.content).length < 1) {
      throw new WIKI.Error.PageEmptyContent()
    }

NGPixel's avatar
NGPixel committed
271
    // -> Format CSS Scripts
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    let scriptCss = ''
    if (WIKI.auth.checkAccess(opts.user, ['write:styles'], {
      locale: opts.locale,
      path: opts.path
    })) {
      if (!_.isEmpty(opts.scriptCss)) {
        scriptCss = new CleanCSS({ inline: false }).minify(opts.scriptCss).styles
      } else {
        scriptCss = ''
      }
    }

    // -> Format JS Scripts
    let scriptJs = ''
    if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
      locale: opts.locale,
      path: opts.path
    })) {
      scriptJs = opts.scriptJs || ''
    }

NGPixel's avatar
NGPixel committed
293
    // -> Create page
294
    await WIKI.models.pages.query().insert({
NGPixel's avatar
NGPixel committed
295
      authorId: opts.user.id,
296
      content: opts.content,
NGPixel's avatar
NGPixel committed
297
      creatorId: opts.user.id,
298
      contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
299 300
      description: opts.description,
      editorKey: opts.editor,
301
      hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
302 303 304 305
      isPrivate: opts.isPrivate,
      isPublished: opts.isPublished,
      localeCode: opts.locale,
      path: opts.path,
306 307 308
      publishEndDate: opts.publishEndDate || '',
      publishStartDate: opts.publishStartDate || '',
      title: opts.title,
309 310 311 312 313
      toc: '[]',
      extra: JSON.stringify({
        js: scriptJs,
        css: scriptCss
      })
314
    })
315 316 317
    const page = await WIKI.models.pages.getPageFromDb({
      path: opts.path,
      locale: opts.locale,
NGPixel's avatar
NGPixel committed
318
      userId: opts.user.id,
319 320
      isPrivate: opts.isPrivate
    })
321

322
    // -> Save Tags
323
    if (opts.tags && opts.tags.length > 0) {
324 325 326
      await WIKI.models.tags.associateTags({ tags: opts.tags, page })
    }

327
    // -> Render page to HTML
328
    await WIKI.models.pages.renderPage(page)
329

330 331 332
    // -> Rebuild page tree
    await WIKI.models.pages.rebuildTree()

333 334 335
    // -> Add to Search Index
    const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
    page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
336
    await WIKI.data.searchEngine.created(page)
337 338

    // -> Add to Storage
Nick's avatar
Nick committed
339 340 341 342 343 344
    if (!opts.skipStorage) {
      await WIKI.models.storage.pageEvent({
        event: 'created',
        page
      })
    }
345

346 347 348 349 350 351 352
    // -> Reconnect Links
    await WIKI.models.pages.reconnectLinks({
      locale: page.localeCode,
      path: page.path,
      mode: 'create'
    })

353 354 355
    // -> Get latest updatedAt
    page.updatedAt = await WIKI.models.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)

356 357 358
    return page
  }

359 360 361 362 363 364
  /**
   * Update an Existing Page
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise of the Page Model Instance
   */
365
  static async updatePage(opts) {
NGPixel's avatar
NGPixel committed
366
    // -> Fetch original page
367
    const ogPage = await WIKI.models.pages.query().findById(opts.id)
368 369 370
    if (!ogPage) {
      throw new Error('Invalid Page Id')
    }
Nick's avatar
Nick committed
371

NGPixel's avatar
NGPixel committed
372 373 374 375 376 377 378 379 380
    // -> Check for page access
    if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
      locale: opts.locale,
      path: opts.path
    })) {
      throw new WIKI.Error.PageUpdateForbidden()
    }

    // -> Check for empty content
Nick's avatar
Nick committed
381 382 383 384
    if (!opts.content || _.trim(opts.content).length < 1) {
      throw new WIKI.Error.PageEmptyContent()
    }

NGPixel's avatar
NGPixel committed
385
    // -> Create version snapshot
Nicolas Giard's avatar
Nicolas Giard committed
386 387
    await WIKI.models.pageHistory.addVersion({
      ...ogPage,
Nick's avatar
Nick committed
388
      isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
NGPixel's avatar
NGPixel committed
389 390
      action: opts.action ? opts.action : 'updated',
      versionDate: ogPage.updatedAt
Nicolas Giard's avatar
Nicolas Giard committed
391
    })
NGPixel's avatar
NGPixel committed
392

393 394 395 396 397
    // -> Format Extra Properties
    if (!_.isPlainObject(ogPage.extra)) {
      ogPage.extra = {}
    }

NGPixel's avatar
NGPixel committed
398
    // -> Format CSS Scripts
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
    let scriptCss = _.get(ogPage, 'extra.css', '')
    if (WIKI.auth.checkAccess(opts.user, ['write:styles'], {
      locale: opts.locale,
      path: opts.path
    })) {
      if (!_.isEmpty(opts.scriptCss)) {
        scriptCss = new CleanCSS({ inline: false }).minify(opts.scriptCss).styles
      } else {
        scriptCss = ''
      }
    }

    // -> Format JS Scripts
    let scriptJs = _.get(ogPage, 'extra.js', '')
    if (WIKI.auth.checkAccess(opts.user, ['write:scripts'], {
      locale: opts.locale,
      path: opts.path
    })) {
      scriptJs = opts.scriptJs || ''
    }

NGPixel's avatar
NGPixel committed
420
    // -> Update page
421
    await WIKI.models.pages.query().patch({
NGPixel's avatar
NGPixel committed
422
      authorId: opts.user.id,
423 424
      content: opts.content,
      description: opts.description,
Nick's avatar
Nick committed
425
      isPublished: opts.isPublished === true || opts.isPublished === 1,
426 427
      publishEndDate: opts.publishEndDate || '',
      publishStartDate: opts.publishStartDate || '',
428 429 430 431 432 433
      title: opts.title,
      extra: JSON.stringify({
        ...ogPage.extra,
        js: scriptJs,
        css: scriptCss
      })
434
    }).where('id', ogPage.id)
435
    let page = await WIKI.models.pages.getPageFromDb(ogPage.id)
436

437 438 439
    // -> Save Tags
    await WIKI.models.tags.associateTags({ tags: opts.tags, page })

440
    // -> Render page to HTML
441
    await WIKI.models.pages.renderPage(page)
NGPixel's avatar
NGPixel committed
442
    WIKI.events.outbound.emit('deletePageFromCache', page.hash)
443 444 445 446

    // -> Update Search Index
    const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
    page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
447
    await WIKI.data.searchEngine.updated(page)
448 449

    // -> Update on Storage
Nick's avatar
Nick committed
450 451 452 453 454 455
    if (!opts.skipStorage) {
      await WIKI.models.storage.pageEvent({
        event: 'updated',
        page
      })
    }
NGPixel's avatar
NGPixel committed
456 457

    // -> Perform move?
458
    if ((opts.locale && opts.locale !== page.localeCode) || (opts.path && opts.path !== page.path)) {
NGPixel's avatar
NGPixel committed
459 460 461 462 463 464
      await WIKI.models.pages.movePage({
        id: page.id,
        destinationLocale: opts.locale,
        destinationPath: opts.path,
        user: opts.user
      })
465 466 467 468 469
    } else {
      // -> Update title of page tree entry
      await WIKI.models.knex.table('pageTree').where({
        pageId: page.id
      }).update('title', page.title)
NGPixel's avatar
NGPixel committed
470 471
    }

472 473 474
    // -> Get latest updatedAt
    page.updatedAt = await WIKI.models.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)

475 476
    return page
  }
477

NGPixel's avatar
NGPixel committed
478 479 480 481 482 483 484 485 486 487 488 489 490
  /**
   * Convert an Existing Page
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise of the Page Model Instance
   */
  static async convertPage(opts) {
    // -> Fetch original page
    const ogPage = await WIKI.models.pages.query().findById(opts.id)
    if (!ogPage) {
      throw new Error('Invalid Page Id')
    }

491 492 493 494
    if (ogPage.editorKey === opts.editor) {
      throw new Error('Page is already using this editor. Nothing to convert.')
    }

NGPixel's avatar
NGPixel committed
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
    // -> Check for page access
    if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
      locale: ogPage.localeCode,
      path: ogPage.path
    })) {
      throw new WIKI.Error.PageUpdateForbidden()
    }

    // -> Check content type
    const sourceContentType = ogPage.contentType
    const targetContentType = _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text')
    const shouldConvert = sourceContentType !== targetContentType
    let convertedContent = null

    // -> Convert content
    if (shouldConvert) {
      // -> Markdown => HTML
      if (sourceContentType === 'markdown' && targetContentType === 'html') {
        if (!ogPage.render) {
          throw new Error('Aborted conversion because rendered page content is empty!')
        }
        convertedContent = ogPage.render

        const $ = cheerio.load(convertedContent, {
          decodeEntities: true
        })

        if ($.root().children().length > 0) {
523
          // Remove header anchors
NGPixel's avatar
NGPixel committed
524 525
          $('.toc-anchor').remove()

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
          // Attempt to convert tabsets
          $('tabset').each((tabI, tabElm) => {
            const tabHeaders = []
            // -> Extract templates
            $(tabElm).children('template').each((tmplI, tmplElm) => {
              if ($(tmplElm).attr('v-slot:tabs') === '') {
                $(tabElm).before('<ul class="tabset-headers">' + $(tmplElm).html() + '</ul>')
              } else {
                $(tabElm).after('<div class="markdown-tabset">' + $(tmplElm).html() + '</div>')
              }
            })
            // -> Parse tab headers
            $(tabElm).prev('.tabset-headers').children((i, elm) => {
              tabHeaders.push($(elm).html())
            })
            $(tabElm).prev('.tabset-headers').remove()
            // -> Inject tab headers
            $(tabElm).next('.markdown-tabset').children((i, elm) => {
              if (tabHeaders.length > i) {
                $(elm).prepend(`<h2>${tabHeaders[i]}</h2>`)
              }
            })
            $(tabElm).next('.markdown-tabset').prepend('<h1>Tabset</h1>')
            $(tabElm).remove()
          })

NGPixel's avatar
NGPixel committed
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
          convertedContent = $.html('body').replace('<body>', '').replace('</body>', '').replace(/&#x([0-9a-f]{1,6});/ig, (entity, code) => {
            code = parseInt(code, 16)

            // Don't unescape ASCII characters, assuming they're encoded for a good reason
            if (code < 0x80) return entity

            return String.fromCodePoint(code)
          })
        }

      // -> HTML => Markdown
      } else if (sourceContentType === 'html' && targetContentType === 'markdown') {
        const td = new TurndownService({
          bulletListMarker: '-',
          codeBlockStyle: 'fenced',
          emDelimiter: '*',
          fence: '```',
          headingStyle: 'atx',
          hr: '---',
          linkStyle: 'inlined',
          preformattedCode: true,
          strongDelimiter: '**'
        })

        td.use(turndownPluginGfm)

        td.keep(['kbd'])

        td.addRule('subscript', {
          filter: ['sub'],
          replacement: c => `~${c}~`
        })

        td.addRule('superscript', {
          filter: ['sup'],
          replacement: c => `^${c}^`
        })

        td.addRule('underline', {
          filter: ['u'],
          replacement: c => `_${c}_`
        })

595 596 597 598 599 600 601 602 603
        td.addRule('taskList', {
          filter: (n, o) => {
            return n.nodeName === 'INPUT' && n.getAttribute('type') === 'checkbox'
          },
          replacement: (c, n) => {
            return n.getAttribute('checked') ? '[x] ' : '[ ] '
          }
        })

NGPixel's avatar
NGPixel committed
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
        td.addRule('removeTocAnchors', {
          filter: (n, o) => {
            return n.nodeName === 'A' && n.classList.contains('toc-anchor')
          },
          replacement: c => ''
        })

        convertedContent = td.turndown(ogPage.content)
      // -> Unsupported
      } else {
        throw new Error('Unsupported source / destination content types combination.')
      }
    }

    // -> Create version snapshot
    if (shouldConvert) {
      await WIKI.models.pageHistory.addVersion({
        ...ogPage,
        isPublished: ogPage.isPublished === true || ogPage.isPublished === 1,
        action: 'updated',
        versionDate: ogPage.updatedAt
      })
    }

    // -> Update page
    await WIKI.models.pages.query().patch({
      contentType: targetContentType,
      editorKey: opts.editor,
      ...(convertedContent ? { content: convertedContent } : {})
    }).where('id', ogPage.id)
    const page = await WIKI.models.pages.getPageFromDb(ogPage.id)

    await WIKI.models.pages.deletePageFromCache(page.hash)
    WIKI.events.outbound.emit('deletePageFromCache', page.hash)

    // -> Update on Storage
    await WIKI.models.storage.pageEvent({
      event: 'updated',
      page
    })
  }

NGPixel's avatar
NGPixel committed
646 647 648 649 650 651 652
  /**
   * Move a Page
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise with no value
   */
  static async movePage(opts) {
653 654 655 656 657 658 659 660 661
    let page
    if (_.has(opts, 'id')) {
      page = await WIKI.models.pages.query().findById(opts.id)
    } else {
      page = await WIKI.models.pages.query().findOne({
        path: opts.path,
        localeCode: opts.locale
      })
    }
NGPixel's avatar
NGPixel committed
662 663 664 665
    if (!page) {
      throw new WIKI.Error.PageNotFound()
    }

666
    // -> Validate path
667
    if (opts.destinationPath.includes('.') || opts.destinationPath.includes(' ') || opts.destinationPath.includes('\\') || opts.destinationPath.includes('//')) {
668 669 670 671
      throw new WIKI.Error.PageIllegalPath()
    }

    // -> Remove trailing slash
NGPixel's avatar
NGPixel committed
672
    if (opts.destinationPath.endsWith('/')) {
673 674 675
      opts.destinationPath = opts.destinationPath.slice(0, -1)
    }

676 677 678 679 680
    // -> Remove starting slash
    if (opts.destinationPath.startsWith('/')) {
      opts.destinationPath = opts.destinationPath.slice(1)
    }

NGPixel's avatar
NGPixel committed
681 682
    // -> Check for source page access
    if (!WIKI.auth.checkAccess(opts.user, ['manage:pages'], {
683 684
      locale: page.localeCode,
      path: page.path
NGPixel's avatar
NGPixel committed
685 686 687 688 689 690 691 692 693 694 695 696
    })) {
      throw new WIKI.Error.PageMoveForbidden()
    }
    // -> Check for destination page access
    if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
      locale: opts.destinationLocale,
      path: opts.destinationPath
    })) {
      throw new WIKI.Error.PageMoveForbidden()
    }

    // -> Check for existing page at destination path
697
    const destPage = await WIKI.models.pages.query().findOne({
NGPixel's avatar
NGPixel committed
698 699 700 701 702 703 704 705 706 707
      path: opts.destinationPath,
      localeCode: opts.destinationLocale
    })
    if (destPage) {
      throw new WIKI.Error.PagePathCollision()
    }

    // -> Create version snapshot
    await WIKI.models.pageHistory.addVersion({
      ...page,
NGPixel's avatar
NGPixel committed
708 709
      action: 'moved',
      versionDate: page.updatedAt
NGPixel's avatar
NGPixel committed
710 711 712 713 714
    })

    const destinationHash = pageHelper.generateHash({ path: opts.destinationPath, locale: opts.destinationLocale, privateNS: opts.isPrivate ? 'TODO' : '' })

    // -> Move page
715
    const destinationTitle = (page.title === page.path ? opts.destinationPath : page.title)
NGPixel's avatar
NGPixel committed
716 717 718
    await WIKI.models.pages.query().patch({
      path: opts.destinationPath,
      localeCode: opts.destinationLocale,
719
      title: destinationTitle,
NGPixel's avatar
NGPixel committed
720 721
      hash: destinationHash
    }).findById(page.id)
722 723
    await WIKI.models.pages.deletePageFromCache(page.hash)
    WIKI.events.outbound.emit('deletePageFromCache', page.hash)
NGPixel's avatar
NGPixel committed
724

725 726 727
    // -> Rebuild page tree
    await WIKI.models.pages.rebuildTree()

NGPixel's avatar
NGPixel committed
728
    // -> Rename in Search Index
729 730
    const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
    page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
NGPixel's avatar
NGPixel committed
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
    await WIKI.data.searchEngine.renamed({
      ...page,
      destinationPath: opts.destinationPath,
      destinationLocaleCode: opts.destinationLocale,
      destinationHash
    })

    // -> Rename in Storage
    if (!opts.skipStorage) {
      await WIKI.models.storage.pageEvent({
        event: 'renamed',
        page: {
          ...page,
          destinationPath: opts.destinationPath,
          destinationLocaleCode: opts.destinationLocale,
          destinationHash,
          moveAuthorId: opts.user.id,
          moveAuthorName: opts.user.name,
          moveAuthorEmail: opts.user.email
        }
      })
    }

754
    // -> Reconnect Links : Changing old links to the new path
NGPixel's avatar
NGPixel committed
755 756 757 758 759 760 761
    await WIKI.models.pages.reconnectLinks({
      sourceLocale: page.localeCode,
      sourcePath: page.path,
      locale: opts.destinationLocale,
      path: opts.destinationPath,
      mode: 'move'
    })
762

763 764 765 766 767 768
    // -> Reconnect Links : Validate invalid links to the new path
    await WIKI.models.pages.reconnectLinks({
      locale: opts.destinationLocale,
      path: opts.destinationPath,
      mode: 'create'
    })
NGPixel's avatar
NGPixel committed
769 770
  }

771 772 773 774 775 776
  /**
   * Delete an Existing Page
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise with no value
   */
Nicolas Giard's avatar
Nicolas Giard committed
777
  static async deletePage(opts) {
Nick's avatar
Nick committed
778 779 780 781
    let page
    if (_.has(opts, 'id')) {
      page = await WIKI.models.pages.query().findById(opts.id)
    } else {
782
      page = await WIKI.models.pages.query().findOne({
Nick's avatar
Nick committed
783 784 785 786
        path: opts.path,
        localeCode: opts.locale
      })
    }
Nicolas Giard's avatar
Nicolas Giard committed
787
    if (!page) {
788
      throw new WIKI.Error.PageNotFound()
Nicolas Giard's avatar
Nicolas Giard committed
789
    }
NGPixel's avatar
NGPixel committed
790 791 792 793 794 795 796 797 798 799

    // -> Check for page access
    if (!WIKI.auth.checkAccess(opts.user, ['delete:pages'], {
      locale: page.locale,
      path: page.path
    })) {
      throw new WIKI.Error.PageDeleteForbidden()
    }

    // -> Create version snapshot
Nicolas Giard's avatar
Nicolas Giard committed
800 801
    await WIKI.models.pageHistory.addVersion({
      ...page,
NGPixel's avatar
NGPixel committed
802 803
      action: 'deleted',
      versionDate: page.updatedAt
Nicolas Giard's avatar
Nicolas Giard committed
804
    })
NGPixel's avatar
NGPixel committed
805 806

    // -> Delete page
Nicolas Giard's avatar
Nicolas Giard committed
807
    await WIKI.models.pages.query().delete().where('id', page.id)
808 809
    await WIKI.models.pages.deletePageFromCache(page.hash)
    WIKI.events.outbound.emit('deletePageFromCache', page.hash)
810

811 812 813
    // -> Rebuild page tree
    await WIKI.models.pages.rebuildTree()

814
    // -> Delete from Search Index
815
    await WIKI.data.searchEngine.deleted(page)
816 817

    // -> Delete from Storage
Nick's avatar
Nick committed
818 819 820 821 822 823
    if (!opts.skipStorage) {
      await WIKI.models.storage.pageEvent({
        event: 'deleted',
        page
      })
    }
824 825 826 827 828 829 830 831 832 833

    // -> Reconnect Links
    await WIKI.models.pages.reconnectLinks({
      locale: page.localeCode,
      path: page.path,
      mode: 'delete'
    })
  }

  /**
834
   * Reconnect links to new/move/deleted page
835 836 837 838 839 840
   *
   * @param {Object} opts - Page parameters
   * @param {string} opts.path - Page Path
   * @param {string} opts.locale - Page Locale Code
   * @param {string} [opts.sourcePath] - Previous Page Path (move only)
   * @param {string} [opts.sourceLocale] - Previous Page Locale Code (move only)
841
   * @param {string} opts.mode - Page Update mode (create, move, delete)
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
   * @returns {Promise} Promise with no value
   */
  static async reconnectLinks (opts) {
    const pageHref = `/${opts.locale}/${opts.path}`
    let replaceArgs = {
      from: '',
      to: ''
    }
    switch (opts.mode) {
      case 'create':
        replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
        replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
        break
      case 'move':
        const prevPageHref = `/${opts.sourceLocale}/${opts.sourcePath}`
857
        replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-valid-page">`
858 859 860 861 862 863 864 865 866 867 868
        replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
        break
      case 'delete':
        replaceArgs.from = `<a href="${pageHref}" class="is-internal-link is-valid-page">`
        replaceArgs.to = `<a href="${pageHref}" class="is-internal-link is-invalid-page">`
        break
      default:
        return false
    }

    let affectedHashes = []
869 870
    // -> Perform replace and return affected page hashes (POSTGRES only)
    if (WIKI.config.db.type === 'postgres') {
871
      const qryHashes = await WIKI.models.pages.query()
872 873 874 875 876 877 878 879 880 881
        .returning('hash')
        .patch({
          render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
        })
        .whereIn('pages.id', function () {
          this.select('pageLinks.pageId').from('pageLinks').where({
            'pageLinks.path': opts.path,
            'pageLinks.localeCode': opts.locale
          })
        })
882
      affectedHashes = qryHashes.map(h => h.hash)
883
    } else {
884
      // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, MSSQL, SQLITE only)
885 886 887 888 889 890 891 892 893 894
      await WIKI.models.pages.query()
        .patch({
          render: WIKI.models.knex.raw('REPLACE(??, ?, ?)', ['render', replaceArgs.from, replaceArgs.to])
        })
        .whereIn('pages.id', function () {
          this.select('pageLinks.pageId').from('pageLinks').where({
            'pageLinks.path': opts.path,
            'pageLinks.localeCode': opts.locale
          })
        })
895
      const qryHashes = await WIKI.models.pages.query()
896 897 898 899 900 901 902
        .column('hash')
        .whereIn('pages.id', function () {
          this.select('pageLinks.pageId').from('pageLinks').where({
            'pageLinks.path': opts.path,
            'pageLinks.localeCode': opts.locale
          })
        })
903
      affectedHashes = qryHashes.map(h => h.hash)
904 905
    }
    for (const hash of affectedHashes) {
906 907
      await WIKI.models.pages.deletePageFromCache(hash)
      WIKI.events.outbound.emit('deletePageFromCache', hash)
908
    }
Nicolas Giard's avatar
Nicolas Giard committed
909 910
  }

911 912 913 914 915 916 917 918 919 920 921 922 923 924
  /**
   * Rebuild page tree for new/updated/deleted page
   *
   * @returns {Promise} Promise with no value
   */
  static async rebuildTree() {
    const rebuildJob = await WIKI.scheduler.registerJob({
      name: 'rebuild-tree',
      immediate: true,
      worker: true
    })
    return rebuildJob.finished
  }

925 926 927 928 929 930
  /**
   * Trigger the rendering of a page
   *
   * @param {Object} page Page Model Instance
   * @returns {Promise} Promise with no value
   */
931
  static async renderPage(page) {
932 933 934 935 936 937
    const renderJob = await WIKI.scheduler.registerJob({
      name: 'render-page',
      immediate: true,
      worker: true
    }, page.id)
    return renderJob.finished
938
  }
939

940 941 942 943 944 945
  /**
   * Fetch an Existing Page from Cache if possible, from DB otherwise and save render to Cache
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise of the Page Model Instance
   */
946
  static async getPage(opts) {
947
    // -> Get from cache first
948 949
    let page = await WIKI.models.pages.getPageFromCache(opts)
    if (!page) {
950
      // -> Get from DB
951
      page = await WIKI.models.pages.getPageFromDb(opts)
952
      if (page) {
953 954 955 956 957 958 959 960
        if (page.render) {
          // -> Save render to cache
          await WIKI.models.pages.savePageToCache(page)
        } else {
          // -> No render? Possible duplicate issue
          /* TODO: Detect duplicate and delete */
          throw new Error('Error while fetching page. Duplicate entry detected. Reload the page to try again.')
        }
961
      }
962 963 964 965
    }
    return page
  }

966 967 968 969 970 971
  /**
   * Fetch an Existing Page from the Database
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise of the Page Model Instance
   */
972
  static async getPageFromDb(opts) {
973
    const queryModeID = _.isNumber(opts)
974 975 976
    try {
      return WIKI.models.pages.query()
        .column([
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
          'pages.id',
          'pages.path',
          'pages.hash',
          'pages.title',
          'pages.description',
          'pages.isPrivate',
          'pages.isPublished',
          'pages.privateNS',
          'pages.publishStartDate',
          'pages.publishEndDate',
          'pages.content',
          'pages.render',
          'pages.toc',
          'pages.contentType',
          'pages.createdAt',
          'pages.updatedAt',
          'pages.editorKey',
          'pages.localeCode',
          'pages.authorId',
          'pages.creatorId',
NGPixel's avatar
NGPixel committed
997
          'pages.extra',
998 999 1000 1001 1002 1003 1004
          {
            authorName: 'author.name',
            authorEmail: 'author.email',
            creatorName: 'creator.name',
            creatorEmail: 'creator.email'
          }
        ])
NGPixel's avatar
NGPixel committed
1005 1006
        .joinRelated('author')
        .joinRelated('creator')
1007 1008 1009
        .withGraphJoined('tags')
        .modifyGraph('tags', builder => {
          builder.select('tag', 'title')
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        })
        .where(queryModeID ? {
          'pages.id': opts
        } : {
          'pages.path': opts.path,
          'pages.localeCode': opts.locale
        })
        // .andWhere(builder => {
        //   if (queryModeID) return
        //   builder.where({
        //     'pages.isPublished': true
        //   }).orWhere({
        //     'pages.isPublished': false,
        //     'pages.authorId': opts.userId
        //   })
        // })
        // .andWhere(builder => {
        //   if (queryModeID) return
        //   if (opts.isPrivate) {
        //     builder.where({ 'pages.isPrivate': true, 'pages.privateNS': opts.privateNS })
        //   } else {
        //     builder.where({ 'pages.isPrivate': false })
        //   }
        // })
        .first()
    } catch (err) {
      WIKI.logger.warn(err)
      throw err
    }
1039 1040
  }

1041 1042 1043 1044 1045 1046
  /**
   * Save a Page Model Instance to Cache
   *
   * @param {Object} page Page Model Instance
   * @returns {Promise} Promise with no value
   */
1047
  static async savePageToCache(page) {
1048
    const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${page.hash}.bin`)
1049
    await fs.outputFile(cachePath, WIKI.models.pages.cacheSchema.encode({
Nicolas Giard's avatar
Nicolas Giard committed
1050
      id: page.id,
1051 1052 1053 1054 1055 1056
      authorId: page.authorId,
      authorName: page.authorName,
      createdAt: page.createdAt,
      creatorId: page.creatorId,
      creatorName: page.creatorName,
      description: page.description,
NGPixel's avatar
NGPixel committed
1057
      editorKey: page.editorKey,
NGPixel's avatar
NGPixel committed
1058
      extra: {
1059 1060
        css: _.get(page, 'extra.css', ''),
        js: _.get(page, 'extra.js', '')
NGPixel's avatar
NGPixel committed
1061
      },
1062 1063
      isPrivate: page.isPrivate === 1 || page.isPrivate === true,
      isPublished: page.isPublished === 1 || page.isPublished === true,
1064 1065 1066
      publishEndDate: page.publishEndDate,
      publishStartDate: page.publishStartDate,
      render: page.render,
1067
      tags: page.tags.map(t => _.pick(t, ['tag', 'title'])),
1068
      title: page.title,
1069
      toc: _.isString(page.toc) ? page.toc : JSON.stringify(page.toc),
1070 1071 1072 1073
      updatedAt: page.updatedAt
    }))
  }

1074 1075 1076 1077 1078 1079
  /**
   * Fetch an Existing Page from Cache
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise of the Page Model Instance
   */
1080 1081
  static async getPageFromCache(opts) {
    const pageHash = pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' })
1082
    const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${pageHash}.bin`)
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100

    try {
      const pageBuffer = await fs.readFile(cachePath)
      let page = WIKI.models.pages.cacheSchema.decode(pageBuffer)
      return {
        ...page,
        path: opts.path,
        localeCode: opts.locale,
        isPrivate: opts.isPrivate
      }
    } catch (err) {
      if (err.code === 'ENOENT') {
        return false
      }
      WIKI.logger.error(err)
      throw err
    }
  }
Nicolas Giard's avatar
Nicolas Giard committed
1101

1102 1103 1104
  /**
   * Delete an Existing Page from Cache
   *
NGPixel's avatar
NGPixel committed
1105
   * @param {String} page Page Unique Hash
1106 1107
   * @returns {Promise} Promise with no value
   */
NGPixel's avatar
NGPixel committed
1108 1109
  static async deletePageFromCache(hash) {
    return fs.remove(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${hash}.bin`))
Nicolas Giard's avatar
Nicolas Giard committed
1110
  }
1111

1112 1113 1114
  /**
   * Flush the contents of the Cache
   */
Nick's avatar
Nick committed
1115
  static async flushCache() {
1116
    return fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache`))
Nick's avatar
Nick committed
1117 1118
  }

1119 1120 1121 1122 1123 1124 1125 1126
  /**
   * Migrate all pages from a source locale to the target locale
   *
   * @param {Object} opts Migration properties
   * @param {string} opts.sourceLocale Source Locale Code
   * @param {string} opts.targetLocale Target Locale Code
   * @returns {Promise} Promise with no value
   */
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
  static async migrateToLocale({ sourceLocale, targetLocale }) {
    return WIKI.models.pages.query()
      .patch({
        localeCode: targetLocale
      })
      .where({
        localeCode: sourceLocale
      })
      .whereNotExists(function() {
        this.select('id').from('pages AS pagesm').where('pagesm.localeCode', targetLocale).andWhereRaw('pagesm.path = pages.path')
      })
  }

1140 1141 1142 1143 1144 1145
  /**
   * Clean raw HTML from content for use in search engines
   *
   * @param {string} rawHTML Raw HTML
   * @returns {string} Cleaned Content Text
   */
1146
  static cleanHTML(rawHTML = '') {
1147
    let data = striptags(rawHTML || '', [], ' ')
1148
      .replace(emojiRegex(), '')
1149 1150
      // .replace(htmlEntitiesRegex, '')
    return he.decode(data)
1151 1152 1153 1154 1155
      .replace(punctuationRegex, ' ')
      .replace(/(\r\n|\n|\r)/gm, ' ')
      .replace(/\s\s+/g, ' ')
      .split(' ').filter(w => w.length > 1).join(' ').toLowerCase()
  }
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

  /**
   * Subscribe to HA propagation events
   */
  static subscribeToEvents() {
    WIKI.events.inbound.on('deletePageFromCache', hash => {
      WIKI.models.pages.deletePageFromCache(hash)
    })
    WIKI.events.inbound.on('flushCache', () => {
      WIKI.models.pages.flushCache()
    })
  }
1168
}