Completed
Push — master ( 2d4977...3189d6 )
by Michael
10:50
created
class/smartobjecthandler.php 1 patch
Indentation   +966 added lines, -966 removed lines patch added patch discarded remove patch
@@ -25,970 +25,970 @@
 block discarded – undo
25 25
  */
26 26
 class SmartPersistableObjectHandler extends XoopsObjectHandler
27 27
 {
28
-    public $_itemname;
29
-
30
-    /**
31
-     * Name of the table use to store this {@link SmartObject}
32
-     *
33
-     * Note that the name of the table needs to be free of the database prefix.
34
-     * For example "smartsection_categories"
35
-     * @var string
36
-     */
37
-    public $table;
38
-
39
-    /**
40
-     * Name of the table key that uniquely identify each {@link SmartObject}
41
-     *
42
-     * For example: "categoryid"
43
-     * @var string
44
-     */
45
-    public $keyName;
46
-
47
-    /**
48
-     * Name of the class derived from {@link SmartObject} and which this handler is handling
49
-     *
50
-     * Note that this string needs to be lowercase
51
-     *
52
-     * For example: "smartsectioncategory"
53
-     * @var string
54
-     */
55
-    public $className;
56
-
57
-    /**
58
-     * Name of the field which properly identify the {@link SmartObject}
59
-     *
60
-     * For example: "name" (this will be the category's name)
61
-     * @var string
62
-     */
63
-    public $identifierName;
64
-
65
-    /**
66
-     * Name of the field which will be use as a summary for the object
67
-     *
68
-     * For example: "summary"
69
-     * @var string
70
-     */
71
-    public $summaryName;
72
-
73
-    /**
74
-     * Page name use to basically manage and display the {@link SmartObject}
75
-     *
76
-     * This page needs to be the same in user side and admin side
77
-     *
78
-     * For example category.php - we will deduct smartsection/category.php as well as smartsection/admin/category.php
79
-     * @todo this could probably be automatically deducted from the class name - for example, the class SmartsectionCategory will have "category.php" as it's managing page
80
-     * @var string
81
-     */
82
-    public $_page;
83
-
84
-    /**
85
-     * Full path of the module using this {@link SmartObject}
86
-     *
87
-     * <code>XOOPS_URL . "/modules/smartsection/"</code>
88
-     * @todo this could probably be automatically deducted from the class name as it is always prefixed with the module name
89
-     * @var string
90
-     */
91
-    public $_modulePath;
92
-
93
-    public $_moduleUrl;
94
-
95
-    public $_moduleName;
96
-
97
-    public $_uploadUrl;
98
-
99
-    public $_uploadPath;
100
-
101
-    public $_allowedMimeTypes = 0;
102
-
103
-    public $_maxFileSize = 1000000;
104
-
105
-    public $_maxWidth = 500;
106
-
107
-    public $_maxHeight = 500;
108
-
109
-    public $highlightFields = array();
110
-
111
-    /**
112
-     * Array containing the events name and functions
113
-     *
114
-     * @var array
115
-     */
116
-    public $eventArray = array();
117
-
118
-    /**
119
-     * Array containing the permissions that this handler will manage on the objects
120
-     *
121
-     * @var array
122
-     */
123
-    public $permissionsArray = false;
124
-
125
-    public $generalSQL = false;
126
-
127
-    public $_eventHooks     = array();
128
-    public $_disabledEvents = array();
129
-
130
-    /**
131
-     * Constructor - called from child classes
132
-     *
133
-     * @param object|XoopsDatabase $db           {@link XoopsDatabase}
134
-     *                                           object
135
-     * @param                      $itemname
136
-     * @param string               $keyname      Name of the table key that uniquely identify each {@link SmartObject}
137
-     * @param string               $idenfierName Name of the field which properly identify the {@link SmartObject}
138
-     * @param                      $summaryName
139
-     * @param                      $modulename
140
-     * @internal param string $tablename Name of the table use to store this <a href='psi_element://SmartObject'>SmartObject</a>
141
-     * @internal param Name $string of the class derived from <a href='psi_element://SmartObject'>SmartObject</a> and which this handler is handling and which this handler is handling
142
-     * @internal param string $page Page name use to basically manage and display the <a href='psi_element://SmartObject'>SmartObject</a>
143
-     * @internal param string $moduleName name of the module
144
-     */
145
-    public function __construct(XoopsDatabase $db, $itemname, $keyname, $idenfierName, $summaryName, $modulename)
146
-    {
147
-        parent::__construct($db);
148
-
149
-        $this->_itemname      = $itemname;
150
-        $this->_moduleName    = $modulename;
151
-        $this->table          = $db->prefix($modulename . '_' . $itemname);
152
-        $this->keyName        = $keyname;
153
-        $this->className      = ucfirst($modulename) . ucfirst($itemname);
154
-        $this->identifierName = $idenfierName;
155
-        $this->summaryName    = $summaryName;
156
-        $this->_page          = $itemname . '.php';
157
-        $this->_modulePath    = XOOPS_ROOT_PATH . '/modules/' . $this->_moduleName . '/';
158
-        $this->_moduleUrl     = XOOPS_URL . '/modules/' . $this->_moduleName . '/';
159
-        $this->_uploadPath    = XOOPS_UPLOAD_PATH . '/' . $this->_moduleName . '/';
160
-        $this->_uploadUrl     = XOOPS_UPLOAD_URL . '/' . $this->_moduleName . '/';
161
-    }
162
-
163
-    /**
164
-     * @param $event
165
-     * @param $method
166
-     */
167
-    public function addEventHook($event, $method)
168
-    {
169
-        $this->_eventHooks[$event] = $method;
170
-    }
171
-
172
-    /**
173
-     * Add a permission that this handler will manage for its objects
174
-     *
175
-     * Example: $this->addPermission('view', _AM_SSHOP_CAT_PERM_READ, _AM_SSHOP_CAT_PERM_READ_DSC);
176
-     *
177
-     * @param string      $perm_name   name of the permission
178
-     * @param string      $caption     caption of the control that will be displayed in the form
179
-     * @param bool|string $description description of the control that will be displayed in the form
180
-     */
181
-    public function addPermission($perm_name, $caption, $description = false)
182
-    {
183
-        include_once(SMARTOBJECT_ROOT_PATH . 'class/smartobjectpermission.php');
184
-
185
-        $this->permissionsArray[] = array(
186
-            'perm_name'   => $perm_name,
187
-            'caption'     => $caption,
188
-            'description' => $description
189
-        );
190
-    }
191
-
192
-    /**
193
-     * @param $criteria
194
-     * @param $perm_name
195
-     * @return bool
196
-     */
197
-    public function setGrantedObjectsCriteria(&$criteria, $perm_name)
198
-    {
199
-        $smartPermissionsHandler = new SmartobjectPermissionHandler($this);
200
-        $grantedItems             = $smartPermissionsHandler->getGrantedItems($perm_name);
201
-        if (count($grantedItems) > 0) {
202
-            $criteria->add(new Criteria($this->keyName, '(' . implode(', ', $grantedItems) . ')', 'IN'));
203
-
204
-            return true;
205
-        } else {
206
-            return false;
207
-        }
208
-    }
209
-
210
-    /**
211
-     * @param bool $_uploadPath
212
-     * @param bool $_allowedMimeTypes
213
-     * @param bool $_maxFileSize
214
-     * @param bool $_maxWidth
215
-     * @param bool $_maxHeight
216
-     */
217
-    public function setUploaderConfig($_uploadPath = false, $_allowedMimeTypes = false, $_maxFileSize = false, $_maxWidth = false, $_maxHeight = false)
218
-    {
219
-        $this->_uploadPath       = $_uploadPath ?: $this->_uploadPath;
220
-        $this->_allowedMimeTypes = $_allowedMimeTypes ?: $this->_allowedMimeTypes;
221
-        $this->_maxFileSize      = $_maxFileSize ?: $this->_maxFileSize;
222
-        $this->_maxWidth         = $_maxWidth ?: $this->_maxWidth;
223
-        $this->_maxHeight        = $_maxHeight ?: $this->_maxHeight;
224
-    }
225
-
226
-    /**
227
-     * create a new {@link SmartObject}
228
-     *
229
-     * @param bool $isNew Flag the new objects as "new"?
230
-     *
231
-     * @return object {@link SmartObject}
232
-     */
233
-    public function &create($isNew = true)
234
-    {
235
-        $obj = new $this->className($this);
236
-        $obj->setImageDir($this->getImageUrl(), $this->getImagePath());
237
-        if (!$obj->handler) {
238
-            $obj->handler =& $this;
239
-        }
240
-
241
-        if ($isNew === true) {
242
-            $obj->setNew();
243
-        }
244
-
245
-        return $obj;
246
-    }
247
-
248
-    /**
249
-     * @return string
250
-     */
251
-    public function getImageUrl()
252
-    {
253
-        return $this->_uploadUrl . $this->_itemname . '/';
254
-    }
255
-
256
-    /**
257
-     * @return string
258
-     */
259
-    public function getImagePath()
260
-    {
261
-        $dir = $this->_uploadPath . $this->_itemname;
262
-        if (!file_exists($dir)) {
263
-            smart_admin_mkdir($dir);
264
-        }
265
-
266
-        return $dir . '/';
267
-    }
268
-
269
-    /**
270
-     * retrieve a {@link SmartObject}
271
-     *
272
-     * @param  mixed $id        ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
273
-     * @param  bool  $as_object whether to return an object or an array
274
-     * @param  bool  $debug
275
-     * @param  bool  $criteria
276
-     * @return mixed reference to the <a href='psi_element://SmartObject'>SmartObject</a>, FALSE if failed
277
-     *                          FALSE if failed
278
-     */
279
-    public function get($id, $as_object = true, $debug = false, $criteria = false)
280
-    {
281
-        if (!$criteria) {
282
-            $criteria = new CriteriaCompo();
283
-        }
284
-        if (is_array($this->keyName)) {
285
-            for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
286
-                /**
287
-                 * In some situations, the $id is not an INTEGER. SmartObjectTag is an example.
288
-                 * Is the fact that we removed the (int)() represents a security risk ?
289
-                 */
290
-                //$criteria->add(new Criteria($this->keyName[$i], ($id[$i]), '=', $this->_itemname));
291
-                $criteria->add(new Criteria($this->keyName[$i], $id[$i], '=', $this->_itemname));
292
-            }
293
-        } else {
294
-            //$criteria = new Criteria($this->keyName, (int)($id), '=', $this->_itemname);
295
-            /**
296
-             * In some situations, the $id is not an INTEGER. SmartObjectTag is an example.
297
-             * Is the fact that we removed the (int)() represents a security risk ?
298
-             */
299
-            $criteria->add(new Criteria($this->keyName, $id, '=', $this->_itemname));
300
-        }
301
-        $criteria->setLimit(1);
302
-        if ($debug) {
303
-            $obj_array = $this->getObjectsD($criteria, false, $as_object);
304
-        } else {
305
-            $obj_array = $this->getObjects($criteria, false, $as_object);
306
-            //patch: weird bug of indexing by id even if id_as_key = false;
307
-            if (!isset($obj_array[0]) && is_object($obj_array[$id])) {
308
-                $obj_array[0] = $obj_array[$id];
309
-                unset($obj_array[$id]);
310
-                $obj_array[0]->unsetNew();
311
-            }
312
-        }
313
-
314
-        if (count($obj_array) != 1) {
315
-            $obj =& $this->create();
316
-
317
-            return $obj;
318
-        }
319
-
320
-        return $obj_array[0];
321
-    }
322
-
323
-    /**
324
-     * retrieve a {@link SmartObject}
325
-     *
326
-     * @param  mixed $id        ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
327
-     * @param  bool  $as_object whether to return an object or an array
328
-     * @return mixed reference to the {@link SmartObject}, FALSE if failed
329
-     */
330
-    public function &getD($id, $as_object = true)
331
-    {
332
-        return $this->get($id, $as_object, true);
333
-    }
334
-
335
-    /**
336
-     * retrieve objects from the database
337
-     *
338
-     * @param object $criteria  {@link CriteriaElement} conditions to be met
339
-     * @param bool   $id_as_key use the ID as key for the array?
340
-     * @param bool   $as_object return an array of objects?
341
-     *
342
-     * @param  bool  $sql
343
-     * @param  bool  $debug
344
-     * @return array
345
-     */
346
-    public function getObjects($criteria = null, $id_as_key = false, $as_object = true, $sql = false, $debug = false)
347
-    {
348
-        $ret   = array();
349
-        $limit = $start = 0;
350
-
351
-        if ($this->generalSQL) {
352
-            $sql = $this->generalSQL;
353
-        } elseif (!$sql) {
354
-            $sql = 'SELECT * FROM ' . $this->table . ' AS ' . $this->_itemname;
355
-        }
356
-
357
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
358
-            $sql .= ' ' . $criteria->renderWhere();
359
-            if ($criteria->getSort() != '') {
360
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
361
-            }
362
-            $limit = $criteria->getLimit();
363
-            $start = $criteria->getStart();
364
-        }
365
-        if ($debug) {
366
-            xoops_debug($sql);
367
-        }
368
-
369
-        $result = $this->db->query($sql, $limit, $start);
370
-        if (!$result) {
371
-            return $ret;
372
-        }
373
-
374
-        return $this->convertResultSet($result, $id_as_key, $as_object);
375
-    }
376
-
377
-    /**
378
-     * @param       $sql
379
-     * @param       $criteria
380
-     * @param  bool $force
381
-     * @param  bool $debug
382
-     * @return array
383
-     */
384
-    public function query($sql, $criteria, $force = false, $debug = false)
385
-    {
386
-        $ret = array();
387
-
388
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
389
-            $sql .= ' ' . $criteria->renderWhere();
390
-            if ($criteria->groupby) {
391
-                $sql .= $criteria->getGroupby();
392
-            }
393
-            if ($criteria->getSort() != '') {
394
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
395
-            }
396
-        }
397
-        if ($debug) {
398
-            xoops_debug($sql);
399
-        }
400
-
401
-        if ($force) {
402
-            $result = $this->db->queryF($sql);
403
-        } else {
404
-            $result = $this->db->query($sql);
405
-        }
406
-
407
-        if (!$result) {
408
-            return $ret;
409
-        }
410
-
411
-        while ($myrow = $this->db->fetchArray($result)) {
412
-            $ret[] = $myrow;
413
-        }
414
-
415
-        return $ret;
416
-    }
417
-
418
-    /**
419
-     * retrieve objects with debug mode - so will show the query
420
-     *
421
-     * @param object $criteria  {@link CriteriaElement} conditions to be met
422
-     * @param bool   $id_as_key use the ID as key for the array?
423
-     * @param bool   $as_object return an array of objects?
424
-     *
425
-     * @param  bool  $sql
426
-     * @return array
427
-     */
428
-    public function getObjectsD($criteria = null, $id_as_key = false, $as_object = true, $sql = false)
429
-    {
430
-        return $this->getObjects($criteria, $id_as_key, $as_object, $sql, true);
431
-    }
432
-
433
-    /**
434
-     * @param $arrayObjects
435
-     * @return array|bool
436
-     */
437
-    public function getObjectsAsArray($arrayObjects)
438
-    {
439
-        $ret = array();
440
-        foreach ($arrayObjects as $key => $object) {
441
-            $ret[$key] = $object->toArray();
442
-        }
443
-        if (count($ret > 0)) {
444
-            return $ret;
445
-        } else {
446
-            return false;
447
-        }
448
-    }
449
-
450
-    /**
451
-     * Convert a database resultset to a returnable array
452
-     *
453
-     * @param object $result    database resultset
454
-     * @param bool   $id_as_key - should NOT be used with joint keys
455
-     * @param bool   $as_object
456
-     *
457
-     * @return array
458
-     */
459
-    public function convertResultSet($result, $id_as_key = false, $as_object = true)
460
-    {
461
-        $ret = array();
462
-        while ($myrow = $this->db->fetchArray($result)) {
463
-            $obj =& $this->create(false);
464
-            $obj->assignVars($myrow);
465
-            if (!$id_as_key) {
466
-                if ($as_object) {
467
-                    $ret[] =& $obj;
468
-                } else {
469
-                    $ret[] = $obj->toArray();
470
-                }
471
-            } else {
472
-                if ($as_object) {
473
-                    $value =& $obj;
474
-                } else {
475
-                    $value = $obj->toArray();
476
-                }
477
-                if ($id_as_key === 'parentid') {
478
-                    $ret[$obj->getVar('parentid', 'e')][$obj->getVar($this->keyName)] =& $value;
479
-                } else {
480
-                    $ret[$obj->getVar($this->keyName)] = $value;
481
-                }
482
-            }
483
-            unset($obj);
484
-        }
485
-
486
-        return $ret;
487
-    }
488
-
489
-    /**
490
-     * @param  null $criteria
491
-     * @param  int  $limit
492
-     * @param  int  $start
493
-     * @return array
494
-     */
495
-    public function getListD($criteria = null, $limit = 0, $start = 0)
496
-    {
497
-        return $this->getList($criteria, $limit, $start, true);
498
-    }
499
-
500
-    /**
501
-     * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS
502
-     *
503
-     * @param object $criteria {@link CriteriaElement} conditions to be met
504
-     * @param int    $limit    Max number of objects to fetch
505
-     * @param int    $start    Which record to start at
506
-     *
507
-     * @param  bool  $debug
508
-     * @return array
509
-     */
510
-    public function getList($criteria = null, $limit = 0, $start = 0, $debug = false)
511
-    {
512
-        $ret = array();
513
-        if ($criteria == null) {
514
-            $criteria = new CriteriaCompo();
515
-        }
516
-
517
-        if ($criteria->getSort() == '') {
518
-            $criteria->setSort($this->getIdentifierName());
519
-        }
520
-
521
-        $sql = 'SELECT ' . (is_array($this->keyName) ? implode(', ', $this->keyName) : $this->keyName);
522
-        if (!empty($this->identifierName)) {
523
-            $sql .= ', ' . $this->getIdentifierName();
524
-        }
525
-        $sql .= ' FROM ' . $this->table . ' AS ' . $this->_itemname;
526
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
527
-            $sql .= ' ' . $criteria->renderWhere();
528
-            if ($criteria->getSort() != '') {
529
-                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
530
-            }
531
-            $limit = $criteria->getLimit();
532
-            $start = $criteria->getStart();
533
-        }
534
-
535
-        if ($debug) {
536
-            xoops_debug($sql);
537
-        }
538
-
539
-        $result = $this->db->query($sql, $limit, $start);
540
-        if (!$result) {
541
-            return $ret;
542
-        }
543
-
544
-        $myts = MyTextSanitizer::getInstance();
545
-        while ($myrow = $this->db->fetchArray($result)) {
546
-            //identifiers should be textboxes, so sanitize them like that
547
-            $ret[$myrow[$this->keyName]] = empty($this->identifierName) ? 1 : $myts->displayTarea($myrow[$this->identifierName]);
548
-        }
549
-
550
-        return $ret;
551
-    }
552
-
553
-    /**
554
-     * count objects matching a condition
555
-     *
556
-     * @param  object $criteria {@link CriteriaElement} to match
557
-     * @return int    count of objects
558
-     */
559
-    public function getCount($criteria = null)
560
-    {
561
-        $field   = '';
562
-        $groupby = false;
563
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
564
-            if ($criteria->groupby != '') {
565
-                $groupby = true;
566
-                $field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
567
-            }
568
-        }
569
-        /**
570
-         * if we have a generalSQL, lets used this one.
571
-         * This needs to be improved...
572
-         */
573
-        if ($this->generalSQL) {
574
-            $sql = $this->generalSQL;
575
-            $sql = str_replace('SELECT *', 'SELECT COUNT(*)', $sql);
576
-        } else {
577
-            $sql = 'SELECT ' . $field . 'COUNT(*) FROM ' . $this->table . ' AS ' . $this->_itemname;
578
-        }
579
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
580
-            $sql .= ' ' . $criteria->renderWhere();
581
-            if ($criteria->groupby != '') {
582
-                $sql .= $criteria->getGroupby();
583
-            }
584
-        }
585
-
586
-        $result = $this->db->query($sql);
587
-        if (!$result) {
588
-            return 0;
589
-        }
590
-        if ($groupby == false) {
591
-            list($count) = $this->db->fetchRow($result);
592
-
593
-            return $count;
594
-        } else {
595
-            $ret = array();
596
-            while (list($id, $count) = $this->db->fetchRow($result)) {
597
-                $ret[$id] = $count;
598
-            }
599
-
600
-            return $ret;
601
-        }
602
-    }
603
-
604
-    /**
605
-     * delete an object from the database
606
-     *
607
-     * @param  XoopsObject $obj reference to the object to delete
608
-     * @param  bool        $force
609
-     * @return bool        FALSE if failed.
610
-     */
611
-    public function delete(XoopsObject $obj, $force = false)
612
-    {
613
-        $eventResult = $this->executeEvent('beforeDelete', $obj);
614
-        if (!$eventResult) {
615
-            $obj->setErrors('An error occured during the BeforeDelete event');
616
-
617
-            return false;
618
-        }
619
-
620
-        if (is_array($this->keyName)) {
621
-            $clause = array();
622
-            for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
623
-                $clause[] = $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
624
-            }
625
-            $whereclause = implode(' AND ', $clause);
626
-        } else {
627
-            $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
628
-        }
629
-        $sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
630
-        if (false != $force) {
631
-            $result = $this->db->queryF($sql);
632
-        } else {
633
-            $result = $this->db->query($sql);
634
-        }
635
-        if (!$result) {
636
-            return false;
637
-        }
638
-
639
-        $eventResult = $this->executeEvent('afterDelete', $obj);
640
-        if (!$eventResult) {
641
-            $obj->setErrors('An error occured during the AfterDelete event');
642
-
643
-            return false;
644
-        }
645
-
646
-        return true;
647
-    }
648
-
649
-    /**
650
-     * @param $event
651
-     */
652
-    public function disableEvent($event)
653
-    {
654
-        if (is_array($event)) {
655
-            foreach ($event as $v) {
656
-                $this->_disabledEvents[] = $v;
657
-            }
658
-        } else {
659
-            $this->_disabledEvents[] = $event;
660
-        }
661
-    }
662
-
663
-    /**
664
-     * @return array
665
-     */
666
-    public function getPermissions()
667
-    {
668
-        return $this->permissionsArray;
669
-    }
670
-
671
-    /**
672
-     * insert a new object in the database
673
-     *
674
-     * @param  XoopsObject $obj         reference to the object
675
-     * @param  bool        $force       whether to force the query execution despite security settings
676
-     * @param  bool        $checkObject check if the object is dirty and clean the attributes
677
-     * @param  bool        $debug
678
-     * @return bool        FALSE if failed, TRUE if already present and unchanged or successful
679
-     */
680
-    public function insert(XoopsObject $obj, $force = false, $checkObject = true, $debug = false)
681
-    {
682
-        if ($checkObject != false) {
683
-            if (!is_object($obj)) {
684
-                return false;
685
-            }
686
-            /**
687
-             * @TODO: Change to if (!(class_exists($this->className) && $obj instanceof $this->className)) when going fully PHP5
688
-             */
689
-            if (!is_a($obj, $this->className)) {
690
-                $obj->setError(get_class($obj) . ' Differs from ' . $this->className);
691
-
692
-                return false;
693
-            }
694
-            if (!$obj->isDirty()) {
695
-                $obj->setErrors('Not dirty'); //will usually not be outputted as errors are not displayed when the method returns true, but it can be helpful when troubleshooting code - Mith
696
-
697
-                return true;
698
-            }
699
-        }
700
-
701
-        if ($obj->seoEnabled) {
702
-            // Auto create meta tags if empty
703
-            $smartobjectMetagen = new SmartMetagen($obj->title(), $obj->getVar('meta_keywords'), $obj->summary());
704
-
705
-            if (!$obj->getVar('meta_keywords') || !$obj->getVar('meta_description')) {
706
-                if (!$obj->meta_keywords()) {
707
-                    $obj->setVar('meta_keywords', $smartobjectMetagen->_keywords);
708
-                }
709
-
710
-                if (!$obj->meta_description()) {
711
-                    $obj->setVar('meta_description', $smartobjectMetagen->_meta_description);
712
-                }
713
-            }
714
-
715
-            // Auto create short_url if empty
716
-            if (!$obj->short_url()) {
717
-                $obj->setVar('short_url', $smartobjectMetagen->generateSeoTitle($obj->title('n'), false));
718
-            }
719
-        }
720
-
721
-        $eventResult = $this->executeEvent('beforeSave', $obj);
722
-        if (!$eventResult) {
723
-            $obj->setErrors('An error occured during the BeforeSave event');
724
-
725
-            return false;
726
-        }
727
-
728
-        if ($obj->isNew()) {
729
-            $eventResult = $this->executeEvent('beforeInsert', $obj);
730
-            if (!$eventResult) {
731
-                $obj->setErrors('An error occured during the BeforeInsert event');
732
-
733
-                return false;
734
-            }
735
-        } else {
736
-            $eventResult = $this->executeEvent('beforeUpdate', $obj);
737
-            if (!$eventResult) {
738
-                $obj->setErrors('An error occured during the BeforeUpdate event');
739
-
740
-                return false;
741
-            }
742
-        }
743
-        if (!$obj->cleanVars()) {
744
-            $obj->setErrors('Variables were not cleaned properly.');
745
-
746
-            return false;
747
-        }
748
-        $fieldsToStoreInDB = array();
749
-        foreach ($obj->cleanVars as $k => $v) {
750
-            if ($obj->vars[$k]['data_type'] == XOBJ_DTYPE_INT) {
751
-                $cleanvars[$k] = (int)$v;
752
-            } elseif (is_array($v)) {
753
-                $cleanvars[$k] = $this->db->quoteString(implode(',', $v));
754
-            } else {
755
-                $cleanvars[$k] = $this->db->quoteString($v);
756
-            }
757
-            if ($obj->vars[$k]['persistent']) {
758
-                $fieldsToStoreInDB[$k] = $cleanvars[$k];
759
-            }
760
-        }
761
-        if ($obj->isNew()) {
762
-            if (!is_array($this->keyName)) {
763
-                if ($cleanvars[$this->keyName] < 1) {
764
-                    $cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
765
-                }
766
-            }
767
-
768
-            $sql = 'INSERT INTO ' . $this->table . ' (' . implode(',', array_keys($fieldsToStoreInDB)) . ') VALUES (' . implode(',', array_values($fieldsToStoreInDB)) . ')';
769
-        } else {
770
-            $sql = 'UPDATE ' . $this->table . ' SET';
771
-            foreach ($fieldsToStoreInDB as $key => $value) {
772
-                if ((!is_array($this->keyName) && $key == $this->keyName) || (is_array($this->keyName) && in_array($key, $this->keyName))) {
773
-                    continue;
774
-                }
775
-                if (isset($notfirst)) {
776
-                    $sql .= ',';
777
-                }
778
-                $sql .= ' ' . $key . ' = ' . $value;
779
-                $notfirst = true;
780
-            }
781
-            if (is_array($this->keyName)) {
782
-                $whereclause = '';
783
-                for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
784
-                    if ($i > 0) {
785
-                        $whereclause .= ' AND ';
786
-                    }
787
-                    $whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
788
-                }
789
-            } else {
790
-                $whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
791
-            }
792
-            $sql .= ' WHERE ' . $whereclause;
793
-        }
794
-
795
-        if ($debug) {
796
-            xoops_debug($sql);
797
-        }
798
-
799
-        if (false != $force) {
800
-            $result = $this->db->queryF($sql);
801
-        } else {
802
-            $result = $this->db->query($sql);
803
-        }
804
-
805
-        if (!$result) {
806
-            $obj->setErrors($this->db->error());
807
-
808
-            return false;
809
-        }
810
-
811
-        if ($obj->isNew() && !is_array($this->keyName)) {
812
-            $obj->assignVar($this->keyName, $this->db->getInsertId());
813
-        }
814
-        $eventResult = $this->executeEvent('afterSave', $obj);
815
-        if (!$eventResult) {
816
-            $obj->setErrors('An error occured during the AfterSave event');
817
-
818
-            return false;
819
-        }
820
-
821
-        if ($obj->isNew()) {
822
-            $obj->unsetNew();
823
-            $eventResult = $this->executeEvent('afterInsert', $obj);
824
-            if (!$eventResult) {
825
-                $obj->setErrors('An error occured during the AfterInsert event');
826
-
827
-                return false;
828
-            }
829
-        } else {
830
-            $eventResult = $this->executeEvent('afterUpdate', $obj);
831
-            if (!$eventResult) {
832
-                $obj->setErrors('An error occured during the AfterUpdate event');
833
-
834
-                return false;
835
-            }
836
-        }
837
-
838
-        return true;
839
-    }
840
-
841
-    /**
842
-     * @param       $obj
843
-     * @param  bool $force
844
-     * @param  bool $checkObject
845
-     * @param  bool $debug
846
-     * @return bool
847
-     */
848
-    public function insertD(&$obj, $force = false, $checkObject = true, $debug = false)
849
-    {
850
-        return $this->insert($obj, $force, $checkObject, true);
851
-    }
852
-
853
-    /**
854
-     * Change a value for objects with a certain criteria
855
-     *
856
-     * @param string $fieldname  Name of the field
857
-     * @param string $fieldvalue Value to write
858
-     * @param object $criteria   {@link CriteriaElement}
859
-     *
860
-     * @param  bool  $force
861
-     * @return bool
862
-     */
863
-    public function updateAll($fieldname, $fieldvalue, $criteria = null, $force = false)
864
-    {
865
-        $set_clause = $fieldname . ' = ';
866
-        if (is_numeric($fieldvalue)) {
867
-            $set_clause .= $fieldvalue;
868
-        } elseif (is_array($fieldvalue)) {
869
-            $set_clause .= $this->db->quoteString(implode(',', $fieldvalue));
870
-        } else {
871
-            $set_clause .= $this->db->quoteString($fieldvalue);
872
-        }
873
-        $sql = 'UPDATE ' . $this->table . ' SET ' . $set_clause;
874
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
875
-            $sql .= ' ' . $criteria->renderWhere();
876
-        }
877
-        if (false != $force) {
878
-            $result = $this->db->queryF($sql);
879
-        } else {
880
-            $result = $this->db->query($sql);
881
-        }
882
-        if (!$result) {
883
-            return false;
884
-        }
885
-
886
-        return true;
887
-    }
888
-
889
-    /**
890
-     * delete all objects meeting the conditions
891
-     *
892
-     * @param  object $criteria {@link CriteriaElement} with conditions to meet
893
-     * @return bool
894
-     */
895
-
896
-    public function deleteAll($criteria = null)
897
-    {
898
-        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
899
-            $sql = 'DELETE FROM ' . $this->table;
900
-            $sql .= ' ' . $criteria->renderWhere();
901
-            if (!$this->db->query($sql)) {
902
-                return false;
903
-            }
904
-            $rows = $this->db->getAffectedRows();
905
-
906
-            return $rows > 0 ? $rows : true;
907
-        }
908
-
909
-        return false;
910
-    }
911
-
912
-    /**
913
-     * @return mixed
914
-     */
915
-    public function getModuleInfo()
916
-    {
917
-        return smart_getModuleInfo($this->_moduleName);
918
-    }
919
-
920
-    /**
921
-     * @return bool
922
-     */
923
-    public function getModuleConfig()
924
-    {
925
-        return smart_getModuleConfig($this->_moduleName);
926
-    }
927
-
928
-    /**
929
-     * @return string
930
-     */
931
-    public function getModuleItemString()
932
-    {
933
-        $ret = $this->_moduleName . '_' . $this->_itemname;
934
-
935
-        return $ret;
936
-    }
937
-
938
-    /**
939
-     * @param $object
940
-     */
941
-    public function updateCounter($object)
942
-    {
943
-        if (isset($object->vars['counter'])) {
944
-            $new_counter = $object->getVar('counter') + 1;
945
-            $sql         = 'UPDATE ' . $this->table . ' SET counter=' . $new_counter . ' WHERE ' . $this->keyName . '=' . $object->id();
946
-            $this->query($sql, null, true);
947
-        }
948
-    }
949
-
950
-    /**
951
-     * Execute the function associated with an event
952
-     * This method will check if the function is available
953
-     *
954
-     * @param string $event name of the event
955
-     * @param        $executeEventObj
956
-     * @return mixed result of the execution of the function or FALSE if the function was not executed
957
-     * @internal param object $obj $object on which is performed the event
958
-     */
959
-    public function executeEvent($event, &$executeEventObj)
960
-    {
961
-        if (!in_array($event, $this->_disabledEvents)) {
962
-            if (method_exists($this, $event)) {
963
-                $ret = $this->$event($executeEventObj);
964
-            } else {
965
-                // check to see if there is a hook for this event
966
-                if (isset($this->_eventHooks[$event])) {
967
-                    $method = $this->_eventHooks[$event];
968
-                    // check to see if the method specified by this hook exists
969
-                    if (method_exists($this, $method)) {
970
-                        $ret = $this->$method($executeEventObj);
971
-                    }
972
-                }
973
-                $ret = true;
974
-            }
975
-
976
-            return $ret;
977
-        }
978
-
979
-        return true;
980
-    }
981
-
982
-    /**
983
-     * @param  bool $withprefix
984
-     * @return string
985
-     */
986
-    public function getIdentifierName($withprefix = true)
987
-    {
988
-        if ($withprefix) {
989
-            return $this->_itemname . '.' . $this->identifierName;
990
-        } else {
991
-            return $this->identifierName;
992
-        }
993
-    }
28
+	public $_itemname;
29
+
30
+	/**
31
+	 * Name of the table use to store this {@link SmartObject}
32
+	 *
33
+	 * Note that the name of the table needs to be free of the database prefix.
34
+	 * For example "smartsection_categories"
35
+	 * @var string
36
+	 */
37
+	public $table;
38
+
39
+	/**
40
+	 * Name of the table key that uniquely identify each {@link SmartObject}
41
+	 *
42
+	 * For example: "categoryid"
43
+	 * @var string
44
+	 */
45
+	public $keyName;
46
+
47
+	/**
48
+	 * Name of the class derived from {@link SmartObject} and which this handler is handling
49
+	 *
50
+	 * Note that this string needs to be lowercase
51
+	 *
52
+	 * For example: "smartsectioncategory"
53
+	 * @var string
54
+	 */
55
+	public $className;
56
+
57
+	/**
58
+	 * Name of the field which properly identify the {@link SmartObject}
59
+	 *
60
+	 * For example: "name" (this will be the category's name)
61
+	 * @var string
62
+	 */
63
+	public $identifierName;
64
+
65
+	/**
66
+	 * Name of the field which will be use as a summary for the object
67
+	 *
68
+	 * For example: "summary"
69
+	 * @var string
70
+	 */
71
+	public $summaryName;
72
+
73
+	/**
74
+	 * Page name use to basically manage and display the {@link SmartObject}
75
+	 *
76
+	 * This page needs to be the same in user side and admin side
77
+	 *
78
+	 * For example category.php - we will deduct smartsection/category.php as well as smartsection/admin/category.php
79
+	 * @todo this could probably be automatically deducted from the class name - for example, the class SmartsectionCategory will have "category.php" as it's managing page
80
+	 * @var string
81
+	 */
82
+	public $_page;
83
+
84
+	/**
85
+	 * Full path of the module using this {@link SmartObject}
86
+	 *
87
+	 * <code>XOOPS_URL . "/modules/smartsection/"</code>
88
+	 * @todo this could probably be automatically deducted from the class name as it is always prefixed with the module name
89
+	 * @var string
90
+	 */
91
+	public $_modulePath;
92
+
93
+	public $_moduleUrl;
94
+
95
+	public $_moduleName;
96
+
97
+	public $_uploadUrl;
98
+
99
+	public $_uploadPath;
100
+
101
+	public $_allowedMimeTypes = 0;
102
+
103
+	public $_maxFileSize = 1000000;
104
+
105
+	public $_maxWidth = 500;
106
+
107
+	public $_maxHeight = 500;
108
+
109
+	public $highlightFields = array();
110
+
111
+	/**
112
+	 * Array containing the events name and functions
113
+	 *
114
+	 * @var array
115
+	 */
116
+	public $eventArray = array();
117
+
118
+	/**
119
+	 * Array containing the permissions that this handler will manage on the objects
120
+	 *
121
+	 * @var array
122
+	 */
123
+	public $permissionsArray = false;
124
+
125
+	public $generalSQL = false;
126
+
127
+	public $_eventHooks     = array();
128
+	public $_disabledEvents = array();
129
+
130
+	/**
131
+	 * Constructor - called from child classes
132
+	 *
133
+	 * @param object|XoopsDatabase $db           {@link XoopsDatabase}
134
+	 *                                           object
135
+	 * @param                      $itemname
136
+	 * @param string               $keyname      Name of the table key that uniquely identify each {@link SmartObject}
137
+	 * @param string               $idenfierName Name of the field which properly identify the {@link SmartObject}
138
+	 * @param                      $summaryName
139
+	 * @param                      $modulename
140
+	 * @internal param string $tablename Name of the table use to store this <a href='psi_element://SmartObject'>SmartObject</a>
141
+	 * @internal param Name $string of the class derived from <a href='psi_element://SmartObject'>SmartObject</a> and which this handler is handling and which this handler is handling
142
+	 * @internal param string $page Page name use to basically manage and display the <a href='psi_element://SmartObject'>SmartObject</a>
143
+	 * @internal param string $moduleName name of the module
144
+	 */
145
+	public function __construct(XoopsDatabase $db, $itemname, $keyname, $idenfierName, $summaryName, $modulename)
146
+	{
147
+		parent::__construct($db);
148
+
149
+		$this->_itemname      = $itemname;
150
+		$this->_moduleName    = $modulename;
151
+		$this->table          = $db->prefix($modulename . '_' . $itemname);
152
+		$this->keyName        = $keyname;
153
+		$this->className      = ucfirst($modulename) . ucfirst($itemname);
154
+		$this->identifierName = $idenfierName;
155
+		$this->summaryName    = $summaryName;
156
+		$this->_page          = $itemname . '.php';
157
+		$this->_modulePath    = XOOPS_ROOT_PATH . '/modules/' . $this->_moduleName . '/';
158
+		$this->_moduleUrl     = XOOPS_URL . '/modules/' . $this->_moduleName . '/';
159
+		$this->_uploadPath    = XOOPS_UPLOAD_PATH . '/' . $this->_moduleName . '/';
160
+		$this->_uploadUrl     = XOOPS_UPLOAD_URL . '/' . $this->_moduleName . '/';
161
+	}
162
+
163
+	/**
164
+	 * @param $event
165
+	 * @param $method
166
+	 */
167
+	public function addEventHook($event, $method)
168
+	{
169
+		$this->_eventHooks[$event] = $method;
170
+	}
171
+
172
+	/**
173
+	 * Add a permission that this handler will manage for its objects
174
+	 *
175
+	 * Example: $this->addPermission('view', _AM_SSHOP_CAT_PERM_READ, _AM_SSHOP_CAT_PERM_READ_DSC);
176
+	 *
177
+	 * @param string      $perm_name   name of the permission
178
+	 * @param string      $caption     caption of the control that will be displayed in the form
179
+	 * @param bool|string $description description of the control that will be displayed in the form
180
+	 */
181
+	public function addPermission($perm_name, $caption, $description = false)
182
+	{
183
+		include_once(SMARTOBJECT_ROOT_PATH . 'class/smartobjectpermission.php');
184
+
185
+		$this->permissionsArray[] = array(
186
+			'perm_name'   => $perm_name,
187
+			'caption'     => $caption,
188
+			'description' => $description
189
+		);
190
+	}
191
+
192
+	/**
193
+	 * @param $criteria
194
+	 * @param $perm_name
195
+	 * @return bool
196
+	 */
197
+	public function setGrantedObjectsCriteria(&$criteria, $perm_name)
198
+	{
199
+		$smartPermissionsHandler = new SmartobjectPermissionHandler($this);
200
+		$grantedItems             = $smartPermissionsHandler->getGrantedItems($perm_name);
201
+		if (count($grantedItems) > 0) {
202
+			$criteria->add(new Criteria($this->keyName, '(' . implode(', ', $grantedItems) . ')', 'IN'));
203
+
204
+			return true;
205
+		} else {
206
+			return false;
207
+		}
208
+	}
209
+
210
+	/**
211
+	 * @param bool $_uploadPath
212
+	 * @param bool $_allowedMimeTypes
213
+	 * @param bool $_maxFileSize
214
+	 * @param bool $_maxWidth
215
+	 * @param bool $_maxHeight
216
+	 */
217
+	public function setUploaderConfig($_uploadPath = false, $_allowedMimeTypes = false, $_maxFileSize = false, $_maxWidth = false, $_maxHeight = false)
218
+	{
219
+		$this->_uploadPath       = $_uploadPath ?: $this->_uploadPath;
220
+		$this->_allowedMimeTypes = $_allowedMimeTypes ?: $this->_allowedMimeTypes;
221
+		$this->_maxFileSize      = $_maxFileSize ?: $this->_maxFileSize;
222
+		$this->_maxWidth         = $_maxWidth ?: $this->_maxWidth;
223
+		$this->_maxHeight        = $_maxHeight ?: $this->_maxHeight;
224
+	}
225
+
226
+	/**
227
+	 * create a new {@link SmartObject}
228
+	 *
229
+	 * @param bool $isNew Flag the new objects as "new"?
230
+	 *
231
+	 * @return object {@link SmartObject}
232
+	 */
233
+	public function &create($isNew = true)
234
+	{
235
+		$obj = new $this->className($this);
236
+		$obj->setImageDir($this->getImageUrl(), $this->getImagePath());
237
+		if (!$obj->handler) {
238
+			$obj->handler =& $this;
239
+		}
240
+
241
+		if ($isNew === true) {
242
+			$obj->setNew();
243
+		}
244
+
245
+		return $obj;
246
+	}
247
+
248
+	/**
249
+	 * @return string
250
+	 */
251
+	public function getImageUrl()
252
+	{
253
+		return $this->_uploadUrl . $this->_itemname . '/';
254
+	}
255
+
256
+	/**
257
+	 * @return string
258
+	 */
259
+	public function getImagePath()
260
+	{
261
+		$dir = $this->_uploadPath . $this->_itemname;
262
+		if (!file_exists($dir)) {
263
+			smart_admin_mkdir($dir);
264
+		}
265
+
266
+		return $dir . '/';
267
+	}
268
+
269
+	/**
270
+	 * retrieve a {@link SmartObject}
271
+	 *
272
+	 * @param  mixed $id        ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
273
+	 * @param  bool  $as_object whether to return an object or an array
274
+	 * @param  bool  $debug
275
+	 * @param  bool  $criteria
276
+	 * @return mixed reference to the <a href='psi_element://SmartObject'>SmartObject</a>, FALSE if failed
277
+	 *                          FALSE if failed
278
+	 */
279
+	public function get($id, $as_object = true, $debug = false, $criteria = false)
280
+	{
281
+		if (!$criteria) {
282
+			$criteria = new CriteriaCompo();
283
+		}
284
+		if (is_array($this->keyName)) {
285
+			for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
286
+				/**
287
+				 * In some situations, the $id is not an INTEGER. SmartObjectTag is an example.
288
+				 * Is the fact that we removed the (int)() represents a security risk ?
289
+				 */
290
+				//$criteria->add(new Criteria($this->keyName[$i], ($id[$i]), '=', $this->_itemname));
291
+				$criteria->add(new Criteria($this->keyName[$i], $id[$i], '=', $this->_itemname));
292
+			}
293
+		} else {
294
+			//$criteria = new Criteria($this->keyName, (int)($id), '=', $this->_itemname);
295
+			/**
296
+			 * In some situations, the $id is not an INTEGER. SmartObjectTag is an example.
297
+			 * Is the fact that we removed the (int)() represents a security risk ?
298
+			 */
299
+			$criteria->add(new Criteria($this->keyName, $id, '=', $this->_itemname));
300
+		}
301
+		$criteria->setLimit(1);
302
+		if ($debug) {
303
+			$obj_array = $this->getObjectsD($criteria, false, $as_object);
304
+		} else {
305
+			$obj_array = $this->getObjects($criteria, false, $as_object);
306
+			//patch: weird bug of indexing by id even if id_as_key = false;
307
+			if (!isset($obj_array[0]) && is_object($obj_array[$id])) {
308
+				$obj_array[0] = $obj_array[$id];
309
+				unset($obj_array[$id]);
310
+				$obj_array[0]->unsetNew();
311
+			}
312
+		}
313
+
314
+		if (count($obj_array) != 1) {
315
+			$obj =& $this->create();
316
+
317
+			return $obj;
318
+		}
319
+
320
+		return $obj_array[0];
321
+	}
322
+
323
+	/**
324
+	 * retrieve a {@link SmartObject}
325
+	 *
326
+	 * @param  mixed $id        ID of the object - or array of ids for joint keys. Joint keys MUST be given in the same order as in the constructor
327
+	 * @param  bool  $as_object whether to return an object or an array
328
+	 * @return mixed reference to the {@link SmartObject}, FALSE if failed
329
+	 */
330
+	public function &getD($id, $as_object = true)
331
+	{
332
+		return $this->get($id, $as_object, true);
333
+	}
334
+
335
+	/**
336
+	 * retrieve objects from the database
337
+	 *
338
+	 * @param object $criteria  {@link CriteriaElement} conditions to be met
339
+	 * @param bool   $id_as_key use the ID as key for the array?
340
+	 * @param bool   $as_object return an array of objects?
341
+	 *
342
+	 * @param  bool  $sql
343
+	 * @param  bool  $debug
344
+	 * @return array
345
+	 */
346
+	public function getObjects($criteria = null, $id_as_key = false, $as_object = true, $sql = false, $debug = false)
347
+	{
348
+		$ret   = array();
349
+		$limit = $start = 0;
350
+
351
+		if ($this->generalSQL) {
352
+			$sql = $this->generalSQL;
353
+		} elseif (!$sql) {
354
+			$sql = 'SELECT * FROM ' . $this->table . ' AS ' . $this->_itemname;
355
+		}
356
+
357
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
358
+			$sql .= ' ' . $criteria->renderWhere();
359
+			if ($criteria->getSort() != '') {
360
+				$sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
361
+			}
362
+			$limit = $criteria->getLimit();
363
+			$start = $criteria->getStart();
364
+		}
365
+		if ($debug) {
366
+			xoops_debug($sql);
367
+		}
368
+
369
+		$result = $this->db->query($sql, $limit, $start);
370
+		if (!$result) {
371
+			return $ret;
372
+		}
373
+
374
+		return $this->convertResultSet($result, $id_as_key, $as_object);
375
+	}
376
+
377
+	/**
378
+	 * @param       $sql
379
+	 * @param       $criteria
380
+	 * @param  bool $force
381
+	 * @param  bool $debug
382
+	 * @return array
383
+	 */
384
+	public function query($sql, $criteria, $force = false, $debug = false)
385
+	{
386
+		$ret = array();
387
+
388
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
389
+			$sql .= ' ' . $criteria->renderWhere();
390
+			if ($criteria->groupby) {
391
+				$sql .= $criteria->getGroupby();
392
+			}
393
+			if ($criteria->getSort() != '') {
394
+				$sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
395
+			}
396
+		}
397
+		if ($debug) {
398
+			xoops_debug($sql);
399
+		}
400
+
401
+		if ($force) {
402
+			$result = $this->db->queryF($sql);
403
+		} else {
404
+			$result = $this->db->query($sql);
405
+		}
406
+
407
+		if (!$result) {
408
+			return $ret;
409
+		}
410
+
411
+		while ($myrow = $this->db->fetchArray($result)) {
412
+			$ret[] = $myrow;
413
+		}
414
+
415
+		return $ret;
416
+	}
417
+
418
+	/**
419
+	 * retrieve objects with debug mode - so will show the query
420
+	 *
421
+	 * @param object $criteria  {@link CriteriaElement} conditions to be met
422
+	 * @param bool   $id_as_key use the ID as key for the array?
423
+	 * @param bool   $as_object return an array of objects?
424
+	 *
425
+	 * @param  bool  $sql
426
+	 * @return array
427
+	 */
428
+	public function getObjectsD($criteria = null, $id_as_key = false, $as_object = true, $sql = false)
429
+	{
430
+		return $this->getObjects($criteria, $id_as_key, $as_object, $sql, true);
431
+	}
432
+
433
+	/**
434
+	 * @param $arrayObjects
435
+	 * @return array|bool
436
+	 */
437
+	public function getObjectsAsArray($arrayObjects)
438
+	{
439
+		$ret = array();
440
+		foreach ($arrayObjects as $key => $object) {
441
+			$ret[$key] = $object->toArray();
442
+		}
443
+		if (count($ret > 0)) {
444
+			return $ret;
445
+		} else {
446
+			return false;
447
+		}
448
+	}
449
+
450
+	/**
451
+	 * Convert a database resultset to a returnable array
452
+	 *
453
+	 * @param object $result    database resultset
454
+	 * @param bool   $id_as_key - should NOT be used with joint keys
455
+	 * @param bool   $as_object
456
+	 *
457
+	 * @return array
458
+	 */
459
+	public function convertResultSet($result, $id_as_key = false, $as_object = true)
460
+	{
461
+		$ret = array();
462
+		while ($myrow = $this->db->fetchArray($result)) {
463
+			$obj =& $this->create(false);
464
+			$obj->assignVars($myrow);
465
+			if (!$id_as_key) {
466
+				if ($as_object) {
467
+					$ret[] =& $obj;
468
+				} else {
469
+					$ret[] = $obj->toArray();
470
+				}
471
+			} else {
472
+				if ($as_object) {
473
+					$value =& $obj;
474
+				} else {
475
+					$value = $obj->toArray();
476
+				}
477
+				if ($id_as_key === 'parentid') {
478
+					$ret[$obj->getVar('parentid', 'e')][$obj->getVar($this->keyName)] =& $value;
479
+				} else {
480
+					$ret[$obj->getVar($this->keyName)] = $value;
481
+				}
482
+			}
483
+			unset($obj);
484
+		}
485
+
486
+		return $ret;
487
+	}
488
+
489
+	/**
490
+	 * @param  null $criteria
491
+	 * @param  int  $limit
492
+	 * @param  int  $start
493
+	 * @return array
494
+	 */
495
+	public function getListD($criteria = null, $limit = 0, $start = 0)
496
+	{
497
+		return $this->getList($criteria, $limit, $start, true);
498
+	}
499
+
500
+	/**
501
+	 * Retrieve a list of objects as arrays - DON'T USE WITH JOINT KEYS
502
+	 *
503
+	 * @param object $criteria {@link CriteriaElement} conditions to be met
504
+	 * @param int    $limit    Max number of objects to fetch
505
+	 * @param int    $start    Which record to start at
506
+	 *
507
+	 * @param  bool  $debug
508
+	 * @return array
509
+	 */
510
+	public function getList($criteria = null, $limit = 0, $start = 0, $debug = false)
511
+	{
512
+		$ret = array();
513
+		if ($criteria == null) {
514
+			$criteria = new CriteriaCompo();
515
+		}
516
+
517
+		if ($criteria->getSort() == '') {
518
+			$criteria->setSort($this->getIdentifierName());
519
+		}
520
+
521
+		$sql = 'SELECT ' . (is_array($this->keyName) ? implode(', ', $this->keyName) : $this->keyName);
522
+		if (!empty($this->identifierName)) {
523
+			$sql .= ', ' . $this->getIdentifierName();
524
+		}
525
+		$sql .= ' FROM ' . $this->table . ' AS ' . $this->_itemname;
526
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
527
+			$sql .= ' ' . $criteria->renderWhere();
528
+			if ($criteria->getSort() != '') {
529
+				$sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
530
+			}
531
+			$limit = $criteria->getLimit();
532
+			$start = $criteria->getStart();
533
+		}
534
+
535
+		if ($debug) {
536
+			xoops_debug($sql);
537
+		}
538
+
539
+		$result = $this->db->query($sql, $limit, $start);
540
+		if (!$result) {
541
+			return $ret;
542
+		}
543
+
544
+		$myts = MyTextSanitizer::getInstance();
545
+		while ($myrow = $this->db->fetchArray($result)) {
546
+			//identifiers should be textboxes, so sanitize them like that
547
+			$ret[$myrow[$this->keyName]] = empty($this->identifierName) ? 1 : $myts->displayTarea($myrow[$this->identifierName]);
548
+		}
549
+
550
+		return $ret;
551
+	}
552
+
553
+	/**
554
+	 * count objects matching a condition
555
+	 *
556
+	 * @param  object $criteria {@link CriteriaElement} to match
557
+	 * @return int    count of objects
558
+	 */
559
+	public function getCount($criteria = null)
560
+	{
561
+		$field   = '';
562
+		$groupby = false;
563
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
564
+			if ($criteria->groupby != '') {
565
+				$groupby = true;
566
+				$field   = $criteria->groupby . ', '; //Not entirely secure unless you KNOW that no criteria's groupby clause is going to be mis-used
567
+			}
568
+		}
569
+		/**
570
+		 * if we have a generalSQL, lets used this one.
571
+		 * This needs to be improved...
572
+		 */
573
+		if ($this->generalSQL) {
574
+			$sql = $this->generalSQL;
575
+			$sql = str_replace('SELECT *', 'SELECT COUNT(*)', $sql);
576
+		} else {
577
+			$sql = 'SELECT ' . $field . 'COUNT(*) FROM ' . $this->table . ' AS ' . $this->_itemname;
578
+		}
579
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
580
+			$sql .= ' ' . $criteria->renderWhere();
581
+			if ($criteria->groupby != '') {
582
+				$sql .= $criteria->getGroupby();
583
+			}
584
+		}
585
+
586
+		$result = $this->db->query($sql);
587
+		if (!$result) {
588
+			return 0;
589
+		}
590
+		if ($groupby == false) {
591
+			list($count) = $this->db->fetchRow($result);
592
+
593
+			return $count;
594
+		} else {
595
+			$ret = array();
596
+			while (list($id, $count) = $this->db->fetchRow($result)) {
597
+				$ret[$id] = $count;
598
+			}
599
+
600
+			return $ret;
601
+		}
602
+	}
603
+
604
+	/**
605
+	 * delete an object from the database
606
+	 *
607
+	 * @param  XoopsObject $obj reference to the object to delete
608
+	 * @param  bool        $force
609
+	 * @return bool        FALSE if failed.
610
+	 */
611
+	public function delete(XoopsObject $obj, $force = false)
612
+	{
613
+		$eventResult = $this->executeEvent('beforeDelete', $obj);
614
+		if (!$eventResult) {
615
+			$obj->setErrors('An error occured during the BeforeDelete event');
616
+
617
+			return false;
618
+		}
619
+
620
+		if (is_array($this->keyName)) {
621
+			$clause = array();
622
+			for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
623
+				$clause[] = $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
624
+			}
625
+			$whereclause = implode(' AND ', $clause);
626
+		} else {
627
+			$whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
628
+		}
629
+		$sql = 'DELETE FROM ' . $this->table . ' WHERE ' . $whereclause;
630
+		if (false != $force) {
631
+			$result = $this->db->queryF($sql);
632
+		} else {
633
+			$result = $this->db->query($sql);
634
+		}
635
+		if (!$result) {
636
+			return false;
637
+		}
638
+
639
+		$eventResult = $this->executeEvent('afterDelete', $obj);
640
+		if (!$eventResult) {
641
+			$obj->setErrors('An error occured during the AfterDelete event');
642
+
643
+			return false;
644
+		}
645
+
646
+		return true;
647
+	}
648
+
649
+	/**
650
+	 * @param $event
651
+	 */
652
+	public function disableEvent($event)
653
+	{
654
+		if (is_array($event)) {
655
+			foreach ($event as $v) {
656
+				$this->_disabledEvents[] = $v;
657
+			}
658
+		} else {
659
+			$this->_disabledEvents[] = $event;
660
+		}
661
+	}
662
+
663
+	/**
664
+	 * @return array
665
+	 */
666
+	public function getPermissions()
667
+	{
668
+		return $this->permissionsArray;
669
+	}
670
+
671
+	/**
672
+	 * insert a new object in the database
673
+	 *
674
+	 * @param  XoopsObject $obj         reference to the object
675
+	 * @param  bool        $force       whether to force the query execution despite security settings
676
+	 * @param  bool        $checkObject check if the object is dirty and clean the attributes
677
+	 * @param  bool        $debug
678
+	 * @return bool        FALSE if failed, TRUE if already present and unchanged or successful
679
+	 */
680
+	public function insert(XoopsObject $obj, $force = false, $checkObject = true, $debug = false)
681
+	{
682
+		if ($checkObject != false) {
683
+			if (!is_object($obj)) {
684
+				return false;
685
+			}
686
+			/**
687
+			 * @TODO: Change to if (!(class_exists($this->className) && $obj instanceof $this->className)) when going fully PHP5
688
+			 */
689
+			if (!is_a($obj, $this->className)) {
690
+				$obj->setError(get_class($obj) . ' Differs from ' . $this->className);
691
+
692
+				return false;
693
+			}
694
+			if (!$obj->isDirty()) {
695
+				$obj->setErrors('Not dirty'); //will usually not be outputted as errors are not displayed when the method returns true, but it can be helpful when troubleshooting code - Mith
696
+
697
+				return true;
698
+			}
699
+		}
700
+
701
+		if ($obj->seoEnabled) {
702
+			// Auto create meta tags if empty
703
+			$smartobjectMetagen = new SmartMetagen($obj->title(), $obj->getVar('meta_keywords'), $obj->summary());
704
+
705
+			if (!$obj->getVar('meta_keywords') || !$obj->getVar('meta_description')) {
706
+				if (!$obj->meta_keywords()) {
707
+					$obj->setVar('meta_keywords', $smartobjectMetagen->_keywords);
708
+				}
709
+
710
+				if (!$obj->meta_description()) {
711
+					$obj->setVar('meta_description', $smartobjectMetagen->_meta_description);
712
+				}
713
+			}
714
+
715
+			// Auto create short_url if empty
716
+			if (!$obj->short_url()) {
717
+				$obj->setVar('short_url', $smartobjectMetagen->generateSeoTitle($obj->title('n'), false));
718
+			}
719
+		}
720
+
721
+		$eventResult = $this->executeEvent('beforeSave', $obj);
722
+		if (!$eventResult) {
723
+			$obj->setErrors('An error occured during the BeforeSave event');
724
+
725
+			return false;
726
+		}
727
+
728
+		if ($obj->isNew()) {
729
+			$eventResult = $this->executeEvent('beforeInsert', $obj);
730
+			if (!$eventResult) {
731
+				$obj->setErrors('An error occured during the BeforeInsert event');
732
+
733
+				return false;
734
+			}
735
+		} else {
736
+			$eventResult = $this->executeEvent('beforeUpdate', $obj);
737
+			if (!$eventResult) {
738
+				$obj->setErrors('An error occured during the BeforeUpdate event');
739
+
740
+				return false;
741
+			}
742
+		}
743
+		if (!$obj->cleanVars()) {
744
+			$obj->setErrors('Variables were not cleaned properly.');
745
+
746
+			return false;
747
+		}
748
+		$fieldsToStoreInDB = array();
749
+		foreach ($obj->cleanVars as $k => $v) {
750
+			if ($obj->vars[$k]['data_type'] == XOBJ_DTYPE_INT) {
751
+				$cleanvars[$k] = (int)$v;
752
+			} elseif (is_array($v)) {
753
+				$cleanvars[$k] = $this->db->quoteString(implode(',', $v));
754
+			} else {
755
+				$cleanvars[$k] = $this->db->quoteString($v);
756
+			}
757
+			if ($obj->vars[$k]['persistent']) {
758
+				$fieldsToStoreInDB[$k] = $cleanvars[$k];
759
+			}
760
+		}
761
+		if ($obj->isNew()) {
762
+			if (!is_array($this->keyName)) {
763
+				if ($cleanvars[$this->keyName] < 1) {
764
+					$cleanvars[$this->keyName] = $this->db->genId($this->table . '_' . $this->keyName . '_seq');
765
+				}
766
+			}
767
+
768
+			$sql = 'INSERT INTO ' . $this->table . ' (' . implode(',', array_keys($fieldsToStoreInDB)) . ') VALUES (' . implode(',', array_values($fieldsToStoreInDB)) . ')';
769
+		} else {
770
+			$sql = 'UPDATE ' . $this->table . ' SET';
771
+			foreach ($fieldsToStoreInDB as $key => $value) {
772
+				if ((!is_array($this->keyName) && $key == $this->keyName) || (is_array($this->keyName) && in_array($key, $this->keyName))) {
773
+					continue;
774
+				}
775
+				if (isset($notfirst)) {
776
+					$sql .= ',';
777
+				}
778
+				$sql .= ' ' . $key . ' = ' . $value;
779
+				$notfirst = true;
780
+			}
781
+			if (is_array($this->keyName)) {
782
+				$whereclause = '';
783
+				for ($i = 0, $iMax = count($this->keyName); $i < $iMax; ++$i) {
784
+					if ($i > 0) {
785
+						$whereclause .= ' AND ';
786
+					}
787
+					$whereclause .= $this->keyName[$i] . ' = ' . $obj->getVar($this->keyName[$i]);
788
+				}
789
+			} else {
790
+				$whereclause = $this->keyName . ' = ' . $obj->getVar($this->keyName);
791
+			}
792
+			$sql .= ' WHERE ' . $whereclause;
793
+		}
794
+
795
+		if ($debug) {
796
+			xoops_debug($sql);
797
+		}
798
+
799
+		if (false != $force) {
800
+			$result = $this->db->queryF($sql);
801
+		} else {
802
+			$result = $this->db->query($sql);
803
+		}
804
+
805
+		if (!$result) {
806
+			$obj->setErrors($this->db->error());
807
+
808
+			return false;
809
+		}
810
+
811
+		if ($obj->isNew() && !is_array($this->keyName)) {
812
+			$obj->assignVar($this->keyName, $this->db->getInsertId());
813
+		}
814
+		$eventResult = $this->executeEvent('afterSave', $obj);
815
+		if (!$eventResult) {
816
+			$obj->setErrors('An error occured during the AfterSave event');
817
+
818
+			return false;
819
+		}
820
+
821
+		if ($obj->isNew()) {
822
+			$obj->unsetNew();
823
+			$eventResult = $this->executeEvent('afterInsert', $obj);
824
+			if (!$eventResult) {
825
+				$obj->setErrors('An error occured during the AfterInsert event');
826
+
827
+				return false;
828
+			}
829
+		} else {
830
+			$eventResult = $this->executeEvent('afterUpdate', $obj);
831
+			if (!$eventResult) {
832
+				$obj->setErrors('An error occured during the AfterUpdate event');
833
+
834
+				return false;
835
+			}
836
+		}
837
+
838
+		return true;
839
+	}
840
+
841
+	/**
842
+	 * @param       $obj
843
+	 * @param  bool $force
844
+	 * @param  bool $checkObject
845
+	 * @param  bool $debug
846
+	 * @return bool
847
+	 */
848
+	public function insertD(&$obj, $force = false, $checkObject = true, $debug = false)
849
+	{
850
+		return $this->insert($obj, $force, $checkObject, true);
851
+	}
852
+
853
+	/**
854
+	 * Change a value for objects with a certain criteria
855
+	 *
856
+	 * @param string $fieldname  Name of the field
857
+	 * @param string $fieldvalue Value to write
858
+	 * @param object $criteria   {@link CriteriaElement}
859
+	 *
860
+	 * @param  bool  $force
861
+	 * @return bool
862
+	 */
863
+	public function updateAll($fieldname, $fieldvalue, $criteria = null, $force = false)
864
+	{
865
+		$set_clause = $fieldname . ' = ';
866
+		if (is_numeric($fieldvalue)) {
867
+			$set_clause .= $fieldvalue;
868
+		} elseif (is_array($fieldvalue)) {
869
+			$set_clause .= $this->db->quoteString(implode(',', $fieldvalue));
870
+		} else {
871
+			$set_clause .= $this->db->quoteString($fieldvalue);
872
+		}
873
+		$sql = 'UPDATE ' . $this->table . ' SET ' . $set_clause;
874
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
875
+			$sql .= ' ' . $criteria->renderWhere();
876
+		}
877
+		if (false != $force) {
878
+			$result = $this->db->queryF($sql);
879
+		} else {
880
+			$result = $this->db->query($sql);
881
+		}
882
+		if (!$result) {
883
+			return false;
884
+		}
885
+
886
+		return true;
887
+	}
888
+
889
+	/**
890
+	 * delete all objects meeting the conditions
891
+	 *
892
+	 * @param  object $criteria {@link CriteriaElement} with conditions to meet
893
+	 * @return bool
894
+	 */
895
+
896
+	public function deleteAll($criteria = null)
897
+	{
898
+		if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
899
+			$sql = 'DELETE FROM ' . $this->table;
900
+			$sql .= ' ' . $criteria->renderWhere();
901
+			if (!$this->db->query($sql)) {
902
+				return false;
903
+			}
904
+			$rows = $this->db->getAffectedRows();
905
+
906
+			return $rows > 0 ? $rows : true;
907
+		}
908
+
909
+		return false;
910
+	}
911
+
912
+	/**
913
+	 * @return mixed
914
+	 */
915
+	public function getModuleInfo()
916
+	{
917
+		return smart_getModuleInfo($this->_moduleName);
918
+	}
919
+
920
+	/**
921
+	 * @return bool
922
+	 */
923
+	public function getModuleConfig()
924
+	{
925
+		return smart_getModuleConfig($this->_moduleName);
926
+	}
927
+
928
+	/**
929
+	 * @return string
930
+	 */
931
+	public function getModuleItemString()
932
+	{
933
+		$ret = $this->_moduleName . '_' . $this->_itemname;
934
+
935
+		return $ret;
936
+	}
937
+
938
+	/**
939
+	 * @param $object
940
+	 */
941
+	public function updateCounter($object)
942
+	{
943
+		if (isset($object->vars['counter'])) {
944
+			$new_counter = $object->getVar('counter') + 1;
945
+			$sql         = 'UPDATE ' . $this->table . ' SET counter=' . $new_counter . ' WHERE ' . $this->keyName . '=' . $object->id();
946
+			$this->query($sql, null, true);
947
+		}
948
+	}
949
+
950
+	/**
951
+	 * Execute the function associated with an event
952
+	 * This method will check if the function is available
953
+	 *
954
+	 * @param string $event name of the event
955
+	 * @param        $executeEventObj
956
+	 * @return mixed result of the execution of the function or FALSE if the function was not executed
957
+	 * @internal param object $obj $object on which is performed the event
958
+	 */
959
+	public function executeEvent($event, &$executeEventObj)
960
+	{
961
+		if (!in_array($event, $this->_disabledEvents)) {
962
+			if (method_exists($this, $event)) {
963
+				$ret = $this->$event($executeEventObj);
964
+			} else {
965
+				// check to see if there is a hook for this event
966
+				if (isset($this->_eventHooks[$event])) {
967
+					$method = $this->_eventHooks[$event];
968
+					// check to see if the method specified by this hook exists
969
+					if (method_exists($this, $method)) {
970
+						$ret = $this->$method($executeEventObj);
971
+					}
972
+				}
973
+				$ret = true;
974
+			}
975
+
976
+			return $ret;
977
+		}
978
+
979
+		return true;
980
+	}
981
+
982
+	/**
983
+	 * @param  bool $withprefix
984
+	 * @return string
985
+	 */
986
+	public function getIdentifierName($withprefix = true)
987
+	{
988
+		if ($withprefix) {
989
+			return $this->_itemname . '.' . $this->identifierName;
990
+		} else {
991
+			return $this->identifierName;
992
+		}
993
+	}
994 994
 }
Please login to merge, or discard this patch.
class/rating.php 1 patch
Indentation   +208 added lines, -208 removed lines patch added patch discarded remove patch
@@ -37,125 +37,125 @@  discard block
 block discarded – undo
37 37
  */
38 38
 class SmartobjectRating extends SmartObject
39 39
 {
40
-    public $_modulePlugin = false;
41
-
42
-    /**
43
-     * SmartobjectRating constructor.
44
-     */
45
-    public function __construct()
46
-    {
47
-        $this->quickInitVar('ratingid', XOBJ_DTYPE_INT, true);
48
-        $this->quickInitVar('dirname', XOBJ_DTYPE_TXTBOX, true, _CO_SOBJECT_RATING_DIRNAME);
49
-        $this->quickInitVar('item', XOBJ_DTYPE_TXTBOX, true, _CO_SOBJECT_RATING_ITEM);
50
-        $this->quickInitVar('itemid', XOBJ_DTYPE_INT, true, _CO_SOBJECT_RATING_ITEMID);
51
-        $this->quickInitVar('uid', XOBJ_DTYPE_INT, true, _CO_SOBJECT_RATING_UID);
52
-        $this->quickInitVar('date', XOBJ_DTYPE_LTIME, true, _CO_SOBJECT_RATING_DATE);
53
-        $this->quickInitVar('rate', XOBJ_DTYPE_INT, true, _CO_SOBJECT_RATING_RATE);
54
-
55
-        $this->initNonPersistableVar('name', XOBJ_DTYPE_TXTBOX, 'user', _CO_SOBJECT_RATING_NAME);
56
-
57
-        $this->setControl('dirname', array(
58
-            'handler'  => 'rating',
59
-            'method'   => 'getModuleList',
60
-            'onSelect' => 'submit'
61
-        ));
62
-
63
-        $this->setControl('item', array(
64
-            'object' => &$this,
65
-            'method' => 'getItemList'
66
-        ));
67
-
68
-        $this->setControl('uid', 'user');
69
-
70
-        $this->setControl('rate', array(
71
-            'handler' => 'rating',
72
-            'method'  => 'getRateList'
73
-        ));
74
-    }
75
-
76
-    /**
77
-     * @param  string $key
78
-     * @param  string $format
79
-     * @return mixed
80
-     */
81
-    public function getVar($key, $format = 's')
82
-    {
83
-        if ($format === 's' && in_array($key, array('name', 'dirname'))) {
84
-            //            return call_user_func(array($this, $key));
85
-            return $this->{$key}();
86
-        }
87
-
88
-        return parent::getVar($key, $format);
89
-    }
90
-
91
-    /**
92
-     * @return string
93
-     */
94
-    public function name()
95
-    {
96
-        $ret = smart_getLinkedUnameFromId($this->getVar('uid', 'e'), true, array());
97
-
98
-        return $ret;
99
-    }
100
-
101
-    /**
102
-     * @return mixed
103
-     */
104
-    public function dirname()
105
-    {
106
-        global $smartobjectRatingHandler;
107
-        $moduleArray = $smartobjectRatingHandler->getModuleList();
108
-
109
-        return $moduleArray[$this->getVar('dirname', 'n')];
110
-    }
111
-
112
-    /**
113
-     * @return mixed
114
-     */
115
-    public function getItemList()
116
-    {
117
-        $plugin = $this->getModulePlugin();
118
-
119
-        return $plugin->getItemList();
120
-    }
121
-
122
-    /**
123
-     * @return string
124
-     */
125
-    public function getItemValue()
126
-    {
127
-        $moduleUrl      = XOOPS_URL . '/modules/' . $this->getVar('dirname', 'n') . '/';
128
-        $plugin         = $this->getModulePlugin();
129
-        $pluginItemInfo = $plugin->getItemInfo($this->getVar('item'));
130
-        if (!$pluginItemInfo) {
131
-            return '';
132
-        }
133
-        $itemPath = sprintf($pluginItemInfo['url'], $this->getVar('itemid'));
134
-        $ret      = '<a href="' . $moduleUrl . $itemPath . '">' . $pluginItemInfo['caption'] . '</a>';
135
-
136
-        return $ret;
137
-    }
138
-
139
-    /**
140
-     * @return mixed
141
-     */
142
-    public function getRateValue()
143
-    {
144
-        return $this->getVar('rate');
145
-    }
146
-
147
-    /**
148
-     * @return bool
149
-     */
150
-    public function getModulePlugin()
151
-    {
152
-        if (!$this->_modulePlugin) {
153
-            global $smartobjectRatingHandler;
154
-            $this->_modulePlugin = $smartobjectRatingHandler->pluginsObject->getPlugin($this->getVar('dirname', 'n'));
155
-        }
156
-
157
-        return $this->_modulePlugin;
158
-    }
40
+	public $_modulePlugin = false;
41
+
42
+	/**
43
+	 * SmartobjectRating constructor.
44
+	 */
45
+	public function __construct()
46
+	{
47
+		$this->quickInitVar('ratingid', XOBJ_DTYPE_INT, true);
48
+		$this->quickInitVar('dirname', XOBJ_DTYPE_TXTBOX, true, _CO_SOBJECT_RATING_DIRNAME);
49
+		$this->quickInitVar('item', XOBJ_DTYPE_TXTBOX, true, _CO_SOBJECT_RATING_ITEM);
50
+		$this->quickInitVar('itemid', XOBJ_DTYPE_INT, true, _CO_SOBJECT_RATING_ITEMID);
51
+		$this->quickInitVar('uid', XOBJ_DTYPE_INT, true, _CO_SOBJECT_RATING_UID);
52
+		$this->quickInitVar('date', XOBJ_DTYPE_LTIME, true, _CO_SOBJECT_RATING_DATE);
53
+		$this->quickInitVar('rate', XOBJ_DTYPE_INT, true, _CO_SOBJECT_RATING_RATE);
54
+
55
+		$this->initNonPersistableVar('name', XOBJ_DTYPE_TXTBOX, 'user', _CO_SOBJECT_RATING_NAME);
56
+
57
+		$this->setControl('dirname', array(
58
+			'handler'  => 'rating',
59
+			'method'   => 'getModuleList',
60
+			'onSelect' => 'submit'
61
+		));
62
+
63
+		$this->setControl('item', array(
64
+			'object' => &$this,
65
+			'method' => 'getItemList'
66
+		));
67
+
68
+		$this->setControl('uid', 'user');
69
+
70
+		$this->setControl('rate', array(
71
+			'handler' => 'rating',
72
+			'method'  => 'getRateList'
73
+		));
74
+	}
75
+
76
+	/**
77
+	 * @param  string $key
78
+	 * @param  string $format
79
+	 * @return mixed
80
+	 */
81
+	public function getVar($key, $format = 's')
82
+	{
83
+		if ($format === 's' && in_array($key, array('name', 'dirname'))) {
84
+			//            return call_user_func(array($this, $key));
85
+			return $this->{$key}();
86
+		}
87
+
88
+		return parent::getVar($key, $format);
89
+	}
90
+
91
+	/**
92
+	 * @return string
93
+	 */
94
+	public function name()
95
+	{
96
+		$ret = smart_getLinkedUnameFromId($this->getVar('uid', 'e'), true, array());
97
+
98
+		return $ret;
99
+	}
100
+
101
+	/**
102
+	 * @return mixed
103
+	 */
104
+	public function dirname()
105
+	{
106
+		global $smartobjectRatingHandler;
107
+		$moduleArray = $smartobjectRatingHandler->getModuleList();
108
+
109
+		return $moduleArray[$this->getVar('dirname', 'n')];
110
+	}
111
+
112
+	/**
113
+	 * @return mixed
114
+	 */
115
+	public function getItemList()
116
+	{
117
+		$plugin = $this->getModulePlugin();
118
+
119
+		return $plugin->getItemList();
120
+	}
121
+
122
+	/**
123
+	 * @return string
124
+	 */
125
+	public function getItemValue()
126
+	{
127
+		$moduleUrl      = XOOPS_URL . '/modules/' . $this->getVar('dirname', 'n') . '/';
128
+		$plugin         = $this->getModulePlugin();
129
+		$pluginItemInfo = $plugin->getItemInfo($this->getVar('item'));
130
+		if (!$pluginItemInfo) {
131
+			return '';
132
+		}
133
+		$itemPath = sprintf($pluginItemInfo['url'], $this->getVar('itemid'));
134
+		$ret      = '<a href="' . $moduleUrl . $itemPath . '">' . $pluginItemInfo['caption'] . '</a>';
135
+
136
+		return $ret;
137
+	}
138
+
139
+	/**
140
+	 * @return mixed
141
+	 */
142
+	public function getRateValue()
143
+	{
144
+		return $this->getVar('rate');
145
+	}
146
+
147
+	/**
148
+	 * @return bool
149
+	 */
150
+	public function getModulePlugin()
151
+	{
152
+		if (!$this->_modulePlugin) {
153
+			global $smartobjectRatingHandler;
154
+			$this->_modulePlugin = $smartobjectRatingHandler->pluginsObject->getPlugin($this->getVar('dirname', 'n'));
155
+		}
156
+
157
+		return $this->_modulePlugin;
158
+	}
159 159
 }
160 160
 
161 161
 /**
@@ -163,93 +163,93 @@  discard block
 block discarded – undo
163 163
  */
164 164
 class SmartobjectRatingHandler extends SmartPersistableObjectHandler
165 165
 {
166
-    public $_rateOptions = array();
167
-    public $_moduleList  = false;
168
-    public $pluginsObject;
169
-
170
-    /**
171
-     * SmartobjectRatingHandler constructor.
172
-     * @param XoopsDatabase $db
173
-     */
174
-    public function __construct($db)
175
-    {
176
-        parent::__construct($db, 'rating', 'ratingid', 'rate', '', 'smartobject');
177
-        $this->generalSQL = 'SELECT * FROM ' . $this->table . ' AS ' . $this->_itemname . ' INNER JOIN ' . $this->db->prefix('users') . ' AS user ON ' . $this->_itemname . '.uid=user.uid';
178
-
179
-        $this->_rateOptions[1] = 1;
180
-        $this->_rateOptions[2] = 2;
181
-        $this->_rateOptions[3] = 3;
182
-        $this->_rateOptions[4] = 4;
183
-        $this->_rateOptions[5] = 5;
184
-
185
-        $this->pluginsObject = new SmartPluginHandler();
186
-    }
187
-
188
-    /**
189
-     * @return bool
190
-     */
191
-    public function getModuleList()
192
-    {
193
-        if (!$this->_moduleList) {
194
-            $moduleArray          = $this->pluginsObject->getPluginsArray();
195
-            $this->_moduleList[0] = _CO_SOBJECT_MAKE_SELECTION;
196
-            foreach ($moduleArray as $k => $v) {
197
-                $this->_moduleList[$k] = $v;
198
-            }
199
-        }
200
-
201
-        return $this->_moduleList;
202
-    }
203
-
204
-    /**
205
-     * @return array
206
-     */
207
-    public function getRateList()
208
-    {
209
-        return $this->_rateOptions;
210
-    }
211
-
212
-    /**
213
-     * @param $itemid
214
-     * @param $dirname
215
-     * @param $item
216
-     * @return int
217
-     */
218
-    public function getRatingAverageByItemId($itemid, $dirname, $item)
219
-    {
220
-        $sql    = 'SELECT AVG(rate), COUNT(ratingid) FROM ' . $this->table . " WHERE itemid=$itemid AND dirname='$dirname' AND item='$item' GROUP BY itemid";
221
-        $result = $this->db->query($sql);
222
-        if (!$result) {
223
-            return 0;
224
-        }
225
-        list($average, $sum) = $this->db->fetchRow($result);
226
-        $ret['average'] = isset($average) ? $average : 0;
227
-        $ret['sum']     = isset($sum) ? $sum : 0;
228
-
229
-        return $ret;
230
-    }
231
-
232
-    /**
233
-     * @param $item
234
-     * @param $itemid
235
-     * @param $dirname
236
-     * @param $uid
237
-     * @return bool
238
-     */
239
-    public function already_rated($item, $itemid, $dirname, $uid)
240
-    {
241
-        $criteria = new CriteriaCompo();
242
-        $criteria->add(new Criteria('item', $item));
243
-        $criteria->add(new Criteria('itemid', $itemid));
244
-        $criteria->add(new Criteria('dirname', $dirname));
245
-        $criteria->add(new Criteria('user.uid', $uid));
246
-
247
-        $ret = $this->getObjects($criteria);
248
-
249
-        if (!$ret) {
250
-            return false;
251
-        } else {
252
-            return $ret[0];
253
-        }
254
-    }
166
+	public $_rateOptions = array();
167
+	public $_moduleList  = false;
168
+	public $pluginsObject;
169
+
170
+	/**
171
+	 * SmartobjectRatingHandler constructor.
172
+	 * @param XoopsDatabase $db
173
+	 */
174
+	public function __construct($db)
175
+	{
176
+		parent::__construct($db, 'rating', 'ratingid', 'rate', '', 'smartobject');
177
+		$this->generalSQL = 'SELECT * FROM ' . $this->table . ' AS ' . $this->_itemname . ' INNER JOIN ' . $this->db->prefix('users') . ' AS user ON ' . $this->_itemname . '.uid=user.uid';
178
+
179
+		$this->_rateOptions[1] = 1;
180
+		$this->_rateOptions[2] = 2;
181
+		$this->_rateOptions[3] = 3;
182
+		$this->_rateOptions[4] = 4;
183
+		$this->_rateOptions[5] = 5;
184
+
185
+		$this->pluginsObject = new SmartPluginHandler();
186
+	}
187
+
188
+	/**
189
+	 * @return bool
190
+	 */
191
+	public function getModuleList()
192
+	{
193
+		if (!$this->_moduleList) {
194
+			$moduleArray          = $this->pluginsObject->getPluginsArray();
195
+			$this->_moduleList[0] = _CO_SOBJECT_MAKE_SELECTION;
196
+			foreach ($moduleArray as $k => $v) {
197
+				$this->_moduleList[$k] = $v;
198
+			}
199
+		}
200
+
201
+		return $this->_moduleList;
202
+	}
203
+
204
+	/**
205
+	 * @return array
206
+	 */
207
+	public function getRateList()
208
+	{
209
+		return $this->_rateOptions;
210
+	}
211
+
212
+	/**
213
+	 * @param $itemid
214
+	 * @param $dirname
215
+	 * @param $item
216
+	 * @return int
217
+	 */
218
+	public function getRatingAverageByItemId($itemid, $dirname, $item)
219
+	{
220
+		$sql    = 'SELECT AVG(rate), COUNT(ratingid) FROM ' . $this->table . " WHERE itemid=$itemid AND dirname='$dirname' AND item='$item' GROUP BY itemid";
221
+		$result = $this->db->query($sql);
222
+		if (!$result) {
223
+			return 0;
224
+		}
225
+		list($average, $sum) = $this->db->fetchRow($result);
226
+		$ret['average'] = isset($average) ? $average : 0;
227
+		$ret['sum']     = isset($sum) ? $sum : 0;
228
+
229
+		return $ret;
230
+	}
231
+
232
+	/**
233
+	 * @param $item
234
+	 * @param $itemid
235
+	 * @param $dirname
236
+	 * @param $uid
237
+	 * @return bool
238
+	 */
239
+	public function already_rated($item, $itemid, $dirname, $uid)
240
+	{
241
+		$criteria = new CriteriaCompo();
242
+		$criteria->add(new Criteria('item', $item));
243
+		$criteria->add(new Criteria('itemid', $itemid));
244
+		$criteria->add(new Criteria('dirname', $dirname));
245
+		$criteria->add(new Criteria('user.uid', $uid));
246
+
247
+		$ret = $this->getObjects($criteria);
248
+
249
+		if (!$ret) {
250
+			return false;
251
+		} else {
252
+			return $ret[0];
253
+		}
254
+	}
255 255
 }
Please login to merge, or discard this patch.
class/smartaddto.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -9,66 +9,66 @@
 block discarded – undo
9 9
 
10 10
 class SmartAddto
11 11
 {
12
-    public $_layout;
13
-    public $_method;
12
+	public $_layout;
13
+	public $_method;
14 14
 
15
-    /**
16
-     * Constructor of SmartAddTo
17
-     *
18
-     * @param int $layout 0=Horizontal 1 row, 1=Horizontal 2 rows, 2=Vertical with icons, 3=Vertical no icons
19
-     * @param int $method 0=directpage, 1=popup
20
-     */
21
-    public function __construct($layout = 0, $method = 1)
22
-    {
23
-        $layout = (int)$layout;
24
-        if ($layout < 0 || $layout > 3) {
25
-            $layout = 0;
26
-        }
27
-        $this->_layout = $layout;
15
+	/**
16
+	 * Constructor of SmartAddTo
17
+	 *
18
+	 * @param int $layout 0=Horizontal 1 row, 1=Horizontal 2 rows, 2=Vertical with icons, 3=Vertical no icons
19
+	 * @param int $method 0=directpage, 1=popup
20
+	 */
21
+	public function __construct($layout = 0, $method = 1)
22
+	{
23
+		$layout = (int)$layout;
24
+		if ($layout < 0 || $layout > 3) {
25
+			$layout = 0;
26
+		}
27
+		$this->_layout = $layout;
28 28
 
29
-        $method = (int)$method;
30
-        if ($method < 0 || $method > 1) {
31
-            $method = 1;
32
-        }
33
-        $this->_method = $method;
34
-    }
29
+		$method = (int)$method;
30
+		if ($method < 0 || $method > 1) {
31
+			$method = 1;
32
+		}
33
+		$this->_method = $method;
34
+	}
35 35
 
36
-    /**
37
-     * @param  bool $fetchOnly
38
-     * @return mixed|string|void
39
-     */
40
-    public function render($fetchOnly = false)
41
-    {
42
-        global $xoTheme, $xoopsTpl;
36
+	/**
37
+	 * @param  bool $fetchOnly
38
+	 * @return mixed|string|void
39
+	 */
40
+	public function render($fetchOnly = false)
41
+	{
42
+		global $xoTheme, $xoopsTpl;
43 43
 
44
-        $xoTheme->addStylesheet(SMARTOBJECT_URL . 'include/addto/addto.css');
44
+		$xoTheme->addStylesheet(SMARTOBJECT_URL . 'include/addto/addto.css');
45 45
 
46
-        $xoopsTpl->assign('smartobject_addto_method', $this->_method);
47
-        $xoopsTpl->assign('smartobject_addto_layout', $this->_layout);
46
+		$xoopsTpl->assign('smartobject_addto_method', $this->_method);
47
+		$xoopsTpl->assign('smartobject_addto_layout', $this->_layout);
48 48
 
49
-        $xoopsTpl->assign('smartobject_addto_url', SMARTOBJECT_URL . 'include/addto/');
49
+		$xoopsTpl->assign('smartobject_addto_url', SMARTOBJECT_URL . 'include/addto/');
50 50
 
51
-        if ($fetchOnly) {
52
-            return $xoopsTpl->fetch('db:smartobject_addto.tpl');
53
-        } else {
54
-            $xoopsTpl->display('db:smartobject_addto.tpl');
55
-        }
56
-    }
51
+		if ($fetchOnly) {
52
+			return $xoopsTpl->fetch('db:smartobject_addto.tpl');
53
+		} else {
54
+			$xoopsTpl->display('db:smartobject_addto.tpl');
55
+		}
56
+	}
57 57
 
58
-    /**
59
-     * @return array
60
-     */
61
-    public function renderForBlock()
62
-    {
63
-        global $xoTheme;
58
+	/**
59
+	 * @return array
60
+	 */
61
+	public function renderForBlock()
62
+	{
63
+		global $xoTheme;
64 64
 
65
-        $xoTheme->addStylesheet(SMARTOBJECT_URL . 'include/addto/addto.css');
65
+		$xoTheme->addStylesheet(SMARTOBJECT_URL . 'include/addto/addto.css');
66 66
 
67
-        $block                             = array();
68
-        $block['smartobject_addto_method'] = $this->_method;
69
-        $block['smartobject_addto_layout'] = $this->_layout;
70
-        $block['smartobject_addto_url']    = SMARTOBJECT_URL . 'include/addto/';
67
+		$block                             = array();
68
+		$block['smartobject_addto_method'] = $this->_method;
69
+		$block['smartobject_addto_layout'] = $this->_layout;
70
+		$block['smartobject_addto_url']    = SMARTOBJECT_URL . 'include/addto/';
71 71
 
72
-        return $block;
73
-    }
72
+		return $block;
73
+	}
74 74
 }
Please login to merge, or discard this patch.
class/file.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -8,14 +8,14 @@  discard block
 block discarded – undo
8 8
  */
9 9
 class SmartobjectFile extends SmartobjectBasedUrl
10 10
 {
11
-    /**
12
-     * SmartobjectFile constructor.
13
-     */
14
-    public function __construct()
15
-    {
16
-        parent::__construct();
17
-        $this->quickInitVar('fileid', XOBJ_DTYPE_TXTBOX, true, _CO_SOBJECT_RATING_DIRNAME);
18
-    }
11
+	/**
12
+	 * SmartobjectFile constructor.
13
+	 */
14
+	public function __construct()
15
+	{
16
+		parent::__construct();
17
+		$this->quickInitVar('fileid', XOBJ_DTYPE_TXTBOX, true, _CO_SOBJECT_RATING_DIRNAME);
18
+	}
19 19
 }
20 20
 
21 21
 /**
@@ -23,12 +23,12 @@  discard block
 block discarded – undo
23 23
  */
24 24
 class SmartobjectFileHandler extends SmartPersistableObjectHandler
25 25
 {
26
-    /**
27
-     * SmartobjectFileHandler constructor.
28
-     * @param object|XoopsDatabase $db
29
-     */
30
-    public function __construct($db)
31
-    {
32
-        parent::__construct($db, 'file', 'fileid', 'caption', 'desc', 'smartobject');
33
-    }
26
+	/**
27
+	 * SmartobjectFileHandler constructor.
28
+	 * @param object|XoopsDatabase $db
29
+	 */
30
+	public function __construct($db)
31
+	{
32
+		parent::__construct($db, 'file', 'fileid', 'caption', 'desc', 'smartobject');
33
+	}
34 34
 }
Please login to merge, or discard this patch.
class/smartobjectcontroller.php 1 patch
Indentation   +474 added lines, -474 removed lines patch added patch discarded remove patch
@@ -31,478 +31,478 @@
 block discarded – undo
31 31
  */
32 32
 class SmartObjectController
33 33
 {
34
-    public $handler;
35
-
36
-    /**
37
-     * SmartObjectController constructor.
38
-     * @param $handler
39
-     */
40
-    public function __construct($handler)
41
-    {
42
-        $this->handler = $handler;
43
-    }
44
-
45
-    /**
46
-     * @param $smartObj
47
-     */
48
-    public function postDataToObject(&$smartObj)
49
-    {
50
-        foreach (array_keys($smartObj->vars) as $key) {
51
-            switch ($smartObj->vars[$key]['data_type']) {
52
-                case XOBJ_DTYPE_IMAGE:
53
-                    if (isset($_POST['url_' . $key]) && $_POST['url_' . $key] != '') {
54
-                        $oldFile = $smartObj->getUploadDir(true) . $smartObj->getVar($key, 'e');
55
-                        $smartObj->setVar($key, $_POST['url_' . $key]);
56
-                        if (file_exists($oldFile)) {
57
-                            unlink($oldFile);
58
-                        }
59
-                    }
60
-                    if (isset($_POST['delete_' . $key]) && $_POST['delete_' . $key] == '1') {
61
-                        $oldFile = $smartObj->getUploadDir(true) . $smartObj->getVar($key, 'e');
62
-                        $smartObj->setVar($key, '');
63
-                        if (file_exists($oldFile)) {
64
-                            unlink($oldFile);
65
-                        }
66
-                    }
67
-                    break;
68
-
69
-                case XOBJ_DTYPE_URLLINK:
70
-                    $linkObj = $smartObj->getUrlLinkObj($key);
71
-                    $linkObj->setVar('caption', $_POST['caption_' . $key]);
72
-                    $linkObj->setVar('description', $_POST['desc_' . $key]);
73
-                    $linkObj->setVar('target', $_POST['target_' . $key]);
74
-                    $linkObj->setVar('url', $_POST['url_' . $key]);
75
-                    if ($linkObj->getVar('url') != '') {
76
-                        $smartObj->storeUrlLinkObj($linkObj);
77
-                    }
78
-                    //todo: catch errors
79
-                    $smartObj->setVar($key, $linkObj->getVar('urllinkid'));
80
-                    break;
81
-
82
-                case XOBJ_DTYPE_FILE:
83
-                    if (!isset($_FILES['upload_' . $key]['name']) || $_FILES['upload_' . $key]['name'] == '') {
84
-                        $fileObj = $smartObj->getFileObj($key);
85
-                        $fileObj->setVar('caption', $_POST['caption_' . $key]);
86
-                        $fileObj->setVar('description', $_POST['desc_' . $key]);
87
-                        $fileObj->setVar('url', $_POST['url_' . $key]);
88
-                        if (!($fileObj->getVar('url') == '' && $fileObj->getVar('url') == '' && $fileObj->getVar('url') == '')) {
89
-                            $res = $smartObj->storeFileObj($fileObj);
90
-                            if ($res) {
91
-                                $smartObj->setVar($key, $fileObj->getVar('fileid'));
92
-                            } else {
93
-                                //error setted, but no error message (to be improved)
94
-                                $smartObj->setErrors($fileObj->getErrors());
95
-                            }
96
-                        }
97
-                    }
98
-                    break;
99
-
100
-                case XOBJ_DTYPE_STIME:
101
-                case XOBJ_DTYPE_MTIME:
102
-                case XOBJ_DTYPE_LTIME:
103
-                    // check if this field's value is available in the POST array
104
-                    if (is_array($_POST[$key]) && isset($_POST[$key]['date'])) {
105
-                        $value = strtotime($_POST[$key]['date']) + $_POST[$key]['time'];
106
-                    } else {
107
-                        $value = strtotime($_POST[$key]);
108
-                        //if strtotime returns false, the value is already a time stamp
109
-                        if (!$value) {
110
-                            $value = (int)$_POST[$key];
111
-                        }
112
-                    }
113
-                    $smartObj->setVar($key, $value);
114
-
115
-                    break;
116
-
117
-                default:
118
-                    $smartObj->setVar($key, $_POST[$key]);
119
-                    break;
120
-            }
121
-        }
122
-    }
123
-
124
-    /**
125
-     * @param       $smartObj
126
-     * @param       $objectid
127
-     * @param       $created_success_msg
128
-     * @param       $modified_success_msg
129
-     * @param  bool $redirect_page
130
-     * @param  bool $debug
131
-     * @return mixed
132
-     */
133
-    public function doStoreFromDefaultForm(&$smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page = false, $debug = false)
134
-    {
135
-        global $smart_previous_page;
136
-
137
-        $this->postDataToObject($smartObj);
138
-
139
-        if ($smartObj->isNew()) {
140
-            $redirect_msg = $created_success_msg;
141
-        } else {
142
-            $redirect_msg = $modified_success_msg;
143
-        }
144
-
145
-        // Check if there were uploaded files
146
-        if (isset($_POST['smart_upload_image']) || isset($_POST['smart_upload_file'])) {
147
-            include_once XOOPS_ROOT_PATH . '/modules/smartobject/class/smartuploader.php';
148
-            $uploaderObj = new SmartUploader($smartObj->getImageDir(true), $this->handler->_allowedMimeTypes, $this->handler->_maxFileSize, $this->handler->_maxWidth, $this->handler->_maxHeight);
149
-            foreach ($_FILES as $name => $file_array) {
150
-                if (isset($file_array['name']) && $file_array['name'] != '' && in_array(str_replace('upload_', '', $name), array_keys($smartObj->vars))) {
151
-                    if ($uploaderObj->fetchMedia($name)) {
152
-                        $uploaderObj->setTargetFileName(time() . '_' . $uploaderObj->getMediaName());
153
-                        if ($uploaderObj->upload()) {
154
-                            // Find the related field in the SmartObject
155
-                            $related_field   = str_replace('upload_', '', $name);
156
-                            $uploadedArray[] = $related_field;
157
-                            //si c'est un fichier Rich
158
-                            if ($smartObj->vars[$related_field]['data_type'] === XOBJ_DTYPE_FILE) {
159
-                                $object_fileurl = $smartObj->getUploadDir();
160
-                                $fileObj        = $smartObj->getFileObj($related_field);
161
-                                $fileObj->setVar('url', $object_fileurl . $uploaderObj->getSavedFileName());
162
-                                $fileObj->setVar('caption', $_POST['caption_' . $related_field]);
163
-                                $fileObj->setVar('description', $_POST['desc_' . $related_field]);
164
-                                $smartObj->storeFileObj($fileObj);
165
-                                //todo: catch errors
166
-                                $smartObj->setVar($related_field, $fileObj->getVar('fileid'));
167
-                            } else {
168
-                                $old_file = $smartObj->getUploadDir(true) . $smartObj->getVar($related_field);
169
-                                unlink($old_file);
170
-                                $smartObj->setVar($related_field, $uploaderObj->getSavedFileName());
171
-                            }
172
-                        } else {
173
-                            $smartObj->setErrors($uploaderObj->getErrors(false));
174
-                        }
175
-                    } else {
176
-                        $smartObj->setErrors($uploaderObj->getErrors(false));
177
-                    }
178
-                }
179
-            }
180
-        }
181
-
182
-        if ($debug) {
183
-            $storeResult = $this->handler->insertD($smartObj);
184
-        } else {
185
-            $storeResult = $this->handler->insert($smartObj);
186
-        }
187
-
188
-        if ($storeResult) {
189
-            if ($this->handler->getPermissions()) {
190
-                $smartPermissionsHandler = new SmartobjectPermissionHandler($this->handler);
191
-                $smartPermissionsHandler->storeAllPermissionsForId($smartObj->id());
192
-            }
193
-        }
194
-
195
-        if ($redirect_page === null) {
196
-            return $smartObj;
197
-        } else {
198
-            if (!$storeResult) {
199
-                redirect_header($smart_previous_page, 3, _CO_SOBJECT_SAVE_ERROR . $smartObj->getHtmlErrors());
200
-            }
201
-
202
-            $redirect_page = $redirect_page ?: smart_get_page_before_form();
203
-
204
-            redirect_header($redirect_page, 2, $redirect_msg);
205
-        }
206
-    }
207
-
208
-    /**
209
-     * Store the object in the database autmatically from a form sending POST data
210
-     *
211
-     * @param  string      $created_success_msg  message to display if new object was created
212
-     * @param  string      $modified_success_msg message to display if object was successfully edited
213
-     * @param  bool|string $redirect_page        redirect page, if not set, then we backup once
214
-     * @param  bool        $debug
215
-     * @param  bool        $x_param
216
-     * @return bool
217
-     * @internal param string $created_redir_page redirect page after creating the object
218
-     * @internal param string $modified_redir_page redirect page after editing the object
219
-     * @internal param bool $exit if set to TRUE then the script ends
220
-     */
221
-    public function storeFromDefaultForm($created_success_msg, $modified_success_msg, $redirect_page = false, $debug = false, $x_param = false)
222
-    {
223
-        $objectid = isset($_POST[$this->handler->keyName]) ? (int)$_POST[$this->handler->keyName] : 0;
224
-        if ($debug) {
225
-            if ($x_param) {
226
-                $smartObj = $this->handler->getD($objectid, true, $x_param);
227
-            } else {
228
-                $smartObj = $this->handler->getD($objectid);
229
-            }
230
-        } else {
231
-            if ($x_param) {
232
-                $smartObj = $this->handler->get($objectid, true, false, false, $x_param);
233
-            } else {
234
-                $smartObj = $this->handler->get($objectid);
235
-            }
236
-        }
237
-
238
-        // if handler is the Multilanguage handler, we will need to treat this for multilanguage
239
-        if (is_subclass_of($this->handler, 'smartpersistablemlobjecthandler')) {
240
-            if ($smartObj->isNew()) {
241
-                // This is a new object. We need to store the meta data and then the language data
242
-                // First, we will get rid of the multilanguage data to only store the meta data
243
-                $smartObj->stripMultilanguageFields();
244
-                $newObject = $this->doStoreFromDefaultForm($smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
245
-                /**
246
-                 * @todo we need to trap potential errors here
247
-                 */
248
-
249
-                // ok, the meta daa is stored. Let's recreate the object and then
250
-                // get rid of anything not multilanguage
251
-                unset($smartObj);
252
-                $smartObj = $this->handler->get($objectid);
253
-                $smartObj->stripNonMultilanguageFields();
254
-
255
-                $smartObj->setVar($this->handler->keyName, $newObject->getVar($this->handler->keyName));
256
-                $this->handler->changeTableNameForML();
257
-                $ret = $this->doStoreFromDefaultForm($smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
258
-
259
-                return $ret;
260
-            }
261
-        } else {
262
-            return $this->doStoreFromDefaultForm($smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
263
-        }
264
-    }
265
-
266
-    /**
267
-     * @return bool
268
-     */
269
-    public function storeSmartObjectD()
270
-    {
271
-        return $this->storeSmartObject(true);
272
-    }
273
-
274
-    /**
275
-     * @param  bool $debug
276
-     * @param  bool $xparam
277
-     * @return bool
278
-     */
279
-    public function storeSmartObject($debug = false, $xparam = false)
280
-    {
281
-        $ret = $this->storeFromDefaultForm('', '', null, $debug, $xparam);
282
-
283
-        return $ret;
284
-    }
285
-
286
-    /**
287
-     * Handles deletion of an object which keyid is passed as a GET param
288
-     *
289
-     * @param  bool   $confirm_msg
290
-     * @param  string $op
291
-     * @param  bool   $userSide
292
-     * @return bool
293
-     * @internal param string $redir_page redirect page after deleting the object
294
-     */
295
-    public function handleObjectDeletion($confirm_msg = false, $op = 'del', $userSide = false)
296
-    {
297
-        global $smart_previous_page;
298
-
299
-        $objectid = isset($_REQUEST[$this->handler->keyName]) ? (int)$_REQUEST[$this->handler->keyName] : 0;
300
-        $smartObj = $this->handler->get($objectid);
301
-
302
-        if ($smartObj->isNew()) {
303
-            redirect_header('javascript:history.go(-1)', 3, _CO_SOBJECT_NOT_SELECTED);
304
-        }
305
-
306
-        $confirm = isset($_POST['confirm']) ? $_POST['confirm'] : 0;
307
-        if ($confirm) {
308
-            if (!$this->handler->delete($smartObj)) {
309
-                redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_ERROR . $smartObj->getHtmlErrors());
310
-                exit;
311
-            }
312
-
313
-            redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_SUCCESS);
314
-        } else {
315
-            // no confirm: show deletion condition
316
-
317
-            xoops_cp_header();
318
-
319
-            if (!$confirm_msg) {
320
-                $confirm_msg = _CO_SOBJECT_DELETE_CONFIRM;
321
-            }
322
-
323
-            xoops_confirm(array('op' => $op, $this->handler->keyName => $smartObj->getVar($this->handler->keyName), 'confirm' => 1, 'redirect_page' => $smart_previous_page), xoops_getenv('PHP_SELF'), sprintf($confirm_msg, $smartObj->getVar($this->handler->identifierName)), _CO_SOBJECT_DELETE);
324
-
325
-            xoops_cp_footer();
326
-        }
327
-        exit();
328
-    }
329
-
330
-    /**
331
-     * @param bool   $confirm_msg
332
-     * @param string $op
333
-     */
334
-    public function handleObjectDeletionFromUserSide($confirm_msg = false, $op = 'del')
335
-    {
336
-        global $smart_previous_page, $xoopsTpl;
337
-
338
-        $objectid = isset($_REQUEST[$this->handler->keyName]) ? (int)$_REQUEST[$this->handler->keyName] : 0;
339
-        $smartObj = $this->handler->get($objectid);
340
-
341
-        if ($smartObj->isNew()) {
342
-            redirect_header('javascript:history.go(-1)', 3, _CO_SOBJECT_NOT_SELECTED);
343
-        }
344
-
345
-        $confirm = isset($_POST['confirm']) ? $_POST['confirm'] : 0;
346
-        if ($confirm) {
347
-            if (!$this->handler->delete($smartObj)) {
348
-                redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_ERROR . $smartObj->getHtmlErrors());
349
-                exit;
350
-            }
351
-
352
-            redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_SUCCESS);
353
-        } else {
354
-            // no confirm: show deletion condition
355
-            if (!$confirm_msg) {
356
-                $confirm_msg = _CO_SOBJECT_DELETE_CONFIRM;
357
-            }
358
-
359
-            ob_start();
360
-            xoops_confirm(array('op' => $op, $this->handler->keyName => $smartObj->getVar($this->handler->keyName), 'confirm' => 1, 'redirect_page' => $smart_previous_page), xoops_getenv('PHP_SELF'), sprintf($confirm_msg, $smartObj->getVar($this->handler->identifierName)), _CO_SOBJECT_DELETE);
361
-            $smartobjectDeleteConfirm = ob_get_clean();
362
-            $xoopsTpl->assign('smartobject_delete_confirm', $smartobjectDeleteConfirm);
363
-        }
364
-    }
365
-
366
-    /**
367
-     * Retreive the object admin side link for a {@link SmartObjectSingleView} page
368
-     *
369
-     * @param  object $smartObj reference to the object from which we want the user side link
370
-     * @param  bool   $onlyUrl  wether or not to return a simple URL or a full <a> link
371
-     * @param  bool   $withimage
372
-     * @return string admin side link to the object
373
-     */
374
-    public function getAdminViewItemLink($smartObj, $onlyUrl = false, $withimage = false)
375
-    {
376
-        $ret = $this->handler->_moduleUrl . 'admin/' . $this->handler->_page . '?op=view&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
377
-        if ($onlyUrl) {
378
-            return $ret;
379
-        } elseif ($withimage) {
380
-            return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "viewmag.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_ADMIN_VIEW . "'  title='" . _CO_SOBJECT_ADMIN_VIEW . "'/></a>";
381
-        }
382
-
383
-        return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
384
-    }
385
-
386
-    /**
387
-     * Retreive the object user side link
388
-     *
389
-     * @param  object $smartObj reference to the object from which we want the user side link
390
-     * @param  bool   $onlyUrl  wether or not to return a simple URL or a full <a> link
391
-     * @return string user side link to the object
392
-     */
393
-    public function getItemLink(&$smartObj, $onlyUrl = false)
394
-    {
395
-        $seoMode       = smart_getModuleModeSEO($this->handler->_moduleName);
396
-        $seoModuleName = smart_getModuleNameForSEO($this->handler->_moduleName);
397
-
398
-        /**
399
-         * $seoIncludeId feature is not finished yet, so let's put it always to true
400
-         */
401
-        //$seoIncludeId = smart_getModuleIncludeIdSEO($this->handler->_moduleName);
402
-        $seoIncludeId = true;
403
-
404
-        if ($seoMode === 'rewrite') {
405
-            $ret = XOOPS_URL . '/' . $seoModuleName . '.' . $this->handler->_itemname . ($seoIncludeId ? '.' . $smartObj->getVar($this->handler->keyName) : '') . '/' . $smartObj->getVar('short_url') . '.html';
406
-        } elseif ($seoMode === 'pathinfo') {
407
-            $ret = SMARTOBJECT_URL . 'seo.php/' . $seoModuleName . '.' . $this->handler->_itemname . ($seoIncludeId ? '.' . $smartObj->getVar($this->handler->keyName) : '') . '/' . $smartObj->getVar('short_url') . '.html';
408
-        } else {
409
-            $ret = $this->handler->_moduleUrl . $this->handler->_page . '?' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
410
-        }
411
-
412
-        if (!$onlyUrl) {
413
-            $ret = "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
414
-        }
415
-
416
-        return $ret;
417
-    }
418
-
419
-    /**
420
-     * @param       $smartObj
421
-     * @param  bool $onlyUrl
422
-     * @param  bool $withimage
423
-     * @return string
424
-     */
425
-    public function getEditLanguageLink($smartObj, $onlyUrl = false, $withimage = true)
426
-    {
427
-        $ret = $this->handler->_moduleUrl . 'admin/' . $this->handler->_page . '?op=mod&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName) . '&language=' . $smartObj->getVar('language');
428
-        if ($onlyUrl) {
429
-            return $ret;
430
-        } elseif ($withimage) {
431
-            return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "wizard.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_LANGUAGE_MODIFY . "'  title='" . _CO_SOBJECT_LANGUAGE_MODIFY . "'/></a>";
432
-        }
433
-
434
-        return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
435
-    }
436
-
437
-    /**
438
-     * @param       $smartObj
439
-     * @param  bool $onlyUrl
440
-     * @param  bool $withimage
441
-     * @param  bool $userSide
442
-     * @return string
443
-     */
444
-    public function getEditItemLink($smartObj, $onlyUrl = false, $withimage = true, $userSide = false)
445
-    {
446
-        $admin_side = $userSide ? '' : 'admin/';
447
-        $ret        = $this->handler->_moduleUrl . $admin_side . $this->handler->_page . '?op=mod&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
448
-        if ($onlyUrl) {
449
-            return $ret;
450
-        } elseif ($withimage) {
451
-            return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "edit.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_MODIFY . "'  title='" . _CO_SOBJECT_MODIFY . "'/></a>";
452
-        }
453
-
454
-        return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
455
-    }
456
-
457
-    /**
458
-     * @param       $smartObj
459
-     * @param  bool $onlyUrl
460
-     * @param  bool $withimage
461
-     * @param  bool $userSide
462
-     * @return string
463
-     */
464
-    public function getDeleteItemLink($smartObj, $onlyUrl = false, $withimage = true, $userSide = false)
465
-    {
466
-        $admin_side = $userSide ? '' : 'admin/';
467
-        $ret        = $this->handler->_moduleUrl . $admin_side . $this->handler->_page . '?op=del&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
468
-        if ($onlyUrl) {
469
-            return $ret;
470
-        } elseif ($withimage) {
471
-            return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "editdelete.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_DELETE . "'  title='" . _CO_SOBJECT_DELETE . "'/></a>";
472
-        }
473
-
474
-        return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
475
-    }
476
-
477
-    /**
478
-     * @param $smartObj
479
-     * @return string
480
-     */
481
-    public function getPrintAndMailLink($smartObj)
482
-    {
483
-        global $xoopsConfig;
484
-
485
-        $printlink = $this->handler->_moduleUrl . 'print.php?' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
486
-        $js        = "javascript:openWithSelfMain('" . $printlink . "', 'smartpopup', 700, 519);";
487
-        $printlink = '<a href="' . $js . '"><img  src="' . SMARTOBJECT_IMAGES_ACTIONS_URL . 'fileprint.png" alt="" style="vertical-align: middle;"/></a>';
488
-
489
-        $smartModule = smart_getModuleInfo($smartObj->handler->_moduleName);
490
-        $link        = smart_getCurrentPage();
491
-        $mid         = $smartModule->getVar('mid');
492
-        $friendlink  = "<a href=\"javascript:openWithSelfMain('" . SMARTOBJECT_URL . 'sendlink.php?link=' . $link . '&amp;mid=' . $mid . "', ',',',',',','sendmessage', 674, 500);\"><img src=\"" . SMARTOBJECT_IMAGES_ACTIONS_URL . "mail_send.png\"  alt=\"" . _CO_SOBJECT_EMAIL . "\" title=\"" . _CO_SOBJECT_EMAIL . "\" style=\"vertical-align: middle;\"/></a>";
493
-
494
-        $ret = '<span id="smartobject_print_button">' . $printlink . '&nbsp;</span>' . '<span id="smartobject_mail_button">' . $friendlink . '</span>';
495
-
496
-        return $ret;
497
-    }
498
-
499
-    /**
500
-     * @return string
501
-     */
502
-    public function getModuleItemString()
503
-    {
504
-        $ret = $this->handler->_moduleName . '_' . $this->handler->_itemname;
505
-
506
-        return $ret;
507
-    }
34
+	public $handler;
35
+
36
+	/**
37
+	 * SmartObjectController constructor.
38
+	 * @param $handler
39
+	 */
40
+	public function __construct($handler)
41
+	{
42
+		$this->handler = $handler;
43
+	}
44
+
45
+	/**
46
+	 * @param $smartObj
47
+	 */
48
+	public function postDataToObject(&$smartObj)
49
+	{
50
+		foreach (array_keys($smartObj->vars) as $key) {
51
+			switch ($smartObj->vars[$key]['data_type']) {
52
+				case XOBJ_DTYPE_IMAGE:
53
+					if (isset($_POST['url_' . $key]) && $_POST['url_' . $key] != '') {
54
+						$oldFile = $smartObj->getUploadDir(true) . $smartObj->getVar($key, 'e');
55
+						$smartObj->setVar($key, $_POST['url_' . $key]);
56
+						if (file_exists($oldFile)) {
57
+							unlink($oldFile);
58
+						}
59
+					}
60
+					if (isset($_POST['delete_' . $key]) && $_POST['delete_' . $key] == '1') {
61
+						$oldFile = $smartObj->getUploadDir(true) . $smartObj->getVar($key, 'e');
62
+						$smartObj->setVar($key, '');
63
+						if (file_exists($oldFile)) {
64
+							unlink($oldFile);
65
+						}
66
+					}
67
+					break;
68
+
69
+				case XOBJ_DTYPE_URLLINK:
70
+					$linkObj = $smartObj->getUrlLinkObj($key);
71
+					$linkObj->setVar('caption', $_POST['caption_' . $key]);
72
+					$linkObj->setVar('description', $_POST['desc_' . $key]);
73
+					$linkObj->setVar('target', $_POST['target_' . $key]);
74
+					$linkObj->setVar('url', $_POST['url_' . $key]);
75
+					if ($linkObj->getVar('url') != '') {
76
+						$smartObj->storeUrlLinkObj($linkObj);
77
+					}
78
+					//todo: catch errors
79
+					$smartObj->setVar($key, $linkObj->getVar('urllinkid'));
80
+					break;
81
+
82
+				case XOBJ_DTYPE_FILE:
83
+					if (!isset($_FILES['upload_' . $key]['name']) || $_FILES['upload_' . $key]['name'] == '') {
84
+						$fileObj = $smartObj->getFileObj($key);
85
+						$fileObj->setVar('caption', $_POST['caption_' . $key]);
86
+						$fileObj->setVar('description', $_POST['desc_' . $key]);
87
+						$fileObj->setVar('url', $_POST['url_' . $key]);
88
+						if (!($fileObj->getVar('url') == '' && $fileObj->getVar('url') == '' && $fileObj->getVar('url') == '')) {
89
+							$res = $smartObj->storeFileObj($fileObj);
90
+							if ($res) {
91
+								$smartObj->setVar($key, $fileObj->getVar('fileid'));
92
+							} else {
93
+								//error setted, but no error message (to be improved)
94
+								$smartObj->setErrors($fileObj->getErrors());
95
+							}
96
+						}
97
+					}
98
+					break;
99
+
100
+				case XOBJ_DTYPE_STIME:
101
+				case XOBJ_DTYPE_MTIME:
102
+				case XOBJ_DTYPE_LTIME:
103
+					// check if this field's value is available in the POST array
104
+					if (is_array($_POST[$key]) && isset($_POST[$key]['date'])) {
105
+						$value = strtotime($_POST[$key]['date']) + $_POST[$key]['time'];
106
+					} else {
107
+						$value = strtotime($_POST[$key]);
108
+						//if strtotime returns false, the value is already a time stamp
109
+						if (!$value) {
110
+							$value = (int)$_POST[$key];
111
+						}
112
+					}
113
+					$smartObj->setVar($key, $value);
114
+
115
+					break;
116
+
117
+				default:
118
+					$smartObj->setVar($key, $_POST[$key]);
119
+					break;
120
+			}
121
+		}
122
+	}
123
+
124
+	/**
125
+	 * @param       $smartObj
126
+	 * @param       $objectid
127
+	 * @param       $created_success_msg
128
+	 * @param       $modified_success_msg
129
+	 * @param  bool $redirect_page
130
+	 * @param  bool $debug
131
+	 * @return mixed
132
+	 */
133
+	public function doStoreFromDefaultForm(&$smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page = false, $debug = false)
134
+	{
135
+		global $smart_previous_page;
136
+
137
+		$this->postDataToObject($smartObj);
138
+
139
+		if ($smartObj->isNew()) {
140
+			$redirect_msg = $created_success_msg;
141
+		} else {
142
+			$redirect_msg = $modified_success_msg;
143
+		}
144
+
145
+		// Check if there were uploaded files
146
+		if (isset($_POST['smart_upload_image']) || isset($_POST['smart_upload_file'])) {
147
+			include_once XOOPS_ROOT_PATH . '/modules/smartobject/class/smartuploader.php';
148
+			$uploaderObj = new SmartUploader($smartObj->getImageDir(true), $this->handler->_allowedMimeTypes, $this->handler->_maxFileSize, $this->handler->_maxWidth, $this->handler->_maxHeight);
149
+			foreach ($_FILES as $name => $file_array) {
150
+				if (isset($file_array['name']) && $file_array['name'] != '' && in_array(str_replace('upload_', '', $name), array_keys($smartObj->vars))) {
151
+					if ($uploaderObj->fetchMedia($name)) {
152
+						$uploaderObj->setTargetFileName(time() . '_' . $uploaderObj->getMediaName());
153
+						if ($uploaderObj->upload()) {
154
+							// Find the related field in the SmartObject
155
+							$related_field   = str_replace('upload_', '', $name);
156
+							$uploadedArray[] = $related_field;
157
+							//si c'est un fichier Rich
158
+							if ($smartObj->vars[$related_field]['data_type'] === XOBJ_DTYPE_FILE) {
159
+								$object_fileurl = $smartObj->getUploadDir();
160
+								$fileObj        = $smartObj->getFileObj($related_field);
161
+								$fileObj->setVar('url', $object_fileurl . $uploaderObj->getSavedFileName());
162
+								$fileObj->setVar('caption', $_POST['caption_' . $related_field]);
163
+								$fileObj->setVar('description', $_POST['desc_' . $related_field]);
164
+								$smartObj->storeFileObj($fileObj);
165
+								//todo: catch errors
166
+								$smartObj->setVar($related_field, $fileObj->getVar('fileid'));
167
+							} else {
168
+								$old_file = $smartObj->getUploadDir(true) . $smartObj->getVar($related_field);
169
+								unlink($old_file);
170
+								$smartObj->setVar($related_field, $uploaderObj->getSavedFileName());
171
+							}
172
+						} else {
173
+							$smartObj->setErrors($uploaderObj->getErrors(false));
174
+						}
175
+					} else {
176
+						$smartObj->setErrors($uploaderObj->getErrors(false));
177
+					}
178
+				}
179
+			}
180
+		}
181
+
182
+		if ($debug) {
183
+			$storeResult = $this->handler->insertD($smartObj);
184
+		} else {
185
+			$storeResult = $this->handler->insert($smartObj);
186
+		}
187
+
188
+		if ($storeResult) {
189
+			if ($this->handler->getPermissions()) {
190
+				$smartPermissionsHandler = new SmartobjectPermissionHandler($this->handler);
191
+				$smartPermissionsHandler->storeAllPermissionsForId($smartObj->id());
192
+			}
193
+		}
194
+
195
+		if ($redirect_page === null) {
196
+			return $smartObj;
197
+		} else {
198
+			if (!$storeResult) {
199
+				redirect_header($smart_previous_page, 3, _CO_SOBJECT_SAVE_ERROR . $smartObj->getHtmlErrors());
200
+			}
201
+
202
+			$redirect_page = $redirect_page ?: smart_get_page_before_form();
203
+
204
+			redirect_header($redirect_page, 2, $redirect_msg);
205
+		}
206
+	}
207
+
208
+	/**
209
+	 * Store the object in the database autmatically from a form sending POST data
210
+	 *
211
+	 * @param  string      $created_success_msg  message to display if new object was created
212
+	 * @param  string      $modified_success_msg message to display if object was successfully edited
213
+	 * @param  bool|string $redirect_page        redirect page, if not set, then we backup once
214
+	 * @param  bool        $debug
215
+	 * @param  bool        $x_param
216
+	 * @return bool
217
+	 * @internal param string $created_redir_page redirect page after creating the object
218
+	 * @internal param string $modified_redir_page redirect page after editing the object
219
+	 * @internal param bool $exit if set to TRUE then the script ends
220
+	 */
221
+	public function storeFromDefaultForm($created_success_msg, $modified_success_msg, $redirect_page = false, $debug = false, $x_param = false)
222
+	{
223
+		$objectid = isset($_POST[$this->handler->keyName]) ? (int)$_POST[$this->handler->keyName] : 0;
224
+		if ($debug) {
225
+			if ($x_param) {
226
+				$smartObj = $this->handler->getD($objectid, true, $x_param);
227
+			} else {
228
+				$smartObj = $this->handler->getD($objectid);
229
+			}
230
+		} else {
231
+			if ($x_param) {
232
+				$smartObj = $this->handler->get($objectid, true, false, false, $x_param);
233
+			} else {
234
+				$smartObj = $this->handler->get($objectid);
235
+			}
236
+		}
237
+
238
+		// if handler is the Multilanguage handler, we will need to treat this for multilanguage
239
+		if (is_subclass_of($this->handler, 'smartpersistablemlobjecthandler')) {
240
+			if ($smartObj->isNew()) {
241
+				// This is a new object. We need to store the meta data and then the language data
242
+				// First, we will get rid of the multilanguage data to only store the meta data
243
+				$smartObj->stripMultilanguageFields();
244
+				$newObject = $this->doStoreFromDefaultForm($smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
245
+				/**
246
+				 * @todo we need to trap potential errors here
247
+				 */
248
+
249
+				// ok, the meta daa is stored. Let's recreate the object and then
250
+				// get rid of anything not multilanguage
251
+				unset($smartObj);
252
+				$smartObj = $this->handler->get($objectid);
253
+				$smartObj->stripNonMultilanguageFields();
254
+
255
+				$smartObj->setVar($this->handler->keyName, $newObject->getVar($this->handler->keyName));
256
+				$this->handler->changeTableNameForML();
257
+				$ret = $this->doStoreFromDefaultForm($smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
258
+
259
+				return $ret;
260
+			}
261
+		} else {
262
+			return $this->doStoreFromDefaultForm($smartObj, $objectid, $created_success_msg, $modified_success_msg, $redirect_page, $debug);
263
+		}
264
+	}
265
+
266
+	/**
267
+	 * @return bool
268
+	 */
269
+	public function storeSmartObjectD()
270
+	{
271
+		return $this->storeSmartObject(true);
272
+	}
273
+
274
+	/**
275
+	 * @param  bool $debug
276
+	 * @param  bool $xparam
277
+	 * @return bool
278
+	 */
279
+	public function storeSmartObject($debug = false, $xparam = false)
280
+	{
281
+		$ret = $this->storeFromDefaultForm('', '', null, $debug, $xparam);
282
+
283
+		return $ret;
284
+	}
285
+
286
+	/**
287
+	 * Handles deletion of an object which keyid is passed as a GET param
288
+	 *
289
+	 * @param  bool   $confirm_msg
290
+	 * @param  string $op
291
+	 * @param  bool   $userSide
292
+	 * @return bool
293
+	 * @internal param string $redir_page redirect page after deleting the object
294
+	 */
295
+	public function handleObjectDeletion($confirm_msg = false, $op = 'del', $userSide = false)
296
+	{
297
+		global $smart_previous_page;
298
+
299
+		$objectid = isset($_REQUEST[$this->handler->keyName]) ? (int)$_REQUEST[$this->handler->keyName] : 0;
300
+		$smartObj = $this->handler->get($objectid);
301
+
302
+		if ($smartObj->isNew()) {
303
+			redirect_header('javascript:history.go(-1)', 3, _CO_SOBJECT_NOT_SELECTED);
304
+		}
305
+
306
+		$confirm = isset($_POST['confirm']) ? $_POST['confirm'] : 0;
307
+		if ($confirm) {
308
+			if (!$this->handler->delete($smartObj)) {
309
+				redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_ERROR . $smartObj->getHtmlErrors());
310
+				exit;
311
+			}
312
+
313
+			redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_SUCCESS);
314
+		} else {
315
+			// no confirm: show deletion condition
316
+
317
+			xoops_cp_header();
318
+
319
+			if (!$confirm_msg) {
320
+				$confirm_msg = _CO_SOBJECT_DELETE_CONFIRM;
321
+			}
322
+
323
+			xoops_confirm(array('op' => $op, $this->handler->keyName => $smartObj->getVar($this->handler->keyName), 'confirm' => 1, 'redirect_page' => $smart_previous_page), xoops_getenv('PHP_SELF'), sprintf($confirm_msg, $smartObj->getVar($this->handler->identifierName)), _CO_SOBJECT_DELETE);
324
+
325
+			xoops_cp_footer();
326
+		}
327
+		exit();
328
+	}
329
+
330
+	/**
331
+	 * @param bool   $confirm_msg
332
+	 * @param string $op
333
+	 */
334
+	public function handleObjectDeletionFromUserSide($confirm_msg = false, $op = 'del')
335
+	{
336
+		global $smart_previous_page, $xoopsTpl;
337
+
338
+		$objectid = isset($_REQUEST[$this->handler->keyName]) ? (int)$_REQUEST[$this->handler->keyName] : 0;
339
+		$smartObj = $this->handler->get($objectid);
340
+
341
+		if ($smartObj->isNew()) {
342
+			redirect_header('javascript:history.go(-1)', 3, _CO_SOBJECT_NOT_SELECTED);
343
+		}
344
+
345
+		$confirm = isset($_POST['confirm']) ? $_POST['confirm'] : 0;
346
+		if ($confirm) {
347
+			if (!$this->handler->delete($smartObj)) {
348
+				redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_ERROR . $smartObj->getHtmlErrors());
349
+				exit;
350
+			}
351
+
352
+			redirect_header($_POST['redirect_page'], 3, _CO_SOBJECT_DELETE_SUCCESS);
353
+		} else {
354
+			// no confirm: show deletion condition
355
+			if (!$confirm_msg) {
356
+				$confirm_msg = _CO_SOBJECT_DELETE_CONFIRM;
357
+			}
358
+
359
+			ob_start();
360
+			xoops_confirm(array('op' => $op, $this->handler->keyName => $smartObj->getVar($this->handler->keyName), 'confirm' => 1, 'redirect_page' => $smart_previous_page), xoops_getenv('PHP_SELF'), sprintf($confirm_msg, $smartObj->getVar($this->handler->identifierName)), _CO_SOBJECT_DELETE);
361
+			$smartobjectDeleteConfirm = ob_get_clean();
362
+			$xoopsTpl->assign('smartobject_delete_confirm', $smartobjectDeleteConfirm);
363
+		}
364
+	}
365
+
366
+	/**
367
+	 * Retreive the object admin side link for a {@link SmartObjectSingleView} page
368
+	 *
369
+	 * @param  object $smartObj reference to the object from which we want the user side link
370
+	 * @param  bool   $onlyUrl  wether or not to return a simple URL or a full <a> link
371
+	 * @param  bool   $withimage
372
+	 * @return string admin side link to the object
373
+	 */
374
+	public function getAdminViewItemLink($smartObj, $onlyUrl = false, $withimage = false)
375
+	{
376
+		$ret = $this->handler->_moduleUrl . 'admin/' . $this->handler->_page . '?op=view&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
377
+		if ($onlyUrl) {
378
+			return $ret;
379
+		} elseif ($withimage) {
380
+			return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "viewmag.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_ADMIN_VIEW . "'  title='" . _CO_SOBJECT_ADMIN_VIEW . "'/></a>";
381
+		}
382
+
383
+		return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
384
+	}
385
+
386
+	/**
387
+	 * Retreive the object user side link
388
+	 *
389
+	 * @param  object $smartObj reference to the object from which we want the user side link
390
+	 * @param  bool   $onlyUrl  wether or not to return a simple URL or a full <a> link
391
+	 * @return string user side link to the object
392
+	 */
393
+	public function getItemLink(&$smartObj, $onlyUrl = false)
394
+	{
395
+		$seoMode       = smart_getModuleModeSEO($this->handler->_moduleName);
396
+		$seoModuleName = smart_getModuleNameForSEO($this->handler->_moduleName);
397
+
398
+		/**
399
+		 * $seoIncludeId feature is not finished yet, so let's put it always to true
400
+		 */
401
+		//$seoIncludeId = smart_getModuleIncludeIdSEO($this->handler->_moduleName);
402
+		$seoIncludeId = true;
403
+
404
+		if ($seoMode === 'rewrite') {
405
+			$ret = XOOPS_URL . '/' . $seoModuleName . '.' . $this->handler->_itemname . ($seoIncludeId ? '.' . $smartObj->getVar($this->handler->keyName) : '') . '/' . $smartObj->getVar('short_url') . '.html';
406
+		} elseif ($seoMode === 'pathinfo') {
407
+			$ret = SMARTOBJECT_URL . 'seo.php/' . $seoModuleName . '.' . $this->handler->_itemname . ($seoIncludeId ? '.' . $smartObj->getVar($this->handler->keyName) : '') . '/' . $smartObj->getVar('short_url') . '.html';
408
+		} else {
409
+			$ret = $this->handler->_moduleUrl . $this->handler->_page . '?' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
410
+		}
411
+
412
+		if (!$onlyUrl) {
413
+			$ret = "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
414
+		}
415
+
416
+		return $ret;
417
+	}
418
+
419
+	/**
420
+	 * @param       $smartObj
421
+	 * @param  bool $onlyUrl
422
+	 * @param  bool $withimage
423
+	 * @return string
424
+	 */
425
+	public function getEditLanguageLink($smartObj, $onlyUrl = false, $withimage = true)
426
+	{
427
+		$ret = $this->handler->_moduleUrl . 'admin/' . $this->handler->_page . '?op=mod&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName) . '&language=' . $smartObj->getVar('language');
428
+		if ($onlyUrl) {
429
+			return $ret;
430
+		} elseif ($withimage) {
431
+			return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "wizard.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_LANGUAGE_MODIFY . "'  title='" . _CO_SOBJECT_LANGUAGE_MODIFY . "'/></a>";
432
+		}
433
+
434
+		return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
435
+	}
436
+
437
+	/**
438
+	 * @param       $smartObj
439
+	 * @param  bool $onlyUrl
440
+	 * @param  bool $withimage
441
+	 * @param  bool $userSide
442
+	 * @return string
443
+	 */
444
+	public function getEditItemLink($smartObj, $onlyUrl = false, $withimage = true, $userSide = false)
445
+	{
446
+		$admin_side = $userSide ? '' : 'admin/';
447
+		$ret        = $this->handler->_moduleUrl . $admin_side . $this->handler->_page . '?op=mod&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
448
+		if ($onlyUrl) {
449
+			return $ret;
450
+		} elseif ($withimage) {
451
+			return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "edit.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_MODIFY . "'  title='" . _CO_SOBJECT_MODIFY . "'/></a>";
452
+		}
453
+
454
+		return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
455
+	}
456
+
457
+	/**
458
+	 * @param       $smartObj
459
+	 * @param  bool $onlyUrl
460
+	 * @param  bool $withimage
461
+	 * @param  bool $userSide
462
+	 * @return string
463
+	 */
464
+	public function getDeleteItemLink($smartObj, $onlyUrl = false, $withimage = true, $userSide = false)
465
+	{
466
+		$admin_side = $userSide ? '' : 'admin/';
467
+		$ret        = $this->handler->_moduleUrl . $admin_side . $this->handler->_page . '?op=del&' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
468
+		if ($onlyUrl) {
469
+			return $ret;
470
+		} elseif ($withimage) {
471
+			return "<a href='" . $ret . "'><img src='" . SMARTOBJECT_IMAGES_ACTIONS_URL . "editdelete.png' style='vertical-align: middle;' alt='" . _CO_SOBJECT_DELETE . "'  title='" . _CO_SOBJECT_DELETE . "'/></a>";
472
+		}
473
+
474
+		return "<a href='" . $ret . "'>" . $smartObj->getVar($this->handler->identifierName) . '</a>';
475
+	}
476
+
477
+	/**
478
+	 * @param $smartObj
479
+	 * @return string
480
+	 */
481
+	public function getPrintAndMailLink($smartObj)
482
+	{
483
+		global $xoopsConfig;
484
+
485
+		$printlink = $this->handler->_moduleUrl . 'print.php?' . $this->handler->keyName . '=' . $smartObj->getVar($this->handler->keyName);
486
+		$js        = "javascript:openWithSelfMain('" . $printlink . "', 'smartpopup', 700, 519);";
487
+		$printlink = '<a href="' . $js . '"><img  src="' . SMARTOBJECT_IMAGES_ACTIONS_URL . 'fileprint.png" alt="" style="vertical-align: middle;"/></a>';
488
+
489
+		$smartModule = smart_getModuleInfo($smartObj->handler->_moduleName);
490
+		$link        = smart_getCurrentPage();
491
+		$mid         = $smartModule->getVar('mid');
492
+		$friendlink  = "<a href=\"javascript:openWithSelfMain('" . SMARTOBJECT_URL . 'sendlink.php?link=' . $link . '&amp;mid=' . $mid . "', ',',',',',','sendmessage', 674, 500);\"><img src=\"" . SMARTOBJECT_IMAGES_ACTIONS_URL . "mail_send.png\"  alt=\"" . _CO_SOBJECT_EMAIL . "\" title=\"" . _CO_SOBJECT_EMAIL . "\" style=\"vertical-align: middle;\"/></a>";
493
+
494
+		$ret = '<span id="smartobject_print_button">' . $printlink . '&nbsp;</span>' . '<span id="smartobject_mail_button">' . $friendlink . '</span>';
495
+
496
+		return $ret;
497
+	}
498
+
499
+	/**
500
+	 * @return string
501
+	 */
502
+	public function getModuleItemString()
503
+	{
504
+		$ret = $this->handler->_moduleName . '_' . $this->handler->_itemname;
505
+
506
+		return $ret;
507
+	}
508 508
 }
Please login to merge, or discard this patch.
class/smartobjectlink.php 1 patch
Indentation   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -35,154 +35,154 @@  discard block
 block discarded – undo
35 35
  */
36 36
 class SmartobjectLink extends SmartObject
37 37
 {
38
-    /**
39
-     * SmartobjectLink constructor.
40
-     */
41
-    public function __construct()
42
-    {
43
-        $this->initVar('linkid', XOBJ_DTYPE_INT, '', true);
44
-        $this->initVar('date', XOBJ_DTYPE_INT, 0, false, null, '', false, _CO_SOBJECT_LINK_DATE, '', true, true, false);
45
-        $this->initVar('from_uid', XOBJ_DTYPE_INT, '', false, null, '', false, _CO_SOBJECT_LINK_FROM_UID, _CO_SOBJECT_LINK_FROM_UID_DSC);
46
-        $this->initVar('from_email', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_FROM_EMAIL, _CO_SOBJECT_LINK_FROM_EMAIL_DSC, true);
47
-        $this->initVar('from_name', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_FROM_NAME, _CO_SOBJECT_LINK_FROM_NAME_DSC, true);
48
-        $this->initVar('to_uid', XOBJ_DTYPE_INT, '', false, null, '', false, _CO_SOBJECT_LINK_TO_UID, _CO_SOBJECT_LINK_TO_UID_DSC);
49
-        $this->initVar('to_email', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_TO_EMAIL, _CO_SOBJECT_LINK_TO_EMAIL_DSC, true);
50
-        $this->initVar('to_name', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_TO_NAME, _CO_SOBJECT_LINK_TO_NAME_DSC, true);
51
-        $this->initVar('link', XOBJ_DTYPE_TXTBOX, '', false, 255, '', false, _CO_SOBJECT_LINK_LINK, _CO_SOBJECT_LINK_LINK_DSC, true);
52
-        $this->initVar('subject', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_SUBJECT, _CO_SOBJECT_LINK_SUBJECT_DSC, true);
53
-        $this->initVar('body', XOBJ_DTYPE_TXTAREA, '', true, null, '', false, _CO_SOBJECT_LINK_BODY, _CO_SOBJECT_LINK_BODY_DSC);
54
-        $this->initVar('mid', XOBJ_DTYPE_INT, '', false, null, '', false, _CO_SOBJECT_LINK_MID, _CO_SOBJECT_LINK_MID_DSC);
55
-        $this->initVar('mid_name', XOBJ_DTYPE_TXTBOX, '', false, 255, '', false, _CO_SOBJECT_LINK_MID_NAME, _CO_SOBJECT_LINK_MID_NAME_DSC, true);
56
-    }
57
-
58
-    /**
59
-     * returns a specific variable for the object in a proper format
60
-     *
61
-     * @access public
62
-     * @param  string $key    key of the object's variable to be returned
63
-     * @param  string $format format to use for the output
64
-     * @return mixed  formatted value of the variable
65
-     */
66
-    public function getVar($key, $format = 's')
67
-    {
68
-        if ($format === 's' && in_array($key, array('from_uid', 'to_uid', 'date', 'link'))) {
69
-            //            return call_user_func(array($this, $key));
70
-            return $this->{$key}();
71
-        }
72
-
73
-        return parent::getVar($key, $format);
74
-    }
75
-
76
-    /**
77
-     * @return string
78
-     */
79
-    public function from_uid()
80
-    {
81
-        $ret = smart_getLinkedUnameFromId($this->getVar('from_uid', 'e'), 1, null, true);
82
-
83
-        return $ret;
84
-    }
85
-
86
-    /**
87
-     * @param  bool $withContact
88
-     * @return string
89
-     */
90
-    public function to_uid($withContact = false)
91
-    {
92
-        $ret = smart_getLinkedUnameFromId($this->getVar('to_uid', 'e'), 1, null, true);
93
-
94
-        return $ret;
95
-    }
96
-
97
-    /**
98
-     * @return string
99
-     */
100
-    public function date()
101
-    {
102
-        $ret = formatTimestamp($this->getVar('date', 'e'));
103
-
104
-        return $ret;
105
-    }
106
-
107
-    /**
108
-     * @param  bool $full
109
-     * @return mixed|string
110
-     */
111
-    public function link($full = false)
112
-    {
113
-        $ret = $this->getVar('link', 'e');
114
-        if ($full) {
115
-            $myts = MyTextSanitizer::getInstance();
116
-            $ret  = $myts->displayTarea($ret);
117
-
118
-            return $ret;
119
-        } else {
120
-            $ret = '<a href="' . $ret . '" alt="' . $this->getVar('link', 'e') . '" title="' . $this->getVar('link', 'e') . '">' . _AM_SOBJECT_SENT_LINKS_GOTO . '</a>';
121
-
122
-            return $ret;
123
-        }
124
-    }
125
-
126
-    /**
127
-     * @return string
128
-     */
129
-    public function getViewItemLink()
130
-    {
131
-        $ret = '<a href="' . SMARTOBJECT_URL . 'admin/link.php?op=view&linkid=' . $this->getVar('linkid') . '"><img src="' . SMARTOBJECT_IMAGES_ACTIONS_URL . 'mail_find.png" alt="' . _AM_SOBJECT_SENT_LINK_VIEW . '" title="' . _AM_SOBJECT_SENT_LINK_VIEW . '" /></a>';
132
-
133
-        return $ret;
134
-    }
135
-
136
-    /**
137
-     * @return string
138
-     */
139
-    public function getFromInfo()
140
-    {
141
-        // check if from_uid represent a user
142
-
143
-        if ($this->getVar('from_uid')) {
144
-            $user = smart_getLinkedUnameFromId($this->getVar('from_uid'));
145
-            if ($user == $GLOBALS['xoopsConfig']['anonymous']) {
146
-                $user = '<a href="mailto:' . $this->getVar('from_email') . '">' . $this->getVar('from_email') . '</a>';
147
-            }
148
-        } else {
149
-            $user = '<a href="mailto:' . $this->getVar('from_email') . '">' . $this->getVar('from_email') . '</a>';
150
-        }
151
-
152
-        return $user;
153
-    }
154
-
155
-    /**
156
-     * @return array
157
-     */
158
-    public function toArray()
159
-    {
160
-        $ret             = parent::toArray();
161
-        $ret['fromInfo'] = $this->getFromInfo();
162
-        $ret['toInfo']   = $this->getToInfo();
163
-        $ret['fullLink'] = $this->link(true);
164
-
165
-        return $ret;
166
-    }
167
-
168
-    /**
169
-     * @return string
170
-     */
171
-    public function getToInfo()
172
-    {
173
-        // check if from_uid represent a user
174
-
175
-        if ($this->getVar('to_uid')) {
176
-            $user = smart_getLinkedUnameFromId($this->getVar('to_uid'));
177
-            if ($user == $GLOBALS['xoopsConfig']['anonymous']) {
178
-                $user = '<a href="mailto:' . $this->getVar('to_email') . '">' . $this->getVar('to_email') . '</a>';
179
-            }
180
-        } else {
181
-            $user = '<a href="mailto:' . $this->getVar('to_email') . '">' . $this->getVar('to_email') . '</a>';
182
-        }
183
-
184
-        return $user;
185
-    }
38
+	/**
39
+	 * SmartobjectLink constructor.
40
+	 */
41
+	public function __construct()
42
+	{
43
+		$this->initVar('linkid', XOBJ_DTYPE_INT, '', true);
44
+		$this->initVar('date', XOBJ_DTYPE_INT, 0, false, null, '', false, _CO_SOBJECT_LINK_DATE, '', true, true, false);
45
+		$this->initVar('from_uid', XOBJ_DTYPE_INT, '', false, null, '', false, _CO_SOBJECT_LINK_FROM_UID, _CO_SOBJECT_LINK_FROM_UID_DSC);
46
+		$this->initVar('from_email', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_FROM_EMAIL, _CO_SOBJECT_LINK_FROM_EMAIL_DSC, true);
47
+		$this->initVar('from_name', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_FROM_NAME, _CO_SOBJECT_LINK_FROM_NAME_DSC, true);
48
+		$this->initVar('to_uid', XOBJ_DTYPE_INT, '', false, null, '', false, _CO_SOBJECT_LINK_TO_UID, _CO_SOBJECT_LINK_TO_UID_DSC);
49
+		$this->initVar('to_email', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_TO_EMAIL, _CO_SOBJECT_LINK_TO_EMAIL_DSC, true);
50
+		$this->initVar('to_name', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_TO_NAME, _CO_SOBJECT_LINK_TO_NAME_DSC, true);
51
+		$this->initVar('link', XOBJ_DTYPE_TXTBOX, '', false, 255, '', false, _CO_SOBJECT_LINK_LINK, _CO_SOBJECT_LINK_LINK_DSC, true);
52
+		$this->initVar('subject', XOBJ_DTYPE_TXTBOX, '', true, 255, '', false, _CO_SOBJECT_LINK_SUBJECT, _CO_SOBJECT_LINK_SUBJECT_DSC, true);
53
+		$this->initVar('body', XOBJ_DTYPE_TXTAREA, '', true, null, '', false, _CO_SOBJECT_LINK_BODY, _CO_SOBJECT_LINK_BODY_DSC);
54
+		$this->initVar('mid', XOBJ_DTYPE_INT, '', false, null, '', false, _CO_SOBJECT_LINK_MID, _CO_SOBJECT_LINK_MID_DSC);
55
+		$this->initVar('mid_name', XOBJ_DTYPE_TXTBOX, '', false, 255, '', false, _CO_SOBJECT_LINK_MID_NAME, _CO_SOBJECT_LINK_MID_NAME_DSC, true);
56
+	}
57
+
58
+	/**
59
+	 * returns a specific variable for the object in a proper format
60
+	 *
61
+	 * @access public
62
+	 * @param  string $key    key of the object's variable to be returned
63
+	 * @param  string $format format to use for the output
64
+	 * @return mixed  formatted value of the variable
65
+	 */
66
+	public function getVar($key, $format = 's')
67
+	{
68
+		if ($format === 's' && in_array($key, array('from_uid', 'to_uid', 'date', 'link'))) {
69
+			//            return call_user_func(array($this, $key));
70
+			return $this->{$key}();
71
+		}
72
+
73
+		return parent::getVar($key, $format);
74
+	}
75
+
76
+	/**
77
+	 * @return string
78
+	 */
79
+	public function from_uid()
80
+	{
81
+		$ret = smart_getLinkedUnameFromId($this->getVar('from_uid', 'e'), 1, null, true);
82
+
83
+		return $ret;
84
+	}
85
+
86
+	/**
87
+	 * @param  bool $withContact
88
+	 * @return string
89
+	 */
90
+	public function to_uid($withContact = false)
91
+	{
92
+		$ret = smart_getLinkedUnameFromId($this->getVar('to_uid', 'e'), 1, null, true);
93
+
94
+		return $ret;
95
+	}
96
+
97
+	/**
98
+	 * @return string
99
+	 */
100
+	public function date()
101
+	{
102
+		$ret = formatTimestamp($this->getVar('date', 'e'));
103
+
104
+		return $ret;
105
+	}
106
+
107
+	/**
108
+	 * @param  bool $full
109
+	 * @return mixed|string
110
+	 */
111
+	public function link($full = false)
112
+	{
113
+		$ret = $this->getVar('link', 'e');
114
+		if ($full) {
115
+			$myts = MyTextSanitizer::getInstance();
116
+			$ret  = $myts->displayTarea($ret);
117
+
118
+			return $ret;
119
+		} else {
120
+			$ret = '<a href="' . $ret . '" alt="' . $this->getVar('link', 'e') . '" title="' . $this->getVar('link', 'e') . '">' . _AM_SOBJECT_SENT_LINKS_GOTO . '</a>';
121
+
122
+			return $ret;
123
+		}
124
+	}
125
+
126
+	/**
127
+	 * @return string
128
+	 */
129
+	public function getViewItemLink()
130
+	{
131
+		$ret = '<a href="' . SMARTOBJECT_URL . 'admin/link.php?op=view&linkid=' . $this->getVar('linkid') . '"><img src="' . SMARTOBJECT_IMAGES_ACTIONS_URL . 'mail_find.png" alt="' . _AM_SOBJECT_SENT_LINK_VIEW . '" title="' . _AM_SOBJECT_SENT_LINK_VIEW . '" /></a>';
132
+
133
+		return $ret;
134
+	}
135
+
136
+	/**
137
+	 * @return string
138
+	 */
139
+	public function getFromInfo()
140
+	{
141
+		// check if from_uid represent a user
142
+
143
+		if ($this->getVar('from_uid')) {
144
+			$user = smart_getLinkedUnameFromId($this->getVar('from_uid'));
145
+			if ($user == $GLOBALS['xoopsConfig']['anonymous']) {
146
+				$user = '<a href="mailto:' . $this->getVar('from_email') . '">' . $this->getVar('from_email') . '</a>';
147
+			}
148
+		} else {
149
+			$user = '<a href="mailto:' . $this->getVar('from_email') . '">' . $this->getVar('from_email') . '</a>';
150
+		}
151
+
152
+		return $user;
153
+	}
154
+
155
+	/**
156
+	 * @return array
157
+	 */
158
+	public function toArray()
159
+	{
160
+		$ret             = parent::toArray();
161
+		$ret['fromInfo'] = $this->getFromInfo();
162
+		$ret['toInfo']   = $this->getToInfo();
163
+		$ret['fullLink'] = $this->link(true);
164
+
165
+		return $ret;
166
+	}
167
+
168
+	/**
169
+	 * @return string
170
+	 */
171
+	public function getToInfo()
172
+	{
173
+		// check if from_uid represent a user
174
+
175
+		if ($this->getVar('to_uid')) {
176
+			$user = smart_getLinkedUnameFromId($this->getVar('to_uid'));
177
+			if ($user == $GLOBALS['xoopsConfig']['anonymous']) {
178
+				$user = '<a href="mailto:' . $this->getVar('to_email') . '">' . $this->getVar('to_email') . '</a>';
179
+			}
180
+		} else {
181
+			$user = '<a href="mailto:' . $this->getVar('to_email') . '">' . $this->getVar('to_email') . '</a>';
182
+		}
183
+
184
+		return $user;
185
+	}
186 186
 }
187 187
 
188 188
 /**
@@ -190,12 +190,12 @@  discard block
 block discarded – undo
190 190
  */
191 191
 class SmartobjectLinkHandler extends SmartPersistableObjectHandler
192 192
 {
193
-    /**
194
-     * SmartobjectLinkHandler constructor.
195
-     * @param object|XoopsDatabase $db
196
-     */
197
-    public function __construct($db)
198
-    {
199
-        parent::__construct($db, 'link', 'linkid', 'subject', 'body', 'smartobject');
200
-    }
193
+	/**
194
+	 * SmartobjectLinkHandler constructor.
195
+	 * @param object|XoopsDatabase $db
196
+	 */
197
+	public function __construct($db)
198
+	{
199
+		parent::__construct($db, 'link', 'linkid', 'subject', 'body', 'smartobject');
200
+	}
201 201
 }
Please login to merge, or discard this patch.
class/smarttip.php 1 patch
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -10,45 +10,45 @@
 block discarded – undo
10 10
 
11 11
 class SmartTip
12 12
 {
13
-    public $id;
14
-    public $caption;
15
-    public $message;
16
-    public $visible;
17
-    public $_tpl;
13
+	public $id;
14
+	public $caption;
15
+	public $message;
16
+	public $visible;
17
+	public $_tpl;
18 18
 
19
-    /**
20
-     * SmartTip constructor.
21
-     * @param      $id
22
-     * @param      $caption
23
-     * @param      $message
24
-     * @param bool $visible
25
-     */
26
-    public function __construct($id, $caption, $message, $visible = false)
27
-    {
28
-        $this->id      = $id;
29
-        $this->caption = $caption;
30
-        $this->message = $message;
31
-        $this->visible = $visible;
32
-        $this->_tpl    = new XoopsTpl();
33
-    }
19
+	/**
20
+	 * SmartTip constructor.
21
+	 * @param      $id
22
+	 * @param      $caption
23
+	 * @param      $message
24
+	 * @param bool $visible
25
+	 */
26
+	public function __construct($id, $caption, $message, $visible = false)
27
+	{
28
+		$this->id      = $id;
29
+		$this->caption = $caption;
30
+		$this->message = $message;
31
+		$this->visible = $visible;
32
+		$this->_tpl    = new XoopsTpl();
33
+	}
34 34
 
35
-    /**
36
-     * @param  bool $outputNow
37
-     * @return mixed|string|void
38
-     */
39
-    public function render($outputNow = true)
40
-    {
41
-        $aTip = array(
42
-            'id'      => $this->id,
43
-            'caption' => $this->caption,
44
-            'message' => $this->message,
45
-            'visible' => $this->visible ? 'block' : 'none'
46
-        );
47
-        $this->_tpl->assign('tip', $aTip);
48
-        if ($outputNow) {
49
-            $this->_tpl->display('db:smartobject_tip.tpl');
50
-        } else {
51
-            return $this->_tpl->fetch('db:smartobject_tip.tpl');
52
-        }
53
-    }
35
+	/**
36
+	 * @param  bool $outputNow
37
+	 * @return mixed|string|void
38
+	 */
39
+	public function render($outputNow = true)
40
+	{
41
+		$aTip = array(
42
+			'id'      => $this->id,
43
+			'caption' => $this->caption,
44
+			'message' => $this->message,
45
+			'visible' => $this->visible ? 'block' : 'none'
46
+		);
47
+		$this->_tpl->assign('tip', $aTip);
48
+		if ($outputNow) {
49
+			$this->_tpl->display('db:smartobject_tip.tpl');
50
+		} else {
51
+			return $this->_tpl->fetch('db:smartobject_tip.tpl');
52
+		}
53
+	}
54 54
 }
Please login to merge, or discard this patch.
class/smartobjectabout.php 1 patch
Indentation   +160 added lines, -160 removed lines patch added patch discarded remove patch
@@ -19,164 +19,164 @@
 block discarded – undo
19 19
  */
20 20
 class SmartobjectAbout
21 21
 {
22
-    public $_lang_aboutTitle;
23
-    public $_lang_author_info;
24
-    public $_lang_developer_lead;
25
-    public $_lang_developer_contributor;
26
-    public $_lang_developer_website;
27
-    public $_lang_developer_email;
28
-    public $_lang_developer_credits;
29
-    public $_lang_module_info;
30
-    public $_lang_module_status;
31
-    public $_lang_module_release_date;
32
-    public $_lang_module_demo;
33
-    public $_lang_module_support;
34
-    public $_lang_module_bug;
35
-    public $_lang_module_submit_bug;
36
-    public $_lang_module_feature;
37
-    public $_lang_module_submit_feature;
38
-    public $_lang_module_disclaimer;
39
-    public $_lang_author_word;
40
-    public $_lang_version_history;
41
-    public $_lang_by;
42
-    public $_tpl;
43
-
44
-    /**
45
-     * SmartobjectAbout constructor.
46
-     * @param string $aboutTitle
47
-     */
48
-    public function __construct($aboutTitle = 'About')
49
-    {
50
-        global $xoopsModule, $xoopsConfig;
51
-
52
-        $fileName = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/modinfo.php';
53
-        if (file_exists($fileName)) {
54
-            include_once $fileName;
55
-        } else {
56
-            include_once XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/english/modinfo.php';
57
-        }
58
-        $this->_aboutTitle = $aboutTitle;
59
-
60
-        $this->_lang_developer_contributor = _CO_SOBJECT_DEVELOPER_CONTRIBUTOR;
61
-        $this->_lang_developer_website     = _CO_SOBJECT_DEVELOPER_WEBSITE;
62
-        $this->_lang_developer_email       = _CO_SOBJECT_DEVELOPER_EMAIL;
63
-        $this->_lang_developer_credits     = _CO_SOBJECT_DEVELOPER_CREDITS;
64
-        $this->_lang_module_info           = _CO_SOBJECT_MODULE_INFO;
65
-        $this->_lang_module_status         = _CO_SOBJECT_MODULE_STATUS;
66
-        $this->_lang_module_release_date   = _CO_SOBJECT_MODULE_RELEASE_DATE;
67
-        $this->_lang_module_demo           = _CO_SOBJECT_MODULE_DEMO;
68
-        $this->_lang_module_support        = _CO_SOBJECT_MODULE_SUPPORT;
69
-        $this->_lang_module_bug            = _CO_SOBJECT_MODULE_BUG;
70
-        $this->_lang_module_submit_bug     = _CO_SOBJECT_MODULE_SUBMIT_BUG;
71
-        $this->_lang_module_feature        = _CO_SOBJECT_MODULE_FEATURE;
72
-        $this->_lang_module_submit_feature = _CO_SOBJECT_MODULE_SUBMIT_FEATURE;
73
-        $this->_lang_module_disclaimer     = _CO_SOBJECT_MODULE_DISCLAIMER;
74
-        $this->_lang_author_word           = _CO_SOBJECT_AUTHOR_WORD;
75
-        $this->_lang_version_history       = _CO_SOBJECT_VERSION_HISTORY;
76
-    }
77
-
78
-    /**
79
-     * @param $value
80
-     * @return mixed
81
-     */
82
-    public function sanitize($value)
83
-    {
84
-        $myts = MyTextSanitizer::getInstance();
85
-
86
-        return $myts->displayTarea($value, 1);
87
-    }
88
-
89
-    public function render()
90
-    {
91
-        /**
92
-         * @todo move the output to a template
93
-         * @todo make the output XHTML compliant
94
-         */
95
-
96
-        $myts = MyTextSanitizer::getInstance();
97
-
98
-        global $xoopsModule;
99
-
100
-        smart_xoops_cp_header();
101
-
102
-        $moduleHandler = xoops_getHandler('module');
103
-        $versioninfo    = &$moduleHandler->get($xoopsModule->getVar('mid'));
104
-
105
-        //smart_adminMenu(-1, $this->_aboutTitle . " " . $versioninfo->getInfo('name'));
106
-
107
-        include_once XOOPS_ROOT_PATH . '/class/template.php';
108
-
109
-        // ---
110
-        // 2012-01-01 PHP 5.3: Assigning the return value of new by reference is now deprecated.
111
-        //      $this->_tpl =& new XoopsTpl();
112
-        $this->_tpl = new XoopsTpl();
113
-        // ---
114
-
115
-        $this->_tpl->assign('module_url', XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/');
116
-        $this->_tpl->assign('module_image', $versioninfo->getInfo('image'));
117
-        $this->_tpl->assign('module_name', $versioninfo->getInfo('name'));
118
-        $this->_tpl->assign('module_version', $versioninfo->getInfo('version'));
119
-        $this->_tpl->assign('module_status_version', $versioninfo->getInfo('status_version'));
120
-
121
-        // Left headings...
122
-        if ($versioninfo->getInfo('author_realname') != '') {
123
-            $author_name = $versioninfo->getInfo('author') . ' (' . $versioninfo->getInfo('author_realname') . ')';
124
-        } else {
125
-            $author_name = $versioninfo->getInfo('author');
126
-        }
127
-        $this->_tpl->assign('module_author_name', $author_name);
128
-
129
-        $this->_tpl->assign('module_license', $versioninfo->getInfo('license'));
130
-
131
-        $this->_tpl->assign('module_credits', $versioninfo->getInfo('credits'));
132
-
133
-        // Developers Information
134
-        $this->_tpl->assign('module_developer_lead', $versioninfo->getInfo('developer_lead'));
135
-        $this->_tpl->assign('module_developer_contributor', $versioninfo->getInfo('developer_contributor'));
136
-        $this->_tpl->assign('module_developer_website_url', $versioninfo->getInfo('developer_website_url'));
137
-        $this->_tpl->assign('module_developer_website_name', $versioninfo->getInfo('developer_website_name'));
138
-        $this->_tpl->assign('module_developer_email', $versioninfo->getInfo('developer_email'));
139
-
140
-        $people = $versioninfo->getInfo('people');
141
-        if ($people) {
142
-            $this->_tpl->assign('module_people_developers', isset($people['developers']) ? array_map(array($this, 'sanitize'), $people['developers']) : false);
143
-            $this->_tpl->assign('module_people_testers', isset($people['testers']) ? array_map(array($this, 'sanitize'), $people['testers']) : false);
144
-            $this->_tpl->assign('module_people_translators', isset($people['translators']) ? array_map(array($this, 'sanitize'), $people['translators']) : false);
145
-            $this->_tpl->assign('module_people_documenters', isset($people['documenters']) ? array_map(array($this, 'sanitize'), $people['documenters']) : false);
146
-            $this->_tpl->assign('module_people_other', isset($people['other']) ? array_map(array($this, 'sanitize'), $people['other']) : false);
147
-        }
148
-        //$this->_tpl->assign('module_developers', $versioninfo->getInfo('developer_email'));
149
-
150
-        // Module Development information
151
-        $this->_tpl->assign('module_date', $versioninfo->getInfo('date'));
152
-        $this->_tpl->assign('module_status', $versioninfo->getInfo('status'));
153
-        $this->_tpl->assign('module_demo_site_url', $versioninfo->getInfo('demo_site_url'));
154
-        $this->_tpl->assign('module_demo_site_name', $versioninfo->getInfo('demo_site_name'));
155
-        $this->_tpl->assign('module_support_site_url', $versioninfo->getInfo('support_site_url'));
156
-        $this->_tpl->assign('module_support_site_name', $versioninfo->getInfo('support_site_name'));
157
-        $this->_tpl->assign('module_submit_bug', $versioninfo->getInfo('submit_bug'));
158
-        $this->_tpl->assign('module_submit_feature', $versioninfo->getInfo('submit_feature'));
159
-
160
-        // Warning
161
-        $this->_tpl->assign('module_warning', $this->sanitize($versioninfo->getInfo('warning')));
162
-
163
-        // Author's note
164
-        $this->_tpl->assign('module_author_word', $versioninfo->getInfo('author_word'));
165
-
166
-        // For changelog thanks to 3Dev
167
-        global $xoopsModule;
168
-        $filename = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/changelog.txt';
169
-        if (is_file($filename)) {
170
-            $filesize = filesize($filename);
171
-            $handle   = fopen($filename, 'r');
172
-            $this->_tpl->assign('module_version_history', $myts->displayTarea(fread($handle, $filesize), true));
173
-            fclose($handle);
174
-        }
175
-
176
-        $this->_tpl->display('db:smartobject_about.tpl');
177
-
178
-        smart_modFooter();
179
-
180
-        xoops_cp_footer();
181
-    }
22
+	public $_lang_aboutTitle;
23
+	public $_lang_author_info;
24
+	public $_lang_developer_lead;
25
+	public $_lang_developer_contributor;
26
+	public $_lang_developer_website;
27
+	public $_lang_developer_email;
28
+	public $_lang_developer_credits;
29
+	public $_lang_module_info;
30
+	public $_lang_module_status;
31
+	public $_lang_module_release_date;
32
+	public $_lang_module_demo;
33
+	public $_lang_module_support;
34
+	public $_lang_module_bug;
35
+	public $_lang_module_submit_bug;
36
+	public $_lang_module_feature;
37
+	public $_lang_module_submit_feature;
38
+	public $_lang_module_disclaimer;
39
+	public $_lang_author_word;
40
+	public $_lang_version_history;
41
+	public $_lang_by;
42
+	public $_tpl;
43
+
44
+	/**
45
+	 * SmartobjectAbout constructor.
46
+	 * @param string $aboutTitle
47
+	 */
48
+	public function __construct($aboutTitle = 'About')
49
+	{
50
+		global $xoopsModule, $xoopsConfig;
51
+
52
+		$fileName = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/modinfo.php';
53
+		if (file_exists($fileName)) {
54
+			include_once $fileName;
55
+		} else {
56
+			include_once XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/english/modinfo.php';
57
+		}
58
+		$this->_aboutTitle = $aboutTitle;
59
+
60
+		$this->_lang_developer_contributor = _CO_SOBJECT_DEVELOPER_CONTRIBUTOR;
61
+		$this->_lang_developer_website     = _CO_SOBJECT_DEVELOPER_WEBSITE;
62
+		$this->_lang_developer_email       = _CO_SOBJECT_DEVELOPER_EMAIL;
63
+		$this->_lang_developer_credits     = _CO_SOBJECT_DEVELOPER_CREDITS;
64
+		$this->_lang_module_info           = _CO_SOBJECT_MODULE_INFO;
65
+		$this->_lang_module_status         = _CO_SOBJECT_MODULE_STATUS;
66
+		$this->_lang_module_release_date   = _CO_SOBJECT_MODULE_RELEASE_DATE;
67
+		$this->_lang_module_demo           = _CO_SOBJECT_MODULE_DEMO;
68
+		$this->_lang_module_support        = _CO_SOBJECT_MODULE_SUPPORT;
69
+		$this->_lang_module_bug            = _CO_SOBJECT_MODULE_BUG;
70
+		$this->_lang_module_submit_bug     = _CO_SOBJECT_MODULE_SUBMIT_BUG;
71
+		$this->_lang_module_feature        = _CO_SOBJECT_MODULE_FEATURE;
72
+		$this->_lang_module_submit_feature = _CO_SOBJECT_MODULE_SUBMIT_FEATURE;
73
+		$this->_lang_module_disclaimer     = _CO_SOBJECT_MODULE_DISCLAIMER;
74
+		$this->_lang_author_word           = _CO_SOBJECT_AUTHOR_WORD;
75
+		$this->_lang_version_history       = _CO_SOBJECT_VERSION_HISTORY;
76
+	}
77
+
78
+	/**
79
+	 * @param $value
80
+	 * @return mixed
81
+	 */
82
+	public function sanitize($value)
83
+	{
84
+		$myts = MyTextSanitizer::getInstance();
85
+
86
+		return $myts->displayTarea($value, 1);
87
+	}
88
+
89
+	public function render()
90
+	{
91
+		/**
92
+		 * @todo move the output to a template
93
+		 * @todo make the output XHTML compliant
94
+		 */
95
+
96
+		$myts = MyTextSanitizer::getInstance();
97
+
98
+		global $xoopsModule;
99
+
100
+		smart_xoops_cp_header();
101
+
102
+		$moduleHandler = xoops_getHandler('module');
103
+		$versioninfo    = &$moduleHandler->get($xoopsModule->getVar('mid'));
104
+
105
+		//smart_adminMenu(-1, $this->_aboutTitle . " " . $versioninfo->getInfo('name'));
106
+
107
+		include_once XOOPS_ROOT_PATH . '/class/template.php';
108
+
109
+		// ---
110
+		// 2012-01-01 PHP 5.3: Assigning the return value of new by reference is now deprecated.
111
+		//      $this->_tpl =& new XoopsTpl();
112
+		$this->_tpl = new XoopsTpl();
113
+		// ---
114
+
115
+		$this->_tpl->assign('module_url', XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/');
116
+		$this->_tpl->assign('module_image', $versioninfo->getInfo('image'));
117
+		$this->_tpl->assign('module_name', $versioninfo->getInfo('name'));
118
+		$this->_tpl->assign('module_version', $versioninfo->getInfo('version'));
119
+		$this->_tpl->assign('module_status_version', $versioninfo->getInfo('status_version'));
120
+
121
+		// Left headings...
122
+		if ($versioninfo->getInfo('author_realname') != '') {
123
+			$author_name = $versioninfo->getInfo('author') . ' (' . $versioninfo->getInfo('author_realname') . ')';
124
+		} else {
125
+			$author_name = $versioninfo->getInfo('author');
126
+		}
127
+		$this->_tpl->assign('module_author_name', $author_name);
128
+
129
+		$this->_tpl->assign('module_license', $versioninfo->getInfo('license'));
130
+
131
+		$this->_tpl->assign('module_credits', $versioninfo->getInfo('credits'));
132
+
133
+		// Developers Information
134
+		$this->_tpl->assign('module_developer_lead', $versioninfo->getInfo('developer_lead'));
135
+		$this->_tpl->assign('module_developer_contributor', $versioninfo->getInfo('developer_contributor'));
136
+		$this->_tpl->assign('module_developer_website_url', $versioninfo->getInfo('developer_website_url'));
137
+		$this->_tpl->assign('module_developer_website_name', $versioninfo->getInfo('developer_website_name'));
138
+		$this->_tpl->assign('module_developer_email', $versioninfo->getInfo('developer_email'));
139
+
140
+		$people = $versioninfo->getInfo('people');
141
+		if ($people) {
142
+			$this->_tpl->assign('module_people_developers', isset($people['developers']) ? array_map(array($this, 'sanitize'), $people['developers']) : false);
143
+			$this->_tpl->assign('module_people_testers', isset($people['testers']) ? array_map(array($this, 'sanitize'), $people['testers']) : false);
144
+			$this->_tpl->assign('module_people_translators', isset($people['translators']) ? array_map(array($this, 'sanitize'), $people['translators']) : false);
145
+			$this->_tpl->assign('module_people_documenters', isset($people['documenters']) ? array_map(array($this, 'sanitize'), $people['documenters']) : false);
146
+			$this->_tpl->assign('module_people_other', isset($people['other']) ? array_map(array($this, 'sanitize'), $people['other']) : false);
147
+		}
148
+		//$this->_tpl->assign('module_developers', $versioninfo->getInfo('developer_email'));
149
+
150
+		// Module Development information
151
+		$this->_tpl->assign('module_date', $versioninfo->getInfo('date'));
152
+		$this->_tpl->assign('module_status', $versioninfo->getInfo('status'));
153
+		$this->_tpl->assign('module_demo_site_url', $versioninfo->getInfo('demo_site_url'));
154
+		$this->_tpl->assign('module_demo_site_name', $versioninfo->getInfo('demo_site_name'));
155
+		$this->_tpl->assign('module_support_site_url', $versioninfo->getInfo('support_site_url'));
156
+		$this->_tpl->assign('module_support_site_name', $versioninfo->getInfo('support_site_name'));
157
+		$this->_tpl->assign('module_submit_bug', $versioninfo->getInfo('submit_bug'));
158
+		$this->_tpl->assign('module_submit_feature', $versioninfo->getInfo('submit_feature'));
159
+
160
+		// Warning
161
+		$this->_tpl->assign('module_warning', $this->sanitize($versioninfo->getInfo('warning')));
162
+
163
+		// Author's note
164
+		$this->_tpl->assign('module_author_word', $versioninfo->getInfo('author_word'));
165
+
166
+		// For changelog thanks to 3Dev
167
+		global $xoopsModule;
168
+		$filename = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/changelog.txt';
169
+		if (is_file($filename)) {
170
+			$filesize = filesize($filename);
171
+			$handle   = fopen($filename, 'r');
172
+			$this->_tpl->assign('module_version_history', $myts->displayTarea(fread($handle, $filesize), true));
173
+			fclose($handle);
174
+		}
175
+
176
+		$this->_tpl->display('db:smartobject_about.tpl');
177
+
178
+		smart_modFooter();
179
+
180
+		xoops_cp_footer();
181
+	}
182 182
 }
Please login to merge, or discard this patch.
class/smartdbupdater.php 1 patch
Indentation   +831 added lines, -831 removed lines patch added patch discarded remove patch
@@ -1,32 +1,32 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 /**
3
- * Contains the classes for updating database tables
4
- *
5
- * @license GNU
6
- * @author  marcan <[email protected]>
7
- * @link    http://www.smartfactory.ca The SmartFactory
8
- * @package SmartObject
9
- */
3
+	 * Contains the classes for updating database tables
4
+	 *
5
+	 * @license GNU
6
+	 * @author  marcan <[email protected]>
7
+	 * @link    http://www.smartfactory.ca The SmartFactory
8
+	 * @package SmartObject
9
+	 */
10 10
 /**
11
- * SmartDbTable class
12
- *
13
- * Information about an individual table
14
- *
15
- * @package SmartObject
16
- * @author  marcan <[email protected]>
17
- * @link    http://www.smartfactory.ca The SmartFactory
18
- */
11
+	 * SmartDbTable class
12
+	 *
13
+	 * Information about an individual table
14
+	 *
15
+	 * @package SmartObject
16
+	 * @author  marcan <[email protected]>
17
+	 * @link    http://www.smartfactory.ca The SmartFactory
18
+	 */
19 19
 // defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
20 20
 if (!defined('SMARTOBJECT_ROOT_PATH')) {
21
-    include_once(XOOPS_ROOT_PATH . '/modules/smartobject/include/common.php');
21
+	include_once(XOOPS_ROOT_PATH . '/modules/smartobject/include/common.php');
22 22
 }
23 23
 /**
24
- * Include the language constants for the SmartObjectDBUpdater
25
- */
24
+	 * Include the language constants for the SmartObjectDBUpdater
25
+	 */
26 26
 global $xoopsConfig;
27 27
 $common_file = SMARTOBJECT_ROOT_PATH . 'language/' . $xoopsConfig['language'] . '/smartdbupdater.php';
28 28
 if (!file_exists($common_file)) {
29
-    $common_file = SMARTOBJECT_ROOT_PATH . 'language/english/smartdbupdater.php';
29
+	$common_file = SMARTOBJECT_ROOT_PATH . 'language/english/smartdbupdater.php';
30 30
 }
31 31
 include($common_file);
32 32
 
@@ -35,500 +35,500 @@  discard block
 block discarded – undo
35 35
  */
36 36
 class SmartDbTable
37 37
 {
38
-    /**
39
-     * @var string $_name name of the table
40
-     */
41
-    public $_name;
42
-    /**
43
-     * @var string $_structure structure of the table
44
-     */
45
-    public $_structure;
46
-
47
-    /**
48
-     * @var array $_data containing valued of each records to be added
49
-     */
50
-    public $_data;
51
-
52
-    /**
53
-     * @var array $_alteredFields containing fields to be altered
54
-     */
55
-    public $_alteredFields;
56
-
57
-    /**
58
-     * @var array $_newFields containing new fields to be added
59
-     */
60
-    public $_newFields;
61
-
62
-    /**
63
-     * @var array $_droppedFields containing fields to be dropped
64
-     */
65
-    public $_droppedFields;
66
-
67
-    /**
68
-     * @var array $_flagForDrop flag table to drop it
69
-     */
70
-    public $_flagForDrop = false;
71
-
72
-    /**
73
-     * @var array $_updatedFields containing fields which values will be updated
74
-     */
75
-    public $_updatedFields;
76
-
77
-    /**
78
-     * @var array $_updatedFields containing fields which values will be updated
79
-     */ //felix
80
-    public $_updatedWhere;
81
-
82
-    public $_existingFieldsArray = false;
83
-
84
-    /**
85
-     * Constructor
86
-     *
87
-     * @param string $name name of the table
88
-     *
89
-     */
90
-    public function __construct($name)
91
-    {
92
-        $this->_name = $name;
93
-        $this->_data = array();
94
-    }
95
-
96
-    /**
97
-     * Return the table name, prefixed with site table prefix
98
-     *
99
-     * @return string table name
100
-     *
101
-     */
102
-    public function name()
103
-    {
104
-        global $xoopsDB;
105
-
106
-        return $xoopsDB->prefix($this->_name);
107
-    }
108
-
109
-    /**
110
-     * Checks if the table already exists in the database
111
-     *
112
-     * @return bool TRUE if it exists, FALSE if not
113
-     *
114
-     */
115
-    public function exists()
116
-    {
117
-        return smart_TableExists($this->_name);
118
-    }
119
-
120
-    /**
121
-     * @return mixed
122
-     */
123
-    public function getExistingFieldsArray()
124
-    {
125
-        global $xoopsDB;
126
-        $result = $xoopsDB->query('SHOW COLUMNS FROM ' . $this->name());
127
-        while ($existing_field = $xoopsDB->fetchArray($result)) {
128
-            $fields[$existing_field['Field']] = $existing_field['Type'];
129
-            if ($existing_field['Null'] !== 'YES') {
130
-                $fields[$existing_field['Field']] .= ' NOT NULL';
131
-            }
132
-            if ($existing_field['Extra']) {
133
-                $fields[$existing_field['Field']] .= ' ' . $existing_field['Extra'];
134
-            }
135
-            if (!($existing_field['Default'] === null) && ($existing_field['Default'] || $existing_field['Default'] == '' || $existing_field['Default'] == 0)) {
136
-                $fields[$existing_field['Field']] .= " default '" . $existing_field['Default'] . "'";
137
-            }
138
-        }
139
-
140
-        return $fields;
141
-    }
142
-
143
-    /**
144
-     * @param $field
145
-     * @return bool
146
-     */
147
-    public function fieldExists($field)
148
-    {
149
-        $existingFields = $this->getExistingFieldsArray();
150
-
151
-        return isset($existingFields[$field]);
152
-    }
153
-
154
-    /**
155
-     * Set the table structure
156
-     *
157
-     * Example:
158
-     *
159
-     *      $table->setStructure("`transactionid` int(11) NOT NULL auto_increment,
160
-     *                `date` int(11) NOT NULL default '0',
161
-     *                `status` int(1) NOT NULL default '-1',
162
-     *                `itemid` int(11) NOT NULL default '0',
163
-     *                `uid` int(11) NOT NULL default '0',
164
-     *                `price` float NOT NULL default '0',
165
-     *                `currency` varchar(100) NOT NULL default '',
166
-     *                PRIMARY KEY  (`transactionid`)");
167
-     *
168
-     * @param string $structure table structure
169
-     *
170
-     */
171
-    public function setStructure($structure)
172
-    {
173
-        $this->_structure = $structure;
174
-    }
175
-
176
-    /**
177
-     * Return the table structure
178
-     *
179
-     * @return string table structure
180
-     *
181
-     */
182
-    public function getStructure()
183
-    {
184
-        return sprintf($this->_structure, $this->name());
185
-    }
186
-
187
-    /**
188
-     * Add values of a record to be added
189
-     *
190
-     * @param string $data values of a record
191
-     *
192
-     */
193
-    public function setData($data)
194
-    {
195
-        $this->_data[] = $data;
196
-    }
197
-
198
-    /**
199
-     * Get the data array
200
-     *
201
-     * @return array containing the records values to be added
202
-     *
203
-     */
204
-    public function getData()
205
-    {
206
-        return $this->_data;
207
-    }
208
-
209
-    /**
210
-     * Use to insert data in a table
211
-     *
212
-     * @return bool true if success, false if an error occured
213
-     *
214
-     */
215
-    public function addData()
216
-    {
217
-        global $xoopsDB;
218
-        foreach ($this->getData() as $data) {
219
-            $query = sprintf('INSERT INTO %s VALUES (%s)', $this->name(), $data);
220
-            $ret   = $xoopsDB->query($query);
221
-            if (!$ret) {
222
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_ADD_DATA_ERR, $this->name()) . '<br />';
223
-            } else {
224
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_ADD_DATA, $this->name()) . '<br />';
225
-            }
226
-        }
227
-
228
-        return $ret;
229
-    }
230
-
231
-    /**
232
-     * Add a field to be added
233
-     *
234
-     * @param string $name       name of the field
235
-     * @param string $properties properties of the field
236
-     * @param bool   $newname
237
-     * @param bool   $showerror
238
-     */
239
-    public function addAlteredField($name, $properties, $newname = false, $showerror = true)
240
-    {
241
-        $field['name']          = $name;
242
-        $field['properties']    = $properties;
243
-        $field['showerror']     = $showerror;
244
-        $field['newname']       = $newname;
245
-        $this->_alteredFields[] = $field;
246
-    }
247
-    /**
248
-     * Invert values 0 to 1 and 1 to 0
249
-     *
250
-     * @param string $name name of the field
251
-     * @param        $newValue
252
-     * @param        $oldValue
253
-     * @internal param string $old old propertie
254
-     * @internal param string $new new propertie
255
-     */ //felix
256
-    public function addUpdatedWhere($name, $newValue, $oldValue)
257
-    {
258
-        $field['name']         = $name;
259
-        $field['value']        = $newValue;
260
-        $field['where']        = $oldValue;
261
-        $this->_updatedWhere[] = $field;
262
-    }
263
-
264
-    /**
265
-     * Add new field of a record to be added
266
-     *
267
-     * @param string $name       name of the field
268
-     * @param string $properties properties of the field
269
-     *
270
-     */
271
-    public function addNewField($name, $properties)
272
-    {
273
-        $field['name']       = $name;
274
-        $field['properties'] = $properties;
275
-        $this->_newFields[]  = $field;
276
-    }
277
-
278
-    /**
279
-     * Get fields that need to be altered
280
-     *
281
-     * @return array fields that need to be altered
282
-     *
283
-     */
284
-    public function getAlteredFields()
285
-    {
286
-        return $this->_alteredFields;
287
-    }
288
-
289
-    /**
290
-     * Add field for which the value will be updated
291
-     *
292
-     * @param string $name  name of the field
293
-     * @param string $value value to be set
294
-     *
295
-     */
296
-    public function addUpdatedField($name, $value)
297
-    {
298
-        $field['name']          = $name;
299
-        $field['value']         = $value;
300
-        $this->_updatedFields[] = $field;
301
-    }
302
-
303
-    /**
304
-     * Get new fields to be added
305
-     *
306
-     * @return array fields to be added
307
-     *
308
-     */
309
-    public function getNewFields()
310
-    {
311
-        return $this->_newFields;
312
-    }
313
-
314
-    /**
315
-     * Get fields which values need to be updated
316
-     *
317
-     * @return array fields which values need to be updated
318
-     *
319
-     */
320
-    public function getUpdatedFields()
321
-    {
322
-        return $this->_updatedFields;
323
-    }
324
-    /**
325
-     * Get fields which values need to be updated
326
-     *
327
-     * @return array fields which values need to be updated
328
-     *
329
-     */ //felix
330
-    public function getUpdatedWhere()
331
-    {
332
-        return $this->_updatedWhere;
333
-    }
334
-
335
-    /**
336
-     * Add values of a record to be added
337
-     *
338
-     * @param string $name name of the field
339
-     *
340
-     */
341
-    public function addDroppedField($name)
342
-    {
343
-        $this->_droppedFields[] = $name;
344
-    }
345
-
346
-    /**
347
-     * Get fields that need to be dropped
348
-     *
349
-     * @return array fields that need to be dropped
350
-     *
351
-     */
352
-    public function getDroppedFields()
353
-    {
354
-        return $this->_droppedFields;
355
-    }
356
-
357
-    /**
358
-     * Set the flag to drop the table
359
-     *
360
-     */
361
-    public function setFlagForDrop()
362
-    {
363
-        $this->_flagForDrop = true;
364
-    }
365
-
366
-    /**
367
-     * Use to create a table
368
-     *
369
-     * @return bool true if success, false if an error occured
370
-     *
371
-     */
372
-    public function createTable()
373
-    {
374
-        global $xoopsDB;
375
-        $query = $this->getStructure();
376
-        $query = 'CREATE TABLE `' . $this->name() . '` (' . $query . ") ENGINE=MyISAM COMMENT='The SmartFactory <www.smartfactory.ca>'";
377
-        //xoops_debug($query);
378
-        $ret = $xoopsDB->query($query);
379
-        if (!$ret) {
380
-            echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CREATE_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
381
-        } else {
382
-            echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CREATE_TABLE, $this->name()) . '<br />';
383
-        }
384
-
385
-        return $ret;
386
-    }
387
-
388
-    /**
389
-     * Use to drop a table
390
-     *
391
-     * @return bool true if success, false if an error occured
392
-     *
393
-     */
394
-    public function dropTable()
395
-    {
396
-        global $xoopsDB;
397
-        $query = sprintf('DROP TABLE %s', $this->name());
398
-        $ret   = $xoopsDB->query($query);
399
-        if (!$ret) {
400
-            echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROP_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
401
-
402
-            return false;
403
-        } else {
404
-            echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROP_TABLE, $this->name()) . '<br />';
405
-
406
-            return true;
407
-        }
408
-    }
409
-
410
-    /**
411
-     * Use to alter a table
412
-     *
413
-     * @return bool true if success, false if an error occured
414
-     *
415
-     */
416
-    public function alterTable()
417
-    {
418
-        global $xoopsDB;
419
-        $ret = true;
420
-
421
-        foreach ($this->getAlteredFields() as $alteredField) {
422
-            if (!$alteredField['newname']) {
423
-                $alteredField['newname'] = $alteredField['name'];
424
-            }
425
-
426
-            $query = sprintf('ALTER TABLE `%s` CHANGE `%s` `%s` %s', $this->name(), $alteredField['name'], $alteredField['newname'], $alteredField['properties']);
427
-            $ret   = $ret && $xoopsDB->query($query);
428
-            if ($alteredField['showerror']) {
429
-                if (!$ret) {
430
-                    echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CHGFIELD_ERR, $alteredField['name'], $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
431
-                } else {
432
-                    echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CHGFIELD, $alteredField['name'], $this->name()) . '<br />';
433
-                }
434
-            }
435
-        }
436
-
437
-        return $ret;
438
-    }
439
-
440
-    /**
441
-     * Use to add new fileds in the table
442
-     *
443
-     * @return bool true if success, false if an error occured
444
-     *
445
-     */
446
-    public function addNewFields()
447
-    {
448
-        global $xoopsDB;
449
-        $ret = true;
450
-        foreach ($this->getNewFields() as $newField) {
451
-            $query = sprintf('ALTER TABLE `%s` ADD `%s` %s', $this->name(), $newField['name'], $newField['properties']);
452
-            //echo $query;
453
-            $ret = $ret && $xoopsDB->query($query);
454
-            if (!$ret) {
455
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_NEWFIELD_ERR, $newField['name'], $this->name()) . '<br />';
456
-            } else {
457
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_NEWFIELD, $newField['name'], $this->name()) . '<br />';
458
-            }
459
-        }
460
-
461
-        return $ret;
462
-    }
463
-
464
-    /**
465
-     * Use to update fields values
466
-     *
467
-     * @return bool true if success, false if an error occured
468
-     *
469
-     */
470
-    public function updateFieldsValues()
471
-    {
472
-        global $xoopsDB;
473
-        $ret = true;
474
-        foreach ($this->getUpdatedFields() as $updatedField) {
475
-            $query = sprintf('UPDATE %s SET %s = %s', $this->name(), $updatedField['name'], $updatedField['value']);
476
-            $ret   = $ret && $xoopsDB->query($query);
477
-            if (!$ret) {
478
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
479
-            } else {
480
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE, $this->name()) . '<br />';
481
-            }
482
-        }
483
-
484
-        return $ret;
485
-    }
486
-    /**
487
-     * Use to update fields values
488
-     *
489
-     * @return bool true if success, false if an error occured
490
-     *
491
-     */ //felix
492
-    public function updateWhereValues()
493
-    {
494
-        global $xoopsDB;
495
-        $ret = true;
496
-        foreach ($this->getUpdatedWhere() as $updatedWhere) {
497
-            $query = sprintf('UPDATE %s SET %s = %s WHERE %s  %s', $this->name(), $updatedWhere['name'], $updatedWhere['value'], $updatedWhere['name'], $updatedWhere['where']);
498
-            //echo $query."<br>";
499
-            $ret = $ret && $xoopsDB->query($query);
500
-            if (!$ret) {
501
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
502
-            } else {
503
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE, $this->name()) . '<br />';
504
-            }
505
-        }
506
-
507
-        return $ret;
508
-    }
509
-
510
-    /**
511
-     * Use to drop fields
512
-     *
513
-     * @return bool true if success, false if an error occured
514
-     *
515
-     */
516
-    public function dropFields()
517
-    {
518
-        global $xoopsDB;
519
-        $ret = true;
520
-        foreach ($this->getDroppedFields() as $droppedField) {
521
-            $query = sprintf('ALTER TABLE %s DROP %s', $this->name(), $droppedField);
522
-            $ret   = $ret && $xoopsDB->query($query);
523
-            if (!$ret) {
524
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROPFIELD_ERR, $droppedField, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
525
-            } else {
526
-                echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROPFIELD, $droppedField, $this->name()) . '<br />';
527
-            }
528
-        }
529
-
530
-        return $ret;
531
-    }
38
+	/**
39
+	 * @var string $_name name of the table
40
+	 */
41
+	public $_name;
42
+	/**
43
+	 * @var string $_structure structure of the table
44
+	 */
45
+	public $_structure;
46
+
47
+	/**
48
+	 * @var array $_data containing valued of each records to be added
49
+	 */
50
+	public $_data;
51
+
52
+	/**
53
+	 * @var array $_alteredFields containing fields to be altered
54
+	 */
55
+	public $_alteredFields;
56
+
57
+	/**
58
+	 * @var array $_newFields containing new fields to be added
59
+	 */
60
+	public $_newFields;
61
+
62
+	/**
63
+	 * @var array $_droppedFields containing fields to be dropped
64
+	 */
65
+	public $_droppedFields;
66
+
67
+	/**
68
+	 * @var array $_flagForDrop flag table to drop it
69
+	 */
70
+	public $_flagForDrop = false;
71
+
72
+	/**
73
+	 * @var array $_updatedFields containing fields which values will be updated
74
+	 */
75
+	public $_updatedFields;
76
+
77
+	/**
78
+	 * @var array $_updatedFields containing fields which values will be updated
79
+	 */ //felix
80
+	public $_updatedWhere;
81
+
82
+	public $_existingFieldsArray = false;
83
+
84
+	/**
85
+	 * Constructor
86
+	 *
87
+	 * @param string $name name of the table
88
+	 *
89
+	 */
90
+	public function __construct($name)
91
+	{
92
+		$this->_name = $name;
93
+		$this->_data = array();
94
+	}
95
+
96
+	/**
97
+	 * Return the table name, prefixed with site table prefix
98
+	 *
99
+	 * @return string table name
100
+	 *
101
+	 */
102
+	public function name()
103
+	{
104
+		global $xoopsDB;
105
+
106
+		return $xoopsDB->prefix($this->_name);
107
+	}
108
+
109
+	/**
110
+	 * Checks if the table already exists in the database
111
+	 *
112
+	 * @return bool TRUE if it exists, FALSE if not
113
+	 *
114
+	 */
115
+	public function exists()
116
+	{
117
+		return smart_TableExists($this->_name);
118
+	}
119
+
120
+	/**
121
+	 * @return mixed
122
+	 */
123
+	public function getExistingFieldsArray()
124
+	{
125
+		global $xoopsDB;
126
+		$result = $xoopsDB->query('SHOW COLUMNS FROM ' . $this->name());
127
+		while ($existing_field = $xoopsDB->fetchArray($result)) {
128
+			$fields[$existing_field['Field']] = $existing_field['Type'];
129
+			if ($existing_field['Null'] !== 'YES') {
130
+				$fields[$existing_field['Field']] .= ' NOT NULL';
131
+			}
132
+			if ($existing_field['Extra']) {
133
+				$fields[$existing_field['Field']] .= ' ' . $existing_field['Extra'];
134
+			}
135
+			if (!($existing_field['Default'] === null) && ($existing_field['Default'] || $existing_field['Default'] == '' || $existing_field['Default'] == 0)) {
136
+				$fields[$existing_field['Field']] .= " default '" . $existing_field['Default'] . "'";
137
+			}
138
+		}
139
+
140
+		return $fields;
141
+	}
142
+
143
+	/**
144
+	 * @param $field
145
+	 * @return bool
146
+	 */
147
+	public function fieldExists($field)
148
+	{
149
+		$existingFields = $this->getExistingFieldsArray();
150
+
151
+		return isset($existingFields[$field]);
152
+	}
153
+
154
+	/**
155
+	 * Set the table structure
156
+	 *
157
+	 * Example:
158
+	 *
159
+	 *      $table->setStructure("`transactionid` int(11) NOT NULL auto_increment,
160
+	 *                `date` int(11) NOT NULL default '0',
161
+	 *                `status` int(1) NOT NULL default '-1',
162
+	 *                `itemid` int(11) NOT NULL default '0',
163
+	 *                `uid` int(11) NOT NULL default '0',
164
+	 *                `price` float NOT NULL default '0',
165
+	 *                `currency` varchar(100) NOT NULL default '',
166
+	 *                PRIMARY KEY  (`transactionid`)");
167
+	 *
168
+	 * @param string $structure table structure
169
+	 *
170
+	 */
171
+	public function setStructure($structure)
172
+	{
173
+		$this->_structure = $structure;
174
+	}
175
+
176
+	/**
177
+	 * Return the table structure
178
+	 *
179
+	 * @return string table structure
180
+	 *
181
+	 */
182
+	public function getStructure()
183
+	{
184
+		return sprintf($this->_structure, $this->name());
185
+	}
186
+
187
+	/**
188
+	 * Add values of a record to be added
189
+	 *
190
+	 * @param string $data values of a record
191
+	 *
192
+	 */
193
+	public function setData($data)
194
+	{
195
+		$this->_data[] = $data;
196
+	}
197
+
198
+	/**
199
+	 * Get the data array
200
+	 *
201
+	 * @return array containing the records values to be added
202
+	 *
203
+	 */
204
+	public function getData()
205
+	{
206
+		return $this->_data;
207
+	}
208
+
209
+	/**
210
+	 * Use to insert data in a table
211
+	 *
212
+	 * @return bool true if success, false if an error occured
213
+	 *
214
+	 */
215
+	public function addData()
216
+	{
217
+		global $xoopsDB;
218
+		foreach ($this->getData() as $data) {
219
+			$query = sprintf('INSERT INTO %s VALUES (%s)', $this->name(), $data);
220
+			$ret   = $xoopsDB->query($query);
221
+			if (!$ret) {
222
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_ADD_DATA_ERR, $this->name()) . '<br />';
223
+			} else {
224
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_ADD_DATA, $this->name()) . '<br />';
225
+			}
226
+		}
227
+
228
+		return $ret;
229
+	}
230
+
231
+	/**
232
+	 * Add a field to be added
233
+	 *
234
+	 * @param string $name       name of the field
235
+	 * @param string $properties properties of the field
236
+	 * @param bool   $newname
237
+	 * @param bool   $showerror
238
+	 */
239
+	public function addAlteredField($name, $properties, $newname = false, $showerror = true)
240
+	{
241
+		$field['name']          = $name;
242
+		$field['properties']    = $properties;
243
+		$field['showerror']     = $showerror;
244
+		$field['newname']       = $newname;
245
+		$this->_alteredFields[] = $field;
246
+	}
247
+	/**
248
+	 * Invert values 0 to 1 and 1 to 0
249
+	 *
250
+	 * @param string $name name of the field
251
+	 * @param        $newValue
252
+	 * @param        $oldValue
253
+	 * @internal param string $old old propertie
254
+	 * @internal param string $new new propertie
255
+	 */ //felix
256
+	public function addUpdatedWhere($name, $newValue, $oldValue)
257
+	{
258
+		$field['name']         = $name;
259
+		$field['value']        = $newValue;
260
+		$field['where']        = $oldValue;
261
+		$this->_updatedWhere[] = $field;
262
+	}
263
+
264
+	/**
265
+	 * Add new field of a record to be added
266
+	 *
267
+	 * @param string $name       name of the field
268
+	 * @param string $properties properties of the field
269
+	 *
270
+	 */
271
+	public function addNewField($name, $properties)
272
+	{
273
+		$field['name']       = $name;
274
+		$field['properties'] = $properties;
275
+		$this->_newFields[]  = $field;
276
+	}
277
+
278
+	/**
279
+	 * Get fields that need to be altered
280
+	 *
281
+	 * @return array fields that need to be altered
282
+	 *
283
+	 */
284
+	public function getAlteredFields()
285
+	{
286
+		return $this->_alteredFields;
287
+	}
288
+
289
+	/**
290
+	 * Add field for which the value will be updated
291
+	 *
292
+	 * @param string $name  name of the field
293
+	 * @param string $value value to be set
294
+	 *
295
+	 */
296
+	public function addUpdatedField($name, $value)
297
+	{
298
+		$field['name']          = $name;
299
+		$field['value']         = $value;
300
+		$this->_updatedFields[] = $field;
301
+	}
302
+
303
+	/**
304
+	 * Get new fields to be added
305
+	 *
306
+	 * @return array fields to be added
307
+	 *
308
+	 */
309
+	public function getNewFields()
310
+	{
311
+		return $this->_newFields;
312
+	}
313
+
314
+	/**
315
+	 * Get fields which values need to be updated
316
+	 *
317
+	 * @return array fields which values need to be updated
318
+	 *
319
+	 */
320
+	public function getUpdatedFields()
321
+	{
322
+		return $this->_updatedFields;
323
+	}
324
+	/**
325
+	 * Get fields which values need to be updated
326
+	 *
327
+	 * @return array fields which values need to be updated
328
+	 *
329
+	 */ //felix
330
+	public function getUpdatedWhere()
331
+	{
332
+		return $this->_updatedWhere;
333
+	}
334
+
335
+	/**
336
+	 * Add values of a record to be added
337
+	 *
338
+	 * @param string $name name of the field
339
+	 *
340
+	 */
341
+	public function addDroppedField($name)
342
+	{
343
+		$this->_droppedFields[] = $name;
344
+	}
345
+
346
+	/**
347
+	 * Get fields that need to be dropped
348
+	 *
349
+	 * @return array fields that need to be dropped
350
+	 *
351
+	 */
352
+	public function getDroppedFields()
353
+	{
354
+		return $this->_droppedFields;
355
+	}
356
+
357
+	/**
358
+	 * Set the flag to drop the table
359
+	 *
360
+	 */
361
+	public function setFlagForDrop()
362
+	{
363
+		$this->_flagForDrop = true;
364
+	}
365
+
366
+	/**
367
+	 * Use to create a table
368
+	 *
369
+	 * @return bool true if success, false if an error occured
370
+	 *
371
+	 */
372
+	public function createTable()
373
+	{
374
+		global $xoopsDB;
375
+		$query = $this->getStructure();
376
+		$query = 'CREATE TABLE `' . $this->name() . '` (' . $query . ") ENGINE=MyISAM COMMENT='The SmartFactory <www.smartfactory.ca>'";
377
+		//xoops_debug($query);
378
+		$ret = $xoopsDB->query($query);
379
+		if (!$ret) {
380
+			echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CREATE_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
381
+		} else {
382
+			echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CREATE_TABLE, $this->name()) . '<br />';
383
+		}
384
+
385
+		return $ret;
386
+	}
387
+
388
+	/**
389
+	 * Use to drop a table
390
+	 *
391
+	 * @return bool true if success, false if an error occured
392
+	 *
393
+	 */
394
+	public function dropTable()
395
+	{
396
+		global $xoopsDB;
397
+		$query = sprintf('DROP TABLE %s', $this->name());
398
+		$ret   = $xoopsDB->query($query);
399
+		if (!$ret) {
400
+			echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROP_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
401
+
402
+			return false;
403
+		} else {
404
+			echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROP_TABLE, $this->name()) . '<br />';
405
+
406
+			return true;
407
+		}
408
+	}
409
+
410
+	/**
411
+	 * Use to alter a table
412
+	 *
413
+	 * @return bool true if success, false if an error occured
414
+	 *
415
+	 */
416
+	public function alterTable()
417
+	{
418
+		global $xoopsDB;
419
+		$ret = true;
420
+
421
+		foreach ($this->getAlteredFields() as $alteredField) {
422
+			if (!$alteredField['newname']) {
423
+				$alteredField['newname'] = $alteredField['name'];
424
+			}
425
+
426
+			$query = sprintf('ALTER TABLE `%s` CHANGE `%s` `%s` %s', $this->name(), $alteredField['name'], $alteredField['newname'], $alteredField['properties']);
427
+			$ret   = $ret && $xoopsDB->query($query);
428
+			if ($alteredField['showerror']) {
429
+				if (!$ret) {
430
+					echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CHGFIELD_ERR, $alteredField['name'], $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
431
+				} else {
432
+					echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_CHGFIELD, $alteredField['name'], $this->name()) . '<br />';
433
+				}
434
+			}
435
+		}
436
+
437
+		return $ret;
438
+	}
439
+
440
+	/**
441
+	 * Use to add new fileds in the table
442
+	 *
443
+	 * @return bool true if success, false if an error occured
444
+	 *
445
+	 */
446
+	public function addNewFields()
447
+	{
448
+		global $xoopsDB;
449
+		$ret = true;
450
+		foreach ($this->getNewFields() as $newField) {
451
+			$query = sprintf('ALTER TABLE `%s` ADD `%s` %s', $this->name(), $newField['name'], $newField['properties']);
452
+			//echo $query;
453
+			$ret = $ret && $xoopsDB->query($query);
454
+			if (!$ret) {
455
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_NEWFIELD_ERR, $newField['name'], $this->name()) . '<br />';
456
+			} else {
457
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_NEWFIELD, $newField['name'], $this->name()) . '<br />';
458
+			}
459
+		}
460
+
461
+		return $ret;
462
+	}
463
+
464
+	/**
465
+	 * Use to update fields values
466
+	 *
467
+	 * @return bool true if success, false if an error occured
468
+	 *
469
+	 */
470
+	public function updateFieldsValues()
471
+	{
472
+		global $xoopsDB;
473
+		$ret = true;
474
+		foreach ($this->getUpdatedFields() as $updatedField) {
475
+			$query = sprintf('UPDATE %s SET %s = %s', $this->name(), $updatedField['name'], $updatedField['value']);
476
+			$ret   = $ret && $xoopsDB->query($query);
477
+			if (!$ret) {
478
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
479
+			} else {
480
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE, $this->name()) . '<br />';
481
+			}
482
+		}
483
+
484
+		return $ret;
485
+	}
486
+	/**
487
+	 * Use to update fields values
488
+	 *
489
+	 * @return bool true if success, false if an error occured
490
+	 *
491
+	 */ //felix
492
+	public function updateWhereValues()
493
+	{
494
+		global $xoopsDB;
495
+		$ret = true;
496
+		foreach ($this->getUpdatedWhere() as $updatedWhere) {
497
+			$query = sprintf('UPDATE %s SET %s = %s WHERE %s  %s', $this->name(), $updatedWhere['name'], $updatedWhere['value'], $updatedWhere['name'], $updatedWhere['where']);
498
+			//echo $query."<br>";
499
+			$ret = $ret && $xoopsDB->query($query);
500
+			if (!$ret) {
501
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE_ERR, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
502
+			} else {
503
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_UPDATE_TABLE, $this->name()) . '<br />';
504
+			}
505
+		}
506
+
507
+		return $ret;
508
+	}
509
+
510
+	/**
511
+	 * Use to drop fields
512
+	 *
513
+	 * @return bool true if success, false if an error occured
514
+	 *
515
+	 */
516
+	public function dropFields()
517
+	{
518
+		global $xoopsDB;
519
+		$ret = true;
520
+		foreach ($this->getDroppedFields() as $droppedField) {
521
+			$query = sprintf('ALTER TABLE %s DROP %s', $this->name(), $droppedField);
522
+			$ret   = $ret && $xoopsDB->query($query);
523
+			if (!$ret) {
524
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROPFIELD_ERR, $droppedField, $this->name()) . ' (' . $xoopsDB->error() . ')<br />';
525
+			} else {
526
+				echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_DROPFIELD, $droppedField, $this->name()) . '<br />';
527
+			}
528
+		}
529
+
530
+		return $ret;
531
+	}
532 532
 }
533 533
 
534 534
 /**
@@ -542,328 +542,328 @@  discard block
 block discarded – undo
542 542
  */
543 543
 class SmartobjectDbupdater
544 544
 {
545
-    public $_dbTypesArray;
546
-
547
-    /**
548
-     * SmartobjectDbupdater constructor.
549
-     */
550
-    public function __construct()
551
-    {
552
-        $this->_dbTypesArray[XOBJ_DTYPE_TXTBOX]       = 'varchar(255)';
553
-        $this->_dbTypesArray[XOBJ_DTYPE_TXTAREA]      = 'text';
554
-        $this->_dbTypesArray[XOBJ_DTYPE_INT]          = 'int(11)';
555
-        $this->_dbTypesArray[XOBJ_DTYPE_URL]          = 'varchar(255)';
556
-        $this->_dbTypesArray[XOBJ_DTYPE_EMAIL]        = 'varchar(255)';
557
-        $this->_dbTypesArray[XOBJ_DTYPE_ARRAY]        = 'text';
558
-        $this->_dbTypesArray[XOBJ_DTYPE_OTHER]        = 'text';
559
-        $this->_dbTypesArray[XOBJ_DTYPE_SOURCE]       = 'text';
560
-        $this->_dbTypesArray[XOBJ_DTYPE_STIME]        = 'int(11)';
561
-        $this->_dbTypesArray[XOBJ_DTYPE_MTIME]        = 'int(11)';
562
-        $this->_dbTypesArray[XOBJ_DTYPE_LTIME]        = 'int(11)';
563
-        $this->_dbTypesArray[XOBJ_DTYPE_SIMPLE_ARRAY] = 'text';
564
-        $this->_dbTypesArray[XOBJ_DTYPE_CURRENCY]     = 'text';
565
-        $this->_dbTypesArray[XOBJ_DTYPE_FLOAT]        = 'float';
566
-        $this->_dbTypesArray[XOBJ_DTYPE_TIME_ONLY]    = 'int(11)';
567
-        $this->_dbTypesArray[XOBJ_DTYPE_URLLINK]      = 'int(11)';
568
-        $this->_dbTypesArray[XOBJ_DTYPE_FILE]         = 'int(11)';
569
-        $this->_dbTypesArray[XOBJ_DTYPE_IMAGE]        = 'varchar(255)';
570
-    }
571
-
572
-    /**
573
-     * Use to execute a general query
574
-     *
575
-     * @param string $query   query that will be executed
576
-     * @param string $goodmsg message displayed on success
577
-     * @param string $badmsg  message displayed on error
578
-     *
579
-     * @return bool true if success, false if an error occured
580
-     *
581
-     */
582
-    public function runQuery($query, $goodmsg, $badmsg)
583
-    {
584
-        global $xoopsDB;
585
-        $ret = $xoopsDB->query($query);
586
-        if (!$ret) {
587
-            echo "&nbsp;&nbsp;$badmsg<br />";
588
-
589
-            return false;
590
-        } else {
591
-            echo "&nbsp;&nbsp;$goodmsg<br />";
592
-
593
-            return true;
594
-        }
595
-    }
596
-
597
-    /**
598
-     * Use to rename a table
599
-     *
600
-     * @param string $from name of the table to rename
601
-     * @param string $to   new name of the renamed table
602
-     *
603
-     * @return bool true if success, false if an error occured
604
-     */
605
-    public function renameTable($from, $to)
606
-    {
607
-        global $xoopsDB;
608
-        $from  = $xoopsDB->prefix($from);
609
-        $to    = $xoopsDB->prefix($to);
610
-        $query = sprintf('ALTER TABLE %s RENAME %s', $from, $to);
611
-        $ret   = $xoopsDB->query($query);
612
-        if (!$ret) {
613
-            echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_RENAME_TABLE_ERR, $from) . '<br />';
614
-
615
-            return false;
616
-        } else {
617
-            echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_RENAME_TABLE, $from, $to) . '<br />';
618
-
619
-            return true;
620
-        }
621
-    }
622
-
623
-    /**
624
-     * Use to update a table
625
-     *
626
-     * @param object $table {@link SmartDbTable} that will be updated
627
-     *
628
-     * @see SmartDbTable
629
-     *
630
-     * @return bool true if success, false if an error occured
631
-     */
632
-    public function updateTable($table)
633
-    {
634
-        global $xoopsDB;
635
-        $ret = true;
636
-        // If table has a structure, create the table
637
-        if ($table->getStructure()) {
638
-            $ret = $table->createTable() && $ret;
639
-        }
640
-        // If table is flag for drop, drop it
641
-        if ($table->_flagForDrop) {
642
-            $ret = $table->dropTable() && $ret;
643
-        }
644
-        // If table has data, insert it
645
-        if ($table->getData()) {
646
-            $ret = $table->addData() && $ret;
647
-        }
648
-        // If table has new fields to be added, add them
649
-        if ($table->getNewFields()) {
650
-            $ret = $table->addNewFields() && $ret;
651
-        }
652
-        // If table has altered field, alter the table
653
-        if ($table->getAlteredFields()) {
654
-            $ret = $table->alterTable() && $ret;
655
-        }
656
-        // If table has updated field values, update the table
657
-        if ($table->getUpdatedFields()) {
658
-            $ret = $table->updateFieldsValues($table) && $ret;
659
-        }
660
-        // If table has dropped field, alter the table
661
-        if ($table->getDroppedFields()) {
662
-            $ret = $table->dropFields($table) && $ret;
663
-        }
664
-        //felix
665
-        // If table has updated field values, update the table
666
-        if ($table->getUpdatedWhere()) {
667
-            $ret = $table->UpdateWhereValues($table) && $ret;
668
-        }
669
-
670
-        return $ret;
671
-    }
672
-
673
-    /**
674
-     * @param $module
675
-     * @param $item
676
-     */
677
-    public function automaticUpgrade($module, $item)
678
-    {
679
-        if (is_array($item)) {
680
-            foreach ($item as $v) {
681
-                $this->upgradeObjectItem($module, $v);
682
-            }
683
-        } else {
684
-            $this->upgradeObjectItem($module, $item);
685
-        }
686
-    }
687
-
688
-    /**
689
-     * @param $var
690
-     * @return string
691
-     */
692
-    public function getFieldTypeFromVar($var)
693
-    {
694
-        $ret = isset($this->_dbTypesArray[$var['data_type']]) ? $this->_dbTypesArray[$var['data_type']] : 'text';
695
-
696
-        return $ret;
697
-    }
698
-
699
-    /**
700
-     * @param       $var
701
-     * @param  bool $key
702
-     * @return string
703
-     */
704
-    public function getFieldDefaultFromVar($var, $key = false)
705
-    {
706
-        if ($var['value']) {
707
-            return $var['value'];
708
-        } else {
709
-            if (in_array($var['data_type'], array(
710
-                XOBJ_DTYPE_INT,
711
-                XOBJ_DTYPE_STIME,
712
-                XOBJ_DTYPE_MTIME,
713
-                XOBJ_DTYPE_LTIME,
714
-                XOBJ_DTYPE_TIME_ONLY,
715
-                XOBJ_DTYPE_URLLINK,
716
-                XOBJ_DTYPE_FILE
717
-            ))) {
718
-                return '0';
719
-            } else {
720
-                return '';
721
-            }
722
-        }
723
-    }
724
-
725
-    /**
726
-     * @param $module
727
-     * @param $item
728
-     * @return bool
729
-     */
730
-    public function upgradeObjectItem($module, $item)
731
-    {
732
-        $moduleHandler = xoops_getModuleHandler($item, $module);
733
-        if (!$moduleHandler) {
734
-            return false;
735
-        }
736
-
737
-        $table      = new SmartDbTable($module . '_' . $item);
738
-        $object     = $moduleHandler->create();
739
-        $objectVars = $object->getVars();
740
-
741
-        if (!$table->exists()) {
742
-            // table was never created, let's do it
743
-            $structure = '';
744
-            foreach ($objectVars as $key => $var) {
745
-                if ($var['persistent']) {
746
-                    $type = $this->getFieldTypeFromVar($var);
747
-                    if ($key == $moduleHandler->keyName) {
748
-                        $extra = 'auto_increment';
749
-                    } else {
750
-                        $default = $this->getFieldDefaultFromVar($var);
751
-                        $extra   = "default '$default'
545
+	public $_dbTypesArray;
546
+
547
+	/**
548
+	 * SmartobjectDbupdater constructor.
549
+	 */
550
+	public function __construct()
551
+	{
552
+		$this->_dbTypesArray[XOBJ_DTYPE_TXTBOX]       = 'varchar(255)';
553
+		$this->_dbTypesArray[XOBJ_DTYPE_TXTAREA]      = 'text';
554
+		$this->_dbTypesArray[XOBJ_DTYPE_INT]          = 'int(11)';
555
+		$this->_dbTypesArray[XOBJ_DTYPE_URL]          = 'varchar(255)';
556
+		$this->_dbTypesArray[XOBJ_DTYPE_EMAIL]        = 'varchar(255)';
557
+		$this->_dbTypesArray[XOBJ_DTYPE_ARRAY]        = 'text';
558
+		$this->_dbTypesArray[XOBJ_DTYPE_OTHER]        = 'text';
559
+		$this->_dbTypesArray[XOBJ_DTYPE_SOURCE]       = 'text';
560
+		$this->_dbTypesArray[XOBJ_DTYPE_STIME]        = 'int(11)';
561
+		$this->_dbTypesArray[XOBJ_DTYPE_MTIME]        = 'int(11)';
562
+		$this->_dbTypesArray[XOBJ_DTYPE_LTIME]        = 'int(11)';
563
+		$this->_dbTypesArray[XOBJ_DTYPE_SIMPLE_ARRAY] = 'text';
564
+		$this->_dbTypesArray[XOBJ_DTYPE_CURRENCY]     = 'text';
565
+		$this->_dbTypesArray[XOBJ_DTYPE_FLOAT]        = 'float';
566
+		$this->_dbTypesArray[XOBJ_DTYPE_TIME_ONLY]    = 'int(11)';
567
+		$this->_dbTypesArray[XOBJ_DTYPE_URLLINK]      = 'int(11)';
568
+		$this->_dbTypesArray[XOBJ_DTYPE_FILE]         = 'int(11)';
569
+		$this->_dbTypesArray[XOBJ_DTYPE_IMAGE]        = 'varchar(255)';
570
+	}
571
+
572
+	/**
573
+	 * Use to execute a general query
574
+	 *
575
+	 * @param string $query   query that will be executed
576
+	 * @param string $goodmsg message displayed on success
577
+	 * @param string $badmsg  message displayed on error
578
+	 *
579
+	 * @return bool true if success, false if an error occured
580
+	 *
581
+	 */
582
+	public function runQuery($query, $goodmsg, $badmsg)
583
+	{
584
+		global $xoopsDB;
585
+		$ret = $xoopsDB->query($query);
586
+		if (!$ret) {
587
+			echo "&nbsp;&nbsp;$badmsg<br />";
588
+
589
+			return false;
590
+		} else {
591
+			echo "&nbsp;&nbsp;$goodmsg<br />";
592
+
593
+			return true;
594
+		}
595
+	}
596
+
597
+	/**
598
+	 * Use to rename a table
599
+	 *
600
+	 * @param string $from name of the table to rename
601
+	 * @param string $to   new name of the renamed table
602
+	 *
603
+	 * @return bool true if success, false if an error occured
604
+	 */
605
+	public function renameTable($from, $to)
606
+	{
607
+		global $xoopsDB;
608
+		$from  = $xoopsDB->prefix($from);
609
+		$to    = $xoopsDB->prefix($to);
610
+		$query = sprintf('ALTER TABLE %s RENAME %s', $from, $to);
611
+		$ret   = $xoopsDB->query($query);
612
+		if (!$ret) {
613
+			echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_RENAME_TABLE_ERR, $from) . '<br />';
614
+
615
+			return false;
616
+		} else {
617
+			echo '&nbsp;&nbsp;' . sprintf(_SDU_MSG_RENAME_TABLE, $from, $to) . '<br />';
618
+
619
+			return true;
620
+		}
621
+	}
622
+
623
+	/**
624
+	 * Use to update a table
625
+	 *
626
+	 * @param object $table {@link SmartDbTable} that will be updated
627
+	 *
628
+	 * @see SmartDbTable
629
+	 *
630
+	 * @return bool true if success, false if an error occured
631
+	 */
632
+	public function updateTable($table)
633
+	{
634
+		global $xoopsDB;
635
+		$ret = true;
636
+		// If table has a structure, create the table
637
+		if ($table->getStructure()) {
638
+			$ret = $table->createTable() && $ret;
639
+		}
640
+		// If table is flag for drop, drop it
641
+		if ($table->_flagForDrop) {
642
+			$ret = $table->dropTable() && $ret;
643
+		}
644
+		// If table has data, insert it
645
+		if ($table->getData()) {
646
+			$ret = $table->addData() && $ret;
647
+		}
648
+		// If table has new fields to be added, add them
649
+		if ($table->getNewFields()) {
650
+			$ret = $table->addNewFields() && $ret;
651
+		}
652
+		// If table has altered field, alter the table
653
+		if ($table->getAlteredFields()) {
654
+			$ret = $table->alterTable() && $ret;
655
+		}
656
+		// If table has updated field values, update the table
657
+		if ($table->getUpdatedFields()) {
658
+			$ret = $table->updateFieldsValues($table) && $ret;
659
+		}
660
+		// If table has dropped field, alter the table
661
+		if ($table->getDroppedFields()) {
662
+			$ret = $table->dropFields($table) && $ret;
663
+		}
664
+		//felix
665
+		// If table has updated field values, update the table
666
+		if ($table->getUpdatedWhere()) {
667
+			$ret = $table->UpdateWhereValues($table) && $ret;
668
+		}
669
+
670
+		return $ret;
671
+	}
672
+
673
+	/**
674
+	 * @param $module
675
+	 * @param $item
676
+	 */
677
+	public function automaticUpgrade($module, $item)
678
+	{
679
+		if (is_array($item)) {
680
+			foreach ($item as $v) {
681
+				$this->upgradeObjectItem($module, $v);
682
+			}
683
+		} else {
684
+			$this->upgradeObjectItem($module, $item);
685
+		}
686
+	}
687
+
688
+	/**
689
+	 * @param $var
690
+	 * @return string
691
+	 */
692
+	public function getFieldTypeFromVar($var)
693
+	{
694
+		$ret = isset($this->_dbTypesArray[$var['data_type']]) ? $this->_dbTypesArray[$var['data_type']] : 'text';
695
+
696
+		return $ret;
697
+	}
698
+
699
+	/**
700
+	 * @param       $var
701
+	 * @param  bool $key
702
+	 * @return string
703
+	 */
704
+	public function getFieldDefaultFromVar($var, $key = false)
705
+	{
706
+		if ($var['value']) {
707
+			return $var['value'];
708
+		} else {
709
+			if (in_array($var['data_type'], array(
710
+				XOBJ_DTYPE_INT,
711
+				XOBJ_DTYPE_STIME,
712
+				XOBJ_DTYPE_MTIME,
713
+				XOBJ_DTYPE_LTIME,
714
+				XOBJ_DTYPE_TIME_ONLY,
715
+				XOBJ_DTYPE_URLLINK,
716
+				XOBJ_DTYPE_FILE
717
+			))) {
718
+				return '0';
719
+			} else {
720
+				return '';
721
+			}
722
+		}
723
+	}
724
+
725
+	/**
726
+	 * @param $module
727
+	 * @param $item
728
+	 * @return bool
729
+	 */
730
+	public function upgradeObjectItem($module, $item)
731
+	{
732
+		$moduleHandler = xoops_getModuleHandler($item, $module);
733
+		if (!$moduleHandler) {
734
+			return false;
735
+		}
736
+
737
+		$table      = new SmartDbTable($module . '_' . $item);
738
+		$object     = $moduleHandler->create();
739
+		$objectVars = $object->getVars();
740
+
741
+		if (!$table->exists()) {
742
+			// table was never created, let's do it
743
+			$structure = '';
744
+			foreach ($objectVars as $key => $var) {
745
+				if ($var['persistent']) {
746
+					$type = $this->getFieldTypeFromVar($var);
747
+					if ($key == $moduleHandler->keyName) {
748
+						$extra = 'auto_increment';
749
+					} else {
750
+						$default = $this->getFieldDefaultFromVar($var);
751
+						$extra   = "default '$default'
752 752
 ";
753
-                    }
754
-                    $structure .= "`$key` $type not null $extra,
753
+					}
754
+					$structure .= "`$key` $type not null $extra,
755 755
 ";
756
-                }
757
-            }
758
-            $structure .= 'PRIMARY KEY  (`' . $moduleHandler->keyName . '`)
756
+				}
757
+			}
758
+			$structure .= 'PRIMARY KEY  (`' . $moduleHandler->keyName . '`)
759 759
 ';
760
-            $table->setStructure($structure);
761
-            if (!$this->updateTable($table)) {
762
-                /**
763
-                 * @todo trap the errors
764
-                 */
765
-            }
766
-        } else {
767
-            $existingFieldsArray = $table->getExistingFieldsArray();
768
-            foreach ($objectVars as $key => $var) {
769
-                if ($var['persistent']) {
770
-                    if (!isset($existingFieldsArray[$key])) {
771
-                        // the fiels does not exist, let's create it
772
-                        $type    = $this->getFieldTypeFromVar($var);
773
-                        $default = $this->getFieldDefaultFromVar($var);
774
-                        $table->addNewField($key, "$type not null default '$default'");
775
-                    } else {
776
-                        // if field already exists, let's check if the definition is correct
777
-                        $definition = strtolower($existingFieldsArray[$key]);
778
-                        $type       = $this->getFieldTypeFromVar($var);
779
-                        if ($key == $moduleHandler->keyName) {
780
-                            $extra = 'auto_increment';
781
-                        } else {
782
-                            $default = $this->getFieldDefaultFromVar($var, $key);
783
-                            $extra   = "default '$default'";
784
-                        }
785
-                        $actual_definition = "$type not null $extra";
786
-                        if ($definition != $actual_definition) {
787
-                            $table->addAlteredField($key, $actual_definition);
788
-                        }
789
-                    }
790
-                }
791
-            }
792
-
793
-            // check to see if there are some unused fields left in the table
794
-            foreach ($existingFieldsArray as $key => $v) {
795
-                if (!isset($objectVars[$key]) || !$objectVars[$key]['persistent']) {
796
-                    $table->addDroppedField($key);
797
-                }
798
-            }
799
-
800
-            if (!$this->updateTable($table)) {
801
-                /**
802
-                 * @todo trap the errors
803
-                 */
804
-            }
805
-        }
806
-    }
807
-
808
-    /**
809
-     * @param $module
810
-     * @return bool
811
-     */
812
-    public function moduleUpgrade(&$module)
813
-    {
814
-        $dirname = $module->getVar('dirname');
815
-
816
-        ob_start();
817
-
818
-        $table = new SmartDbTable($dirname . '_meta');
819
-        if (!$table->exists()) {
820
-            $table->setStructure("
760
+			$table->setStructure($structure);
761
+			if (!$this->updateTable($table)) {
762
+				/**
763
+				 * @todo trap the errors
764
+				 */
765
+			}
766
+		} else {
767
+			$existingFieldsArray = $table->getExistingFieldsArray();
768
+			foreach ($objectVars as $key => $var) {
769
+				if ($var['persistent']) {
770
+					if (!isset($existingFieldsArray[$key])) {
771
+						// the fiels does not exist, let's create it
772
+						$type    = $this->getFieldTypeFromVar($var);
773
+						$default = $this->getFieldDefaultFromVar($var);
774
+						$table->addNewField($key, "$type not null default '$default'");
775
+					} else {
776
+						// if field already exists, let's check if the definition is correct
777
+						$definition = strtolower($existingFieldsArray[$key]);
778
+						$type       = $this->getFieldTypeFromVar($var);
779
+						if ($key == $moduleHandler->keyName) {
780
+							$extra = 'auto_increment';
781
+						} else {
782
+							$default = $this->getFieldDefaultFromVar($var, $key);
783
+							$extra   = "default '$default'";
784
+						}
785
+						$actual_definition = "$type not null $extra";
786
+						if ($definition != $actual_definition) {
787
+							$table->addAlteredField($key, $actual_definition);
788
+						}
789
+					}
790
+				}
791
+			}
792
+
793
+			// check to see if there are some unused fields left in the table
794
+			foreach ($existingFieldsArray as $key => $v) {
795
+				if (!isset($objectVars[$key]) || !$objectVars[$key]['persistent']) {
796
+					$table->addDroppedField($key);
797
+				}
798
+			}
799
+
800
+			if (!$this->updateTable($table)) {
801
+				/**
802
+				 * @todo trap the errors
803
+				 */
804
+			}
805
+		}
806
+	}
807
+
808
+	/**
809
+	 * @param $module
810
+	 * @return bool
811
+	 */
812
+	public function moduleUpgrade(&$module)
813
+	{
814
+		$dirname = $module->getVar('dirname');
815
+
816
+		ob_start();
817
+
818
+		$table = new SmartDbTable($dirname . '_meta');
819
+		if (!$table->exists()) {
820
+			$table->setStructure("
821 821
               `metakey` varchar(50) NOT NULL default '',
822 822
               `metavalue` varchar(255) NOT NULL default '',
823 823
               PRIMARY KEY (`metakey`)");
824
-            $table->setData("'version',0");
825
-            if (!$this->updateTable($table)) {
826
-                /**
827
-                 * @todo trap the errors
828
-                 */
829
-            }
830
-        }
831
-
832
-        $dbVersion = smart_GetMeta('version', $dirname);
833
-        if (!$dbVersion) {
834
-            $dbVersion = 0;
835
-        }
836
-        $newDbVersion = constant(strtoupper($dirname . '_db_version')) ?: 0;
837
-        echo 'Database version: ' . $dbVersion . '<br />';
838
-        echo 'New database version: ' . $newDbVersion . '<br />';
839
-
840
-        if ($newDbVersion > $dbVersion) {
841
-            for ($i = $dbVersion + 1; $i <= $newDbVersion; ++$i) {
842
-                $upgrade_function = $dirname . '_db_upgrade_' . $i;
843
-                if (function_exists($upgrade_function)) {
844
-                    $upgrade_function();
845
-                }
846
-            }
847
-        }
848
-
849
-        echo '<code>' . _SDU_UPDATE_UPDATING_DATABASE . '<br />';
850
-
851
-        // if there is a function to execute for this DB version, let's do it
852
-        //$function_
853
-
854
-        $module_info = smart_getModuleInfo($dirname);
855
-        $this->automaticUpgrade($dirname, $module_info->modinfo['object_items']);
856
-
857
-        echo '</code>';
858
-
859
-        $feedback = ob_get_clean();
860
-        if (method_exists($module, 'setMessage')) {
861
-            $module->setMessage($feedback);
862
-        } else {
863
-            echo $feedback;
864
-        }
865
-        smart_SetMeta('version', $newDbVersion, $dirname); //Set meta version to current
866
-
867
-        return true;
868
-    }
824
+			$table->setData("'version',0");
825
+			if (!$this->updateTable($table)) {
826
+				/**
827
+				 * @todo trap the errors
828
+				 */
829
+			}
830
+		}
831
+
832
+		$dbVersion = smart_GetMeta('version', $dirname);
833
+		if (!$dbVersion) {
834
+			$dbVersion = 0;
835
+		}
836
+		$newDbVersion = constant(strtoupper($dirname . '_db_version')) ?: 0;
837
+		echo 'Database version: ' . $dbVersion . '<br />';
838
+		echo 'New database version: ' . $newDbVersion . '<br />';
839
+
840
+		if ($newDbVersion > $dbVersion) {
841
+			for ($i = $dbVersion + 1; $i <= $newDbVersion; ++$i) {
842
+				$upgrade_function = $dirname . '_db_upgrade_' . $i;
843
+				if (function_exists($upgrade_function)) {
844
+					$upgrade_function();
845
+				}
846
+			}
847
+		}
848
+
849
+		echo '<code>' . _SDU_UPDATE_UPDATING_DATABASE . '<br />';
850
+
851
+		// if there is a function to execute for this DB version, let's do it
852
+		//$function_
853
+
854
+		$module_info = smart_getModuleInfo($dirname);
855
+		$this->automaticUpgrade($dirname, $module_info->modinfo['object_items']);
856
+
857
+		echo '</code>';
858
+
859
+		$feedback = ob_get_clean();
860
+		if (method_exists($module, 'setMessage')) {
861
+			$module->setMessage($feedback);
862
+		} else {
863
+			echo $feedback;
864
+		}
865
+		smart_SetMeta('version', $newDbVersion, $dirname); //Set meta version to current
866
+
867
+		return true;
868
+	}
869 869
 }
Please login to merge, or discard this patch.