function approve($comment, $member = null, $notify = true)
 {
     if (!$member) {
         $member = Member::currentUser();
     }
     if (!$this->owner->Page()->canPublish($member)) {
         return false;
     }
     if ($this->owner->ClassName == 'WorkflowDeletionRequest') {
         if (isset($_REQUEST['DeletionScheduling']) && $_REQUEST['DeletionScheduling'] == 'scheduled') {
             // Update SiteTree_Live directly, rather than doing a publish
             // Because otherwise, unauthorized edits could be pushed live.
             list($day, $month, $year) = explode('/', $_REQUEST['ExpiryDate']['Date']);
             $expiryTimestamp = Convert::raw2sql(date('Y-m-d H:i:s', strtotime("{$year}-{$month}-{$day} {$_REQUEST['ExpiryDate']['Time']}")));
             $pageID = $this->owner->Page()->ID;
             if ($expiryTimestamp) {
                 DB::query("UPDATE \"SiteTree_Live\" SET \"ExpiryDate\" = '{$expiryTimestamp}' WHERE \"ID\" = {$pageID}");
             }
         }
     }
     $this->owner->PublisherID = $member->ID;
     $this->owner->Status = 'Approved';
     $this->owner->write();
     // Embargo means we go Approved -> Scheduled
     if ($this->owner->EmbargoDate) {
         $this->owner->setSchedule();
         $this->owner->addNewChange($comment, $this->owner->Status, $member);
         // Otherwise we go Approved -> Published
     } else {
         $this->owner->publish($comment, $member, $notify);
     }
     return _t('SiteTreeCMSWorkflow.APPROVEDANDPUBLISHMESSAGE', 'Approved request and published changes to live version. Emailed %s.');
 }
 /**
  * @param $data
  * @param $form
  * @return bool|SS_HTTPResponse|void
  * @throws ValidationException
  * @throws null
  */
 public function Save($data, $form)
 {
     /** @var Form $form */
     $data = $form->getData();
     if ($CurrentMember = Member::currentUser()) {
         if ($member = DataObject::get_one('Member', "Email = '" . Convert::raw2sql($data['Email']) . "' AND ID != " . $CurrentMember->ID)) {
             $form->addErrorMessage('Email', 'Sorry, that Email already exists.', 'validation');
             return $this->controller->redirectBack();
         } else {
             /** If no password don't save the field */
             if (!isset($data['password'])) {
                 unset($data['password']);
             }
             $this->controller->setFlash('Your profile has been updated', 'success');
             $form->saveInto($CurrentMember);
             $CurrentMember->write();
             return $this->controller->redirect($this->controller->Link());
         }
     } else {
         /** Get registration page otherwise display warning.
          *
          * @var RegistrationPage $registerPage
          */
         if ($registerPage = DataObject::get_one('RegistrationPage')) {
             return Security::PermissionFailure($this->controller, 'You must <a href="' . $registerPage->Link() . '">registered</a> and logged in to edit your profile.');
         } else {
             $this->controller->setFlash('You must registered and logged in to edit your profile.', 'warning');
             return $this->controller->redirect(Director::absoluteBaseURL());
         }
     }
 }
 /**
  * Handles form submission
  * @param array $data
  * @return bool|\SS_HTTPResponse
  */
 public function addtocart(array $data)
 {
     $groupedProduct = $this->getController()->data();
     if (empty($data) || empty($data['Product']) || !is_array($data['Product'])) {
         $this->sessionMessage(_t('GroupedCartForm.EMPTY', 'Please select at least one product.'), 'bad');
         $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
         return $response ? $response : $this->controller->redirectBack();
     }
     $cart = ShoppingCart::singleton();
     foreach ($data['Product'] as $id => $prodReq) {
         if (!empty($prodReq['Quantity']) && $prodReq['Quantity'] > 0) {
             $prod = Product::get()->byID($id);
             if ($prod && $prod->exists()) {
                 $saveabledata = !empty($this->saveablefields) ? Convert::raw2sql(array_intersect_key($data, array_combine($this->saveablefields, $this->saveablefields))) : $prodReq;
                 $buyable = $prod;
                 if (isset($prodReq['Attributes'])) {
                     $buyable = $prod->getVariationByAttributes($prodReq['Attributes']);
                     if (!$buyable || !$buyable->exists()) {
                         $this->sessionMessage("{$prod->InternalItemID} is not available with the selected options.", "bad");
                         $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
                         return $response ? $response : $this->controller->redirectBack();
                     }
                 }
                 if (!$cart->add($buyable, (int) $prodReq['Quantity'], $saveabledata)) {
                     $this->sessionMessage($cart->getMessage(), $cart->getMessageType());
                     $this->extend('updateErrorResponse', $this->request, $response, $groupedProduct, $data, $this);
                     return $response ? $response : $this->controller->redirectBack();
                 }
             }
         }
     }
     $this->extend('updateGroupCartResponse', $this->request, $response, $groupedProduct, $data, $this);
     return $response ? $response : ShoppingCart_Controller::direct($cart->getMessageType());
 }
 /**
  * Send email to subscribers, notifying them the thread has been created or post added.
  */
 public function notifySubscribers()
 {
     // all members id except current user
     $member_id = Member::currentUserID();
     $list = DataObject::get("Forum_Subscribers", "\"ForumID\" = '" . $this->owner->ForumID . "' AND \"MemberID\" != '{$member_id}'");
     if ($list) {
         foreach ($list as $obj) {
             $SQL_id = Convert::raw2sql((int) $obj->MemberID);
             // Get the members details
             $member = DataObject::get_one("Member", "\"Member\".\"ID\" = '{$SQL_id}'");
             if ($member) {
                 //error_log("email sent ".$member->Email);
                 $type = $obj->Type;
                 switch ($type) {
                     // send all email notification
                     case 'all':
                         $this->createEmail($member);
                         break;
                         // send new thread only email notification
                     // send new thread only email notification
                     case 'thread':
                         //if($this->owner->isFirstPost()){
                         $this->createEmail($member);
                         //}
                         break;
                         //
                     //
                     default:
                         break;
                 }
             }
         }
     }
 }
 /**
  * Displays a random image with colorbox effect from a given assets subfolder
  * Uses template "csoft-shortcode/templates/Includes/RandomImage.ss" for output 
  * 
  * @param mixed $arguments (folder='subfolder_in_assets' align='left|right')
  * @param $content = null
  * @param $parser = null
  * @return processed template RandomImage.ss
  */
 public static function cwsShortCodeRandomImageHandler($arguments, $content = null, $parser = null)
 {
     // only proceed if subfolder was defined
     if (!isset($arguments['folder'])) {
         return;
     }
     // sanitize user inputs
     $folder = Convert::raw2sql($arguments['folder']);
     $align = isset($arguments['align']) ? strtolower(Convert::raw2xml($arguments['align'])) : '';
     // fetch all images in random order from the user defined folder
     $folder = Folder::get()->filter('Filename', "assets/{$folder}/")->First();
     $randomImage = $folder ? Image::get()->filter('ParentID', $folder->ID)->sort('RAND()') : false;
     // exit if user defined folder does not contain any image
     if (!$randomImage) {
         return;
     }
     // extract image caption from image filename
     $caption = $randomImage->Title;
     if (preg_match('#(\\d*-)?(.+)\\.(jpg|gif|png)#i', $caption, $matches)) {
         $caption = ucfirst(str_replace('-', ' ', $matches[2]));
     }
     // prepare data for output
     $data = array('RandomImage' => $randomImage->First(), 'Alignment' => $align, 'Caption' => $caption);
     // load template and process data
     $template = new SSViewer('RandomImage');
     return $template->process(new ArrayData($data));
 }
 /**
  *	The process to automatically construct data object output configurations, executed on project build.
  */
 public function requireDefaultRecords()
 {
     parent::requireDefaultRecords();
     // Grab the list of data objects that have been completely removed.
     foreach (DB::getConn()->tableList() as $table) {
         // Delete existing output configurations for these data objects.
         if (!class_exists($table)) {
             $existing = DataObjectOutputConfiguration::get_one('DataObjectOutputConfiguration', "IsFor = '" . Convert::raw2sql($table) . "'");
             $this->deleteConfiguration($table, $existing);
         }
     }
     // Grab the list of all data object types, along with any inclusions/exclusions defined.
     $objects = ClassInfo::subclassesFor('DataObject');
     $inclusions = self::$custom_inclusions;
     $exclusions = array_unique(array_merge(self::$exclusions, self::$custom_exclusions));
     // Check existing output configurations for these data objects.
     foreach ($objects as $object) {
         $existing = DataObjectOutputConfiguration::get_one('DataObjectOutputConfiguration', "IsFor = '" . Convert::raw2sql($object) . "'");
         // Delete existing output configurations for invalid data objects, or for those excluded.
         if ($existing && (self::$disabled || get_parent_class($object) !== 'DataObject' || ClassInfo::classImplements($object, 'TestOnly') || count($inclusions) > 0 && !in_array($object, $inclusions) || count($inclusions) === 0 && in_array($object, $exclusions))) {
             $this->deleteConfiguration($object, $existing);
         } else {
             if (!$existing && !self::$disabled && get_parent_class($object) === 'DataObject' && !ClassInfo::classImplements($object, 'TestOnly') && (count($inclusions) > 0 && in_array($object, $inclusions) || count($inclusions) === 0 && !in_array($object, $exclusions))) {
                 $this->addConfiguration($object);
             }
         }
     }
 }
 function Presentations()
 {
     $Speaker = NULL;
     if (isset($_GET['key'])) {
         $key = Convert::raw2sql($_GET['key']);
         $username = SchedSpeaker::HashToUsername($key);
         $Speaker = SchedSpeaker::get()->filter('username', $username)->first();
     } elseif ($speakerID = Session::get('UploadMedia.SpeakerID')) {
         $Speaker = SchedSpeaker::get()->byID($speakerID);
     }
     // Speaker not found
     if (!$Speaker) {
         return $this->httpError(404, 'Sorry, that does not appear to be a valid token.');
     }
     Session::set('UploadMedia.SpeakerID', $Speaker->ID);
     $Presentations = $Speaker->PresentationsForThisSpeaker();
     // No presentations
     if (!$Presentations) {
         return $this->httpError(404, 'Sorry, it does not appear that you have any presentations.');
     }
     // IF there's only one presentation with no media, go ahead and forward to it's page
     if ($Presentations->count() == 1 && !$Presentations->first()->UploadedMedia()) {
         $PresentationID = $Presentations->first()->ID;
         $this->redirect($this->link() . 'Upload/' . $PresentationID);
         return;
     }
     $data["Speaker"] = $Speaker;
     $data["Presentations"] = $Presentations;
     return $this->Customise($data);
 }
 public function getCurrentFilms()
 {
     $r = new ArrayList();
     //$RestfulService = new RestfulService("http://www.odeon.co.uk/api/uk/v2/cinemas/cinema/{$this->ID}/filmswithdetails.json");
     $RestfulService = new RestfulService("http://www.odeon.co.uk/api/uk/v2/cinemas/cinema/{$this->ID}/", 259200);
     $Response = $RestfulService->request("filmswithdetails.json");
     if (!$Response->isError()) {
         $films = Convert::json2array($Response->getBody());
         foreach ($films as $film) {
             $OdeonFilm = OdeonFilm::get_by_id('OdeonFilm', (int) $film['masterId']);
             if (!$OdeonFilm) {
                 $OdeonFilm = new OdeonFilm();
                 $OdeonFilm->ID = (int) $film['masterId'];
                 $OdeonFilm->Title = Convert::raw2sql($film['title']);
                 if (isset($film['media']['imageUrl400'])) {
                     $OdeonFilm->imageUrlSmall = Convert::raw2sql($film['media']['imageUrl400']);
                 }
                 if (isset($film['casts'])) {
                     $OdeonFilm->Content = Convert::raw2sql($film['casts']);
                 }
                 $OdeonFilm->write();
             }
             $r->push($OdeonFilm);
         }
     }
     return $r->sort("Title DESC");
 }
 /**
  * Applies the filter.
  * Builds the where clause with the given IDs and boolean values in
  * $this->value
  * 
  * @param DataQuery $query Query to build where clause for
  * 
  * @return DataQuery
  * 
  * @author Sebastian Diel <*****@*****.**>
  * @since 25.06.2014
  */
 public function apply(DataQuery $query)
 {
     $result = false;
     $value = $this->getValue();
     if (is_array($value) && count($value) > 0) {
         $this->model = $query->applyRelation($this->relation);
         $values = array(0 => array(), 1 => array());
         foreach ($value as $ID => $boolean) {
             $operator = '!=';
             if ($boolean) {
                 $operator = '=';
             }
             $values[$boolean][] = sprintf("%s %s '%s'", $this->getDbName(), $operator, Convert::raw2sql($ID));
         }
         $negativeWhereClause = implode(' AND ', $values[0]);
         $positiveWhereClause = implode(' OR ', $values[1]);
         if (count($values[0]) > 0 && count($values[1]) > 0) {
             $where = sprintf('(%s) AND (%s)', $negativeWhereClause, $positiveWhereClause);
         } elseif (count($values[0]) > 0) {
             $where = $negativeWhereClause;
         } else {
             $where = $positiveWhereClause;
         }
         $result = $query->where($where);
     }
     return $result;
 }
 function run()
 {
     $batch_size = 15;
     if (isset($_GET['batch_size'])) {
         $batch_size = intval(trim(Convert::raw2sql($_GET['batch_size'])));
     }
     $surveys = DeploymentSurvey::getNotDigestSent($batch_size);
     $deployments = Deployment::getNotDigestSent($batch_size);
     if ($surveys) {
         foreach ($surveys as $survey) {
             $survey->SendDigest = 1;
             $survey->write();
         }
     }
     if ($deployments) {
         foreach ($deployments as $dep) {
             $dep->SendDigest = 1;
             $dep->write();
         }
     }
     if ((!is_null($surveys) && count($surveys)) > 0 || !is_null($deployments) && count($deployments)) {
         global $email_new_deployment;
         $email = EmailFactory::getInstance()->buildEmail($email_new_deployment, $email_new_deployment, $subject = 'New Deployments and Surveys');
         $email->setTemplate('NewDeploymentsSurveysEmail');
         $email->populateTemplate(array('SurveysUrl' => Director::absoluteURL('admin/deployments/DeploymentSurvey/EditForm/field/DeploymentSurvey/item'), 'DeploymentsUrl' => Director::absoluteURL('admin/deployments/Deployment/EditForm/field/Deployment/item'), 'SangriaDeploymentsUrl' => Director::absoluteURL('sangria/ViewDeploymentDetails'), 'Surveys' => $surveys, 'Deployments' => $deployments));
         $email->send();
     }
 }
 public function Results()
 {
     $list = Family::get()->leftJoin('House', '"Family"."ID" = "House"."FamilyID"');
     $status = Convert::raw2sql($this->request->getVar('Status'));
     $holdsRationCard = Convert::raw2sql($this->request->getVar('HoldsRationCard'));
     $cardType = Convert::raw2sql($this->request->getVar('CardType'));
     $houseType = Convert::raw2sql($this->request->getVar('Type'));
     $parishID = Convert::raw2sql($this->request->getVar('ParishID'));
     if ($parishID) {
         $list = $list->filter(array('ParishID' => $parishID));
     }
     if ($status) {
         $list = $list->filter(array('House.Status' => $status));
     }
     if ($holdsRationCard != '') {
         $list = $list->filter(array('House.HoldsRationCard' => $holdsRationCard));
     }
     if ($holdsRationCard && $cardType) {
         $list = $list->filter(array('House.CardType' => $cardType));
     }
     if ($houseType) {
         $list = $list->filter(array('House.Type' => $houseType));
     }
     //$list = $list->leftJoin('Contact', "\"Contact\".\"FamilyID\" = \"Family\".\"ID\"");
     //Debug::show($list);
     return $list;
 }
 protected function recursiveQuote($val)
 {
     if (is_array($val)) {
         $return = array();
         foreach ($val as $v) {
             $return[] = $this->recursiveQuote($v);
         }
         return '(' . implode(',', $return) . ')';
     } else {
         if (is_null($val)) {
             $val = 'NULL';
         } else {
             if (is_int($val)) {
                 $val = (int) $val;
             } else {
                 if (is_double($val)) {
                     $val = (double) $val;
                 } else {
                     if (is_float($val)) {
                         $val = (double) $val;
                     } else {
                         $val = "'" . Convert::raw2sql($val) . "'";
                     }
                 }
             }
         }
     }
     return $val;
 }
    public function getQuery($searchParams, $sort = false, $limit = false, $existingQuery = null)
    {
        $dataList = parent::getQuery($searchParams, $sort, $limit, $existingQuery);
        $params = is_object($searchParams) ? $searchParams->getVars() : $searchParams;
        $query = $dataList->dataQuery();
        if (!is_object($searchParams)) {
            if (isset($params['Locale']) && !empty($params['Locale'])) {
                $query->where('"Locale" = \'' . Convert::raw2sql($params['Locale']) . '\'');
            }
            if (isset($params['Name']) && !empty($params['Name'])) {
                $query->where('"FirstName" LIKE \'%' . Convert::raw2sql($params['Name']) . '%\' OR "Surname" LIKE \'%' . Convert::raw2sql($params['Name']) . '%\'');
            }
            if (isset($params['Status'])) {
                $query->where('EXISTS ( SELECT 1 FROM "' . $this->modelClass . '_Statuses"
					WHERE "' . $this->modelClass . 'ID" = "' . $this->modelClass . '"."ID"
					AND "' . $this->modelClass . '_Statuses"."CustomerStatusID" IN (' . implode(',', $params['Status']) . ')
				)');
            }
            if (isset($params['Tags'])) {
                $query->where('EXISTS ( SELECT 1 FROM "' . $this->modelClass . '_Tags"
					WHERE "' . $this->modelClass . 'ID" = "' . $this->modelClass . '"."ID"
					AND "' . $this->modelClass . '_Tags"."CustomerTagID" IN (' . implode(',', $params['Tags']) . ')
				)');
            }
            $this->extend('updateGetQuery', $query, $params);
        }
        return $dataList->setDataQuery($query);
    }
 public function php($data)
 {
     $member = $this->member;
     $valid = true;
     foreach ($this->unique as $field) {
         $other = DataObject::get_one('Member', sprintf('"%s" = \'%s\'', Convert::raw2sql($field), Convert::raw2sql($data[$field])));
         if ($other && (!$this->member || !$this->member->exists() || $other->ID != $this->member->ID)) {
             $fieldInstance = $this->form->Fields()->dataFieldByName($field);
             if ($fieldInstance->getCustomValidationMessage()) {
                 $message = $fieldInstance->getCustomValidationMessage();
             } else {
                 $message = sprintf(_t('MemberProfiles.MEMBERWITHSAME', 'There is already a member with the same %s.'), $field);
             }
             $valid = false;
             $this->validationError($field, $message, 'required');
         }
     }
     // Create a dummy member as this is required for custom password validators
     if (isset($data['Password']) && $data['Password'] !== "") {
         if (is_null($member)) {
             $member = Member::create();
         }
         if ($validator = $member::password_validator()) {
             $results = $validator->validate($data['Password'], $member);
             if (!$results->valid()) {
                 $valid = false;
                 foreach ($results->messageList() as $key => $value) {
                     $this->validationError('Password', $value, 'required');
                 }
             }
         }
     }
     return $valid && parent::php($data);
 }
 /**
  * Create member account from data array.
  * Data must contain unique identifier.
  *
  * @throws ValidationException
  * @param $data - map of member data
  * @return Member|boolean - new member (not saved to db), or false if there is an error.
  */
 public function create($data)
 {
     $result = new ValidationResult();
     if (!Checkout::member_creation_enabled()) {
         $result->error(_t("Checkout.MEMBERSHIPSNOTALLOWED", "Creating new memberships is not allowed"));
         throw new ValidationException($result);
     }
     $idfield = Config::inst()->get('Member', 'unique_identifier_field');
     if (!isset($data[$idfield]) || empty($data[$idfield])) {
         $result->error(sprintf(_t("Checkout.IDFIELDNOTFOUND", "Required field not found: %s"), $idfield));
         throw new ValidationException($result);
     }
     if (!isset($data['Password']) || empty($data['Password'])) {
         $result->error(_t("Checkout.PASSWORDREQUIRED", "A password is required"));
         throw new ValidationException($result);
     }
     $idval = $data[$idfield];
     if (ShopMember::get_by_identifier($idval)) {
         $result->error(sprintf(_t("Checkout.MEMBEREXISTS", "A member already exists with the %s %s"), _t("Member." . $idfield, $idfield), $idval));
         throw new ValidationException($result);
     }
     $member = new Member(Convert::raw2sql($data));
     $validation = $member->validate();
     if (!$validation->valid()) {
         //TODO need to handle i18n here?
         $result->error($validation->message());
     }
     if (!$result->valid()) {
         throw new ValidationException($result);
     }
     return $member;
 }
 public function apply(DataQuery $query)
 {
     $this->model = $query->applyRelation($this->relation);
     // hack
     // PREVIOUS $values = explode(',',$this->getValue());
     $values = array();
     if (is_string($this->getValue())) {
         $values = explode(',', $this->getValue());
     } else {
         foreach ($this->getValue() as $v) {
             $values[] = $v;
         }
     }
     if (!$values) {
         return false;
     }
     for ($i = 0; $i < count($values); $i++) {
         if (!is_numeric($values[$i])) {
             // @todo Fix string replacement to only replace leading and tailing quotes
             $values[$i] = str_replace("'", '', $values[$i]);
             $values[$i] = Convert::raw2sql($values[$i]);
         }
     }
     $SQL_valueStr = "'" . implode("','", $values) . "'";
     return $query->where(sprintf("%s IN (%s)", $this->getDbName(), $SQL_valueStr));
 }
 /**
  * Generate an list of items that will be loaded into the custom menu
  *
  * @param $menu template slug for retriving a menu
  * @return ArrayList
  */
 public function CustomMenu($menu = "")
 {
     $menu_items = new ArrayList();
     if (isset($menu)) {
         // Ensure argument is safe for database
         $menu = Convert::raw2sql($menu);
         $filter = array('Slug' => $menu);
         if ($menu = CustomMenuHolder::get()->filter($filter)->first()) {
             // If a custom order is set, use it
             if ($menu->Order) {
                 $order = explode(',', $menu->Order);
             }
             if (isset($order) && is_array($order) && count($order) > 0) {
                 foreach ($order as $item) {
                     $menu_items->push($menu->Pages()->find('ID', $item));
                 }
             } else {
                 foreach ($menu->Pages() as $item) {
                     $menu_items->push($item);
                 }
             }
         }
     }
     return $menu_items;
 }
 /**
  * @return void
  */
 public function run()
 {
     try {
         $batch_size = 100;
         $init_time = time();
         $summit = null;
         if (isset($_GET['batch_size'])) {
             $batch_size = intval(trim(Convert::raw2sql($_GET['batch_size'])));
             echo sprintf('batch_size set to %s', $batch_size) . PHP_EOL;
         }
         if (isset($_GET['summit_id'])) {
             $summit = Summit::get()->byID(intval($_GET['summit_id']));
         }
         if (is_null($summit)) {
             throw new Exception('summit_id is not valid!');
         }
         $manager = Injector::inst()->get('SpeakerSecondBreakoutAnnouncementSenderManager');
         if (!$manager instanceof ISpeakerSecondBreakoutAnnouncementSenderManager) {
             return;
         }
         $processed = $manager->send($summit, $batch_size);
         $finish_time = time() - $init_time;
         echo 'processed records ' . $processed . ' - time elapsed : ' . $finish_time . ' seconds.';
     } catch (Exception $ex) {
         SS_Log::log($ex->getMessage(), SS_Log::ERR);
     }
 }
    /**
     * @param IQuerySpecification $specification
     * @return IQueryResult
     */
    public function handle(IQuerySpecification $specification)
    {
        $params = $specification->getSpecificationParams();
        $current_date = @$params['name_pattern'];
        $date_filter = "";
        if ($current_date) {
            $current_date = Convert::raw2sql($current_date);
            $date_filter = "AND (\n                                    (\n                                        (DATE('{$current_date}') < TrainingCourseScheduleTime.EndDate)\n                                        OR\n                                        (TrainingCourse.Online=1 AND TrainingCourseScheduleTime.StartDate IS NULL AND TrainingCourseScheduleTime.EndDate IS NULL)\n                                    )\n                                )";
        }
        $sql = <<<SQL
        SELECT C.Name AS CompanyName
        FROM TrainingCourse
        INNER JOIN CompanyService ON CompanyService.ID  = TrainingCourse.TrainingServiceID AND CompanyService.ClassName='TrainingService'
        INNER JOIN Company C on C.ID = CompanyService.CompanyID
        INNER JOIN TrainingCourseSchedule ON TrainingCourseSchedule.CourseID = TrainingCourse.ID
        LEFT JOIN TrainingCourseScheduleTime ON TrainingCourseScheduleTime.LocationID = TrainingCourseSchedule.ID
        WHERE CompanyService.Active = 1
        {$date_filter}
        GROUP BY C.Name
        ORDER BY C.Name ASC;
SQL;
        $results = DB::query($sql);
        $companies = array();
        for ($i = 0; $i < $results->numRecords(); $i++) {
            $record = $results->nextRecord();
            $company = $record['CompanyName'];
            $value = sprintf('%s', $company);
            array_push($companies, new SearchDTO($value, $value));
        }
        return new OpenStackImplementationNamesQueryResult($companies);
    }
 /**
  * Displays random quote from a CSV file located in a assets subfolder
  * Uses template "cwsoft-shortcode/templates/Includes/RandomQuote.ss" for output 
  * 
  * @param $arguments (csv_file = 'subfolder_in_assets/csv_file.csv')
  * @param $content = null
  * @param $parser = null
  * @return processed template RandomQuote.ss
  */
 public static function cwsShortCodeRandomQuoteHandler($arguments, $content = null, $parser = null)
 {
     // only proceed if a CSV file was specified
     if (!isset($arguments['csv_file'])) {
         return;
     }
     $data = array();
     // check if CSV file exists in assets folder
     $csvFile = ASSETS_DIR . '/' . Convert::raw2sql($arguments['csv_file']);
     if (Director::fileExists($csvFile)) {
         $csv = new CSVParser($filename = $csvFile, $delimiter = '|', $enclosure = '"');
         // iterate through imported Quotes|Author entries and store results in array
         $citations = array();
         foreach ($csv as $row) {
             // only store entries with two data fields (quotation and author)
             if (count($row) !== 2) {
                 continue;
             }
             $citations[] = $row;
         }
         // prepare data for output (randomize array and fetch first citation for output)
         shuffle($citations);
         $data = $citations[0];
     }
     // use default citation if CSV file does not exist or is invalid
     if (!(isset($data['Quote']) && isset($data['Author']))) {
         $data['Quote'] = _t('cwsShortCodeRandomQuote.DEFAULT_QUOTE', 'Only who puts his heart and soul in it, can ignite the fire in others.');
         $data['Author'] = _t('cwsShortCodeRandomQuote.DEFAULT_AUTHOR', 'Augustinus');
     }
     // load template and process data
     $template = new SSViewer('RandomQuote');
     return $template->process(new ArrayData($data));
 }
 public function Results()
 {
     $list = Family::get();
     $blockNo = Convert::raw2sql($this->request->getVar('BlockNo'));
     $unitNo = Convert::raw2sql($this->request->getVar('UnitNo'));
     $parishID = Convert::raw2sql($this->request->getVar('ParishID'));
     $pincode = Convert::raw2sql($this->request->getVar('Pincode'));
     $isPanchayat = Convert::raw2sql($this->request->getVar('IsPanchayat'));
     $isMunicipality = Convert::raw2sql($this->request->getVar('IsMunicipality'));
     $isCorporation = Convert::raw2sql($this->request->getVar('IsCorporation'));
     if ($parishID) {
         $list = $list->filter(array('ParishID' => $parishID));
     }
     if ($blockNo) {
         $list = $list->filter(array('BlockNo' => $blockNo));
     }
     if ($unitNo) {
         $list = $list->filter(array('UnitNo' => $unitNo));
     }
     if ($pincode) {
         $list = $list->filter(array('Pincode' => $pincode));
     }
     if ($isPanchayat) {
         $list = $list->filter(array('IsPanchayat' => $isPanchayat));
     }
     if ($isMunicipality) {
         $list = $list->filter(array('IsMunicipality' => $isMunicipality));
     }
     if ($isCorporation) {
         $list = $list->filter(array('IsCorporation' => $isCorporation));
     }
     //$list = $list->leftJoin('Contact', "\"Contact\".\"FamilyID\" = \"Family\".\"ID\"");
     //Debug::show($list);
     return $list;
 }
 public function transform($item, $parentObject, $duplicateStrategy)
 {
     $pageChildren = $item->stageChildren();
     // okay, first we'll create the new page item,
     // and map a bunch of child information across
     $newFolder = new Folder();
     $parentId = $parentObject ? $parentObject->ID : 0;
     $existing = DataObject::get_one('File', '"ParentID" = \'' . Convert::raw2sql($parentId) . '\' and "Name" = \'' . Convert::raw2sql($item->Title) . '\'');
     if ($existing && $duplicateStrategy == ExternalContentTransformer::DS_SKIP) {
         // just return the existing children
         return new TransformResult($existing, $pageChildren);
     } else {
         if ($existing && $duplicateStrategy == ExternalContentTransformer::DS_OVERWRITE) {
             $newFolder = $existing;
         }
     }
     $newFolder->Name = $item->Title;
     $newFolder->Title = $item->Title;
     $newFolder->MenuTitle = $item->MenuTitle;
     // what else should we map across?
     // $newPage->MatrixId = $item->id;
     // $newPage->OriginalProperties = serialize($item->getRemoteProperties());
     $newFolder->ParentID = $parentObject->ID;
     $newFolder->Sort = 0;
     $newFolder->write();
     if (!file_exists($newFolder->getFullPath())) {
         mkdir($newFolder->getFullPath(), Filesystem::$folder_create_mask);
     }
     return new TransformResult($newFolder, $pageChildren);
 }
Beispiel #23
0
 public function perform()
 {
     set_time_limit(0);
     $log = new DeploynautLogFile($this->args['logfile']);
     $projects = DNProject::get()->filter('Name', Convert::raw2sql($this->args['projectName']));
     $project = $projects->first();
     $path = $project->getLocalCVSPath();
     $env = $this->args['env'];
     $log->write('Starting git fetch for project "' . $project->Name . '"');
     // if an alternate user has been configured for clone, run the command as that user
     // @todo Gitonomy doesn't seem to have any way to prefix the command properly, if you
     // set 'sudo -u composer git' as the "command" parameter, it tries to run the whole
     // thing as a single command and fails
     $user = DNData::inst()->getGitUser();
     if (!empty($user)) {
         $command = sprintf('cd %s && sudo -u %s git fetch -p origin +refs/heads/*:refs/heads/* --tags', $path, $user);
         $process = new \Symfony\Component\Process\Process($command);
         $process->setEnv($env);
         $process->setTimeout(3600);
         $process->run();
         if (!$process->isSuccessful()) {
             throw new RuntimeException($process->getErrorOutput());
         }
     } else {
         $repository = new Gitonomy\Git\Repository($path, array('environment_variables' => $env));
         $repository->run('fetch', array('-p', 'origin', '+refs/heads/*:refs/heads/*', '--tags'));
     }
     $log->write('Git fetch is finished');
 }
 public function getPopularInteractions($interactionType, $itemClass, $days, $number = 10)
 {
     $since = date('Y-m-d H:i:s', strtotime("-{$days} days"));
     // Execute an SQL query so we can group by and count.
     $interactions = UserInteraction::get()->filter(array('Type' => $interactionType, 'ItemClass' => $itemClass, 'Created:GreaterThan' => $since));
     $interactionType = Convert::raw2sql($interactionType);
     $itemClass = Convert::raw2sql($itemClass);
     $subs = ClassInfo::subclassesFor($itemClass);
     $subs[] = $itemClass;
     if ($i = array_search('ErrorPage', $subs)) {
         unset($subs[$i]);
     }
     $in = "'" . implode("','", $subs) . "'";
     $query = new SQLQuery('*', 'UserInteraction', "Type = '{$interactionType}' AND ItemClass IN ({$in}) AND DATEDIFF(NOW(), Created) <= {$days}", 'Views DESC, Title ASC', 'Title', '', $number);
     $query->selectField('COUNT(Title)', 'Views');
     $results = $query->execute();
     $container = ArrayList::create();
     // The array list will need to be populated with objects so the template accepts it.
     for ($i = 0; $i < $results->numRecords(); $i++) {
         $object = UserInteraction::create($results->record());
         if ($object->canView()) {
             $container->add($object);
         }
     }
     return $container;
 }
 /**
  * Form action handler for ContactInquiryForm.
  *
  * @param array $data The form request data submitted
  * @param Form $form The {@link Form} this was submitted on
  */
 function dosave(array $data, Form $form, SS_HTTPRequest $request)
 {
     $SQLData = Convert::raw2sql($data);
     $attrs = $form->getAttributes();
     if ($SQLData['Comment'] != '' || $SQLData['Url'] != '') {
         // most probably spam - terminate silently
         Director::redirect(Director::baseURL() . $this->URLSegment . "/success");
         return;
     }
     $item = new ContactInquiry();
     $form->saveInto($item);
     // $form->sessionMessage(_t("ContactPage.FORMMESSAGEGOOD", "Your inquiry has been submitted. Thanks!"), 'good');
     $item->write();
     $mailFrom = $this->currController->MailFrom ? $this->currController->MailFrom : $SQLData['Email'];
     $mailTo = $this->currController->MailTo ? $this->currController->MailTo : Email::getAdminEmail();
     $mailSubject = $this->currController->MailSubject ? $this->currController->MailSubject . ' - ' . $SQLData['Ref'] : _t('ContactPage.SUBJECT', '[web] New contact inquiry - ') . ' ' . $data['Ref'];
     $email = new Email($mailFrom, $mailTo, $mailSubject);
     $email->replyTo($SQLData['Email']);
     $email->setTemplate("ContactInquiry");
     $email->populateTemplate($SQLData);
     $email->send();
     // $this->controller->redirectBack();
     if ($email->send()) {
         $this->controller->redirect($this->controller->Link() . "success");
     } else {
         $this->controller->redirect($this->controller->Link() . "error");
     }
     return false;
 }
 public function localupdate()
 {
     if ($this->canEdit() && ($imageDataString = $this->request->requestVar('imageData')) && ($imageID = $this->request->requestVar('imageID')) && ($image = Image::get()->byID(Convert::raw2sql($imageID)))) {
         //$imageDataString = file_get_contents($newFile);
         $imageData = base64_decode(preg_replace('#^data:image/\\w+;base64,#i', '', $imageDataString));
         $path = $image->getFullPath();
         // if we have a new file + old path, overwrite old image wiith new image.
         if ($imageData && $path) {
             // Do we need to validate it the filetype is still the same as the original?
             //$f = finfo_open();
             //$mime_type = finfo_buffer($f, $imageData, FILEINFO_MIME_TYPE);
             //finfo_close($f);
             file_put_contents($path, $imageData);
             $image->forceChange();
             $image->deleteFormattedImages();
             $image->write();
             // return new thumbnail
             $formattedImage = $image->getFormattedImage('SetWidth', Config::inst()->get('Image', 'asset_preview_width'));
             $thumbnail = $formattedImage ? $formattedImage->URL : '';
             if ($this->request->isAjax()) {
                 $this->request->addHeader('Content-type', 'application/json');
                 return json_encode(['thumbnail' => $thumbnail]);
             }
             return $thumbnail;
         }
     }
 }
 /**
  * Get the full form (e.g. /home/) relative link to the home page for the current HTTP_HOST value. Note that the
  * link is trimmed of leading and trailing slashes before returning to ensure consistency.
  *
  * @return string
  */
 public static function get_homepage_link()
 {
     if (!self::$cached_homepage_link) {
         // TODO Move to 'homepagefordomain' module
         if (class_exists('HomepageForDomainExtension')) {
             $host = str_replace('www.', null, $_SERVER['HTTP_HOST']);
             $SQL_host = Convert::raw2sql($host);
             $candidates = DataObject::get('SiteTree', "\"HomepageForDomain\" LIKE '%{$SQL_host}%'");
             if ($candidates) {
                 foreach ($candidates as $candidate) {
                     if (preg_match('/(,|^) *' . preg_quote($host) . ' *(,|$)/', $candidate->HomepageForDomain)) {
                         self::$cached_homepage_link = trim($candidate->RelativeLink(true), '/');
                     }
                 }
             }
         }
         if (!self::$cached_homepage_link) {
             // TODO Move to 'translatable' module
             if (class_exists('Translatable') && Object::has_extension('SiteTree', 'Translatable') && ($link = Translatable::get_homepage_link_by_locale(Translatable::get_current_locale()))) {
                 self::$cached_homepage_link = $link;
             } else {
                 self::$cached_homepage_link = self::get_default_homepage_link();
             }
         }
     }
     return self::$cached_homepage_link;
 }
 /**
  * @param $data
  * @param $form
  * @return bool|SS_HTTPResponse
  */
 function Register($data, $form)
 {
     // Set session array individually as setting the password breaks the form.
     $sessionArray = array('Email' => $data['Email']);
     // Check for existing member email address
     if ($existingUser = DataObject::get_one('Member', "Email = '" . Convert::raw2sql($data['Email']) . "'")) {
         $form->AddErrorMessage('Email', _t('RegistrationPage.EmailValidationText', 'Sorry, that email address already exists. Please choose another.'), 'validation');
         Session::set('FormInfo.Form_RegistrationForm.data', $sessionArray);
         return $this->redirectBack();
     }
     // Otherwise create new member and log them in
     $Member = new Member();
     $form->saveInto($Member);
     $Member->write();
     $Member->login();
     // Find or create the 'user' group
     if (!($userGroup = DataObject::get_one('Group', "Code = 'users'"))) {
         $userGroup = new Group();
         $userGroup->Code = 'users';
         $userGroup->Title = 'Users';
         $userGroup->Write();
         $userGroup->Members()->add($Member);
     }
     // Add member to user group
     $userGroup->Members()->add($Member);
     // Get profile page otherwise display warning.
     if ($ProfilePage = DataObject::get_one('EditProfilePage')) {
         $name = $data['FirstName'] ?: ($name = $data['Email']);
         $this->setFlash(_t('RegistrationPage.RegisteredSuccessText', 'Welcome ' . $name . ', your account has been created!'), 'success');
         return $this->redirect($ProfilePage->Link());
     } else {
         $this->setFlash(_t('RegistrationPage.RegisteredWarningText', 'Please add a "Edit Profile Page" in your SiteTree to enable profile editing'), 'warning');
         return $this->redirect(Director::absoluteBaseURL());
     }
 }
	function __construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter = "", $sourceSort = "", $sourceJoin = "") {
		parent::__construct($controller, $name, $sourceClass, $fieldList, $detailFormFields, $sourceFilter, $sourceSort, $sourceJoin);
		
		$SNG_file = singleton('File');
		
		// If search was request, filter the results here
		$SQL_search = (!empty($_REQUEST['FileSearch'])) ? Convert::raw2sql($_REQUEST['FileSearch']) : null;
		if($SQL_search) {
			$searchFilters = array();
			foreach($SNG_file->searchableFields() as $fieldName => $fieldSpec) {
				if(strpos($fieldName, '.') === false) $searchFilters[] = "\"$fieldName\" LIKE '%{$SQL_search}%'";
			}
			$this->sourceFilter = '(' . implode(' OR ', $searchFilters) . ')';
			$this->searchingFor = $_REQUEST['FileSearch'];
			
			// @todo Integrate search form more closely and don't rely on deprecated
			//  $extraLinkParams.
			$this->extraLinkParams = array(
				'FileSearch' => $SQL_search
			);
		}
		
		$this->sourceSort = 'Title';
		$this->Markable = true;
	}
 /**
  * @param string $keywords
  * @param array $filters [optional]
  * @param array $facetSpec [optional]
  * @param int $start [optional]
  * @param int $limit [optional]
  * @param string $sort [optional]
  * @return ArrayData
  */
 function searchFromVars($keywords, array $filters = array(), array $facetSpec = array(), $start = -1, $limit = -1, $sort = '')
 {
     $searchable = ShopSearch::get_searchable_classes();
     $matches = new ArrayList();
     foreach ($searchable as $className) {
         $list = DataObject::get($className);
         // get searchable fields
         $keywordFields = $this->getSearchFields($className);
         // build the filter
         $filter = array();
         // Use parametrized query if SilverStripe >= 3.2
         if (SHOP_SEARCH_IS_SS32) {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = array("MATCH ({$indexFields}) AGAINST (?)" => $keywords);
             }
             $list = $list->whereAny($filter);
         } else {
             foreach ($keywordFields as $indexFields) {
                 $filter[] = sprintf("MATCH ({$indexFields}) AGAINST ('%s')", Convert::raw2sql($keywords));
             }
             // join all the filters with an "OR" statement
             $list = $list->where(implode(' OR ', $filter));
         }
         // add in any other filters
         $list = FacetHelper::inst()->addFiltersToDataList($list, $filters);
         // add any matches to the big list
         $matches->merge($list);
     }
     return new ArrayData(array('Matches' => $matches, 'Facets' => FacetHelper::inst()->buildFacets($matches, $facetSpec, (bool) Config::inst()->get('ShopSearch', 'auto_facet_attributes'))));
 }