pages.js 34.1 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
      isPrivate: 'boolean',
      isPublished: 'boolean',
      publishEndDate: 'string',
      publishStartDate: 'string',
NGPixel's avatar
NGPixel committed
151
      contentType: 'string',
152
      render: 'string',
153 154 155 156 157 158
      tags: [
        {
          tag: 'string',
          title: 'string'
        }
      ],
NGPixel's avatar
NGPixel committed
159 160 161 162
      extra: {
        js: 'string',
        css: 'string'
      },
163
      title: 'string',
164
      toc: 'string',
165 166
      updatedAt: 'string'
    })
167 168
  }

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

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

Nick's avatar
Nick committed
187 188 189 190 191
  /**
   * Parse injected page metadata from raw content
   *
   * @param {String} raw Raw file contents
   * @param {String} contentType Content Type
192
   * @returns {Object} Parsed Page Metadata with Raw Content
Nick's avatar
Nick committed
193 194 195
   */
  static parseMetadata (raw, contentType) {
    let result
196 197 198 199
    try {
      switch (contentType) {
        case 'markdown':
          result = frontmatterRegex.markdown.exec(raw)
Nick's avatar
Nick committed
200 201
          if (result[2]) {
            return {
202 203 204 205 206 207 208 209 210 211 212 213
              ...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]
              }
Nick's avatar
Nick committed
214 215
            }
          }
216 217 218 219 220 221 222 223
          break
        case 'html':
          result = frontmatterRegex.html.exec(raw)
          if (result[2]) {
            return {
              ...yaml.safeLoad(result[2]),
              content: result[3]
            }
Nick's avatar
Nick committed
224
          }
225 226 227 228
          break
      }
    } catch (err) {
      WIKI.logger.warn('Failed to parse page metadata. Invalid syntax.')
Nick's avatar
Nick committed
229 230 231 232 233 234
    }
    return {
      content: raw
    }
  }

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

247
    // -> Remove trailing slash
NGPixel's avatar
NGPixel committed
248
    if (opts.path.endsWith('/')) {
249 250 251
      opts.path = opts.path.slice(0, -1)
    }

252 253 254 255 256
    // -> Remove starting slash
    if (opts.path.startsWith('/')) {
      opts.path = opts.path.slice(1)
    }

NGPixel's avatar
NGPixel committed
257 258 259 260 261 262 263 264 265
    // -> 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
266 267 268 269 270
    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
271
    // -> Check for empty content
Nick's avatar
Nick committed
272 273 274 275
    if (!opts.content || _.trim(opts.content).length < 1) {
      throw new WIKI.Error.PageEmptyContent()
    }

NGPixel's avatar
NGPixel committed
276
    // -> Format CSS Scripts
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    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
298
    // -> Create page
299
    await WIKI.models.pages.query().insert({
NGPixel's avatar
NGPixel committed
300
      authorId: opts.user.id,
301
      content: opts.content,
NGPixel's avatar
NGPixel committed
302
      creatorId: opts.user.id,
303
      contentType: _.get(_.find(WIKI.data.editors, ['key', opts.editor]), `contentType`, 'text'),
304 305
      description: opts.description,
      editorKey: opts.editor,
306
      hash: pageHelper.generateHash({ path: opts.path, locale: opts.locale, privateNS: opts.isPrivate ? 'TODO' : '' }),
307 308 309 310
      isPrivate: opts.isPrivate,
      isPublished: opts.isPublished,
      localeCode: opts.locale,
      path: opts.path,
311 312 313
      publishEndDate: opts.publishEndDate || '',
      publishStartDate: opts.publishStartDate || '',
      title: opts.title,
314 315 316 317 318
      toc: '[]',
      extra: JSON.stringify({
        js: scriptJs,
        css: scriptCss
      })
319
    })
320 321 322
    const page = await WIKI.models.pages.getPageFromDb({
      path: opts.path,
      locale: opts.locale,
NGPixel's avatar
NGPixel committed
323
      userId: opts.user.id,
324 325
      isPrivate: opts.isPrivate
    })
326

327
    // -> Save Tags
328
    if (opts.tags && opts.tags.length > 0) {
329 330 331
      await WIKI.models.tags.associateTags({ tags: opts.tags, page })
    }

332
    // -> Render page to HTML
333
    await WIKI.models.pages.renderPage(page)
334

335 336 337
    // -> Rebuild page tree
    await WIKI.models.pages.rebuildTree()

338 339 340
    // -> Add to Search Index
    const pageContents = await WIKI.models.pages.query().findById(page.id).select('render')
    page.safeContent = WIKI.models.pages.cleanHTML(pageContents.render)
341
    await WIKI.data.searchEngine.created(page)
342 343

    // -> Add to Storage
Nick's avatar
Nick committed
344 345 346 347 348 349
    if (!opts.skipStorage) {
      await WIKI.models.storage.pageEvent({
        event: 'created',
        page
      })
    }
350

351 352 353 354 355 356 357
    // -> Reconnect Links
    await WIKI.models.pages.reconnectLinks({
      locale: page.localeCode,
      path: page.path,
      mode: 'create'
    })

358 359 360
    // -> Get latest updatedAt
    page.updatedAt = await WIKI.models.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)

361 362 363
    return page
  }

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

NGPixel's avatar
NGPixel committed
377 378
    // -> Check for page access
    if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
379 380
      locale: ogPage.localeCode,
      path: ogPage.path
NGPixel's avatar
NGPixel committed
381 382 383 384 385
    })) {
      throw new WIKI.Error.PageUpdateForbidden()
    }

    // -> Check for empty content
Nick's avatar
Nick committed
386 387 388 389
    if (!opts.content || _.trim(opts.content).length < 1) {
      throw new WIKI.Error.PageEmptyContent()
    }

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

398 399 400 401 402
    // -> Format Extra Properties
    if (!_.isPlainObject(ogPage.extra)) {
      ogPage.extra = {}
    }

NGPixel's avatar
NGPixel committed
403
    // -> Format CSS Scripts
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
    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
425
    // -> Update page
426
    await WIKI.models.pages.query().patch({
NGPixel's avatar
NGPixel committed
427
      authorId: opts.user.id,
428 429
      content: opts.content,
      description: opts.description,
Nick's avatar
Nick committed
430
      isPublished: opts.isPublished === true || opts.isPublished === 1,
431 432
      publishEndDate: opts.publishEndDate || '',
      publishStartDate: opts.publishStartDate || '',
433 434 435 436 437 438
      title: opts.title,
      extra: JSON.stringify({
        ...ogPage.extra,
        js: scriptJs,
        css: scriptCss
      })
439
    }).where('id', ogPage.id)
440
    let page = await WIKI.models.pages.getPageFromDb(ogPage.id)
441

442 443 444
    // -> Save Tags
    await WIKI.models.tags.associateTags({ tags: opts.tags, page })

445
    // -> Render page to HTML
446
    await WIKI.models.pages.renderPage(page)
NGPixel's avatar
NGPixel committed
447
    WIKI.events.outbound.emit('deletePageFromCache', page.hash)
448 449 450 451

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

    // -> Update on Storage
Nick's avatar
Nick committed
455 456 457 458 459 460
    if (!opts.skipStorage) {
      await WIKI.models.storage.pageEvent({
        event: 'updated',
        page
      })
    }
NGPixel's avatar
NGPixel committed
461 462

    // -> Perform move?
463
    if ((opts.locale && opts.locale !== page.localeCode) || (opts.path && opts.path !== page.path)) {
464 465 466 467 468 469 470 471
      // -> Check target path access
      if (!WIKI.auth.checkAccess(opts.user, ['write:pages'], {
        locale: opts.locale,
        path: opts.path
      })) {
        throw new WIKI.Error.PageMoveForbidden()
      }

NGPixel's avatar
NGPixel committed
472 473 474 475 476 477
      await WIKI.models.pages.movePage({
        id: page.id,
        destinationLocale: opts.locale,
        destinationPath: opts.path,
        user: opts.user
      })
478 479 480 481 482
    } 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
483 484
    }

485 486 487
    // -> Get latest updatedAt
    page.updatedAt = await WIKI.models.pages.query().findById(page.id).select('updatedAt').then(r => r.updatedAt)

488 489
    return page
  }
490

NGPixel's avatar
NGPixel committed
491 492 493 494 495 496 497 498 499 500 501 502 503
  /**
   * 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')
    }

504 505 506 507
    if (ogPage.editorKey === opts.editor) {
      throw new Error('Page is already using this editor. Nothing to convert.')
    }

NGPixel's avatar
NGPixel committed
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
    // -> 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) {
536
          // Remove header anchors
NGPixel's avatar
NGPixel committed
537 538
          $('.toc-anchor').remove()

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
          // 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
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
          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}_`
        })

608 609 610 611 612 613 614 615 616
        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
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
        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
659 660 661 662 663 664 665
  /**
   * Move a Page
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise with no value
   */
  static async movePage(opts) {
666 667 668 669 670 671 672 673 674
    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
675 676 677 678
    if (!page) {
      throw new WIKI.Error.PageNotFound()
    }

679
    // -> Validate path
680
    if (opts.destinationPath.includes('.') || opts.destinationPath.includes(' ') || opts.destinationPath.includes('\\') || opts.destinationPath.includes('//')) {
681 682 683 684
      throw new WIKI.Error.PageIllegalPath()
    }

    // -> Remove trailing slash
NGPixel's avatar
NGPixel committed
685
    if (opts.destinationPath.endsWith('/')) {
686 687 688
      opts.destinationPath = opts.destinationPath.slice(0, -1)
    }

689 690 691 692 693
    // -> Remove starting slash
    if (opts.destinationPath.startsWith('/')) {
      opts.destinationPath = opts.destinationPath.slice(1)
    }

NGPixel's avatar
NGPixel committed
694 695
    // -> Check for source page access
    if (!WIKI.auth.checkAccess(opts.user, ['manage:pages'], {
696 697
      locale: page.localeCode,
      path: page.path
NGPixel's avatar
NGPixel committed
698 699 700 701 702 703 704 705 706 707 708 709
    })) {
      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
710
    const destPage = await WIKI.models.pages.query().findOne({
NGPixel's avatar
NGPixel committed
711 712 713 714 715 716 717 718 719 720
      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
721 722
      action: 'moved',
      versionDate: page.updatedAt
NGPixel's avatar
NGPixel committed
723 724 725 726 727
    })

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

    // -> Move page
728
    const destinationTitle = (page.title === _.last(page.path.split('/')) ? _.last(opts.destinationPath.split('/')) : page.title)
NGPixel's avatar
NGPixel committed
729 730 731
    await WIKI.models.pages.query().patch({
      path: opts.destinationPath,
      localeCode: opts.destinationLocale,
732
      title: destinationTitle,
NGPixel's avatar
NGPixel committed
733 734
      hash: destinationHash
    }).findById(page.id)
735 736
    await WIKI.models.pages.deletePageFromCache(page.hash)
    WIKI.events.outbound.emit('deletePageFromCache', page.hash)
NGPixel's avatar
NGPixel committed
737

738 739 740
    // -> Rebuild page tree
    await WIKI.models.pages.rebuildTree()

NGPixel's avatar
NGPixel committed
741
    // -> Rename in Search Index
742 743
    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
744 745 746 747
    await WIKI.data.searchEngine.renamed({
      ...page,
      destinationPath: opts.destinationPath,
      destinationLocaleCode: opts.destinationLocale,
748
      title: destinationTitle,
NGPixel's avatar
NGPixel committed
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
      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
        }
      })
    }

768
    // -> Reconnect Links : Changing old links to the new path
NGPixel's avatar
NGPixel committed
769 770 771 772 773 774 775
    await WIKI.models.pages.reconnectLinks({
      sourceLocale: page.localeCode,
      sourcePath: page.path,
      locale: opts.destinationLocale,
      path: opts.destinationPath,
      mode: 'move'
    })
776

777 778 779 780 781 782
    // -> 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
783 784
  }

785 786 787 788 789 790
  /**
   * Delete an Existing Page
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise with no value
   */
Nicolas Giard's avatar
Nicolas Giard committed
791
  static async deletePage(opts) {
NGPixel's avatar
NGPixel committed
792
    const page = await WIKI.models.pages.getPageFromDb(_.has(opts, 'id') ? opts.id : opts)
Nicolas Giard's avatar
Nicolas Giard committed
793
    if (!page) {
794
      throw new WIKI.Error.PageNotFound()
Nicolas Giard's avatar
Nicolas Giard committed
795
    }
NGPixel's avatar
NGPixel committed
796 797 798 799 800 801 802 803 804 805

    // -> 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
806 807
    await WIKI.models.pageHistory.addVersion({
      ...page,
NGPixel's avatar
NGPixel committed
808 809
      action: 'deleted',
      versionDate: page.updatedAt
Nicolas Giard's avatar
Nicolas Giard committed
810
    })
NGPixel's avatar
NGPixel committed
811 812

    // -> Delete page
Nicolas Giard's avatar
Nicolas Giard committed
813
    await WIKI.models.pages.query().delete().where('id', page.id)
814 815
    await WIKI.models.pages.deletePageFromCache(page.hash)
    WIKI.events.outbound.emit('deletePageFromCache', page.hash)
816

817 818 819
    // -> Rebuild page tree
    await WIKI.models.pages.rebuildTree()

820
    // -> Delete from Search Index
821
    await WIKI.data.searchEngine.deleted(page)
822 823

    // -> Delete from Storage
Nick's avatar
Nick committed
824 825 826 827 828 829
    if (!opts.skipStorage) {
      await WIKI.models.storage.pageEvent({
        event: 'deleted',
        page
      })
    }
830 831 832 833 834 835 836 837 838 839

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

  /**
840
   * Reconnect links to new/move/deleted page
841 842 843 844 845 846
   *
   * @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)
847
   * @param {string} opts.mode - Page Update mode (create, move, delete)
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
   * @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}`
863
        replaceArgs.from = `<a href="${prevPageHref}" class="is-internal-link is-valid-page">`
864 865 866 867 868 869 870 871 872 873 874
        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 = []
875 876
    // -> Perform replace and return affected page hashes (POSTGRES only)
    if (WIKI.config.db.type === 'postgres') {
877
      const qryHashes = await WIKI.models.pages.query()
878 879 880 881 882 883 884 885 886 887
        .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
          })
        })
888
      affectedHashes = qryHashes.map(h => h.hash)
889
    } else {
890
      // -> Perform replace, then query affected page hashes (MYSQL, MARIADB, MSSQL, SQLITE only)
891 892 893 894 895 896 897 898 899 900
      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
          })
        })
901
      const qryHashes = await WIKI.models.pages.query()
902 903 904 905 906 907 908
        .column('hash')
        .whereIn('pages.id', function () {
          this.select('pageLinks.pageId').from('pageLinks').where({
            'pageLinks.path': opts.path,
            'pageLinks.localeCode': opts.locale
          })
        })
909
      affectedHashes = qryHashes.map(h => h.hash)
910 911
    }
    for (const hash of affectedHashes) {
912 913
      await WIKI.models.pages.deletePageFromCache(hash)
      WIKI.events.outbound.emit('deletePageFromCache', hash)
914
    }
Nicolas Giard's avatar
Nicolas Giard committed
915 916
  }

917 918 919 920 921 922 923 924 925 926 927 928 929 930
  /**
   * 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
  }

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

946 947 948 949 950 951
  /**
   * 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
   */
952
  static async getPage(opts) {
953
    // -> Get from cache first
954 955
    let page = await WIKI.models.pages.getPageFromCache(opts)
    if (!page) {
956
      // -> Get from DB
957
      page = await WIKI.models.pages.getPageFromDb(opts)
958
      if (page) {
959 960 961 962
        if (page.render) {
          // -> Save render to cache
          await WIKI.models.pages.savePageToCache(page)
        } else {
963 964
          // -> No render? Last page render failed...
          throw new Error('Page has no rendered version. Looks like the Last page render failed. Try to edit the page and save it again.')
965
        }
966
      }
967 968 969 970
    }
    return page
  }

971 972 973 974 975 976
  /**
   * Fetch an Existing Page from the Database
   *
   * @param {Object} opts Page Properties
   * @returns {Promise} Promise of the Page Model Instance
   */
977
  static async getPageFromDb(opts) {
978
    const queryModeID = _.isNumber(opts)
979 980 981
    try {
      return WIKI.models.pages.query()
        .column([
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
          '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
1002
          'pages.extra',
1003 1004 1005 1006 1007 1008 1009
          {
            authorName: 'author.name',
            authorEmail: 'author.email',
            creatorName: 'creator.name',
            creatorEmail: 'creator.email'
          }
        ])
NGPixel's avatar
NGPixel committed
1010 1011
        .joinRelated('author')
        .joinRelated('creator')
1012 1013 1014
        .withGraphJoined('tags')
        .modifyGraph('tags', builder => {
          builder.select('tag', 'title')
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
        })
        .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
    }
1044 1045
  }

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

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

    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
1107

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

1118 1119 1120
  /**
   * Flush the contents of the Cache
   */
Nick's avatar
Nick committed
1121
  static async flushCache() {
1122
    return fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache`))
Nick's avatar
Nick committed
1123 1124
  }

1125 1126 1127 1128 1129 1130 1131 1132
  /**
   * 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
   */
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
  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')
      })
  }

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

  /**
   * 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()
    })
  }
1174
}