function export($path = null, $destination = null) { set_time_limit(0); if (!is_array($path) && !empty($path)) { $path = Site::splitPath($path); } if (empty($path)) { $files = DB::allRecords('SELECT MAX(`ID`) as `RID`' . ' FROM `_e_files`' . ' GROUP BY `Handle`,`CollectionID`'); foreach ($files as $file) { $SiteFile = SiteFile::getByID($file['RID'])->getData(); if (strpos($SiteFile['FullPath'], '_parent') !== 0 && $SiteFile['Status'] != 'Deleted') { $SiteFiles[$SiteFile['FullPath']] = Site::$rootPath . '/data/' . $SiteFile['ID']; } } } else { throw new Exception('Sub directories not yet supported.'); } if (count($SiteFiles)) { $zip = new ZipArchive(); $tmp = $destination ? $destination : tempnam("/tmp", "emr"); if ($zip->open($tmp) === TRUE) { foreach ($SiteFiles as $virtualPath => $realPath) { $zip->addFromString($virtualPath, file_get_contents($realPath)); } } $zip->close(); return $tmp; } else { throw new Exception('Nothing to compress found.'); } }
public static function handleCollectionsRequest() { $tags = DB::allRecords('SELECT Tag.*, (SELECT COUNT(*) FROM `%2$s` AS TagItem WHERE Tag.`%3$s` = TagItem.`%4$s` AND TagItem.`%6$s` = "Media") AS itemsCount FROM `%1$s` AS Tag ORDER BY itemsCount', array(Tag::$tableName, TagItem::$tableName, Tag::getColumnName('ID'), TagItem::getColumnName('TagID'), Tag::getColumnName('Title'), TagItem::getColumnName('ContextClass'))); $allMediaCollection = array('Title' => 'All Media', 'itemsCount' => DB::oneValue('SELECT COUNT(*) FROM `%s`', Media::$tableName), 'nodeType' => 'allMedia'); $tagsCollection = array('Title' => 'Tagged Media', 'itemsCount' => array_sum(array_map(function ($tag) { return $tag['itemsCount']; }, $tags)), 'nodeType' => 'tags', 'children' => array_map(function ($tag) { $tag['nodeType'] = 'tag'; return $tag; }, $tags)); return static::respond('collections', array($allMediaCollection, $tagsCollection)); }
public static function getTagsSummary($options = array()) { $options = array_merge(array('tagConditions' => array(), 'itemConditions' => array(), 'Class' => false, 'classConditions' => array(), 'overlayTag' => false, 'order' => 'itemsCount DESC', 'excludeEmpty' => true, 'limit' => false), $options); // initialize conditions $options['tagConditions'] = Tag::mapConditions($options['tagConditions']); if (!empty($options['Class'])) { $options['classConditions'] = $options['Class']::mapConditions($options['classConditions']); } $options['itemConditions'] = TagItem::mapConditions($options['itemConditions']); // build query if (!empty($options['classConditions'])) { $classSubquery = 'SELECT `%s` FROM `%s` WHERE (%s)'; $classParams = array($options['Class']::getColumnName('ID'), $options['Class']::$tableName, join(') AND (', $options['classConditions'])); } $itemsCountQuery = 'SELECT COUNT(*) FROM `%s` TagItem WHERE TagItem.`%s` = Tag.`%s` AND (%s)'; $itemsCountParams = array(TagItem::$tableName, TagItem::getColumnName('TagID'), Tag::getColumnName('ID'), count($options['itemConditions']) ? join(') AND (', $options['itemConditions']) : '1'); if (!empty($options['overlayTag'])) { if (!is_object($OverlayTag = $options['overlayTag']) && !($OverlayTag = Tag::getByHandle($options['overlayTag']))) { throw new Excoption('Overlay tag not found'); } $itemsCountQuery .= sprintf(' AND (TagItem.`%s`,TagItem.`%s`) IN (SELECT OverlayTagItem.`%s`, OverlayTagItem.`%s` FROM `%s` OverlayTagItem WHERE OverlayTagItem.`%s` = %u)', TagItem::getColumnName('ContextClass'), TagItem::getColumnName('ContextID'), TagItem::getColumnName('ContextClass'), TagItem::getColumnName('ContextID'), TagItem::$tableName, TagItem::getColumnName('TagID'), $OverlayTag->ID); } if (isset($classSubquery)) { $itemsCountQuery .= sprintf(' AND TagItem.`%s` = "%s" AND TagItem.`%s` IN (%s)', TagItem::getColumnName('ContextClass'), $options['Class']::getStaticRootClass(), TagItem::getColumnName('ContextID'), DB::prepareQuery($classSubquery, $classParams)); } $tagSummaryQuery = 'SELECT Tag.*, (%s) AS itemsCount FROM `%s` Tag WHERE (%s)'; $tagSummaryParams = array(DB::prepareQuery($itemsCountQuery, $itemsCountParams), Tag::$tableName, count($options['tagConditions']) ? join(') AND (', $options['tagConditions']) : '1'); // exclude empty if ($options['excludeEmpty']) { $tagSummaryQuery .= ' HAVING itemsCount > 0'; } // add order options if ($options['order']) { $tagSummaryQuery .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order'])); } // add limit options if ($options['limit']) { $tagSummaryQuery .= sprintf(' LIMIT %u,%u', $options['offset'], $options['limit']); } try { // return indexed table or list if ($options['indexField']) { return DB::table(Tag::getColumnName($options['indexField']), $tagSummaryQuery, $tagSummaryParams); } else { return DB::allRecords($tagSummaryQuery, $tagSummaryParams); } } catch (TableNotFoundException $e) { return array(); } }
public static function getRevisionRecords($options = array()) { $options = array_merge(array('indexField' => false, 'conditions' => array(), 'order' => false, 'limit' => false, 'offset' => 0), $options); $query = 'SELECT * FROM `%s` WHERE (%s)'; $params = array(static::getHistoryTableName(), count($options['conditions']) ? join(') AND (', static::_mapConditions($options['conditions'])) : 1); if ($options['order']) { $query .= ' ORDER BY ' . join(',', static::_mapFieldOrder($options['order'])); } if ($options['limit']) { $query .= sprintf(' LIMIT %u,%u', $options['offset'], $options['limit']); } if ($options['indexField']) { return DB::table(static::_cn($options['indexField']), $query, $params); } else { return DB::allRecords($query, $params); } }
public static function getTreeFilesFromTree($tree, $conditions = array()) { $conditions['Status'] = 'Normal'; // map conditions $mappedConditions = array(); foreach ($conditions as $key => $value) { if (is_string($key)) { $mappedConditions[] = sprintf('`%s` = "%s"', $key, DB::escape($value)); } else { $mappedConditions[] = $value; } } // separate local and remote layers $localCollections = array(); $remoteCollections = array(); foreach ($tree as &$collectionInfo) { if ($collectionInfo['Site'] == 'Local') { $localCollections[] = $collectionInfo['ID']; } else { $remoteCollections[] = $collectionInfo['ID']; } } // build files query $filesSql = 'SELECT' . ' f2.ID, f2.CollectionID, f2.SHA1' . ',CONCAT(' . '(' . 'SELECT GROUP_CONCAT(parent.Handle ORDER BY parent.PosLeft SEPARATOR "/")' . ' FROM `%2$s` AS node, `%2$s` AS parent' . ' WHERE node.PosLeft BETWEEN parent.PosLeft AND parent.PosRight AND node.ID = f2.CollectionID' . ')' . ',"/"' . ',f2.Handle' . ') AS Path' . ' FROM (' . ' SELECT MAX(f1.ID) AS ID' . ' FROM `%1$s` f1' . ' WHERE CollectionID IN (%3$s)' . ' GROUP BY f1.CollectionID, f1.Handle' . ') AS lastestFiles' . ' LEFT JOIN `%1$s` f2 USING (ID)' . ' WHERE (%4$s)'; // retrieve local and remote files $localFiles = count($localCollections) ? DB::allRecords($filesSql, array(SiteFile::$tableName, SiteCollection::$tableName, join(',', $localCollections), join(' ) AND (', $mappedConditions))) : array(); $remoteFiles = count($remoteCollections) ? DB::allRecords($filesSql, array(SiteFile::$tableName, SiteCollection::$tableName, join(',', $remoteCollections), join(' ) AND (', $mappedConditions))) : array(); // merge trees $mergedTree = array(); foreach (array('Remote' => $remoteFiles, 'Local' => $localFiles) as $layerName => $layerFiles) { foreach ($layerFiles as &$fileInfo) { $mergedTree[$fileInfo['Path']] = array('ID' => $fileInfo['ID'], 'CollectionID' => $fileInfo['CollectionID'], 'SHA1' => $fileInfo['SHA1'], 'Site' => $layerName); } } return $mergedTree; }
public static function handleSearchRequest() { if (empty($_REQUEST['q'])) { return static::throwError('You did not supply any search terms'); } if (!empty($_REQUEST['tag'])) { if (!($Tag = Tag::getByHandle($_REQUEST['tag']))) { return static::throwNotFoundException('Tag does not exist'); } } if (empty(static::$searchClasses)) { return static::throwError('No search classes configured for this site'); } $searchResults = array(); $totalResults = 0; /* // Extra feature. Specify which classes to search for in Request parameter 'searchClasses' if(!empty($_REQUEST['searchClasses'])) { $classes = explode(',', $_REQUEST['searchClasses']); foreach(static::$searchClasses AS $className => $options) { if(!in_array($className,$classes)) unset(static::$searchClasses[$className]); } } */ foreach (static::$searchClasses as $className => $options) { if (is_string($options)) { $className = $options; $options = array(); } $options = array_merge(array('className' => $className, 'fields' => array('Title'), 'conditions' => array()), $options); if (empty($options['fields'])) { continue; } // parse fields $columns = array('fulltext' => array(), 'like' => array(), 'exact' => array(), 'sql' => array()); foreach ($options['fields'] as $field) { // transform string-only if (is_string($field)) { $field = array('field' => $field); } // apply defaults $field = array_merge(array('method' => 'fulltext'), $field); // sort conditions $columns[$field['method']][] = $field['method'] == 'sql' ? $field['sql'] : $className::getColumnName($field['field']); } // add match conditions $escapedQuery = DB::escape($_REQUEST['q']); $matchConditions = array(); if ($columns['fulltext']) { $matchConditions[] = sprintf('MATCH (`%s`) AGAINST ("%s" %s)', implode('`,`', $columns['fulltext']), $escapedQuery, static::$useBoolean ? 'IN BOOLEAN MODE' : ''); } if ($columns['like']) { $matchConditions[] = '(' . join(') OR (', array_map(function ($column) use($escapedQuery) { return sprintf('`%s` LIKE "%%%s%%"', $column, $escapedQuery); }, $columns['like'])) . ')'; } if ($columns['exact']) { $matchConditions[] = '(' . join(') OR (', array_map(function ($column) use($escapedQuery) { return sprintf('`%s` = "%s"', $column, $escapedQuery); }, $columns['exact'])) . ')'; } if ($columns['sql']) { $matchConditions[] = '(' . join(') OR (', array_map(function ($sql) use($escapedQuery) { return sprintf($sql, $escapedQuery); }, $columns['sql'])) . ')'; } $options['conditions'][] = join(' OR ', $matchConditions); try { if (isset($Tag)) { $results = DB::allRecords('SELECT p.*' . ' FROM `tag_items` t' . ' INNER JOIN `%s` p ON (p.ID = t.`ContextID`)' . ' WHERE t.`TagID` = %u AND t.`ContextClass` = "%s"' . ' AND (%s)', array($className::$tableName, $Tag->ID, $className, join(') AND (', $className::mapConditions($options['conditions'])))); } else { $results = DB::allRecords('SELECT * FROM `%s` p WHERE (%s)', array($className::$tableName, join(') AND (', $className::mapConditions($options['conditions'])))); } } catch (TableNotFoundException $e) { $results = array(); } $classResults = count($results); $totalResults += $classResults; $searchResults[$className] = $classResults ? ActiveRecord::instantiateRecords($results) : array(); } //DebugLog::dumpLog(); static::respond('search', array('data' => $searchResults, 'totalResults' => $totalResults)); }
$pageData['projectsTags']['byTopic'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "topic.%"'), 'itemConditions' => array('ContextClass' => Laddr\Project::getStaticRootClass()))); $pageData['projectsTags']['byEvent'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "event.%"'), 'itemConditions' => array('ContextClass' => Laddr\Project::getStaticRootClass()))); $pageData['projectsStages'] = Laddr\Project::getStagesSummary(); // members $pageData['membersTotal'] = Emergence\People\Person::getCount(); $pageData['membersTags']['byTech'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "tech.%"'), 'itemConditions' => array('ContextClass' => Emergence\People\Person::getStaticRootClass()))); $pageData['membersTags']['byTopic'] = TagItem::getTagsSummary(array('tagConditions' => array('Handle LIKE "topic.%"'), 'itemConditions' => array('ContextClass' => Emergence\People\Person::getStaticRootClass()))); // build activity stream if (!($pageData['activity'] = Cache::fetch('home-activity'))) { $existingTables = \DB::allValues('table_name', 'SELECT table_name FROM information_schema.TABLES WHERE TABLE_SCHEMA = SCHEMA()'); $activityQueries = []; if (in_array(Emergence\CMS\AbstractContent::$tableName, $existingTables)) { $activityQueries[] = sprintf('SELECT' . ' ID, Class, Published AS Timestamp' . ' FROM `%s`' . ' WHERE' . ' Class = "%s" AND' . ' Visibility = "Public" AND' . ' Status = "Published" AND' . ' (Published IS NULL OR Published <= CURRENT_TIMESTAMP)', Emergence\CMS\AbstractContent::$tableName, DB::escape(Emergence\CMS\BlogPost::class)); } if (in_array(Laddr\ProjectUpdate::$tableName, $existingTables)) { $activityQueries[] = sprintf('SELECT ID, Class, Created AS Timestamp FROM `%s`', Laddr\ProjectUpdate::$tableName); } if (in_array(Laddr\ProjectBuzz::$tableName, $existingTables)) { $activityQueries[] = sprintf('SELECT ID, Class, Published AS Timestamp FROM `%s`', Laddr\ProjectBuzz::$tableName); } if (count($activityQueries)) { $pageData['activity'] = array_map(function ($result) { return $result['Class']::getByID($result['ID']); }, DB::allRecords(implode(' UNION ', $activityQueries) . ' ORDER BY Timestamp DESC LIMIT 10')); } else { $pageData['activity'] = []; } Cache::store('home-activity', $pageData['activity'], 30); } // render data against home template RequestHandler::respond('home', $pageData);
public static function getAllByQuery($query, $params = array()) { try { return static::instantiateRecords(DB::allRecords($query, $params)); } catch (TableNotFoundException $e) { return array(); } }
function Dwoo_Plugin_sencha_preloader(Dwoo_Core $dwoo, $classes = "app", $App = null) { if (!$App) { $App = $dwoo->data['App']; } $appName = $App->getName(); $appPath = "sencha-workspace/{$appName}"; // include classpath files $classPaths = explode(',', $App->getBuildCfg('app.classpath')); $srcCollections = array(); foreach ($classPaths as $classPath) { if (strpos($classPath, '${workspace.dir}/x/') === 0) { $classPath = 'ext-library/' . substr($classPath, 19); } elseif (substr($classPath, 0, 11) == '${app.dir}/') { $classPath = $appPath . substr($classPath, 10); } else { continue; } try { $tree = Emergence_FS::getTree($classPath); $srcCollections = array_merge($srcCollections, array_keys($tree)); } catch (Exception $e) { continue; } } // include package files $requiredPackages = $App->getAppCfg('requires'); if (!is_array($requiredPackages)) { $requiredPackages = array(); } if (($themeName = $App->getBuildCfg('app.theme')) && !in_array($themeName, $requiredPackages)) { $requiredPackages[] = $themeName; } foreach ($requiredPackages as $packageName) { $packagePath = "sencha-workspace/packages/{$packageName}"; foreach (array("{$packagePath}/src", "{$packagePath}/overrides") as $classPath) { try { $tree = Emergence_FS::getTree($classPath); $srcCollections = array_merge($srcCollections, array_keys($tree)); } catch (Exception $e) { continue; } } } # Benchmark::startLive(); # Benchmark::mark("sencha_preload"); # Benchmark::mark("getting files from ".count($srcCollections)." collections"); // get files if (count($srcCollections)) { $sources = DB::allRecords('SELECT' . ' f2.SHA1' . ',CONCAT(' . '(' . 'SELECT GROUP_CONCAT(parent.Handle ORDER BY parent.PosLeft SEPARATOR "/")' . ' FROM `%2$s` AS node, `%2$s` AS parent' . ' WHERE node.PosLeft BETWEEN parent.PosLeft AND parent.PosRight AND node.ID = f2.CollectionID' . ')' . ',"/"' . ',f2.Handle' . ') AS Path' . ' FROM (' . ' SELECT MAX(f1.ID) AS ID' . ' FROM `%1$s` f1' . ' WHERE CollectionID IN (%3$s)' . ' GROUP BY f1.CollectionID, f1.Handle' . ') AS lastestFiles' . ' LEFT JOIN `%1$s` f2 USING (ID)' . ' WHERE f2.Status = "Normal" AND f2.Type = "application/javascript"', array(SiteFile::$tableName, SiteCollection::$tableName, join(',', $srcCollections))); } else { $sources = array(); } // compile keyed manifest with localized paths $manifest = array(); foreach ($sources as $source) { if (strpos($source['Path'], "{$appPath}/") === 0) { $manifest[substr($source['Path'], strlen($appPath) + 1)] = $source['SHA1']; } elseif (strpos($source['Path'], 'ext-library/') === 0) { $manifest["/app/{$appName}/x" . substr($source['Path'], 11)] = $source['SHA1']; } elseif (strpos($source['Path'], 'sencha-workspace/packages/') === 0) { $manifest['../' . substr($source['Path'], 17)] = $source['SHA1']; } } # $srcMasterHash = sha1(join(PHP_EOL, $srcHashes)); # # Benchmark::mark("found ".count($srcHashes)." files"); # # // try to get src from cache # $cacheKey = "app-cache/$srcMasterHash"; # # if(!Cache::exists($cacheKey)) { # $src = ''; # # foreach($srcHashes AS $fileId => $sha1) { # $src .= JSMin::minify(file_get_contents(SiteFile::getRealPathByID($fileId))); # } # # Cache::store($cacheKey, $src); # } # # Benchmark::mark("compiled: ".strlen($src)." bytes"); # //getRealPathByID return '<script type="text/javascript">(function(){' . 'var srcManifest = ' . json_encode($manifest) . ',origLoadScript = Ext.Loader.loadScript' . ',origLoadScriptFile = Ext.Loader.loadScriptFile' . ',dcParam = Ext.Loader.getConfig("disableCachingParam")' . ',now = Ext.Date.now();' . 'function _versionScriptUrl(url) {' . 'if(url in srcManifest) {' . 'url += "?_sha1=" + srcManifest[url];' . '} else {' . 'url += "?" + dcParam + "=" + now;' . '}' . 'return url;' . '}' . 'Ext.Loader.setConfig("disableCaching", false);' . 'Ext.Loader.loadScript = function(options) {' . 'if (typeof options == "string") {' . 'options = _versionScriptUrl(options);' . '} else {' . 'options.url = _versionScriptUrl(options.url);' . '}' . 'origLoadScript.call(Ext.Loader, options);' . '};' . 'Ext.Loader.loadScriptFile = function(url, onLoad, onError, scope, synchronous) {' . 'origLoadScriptFile.call(Ext.Loader, _versionScriptUrl(url), onLoad, onError, scope, synchronous);' . '};' . '})()</script>'; }
public function getItems() { return static::instantiateRecords(DB::allRecords(sprintf("SELECT `Content`.* FROM `category_items` Link JOIN `content` Content ON (`Content`.`ID`=`Link`.`ContextID`) WHERE `Link`.`CategoryID`='%d'", $this->ID))); }
public static function getGroupConditions($handle, $matchedCondition) { $group = Group::getByHandle($handle); if (!$group) { return false; } $containedGroups = DB::allRecords('SELECT ID FROM %s WHERE `Left` BETWEEN %u AND %u', array(Group::$tableName, $group->Left, $group->Right)); $containedGroups = array_map(function ($group) { return $group['ID']; }, $containedGroups); $condition = $matchedCondition['join']['aliasName'] . '.GroupID' . ' IN (' . implode(',', $containedGroups) . ')'; return $condition; }
public function getItemsByClass($class, $options = array()) { // apply defaults $options = array_merge(array('conditions' => false, 'order' => false, 'limit' => is_numeric($options) ? $options : false, 'offset' => 0, 'overlayTag' => false, 'calcFoundRows' => false), $options); // build TagItem query $tagWhere = array(); $tagWhere[] = sprintf('`%s` = %u', TagItem::getColumnName('TagID'), $this->ID); $tagWhere[] = sprintf('`%s` = "%s"', TagItem::getColumnName('ContextClass'), DB::escape($class::getStaticRootClass())); $tagQuery = sprintf('SELECT ContextID FROM `%s` TagItem WHERE (%s)', TagItem::$tableName, count($tagWhere) ? join(') AND (', $tagWhere) : '1', $options['limit'] ? sprintf('LIMIT %u', $options['limit']) : ''); if (!empty($options['overlayTag'])) { if (!is_object($OverlayTag = $options['overlayTag']) && !($OverlayTag = Tag::getByHandle($options['overlayTag']))) { throw new Exception('Overlay tag not found'); } $tagQuery .= sprintf(' AND (TagItem.`%s`,TagItem.`%s`) IN (SELECT OverlayTagItem.`%s`, OverlayTagItem.`%s` FROM `%s` OverlayTagItem WHERE OverlayTagItem.`%s` = %u)', TagItem::getColumnName('ContextClass'), TagItem::getColumnName('ContextID'), TagItem::getColumnName('ContextClass'), TagItem::getColumnName('ContextID'), TagItem::$tableName, TagItem::getColumnName('TagID'), $OverlayTag->ID); } // built class table query if ($options['conditions']) { if (!is_array($options['conditions'])) { $options['conditions'] = array($options['conditions']); } $classWhere = $class::_mapConditions($options['conditions']); } else { $classWhere = array(); } // return objects $classQuery = sprintf('SELECT %s' . ' Content.*' . ' FROM (%s) TagItem' . ' JOIN `%s` Content ON (Content.ID = TagItem.ContextID)' . ' WHERE (%s)', $options['calcFoundRows'] ? 'SQL_CALC_FOUND_ROWS' : '', $tagQuery, $class::$tableName, count($classWhere) ? join(') AND (', $classWhere) : '1'); if ($options['order']) { $classQuery .= ' ORDER BY ' . join(',', $class::_mapFieldOrder($options['order'])); } if ($options['limit']) { $classQuery .= sprintf(' LIMIT %u,%u', $options['offset'], $options['limit']); } return $class::instantiateRecords(DB::allRecords($classQuery)); }
if (in_array($validHour, $hours)) { $where[] = "Site{$validHour} = 1"; } } } // add features filter if (!empty($_GET['features'])) { $validFeatures = ['TransportationProvided']; $features = is_array($_GET['features']) ? $_GET['features'] : [$_GET['features']]; foreach ($validFeatures as $validFeature) { if (in_array($validFeature, $features)) { $where[] = "Site{$validFeature} = 1"; } } } // calculate limit params if (!empty($_GET['limit']) && ctype_digit($_GET['limit'])) { $limit = (int) $_GET['limit']; } else { $limit = 25; } if (!empty($_GET['offset']) && ctype_digit($_GET['offset'])) { $offset = (int) $_GET['offset']; } else { $offset = 0; } // execute query and print JSON response #Debug::dumpVar($_GET, false, 'get'); #Debug::dumpVar($where, true, '$where'); JSON::respond(['results' => DB::allRecords('SELECT SQL_CALC_FOUND_ROWS ' . implode(',', $selectFields) . ' FROM Site' . ' WHERE SiteApproved = 1 AND (' . (count($where) ? implode(') AND (', $where) : '1') . ')' . " ORDER BY {$order}" . " LIMIT {$offset}, {$limit}"), 'limit' => $limit, 'offset' => $offset, 'total' => (int) DB::foundRows()]);
public static function getStagesSummary() { try { $stages = \DB::allRecords('SELECT Stage, COUNT(*) AS itemsCount FROM `%s` GROUP BY Stage ORDER BY itemsCount DESC', [static::$tableName]); } catch (\TableNotFoundException $e) { $stages = []; } return $stages; }