/**
  * Update any requests to limit the results to the current site
  */
 public function augmentSQL(SQLSelect $query)
 {
     if (Subsite::$disable_subsite_filter) {
         return;
     }
     // If you're querying by ID, ignore the sub-site - this is a bit ugly... (but it was WAYYYYYYYYY worse)
     //@TODO I don't think excluding if SiteTree_ImageTracking is a good idea however because of the SS 3.0 api and ManyManyList::removeAll() changing the from table after this function is called there isn't much of a choice
     $from = $query->getFrom();
     if (isset($from['SiteTree_ImageTracking']) || $query->filtersOnID()) {
         return;
     }
     $subsiteID = (int) Subsite::currentSubsiteID();
     // The foreach is an ugly way of getting the first key :-)
     foreach ($query->getFrom() as $tableName => $info) {
         $where = "\"{$tableName}\".\"SubsiteID\" IN (0, {$subsiteID})";
         $query->addWhere($where);
         break;
     }
     $sect = array_values($query->getSelect());
     $isCounting = strpos($sect[0], 'COUNT') !== false;
     // Ordering when deleting or counting doesn't apply
     if (!$isCounting) {
         $query->addOrderBy("\"SubsiteID\"");
     }
 }
 /**
  * Update any requests to limit the results to the current site
  */
 public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = NULL)
 {
     if (Subsite::$disable_subsite_filter) {
         return;
     }
     if ($dataQuery->getQueryParam('Subsite.filter') === false) {
         return;
     }
     // If you're querying by ID, ignore the sub-site - this is a bit ugly...
     // if(!$query->where || (strpos($query->where[0], ".\"ID\" = ") === false && strpos($query->where[0], ".`ID` = ") === false && strpos($query->where[0], ".ID = ") === false && strpos($query->where[0], "ID = ") !== 0)) {
     if ($query->filtersOnID()) {
         return;
     }
     if (Subsite::$force_subsite) {
         $subsiteID = Subsite::$force_subsite;
     } else {
         /*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID;
           else */
         $subsiteID = (int) Subsite::currentSubsiteID();
     }
     // The foreach is an ugly way of getting the first key :-)
     foreach ($query->getFrom() as $tableName => $info) {
         // The tableName should be SiteTree or SiteTree_Live...
         if (strpos($tableName, 'SiteTree') === false) {
             break;
         }
         $query->addWhere("\"{$tableName}\".\"SubsiteID\" IN ({$subsiteID})");
         break;
     }
 }
 /**
  * Update any requests to limit the results to the current site
  */
 public function augmentSQL(SQLSelect $query)
 {
     if (Subsite::$disable_subsite_filter) {
         return;
     }
     // If you're querying by ID, ignore the sub-site - this is a bit ugly...
     if ($query->filtersOnID()) {
         return;
     }
     $regexp = '/^(.*\\.)?("|`)?SubsiteID("|`)?\\s?=/';
     foreach ($query->getWhereParameterised($parameters) as $predicate) {
         if (preg_match($regexp, $predicate)) {
             return;
         }
     }
     /*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID;
     		else */
     $subsiteID = (int) Subsite::currentSubsiteID();
     $froms = $query->getFrom();
     $froms = array_keys($froms);
     $tableName = array_shift($froms);
     if ($tableName != 'SiteConfig') {
         return;
     }
     $query->addWhere("\"{$tableName}\".\"SubsiteID\" IN ({$subsiteID})");
 }
 /**
  * Update any requests to limit the results to the current site
  */
 public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = NULL)
 {
     if (Subsite::$disable_subsite_filter) {
         return;
     }
     // If you're querying by ID, ignore the sub-site - this is a bit ugly...
     if ($query->filtersOnID()) {
         return;
     }
     $regexp = '/^(.*\\.)?("|`)?SubsiteID("|`)?\\s?=/';
     foreach ($query->getWhereParameterised($parameters) as $predicate) {
         if (preg_match($regexp, $predicate)) {
             return;
         }
     }
     try {
         $subsiteID = (int) Subsite::currentSubsiteID();
         $froms = $query->getFrom();
         $froms = array_keys($froms);
         $tableName = array_shift($froms);
         if ($tableName != 'SiteConfig') {
             return;
         }
         $query->addWhere("\"{$tableName}\".\"SubsiteID\" IN ({$subsiteID})");
     } catch (UnexpectedValueException $e) {
         // No subsites exist yet
     }
 }
 /**
  * Update any requests to limit the results to the current site
  */
 public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
 {
     if (Subsite::$disable_subsite_filter) {
         return;
     }
     if (Cookie::get('noSubsiteFilter') == 'true') {
         return;
     }
     // If you're querying by ID, ignore the sub-site - this is a bit ugly...
     if (!$query->filtersOnID()) {
         /*if($context = DataObject::context_obj()) $subsiteID = (int)$context->SubsiteID;
         		else */
         $subsiteID = (int) Subsite::currentSubsiteID();
         // Don't filter by Group_Subsites if we've already done that
         $hasGroupSubsites = false;
         foreach ($query->getFrom() as $item) {
             if (is_array($item) && strpos($item['table'], 'Group_Subsites') !== false || !is_array($item) && strpos($item, 'Group_Subsites') !== false) {
                 $hasGroupSubsites = true;
                 break;
             }
         }
         if (!$hasGroupSubsites) {
             if ($subsiteID) {
                 $query->addLeftJoin("Group_Subsites", "\"Group_Subsites\".\"GroupID\" \n\t\t\t\t\t\t= \"Group\".\"ID\" AND \"Group_Subsites\".\"SubsiteID\" = {$subsiteID}");
                 $query->addWhere("(\"Group_Subsites\".\"SubsiteID\" IS NOT NULL OR\n\t\t\t\t\t\t\"Group\".\"AccessAllSubsites\" = 1)");
             } else {
                 $query->addWhere("\"Group\".\"AccessAllSubsites\" = 1");
             }
         }
         // WORKAROUND for databases that complain about an ORDER BY when the column wasn't selected (e.g. SQL Server)
         $select = $query->getSelect();
         if (isset($select[0]) && !$select[0] == 'COUNT(*)') {
             $query->orderby = "\"AccessAllSubsites\" DESC" . ($query->orderby ? ', ' : '') . $query->orderby;
         }
     }
 }
 /**
  * Augment the the SQLSelect that is created by the DataQuery
  * @todo Should this all go into VersionedDataQuery?
  */
 public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
 {
     if (!$dataQuery || !$dataQuery->getQueryParam('Versioned.mode')) {
         return;
     }
     $baseTable = ClassInfo::baseDataClass($dataQuery->dataClass());
     switch ($dataQuery->getQueryParam('Versioned.mode')) {
         // Reading a specific data from the archive
         case 'archive':
             $date = $dataQuery->getQueryParam('Versioned.date');
             foreach ($query->getFrom() as $table => $dummy) {
                 if (!DB::get_schema()->hasTable($table . '_versions')) {
                     continue;
                 }
                 $query->renameTable($table, $table . '_versions');
                 $query->replaceText("\"{$table}_versions\".\"ID\"", "\"{$table}_versions\".\"RecordID\"");
                 $query->replaceText("`{$table}_versions`.`ID`", "`{$table}_versions`.`RecordID`");
                 // Add all <basetable>_versions columns
                 foreach (Config::inst()->get('Versioned', 'db_for_versions_table') as $name => $type) {
                     $query->selectField(sprintf('"%s_versions"."%s"', $baseTable, $name), $name);
                 }
                 $query->selectField(sprintf('"%s_versions"."%s"', $baseTable, 'RecordID'), "ID");
                 if ($table != $baseTable) {
                     $query->addWhere("\"{$table}_versions\".\"Version\" = \"{$baseTable}_versions\".\"Version\"");
                 }
             }
             // Link to the version archived on that date
             $query->addWhere(array("\"{$baseTable}_versions\".\"Version\" IN\n\t\t\t\t(SELECT LatestVersion FROM\n\t\t\t\t\t(SELECT\n\t\t\t\t\t\t\"{$baseTable}_versions\".\"RecordID\",\n\t\t\t\t\t\tMAX(\"{$baseTable}_versions\".\"Version\") AS LatestVersion\n\t\t\t\t\t\tFROM \"{$baseTable}_versions\"\n\t\t\t\t\t\tWHERE \"{$baseTable}_versions\".\"LastEdited\" <= ?\n\t\t\t\t\t\tGROUP BY \"{$baseTable}_versions\".\"RecordID\"\n\t\t\t\t\t) AS \"{$baseTable}_versions_latest\"\n\t\t\t\t\tWHERE \"{$baseTable}_versions_latest\".\"RecordID\" = \"{$baseTable}_versions\".\"RecordID\"\n\t\t\t\t)" => $date));
             break;
             // Reading a specific stage (Stage or Live)
         // Reading a specific stage (Stage or Live)
         case 'stage':
             $stage = $dataQuery->getQueryParam('Versioned.stage');
             if ($stage && $stage != $this->defaultStage) {
                 foreach ($query->getFrom() as $table => $dummy) {
                     // Only rewrite table names that are actually part of the subclass tree
                     // This helps prevent rewriting of other tables that get joined in, in
                     // particular, many_many tables
                     if (class_exists($table) && ($table == $this->owner->class || is_subclass_of($table, $this->owner->class) || is_subclass_of($this->owner->class, $table))) {
                         $query->renameTable($table, $table . '_' . $stage);
                     }
                 }
             }
             break;
             // Reading a specific stage, but only return items that aren't in any other stage
         // Reading a specific stage, but only return items that aren't in any other stage
         case 'stage_unique':
             $stage = $dataQuery->getQueryParam('Versioned.stage');
             // Recurse to do the default stage behavior (must be first, we rely on stage renaming happening before
             // below)
             $dataQuery->setQueryParam('Versioned.mode', 'stage');
             $this->augmentSQL($query, $dataQuery);
             $dataQuery->setQueryParam('Versioned.mode', 'stage_unique');
             // Now exclude any ID from any other stage. Note that we double rename to avoid the regular stage rename
             // renaming all subquery references to be Versioned.stage
             foreach ($this->stages as $excluding) {
                 if ($excluding == $stage) {
                     continue;
                 }
                 $tempName = 'ExclusionarySource_' . $excluding;
                 $excludingTable = $baseTable . ($excluding && $excluding != $this->defaultStage ? "_{$excluding}" : '');
                 $query->addWhere('"' . $baseTable . '"."ID" NOT IN (SELECT "ID" FROM "' . $tempName . '")');
                 $query->renameTable($tempName, $excludingTable);
             }
             break;
             // Return all version instances
         // Return all version instances
         case 'all_versions':
         case 'latest_versions':
             foreach ($query->getFrom() as $alias => $join) {
                 if ($alias != $baseTable) {
                     $query->setJoinFilter($alias, "\"{$alias}\".\"RecordID\" = \"{$baseTable}_versions\".\"RecordID\"" . " AND \"{$alias}\".\"Version\" = \"{$baseTable}_versions\".\"Version\"");
                 }
                 $query->renameTable($alias, $alias . '_versions');
             }
             // Add all <basetable>_versions columns
             foreach (Config::inst()->get('Versioned', 'db_for_versions_table') as $name => $type) {
                 $query->selectField(sprintf('"%s_versions"."%s"', $baseTable, $name), $name);
             }
             // Alias the record ID as the row ID
             $query->selectField(sprintf('"%s_versions"."%s"', $baseTable, 'RecordID'), "ID");
             // Ensure that any sort order referring to this ID is correctly aliased
             $orders = $query->getOrderBy();
             foreach ($orders as $order => $dir) {
                 if ($order === "\"{$baseTable}\".\"ID\"") {
                     unset($orders[$order]);
                     $orders["\"{$baseTable}_versions\".\"RecordID\""] = $dir;
                 }
             }
             $query->setOrderBy($orders);
             // latest_version has one more step
             // Return latest version instances, regardless of whether they are on a particular stage
             // This provides "show all, including deleted" functonality
             if ($dataQuery->getQueryParam('Versioned.mode') == 'latest_versions') {
                 $query->addWhere("\"{$alias}_versions\".\"Version\" IN\n\t\t\t\t\t(SELECT LatestVersion FROM\n\t\t\t\t\t\t(SELECT\n\t\t\t\t\t\t\t\"{$alias}_versions\".\"RecordID\",\n\t\t\t\t\t\t\tMAX(\"{$alias}_versions\".\"Version\") AS LatestVersion\n\t\t\t\t\t\t\tFROM \"{$alias}_versions\"\n\t\t\t\t\t\t\tGROUP BY \"{$alias}_versions\".\"RecordID\"\n\t\t\t\t\t\t) AS \"{$alias}_versions_latest\"\n\t\t\t\t\t\tWHERE \"{$alias}_versions_latest\".\"RecordID\" = \"{$alias}_versions\".\"RecordID\"\n\t\t\t\t\t)");
             } else {
                 // If all versions are requested, ensure that records are sorted by this field
                 $query->addOrderBy(sprintf('"%s_versions"."%s"', $baseTable, 'Version'));
             }
             break;
         default:
             throw new InvalidArgumentException("Bad value for query parameter Versioned.mode: " . $dataQuery->getQueryParam('Versioned.mode'));
     }
 }
 /**
  * Changes any SELECT query thats not filtering on an ID
  * to limit by the current language defined in {@link get_current_locale()}.
  * It falls back to "Locale='' OR Lang IS NULL" and assumes that
  * this implies querying for the default language.
  * 
  * Use {@link disable_locale_filter()} to temporarily disable this "auto-filtering".
  */
 public function augmentSQL(SQLSelect $query, DataQuery $dataQuery = null)
 {
     // If the record is saved (and not a singleton), and has a locale,
     // limit the current call to its locale. This fixes a lot of problems
     // with other extensions like Versioned
     if ($this->owner->ID && !empty($this->owner->Locale)) {
         $locale = $this->owner->Locale;
     } else {
         $locale = Translatable::get_current_locale();
     }
     $baseTable = ClassInfo::baseDataClass($this->owner->class);
     if ($locale && self::locale_filter_enabled() && $dataQuery->getQueryParam(self::QUERY_LOCALE_FILTER_ENABLED) && !$query->filtersOnID() && array_search($baseTable, array_keys($query->getFrom())) !== false) {
         // Or we're already filtering by Lang (either from an earlier augmentSQL()
         // call or through custom SQL filters)
         $filtersOnLocale = array_filter($query->getWhere(), function ($predicates) {
             foreach ($predicates as $predicate => $params) {
                 if (preg_match('/("|\'|`)Locale("|\'|`)/', $predicate)) {
                     return true;
                 }
             }
         });
         if (!$filtersOnLocale) {
             $qry = sprintf('"%s"."Locale" = \'%s\'', $baseTable, Convert::raw2sql($locale));
             $query->addWhere($qry);
         }
     }
 }