All files / models page.js

53.79% Statements 341/634
41.85% Branches 95/227
46.15% Functions 78/169
53.49% Lines 337/630

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 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 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 126015x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x     10x       5x       2x     15x                                     14x 14x           2x                       15x 15x   15x       15x         15x       15x       15x 9x 2x     7x     15x       15x 6x 1x 5x 2x     3x     15x 5x 3x     2x       2x     15x                 15x               15x           15x       15x       15x                                                   15x                                                     15x                               15x           15x                                                 15x 2x 2x       2x     15x 1x 1x   1x     15x 1x 1x 1x 1x 1x     1x         15x 3x   3x 3x     3x 3x   3x 3x                 3x 3x       3x             15x                             15x                                               15x 3x   3x 3x 3x         3x         15x                           15x 1x 1x 1x   1x   1x     15x 4x 2x     4x   4x     15x 1x     15x 2x 1x   2x     15x 3x     15x 5x       5x 5x 5x 2x       3x     15x 59x                           59x 59x 649x 649x 55x       59x     15x       15x           15x 5x 5x     15x                   15x 3x   3x 3x 3x       3x     3x         15x 2x   2x 2x   2x 1x     1x                 15x 1x   1x 1x 1x       1x 1x       1x 1x 1x                               15x 3x   3x 3x 3x       3x         15x 6x   6x 6x 6x     6x       6x         15x                                 15x                                                       15x                           15x                                         15x                                                           15x                                           15x 5x 5x 5x   5x     5x           5x 5x 5x     5x 5x 5x 5x     5x   5x                                   5x 5x         5x 5x             15x 5x 5x     15x                 15x         15x           15x 3x 3x   3x 3x       3x         15x                                           15x                             15x 6x 6x 6x 6x     6x 6x 6x         6x 6x 6x 6x 6x 6x           6x 6x               15x 7x 7x 7x 7x 7x     7x       7x 7x 7x       7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 1x     6x 6x   6x 6x                     15x                                                         15x                                                         15x                                                                       15x                                             15x                               15x             15x                                 15x                                       15x 3x 3x 3x 3x 3x   3x 3x 3x     3x     3x     3x   3x           3x   3x         15x 2x 2x 5x   5x     15x 1x 1x 1x 1x 2x 2x 2x   2x 2x           2x 1x   2x   1x     15x 1x 1x 1x   3x                   1x   3x 3x       3x 3x 3x               15x           15x 9x 9x 9x   9x 9x 9x   9x 9x   9x 9x 9x 36x 36x 27x 27x     9x   9x     15x 84x 84x   6x   78x     15x 15x 15x 15x 15x 15x 15x 15x   15x    
module.exports = function(crowi) {
  const debug = require('debug')('crowi:models:page')
  const mongoose = require('mongoose')
  const ObjectId = mongoose.Schema.Types.ObjectId
  const GRANT_PUBLIC = 1
  const GRANT_RESTRICTED = 2
  const GRANT_SPECIFIED = 3
  const GRANT_OWNER = 4
  const PAGE_GRANT_ERROR = 1
  const STATUS_WIP = 'wip'
  const STATUS_PUBLISHED = 'published'
  const STATUS_DELETED = 'deleted'
  const STATUS_DEPRECATED = 'deprecated'
  const TYPE_PORTAL = 'portal'
  const TYPE_USER = 'user'
  const TYPE_PUBLIC = 'public'
  const pageEvent = crowi.event('Page')
 
  function isPortalPath(path) {
    return path.endsWith('/')
  }
 
  function addTrailingSlash(path) {
    return path.endsWith('/') ? path : `${path}/`
  }
 
  function removeTrailingSlash(string) {
    return string.endsWith('/') ? string.substring(0, string.length - 1) : string
  }
 
  const pageSchema = new mongoose.Schema(
    {
      path: { type: String, required: true, index: true, unique: true },
      revision: { type: ObjectId, ref: 'Revision' },
      redirectTo: { type: String, index: true },
      status: { type: String, default: STATUS_PUBLISHED, index: true },
      grant: { type: Number, default: GRANT_PUBLIC, index: true },
      grantedUsers: [{ type: ObjectId, ref: 'User' }],
      creator: { type: ObjectId, ref: 'User', index: true },
      // lastUpdateUser: this schema is from 1.5.x (by deletion feature), and null is default.
      // the last update user on the screen is by revesion.author for B.C.
      lastUpdateUser: { type: ObjectId, ref: 'User', index: true },
      liker: [{ type: ObjectId, ref: 'User', index: true }],
      seenUsers: [{ type: ObjectId, ref: 'User', index: true }],
      commentCount: { type: Number, default: 0 },
      extended: {
        type: String,
        default: '{}',
        get: function(data) {
          try {
            return JSON.parse(data)
          } catch (e) {
            return data
          }
        },
        set: function(data) {
          return JSON.stringify(data)
        },
      },
      createdAt: { type: Date, default: Date.now },
      updatedAt: Date,
    },
    {
      toJSON: { getters: true },
      toObject: { getters: true },
    },
  )
 
  pageEvent.on('create', pageEvent.onCreate)
  pageEvent.on('update', pageEvent.onUpdate)
 
  pageSchema.methods.isWIP = function() {
    return this.status === STATUS_WIP
  }
 
  pageSchema.methods.isPublished = function() {
    // null: this is for B.C.
    return this.status === null || this.status === STATUS_PUBLISHED
  }
 
  pageSchema.methods.isDeleted = function() {
    return this.status === STATUS_DELETED
  }
 
  pageSchema.methods.isDeprecated = function() {
    return this.status === STATUS_DEPRECATED
  }
 
  pageSchema.methods.isPublic = function() {
    if (!this.grant || this.grant == GRANT_PUBLIC) {
      return true
    }
 
    return false
  }
 
  pageSchema.methods.isPortal = function() {
    return isPortalPath(this.path)
  }
 
  pageSchema.methods.isCreator = function(userData) {
    if (this.populated('creator') && this.creator._id.toString() === userData._id.toString()) {
      return true
    } else if (this.creator.toString() === userData._id.toString()) {
      return true
    }
 
    return false
  }
 
  pageSchema.methods.isGrantedFor = function(userData) {
    if (this.isPublic() || this.isCreator(userData)) {
      return true
    }
 
    Iif (this.grantedUsers.indexOf(userData._id) >= 0) {
      return true
    }
 
    return false
  }
 
  pageSchema.methods.isLatestRevision = function() {
    // populate されていなくて判断できない
    if (!this.latestRevision || !this.revision) {
      return true
    }
 
    return this.latestRevision == this.revision._id.toString()
  }
 
  pageSchema.methods.isUpdatable = function(previousRevision) {
    var revision = this.latestRevision || this.revision
    if (revision != previousRevision) {
      return false
    }
    return true
  }
 
  pageSchema.methods.isLiked = function(userData) {
    return this.liker.some(function(likedUser) {
      return likedUser == userData._id.toString()
    })
  }
 
  pageSchema.methods.isRedirectOriginPage = function() {
    return this.redirectTo !== null
  }
 
  pageSchema.methods.isUnlinkable = function(userData) {
    return this.isRedirectOriginPage() && this.isGrantedFor(userData)
  }
 
  pageSchema.methods.like = function(userData) {
    var self = this
    var Activity = crowi.model('Activity')
 
    return new Promise(function(resolve, reject) {
      var added = self.liker.addToSet(userData._id)
      if (added.length > 0) {
        self.save(function(err, data) {
          if (err) {
            return reject(err)
          }
          debug('liker updated!', added)
 
          Activity.createByPageLike(data, userData)
            .then(activityLog => debug('Activity created', activityLog))
            .catch(err => debug('Activity err', err))
 
          return resolve(data)
        })
      } else {
        debug('liker not updated')
        return reject(self)
      }
    })
  }
 
  pageSchema.methods.unlike = function(userData, callback) {
    var self = this
    var Activity = crowi.model('Activity')
 
    return new Promise(function(resolve, reject) {
      var beforeCount = self.liker.length
      self.liker.pull(userData._id)
      if (self.liker.length != beforeCount) {
        self.save(function(err, data) {
          if (err) {
            return reject(err)
          }
 
          Activity.removeByPageUnlike(data, userData)
            .then(activityLog => debug('Activity removed'))
            .catch(err => debug('Activity remove err', err))
 
          return resolve(data)
        })
      } else {
        debug('liker not updated')
        return reject(self)
      }
    })
  }
 
  // Unlink: Remove redirect origin page
  pageSchema.methods.unlink = async function(userData) {
    const Page = crowi.model('Page')
    if (this.isUnlinkable(userData)) {
      debug('Unlink page', this._id, this.path)
      try {
        const redirectPage = await Page.removePageById(this._id)
        debug('Redirect Page deleted', redirectPage.path)
      } catch (err) {
        debug('Error occured while get setting', err, err.stack)
        throw new Error(`Failed to delete redirect page (${this.path}).`)
      }
    } else {
      throw new Error('Page is not unlinkable')
    }
  }
 
  pageSchema.methods.isSeenUser = function(userData) {
    return this.seenUsers.some(function(seenUser) {
      return seenUser.equals(userData._id)
    })
  }
 
  pageSchema.methods.seen = function(userData) {
    var self = this
 
    if (this.isSeenUser(userData)) {
      debug('seenUsers not updated')
      return Promise.resolve(this)
    }
 
    return new Promise(function(resolve, reject) {
      if (!userData || !userData._id) {
        reject(new Error('User data is not valid'))
      }
 
      var added = self.seenUsers.addToSet(userData)
      self.save(function(err, data) {
        if (err) {
          return reject(err)
        }
 
        debug('seenUsers updated!', added)
        return resolve(self)
      })
    })
  }
 
  pageSchema.methods.getSlackChannel = function() {
    var extended = this.get('extended')
    Iif (!extended) {
      return ''
    }
 
    return extended.slack || ''
  }
 
  pageSchema.methods.updateSlackChannel = function(slackChannel) {
    var extended = this.extended
    extended.slack = slackChannel
 
    return this.updateExtended(extended)
  }
 
  pageSchema.methods.updateExtended = function(extended) {
    var page = this
    page.extended = extended
    return new Promise(function(resolve, reject) {
      return page.save(function(err, doc) {
        Iif (err) {
          return reject(err)
        }
        return resolve(doc)
      })
    })
  }
 
  pageSchema.statics.populatePageData = function(pageData, revisionId) {
    var Page = crowi.model('Page')
 
    pageData.latestRevision = pageData.revision
    Iif (revisionId) {
      pageData.revision = revisionId
    }
    pageData.likerCount = pageData.liker.length || 0
    pageData.seenUsersCount = pageData.seenUsers.length || 0
 
    return new Promise(function(resolve, reject) {
      pageData.populate(
        [
          { path: 'lastUpdateUser', model: 'User' },
          { path: 'creator', model: 'User' },
          { path: 'revision', model: 'Revision' },
          // {path: 'liker', options: { limit: 11 }},
          // {path: 'seenUsers', options: { limit: 11 }},
        ],
        function(err, pageData) {
          Page.populate(pageData, { path: 'revision.author', model: 'User' }, function(err, data) {
            Iif (err) {
              return reject(err)
            }
 
            return resolve(data)
          })
        },
      )
    })
  }
 
  pageSchema.statics.populatePagesRevision = function(pages, revisions) {
    const Page = this
    if (pages.length !== revisions.length) {
      throw new TypeError('page.length must be equal revisions.length')
    }
    pages = pages.map((page, i) => {
      const revision = revisions[i]
      if (revision) {
        page.revision = revision
      }
      return page
    })
    return Page.populate(pages, { path: 'revision', model: 'Revision' })
  }
 
  pageSchema.statics.populatePageListToAnyObjects = function(pageIdObjectArray) {
    var Page = this
    var pageIdMappings = {}
    var pageIds = pageIdObjectArray.map(function(page, idx) {
      if (!page._id) {
        throw new Error('Pass the arg of populatePageListToAnyObjects() must have _id on each element.')
      }
 
      pageIdMappings[String(page._id)] = idx
      return page._id
    })
 
    return new Promise(function(resolve, reject) {
      Page.findListByPageIds(pageIds, { limit: 100 }) // limit => if the pagIds is greater than 100, ignore
        .then(function(pages) {
          pages.forEach(function(page) {
            Object.assign(pageIdObjectArray[pageIdMappings[String(page._id)]], page._doc)
          })
 
          resolve(pageIdObjectArray)
        })
    })
  }
 
  pageSchema.statics.updateCommentCount = function(page, num) {
    var self = this
 
    return new Promise(function(resolve, reject) {
      self.update({ _id: page }, { commentCount: num }, {}, function(err, data) {
        Iif (err) {
          debug('Update commentCount Error', err)
          return reject(err)
        }
 
        return resolve(data)
      })
    })
  }
 
  pageSchema.statics.hasPortalPage = function(path, user, revisionId) {
    var self = this
    return new Promise(function(resolve, reject) {
      self
        .findPage(path, user, revisionId)
        .then(function(page) {
          resolve(page)
        })
        .catch(function(err) {
          resolve(null) // check only has portal page, through error
        })
    })
  }
 
  pageSchema.statics.getGrantLabels = function() {
    var grantLabels = {}
    grantLabels[GRANT_PUBLIC] = 'Public' // 公開
    grantLabels[GRANT_RESTRICTED] = 'Anyone with the link' // リンクを知っている人のみ
    // grantLabels[GRANT_SPECIFIED]  = 'Specified users only'; // 特定ユーザーのみ
    grantLabels[GRANT_OWNER] = 'Just me' // 自分のみ
 
    return grantLabels
  }
 
  pageSchema.statics.normalizePath = function(path) {
    if (!path.match(/^\//)) {
      path = '/' + path
    }
 
    path = path.replace(/\/\s+?/g, '/').replace(/\s+\//g, '/')
 
    return path
  }
 
  pageSchema.statics.getUserPagePath = function(user) {
    return '/user/' + user.username
  }
 
  pageSchema.statics.getDeletedPageName = function(path) {
    if (path.match('/')) {
      path = path.substr(1)
    }
    return '/trash/' + path
  }
 
  pageSchema.statics.getRevertDeletedPageName = function(path) {
    return path.replace('/trash', '')
  }
 
  pageSchema.statics.isDeletableName = function(path) {
    var notDeletable = [
      /^\/user\/[^/]+$/, // user page
    ]
 
    for (var i = 0; i < notDeletable.length; i++) {
      var pattern = notDeletable[i]
      if (path.match(pattern)) {
        return false
      }
    }
 
    return true
  }
 
  pageSchema.statics.isCreatableName = function(name) {
    var forbiddenPages = [
      /\^|\$|\*|\+|\?|#/,
      /^\/_.*/, // /_api/* and so on
      /^\/-\/.*/,
      /^\/_r\/.*/,
      /^\/user\/[^/]+\/(bookmarks|comments|activities|pages|recent-create|recent-edit)/, // reserved
      /^\/?https?:\/\/.+$/, // avoid miss in renaming
      /\/{2,}/, // avoid miss in renaming
      /\s+\/\s+/, // avoid miss in renaming
      /.+\/edit$/,
      /.+\.md$/,
      /^\/(installer|register|login|logout|admin|me|files|trash|paste|comments)(\/.*|$)/,
    ]
 
    var isCreatable = true
    forbiddenPages.forEach(function(page) {
      var pageNameReg = new RegExp(page)
      if (name.match(pageNameReg)) {
        isCreatable = false
      }
    })
 
    return isCreatable
  }
 
  pageSchema.statics.fixToCreatableName = function(path) {
    return path.replace(/\/\//g, '/')
  }
 
  pageSchema.statics.updateRevision = function(pageId, revisionId, cb) {
    this.update({ _id: pageId }, { revision: revisionId }, {}, function(err, data) {
      cb(err, data)
    })
  }
 
  pageSchema.statics.exists = async function(query) {
    const count = await this.count(query)
    return count > 0
  }
 
  pageSchema.statics.findUpdatedList = function(offset, limit, cb) {
    this.find({})
      .sort({ updatedAt: -1 })
      .skip(offset)
      .limit(limit)
      .exec(function(err, data) {
        cb(err, data)
      })
  }
 
  pageSchema.statics.findPageById = function(id) {
    var Page = this
 
    return new Promise(function(resolve, reject) {
      Page.findOne({ _id: id }, function(err, pageData) {
        Iif (err) {
          return reject(err)
        }
 
        Iif (pageData == null) {
          return reject(new Error('Page not found'))
        }
        return Page.populatePageData(pageData, null).then(resolve)
      })
    })
  }
 
  pageSchema.statics.findPageByIdAndGrantedUser = function(id, userData) {
    var Page = this
 
    return new Promise(function(resolve, reject) {
      Page.findPageById(id)
        .then(function(pageData) {
          if (userData && !pageData.isGrantedFor(userData)) {
            return reject(new Error('Page is not granted for the user')) // PAGE_GRANT_ERROR, null);
          }
 
          return resolve(pageData)
        })
        .catch(function(err) {
          return reject(err)
        })
    })
  }
 
  // find page and check if granted user
  pageSchema.statics.findPage = function(path, userData, revisionId, ignoreNotFound) {
    var self = this
 
    return new Promise(function(resolve, reject) {
      self.findOne({ path: path }, function(err, pageData) {
        Iif (err) {
          return reject(err)
        }
 
        Eif (pageData === null) {
          Iif (ignoreNotFound) {
            return resolve(null)
          }
 
          var pageNotFoundError = new Error('Page Not Found')
          pageNotFoundError.name = 'Crowi:Page:NotFound'
          return reject(pageNotFoundError)
        }
 
        if (!pageData.isGrantedFor(userData)) {
          return reject(new Error('Page is not granted for the user')) // PAGE_GRANT_ERROR, null);
        }
 
        self
          .populatePageData(pageData, revisionId || null)
          .then(resolve)
          .catch(reject)
      })
    })
  }
 
  // find page by path
  pageSchema.statics.findPageByPath = function(path) {
    var Page = this
 
    return new Promise(function(resolve, reject) {
      Page.findOne({ path: path }, function(err, pageData) {
        Iif (err || pageData === null) {
          return reject(err)
        }
 
        return resolve(pageData)
      })
    })
  }
 
  pageSchema.statics.isExistByPath = function(path) {
    var Page = this
 
    return new Promise(function(resolve, reject) {
      Page.findOne({ path: path }, function(err, pageData) {
        Iif (err) {
          return reject(err)
        }
        Iif (pageData === null) {
          return resolve(false)
        }
 
        return resolve(pageData._id)
      })
    })
  }
 
  pageSchema.statics.isExistById = function(id) {
    var Page = this
 
    return new Promise(function(resolve, reject) {
      Page.findOne({ _id: id }, function(err, pageData) {
        if (err) {
          return reject(err)
        }
        if (pageData === null) {
          return resolve(false)
        }
 
        return resolve(pageData._id)
      })
    })
  }
 
  pageSchema.statics.findListByPageIds = function(ids, options) {
    var Page = this
    var options = options || {}
    var limit = options.limit || 50
    var offset = options.skip || 0
 
    return new Promise(function(resolve, reject) {
      Page.find({ _id: { $in: ids }, grant: GRANT_PUBLIC })
        // .sort({createdAt: -1}) // TODO optionize
        .skip(offset)
        .limit(limit)
        .populate([{ path: 'creator', model: 'User' }, { path: 'revision', model: 'Revision' }])
        .exec(function(err, pages) {
          if (err) {
            return reject(err)
          }
 
          Page.populate(pages, { path: 'revision.author', model: 'User' }, function(err, data) {
            if (err) {
              return reject(err)
            }
 
            return resolve(data)
          })
        })
    })
  }
 
  pageSchema.statics.findPageByRedirectTo = function(path) {
    var Page = this
 
    return new Promise(function(resolve, reject) {
      Page.findOne({ redirectTo: path }, function(err, pageData) {
        if (err || pageData === null) {
          return reject(err)
        }
 
        return resolve(pageData)
      })
    })
  }
 
  pageSchema.statics.findPagesByIds = function(ids) {
    const Page = this
 
    return Page.find({
      _id: { $in: ids },
      redirectTo: null,
    })
      .populate([
        { path: 'creator', model: 'User' },
        {
          path: 'revision',
          model: 'Revision',
          populate: {
            path: 'author',
            model: 'User',
          },
        },
      ])
      .exec()
  }
 
  pageSchema.statics.findListByCreator = function(user, option, currentUser) {
    var Page = this
    var limit = option.limit || 50
    var offset = option.offset || 0
    var conditions = {
      creator: user._id,
      redirectTo: null,
      $or: [{ status: null }, { status: STATUS_PUBLISHED }],
    }
 
    if (!user.equals(currentUser._id)) {
      conditions.grant = GRANT_PUBLIC
    }
 
    return new Promise(function(resolve, reject) {
      Page.find(conditions)
        .sort({ createdAt: -1 })
        .skip(offset)
        .limit(limit)
        .populate('revision')
        .exec()
        .then(function(pages) {
          return Page.populate(pages, { path: 'revision.author', model: 'User' }).then(resolve)
        })
    })
  }
 
  /**
   * Bulk get (for internal only)
   */
  pageSchema.statics.getStreamOfFindAll = function(options) {
    var options = options || {}
    var publicOnly = options.publicOnly || true
    var criteria = { redirectTo: null }
 
    if (publicOnly) {
      criteria.grant = GRANT_PUBLIC
    }
 
    return this.find(criteria)
      .populate([{ path: 'creator', model: 'User' }, { path: 'revision', model: 'Revision' }])
      .lean()
      .cursor()
  }
 
  /**
   * findListByStartWith
   *
   * If `path` has `/` at the end, returns '{path}/*' and '{path}' self.
   * If `path` doesn't have `/` at the end, returns '{path}*'
   * e.g.
   */
  pageSchema.statics.findListByStartWith = function(path, userData, option) {
    var Page = this
    var pathCondition = []
    var includeDeletedPage = option.includeDeletedPage || false
 
    Iif (!option) {
      option = { sort: 'updatedAt', desc: -1, offset: 0, limit: 50 }
    }
    var opt = {
      sort: option.sort || 'updatedAt',
      desc: option.desc || -1,
      offset: option.offset || 0,
      limit: option.limit === 0 ? 0 : option.limit || 50,
    }
    var sortOpt = {}
    sortOpt[opt.sort] = opt.desc
    var queryReg = new RegExp('^' + path)
    // var sliceOption = option.revisionSlice || { $slice: 1 }
 
    pathCondition.push({ path: queryReg })
    Eif (path.match(/\/$/)) {
      debug('Page list by ending with /, so find also upper level page')
      pathCondition.push({ path: path.substr(0, path.length - 1) })
    }
 
    return new Promise(function(resolve, reject) {
      // FIXME: might be heavy
      var q = Page.find({
        redirectTo: null,
        $or: [
          { grant: null },
          { grant: GRANT_PUBLIC },
          { grant: GRANT_RESTRICTED, grantedUsers: userData._id },
          { grant: GRANT_SPECIFIED, grantedUsers: userData._id },
          { grant: GRANT_OWNER, grantedUsers: userData._id },
        ],
      })
        .populate('revision')
        .and({
          $or: pathCondition,
        })
        .sort(sortOpt)
        .skip(opt.offset)
        .limit(opt.limit)
 
      Eif (!includeDeletedPage) {
        q.and({
          $or: [{ status: null }, { status: STATUS_PUBLISHED }],
        })
      }
 
      q.exec().then(function(pages) {
        Page.populate(pages, { path: 'revision.author', model: 'User' })
          .then(resolve)
          .catch(reject)
      })
    })
  }
 
  pageSchema.statics.findChildrenByPath = async function(path, userData, option) {
    path = addTrailingSlash(path)
    return this.findListByStartWith(path, userData, { limit: 0, ...option })
  }
 
  pageSchema.statics.findUnfurlablePages = async function(type, array, grants = [GRANT_PUBLIC, GRANT_RESTRICTED]) {
    const Page = this
    const page = await Page.find({
      [type]: { $in: array },
      $or: grants.map(grant => ({ grant })),
    })
    return page
  }
 
  pageSchema.statics.findUnfurlablePagesByIds = async function(ids) {
    const Page = this
    return Page.findUnfurlablePages('_id', ids)
  }
 
  pageSchema.statics.findUnfurlablePagesByPaths = async function(paths) {
    const Page = this
    // `GRANT_RESTRICTED` pages can not be accessed using path
    return Page.findUnfurlablePages('path', paths, [GRANT_PUBLIC])
  }
 
  pageSchema.statics.updatePageProperty = function(page, updateData) {
    var Page = this
    return new Promise(function(resolve, reject) {
      // TODO foreach して save
      Page.update({ _id: page._id }, { $set: updateData }, function(err, data) {
        Iif (err) {
          return reject(err)
        }
 
        return resolve(data)
      })
    })
  }
 
  pageSchema.statics.updateGrant = function(page, grant, userData) {
    return new Promise(function(resolve, reject) {
      page.grant = grant
      if (grant == GRANT_PUBLIC) {
        page.grantedUsers = []
      } else {
        page.grantedUsers = []
        page.grantedUsers.addToSet(userData._id)
      }
 
      page.save(function(err, data) {
        debug('Page.updateGrant, saved grantedUsers.', err, (data && data.path) || {})
        if (err) {
          return reject(err)
        }
 
        return resolve(data)
      })
    })
  }
 
  // Instance method でいいのでは
  pageSchema.statics.pushToGrantedUsers = function(page, userData) {
    return new Promise(function(resolve, reject) {
      if (!page.grantedUsers || !Array.isArray(page.grantedUsers)) {
        page.grantedUsers = []
      }
      page.grantedUsers.addToSet(userData)
      page.save(function(err, data) {
        if (err) {
          return reject(err)
        }
        return resolve(data)
      })
    })
  }
 
  pageSchema.statics.pushRevision = function(pageData, newRevision, user) {
    var isCreate = false
    Eif (pageData.revision === undefined) {
      debug('pushRevision on Create')
      isCreate = true
    }
 
    return new Promise(function(resolve, reject) {
      newRevision.save(function(err, newRevision) {
        Iif (err) {
          debug('Error on saving revision', err)
          return reject(err)
        }
 
        debug('Successfully saved new revision', newRevision)
        pageData.revision = newRevision
        pageData.lastUpdateUser = user
        pageData.updatedAt = Date.now()
        pageData.save(function(err, data) {
          Iif (err) {
            // todo: remove new revision?
            debug('Error on save page data (after push revision)', err)
            return reject(err)
          }
 
          resolve(data)
          Iif (!isCreate) {
            debug('pushRevision on Update')
          }
        })
      })
    })
  }
 
  pageSchema.statics.create = function(path, body, user, options) {
    var Page = this
    var Revision = crowi.model('Revision')
    var format = options.format || 'markdown'
    var grant = options.grant || GRANT_PUBLIC
    var redirectTo = options.redirectTo || null
 
    // force public
    Iif (isPortalPath(path)) {
      grant = GRANT_PUBLIC
    }
 
    return new Promise(function(resolve, reject) {
      Page.findOne({ path: path }, function(err, pageData) {
        Iif (pageData) {
          return reject(new Error('Cannot create new page to existed path'))
        }
 
        var newPage = new Page()
        newPage.path = path
        newPage.creator = user
        newPage.lastUpdateUser = user
        newPage.createdAt = Date.now()
        newPage.updatedAt = Date.now()
        newPage.redirectTo = redirectTo
        newPage.grant = grant
        newPage.status = STATUS_PUBLISHED
        newPage.grantedUsers = []
        newPage.grantedUsers.push(user)
 
        newPage.save(function(err, newPage) {
          if (err) {
            return reject(err)
          }
 
          var newRevision = Revision.prepareRevision(newPage, body, user, { format: format })
          Page.pushRevision(newPage, newRevision, user)
            .then(function(data) {
              resolve(data)
              pageEvent.emit('create', data, user)
            })
            .catch(function(err) {
              debug('Push Revision Error on create page', err)
              return reject(err)
            })
        })
      })
    })
  }
 
  pageSchema.statics.updatePage = async function(pageData, body, user, options = {}) {
    const Page = this
    const Revision = crowi.model('Revision')
    const Bookmark = crowi.model('Bookmark')
    const grant = options.grant || null
    // update existing page
    const newRevision = Revision.prepareRevision(pageData, body, user)
 
    try {
      const revision = await Page.pushRevision(pageData, newRevision, user)
      const bookmarkCount = await Bookmark.countByPageId(pageData._id)
 
      if (grant != pageData.grant) {
        const data = await Page.updateGrant(pageData, grant, user)
        pageEvent.emit('update', data, user, bookmarkCount)
 
        return data
      } else {
        pageEvent.emit('update', pageData, user, bookmarkCount)
 
        return pageData
      }
    } catch (err) {
      debug('Error on update', err.message)
      debug('Error on update', err.stack)
      throw new Error(err.message)
    }
  }
 
  pageSchema.statics.deletePage = function(pageData, user, options) {
    var Page = this
    var Share = crowi.model('Share')
    var newPath = Page.getDeletedPageName(pageData.path)
    if (Page.isDeletableName(pageData.path)) {
      return new Promise(function(resolve, reject) {
        Page.updatePageProperty(pageData, { status: STATUS_DELETED, lastUpdateUser: user })
          .then(function() {
            return Share.deleteByPageId(pageData._id)
          })
          .then(function(share) {
            pageData.status = STATUS_DELETED
 
            // ページ名が /trash/ 以下に存在する場合、おかしなことになる
            // が、 /trash 以下にページが有るのは、個別に作っていたケースのみ。
            // 一応しばらく前から uncreatable pages になっているのでこれでいいことにする
            debug('Deleted the page, and rename it', pageData.path, newPath)
            return Page.rename(pageData, newPath, user, { createRedirectPage: true })
          })
          .then(function(pageData) {
            resolve(pageData)
          })
          .catch(reject)
      })
    } else {
      return Promise.reject(new Error('Page is not deletable.'))
    }
  }
 
  pageSchema.statics.revertDeletedPage = function(pageData, user, options) {
    var Page = this
    var newPath = Page.getRevertDeletedPageName(pageData.path)
 
    // 削除時、元ページの path には必ず redirectTo 付きで、ページが作成される。
    // そのため、そいつは削除してOK
    // が、redirectTo ではないページが存在している場合それは何かがおかしい。(データ補正が必要)
    return new Promise(function(resolve, reject) {
      Page.findPageByPath(newPath)
        .then(function(originPageData) {
          if (originPageData.redirectTo !== pageData.path) {
            throw new Error('The new page of to revert is exists and the redirect path of the page is not the deleted page.')
          }
 
          return Page.completelyDeletePage(originPageData)
        })
        .then(function(done) {
          return Page.updatePageProperty(pageData, { status: STATUS_PUBLISHED, lastUpdateUser: user })
        })
        .then(function(done) {
          pageData.status = STATUS_PUBLISHED
 
          debug('Revert deleted the page, and rename again it', pageData, newPath)
          return Page.rename(pageData, newPath, user, {})
        })
        .then(function(done) {
          pageData.path = newPath
          resolve(pageData)
        })
        .catch(reject)
    })
  }
 
  /**
   * This is danger.
   */
  pageSchema.statics.completelyDeletePage = async function(pageData, user, options) {
    // Delete Bookmarks, Attachments, Revisions, Pages and emit delete
    const Bookmark = crowi.model('Bookmark')
    const Attachment = crowi.model('Attachment')
    const Comment = crowi.model('Comment')
    const Activity = crowi.model('Activity')
    const Page = this
    const pageId = pageData._id
 
    debug('Completely delete', pageData.path)
 
    await Bookmark.removeBookmarksByPageId(pageId)
    await Attachment.removeAttachmentsByPageId(pageId)
    await Comment.removeCommentsByPageId(pageId)
    await Page.removePageById(pageId)
    await Page.removeRedirectOriginPageByPath(pageData.path)
    await Activity.removeByPage(pageId)
 
    pageEvent.emit('delete', pageData, user) // update as renamed page
 
    return pageData
  }
 
  pageSchema.statics.removePage = async function(pageData) {
    const Page = this
    const Revision = crowi.model('Revision')
    const { _id } = pageData
 
    debug('Remove phisically, the page', _id)
    try {
      await Page.remove({ _id })
    } catch (err) {
      debug(' --> error', _id)
      throw err
    }
    await Revision.removeRevisionsByPath(pageData.path)
    return pageData
  }
 
  pageSchema.statics.removePageById = async function(pageId) {
    const Page = this
    const pageData = await Page.findPageById(pageId)
    await Page.removePage(pageData)
    return pageData
  }
 
  pageSchema.statics.removePageByPath = async function(pagePath) {
    const Page = this
    const pageData = await Page.findPageByPath(pagePath)
    await Page.removePage(pageData)
    return pageData
  }
 
  /**
   * remove the page that is redirecting to specified `pagePath` recursively
   *  ex: when
   *    '/page1' redirects to '/page2' and
   *    '/page2' redirects to '/page3'
   *    and given '/page3',
   *    '/page1' and '/page2' will be removed
   *
   * @param {string} pagePath
   */
  pageSchema.statics.removeRedirectOriginPageByPath = function(pagePath) {
    var Page = this
 
    return Page.findPageByRedirectTo(pagePath)
      .then(redirectOriginPageData => {
        // remove
        return (
          Page.removePageById(redirectOriginPageData.id)
            // remove recursive
            .then(() => {
              return Page.removeRedirectOriginPageByPath(redirectOriginPageData.path)
            })
        )
      })
      .catch(err => {
        // do nothing if origin page doesn't exist
        return Promise.resolve()
      })
  }
 
  pageSchema.statics.rename = function(pageData, newPagePath, user, options) {
    const Page = this
    const Revision = crowi.model('Revision')
    const path = pageData.path
    const createRedirectPage = options.createRedirectPage || false
    const preserveUpdatedAt = options.preserveUpdatedAt || false
 
    return new Promise(function(resolve, reject) {
      const updatedAt = preserveUpdatedAt ? {} : { updatedAt: Date.now() }
      const updateData = { path: newPagePath, lastUpdateUser: user, ...updatedAt }
 
      // pageData の path を変更
      Page.updatePageProperty(pageData, updateData)
        .then(function(data) {
          // reivisions の path を変更
          return Revision.updateRevisionListByPath(path, { path: newPagePath }, {})
        })
        .then(function(data) {
          pageData.path = newPagePath
 
          Iif (createRedirectPage) {
            var body = 'redirect ' + newPagePath
            Page.create(path, body, user, { redirectTo: newPagePath })
              .then(resolve)
              .catch(reject)
          } else {
            resolve(data)
          }
          pageEvent.emit('update', pageData, user) // update as renamed page
        })
    })
  }
 
  pageSchema.statics.getPathMap = function(paths, search, replace) {
    search = removeTrailingSlash(search)
    replace = this.normalizePath(replace)
    const renamePath = path => path.replace(search, replace)
    // { [oldPath]: newPath }
    return paths.map(({ path }) => [path, renamePath(path)]).reduce((l, [k, v]) => Object.assign(l, { [k]: v }), {})
  }
 
  pageSchema.statics.checkPagesRenamable = async function(paths, user) {
    const Page = this
    let error = false
    let errors = {}
    for (const path of paths) {
      const e = []
      Eif (!Page.isCreatableName(path)) {
        e.push('rename_tree.error.can_not_use_this_name')
      }
      const isAlreadyExists = await Page.exists({ path })
      Iif (isAlreadyExists) {
        const newPage = await Page.findPageByPath(path)
        if (!newPage.isUnlinkable(user)) {
          e.push('rename_tree.error.already_exists')
        }
      }
      if (!error && e.length > 0) {
        error = true
      }
      errors = Object.assign(errors, { [path]: e })
    }
    return [error, errors]
  }
 
  pageSchema.statics.renameTree = async function(pathMap, user, options) {
    const Page = this
    const { createRedirectPage = false, preserveUpdatedAt = true } = options
    await Promise.all(
      Object.values(pathMap).map(async newPath => {
        Iif (await Page.exists({ path: newPath })) {
          const newPage = await Page.findPageByPath(newPath)
          if (newPage.isUnlinkable(user)) {
            await newPage.unlink(user)
          } else {
            throw new Error(`Failed to create this page (${newPage.path}). It already exists.`)
          }
        }
      }),
    )
    return Promise.all(
      Object.entries(pathMap).map(async ([oldPath, newPath]) => {
        try {
          const options = {
            createRedirectPage: !isPortalPath(newPath) && createRedirectPage,
            preserveUpdatedAt,
          }
          const oldPage = await Page.findPageByPath(oldPath)
          await Page.rename(oldPage, newPath, user, options)
          return oldPage
        } catch (err) {
          throw new Error(`Failed to update page (${oldPath}).`)
        }
      }),
    )
  }
 
  pageSchema.statics.allPageCount = function() {
    const Page = this
 
    return Page.count({ redirectTo: null, grant: GRANT_PUBLIC }) // TODO: option にする
  }
 
  pageSchema.methods.getNotificationTargetUsers = async function() {
    var Comment = crowi.model('Comment')
    var Revision = crowi.model('Revision')
    var self = this
 
    const [commentCreators, revisionAuthors] = await Promise.all([Comment.findCreatorsByPage(self), Revision.findAuthorsByPage(self)])
    debug('commentCreators', commentCreators)
    debug('revisionAuthors', revisionAuthors)
 
    const targetUsers = [self.creator].concat(commentCreators, revisionAuthors)
    debug('targetUsers', targetUsers)
 
    var uniqueChecker = {}
    var uniqueUsers = []
    targetUsers.forEach(function(user) {
      var userId = user.toString()
      if (uniqueChecker[userId] !== 1) {
        uniqueUsers.push(user)
        uniqueChecker[userId] = 1
      }
    })
    debug('uniqueUsers', uniqueUsers)
 
    return uniqueUsers
  }
 
  pageSchema.post('save', savedPage => {
    var Backlink = crowi.model('Backlink')
    Backlink.createBySavedPage(savedPage)
      .then(result => {
        debug(result)
      })
      .catch(err => err)
  })
 
  pageSchema.statics.GRANT_PUBLIC = GRANT_PUBLIC
  pageSchema.statics.GRANT_RESTRICTED = GRANT_RESTRICTED
  pageSchema.statics.GRANT_SPECIFIED = GRANT_SPECIFIED
  pageSchema.statics.GRANT_OWNER = GRANT_OWNER
  pageSchema.statics.PAGE_GRANT_ERROR = PAGE_GRANT_ERROR
  pageSchema.statics.TYPE_PORTAL = TYPE_PORTAL
  pageSchema.statics.TYPE_PUBLIC = TYPE_PUBLIC
  pageSchema.statics.TYPE_USER = TYPE_USER
 
  return mongoose.model('Page', pageSchema)
}