1<?php
2define('DOKU_INC', realpath(dirname(__FILE__)) . '/../../../../');
3require_once(DOKU_INC.'inc/init.php');
4require_once(DOKU_INC.'inc/io.php');
5
6/*
7  *  @author Myron Turner <turnermm02@shaw.ca>
8  *  When a snippet is updated a table of pages appears on the snippet page
9  *  listing the pages where this snippet has been inserted. Each page name is
10  *  a link which accesses this script by means of an ajax call.
11  *  This script does two things:
12  *    1. Inserts updated snippet into page
13  *    2. Checks and updates meta file of page to prune away any references
14  *    to snippets which are no longer on page.  This is done only if requested
15  *    by ticking off check box at head of table
16*/
17
18if(isset($_REQUEST) && !empty($_REQUEST['update'])) {
19    $id = urldecode($_REQUEST['update']);  // file to update
20    $snippet = urldecode($_REQUEST['snippet']);
21}
22else {  // used for testing
23  $id = $argv[1];
24  echo $id . "\n";
25 $snippet = 'snippet_1';
26}
27
28$helper = plugin_load('helper', 'snippets');
29$page = wikiFN($id);
30$result = io_readFile($page);
31$helper->insertSnippet($result, $id,false);   // insert all updated snippets
32
33// update timestamps in metafiles
34global $snip_data;
35$snip_data=unserialize(io_readFile($helper->getMetaFileName(),false));
36if(array_key_exists($id,$snip_data['doc'])) {
37    $snippets = $snip_data['doc'][$id];
38    foreach($snippets as $snip) {
39        $helper->updateMetaTime($id,$snip) ;
40    }
41}
42io_saveFile($page,$result);  // save updated page
43
44
45// if requested prune out dead timestamps: default is to prune
46if(isset($_REQUEST['prune'])) {
47   snippets_prune_meta($id,$snippet);
48}
49
50function snippets_prune_meta($id,$snip) {
51    global $snip_data,$helper;
52
53    $data = p_get_metadata($id, 'relation isreferencedby');
54    $snippets = array_keys($data['snippets']);
55    $file=wikiFN($id);
56    $text = file_get_contents($file);
57    preg_match_all("/~~SNIPPET_C~~(.*?)~~/",$text,$matches);
58    $intersect = array_intersect($matches[1],$snippets);
59
60    if(!in_array($snip,$intersect) ){  //was this snippet found in the current page
61      $pages = $helper->getPageArray($snip_data['snip'][$snip] , $id);  // if not, remove it from the snippet's page array
62      $snip_data['snip'][$snip] = $pages;
63       io_saveFile($helper->getMetaFileName(),serialize($snip_data));
64    }
65
66    $isref = array('snippets'=>array());
67    foreach ($intersect as $i) {
68        $isref['snippets'][$i]=$data['snippets'][$i];
69    }
70
71    $data = array();
72     $data['relation']['isreferencedby']=$isref;
73
74     p_set_metadata($id, $data);
75}
76exit;
77
78
79
80
81
82