function run($request)
 {
     $customerGroup = EcommerceRole::get_customer_group();
     if ($customerGroup) {
         $allCombos = DB::query("\n\t\t\t\tSELECT \"Group_Members\".\"ID\", \"Group_Members\".\"MemberID\", \"Group_Members\".\"GroupID\"\n\t\t\t\tFROM \"Group_Members\"\n\t\t\t\tWHERE \"Group_Members\".\"GroupID\" = " . $customerGroup->ID . ";");
         //make an array of all combos
         $alreadyAdded = array();
         $alreadyAdded[-1] = -1;
         if ($allCombos) {
             foreach ($allCombos as $combo) {
                 $alreadyAdded[$combo["MemberID"]] = $combo["MemberID"];
             }
         }
         $unlistedMembers = DataObject::get("Member", $where = "\"Member\".\"ID\" NOT IN (" . implode(",", $alreadyAdded) . ")", $sort = "", $join = "INNER JOIN \"Order\" ON \"Order\".\"MemberID\" = \"Member\".\"ID\"");
         //add combos
         if ($unlistedMembers) {
             $existingMembers = $customerGroup->Members();
             foreach ($unlistedMembers as $member) {
                 $existingMembers->add($member);
                 DB::alteration_message("Added member to customers: " . $member->Email, "created");
             }
         }
     } else {
         DB::alteration_message("NO customer group found", "deleted");
     }
 }
 function run($request)
 {
     $productVariationArrayID = array();
     if (empty($_GET["live"])) {
         $live = false;
     } else {
         $live = intval($_GET["live"]) == 1 ? true : false;
     }
     if ($live) {
         DB::alteration_message("this is a live task", "deleted");
     } else {
         DB::alteration_message("this is a test only. If you add a live=1 get variable then you can make it for real ;-)", "created");
     }
     foreach ($this->tableArray as $table) {
         $sql = "DELETE FROM \"{$table}\"";
         DB::alteration_message("<pre>DELETING FROM {$table}: <br /><br />" . $sql . "</pre>");
         if ($live) {
             DB::query($sql);
         }
         $sql = "SELECT COUNT(ID) FROM \"{$table}\"";
         $count = DB::query($sql)->value();
         if ($count == 0) {
             $style = "created";
         } else {
             $style = "deleted";
         }
         DB::alteration_message(" **** COMPLETED, NUMBER OF REMAINING RECORD: " . $count . " **** ", $style);
     }
 }
    public function run($request)
    {
        if (!Director::is_cli() && !isset($_GET['run'])) {
            DB::alteration_message('Must add ?run=1', 'error');
            return false;
        }
        if (!Director::is_cli()) {
            // - Add UTF-8 so characters will render as they should when debugging (so you can visualize inproperly formatted characters easier)
            // - Add base_tag so that printing blocks of HTML works properly with relative links (helps with visualizing errors)
            ?>
			<head>
				<?php 
            echo SSViewer::get_base_tag('');
            ?>
				<meta charset="UTF-8">
			</head>
<?php 
        }
        increase_time_limit_to(300);
        WordpressDatabase::$default_config = $this->config()->default_db;
        $this->db = $this->wordpressImportService->getDatabase();
        // Login as default admin so 'canPublish()' definitely returns true in 'SiteTree::doPublish()'
        if (!Member::currentUser()) {
            $defaultAdmin = Member::default_admin();
            if ($defaultAdmin && $defaultAdmin->exists()) {
                Session::set('loggedInAs', $defaultAdmin->ID);
            }
        }
        // Unsure if the importing functionality can ever hit this, but just incase.
        if (Versioned::current_stage() !== 'Stage') {
            throw new Exception('Versioned::current_stage() must be "Stage".');
        }
        $this->runCustom($request);
    }
 /**
  * Check for default group, and if it doesn't exist, create it
  * Should be run under "requireDefaultRecords"
  * @param string $code
  * @param string $title
  * @param string $parent
  * @param array $permissions
  */
 public static function default_group($code, $title, $parentCode = null, $permissions = array())
 {
     $group = null;
     $action = null;
     if (!DataObject::get_one('Group', "Code = '" . $code . "'")) {
         $action = 'create';
         $group = new Group();
     } else {
         $action = 'update';
         $group = DataObject::get_one('Group', "Code = '" . $code . "'");
     }
     $group->Title = $title;
     $group->Code = $code;
     if ($parentCode) {
         $parentObj = DataObject::get_one("Group", "Code = '" . $parentCode . "'");
         $group->ParentID = $parentObj->ID;
     }
     $group->write();
     if (!empty($permissions)) {
         foreach ($permissions as $p) {
             Permission::grant($group->ID, $p);
         }
     }
     if ($action == 'create') {
         DB::alteration_message('Group ' . $title . ' (' . $code . ') has been created.', "created");
     }
     if ($action == 'update') {
         DB::alteration_message('Group ' . $title . ' (' . $code . ') has been updated.', "updated");
     }
     return $group;
 }
 function run($request)
 {
     $orderItemSingleton = singleton('OrderItem');
     $query = $orderItemSingleton->buildSQL("\"Quantity\" > 0");
     $select = $query->select;
     $select['NewNumberSold'] = self::$number_sold_calculation_type . "(\"OrderItem\".\"Quantity\") AS \"NewNumberSold\"";
     $query->select($select);
     $query->groupby("\"BuyableClassName\", \"BuyableID\" ");
     $query->orderby("\"BuyableClassName\", \"BuyableID\" ");
     //$q->leftJoin('OrderItem','"Product"."ID" = "OrderItem"."BuyableID"');
     //$q->where("\"OrderItem\".\"BuyableClassName\" = 'Product'");
     $records = $query->execute();
     $orderItems = $orderItemSingleton->buildDataObjectSet($records, "DataObjectSet", $query, 'OrderItem');
     if ($orderItems) {
         foreach ($orderItems as $orderItem) {
             if (!$orderItem->NewNumberSold) {
                 $orderItem->NewNumberSold = 0;
             }
             $buyable = DataObject::get_by_id($orderItem->BuyableClassName, $orderItem->BuyableID);
             if ($buyable) {
                 if ($orderItem->NewNumberSold != $buyable->NumberSold) {
                     $buyable->NumberSold = $orderItem->NewNumberSold;
                     if ($buyable instanceof SiteTree) {
                     }
                 }
             } else {
                 DB::alteration_message("could not find " . $orderItem->BuyableClassName . "." . $orderItem->BuyableID . " ... ", "deleted");
             }
         }
     }
 }
 /**
  *	The process to automatically consolidate existing and configuration defined tag types, executed on project build.
  */
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     // Retrieve existing and configuration defined tag types that have not been consolidated.
     foreach ($this->service->getFusionTagTypes() as $type => $field) {
         if (($tags = $type::get()->filter('FusionTagID', 0)) && $tags->exists()) {
             foreach ($tags as $tag) {
                 // Determine whether there's an existing fusion tag.
                 if (!($existing = FusionTag::get()->filter('Title', $tag->{$field})->first())) {
                     // There is no fusion tag, therefore instantiate one using the current tag.
                     $fusion = FusionTag::create();
                     $fusion->Title = $tag->{$field};
                     $fusion->TagTypes = serialize(array($tag->ClassName => $tag->ClassName));
                     $fusion->write();
                     $fusionID = $fusion->ID;
                 } else {
                     // There is a fusion tag, therefore append the current tag type.
                     $types = unserialize($existing->TagTypes);
                     $types[$tag->ClassName] = $tag->ClassName;
                     $existing->TagTypes = serialize($types);
                     $existing->write();
                     $fusionID = $existing->ID;
                 }
                 // Update the current tag to point to this.
                 $tag->FusionTagID = $fusionID;
                 $tag->write();
                 DB::alteration_message("\"{$tag->{$field}}\" Fusion Tag", 'created');
             }
         }
     }
 }
 function run($request)
 {
     //IMPORTANT!
     Config::inst()->update("Email", "send_all_emails_to", "no-one@localhost");
     Email::set_mailer(new EcommerceTaskTryToFinaliseOrders_Mailer());
     $orderStatusLogClassName = "OrderStatusLog";
     $submittedOrderStatusLogClassName = EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order");
     if ($submittedOrderStatusLogClassName) {
         $sampleSubmittedStatusLog = $submittedOrderStatusLogClassName::get()->First();
         if ($sampleSubmittedStatusLog) {
             $lastOrderStep = OrderStep::get()->sort("Sort", "DESC")->First();
             if ($lastOrderStep) {
                 $joinSQL = "INNER JOIN \"{$orderStatusLogClassName}\" ON \"{$orderStatusLogClassName}\".\"OrderID\" = \"Order\".\"ID\"";
                 $whereSQL = "WHERE \"StatusID\" <> " . $lastOrderStep->ID . " AND \"{$orderStatusLogClassName}\".ClassName = '{$submittedOrderStatusLogClassName}'";
                 $count = DB::query("\r\n\t\t\t\t\t\tSELECT COUNT (\"Order\".\"ID\")\r\n\t\t\t\t\t\tFROM \"Order\"\r\n\t\t\t\t\t\t{$joinSQL}\r\n\t\t\t\t\t\t{$whereSQL}\r\n\t\t\t\t\t")->value();
                 $do = DB::query("\r\n\t\t\t\t\t\tUPDATE \"Order\"\r\n\t\t\t\t\t\t{$joinSQL}\r\n\t\t\t\t\t\tSET \"Order\".\"StatusID\" = " . $lastOrderStep->ID . "\r\n\t\t\t\t\t\t{$whereSQL}\r\n\t\t\t\t\t");
                 if ($count) {
                     DB::alteration_message("NOTE: {$count} records were updated.", "created");
                 } else {
                     DB::alteration_message("No records were updated.");
                 }
             } else {
                 DB::alteration_message("Could not find the last order step.", "deleted");
             }
         } else {
             DB::alteration_message("Could not find any submitted order logs.", "deleted");
         }
     } else {
         DB::alteration_message("Could not find a class name for submitted orders.", "deleted");
     }
 }
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     if (!$this->owner->config()->upgrade_on_build) {
         return;
     }
     // Perform migrations (the legacy field will be left in the DB by the ORM)
     $class = $this->owner->class;
     $baseclass = $this->ownerBaseClass;
     if ($baseclass == $class) {
         // if(in_array('FeaturedImageExtension', Config::inst()->get($class, 'extensions'))){
         $rows = DB::query('SELECT * FROM "' . $baseclass . '"');
         $altered = false;
         foreach ($rows as $page) {
             if (array_key_exists('FeaturedImageID', $page) && ($imageID = $page['FeaturedImageID'])) {
                 DB::query('INSERT INTO "' . $baseclass . '_FeaturedImages" (' . $class . 'ID, ImageID) VALUES (' . $page['ID'] . ', ' . $page['FeaturedImageID'] . ')');
                 $altered = true;
                 //$page->FeaturedImages()->add($imageID);
                 //$page->FeaturedImageID = null; // leave as is...
                 //					$page->write();
             }
         }
         // Now drop the legacy field
         if ($altered) {
             DB::query('ALTER TABLE "' . $baseclass . '" DROP "FeaturedImageID"');
             DB::alteration_message('Migrated FeaturedImages to many_many on ' . $baseclass, 'changed');
         }
     }
 }
 function run($request)
 {
     $days = intval($request->getVar("days") - 0);
     if (!$days) {
         $days = $this->defaultDays;
     }
     $countMin = intval($request->getVar("min") - 0);
     if (!$countMin) {
         $countMin = $this->defaultMinimum;
     }
     $endingDaysBack = intval($request->getVar("ago") - 0);
     if (!$endingDaysBack) {
         $endingDaysBack = $this->endingDaysBack;
     }
     $field = EcommerceSearchHistoryFormField::create("stats", $this->title)->setNumberOfDays($days)->setMinimumCount($countMin)->setEndingDaysBack($endingDaysBack);
     echo $field->forTemplate();
     $arrayNumberOfDays = array(30, 365);
     $link = "/dev/tasks/EcommerceTaskReviewSearches/";
     for ($months = 0; $months++; $months < 36) {
         foreach ($arrayNumberOfDays as $numberOfDays) {
             $myLink = $link . "?ago=" . floor($months * 30.5) . "&amp;days=" . $numberOfDays;
             DB::alteration_message("<a href=\"" . $myLink . "\">{$months} months ago, last {$numberOfDays} days</a>");
         }
     }
 }
 /**
  * Ensures that there is always a 404 page
  * by checking if there's an instance of
  * ErrorPage with a 404 and 500 error code. If there
  * is not, one is created when the DB is built.
  */
 function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     $pageNotFoundErrorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = '404'");
     if (!($pageNotFoundErrorPage && $pageNotFoundErrorPage->exists())) {
         $pageNotFoundErrorPage = new ErrorPage();
         $pageNotFoundErrorPage->ErrorCode = 404;
         $pageNotFoundErrorPage->Title = _t('ErrorPage.DEFAULTERRORPAGETITLE', 'Page not found');
         $pageNotFoundErrorPage->Content = _t('ErrorPage.DEFAULTERRORPAGECONTENT', '<p>Sorry, it seems you were trying to access a page that doesn\'t exist.</p><p>Please check the spelling of the URL you were trying to access and try again.</p>');
         $pageNotFoundErrorPage->Status = 'New page';
         $pageNotFoundErrorPage->write();
         $pageNotFoundErrorPage->publish('Stage', 'Live');
         DB::alteration_message('404 page created', 'created');
     }
     $serverErrorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = '500'");
     if (!($serverErrorPage && $serverErrorPage->exists())) {
         $serverErrorPage = new ErrorPage();
         $serverErrorPage->ErrorCode = 500;
         $serverErrorPage->Title = _t('ErrorPage.DEFAULTSERVERERRORPAGETITLE', 'Server error');
         $serverErrorPage->Content = _t('ErrorPage.DEFAULTSERVERERRORPAGECONTENT', '<p>Sorry, there was a problem with handling your request.</p>');
         $serverErrorPage->Status = 'New page';
         $serverErrorPage->write();
         $serverErrorPage->publish('Stage', 'Live');
         DB::alteration_message('500 page created', 'created');
     }
 }
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     if (!CommerceCurrency::get()->exists()) {
         $gbp = new CommerceCurrency();
         $gbp->Title = "UK Pounds";
         $gbp->HTMLNotation = "&pound;";
         $gbp->GatewayCode = "GBP";
         $gbp->write();
         $gbp->flushCache();
         DB::alteration_message('UK Pounds created', 'created');
         $eur = new CommerceCurrency();
         $eur->Title = "Euro";
         $eur->HTMLNotation = "&euro;";
         $eur->GatewayCode = "EUR";
         $eur->write();
         $eur->flushCache();
         DB::alteration_message('Euro created', 'created');
         $usd = new CommerceCurrency();
         $usd->Title = "US Dollars";
         $usd->HTMLNotation = "&#36;";
         $usd->GatewayCode = "USD";
         $usd->write();
         $usd->flushCache();
         DB::alteration_message('US Dollars created', 'created');
     }
 }
 function run($request)
 {
     $db = DB::getConn();
     if ($db instanceof PostgreSQLDatabase) {
         $exist = DB::query("SELECT column_name FROM information_schema.columns WHERE table_name ='PickUpOrDeliveryModifier' AND column_name = 'PickupOrDeliveryType'")->numRecords();
     } else {
         // default is MySQL - broken for others, each database conn type supported must be checked for!
         $exist = DB::query("SHOW COLUMNS FROM \"PickUpOrDeliveryModifier\" LIKE 'PickupOrDeliveryType'")->numRecords();
     }
     if ($exist > 0) {
         $defaultOption = PickUpOrDeliveryModifierOptions::get()->filter(array("IsDefault" => 1))->First();
         $modifiers = PickUpOrDeliveryModifier::get()->filter(array("OptionID" => 0));
         if ($modifiers->count()) {
             foreach ($modifiers as $modifier) {
                 if (!isset($modifier->OptionID) || !$modifier->OptionID) {
                     if (!isset(self::$options_old_to_new[$modifier->Code])) {
                         $option = PickUpOrDeliveryModifierOptions::get()->filter(array("Code" => $modifier->Code))->First();
                         if (!$option) {
                             $option = $defaultOption;
                         }
                         self::$options_old_to_new[$modifier->Code] = $option->ID;
                     }
                     $myOption = self::$options_old_to_new[$modifier->Code];
                     // USING QUERY TO UPDATE
                     DB::query("UPDATE \"PickUpOrDeliveryModifier\" SET \"OptionID\" = " . $myOption . " WHERE \"PickUpOrDeliveryModifier\".\"ID\" = " . $modifier->ID);
                     DB::alteration_message('Updated modifier #' . $modifier->ID . ' from code to option ID ' . $myOption, 'edited');
                 }
             }
         }
     }
     DB::alteration_message("<hr />COMPLETED<hr />", "created");
 }
Exemple #13
0
 public function XrequireDefaultRecords()
 {
     foreach ($this->config()->get('records') as $code => $record) {
         if ($record['IsDev'] && Director::isDev() || $record['IsTest'] && Director::isTest() || $record['IsLive'] && Director::isLive()) {
             if (!($discountType = StreakDiscountType::get_by_code($code))) {
                 $discountType = StreakDiscountType::create();
                 DB::alteration_message("Added discount type '{$code}'", "changed");
             }
             // if the record is using default code then update from config.
             if ($code == self::DefaultCode) {
                 $record['Code'] = $this->config()->get('default_code');
             } else {
                 $record['Code'] = $code;
             }
             $title = $record['Title'];
             // if the record is using default title then update from config as hasn't changed, if different
             // then leave alone
             if ($title == self::DefaultTitle) {
                 $record['Title'] = $this->config()->get('default_title');
             }
             $data = array_diff_key($record, array_flip(array('IsDev', 'IsTest', 'IsLive')));
             $discountType->update($data);
             $discountType->write();
         }
     }
 }
 protected function createSubmissionLogForArchivedOrders()
 {
     $lastOrderStep = OrderStep::get()->sort("Sort", "DESC")->First();
     $submissionLogClassName = EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order");
     $obj = $submissionLogClassName::create();
     if (!is_a($obj, Object::getCustomClass("OrderStatusLog"))) {
         user_error('EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order") refers to a class that is NOT an instance of OrderStatusLog');
     }
     $orderStatusLogClassName = "OrderStatusLog";
     $offset = 0;
     $orders = $this->getOrdersForCreateSubmissionLogForArchivedOrders($lastOrderStep, $orderStatusLogClassName, $offset);
     while ($orders->count()) {
         foreach ($orders as $order) {
             $isSubmitted = $submissionLogClassName::get()->Filter(array("OrderID" => $order->ID))->count();
             if (!$isSubmitted) {
                 $obj = $submissionLogClassName::create();
                 $obj->OrderID = $order->ID;
                 //it is important we add this here so that we can save the 'submitted' version.
                 //this is particular important for the Order Item Links.
                 $obj->write();
                 $obj->OrderAsHTML = $order->ConvertToHTML();
                 $obj->write();
                 DB::alteration_message("creating submission log for Order #" . $obj->OrderID, "created");
             }
         }
         $offset += 100;
         $orders = $this->getOrdersForCreateSubmissionLogForArchivedOrders($lastOrderStep, $orderStatusLogClassName, $offset);
     }
 }
 function run($request)
 {
     $problem = DB::query("SELECT COUNT(OrderStatusLog.ID) FROM OrderStatusLog_Submitted INNER JOIN OrderStatusLog ON OrderStatusLog_Submitted.ID = OrderStatusLog.ID WHERE OrderID = 0");
     if ($problem->value()) {
         DB::alteration_message("the size of the problem is: " . $problem->value(), "deleted");
     } else {
         DB::alteration_message("No broken links found.", "created");
     }
     $rows = DB::query("Select \"ID\" from \"Order\" WHERE \"StatusID\" > 1");
     if ($rows) {
         foreach ($rows as $row) {
             $orderID = $row["ID"];
             $inners = DB::query("SELECT COUNT(OrderStatusLog.ID) FROM OrderStatusLog_Submitted INNER JOIN OrderStatusLog ON OrderStatusLog_Submitted.ID = OrderStatusLog.ID WHERE OrderID = {$orderID}");
             if ($inners->value() < 1) {
                 $sql = "\r\n\t\t\t\t\tSELECT *\r\n\t\t\t\t\tFROM OrderStatusLog_Submitted\r\n\t\t\t\t\tWHERE\r\n\t\t\t\t\t\t\"OrderAsString\" LIKE '%s:7:\"OrderID\";i:" . $orderID . "%'\r\n\t\t\t\t\t\tOR \"OrderAsHTML\" LIKE '%Order #" . $orderID . "%'\r\n\r\n\t\t\t\t\tLIMIT 1";
                 if ($innerInners = DB::query($sql)) {
                     foreach ($innerInners as $innerInnerRow) {
                         DB::alteration_message("FOUND " . $innerInnerRow["ID"], "created");
                         DB::query("UPDATE \"OrderStatusLog\" SET \"OrderID\" = {$orderID} WHERE \"OrderStatusLog\".\"ID\" = " . $innerInnerRow["ID"] . " AND \"OrderID\" < 1");
                     }
                 }
             }
         }
     }
 }
 /**
  *
  */
 public function onAfterPopulateRecords()
 {
     $path = $this->getPath();
     DB::alteration_message("Saving populate state to {$path}", "success");
     $result = DB::query('SHOW TABLES');
     $tables = $result->column();
     $return = '';
     foreach ($tables as $table) {
         $return .= 'DROP TABLE IF EXISTS `' . $table . '`;';
         $row2 = DB::query("SHOW CREATE TABLE `{$table}`");
         $create = $row2->nextRecord();
         $create = str_replace("\"", "`", $create);
         $return .= "\n\n" . $create['Create Table'] . ";\n\n";
         $result = DB::query("SELECT * FROM `{$table}`");
         while ($row = $result->nextRecord()) {
             $return .= 'INSERT INTO ' . $table . ' VALUES(';
             foreach ($row as $k => $v) {
                 $v = addslashes($v);
                 $v = str_replace("\n", "\\n", $v);
                 if ($v) {
                     $return .= '"' . $v . '"';
                 } else {
                     $return .= '""';
                 }
                 $return .= ',';
             }
             $return = rtrim($return, ',');
             $return .= ");\n";
         }
     }
     $return .= "\n\n\n";
     $handle = fopen($path, 'w+');
     fwrite($handle, $return);
     fclose($handle);
 }
 public static function update($baseTable, $field, $value, $id = 0, $replace = false, $addLive = false)
 {
     $object = $baseTable::get()->First();
     if ($object) {
         $tableArray = array($baseTable);
         if ($object instanceof SiteTree) {
             $tableArray[] = $baseTable . "_Live";
         }
         foreach ($tableArray as $table) {
             $value = Convert::raw2sql($value);
             $sql = "UPDATE \"{$table}\" SET \"{$table}\".\"{$field}\" = '{$value}'";
             $where = array();
             if ($id) {
                 $where[] = "  \"{$table}\".\"ID\" = " . $id;
             }
             if (!$replace) {
                 $where[] = " \"{$table}\".\"{$field}\" IS NULL OR \"{$table}\".\"{$field}\" = '' OR \"{$table}\".\"{$field}\" = 0 ";
             }
             $wherePhrase = '';
             if (count($where)) {
                 $wherePhrase = " WHERE ( " . implode(") AND (", $where) . " )";
             }
             $result = DB::query("SELECT COUNT(\"{$table}\".\"ID\") C FROM \"{$table}\" " . $wherePhrase);
             if ($result && $result->value()) {
                 $sql .= $wherePhrase;
                 DB::query($sql);
                 DB::alteration_message("Updated {$field} in {$table} to {$value} ", "added");
             }
         }
     }
 }
Exemple #18
0
 /**
  * Add default records to database.
  *
  * This function is called whenever the database is built, after the
  * database tables have all been created. Overload this to add default
  * records when the database is built, but make sure you call
  * parent::requireDefaultRecords().
  */
 public function requireDefaultRecords()
 {
     if (!SiteTree::get_by_link(Config::inst()->get('RootURLController', 'default_homepage_link'))) {
         $homepage = new HomePage();
         $homepage->Title = 'Home';
         $homepage->URLSegment = Config::inst()->get('RootURLController', 'default_homepage_link');
         $homepage->Sort = 1;
         $homepage->write();
         $homepage->publish('Stage', 'Live');
         $homepage->flushCache();
         DB::alteration_message('Home page created', 'created');
     }
     if (DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) {
         $aboutus = new RootPage();
         $aboutus->Title = 'About Us';
         $aboutus->Sort = 2;
         $aboutus->write();
         $aboutus->publish('Stage', 'Live');
         $aboutus->flushCache();
         DB::alteration_message('Book 1 created', 'created');
         $contactus = new RootPage();
         $contactus->Title = 'Contact Us';
         $contactus->Sort = 3;
         $contactus->write();
         $contactus->publish('Stage', 'Live');
         $contactus->flushCache();
         DB::alteration_message('Book 2 created', 'created');
     }
     // call it on the parent
     parent::requireDefaultRecords();
 }
 public function run($request)
 {
     $migrated = FileMigrationHelper::singleton()->run();
     if ($migrated) {
         DB::alteration_message("{$migrated} File DataObjects upgraded", "changed");
     }
 }
 /**
  * Create an {@link ErrorPage} for status code 503
  * 
  * @see UnderConstruction_Extension::onBeforeInit()
  * @see DataObjectDecorator::requireDefaultRecords()
  * @return Void
  */
 function requireDefaultRecords()
 {
     // Ensure that an assets path exists before we do any error page creation
     if (!file_exists(ASSETS_PATH)) {
         mkdir(ASSETS_PATH);
     }
     $pageUnderConstructionErrorPage = DataObject::get_one('ErrorPage', "\"ErrorCode\" = '503'");
     $pageUnderConstructionErrorPageExists = $pageUnderConstructionErrorPage && $pageUnderConstructionErrorPage->exists() ? true : false;
     $pageUnderConstructionErrorPagePath = ErrorPage::get_filepath_for_errorcode(503);
     if (!($pageUnderConstructionErrorPageExists && file_exists($pageUnderConstructionErrorPagePath))) {
         if (!$pageUnderConstructionErrorPageExists) {
             $pageUnderConstructionErrorPage = new ErrorPage();
             $pageUnderConstructionErrorPage->ErrorCode = 503;
             $pageUnderConstructionErrorPage->Title = _t('UnderConstruction.TITLE', 'Under Construction');
             $pageUnderConstructionErrorPage->Content = _t('UnderConstruction.CONTENT', '<p>Sorry, this site is currently under construction.</p>');
             $pageUnderConstructionErrorPage->Status = 'New page';
             $pageUnderConstructionErrorPage->write();
             $pageUnderConstructionErrorPage->publish('Stage', 'Live');
         }
         // Ensure a static error page is created from latest error page content
         $response = Director::test(Director::makeRelative($pageUnderConstructionErrorPage->Link()));
         if ($fh = fopen($pageUnderConstructionErrorPagePath, 'w')) {
             $written = fwrite($fh, $response->getBody());
             fclose($fh);
         }
         if ($written) {
             DB::alteration_message('503 error page created', 'created');
         } else {
             DB::alteration_message(sprintf('503 error page could not be created at %s. Please check permissions', $pageUnderConstructionErrorPagePath), 'error');
         }
     }
 }
 function run($request)
 {
     $orderStatusLogClassName = "OrderStatusLog";
     $submittedOrderStatusLogClassName = EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order");
     if ($submittedOrderStatusLogClassName) {
         $sampleSubmittedStatusLog = DataObject::get_one($submittedOrderStatusLogClassName);
         if ($sampleSubmittedStatusLog) {
             $lastOrderStep = DataObject::get_one("OrderStep", "", "\"Sort\" DESC");
             if ($lastOrderStep) {
                 $joinSQL = "INNER JOIN \"{$orderStatusLogClassName}\" ON \"{$orderStatusLogClassName}\".\"OrderID\" = \"Order\".\"ID\"";
                 $whereSQL = "WHERE \"StatusID\" <> " . $lastOrderStep->ID . " AND \"{$orderStatusLogClassName}\".ClassName = '{$submittedOrderStatusLogClassName}'";
                 $count = DB::query("\r\n\t\t\t\t\t\tSELECT COUNT (\"Order\".\"ID\")\r\n\t\t\t\t\t\tFROM \"Order\"\r\n\t\t\t\t\t\t{$joinSQL}\r\n\t\t\t\t\t\t{$whereSQL}\r\n\t\t\t\t\t")->value();
                 $do = DB::query("\r\n\t\t\t\t\t\tUPDATE \"Order\"\r\n\t\t\t\t\t\t{$joinSQL}\r\n\t\t\t\t\t\tSET \"StatusID\" = " . $lastOrderStep->ID . "\r\n\t\t\t\t\t\t{$whereSQL}\r\n\t\t\t\t\t");
                 if ($count) {
                     DB::alteration_message("NOTE: {$count} records were updated.", "created");
                 } else {
                     DB::alteration_message("No records were updated.");
                 }
             } else {
                 DB::alteration_message("Could not find the last order step.", "deleted");
             }
         } else {
             DB::alteration_message("Could not find any submitted order logs.", "deleted");
         }
     } else {
         DB::alteration_message("Could not find a class name for submitted orders.", "deleted");
     }
 }
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     // Add default author group if no other group exists
     $frontend_group = Group::get()->filter("Code", "users-frontend");
     if (!$frontend_group->exists()) {
         $frontend_group = new Group();
         $frontend_group->Code = 'users-frontend';
         $frontend_group->Title = "Frontend Users";
         $frontend_group->Sort = 1;
         $frontend_group->write();
         Permission::grant($frontend_group->ID, 'USERS_MANAGE_ACCOUNT');
         DB::alteration_message('Front end users group created', 'created');
     }
     // Add a verified users group (only used if we turn on
     // verification)
     $verify_group = Group::get()->filter("Code", "users-verified");
     if (!$verify_group->exists()) {
         $verify_group = new Group();
         $verify_group->Code = 'users-verified';
         $verify_group->Title = "Verified Users";
         $verify_group->Sort = 1;
         $verify_group->write();
         Permission::grant($verify_group->ID, 'USERS_VERIFIED');
         DB::alteration_message('Verified users group created', 'created');
     }
 }
 public function requireDefaultRecords()
 {
     // If no tax rates, setup some defaults
     if (!TaxRate::get()->exists()) {
         $vat = TaxRate::create();
         $vat->Title = "VAT";
         $vat->Amount = 20;
         $vat->Code = "T1";
         $vat->write();
         DB::alteration_message('VAT tax rate created.', 'created');
         $reduced = TaxRate::create();
         $reduced->Title = "Reduced rate";
         $reduced->Amount = 5;
         $reduced->Code = "T2";
         $reduced->write();
         DB::alteration_message('Reduced tax rate created.', 'created');
         $zero = TaxRate::create();
         $zero->Title = "Zero rate";
         $zero->Amount = 0;
         $zero->Code = "T4";
         $zero->write();
         DB::alteration_message('Zero tax rate created.', 'created');
     }
     parent::requireDefaultRecords();
 }
 function run($request)
 {
     increase_time_limit_to(3600);
     $modules = GitRepoFinder::get_all_repos();
     $gitUser = Config::inst()->get('GitRepoFinder', "github_user_name");
     $packagistUser = $this->Config()->get("packagist_user_name");
     if ($gitUser && $packagistUser) {
         //all is good ...
     } else {
         user_error("make sure to set your git and packagist usernames via the standard config system");
     }
     $count = 0;
     echo "<h1>Testing " . count($modules) . " modules (git user: {$gitUser} and packagist user: {$packagistUser}) ...</h1>";
     $methodsToCheck = $this->Config()->get("methods_to_check");
     foreach ($modules as $module) {
         $count++;
         $failures = 0;
         echo "<h3><a href=\"https://github.com/" . $gitUser . "/silverstripe-" . $module . "\"></a>{$count}. checking {$module}</h3>";
         foreach ($methodsToCheck as $method) {
             if (!$this->{$method}($module)) {
                 $failures++;
                 DB::alteration_message("bad response for {$method}", "deleted");
             }
         }
         if ($failures == 0) {
             DB::alteration_message("OK", "created");
         }
         ob_flush();
         flush();
     }
     echo "----------------------------- THE END --------------------------";
 }
 /**
  *	Instantiate a search page, should one not exist.
  */
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     $mode = Versioned::get_reading_mode();
     Versioned::reading_stage('Stage');
     // Determine whether pages should be created.
     if (self::config()->create_default_pages) {
         // Determine whether an extensible search page already exists.
         if (!ExtensibleSearchPage::get()->first()) {
             // Instantiate an extensible search page.
             $page = ExtensibleSearchPage::create();
             $page->Title = 'Search Page';
             $page->write();
             DB::alteration_message('"Default" Extensible Search Page', 'created');
         }
     } else {
         if (ClassInfo::exists('Multisites')) {
             foreach (Site::get() as $site) {
                 // Determine whether an extensible search page already exists.
                 if (!ExtensibleSearchPage::get()->filter('SiteID', $site->ID)->first()) {
                     // Instantiate an extensible search page.
                     $page = ExtensibleSearchPage::create();
                     $page->ParentID = $site->ID;
                     $page->Title = 'Search Page';
                     $page->write();
                     DB::alteration_message("\"{$site->Title}\" Extensible Search Page", 'created');
                 }
             }
         }
     }
     Versioned::set_reading_mode($mode);
 }
 function clearfieldcache($showoutput = false)
 {
     $fieldsToClear = array();
     $fieldsForEach = Config::inst()->get("MenuCache", "fields");
     foreach ($fieldsForEach as $key => $field) {
         $fieldName = self::field_maker($key);
         $fieldsToClear[] = "\"" . $fieldName . "\" = ''";
     }
     if (count($fieldsToClear)) {
         $tablesForEach = Config::inst()->get("MenuCache", "tables_to_clear");
         foreach ($tablesForEach as $table) {
             $msg = '';
             $sql = "UPDATE \"" . $table . "\" SET " . implode(", ", $fieldsToClear);
             if (Controller::curr()->getRequest()->param("ID") == "days" && ($days = intval(Controller::curr()->getRequest()->param("OtherID")))) {
                 $sql .= ' WHERE \\"LastEdited\\" > ( NOW() - INTERVAL ' . $days . ' DAY )';
                 $msg .= ', created before the last ' . $days . ' days';
             } elseif (Controller::curr()->getRequest()->param("ID") == "thispage") {
                 $sql .= " WHERE  \"" . $table . "\".\"ID\" = " . $this->owner->ID;
                 $msg .= ', for page with ID = ' . $this->owner->ID;
             }
             if ($showoutput) {
                 DB::alteration_message("Deleting cached data from {$table}, " . $msg);
                 debug::show($sql);
             }
             DB::query($sql);
         }
     }
     return array();
 }
 /**
  * 
  * @param SS_HTTPRequest $request
  */
 public function run($request)
 {
     increase_time_limit_to();
     echo 'Pass ?refresh=1 to refresh your members<br/>';
     echo '<hr/>';
     $refresh = $request->getVar('refresh');
     if ($refresh) {
         DB::alteration_message("Resetting all members location");
         DB::query('UPDATE Member SET Latitude = 0, Longitude = 0');
     }
     $Members = Member::get()->filter(array('Latitude' => 0));
     foreach ($Members as $Member) {
         DB::alteration_message('Processing member #' . $Member->ID . ' - ' . $Member->getTitle());
         if (!$Member->Latitude) {
             if ($Member->canBeGeolocalized()) {
                 DB::alteration_message($Member->GeocodeText());
                 if (!$Member->CountryCode) {
                     DB::alteration_message("Warning ! This member has no country code", "error");
                 }
                 /* @var $res Geocoder\Model\Address */
                 $res = $Member->Geocode();
                 if ($res) {
                     DB::alteration_message('Geocode success on ' . $res->getLatitude() . ',' . $res->getLongitude() . ' : ' . $res->getStreetNumber() . ', ' . $res->getStreetName() . ' ' . $res->getPostalCode() . ' ' . $res->getLocality() . ' ' . $res->getCountry(), 'created');
                     $Member->write();
                 } else {
                     DB::alteration_message('Geocode error', 'error');
                 }
             } else {
                 DB::alteration_message('Cannot be geolocalized', 'error');
             }
         } else {
             DB::alteration_message('Already geolocalized', 'error');
         }
     }
 }
 function run($request)
 {
     $customerGroup = EcommerceRole::get_customer_group();
     if ($customerGroup) {
         $allCombos = DB::query("\n\t\t\t\tSELECT \"Group_Members\".\"ID\", \"Group_Members\".\"MemberID\", \"Group_Members\".\"GroupID\"\n\t\t\t\tFROM \"Group_Members\"\n\t\t\t\tWHERE \"Group_Members\".\"GroupID\" = " . $customerGroup->ID . ";");
         //make an array of all combos
         $alreadyAdded = array();
         $alreadyAdded[-1] = -1;
         if ($allCombos) {
             foreach ($allCombos as $combo) {
                 $alreadyAdded[$combo["MemberID"]] = $combo["MemberID"];
             }
         }
         $unlistedMembers = Member::get()->exclude(array("ID" => $alreadyAdded))->innerJoin("Order", "\"Order\".\"MemberID\" = \"Member\".\"ID\"");
         //add combos
         if ($unlistedMembers->count()) {
             $existingMembers = $customerGroup->Members();
             foreach ($unlistedMembers as $member) {
                 $existingMembers->add($member);
                 DB::alteration_message("Added member to customers: " . $member->Email, "created");
             }
         }
     } else {
         DB::alteration_message("NO customer group found", "deleted");
     }
 }
 function run($request)
 {
     ini_set('max_execution_time', 3000);
     $tables = DB::query('SHOW TABLE STATUS WHERE ENGINE <>  \'InnoDB\'');
     foreach ($tables as $table) {
         $table = $table["Name"];
         DB::alteration_message("Updating {$table} to innoDB", "created");
         $this->flushNow();
         $indexRows = DB::query("SHOW INDEX FROM \"{$table}\" WHERE Index_type = 'FULLTEXT'");
         unset($done);
         $done = array();
         foreach ($indexRows as $indexRow) {
             $key = $indexRow["Key_name"];
             if (!isset($done[$key])) {
                 DB::alteration_message("Deleting INDEX {$key} in {$table} (FullText Index)", "deleted");
                 $this->flushNow();
                 DB::query("ALTER TABLE \"{$table}\" DROP INDEX {$key};");
                 $done[$key] = $key;
             }
         }
         $sql = "ALTER TABLE \"{$table}\" ENGINE=INNODB";
         DB::query($sql);
     }
     //$rows = DB::query("SHOW GLOBAL STATUS LIKE  'Innodb_page_size'");
     $currentInnoDBSetting = DB::query("SELECT @@innodb_buffer_pool_size as V;")->Value();
     $innoDBBufferUsed = DB::query("\r\n\r\nSELECT (PagesData*PageSize)/POWER(1024,3) DataGB FROM\r\n(SELECT variable_value PagesData\r\nFROM information_schema.global_status\r\nWHERE variable_name='Innodb_buffer_pool_pages_data') A,\r\n(SELECT variable_value PageSize\r\nFROM information_schema.global_status\r\nWHERE variable_name='Innodb_page_size') B;\r\n\r\n\t\t")->value();
     $innoBDBufferRecommended = DB::query("\r\nSELECT CEILING(Total_InnoDB_Bytes*1.6/POWER(1024,3)) RIBPS FROM\r\n (SELECT SUM(data_length+index_length) Total_InnoDB_Bytes\r\n FROM information_schema.tables WHERE engine='InnoDB') A;\r\n")->value();
     DB::alteration_message("<hr /><hr /><hr /><hr /><hr /><hr /><hr />COMPLETED\r\n\t\t<br />\r\n\t\tPlease check your MYSQL innodb_buffer_pool_size setting.\r\n\t\tIt is currently using " . round($innoDBBufferUsed, 3) . "G,\r\n\t\tbut it should be set to " . round($innoBDBufferRecommended, 3) . "G.\r\n\t\tThe current setting is: " . round($currentInnoDBSetting / (1042 * 1024 * 1024)) . "G\r\n\t\t<hr /><hr /><hr /><hr /><hr /><hr /><hr />");
 }
 /**
  * Create default blog setup
  */
 function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     if (!DataObject::get_one('UserAgreementPage')) {
         if (class_exists('Site') && ($sites = Site::get())) {
             if ($sites->first()) {
                 foreach ($sites as $site) {
                     $page = new UserAgreementPage();
                     $page->Title = "User Agreement";
                     $page->URLSegment = "user-agreement";
                     $page->Status = "Published";
                     $page->ShowInMenus = 0;
                     $page->ParentID = $site->ID;
                     $page->write();
                     $page->publish("Stage", "Live");
                     DB::alteration_message("User Agreement Page Created", "created");
                 }
             }
         } else {
             $page = new UserAgreementPage();
             $page->Title = "User Agreement";
             $page->URLSegment = "user-agreement";
             $page->Status = "Published";
             $page->ShowInMenus = 0;
             $page->write();
             $page->publish("Stage", "Live");
             DB::alteration_message("User Agreement Page Created", "created");
         }
     }
 }