YATA.class.php 36.4 KB
Newer Older
vermeul's avatar
vermeul committed
1
2
3
4
5
6
7
8
9
10
<?php
/**
 * YATA extension
 * @author Swen Vermeul
 * @file
 * @version 0.1
 * @license GNU General Public Licence 2.0
 */

class YATA {
11
    public static $annotations = "";
vermeul's avatar
vermeul committed
12
    //
vermeul's avatar
vermeul committed
13
    // Register any render callbacks with the parser
vermeul's avatar
vermeul committed
14
    //
vermeul's avatar
vermeul committed
15
16
17
18
19
    public static function onParserSetup( &$parser ) {

       // Create a function hook associating the "example" magic word with renderExample()
       $parser->setFunctionHook( 'annot', 'YATA::renderStartAnnot' );
       $parser->setFunctionHook( 'annotend', 'YATA::renderEndAnnot' );
vermeul's avatar
vermeul committed
20
       $parser->setFunctionHook( 'annotlist', 'YATA::annotations_list' );
21
       $parser->setFunctionHook( 'annotask', 'YATA::annotation_query' );
vermeul's avatar
vermeul committed
22
       $parser->setFunctionHook( 'annotcat', 'YATA::annotation_categories' );
vermeul's avatar
vermeul committed
23
24
    }

vermeul's avatar
vermeul committed
25
    //
vermeul's avatar
vermeul committed
26
    // Render the output of {{#annot: comment | category | id}}.
vermeul's avatar
vermeul committed
27
    //
vermeul's avatar
vermeul committed
28
    public static function renderStartAnnot( $parser, $comment='', $category='', $id='' ) {
vermeul's avatar
vermeul committed
29
        return "<span id=$id style='background: rgba(0,0,0,0.05)' title='$comment'>";
vermeul's avatar
vermeul committed
30
31
    }

vermeul's avatar
vermeul committed
32
    //
vermeul's avatar
vermeul committed
33
    // Render the output of {{#annotend:}}.
vermeul's avatar
vermeul committed
34
    //
vermeul's avatar
vermeul committed
35
    public static function renderEndAnnot( $parser, $id='' ) {
vermeul's avatar
vermeul committed
36
37
38
       return "</span>";
    }
    
vermeul's avatar
vermeul committed
39
    //
vermeul's avatar
vermeul committed
40
    // Render the output of {{#annoask:}}
vermeul's avatar
vermeul committed
41
    //
vermeul's avatar
vermeul committed
42
    public static function annotation_query( $parser, $querystring) {
43
44
        $title = $parser->getTitle();
        $wikiPage = new WikiPage( $title );
vermeul's avatar
vermeul committed
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
        $queries_found = preg_match_all(
            '/\[\[(?P<query>.*?)\]\]/s',
            $querystring, 
            $query_params, 
            PREG_OFFSET_CAPTURE
        );

        $where = array();
        $dbr = wfGetDB( DB_REPLICA );
        $seen = array();
        foreach($query_params["query"] as $query) {
            list($field, $values) = preg_split('/\s*\:\s*/', $query[0]);
            if( $field === 'category') {
                $categories = preg_split('/\s*\,\s*/', $values);
                $cat_ids = array();
                foreach( $categories as $category ) {
                    $cat = self::get_category($dbr, $category);
                    if ($cat) {
                        $cat_ids[] = $cat->id;
                        $child_categories = self::get_child_categories($dbr, $cat);
                        foreach($child_categories as $child_category) {
                            $cat_ids[] = $child_category->id;
                        }
                    }
                    else {
                        die("no such category found: $category");
                    }
                }
                $where[] = 
                    "EXISTS( 
                        SELECT NULL 
                        FROM yata_annotation_category ac 
                        WHERE ac.annotation_id = a.id
                        AND ac.category_id IN ("
                    . join(',', $cat_ids)
                    . ")
                    )";
            }
            elseif( $field === 'user' ) {
                $where["u.username"] = $values;
            }
            elseif( in_array($field, array('wiki_text', 'comment')) ) {
                if ( preg_match( '/[\%_]/', $values ) ) {
                    $where[] = "$field LIKE (" . $dbr->addQuotes($values).")";
                }
                else {
                    $where["a.$field"] = $values;
                }
            }
        }
        

        # fetch the annotation details
        $annotations = $dbr->select(
            array(
                a => 'yata_annotation',
                u => 'user',
                ac=> 'yata_annotation_category',
                c => 'yata_category',
                pc=> 'yata_category',
                p => 'page',
            ),
            array(
                category        => "c.name",
                parent_category => "pc.name",
                title           => "p.page_title",
                comment         => "a.comment", 
                wiki_text       => "a.wiki_text",
                start_char      => "a.start_char",
                bookmark        => "a.bookmark",
                last_edited_by  => "u.user_name",
                last_modified   => "a.modified_date"
            ),
            $where,
            __METHOD__, 
            array(
                'ORDER BY' => 'a.start_char ASC' 
            ), 
            array( 
                'u'  => array( 'LEFT JOIN', array( 'u.user_id = a.user_id') ),
                'ac' => array( 'LEFT JOIN', array( 'ac.annotation_id = a.id' ) ),
                'c'  => array( 'LEFT JOIN', array( 'ac.category_id = c.id' ) ),
                'pc' => array( 'LEFT JOIN', array( 'pc.id = c.parent_id') ),
                'p'  => array( 'INNER JOIN', array( 'p.page_id = a.page_id') ),
            )
        );

        $table = <<<"EOT"
{| class="wikitable sortable"
|-
! Category !! Comment !! Link !! Annotated text !! Last edited by !! Modification date

EOT;
        # compose the wiki table
        foreach($annotations as $annotation) {
            # if a category has no parent, just show the category name
            # in all other cases show parent_category:child_category
            $wikitext = preg_replace(
                '/{{\s*#annot(?:<end>end)?.*?}}/', 
                '',
                $annotation->wiki_text
            );
            $cat = $annotation->parent_category ? $annotation->parent_category . "/" . $annotation->category : $annotation->category;
            $table .= "|-\n";
            $table .= "| ".$cat
                   ." || ".$annotation->comment 
                   ." || [[".$annotation->title."#".$annotation->bookmark . "]]"
                   ." || " . $wikitext
                   ."\n || " . $annotation->last_edited_by
                   ."\n || " . wfTimestamp( TS_ISO_8601, $annotation->last_modified)
                   ."\n";
        }
        $table .= "|}";
        return $table;
vermeul's avatar
vermeul committed
159
    }
vermeul's avatar
vermeul committed
160

vermeul's avatar
vermeul committed
161

vermeul's avatar
vermeul committed
162
    //
vermeul's avatar
vermeul committed
163
    // Render the output of {{#annotlist:}}.
vermeul's avatar
vermeul committed
164
    //
vermeul's avatar
vermeul committed
165
166
167
    public static function annotations_list( $parser ) {
        $title = $parser->getTitle();
        $wikiPage = new WikiPage( $title );
168
169
        #$dbr = wfGetDB( DB_REPLICA );
        $dbr = wfGetDB( DB_MASTER );
vermeul's avatar
vermeul committed
170

vermeul's avatar
vermeul committed
171
172
173
        $table = <<<"EOT"
{| class="wikitable sortable"
|-
174
! Category !! Comment !! Link !! Annotated text !! Last edited by !! Modification date
vermeul's avatar
vermeul committed
175

vermeul's avatar
vermeul committed
176
EOT;
177
        # fetch the annotation details
vermeul's avatar
vermeul committed
178
179
180
181
182
        $annotations = $dbr->select(
            array(
                a =>'yata_annotation',
                ac=>'yata_annotation_category',
                c =>'yata_category',
183
184
                pc=>'yata_category',
                u =>'user',
vermeul's avatar
vermeul committed
185
186
            ),
            array(
187
                comment         => "a.comment", 
vermeul's avatar
vermeul committed
188
189
                wiki_text       => "a.wiki_text",
                start_char      => "a.start_char",
vermeul's avatar
vermeul committed
190
                bookmark        => "a.bookmark",
vermeul's avatar
vermeul committed
191
                category        => "c.name",
192
193
194
                parent_category => "pc.name",
                last_edited_by  => "u.user_name",
                last_modified   => "a.modified_date"
vermeul's avatar
vermeul committed
195
196
            ),
            array(
197
                'a.page_id' => $wikiPage->getId()
vermeul's avatar
vermeul committed
198
199
200
201
202
203
            ),
            __METHOD__, 
            array(
                'ORDER BY' => 'a.start_char ASC' 
            ), 
            array( 
204
205
206
207
                'u'  => array( 'LEFT JOIN', array( 'u.user_id = a.user_id') ),
                'ac' => array( 'LEFT JOIN', array( 'ac.annotation_id = a.id' ) ),
                'c'  => array( 'LEFT JOIN', array( 'ac.category_id = c.id' ) ),
                'pc' => array( 'LEFT JOIN', array( 'pc.id = c.parent_id') ),
vermeul's avatar
vermeul committed
208
209
            )
        );
vermeul's avatar
vermeul committed
210

211
        # compose the wiki table
vermeul's avatar
vermeul committed
212
213
214
        foreach($annotations as $annotation) {
            # if a category has no parent, just show the category name
            # in all other cases show parent_category:child_category
215
216
217
218
219
            $wikitext = preg_replace(
                '/{{\s*#annot(?:<end>end)?.*?}}/', 
                '',
                $annotation->wiki_text
            );
220
            $cat = $annotation->parent_category ? $annotation->parent_category . "/" . $annotation->category : $annotation->category;
vermeul's avatar
vermeul committed
221
222
223
            $table .= "|-\n";
            $table .= "| ".$cat
                   ." || ".$annotation->comment 
vermeul's avatar
vermeul committed
224
                   ." || [[$title#".$annotation->bookmark . "]]"
225
226
227
                   ." || " . $wikitext
                   ."\n || " . $annotation->last_edited_by
                   ."\n || " . $annotation->last_modified
vermeul's avatar
vermeul committed
228
                   ."\n";
vermeul's avatar
vermeul committed
229
230
231
232
        }
        $table .= "|}";
        return $table;
        
vermeul's avatar
vermeul committed
233
234
    }

vermeul's avatar
vermeul committed
235
    //
236
    // Render the output of {{#annotcatlist:}}.
vermeul's avatar
vermeul committed
237
238
239
240
241
242
    //
    public static function annotation_categories( $parser, $method, $start_with ) {
        if (! $method  == "list") {
            return "";
        }

243
        $dbr = wfGetDB( DB_MASTER );
244
245
246
        $table = <<<"EOT"
{| class="wikitable sortable"
|-
vermeul's avatar
vermeul committed
247
! Category !! Description !! Parent
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263

EOT;

        $categories = $dbr->select(
            array(
                c =>'yata_category',
                pc=>'yata_category',
                gpc=>'yata_category',
            ),
            array(
                name              => "c.name",
                description       => "c.description",
                parent_name       => "pc.name",
                grand_parent_name => "gpc.name"
            ),
            array(
vermeul's avatar
vermeul committed
264
                #'ac.page_id' => $wikiPage->getId()
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
            ),
            __METHOD__, 
            array(
                #'ORDER BY' => 'a.start_char ASC' 
            ), 
            array( 
                'pc' => array( 'LEFT JOIN',  array( 'pc.id = c.parent_id') ),
                'gpc' => array( 'LEFT JOIN',  array( 'gpc.id = pc.parent_id') )
            )
        );

        foreach($categories as $category) {
            # if a category has no parent, just show the category name
            # in all other cases show parent_category:child_category
            $table .= "|-\n";
vermeul's avatar
vermeul committed
280
281
            $table .= "| ".$category->name
                   ." || ".$category->description
282
                   ." || ".$category->grand_parent_name . "/" . $category->parent_name
vermeul's avatar
vermeul committed
283
                   ."\n";
284
285
286
287
288
289
        }
        $table .= "|}";
        return $table;

    }

vermeul's avatar
vermeul committed
290

vermeul's avatar
vermeul committed
291
292
293
294
295
296
    /* 
        Hook on when page is saved
        we change the content where necessary, e.g.
        - change {{#annotend}} to {{#annotend:}}
        - add errors as hidden text at the beginning of the wikitext
    */ 
vermeul's avatar
vermeul committed
297
    public static function onPageContentSave(WikiPage &$wikiPage, User &$user, Content &$content, $summary, $isMinor, $isWatch, $section, $flags, Status &$status ){
298
        #die("3: onPageContentSave");
vermeul's avatar
vermeul committed
299
    /*
vermeul's avatar
vermeul committed
300
        0. manage all categories (add/delete them)
vermeul's avatar
vermeul committed
301
        1. get all existing annotations which exist on that page.
vermeul's avatar
vermeul committed
302
303
304
305
306
307
        2. find out which annotations have been deleted.
        3. find out which annotations have been added -> assign a unique identifier
        4. find out which annotations have been updated (using the unique
        identifier)
        5. assign every annotation to one or more categories
        6. assign every annotation to this page
vermeul's avatar
vermeul committed
308
309
310
311
312
313
314
315
316
317
    */

        # get database handler
        $dbw = wfGetDB( DB_MASTER );
        $dbr = wfGetDB( DB_REPLICA );
        if ( $content instanceof TextContent ) {

            $data = $content->getNativeData();
            # replace all convenience {{#annotend}} or {{annotend}} with {{#annotend:}}, where necessary
            $data = preg_replace( '/{{#*annotend}}/U','{{#annotend:}}', $data);
318
319
320

            # add / delete categories 
            $data = self::manage_categories($dbw, $data);
vermeul's avatar
vermeul committed
321

322
323
            # get all annotations that exist in the current wikitext
            $annotations = self::parse_annotations($dbw, $data, $wikiPage);
324

325
            # keep the annotations for saving later (onPageContentSaveComplete)
326
            self::$annotations = $annotations;
327
328

            # replace the content and save it
329
330
331
            $content = new WikitextContent( $data );
        }
    }
vermeul's avatar
vermeul committed
332

333
334
335
336
    /**
    * Occurs after the save page request has been processed.
    * @see https://www.mediawiki.org/wiki/Manual:Hooks/PageContentSaveComplete
    *
337
    * save all new or updated annotations. Annotations which are
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
    * no longer present are being deleted.
    */
    public static function onPageContentSaveComplete($wikiPage, $user, $content, $summary,
    $isMinor, $isWatch, $section, $flags, $revision, $status, $baseRevId ) {
        $dbw = wfGetDB( DB_MASTER );
        $seen_bookmarks = array();

        foreach ( self::$annotations as $bookmark => $annotation ){
            $annotation_id = 0;
            $ex_annot = self::get_annotation($dbw, $wikiPage, $bookmark);
            if ($ex_annot) {
                $annotation_id = $ex_annot->id;
                $ex_annot = self::get_annotation($dbw, $wikiPage, $bookmark);
                if ($ex_annot->wiki_text != $annotation["wiki_text"] 
                     or $ex_annot->comment != $annotation["comment"] ) {
                    $dbw->update(
                        'yata_annotation',
                        array(
                            wiki_text => $annotation["wiki_text"],
                            comment   => $annotation["comment"],
                            user_id   => $user->getId(),
                            modified_date => $dbw->timestamp(),
                        ),
                        array(
                            page_id  => $wikiPage->getId(),
                            bookmark => $bookmark
                        )
                    );
                }
            }
            else {
vermeul's avatar
vermeul committed
369
370
371
372
                # write annotation
                $dbw->insert(
                    'yata_annotation',
                    array(
373
                        page_id    => $wikiPage->getId(),
vermeul's avatar
vermeul committed
374
375
                        comment    => $annotation['comment'],
                        wiki_text  => $annotation['wiki_text'],
376
                        bookmark   => $bookmark,
vermeul's avatar
vermeul committed
377
                        user_id    => $user->getId(),
378
379
                        insert_date => $dbw->timestamp(),
                        modified_date => $dbw->timestamp(),
vermeul's avatar
vermeul committed
380
381
382
                    )
                );
                $annotation_id = $dbw->insertId();
383
            }
vermeul's avatar
vermeul committed
384

385
386
387
388
            # insert / update the annotation categories
            if ( $annotation['categories'] ) {
                #die(var_dump( $annotation['categories'] ));
                $seen_acs = array();
389
                foreach ( $annotation['categories'] as $category ){
vermeul's avatar
vermeul committed
390
391
                    # assign all found categories to this annotation
                    if(! is_null($category)) {
392
393
                        self::insert_annotation_category($dbw, $wikiPage, $annotation_id, $category->id);
                        array_push($seen_acs, $category->id);
vermeul's avatar
vermeul committed
394
395
                    }
                }
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
                # delete all annotation categories which are no longer assigned
                # to this annotation
                    $dbw->delete(
                        'yata_annotation_category',
                        array( 
                            page_id       => $wikiPage->getId(),
                            annotation_id => $annotation_id,
                            'category_id NOT IN(' .$dbw->makeList($seen_acs). ')'
                        )
                    );
                }
            else {
                # delete all existing annotation categories,
                # since no category is assigned anymore
                $dbw->delete(
                    'yata_annotation_category',
                    array(
                        page_id       => $wikiPage->getId(),
                        annotation_id => $annotation_id,
                    )
                );
vermeul's avatar
vermeul committed
417
            }
418

vermeul's avatar
vermeul committed
419
420
421
422
423
424
425
            $seen_bookmarks[] =  $bookmark;
        }

        $where = array();
        $where["page_id"] = $wikiPage->getId();
        if ($seen_bookmarks) {
            $where[] = 'bookmark NOT IN(' .$dbw->makeList($seen_bookmarks). ')';
426
427
428
429
430
431
        }

        # find all all annotations which are no longer present
        $annotations_to_delete = $dbw->select(
            'yata_annotation',
            array( 'id' ),
vermeul's avatar
vermeul committed
432
            $where
433
        );
vermeul's avatar
vermeul committed
434
       
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454

        # delete all annotations which are no longer present
        foreach( $annotations_to_delete as $annotation) {
            $dbw->delete(
                'yata_annotation',
                array(
                    id => $annotation->id
                )
            );
        }
        
        # delete all annotation categories
        # of these to-be-deleted annotations
        foreach( $annotations_to_delete as $annotation) {
            $dbw->delete(
                'yata_annotation_category',
                array(
                    id => $annotation->id
                )
            );
vermeul's avatar
vermeul committed
455
456
457
        }
    }

vermeul's avatar
vermeul committed
458
459
    public static function add_category($dbw, $category_name, $description, $parent) {
        $category_name = trim($category_name);
460
461
462
463
        $parent_path = "";
        $parent_id = null;
        if (! is_null($parent)) {
            $parent_category = self::get_category($dbw, $parent);
vermeul's avatar
vermeul committed
464
465
466
            if(! $parent_category) {
                die("no such parent category found: $parent");
            }
467
468
469
470
            $parent_path = $parent_category->path;
            $parent_id = $parent_category->id;
        }

vermeul's avatar
vermeul committed
471
472
473
474
475
476
477
478
479
480
481
482
483
        $exists = $dbw->selectRow(
            'yata_category',
            array('id'),
            array(
                name => $category_name,
                parent_id => $parent_id
            )
        );

        if ($exists) {
            return;
        }

484
485
486
        $dbw->insert(
            'yata_category',
            array(
vermeul's avatar
vermeul committed
487
                name        => $category_name,
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
                description => trim($description),
                parent_id   => $parent_id
            )
        );

        # update the path for the category just inserted
        $dbw->update(
            'yata_category',
            array( 
                path => $parent_path . $dbw->insertId() . "/" 
            ),
            array(
                id => $dbw->insertId()
            )
        );
    }

vermeul's avatar
vermeul committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
    public static function up_category($dbw, $category_name, $description, $parent_name) {
        $category = self::get_category($dbw, $category_name);
        $parent_category = self::get_category($dbw, $parent_name);
        if ($category) {
            $set = array();
            if ($description) {
                $set["description"] = $description;
            }
            if ($parent_category) {
                $set["parent_id"] = $parent_category->id;
            }
            $dbw->update(
                'yata_category',
                $set,
                array(
                    id => $category->id
                )
            );
                
        }
    }

    public static function del_category($dbw, $category_name) {
528

vermeul's avatar
vermeul committed
529
        $cat_entry = self::get_category($dbw, $category_name);
530
531
532
533
534
535
536
537
538
539
        $dbw->delete(
            'yata_category',
            array(
                id => $cat_entry->id
            )
        );
    }

    private static function category_add_del_callback($matches) {
        $dbw = wfGetDB( DB_MASTER );
vermeul's avatar
vermeul committed
540
        list($method, $category_name, $description, $parent) = preg_split('/\s*\|\s*/', $matches["params"]);
541
        if ( $method === "add" ) {
vermeul's avatar
vermeul committed
542
543
544
545
            self::add_category($dbw, $category_name, $description, $parent);
        }
        elseif ( $method === "up" ) {
            self::up_category($dbw, $category_name, $description, $parent);
546
547
        }
        elseif ( $method === "del" ) {
vermeul's avatar
vermeul committed
548
            self::del_category($dbw, $category_name);
549
        }
vermeul's avatar
vermeul committed
550
551
552
        else {
            return $matches[0];
        }
vermeul's avatar
vermeul committed
553
554
555

        # remove the {{#annotcat: add|up|del }} commands from the source code
        # by returning an empty string
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
        return "";
    }

    // manage any categories added
    public static function manage_categories( $dbw, $data) {
        # look for all tags {{#annotcat:(.*)}}
        # and pass the matches to the callback function category_add_del_callback
        # which will return an empty string in order to remove this tag before saving the page.
        $data = preg_replace_callback(
            '/({{#annotcat:\s*(?P<params>.*?)}})/s',
            'self::category_add_del_callback',
            $data
        );
        return $data;
    }

572
573
574
575
576
577
578
579
580
581
582
583
    public static function get_annotation($dbr, $wikiPage, $bookmark) {
        $row = $dbr->selectRow(
            'yata_annotation',
            array('id', 'wiki_text', 'comment'),
            array(
                page_id  => $wikiPage->getId(),
                bookmark => $bookmark
            )
        );
        return $row;
    }

584
585
586
587
588
589
590
591

    public static function get_category($dbr, $category) {
        $category = trim($category);
        # get parent and child category: parent_cat/child_cat
        list($parent_cat, $child_cat) = preg_split('/\s*\/\s*/', $category);

        # we might only have a parent (top) category
        if (is_null($child_cat)) {
vermeul's avatar
vermeul committed
592
593
594
595
596
            # search for a top category (no parent)
            $row = $dbr->selectRow(
                'yata_category',
                array( 'id', 'name', 'description', 'parent_id' ),
                array(
597
                    name      => $parent_cat,
598
                    parent_id => null
vermeul's avatar
vermeul committed
599
600
601
602
603
604
605
606
                )
            );
            return $row;
        }
        else {
            # search for category where parent matches
            # by self-joining table via parent_id
            $row = $dbr->selectRow(
607
                array(pc=>'yata_category', cc=>'yata_category'),
vermeul's avatar
vermeul committed
608
                array( 
609
610
611
612
613
                    id          => 'cc.id', 
                    name        => 'cc.name', 
                    description => 'cc.description',
                    parent_name => 'pc.name',
                    parent_id   => 'cc.parent_id' 
vermeul's avatar
vermeul committed
614
615
                ),
                array(
616
617
                    'cc.name' => $child_cat,
                    'pc.name' => $parent_cat,
vermeul's avatar
vermeul committed
618
619
620
                ),
                __METHOD__,
                array(),
621
                array( 'pc' => array( 'INNER JOIN', array ( 'cc.parent_id = pc.id' ) ) )
vermeul's avatar
vermeul committed
622
623
624
625
626
            );
            return $row;
        } 
    }

vermeul's avatar
vermeul committed
627
628
629
630
631
632
633
634
635
    public static function get_category_for_id($dbr, $id) {
        $row = $dbr->selectRow(
            array('yata_category'),
            array('id', 'name', 'description', 'path'),
            array( id => $id )
        );
        return $row;
    }

636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
    public static function get_category_and_parent_for_id($dbr, $id) {
        $row = $dbr->selectRow(
            array(c=>'yata_category', pc=>'yata_category'),
            array(
                id =>   'c.id',
                name => 'c.name',
                description => 'c.description',
                parent_name => 'pc.name',
                parent_id   => 'pc.id'
            ),
            array(
                'c.id' => $id
            ),
            __METHOD__,
            array(),
            array('pc' => array('LEFT JOIN', array('c.parent_id = pc.id') ) )
        );
        return $row;
    }

vermeul's avatar
vermeul committed
656
    public static function get_child_categories($dbr, $category) {
vermeul's avatar
vermeul committed
657
658
659
        $rows = $dbr->select(
            array('yata_category'),
            array('id', 'name', 'description', 'path'),
vermeul's avatar
vermeul committed
660
661
662
            array(
                "parent_id" => $category->id
            )
vermeul's avatar
vermeul committed
663
        );
vermeul's avatar
vermeul committed
664
665
666
667
668
669
670
671
672
673
674
675
676

        $all_child_categories = array();

        foreach($rows as $row) {
            array_push($all_child_categories, $row);

            $child_categories = self::get_child_categories($dbr, $row);

            foreach($child_categories as $child_category) {
                array_push($all_child_categories, $child_category);
            }
        }
        return $all_child_categories;
vermeul's avatar
vermeul committed
677
678
679
680
681
682
683
684
    }

    public static function get_parent_categories($dbr, $category_id) {
        $row = self::get_category_for_id($category_id);

        $rows = $dbr->select(
            array('yata_category'),
            array('id', 'name', 'description', 'path'),
vermeul's avatar
vermeul committed
685
            $dbr->addQuotes($row->path) . " LIKE CONCAT(path, '%')"
vermeul's avatar
vermeul committed
686
687
688
689
        );
        return $rows;
    }

vermeul's avatar
vermeul committed
690
691
692
693
694
695
696
697
698
    public static function delete_annotations($dbw, $wikiPage) {
        $dbw->delete(
            'yata_annotation',
            array(
                page_id => $wikiPage->getId()
            )
        );
    }

699
700
701
702
703
704
705
706
707
708
709
710
    public static function check_annotation_bookmark_exist($dbr, $wikiPage, $bookmark) {
        $row = $dbr->selectRow(
            array('yata_annotation'),
            array('id'),
            array(
                bookmark => $bookmark,
                page_id  => $wikiPage->getId()
            )
        );
        return $row;
    }

vermeul's avatar
vermeul committed
711
712
713
714
715
716
717
718
719
    public static function delete_annotation_categories($dbw, $wikiPage) {
        $dbw->delete(
            'yata_annotation_category',
            array(
                page_id => $wikiPage->getId()
            )
        );
    }

720
721
    public static function insert_annotation_category($dbw, $wikiPage, $annotation_id, $category_id) {
        $ex_ac = $dbw->selectRow(
vermeul's avatar
vermeul committed
722
            'yata_annotation_category',
723
            array('anz' => 'COUNT(*)'),
vermeul's avatar
vermeul committed
724
            array(
725
                page_id       => $wikiPage->getId(),
vermeul's avatar
vermeul committed
726
727
728
729
                annotation_id => $annotation_id,
                category_id   => $category_id
            )
        );
730
731
732
733
734
735
736
737
738
739
740
741
742
        if ($ex_ac->anz) {
            return;
        }
        else {
            $dbw->insert(
                'yata_annotation_category',
                array(
                    page_id       => $wikiPage->getId(),
                    annotation_id => $annotation_id,
                    category_id   => $category_id
                )
            );
        }
vermeul's avatar
vermeul committed
743
744
745
746
747
748
749
750
751
752
753
754
755
    }

    public static function register_error($dbw, $page_id, $error_msg, $location_char) {
        $dbw->insert(
            'yata_annotation_error',
            array(
                page_id => $page_id,
                error   => $error_msg,
                location_char => $location_char
            )
        );
    }

756
    public static function delete_parsing_errors($dbw, $wikiPage) {
vermeul's avatar
vermeul committed
757
758
759
760
761
762
763
764
        $dbw->delete(
            'yata_annotation_error',
            array(
                page_id => $wikiPage->getId()
            )
        );
    }

765
766
767
768
769
770
771
772
773
774
775
776
777
    # create a unique identifier / bookmark for all
    # annotations which don't have one.
    # It should be long enough to be 99.999% unique on a page
    public static function create_bookmark() {
        $id = substr(
                str_shuffle(
                    str_repeat(
                        '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
                        mt_rand(1,10)
                    )
                
                ),
        1,4);
vermeul's avatar
vermeul committed
778
779
780
        return $id;
    }

781
782
783
    # Main function to parse all annotations,
    # insert a random id (where it doesn't exist)
    public static function parse_annotations($dbw, &$data, $wikiPage){
vermeul's avatar
vermeul committed
784

785
        self::delete_parsing_errors($dbw, $wikiPage);
vermeul's avatar
vermeul committed
786
787


788
789
790
791
        # match either #annot: or #annotend:
        # fetch all options too
        $annotations_found = preg_match_all(
            '/(?P<annotation>{{\s*#annot(?P<end>end)?\s*:\s*(?P<opts>.*?)\s*}})/s', 
vermeul's avatar
vermeul committed
792
            $data, 
793
            $reg_params, 
vermeul's avatar
vermeul committed
794
795
            PREG_OFFSET_CAPTURE
        );
796
797
798
799
800
801
802
803
804
805
806
807
808

        # we can have annotations with an id or without.
        # The id was either entered by hand (for creating overlapping annotations)
        # or it was automatically generated.
        $annotations_with_id = array();
        $annotations = array();

        # as we crawl through the found annotations and give them new ids,
        # we also recreate the wikitext containing all the new ids.
        $new_data = "";  
        $starts = array();
        $start_loc = 0;
        $end_loc   = 0;
vermeul's avatar
vermeul committed
809
        
810
811
812
813
814
815
816
        foreach($reg_params["annotation"] as $index => $value) {
            # $value[1] contains the location where the current tag has been found
            $end_loc = $value[1];
            # rewrite the source code to include new ids in the code
            $new_data = $new_data . substr($data, $start_loc, $end_loc-$start_loc);
            $start_loc = $value[1] + strlen($value[0]);

817
            # we encountered an annotation START
818
819
820
821
822
823
824
825
826
827
828
829
830
            if ($reg_params["end"][$index][0] === "") {
                # split comment|$category|$bookmark by vertical bar
                list($comment, $category, $bookmark) = preg_split(
                    '/\s*\|\s*/', 
                    $reg_params["opts"][$index][0]
                ); 
                # more than one category can be split using a comma: 
                #   category1, category2
                # categories are by default hierarchically organized and must appear
                # in following formats:
                #   parent_category/child_category
                #   /top_category
                #   top_category
831
832
833
834
835
836
837
838
839
840
841
				$cat_strs = preg_split("/\s*\,\s*/", $category, -1, PREG_SPLIT_NO_EMPTY);
                $cats = array();
                foreach($cat_strs as $cat_str) {
                    $cat = self::get_category($dbw, $cat_str);
                    if ($cat) {
                        array_push($cats, $cat);
                    }
                    else {
                        die("could not find category: $cat_str");
                    }
                }
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
                # we encountered an id: replace it with a unique one,
                # if it doesn't exist yet.
                $new_bookmark = 0;
                if ($bookmark) {
                    if ( self::check_annotation_bookmark_exist($dbw, $wikiPage, $bookmark))
                        {
                        # it is an existing annotation, we keep the id
                        $new_bookmark = $bookmark;
                    } 
                    else {
                        # we replace the manually entered id by a random one
                        $new_bookmark = self::create_bookmark();
                    }
                    $annotations_with_id[$bookmark] = $new_bookmark;
                    $annotations[$new_bookmark] = array();
                    $annotations[$new_bookmark]["start_char"] = $value[1] + strlen($value[0]);
                    $annotations[$new_bookmark]["is_new"] = true;
859
                    $annotations[$new_bookmark]["categories"] = $cats;
860
861
862
863
864
865
866
                    $annotations[$new_bookmark]["comment"] = $comment;
                }
                # we found no id, push it on the stack to find its 
                # ending counterpart later
                else {
                    $new_bookmark = self::create_bookmark();
                    $value["new_bookmark"] = $new_bookmark;
867
                    $value["categories"] = $cats;
868
869
870
                    $value["comment"] = $comment;
                    array_push($starts, $value);
                }
871
872
873
874
875
876
877
878
879

                # replace category names with their corresponding id's
                $new_category = join(',',
                    array_map(
                        function($row) { return $row->id; },
                        $cats
                    )
                );
                $new_data = $new_data . "{{#annot:$comment|$new_category|$new_bookmark}}";
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
            }

            # we encountered an annotation ending
            elseif ($reg_params["end"][$index][0] === "end") {
                $bookmark = $reg_params["opts"][$index][0];
                # we encountered an id: try to find its beginning
                if ($bookmark) {
                    if ( $annotations_with_id[$bookmark] ) {
                        # we fetch the new id we created.
                        $new_bookmark = $annotations_with_id[$bookmark];
                        $annotations[ $new_bookmark ]["end"] = 
                            $reg_params["end"][$index];

                        # extract the wiki text between the annotations
                        #$start_char = $annotations[$new_bookmark]["start"][1] 
                        #            + strlen($annotations[ $new_bookmark ]["start"][0]);
                        $start_char = $annotations[$new_bookmark]["start_char"];
                        $end_char   = $reg_params["annotation"][$index][1];
                        $annotations[$new_bookmark]["wiki_text"]  = 
                            substr($data, $start_char, $end_char-$start_char);

                        $new_data = $new_data . "{{#annotend:$new_bookmark}}";
                    }
                    else {
                        die("found #annotend with bookmark=$bookmark but no annotation start with same bookmark");
                    }
                }
                # we found an ending, but have not enough starts: there seems to be a start-ending mismatch
                elseif ( count($starts) == 0 ) {
                    die("starts and ends do not match!");
                }
                # we pop the last start from our stack to match it with its ending
                else {
                    $start = array_pop($starts);
                    $start_char = $start[1] + strlen($start[0]);
                    $end_char   = $reg_params["annotation"][$index][1];
        
                    $new_bookmark = $start["new_bookmark"];
                    $annotations[$new_bookmark] = array(
                        "is_new"     => true,
                        "categories" => $start["categories"],
                        "comment"    => $start["comment"],
                        "wiki_text"  => substr($data, $start_char, $end_char-$start_char)
                    );
                    $reg_params["annotation"][$index][2] = $new_bookmark;
                    $reg_params["annotation"][$index]["new_annot"] = "{{#annotend:$new_bookmark}}";
                    $new_data = $new_data . "{{#annotend:$new_bookmark}}";
                }
            }
        }
        # add the end of the text
        $new_data = $new_data . substr($data, $start_loc, strlen($data)-$start_loc);

        # replace the original wikiText
        $data = $new_data;
vermeul's avatar
vermeul committed
935
936
937
938
        return $annotations;
    }


939
940
941
942
    //
    // Schema updates, called on Vagrant machine with: mwscript update.php
    // otherwise: cd maintenance; php update.php
    // creates the necessary tables for YATA.
vermeul's avatar
vermeul committed
943
944
945
946
947
948
949
    public static function onLoadExtensionSchemaUpdates( DatabaseUpdater $updater ) {
        $updater->addExtensionTable( 'yata_annotation', __DIR__ . '/sql/yata_annotation.sql');
        $updater->addExtensionTable( 'yata_category', __DIR__ . '/sql/yata_category.sql');
        $updater->addExtensionTable( 'yata_annotation_category', __DIR__ . '/sql/yata_annotation_category.sql');
        $updater->addExtensionTable( 'yata_annotation_error', __DIR__ . '/sql/yata_annotation_error.sql');
    }

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
    // called right after «Save Changes»
    // when an error is present, returns to edit page and prints the error
    // used to check whether the syntax of the annotations is correct
    public static function onEditFilter($editor, $text, $section, &$error, $summary) {
        #$error = "gaht's eigentli no?";
        #die("1: onEditFilter");
    }

    // this is called after «Save changes»
    // and after onEditFilter
    public static function onArticlePrepareTextForEdit(&$wikiPage, &$popts) {
        #die("2: onArticlePrepareTextForEdit"); 
    }

    // first hook called when editing a page
    // even before any checks whether a user is allowed to
    public static function onAlternateEdit(&$editPage) {
    #    die("onAlternateEdit");
    }

    // transforms all categories from their internal ID to a text.
    // This allows us to change the category names later without having
    // to change all source code where this category occurs.
    public static function onEditFormInitialText(&$editPage) {
        $data = $editPage->textbox1;
        $data =  preg_replace_callback(
            '/(?:{{#annot:(?P<params>.*?)}})/s',
            'self::replace_id_with_category',
            $data
        );
        // assign the new content
        $editPage->textbox1 = $data;
    }

    // preload edit forms with some content
    public static function onEditFormPreloadText(&$text, &$title) {
        #die("onEditFormPreloadText: $text");
    }

    // callback function for onEditFormInitialText hook
    // all category_id's are replaced with the category names themselves
    // using the parent_category/child_category naming scheme.
    private static function replace_id_with_category($matches) {
        $dbw = wfGetDB( DB_MASTER );
        list($comment, $cat, $bookmark) = preg_split('/\s*\|\s*/', $matches["params"]);
        
        if (!$cat) {
            return $matches[0];
        }
        # TODO: check whether category is numeric
        $categories = preg_split('/\s*,\s*/', $cat);