Esempio n. 1
0
 public static function exportFromDatabase($saveDir = "")
 {
     // Prepare Values
     $class = get_called_class();
     $entityRecords = [];
     // Get the full list of entity records
     $records = Database::selectMultiple("SELECT id, data FROM entity_" . $class, []);
     foreach ($records as $record) {
         $entityRecords[$record['id']] = json_decode($record['data'], true);
     }
     // Get Relationships
     $results = Database::selectMultiple("SELECT entity_id, attribute, related_id FROM `entity_relationships` WHERE entity_class=?", [$class]);
     foreach ($results as $result) {
         $entityRecords[$result['entity_id']][$result['attribute']][] = $result['related_id'];
     }
     // If we have a save directory set, save this output to it
     if ($saveDir) {
         foreach ($entityRecords as $entityID => $entity) {
             File::create($saveDir . "/" . $class . "/" . $entityID . ".json", json_encode($entity, JSON_PRETTY_PRINT));
         }
     }
     return json_encode($entityRecords, JSON_PRETTY_PRINT);
 }
    public static function buildInput($columnName, $columnRules, $value, $parentCol = "", $number = 0)
    {
        // Prepare the name of the input
        $inputName = $parentCol == "" ? $columnName : $parentCol . "[" . $number . "][" . $columnName . "]";
        // Determine which column type the input is
        switch ($columnRules[0]) {
            ### Reference ###
            case "reference":
                // Get the related class, and make sure that it's valid
                $class = isset($columnRules[2]) ? $columnRules[2] : '';
                if (!$class or !class_exists($class)) {
                    continue;
                }
                // Get the reference type: int, string, etc.
                $referenceType = isset($columnRules[1]) ? (int) $columnRules[1] : 0;
                $displayFormat = $class::$displayFormat ? $class::$displayFormat : "";
                // Pull data from the reference table
                $fetchRef = Database::selectMultiple("SELECT * FROM " . $class::$table, []);
                // Use the join class' display format to format the dropdown text
                $seldropdown = '
				<select id="' . $columnName . '" name="' . $inputName . '">
					<option value="">-- Select Reference --</option>';
                foreach ($fetchRef as $ref) {
                    $text = $displayFormat;
                    foreach ($ref as $k => $v) {
                        $text = str_replace("{" . $k . "}", $v, $text);
                    }
                    $seldropdown .= '
					<option value="' . $ref[$class::$lookupKey] . '">' . $text . '</option>';
                }
                $seldropdown .= '
				</select>';
                return $seldropdown;
                ### Strings and Text ###
            ### Strings and Text ###
            case "string":
            case "text":
                // Identify all string-related form variables
                $minLength = isset($columnRules[1]) ? (int) $columnRules[1] : 0;
                $maxLength = isset($columnRules[2]) ? (int) $columnRules[2] : ($columnRules[0] == "text" ? 0 : 250);
                // Display a textarea for strings of 101 characters or more
                if (!$maxLength or $maxLength > 100) {
                    return '
					<textarea id="' . $columnName . '" name="' . $inputName . '"' . ($maxLength ? 'maxlength="' . $maxLength . '"' : '') . '>' . htmlspecialchars($value) . '</textarea>';
                }
                // Display a text input for a string of 100 characters or less
                return '
				<input id="' . $columnName . '" type="text"
					name="' . $inputName . '"
					value="' . htmlspecialchars($value) . '"' . ($maxLength ? 'maxlength="' . $maxLength . '"' : '') . '
					/>';
                ### Integers ###
            ### Integers ###
            case "tinyint":
                // 256
            // 256
            case "smallint":
                // 65k
            // 65k
            case "mediumint":
            case "int":
            case "bigint":
                // Identify all string-related form variables
                $minRange = isset($columnRules[1]) ? (int) $columnRules[1] : null;
                $maxRange = isset($columnRules[2]) ? (int) $columnRules[2] : null;
                $maxLength = self::getLengthOfNumberType($columnRules[0], $minRange, $maxRange);
                // Display the form field for an integer
                return '
				<input id="' . $columnName . '" type="number"
					name="' . $inputName . '"
					value="' . (int) $value . '"' . ($maxLength ? 'maxlength="' . $maxLength . '"' : '') . ($minRange ? 'min="' . $minRange . '"' : '') . ($maxRange ? 'max="' . $maxRange . '"' : '') . '
					/>';
                ### Floats ###
            ### Floats ###
            case "float":
            case "double":
                // Identify all string-related form variables
                $minRange = isset($columnRules[1]) ? (int) $columnRules[1] : null;
                $maxRange = isset($columnRules[2]) ? (int) $columnRules[2] : null;
                $maxLength = self::getLengthOfNumberType($columnRules[0], $minRange, $maxRange);
                // Display the form field for an integer
                return '
				<input id="' . $columnName . '" type="text"
					name="' . $inputName . '"
					value="' . (int) $value . '"' . ($maxLength ? 'maxlength="' . ($maxLength + ceil($maxLength / 3)) . '"' : '') . '
					/>';
                ### Booleans ###
            ### Booleans ###
            case "bool":
            case "boolean":
                // If the boolean types are not declared, set defaults
                $trueName = isset($columnRules[1]) ? $columnRules[1] : 'True';
                $falseName = isset($columnRules[2]) ? $columnRules[2] : 'False';
                // Display the form field for a boolean
                return str_replace('value="' . $value . '"', 'value="' . $value . '" selected', '
				<select id="' . $columnName . '" name="' . $inputName . '">
					<option value="1">' . htmlspecialchars($trueName) . '</option>
					<option value="0">' . htmlspecialchars($falseName) . '</option>
				</select>');
                ### Enumerators ###
            ### Enumerators ###
            case "enum-number":
            case "enum-string":
                // Get the available list of enumerators
                $enums = array_slice($columnRules, 1);
                // Display the form field for a boolean
                $inputHTML = '
				<select id="' . $columnName . '" name="' . $inputName . '">';
                // Handle numeric enumerators differently than string enumerators
                // These will have a numeric counter associated with each value
                if ($columnRules[0] == "enum-number") {
                    $enumCount = count($enums);
                    for ($i = 0; $i < $enumCount; $i++) {
                        $inputHTML .= '
						<option value="' . $i . '"' . ($value == $i ? ' selected' : '') . '>' . htmlspecialchars($enums[$i]) . '</option>';
                    }
                } else {
                    foreach ($enums as $enum) {
                        $inputHTML .= '
						<option value="' . htmlspecialchars($enum) . '"' . ($value == $enum ? ' selected' : '') . '>' . htmlspecialchars($enum) . '</option>';
                    }
                }
                $inputHTML .= '
				</select>';
                return $inputHTML;
        }
    }
 private function getSimpleDiff($branchID, $versionPast, $versionFuture)
 {
     // Prepare the diff
     $diff = array();
     // Pull all commits between $versionPast and $versionFuture
     $results = Database::selectMultiple("SELECT instruction_set FROM version_control_commits WHERE branch_id=? AND commit_id BETWEEN ? AND ? ORDER BY commit_id=?", array($branchID, $versionPast, $versionFuture));
     // Loop through each commit
     foreach ($results as $instruction) {
         // Loop through each table in the instruction set
         foreach ($instruction['instruction_set'] as $table => $tableData) {
             // Extract the unique key
             $uniqueKey = $tableData['~uniqueKey'];
             // Remove the unique key from the list (for looping)
             unset($tableData['~uniqueKey']);
             // Loop through each row
             foreach ($tableData as $rowID => $updateList) {
                 // Loop through each row's updates
                 foreach ($updateList as $nextUpdate) {
                     // Check if the diff entry for this row/column has already been created.
                     if (isset($diff[$table][$rowID][$nextUpdate[0]])) {
                         // Don't overwrite the past version for thiw row/column
                         $diff[$table][$rowID][$nextUpdate[0]]["future"] = $nextUpdate[2];
                     } else {
                         $diff[$table][$rowID][$nextUpdate[0]] = array("past" => $nextUpdate[1], "future" => $nextUpdate[2]);
                     }
                 }
             }
         }
     }
     // Return the diff
     return $diff;
 }
Esempio n. 4
0
 public static function load($keyGroup, $keyName = "", $table = "")
 {
     $table = $table == "" ? "site_variables" : Sanitize::variable($table);
     // Retrieve the whole key group
     if ($keyName == "") {
         $keyList = array();
         $getValues = Database::selectMultiple("SELECT key_name, value FROM " . $table . " WHERE key_group=?", array($keyGroup));
         foreach ($getValues as $value) {
             $keyList[$value['key_name']] = json_decode($value['value']);
         }
         return $keyList;
     }
     // Retrieve a specific key
     if ($getValue = Database::selectValue("SELECT value FROM " . $table . " WHERE key_group=? AND key_name=? LIMIT 1", array($keyGroup, $keyName))) {
         return json_decode($getValue);
     }
     return false;
 }
 public static function showPartitions($table)
 {
     return Database::selectMultiple("SELECT partition_name, partition_description, table_rows FROM information_schema.partitions WHERE table_schema=schema() AND table_name=?", array($table));
 }
Esempio n. 6
0
    header("Location: /admin");
    exit;
}
// Prepare Values
set_time_limit(300);
// Set the timeout limit to 5 minutes.
// Run Header
require SYS_PATH . "/controller/includes/admin_header.php";
// Run Global Script (if applicable)
if (isset($_GET['action']) and $_GET['action'] == "run") {
    Database::initRoot();
    echo "Running Script:<br />";
    // Prepare Valuess
    define("PROTECTED", true);
    // Gather Sites
    $siteList = Database::selectMultiple("SELECT site_handle, site_name FROM network_data", array());
    foreach ($siteList as $site) {
        $apiData = API_Data::get($site['site_handle']);
        $success = API_Connect::call($apiData['site_url'] . "/api/AuthCommand", "system-script", $apiData['site_key']);
        if ($success) {
            echo "<br /><span style='color:green;'>" . $site['site_name'] . " run their instructions SUCCESSFULLY!</span>";
        } else {
            echo "<br /><span style='color:red;'>" . $site['site_name'] . " FAILED! Some or all of the instructions did not run as desired.</span>";
        }
    }
    echo "<br /><br />Script Complete.";
} else {
    echo '
	<p>Are you sure you want to have all sites run the system-wide script "{SYS_PATH}/system-script.php" on the entire universe system?</p>
	<p><a class="button" href="/admin/scripts/run-universe?action=run">Yes, run the script</a></p>';
}
Esempio n. 7
0
/*

This page is used to force the sync to run.
*/
// Run Permissions
require SYS_PATH . "/controller/includes/admin_perm.php";
// Only the webmaster can access this page
if (Me::$clearance < 9) {
    header("Location: /admin");
    exit;
}
// Run Header
require SYS_PATH . "/controller/includes/admin_header.php";
// Display Page
var_dump(time());
$results = Database::selectMultiple("SELECT * FROM sync_tracker", array());
echo '
<table class="mod-table">
<tr>
	<td>Class</td>
	<td>Tracker</td>
	<td>Last Sync Time</td>
	<td>Delay</td>
</tr>';
foreach ($results as $syncData) {
    echo '
	<tr>
		<td>' . $syncData['plugin'] . '</td>
		<td>' . Time_Fuzzy::run((int) $syncData['tracker_time']) . '</td>
		<td>' . Time_Fuzzy::run((int) $syncData['sync_time']) . '</td>
		<td>' . $syncData['delay'] . '</td>
Esempio n. 8
0
 public static function search($searchArgs = ['_GET'], &$rowCount = 0, $pullChildren = false)
 {
     // If no search arguments are provided, default to using $_GET
     if ($searchArgs == ['_GET']) {
         $searchArgs = $_GET;
     }
     // Prepare values that handle reserved keywords
     list($limit, $offset, $orderBy, $columns) = static::extractReservedKeywords($searchArgs);
     // Load the conversion
     list($whereStr, $sqlArray) = static::convertArgsToWhereSQL($searchArgs);
     // If we're retrieving multiple columns, we need to delimit them
     if (is_array($columns)) {
         $columns = implode(", ", $columns);
     }
     // Prepare Ordering
     $orderStr = "";
     foreach ($orderBy as $order) {
         $orderStr .= ($orderStr ? ", " : "") . $order[0] . " " . $order[1];
     }
     $orderStr = $orderStr ? " ORDER BY " . $orderStr : "";
     // Prepare the Limit / Pagination
     $limitStr = $limit ? " LIMIT " . ($offset + 0) . ", " . ($limit + 0) : "";
     // Get the number of rows that were possible to retrieve (for pagination purposes)
     $rowCount = Database::selectValue("SELECT COUNT(*) as totalNum FROM `" . static::$table . "`" . ($whereStr ? " WHERE " . $whereStr : ""), $sqlArray);
     // Pull the rows located by the search
     $results = Database::selectMultiple("SELECT " . $columns . " FROM `" . static::$table . "`" . ($whereStr ? " WHERE " . $whereStr : "") . $orderStr . $limitStr, $sqlArray);
     // For searches that are not traversing the tree, we can end here.
     // Also, if there were no results, return now before trying to locate children classes.
     if ($pullChildren == false or !$results) {
         return $results;
     }
     // Now for the complicated work....
     /*
     	We have an important mapping behavior to consider:
     	
     	The lookup ID's of the child results are important for mapping child records BACK to their parent records.
     	Therefore, we need to map the child records to the result ID's of the parent using the lookup key
     	that was used to call them.
     	
     	For example:
     		The first RESULT ID is always equal to 0. The LOOKUP KEY is "id" and it matched a LOOKUP ID of "7".
     		By mapping LOOKUP ID of 7 to RESULT ID of 0, we can save the records properly.
     */
     // Extract the lookup ID's from the results
     // This is essentially doing array_map()'s work, but we need to pass the lookup key, which it doesn't allow.
     $mapLookupIDToResultID = [];
     foreach ($results as $key => $res) {
         $mapLookupIDToResultID[$res[static::$lookupKey]] = $key;
     }
     // Now that we have the IDs that were tracked, we can load them into the relationships.
     // Find the relationship classes and include them with the traversal
     foreach (static::$schema['relationships'] as $relColumn => $relatedClass) {
         // Get insight into the type of class that we're joining
         $relationshipType = get_parent_class($relatedClass);
         if ($relationshipType == "Model_Join") {
             $joinedClass = $relatedClass::$relatedClass;
             $canHaveMany = true;
             // Get the child results through the join table
             $childResults = Database::selectMultiple("SELECT t1." . $relatedClass::$lookupKey . " as _t1_lookupID, t2.* FROM " . $relatedClass::$table . " t1 INNER JOIN " . $joinedClass::$table . " t2 ON t1." . $relatedClass::$relatedKey . "=t2." . $joinedClass::$lookupKey . " WHERE t1." . $relatedClass::$lookupKey . " IN (?" . str_repeat(', ?', count($mapLookupIDToResultID) - 1) . ")", array_keys($mapLookupIDToResultID));
             // We need to set the keys in the child results to match the ID's of the parent results
             // so that we know how they relate.
             $newChildResults = [];
             foreach ($childResults as $row) {
                 // We need to remove the lookup ID from the list, but preserve the value
                 $recordID = $mapLookupIDToResultID[$row['_t1_lookupID']];
                 unset($row['_t1_lookupID']);
                 $newChildResults[$recordID][] = $row;
             }
             // Now we load the child results into the parent records
             foreach ($newChildResults as $resultID => $row) {
                 $results[$resultID][$relColumn] = $row;
             }
         } else {
             if ($relationshipType == "Model_Child") {
                 // Get the child records
                 $childResults = Database::selectMultiple("SELECT t1.* FROM " . $relatedClass::$table . " t1 WHERE " . $relatedClass::$lookupKey . " IN (?" . str_repeat(', ?', count($mapLookupIDToResultID) - 1) . ")", array_keys($mapLookupIDToResultID));
                 // We need to set the keys in the child results to match the ID's of the parent results
                 // so that we know how they relate.
                 $newChildResults = [];
                 foreach ($childResults as $row) {
                     $newChildResults[$mapLookupIDToResultID[$row[$relatedClass::$lookupKey]]][] = $row;
                 }
                 // Now we load the child results into the parent records
                 // However, we first check if there can be multiple children rows - since this
                 // will affect how we append each row.
                 if ($relatedClass::$canHaveMany == true) {
                     foreach ($newChildResults as $resultID => $row) {
                         $results[$resultID][$relColumn][] = $row;
                     }
                 } else {
                     foreach ($newChildResults as $resultID => $row) {
                         $results[$resultID][$relColumn] = $row;
                     }
                 }
             }
         }
     }
     return $results;
 }
Esempio n. 9
0
 public static function loadWidgetsFromDatabase($container = "")
 {
     // Load the container's widgets from the database if one was specified
     if ($container !== "") {
         $widgetList = Database::selectMultiple("SELECT * FROM widget_loader WHERE container=?", array($container));
     } else {
         $widgetList = Database::selectMultiple("SELECT * FROM widget_loader", array($container));
     }
     // Attempts to find the widget plugin being loaded
     foreach ($widgetList as $widget) {
         // Make sure the widget's class exists
         if (!class_exists($widget['widget'])) {
             continue;
         }
         // Make sure this is a valid widget
         if (get_parent_class($widgetClass) != "Widget") {
             continue;
         }
         // Use the JSON value provided to insert arguments that the widget uses
         $instructions = json_decode($widget['instructions']);
         // Make sure the instructions come from a valid array
         if (!is_array($instructions)) {
             continue;
         }
         // Instantiate $widgetClass
         $widgetClass = new $widget['widget']($instructions);
         // Add the widget to the container
         self::$slots[$container][(int) $widget['sort_order']][] = $widgetClass->content;
     }
 }