File: template.inc.php

package info (click to toggle)
zoph 1.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,632 kB
  • sloc: php: 28,044; javascript: 10,435; sql: 527; sh: 153; makefile: 4
file content (578 lines) | stat: -rw-r--r-- 19,146 bytes parent folder | download
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
<?php
/**
 * Class that takes care of displaying templates
 *
 * This file is part of Zoph.
 *
 * Zoph is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @author Jeroen Roos
 * @package Zoph
 */

namespace template;

use log;
use page;
use photo;
use router\router;
use settings;
use user;
use Time;
use DateInterval;

use conf\conf;
use zoph\app;

/**
 * This class takes care of displaying templates
 *
 * @author Jeroen Roos
 * @package Zoph
 */
class template {
    /** @var array javascript for this template */
    public $js=array();
    /** @var array variables that can be used in the template
                    all variables will be preceeded with $tpl_ */
    public $vars=array();
    /** @var string CSS style for this template */
    public $style="";
    /** @var string Javascript to be included in header */
    public array $scripts = array();
    /** @var array CSS files to be included */
    public $css=array();
    /** @var string HTML title for the page to be displayed */
    public $title="Zoph";
    /** @var string Template file to be used */
    public $template="";

    /** @var array contains actionlinks */
    private $actionlinks=array();

    /**
     * @var array contains blocks or sub-templates that will be
     *              displayed inside this template by calling the
     *              getBlocks() function from within the template
     */
    private $blocks=array();

    /**
     * Create template object
     *
     * @param string Name of template (without path or extension)
     * @param array Array of variables that can be used in the template
     * @return template
     */
    public function __construct($template, $vars=null) {
        $tpl=conf::get("interface.template");
        $this->vars=$vars;
        if (preg_match("/^[A-Za-z0-9_\-]+$/", $tpl) &&
                preg_match("/^[A-Za-z0-9_\-]+$/", $template)) {
            $file="templates/" . $tpl . "/" . $template . ".tpl.php";
            if (!file_exists($file)) {
                $file="templates/default/" . $template . ".tpl.php";
            }
            $this->template=$file;

            $this->vars["css"][]="css";
        } else {
            log::msg("Illegal characters in template", log::FATAL, log::GENERAL);
        }
    }

    public static function getFile(string $dir, string $filename) {
        $tpl=conf::get("interface.template");
        if (preg_match("/^[A-Za-z0-9_\-\/\.]+$/", $filename) && !preg_match("/\.\./", $filename)) {
            $file="templates/" . $tpl . "/" . $dir . "/" . $filename;
            if (!file_exists($file)) {
                $file="templates/default/" . $dir . "/" . $filename;
            }
            return "/" . $file;
        } else {
            log::msg("Illegal characters in file name", log::FATAL, log::GENERAL);
        }
    }

    /**
     * Get image URL for specific template.
     * if the image does not exist in the current template, the default will be be returned
     * This enables template builders to only include the parts of the template that
     * have been changed
     * @param string image name
     * @return string relative image url
     */
    public static function getImage(string $image) {
        $path = app::getBasePath() . self::getFile("images", $image);
        return str_replace("//", "/", $path);
    }

    /**
     * Print the template
     *
     * @return string
     */
    public function __toString() {
        $this->vars["basepath"] = app::getBasePath();
        if ($this->vars) {
            extract($this->vars, EXTR_PREFIX_ALL, "tpl");
        }
        if (!defined("ZOPH")) {
            define('ZOPH', true);
        }
        try {
            ob_start();
                include $this->template;
            return trim(ob_get_clean());
        } catch (\Exception $e) {
            echo $e->getMessage();
            die();
        }
    }

    /**
     * Add a block
     * @param block Block to be added
     */
    public function addBlock(block $block=null) {
        $this->blocks[]=$block;
    }

    /**
     * Add a page
     * A page can simply be added to the list of blocks as it can be displayed
     * with the __toString() function
     * @param page Page to be added
     */
    public function addPage(page $page) {
        $this->blocks[]=$page;
    }

    /**
     * Add a break
     */
    public function addBreak() {
        $this->blocks[]=new block("br", array());
    }

    /**
     * Add multiple blocks
     * @param array Blocks to be added
     */
    public function addBlocks(array $blocks) {
        foreach ($blocks as $block) {
            $this->addBlock($block);
        }
    }

    /**
     * Get the blocks inside this template
     * @return array blocks
     */
    protected function getBlocks() {
        return $this->blocks;
    }

    /**
     * Display the blocks inside this template
     * @return string HTML code for the blocks
     */
    protected function displayBlocks() {
        $html="";
        foreach ($this->getBlocks() as $block) {
            $html.=$block;
        }
        return $html;
    }

    /**
     * Add an actionlink
     * @param string Title to be displayed
     * @param string URL
     */
    public function addActionlink($title, $link) {
        $this->actionlinks[$title]=$link;
    }

    /**
     * Add multiple actionlinks
     * @param array of actionlinks
     */
    public function addActionlinks(array $al) {
        foreach ($al as $title => $link) {
            $this->addActionlink($title, $link);
        }
    }

    /**
     * Markup an array of actionlinks using the actionlinks template
     * @param array Optional array of actionlinks, otherwise use the ones in the class
     */
    private function getActionlinks(array $actionlinks=null) {
        if ($actionlinks==null) {
            $actionlinks=$this->actionlinks;
        }
        if (is_array($actionlinks)) {
            return new block("actionlinks", array(
                "actionlinks"   => $actionlinks
            ));
        }
    }

    /**
     * Create a link list
     * Creates a comma separated list of links from the given records.
     * The class of the records must implement the getURL() and getName() function.
     * @param array Array of records to be displayed
     * @return string Comma separated links to records
     */
    public static function createLinkList(array $records) : ?block {
        $tpl = null;
        if ($records) {
            $tpl = new block("links", array(
                "objects" => $records
            ));
        }

        return $tpl;
    }

    /**
     * Creates an array to be used in the createDropdown methods.  The
     * values of the fields in the name_fields parameter are concatentated
     * together to construnct the titles of the selections.
     * @param array Records to be processed
     * @param array fields to use to contruct title
     * @return array Array that can be fed to the createDropdown methods.
     */
    public static function createSelectArray(array $records, array $nameFields, $addEmpty=false) {
        if (empty($records) || !$nameFields) {
            return array();
        }
        $sa=array();

        if ($addEmpty) {
            $sa[]="&nbsp;";
        }

        foreach ($records as $rec) {
            // this only makes sense when there is one key
            $id = $rec->getId();

            $name = "";
            foreach ($nameFields as $n) {
                if ($name) {
                    $name .= " ";
                }
                $name .= $rec->get($n);
            }

            $sa[$id] = $name;
        }

        return $sa;
    }

    public static function createInputDate($name, $value, $label=null) {
        return static::createInput($name, $value, label: $label, type: "date");
    }
    public static function createInputTime($name, $value, $label=null) {
        return static::createInput($name, $value, label: $label, type: "time");
    }
    public static function createInputEmail($name, $value, $label=null) {
        return static::createInput($name, $value, maxlength: 64, size: 32, label: $label, type: "email");
    }
    public static function createInputNumber($name, $value, $label=null, $min = 0, $max = 100) {
        $size = log10($max) + 5;
        return static::createInput($name, $value, label: $label, type: "number", size: $size, min: $min, max: $max);
    }
    /**
     * Create form input field
     * @param string name of the input
     * @param string initial value
     * @param int maximum length
     * @param string label to be added
     * @param int|null display size, will be set from maxlength if null
     * @param string hint - add some text after the input to help the user what to put there
     * @param string type - html type [ text, date, time, ... ]
     * @param int minimum value (only for type = number/range)
     * @param int maximum value (only for type = number/range)
     */
    public static function createInput($name, $value, $maxlength = 32, $label=null, $size=null, $hint=null, $type="text", $min = 0, $max = 100) {
        if (!$size) {
            $size=$maxlength;
        }
        return new block("formInputText", array(
            "label"     => e($label),
            "name"      => e($name),
            "value"     => e($value),
            "size"      => (int) $size,
            "maxlength" => (int) $maxlength,
            "hint"      => e($hint),
            "type"      => $type,
            "min"       => $min,
            "max"       => $max
        ));
    }

    /**
     * Create dropdown (select)
     * @param string name for select box
     * @param string current value
     * @param array array of options
     * @param bool autosubmit form after making a change
     */
    public static function createDropdown($name, $value, $selectArray, $autosubmit=false, $onchange=null) {
        return new block("select", array(
            "name"  => $name,
            "id"    => preg_replace("/^_+/", "", $name),
            "options" => $selectArray,
            "value" => $value,
            "autosubmit"    => (bool) $autosubmit,
            "onchange" => $onchange
        ));
    }

    /**
     * Create dropdown (select) to change the view
     * @param string name for select box
     * @param string current value
     * @param bool autosubmit form after making a change
     */
    public static function createViewDropdown($name, $value, $autosubmit=false) {
        return static::createDropdown($name, $value, array(
            "list" => translate("List", 0),
            "tree" => translate("Tree", 0),
            "thumbs" => translate("Thumbnails", 0)), (bool) $autosubmit);
    }

    /**
     * Create dropdown (select) to determine how the automatic thumbnail is selected
     * @param string name for select box
     * @param string current value
     * @param bool autosubmit form after making a change
     */
    public static function createAutothumbDropdown($name, $value, $autosubmit=false) {
        return  static::createDropdown($name, $value, array(
            "oldest" => translate("Oldest photo", 0),
            "newest" => translate("Newest photo", 0),
            "first" => translate("Changed least recently", 0),
            "last" => translate("Changed most recently", 0),
            "highest" => translate("Highest ranked", 0),
            "random" => translate("Random", 0)),
        (bool)$autosubmit);
    }

    /**
     * Create dropdown (select) that lists all photo fields
     * @param string name for select box
     * @param string current value
     */
    public static function createPhotoFieldDropdown($name, $value) {
        return  static::createDropdown($name, $value, translate(photo::getFields(), 0));
    }

    public static function createPhotoTextDropdown($name, $value) {
        return template::createDropdown($name, $value, array(
            "" => "",
            "album" => translate("album", 0),
            "category" => translate("category", 0),
            "person" => translate("person", 0),
            "photographer" => translate("photographer", 0)));
    }

    /**
     * Create dropdown (select) that lists photo fields for the import page
     * @param string name for select box
     * @param string current value
     */
    public static function createImportFieldDropdown($name, $value) {
        return  static::createDropdown($name, $value, translate(photo::getImportFields(), 0));
    }

    /**
     * Create comparison operator dropdown, tailored for text comparison
     * @param string name for select box
     * @param string current value
     */
    public static function createTextOperatorDropdown($name, $value = "=") {
        return static::createDropdown($name, $value,
            array(
                "="     => "=",
                "!="    => "!=",
                "like" => translate("like", 0),
                "not like" => translate("not like", 0)
        ));
    }

    /**
     * Create comparison operator dropdown
     * @param string name for select box
     * @param string current value
     */
    public static function createOperatorDropdown($name, $value = "=") {
        return static::createDropdown($name, $value,
            array(
                "="     => "=",
                "!="    => "!=",
                ">"     => ">",
                ">="    => ">=",
                "<"     => "<",
                "<="    => "<=",
                "like" => translate("like", 0),
                "not like" => translate("not like", 0)
        ));
    }

    /**
     * Create inequality operator [less than/more than] dropdown
     * @param string name for select box
     * @param string current value
     */
    public static function createInequalityOperatorDropdown($name, $value = "") {
        return template::createDropdown($name, $value,
           array(">" => translate("less than"), "<" => translate("more than")));
    }

    /**
     * Create dropdown (select) with options "yes" and "no" (translated)
     * @param string name for select box
     * @param string current value
     */
    public static function createBinaryOperatorDropdown($name, $value = "=") {
        return  static::createDropdown($name, $value, array(
            "=" => "=",
            "!=" => "!="
        ));
    }

    public static function createPresentOperatorDropdown($name, $value = "=") {
        return template::createDropdown($name, $value,
            array(
                "=" => translate("is in photo", 0),
                "!=" => translate("is not in photo", 0)
        ));
    }


    /**
     * Create dropdown (select) with options "yes" and "no" (translated)
     * @param string name for select box
     * @param string current value
     */
    public static function createYesNoDropdown($name, $value) {
        return  static::createDropdown($name, $value, array(
            "0" => translate("No", 0),
            "1" => translate("Yes", 0)
        ));
    }

    /**
     * Create conjunction [and/or] dropdown
     * @param string name for select box
     * @param string current value
     */
    public static function createConjunctionDropdown($name, $value = "") {
        return template::createDropdown($name, $value,
            array("" => "", "and" => translate("and", 0), "or" => translate("or", 0)));
    }

    /**
     * Create dropdown with variable number of days
     * @param string name for select box
     * @param string current value
     */
    public static function createDaysAgoDropdown($name, $value) {
        $dt=new Time(date("Y-m-d"));
        $dateArray=array("" => "");

        $day=new DateInterval("P1D");
        for ($i = 1; $i <= conf::get("interface.max.days"); $i++) {
            $dt->sub($day);
            $dateArray[$dt->format("Y-m-d")] = $i;
        }

        return template::createDropdown($name, $value, $dateArray);
    }

    /**
     * Create dropdown with integers
     * @param string name for select box
     * @param string current value
     */
    public static function createIntegerDropdown($name, $value, $min, $max) {
        $intArray=array();
        for ($i = $min; $i <= $max; $i++) {
            $intArray["$i"] = $i;
        }
        return template::createDropdown($name, $value, $intArray);
    }

    /**
     * transforms a size in bytes into a human readable format using
     * Ki Mi Gi, etc. prefixes
     * Give me a call if your database grows bigger than 1024 Yobbibytes. :-)
     * @param int bytes number of bytes
     * @return string human readable filesize
     */
    public static function getHumanReadableBytes(int $bytes) {
        if ($bytes==0) {
            // prevents div by 0
            return "0B";
        } else {
            $prefixes=array("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi");
            $length=floor(log($bytes, 2)/10);
            return round($bytes/pow(2, 10*($length)), 1) . $prefixes[floor($length)] . "B";
        }
    }

    /**
     * Display warning about disabled Javascript
     */
    public static function showJSwarning() {
        $user=user::getCurrent();
        if ((($user->prefs->get("autocomp_albums")) ||
            ($user->prefs->get("autocomp_categories")) ||
            ($user->prefs->get("autocomp_places")) ||
            ($user->prefs->get("autocomp_people")) ||
            ($user->prefs->get("autocomp_photographer"))) &&
            conf::get("interface.autocomplete")) {

            $warning=new block("message", array(
                "class" => "warning",
                "text"  => translate("You have enabled autocompletion for one or more dropdown " .
                                     "boxes on this page, however, you do not seem to have Javascript " .
                                     "support. You should either enable javascript or turn autocompletion " .
                                     "off, or this page will not work as expected!")
            ));

            $noscript=new block("noscript");
            $noscript->addBlocks(array($warning));
            return $noscript;
        }
    }

    /**
     * Get all templates
     * Search the template directory for directory entries
     */
    public static function getAll() {
        $templates=array();
        foreach (glob(settings::$phpLocation . "/templates/*", GLOB_ONLYDIR) as $tpl) {
            $tpl=basename($tpl);
            $templates[$tpl]=$tpl;
        }
        return $templates;
    }
}