summaryrefslogtreecommitdiff
path: root/pages/docs.inc
blob: 6d01489eac04c7fdb75c01d1d9d6bfac69ff89d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/init.inc"; global $title; global $isLoggedIn; global $_PROFILE;
require_once $_SERVER['DOCUMENT_ROOT'] . "/includes/random.inc";

$parts = explode("/", $_GET['_']);
$select = $parts[2] ?? null;

if ($select === "add") {
    $id = random();
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/docs/" . $id . ".json", json_encode([
        "name" => "Untitled document ($id)",
        "category" => null,
        "contents" => "<div class='alert alert-primary'>This is a new document you just created.</div>",
        "last" => [
            "author" => $_PROFILE["login"],
            "date" => time()
        ]
    ]));

    header("Location: /-/docs/$id");
    die();
} elseif (isset($select)) {
    if (ctype_alnum($select) && file_exists($_SERVER['DOCUMENT_ROOT'] . "/includes/data/docs/" . $select . ".json")) {
        $id = $_documentId = $select;
        $data = json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/docs/" . $select . ".json"), true);
        $titleBase = " · " . $title . " · Cold Haze";
        $title = $data["name"] . " · " . $title;
    } else {
        header("Location: /-/docs");
        die();
    }
}

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/header.inc';

?>

<br>
<div class="container">
    <div>
        <?php if (isset($data)): ?><div id="page-content">
            <h2>
                <span contenteditable="true" id="document-name" style="outline: none;"><?= $data["name"] ?></span>
                <a href="/-/docs" class="small btn btn-outline-light" style="float:right;margin-top:5px;vertical-align:middle;opacity:1 !important; color:white;">Back</a>
            </h2>
            <p><b>Category:</b> <span id="category" contenteditable="true" style="outline: none;"><?= $data["category"] ?? "Unsorted" ?></span></p>
            <p>
                <?php if ($data["last"]["date"] === 0): ?>
                    Last modified <span id="last-edit-time" class="relative-time" data-relative-timestamp="">never</span>
                <?php else: ?>
                    Last modified <span id="last-edit-time" class="relative-time" data-relative-timestamp="<?= $data["last"]["date"] ?>"><?= timeAgo($data["last"]["date"]) ?></span>
                    <?php if ($data["last"]["author"] !== $_PROFILE["login"]): ?>
                        <span id="last-edit-author">by <?= $data["last"]["author"] === "raindrops" ? "the Raindrops System" : "the Cloudburst System" ?></span>
                    <?php endif; ?>
                <?php endif; ?>
                · <span id="editor-save-status" class="text-muted">Saved</span>
            </p>

            <?php $timeDiff = round((1800 - (time() - $data["last"]["date"])) / 60); if ($timeDiff >= 0 && $data["last"]["author"] !== $_PROFILE["login"]): ?>
            <div class="alert alert-warning">
                <b>This document is currently in use by <?= $data["last"]["author"] === "raindrops" ? "the Raindrops System" : "the Cloudburst System" ?>.</b> It has been open in read-only to prevent conflicts with the changes they make. If they stopped editing the document, it will become editable for you after you refresh the page in <?= $timeDiff ?> minute<?= $timeDiff > 1 ? "s" : "" ?>.
            </div>
            <?= $data["contents"] ?>
            <?php else: ?>
            <textarea id="editor"><?= $data["contents"] ?></textarea>

            <script src="/assets/editor/editor.js"></script>
            <script>
                let editor;
                ClassicEditor
                    .create( document.querySelector( '#editor' ), {
                        toolbar: [
                            'undo', 'redo', '|', 'removeFormat', '|', 'heading', '|', 'fontSize', 'fontColor', 'fontBackgroundColor', 'alignment', '|', 'bold', 'italic', 'underline', 'strikethrough', '|', 'subscript', 'superscript', '|', 'code', '|', 'outdent', 'indent', '|', 'bulletedList', 'numberedList', '|', 'link', 'imageUpload', 'mediaEmbed', 'blockQuote', 'insertTable', 'codeBlock', '|', 'horizontalLine'
                        ]
                    } )

                    .then( newEditor => {
                        editor = newEditor;
                    } )
                    .catch( error => {
                        console.error( error );
                    } );
            </script>
            <!--suppress CssUnresolvedCustomProperty -->
            <style>
                :root {
                    --ck-color-base-background: transparent;
                }

                .ck-toolbar {
                    filter: invert(1);
                    border-bottom-left-radius: var(--ck-border-radius) !important;
                    border-bottom-right-radius: var(--ck-border-radius) !important;
                    border-bottom-width: 1px !important;
                }

                .ck-tooltip__text {
                    color: white !important;
                }

                .ck-dropdown__panel {
                    background: #ddd !important;
                }

                .ck-color-grid__tile {
                    filter: invert(1);
                }

                .ck-balloon-rotator {
                    background-color: #ccc !important;
                }

                .ck-balloon-panel {
                    filter: invert(1);
                }

                .ck-editor__editable {
                    border-color: transparent !important;
                }

                .ck.ck-sticky-panel__content_sticky {
                    top: 59px !important;
                }
            </style>
            <script>

                let titleBase = "<?= $titleBase ?>";
                let lastSavedData = editor.getData();
                let lastFetchedData = editor.getData();
                let timeSinceLastModified = 0;
                let saving = false;

                async function save() {
                    let data = editor.getData();
                    document.getElementById("editor-save-status").innerHTML = "Saving...";
                    document.getElementById("editor-save-status").classList.remove("text-danger");
                    document.getElementById("editor-save-status").classList.remove("text-muted");
                    document.getElementById("editor-save-status").classList.remove("text-warning");
                    document.getElementById("editor-save-status").classList.add("text-primary");
                    saving = true;

                    try {
                        await window.fetch("/api/docs?id=<?= $_documentId ?>", {
                            method: "POST",
                            body: JSON.stringify({ content: data, name: document.getElementById("document-name").innerText, category: document.getElementById("category").innerText })
                        });
                        document.getElementById("last-edit-time").setAttribute("data-relative-timestamp", (new Date().getTime() / 1000).toFixed(0));
                        if (document.getElementById("last-edit-author")) document.getElementById("last-edit-author").outerHTML = "";
                        document.title = document.getElementById("document-name").innerText + titleBase;
                        document.getElementById("editor-save-status").innerHTML = "Saved";
                        document.getElementById("editor-save-status").classList.remove("text-danger");
                        document.getElementById("editor-save-status").classList.add("text-muted");
                        document.getElementById("editor-save-status").classList.remove("text-warning");
                        document.getElementById("editor-save-status").classList.remove("text-primary");
                        lastSavedData = data;
                        saving = false;
                    } catch (e) {
                        console.error(e);
                        document.getElementById("editor-save-status").innerHTML = "Failed to save";
                        document.getElementById("editor-save-status").classList.add("text-danger");
                        document.getElementById("editor-save-status").classList.remove("text-muted");
                        document.getElementById("editor-save-status").classList.remove("text-warning");
                        document.getElementById("editor-save-status").classList.remove("text-primary");
                    }
                }

                document.onclick = async () => {
                    if (saving) return;

                    if (editor.getData() !== lastSavedData) {
                        await save();
                    }
                }

                setInterval(async () => {
                    if (saving) return;

                    if (editor.getData() !== lastSavedData) {
                        document.getElementById("editor-save-status").innerHTML = "Modified";
                        document.getElementById("editor-save-status").classList.remove("text-danger");
                        document.getElementById("editor-save-status").classList.remove("text-muted");
                        document.getElementById("editor-save-status").classList.add("text-warning");
                        document.getElementById("editor-save-status").classList.remove("text-primary");

                        if (editor.getData() !== lastFetchedData) {
                            lastFetchedData = editor.getData();
                            timeSinceLastModified = 0;
                        } else {
                            timeSinceLastModified++;
                        }

                        if (timeSinceLastModified > 20 || !document.hasFocus()) {
                            await save();
                        }
                    } else {
                        timeSinceLastModified = 0;
                    }
                }, 100)

            </script>
            <?php endif; ?>
        </div><?php else: ?>
            <h2>Documents</h2>
            <div id="list">
                <?php

                $documents = array_map(function ($i) {
                    return [
                        "id" => substr($i, 0, -5),
                        ...(json_decode(file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/includes/data/docs/" . $i), true) ?? [])
                    ];
                }, array_filter(scandir($_SERVER['DOCUMENT_ROOT'] . "/includes/data/docs"), function ($i) {
                    return !str_starts_with($i, ".") && str_ends_with($i, ".json");
                }));

                $deletable = array_values(array_filter($documents, function ($i) {
                    return strip_tags($i["contents"]) === "/delete";
                }));
                $unsorted_pre = array_values(array_filter($documents, function ($i) {
                    return strip_tags($i["contents"]) !== "/delete";
                }));

                $categoryFirst = [];
                $unsorted = [];
                $categories = [];
                foreach ($unsorted_pre as $item) {
                    if (isset($item["category"])) {
                        $existing_categories = [...array_keys($categories), ...array_keys($categoryFirst)];
                        $matched_category = null;

                        foreach ($existing_categories as $existing_category) {
                            if (levenshtein($item["category"], $existing_category) < 3) {
                                $matched_category = $existing_category;
                            }
                        }

                        $selected_category = $matched_category ?? $item["category"];

                        if (str_starts_with($item["category"], ".")) {
                            if (!isset($categoryFirst[$selected_category])) $categoryFirst[$selected_category] = [];
                            $categoryFirst[$selected_category][] = $item;
                        } else {
                            if (!isset($categories[$selected_category])) $categories[$selected_category] = [];
                            $categories[$selected_category][] = $item;
                        }
                    } else {
                        $unsorted[] = $item;
                    }
                }

                uasort($unsorted, function ($a, $b) {
                    return $b["last"]["date"] - $a["last"]["date"];
                });

                uasort($deletable, function ($a, $b) {
                    return $b["last"]["date"] - $a["last"]["date"];
                });

                $fullList = [...$categoryFirst, ...$categories];

                ?>

                <?php foreach ($fullList as $category => $items): ?>
                <h4><?= str_starts_with($category, ".") ? substr($category, 1) : $category ?></h4><div class="list-group">
                <?php foreach ($items as $item): ?>
                    <a href="/-/docs/<?= $item["id"] ?>" id="document-<?= $item["id"] ?>" class="list-group-item list-group-item-action document-listing <?php if (strip_tags($item["contents"]) === "/delete"): ?>opacity-75<?php endif; ?>">
                        <?= $item["name"] ?>&nbsp;
                        <?php if (strip_tags($item["contents"]) === "/delete"): ?>
                            <span class="badge bg-warning rounded-pill text-black">Deleting in <?= round((($item["last"]["date"] + 86400) - time()) / 3600) ?> hours</span>
                        <?php else: ?>
                            <span class="relative-time text-muted" data-relative-timestamp="<?= $item["last"]["date"] ?>"><?= timeAgo($item["last"]["date"]) ?></span>
                        <?php endif; ?>
                    </a>
                <?php endforeach; ?></div>
                <hr>
                <?php endforeach; ?>

                <h4>Unsorted</h4><div class="list-group">
                <?php foreach ($unsorted as $item): ?>
                <a href="/-/docs/<?= $item["id"] ?>" id="document-<?= $item["id"] ?>" class="list-group-item list-group-item-action document-listing <?php if (strip_tags($item["contents"]) === "/delete"): ?>opacity-75<?php endif; ?>">
                    <?= $item["name"] ?>&nbsp;
                    <?php if (strip_tags($item["contents"]) === "/delete"): ?>
                    <span class="badge bg-warning rounded-pill text-black">Deleting in <?= round((($item["last"]["date"] + 86400) - time()) / 3600) ?> hours</span>
                    <?php else: ?>
                    <span class="relative-time text-muted" data-relative-timestamp="<?= $item["last"]["date"] ?>"><?= timeAgo($item["last"]["date"]) ?></span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?></div>

                <hr>
                <h4 id="deletable">Marked for deletion</h4><div class="list-group">
                <?php foreach ($deletable as $item): ?>
                <a href="/-/docs/<?= $item["id"] ?>" id="document-<?= $item["id"] ?>" class="list-group-item list-group-item-action document-listing <?php if (strip_tags($item["contents"]) === "/delete"): ?>opacity-75<?php endif; ?>">
                    <?= $item["name"] ?>&nbsp;
                    <?php if (strip_tags($item["contents"]) === "/delete"): ?>
                        <span class="badge bg-warning rounded-pill text-black">Deleting in <?= round((($item["last"]["date"] + 86400) - time()) / 3600) ?> hours</span>
                    <?php else: ?>
                        <span class="relative-time text-muted" data-relative-timestamp="<?= $item["last"]["date"] ?>"><?= timeAgo($item["last"]["date"]) ?></span>
                    <?php endif; ?>
                </a>
                <?php endforeach; ?></div>
            </div>

            <hr>
            <div id="page-content">
                <a href="/-/docs/add">Create a new document</a>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
    setInterval(async () => {
        Array.from(document.getElementsByClassName("relative-time")).forEach((el) => {
            el.innerText = timeAgo(parseInt(el.getAttribute("data-relative-timestamp")) * 1000);
        })
    }, 1000)

    function timeAgo(time) {
        if (!isNaN(parseInt(time))) {
            time = new Date(time).getTime();
        }

        let periods = ["sec.", "mn.", "hr.", "d.", "wk.", "mo.", "y.", "ages"];

        let lengths = ["60", "60", "24", "7", "4.35", "12", "100"];

        let now = new Date().getTime();

        let difference = Math.round((now - time) / 1000);
        let tense;
        let period;

        if (difference <= 10 && difference >= 0) {
            return "now";
        } else if (difference > 0) {
            tense = "ago";
        } else {
            tense = "later";
        }

        let j;

        for (j = 0; difference >= lengths[j] && j < lengths.length - 1; j++) {
            difference /= lengths[j];
        }

        difference = Math.round(difference);

        period = periods[j];

        return `${difference} ${period} ${tense}`;
    }
</script>
<style>
    .list-group-item {
        color: #fff;
        background-color: #222;
        border: 1px solid rgba(255, 255, 255, .125);
    }

    .list-group-item.disabled {
        color: #fff;
        background-color: #222;
        border-color: rgba(255, 255, 255, .125);
        opacity: .75;
    }

    .list-group-item:hover {
        background-color: #252525;
        color: #ddd;
    }

    .list-group-item:active, .list-group-item:focus {
        background-color: #272727;
        color: #bbb;
    }
</style>

<?php require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.inc'; ?>