aboutsummaryrefslogblamecommitdiffstats
path: root/Zotlabs/Lib/NativeWikiPage.php
blob: c78661654405b8881613b28760e3412d26059722 (plain) (tree)
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












































































































































































































































































































































































































































































































































































































































                                                                                                                                                                
<?php

namespace Zotlabs\Lib;

use \Zotlabs\Lib as Zlib;

class NativeWikiPage {

	static public function page_list($channel_id,$observer_hash, $resource_id) {

		// TODO: Create item table records for pages so that metadata like title can be applied
		$w = Zlib\NativeWiki::get_wiki($channel_id,$observer_hash,$resource_id);

		$pages[] = [
			'resource_id' => '',
			'title'       => 'Home',
			'url'         => 'Home',
			'link_id'     => 'id_wiki_home_0'
		];

		$sql_extra = item_permissions_sql($channel_id,$observer_hash);

		$r = q("select * from item where resource_type = 'nwikipage' and resource_id = '%s' and uid = %d $sql_extra group by mid",
			dbesc($resource_id),
			intval($channel_id)
		);
		if($r) {
			$items = fetch_post_tags($r,true);
			foreach($items as $page_item) {
				$title = get_iconfig($page_item['id'],'nwikipage','pagetitle',t('(No Title)'));
				if(urldecode($title) !== 'Home') {
					$pages[] = [
						'resource_id' => $resource_id,
						'title'       => urldecode($title),
						'url'         => $title,
						'link_id'     => 'id_' . substr($resource_id, 0, 10) . '_' . $page_item['id']
					];
				}
			}
		}

		return array('pages' => $pages, 'wiki' => $w);
	}


	static public function create_page($channel_id, $observer_hash, $name, $resource_id) {

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);

		// create an empty activity

		$arr = [];
		$arr['uid'] = $channel_id;
		$arr['author_xchan'] = $observer_hash;
		$arr['resource_type'] = 'nwikipage';
		$arr['resource_id'] = $resource_id;

		set_iconfig($arr,'nwikipage','pagetitle',urlencode(($name) ? $name : t('(No Title)')),true);

		post_activity_item($arr, false, false);

		$page = [ 
			'rawName'  => $name,
			'htmlName' => escape_tags($name),
			'urlName'  => urlencode(escape_tags($name)), 
			'fileName' => urlencode(escape_tags($name)) . Zlib\NativeWikiPage::get_file_ext($w)
		];

		return array('page' => $page, 'wiki' => $w, 'message' => '', 'success' => true);
	}

	static public function rename_page($arr) {
		$pageUrlName   = ((array_key_exists('pageUrlName',$arr))   ? $arr['pageUrlName']   : '');
		$pageNewName   = ((array_key_exists('pageNewName',$arr))   ? $arr['pageNewName']   : '');
		$resource_id   = ((array_key_exists('resource_id',$arr))   ? $arr['resource_id']   : '');
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash'] : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']    : 0);

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);
		if(! $w['path']) {
			return array('message' => t('Wiki not found.'), 'success' => false);
		}

		$page_path_old = $w['path'] . '/' . $pageUrlName . \Zlib\NativeWikiPage::get_file_ext($w);

		if(! is_readable($page_path_old) === true) {
			return array('message' => 'Cannot read wiki page: ' . $page_path_old, 'success' => false);
		}

		$page = [ 
			'rawName' => $pageNewName, 
			'htmlName' => escape_tags($pageNewName), 
			'urlName' => urlencode(escape_tags($pageNewName)), 
			'fileName' => urlencode(escape_tags($pageNewName)) . \Zlib\NativeWikiPage::get_file_ext($w)
		];

		$page_path_new = $w['path'] . '/' . $page['fileName'] ;

		if(is_file($page_path_new)) {
			return array('message' => 'Page already exists.', 'success' => false);
		}

		// Rename the page file in the wiki repo
		if(! rename($page_path_old, $page_path_new)) {
			return array('message' => 'Error renaming page file.', 'success' => false);
		}
		else {
			return array('page' => $page, 'message' => '', 'success' => true);
		}
	
	}

	static public function get_page_content($arr) {
		$pageUrlName   = ((array_key_exists('pageUrlName',$arr))   ? $arr['pageUrlName']        : '');
		$resource_id   = ((array_key_exists('resource_id',$arr))   ? $arr['resource_id']        : '');
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash']      : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? intval($arr['channel_id']) : 0);
		$revision      = ((array_key_exists('revision',$arr))      ? intval($arr['revision'])   : (-1));

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);
		if (! $w['wiki']) {
			return array('content' => null, 'message' => 'Error reading wiki', 'success' => false);
		}

		$item = self::load_page($arr);

		if($item) {
			$content = $item['body'];

			return [ 
				'content' => json_encode($content), 
				'mimeType' => $w['mimeType'], 
				'message' => '', 
				'success' => true
			];
		}
	
		return array('content' => null, 'message' => t('Error reading page content'), 'success' => false);

	}

	static public function page_history($arr) {
		$pageUrlName = ((array_key_exists('pageUrlName',$arr)) ? $arr['pageUrlName'] : '');
		$resource_id = ((array_key_exists('resource_id',$arr)) ? $arr['resource_id'] : '');
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash'] : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']    : 0);

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);
		if (!$w['wiki']) {
			return array('history' => null, 'message' => 'Error reading wiki', 'success' => false);
		}

		$items = self::load_page_history($arr);

		$history = [];

		if($items) {
			$processed = 0;
			foreach($items as $item) {
				if($processed > 1000)
					break;
				$processed ++;
				$history[] = [ 
					'revision' => $item['revision'],
					'date' => datetime_convert('UTC',date_default_timezone_get(),$item['created']),
					'name' => $item['author']['xchan_name'],
					'title' => get_iconfig($item,'nwikipage','commit_msg') 
				];

			}

			return [ 'success' => true, 'history' => $history ];
		}

		return [ 'success' => false ];

	}
	

	static public function load_page($arr) {
logger('arr: ' . print_r($arr,true));
		$pageUrlName   = ((array_key_exists('pageUrlName',$arr))   ? $arr['pageUrlName']     : '');
		$resource_id   = ((array_key_exists('resource_id',$arr))   ? $arr['resource_id']     : '');
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash']   : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']      : 0);
		$revision      = ((array_key_exists('revision',$arr))      ? $arr['revision']        : (-1));

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);
		if (! $w['wiki']) {
			return array('content' => null, 'message' => 'Error reading wiki', 'success' => false);
		}

		$ids = '';
dbg(0);
		$ic = q("select * from iconfig left join item on iconfig.iid = item.id where uid = %d and cat = 'nwikipage' and k = 'pagetitle' and v = '%s'",
			intval($channel_id),
			dbesc($pageUrlName)
		);
	
		if($ic) {
			foreach($ic as $c) {
				if($ids)
					$ids .= ',';
				$ids .= intval($c['iid']);
			}
		}

		$sql_extra = item_permissions_sql($channel_id,$observer_hash);
		if($revision == (-1))
	        $sql_extra .= " order by revision desc ";
    	elseif($revision)
        	$sql_extra .= " and revision = " . intval($revision) . " ";

		$r = null;
		if($ids) {
			$r = q("select * from item where resource_type = 'nwikipage' and resource_id = '%s' and uid = %d and id in ( $ids ) $sql_extra limit 1",
				dbesc($resource_id),
				intval($channel_id)
			);
dbg(0);
			if($r) {
				$items = fetch_post_tags($r,true);
				return $items[0];
			}
		}
dbg(0);
		return null;
	}

	static public function load_page_history($arr) {

		$pageUrlName   = ((array_key_exists('pageUrlName',$arr))   ? $arr['pageUrlName']     : '');
		$resource_id   = ((array_key_exists('resource_id',$arr))   ? $arr['resource_id']     : '');
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash']   : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']      : 0);
		$revision      = ((array_key_exists('revision',$arr))      ? $arr['revision']        : (-1));

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);
		if (! $w['wiki']) {
			return array('content' => null, 'message' => 'Error reading wiki', 'success' => false);
		}

		$ids = '';

		$ic = q("select * from iconfig left join item on iconfig.iid = item.id where uid = %d and cat = 'nwikipage' and k = 'pagetitle' and v = '%s'",
			intval($channel_id),
			dbesc($pageUrlName)
		);
	
		if($ic) {
			foreach($ic as $c) {
				if($ids)
					$ids .= ',';
				$ids .= intval($c['iid']);
			}
		}

		$sql_extra = item_permissions_sql($channel_id,$observer_hash);
		$sql_extra .= " order by revision desc ";

		$r = null;
		if($ids) {
			$r = q("select * from item where resource_type = 'nwikipage' and resource_id = '%s' and uid = %d and id in ( $ids ) $sql_extra",
				dbesc($resource_id),
				intval($channel_id)
			);
			if($r) {
				xchan_query($r);
				$items = fetch_post_tags($r,true);
				return $items;
			}
		}

		return null;
	}



	static public function prepare_content($s) {
			
		$text = preg_replace_callback('{
					(?:\n\n|\A\n?)
					(	            # $1 = the code block -- one or more lines, starting with a space/tab
					  (?>
						[ ]{'.'4'.'}  # Lines must start with a tab or a tab-width of spaces
						.*\n+
					  )+
					)
					((?=^[ ]{0,'.'4'.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
				}xm',
				'self::nwiki_prepare_content_callback', $s);
	
		return $text;
	}
	
	static public function nwiki_prepare_content_callback($matches) {
		$codeblock = $matches[1];
	
		$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES, UTF8, false);
		return "\n\n" . $codeblock ;
	}
	
	
	
	static public function save_page($arr) {

		$pageUrlName = ((array_key_exists('pageUrlName',$arr)) ? $arr['pageUrlName'] : '');
		$content = ((array_key_exists('content',$arr)) ? purify_html(Zlib\NativeWikiPage::prepare_content($arr['content'])) : '');
		$resource_id = ((array_key_exists('resource_id',$arr)) ? $arr['resource_id'] : '');
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash'] : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']    : 0);
		$revision = ((array_key_exists('revision',$arr))    ? $arr['revision']    : 0);

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);

		if (!$w['wiki']) {
			return array('message' => t('Error reading wiki'), 'success' => false);
		}
	
		$item = self::load_page($arr);
		if(! $item) {
			return array('message' => t('Page not found'), 'success' => false);
		}
		unset($item['id']);
		unset($item['author']);

		$item['parent'] = 0;
		$item['body'] = $content;
		$item['author_xchan'] = $observer_hash;
		$item['revision'] = (($arr['revision']) ? intval($arr['revision']) + 1 : intval($item['revision']) + 1);

		if($item['iconfig'] && is_array($item['iconfig']) && count($item['iconfig'])) {
			for($x = 0; $x < count($item['iconfig']); $x ++) {
				unset($item['iconfig'][$x]['id']);
				unset($item['iconfig'][$x]['iid']);
			}
		}

		$ret = item_store($item, false, false);

		if($ret['item_id'])
			return array('message' => '', 'filename' => $filename, 'success' => true);
		else
			return array('message' => t('Page update failed.'), 'success' => false);
	}	

	static public function delete_page($arr) {
		$pageUrlName = ((array_key_exists('pageUrlName',$arr)) ? $arr['pageUrlName'] : '');
		$resource_id = ((array_key_exists('resource_id',$arr)) ? $arr['resource_id'] : '');
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash'] : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']    : 0);

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);

		if (!$w['path']) {
			return array('message' => t('Error reading wiki'), 'success' => false);
		}
		$page_path = $w['path'] . '/' . $pageUrlName . wiki_get_file_ext($w);
		if (is_writable($page_path) === true) {
			if(!unlink($page_path)) {
				return array('message' => t('Error deleting page file'), 'success' => false);
			}
			return array('message' => '', 'success' => true);
		} 
		else {
			return array('message' => t('Page file not writable'), 'success' => false);
		}	
	}
	
	static public function revert_page($arr) {
		$pageUrlName   = ((array_key_exists('pageUrlName',$arr))   ? $arr['pageUrlName']   : '');
		$resource_id   = ((array_key_exists('resource_id',$arr))   ? $arr['resource_id']   : '');
		$commitHash    = ((array_key_exists('commitHash',$arr))    ? $arr['commitHash']    : null);
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash'] : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']    : 0);

		if (! $commitHash) {
			return array('content' => $content, 'message' => 'No commit was provided', 'success' => false);
		}

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);
		if (!$w['wiki']) {
			return array('content' => $content, 'message' => 'Error reading wiki', 'success' => false);
		}

		$x = $arr;

		if(intval($commitHash) > 0) {
			unset($x['commitHash']);
			$x['revision'] = intval($commitHash) - 1;
			$loaded = self::load_page($x);

			if($loaded) {
				$content = $loaded['body'];
				return [ 'content' => $content, 'success' => true ];
			}
			return [ 'content' => $content, 'success' => false ]; 
		}
	}
	
	static public function compare_page($arr) {
		$pageUrlName = ((array_key_exists('pageUrlName',$arr)) ? $arr['pageUrlName'] : '');
		$resource_id = ((array_key_exists('resource_id',$arr)) ? $arr['resource_id'] : '');
		$currentCommit = ((array_key_exists('currentCommit',$arr)) ? $arr['currentCommit'] : 'HEAD');
		$compareCommit = ((array_key_exists('compareCommit',$arr)) ? $arr['compareCommit'] : null);
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash'] : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']    : 0);

		if (! $compareCommit) {
			return array('message' => t('No compare commit was provided'), 'success' => false);
		}

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);

		if (!$w['path']) {
			return array('message' => t('Error reading wiki'), 'success' => false);
		}
		$page_path = $w['path'] . '/' . $pageUrlName . \Zlib\NativeWikiPage::get_file_ext($w);
		if (is_readable($page_path) === true) {
			$reponame = ((array_key_exists('title', $w['wiki'])) ? urlencode($w['wiki']['title']) : 'repo');
			if($reponame === '') {
				$reponame = 'repo';
			}
			$git = new GitRepo('', null, false, $w['wiki']['title'], $w['path']);
			$compareContent = $currentContent = '';
			try {
				foreach ($git->git->tree($currentCommit) as $object) {
					if ($object['type'] == 'blob' && $object['file'] === $pageUrlName . wiki_get_file_ext($w)) {
							$currentContent = $git->git->cat->blob($object['hash']);						
					}
				}
				foreach ($git->git->tree($compareCommit) as $object) {
					if ($object['type'] == 'blob' && $object['file'] === $pageUrlName . wiki_get_file_ext($w)) {
							$compareContent = $git->git->cat->blob($object['hash']);						
					}
				}
				require_once('library/class.Diff.php');
				$diff = Diff::toTable(Diff::compare($currentContent, $compareContent));
			} 
			catch (\PHPGit\Exception\GitException $e) {
				return array('message' => t('GitRepo error thrown'), 'success' => false);
			}
			return array('diff' => $diff, 'message' => '', 'success' => true);
		} 
		else {
			return array('message' => t('Page file not writable'), 'success' => false);
		}
	}
	
	static public function commit($arr) {
logger('committing');
		$commit_msg    = ((array_key_exists('commit_msg', $arr))   ? $arr['commit_msg']    : t('Page updated'));
		$observer_hash = ((array_key_exists('observer_hash',$arr)) ? $arr['observer_hash'] : '');
		$channel_id    = ((array_key_exists('channel_id',$arr))    ? $arr['channel_id']    : 0);
		$pageUrlName   = ((array_key_exists('pageUrlName',$arr))   ? $arr['pageUrlName']   : t('Untitled'));

		if(array_key_exists('resource_id', $arr)) {
			$resource_id = $arr['resource_id'];
		}
		else {
			return array('message' => t('Wiki resource_id required for git commit'), 'success' => false);
		}

		$w = Zlib\NativeWiki::get_wiki($channel_id, $observer_hash, $resource_id);

		if (! $w['wiki']) {
			return array('message' => t('Error reading wiki'), 'success' => false);
		}

		$page = self::load_page($arr);
logger('commit: page: ' . print_r($page,true));
		if($page) {
			set_iconfig($page['id'],'nwikipage','commit_msg',escape_tags($commit_msg),true);
			return [ 'success' => true, 'page' => $page ];
		}

		return [ 'success' => false, 'message' => t('Page not found.') ];

	}
	
	static public function convert_links($s, $wikiURL) {
		
		if (strpos($s,'[[') !== false) {
			preg_match_all("/\[\[(.*?)\]\]/", $s, $match);
			$pages = $pageURLs = array();
			foreach ($match[1] as $m) {
				// TODO: Why do we need to double urlencode for this to work?
				$pageURLs[] = urlencode(urlencode(escape_tags($m)));
				$pages[] = $m;
			}
			$idx = 0;
			while(strpos($s,'[[') !== false) {
			$replace = '<a href="'.$wikiURL.'/'.$pageURLs[$idx].'">'.$pages[$idx].'</a>';
				$s = preg_replace("/\[\[(.*?)\]\]/", $replace, $s, 1);
				$idx++;
			}
		}
		return $s;
	}
	
	/**
	 * Replace the instances of the string [toc] with a list element that will be populated by
	 * a table of contents by the JavaScript library
	 * @param string $s
	 * @return string
	 */
	static public function generate_toc($s) {
		if (strpos($s,'[toc]') !== false) {
			//$toc_md = wiki_toc($s);	// Generate Markdown-formatted list prior to HTML render
			$toc_md = '<ul id="wiki-toc"></ul>'; // use the available jQuery plugin http://ndabas.github.io/toc/
			$s = preg_replace("/\[toc\]/", $toc_md, $s, -1);
		}
		return $s;
	}
	
	/**
	 *  Converts a select set of bbcode tags. Much of the code is copied from include/bbcode.php
	 * @param string $s
	 * @return string
	 */
	static public function bbcode($s) {
			
			$s = str_replace(array('[baseurl]', '[sitename]'), array(z_root(), get_config('system', 'sitename')), $s);
			
			$observer = App::get_observer();
			if ($observer) {
					$s1 = '<span class="bb_observer" title="' . t('Different viewers will see this text differently') . '">';
					$s2 = '</span>';
					$obsBaseURL = $observer['xchan_connurl'];
					$obsBaseURL = preg_replace("/\/poco\/.*$/", '', $obsBaseURL);
					$s = str_replace('[observer.baseurl]', $obsBaseURL, $s);
					$s = str_replace('[observer.url]', $observer['xchan_url'], $s);
					$s = str_replace('[observer.name]', $s1 . $observer['xchan_name'] . $s2, $s);
					$s = str_replace('[observer.address]', $s1 . $observer['xchan_addr'] . $s2, $s);
					$s = str_replace('[observer.webname]', substr($observer['xchan_addr'], 0, strpos($observer['xchan_addr'], '@')), $s);
					$s = str_replace('[observer.photo]', '', $s);
			} else {
					$s = str_replace('[observer.baseurl]', '', $s);
					$s = str_replace('[observer.url]', '', $s);
					$s = str_replace('[observer.name]', '', $s);
					$s = str_replace('[observer.address]', '', $s);
					$s = str_replace('[observer.webname]', '', $s);
					$s = str_replace('[observer.photo]', '', $s);
			}
	
			return $s;
	}
	
	static public function get_file_ext($arr) {
		if($arr['mimeType'] == 'text/bbcode')
			return '.bb';
		else
			return '.md';
	}
	
	// This function is derived from 
	// http://stackoverflow.com/questions/32068537/generate-table-of-contents-from-markdown-in-php
	static public function toc($content) {
	  // ensure using only "\n" as line-break
	  $source = str_replace(["\r\n", "\r"], "\n", $content);
	
	  // look for markdown TOC items
	  preg_match_all(
		'/^(?:=|-|#).*$/m',
		$source,
		$matches,
		PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE
	  );
	
	  // preprocess: iterate matched lines to create an array of items
	  // where each item is an array(level, text)
	  $file_size = strlen($source);
	  foreach ($matches[0] as $item) {
		$found_mark = substr($item[0], 0, 1);
		if ($found_mark == '#') {
		  // text is the found item
		  $item_text = $item[0];
		  $item_level = strrpos($item_text, '#') + 1;
		  $item_text = substr($item_text, $item_level);
		} else {
		  // text is the previous line (empty if <hr>)
		  $item_offset = $item[1];
		  $prev_line_offset = strrpos($source, "\n", -($file_size - $item_offset + 2));
		  $item_text =
			substr($source, $prev_line_offset, $item_offset - $prev_line_offset - 1);
		  $item_text = trim($item_text);
		  $item_level = $found_mark == '=' ? 1 : 2;
		}
		if (!trim($item_text) OR strpos($item_text, '|') !== FALSE) {
		  // item is an horizontal separator or a table header, don't mind
		  continue;
		}
		$raw_toc[] = ['level' => $item_level, 'text' => trim($item_text)];
	  }
		$o = '';
		foreach($raw_toc as $t) {
			$level = intval($t['level']);
			$text = $t['text'];
			switch ($level) {
				case 1:
					$li = '* ';
					break;
				case 2:
					$li = '  * ';
					break;
				case 3:
					$li = '    * ';
					break;
				case 4:
					$li = '      * ';
					break;
				default:
					$li = '* ';
					break;
			}
			$o .= $li . $text . "\n";
		}
	  return $o;
	}

}