1<?php
2/*
3 *  plugin: numbering
4 *  clicking on numbering toolbar icon prints next number to editor
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author   Myron Turner <turnemm02@shaw.ca>
7 */
8
9define('DOKU_INC', realpath(dirname(__FILE__)) . '/../../../../');
10require_once(DOKU_INC.'inc/init.php');
11require_once(DOKU_INC.'inc/io.php');
12
13numberingProcessNum();
14exit;
15
16function numberingProcessNum()
17{
18    $db = numberingDB();
19    $helper = plugin_load('helper', 'numbering');
20
21    $start = urldecode($helper->getConfValue('nstart'));
22    $number = getNumberingNextNumber($db, $start);
23
24    $padding =  urldecode($helper->getConfValue('padding'));
25    $len = (int)  urldecode($helper->getConfValue('pad_length'));
26    $set_date =  $helper->getConfValue('set_date');
27    $format  =   urldecode($helper->getConfValue('format'));
28
29    if($helper->getConfValue('use_imgs') ){
30        $imagestr=urldecode($helper->getConfValue('imgs'));
31        $images = explode(',',$imagestr);
32        $i_no = 0;
33         foreach($images as $img) {
34            $nxt =  '%i' . ++$i_no;
35            $format =  str_replace($nxt , '{{' . $img . '}}' ,$format);
36         }
37    }
38
39    if($set_date) {
40       $dformat  =  urldecode($helper->getConfValue('datestyle'));
41       $time = strftime($dformat);
42       $format = str_replace('%d', $time, $format);
43    }
44
45    $n =  str_pad((string)$number, (int)$len, $padding, STR_PAD_LEFT);
46    $format = str_replace('%n', $n, $format);
47    echo "$format\n\n";
48}
49
50
51function getNumberingNextNumber($db, $start) {
52
53    io_lock($db);
54    $ar = unserialize(io_readFile($db,false));
55    if(!$ar) {
56        $ar['saved'] = $start;
57        $ar['start'] = $start;
58    }
59    else {
60        $number = $ar['saved'];
61        if($ar['start'] != $start) {
62             $ar['start'] = $start;
63             $number = $start;
64        }
65        else $number = $ar['saved'];
66    }
67    if($number < $start) $number = $start-1;
68    $ar['saved'] =  ++$number;
69
70    file_put_contents($db,serialize($ar));
71    io_unlock($db);
72    return "$number";
73}
74
75function numberingDB() {
76$db  = metaFN("numbering:seqnum",'.ser');
77if(!file_exists($db)) {
78    io_saveFile($db,"", array());
79}
80return $db;
81}
82
83