Campsite /campsite/src/classes/ArticleTypeField.php

Language PHP Lines 877
MD5 Hash 91c26f8eccab17115f980c7db0e9c182
Repository https://github.com/joechrysler/Campsite.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
<?php
/**
 * @package Campsite
 */

/**
 * Includes
 */
require_once($GLOBALS['g_campsiteDir'].'/classes/Log.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/Topic.php');
require_once($GLOBALS['g_campsiteDir'].'/classes/CampCacheList.php');


/**
 * @package Campsite
 */
class ArticleTypeField extends DatabaseObject {
    const TYPE_TEXT = 'text';
    const TYPE_BODY = 'body';
    const TYPE_DATE = 'date';
    const TYPE_TOPIC = 'topic';
    const TYPE_SWITCH = 'switch';
    const TYPE_NUMERIC = 'numeric';
    
    const NUMERIC_DEFAULT_DIGITS = 65;
    const NUMERIC_DEFAULT_PRECISION = 2;

    var $m_dbTableName = 'ArticleTypeMetadata';
	var $m_keyColumnNames = array('type_name', 'field_name');
    var $m_columnNames = array(
        'type_name',
        'field_name',
        'field_weight',
        'is_hidden',
        'comments_enabled',
        'fk_phrase_id',
        'field_type',
        'field_type_param',
        'is_content_field');
    private $m_rootTopicId = null;
    private $m_precision = null;


	public function __construct($p_articleTypeName = null, $p_fieldName = null)
	{
		$this->m_data['type_name'] = $p_articleTypeName;
		$this->m_data['field_name'] = $p_fieldName;
        if ($this->keyValuesExist()) {
            $this->fetch();
        }
	} // constructor


	/**
	 * Returns the article type name.
	 *
	 * @return string
	 */
	public function getArticleType()
	{
		return $this->m_data['type_name'];
	} // fn getArticleType


	/**
	 * Rename the article type field.
	 *
	 * @param string p_newName
	 *
	 */
	public function rename($p_newName)
	{
		global $g_ado_db;
		if (!$this->exists() || !ArticleType::isValidFieldName($p_newName)) {
			return 0;
		}

		$types = self::DatabaseTypes(null, $this->m_precision);

		$queryStr = "ALTER TABLE `X". $this->m_data['type_name']."` CHANGE COLUMN `"
		. $this->getName() ."` `F$p_newName` ". $types[$this->getType()];
		$success = $g_ado_db->Execute($queryStr);

		if ($success) {
			$fieldName = $this->m_data['field_name'];
			$this->setProperty('field_name', $p_newName);
			if (function_exists("camp_load_translation_strings")) {
				camp_load_translation_strings("api");
			}
			$logText = getGS('The article type field "$1" has been renamed to "$2".',
			$fieldName, $p_newName);
			Log::Message($logText, null, 62);
		}
	} // fn rename


    /**
     * Fetch a single record from the database for the given key.
     *
     * @param array $p_recordSet
     *      If the record has already been fetched and we just need to
     *      assign the data to the object's internal member variable.
     *
     * @return boolean
     *      TRUE on success, FALSE on failure
     */
	public function fetch($p_recordSet = null)
	{
		$success = parent::fetch($p_recordSet);
		if ($success && $this->getType() == self::TYPE_NUMERIC) {
			$params = explode('=', $this->m_data['field_type_param']);
			if (isset($params[0]) && $params[0] == 'precision') {
				$this->m_precision = (int) $params[1];
			}
		}
		return $success;
	}


	/**
	 * Create a column in the table.
	 * @param string $p_type
	 *		Can be one of: 'text', 'date', 'body', 'switch', 'numeric'.
	 */
	public function create($p_type, array $p_params = array())
	{
		global $g_ado_db;

        $p_type = strtolower($p_type);
        $numericPrecision = isset($p_params['precision']) ? $p_params['precision'] : null;
        $types = self::DatabaseTypes(null, $numericPrecision);
		if ($this->getPrintName() != 'NULL' && !array_key_exists($p_type, $types)) {
			return false;
		}

		if ($p_type == self::TYPE_TOPIC && $this->getPrintName() != 'NULL') {
			if (!isset($p_params['root_topic_id']) && !is_numeric($p_params['root_topic_id'])) {
				return false;
			}
			$rootTopicId = (int)$p_params['root_topic_id'];
			$queryStr2 = "INSERT INTO TopicFields (ArticleType, FieldName, RootTopicId) "
			. "VALUES ('".$g_ado_db->escape($this->m_data['type_name']) . "', '"
			. $g_ado_db->escape($this->m_data['field_name']) . "', '$rootTopicId')";
			if (!$g_ado_db->Execute($queryStr2)) {
				return false;
			}
		}

		if ($this->getPrintName() != 'NULL') {
			$queryStr = "ALTER TABLE `X" . $this->m_data['type_name'] . "` ADD COLUMN `"
			. $this->getName() . '` ' . $types[$p_type];
			$success = $g_ado_db->Execute($queryStr);
		}
		if ($success || $this->getPrintName() == 'NULL') {
			$data = array();
			if ($this->getPrintName() != 'NULL') {
				if ($p_type == self::TYPE_BODY && isset($p_params['is_content'])) {
                    $data['is_content_field'] = (int)$p_params['is_content'];
				}
				if ($p_type == self::TYPE_NUMERIC && isset($p_params['precision'])) {
					$data['field_type_param'] = 'precision=' . (int)$p_params['precision'];
				}
				$data['field_type'] = $p_type;
				$data['field_weight'] = $this->getNextOrder();
			}
			$success = parent::create($data);
		}

		if ($success) {
			if (function_exists("camp_load_translation_strings")) {
				camp_load_translation_strings("api");
			}
			$logtext = getGS('Article type field "$1" created', $this->m_data['field_name']);
			Log::Message($logtext, null, 71);
            CampCache::singleton()->clear('user');
		}
		return $success;
	} // fn create


	/**
	 * Returns an array of types compatible with the given field type.
	 * @return array
	 */
	public static function TypesConvertibleTo($p_type)
	{
		switch ($p_type) {
			case self::TYPE_BODY:
				return array(self::TYPE_TEXT, self::TYPE_DATE, self::TYPE_TOPIC, self::TYPE_SWITCH, self::TYPE_NUMERIC);
			case self::TYPE_TEXT:
				return array(self::TYPE_DATE, self::TYPE_TOPIC, self::TYPE_SWITCH, self::TYPE_NUMERIC);
			case self::TYPE_DATE:
				return array();
			case self::TYPE_TOPIC:
				return array();
			case self::TYPE_SWITCH:
				return array();
			case self::TYPE_NUMERIC:
				return array();
		}
		return false;
	}


	public static function TypesConvertibleFrom($p_type)
	{
		$allTypes = self::DatabaseTypes();
		if (!array_key_exists($p_type, $allTypes)) {
			return false;
		}
		$convertibleFromTypes = array();
		foreach ($allTypes as $typeName=>$sqlDesc) {
			if (array_search($p_type, self::TypesConvertibleTo($typeName)) !== false) {
				$convertibleFromTypes[] = $typeName;
			}
		}
		return $convertibleFromTypes;
	}


	public function getConvertibleFromTypes()
	{
		return self::TypesConvertibleTo($this->getType());
	}


	public function getConvertibleToTypes()
	{
		return self::TypesConvertibleFrom($this->getType());
	}


	/**
	 * Returns true if the given type can be converted to the current field type.
	 * @param $p_type
	 * @return boolean
	 */
	public function isConvertibleFrom($p_type)
	{
		if (is_object($p_type) && get_class($p_type) == __CLASS__) {
			if ($this->getType() == 'topic' && $p_type->getType() == 'topic') {
				return $this->getTopicTypeRootElement() == $p_type->getTopicTypeRootElement();
			}
			$p_type = $p_type->getType();
		}
		return ($this->getType() == $p_type && $p_type != 'topic')
		|| array_search($p_type, $this->getConvertibleFromTypes()) !== false;
	}


	public function isConvertibleTo($p_type)
	{
		return array_search($p_type, $this->getConvertibleToTypes());
	}


	/**
     * Changes the type of the field
     *
     * @param string p_type (text|date|body|topic|switch|numeric)
     */
	public function setType($p_type)
	{
		global $g_ado_db;

		$p_type = strtolower($p_type);
        $types = self::DatabaseTypes();
        if (!array_key_exists($p_type, $types)) {
            return false;
        }
        if ($this->getType() == $p_type) {
        	return true;
        }

        if ($this->getType() == self::TYPE_TOPIC) {
        	$queryStr = "DELETE FROM TopicFields WHERE ArticleType = '"
        	. $g_ado_db->escape($this->m_data['type_name'])
            ."' AND FieldName = '". $g_ado_db->escape($this->m_data['field_name']) ."'";
            if (!$g_ado_db->Execute($queryStr)) {
                return false;
            }
        }
        $queryStr = "ALTER TABLE `X" . $this->m_data['type_name'] . "` MODIFY `"
        . $this->getName() . '` ' . $types[$p_type];
		$success = $g_ado_db->Execute($queryStr);
		if ($success) {
			$this->setProperty('field_type_param', null);
			$success = $this->setProperty('field_type', $p_type);
            $this->m_rootTopicId = null;
		}

		if ($success) {
			if (function_exists("camp_load_translation_strings")) {
				camp_load_translation_strings("api");
			}
			$logtext = getGS('Article type field "$1" changed', $this->m_data['field_name']);
			Log::Message($logtext, null, 71);
		}
		return $success;
	} // fn setType


	/**
	 * Deletes the current article type field.
	 */
	public function delete()
	{
		global $g_ado_db;
		
		if (!$this->exists()) {
			return false;
		}

		$orders = $this->getOrders();

        $translation = new Translation(null, $this->getPhraseId());
        $translation->deletePhrase();

        if ($this->getPrintName() != 'NULL') {
			$queryStr = "ALTER TABLE `X" . $this->m_data['type_name']
			. "` DROP COLUMN `" . $this->getName() . "`";
			$success = $g_ado_db->Execute($queryStr);
		}

		if ($success || $this->getPrintName() == 'NULL') {
            $myType = $this->getType();
			if ($myType == self::TYPE_TOPIC) {
                $queryStr = "DELETE FROM TopicFields WHERE ArticleType = '"
                . $g_ado_db->escape($this->m_data['type_name']) . "' and FieldName = '"
                . $g_ado_db->escape($this->m_data['field_name']) . "'";
                $g_ado_db->Execute($queryStr);
                $this->m_rootTopicId = null;
            }
			$fieldName = $this->m_data['field_name'];
			$success = parent::delete();
		}

		// reorder
		if ($success) {
            $newOrders = array();
            foreach ($orders as $k => $v) {
                if ($v != $this->m_data['field_name'])
                    $newOrders[] = $v;

            }
            $newOrders = array_reverse($newOrders);
			$this->setOrders($newOrders);

			if (function_exists("camp_load_translation_strings")) {
			    camp_load_translation_strings("api");
			}
			$logtext = getGS('Article type field "$1" deleted', $fieldName);
			Log::Message($logtext, null, 72);
            CampCache::singleton()->clear('user');
		}
		return $success;
	} // fn delete


	/**
	 * @return string
	 */
	public function getName()
	{
		return 'F'.$this->m_data['field_name'];
	} // fn getName


	/**
	 * @return string
	 */
	public function getPrintName()
	{
		return $this->m_data['field_name'];
	} // fn getPrintName


	/**
	 * @return string
	 */
	public function getType()
	{
		return $this->m_data['field_type'];
	} // fn getType
	
	
	public function getGenericType()
	{
		switch ($this->getType()) {
			case self::TYPE_BODY:
			case self::TYPE_TEXT:
				return 'string';
			case self::TYPE_DATE:
				return 'date';
			case self::TYPE_NUMERIC:
				return 'integer';
			case self::TYPE_SWITCH:
				return 'switch';
			case self::TYPE_TOPIC:
				return 'topic';
		}
		return null;
	}


	/**
	 * @return string
	 */
	public function getTopicTypeRootElement()
	{
		global $g_ado_db;

		if ($this->getType() == self::TYPE_TOPIC && is_null($this->m_rootTopicId)) {
    		$queryStr = "SELECT RootTopicId FROM TopicFields WHERE ArticleType = '"
    		. $g_ado_db->escape($this->getArticleType()) . "' and FieldName = '"
    		. $g_ado_db->escape($this->getPrintName()) . "'";
    		$this->m_rootTopicId = $g_ado_db->GetOne($queryStr);
		}
		return $this->m_rootTopicId;
	}


	/**
	 * Get a human-readable representation of the column type.
	 * @return string
	 */
	public static function VerboseTypeName($p_typeName, $p_languageId = 1, $p_rootTopicId = null)
	{
		switch ($p_typeName) {
	    case self::TYPE_BODY:
	    	return getGS('Multi-line Text with WYSIWYG');
	    case self::TYPE_TEXT:
	    	return getGS('Single-line Text');
	    case self::TYPE_DATE:
	    	return getGS('Date');
	    case self::TYPE_TOPIC:
	    	if (is_null($p_rootTopicId)) {
	    		return getGS('Topic');
	    	}
   			$topic = new Topic($p_rootTopicId);
   			$translations = $topic->getTranslations();
   			if (array_key_exists($p_languageId, $translations)) {
   				return getGS('Topic') . ' (' . $translations[$p_languageId] . ')';
   			} elseif ($p_languageId != 1 && array_key_exists(1, $translations)) {
   				return getGS('Topic') . ' (' . $translations[1] . ')';
   			} else {
   				return getGS('Topic') . ' (' . end($translations) . ')';
   			}
	    	break;
	    case self::TYPE_SWITCH:
	    	return getGS('Switch');
	    case self::TYPE_NUMERIC:
	    	return getGS('Numeric');
	    default:
	    	return getGS("unknown");
		}
	} // fn VerboseTypeName


	public function getVerboseTypeName($p_languageId = 1)
	{
		$rootTopicId = $this->getType() == self::TYPE_TOPIC ? $this->getTopicTypeRootElement() : null;
		return self::VerboseTypeName($this->getType(), $p_languageId, $rootTopicId);
	}


	/**
	 * Gets the language code of the current translation language; or none
	 * if there is no translation.
	 *
	 * @param int p_lang
	 *
	 * @return string
	 */
	public function getDisplayNameLanguageCode($p_lang = 0)
	{
		if (!$p_lang) {
			$lang = camp_session_get('LoginLanguageId', 1);
		} else {
			$lang = $p_lang;
		}
		$languageObj = new Language($lang);
		$translations = $this->getTranslations();
		if (!isset($translations[$lang])) {
		    return '';
		}
		return '('. $languageObj->getCode() .')';
	} // fn getDisplayNameLanguageCode


	/**
	 * Gets the translation for a given language; default language is the
	 * session language.  If no translation is set for that language, we
	 * return the dbTableName.
     *
	 * @param int p_lang
	 *
	 * @return string
	 */
	public function getDisplayName($p_lang = 0)
	{
		if (!$p_lang) {
			$lang = camp_session_get('LoginLanguageId', 1);
		} else {
			$lang = $p_lang;
		}

		$translations = $this->getTranslations();
		if (!isset($translations[$lang])) {
		    return $this->getPrintName();
		}
		return $translations[$lang];
	} // fn getDisplayName


	/**
	 * Returns the is_hidden status of a field.  Returns 'hidden' or 'shown'.
	 *
	 * @return string (shown|hidden)
	 */
	public function getStatus()
	{
		if ($this->m_data['is_hidden']) {
		    return 'hidden';
		} else {
		    return 'shown';
		}
	} // fn getStatus


	/**
	 * @param string p_status (hide|show)
	 */
	public function setStatus($p_status)
	{
		if ($p_status == 'show') {
			$hidden = 0;
		} elseif ($p_status == 'hide') {
			$hidden = 1;
		} else {
			return null;
		}
		return $this->setProperty('is_hidden', $hidden);
	} // fn setStatus


	/**
	 * Return an associative array of the metadata in ArticleFieldMetadata.
	 *
	 * @return array
	 */
	public function getMetadata() {
		return $this->m_data;
	} // fn getMetadata


	/**
	 * @return -1 OR int
	 */
	public function getPhraseId()
	{
		if (isset($this->m_data['fk_phrase_id'])) {
		    return $this->m_data['fk_phrase_id'];
		}
		return -1;
	} // fn getPhraseId()


	/**
	 * Returns an array of translation strings for the field name.
	 * @return array
	 */
	public function getTranslations()
	{
		$return = array();
		$tmp = Translation::getTranslations($this->getPhraseId());
		foreach ($tmp as $k => $v) {
			$return[$k] = $v;
		}
		return $return;
	} // fn getTransltions


    /**
     * Returns true if the current field is hidden.
     * @return boolean
     */
	public function isHidden()
	{
		return $this->m_data['is_hidden'];
	}


	/**
	 * Returns true if the current field is a content field.
	 * @return boolean
	 */
	public function isContent() {
	    return $this->m_data['is_content_field'];
	}
	


	/**
	 * Sets the content flag. Returns true on success, false otherwise.
	 * @param $p_isContent
	 * @return boolean
	 */
	public function setIsContent($p_isContent)
	{
		return $this->setProperty('is_content_field', (int)$p_isContent);
	}


	/**
	 * Quick lookup to see if the current language is already translated for this article type: used by delete and update in setName
	 * returns 0 if no translation or the phrase_id if there is one.
	 *
	 * @param int p_languageId
	 *
	 * @return 0 or phrase id (int)
	 */
	public function translationExists($p_languageId) {
		$translation = new Translation($p_languageId, $this->m_data['fk_phrase_id']);
		return $translation->exists();
	} // fn translationExists


	/**
	 * Set the type name for the given language.  A new entry in
	 * the database will be created if the language did not exist.
	 *
	 * @param int $p_languageId
	 * @param string $p_value
	 *
	 * @return boolean
	 */
	public function setName($p_languageId, $p_value)
	{
		global $g_ado_db;
		if (!is_numeric($p_languageId)) {
			return false;
		}
		// if the string is empty, nuke it
		if (!is_string($p_value) || $p_value == '') {
			if ($phrase_id = $this->translationExists($p_languageId)) {
			    $trans = new Translation($p_languageId, $phrase_id);
			    $trans->delete();
				$changed = true;
			} else {
			    $changed = false;
			}
		} else {
			$description = new Translation($p_languageId, $this->getProperty('fk_phrase_id'));
			if ($description->exists()) {
                $changed = $description->setText($p_value);
			} else {
				$changed = $description->create($p_value);
				if ($changed && is_null($this->getProperty('fk_phrase_id'))) {
					$this->setProperty('fk_phrase_id', $description->getPhraseId());
				}
			}
		}

		if ($changed) {
			if (function_exists("camp_load_translation_strings")) {
			    camp_load_translation_strings("api");
			}
			$logtext = getGS('Field "$1" updated', $this->m_data['field_name']);
			Log::Message($logtext, null, 143);
		}

		return $changed;
	} // fn setName


	/**
	 * Returns the highest weight + 1 or 0 for the starter
	 *
	 * @return int
	 */
	public function getNextOrder()
	{
		global $g_ado_db;
		$queryStr = "SELECT field_weight FROM `" . $this->m_dbTableName
		. "` WHERE type_name = '" . $g_ado_db->escape($this->m_data['type_name']) . "'"
		. " AND field_name != 'NULL' ORDER BY field_weight DESC";
		$field_weight = $g_ado_db->GetOne($queryStr);
		if (!is_null($field_weight)) {
			$next = $field_weight + 1;
	    } else {
		    $next = 1;
		}
		return $next;
	} // fn getNextOrder


	/**
	 * Get the ordering of all fields; initially, a field has a field_weight
	 * of NULL when it is created.  if we discover that a field has a field
	 * weight of NULL, we give it the MAX+1 field_weight.  Returns a NUMERIC
	 * array of ORDER => FIELDNAME.
	 *
	 * @return array
	 */
	public function getOrders()
	{
		global $g_ado_db;

		$queryStr = "SELECT field_weight, field_name FROM `" . $this->m_dbTableName
		. "` WHERE type_name = '" . $g_ado_db->escape($this->m_data['type_name'])
		. "' AND field_name != 'NULL' ORDER BY field_weight DESC";
		$queryArray = $g_ado_db->GetAll($queryStr);
		$orderArray = array();
		foreach ($queryArray as $row => $values) {
			if ($values['field_weight'] == NULL) {
			    $values['field_weight'] = $this->getNextOrder();
			}
			$orderArray[$values['field_weight']] = $values['field_name'];
		}
		return $orderArray;
	} // fn getOrders


	/**
	 * Saves the ordering of all the fields.  Accepts an NUMERIC array of
	 * ORDERRANK => FIELDNAME. (see getOrders)
	 *
	 * @param array orderArray
	 */
	public function setOrders($orderArray)
	{
		global $g_ado_db;
		foreach ($orderArray as $order => $field) {
			$field = new ArticleTypeField($this->m_data['type_name'], $field);
			if ($field->exists()) {
				$field->setProperty('field_weight', $order);
			}
		}
	} // fn setOrders


	/**
     * Reorders the current field; accepts either "up" or "down"
     *
     * @param string move (up|down)
	 */
	public function reorder($move)
	{
		$orders = $this->getOrders();

		$tmp = array_keys($orders, $this->m_data['field_name']);
		if (count($tmp) == 0) {
			return;
		}
		$pos = $tmp[0];

		reset($orders);
		list($max, $value) = each($orders);
		end($orders);
		list($min, $value) = each($orders);

		if ($pos <= $min && $move == 'up') {
		    return;
		}
		if ($pos >= $max && $move == 'down') {
		    return;
		}
		if ($move == 'down') {
			$tmp = $orders[$pos + 1];
			$orders[$pos + 1] = $orders[$pos];
			$orders[$pos] = $tmp;
		}
		if ($move == 'up') {
			$tmp = $orders[$pos - 1];
			$orders[$pos - 1] = $orders[$pos];
			$orders[$pos] = $tmp;
		}

		$this->setOrders($orders);
	} // fn reorder


	/**
	 * Returns an array of fields from all article types that match
	 * the given conditions.
	 *
	 * @param $p_name
	 *         if specified returns fields with the given name
	 * @param $p_articleType
	 *         if specified returns fields of the given article type
	 * @param $p_dataType
	 *         if specified returns the fields having the given data type
	 *
	 * @return array
	 */
	public static function FetchFields($p_name = null, $p_articleType = null,
	$p_dataType = null, $p_negateName = false, $p_negateArticleType = false,
	$p_negateDataType = false, $p_selectHidden = true, $p_skipCache = false)
	{
	    global $g_ado_db;

	    if (!$p_skipCache && CampCache::IsEnabled()) {
	    	$paramsArray['name'] = (is_null($p_name)) ? 'null' : $p_name;
	    	$paramsArray['article_type'] = (is_null($p_articleType)) ? 'null' : $p_articleType;
	    	$paramsArray['data_type'] = (is_null($p_dataType)) ? 'null' : $p_dataType;
	    	$paramsArray['negate_name'] = ($p_negateName == false) ? 'false' : 'true';
	    	$paramsArray['negate_article_type'] = ($p_negateArticleType == false) ? 'false' : 'true';
	    	$paramsArray['negate_data_type'] = ($p_negateDataType == false) ? 'false' : 'true';
	    	$paramsArray['select_hidden'] = ($p_selectHidden == false)? 'false' : 'true';
	    	$cacheListObj = new CampCacheList($paramsArray, __METHOD__);
	    	$articleTypeFieldsList = $cacheListObj->fetchFromCache();
	    	if ($articleTypeFieldsList !== false
	    	&& is_array($articleTypeFieldsList)) {
	    		return $articleTypeFieldsList;
	    	}
	    }

	    $whereClauses = array();
	    if (isset($p_name)) {
	    	$operator = $p_negateName ? '<>' : '=';
	        $whereClauses[] = "field_name $operator '" . $g_ado_db->escape($p_name) . "'";
	    }
	    if (isset($p_articleType)) {
            $operator = $p_negateArticleType ? '<>' : '=';
	    	$whereClauses[] = "type_name $operator '" . $g_ado_db->escape($p_articleType) . "'";
	    }
	    if (isset($p_dataType)) {
            $operator = $p_negateDataType ? '<>' : '=';
	    	$whereClauses[] = "field_type $operator '" . $g_ado_db->escape($p_dataType) . "'";
	    }
	    if (!$p_selectHidden) {
	    	$whereClauses[] = 'is_hidden = false';
	    }
	    $where = count($whereClauses) > 0 ? ' WHERE ' . implode(' and ', $whereClauses) : null;
	    $query = "SELECT * FROM `ArticleTypeMetadata` $where ORDER BY type_name ASC, field_weight ASC";
	    $rows = $g_ado_db->GetAll($query);
	    $fields = array();
	    foreach ($rows as $row) {
	    	$field = new ArticleTypeField($row['type_name'], $row['field_name']);
	    	if ($field->getPrintName() == '') {
	    		$field->delete();
	    		continue;
	    	}
	        $fields[] = $field;
	    }
	    if (!$p_skipCache && CampCache::IsEnabled()) {
	        $cacheListObj->storeInCache($fields);
	    }

	    return $fields;
	} // fn FetchFields


	/**
	 * Returns an array of valid field data types.
	 * @return array
	 */
	public static function DatabaseTypes($p_numericDigits = null, $p_numericPrecision = null)
	{
		$p_numericDigits = is_null($p_numericDigits) ? self::NUMERIC_DEFAULT_DIGITS : $p_numericDigits;
		$p_numericPrecision = is_null($p_numericPrecision) ? self::NUMERIC_DEFAULT_PRECISION : $p_numericPrecision;
		settype($p_numericDigits, 'integer');
		settype($p_numericPrecision, 'integer');
		$numericDef = "NUMERIC($p_numericDigits, $p_numericPrecision) NOT NULL";

		$types = array(self::TYPE_TEXT=>'VARCHAR(255) NOT NULL',
			 self::TYPE_BODY=>'MEDIUMBLOB NOT NULL',
			 self::TYPE_DATE=>'DATE NOT NULL',
			 self::TYPE_TOPIC=>'INTEGER UNSIGNED NOT NULL',
			 self::TYPE_SWITCH=>'BOOLEAN NOT NULL',
			 self::TYPE_NUMERIC=>$numericDef);
        return $types;
	}
} // class ArticleTypeField

?>
Back to Top