This repository was archived by the owner on Aug 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathUtil.php
More file actions
712 lines (680 loc) · 22.9 KB
/
Util.php
File metadata and controls
712 lines (680 loc) · 22.9 KB
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
<?php
/**
* Clip
*
* @copyright (c) Clip Team
* @link http://github.com/zikula-modules/clip/
* @license GNU/GPL - http://www.gnu.org/copyleft/gpl.html
* @package Clip
* @subpackage Lib
*/
namespace Matheo\Clip;
use Matheo\Clip\Form\ViewForm;
use ModUtil;
use StringUtil;
use Zikula_AbstractController;
use Zikula_View;
use ZLoader;
use Matheo\Clip\Generator;
use CategoryRegistryUtil;
use Doctrine_Core;
use DataUtil;
use FormUtil;
use Matheo\Clip\Util\PluginsUtil;
use ZLanguage;
use Matheo\Clip\Import\BatchImport;
use LogUtil;
use ServiceUtil;
use Zikula_View_Resource;
use Matheo\Clip\Util\ViewUtil;
use Matheo\Clip\Doctrine\PubdataDoctrine;
use Matheo_Clip_Model_Pubtype;
class Util
{
const REGEX_FOLDER = '#[^a-z0-9_/]+#i';
const REGEX_TEMPLATE = '/[^a-z0-9_\\.\\-]+/i';
const REGEX_URLTITLE = '/[^a-z0-9_\\-]+/i';
/**
* Arguments store.
*
* @var array
*/
protected static $args = array();
/**
* self::$args getter.
*/
public static function getArgs($id = null)
{
if ($id && isset(self::$args[$id])) {
return self::$args[$id];
}
return self::$args;
}
/**
* self::$args setter.
*/
public static function setArgs($id, $args)
{
self::$args[$id] = $args;
}
/**
* Clip boot
*
* @return void
*/
public static function boot()
{
static $booted = false;
if (!$booted) {
// add the dynamic models path
ZLoader::addAutoloader('ClipModels', realpath(StringUtil::left(ModUtil::getVar('Clip', 'modelspath'), -11)));
// check if the models are already created
Generator::checkModels();
$booted = true;
}
}
/**
* Extract the TID from a string end.
*
* @return integer Publication type ID.
*/
public static function getDefaultCategoryID()
{
static $id;
if (!isset($id)) {
$id = (int) CategoryRegistryUtil::getRegisteredModuleCategory('Clip', 'clip_pubtypes', 'Global');
}
return $id;
}
/**
* Extract the first GID from the grouptypes.
*
* @return integer Grouptype ID.
*/
public static function getDefaultGrouptype()
{
static $id;
if (!isset($id)) {
$id = (int) Doctrine_Core::getTable('Matheo_Clip_Model_Grouptype')->createQuery()->select('gid')->orderBy('gid')->where('gid > ?', 1)->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
}
return $id;
}
/**
* Extract the arguments.
*
* @param array $args
*
* @return array Extracted arguments.
*/
public static function getClipArgs(
&$clipvalues,
$get,
$args = array()
) {
foreach (array_keys($get->getCollection()) as $param) {
if (strpos($param, '_') === 0) {
$clipvalues[substr($param, 1)] = $get->filter($param);
}
}
foreach (array_keys((array) $args) as $param) {
if (strpos($param, '_') === 0) {
$clipvalues[substr($param, 1)] = $args[$param];
}
}
}
/**
* Format the orderby parameter.
*
* @param string $orderby Order by string.
* @param array $relfields Relation field aliases on this table.
*
* @return string Orderby clause.
*/
public static function createOrderBy($orderby, $relfields = array())
{
$orderbylist = !is_array($orderby) ? explode(',', $orderby) : $orderby;
$orderbylist = array_map('trim', $orderbylist);
$orderby = '';
foreach ($orderbylist as $key => $value) {
if ($key > 0) {
$orderby .= ', ';
}
// $value = {col[:(asc|desc)]}
$value = explode(':', $value);
$orderby .= isset($relfields[$value[0]]) ? DataUtil::formatForStore($relfields[$value[0]]) : DataUtil::formatForStore($value[0]);
$orderby .= isset($value[1]) && in_array(strtoupper($value[1]), array('ASC', 'DESC')) ? ' ' . strtoupper($value[1]) : '';
}
return $orderby;
}
/**
* Name reference generator.
*
* @return string Random id.
*/
public static function getNewFileReference()
{
$chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$charLen = strlen($chars);
$id = '';
for ($i = 0; $i < 30; ++$i) {
$id .= $chars[mt_rand(0, $charLen - 1)];
}
return $id;
}
/**
* Extract the filter from the input to build a cacheid.
*
* @param string $varname Name of the filter variable on use.
*
* @see FilterUtil::getFiltersFromInput()
*
* @return string Filter id to use inside cacheid.
*/
public static function getFilterCacheId($varname = 'filter')
{
$i = 1;
$filterid = array();
// Get unnumbered filter string
$filterStr = FormUtil::getPassedValue($varname, '');
if (!empty($filterStr)) {
$filterid[] = urldecode($filterStr);
}
// Get filter1 ... filterN
while (true) {
$filterStr = FormUtil::getPassedValue("{$varname}{$i}", '');
if (empty($filterStr)) {
break;
}
$filterid[] = urldecode($filterStr);
++$i;
}
if (count($filterid) > 0) {
$filterid = implode('*', $filterid);
}
return self::getFilterCacheString($filterid);
}
/**
* Checker of simple templates.
*
* Simple templates are display ones without a Publication loaded on them,
* useful for notifications like pending.
*
* @param string $template Template to evaluate.
*
* @return boolean True if it's a simple template, false otherwise.
*/
public static function isSimpleTemplate($template)
{
$simpletemplates = array('pending');
if (!in_array($template, $simpletemplates)) {
$template = strpos($template, 'simple') === 0 ? substr($template, 6) : false;
}
return $template;
}
/**
* Replace some critical vars of the filter definition.
*
* @param string $filter Filter definition.
*
* @return string Filter string to use inside cacheid.
*/
public static function getFilterCacheString($filter)
{
return str_replace(array('(', ')', '*', ','), array('-', '-', '__', '___'), $filter);
}
/**
* Publication type configuration getter.
*
* @param string $section Section to retrieve.
* @param array $config A configuration section to validate.
*
* @return array Pubtype config array.
*/
public static function getPubtypeConfig($section = null, $config = array())
{
$result = array('list' => array('load' => false, 'onlyown' => true, 'checkperm' => false), 'display' => array('load' => true, 'onlyown' => true, 'checkperm' => true), 'edit' => array('load' => true, 'onlyown' => true, 'checkperm' => false));
if ($config && $section && isset($result[$section])) {
$config = array_intersect_key($config, $result[$section]);
return array_merge($result[$section], $config);
}
if ($section && isset($result[$section])) {
return $result[$section];
}
return $result;
}
/**
* Validates that a value is not a reserved word.
*
* @param string $value
*
* @return boolean True on valid, false on reserved word.
*/
public static function validateReservedWord($value)
{
$reservedwords = array('module', 'modname', 'func', 'type', 'tid', 'pid', 'id', 'submit', 'edit', 'commandName', '__WORKFLOW__');
return in_array($value, $reservedwords) || strpos('core_', $value) === 0 || strpos('rel_', $value) === 0;
}
/**
* Validates a TID number.
*
* @param integer $tid
*
* @return boolean True on valid publication type, false otherwise.
*/
public static function validateTid($tid)
{
if (is_numeric($tid) && $tid > 0 && self::getPubType($tid)) {
return true;
} else {
if (!is_numeric($tid) && self::getPubType($tid)) {
return true;
}
}
return false;
}
/**
* Extract the TID from a string end.
*
* @param string $tablename
*
* @return integer Publication type ID.
*/
public static function getTidFromString($tablename)
{
$tid = '';
while (is_numeric(substr($tablename, -1))) {
$tid = substr($tablename, -1) . $tid;
$tablename = substr($tablename, 0, strlen($tablename) - 1);
}
return $tid;
}
/**
* Removes any numerical suffix of a string.
*
* @param string $string
*
* @return string String without numeric suffix.
*/
public static function getStringPrefix($string)
{
$suffixnumber = self::getTidFromString($string);
return str_replace($suffixnumber, '', $string);
}
/**
* PubType getter.
*
* @param integer $tid Pubtype ID or urltitle.
*
* @return Matheo_Clip_Model_Pubtype Information of one or all the pubtypes.
*/
public static function getPubType(
$tid = -1,
$field = null,
$force = false
) {
static $pubtypes, $urltitles;
if (!isset($pubtypes) || $force) {
$pubtypes = Doctrine_Core::getTable('Matheo_Clip_Model_Pubtype')->getPubtypes();
$urltitles = $pubtypes->toKeyValueArray('urltitle', 'tid');
}
if ($tid == -1) {
return $pubtypes;
}
if (!is_numeric($tid)) {
$tid = isset($urltitles[$tid]) ? $urltitles[$tid] : $tid;
}
if (isset($pubtypes[$tid])) {
$pubtype = self::getPubTypeSub($pubtypes[$tid], $tid);
if ($pubtype != null) {
if ($field) {
// TODO get() for unloaded properties?
return isset($pubtype[$field]) ? $pubtype[$field] : $field;
}
return $pubtype;
}
}
$null = null;
return $null;
}
/* Utility function to return the pubtype reference */
private static function getPubTypeSub(&$pubtype, $tid)
{
if ($pubtype['tid'] == $tid) {
return $pubtype;
}
$null = null;
return $null;
}
/**
* Pubtype Relations getter.
*
* @param integer $tid Pubtype ID.
* @param boolean $owningSide Whether to fetch the owning side relations of the pubtype.
* @þaram boolean $force Whether to force the refresh of the cache.
*
* @return array Relations for the passed pubtype.
*/
public static function getRelations(
$tid = -1,
$owningSide = true,
$force = false
) {
static $relation_arr;
if (!isset($relation_arr) || $force) {
$relation_arr = Doctrine_Core::getTable('Matheo_Clip_Model_Pubrelation')->getClipRelations();
}
$own = $owningSide ? 'own' : 'not';
if ($tid == -1) {
return $relation_arr[$own];
}
return isset($relation_arr[$own][$tid]) ? $relation_arr[$own][$tid] : array();
}
/**
* PubFields getter.
*
* @param integer $tid Pubtype ID.
* @param string $name Name of the field to get.
* @param string $orderBy Field name to sort by.
* @param boolean $attrs Whether to load field attributes or not.
*
* @return array Array of fields of one or all the loaded pubtypes.
*/
public static function getPubFields(
$tid,
$name = null,
$orderBy = 'lineno',
$attrs = false
) {
static $pubfields_arr;
$tid = (int) $tid;
if ($tid && !isset($pubfields_arr[$tid])) {
$pubfields_arr[$tid] = Doctrine_Core::getTable('Matheo_Clip_Model_Pubfield')->selectCollection(
"tid = '{$tid}'",
$orderBy,
-1,
-1,
'name'
);
}
if ($name) {
return isset($pubfields_arr[$tid][$name]) ? $pubfields_arr[$tid][$name] : array();
}
if ($attrs) {
foreach ($pubfields_arr[$tid] as $name => &$field) {
if ($field->hasMappedValue('attrs')) {
// already loaded
break;
}
$plugin = PluginsUtil::get($field['fieldplugin']);
$field->mapValue('attrs', method_exists($plugin, 'clipAttributes') ? (array) $plugin->clipAttributes($field) : array());
}
}
return isset($pubfields_arr[$tid]) ? $pubfields_arr[$tid] : array();
}
/**
* PubField data getter.
*
* @param integer $tid Pubtype ID.
* @param string $name Name of the field to get.
* @param string $property Field to retrieve.
*
* @return mixed Field or one of its properties.
*/
public static function getPubFieldData(
$tid,
$name,
$property = null
) {
if (!$name) {
return null;
}
if (strpos($name, 'core_') === 0) {
return PluginsUtil::getCoreFieldData($name, $property);
}
$pubfield = self::getPubFields($tid, $name);
if (!$pubfield) {
return null;
}
if ($property) {
return isset($pubfield[$property]) ? $pubfield[$property] : null;
}
return $pubfield;
}
/**
* Title field getter.
*
* @param integer $tid Pubtype ID.
*
* @return array One or all the pubtype titles.
*/
public static function getTitleField($tid)
{
$titlefield = Doctrine_Core::getTable('Matheo_Clip_Model_Pubfield')->selectField('name', "tid = '{$tid}' AND istitle = '1'");
return $titlefield ? $titlefield : 'id';
}
/**
* Loop the pubfields array until get the title field.
*
* @param array $pubfields
*
* @return string Name of the title field.
*/
public static function findTitleField($pubfields)
{
$core_title = 'id';
foreach ($pubfields as $i => $pubfield) {
if ($pubfield['istitle'] == 1) {
$core_title = $pubfield['name'];
break;
}
}
return $core_title;
}
/**
* Install the default 'blog' and 'staticpages' publication types.
*
* @return void
*/
public static function installDefaultypes()
{
$dom = ZLanguage::getModuleDomain('Clip');
$lang = ZLanguage::getLanguageCode();
$batch = new BatchImport();
$defaults = array('blog', 'staticpages');
foreach ($defaults as $default) {
// check if the pubtype exists
$pubtype = Doctrine_Core::getTable('Matheo_Clip_Model_Pubtype')->findByUrltitle($default);
if (count($pubtype)) {
LogUtil::registerStatus(__f('There is already a \'%s\' publication type.', $default, $dom));
} else {
// import the default XML
$file = "modules/matheo/clip-module/Resources/docs/xml/{$lang}/{$default}.xml";
if (!file_exists($file)) {
$file = "modules/matheo/clip-module/Resources/docs/xml/en/{$default}.xml";
}
if ($batch->setup(array('url' => $file)) && $batch->execute()) {
LogUtil::registerStatus(__f('Default \'%s\' publication type created successfully.', $default, $dom));
} else {
LogUtil::registerStatus(__f('Could not import the \'%s\' publication type.', $default, $dom));
}
}
}
}
/**
* Form view instance builder.
*
* @param Zikula_AbstractController $controller Related controller.
* @param boolean $force Wheter to force the creation of a new instance or not.
* @see FormUtil::newForm
*
* @return ViewForm Form view instance.
*/
public static function newForm($controller = null, $force = false)
{
$serviceManager = ServiceUtil::getManager();
$serviceId = 'zikula.view.form.clip';
if ($force && $serviceManager->hasService($serviceId)) {
$serviceManager->detachService($serviceId);
}
if ($force || !$serviceManager->hasService($serviceId)) {
$form = new ViewForm($serviceManager, 'Clip');
$serviceManager->attachService($serviceId, $form);
} else {
$form = $serviceManager->getService($serviceId);
}
if ($controller) {
$form->setController($controller);
$form->assign('controller', $controller);
$form->setEntityManager($controller->getEntityManager());
}
return $form;
}
/**
* Clear the Theme's Engine cache.
*
* @return void
*/
public static function clearThemeCache($cacheid)
{
$serviceManager = ServiceUtil::getManager();
$serviceId = 'zikula.theme';
if ($serviceManager->hasService($serviceId)) {
$themeInstance = $serviceManager->getService($serviceId);
if ($themeInstance->getCaching()) {
$themeInstance->clear_cache(null, $cacheid);
}
}
}
/**
* Registration of Clip's plugins sensible to cache.
*
* @return void
*/
public static function register_nocache_plugins(Zikula_View &$view)
{
// disables the cache for them and do not load them yet
// that happens later when required
$delayed_load = true;
$cacheable = false;
/* blocks */
// Accessblock
Zikula_View_Resource::register($view, 'block', 'Accessblock', $delayed_load, $cacheable, array('gid', 'tid', 'pub', 'pid', 'id', 'context', 'tplid', 'permlvl'));
/* plugins */
// Access
Zikula_View_Resource::register($view, 'function', 'Access', $delayed_load, $cacheable, array('gid', 'tid', 'pub', 'pid', 'id', 'context', 'tplid', 'permlvl', 'assign'));
// clip_filter
Zikula_View_Resource::register($view, 'function', 'clip_filter', $delayed_load, $cacheable, array('template'));
// clip_hitcount
Zikula_View_Resource::register($view, 'function', 'Access', $delayed_load, $cacheable, array('gid', 'tid', 'pub', 'pid', 'id', 'context', 'tplid', 'permlvl', 'assign'));
}
/**
* Process of Clip's view for its controllers.
*
* @return void
*/
public static function register_utilities(Zikula_View &$view)
{
static $tids, $dirs;
// clip_notifyfilters requires the core modifier
require_once $view->_get_plugin_filepath('modifier', 'notifyfilters');
if (!isset($tids) || !isset($dirs)) {
$pubtypes = self::getPubType();
// index the IDs with the urltitle
$tids = $dirs = array();
foreach ($pubtypes as $tid => $pubtype) {
$tids[$pubtype->urltitle] = $tid;
$dirs[$pubtype->urltitle] = $pubtype->folder;
}
}
// clip pubtype IDs array
$view->assign('cliptids', $tids)->assign('clipdirs', $dirs);
// Util
if (!isset($view->_reg_objects['Util'])) {
$Util = new ViewUtil();
$view->register_object('Util', $Util);
}
}
/**
* Build a public Clip URL.
*
* @param mixed $obj A pubtype, a publication or a tid.
* @param string $func The specific function to run.
* @param array $args The array of arguments to put on the URL.
* @param boolean|null $ssl Set to constant null,true,false $ssl = true not $ssl = 'true' null - leave the current status untouched,
* true - create a ssl url, false - create a non-ssl url.
* @param string $fragment The framgment to target within the URL.
* @param boolean|null $fqurl Fully Qualified URL. True to get full URL, eg for Redirect, else gets root-relative path unless SSL.
* @param boolean $forcelongurl Force ModUtil::url to not create a short url even if the system is configured to do so.
* @param boolean|string $forcelang Force the inclusion of the $forcelang or default system language in the generated url.
*
* @return string
*/
public static function url(
$obj,
$func,
$args = array(),
$ssl = null,
$fragment = null,
$fqurl = null,
$forcelongurl = false,
$forcelang = false
) {
if ($obj instanceof PubtypeModel) {
$args['tid'] = $obj['tid'];
} else {
if ($obj instanceof PubdataDoctrine) {
$args['tid'] = $obj['core_tid'];
if ($func == 'display' || $func == 'edit') {
if ($obj['core_pid']) {
$args['pid'] = $obj['core_pid'];
if ($func == 'edit') {
$args['id'] = $obj['id'];
}
$args['urltitle'] = $obj['core_urltitle'];
} else {
$func = 'main';
}
}
} else {
$args['tid'] = $obj;
}
}
return ModUtil::url('Clip', 'user', $func, $args, $ssl, $fragment, $fqurl, $forcelongurl, $forcelang);
}
/**
* Build a public Clip URL object.
*
* @param mixed $obj A pubtype, a publication or a tid.
* @param string $func The specific function to run.
* @param array $args The array of arguments to put on the URL.
* @param string $language Force the inclusion of the $forcelang or default system language in the generated url.
* @param string $fragment The framgment to target within the URL.
*
* @return object Clip_Url instance.
*/
public static function urlobj(
$obj,
$func,
$args = array(),
$language = null,
$fragment = null
) {
if ($obj instanceof PubtypeModel) {
$args['tid'] = $obj['tid'];
} else {
if ($obj instanceof PubdataDoctrine) {
$args['tid'] = $obj['core_tid'];
if ($func == 'display' || $func == 'edit') {
$args['pid'] = $obj['core_pid'];
if ($func == 'edit') {
$args['id'] = $obj['id'];
}
$args['urltitle'] = $obj['core_urltitle'];
}
} else {
$args['tid'] = $obj;
}
}
return new Url('Clip', 'user', $func, $args, $language, $fragment);
}
}