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)
 {
     $tables = array("ProductGroup", "ProductGroup_Live", "Product", "Product_Live");
     if (class_exists("ProductVariation")) {
         $tables[] = "ProductVariation";
     }
     //todo: make list based on buyables rather than hard-coded.
     foreach ($tables as $tableName) {
         $classErrorCount = 0;
         $removeCount = 0;
         $updateClassCount = 0;
         $rowCount = DB::query("SELECT COUNT(\"ImageID\") FROM \"{$tableName}\" WHERE ImageID > 0;")->value();
         DB::alteration_message("<h2><strong>CHECKING {$tableName} ( {$rowCount} records ):</strong></h2>");
         $rows = DB::query("SELECT \"ImageID\", \"{$tableName}\".\"ID\" FROM \"{$tableName}\" WHERE ImageID > 0;");
         if ($rows) {
             foreach ($rows as $row) {
                 $remove = false;
                 $classErrorCount += DB::query("\r\n\t\t\t\t\t\tSELECT COUNT (\"File\".\"ID\")\r\n\t\t\t\t\t\tFROM \"File\"\r\n\t\t\t\t\t\tWHERE\r\n\t\t\t\t\t\t\t\"File\".\"ID\" = " . $row["ImageID"] . "\r\n\t\t\t\t\t\t\tAND  (\r\n\t\t\t\t\t\t\t \"ClassName\" = 'Image' OR\r\n\t\t\t\t\t\t\t \"ClassName\" = 'ProductVariation_Image' OR\r\n\t\t\t\t\t\t\t \"ClassName\" = ''\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t")->value();
                 DB::query("\r\n\t\t\t\t\t\tUPDATE \"File\"\r\n\t\t\t\t\t\tSET \"ClassName\" = 'Product_Image'\r\n\t\t\t\t\t\tWHERE\r\n\t\t\t\t\t\t\t\"File\".\"ID\" = " . $row["ImageID"] . "\r\n\t\t\t\t\t\t\tAND  (\r\n\t\t\t\t\t\t\t \"ClassName\" = 'Image' OR\r\n\t\t\t\t\t\t\t \"ClassName\" = 'ProductVariation_Image' OR\r\n\t\t\t\t\t\t\t \"ClassName\" = ''\r\n\t\t\t\t\t\t\t);\r\n\t\t\t\t\t");
                 $image = Product_Image::get()->byID($row["ImageID"]);
                 if (!$image) {
                     $remove = true;
                 } elseif (!$image->getTag()) {
                     $remove = true;
                 }
                 if ($remove) {
                     $removeCount++;
                     DB::query("UPDATE \"{$tableName}\" SET \"ImageID\" = 0 WHERE \"{$tableName}\".\"ID\" = " . $row["ID"] . " AND \"{$tableName}\".\"ImageID\" = " . $row["ImageID"] . ";");
                 } elseif (!is_a($image, Object::getCustomClass("Product_Image"))) {
                     $updateClassCount++;
                     $image = $image->newClassInstance("Product_Image");
                     $image - write();
                 }
             }
         }
         if ($classErrorCount) {
             DB::alteration_message("<strong>{$tableName}:</strong> there were {$classErrorCount} files with the wrong class names.  These have been fixed.", "deleted");
         } else {
             DB::alteration_message("<strong>{$tableName}:</strong> there were no files with the wrong class names. ", "created");
         }
         if ($removeCount) {
             DB::alteration_message("<strong>{$tableName}:</strong> Removed {$removeCount} image(s) from products and variations because they do not exist in the file-system or database", "deleted");
         } else {
             DB::alteration_message("<strong>{$tableName}:</strong> All product images are accounted for", "created");
         }
         if ($updateClassCount) {
             DB::alteration_message("<strong>{$tableName}:</strong> {$removeCount} image(s) did not match the requirement 'instanceOF Product_Image', this has been corrected.", "deleted");
         } else {
             DB::alteration_message("<strong>{$tableName}:</strong> All product images instancesOF Product_Image", "created");
         }
     }
 }
 /**
  * standard SS method.
  * Runs before the Page::init method is called.
  *
  */
 function onBeforeInit()
 {
     $this->secureHostSwitcher();
     Requirements::javascript(THIRDPARTY_DIR . "/jquery/jquery.js");
     //Requirements::block(THIRDPARTY_DIR."/jquery/jquery.js");
     //Requirements::javascript(Director::protocol()."ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js");
     //todo: check if we even need this (via ShoppingCartsRequirements.ss)
     if ($this->owner->dataRecord) {
         if (is_a($this->owner->dataRecord, Object::getCustomClass("Product")) || is_a($this->owner->dataRecord, Object::getCustomClass("ProductGroup"))) {
             Session::set("ContinueShoppingLink", $this->owner->Link());
         }
     }
 }
コード例 #4
0
 /**
  * Add a member to the order - in case he / she is not a shop admin.
  *
  * @param Order object
  * @return Boolean - true if run correctly.
  **/
 public function doStep(Order $order)
 {
     if (!$order->IsSubmitted()) {
         $className = $this->getRelevantLogEntryClassName();
         if (class_exists($className)) {
             //add currency if needed.
             $order->getHasAlternativeCurrency();
             $obj = $className::create();
             if (is_a($obj, Object::getCustomClass("OrderStatusLog"))) {
                 $obj->OrderID = $order->ID;
                 $obj->Title = $this->Name;
                 //it is important we add this here so that we can save the 'submitted' version.
                 //this is particular important for the Order Item Links.
                 //order write will also update all the OrderAttributes!
                 $obj->write();
                 $obj = OrderStatusLog::get()->byID($obj->ID);
                 $saved = false;
                 if ($this->SaveOrderAsSerializedObject) {
                     $obj->OrderAsString = $order->ConvertToString();
                     $saved = true;
                 }
                 if ($this->SaveOrderAsHTML || !$saved) {
                     $obj->OrderAsHTML = Convert::raw2sql($order->ConvertToHTML());
                 }
                 $obj->write();
             } else {
                 user_error('EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order") refers to a class that is NOT an instance of OrderStatusLog');
             }
         } else {
             user_error('EcommerceConfig::get("OrderStatusLog", "order_status_log_class_used_for_submitting_order") refers to a non-existing class');
         }
         $order->LastEdited = "'" . SS_Datetime::now()->Rfc2822() . "'";
         //add member if needed...
         if (!$order->MemberID) {
             //lets see if we can find a member
             $memberOrderID = Session::get("Ecommerce_Member_For_Order");
             Session::clear("Ecommerce_Member_For_Order");
             Session::set("Ecommerce_Member_For_Order", 0);
             Session::save();
             if ($memberOrderID) {
                 $order->MemberID = $memberOrderID;
             }
         }
         $order->write($showDebug = false, $forceInsert = false, $forceWrite = true);
     }
     return true;
 }
 /**
  * @return ArrayList
  */
 public function PageTypes()
 {
     $pageTypes = parent::PageTypes();
     $result = new ArrayList();
     $productClass = Object::getCustomClass("Product");
     $productGroupClass = Object::getCustomClass("Product");
     $acceptedClasses1 = ClassInfo::subclassesFor("ProductGroup");
     $acceptedClasses1[$productClass] = $productClass;
     $acceptedClasses2 = ClassInfo::subclassesFor($productGroupClass);
     $acceptedClasses2[$productGroupClass] = $productGroupClass;
     $acceptedClasses = $acceptedClasses1 + $acceptedClasses2;
     foreach ($pageTypes as $type) {
         if (in_array($type->ClassName, $acceptedClasses)) {
             $result->push($type);
         }
     }
     return $result;
 }
コード例 #6
0
 /**
  *@param $object - the buyable / OrderItem
  **/
 function __construct($object, $parameters = null)
 {
     Requirements::javascript("ecommerce/javascript/EcomQuantityField.js");
     // LEAVE HERE - NOT EASY TO INCLUDE VIA TEMPLATE
     if ($object instanceof BuyableModel) {
         $this->orderItem = ShoppingCart::singleton()->findOrMakeItem($object, $parameters);
         //provide a 0-quantity facade item if there is no such item in cart OR perhaps we should just store the product itself, and do away with the facade, as it might be unnecessary complication
         if (!$this->orderItem) {
             $className = $object->classNameForOrderItem();
             $this->orderItem = new $className($object->dataRecord, 0);
         }
     } elseif (is_a($object, Object::getCustomClass("OrderItem")) && $object->BuyableID) {
         $this->orderItem = $object;
     } else {
         user_error("EcomQuantityField: no/bad order item or buyable passed to constructor.", E_USER_WARNING);
     }
     $this->parameters = $parameters;
 }
 function run($request)
 {
     $arrayOfBuyables = EcommerceConfig::get("EcommerceDBConfig", "array_of_buyables");
     foreach ($arrayOfBuyables as $buyable) {
         $allproducts = $buyable::get();
         if ($allproducts->count()) {
             foreach ($allproducts as $product) {
                 DB::alteration_message("Deleting " . $product->ClassName . " ID = " . $product->ID, "deleted");
                 if (is_a($product, Object::getCustomClass("SiteTree"))) {
                     $product->deleteFromStage('Live');
                     $product->deleteFromStage('Stage');
                 } else {
                     $product->delete();
                 }
                 $product->destroy();
                 //TODO: remove versions
             }
         }
     }
 }
 public function dataObj()
 {
     if (is_numeric($this->itemID) && is_numeric($this->versionID)) {
         return Versioned::get_version(ClassInfo::baseDataClass(Object::getCustomClass($this->ctf->sourceClass())), $this->itemID, $this->versionID);
     }
 }
コード例 #9
0
ファイル: Permission.php プロジェクト: Raiser/Praktikum
 /**
  * Returns all members for a specific permission.
  * 
  * @param $code String|array Either a single permission code, or a list of permission codes
  * @return DataObjectSet Returns a set of member that have the specified
  *                       permission.
  */
 public static function get_members_by_permission($code)
 {
     $toplevelGroups = self::get_groups_by_permission($code);
     if (!$toplevelGroups) {
         return false;
     }
     $groupIDs = array();
     foreach ($toplevelGroups as $group) {
         $familyIDs = $group->collateFamilyIDs();
         if (is_array($familyIDs)) {
             $groupIDs = array_merge($groupIDs, array_values($familyIDs));
         }
     }
     if (!count($groupIDs)) {
         return false;
     }
     $members = DataObject::get(Object::getCustomClass('Member'), $_filter = "\"Group\".\"ID\" IN (" . implode(",", $groupIDs) . ")", $_sort = "", $_join = "LEFT JOIN \"Group_Members\" ON \"Member\".\"ID\" = \"Group_Members\".\"MemberID\" " . "LEFT JOIN \"Group\" ON \"Group_Members\".\"GroupID\" = \"Group\".\"ID\" ");
     return $members;
 }
コード例 #10
0
	/**
	 * Add existing member to group rather than creating a new member
	 */
	function addtogroup() {
		$data = $_REQUEST;
		unset($data['ID']);
		$ctfID = isset($data['ctf']) ? $data['ctf']['ID'] : null;

		if(!is_numeric($ctfID)) {
			FormResponse::status_messsage(_t('MemberTableField.ADDINGFIELD', 'Adding failed'), 'bad');
		}

		$className = Object::getCustomClass($this->stat('data_class'));
		$record = new $className();

		$record->update($data);
		
		$valid = $record->validate();

		if($valid->valid()) {
			$record->write();
			$record->Groups()->add($ctfID);

			$this->sourceItems();

			// TODO add javascript to highlight added row (problem: might not show up due to sorting/filtering)
			FormResponse::update_dom_id($this->id(), $this->renderWith($this->template), true);
			FormResponse::status_message(_t('MemberTableField.ADDEDTOGROUP','Added member to group'), 'good');
		
		} else {
			FormResponse::status_message(Convert::raw2xml("I couldn't add that user to this group:\n\n" . $valid->starredlist()), 'bad');
		}

		return FormResponse::respond();
	}
コード例 #11
0
 /**
  *
  * @param string $object
  *					A string representation of the class to create
  * @param array $params
  *					An array of parameters to be passed to the constructor
  */
 public function create($class, $params = array())
 {
     $class = Object::getCustomClass($class);
     $reflector = new ReflectionClass($class);
     return $reflector->newInstanceArgs($params);
 }
 /**
  * Adding EcommerceDBConfig values
  */
 protected function addEcommerceDBConfigToConfigs()
 {
     $ecommerceDBConfig = EcommerceDBConfig::current_ecommerce_db_config();
     $fields = $ecommerceDBConfig->fieldLabels();
     if ($fields) {
         foreach ($fields as $field => $description) {
             if ($field != "Title" && $field != "UseThisOne") {
                 $defaultsDefaults = $ecommerceDBConfig->stat("defaults");
                 $this->definitions["EcommerceDBConfig"][$field] = "{$description}. <br />see: <a href=\"/admin/shop/EcommerceDBConfig/EditForm/field/EcommerceDBConfig/item/" . $ecommerceDBConfig->ID . "/edit\">Ecommerce Configuration</a>";
                 $this->configs["EcommerceDBConfig"][$field] = $ecommerceDBConfig->{$field};
                 $this->databaseValues["EcommerceDBConfig"][$field] = true;
                 $this->defaults["EcommerceDBConfig"][$field] = isset($defaultsDefaults[$field]) ? $defaultsDefaults[$field] : "no default set";
                 $imageField = $field . "ID";
                 if (isset($ecommerceDBConfig->{$imageField})) {
                     if ($image = $ecommerceDBConfig->{$field}()) {
                         if ($image->exists() && is_a($image, Object::getCustomClass("Image"))) {
                             $this->configs["EcommerceDBConfig"][$field] = "[Image]  --- <img src=\"" . $image->Link() . "\" />";
                             $this->databaseValues["EcommerceDBConfig"][$field] = true;
                         }
                     }
                 }
             }
         }
     }
 }
コード例 #13
0
 /**
  * Check if two Order Items are the same.
  * Useful when adding two items to cart.
  *
  * @param OrderItem $orderItem
  * @return Boolean
  **/
 function hasSameContent(OrderItem $orderItem)
 {
     return is_a($orderItem, Object::getCustomClass("OrderItem")) && $this->BuyableID == $orderItem->BuyableID && $this->BuyableClassName == $orderItem->BuyableClassName && $this->Version == $orderItem->Version;
 }
コード例 #14
0
 /**
  *@todo: are there times when the Shipping rather than the Billing address should be linked?
  * Copies the last address used by the member.
  *
  * @param Object (Member) $member
  * @param Boolean $write - should the address be written
  * @return DataObject (OrderAddress / ShippingAddress / BillingAddress)
  **/
 public function FillWithLastAddressFromMember(Member $member, $write = false)
 {
     $excludedFields = array("ID", "OrderID");
     $fieldPrefix = $this->fieldPrefix();
     if ($member && $member->exists()) {
         $oldAddress = $member->previousOrderAddress($this->baseClassLinkingToOrder(), $this->ID);
         if ($oldAddress) {
             $fieldNameArray = $this->getFieldNameArray($fieldPrefix);
             foreach ($fieldNameArray as $field) {
                 if (in_array($field, $excludedFields)) {
                     //do nothing
                 } elseif ($this->{$field}) {
                     //do nothing
                 } elseif (isset($oldAddress->{$field})) {
                     $this->{$field} = $oldAddress->{$field};
                 }
             }
         }
         //copy data from  member
         if (is_a($this, Object::getCustomClass("BillingAddress"))) {
             $this->Email = $member->Email;
         }
         $fieldNameArray = array("FirstName" => $fieldPrefix . "FirstName", "Surname" => $fieldPrefix . "Surname");
         foreach ($fieldNameArray as $memberField => $fieldName) {
             //NOTE, we always override the Billing Address (which does not have a fieldPrefix)
             if (!$this->{$fieldName} || is_a($this, Object::getCustomClass("BillingAddress"))) {
                 $this->{$fieldName} = $member->{$memberField};
             }
         }
     }
     if ($write) {
         $this->write();
     }
     return $this;
 }
コード例 #15
0
 /**
  * Import members from the uploaded file
  */
 protected function importMembers($id, $group, $cols, $setFields, $primaryColType = 'Email')
 {
     $startTime = time();
     $importData = Session::get("ImportFile.{$id}");
     $validColumns = array_keys(RecipientImportField::$column_types);
     $columnMap = array_flip($cols);
     // Debug::show($columnMap);
     // locate the primary column's index
     $primaryColumn = $columnMap[$primaryColType];
     // changed fields
     $changedFields = array();
     // intersect the list of valid columns with the column map to find the columns we need
     $importColumns = array_intersect($validColumns, $cols);
     // statistics
     $newMembers = 0;
     $changedMembers = 0;
     $skippedMembers = 0;
     // the class that the imported members will become
     $newMemberClass = Object::getCustomClass('Member');
     // for each row, add a new member or overwrite an existing member
     foreach ($importData as $newMemberRow) {
         // skip rows with an empty value for the primary column
         if (empty($newMemberRow[$primaryColumn])) {
             $skippedMembers++;
             continue;
         }
         // remember to check if the user has unsubscribed
         $trackChanges = true;
         // TODO: Write DataObject::update
         $member = $this->findMember($newMemberRow[$primaryColumn]);
         if (!$member) {
             $newMembers++;
             $trackChanges = false;
             $member = Object::create("Member");
         } else {
             // skip this member if the are unsubscribed
             if ($member->Unsubscribed) {
                 $skippedMembers++;
                 continue;
             }
             if ($member->class != $newMemberClass) {
                 $member->setClassName($newMemberClass);
             }
             $changedMembers++;
         }
         // add each of the valid columns
         foreach ($importColumns as $datum) {
             // perform any required conversions
             $newValue = trim($newMemberRow[$columnMap[$datum]]);
             $oldValue = trim($member->{$datum});
             // Debug::message( "$datum@{$columnMap[$datum]}" );
             // track the modifications to the member data
             if ($trackChanges && $newValue != $oldValue && $datum != $primaryColumn) {
                 $changedFields[] = array($newMemberRow[$primaryColumn], "{$datum}:\n{$oldValue}", "{$datum}:\n{$newValue}");
                 $numChangedFields++;
             }
             $member->{$datum} = $newValue;
         }
         // set any set fields
         if ($setFields) {
             foreach ($setFields as $fieldName => $fieldValue) {
                 $member->{$fieldName} = $fieldValue;
             }
         }
         // add member to group
         $member->write();
         $member->Groups()->add($group->ID);
     }
     $numChangedFields = count($changedFields);
     $this->notifyChanges($changedFields);
     // TODO Refresh window
     $customData = array('ID' => $id, "UploadForm" => $this->controller->UploadForm($id), 'ImportMessage' => 'Imported new members', 'NewMembers' => (string) $newMembers, 'ChangedMembers' => (string) $changedMembers, 'ChangedFields' => (string) $numChangedFields, 'SkippedRecords' => (string) $skippedMembers, 'Time' => time() - $startTime);
     return $this->customise($customData)->renderWith('Newsletter_RecipientImportField');
 }
コード例 #16
0
 /**
  * Checks if an email has been sent for this Order for this status (order step)
  * @return boolean
  **/
 function hasBeenSent()
 {
     $orderStep = $this->order->Status();
     if (is_a($orderStep, Object::getCustomClass("OrderStep"))) {
         return $orderStep->hasBeenSent($this->order);
     }
     return false;
 }
コード例 #17
0
 /**
  * returns JSON in this format:
  * Array(
  *  ClassName => $className,
  *  ID => $obj->ID,
  *  Version => $obj->Version,
  *  Title => $name
  * );
  *
  * @param SS_HTTPRequest
  * @return String (JSON)
  */
 function json(SS_HTTPRequest $request)
 {
     $countOfSuggestions = $request->requestVar("countOfSuggestions");
     $term = Convert::raw2sql($request->requestVar("term"));
     $arrayOfBuyables = EcommerceConfig::get("EcommerceDBConfig", "array_of_buyables");
     $arrayOfAddedItemIDsByClassName = array();
     $lengthOfFieldsToSearch = count($this->fieldsToSearch);
     $lenghtOfBuyables = count($arrayOfBuyables);
     $array = array();
     //search by InternalID ....
     $absoluteCount = 0;
     $buyables = array();
     foreach ($arrayOfBuyables as $key => $buyableClassName) {
         $buyables[$key] = array();
         $singleton = singleton($buyableClassName);
         $buyables[$key]["Singleton"] = $singleton;
         $buyables[$key]["ClassName"] = $buyableClassName;
         $buyables[$key]["TableName"] = $buyableClassName;
         if (is_a($singleton, Object::getCustomClass("SiteTree"))) {
             if (Versioned::current_stage() == "Live") {
                 $buyables[$key]["TableName"] .= "_Live";
             }
         }
     }
     unset($arrayOfBuyables);
     while (count($array) <= $countOfSuggestions && $absoluteCount < 30) {
         $absoluteCount++;
         for ($i = 0; $i < $lengthOfFieldsToSearch; $i++) {
             $fieldName = $this->fieldsToSearch[$i];
             for ($j = 0; $j < $lenghtOfBuyables; $j++) {
                 $buyableArray = $buyables[$j];
                 $singleton = $buyableArray["Singleton"];
                 $className = $buyableArray["ClassName"];
                 $tableName = $buyableArray["TableName"];
                 if (!isset($arrayOfAddedItemIDsByClassName[$className])) {
                     $arrayOfAddedItemIDsByClassName[$className] = array(-1 => -1);
                 }
                 if ($singleton->hasDatabaseField($fieldName)) {
                     $where = "\"{$fieldName}\" LIKE '%{$term}%'\n\t\t\t\t\t\t\t\tAND \"" . $tableName . "\".\"ID\" NOT IN\n\t\t\t\t\t\t\t\tAND \"AllowPurchase\" = 1";
                     $obj = $className::get()->filter(array($fieldName . ":PartialMatch" => $term, "AllowPurchase" => 1))->where("\"{$tableName}\".\"ID\" NOT IN (" . implode(",", $arrayOfAddedItemIDsByClassName[$className]) . ")")->First();
                     if ($obj) {
                         //we found an object, we dont need to find it again.
                         $arrayOfAddedItemIDsByClassName[$className][$obj->ID] = $obj->ID;
                         //now we are only going to add it, if it is available!
                         if ($obj->canPurchase()) {
                             $useVariationsInstead = false;
                             if ($obj->hasExtension("ProductWithVariationDecorator")) {
                                 $variations = $obj->Variations();
                                 if ($variations->count()) {
                                     $useVariationsInstead = true;
                                 }
                             }
                             if (!$useVariationsInstead) {
                                 $name = $obj->FullName ? $obj->FullName : $obj->getTitle();
                                 $array[$className . $obj->ID] = array("ClassName" => $className, "ID" => $obj->ID, "Version" => $obj->Version, "Title" => $name);
                             }
                         }
                     }
                 } else {
                     //echo $singleton->ClassName ." does not have $fieldName";
                 }
             }
         }
     }
     //remove KEYS
     $finalArray = array();
     $count = 0;
     foreach ($array as $item) {
         if ($count < $countOfSuggestions) {
             $finalArray[] = $item;
         }
         $count++;
     }
     return $this->array2json($finalArray);
 }
コード例 #18
0
 /**
  * standard SS method
  * try to finalise order if payment has been made.
  */
 function onAfterWrite()
 {
     parent::onAfterWrite();
     $order = $this->Order();
     if ($order && is_a($order, Object::getCustomClass("Order")) && $order->IsSubmitted()) {
         $order->tryToFinaliseOrder();
     }
 }
コード例 #19
0
 /**
  * NOTE: tried to copy part to the Order Class - but that was not much of a go-er.
  * @param Int | Order $order
  * @return DataObject(Order)
  **/
 public function copyOrder($oldOrder)
 {
     if (is_numeric($oldOrder)) {
         $oldOrder = Order::get()->byID(intval($oldOrder));
     } elseif (is_a($oldOrder, Object::getCustomClass("Order"))) {
         //$oldOrder = $oldOrder;
     } else {
         user_error("Bad order provided as parameter to ShoppingCart::loadOrder()");
     }
     if ($oldOrder) {
         if ($oldOrder->canView()) {
             $newOrder = Order::create();
             //copying fields.
             $newOrder->UseShippingAddress = $oldOrder->UseShippingAddress;
             //important to set it this way...
             $newOrder->setCurrency($oldOrder->CurrencyUsed());
             $newOrder->MemberID = $oldOrder->MemberID;
             //load the order
             $newOrder->write();
             $this->loadOrder($newOrder);
             $items = OrderItem::get()->filter(array("OrderID" => $oldOrder->ID));
             if ($items->count()) {
                 foreach ($items as $item) {
                     $buyable = $item->Buyable($current = true);
                     if ($buyable->canPurchase()) {
                         $this->addBuyable($buyable, $item->Quantity);
                     }
                 }
             }
             $newOrder->CreateOrReturnExistingAddress("BillingAddress");
             $newOrder->CreateOrReturnExistingAddress("ShippingAddress");
             $newOrder->write();
             $this->addMessage(_t("Order.ORDERCOPIED", "Order has been copied."), 'good');
             return true;
         } else {
             $this->addMessage(_t("Order.NOPERMISSION", "You do not have permission to view this order."), 'bad');
             return false;
         }
     } else {
         $this->addMessage(_t("Order.NOORDER", "Order can not be found."), 'bad');
         return false;
     }
 }
コード例 #20
0
 function getSubTotal()
 {
     $result = 0;
     $items = $this->Items();
     if ($items->count()) {
         foreach ($items as $item) {
             if (is_a($item, Object::getCustomClass("OrderAttribute"))) {
                 $result += $item->Total();
             }
         }
     }
     return $result;
 }
コード例 #21
0
 /**
  * Standard SS method
  * @param Member $member
  * @return Boolean
  */
 public function canDelete($member = null)
 {
     if (is_a(Controller::curr(), Object::getCustomClass("ProductsAndGroupsModelAdmin"))) {
         return false;
     }
     return $this->canEdit($member);
 }
コード例 #22
0
	/**
	 * Returns all members for a specific permission.
	 * 
	 * @param $code String|array Either a single permission code, or a list of permission codes
	 * @return DataObjectSet Returns a set of member that have the specified
	 *                       permission.
	 */
	public static function get_members_by_permission($code) {
		$groupIDs = array();
        
        $SQL_codeList = (is_array($code)) ? implode("','", Convert::raw2sql($code)) : Convert::raw2sql($code);

		$SQL_filter = "Permission.Code IN ('" . $SQL_codeList . "') " .
			"AND Permission.Type = " . self::GRANT_PERMISSION;
		
		$toplevelGroups = DataObject::get(
			'Group', 
			$SQL_filter, // filter
			null, // limit
			"LEFT JOIN `Permission` ON `Group`.`ID` = `Permission`.`GroupID`"
		);
		if(!$toplevelGroups)
			return false;

		foreach($toplevelGroups as $group) {
			$familyIDs = $group->collateFamilyIDs();
			if(is_array($familyIDs)) {
				$groupIDs = array_merge($groupIDs, array_values($familyIDs));
			}
		}

		if(!count($groupIDs))
			return false;

		$members = DataObject::get(
			Object::getCustomClass('Member'),
			$_filter = "`Group`.ID IN (" . implode(",",$groupIDs) . ")",
			$_sort = "",
			$_join = "LEFT JOIN `Group_Members` ON `Member`.`ID` = `Group_Members`.`MemberID` " . 
				"LEFT JOIN `Group` ON `Group_Members`.`GroupID` = `Group`.`ID` "
		);
		return $members;
	}
コード例 #23
0
 /**
  * Recursively generate a product menu.
  * @param String $filter
  * @return ArrayList (ProductGroups)
  */
 function GroupsMenu($filter = "ShowInMenus = 1")
 {
     if ($parent = $this->ParentGroup()) {
         return is_a($parent, Object::getCustomClass("ProductGroup")) ? $parent->GroupsMenu() : $this->ChildGroups($filter);
     } else {
         return $this->ChildGroups($filter);
     }
 }
コード例 #24
0
ファイル: Injector.php プロジェクト: prostart/cobblestonepath
 /**
  *
  * @param string $object
  *					A string representation of the class to create
  * @param array $params
  *					An array of parameters to be passed to the constructor
  */
 public function create(Injector $injector, $class, $params = array())
 {
     $class = Object::getCustomClass($class);
     $reflector = new ReflectionClass($class);
     return $reflector->newInstanceArgs($injector->convertServiceProperty($params));
 }
コード例 #25
0
 function __construct($controller, $name, $group, $members = null, $hidePassword = true, $pageLimit = 10)
 {
     if ($group) {
         if (is_object($group)) {
             $this->group = $group;
         } else {
             if (is_numeric($group)) {
                 $this->group = DataObject::get_by_id('Group', $group);
             }
         }
     } else {
         if (is_numeric($_REQUEST['ctf'][$this->Name()]["ID"])) {
             $this->group = DataObject::get_by_id('Group', $_REQUEST['ctf'][$this->Name()]["ID"]);
         }
     }
     $sourceClass = $this->stat("data_class");
     foreach (self::$addedPermissions as $permission) {
         array_push($this->permissions, $permission);
     }
     $fieldList = array("FirstName" => _t('MemberTableField.FIRSTNAME', 'Firstname'), "Surname" => _t('MemberTableField.SURNAME', 'Surname'), "Email" => _t('MemberTableField.EMAIL', 'Email'));
     $csvFieldList = $fieldList;
     foreach (self::$addedCsvFields as $key => $value) {
         $csvFieldList[$key] = $value;
     }
     foreach (self::$addedFields as $key => $value) {
         $fieldList[$key] = $value;
     }
     if (!$hidePassword) {
         $fieldList["SetPassword"] = "******";
     }
     if (isset($_REQUEST['ctf']['childID']) && ($memberID = $_REQUEST['ctf']['childID'])) {
         $SNG_member = DataObject::get_by_id($this->stat("data_class"), $_REQUEST['ctf']['childID']);
     } else {
         $SNG_member = singleton(Object::getCustomClass($this->stat("data_class")));
     }
     $detailFormFields = $SNG_member->getCMSFields();
     $this->detailFormValidator = $SNG_member->getValidator();
     $this->pageSize = $pageLimit;
     // Legacy: Use setCustomSourceItems() instead.
     if ($members) {
         $this->customSourceItems = $this->memberListWithGroupID($members, $group);
     }
     $this->hidePassword = $hidePassword;
     parent::__construct($controller, $name, $sourceClass, $fieldList);
     Requirements::javascript('cms/javascript/MemberTableField.js');
     // construct the filter and sort
     if (isset($_REQUEST['MemberOrderByField'])) {
         $this->sourceSort = '`' . Convert::raw2sql($_REQUEST['MemberOrderByField']) . '`' . Convert::raw2sql($_REQUEST['MemberOrderByOrder']);
     }
     // search
     $SQL_search = isset($_REQUEST['MemberSearch']) ? Convert::raw2sql($_REQUEST['MemberSearch']) : null;
     if (!empty($_REQUEST['MemberSearch'])) {
         $searchFilters = array();
         foreach ($SNG_member->stat('searchable_fields') as $fieldName => $fieldSpec) {
             $searchFilters[] = "`{$fieldName}` LIKE '%{$SQL_search}%'";
         }
         $this->sourceFilter[] = '(' . implode(' OR ', $searchFilters) . ')';
     }
     // filter by groups
     // TODO Not implemented yet
     if (isset($_REQUEST['ctf'][$this->Name()]['GroupID']) && is_numeric($_REQUEST['ctf'][$this->Name()]['GroupID'])) {
         $this->sourceFilter[] = "`GroupID`='{$_REQUEST['ctf'][$this->Name()]['GroupID']}'";
     } elseif ($this->group) {
         //$this->sourceFilter[] = "`GroupID`='{$this->group->ID}'";
         // If the table is not clean (without duplication), the  total and navigation wil not work well, so uncheck the big line below
         $this->sourceFilter[] = "`Group_Members`.`ID` IN (SELECT `ID` FROM `Group_Members` WHERE `GroupID`='{$this->group->ID}' GROUP BY `MemberID` HAVING MIN(`ID`))";
     }
     $this->sourceJoin = " INNER JOIN `Group_Members` ON `MemberID`=`Member`.`ID`";
     $this->setFieldListCsv($csvFieldList);
 }
コード例 #26
0
	/**
	 * Return the data object being manipulated
	 */
	function dataObj() {
		// used to discover fields if requested and for population of field
		if(is_numeric($this->itemID)) {
 			// we have to use the basedataclass, otherwise we might exclude other subclasses 
 			return DataObject::get_by_id(ClassInfo::baseDataClass(Object::getCustomClass($this->ctf->sourceClass())), $this->itemID); 
		}
		
	}
 function run($request)
 {
     if (isset($_REQUEST['start']) && intval($_REQUEST['start'])) {
         $this->start = intval($_REQUEST['start']);
     }
     if (isset($_REQUEST['productid']) && intval($_REQUEST['productid'])) {
         $this->productID = intval($_REQUEST['productid']);
     }
     if ($this->productManyManyField) {
         $products = Product::get()->limit($this->limit, $this->start);
         if ($this->productID) {
             $products = $products->filter(array("ID" => $this->productID));
         }
         if ($products->count()) {
             foreach ($products as $product) {
                 if ($product->InternalItemID) {
                     if ($product->hasMethod($this->productManyManyField)) {
                         $whereStringArray[] = $product->InternalItemID;
                         for ($i = 0; $i < 10; $i++) {
                             for ($j = 0; $j < 10; $j++) {
                                 $number = strval($i) . strval($j);
                                 $whereStringArray[] = $product->InternalItemID . "_" . $number;
                             }
                         }
                         $images = File::get()->filter(array("Name:PartialMatch" => $whereStringArray));
                         if ($images->count()) {
                             $method = $this->productManyManyField;
                             $collection = $product->{$method}();
                             foreach ($images as $image) {
                                 if (is_a($image, Object::getCustomClass("Image")) && $image->ClassName != Object::getCustomClass("Product_Image")) {
                                     $image = $image->newClassInstance("Product_Image");
                                     $image->write();
                                 }
                                 $collection->add($image);
                                 if ($this->verbose) {
                                     DB::alteration_message("Adding image " . $image->Name . " to " . $product->Title, "created");
                                 }
                             }
                         } else {
                             if ($this->verbose) {
                                 DB::alteration_message("No images where found for product with Title <i>" . $product->Title . "</i>: no images could be added.");
                             }
                         }
                     } else {
                         if ($this->verbose) {
                             DB::alteration_message("The method <i>" . $this->productManyManyField . "</i> does not exist on <i>" . $product->Title . " (" . $product->ClassName . ")</i>: no images could be added.");
                         }
                     }
                 } else {
                     if ($this->verbose) {
                         DB::alteration_message("No InternalItemID set for <i>" . $product->Title . "</i>: no images could be added.");
                     }
                 }
             }
             $productCount = Product::get()->count();
             if ($this->limit < $productCount) {
                 $controller = Controller::curr();
                 $controller->redirect($this->nextBatchLink());
             }
         }
     } else {
         if ($this->verbose) {
             DB::alteration_message("No product Many-2-Many method specified.  No further action taken.  ");
         }
     }
 }
コード例 #28
0
 /**
  * Return a string of class names, in order
  * of hierarchy from OrderAttribute for the
  * current attribute.
  *
  * e.g.: "product_orderitem orderitem
  * orderattribute".
  *
  * Used by the templates and for ajax updating functionality.
  *
  * @return string
  */
 function Classes()
 {
     $class = get_class($this);
     $classes = array();
     $classes[] = strtolower($class);
     while (get_parent_class($class) != 'DataObject' && ($class = get_parent_class($class))) {
         $classes[] = strtolower($class);
     }
     if (is_a($this, Object::getCustomClass("OrderItem"))) {
         $classes[] = strtolower($this->BuyableClassName);
     }
     return implode(' ', $classes);
 }
コード例 #29
0
 /**
  * sends an order email, which can be specified in the URL
  * and displays a sample email
  * typically this link is opened in a new window.
  * @param SS_HTTPRequest $request
  * @return HTML
  **/
 function sendemail(SS_HTTPRequest $request)
 {
     if ($this->currentOrder) {
         $emailClassName = "Order_ReceiptEmail";
         if (class_exists($request->param("OtherID"))) {
             if (is_a(singleton($request->param("OtherID")), Object::getCustomClass("Order_Email"))) {
                 $emailClassName = $request->param("OtherID");
             }
         }
         if ($request->getVar("send")) {
             if ($email = $this->currentOrder->getOrderEmail()) {
                 $subject = _t("Account.COPYONLY", "--- COPY ONLY ---");
                 $message = _t("Account.COPYONLY", "--- COPY ONLY ---");
                 if ($this->currentOrder->sendEmail($subject, $message, $resend = true, $adminOnly = false, $emailClassName)) {
                     $this->message = _t('OrderConfirmationPage.RECEIPTSENT', 'An email has been sent to: ') . $email . '.';
                 } else {
                     $this->message = _t('OrderConfirmationPage.RECEIPT_NOT_SENT', 'Email sent unsuccesfully to: ') . $email . '. EMAIL NOT SENT.';
                 }
             } else {
                 $this->message = _t('OrderConfirmationPage.RECEIPTNOTSENTNOEMAIL', 'No customer details found.  EMAIL NOT SENT.');
             }
         } elseif ($use = $request->getVar("use")) {
             //WE MUST MAKE SURE THAT WE DO NOT SAVE ORDER AS
             $this->currentOrder->StatusID = intval($use);
         }
         //display same data...
         Requirements::clear();
         return $this->currentOrder->renderOrderInEmailFormat($this->message, $emailClassName);
     } else {
         return _t('OrderConfirmationPage.RECEIPTNOTSENTNOORDER', 'Order could not be found.');
     }
 }