Tuskfish API
  • Package
  • Class

Packages

  • content
  • core
  • database
  • installation
  • security
  • user
  • utilities

Classes

  • TfishAncestralObject
  • TfishAngryTree
  • TfishArticle
  • TfishArticleHandler
  • TfishAudio
  • TfishAudioHandler
  • TfishBlock
  • TfishBlockHandler
  • TfishCache
  • TfishCollection
  • TfishCollectionHandler
  • TfishContentHandler
  • TfishContentObject
  • TfishCriteria
  • TfishCriteriaItem
  • TfishDatabase
  • TfishDownload
  • TfishDownloadHandler
  • TfishFileHandler
  • TfishFilter
  • TfishImage
  • TfishImageHandler
  • TfishLogger
  • TfishMetadata
  • TfishPreference
  • TfishPreferenceHandler
  • TfishRss
  • TfishSecurityUtility
  • TfishSession
  • TfishStatic
  • TfishStaticHandler
  • TfishTag
  • TfishTagHandler
  • TfishTaglink
  • TfishTaglinkHandler
  • TfishTemplate
  • TfishUser
  • TfishUtils
  • TfishVideo
  • TfishVideoHandler
  • TfishYubikeyAuthenticator

Functions

  • getUrl
  • tfish_autoload
   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  878  879  880  881  882  883  884  885  886  887  888  889  890  891  892  893  894  895  896  897  898  899  900  901  902  903  904  905  906  907  908  909  910  911  912  913  914  915  916  917  918  919  920  921  922  923  924  925  926  927  928  929  930  931  932  933  934  935  936  937  938  939  940  941  942  943  944  945  946  947  948  949  950  951  952  953  954  955  956  957  958  959  960  961  962  963  964  965  966  967  968  969  970  971  972  973  974  975  976  977  978  979  980  981  982  983  984  985  986  987  988  989  990  991  992  993  994  995  996  997  998  999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 
<?php

/**
 * TfishContentHandler class file.
 * 
 * @copyright   Simon Wilkinson 2013-2017 (https://tuskfish.biz)
 * @license     https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html GNU General Public License (GPL) V2
 * @author      Simon Wilkinson <[email protected]>
 * @version     Release: 1.0
 * @since       1.0
 * @package     content
 */

// Enable strict type declaration.
declare(strict_types=1);

if (!defined("TFISH_ROOT_PATH")) die("TFISH_ERROR_ROOT_PATH_NOT_DEFINED");

/**
 * Base class for content handler objects.
 * 
 * Provides base content handler methods that are inherited or overridden by subclass-specific
 * content handlers. You can use it as a generic handler when you want to retrieve mixed content
 * types. If you want to retrieve a specific content type it would be better to use the specific
 * content handler for that type, as it may contain additional functionality for processing or
 * displaying it.
 *
 * @copyright   Simon Wilkinson 2013-2017 (https://tuskfish.biz)
 * @license     https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html GNU General Public License (GPL) V2
 * @author      Simon Wilkinson <[email protected]>
 * @version     Release: 1.0
 * @since       1.0
 * @package     content
 */
class TfishContentHandler
{

    /**
     * Delete a single object from the content table.
     * 
     * @param int $id ID of content object to delete.
     * @return bool True on success, false on failure.
     */
    public static function delete(int $id)
    {
        $clean_id = (int) $id;
        
        if (!TfishFilter::isInt($clean_id, 1)) {
            trigger_error(TFISH_ERROR_NOT_INT, E_USER_ERROR);
            return false;
        }

        // Delete associated files.
        $obj = self::getObject($clean_id);
        
        if (!TfishFilter::isObject($obj)) {
            trigger_error(TFISH_ERROR_NOT_OBJECT, E_USER_ERROR);
            return false;
        }
        
        if (!empty($obj->image)) {
            self::_deleteImage($obj->image);
        }

        if (!empty($obj->media)) {
            self::_deleteMedia($obj->media);
        }

        // Delete associated taglinks. If this object is a tag, delete taglinks referring to it.
        $result = TfishTaglinkHandler::deleteTaglinks($obj);
        
        if (!$result) {
            return false;
        }

        // If object is a collection delete related parent references in child objects.
        if ($obj->type === 'TfishCollection') {
            $criteria = new TfishCriteria();
            $criteria->add(new TfishCriteriaItem('parent', $clean_id));
            $result = TfishDatabase::updateAll('content', array('parent' => 0), $criteria);
            
            if (!$result) {
                return false;
            }
        }

        // Delete the object.
        $result = TfishDatabase::delete('content', $clean_id);
        
        if (!$result) {
            return false;
        }

        return true;
    }
    
    /**
     * Removes references to a collection when it is deleted or changed to another type.
     * 
     * @param int $id ID of the parent collection.
     * @return boolean True on success, false on failure.
     */
    public static function deleteParentalReferences(int $id)
    {
        $clean_id = TfishFilter::isInt($id, 1) ? (int) $id : null;
        
        if (!$clean_id) {
            trigger_error(TFISH_ERROR_NOT_INT, E_USER_ERROR);
        }
        
        $criteria = new TfishCriteria();
        $criteria->add(new TfishCriteriaItem('parent', $clean_id));
        $result = TfishDatabase::updateAll('content', array('parent' => 0), $criteria);

        if (!$result) {
            return false;
        }
        
        return true;
    }

    /**
     * Deletes an uploaded image file associated with a content object.
     * 
     * @param string $filename Name of file.
     * @return bool True on success, false on failure.
     */
    private static function _deleteImage(string $filename)
    {
        if ($filename) {
            return TfishFileHandler::deleteFile('image/' . $filename);
        }
    }

    /**
     * Deletes an uploaded media file associated with a content object.
     * 
     * @param string $filename Name of file.
     * @return bool True on success, false on failure.
     */
    private static function _deleteMedia(string $filename)
    {
        if ($filename) {
            return TfishFileHandler::deleteFile('media/' . $filename);
        }
    }

    /**
     * Inserts a content object into the database.
     * 
     * Note that content child content classes that have unset unused properties from the parent
     * should reset them to null before insertion or update. This is to guard against the case
     * where the admin reassigns the type of a content object - it makes sure that unused properties
     * are zeroed in the database. 
     * 
     * @param object $obj TfishContentObject subclass.
     * @return bool True on success, false on failure.
     */
    public static function insert(TfishContentObject $obj)
    {   
        $key_values = $obj->toArray();
        $key_values['submission_time'] = time(); // Automatically set submission time.
        unset($key_values['id']); // ID is auto-incremented by the database on insert operations.
        unset($key_values['tags']);

        // Process image and media files before inserting the object, as related fields must be set.
        $property_whitelist = $obj->getPropertyWhitelist();
        
        if (array_key_exists('image', $property_whitelist) && !empty($_FILES['image']['name'])) {
            $filename = TfishFilter::trimString($_FILES['image']['name']);
            $clean_filename = TfishFileHandler::uploadFile($filename, 'image');
            
            if ($clean_filename) {
                $key_values['image'] = $clean_filename;
            }
        }

        if (array_key_exists('media', $property_whitelist) && !empty($_FILES['media']['name'])) {
            $filename = TfishFilter::trimString($_FILES['media']['name']);
            $clean_filename = TfishFileHandler::uploadFile($filename, 'media');
            
            if ($clean_filename) {
                $key_values['media'] = $clean_filename;
                $mimetype_whitelist = TfishFileHandler::getPermittedUploadMimetypes();
                $extension = pathinfo($clean_filename, PATHINFO_EXTENSION);
                $key_values['format'] = $mimetype_whitelist[$extension];
                $key_values['file_size'] = $_FILES['media']['size'];
            }
        }

        // Insert the object into the database.
        $result = TfishDatabase::insert('content', $key_values);
        
        if (!$result) {
            trigger_error(TFISH_ERROR_INSERTION_FAILED, E_USER_ERROR);
            return false;
        } else {
            $content_id = TfishDatabase::lastInsertId();
        }
        
        unset($key_values, $result);

        // Tags are stored separately in the taglinks table. Tags are assembled in one batch before
        // proceeding to insertion; so if one fails a range check all should fail.
        if (isset($obj->tags) and TfishFilter::isArray($obj->tags)) {
            // If the lastInsertId could not be retrieved, then halt execution becuase this data
            // is necessary in order to correctly assign taglinks to content objects.
            if (!$content_id) {
                trigger_error(TFISH_ERROR_NO_LAST_INSERT_ID, E_USER_ERROR);
                exit;
            }

            $result = TfishTaglinkHandler::insertTaglinks($content_id, $obj->type, $obj->tags);
            
            if (!$result) {
                return false;
            }
        }

        return true;
    }

    /**
     * Checks if a class name is a sanctioned subclass of TfishContentObject.
     * 
     * Basically this just checks if the class name is whitelisted.
     * 
     * @param string $type Type of content object.
     * @return bool True if sanctioned type otherwise false.
     */
    public static function isSanctionedType(string $type)
    {
        $type = TfishFilter::trimString($type);
        $sanctioned_types = self::getTypes();
        
        if (array_key_exists($type, $sanctioned_types)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * Get a list of tags actually in use by other content objects, optionally filtered by type.
     * 
     * Used primarily to build select box controls. Use $online_only to select only those tags that
     * are marked as online (true), or all tags (false).
     * 
     * @param string $type Type of content object.
     * @param bool $online_only True if marked as online, false if marked as offline.
     * @return array|bool List of tags if available, false if empty.
     */
    public static function getActiveTagList(string $type = null, bool $online_only = true)
    {
        $tags = $distinct_tags = array();

        $clean_online_only = TfishFilter::isBool($online_only) ? (bool) $online_only : true;
        $tags = self::getTagList($clean_online_only);
        
        if (empty($tags)) {
            return false;
        }

        // Restrict tag list to those actually in use.
        $clean_type = (isset($type) && self::isSanctionedType($type))
                ? TfishFilter::trimString($type) : null;

        $criteria = new TfishCriteria();

        // Filter tags by type.
        if (isset($clean_type)) {
            $criteria->add(new TfishCriteriaItem('content_type', $clean_type));
        }

        // Put a check for online status in here.
        $statement = TfishDatabase::selectDistinct('taglink', $criteria, array('tag_id'));
        
        if ($statement) {
            while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
                if (isset($tags[$row['tag_id']])) {
                    $distinct_tags[$row['tag_id']] = $tags[$row['tag_id']];
                }
            }
        }

        // Sort the tags into alphabetical order.
        asort($distinct_tags);

        return $distinct_tags;
    }

    /**
     * Count content objects optionally matching conditions specified with a TfishCriteria object.
     * 
     * @param object $criteria TfishCriteria object used to build conditional database query.
     * @return int $count Number of objects matching conditions.
     */
    public static function getCount(TfishCriteria $criteria = null)
    {
        if (!isset($criteria)) {
            $criteria = new TfishCriteria();
        }
        
        if ($criteria && !empty($criteria->limit)) {
            $limit = $criteria->limit;
            $criteria->limit = 0;
        }
        
        $count = TfishDatabase::selectCount('content', $criteria);
        
        if (isset($limit)) {
            $criteria->limit = (int) $limit;
        }

        return $count;
    }

    /**
     * Returns a list of languages for the content object submission form.
     * 
     * In the interests of brevity and sanity a full list is not provided. Add entries that you
     * want to use to the array using ISO 639-1 two-letter language codes, which you can find at:
     * https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes. Be aware that deleting entries that
     * are in use by your content objects will cause errors.
     * 
     * @return array Array of languages in ISO 639-1 code => name format.
     */
    public static function getLanguages()
    {
        return array(
            "en" => "English",
            "th" => "Thai",
        );
    }

    /**
     * Returns a list of content object titles with ID as key.
     * 
     * @param object $criteria TfishCriteria object used to build conditional database query.
     * @return array Array as id => title of content objects.
     */
    public static function getList(TfishCriteria $criteria = null)
    {
        $content_list = array();
        $columns = array('id', 'title');

        if (!isset($criteria)) {
            $criteria = new TfishCriteria();
        }
        
        // Set default sorting order by submission time descending.
        if (!$criteria->order) {
            $criteria->order = 'date';
        }

        $statement = TfishDatabase::select('content', $criteria, $columns);
        
        if ($statement) {
            while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
                $content_list[$row['id']] = $row['title'];
            }
            unset($statement);
        } else {
            trigger_error(TFISH_ERROR_NO_RESULT, E_USER_ERROR);
        }

        return $content_list;
    }

    /**
     * Retrieves a single content object based on its ID.
     * 
     * @param int $id ID of content object.
     * @return object|bool $object Object on success, false on failure.
     */
    public static function getObject(int $id)
    {
        $clean_id = (int) $id;
        $row = $object = '';
        
        if (TfishFilter::isInt($id, 1)) {
            $criteria = new TfishCriteria();
            $criteria->add(new TfishCriteriaItem('id', $clean_id));
            $statement = TfishDatabase::select('content', $criteria);
            
            if ($statement) {
                $row = $statement->fetch(PDO::FETCH_ASSOC);
            }
            
            if ($row) {
                $object = self::toObject($row);
                return $object;
            }
        }
        
        return false;
    }

    /**
     * Get content objects, optionally matching conditions specified with a TfishCriteria object.
     * 
     * @param object $criteria TfishCriteria object used to build conditional database query.
     * @return array Array of content objects.
     */
    public static function getObjects(TfishCriteria $criteria = null)
    {
        $objects = array();
        
        if (!isset($criteria)) {
            $criteria = new TfishCriteria();
        }

        // Set default sorting order by submission time descending.        
        if (!$criteria->order) {
            $criteria->order = 'date';
        }

        $statement = TfishDatabase::select('content', $criteria);
        if ($statement) {
            // Fetch rows into the appropriate class type, as determined by the first column.
            $statement->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE | PDO::FETCH_PROPS_LATE);
            
            while ($object = $statement->fetch()) {
                $objects[$object->id] = $object;
            }
            
            unset($statement);
        } else {
            trigger_error(TFISH_ERROR_NO_RESULT, E_USER_ERROR);
        }

        // Get the tags for these objects.
        if (!empty($objects)) {
            $taglinks = array();
            $object_ids = array_keys($objects);

            $criteria = new TfishCriteria();
            
            foreach ($object_ids as $id) {
                $criteria->add(new TfishCriteriaItem('content_id', (int) $id), "OR");
                unset($id);
            }

            $statement = TfishDatabase::select('taglink', $criteria);
            
            if ($statement) {
                // Sort tag into multi-dimensional array indexed by content_id.
                while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
                    $taglinks[$row['content_id']][] = $row['tag_id'];
                }

                // Assign the sorted tags to correct content objects.
                foreach ($taglinks as $content_id => $tags) {
                    $objects[$content_id]->tags = $tags;
                    unset($tags);
                }
            } else {
                trigger_error(TFISH_ERROR_NO_RESULT, E_USER_ERROR);
            }
        }

        return $objects;
    }

    /**
     * Generates an online/offline select box.
     * 
     * @param int $selected The currently option.
     * @param string $zero_option The text to display in the zero option of the select box.
     * @return string HTML select box.
     */
    public static function getOnlineSelectBox(int $selected = null,
            string $zero_option = TFISH_ONLINE_STATUS)
    {
        $clean_selected = (isset($selected) && TfishFilter::isInt($selected, 0, 1)) 
                ? (int) $selected : null; // Offline (0) or online (1)
        $clean_zero_option = TfishFilter::escape(TfishFilter::trimString($zero_option));
        $options = array(2 => TFISH_SELECT_STATUS, 1 => TFISH_ONLINE, 0 => TFISH_OFFLINE);
        $select_box = '<select class="form-control custom-select" name="online" id="online" '
                . 'onchange="this.form.submit()">';
        
        if (isset($clean_selected)) {
            foreach ($options as $key => $value) {
                $select_box .= ($key === $clean_selected) ? '<option value="' . $key . '" selected>' 
                        . $value . '</option>' : '<option value="' . $key . '">' . $value 
                        . '</option>';
            }
        } else { // Nothing selected
            $select_box .= '<option value="2" selected>' . TFISH_SELECT_STATUS . '</option>';
            $select_box .= '<option value="1">' . TFISH_ONLINE . '</option>';
            $select_box .= '<option value="0">' . TFISH_OFFLINE . '</option>';
        }

        $select_box .= '</select>';

        return $select_box;
    }

    /**
     * Returns a list of intellectual property rights licenses for the content submission form.
     * 
     * In the interests of brevity and sanity, a comprehensive list is not provided. Add entries
     * that you want to use to the array below. Be aware that deleting entries that are in use by
     * your content objects will cause errors.
     * 
     * @return array Array of copyright licenses.
     */
    public static function getRights()
    {
        return array(
            '1' => TFISH_RIGHTS_COPYRIGHT,
            '2' => TFISH_RIGHTS_ATTRIBUTION,
            '3' => TFISH_RIGHTS_ATTRIBUTION_SHARE_ALIKE,
            '4' => TFISH_RIGHTS_ATTRIBUTION_NO_DERIVS,
            '5' => TFISH_RIGHTS_ATTRIBUTION_NON_COMMERCIAL,
            '6' => TFISH_RIGHTS_ATTRIBUTION_NON_COMMERCIAL_SHARE_ALIKE,
            '7' => TFISH_RIGHTS_ATTRIBUTION_NON_COMMERCIAL_NO_DERIVS,
            '8' => TFISH_RIGHTS_GPL2,
            '9' => TFISH_RIGHTS_GPL3,
            '10' => TFISH_RIGHTS_PUBLIC_DOMAIN,
        );
    }

    /**
     * Get an array of all tag objects in $id => $title format.
     * 
     * @param bool Get tags marked online only.
     * @return array Array of tag IDs and titles.
     */
    public static function getTagList(bool $online_only = true)
    {
        $tags = array();
        $statement = false;
        $clean_online_only = TfishFilter::isBool($online_only) ? (bool) $online_only : true;
        $columns = array('id', 'title');
        $criteria = new TfishCriteria();
        $criteria->add(new TfishCriteriaItem('type', 'TfishTag'));
        
        if ($clean_online_only) {
            $criteria->add(new TfishCriteriaItem('online', true));
        }

        $statement = TfishDatabase::select('content', $criteria, $columns);
        
        if ($statement) {
            while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
                $tags[$row['id']] = $row['title'];
            }
            unset($statement);
        } else {
            trigger_error(TFISH_ERROR_NO_RESULT, E_USER_ERROR);
        }
        
        asort($tags);

        return $tags;
    }

    /**
     * Get an array of all tag objects.
     * 
     * Use this function when you need to build a buffer of tags to reduce database queries, for
     * example when looping through a result set.
     * 
     * @return array Array of TfishTag objects.
     */
    public static function getTags()
    {
        $tags = array();
        $criteria = new TfishCriteria();
        $criteria->add(new TfishCriteriaItem('type', 'TfishTag'));
        $tags = self::getObjects($criteria);
        
        return $tags;
    }
    
    /**
     * Search the filtering criteria ($criteria->items) to see if object type has been set and
     * return the key.
     * 
     * @param array $criteria_items Array of TfishCriteriaItem objects.
     * @return int|null Key of relevant TfishCriteriaItem or null.
     */
    protected static function getTypeIndex(array $criteria_items)
    {
        foreach ($criteria_items as $key => $item) {
            if ($item->column === 'type') {
                return $key;
            }
        }
        
        return null;
    }

    /**
     * Returns a whitelist of permitted content object types, ie. descendants of TfishContentObject.
     * 
     * Use this whitelist when dynamically instantiating content objects. If you create additional
     * types of content object (which must be descendants of the TfishContentObject class) you
     * must add them to the whitelist below. Otherwise their use will be denied in many parts of
     * the Tuskfish system.
     * 
     * @return array Array of whitelisted (permitted) content object types.
     */
    public static function getTypes()
    {
        return array(
            'TfishArticle' => TFISH_TYPE_ARTICLE,
            'TfishAudio' => TFISH_TYPE_AUDIO,
            'TfishBlock' => TFISH_TYPE_BLOCK,
            'TfishCollection' => TFISH_TYPE_COLLECTION,
            'TfishDownload' => TFISH_TYPE_DOWNLOAD,
            'TfishImage' => TFISH_TYPE_IMAGE,
            'TfishStatic' => TFISH_TYPE_STATIC,
            'TfishTag' => TFISH_TYPE_TAG,
            'TfishVideo' => TFISH_TYPE_VIDEO,
        );
    }

    /**
     * Get a content type select box.
     * 
     * @param string $selected Currently selected option.
     * @param string $zero_option The default text to show at top of select box.
     * @return string HTML select box.
     */
    public static function getTypeSelectBox(string $selected = '', string $zero_option = null)
    {
        // The text to display in the zero option of the select box.
        if (isset($zero_option)) {
            $clean_zero_option = TfishFilter::escape(TfishFilter::trimString($zero_option));
        } else {
            $clean_zero_option = TFISH_TYPE;
        }
        
        $clean_selected = '';
        $type_list = self::getTypes();

        if ($selected && TfishFilter::isAlnumUnderscore($selected)) {
            if (array_key_exists($selected, $type_list)) {
                $clean_selected = TfishFilter::trimString($selected);
            }
        }

        $options = array(0 => TFISH_SELECT_TYPE) + $type_list;
        $select_box = '<select class="form-control custom-select" name="type" id="type" '
                . 'onchange="this.form.submit()">';
        
        foreach ($options as $key => $value) {
            $select_box .= ($key === $clean_selected) ? '<option value="' . TfishFilter::escape($key)
                    . '" selected>' . TfishFilter::escape($value) . '</option>' : '<option value="'
                . TfishFilter::escape($key) . '">' . TfishFilter::escape($value) . '</option>';
        }
        
        $select_box .= '</select>';

        return $select_box;
    }

    /**
     * Converts an array of tag_ids into an array of tag links with an arbitrary local target file.
     * 
     * Note that the filename may only consist of alphanumeric characters and underscores. Do not
     * include the file extension (eg. use 'article' instead of 'article.php'. The base URL of the
     * site will be prepended and .php plus the tag_id will be appended.
     * 
     * @param array $tags Array of tag IDs.
     * @param string $target_filename Name of file for tag links to point at.
     * @return array Array of HTML tag links.
     */
    public static function makeTagLinks(array $tags, string $target_filename = '')
    {
        if (empty($target_filename)) {
            $clean_filename = TFISH_URL . '?tag_id=';
        } else {
            if (!TfishFilter::isAlnumUnderscore($target_filename)) {
                trigger_error(TFISH_ERROR_NOT_ALNUMUNDER, E_USER_ERROR);
            } else {
                $target_filename = TfishFilter::trimString($target_filename);
                $clean_filename = TFISH_URL . TfishFilter::escape($target_filename)
                        . '.php?tag_id=';
            }
        }

        $tag_list = self::getTagList(false);
        $tag_links = array();
        
        foreach ($tags as $tag) {
            if (TfishFilter::isInt($tag, 1) && array_key_exists($tag, $tag_list)) {
                $tag_links[$tag] = '<a href="' . TfishFilter::escape($clean_filename . $tag) . '">'
                        . TfishFilter::escape($tag_list[$tag]) . '</a>';
            }
            
            unset($tag);
        }

        return $tag_links;
    }

    /**
     * Provides global search functionality for content objects.
     * 
     * Escaping of search terms is handled through use of a PDO prepared statement with named 
     * placeholders; search terms are inserted indirectly by binding them to the placeholders.
     * Search terms must NEVER be inserted into a query directly (creates an SQL injection
     * vulnerability), otherwise do us all a favour and go shoot yourself now.
     * 
     * Search terms have entity encoding (htmlspecialchars) applied on the teaser and description
     * fields (only) to ensure consistency with the entity encoding treatment that these HTML fields
     * have been subjected to, otherwise searches involving entities will not return results.
     *
     * @param object $tfish_preference TfishPreference object, to make site preferences available.
     * @param string $search_terms Search terms.
     * @param string $andor Operator to chain search terms (AND or OR).
     * @param int $limit Maximum number of results to retrieve (pagination constraint).
     * @param int $offset Starting point for retrieving results (pagination constraint).
     * @return array|bool Array of content objects on success, false failure.
     */
    public static function searchContent(TfishPreference $tfish_preference, string $search_terms,
            string $andor, int $limit = 0, int $offset = 0)
    {
        
        $clean_search_terms = $escaped_search_terms = $clean_escaped_search_terms = array();
        $clean_andor = in_array($andor, array('AND', 'OR', 'exact'))
                ? TfishFilter::trimString($andor) : 'AND';
        $clean_limit = (int) $limit;
        $clean_offset = (int) $offset;
        
        // Create an escaped copy of the search terms that will be used to search the HTML teaser
        // and description fields.
        $escaped_search_terms = htmlspecialchars($search_terms, ENT_NOQUOTES, "UTF-8");

        if ($clean_andor === 'AND' || $clean_andor === 'OR') {
            $search_terms = explode(" ", $search_terms);
            $escaped_search_terms = explode(" ", $escaped_search_terms);
        } else {
            $search_terms = array($search_terms);
            $escaped_search_terms = array($escaped_search_terms);
        }
        
        // Trim search terms and discard any that are less than the minimum search length characters.
        foreach ($search_terms as $term) {
            $term = TfishFilter::TrimString($term);
            
            if (!empty($term) && mb_strlen($term, 'UTF-8') >= $tfish_preference->min_search_length) {
                $clean_search_terms[] = (string) $term;
            }
        }
        
        foreach ($escaped_search_terms as $escaped_term) {
            $escaped_term = TfishFilter::TrimString($escaped_term);
            
            if (!empty($escaped_term) && mb_strlen($escaped_term, 'UTF-8')
                    >= $tfish_preference->min_search_length) {
                $clean_escaped_search_terms[] = (string) $escaped_term;
            }
        }
        
        if (!empty($clean_search_terms)) {
            $results = self::_searchContent($tfish_preference, $clean_search_terms,
                    $clean_escaped_search_terms, $clean_andor, $clean_limit, $clean_offset);
        } else {
            $results = false;
        }

        return $results;
    }

    /** @internal */
    private static function _searchContent(TfishPreference $tfish_preference, array $search_terms,
            array $escaped_terms, string $andor, int $limit, int $offset)
    {
        $sql = $count = '';
        $search_term_placeholders = $escaped_term_placeholders = $results = array();
        
        $sql_count = "SELECT count(*) ";
        $sql_search = "SELECT * ";
        $result = array();

        $sql = "FROM `content` ";
        $count = count($search_terms);
        
        if ($count) {
            $sql .= "WHERE ";
            
            for ($i = 0; $i < $count; $i++) {
                $search_term_placeholders[$i] = ':search_term' . (string) $i;
                $escaped_term_placeholders[$i] = ':escaped_search_term' . (string) $i;
                $sql .= "(";
                $sql .= "`title` LIKE " . $search_term_placeholders[$i] . " OR ";
                $sql .= "`teaser` LIKE " . $escaped_term_placeholders[$i] . " OR ";
                $sql .= "`description` LIKE " . $escaped_term_placeholders[$i] . " OR ";
                $sql .= "`caption` LIKE " . $search_term_placeholders[$i] . " OR ";
                $sql .= "`creator` LIKE " . $search_term_placeholders[$i] . " OR ";
                $sql .= "`publisher` LIKE " . $search_term_placeholders[$i];
                $sql .= ")";
                
                if ($i != ($count - 1)) {
                    $sql .= " " . $andor . " ";
                }
            }
        }
        
        $sql .= " AND `online` = 1 AND `type` != 'TfishBlock' ORDER BY `date` DESC ";
        $sql_count .= $sql;
        
        // Bind the search term values and execute the statement.
        $statement = TfishDatabase::preparedStatement($sql_count);
        
        if ($statement) {
            for ($i = 0; $i < $count; $i++) {
                $statement->bindValue($search_term_placeholders[$i], "%" . $search_terms[$i] . "%",
                        PDO::PARAM_STR);
                $statement->bindValue($escaped_term_placeholders[$i], "%" . $escaped_terms[$i] . "%",
                        PDO::PARAM_STR);
            }
        } else {
            return false;
        }

        // Execute the statement.
        $statement->execute();

        $row = $statement->fetch(PDO::FETCH_NUM);
        $result[0] = reset($row);
        unset($statement);

        // Retrieve the subset of objects actually required.
        if (!$limit) {
            $limit = $tfish_preference->search_pagination;
        }
        
        $sql .= "LIMIT :limit ";
        
        if ($offset) {
            $sql .= "OFFSET :offset ";
        }

        $sql_search .= $sql;
        $statement = TfishDatabase::preparedStatement($sql_search);
        
        if ($statement) {
            for ($i = 0; $i < $count; $i++) {
                $statement->bindValue($search_term_placeholders[$i], "%" . $search_terms[$i] . "%",
                        PDO::PARAM_STR);
                $statement->bindValue($escaped_term_placeholders[$i], "%" . $escaped_terms[$i]
                        . "%", PDO::PARAM_STR);
                $statement->bindValue(":limit", (int) $limit, PDO::PARAM_INT);
                
                if ($offset) {
                    $statement->bindValue(":offset", (int) $offset, PDO::PARAM_INT);
                }
            }
        } else {
            return false;
        }

        // Execute the statement, fetch rows into the appropriate class type as determined by the
        // first column of the table.
        $statement->execute();
        $statement->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_CLASSTYPE | PDO::FETCH_PROPS_LATE);
        
        while ($object = $statement->fetch()) {
            $result[$object->id] = $object;
        }
        
        return $result;
    }

    /**
     * Toggle the online status of a content object.
     * 
     * @param int $id ID of content object.
     * @return boolean True on success, false on failure.
     */
    public static function toggleOnlineStatus(int $id)
    {
        $clean_id = (int) $id;
        return TfishDatabase::toggleBoolean($clean_id, 'content', 'online');
    }

    /**
     * Convert a database content row to a corresponding content object.
     * 
     * Only use this function to convert single objects, as it does a separate query to look up
     * the associated taglinks. Running it through a loop will therefore consume a lot of resources.
     * To convert multiple objects, load them directly into the relevant class files using
     * PDO::FETCH_CLASS, prepare a buffer of tags using getTags() and loop through the objects
     * referring to the buffer rather than hitting the database every time.
     * 
     * @param array $row Array of result set from database.
     * @return object|bool Content object on success, false on failure.
     */
    public static function toObject(array $row)
    {
        if (empty($row) || !TfishFilter::isArray($row)) {
            return false;
        }

        // Check the content type is whitelisted.
        $type_whitelist = self::getTypes();
        
        if (!empty($row['type']) && array_key_exists($row['type'], $type_whitelist)) {
            $content_object = new $row['type'];
        } else {
            trigger_error(TFISH_ERROR_ILLEGAL_VALUE, E_USER_ERROR);
        }

        // Populate the object from the $row using whitelisted properties.
        if ($content_object) {
            $content_object->loadProperties($row, true);

            // Populate the tag property.
            if (isset($content_object->tags) && !empty($content_object->id)) {
                $tags = array();
                $criteria = new TfishCriteria();
                $criteria->add(new TfishCriteriaItem('content_id', (int) $content_object->id));
                $statement = TfishDatabase::select('taglink', $criteria, array('tag_id'));
                
                if ($statement) {
                    while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
                        $tags[] = $row['tag_id'];
                    }
                    $content_object->tags = $tags;
                } else {
                    trigger_error(TFISH_ERROR_NO_RESULT, E_USER_ERROR);
                }
            }

            return $content_object;
        }

        return false;
    }

    /**
     * Updates a content object in the database.
     * 
     * @param object $obj TfishContentObject subclass.
     * @return bool True on success, false on failure.
     */
    public static function update(TfishContentObject $obj)
    {
        $clean_id = TfishFilter::isInt($obj->id, 1) ? (int) $obj->id : 0;
        $key_values = $obj->toArray();
        unset($key_values['submission_time']); // Submission time should not be overwritten.
        $zeroed_properties = $obj->zeroedProperties();
        
        foreach ($zeroed_properties as $property) {
            $key_values[$property] = null;
        }
        
        $property_whitelist = $obj->getPropertyWhitelist();

        // Tags are stored in a separate table and must be handled in a separate query.
        unset($key_values['tags']);

        // Load the saved object from the database. This will be used to make comparisons with the
        // current object state and facilitate clean up of redundant tags, parent references, and
        // image/media files.
        $saved_object = self::getObject($clean_id);
        
        /**
         * Handle image / media files for existing objects.
         */
        if (!empty($saved_object)) {

            /**
             * Image property.
             */
            
            // 1. Check if there is an existing image file associated with this content object.
            $existing_image = self::_checkImage($saved_object);

            // 2. Is this content type allowed to have an image property?
            if (!array_key_exists('image', $property_whitelist)) {
                $key_values['image'] = '';
                if ($existing_image) {
                    self::_deleteImage($existing_image);
                    $existing_image = '';
                }
            }
            
            // 3. Has an existing image file been flagged for deletion?
            if ($existing_image) {
                if (isset($_POST['deleteImage']) && !empty($_POST['deleteImage'])) {
                    $key_values['image'] = '';
                    self::_deleteImage($existing_image);
                    $existing_image = '';
                }
            }
            
            // 4. Check if a new image file has been uploaded by looking in $_FILES.
            if (array_key_exists('image', $property_whitelist)) {

                if (isset($_FILES['image']['name']) && !empty($_FILES['image']['name'])) {
                    $filename = TfishFilter::trimString($_FILES['image']['name']);
                    $clean_filename = TfishFileHandler::uploadFile($filename, 'image');
                    
                    if ($clean_filename) {
                        $key_values['image'] = $clean_filename;
                        
                        // Delete old image file, if any.
                        if ($existing_image) {
                            self::_deleteImage($existing_image);
                        }
                    } else {
                        $key_values['image'] = '';
                    }
                    
                } else { // No new image, use the existing file name.
                    $key_values['image'] = $existing_image;
                }
            }

            // If the updated object has no image attached, or has been instructed to delete
            // attached image, delete any old image files.
            if ($existing_image &&
                    ((!isset($key_values['image']) || empty($key_values['image']))
                    || (isset($_POST['deleteImage']) && !empty($_POST['deleteImage'])))) {
                self::_deleteImage($existing_image);
            }

            /**
             * Media property.
             */
            
            // 1. Check if there is an existing media file associated with this content object.
            $existing_media = self::_checkMedia($saved_object);
            
            // 2. Is this content type allowed to have a media property?
            if (!array_key_exists('media', $property_whitelist)) {
                $key_values['media'] = '';
                $key_values['format'] = '';
                $key_values['file_size'] = '';
                if ($existing_media) {
                    self::_deleteMedia($existing_media);
                    $existing_media = '';
                }
            }
            
            // 3. Has existing media been flagged for deletion?
            if ($existing_media) {
                if (isset($_POST['deleteMedia']) && !empty($_POST['deleteMedia'])) {
                    $key_values['media'] = '';
                    $key_values['format'] = '';
                    $key_values['file_size'] = '';
                    self::_deleteMedia($existing_media);
                    $existing_media = '';
                }
            }
            
            // 4. Process media file.
            if (array_key_exists('media', $property_whitelist)) {
                $clean_filename = '';
                
                // Get a whitelist of permitted mimetypes.
                $mimetype_whitelist = TfishFileHandler::getPermittedUploadMimetypes();
                
                // Get name of newly uploaded file (overwrites old one).
                if (isset($_FILES['media']['name']) && !empty($_FILES['media']['name'])) {
                    $filename = TfishFilter::trimString($_FILES['media']['name']);
                    $clean_filename = TfishFileHandler::uploadFile($filename, 'media'); 
                } else {
                    $clean_filename = $existing_media;
                }

                if ($clean_filename) {
                    if (isset($_FILES['media']['name']) && !empty($_FILES['media']['name'])) {
                        $extension = mb_strtolower(pathinfo($clean_filename, PATHINFO_EXTENSION), 'UTF-8');

                        // Set values of new media file.
                        $key_values['media'] = $clean_filename;
                        $key_values['format'] = $mimetype_whitelist[$extension];
                        $key_values['file_size'] = $_FILES['media']['size'];

                        // Delete any old media file.
                        if ($existing_media) {
                            self::_deleteMedia($existing_media);
                            $existing_media = '';
                        }
                    // No new media, use the existing file name. Still need to validate it as the
                    // content type may have changed.
                    } else {
                        if ($existing_media) {
                            $key_values['media'] = $existing_media;
                            $key_values['format'] = $obj->format;
                            $key_values['file_size'] = $obj->file_size;
                        }
                    }           
                } else {
                    $key_values['media'] = '';
                    $key_values['format'] = '';
                    $key_values['file_size'] = '';

                    // Delete any old media file.
                    if ($existing_media) {
                        self::_deleteMedia($existing_media);
                        $existing_media = '';
                    }
                }
            }
        }

        // Update tags.
        $result = TfishTaglinkHandler::updateTaglinks($clean_id, $obj->type, $obj->tags);
        
        if (!$result) {
            trigger_error(TFISH_ERROR_TAGLINK_UPDATE_FAILED, E_USER_NOTICE);
            return false;
        }
        
        // Check if this object used to be a collection. If it has been changed to something else
        // clean up any parental references to it.
        if ($key_values['type'] !== 'TfishCollection' && !empty($saved_object)) {
            $ex_collection = self::_checkExCollection($saved_object);
            
            if ($ex_collection === true) {
                $result = self::deleteParentalReferences($clean_id);
                
                if (!$result) {
                    trigger_error(TFISH_ERROR_PARENT_UPDATE_FAILED, E_USER_NOTICE);
                    return false;
                }
            }
        }

        // Update the content object.
        $result = TfishDatabase::update('content', $clean_id, $key_values);
        
        if (!$result) {
            trigger_error(TFISH_ERROR_INSERTION_FAILED, E_USER_ERROR);
        }
        
        unset($result);

        return true;
    }
    
    /**
     * Check if a content object is currently registered as a TfishCollection in the database.
     * 
     * When updating an object, this method is used to check if it used to be a collection. If so,
     * other content objects referring to it as parent will need to be updated. Note that you must
     * pass in the SAVED copy of the object from the database, rather than the 'current' version, 
     * as the purpose of the method is to determine if the object *used to be* a collection.
     * 
     * @param object $obj The TfishContentObject to be tested.
     * @return boolean True if content object is registered as a TfishCollection in database,
     * otherwise false.
     */
    private static function _checkExCollection(TfishContentObject $obj)
    {      
        if (!empty($obj->type) && $obj->type === 'TfishCollection') {
           return true; 
        }
        
        return false;
    }

    /**
     * Check if an existing object has an associated image file upload.
     * 
     * @param object $obj The TfishContentObject to be tested.
     * @return string Filename of associated image property.
     */
    private static function _checkImage(TfishContentObject $obj)
    {        
        if (!empty($obj->image)) {
            return $obj->image;
        }

        return '';
    }

    /**
     * Check if an existing object has an associated media file upload.
     * 
     * @param object $obj TfishContentObject to be tested.
     * @return string Filename of associated media property.
     */
    private static function _checkMedia(TfishContentObject $obj)
    {
        if (!empty($obj->media)) {
            return $obj->media;
        }
        
        return '';
    }

    /**
     * Increment a given content object counter field by one.
     * 
     * @param int $id ID of content object.
     */
    public static function updateCounter(int $id)
    {
        $clean_id = (int) $id;
        return TfishDatabase::updateCounter($clean_id, 'content', 'counter');
    }

}
Tuskfish API API documentation generated by ApiGen