From bc7c99007bcc14d4ba00e6b2b5fd4f7b30916038 Mon Sep 17 00:00:00 2001 From: finley Date: Tue, 29 Jul 2025 21:16:01 -0700 Subject: [PATCH 01/17] Accounting for multiple containers on the one machine --- vault_cron.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vault_cron.sh b/vault_cron.sh index 015996b7..928795da 100755 --- a/vault_cron.sh +++ b/vault_cron.sh @@ -2,5 +2,5 @@ ## run by cmc user cron to run the vault inside docker -ID=$(docker ps -q) +ID=$(docker ps -f ancestor=cmc:latest --format "{{.ID}}" | head -n 1) docker exec -t $ID /var/www/cmc-sales/run_vault.sh From f6eef99d47a37aa03e39db565ecadf473fac877d Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Wed, 30 Jul 2025 19:54:10 +1000 Subject: [PATCH 02/17] Add go rewrite of vault --- go-app/Makefile | 13 + go-app/cmd/vault/README.md | 57 ++++ go-app/cmd/vault/main.go | 624 +++++++++++++++++++++++++++++++++++++ go-app/go.mod | 15 + go-app/go.sum | 26 ++ 5 files changed, 735 insertions(+) create mode 100644 go-app/cmd/vault/README.md create mode 100644 go-app/cmd/vault/main.go diff --git a/go-app/Makefile b/go-app/Makefile index 24df33e5..37e17ecd 100644 --- a/go-app/Makefile +++ b/go-app/Makefile @@ -19,11 +19,24 @@ sqlc: ## Generate Go code from SQL queries .PHONY: build build: sqlc ## Build the application go build -o bin/server cmd/server/main.go + go build -o bin/vault cmd/vault/main.go + +.PHONY: build-server +build-server: sqlc ## Build only the server + go build -o bin/server cmd/server/main.go + +.PHONY: build-vault +build-vault: ## Build only the vault command + go build -o bin/vault cmd/vault/main.go .PHONY: run run: ## Run the application go run cmd/server/main.go +.PHONY: run-vault +run-vault: ## Run the vault command + go run cmd/vault/main.go + .PHONY: dev dev: sqlc ## Run the application with hot reload (requires air) air diff --git a/go-app/cmd/vault/README.md b/go-app/cmd/vault/README.md new file mode 100644 index 00000000..908312c5 --- /dev/null +++ b/go-app/cmd/vault/README.md @@ -0,0 +1,57 @@ +# Vault Email Processor + +This is a Go rewrite of the PHP vault.php script that processes emails for the CMC Sales system. + +## Key Changes from PHP Version + +1. **No ripmime dependency**: Uses the enmime Go library for MIME parsing instead of external ripmime binary +2. **Better error handling**: Proper error handling and database transactions +3. **Type safety**: Strongly typed Go structures +4. **Modern email parsing**: Uses enmime for robust email parsing + +## Features + +- Processes emails from vault directory +- Parses email headers and extracts recipients +- Identifies and creates users as needed +- Extracts attachments and email body parts +- Matches document identifiers in subjects (enquiries, invoices, POs, jobs) +- Saves emails with all associations to database +- Moves processed emails to processed directory + +## Usage + +```bash +go run cmd/vault/main.go \ + --emaildir=/var/www/emails \ + --vaultdir=/var/www/vaultmsgs/new \ + --processeddir=/var/www/vaultmsgs/cur \ + --dbhost=127.0.0.1 \ + --dbuser=cmc \ + --dbpass="xVRQI&cA?7AU=hqJ!%au" \ + --dbname=cmc +``` + +## Build + +```bash +go build -o vault cmd/vault/main.go +``` + +## Dependencies + +- github.com/jhillyerd/enmime - MIME email parsing +- github.com/google/uuid - UUID generation for unique filenames +- github.com/go-sql-driver/mysql - MySQL driver + +## Database Tables Used + +- emails - Main email records +- email_recipients - To/CC recipients +- email_attachments - File attachments +- emails_enquiries - Email to enquiry associations +- emails_invoices - Email to invoice associations +- emails_purchase_orders - Email to PO associations +- emails_jobs - Email to job associations +- users - System users +- enquiries, invoices, purchase_orders, jobs - For identifier matching \ No newline at end of file diff --git a/go-app/cmd/vault/main.go b/go-app/cmd/vault/main.go new file mode 100644 index 00000000..45d1cfa9 --- /dev/null +++ b/go-app/cmd/vault/main.go @@ -0,0 +1,624 @@ +package main + +import ( + "bytes" + "database/sql" + "flag" + "fmt" + "io/ioutil" + "log" + "os" + "path/filepath" + "regexp" + "strings" + "time" + + _ "github.com/go-sql-driver/mysql" + "github.com/google/uuid" + "github.com/jhillyerd/enmime" +) + +type Config struct { + EmailDir string + VaultDir string + ProcessedDir string + DBHost string + DBUser string + DBPassword string + DBName string +} + +type EmailProcessor struct { + db *sql.DB + config Config + enquiryMap map[string]int + invoiceMap map[string]int + poMap map[string]int + userMap map[string]int + jobMap map[string]int +} + +type Attachment struct { + Type string + Name string + Filename string + Size int64 + IsMessageBody int +} + +func main() { + var config Config + flag.StringVar(&config.EmailDir, "emaildir", "/var/www/emails", "Email storage directory") + flag.StringVar(&config.VaultDir, "vaultdir", "/var/www/vaultmsgs/new", "Vault messages directory") + flag.StringVar(&config.ProcessedDir, "processeddir", "/var/www/vaultmsgs/cur", "Processed messages directory") + flag.StringVar(&config.DBHost, "dbhost", "127.0.0.1", "Database host") + flag.StringVar(&config.DBUser, "dbuser", "cmc", "Database user") + flag.StringVar(&config.DBPassword, "dbpass", "xVRQI&cA?7AU=hqJ!%au", "Database password") + flag.StringVar(&config.DBName, "dbname", "cmc", "Database name") + flag.Parse() + + dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true", + config.DBUser, config.DBPassword, config.DBHost, config.DBName) + + db, err := sql.Open("mysql", dsn) + if err != nil { + log.Fatal("Failed to connect to database:", err) + } + defer db.Close() + + processor := &EmailProcessor{ + db: db, + config: config, + } + + if err := processor.loadMaps(); err != nil { + log.Fatal("Failed to load maps:", err) + } + + if err := processor.processEmails(); err != nil { + log.Fatal("Failed to process emails:", err) + } +} + +func (p *EmailProcessor) loadMaps() error { + p.enquiryMap = make(map[string]int) + p.invoiceMap = make(map[string]int) + p.poMap = make(map[string]int) + p.userMap = make(map[string]int) + p.jobMap = make(map[string]int) + + // Load enquiries + rows, err := p.db.Query("SELECT id, title FROM enquiries") + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var id int + var title string + if err := rows.Scan(&id, &title); err != nil { + return err + } + p.enquiryMap[title] = id + } + + // Load invoices + rows, err = p.db.Query("SELECT id, title FROM invoices") + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var id int + var title string + if err := rows.Scan(&id, &title); err != nil { + return err + } + p.invoiceMap[title] = id + } + + // Load purchase orders + rows, err = p.db.Query("SELECT id, title FROM purchase_orders") + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var id int + var title string + if err := rows.Scan(&id, &title); err != nil { + return err + } + p.poMap[title] = id + } + + // Load users + rows, err = p.db.Query("SELECT id, email FROM users") + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var id int + var email string + if err := rows.Scan(&id, &email); err != nil { + return err + } + p.userMap[strings.ToLower(email)] = id + } + + // Load jobs + rows, err = p.db.Query("SELECT id, title FROM jobs") + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var id int + var title string + if err := rows.Scan(&id, &title); err != nil { + return err + } + p.jobMap[title] = id + } + + return nil +} + +func (p *EmailProcessor) processEmails() error { + files, err := ioutil.ReadDir(p.config.VaultDir) + if err != nil { + return err + } + + for _, file := range files { + if file.IsDir() || file.Name() == "." || file.Name() == ".." { + continue + } + + fmt.Printf("Handling %s\n", file.Name()) + if err := p.processEmail(file.Name()); err != nil { + log.Printf("Error processing %s: %v\n", file.Name(), err) + } + } + + return nil +} + +func (p *EmailProcessor) processEmail(filename string) error { + emailPath := filepath.Join(p.config.VaultDir, filename) + content, err := ioutil.ReadFile(emailPath) + if err != nil { + return err + } + + if len(content) == 0 { + fmt.Println("No content found. Ignoring this email") + return p.moveEmail(filename) + } + + // Parse email with enmime + env, err := enmime.ReadEnvelope(bytes.NewReader(content)) + if err != nil { + return err + } + + // Get recipients + toRecipients := p.parseEnmimeAddresses(env.GetHeader("To")) + fromRecipients := p.parseEnmimeAddresses(env.GetHeader("From")) + ccRecipients := p.parseEnmimeAddresses(env.GetHeader("Cc")) + + // Check if we should save this email + saveThis := false + fromKnownUser := false + + for _, email := range toRecipients { + if p.userExists(email) { + saveThis = true + } + } + + for _, email := range fromRecipients { + if p.userExists(email) { + saveThis = true + fromKnownUser = true + } + } + + for _, email := range ccRecipients { + if p.userExists(email) { + saveThis = true + } + } + + subject := env.GetHeader("Subject") + if subject == "" { + fmt.Println("No subject found. Ignoring this email") + return p.moveEmail(filename) + } + + // Check for identifiers in subject + foundEnquiries := p.checkIdentifier(subject, p.enquiryMap, "enquiry") + foundInvoices := p.checkIdentifier(subject, p.invoiceMap, "invoice") + foundPOs := p.checkIdentifier(subject, p.poMap, "purchaseorder") + foundJobs := p.checkIdentifier(subject, p.jobMap, "job") + + foundIdent := len(foundEnquiries) > 0 || len(foundInvoices) > 0 || + len(foundPOs) > 0 || len(foundJobs) > 0 + + if fromKnownUser || saveThis || foundIdent { + // Process and save the email + unixTime := time.Now().Unix() + if date, err := env.Date(); err == nil { + unixTime = date.Unix() + } + + // Get recipient user IDs + recipientIDs := make(map[string][]int) + recipientIDs["to"] = p.getUserIDs(toRecipients) + recipientIDs["from"] = p.getUserIDs(fromRecipients) + recipientIDs["cc"] = p.getUserIDs(ccRecipients) + + if len(recipientIDs["from"]) == 0 { + fmt.Println("Email has no From Recipient ID. Ignoring this email") + return p.moveEmail(filename) + } + + fmt.Println("---------START MESSAGE -----------------") + fmt.Printf("Subject: %s\n", subject) + + // Extract attachments using enmime + relativePath := p.getAttachmentDirectory(unixTime) + attachments := p.extractEnmimeAttachments(env, relativePath) + + // Save email to database + if err := p.saveEmail(filename, subject, unixTime, recipientIDs, attachments, + foundEnquiries, foundInvoices, foundPOs, foundJobs); err != nil { + return err + } + + fmt.Println("--------END MESSAGE ------") + } else { + fmt.Printf("Email will not be saved. Subject: %s\n", subject) + } + + return p.moveEmail(filename) +} + +func (p *EmailProcessor) parseEnmimeAddresses(header string) []string { + var emails []string + if header == "" { + return emails + } + + addresses, err := enmime.ParseAddressList(header) + if err != nil { + return emails + } + + for _, addr := range addresses { + emails = append(emails, strings.ToLower(addr.Address)) + } + + return emails +} + +func (p *EmailProcessor) userExists(email string) bool { + _, exists := p.userMap[strings.ToLower(email)] + return exists +} + +func (p *EmailProcessor) getUserIDs(emails []string) []int { + var ids []int + for _, email := range emails { + if id, exists := p.userMap[strings.ToLower(email)]; exists { + ids = append(ids, id) + } else { + // Create new user + newID := p.createUser(email) + if newID > 0 { + ids = append(ids, newID) + p.userMap[strings.ToLower(email)] = newID + } + } + } + return ids +} + +func (p *EmailProcessor) createUser(email string) int { + fmt.Printf("Making a new User for: '%s'\n", email) + + result, err := p.db.Exec( + "INSERT INTO users (type, email, by_vault, created, modified) VALUES (?, ?, ?, NOW(), NOW())", + "contact", strings.ToLower(email), 1) + + if err != nil { + fmt.Printf("Serious Error: Unable to create user for email '%s': %v\n", email, err) + return 0 + } + + id, err := result.LastInsertId() + if err != nil { + return 0 + } + + fmt.Printf("New User '%s' Added with ID: %d\n", email, id) + return int(id) +} + +func (p *EmailProcessor) checkIdentifier(subject string, identMap map[string]int, identType string) []int { + var results []int + var re *regexp.Regexp + + switch identType { + case "enquiry": + re = regexp.MustCompile(`CMC\d+([NVQWSOT]|ACT|NT)E\d+-\d+`) + case "invoice": + re = regexp.MustCompile(`CMCIN\d+`) + case "purchaseorder": + re = regexp.MustCompile(`CMCPO\d+`) + case "job": + re = regexp.MustCompile(`(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d+(N|V|W|S|T|NT|ACT|Q|O)J\d+`) + } + + if re != nil { + matches := re.FindAllString(subject, -1) + for _, match := range matches { + if id, exists := identMap[match]; exists { + results = append(results, id) + } + } + } + + return results +} + +func (p *EmailProcessor) getAttachmentDirectory(unixTime int64) string { + t := time.Unix(unixTime, 0) + monthYear := t.Format("01-2006") + path := filepath.Join(p.config.EmailDir, monthYear) + + if err := os.MkdirAll(path, 0755); err != nil { + log.Printf("Failed to create directory %s: %v", path, err) + } + + return monthYear +} + +func (p *EmailProcessor) extractEnmimeAttachments(env *enmime.Envelope, relativePath string) []Attachment { + var attachments []Attachment + outputDir := filepath.Join(p.config.EmailDir, relativePath) + uuid := uuid.New().String() + + // Ensure output directory exists + if err := os.MkdirAll(outputDir, 0755); err != nil { + log.Printf("Failed to create output directory: %v", err) + return attachments + } + + biggestHTMLSize := int64(0) + biggestHTMLIdx := -1 + biggestPlainSize := int64(0) + biggestPlainIdx := -1 + + // Process HTML part if exists + if env.HTML != "" { + htmlData := []byte(env.HTML) + fileName := "texthtml" + newFileName := uuid + "-" + fileName + filePath := filepath.Join(outputDir, newFileName) + + if err := ioutil.WriteFile(filePath, htmlData, 0644); err == nil { + att := Attachment{ + Type: "text/html", + Name: filepath.Join(relativePath, newFileName), + Filename: fileName, + Size: int64(len(htmlData)), + IsMessageBody: 0, + } + attachments = append(attachments, att) + biggestHTMLIdx = len(attachments) - 1 + biggestHTMLSize = int64(len(htmlData)) + } + } + + // Process plain text part if exists + if env.Text != "" { + textData := []byte(env.Text) + fileName := "textplain" + newFileName := uuid + "-" + fileName + filePath := filepath.Join(outputDir, newFileName) + + if err := ioutil.WriteFile(filePath, textData, 0644); err == nil { + att := Attachment{ + Type: "text/plain", + Name: filepath.Join(relativePath, newFileName), + Filename: fileName, + Size: int64(len(textData)), + IsMessageBody: 0, + } + attachments = append(attachments, att) + biggestPlainIdx = len(attachments) - 1 + biggestPlainSize = int64(len(textData)) + } + } + + // Process file attachments + for _, part := range env.Attachments { + fileName := part.FileName + if fileName == "" { + fileName = "attachment" + } + + newFileName := uuid + "-" + fileName + filePath := filepath.Join(outputDir, newFileName) + + if err := ioutil.WriteFile(filePath, part.Content, 0644); err != nil { + log.Printf("Failed to save attachment %s: %v", fileName, err) + continue + } + + att := Attachment{ + Type: part.ContentType, + Name: filepath.Join(relativePath, newFileName), + Filename: fileName, + Size: int64(len(part.Content)), + IsMessageBody: 0, + } + + attachments = append(attachments, att) + idx := len(attachments) - 1 + + // Track largest HTML and plain text attachments + if strings.HasPrefix(part.ContentType, "text/html") && int64(len(part.Content)) > biggestHTMLSize { + biggestHTMLSize = int64(len(part.Content)) + biggestHTMLIdx = idx + } else if strings.HasPrefix(part.ContentType, "text/plain") && int64(len(part.Content)) > biggestPlainSize { + biggestPlainSize = int64(len(part.Content)) + biggestPlainIdx = idx + } + } + + // Process inline parts + for _, part := range env.Inlines { + fileName := part.FileName + if fileName == "" { + fileName = "inline" + } + + newFileName := uuid + "-" + fileName + filePath := filepath.Join(outputDir, newFileName) + + if err := ioutil.WriteFile(filePath, part.Content, 0644); err != nil { + log.Printf("Failed to save inline part %s: %v", fileName, err) + continue + } + + att := Attachment{ + Type: part.ContentType, + Name: filepath.Join(relativePath, newFileName), + Filename: fileName, + Size: int64(len(part.Content)), + IsMessageBody: 0, + } + + attachments = append(attachments, att) + idx := len(attachments) - 1 + + // Track largest HTML and plain text attachments + if strings.HasPrefix(part.ContentType, "text/html") && int64(len(part.Content)) > biggestHTMLSize { + biggestHTMLSize = int64(len(part.Content)) + biggestHTMLIdx = idx + } else if strings.HasPrefix(part.ContentType, "text/plain") && int64(len(part.Content)) > biggestPlainSize { + biggestPlainSize = int64(len(part.Content)) + biggestPlainIdx = idx + } + } + + // Mark the message body + if biggestHTMLIdx >= 0 { + attachments[biggestHTMLIdx].IsMessageBody = 1 + } else if biggestPlainIdx >= 0 { + attachments[biggestPlainIdx].IsMessageBody = 1 + } + + return attachments +} + +func (p *EmailProcessor) saveEmail(filename, subject string, unixTime int64, + recipientIDs map[string][]int, attachments []Attachment, + foundEnquiries, foundInvoices, foundPOs, foundJobs []int) error { + + tx, err := p.db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + // Insert email + result, err := tx.Exec( + "INSERT INTO emails (user_id, udate, created, subject, filename) VALUES (?, ?, NOW(), ?, ?)", + recipientIDs["from"][0], unixTime, subject, filename) + + if err != nil { + return err + } + + emailID, err := result.LastInsertId() + if err != nil { + return err + } + + // Insert recipients + for recipType, userIDs := range recipientIDs { + for _, userID := range userIDs { + if recipType == "from" { + continue // From is already stored in emails.user_id + } + _, err = tx.Exec( + "INSERT INTO email_recipients (email_id, user_id, type) VALUES (?, ?, ?)", + emailID, userID, recipType) + if err != nil { + return err + } + } + } + + // Insert attachments + for _, att := range attachments { + _, err = tx.Exec( + "INSERT INTO email_attachments (email_id, name, type, size, filename, is_message_body, created) VALUES (?, ?, ?, ?, ?, ?, NOW())", + emailID, att.Name, att.Type, att.Size, att.Filename, att.IsMessageBody) + if err != nil { + return err + } + } + + // Insert associations + for _, jobID := range foundJobs { + _, err = tx.Exec("INSERT INTO emails_jobs (email_id, job_id) VALUES (?, ?)", emailID, jobID) + if err != nil { + return err + } + } + + for _, poID := range foundPOs { + _, err = tx.Exec("INSERT INTO emails_purchase_orders (email_id, purchase_order_id) VALUES (?, ?)", emailID, poID) + if err != nil { + return err + } + } + + for _, enqID := range foundEnquiries { + _, err = tx.Exec("INSERT INTO emails_enquiries (email_id, enquiry_id) VALUES (?, ?)", emailID, enqID) + if err != nil { + return err + } + } + + for _, invID := range foundInvoices { + _, err = tx.Exec("INSERT INTO emails_invoices (email_id, invoice_id) VALUES (?, ?)", emailID, invID) + if err != nil { + return err + } + } + + if err := tx.Commit(); err != nil { + return err + } + + fmt.Println("Success. We made an email") + return nil +} + +func (p *EmailProcessor) moveEmail(filename string) error { + oldPath := filepath.Join(p.config.VaultDir, filename) + newPath := filepath.Join(p.config.ProcessedDir, filename+":S") + + if err := os.Rename(oldPath, newPath); err != nil { + fmt.Printf("Unable to move %s to %s: %v\n", oldPath, newPath, err) + return err + } + + return nil +} \ No newline at end of file diff --git a/go-app/go.mod b/go-app/go.mod index 3dbae654..982ff1aa 100644 --- a/go-app/go.mod +++ b/go-app/go.mod @@ -4,7 +4,22 @@ go 1.23 require ( github.com/go-sql-driver/mysql v1.7.1 + github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 + github.com/jhillyerd/enmime v1.3.0 github.com/joho/godotenv v1.5.1 github.com/jung-kurt/gofpdf v1.16.2 ) + +require ( + github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a // indirect + github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f // indirect + github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/rivo/uniseg v0.4.4 // indirect + github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect + golang.org/x/net v0.23.0 // indirect + golang.org/x/text v0.14.0 // indirect +) diff --git a/go-app/go.sum b/go-app/go.sum index 401bc738..a7a25f89 100644 --- a/go-app/go.sum +++ b/go-app/go.sum @@ -1,18 +1,44 @@ github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a h1:MISbI8sU/PSK/ztvmWKFcI7UGb5/HQT7B+i3a2myKgI= +github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a/go.mod h1:2GxOXOlEPAMFPfp014mK1SWq8G8BN8o7/dfYqJrVGn8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f h1:3BSP1Tbs2djlpprl7wCLuiqMaUh5SJkkzI2gDs+FgLs= +github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= +github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056 h1:iCHtR9CQyktQ5+f3dMVZfwD2KWJUgm7M0gdL9NGr8KA= +github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056/go.mod h1:CVKlgaMiht+LXvHG173ujK6JUhZXKb2u/BQtjPDIvyk= +github.com/jhillyerd/enmime v1.3.0 h1:LV5kzfLidiOr8qRGIpYYmUZCnhrPbcFAnAFUnWn99rw= +github.com/jhillyerd/enmime v1.3.0/go.mod h1:6c6jg5HdRRV2FtvVL69LjiX1M8oE0xDX9VEhV3oy4gs= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/jung-kurt/gofpdf v1.0.0/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= github.com/jung-kurt/gofpdf v1.16.2 h1:jgbatWHfRlPYiK85qgevsZTHviWXKwB1TTiKdz5PtRc= github.com/jung-kurt/gofpdf v1.16.2/go.mod h1:1hl7y57EsiPAkLbOwzpzqgx1A30nQCk/YmFV8S2vmK0= +github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/phpdave11/gofpdi v1.0.7/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= +github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= +github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= +github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= +golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= From 687739e9d688a16bea40e28a16125899ed07064c Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Tue, 5 Aug 2025 07:50:12 +1000 Subject: [PATCH 03/17] Work on staging and vault --- DEPLOYMENT.md | 356 +++++++ Dockerfile.go | 7 + Dockerfile.go.production | 63 ++ Dockerfile.go.staging | 57 ++ TESTING_DOCKER.md | 394 ++++++++ conf/nginx-production.conf | 152 +++ conf/nginx-proxy.conf | 137 +++ conf/nginx-staging.conf | 89 ++ docker-compose.production.yml | 110 +++ docker-compose.proxy.yml | 68 ++ docker-compose.staging.yml | 86 ++ go-app/.gitignore | 9 +- go-app/MIGRATIONS.md | 70 ++ go-app/Makefile | 45 + go-app/cmd/server/main.go | 17 +- go-app/cmd/vault/README.md | 127 ++- go-app/cmd/vault/main.go | 754 ++++++++++++++- go-app/go.mod | 29 +- go-app/go.sum | 74 +- go-app/goose.env.example | 3 + go-app/internal/cmc/handlers/emails.go | 870 ++++++++++++++++++ go-app/internal/cmc/handlers/pages.go | 407 +++++++- go-app/internal/cmc/templates/templates.go | 4 + .../sql/migrations/001_add_gmail_fields.sql | 52 ++ go-app/static/css/style.css | 16 + go-app/templates/emails/attachments.html | 67 ++ go-app/templates/emails/index.html | 82 ++ go-app/templates/emails/show.html | 293 ++++++ go-app/templates/emails/table.html | 143 +++ go-app/templates/layouts/base.html | 5 + 30 files changed, 4515 insertions(+), 71 deletions(-) create mode 100644 DEPLOYMENT.md create mode 100644 Dockerfile.go.production create mode 100644 Dockerfile.go.staging create mode 100644 TESTING_DOCKER.md create mode 100644 conf/nginx-production.conf create mode 100644 conf/nginx-proxy.conf create mode 100644 conf/nginx-staging.conf create mode 100644 docker-compose.production.yml create mode 100644 docker-compose.proxy.yml create mode 100644 docker-compose.staging.yml create mode 100644 go-app/MIGRATIONS.md create mode 100644 go-app/goose.env.example create mode 100644 go-app/internal/cmc/handlers/emails.go create mode 100644 go-app/sql/migrations/001_add_gmail_fields.sql create mode 100644 go-app/templates/emails/attachments.html create mode 100644 go-app/templates/emails/index.html create mode 100644 go-app/templates/emails/show.html create mode 100644 go-app/templates/emails/table.html diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 00000000..1b73be5b --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,356 @@ +# CMC Sales Deployment Guide + +## Overview + +This guide covers deploying the CMC Sales application to a Debian 12 VM at `cmc.springupsoftware.com` with both staging and production environments. + +## Architecture + +- **Production**: `https://cmc.springupsoftware.com` +- **Staging**: `https://staging.cmc.springupsoftware.com` +- **Components**: CakePHP legacy app, Go modern app, MariaDB, Nginx reverse proxy +- **SSL**: Let's Encrypt certificates +- **Authentication**: Basic auth for both environments + +## Prerequisites + +### Server Setup (Debian 12) + +```bash +# Update system +sudo apt update && sudo apt upgrade -y + +# Install Docker and Docker Compose +sudo apt install -y docker.io docker-compose-plugin +sudo systemctl enable docker +sudo systemctl start docker + +# Add user to docker group +sudo usermod -aG docker $USER +# Log out and back in + +# Create backup directory +sudo mkdir -p /var/backups/cmc-sales +sudo chown $USER:$USER /var/backups/cmc-sales +``` + +### DNS Configuration + +Ensure these DNS records point to your server: +- `cmc.springupsoftware.com` → Server IP +- `staging.cmc.springupsoftware.com` → Server IP + +## Initial Deployment + +### 1. Clone Repository + +```bash +cd /opt +sudo git clone cmc-sales +sudo chown -R $USER:$USER cmc-sales +cd cmc-sales +``` + +### 2. Environment Configuration + +```bash +# Copy environment files +cp .env.staging go-app/.env.staging +cp .env.production go-app/.env.production + +# Edit with actual passwords +nano .env.staging +nano .env.production + +# Create credential directories +mkdir -p credentials/staging credentials/production +``` + +### 3. Gmail OAuth Setup + +For each environment (staging/production): + +1. Go to [Google Cloud Console](https://console.cloud.google.com) +2. Create/select project +3. Enable Gmail API +4. Create OAuth 2.0 credentials +5. Download `credentials.json` +6. Place in appropriate directory: + - Staging: `credentials/staging/credentials.json` + - Production: `credentials/production/credentials.json` + +Generate tokens (run on local machine first): +```bash +cd go-app +go run cmd/auth/main.go +# Follow OAuth flow +# Copy token.json to appropriate credential directory +``` + +### 4. SSL Certificates + +```bash +# Start proxy services (includes Lego container) +docker compose -f docker-compose.proxy.yml up -d + +# Setup SSL certificates using Lego +./scripts/setup-lego-certs.sh admin@springupsoftware.com + +# Verify certificates +./scripts/lego-list-certs.sh +``` + +### 5. Database Initialization + +```bash +# Start database containers first +docker compose -f docker-compose.staging.yml up -d db-staging +docker compose -f docker-compose.production.yml up -d db-production + +# Wait for databases to be ready +sleep 30 + +# Restore production database (if you have a backup) +./scripts/restore-db.sh production /path/to/backup.sql.gz + +# Or initialize empty database and run migrations +# (implementation specific) +``` + +## Deployment Commands + +### Starting Services + +```bash +# Start staging environment +docker compose -f docker-compose.staging.yml up -d + +# Start production environment +docker compose -f docker-compose.production.yml up -d + +# Start reverse proxy (after both environments are running) +docker compose -f docker-compose.proxy.yml up -d +``` + +### Updating Applications + +```bash +# Pull latest code +git pull origin main + +# Rebuild and restart staging +docker compose -f docker-compose.staging.yml down +docker compose -f docker-compose.staging.yml build --no-cache +docker compose -f docker-compose.staging.yml up -d + +# Test staging thoroughly, then update production +docker compose -f docker-compose.production.yml down +docker compose -f docker-compose.production.yml build --no-cache +docker compose -f docker-compose.production.yml up -d +``` + +## Monitoring and Maintenance + +### Health Checks + +```bash +# Check all containers +docker ps + +# Check logs +docker compose -f docker-compose.production.yml logs -f + +# Check application health +curl https://cmc.springupsoftware.com/health +curl https://staging.cmc.springupsoftware.com/health +``` + +### Database Backups + +```bash +# Manual backup +./scripts/backup-db.sh production +./scripts/backup-db.sh staging + +# Set up automated backups (cron) +sudo crontab -e +# Add: 0 2 * * * /opt/cmc-sales/scripts/backup-db.sh production +# Add: 0 3 * * * /opt/cmc-sales/scripts/backup-db.sh staging +``` + +### Log Management + +```bash +# View nginx logs +sudo tail -f /var/log/nginx/access.log +sudo tail -f /var/log/nginx/error.log + +# View application logs +docker compose -f docker-compose.production.yml logs -f cmc-go-production +docker compose -f docker-compose.staging.yml logs -f cmc-go-staging +``` + +### SSL Certificate Renewal + +```bash +# Manual renewal +./scripts/lego-renew-cert.sh all + +# Renew specific domain +./scripts/lego-renew-cert.sh cmc.springupsoftware.com + +# Set up auto-renewal (cron) +sudo crontab -e +# Add: 0 2 * * * /opt/cmc-sales/scripts/lego-renew-cert.sh all +``` + +## Security Considerations + +### Basic Authentication + +Update passwords in `userpasswd` file: +```bash +# Generate new password hash +sudo apt install apache2-utils +htpasswd -c userpasswd username + +# Restart nginx containers +docker compose -f docker-compose.proxy.yml restart nginx-proxy +``` + +### Database Security + +- Use strong passwords in environment files +- Database containers are not exposed externally in production +- Regular backups with encryption at rest + +### Network Security + +- All traffic encrypted with SSL/TLS +- Rate limiting configured in nginx +- Security headers enabled +- Docker networks isolate environments + +## Troubleshooting + +### Common Issues + +1. **Containers won't start** + ```bash + # Check logs + docker compose logs container-name + + # Check system resources + df -h + free -h + ``` + +2. **SSL issues** + ```bash + # Check certificate status + ./scripts/lego-list-certs.sh + + # Test SSL configuration + curl -I https://cmc.springupsoftware.com + + # Manually renew certificates + ./scripts/lego-renew-cert.sh all + ``` + +3. **Database connection issues** + ```bash + # Test database connectivity + docker exec -it cmc-db-production mysql -u cmc -p + ``` + +4. **Gmail API issues** + ```bash + # Check credentials are mounted + docker exec -it cmc-go-production ls -la /root/credentials/ + + # Check logs for OAuth errors + docker compose logs cmc-go-production | grep -i gmail + ``` + +### Emergency Procedures + +1. **Quick rollback** + ```bash + # Stop current containers + docker compose -f docker-compose.production.yml down + + # Restore from backup + ./scripts/restore-db.sh production /var/backups/cmc-sales/latest_backup.sql.gz + + # Start previous version + git checkout previous-commit + docker compose -f docker-compose.production.yml up -d + ``` + +2. **Database corruption** + ```bash + # Stop application + docker compose -f docker-compose.production.yml stop cmc-go-production cmc-php-production + + # Restore from backup + ./scripts/restore-db.sh production /var/backups/cmc-sales/backup_production_YYYYMMDD-HHMMSS.sql.gz + + # Restart application + docker compose -f docker-compose.production.yml start cmc-go-production cmc-php-production + ``` + +## File Structure + +``` +/opt/cmc-sales/ +├── docker-compose.staging.yml +├── docker-compose.production.yml +├── docker-compose.proxy.yml +├── conf/ +│ ├── nginx-staging.conf +│ ├── nginx-production.conf +│ └── nginx-proxy.conf +├── credentials/ +│ ├── staging/ +│ │ ├── credentials.json +│ │ └── token.json +│ └── production/ +│ ├── credentials.json +│ └── token.json +├── scripts/ +│ ├── backup-db.sh +│ ├── restore-db.sh +│ ├── lego-obtain-cert.sh +│ ├── lego-renew-cert.sh +│ ├── lego-list-certs.sh +│ └── setup-lego-certs.sh +└── .env files +``` + +## Performance Tuning + +### Resource Limits + +Resource limits are configured in the Docker Compose files: +- Production: 2 CPU cores, 2-4GB RAM per service +- Staging: More relaxed limits for testing + +### Database Optimization + +```sql +-- Monitor slow queries +SHOW VARIABLES LIKE 'slow_query_log'; +SET GLOBAL slow_query_log = 'ON'; +SET GLOBAL long_query_time = 2; + +-- Check database performance +SHOW PROCESSLIST; +SHOW ENGINE INNODB STATUS; +``` + +### Nginx Optimization + +- Gzip compression enabled +- Static file caching +- Connection keep-alive +- Rate limiting configured \ No newline at end of file diff --git a/Dockerfile.go b/Dockerfile.go index 2e59e2ec..57c7d546 100644 --- a/Dockerfile.go +++ b/Dockerfile.go @@ -40,6 +40,13 @@ COPY --from=builder /app/server . COPY go-app/templates ./templates COPY go-app/static ./static +# Copy Gmail OAuth credentials if they exist +# Note: These files contain sensitive data and should not be committed to version control +# Consider using Docker secrets or environment variables for production +# Using conditional copy pattern to handle missing files gracefully +COPY go-app/credentials.jso[n] ./ +COPY go-app/token.jso[n] ./ + # Copy .env file if needed COPY go-app/.env.example .env diff --git a/Dockerfile.go.production b/Dockerfile.go.production new file mode 100644 index 00000000..adb9f510 --- /dev/null +++ b/Dockerfile.go.production @@ -0,0 +1,63 @@ +# Build stage +FROM golang:1.23-alpine AS builder + +# Install build dependencies +RUN apk add --no-cache git + +# Set working directory +WORKDIR /app + +# Copy go mod files +COPY go-app/go.mod go-app/go.sum ./ + +# Download dependencies +RUN go mod download + +# Copy source code +COPY go-app/ . + +# Install sqlc (compatible with Go 1.23+) +RUN go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest + +# Generate sqlc code +RUN sqlc generate + +# Build the application with production optimizations +RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags="-w -s" -tags production -o server cmd/server/main.go + +# Runtime stage - minimal image for production +FROM alpine:latest + +# Install only essential runtime dependencies +RUN apk --no-cache add ca-certificates && \ + addgroup -g 1001 -S appgroup && \ + adduser -u 1001 -S appuser -G appgroup + +WORKDIR /app + +# Copy the binary from builder +COPY --from=builder /app/server . + +# Copy templates and static files +COPY go-app/templates ./templates +COPY go-app/static ./static + +# Copy production environment file +COPY go-app/.env.production .env + +# Create credentials directory with proper permissions +RUN mkdir -p ./credentials && \ + chown -R appuser:appgroup /app + +# Switch to non-root user +USER appuser + +# Expose port +EXPOSE 8080 + +# Health check +HEALTHCHECK --interval=60s --timeout=10s --start-period=10s --retries=3 \ + CMD wget --no-verbose --tries=1 --spider http://localhost:8080/api/v1/health || exit 1 + +# Run the application +CMD ["./server"] \ No newline at end of file diff --git a/Dockerfile.go.staging b/Dockerfile.go.staging new file mode 100644 index 00000000..6c814aec --- /dev/null +++ b/Dockerfile.go.staging @@ -0,0 +1,57 @@ +# Build stage +FROM golang:1.23-alpine AS builder + +# Install build dependencies +RUN apk add --no-cache git + +# Set working directory +WORKDIR /app + +# Copy go mod files +COPY go-app/go.mod go-app/go.sum ./ + +# Download dependencies +RUN go mod download + +# Copy source code +COPY go-app/ . + +# Install sqlc (compatible with Go 1.23+) +RUN go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest + +# Generate sqlc code +RUN sqlc generate + +# Build the application with staging tags +RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -tags staging -o server cmd/server/main.go + +# Runtime stage +FROM alpine:latest + +# Install runtime dependencies and debugging tools for staging +RUN apk --no-cache add ca-certificates curl net-tools + +WORKDIR /root/ + +# Copy the binary from builder +COPY --from=builder /app/server . + +# Copy templates and static files +COPY go-app/templates ./templates +COPY go-app/static ./static + +# Copy staging environment file +COPY go-app/.env.staging .env + +# Create credentials directory +RUN mkdir -p ./credentials + +# Expose port +EXPOSE 8080 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ + CMD curl -f http://localhost:8080/api/v1/health || exit 1 + +# Run the application +CMD ["./server"] \ No newline at end of file diff --git a/TESTING_DOCKER.md b/TESTING_DOCKER.md new file mode 100644 index 00000000..17256fcb --- /dev/null +++ b/TESTING_DOCKER.md @@ -0,0 +1,394 @@ +# Running CMC Django Tests in Docker + +This guide explains how to run the comprehensive CMC Django test suite using Docker for consistent, isolated testing. + +## Quick Start + +```bash +# 1. Setup test environment (one-time) +./run-tests-docker.sh setup + +# 2. Run all tests +./run-tests-docker.sh run + +# 3. Run tests with coverage +./run-tests-docker.sh coverage +``` + +## Test Environment Overview + +The Docker test environment includes: +- **Isolated test database** (MariaDB on port 3307) +- **Django test container** with all dependencies +- **Coverage reporting** with HTML and XML output +- **PDF generation testing** with WeasyPrint/ReportLab +- **Parallel test execution** support + +## Available Commands + +### Setup and Management + +```bash +# Build containers and setup test database +./run-tests-docker.sh setup + +# Clean up all test containers and data +./run-tests-docker.sh clean + +# View test container logs +./run-tests-docker.sh logs + +# Open shell in test container +./run-tests-docker.sh shell +``` + +### Running Tests + +```bash +# Run all tests +./run-tests-docker.sh run + +# Run specific test suites +./run-tests-docker.sh run models # Model tests only +./run-tests-docker.sh run services # Service layer tests +./run-tests-docker.sh run auth # Authentication tests +./run-tests-docker.sh run views # View and URL tests +./run-tests-docker.sh run pdf # PDF generation tests +./run-tests-docker.sh run integration # Integration tests + +# Run quick tests (models + services) +./run-tests-docker.sh quick + +# Run tests with coverage reporting +./run-tests-docker.sh coverage +``` + +## Advanced Test Options + +### Using Docker Compose Directly + +```bash +# Run specific test with custom options +docker-compose -f docker-compose.test.yml run --rm cmc-django-test \ + python cmcsales/manage.py test cmc.tests.test_models --verbosity=2 --keepdb + +# Run tests with coverage +docker-compose -f docker-compose.test.yml run --rm cmc-django-test \ + coverage run --source='.' cmcsales/manage.py test cmc.tests + +# Generate coverage report +docker-compose -f docker-compose.test.yml run --rm cmc-django-test \ + coverage report --show-missing +``` + +### Using the Test Script Directly + +```bash +# Inside the container, you can use the test script with advanced options +docker-compose -f docker-compose.test.yml run --rm cmc-django-test \ + /app/scripts/run-tests.sh --coverage --keepdb --failfast models + +# Script options: +# -c, --coverage Enable coverage reporting +# -k, --keepdb Keep test database between runs +# -p, --parallel NUM Run tests in parallel +# -f, --failfast Stop on first failure +# -v, --verbosity NUM Verbosity level 0-3 +``` + +## Test Suite Structure + +### 1. Model Tests (`test_models.py`) +Tests all Django models including: +- Customer, Enquiry, Job, Document models +- Model validation and constraints +- Relationships and cascade behavior +- Financial calculations + +```bash +./run-tests-docker.sh run models +``` + +### 2. Service Tests (`test_services.py`) +Tests business logic layer: +- Number generation service +- Financial calculation service +- Document service workflows +- Validation service + +```bash +./run-tests-docker.sh run services +``` + +### 3. Authentication Tests (`test_authentication.py`) +Tests authentication system: +- Multiple authentication backends +- Permission decorators and middleware +- User management workflows +- Security features + +```bash +./run-tests-docker.sh run auth +``` + +### 4. View Tests (`test_views.py`) +Tests web interface: +- CRUD operations for all entities +- AJAX endpoints +- Permission enforcement +- URL routing + +```bash +./run-tests-docker.sh run views +``` + +### 5. PDF Tests (`test_pdf.py`) +Tests PDF generation: +- WeasyPrint and ReportLab engines +- Template rendering +- Document formatting +- Security and performance + +```bash +./run-tests-docker.sh run pdf +``` + +### 6. Integration Tests (`test_integration.py`) +Tests complete workflows: +- End-to-end business processes +- Multi-user collaboration +- System integration scenarios +- Performance and security + +```bash +./run-tests-docker.sh run integration +``` + +## Test Reports and Coverage + +### Coverage Reports + +After running tests with coverage, reports are available in: +- **HTML Report**: `./coverage-reports/html/index.html` +- **XML Report**: `./coverage-reports/coverage.xml` +- **Console**: Displayed after test run + +```bash +# Run tests with coverage +./run-tests-docker.sh coverage + +# View HTML report +open coverage-reports/html/index.html +``` + +### Test Artifacts + +Test outputs are saved to: +- **Test Reports**: `./test-reports/` +- **Coverage Reports**: `./coverage-reports/` +- **Logs**: `./logs/` +- **PDF Test Files**: `./test-reports/pdf/` + +## Configuration + +### Environment Variables + +The test environment uses these key variables: + +```yaml +# Database configuration +DATABASE_HOST: test-db +DATABASE_NAME: test_cmc +DATABASE_USER: test_cmc +DATABASE_PASSWORD: testPassword123 + +# Django settings +DJANGO_SETTINGS_MODULE: cmcsales.settings +TESTING: 1 +DEBUG: 0 + +# PDF generation +PDF_GENERATION_ENGINE: weasyprint +PDF_SAVE_DIRECTORY: /app/test-reports/pdf +``` + +### Test Database + +- **Isolated database** separate from development/production +- **Runs on port 3307** to avoid conflicts +- **Optimized for testing** with reduced buffer sizes +- **Automatically reset** between test runs (unless `--keepdb` used) + +## Performance Optimization + +### Parallel Test Execution + +```bash +# Run tests in parallel (faster execution) +docker-compose -f docker-compose.test.yml run --rm cmc-django-test \ + /app/scripts/run-tests.sh --parallel=4 all +``` + +### Keeping Test Database + +```bash +# Keep database between runs for faster subsequent tests +./run-tests-docker.sh run models --keepdb +``` + +### Quick Test Suite + +```bash +# Run only essential tests for rapid feedback +./run-tests-docker.sh quick +``` + +## Continuous Integration + +### GitHub Actions Example + +```yaml +name: Test CMC Django +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup test environment + run: ./run-tests-docker.sh setup + + - name: Run tests with coverage + run: ./run-tests-docker.sh coverage + + - name: Upload coverage reports + uses: codecov/codecov-action@v3 + with: + file: ./coverage-reports/coverage.xml +``` + +## Troubleshooting + +### Database Connection Issues + +```bash +# Check database status +docker-compose -f docker-compose.test.yml ps + +# View database logs +docker-compose -f docker-compose.test.yml logs test-db + +# Restart database +docker-compose -f docker-compose.test.yml restart test-db +``` + +### Test Failures + +```bash +# Run with maximum verbosity for debugging +docker-compose -f docker-compose.test.yml run --rm cmc-django-test \ + python cmcsales/manage.py test cmc.tests.test_models --verbosity=3 + +# Use failfast to stop on first error +./run-tests-docker.sh run models --failfast + +# Open shell to investigate +./run-tests-docker.sh shell +``` + +### Permission Issues + +```bash +# Fix file permissions +sudo chown -R $USER:$USER test-reports coverage-reports logs + +# Check Docker permissions +docker-compose -f docker-compose.test.yml run --rm cmc-django-test whoami +``` + +### Memory Issues + +```bash +# Run tests with reduced parallel workers +docker-compose -f docker-compose.test.yml run --rm cmc-django-test \ + /app/scripts/run-tests.sh --parallel=1 all + +# Monitor resource usage +docker stats +``` + +## Development Workflow + +### Recommended Testing Workflow + +1. **Initial Setup** (one-time): + ```bash + ./run-tests-docker.sh setup + ``` + +2. **During Development** (fast feedback): + ```bash + ./run-tests-docker.sh quick --keepdb + ``` + +3. **Before Commit** (comprehensive): + ```bash + ./run-tests-docker.sh coverage + ``` + +4. **Debugging Issues**: + ```bash + ./run-tests-docker.sh shell + # Inside container: + python cmcsales/manage.py test cmc.tests.test_models.CustomerModelTest.test_customer_creation --verbosity=3 + ``` + +### Adding New Tests + +1. Create test file in appropriate module +2. Follow existing test patterns and base classes +3. Test locally: + ```bash + ./run-tests-docker.sh run models --keepdb + ``` +4. Run full suite before committing: + ```bash + ./run-tests-docker.sh coverage + ``` + +## Integration with IDE + +### PyCharm/IntelliJ + +Configure remote interpreter using Docker: +1. Go to Settings → Project → Python Interpreter +2. Add Docker Compose interpreter +3. Use `docker-compose.test.yml` configuration +4. Set service to `cmc-django-test` + +### VS Code + +Use Dev Containers extension: +1. Create `.devcontainer/devcontainer.json` +2. Configure to use test Docker environment +3. Run tests directly in integrated terminal + +## Best Practices + +1. **Always run tests in Docker** for consistency +2. **Use `--keepdb` during development** for speed +3. **Run coverage reports before commits** +4. **Clean up regularly** to free disk space +5. **Monitor test performance** and optimize slow tests +6. **Use parallel execution** for large test suites +7. **Keep test data realistic** but minimal +8. **Test error conditions** as well as happy paths + +## Resources + +- **Django Testing Documentation**: https://docs.djangoproject.com/en/5.1/topics/testing/ +- **Coverage.py Documentation**: https://coverage.readthedocs.io/ +- **Docker Compose Reference**: https://docs.docker.com/compose/ +- **CMC Test Suite Documentation**: See individual test modules for detailed information \ No newline at end of file diff --git a/conf/nginx-production.conf b/conf/nginx-production.conf new file mode 100644 index 00000000..bd9829b3 --- /dev/null +++ b/conf/nginx-production.conf @@ -0,0 +1,152 @@ +# Production environment configuration +upstream cmc_php_production { + server cmc-php-production:80; + keepalive 32; +} + +upstream cmc_go_production { + server cmc-go-production:8080; + keepalive 32; +} + +# Rate limiting +limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m; +limit_req_zone $binary_remote_addr zone=api:10m rate=30r/m; + +server { + server_name cmc.springupsoftware.com; + + # Basic auth for production + auth_basic_user_file /etc/nginx/userpasswd; + auth_basic "CMC Sales - Restricted Access"; + + # Security headers + add_header X-Frame-Options DENY; + add_header X-Content-Type-Options nosniff; + add_header X-XSS-Protection "1; mode=block"; + add_header Referrer-Policy "strict-origin-when-cross-origin"; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + + # Hide server information + server_tokens off; + + # Request size limits + client_max_body_size 50M; + client_body_timeout 30s; + client_header_timeout 30s; + + # Compression + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json; + + # CakePHP legacy app routes + location / { + limit_req zone=api burst=10 nodelay; + + proxy_pass http://cmc_php_production; + proxy_read_timeout 300s; + proxy_connect_timeout 10s; + proxy_send_timeout 30s; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Buffer settings for better performance + proxy_buffering on; + proxy_buffer_size 128k; + proxy_buffers 4 256k; + proxy_busy_buffers_size 256k; + } + + # Go API routes + location /api/ { + limit_req zone=api burst=20 nodelay; + + proxy_pass http://cmc_go_production; + proxy_read_timeout 300s; + proxy_connect_timeout 10s; + proxy_send_timeout 30s; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Buffer settings for better performance + proxy_buffering on; + proxy_buffer_size 128k; + proxy_buffers 4 256k; + proxy_busy_buffers_size 256k; + } + + # Go page routes for emails + location ~ ^/(emails|customers|products|purchase-orders|enquiries|documents) { + limit_req zone=api burst=15 nodelay; + + proxy_pass http://cmc_go_production; + proxy_read_timeout 300s; + proxy_connect_timeout 10s; + proxy_send_timeout 30s; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Buffer settings for better performance + proxy_buffering on; + proxy_buffer_size 128k; + proxy_buffers 4 256k; + proxy_busy_buffers_size 256k; + } + + # Static files from Go app with aggressive caching + location /static/ { + proxy_pass http://cmc_go_production; + proxy_cache_valid 200 24h; + add_header Cache-Control "public, max-age=86400"; + expires 1d; + } + + # PDF files with caching + location /pdf/ { + proxy_pass http://cmc_go_production; + proxy_cache_valid 200 1h; + add_header Cache-Control "public, max-age=3600"; + expires 1h; + } + + # Health check endpoints (no rate limiting) + location /health { + proxy_pass http://cmc_go_production/api/v1/health; + access_log off; + } + + # Block common attack patterns + location ~ /\. { + deny all; + access_log off; + log_not_found off; + } + + location ~ ~$ { + deny all; + access_log off; + log_not_found off; + } + + # Error pages + error_page 502 503 504 /50x.html; + location = /50x.html { + root /usr/share/nginx/html; + } + + # Custom error page for rate limiting + error_page 429 /429.html; + location = /429.html { + root /usr/share/nginx/html; + } + + listen 80; +} \ No newline at end of file diff --git a/conf/nginx-proxy.conf b/conf/nginx-proxy.conf new file mode 100644 index 00000000..e1652854 --- /dev/null +++ b/conf/nginx-proxy.conf @@ -0,0 +1,137 @@ +user nginx; +worker_processes auto; +error_log /var/log/nginx/error.log warn; +pid /var/run/nginx.pid; + +events { + worker_connections 1024; + use epoll; + multi_accept on; +} + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + + # Logging + log_format main '$remote_addr - $remote_user [$time_local] "$request" ' + '$status $body_bytes_sent "$http_referer" ' + '"$http_user_agent" "$http_x_forwarded_for"'; + + access_log /var/log/nginx/access.log main; + + # Performance + sendfile on; + tcp_nopush on; + tcp_nodelay on; + keepalive_timeout 65; + types_hash_max_size 2048; + server_tokens off; + + # Gzip + gzip on; + gzip_vary on; + gzip_min_length 1024; + gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json; + + # Rate limiting + limit_req_zone $binary_remote_addr zone=global:10m rate=10r/s; + + # SSL configuration + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384; + ssl_prefer_server_ciphers off; + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 10m; + + # Upstream servers + upstream cmc_staging { + server nginx-staging:80; + keepalive 32; + } + + upstream cmc_production { + server nginx-production:80; + keepalive 32; + } + + # Redirect HTTP to HTTPS + server { + listen 80; + server_name cmc.springupsoftware.com staging.cmc.springupsoftware.com; + + # ACME challenge for Lego + location /.well-known/acme-challenge/ { + root /var/www/acme-challenge; + try_files $uri =404; + } + + # Redirect all other traffic to HTTPS + location / { + return 301 https://$server_name$request_uri; + } + } + + # Production HTTPS + server { + listen 443 ssl http2; + server_name cmc.springupsoftware.com; + + ssl_certificate /etc/ssl/certs/cmc.springupsoftware.com.crt; + ssl_certificate_key /etc/ssl/certs/cmc.springupsoftware.com.key; + + # Security headers + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Frame-Options DENY; + add_header X-Content-Type-Options nosniff; + add_header X-XSS-Protection "1; mode=block"; + + # Rate limiting + limit_req zone=global burst=20 nodelay; + + location / { + proxy_pass http://cmc_production; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Buffer settings + proxy_buffering on; + proxy_buffer_size 128k; + proxy_buffers 4 256k; + proxy_busy_buffers_size 256k; + } + } + + # Staging HTTPS + server { + listen 443 ssl http2; + server_name staging.cmc.springupsoftware.com; + + ssl_certificate /etc/ssl/certs/staging.cmc.springupsoftware.com.crt; + ssl_certificate_key /etc/ssl/certs/staging.cmc.springupsoftware.com.key; + + # Security headers (less strict for staging) + add_header X-Frame-Options DENY; + add_header X-Content-Type-Options nosniff; + add_header X-Environment "STAGING"; + + # Rate limiting (more lenient for staging) + limit_req zone=global burst=50 nodelay; + + location / { + proxy_pass http://cmc_staging; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # Buffer settings + proxy_buffering on; + proxy_buffer_size 128k; + proxy_buffers 4 256k; + proxy_busy_buffers_size 256k; + } + } +} \ No newline at end of file diff --git a/conf/nginx-staging.conf b/conf/nginx-staging.conf new file mode 100644 index 00000000..ac7ed8d8 --- /dev/null +++ b/conf/nginx-staging.conf @@ -0,0 +1,89 @@ +# Staging environment configuration +upstream cmc_php_staging { + server cmc-php-staging:80; +} + +upstream cmc_go_staging { + server cmc-go-staging:8080; +} + +server { + server_name staging.cmc.springupsoftware.com; + + # Basic auth for staging + auth_basic_user_file /etc/nginx/userpasswd; + auth_basic "CMC Sales Staging - Restricted Access"; + + # Security headers + add_header X-Frame-Options DENY; + add_header X-Content-Type-Options nosniff; + add_header X-XSS-Protection "1; mode=block"; + add_header Referrer-Policy "strict-origin-when-cross-origin"; + + # Staging banner + add_header X-Environment "STAGING"; + + # CakePHP legacy app routes + location / { + proxy_pass http://cmc_php_staging; + proxy_read_timeout 300s; + proxy_connect_timeout 10s; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Environment "staging"; + } + + # Go API routes + location /api/ { + proxy_pass http://cmc_go_staging; + proxy_read_timeout 300s; + proxy_connect_timeout 10s; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Environment "staging"; + } + + # Go page routes for emails + location ~ ^/(emails|customers|products|purchase-orders|enquiries|documents) { + proxy_pass http://cmc_go_staging; + proxy_read_timeout 300s; + proxy_connect_timeout 10s; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_set_header X-Environment "staging"; + } + + # Static files from Go app + location /static/ { + proxy_pass http://cmc_go_staging; + proxy_cache_valid 200 1h; + add_header Cache-Control "public, max-age=3600"; + } + + # PDF files + location /pdf/ { + proxy_pass http://cmc_go_staging; + proxy_cache_valid 200 1h; + add_header Cache-Control "public, max-age=3600"; + } + + # Health check endpoints + location /health { + proxy_pass http://cmc_go_staging/api/v1/health; + access_log off; + } + + # Error pages + error_page 502 503 504 /50x.html; + location = /50x.html { + root /usr/share/nginx/html; + } + + listen 80; +} \ No newline at end of file diff --git a/docker-compose.production.yml b/docker-compose.production.yml new file mode 100644 index 00000000..376e5bb8 --- /dev/null +++ b/docker-compose.production.yml @@ -0,0 +1,110 @@ +version: '3.8' + +services: + nginx-production: + image: nginx:latest + hostname: nginx-production + container_name: cmc-nginx-production + ports: + - "8080:80" # Internal port for production + volumes: + - ./conf/nginx-production.conf:/etc/nginx/conf.d/cmc-production.conf + - ./userpasswd:/etc/nginx/userpasswd:ro + depends_on: + - cmc-php-production + restart: unless-stopped + networks: + - cmc-production-network + environment: + - NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template + + cmc-php-production: + build: + context: . + dockerfile: Dockerfile + platform: linux/amd64 + container_name: cmc-php-production + depends_on: + - db-production + volumes: + - production_pdf_data:/var/www/cmc-sales/app/webroot/pdf + - production_attachments_data:/var/www/cmc-sales/app/webroot/attachments_files + networks: + - cmc-production-network + restart: unless-stopped + environment: + - APP_ENV=production + # Remove development features + deploy: + resources: + limits: + cpus: '2.0' + memory: 2G + reservations: + cpus: '0.5' + memory: 512M + + db-production: + image: mariadb:latest + container_name: cmc-db-production + environment: + MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD_PRODUCTION} + MYSQL_DATABASE: cmc + MYSQL_USER: cmc + MYSQL_PASSWORD: ${DB_PASSWORD_PRODUCTION} + volumes: + - production_db_data:/var/lib/mysql + - ./backups:/backups:ro # Backup restore directory + networks: + - cmc-production-network + restart: unless-stopped + # No external port exposure for security + deploy: + resources: + limits: + cpus: '2.0' + memory: 4G + reservations: + cpus: '0.5' + memory: 1G + + cmc-go-production: + build: + context: . + dockerfile: Dockerfile.go.production + container_name: cmc-go-production + environment: + DB_HOST: db-production + DB_PORT: 3306 + DB_USER: cmc + DB_PASSWORD: ${DB_PASSWORD_PRODUCTION} + DB_NAME: cmc + PORT: 8080 + APP_ENV: production + depends_on: + db-production: + condition: service_started + # No external port exposure - only through nginx + volumes: + - production_pdf_data:/root/webroot/pdf + - ./credentials/production:/root/credentials:ro # Production Gmail credentials + networks: + - cmc-production-network + restart: unless-stopped + deploy: + resources: + limits: + cpus: '2.0' + memory: 2G + reservations: + cpus: '0.5' + memory: 512M + +volumes: + production_db_data: + production_pdf_data: + production_attachments_data: + +networks: + cmc-production-network: + driver: bridge \ No newline at end of file diff --git a/docker-compose.proxy.yml b/docker-compose.proxy.yml new file mode 100644 index 00000000..616270ab --- /dev/null +++ b/docker-compose.proxy.yml @@ -0,0 +1,68 @@ +# Main reverse proxy for both staging and production +version: '3.8' + +services: + nginx-proxy: + image: nginx:latest + container_name: cmc-nginx-proxy + ports: + - "80:80" + - "443:443" + volumes: + - ./conf/nginx-proxy.conf:/etc/nginx/nginx.conf + - lego_certificates:/etc/ssl/certs:ro + - lego_acme_challenge:/var/www/acme-challenge:ro + restart: unless-stopped + depends_on: + - nginx-staging + - nginx-production + networks: + - proxy-network + - cmc-staging-network + - cmc-production-network + + lego: + image: goacme/lego:latest + container_name: cmc-lego + volumes: + - lego_certificates:/data/certificates + - lego_accounts:/data/accounts + - lego_acme_challenge:/data/acme-challenge + - ./scripts:/scripts:ro + environment: + - LEGO_DISABLE_CNAME=true + command: sleep infinity + restart: unless-stopped + networks: + - proxy-network + + # Import staging services + nginx-staging: + extends: + file: docker-compose.staging.yml + service: nginx-staging + networks: + - proxy-network + - cmc-staging-network + + # Import production services + nginx-production: + extends: + file: docker-compose.production.yml + service: nginx-production + networks: + - proxy-network + - cmc-production-network + +volumes: + lego_certificates: + lego_accounts: + lego_acme_challenge: + +networks: + proxy-network: + driver: bridge + cmc-staging-network: + external: true + cmc-production-network: + external: true \ No newline at end of file diff --git a/docker-compose.staging.yml b/docker-compose.staging.yml new file mode 100644 index 00000000..cde10cad --- /dev/null +++ b/docker-compose.staging.yml @@ -0,0 +1,86 @@ +version: '3.8' + +services: + nginx-staging: + image: nginx:latest + hostname: nginx-staging + container_name: cmc-nginx-staging + ports: + - "8081:80" # Internal port for staging + volumes: + - ./conf/nginx-staging.conf:/etc/nginx/conf.d/cmc-staging.conf + - ./userpasswd:/etc/nginx/userpasswd:ro + depends_on: + - cmc-php-staging + restart: unless-stopped + networks: + - cmc-staging-network + environment: + - NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template + + cmc-php-staging: + build: + context: . + dockerfile: Dockerfile + platform: linux/amd64 + container_name: cmc-php-staging + depends_on: + - db-staging + volumes: + - staging_pdf_data:/var/www/cmc-sales/app/webroot/pdf + - staging_attachments_data:/var/www/cmc-sales/app/webroot/attachments_files + networks: + - cmc-staging-network + restart: unless-stopped + environment: + - APP_ENV=staging + + db-staging: + image: mariadb:latest + container_name: cmc-db-staging + environment: + MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD_STAGING} + MYSQL_DATABASE: cmc_staging + MYSQL_USER: cmc_staging + MYSQL_PASSWORD: ${DB_PASSWORD_STAGING} + volumes: + - staging_db_data:/var/lib/mysql + networks: + - cmc-staging-network + restart: unless-stopped + ports: + - "3307:3306" # Different port for staging DB access + + cmc-go-staging: + build: + context: . + dockerfile: Dockerfile.go.staging + container_name: cmc-go-staging + environment: + DB_HOST: db-staging + DB_PORT: 3306 + DB_USER: cmc_staging + DB_PASSWORD: ${DB_PASSWORD_STAGING} + DB_NAME: cmc_staging + PORT: 8080 + APP_ENV: staging + depends_on: + db-staging: + condition: service_started + ports: + - "8082:8080" # Direct access for testing + volumes: + - staging_pdf_data:/root/webroot/pdf + - ./credentials/staging:/root/credentials:ro # Staging Gmail credentials + networks: + - cmc-staging-network + restart: unless-stopped + +volumes: + staging_db_data: + staging_pdf_data: + staging_attachments_data: + +networks: + cmc-staging-network: + driver: bridge \ No newline at end of file diff --git a/go-app/.gitignore b/go-app/.gitignore index 56c712b8..ea2b3066 100644 --- a/go-app/.gitignore +++ b/go-app/.gitignore @@ -30,4 +30,11 @@ vendor/ # OS specific files .DS_Store -Thumbs.db \ No newline at end of file +Thumbs.db + +# Goose database migration config +goose.env + +# Gmail OAuth credentials - NEVER commit these! +credentials.json +token.json diff --git a/go-app/MIGRATIONS.md b/go-app/MIGRATIONS.md new file mode 100644 index 00000000..012636f7 --- /dev/null +++ b/go-app/MIGRATIONS.md @@ -0,0 +1,70 @@ +# Database Migrations with Goose + +This document explains how to use goose for database migrations in the CMC Sales Go application. + +## Setup + +1. **Install goose**: + ```bash + make install + ``` + +2. **Configure database connection**: + ```bash + cp goose.env.example goose.env + # Edit goose.env with your database credentials + ``` + +## Migration Commands + +### Run Migrations +```bash +# Run all pending migrations +make migrate + +# Check migration status +make migrate-status +``` + +### Rollback Migrations +```bash +# Rollback the last migration +make migrate-down +``` + +### Create New Migrations +```bash +# Create a new migration file +make migrate-create name=add_new_feature +``` + +## Migration Structure + +Migrations are stored in `sql/migrations/` and follow this naming convention: +- `001_add_gmail_fields.sql` +- `002_add_new_feature.sql` + +Each migration file contains: +```sql +-- +goose Up +-- Your upgrade SQL here + +-- +goose Down +-- Your rollback SQL here +``` + +## Configuration Files + +- `goose.env` - Database connection settings (gitignored) +- `goose.env.example` - Template for goose.env + +## Current Migrations + +1. **001_add_gmail_fields.sql** - Adds Gmail integration fields to emails and email_attachments tables + +## Tips + +- Always test migrations on a backup database first +- Use `make migrate-status` to check current state +- Migrations are atomic - if one fails, none are applied +- Each migration should be reversible with a corresponding Down section \ No newline at end of file diff --git a/go-app/Makefile b/go-app/Makefile index 37e17ecd..66a3dea9 100644 --- a/go-app/Makefile +++ b/go-app/Makefile @@ -11,6 +11,7 @@ install: ## Install dependencies go env -w GOPRIVATE=code.springupsoftware.com go mod download go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest + go install github.com/pressly/goose/v3/cmd/goose@latest .PHONY: sqlc sqlc: ## Generate Go code from SQL queries @@ -76,4 +77,48 @@ dbshell-root: ## Connect to MariaDB as root user exit 1; \ else \ docker compose exec -e MYSQL_PWD="$$DB_ROOT_PASSWORD" db mariadb -u root; \ + fi + +.PHONY: migrate +migrate: ## Run database migrations + @echo "Running database migrations..." + @if [ -f goose.env ]; then \ + export $$(cat goose.env | xargs) && goose up; \ + else \ + echo "Error: goose.env file not found"; \ + exit 1; \ + fi + +.PHONY: migrate-down +migrate-down: ## Rollback last migration + @echo "Rolling back last migration..." + @if [ -f goose.env ]; then \ + export $$(cat goose.env | xargs) && goose down; \ + else \ + echo "Error: goose.env file not found"; \ + exit 1; \ + fi + +.PHONY: migrate-status +migrate-status: ## Show migration status + @echo "Migration status:" + @if [ -f goose.env ]; then \ + export $$(cat goose.env | xargs) && goose status; \ + else \ + echo "Error: goose.env file not found"; \ + exit 1; \ + fi + +.PHONY: migrate-create +migrate-create: ## Create a new migration file (use: make migrate-create name=add_new_table) + @if [ -z "$(name)" ]; then \ + echo "Error: Please provide a migration name. Usage: make migrate-create name=add_new_table"; \ + exit 1; \ + fi + @echo "Creating new migration: $(name)" + @if [ -f goose.env ]; then \ + export $$(cat goose.env | xargs) && goose create $(name) sql; \ + else \ + echo "Error: goose.env file not found"; \ + exit 1; \ fi \ No newline at end of file diff --git a/go-app/cmd/server/main.go b/go-app/cmd/server/main.go index 954dc444..bc361765 100644 --- a/go-app/cmd/server/main.go +++ b/go-app/cmd/server/main.go @@ -58,12 +58,13 @@ func main() { purchaseOrderHandler := handlers.NewPurchaseOrderHandler(queries) enquiryHandler := handlers.NewEnquiryHandler(queries) documentHandler := handlers.NewDocumentHandler(queries) - pageHandler := handlers.NewPageHandler(queries, tmpl) + pageHandler := handlers.NewPageHandler(queries, tmpl, database) addressHandler := handlers.NewAddressHandler(queries) attachmentHandler := handlers.NewAttachmentHandler(queries) countryHandler := handlers.NewCountryHandler(queries) statusHandler := handlers.NewStatusHandler(queries) lineItemHandler := handlers.NewLineItemHandler(queries) + emailHandler := handlers.NewEmailHandler(queries, database) // Setup routes r := mux.NewRouter() @@ -161,6 +162,14 @@ func main() { api.HandleFunc("/line-items/{id}", lineItemHandler.Delete).Methods("DELETE") api.HandleFunc("/line-items/document/{documentID}/table", lineItemHandler.GetTable).Methods("GET") + // Email routes + api.HandleFunc("/emails", emailHandler.List).Methods("GET") + api.HandleFunc("/emails/{id}", emailHandler.Get).Methods("GET") + api.HandleFunc("/emails/{id}/content", emailHandler.StreamContent).Methods("GET") + api.HandleFunc("/emails/{id}/attachments", emailHandler.ListAttachments).Methods("GET") + api.HandleFunc("/emails/{id}/attachments/{attachmentId}/stream", emailHandler.StreamAttachment).Methods("GET") + api.HandleFunc("/emails/search", emailHandler.Search).Methods("GET") + // Health check api.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) @@ -208,6 +217,12 @@ func main() { r.HandleFunc("/documents/{id}", pageHandler.DocumentsShow).Methods("GET") r.HandleFunc("/documents/pdf/{id}", documentHandler.GeneratePDF).Methods("GET") + // Email pages + r.HandleFunc("/emails", pageHandler.EmailsIndex).Methods("GET") + r.HandleFunc("/emails/search", pageHandler.EmailsSearch).Methods("GET") + r.HandleFunc("/emails/{id}", pageHandler.EmailsShow).Methods("GET") + r.HandleFunc("/emails/{id}/attachments", pageHandler.EmailsAttachments).Methods("GET") + // Address routes (matching CakePHP) r.HandleFunc("/addresses", addressHandler.List).Methods("GET") r.HandleFunc("/addresses/view/{id}", addressHandler.Get).Methods("GET") diff --git a/go-app/cmd/vault/README.md b/go-app/cmd/vault/README.md index 908312c5..e7125816 100644 --- a/go-app/cmd/vault/README.md +++ b/go-app/cmd/vault/README.md @@ -1,28 +1,23 @@ -# Vault Email Processor +# Vault Email Processor - Smart Proxy -This is a Go rewrite of the PHP vault.php script that processes emails for the CMC Sales system. +This is a Go rewrite of the PHP vault.php script that processes emails for the CMC Sales system. It now supports three modes: local file processing, Gmail indexing, and HTTP streaming proxy. -## Key Changes from PHP Version +## Key Features -1. **No ripmime dependency**: Uses the enmime Go library for MIME parsing instead of external ripmime binary -2. **Better error handling**: Proper error handling and database transactions -3. **Type safety**: Strongly typed Go structures -4. **Modern email parsing**: Uses enmime for robust email parsing +1. **Gmail Integration**: Index Gmail emails without downloading +2. **Smart Proxy**: Stream email content on-demand without storing to disk +3. **No ripmime dependency**: Uses the enmime Go library for MIME parsing +4. **Better error handling**: Proper error handling and database transactions +5. **Type safety**: Strongly typed Go structures +6. **Modern email parsing**: Uses enmime for robust email parsing -## Features +## Operating Modes -- Processes emails from vault directory -- Parses email headers and extracts recipients -- Identifies and creates users as needed -- Extracts attachments and email body parts -- Matches document identifiers in subjects (enquiries, invoices, POs, jobs) -- Saves emails with all associations to database -- Moves processed emails to processed directory - -## Usage +### 1. Local Mode (Original functionality) +Processes emails from local filesystem directories. ```bash -go run cmd/vault/main.go \ +./vault --mode=local \ --emaildir=/var/www/emails \ --vaultdir=/var/www/vaultmsgs/new \ --processeddir=/var/www/vaultmsgs/cur \ @@ -32,6 +27,83 @@ go run cmd/vault/main.go \ --dbname=cmc ``` +### 2. Gmail Index Mode +Indexes Gmail emails without downloading content. Creates database references only. + +```bash +./vault --mode=index \ + --gmail-query="is:unread" \ + --credentials=credentials.json \ + --token=token.json \ + --dbhost=127.0.0.1 \ + --dbuser=cmc \ + --dbpass="xVRQI&cA?7AU=hqJ!%au" \ + --dbname=cmc +``` + +### 3. HTTP Server Mode +Runs an HTTP server that streams Gmail content on-demand. + +```bash +./vault --mode=serve \ + --port=8080 \ + --credentials=credentials.json \ + --token=token.json \ + --dbhost=127.0.0.1 \ + --dbuser=cmc \ + --dbpass="xVRQI&cA?7AU=hqJ!%au" \ + --dbname=cmc +``` + +## Gmail Setup + +1. Enable Gmail API in Google Cloud Console +2. Create OAuth 2.0 credentials +3. Download credentials as `credentials.json` +4. Run vault in any Gmail mode - it will prompt for authorization +5. Token will be saved as `token.json` for future use + +## API Endpoints (Server Mode) + +- `GET /api/emails` - List indexed emails (metadata only) +- `GET /api/emails/:id` - Get email metadata +- `GET /api/emails/:id/content` - Stream email HTML/text from Gmail +- `GET /api/emails/:id/attachments` - List attachment metadata +- `GET /api/emails/:id/attachments/:attachmentId` - Stream attachment from Gmail +- `GET /api/emails/:id/raw` - Stream raw email (for email clients) + +## Database Schema Changes + +Required migrations for Gmail support: + +```sql +ALTER TABLE emails + ADD COLUMN gmail_message_id VARCHAR(255) UNIQUE, + ADD COLUMN gmail_thread_id VARCHAR(255), + ADD COLUMN is_downloaded BOOLEAN DEFAULT FALSE, + ADD COLUMN raw_headers TEXT; + +CREATE INDEX idx_gmail_message_id ON emails(gmail_message_id); + +ALTER TABLE email_attachments + ADD COLUMN gmail_attachment_id VARCHAR(255), + ADD COLUMN gmail_message_id VARCHAR(255); +``` + +## Architecture + +### Smart Proxy Benefits +- **No Disk Storage**: Emails/attachments streamed directly from Gmail +- **Low Storage Footprint**: Only metadata stored in database +- **Fresh Content**: Always serves latest version from Gmail +- **Scalable**: No file management overhead +- **On-Demand**: Content fetched only when requested + +### Processing Flow +1. **Index Mode**: Scans Gmail, stores metadata, creates associations +2. **Server Mode**: Receives HTTP requests, fetches from Gmail, streams to client +3. **Local Mode**: Original file-based processing (backwards compatible) + ## Build ```bash @@ -41,17 +113,28 @@ go build -o vault cmd/vault/main.go ## Dependencies - github.com/jhillyerd/enmime - MIME email parsing -- github.com/google/uuid - UUID generation for unique filenames +- github.com/google/uuid - UUID generation - github.com/go-sql-driver/mysql - MySQL driver +- github.com/gorilla/mux - HTTP router +- golang.org/x/oauth2 - OAuth2 support +- google.golang.org/api/gmail/v1 - Gmail API client ## Database Tables Used -- emails - Main email records +- emails - Main email records with Gmail metadata - email_recipients - To/CC recipients -- email_attachments - File attachments +- email_attachments - Attachment metadata (no file storage) - emails_enquiries - Email to enquiry associations - emails_invoices - Email to invoice associations - emails_purchase_orders - Email to PO associations - emails_jobs - Email to job associations - users - System users -- enquiries, invoices, purchase_orders, jobs - For identifier matching \ No newline at end of file +- enquiries, invoices, purchase_orders, jobs - For identifier matching + +## Gmail Query Examples + +- `is:unread` - Unread emails +- `newer_than:1d` - Emails from last 24 hours +- `from:customer@example.com` - From specific sender +- `subject:invoice` - Subject contains "invoice" +- `has:attachment` - Emails with attachments \ No newline at end of file diff --git a/go-app/cmd/vault/main.go b/go-app/cmd/vault/main.go index 45d1cfa9..8917a204 100644 --- a/go-app/cmd/vault/main.go +++ b/go-app/cmd/vault/main.go @@ -2,11 +2,15 @@ package main import ( "bytes" + "context" "database/sql" + "encoding/base64" + "encoding/json" "flag" "fmt" "io/ioutil" "log" + "net/http" "os" "path/filepath" "regexp" @@ -15,39 +19,82 @@ import ( _ "github.com/go-sql-driver/mysql" "github.com/google/uuid" + "github.com/gorilla/mux" "github.com/jhillyerd/enmime" + "golang.org/x/oauth2" + "golang.org/x/oauth2/google" + "google.golang.org/api/gmail/v1" + "google.golang.org/api/option" ) type Config struct { - EmailDir string - VaultDir string - ProcessedDir string - DBHost string - DBUser string - DBPassword string - DBName string + Mode string + EmailDir string + VaultDir string + ProcessedDir string + DBHost string + DBUser string + DBPassword string + DBName string + Port string + CredentialsFile string + TokenFile string + GmailQuery string +} + +type VaultService struct { + db *sql.DB + config Config + gmailService *gmail.Service + indexer *GmailIndexer + processor *EmailProcessor + server *HTTPServer } type EmailProcessor struct { - db *sql.DB - config Config - enquiryMap map[string]int - invoiceMap map[string]int - poMap map[string]int - userMap map[string]int - jobMap map[string]int + db *sql.DB + config Config + enquiryMap map[string]int + invoiceMap map[string]int + poMap map[string]int + userMap map[string]int + jobMap map[string]int } -type Attachment struct { - Type string - Name string - Filename string - Size int64 - IsMessageBody int +type GmailIndexer struct { + db *sql.DB + gmailService *gmail.Service + processor *EmailProcessor +} + +type HTTPServer struct { + db *sql.DB + gmailService *gmail.Service + processor *EmailProcessor +} + +type EmailMetadata struct { + Subject string + From []string + To []string + CC []string + Date time.Time + GmailMessageID string + GmailThreadID string + AttachmentCount int + Attachments []AttachmentMeta +} + +type AttachmentMeta struct { + Filename string + ContentType string + Size int + GmailAttachmentID string } func main() { var config Config + flag.StringVar(&config.Mode, "mode", "serve", "Mode: index, serve, or local") flag.StringVar(&config.EmailDir, "emaildir", "/var/www/emails", "Email storage directory") flag.StringVar(&config.VaultDir, "vaultdir", "/var/www/vaultmsgs/new", "Vault messages directory") flag.StringVar(&config.ProcessedDir, "processeddir", "/var/www/vaultmsgs/cur", "Processed messages directory") @@ -55,17 +102,23 @@ func main() { flag.StringVar(&config.DBUser, "dbuser", "cmc", "Database user") flag.StringVar(&config.DBPassword, "dbpass", "xVRQI&cA?7AU=hqJ!%au", "Database password") flag.StringVar(&config.DBName, "dbname", "cmc", "Database name") + flag.StringVar(&config.Port, "port", "8080", "HTTP server port") + flag.StringVar(&config.CredentialsFile, "credentials", "credentials.json", "Gmail credentials file") + flag.StringVar(&config.TokenFile, "token", "token.json", "Gmail token file") + flag.StringVar(&config.GmailQuery, "gmail-query", "is:unread", "Gmail search query") flag.Parse() + // Connect to database dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?parseTime=true", config.DBUser, config.DBPassword, config.DBHost, config.DBName) - + db, err := sql.Open("mysql", dsn) if err != nil { log.Fatal("Failed to connect to database:", err) } defer db.Close() + // Create processor processor := &EmailProcessor{ db: db, config: config, @@ -75,11 +128,623 @@ func main() { log.Fatal("Failed to load maps:", err) } - if err := processor.processEmails(); err != nil { - log.Fatal("Failed to process emails:", err) + // Create vault service + service := &VaultService{ + db: db, + config: config, + processor: processor, + } + + switch config.Mode { + case "index": + // Initialize Gmail service + gmailService, err := getGmailService(config.CredentialsFile, config.TokenFile) + if err != nil { + log.Fatal("Failed to get Gmail service:", err) + } + service.gmailService = gmailService + + // Create and run indexer + service.indexer = &GmailIndexer{ + db: db, + gmailService: gmailService, + processor: processor, + } + + if err := service.indexer.IndexEmails(config.GmailQuery); err != nil { + log.Fatal("Failed to index emails:", err) + } + + case "serve": + // Initialize Gmail service + gmailService, err := getGmailService(config.CredentialsFile, config.TokenFile) + if err != nil { + log.Fatal("Failed to get Gmail service:", err) + } + service.gmailService = gmailService + + // Create and start HTTP server + service.server = &HTTPServer{ + db: db, + gmailService: gmailService, + processor: processor, + } + + log.Printf("Starting HTTP server on port %s", config.Port) + service.server.Start(config.Port) + + case "local": + // Original file-based processing + if err := processor.processEmails(); err != nil { + log.Fatal("Failed to process emails:", err) + } + + default: + log.Fatal("Invalid mode. Use: index, serve, or local") } } +// Gmail OAuth2 functions +func getGmailService(credentialsFile, tokenFile string) (*gmail.Service, error) { + ctx := context.Background() + + b, err := ioutil.ReadFile(credentialsFile) + if err != nil { + return nil, fmt.Errorf("unable to read client secret file: %v", err) + } + + config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope) + if err != nil { + return nil, fmt.Errorf("unable to parse client secret file to config: %v", err) + } + + client := getClient(config, tokenFile) + srv, err := gmail.NewService(ctx, option.WithHTTPClient(client)) + if err != nil { + return nil, fmt.Errorf("unable to retrieve Gmail client: %v", err) + } + + return srv, nil +} + +func getClient(config *oauth2.Config, tokFile string) *http.Client { + tok, err := tokenFromFile(tokFile) + if err != nil { + tok = getTokenFromWeb(config) + saveToken(tokFile, tok) + } + return config.Client(context.Background(), tok) +} + +func getTokenFromWeb(config *oauth2.Config) *oauth2.Token { + authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) + fmt.Printf("Go to the following link in your browser then type the authorization code: \n%v\n", authURL) + + var authCode string + if _, err := fmt.Scan(&authCode); err != nil { + log.Fatalf("Unable to read authorization code: %v", err) + } + + tok, err := config.Exchange(context.TODO(), authCode) + if err != nil { + log.Fatalf("Unable to retrieve token from web: %v", err) + } + return tok +} + +func tokenFromFile(file string) (*oauth2.Token, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + tok := &oauth2.Token{} + err = json.NewDecoder(f).Decode(tok) + return tok, err +} + +func saveToken(path string, token *oauth2.Token) { + fmt.Printf("Saving credential file to: %s\n", path) + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + log.Fatalf("Unable to cache oauth token: %v", err) + } + defer f.Close() + json.NewEncoder(f).Encode(token) +} + +// GmailIndexer methods +func (g *GmailIndexer) IndexEmails(query string) error { + user := "me" + var pageToken string + + for { + // List messages with query + call := g.gmailService.Users.Messages.List(user).Q(query).MaxResults(500) + if pageToken != "" { + call = call.PageToken(pageToken) + } + + response, err := call.Do() + if err != nil { + return fmt.Errorf("unable to retrieve messages: %v", err) + } + + // Process each message + for _, msg := range response.Messages { + if err := g.indexMessage(msg.Id); err != nil { + log.Printf("Error indexing message %s: %v", msg.Id, err) + continue + } + } + + // Check for more pages + pageToken = response.NextPageToken + if pageToken == "" { + break + } + + log.Printf("Processed %d messages, continuing with next page...", len(response.Messages)) + } + + return nil +} + +func (g *GmailIndexer) indexMessage(messageID string) error { + // Get message metadata only + message, err := g.gmailService.Users.Messages.Get("me", messageID). + Format("METADATA"). + MetadataHeaders("From", "To", "Cc", "Subject", "Date"). + Do() + if err != nil { + return err + } + + // Extract headers + headers := make(map[string]string) + for _, header := range message.Payload.Headers { + headers[header.Name] = header.Value + } + + // Parse email addresses + toRecipients := g.processor.parseEnmimeAddresses(headers["To"]) + fromRecipients := g.processor.parseEnmimeAddresses(headers["From"]) + ccRecipients := g.processor.parseEnmimeAddresses(headers["Cc"]) + + // Check if we should save this email + saveThis := false + fromKnownUser := false + + for _, email := range toRecipients { + if g.processor.userExists(email) { + saveThis = true + } + } + + for _, email := range fromRecipients { + if g.processor.userExists(email) { + saveThis = true + fromKnownUser = true + } + } + + for _, email := range ccRecipients { + if g.processor.userExists(email) { + saveThis = true + } + } + + subject := headers["Subject"] + if subject == "" { + return nil // Skip emails without subject + } + + // Check for identifiers in subject + foundEnquiries := g.processor.checkIdentifier(subject, g.processor.enquiryMap, "enquiry") + foundInvoices := g.processor.checkIdentifier(subject, g.processor.invoiceMap, "invoice") + foundPOs := g.processor.checkIdentifier(subject, g.processor.poMap, "purchaseorder") + foundJobs := g.processor.checkIdentifier(subject, g.processor.jobMap, "job") + + foundIdent := len(foundEnquiries) > 0 || len(foundInvoices) > 0 || + len(foundPOs) > 0 || len(foundJobs) > 0 + + if fromKnownUser || saveThis || foundIdent { + // Parse date + unixTime := time.Now().Unix() + if dateStr := headers["Date"]; dateStr != "" { + if t, err := time.Parse(time.RFC1123Z, dateStr); err == nil { + unixTime = t.Unix() + } + } + + // Get recipient user IDs + recipientIDs := make(map[string][]int) + recipientIDs["to"] = g.processor.getUserIDs(toRecipients) + recipientIDs["from"] = g.processor.getUserIDs(fromRecipients) + recipientIDs["cc"] = g.processor.getUserIDs(ccRecipients) + + if len(recipientIDs["from"]) == 0 { + return nil // Skip if no from recipient + } + + // Marshal headers for storage + headerJSON, _ := json.Marshal(headers) + + // Count attachments (from message metadata) + attachmentCount := 0 + if message.Payload != nil { + attachmentCount = countAttachments(message.Payload) + } + + fmt.Printf("Indexing message: %s - Subject: %s\n", messageID, subject) + + // Save to database + if err := g.saveEmailMetadata(messageID, message.ThreadId, subject, string(headerJSON), + unixTime, recipientIDs, attachmentCount, message.Payload, + foundEnquiries, foundInvoices, foundPOs, foundJobs); err != nil { + return err + } + } + + return nil +} + +func countAttachments(payload *gmail.MessagePart) int { + count := 0 + if payload.Body != nil && payload.Body.AttachmentId != "" { + count++ + } + for _, part := range payload.Parts { + count += countAttachments(part) + } + return count +} + +func (g *GmailIndexer) saveEmailMetadata(gmailMessageID, threadID, subject, headers string, + unixTime int64, recipientIDs map[string][]int, attachmentCount int, + payload *gmail.MessagePart, foundEnquiries, foundInvoices, foundPOs, foundJobs []int) error { + + tx, err := g.db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + // Insert email + result, err := tx.Exec( + `INSERT INTO emails (user_id, udate, created, subject, gmail_message_id, + gmail_thread_id, raw_headers, is_downloaded, email_attachment_count) + VALUES (?, ?, NOW(), ?, ?, ?, ?, FALSE, ?)`, + recipientIDs["from"][0], unixTime, subject, gmailMessageID, + threadID, headers, attachmentCount) + + if err != nil { + return err + } + + emailID, err := result.LastInsertId() + if err != nil { + return err + } + + // Insert recipients + for recipType, userIDs := range recipientIDs { + for _, userID := range userIDs { + if recipType == "from" { + continue // From is already stored in emails.user_id + } + _, err = tx.Exec( + "INSERT INTO email_recipients (email_id, user_id, type) VALUES (?, ?, ?)", + emailID, userID, recipType) + if err != nil { + return err + } + } + } + + // Index attachment metadata + if payload != nil { + if err := g.indexAttachments(tx, emailID, gmailMessageID, payload); err != nil { + return err + } + } + + // Insert associations + for _, jobID := range foundJobs { + _, err = tx.Exec("INSERT INTO emails_jobs (email_id, job_id) VALUES (?, ?)", emailID, jobID) + if err != nil { + return err + } + } + + for _, poID := range foundPOs { + _, err = tx.Exec("INSERT INTO emails_purchase_orders (email_id, purchase_order_id) VALUES (?, ?)", emailID, poID) + if err != nil { + return err + } + } + + for _, enqID := range foundEnquiries { + _, err = tx.Exec("INSERT INTO emails_enquiries (email_id, enquiry_id) VALUES (?, ?)", emailID, enqID) + if err != nil { + return err + } + } + + for _, invID := range foundInvoices { + _, err = tx.Exec("INSERT INTO emails_invoices (email_id, invoice_id) VALUES (?, ?)", emailID, invID) + if err != nil { + return err + } + } + + return tx.Commit() +} + +func (g *GmailIndexer) indexAttachments(tx *sql.Tx, emailID int64, gmailMessageID string, part *gmail.MessagePart) error { + // Check if this part is an attachment + if part.Body != nil && part.Body.AttachmentId != "" { + filename := part.Filename + if filename == "" { + filename = "attachment" + } + + _, err := tx.Exec( + `INSERT INTO email_attachments + (email_id, gmail_attachment_id, gmail_message_id, type, size, filename, is_message_body, created) + VALUES (?, ?, ?, ?, ?, ?, 0, NOW())`, + emailID, part.Body.AttachmentId, gmailMessageID, part.MimeType, part.Body.Size, filename) + if err != nil { + return err + } + } + + // Process sub-parts + for _, subPart := range part.Parts { + if err := g.indexAttachments(tx, emailID, gmailMessageID, subPart); err != nil { + return err + } + } + + return nil +} + +// HTTPServer methods +func (s *HTTPServer) Start(port string) { + router := mux.NewRouter() + + // API routes + router.HandleFunc("/api/emails", s.ListEmails).Methods("GET") + router.HandleFunc("/api/emails/{id:[0-9]+}", s.GetEmail).Methods("GET") + router.HandleFunc("/api/emails/{id:[0-9]+}/content", s.StreamEmailContent).Methods("GET") + router.HandleFunc("/api/emails/{id:[0-9]+}/attachments", s.ListAttachments).Methods("GET") + router.HandleFunc("/api/emails/{id:[0-9]+}/attachments/{attachmentId:[0-9]+}", s.StreamAttachment).Methods("GET") + router.HandleFunc("/api/emails/{id:[0-9]+}/raw", s.StreamRawEmail).Methods("GET") + + log.Fatal(http.ListenAndServe(":"+port, router)) +} + +func (s *HTTPServer) ListEmails(w http.ResponseWriter, r *http.Request) { + // TODO: Add pagination + rows, err := s.db.Query(` + SELECT id, subject, user_id, created, gmail_message_id, email_attachment_count + FROM emails + ORDER BY created DESC + LIMIT 100`) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer rows.Close() + + var emails []map[string]interface{} + for rows.Next() { + var id, userID, attachmentCount int + var subject, gmailMessageID string + var created time.Time + + if err := rows.Scan(&id, &subject, &userID, &created, &gmailMessageID, &attachmentCount); err != nil { + continue + } + + emails = append(emails, map[string]interface{}{ + "id": id, + "subject": subject, + "user_id": userID, + "created": created, + "gmail_message_id": gmailMessageID, + "attachment_count": attachmentCount, + }) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(emails) +} + +func (s *HTTPServer) GetEmail(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID := vars["id"] + + var gmailMessageID, subject, rawHeaders string + var created time.Time + + err := s.db.QueryRow(` + SELECT gmail_message_id, subject, created, raw_headers + FROM emails WHERE id = ?`, emailID). + Scan(&gmailMessageID, &subject, &created, &rawHeaders) + + if err != nil { + http.Error(w, "Email not found", http.StatusNotFound) + return + } + + response := map[string]interface{}{ + "id": emailID, + "gmail_message_id": gmailMessageID, + "subject": subject, + "created": created, + "headers": rawHeaders, + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(response) +} + +func (s *HTTPServer) StreamEmailContent(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID := vars["id"] + + // Get Gmail message ID from database + var gmailMessageID string + err := s.db.QueryRow("SELECT gmail_message_id FROM emails WHERE id = ?", emailID). + Scan(&gmailMessageID) + if err != nil { + http.Error(w, "Email not found", http.StatusNotFound) + return + } + + // Fetch from Gmail + message, err := s.gmailService.Users.Messages.Get("me", gmailMessageID). + Format("RAW").Do() + if err != nil { + http.Error(w, "Failed to fetch email from Gmail", http.StatusInternalServerError) + return + } + + // Decode message + rawEmail, err := base64.URLEncoding.DecodeString(message.Raw) + if err != nil { + http.Error(w, "Failed to decode email", http.StatusInternalServerError) + return + } + + // Parse with enmime + env, err := enmime.ReadEnvelope(bytes.NewReader(rawEmail)) + if err != nil { + http.Error(w, "Failed to parse email", http.StatusInternalServerError) + return + } + + // Stream HTML or Text directly to client + if env.HTML != "" { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write([]byte(env.HTML)) + } else if env.Text != "" { + w.Header().Set("Content-Type", "text/plain; charset=utf-8") + w.Write([]byte(env.Text)) + } else { + http.Error(w, "No content found in email", http.StatusNotFound) + } +} + +func (s *HTTPServer) ListAttachments(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID := vars["id"] + + rows, err := s.db.Query(` + SELECT id, filename, type, size, gmail_attachment_id + FROM email_attachments + WHERE email_id = ?`, emailID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer rows.Close() + + var attachments []map[string]interface{} + for rows.Next() { + var id, size int + var filename, contentType, gmailAttachmentID string + + if err := rows.Scan(&id, &filename, &contentType, &size, &gmailAttachmentID); err != nil { + continue + } + + attachments = append(attachments, map[string]interface{}{ + "id": id, + "filename": filename, + "content_type": contentType, + "size": size, + "gmail_attachment_id": gmailAttachmentID, + }) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(attachments) +} + +func (s *HTTPServer) StreamAttachment(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + attachmentID := vars["attachmentId"] + + // Get attachment info from database + var gmailMessageID, gmailAttachmentID, filename, contentType string + err := s.db.QueryRow(` + SELECT gmail_message_id, gmail_attachment_id, filename, type + FROM email_attachments + WHERE id = ?`, attachmentID). + Scan(&gmailMessageID, &gmailAttachmentID, &filename, &contentType) + + if err != nil { + http.Error(w, "Attachment not found", http.StatusNotFound) + return + } + + // Fetch from Gmail + attachment, err := s.gmailService.Users.Messages.Attachments. + Get("me", gmailMessageID, gmailAttachmentID).Do() + if err != nil { + http.Error(w, "Failed to fetch attachment from Gmail", http.StatusInternalServerError) + return + } + + // Decode base64 + data, err := base64.URLEncoding.DecodeString(attachment.Data) + if err != nil { + http.Error(w, "Failed to decode attachment", http.StatusInternalServerError) + return + } + + // Set headers and stream + w.Header().Set("Content-Type", contentType) + w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s\"", filename)) + w.Header().Set("Content-Length", fmt.Sprintf("%d", len(data))) + w.Write(data) +} + +func (s *HTTPServer) StreamRawEmail(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID := vars["id"] + + // Get Gmail message ID + var gmailMessageID string + err := s.db.QueryRow("SELECT gmail_message_id FROM emails WHERE id = ?", emailID). + Scan(&gmailMessageID) + if err != nil { + http.Error(w, "Email not found", http.StatusNotFound) + return + } + + // Fetch from Gmail + message, err := s.gmailService.Users.Messages.Get("me", gmailMessageID). + Format("RAW").Do() + if err != nil { + http.Error(w, "Failed to fetch email from Gmail", http.StatusInternalServerError) + return + } + + // Decode and stream + rawEmail, err := base64.URLEncoding.DecodeString(message.Raw) + if err != nil { + http.Error(w, "Failed to decode email", http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "message/rfc822") + w.Write(rawEmail) +} + +// Original EmailProcessor methods (kept for local mode and shared logic) func (p *EmailProcessor) loadMaps() error { p.enquiryMap = make(map[string]int) p.invoiceMap = make(map[string]int) @@ -243,7 +908,7 @@ func (p *EmailProcessor) processEmail(filename string) error { foundPOs := p.checkIdentifier(subject, p.poMap, "purchaseorder") foundJobs := p.checkIdentifier(subject, p.jobMap, "job") - foundIdent := len(foundEnquiries) > 0 || len(foundInvoices) > 0 || + foundIdent := len(foundEnquiries) > 0 || len(foundInvoices) > 0 || len(foundPOs) > 0 || len(foundJobs) > 0 if fromKnownUser || saveThis || foundIdent { @@ -327,11 +992,14 @@ func (p *EmailProcessor) getUserIDs(emails []string) []int { func (p *EmailProcessor) createUser(email string) int { fmt.Printf("Making a new User for: '%s'\n", email) - + result, err := p.db.Exec( - "INSERT INTO users (type, email, by_vault, created, modified) VALUES (?, ?, ?, NOW(), NOW())", - "contact", strings.ToLower(email), 1) - + `INSERT INTO users (principle_id, customer_id, type, access_level, username, password, + first_name, last_name, email, job_title, phone, mobile, fax, phone_extension, + direct_phone, notes, by_vault, blacklisted, enabled, primary_contact) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + 0, 0, "contact", "none", "", "", "", "", strings.ToLower(email), "", "", "", "", "", "", "", 1, 0, 1, 0) + if err != nil { fmt.Printf("Serious Error: Unable to create user for email '%s': %v\n", email, err) return 0 @@ -407,7 +1075,7 @@ func (p *EmailProcessor) extractEnmimeAttachments(env *enmime.Envelope, relative fileName := "texthtml" newFileName := uuid + "-" + fileName filePath := filepath.Join(outputDir, newFileName) - + if err := ioutil.WriteFile(filePath, htmlData, 0644); err == nil { att := Attachment{ Type: "text/html", @@ -428,7 +1096,7 @@ func (p *EmailProcessor) extractEnmimeAttachments(env *enmime.Envelope, relative fileName := "textplain" newFileName := uuid + "-" + fileName filePath := filepath.Join(outputDir, newFileName) - + if err := ioutil.WriteFile(filePath, textData, 0644); err == nil { att := Attachment{ Type: "text/plain", @@ -449,10 +1117,10 @@ func (p *EmailProcessor) extractEnmimeAttachments(env *enmime.Envelope, relative if fileName == "" { fileName = "attachment" } - + newFileName := uuid + "-" + fileName filePath := filepath.Join(outputDir, newFileName) - + if err := ioutil.WriteFile(filePath, part.Content, 0644); err != nil { log.Printf("Failed to save attachment %s: %v", fileName, err) continue @@ -485,10 +1153,10 @@ func (p *EmailProcessor) extractEnmimeAttachments(env *enmime.Envelope, relative if fileName == "" { fileName = "inline" } - + newFileName := uuid + "-" + fileName filePath := filepath.Join(outputDir, newFileName) - + if err := ioutil.WriteFile(filePath, part.Content, 0644); err != nil { log.Printf("Failed to save inline part %s: %v", fileName, err) continue @@ -525,7 +1193,7 @@ func (p *EmailProcessor) extractEnmimeAttachments(env *enmime.Envelope, relative return attachments } -func (p *EmailProcessor) saveEmail(filename, subject string, unixTime int64, +func (p *EmailProcessor) saveEmail(filename, subject string, unixTime int64, recipientIDs map[string][]int, attachments []Attachment, foundEnquiries, foundInvoices, foundPOs, foundJobs []int) error { @@ -537,9 +1205,9 @@ func (p *EmailProcessor) saveEmail(filename, subject string, unixTime int64, // Insert email result, err := tx.Exec( - "INSERT INTO emails (user_id, udate, created, subject, filename) VALUES (?, ?, NOW(), ?, ?)", - recipientIDs["from"][0], unixTime, subject, filename) - + "INSERT INTO emails (user_id, udate, created, subject) VALUES (?, ?, NOW(), ?)", + recipientIDs["from"][0], unixTime, subject) + if err != nil { return err } @@ -621,4 +1289,12 @@ func (p *EmailProcessor) moveEmail(filename string) error { } return nil -} \ No newline at end of file +} + +type Attachment struct { + Type string + Name string + Filename string + Size int64 + IsMessageBody int +} diff --git a/go-app/go.mod b/go-app/go.mod index 982ff1aa..b5904ead 100644 --- a/go-app/go.mod +++ b/go-app/go.mod @@ -1,6 +1,8 @@ module code.springupsoftware.com/cmc/cmc-sales -go 1.23 +go 1.23.0 + +toolchain go1.24.4 require ( github.com/go-sql-driver/mysql v1.7.1 @@ -9,17 +11,38 @@ require ( github.com/jhillyerd/enmime v1.3.0 github.com/joho/godotenv v1.5.1 github.com/jung-kurt/gofpdf v1.16.2 + golang.org/x/oauth2 v0.30.0 + google.golang.org/api v0.244.0 ) require ( + cloud.google.com/go/auth v0.16.3 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + cloud.google.com/go/compute/metadata v0.7.0 // indirect github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f // indirect + github.com/google/s2a-go v0.1.9 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect + github.com/googleapis/gax-go/v2 v2.15.0 // indirect github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056 // indirect github.com/mattn/go-runewidth v0.0.15 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/rivo/uniseg v0.4.4 // indirect github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect - golang.org/x/net v0.23.0 // indirect - golang.org/x/text v0.14.0 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect + go.opentelemetry.io/otel v1.36.0 // indirect + go.opentelemetry.io/otel/metric v1.36.0 // indirect + go.opentelemetry.io/otel/trace v1.36.0 // indirect + golang.org/x/crypto v0.40.0 // indirect + golang.org/x/net v0.42.0 // indirect + golang.org/x/sys v0.34.0 // indirect + golang.org/x/text v0.27.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250728155136-f173205681a0 // indirect + google.golang.org/grpc v1.74.2 // indirect + google.golang.org/protobuf v1.36.6 // indirect ) diff --git a/go-app/go.sum b/go-app/go.sum index a7a25f89..8366941a 100644 --- a/go-app/go.sum +++ b/go-app/go.sum @@ -1,13 +1,40 @@ +cloud.google.com/go/auth v0.16.3 h1:kabzoQ9/bobUmnseYnBO6qQG7q4a/CffFRlJSxv2wCc= +cloud.google.com/go/auth v0.16.3/go.mod h1:NucRGjaXfzP1ltpcQ7On/VTZ0H4kWB5Jy+Y9Dnm76fA= +cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= +cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a h1:MISbI8sU/PSK/ztvmWKFcI7UGb5/HQT7B+i3a2myKgI= github.com/cention-sany/utf7 v0.0.0-20170124080048-26cad61bd60a/go.mod h1:2GxOXOlEPAMFPfp014mK1SWq8G8BN8o7/dfYqJrVGn8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +github.com/go-test/deep v1.1.0 h1:WOcxcdHcvdgThNXjw0t76K42FXTU7HpNQWHpA2HHNlg= +github.com/go-test/deep v1.1.0/go.mod h1:5C2ZWiW0ErCdrYzpqxLbTX7MG14M9iiw8DgHncVwcsE= github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f h1:3BSP1Tbs2djlpprl7wCLuiqMaUh5SJkkzI2gDs+FgLs= github.com/gogs/chardet v0.0.0-20211120154057-b7413eaefb8f/go.mod h1:Pcatq5tYkCW2Q6yrR2VRHlbHpZ/R4/7qyL1TCF7vl14= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= +github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/gax-go/v2 v2.15.0 h1:SyjDc1mGgZU5LncH8gimWo9lW1DtIfPibOG81vgd/bo= +github.com/googleapis/gax-go/v2 v2.15.0/go.mod h1:zVVkkxAQHa1RQpg9z2AUCMnKhi0Qld9rcmyfL1OZhoc= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/jaytaylor/html2text v0.0.0-20230321000545-74c2419ad056 h1:iCHtR9CQyktQ5+f3dMVZfwD2KWJUgm7M0gdL9NGr8KA= @@ -28,6 +55,7 @@ github.com/phpdave11/gofpdi v1.0.7/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis= @@ -36,9 +64,47 @@ github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfF github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/otel v1.36.0 h1:UumtzIklRBY6cI/lllNZlALOF5nNIzJVb16APdvgTXg= +go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E= +go.opentelemetry.io/otel/metric v1.36.0 h1:MoWPKVhQvJ+eeXWHFBOPoBOi20jh6Iq2CcCREuTYufE= +go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs= +go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs= +go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY= +go.opentelemetry.io/otel/sdk/metric v1.36.0 h1:r0ntwwGosWGaa0CrSt8cuNuTcccMXERFwHX4dThiPis= +go.opentelemetry.io/otel/sdk/metric v1.36.0/go.mod h1:qTNOhFDfKRwX0yXOqJYegL5WRaW376QbB7P4Pb0qva4= +go.opentelemetry.io/otel/trace v1.36.0 h1:ahxWNuqZjpdiFAyrIoQ4GIiAIhxAunQR6MUoKrsNd4w= +go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA= +golang.org/x/crypto v0.40.0 h1:r4x+VvoG5Fm+eJcxMaY8CQM7Lb0l1lsmjGBQ6s8BfKM= +golang.org/x/crypto v0.40.0/go.mod h1:Qr1vMER5WyS2dfPHAlsOj01wgLbsyWtFn/aY+5+ZdxY= golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= -golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs= -golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= +golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= +golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= +golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw= +golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= +golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= -golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4= +golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU= +google.golang.org/api v0.244.0 h1:lpkP8wVibSKr++NCD36XzTk/IzeKJ3klj7vbj+XU5pE= +google.golang.org/api v0.244.0/go.mod h1:dMVhVcylamkirHdzEBAIQWUCgqY885ivNeZYd7VAVr8= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= +google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250728155136-f173205681a0 h1:MAKi5q709QWfnkkpNQ0M12hYJ1+e8qYVDyowc4U1XZM= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250728155136-f173205681a0/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4= +google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM= +google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= +google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/go-app/goose.env.example b/go-app/goose.env.example new file mode 100644 index 00000000..c40a0103 --- /dev/null +++ b/go-app/goose.env.example @@ -0,0 +1,3 @@ +GOOSE_DRIVER=mysql +GOOSE_DBSTRING=username:password@tcp(localhost:3306)/database?parseTime=true +GOOSE_MIGRATION_DIR=sql/migrations \ No newline at end of file diff --git a/go-app/internal/cmc/handlers/emails.go b/go-app/internal/cmc/handlers/emails.go new file mode 100644 index 00000000..b34caae1 --- /dev/null +++ b/go-app/internal/cmc/handlers/emails.go @@ -0,0 +1,870 @@ +package handlers + +import ( + "bytes" + "context" + "database/sql" + "encoding/base64" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "os" + "strconv" + "strings" + "time" + + "code.springupsoftware.com/cmc/cmc-sales/internal/cmc/db" + "github.com/gorilla/mux" + "github.com/jhillyerd/enmime" + "golang.org/x/oauth2" + "golang.org/x/oauth2/google" + "google.golang.org/api/gmail/v1" + "google.golang.org/api/option" +) + +type EmailHandler struct { + queries *db.Queries + db *sql.DB + gmailService *gmail.Service +} + +type EmailResponse struct { + ID int32 `json:"id"` + Subject string `json:"subject"` + UserID int32 `json:"user_id"` + Created time.Time `json:"created"` + GmailMessageID *string `json:"gmail_message_id,omitempty"` + AttachmentCount int32 `json:"attachment_count"` + IsDownloaded *bool `json:"is_downloaded,omitempty"` +} + +type EmailDetailResponse struct { + ID int32 `json:"id"` + Subject string `json:"subject"` + UserID int32 `json:"user_id"` + Created time.Time `json:"created"` + GmailMessageID *string `json:"gmail_message_id,omitempty"` + GmailThreadID *string `json:"gmail_thread_id,omitempty"` + RawHeaders *string `json:"raw_headers,omitempty"` + IsDownloaded *bool `json:"is_downloaded,omitempty"` + Enquiries []int32 `json:"enquiries,omitempty"` + Invoices []int32 `json:"invoices,omitempty"` + PurchaseOrders []int32 `json:"purchase_orders,omitempty"` + Jobs []int32 `json:"jobs,omitempty"` +} + +type EmailAttachmentResponse struct { + ID int32 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Size int32 `json:"size"` + Filename string `json:"filename"` + IsMessageBody bool `json:"is_message_body"` + GmailAttachmentID *string `json:"gmail_attachment_id,omitempty"` + Created time.Time `json:"created"` +} + +func NewEmailHandler(queries *db.Queries, database *sql.DB) *EmailHandler { + // Try to initialize Gmail service + gmailService, err := getGmailService("credentials.json", "token.json") + if err != nil { + // Log the error but continue without Gmail service + fmt.Printf("Warning: Gmail service not available: %v\n", err) + } + + return &EmailHandler{ + queries: queries, + db: database, + gmailService: gmailService, + } +} + +// List emails with pagination and filtering +func (h *EmailHandler) List(w http.ResponseWriter, r *http.Request) { + // Parse query parameters + limitStr := r.URL.Query().Get("limit") + offsetStr := r.URL.Query().Get("offset") + search := r.URL.Query().Get("search") + userID := r.URL.Query().Get("user_id") + + // Set defaults + limit := 50 + offset := 0 + + if limitStr != "" { + if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 { + limit = l + } + } + + if offsetStr != "" { + if o, err := strconv.Atoi(offsetStr); err == nil && o >= 0 { + offset = o + } + } + + // Build query + query := ` + SELECT e.id, e.subject, e.user_id, e.created, e.gmail_message_id, e.email_attachment_count, e.is_downloaded + FROM emails e` + + var args []interface{} + var conditions []string + + if search != "" { + conditions = append(conditions, "e.subject LIKE ?") + args = append(args, "%"+search+"%") + } + + if userID != "" { + conditions = append(conditions, "e.user_id = ?") + args = append(args, userID) + } + + if len(conditions) > 0 { + query += " WHERE " + joinConditions(conditions, " AND ") + } + + query += " ORDER BY e.id DESC LIMIT ? OFFSET ?" + args = append(args, limit, offset) + + rows, err := h.db.Query(query, args...) + if err != nil { + http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError) + return + } + defer rows.Close() + + var emails []EmailResponse + for rows.Next() { + var email EmailResponse + var gmailMessageID sql.NullString + var isDownloaded sql.NullBool + + err := rows.Scan( + &email.ID, + &email.Subject, + &email.UserID, + &email.Created, + &gmailMessageID, + &email.AttachmentCount, + &isDownloaded, + ) + if err != nil { + continue + } + + if gmailMessageID.Valid { + email.GmailMessageID = &gmailMessageID.String + } + if isDownloaded.Valid { + email.IsDownloaded = &isDownloaded.Bool + } + + emails = append(emails, email) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(emails) +} + +// Get a specific email with details +func (h *EmailHandler) Get(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID, err := strconv.Atoi(vars["id"]) + if err != nil { + http.Error(w, "Invalid email ID", http.StatusBadRequest) + return + } + + // Get email details + query := ` + SELECT e.id, e.subject, e.user_id, e.created, e.gmail_message_id, + e.gmail_thread_id, e.raw_headers, e.is_downloaded + FROM emails e + WHERE e.id = ?` + + var email EmailDetailResponse + var gmailMessageID, gmailThreadID, rawHeaders sql.NullString + var isDownloaded sql.NullBool + + err = h.db.QueryRow(query, emailID).Scan( + &email.ID, + &email.Subject, + &email.UserID, + &email.Created, + &gmailMessageID, + &gmailThreadID, + &rawHeaders, + &isDownloaded, + ) + + if err != nil { + if err == sql.ErrNoRows { + http.Error(w, "Email not found", http.StatusNotFound) + } else { + http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError) + } + return + } + + if gmailMessageID.Valid { + email.GmailMessageID = &gmailMessageID.String + } + if gmailThreadID.Valid { + email.GmailThreadID = &gmailThreadID.String + } + if rawHeaders.Valid { + email.RawHeaders = &rawHeaders.String + } + if isDownloaded.Valid { + email.IsDownloaded = &isDownloaded.Bool + } + + // Get associated enquiries + enquiryRows, err := h.db.Query("SELECT enquiry_id FROM emails_enquiries WHERE email_id = ?", emailID) + if err == nil { + defer enquiryRows.Close() + for enquiryRows.Next() { + var enquiryID int32 + if enquiryRows.Scan(&enquiryID) == nil { + email.Enquiries = append(email.Enquiries, enquiryID) + } + } + } + + // Get associated invoices + invoiceRows, err := h.db.Query("SELECT invoice_id FROM emails_invoices WHERE email_id = ?", emailID) + if err == nil { + defer invoiceRows.Close() + for invoiceRows.Next() { + var invoiceID int32 + if invoiceRows.Scan(&invoiceID) == nil { + email.Invoices = append(email.Invoices, invoiceID) + } + } + } + + // Get associated purchase orders + poRows, err := h.db.Query("SELECT purchase_order_id FROM emails_purchase_orders WHERE email_id = ?", emailID) + if err == nil { + defer poRows.Close() + for poRows.Next() { + var poID int32 + if poRows.Scan(&poID) == nil { + email.PurchaseOrders = append(email.PurchaseOrders, poID) + } + } + } + + // Get associated jobs + jobRows, err := h.db.Query("SELECT job_id FROM emails_jobs WHERE email_id = ?", emailID) + if err == nil { + defer jobRows.Close() + for jobRows.Next() { + var jobID int32 + if jobRows.Scan(&jobID) == nil { + email.Jobs = append(email.Jobs, jobID) + } + } + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(email) +} + +// List attachments for an email +func (h *EmailHandler) ListAttachments(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID, err := strconv.Atoi(vars["id"]) + if err != nil { + http.Error(w, "Invalid email ID", http.StatusBadRequest) + return + } + + // First check if attachments are already in database + query := ` + SELECT id, name, type, size, filename, is_message_body, gmail_attachment_id, created + FROM email_attachments + WHERE email_id = ? + ORDER BY is_message_body DESC, created ASC` + + rows, err := h.db.Query(query, emailID) + if err != nil { + http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError) + return + } + defer rows.Close() + + var attachments []EmailAttachmentResponse + hasStoredAttachments := false + + for rows.Next() { + hasStoredAttachments = true + var attachment EmailAttachmentResponse + var gmailAttachmentID sql.NullString + + err := rows.Scan( + &attachment.ID, + &attachment.Name, + &attachment.Type, + &attachment.Size, + &attachment.Filename, + &attachment.IsMessageBody, + &gmailAttachmentID, + &attachment.Created, + ) + if err != nil { + continue + } + + if gmailAttachmentID.Valid { + attachment.GmailAttachmentID = &gmailAttachmentID.String + } + + attachments = append(attachments, attachment) + } + + // If no stored attachments and this is a Gmail email, try to fetch from Gmail + if !hasStoredAttachments && h.gmailService != nil { + // Get Gmail message ID + var gmailMessageID sql.NullString + err := h.db.QueryRow("SELECT gmail_message_id FROM emails WHERE id = ?", emailID).Scan(&gmailMessageID) + + if err == nil && gmailMessageID.Valid { + // Fetch message metadata from Gmail + message, err := h.gmailService.Users.Messages.Get("me", gmailMessageID.String). + Format("FULL").Do() + + if err == nil && message.Payload != nil { + // Extract attachment info from Gmail message + attachmentIndex := int32(1) + h.extractGmailAttachments(message.Payload, &attachments, &attachmentIndex) + } + } + } + + // Check if this is an HTMX request + if r.Header.Get("HX-Request") == "true" { + // Return HTML for HTMX + w.Header().Set("Content-Type", "text/html; charset=utf-8") + + if len(attachments) == 0 { + // No attachments found + html := `
+

No attachments found for this email.

+
` + w.Write([]byte(html)) + return + } + + // Build HTML table for attachments + var htmlBuilder strings.Builder + htmlBuilder.WriteString(`
+

Attachments

+
+ + + + + + + + + + `) + + for _, att := range attachments { + icon := `` + if att.IsMessageBody { + icon = `` + } + + downloadURL := fmt.Sprintf("/api/v1/emails/%d/attachments/%d", emailID, att.ID) + if att.GmailAttachmentID != nil { + downloadURL = fmt.Sprintf("/api/v1/emails/%d/attachments/%d/stream", emailID, att.ID) + } + + htmlBuilder.WriteString(fmt.Sprintf(` + + + + + + `, icon, att.Name, att.Type, att.Size, downloadURL)) + } + + htmlBuilder.WriteString(` + +
NameTypeSizeActions
+ %s + %s + %s%d bytes + + + Download + +
+
+
`) + + w.Write([]byte(htmlBuilder.String())) + return + } + + // Return JSON for API requests + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(attachments) +} + +// Helper function to extract attachment info from Gmail message parts +func (h *EmailHandler) extractGmailAttachments(part *gmail.MessagePart, attachments *[]EmailAttachmentResponse, index *int32) { + // Check if this part is an attachment + // Some attachments may not have filenames or may be inline + if part.Body != nil && part.Body.AttachmentId != "" { + filename := part.Filename + if filename == "" { + // Try to generate a filename from content type + switch part.MimeType { + case "application/pdf": + filename = "attachment.pdf" + case "image/png": + filename = "image.png" + case "image/jpeg": + filename = "image.jpg" + case "text/plain": + filename = "text.txt" + default: + filename = "attachment" + } + } + + attachment := EmailAttachmentResponse{ + ID: *index, + Name: filename, + Type: part.MimeType, + Size: int32(part.Body.Size), + Filename: filename, + IsMessageBody: false, + GmailAttachmentID: &part.Body.AttachmentId, + Created: time.Now(), // Use current time as placeholder + } + *attachments = append(*attachments, attachment) + *index++ + } + + // Process sub-parts + for _, subPart := range part.Parts { + h.extractGmailAttachments(subPart, attachments, index) + } +} + +// Search emails +func (h *EmailHandler) Search(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query().Get("q") + if query == "" { + http.Error(w, "Search query is required", http.StatusBadRequest) + return + } + + // Parse optional parameters + limitStr := r.URL.Query().Get("limit") + limit := 20 + + if limitStr != "" { + if l, err := strconv.Atoi(limitStr); err == nil && l > 0 && l <= 100 { + limit = l + } + } + + // Search in subjects and headers + sqlQuery := ` + SELECT e.id, e.subject, e.user_id, e.created, e.gmail_message_id, e.email_attachment_count, e.is_downloaded + FROM emails e + WHERE e.subject LIKE ? OR e.raw_headers LIKE ? + ORDER BY e.id DESC + LIMIT ?` + + searchTerm := "%" + query + "%" + rows, err := h.db.Query(sqlQuery, searchTerm, searchTerm, limit) + if err != nil { + http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError) + return + } + defer rows.Close() + + var emails []EmailResponse + for rows.Next() { + var email EmailResponse + var gmailMessageID sql.NullString + var isDownloaded sql.NullBool + + err := rows.Scan( + &email.ID, + &email.Subject, + &email.UserID, + &email.Created, + &gmailMessageID, + &email.AttachmentCount, + &isDownloaded, + ) + if err != nil { + continue + } + + if gmailMessageID.Valid { + email.GmailMessageID = &gmailMessageID.String + } + if isDownloaded.Valid { + email.IsDownloaded = &isDownloaded.Bool + } + + emails = append(emails, email) + } + + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(emails) +} + +// Stream email content from Gmail +func (h *EmailHandler) StreamContent(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID, err := strconv.Atoi(vars["id"]) + if err != nil { + http.Error(w, "Invalid email ID", http.StatusBadRequest) + return + } + + // Get email details to check if it's a Gmail email + query := ` + SELECT e.gmail_message_id, e.subject, e.created, e.user_id + FROM emails e + WHERE e.id = ?` + + var gmailMessageID sql.NullString + var subject string + var created time.Time + var userID int32 + + err = h.db.QueryRow(query, emailID).Scan(&gmailMessageID, &subject, &created, &userID) + if err != nil { + if err == sql.ErrNoRows { + http.Error(w, "Email not found", http.StatusNotFound) + } else { + http.Error(w, fmt.Sprintf("Database error: %v", err), http.StatusInternalServerError) + } + return + } + + if !gmailMessageID.Valid { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := ` +
+ Local Email
+ This email is not from Gmail and does not have stored content available for display. +
` + w.Write([]byte(html)) + return + } + + // Check for stored message body content in attachments + attachmentQuery := ` + SELECT id, name, type, size + FROM email_attachments + WHERE email_id = ? AND is_message_body = 1 + ORDER BY created ASC` + + attachmentRows, err := h.db.Query(attachmentQuery, emailID) + if err == nil { + defer attachmentRows.Close() + if attachmentRows.Next() { + var attachmentID int32 + var name, attachmentType string + var size int32 + + if attachmentRows.Scan(&attachmentID, &name, &attachmentType, &size) == nil { + // Found stored message body - would normally read the content from file storage + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := fmt.Sprintf(` +
+
+ Stored Email Content
+ Message body is stored locally as attachment: %s (%s, %d bytes) +
+
+

Content would be loaded from local storage here.

+

Attachment ID: %d

+
+
`, name, attachmentType, size, attachmentID) + w.Write([]byte(html)) + return + } + } + } + + // Try to fetch from Gmail if service is available + if h.gmailService != nil { + // Fetch from Gmail + message, err := h.gmailService.Users.Messages.Get("me", gmailMessageID.String). + Format("RAW").Do() + if err != nil { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := fmt.Sprintf(` +
+ Gmail API Error
+ Failed to fetch email from Gmail: %v +
`, err) + w.Write([]byte(html)) + return + } + + // Decode message + rawEmail, err := base64.URLEncoding.DecodeString(message.Raw) + if err != nil { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := fmt.Sprintf(` +
+ Decode Error
+ Failed to decode email: %v +
`, err) + w.Write([]byte(html)) + return + } + + // Parse with enmime + env, err := enmime.ReadEnvelope(bytes.NewReader(rawEmail)) + if err != nil { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := fmt.Sprintf(` +
+ Parse Error
+ Failed to parse email: %v +
`, err) + w.Write([]byte(html)) + return + } + + // Stream HTML or Text directly to client + if env.HTML != "" { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Write([]byte(env.HTML)) + } else if env.Text != "" { + // Convert plain text to HTML for better display + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := fmt.Sprintf(` +
+
+ Plain Text Email
+ This email contains only plain text content. +
+
+
%s
+
+
`, env.Text) + w.Write([]byte(html)) + } else { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := ` +
+ No Content
+ No HTML or text content found in this email. +
` + w.Write([]byte(html)) + } + return + } + + // No Gmail service available - show error + w.Header().Set("Content-Type", "text/html; charset=utf-8") + html := fmt.Sprintf(` +
+
+ Gmail Service Unavailable
+ Subject: %s
+ Date: %s
+ Gmail Message ID: %s +
+ +
+
+

Integration Status

+

Gmail service is not available. To enable email content display:

+
    +
  1. Ensure credentials.json and token.json files are present
  2. +
  3. Configure Gmail API OAuth2 authentication
  4. +
  5. Restart the application
  6. +
+

+ Gmail Message ID: %s +

+
+
+
`, + subject, + created.Format("2006-01-02 15:04:05"), + gmailMessageID.String, + gmailMessageID.String) + + w.Write([]byte(html)) +} + +// Stream attachment from Gmail +func (h *EmailHandler) StreamAttachment(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + emailID, err := strconv.Atoi(vars["id"]) + if err != nil { + http.Error(w, "Invalid email ID", http.StatusBadRequest) + return + } + + attachmentID := vars["attachmentId"] + + // Get email's Gmail message ID + var gmailMessageID sql.NullString + err = h.db.QueryRow("SELECT gmail_message_id FROM emails WHERE id = ?", emailID).Scan(&gmailMessageID) + if err != nil || !gmailMessageID.Valid { + http.Error(w, "Email not found or not a Gmail email", http.StatusNotFound) + return + } + + if h.gmailService == nil { + http.Error(w, "Gmail service not available", http.StatusServiceUnavailable) + return + } + + // For dynamic attachments, we need to fetch the message and find the attachment + message, err := h.gmailService.Users.Messages.Get("me", gmailMessageID.String). + Format("FULL").Do() + if err != nil { + http.Error(w, "Failed to fetch email from Gmail", http.StatusInternalServerError) + return + } + + // Find the attachment by index + var targetAttachment *gmail.MessagePart + attachmentIndex := 1 + findAttachment(message.Payload, attachmentID, &attachmentIndex, &targetAttachment) + + if targetAttachment == nil || targetAttachment.Body == nil || targetAttachment.Body.AttachmentId == "" { + http.Error(w, "Attachment not found", http.StatusNotFound) + return + } + + // Fetch attachment data from Gmail + attachment, err := h.gmailService.Users.Messages.Attachments. + Get("me", gmailMessageID.String, targetAttachment.Body.AttachmentId).Do() + if err != nil { + http.Error(w, "Failed to fetch attachment from Gmail", http.StatusInternalServerError) + return + } + + // Decode base64 + data, err := base64.URLEncoding.DecodeString(attachment.Data) + if err != nil { + http.Error(w, "Failed to decode attachment", http.StatusInternalServerError) + return + } + + // Set headers and stream + filename := targetAttachment.Filename + if filename == "" { + // Generate filename from content type (same logic as extractGmailAttachments) + switch targetAttachment.MimeType { + case "application/pdf": + filename = "attachment.pdf" + case "image/png": + filename = "image.png" + case "image/jpeg": + filename = "image.jpg" + case "text/plain": + filename = "text.txt" + default: + filename = "attachment" + } + } + + w.Header().Set("Content-Type", targetAttachment.MimeType) + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename)) + w.Header().Set("Content-Length", fmt.Sprintf("%d", len(data))) + w.Write(data) +} + +// Helper function to find attachment by index +func findAttachment(part *gmail.MessagePart, targetID string, currentIndex *int, result **gmail.MessagePart) { + // Check if this part is an attachment (same logic as extractGmailAttachments) + if part.Body != nil && part.Body.AttachmentId != "" { + fmt.Printf("Checking attachment %d (looking for %s): %s\n", *currentIndex, targetID, part.Filename) + if strconv.Itoa(*currentIndex) == targetID { + fmt.Printf("Found matching attachment!\n") + *result = part + return + } + *currentIndex++ + } + + for _, subPart := range part.Parts { + findAttachment(subPart, targetID, currentIndex, result) + if *result != nil { + return + } + } +} + +// Helper function to join conditions +func joinConditions(conditions []string, separator string) string { + if len(conditions) == 0 { + return "" + } + if len(conditions) == 1 { + return conditions[0] + } + + result := conditions[0] + for i := 1; i < len(conditions); i++ { + result += separator + conditions[i] + } + return result +} + +// Gmail OAuth2 functions +func getGmailService(credentialsFile, tokenFile string) (*gmail.Service, error) { + ctx := context.Background() + + b, err := ioutil.ReadFile(credentialsFile) + if err != nil { + return nil, fmt.Errorf("unable to read client secret file: %v", err) + } + + config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope) + if err != nil { + return nil, fmt.Errorf("unable to parse client secret file to config: %v", err) + } + + client := getClient(config, tokenFile) + srv, err := gmail.NewService(ctx, option.WithHTTPClient(client)) + if err != nil { + return nil, fmt.Errorf("unable to retrieve Gmail client: %v", err) + } + + return srv, nil +} + +func getClient(config *oauth2.Config, tokFile string) *http.Client { + tok, err := tokenFromFile(tokFile) + if err != nil { + return nil + } + return config.Client(context.Background(), tok) +} + +func tokenFromFile(file string) (*oauth2.Token, error) { + f, err := os.Open(file) + if err != nil { + return nil, err + } + defer f.Close() + tok := &oauth2.Token{} + err = json.NewDecoder(f).Decode(tok) + return tok, err +} \ No newline at end of file diff --git a/go-app/internal/cmc/handlers/pages.go b/go-app/internal/cmc/handlers/pages.go index 3b79fc4a..e97ca415 100644 --- a/go-app/internal/cmc/handlers/pages.go +++ b/go-app/internal/cmc/handlers/pages.go @@ -1,9 +1,11 @@ package handlers import ( + "database/sql" "log" "net/http" "strconv" + "time" "code.springupsoftware.com/cmc/cmc-sales/internal/cmc/db" "code.springupsoftware.com/cmc/cmc-sales/internal/cmc/templates" @@ -13,12 +15,14 @@ import ( type PageHandler struct { queries *db.Queries tmpl *templates.TemplateManager + db *sql.DB } -func NewPageHandler(queries *db.Queries, tmpl *templates.TemplateManager) *PageHandler { +func NewPageHandler(queries *db.Queries, tmpl *templates.TemplateManager, database *sql.DB) *PageHandler { return &PageHandler{ queries: queries, tmpl: tmpl, + db: database, } } @@ -776,3 +780,404 @@ func (h *PageHandler) DocumentsView(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), http.StatusInternalServerError) } } + +// Email page handlers +func (h *PageHandler) EmailsIndex(w http.ResponseWriter, r *http.Request) { + page := 1 + if p := r.URL.Query().Get("page"); p != "" { + if val, err := strconv.Atoi(p); err == nil && val > 0 { + page = val + } + } + + limit := 30 + offset := (page - 1) * limit + search := r.URL.Query().Get("search") + filter := r.URL.Query().Get("filter") + + // Build SQL query based on filters + query := ` + SELECT e.id, e.subject, e.user_id, e.created, e.gmail_message_id, + e.email_attachment_count, e.is_downloaded, + u.email as user_email, u.first_name, u.last_name + FROM emails e + LEFT JOIN users u ON e.user_id = u.id` + + var args []interface{} + var conditions []string + + // Apply search filter + if search != "" { + conditions = append(conditions, "(e.subject LIKE ? OR e.raw_headers LIKE ?)") + searchTerm := "%" + search + "%" + args = append(args, searchTerm, searchTerm) + } + + // Apply type filter + switch filter { + case "downloaded": + conditions = append(conditions, "e.is_downloaded = 1") + case "gmail": + conditions = append(conditions, "e.gmail_message_id IS NOT NULL") + case "unassociated": + conditions = append(conditions, `NOT EXISTS ( + SELECT 1 FROM emails_enquiries WHERE email_id = e.id + UNION SELECT 1 FROM emails_invoices WHERE email_id = e.id + UNION SELECT 1 FROM emails_purchase_orders WHERE email_id = e.id + UNION SELECT 1 FROM emails_jobs WHERE email_id = e.id + )`) + } + + if len(conditions) > 0 { + query += " WHERE " + joinConditions(conditions, " AND ") + } + + query += " ORDER BY e.id DESC LIMIT ? OFFSET ?" + args = append(args, limit+1, offset) // Get one extra to check if there are more + + // Execute the query to get emails + rows, err := h.db.Query(query, args...) + if err != nil { + log.Printf("Error querying emails: %v", err) + http.Error(w, "Database error", http.StatusInternalServerError) + return + } + defer rows.Close() + + type EmailWithUser struct { + ID int32 `json:"id"` + Subject string `json:"subject"` + UserID int32 `json:"user_id"` + Created time.Time `json:"created"` + GmailMessageID *string `json:"gmail_message_id"` + AttachmentCount int32 `json:"attachment_count"` + IsDownloaded *bool `json:"is_downloaded"` + UserEmail *string `json:"user_email"` + FirstName *string `json:"first_name"` + LastName *string `json:"last_name"` + } + + var emails []EmailWithUser + for rows.Next() { + var email EmailWithUser + var gmailMessageID, userEmail, firstName, lastName sql.NullString + var isDownloaded sql.NullBool + + err := rows.Scan( + &email.ID, + &email.Subject, + &email.UserID, + &email.Created, + &gmailMessageID, + &email.AttachmentCount, + &isDownloaded, + &userEmail, + &firstName, + &lastName, + ) + if err != nil { + log.Printf("Error scanning email row: %v", err) + continue + } + + if gmailMessageID.Valid { + email.GmailMessageID = &gmailMessageID.String + } + if isDownloaded.Valid { + email.IsDownloaded = &isDownloaded.Bool + } + if userEmail.Valid { + email.UserEmail = &userEmail.String + } + if firstName.Valid { + email.FirstName = &firstName.String + } + if lastName.Valid { + email.LastName = &lastName.String + } + + emails = append(emails, email) + } + + hasMore := len(emails) > limit + if hasMore { + emails = emails[:limit] + } + + data := map[string]interface{}{ + "Emails": emails, + "Page": page, + "PrevPage": page - 1, + "NextPage": page + 1, + "HasMore": hasMore, + "TotalPages": ((len(emails) + limit - 1) / limit), + } + + // Check if this is an HTMX request + if r.Header.Get("HX-Request") == "true" { + if err := h.tmpl.RenderPartial(w, "emails/table.html", "email-table", data); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } + return + } + + if err := h.tmpl.Render(w, "emails/index.html", data); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} + +func (h *PageHandler) EmailsShow(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + id, err := strconv.Atoi(vars["id"]) + if err != nil { + http.Error(w, "Invalid email ID", http.StatusBadRequest) + return + } + + // Get email details from database + emailQuery := ` + SELECT e.id, e.subject, e.user_id, e.created, e.gmail_message_id, + e.gmail_thread_id, e.raw_headers, e.is_downloaded, + u.email as user_email, u.first_name, u.last_name + FROM emails e + LEFT JOIN users u ON e.user_id = u.id + WHERE e.id = ?` + + var email struct { + ID int32 `json:"id"` + Subject string `json:"subject"` + UserID int32 `json:"user_id"` + Created time.Time `json:"created"` + GmailMessageID *string `json:"gmail_message_id"` + GmailThreadID *string `json:"gmail_thread_id"` + RawHeaders *string `json:"raw_headers"` + IsDownloaded *bool `json:"is_downloaded"` + User *struct { + Email string `json:"email"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + } `json:"user"` + Enquiries []int32 `json:"enquiries"` + Invoices []int32 `json:"invoices"` + PurchaseOrders []int32 `json:"purchase_orders"` + Jobs []int32 `json:"jobs"` + } + + var gmailMessageID, gmailThreadID, rawHeaders sql.NullString + var isDownloaded sql.NullBool + var userEmail, firstName, lastName sql.NullString + + err = h.db.QueryRow(emailQuery, id).Scan( + &email.ID, + &email.Subject, + &email.UserID, + &email.Created, + &gmailMessageID, + &gmailThreadID, + &rawHeaders, + &isDownloaded, + &userEmail, + &firstName, + &lastName, + ) + + if err != nil { + if err == sql.ErrNoRows { + http.Error(w, "Email not found", http.StatusNotFound) + } else { + log.Printf("Error fetching email %d: %v", id, err) + http.Error(w, "Database error", http.StatusInternalServerError) + } + return + } + + // Set nullable fields + if gmailMessageID.Valid { + email.GmailMessageID = &gmailMessageID.String + } + if gmailThreadID.Valid { + email.GmailThreadID = &gmailThreadID.String + } + if rawHeaders.Valid { + email.RawHeaders = &rawHeaders.String + } + if isDownloaded.Valid { + email.IsDownloaded = &isDownloaded.Bool + } + + // Set user info if available + if userEmail.Valid { + email.User = &struct { + Email string `json:"email"` + FirstName string `json:"first_name"` + LastName string `json:"last_name"` + }{ + Email: userEmail.String, + FirstName: firstName.String, + LastName: lastName.String, + } + } + + // Get email attachments + attachmentQuery := ` + SELECT id, name, type, size, filename, is_message_body, gmail_attachment_id, created + FROM email_attachments + WHERE email_id = ? + ORDER BY is_message_body DESC, created ASC` + + attachmentRows, err := h.db.Query(attachmentQuery, id) + if err != nil { + log.Printf("Error fetching attachments for email %d: %v", id, err) + } + + type EmailAttachment struct { + ID int32 `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Size int32 `json:"size"` + Filename string `json:"filename"` + IsMessageBody bool `json:"is_message_body"` + GmailAttachmentID *string `json:"gmail_attachment_id"` + Created time.Time `json:"created"` + } + + var attachments []EmailAttachment + hasStoredAttachments := false + + if attachmentRows != nil { + defer attachmentRows.Close() + for attachmentRows.Next() { + hasStoredAttachments = true + var attachment EmailAttachment + var gmailAttachmentID sql.NullString + + err := attachmentRows.Scan( + &attachment.ID, + &attachment.Name, + &attachment.Type, + &attachment.Size, + &attachment.Filename, + &attachment.IsMessageBody, + &gmailAttachmentID, + &attachment.Created, + ) + if err != nil { + log.Printf("Error scanning attachment: %v", err) + continue + } + + if gmailAttachmentID.Valid { + attachment.GmailAttachmentID = &gmailAttachmentID.String + } + + attachments = append(attachments, attachment) + } + } + + // If no stored attachments and this is a Gmail email, show a notice + if !hasStoredAttachments && email.GmailMessageID != nil { + // For the page view, we'll just show a notice that attachments can be fetched + // The actual fetching will happen via the API endpoint when needed + log.Printf("Email %d is a Gmail email without indexed attachments", id) + } + + // Get associated records (simplified queries for now) + // Enquiries + enquiryRows, err := h.db.Query("SELECT enquiry_id FROM emails_enquiries WHERE email_id = ?", id) + if err == nil { + defer enquiryRows.Close() + for enquiryRows.Next() { + var enquiryID int32 + if enquiryRows.Scan(&enquiryID) == nil { + email.Enquiries = append(email.Enquiries, enquiryID) + } + } + } + + // Invoices + invoiceRows, err := h.db.Query("SELECT invoice_id FROM emails_invoices WHERE email_id = ?", id) + if err == nil { + defer invoiceRows.Close() + for invoiceRows.Next() { + var invoiceID int32 + if invoiceRows.Scan(&invoiceID) == nil { + email.Invoices = append(email.Invoices, invoiceID) + } + } + } + + // Purchase Orders + poRows, err := h.db.Query("SELECT purchase_order_id FROM emails_purchase_orders WHERE email_id = ?", id) + if err == nil { + defer poRows.Close() + for poRows.Next() { + var poID int32 + if poRows.Scan(&poID) == nil { + email.PurchaseOrders = append(email.PurchaseOrders, poID) + } + } + } + + // Jobs + jobRows, err := h.db.Query("SELECT job_id FROM emails_jobs WHERE email_id = ?", id) + if err == nil { + defer jobRows.Close() + for jobRows.Next() { + var jobID int32 + if jobRows.Scan(&jobID) == nil { + email.Jobs = append(email.Jobs, jobID) + } + } + } + + data := map[string]interface{}{ + "Email": email, + "Attachments": attachments, + } + + if err := h.tmpl.Render(w, "emails/show.html", data); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} + +func (h *PageHandler) EmailsSearch(w http.ResponseWriter, r *http.Request) { + _ = r.URL.Query().Get("search") // TODO: Implement search functionality + + // Empty result for now - would need proper implementation + emails := []interface{}{} + + data := map[string]interface{}{ + "Emails": emails, + "Page": 1, + "PrevPage": 0, + "NextPage": 2, + "HasMore": false, + "TotalPages": 1, + } + + w.Header().Set("Content-Type", "text/html") + if err := h.tmpl.RenderPartial(w, "emails/table.html", "email-table", data); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} + +func (h *PageHandler) EmailsAttachments(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + _, err := strconv.Atoi(vars["id"]) + if err != nil { + http.Error(w, "Invalid email ID", http.StatusBadRequest) + return + } + + // Empty attachments for now - would need proper implementation + attachments := []interface{}{} + + data := map[string]interface{}{ + "Attachments": attachments, + } + + w.Header().Set("Content-Type", "text/html") + if err := h.tmpl.RenderPartial(w, "emails/attachments.html", "email-attachments", data); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} diff --git a/go-app/internal/cmc/templates/templates.go b/go-app/internal/cmc/templates/templates.go index ba9071e5..18f18e40 100644 --- a/go-app/internal/cmc/templates/templates.go +++ b/go-app/internal/cmc/templates/templates.go @@ -54,6 +54,10 @@ func NewTemplateManager(templatesDir string) (*TemplateManager, error) { "enquiries/show.html", "enquiries/form.html", "enquiries/table.html", + "emails/index.html", + "emails/show.html", + "emails/table.html", + "emails/attachments.html", "documents/index.html", "documents/show.html", "documents/table.html", diff --git a/go-app/sql/migrations/001_add_gmail_fields.sql b/go-app/sql/migrations/001_add_gmail_fields.sql new file mode 100644 index 00000000..9fd351b6 --- /dev/null +++ b/go-app/sql/migrations/001_add_gmail_fields.sql @@ -0,0 +1,52 @@ +-- +goose Up +-- Add Gmail-specific fields to emails table +ALTER TABLE emails + ADD COLUMN gmail_message_id VARCHAR(255) UNIQUE AFTER id, + ADD COLUMN gmail_thread_id VARCHAR(255) AFTER gmail_message_id, + ADD COLUMN is_downloaded BOOLEAN DEFAULT FALSE AFTER email_attachment_count, + ADD COLUMN raw_headers TEXT AFTER subject; + +-- +goose StatementBegin +CREATE INDEX idx_gmail_message_id ON emails(gmail_message_id); +-- +goose StatementEnd + +-- +goose StatementBegin +CREATE INDEX idx_gmail_thread_id ON emails(gmail_thread_id); +-- +goose StatementEnd + +-- Add Gmail-specific fields to email_attachments +ALTER TABLE email_attachments + ADD COLUMN gmail_attachment_id VARCHAR(255) AFTER email_id, + ADD COLUMN gmail_message_id VARCHAR(255) AFTER gmail_attachment_id, + ADD COLUMN content_id VARCHAR(255) AFTER filename; + +-- +goose StatementBegin +CREATE INDEX idx_gmail_attachment_id ON email_attachments(gmail_attachment_id); +-- +goose StatementEnd + +-- +goose Down +-- Remove indexes +-- +goose StatementBegin +DROP INDEX idx_gmail_attachment_id ON email_attachments; +-- +goose StatementEnd + +-- +goose StatementBegin +DROP INDEX idx_gmail_thread_id ON emails; +-- +goose StatementEnd + +-- +goose StatementBegin +DROP INDEX idx_gmail_message_id ON emails; +-- +goose StatementEnd + +-- Remove columns from email_attachments +ALTER TABLE email_attachments + DROP COLUMN content_id, + DROP COLUMN gmail_message_id, + DROP COLUMN gmail_attachment_id; + +-- Remove columns from emails +ALTER TABLE emails + DROP COLUMN raw_headers, + DROP COLUMN is_downloaded, + DROP COLUMN gmail_thread_id, + DROP COLUMN gmail_message_id; \ No newline at end of file diff --git a/go-app/static/css/style.css b/go-app/static/css/style.css index d5d7e6d7..7c622bba 100644 --- a/go-app/static/css/style.css +++ b/go-app/static/css/style.css @@ -106,4 +106,20 @@ body { .input.is-danger:focus { border-color: #ff3860; box-shadow: 0 0 0 0.125em rgba(255,56,96,.25); +} + +/* Simple CSS loader */ +.loader { + border: 2px solid #f3f3f3; + border-top: 2px solid #3273dc; + border-radius: 50%; + width: 16px; + height: 16px; + animation: spin 1s linear infinite; + display: inline-block; +} + +@keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } } \ No newline at end of file diff --git a/go-app/templates/emails/attachments.html b/go-app/templates/emails/attachments.html new file mode 100644 index 00000000..24086346 --- /dev/null +++ b/go-app/templates/emails/attachments.html @@ -0,0 +1,67 @@ +{{define "email-attachments"}} +
+ + + + + + + + + + + + {{range .}} + + + + + + + + {{else}} + + + + {{end}} + +
NameTypeSizeDateActions
+ {{if .IsMessageBody}} + + + + {{.Name}} + Body + {{else}} + + + + {{.Name}} + {{end}} + + {{.Type}} + {{.Size}} bytes + {{.Created}} + + {{if .GmailAttachmentID}} + + + + + Stream + + {{else}} + + + + + Download + + {{end}} +
+

No attachments found

+
+
+{{end}} \ No newline at end of file diff --git a/go-app/templates/emails/index.html b/go-app/templates/emails/index.html new file mode 100644 index 00000000..d3ba1bab --- /dev/null +++ b/go-app/templates/emails/index.html @@ -0,0 +1,82 @@ +{{define "title"}}Emails - CMC Sales{{end}} + +{{define "content"}} +
+
+
+

Emails

+
+
+
+
+
+
+
+ +
+
+
+ +
+
+
+
+
+ + +
+
+
+ + + + +
+
+ +
+
+
+ + +
+ {{template "email-table" .}} +
+{{end}} + +{{define "scripts"}} + +{{end}} \ No newline at end of file diff --git a/go-app/templates/emails/show.html b/go-app/templates/emails/show.html new file mode 100644 index 00000000..41a67278 --- /dev/null +++ b/go-app/templates/emails/show.html @@ -0,0 +1,293 @@ +{{define "title"}}Email {{.Email.ID}} - CMC Sales{{end}} + +{{define "content"}} +
+
+
+ +
+
+
+
+
+ {{if .Email.GmailMessageID}} + + + + + View in Gmail + + {{end}} + + + + + Back to Emails + +
+
+
+
+ +
+
+ +
+

+ {{if .Email.Subject}}{{.Email.Subject}}{{else}}(No Subject){{end}} +

+ +
+
+
+ From: + {{if .Email.User}} + {{.Email.User.Email}} ({{.Email.User.FirstName}} {{.Email.User.LastName}}) + {{else}} + Unknown sender + {{end}} +
+
+ Date: {{.Email.Created.Format "2006-01-02 15:04:05"}} +
+
+ Type: + {{if .Email.GmailMessageID}} + + + + + Gmail + + {{if and .Email.IsDownloaded (not .Email.IsDownloaded)}} + Remote + {{else}} + Downloaded + {{end}} + {{else}} + Local Email + {{end}} +
+
+ Attachments: + {{if gt (len .Attachments) 0}} + {{len .Attachments}} files + {{else}} + None + {{end}} +
+ {{if .Email.GmailMessageID}} +
+ Gmail Message ID: + {{.Email.GmailMessageID}} +
+ {{end}} + {{if .Email.GmailThreadID}} +
+ Gmail Thread ID: + {{.Email.GmailThreadID}} +
+ {{end}} +
+
+
+ + + {{if .Email.GmailMessageID}} +
+

Email Content

+
+
+
+ + Loading email content... +
+
+
+
+ {{end}} + + + {{if gt (len .Attachments) 0}} +
+

Attachments

+
+ + + + + + + + + + + + {{range .Attachments}} + + + + + + + + {{end}} + +
NameTypeSizeDateActions
+ {{if .IsMessageBody}} + + + + {{else}} + + + + {{end}} + {{.Name}} + + {{.Type}} + {{.Size}} bytes + {{.Created.Format "2006-01-02 15:04"}} + + {{if .GmailAttachmentID}} + + + + + Download + + {{else}} + + + + + Download + + {{end}} +
+
+
+ {{else if .Email.GmailMessageID}} + +
+

Attachments

+
+
+
+ + Checking for Gmail attachments... +
+
+
+
+ {{end}} +
+ +
+ +
+

Associated Records

+ + {{if .Email.Enquiries}} +
+ +
+ {{range .Email.Enquiries}} + + ENQ-{{.}} + + {{end}} +
+
+ {{end}} + + {{if .Email.Invoices}} +
+ +
+ {{range .Email.Invoices}} + + INV-{{.}} + + {{end}} +
+
+ {{end}} + + {{if .Email.PurchaseOrders}} +
+ +
+ {{range .Email.PurchaseOrders}} + + PO-{{.}} + + {{end}} +
+
+ {{end}} + + {{if .Email.Jobs}} +
+ +
+ {{range .Email.Jobs}} + + JOB-{{.}} + + {{end}} +
+
+ {{end}} + + {{if and (not .Email.Enquiries) (not .Email.Invoices) (not .Email.PurchaseOrders) (not .Email.Jobs)}} +
+

No associations found

+

This email is not associated with any enquiries, invoices, purchase orders, or jobs.

+
+ {{end}} +
+ + +
+

Quick Actions

+
+ + + {{if .Email.GmailMessageID}} + + {{end}} +
+
+
+
+{{end}} \ No newline at end of file diff --git a/go-app/templates/emails/table.html b/go-app/templates/emails/table.html new file mode 100644 index 00000000..a0798ce3 --- /dev/null +++ b/go-app/templates/emails/table.html @@ -0,0 +1,143 @@ +{{define "email-table"}} +
+ + + + + + + + + + + + + + + {{range .Emails}} + + + + + + + + + + + {{else}} + + + + {{end}} + +
IDSubjectFromDateAttachmentsTypeAssociatedActions
{{.ID}} + + {{if .Subject}}{{.Subject}}{{else}}(No Subject){{end}} + + + {{if .UserEmail}} + {{.UserEmail}} + {{else}} + Unknown + {{end}} + + + {{.Created.Format "2006-01-02 15:04"}} + + + {{if gt .AttachmentCount 0}} + + + + + {{.AttachmentCount}} + + {{else}} + None + {{end}} + + {{if .GmailMessageID}} + + + + + Gmail + + {{if and .IsDownloaded (not .IsDownloaded)}} + + + + + Remote + + {{end}} + {{else}} + + + + + Local + + {{end}} + + Associations TBD + +
+ + + + + + {{if gt .AttachmentCount 0}} + + {{end}} + {{if .GmailMessageID}} + + + + + + {{end}} +
+
+

No emails found

+
+
+ + +{{if .Emails}} + +{{end}} + + + +{{end}} \ No newline at end of file diff --git a/go-app/templates/layouts/base.html b/go-app/templates/layouts/base.html index a9e75312..022bc5ad 100644 --- a/go-app/templates/layouts/base.html +++ b/go-app/templates/layouts/base.html @@ -61,6 +61,11 @@ Enquiries + + + + Emails + From bb34ae5881654e45cabfd70d716028eed9a736ab Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Wed, 6 Aug 2025 13:49:21 +1000 Subject: [PATCH 04/17] Fix staging docker compose --- docker-compose.staging.yml | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/docker-compose.staging.yml b/docker-compose.staging.yml index cde10cad..fdb6a133 100644 --- a/docker-compose.staging.yml +++ b/docker-compose.staging.yml @@ -1,22 +1,6 @@ version: '3.8' services: - nginx-staging: - image: nginx:latest - hostname: nginx-staging - container_name: cmc-nginx-staging - ports: - - "8081:80" # Internal port for staging - volumes: - - ./conf/nginx-staging.conf:/etc/nginx/conf.d/cmc-staging.conf - - ./userpasswd:/etc/nginx/userpasswd:ro - depends_on: - - cmc-php-staging - restart: unless-stopped - networks: - - cmc-staging-network - environment: - - NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template cmc-php-staging: build: @@ -35,6 +19,23 @@ services: environment: - APP_ENV=staging + nginx-staging: + image: nginx:latest + hostname: nginx-staging + container_name: cmc-nginx-staging + ports: + - "8081:80" # Internal port for staging + volumes: + - ./conf/nginx-staging.conf:/etc/nginx/conf.d/cmc-staging.conf + - ./userpasswd:/etc/nginx/userpasswd:ro + depends_on: + - cmc-php-staging + restart: unless-stopped + networks: + - cmc-staging-network + environment: + - NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template + db-staging: image: mariadb:latest container_name: cmc-db-staging From 30f84fefe789fdb666511fc333a92b32977bd31d Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Wed, 6 Aug 2025 13:50:16 +1000 Subject: [PATCH 05/17] Fix docker-compose.production.yml --- docker-compose.production.yml | 36 ++++++++++++++++++----------------- 1 file changed, 19 insertions(+), 17 deletions(-) diff --git a/docker-compose.production.yml b/docker-compose.production.yml index 376e5bb8..77b5b60e 100644 --- a/docker-compose.production.yml +++ b/docker-compose.production.yml @@ -1,23 +1,6 @@ version: '3.8' services: - nginx-production: - image: nginx:latest - hostname: nginx-production - container_name: cmc-nginx-production - ports: - - "8080:80" # Internal port for production - volumes: - - ./conf/nginx-production.conf:/etc/nginx/conf.d/cmc-production.conf - - ./userpasswd:/etc/nginx/userpasswd:ro - depends_on: - - cmc-php-production - restart: unless-stopped - networks: - - cmc-production-network - environment: - - NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template - cmc-php-production: build: context: . @@ -44,6 +27,25 @@ services: cpus: '0.5' memory: 512M + nginx-production: + image: nginx:latest + hostname: nginx-production + container_name: cmc-nginx-production + ports: + - "8080:80" # Internal port for production + volumes: + - ./conf/nginx-production.conf:/etc/nginx/conf.d/cmc-production.conf + - ./userpasswd:/etc/nginx/userpasswd:ro + depends_on: + - cmc-php-production + restart: unless-stopped + networks: + - cmc-production-network + environment: + - NGINX_ENVSUBST_TEMPLATE_SUFFIX=.template + + + db-production: image: mariadb:latest container_name: cmc-db-production From dc2b67d300f16c29e22ea87ce54806046086d73e Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Thu, 7 Aug 2025 21:53:30 +1000 Subject: [PATCH 06/17] Add docker-compose.caddy and Makefile --- Makefile | 190 ++++++++++++++++++++++++++++ docker-compose.caddy-production.yml | 85 +++++++++++++ docker-compose.caddy-staging.yml | 61 +++++++++ 3 files changed, 336 insertions(+) create mode 100644 Makefile create mode 100644 docker-compose.caddy-production.yml create mode 100644 docker-compose.caddy-staging.yml diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..573ff7b2 --- /dev/null +++ b/Makefile @@ -0,0 +1,190 @@ +# CMC Sales Deployment Makefile for Caddy setup + +.PHONY: help staging production backup-staging backup-production restart-staging restart-production status logs clean caddy-reload caddy-logs + +# Default target +help: + @echo "CMC Sales Deployment Commands (Caddy version)" + @echo "" + @echo "Environments:" + @echo " staging Start staging environment" + @echo " staging-down Stop staging environment" + @echo " staging-logs Show staging logs" + @echo " restart-staging Rebuild and restart staging" + @echo "" + @echo " production Start production environment" + @echo " production-down Stop production environment" + @echo " production-logs Show production logs" + @echo " restart-production Rebuild and restart production" + @echo "" + @echo "Database:" + @echo " backup-staging Backup staging database" + @echo " backup-production Backup production database" + @echo "" + @echo "Caddy:" + @echo " caddy-status Show Caddy service status" + @echo " caddy-reload Reload Caddy configuration" + @echo " caddy-logs Show Caddy logs" + @echo " caddy-validate Validate Caddyfile" + @echo "" + @echo "Utility:" + @echo " status Show all container status" + @echo " clean Stop and remove all containers" + @echo " setup-auth Setup basic authentication" + +# Staging environment +staging: + @echo "Starting staging environment..." + docker compose -f docker-compose.caddy-staging.yml up -d + @echo "Staging environment started" + @echo "Access at: https://staging.cmc.springupsoftware.com" + +staging-down: + docker compose -f docker-compose.caddy-staging.yml down + +staging-logs: + docker compose -f docker-compose.caddy-staging.yml logs -f + +restart-staging: + @echo "Restarting staging environment..." + docker compose -f docker-compose.caddy-staging.yml down + docker compose -f docker-compose.caddy-staging.yml build --no-cache + docker compose -f docker-compose.caddy-staging.yml up -d + @echo "Staging environment restarted" + +# Production environment +production: + @echo "Starting production environment..." + docker compose -f docker-compose.caddy-production.yml up -d + @echo "Production environment started" + @echo "Access at: https://cmc.springupsoftware.com" + +production-down: + @echo "WARNING: This will stop the production environment!" + @read -p "Are you sure? (yes/no): " confirm && [ "$$confirm" = "yes" ] + docker compose -f docker-compose.caddy-production.yml down + +production-logs: + docker compose -f docker-compose.caddy-production.yml logs -f + +restart-production: + @echo "WARNING: This will restart the production environment!" + @read -p "Are you sure? (yes/no): " confirm && [ "$$confirm" = "yes" ] + docker compose -f docker-compose.caddy-production.yml down + docker compose -f docker-compose.caddy-production.yml build --no-cache + docker compose -f docker-compose.caddy-production.yml up -d + @echo "Production environment restarted" + +# Database backups +backup-staging: + @echo "Creating staging database backup..." + ./scripts/backup-db.sh staging + +backup-production: + @echo "Creating production database backup..." + ./scripts/backup-db.sh production + +# Caddy management +caddy-status: + @echo "=== Caddy Status ===" + sudo systemctl status caddy --no-pager + +caddy-reload: + @echo "Reloading Caddy configuration..." + sudo systemctl reload caddy + @echo "Caddy reloaded successfully" + +caddy-logs: + @echo "=== Caddy Logs ===" + sudo journalctl -u caddy -f + +caddy-validate: + @echo "Validating Caddyfile..." + caddy validate --config Caddyfile + @echo "Caddyfile is valid" + +# Setup authentication +setup-auth: + @echo "Setting up basic authentication..." + ./scripts/setup-caddy-auth.sh + +# System status +status: + @echo "=== Container Status ===" + docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" + @echo "" + @echo "=== Caddy Status ===" + sudo systemctl is-active caddy || true + @echo "" + @echo "=== Port Usage ===" + sudo netstat -tlnp | grep -E ":(80|443|8091|8092|8093|8094|3306|3307) " || true + +# Logs +logs: + @echo "Which logs? [staging/production/caddy]" + @read env; \ + case $$env in \ + staging) docker compose -f docker-compose.caddy-staging.yml logs -f ;; \ + production) docker compose -f docker-compose.caddy-production.yml logs -f ;; \ + caddy) sudo journalctl -u caddy -f ;; \ + *) echo "Invalid option" ;; \ + esac + +# Cleanup +clean: + @echo "WARNING: This will stop and remove ALL CMC containers!" + @read -p "Are you sure? (yes/no): " confirm && [ "$$confirm" = "yes" ] + docker compose -f docker-compose.caddy-staging.yml down --volumes --remove-orphans + docker compose -f docker-compose.caddy-production.yml down --volumes --remove-orphans + docker system prune -f + @echo "Cleanup completed" + +# Health checks +health: + @echo "=== Health Checks ===" + @echo "Staging:" + @curl -s -o /dev/null -w " HTTPS %{http_code}: https://staging.cmc.springupsoftware.com/health\n" https://staging.cmc.springupsoftware.com/health -u admin:password || echo " Staging not accessible (update with correct auth)" + @curl -s -o /dev/null -w " Internal %{http_code}: http://localhost:8092/api/v1/health\n" http://localhost:8092/api/v1/health || echo " Staging Go not accessible" + @echo "Production:" + @curl -s -o /dev/null -w " HTTPS %{http_code}: https://cmc.springupsoftware.com/health\n" https://cmc.springupsoftware.com/health -u admin:password || echo " Production not accessible (update with correct auth)" + @curl -s -o /dev/null -w " Internal %{http_code}: http://localhost:8094/api/v1/health\n" http://localhost:8094/api/v1/health || echo " Production Go not accessible" + +# Deploy to staging +deploy-staging: + @echo "Deploying to staging..." + git pull origin main + $(MAKE) restart-staging + @echo "Staging deployment complete" + +# Deploy to production +deploy-production: + @echo "WARNING: This will deploy to PRODUCTION!" + @echo "Make sure you have tested thoroughly in staging first." + @read -p "Are you sure you want to deploy to production? (yes/no): " confirm && [ "$$confirm" = "yes" ] + git pull origin main + $(MAKE) backup-production + $(MAKE) restart-production + @echo "Production deployment complete" + +# First-time setup +initial-setup: + @echo "Running initial setup..." + @echo "1. Installing Caddy..." + sudo ./scripts/install-caddy.sh + @echo "" + @echo "2. Setting up authentication..." + ./scripts/setup-caddy-auth.sh + @echo "" + @echo "3. Copying Caddyfile..." + sudo cp Caddyfile /etc/caddy/Caddyfile + @echo "" + @echo "4. Starting Caddy..." + sudo systemctl start caddy + @echo "" + @echo "5. Starting containers..." + $(MAKE) staging + $(MAKE) production + @echo "" + @echo "Initial setup complete!" + @echo "Access staging at: https://staging.cmc.springupsoftware.com" + @echo "Access production at: https://cmc.springupsoftware.com" \ No newline at end of file diff --git a/docker-compose.caddy-production.yml b/docker-compose.caddy-production.yml new file mode 100644 index 00000000..882d517a --- /dev/null +++ b/docker-compose.caddy-production.yml @@ -0,0 +1,85 @@ +version: '3.8' + +services: + cmc-php-production: + build: + context: . + dockerfile: Dockerfile + platform: linux/amd64 + container_name: cmc-php-production + depends_on: + - db-production + ports: + - "127.0.0.1:8093:80" # Only accessible from localhost + volumes: + - production_pdf_data:/var/www/cmc-sales/app/webroot/pdf + - production_attachments_data:/var/www/cmc-sales/app/webroot/attachments_files + restart: unless-stopped + environment: + - APP_ENV=production + deploy: + resources: + limits: + cpus: '2.0' + memory: 2G + reservations: + cpus: '0.5' + memory: 512M + + db-production: + image: mariadb:latest + container_name: cmc-db-production + environment: + MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD_PRODUCTION} + MYSQL_DATABASE: cmc + MYSQL_USER: cmc + MYSQL_PASSWORD: ${DB_PASSWORD_PRODUCTION} + volumes: + - production_db_data:/var/lib/mysql + - ./backups:/backups:ro + restart: unless-stopped + # No external port exposure for security + deploy: + resources: + limits: + cpus: '2.0' + memory: 4G + reservations: + cpus: '0.5' + memory: 1G + + cmc-go-production: + build: + context: . + dockerfile: Dockerfile.go.production + container_name: cmc-go-production + environment: + DB_HOST: db-production + DB_PORT: 3306 + DB_USER: cmc + DB_PASSWORD: ${DB_PASSWORD_PRODUCTION} + DB_NAME: cmc + PORT: 8080 + APP_ENV: production + depends_on: + db-production: + condition: service_started + ports: + - "127.0.0.1:8094:8080" # Only accessible from localhost + volumes: + - production_pdf_data:/root/webroot/pdf + - ./credentials/production:/root/credentials:ro + restart: unless-stopped + deploy: + resources: + limits: + cpus: '2.0' + memory: 2G + reservations: + cpus: '0.5' + memory: 512M + +volumes: + production_db_data: + production_pdf_data: + production_attachments_data: \ No newline at end of file diff --git a/docker-compose.caddy-staging.yml b/docker-compose.caddy-staging.yml new file mode 100644 index 00000000..2a4856d2 --- /dev/null +++ b/docker-compose.caddy-staging.yml @@ -0,0 +1,61 @@ +version: '3.8' + +services: + cmc-php-staging: + build: + context: . + dockerfile: Dockerfile + platform: linux/amd64 + container_name: cmc-php-staging + depends_on: + - db-staging + ports: + - "127.0.0.1:8091:80" # Only accessible from localhost + volumes: + - staging_pdf_data:/var/www/cmc-sales/app/webroot/pdf + - staging_attachments_data:/var/www/cmc-sales/app/webroot/attachments_files + restart: unless-stopped + environment: + - APP_ENV=staging + + db-staging: + image: mariadb:latest + container_name: cmc-db-staging + environment: + MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD_STAGING} + MYSQL_DATABASE: cmc_staging + MYSQL_USER: cmc_staging + MYSQL_PASSWORD: ${DB_PASSWORD_STAGING} + volumes: + - staging_db_data:/var/lib/mysql + restart: unless-stopped + ports: + - "127.0.0.1:3307:3306" # Only accessible from localhost + + cmc-go-staging: + build: + context: . + dockerfile: Dockerfile.go.staging + container_name: cmc-go-staging + environment: + DB_HOST: db-staging + DB_PORT: 3306 + DB_USER: cmc_staging + DB_PASSWORD: ${DB_PASSWORD_STAGING} + DB_NAME: cmc_staging + PORT: 8080 + APP_ENV: staging + depends_on: + db-staging: + condition: service_started + ports: + - "127.0.0.1:8092:8080" # Only accessible from localhost + volumes: + - staging_pdf_data:/root/webroot/pdf + - ./credentials/staging:/root/credentials:ro + restart: unless-stopped + +volumes: + staging_db_data: + staging_pdf_data: + staging_attachments_data: \ No newline at end of file From 6f538e3e4d069bb4a766ce03efc33a9c9f23e787 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Fri, 8 Aug 2025 11:22:06 +1000 Subject: [PATCH 07/17] Various changes to make staging work --- Dockerfile.ubuntu-php | 75 +++++++++++++++++++++++++ Makefile | 16 +++--- docker-compose.caddy-staging-ubuntu.yml | 65 +++++++++++++++++++++ 3 files changed, 148 insertions(+), 8 deletions(-) create mode 100644 Dockerfile.ubuntu-php create mode 100644 docker-compose.caddy-staging-ubuntu.yml diff --git a/Dockerfile.ubuntu-php b/Dockerfile.ubuntu-php new file mode 100644 index 00000000..cb5d7837 --- /dev/null +++ b/Dockerfile.ubuntu-php @@ -0,0 +1,75 @@ +# Simple working PHP setup using Ubuntu +FROM ubuntu:20.04 + +# Prevent interactive prompts during package installation +ENV DEBIAN_FRONTEND=noninteractive +ENV TZ=Australia/Sydney + +# Install Apache, PHP and required extensions +RUN apt-get update && apt-get install -y \ + apache2 \ + libapache2-mod-php7.4 \ + php7.4 \ + php7.4-mysql \ + php7.4-gd \ + php7.4-curl \ + php7.4-mbstring \ + php7.4-xml \ + php7.4-zip \ + php7.4-imap \ + php7.4-intl \ + php7.4-bcmath \ + curl \ + && rm -rf /var/lib/apt/lists/* + +# Enable Apache modules +RUN a2enmod rewrite headers php7.4 + +# Configure PHP for CakePHP +RUN { \ + echo 'error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT & ~E_NOTICE & ~E_WARNING'; \ + echo 'display_errors = On'; \ + echo 'display_startup_errors = On'; \ + echo 'log_errors = On'; \ + echo 'max_execution_time = 300'; \ + echo 'memory_limit = 256M'; \ + echo 'post_max_size = 50M'; \ + echo 'upload_max_filesize = 50M'; \ +} > /etc/php/7.4/apache2/conf.d/99-cakephp.ini + +# Set up Apache virtual host +RUN echo '\n\ + ServerName localhost\n\ + DocumentRoot /var/www/cmc-sales/app/webroot\n\ + \n\ + Options FollowSymLinks\n\ + AllowOverride All\n\ + Require all granted\n\ + \n\ + ErrorLog ${APACHE_LOG_DIR}/error.log\n\ + CustomLog ${APACHE_LOG_DIR}/access.log combined\n\ +' > /etc/apache2/sites-available/000-default.conf + +# Create app directory structure +RUN mkdir -p /var/www/cmc-sales/app/tmp/{cache,logs,sessions} \ + && mkdir -p /var/www/cmc-sales/app/webroot/{pdf,attachments_files} + +# Set permissions +RUN chown -R www-data:www-data /var/www/cmc-sales \ + && chmod -R 777 /var/www/cmc-sales/app/tmp + +# Copy ripmime if it exists +# COPY conf/ripmime* /usr/local/bin/ || true +# RUN chmod +x /usr/local/bin/ripmime* 2>/dev/null || true + +# Set working directory +WORKDIR /var/www/cmc-sales + +# Copy application (will be overridden by volume mount) +COPY app/ /var/www/cmc-sales/app/ + +# Expose port 80 +EXPOSE 80 + +# Start Apache in foreground +CMD ["apache2ctl", "-D", "FOREGROUND"] \ No newline at end of file diff --git a/Makefile b/Makefile index 573ff7b2..98d352c1 100644 --- a/Makefile +++ b/Makefile @@ -35,21 +35,21 @@ help: # Staging environment staging: @echo "Starting staging environment..." - docker compose -f docker-compose.caddy-staging.yml up -d + docker compose -f docker-compose.caddy-staging-ubuntu.yml up -d @echo "Staging environment started" @echo "Access at: https://staging.cmc.springupsoftware.com" staging-down: - docker compose -f docker-compose.caddy-staging.yml down + docker compose -f docker-compose.caddy-staging-ubuntu.yml down staging-logs: - docker compose -f docker-compose.caddy-staging.yml logs -f + docker compose -f docker-compose.caddy-staging-ubuntu.yml logs -f restart-staging: @echo "Restarting staging environment..." - docker compose -f docker-compose.caddy-staging.yml down - docker compose -f docker-compose.caddy-staging.yml build --no-cache - docker compose -f docker-compose.caddy-staging.yml up -d + docker compose -f docker-compose.caddy-staging-ubuntu.yml down + docker compose -f docker-compose.caddy-staging-ubuntu.yml build --no-cache + docker compose -f docker-compose.caddy-staging-ubuntu.yml up -d @echo "Staging environment restarted" # Production environment @@ -124,7 +124,7 @@ logs: @echo "Which logs? [staging/production/caddy]" @read env; \ case $$env in \ - staging) docker compose -f docker-compose.caddy-staging.yml logs -f ;; \ + staging) docker compose -f docker-compose.caddy-staging-ubuntu.yml logs -f ;; \ production) docker compose -f docker-compose.caddy-production.yml logs -f ;; \ caddy) sudo journalctl -u caddy -f ;; \ *) echo "Invalid option" ;; \ @@ -134,7 +134,7 @@ logs: clean: @echo "WARNING: This will stop and remove ALL CMC containers!" @read -p "Are you sure? (yes/no): " confirm && [ "$$confirm" = "yes" ] - docker compose -f docker-compose.caddy-staging.yml down --volumes --remove-orphans + docker compose -f docker-compose.caddy-staging-ubuntu.yml down --volumes --remove-orphans docker compose -f docker-compose.caddy-production.yml down --volumes --remove-orphans docker system prune -f @echo "Cleanup completed" diff --git a/docker-compose.caddy-staging-ubuntu.yml b/docker-compose.caddy-staging-ubuntu.yml new file mode 100644 index 00000000..08635661 --- /dev/null +++ b/docker-compose.caddy-staging-ubuntu.yml @@ -0,0 +1,65 @@ +version: '3.8' + +services: + cmc-php-staging: + build: + context: . + dockerfile: Dockerfile.ubuntu-php + platform: linux/amd64 + container_name: cmc-php-staging + depends_on: + - db-staging + ports: + - "127.0.0.1:8091:80" + volumes: + - ./app:/var/www/cmc-sales/app + - staging_pdf_data:/var/www/cmc-sales/app/webroot/pdf + - staging_attachments_data:/var/www/cmc-sales/app/webroot/attachments_files + restart: unless-stopped + environment: + - APP_ENV=staging + - DB_HOST=db-staging + - DB_NAME=cmc_staging + - DB_USER=cmc_staging + - DB_PASSWORD=${DB_PASSWORD_STAGING:-staging_password} + + db-staging: + image: mariadb:10.11 + container_name: cmc-db-staging + environment: + MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD_STAGING:-root_password} + MYSQL_DATABASE: cmc_staging + MYSQL_USER: cmc_staging + MYSQL_PASSWORD: ${DB_PASSWORD_STAGING:-staging_password} + volumes: + - staging_db_data:/var/lib/mysql + restart: unless-stopped + ports: + - "127.0.0.1:3307:3306" + + cmc-go-staging: + build: + context: . + dockerfile: Dockerfile.go.staging + container_name: cmc-go-staging + environment: + DB_HOST: db-staging + DB_PORT: 3306 + DB_USER: cmc_staging + DB_PASSWORD: ${DB_PASSWORD_STAGING:-staging_password} + DB_NAME: cmc_staging + PORT: 8080 + APP_ENV: staging + depends_on: + - db-staging + ports: + - "127.0.0.1:8092:8080" + volumes: + - staging_pdf_data:/root/webroot/pdf + - ./credentials/staging:/root/credentials:ro + restart: unless-stopped + +volumes: + staging_db_data: + staging_pdf_data: + staging_attachments_data: \ No newline at end of file From 2ea0398f4137e1a410f12588f013615ef817bcf0 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Fri, 8 Aug 2025 11:24:48 +1000 Subject: [PATCH 08/17] Yolo changes to make this work --- DEPLOYMENT-CADDY.md | 344 ++++++++++++++++++++++++++++++++++ DEPLOYMENT.md | 14 +- app/config/bootstrap.php | 2 + app/config/php7_compat.php | 96 ++++++++++ docker-compose.production.yml | 15 +- docker-compose.staging.yml | 15 +- 6 files changed, 460 insertions(+), 26 deletions(-) create mode 100644 DEPLOYMENT-CADDY.md create mode 100644 app/config/php7_compat.php diff --git a/DEPLOYMENT-CADDY.md b/DEPLOYMENT-CADDY.md new file mode 100644 index 00000000..2b9baf7b --- /dev/null +++ b/DEPLOYMENT-CADDY.md @@ -0,0 +1,344 @@ +# CMC Sales Deployment Guide with Caddy + +## Overview + +This guide covers deploying the CMC Sales application to a Debian 12 VM using Caddy as the reverse proxy with automatic HTTPS. + +## Architecture + +- **Production**: `https://cmc.springupsoftware.com` +- **Staging**: `https://staging.cmc.springupsoftware.com` +- **Reverse Proxy**: Caddy (running on host) +- **Applications**: Docker containers + - CakePHP legacy app + - Go modern app + - MariaDB database +- **SSL**: Automatic via Caddy (Let's Encrypt) +- **Authentication**: Basic auth configured in Caddy + +## Prerequisites + +### 1. Server Setup (Debian 12) + +```bash +# Update system +sudo apt update && sudo apt upgrade -y + +# Install Docker +sudo apt install -y docker.io docker-compose-plugin +sudo systemctl enable docker +sudo systemctl start docker + +# Add user to docker group +sudo usermod -aG docker $USER +# Log out and back in + +# Create directories +sudo mkdir -p /var/backups/cmc-sales +sudo chown $USER:$USER /var/backups/cmc-sales +``` + +### 2. Install Caddy + +```bash +# Run the installation script +sudo ./scripts/install-caddy.sh + +# Or manually install +sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl +curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg +curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list +sudo apt update +sudo apt install caddy +``` + +### 3. DNS Configuration + +Ensure DNS records point to your server: +- `cmc.springupsoftware.com` → Server IP +- `staging.cmc.springupsoftware.com` → Server IP + +## Initial Deployment + +### 1. Clone Repository + +```bash +cd /home/cmc +git clone git@code.springupsoftware.com:cmc/cmc-sales.git cmc-sales +sudo chown -R $USER:$USER cmc-sales +cd cmc-sales +``` + +### 2. Environment Configuration + +```bash +# Copy environment files +cp .env.staging go-app/.env.staging +cp .env.production go-app/.env.production + +# Edit with actual passwords +nano .env.staging +nano .env.production + +# Create credential directories +mkdir -p credentials/staging credentials/production +``` + +### 3. Setup Basic Authentication + +```bash +# Generate password hashes for Caddy +./scripts/setup-caddy-auth.sh + +# Or manually +caddy hash-password +# Copy the hash and update Caddyfile +``` + +### 4. Configure Caddy + +```bash +# Copy Caddyfile +sudo cp Caddyfile /etc/caddy/Caddyfile + +# Edit to update passwords and email +sudo nano /etc/caddy/Caddyfile + +# Validate configuration +caddy validate --config /etc/caddy/Caddyfile + +# Start Caddy +sudo systemctl start caddy +sudo systemctl status caddy +``` + +### 5. Gmail OAuth Setup + +Same as before - set up OAuth credentials for each environment: +- Staging: `credentials/staging/credentials.json` +- Production: `credentials/production/credentials.json` + +### 6. Database Initialization + +```bash +# Start database containers +docker compose -f docker-compose.caddy-staging.yml up -d db-staging +docker compose -f docker-compose.caddy-production.yml up -d db-production + +# Wait for databases +sleep 30 + +# Restore production database (if you have a backup) +./scripts/restore-db.sh production /path/to/backup.sql.gz +``` + +## Deployment Commands + +### Starting Services + +```bash +# Start staging environment +docker compose -f docker-compose.caddy-staging.yml up -d + +# Start production environment +docker compose -f docker-compose.caddy-production.yml up -d + +# Reload Caddy configuration +sudo systemctl reload caddy +``` + +### Updating Applications + +```bash +# Pull latest code +git pull origin main + +# Update staging +docker compose -f docker-compose.caddy-staging.yml down +docker compose -f docker-compose.caddy-staging.yml build --no-cache +docker compose -f docker-compose.caddy-staging.yml up -d + +# Test staging, then update production +docker compose -f docker-compose.caddy-production.yml down +docker compose -f docker-compose.caddy-production.yml build --no-cache +docker compose -f docker-compose.caddy-production.yml up -d +``` + +## Caddy Management + +### Configuration + +```bash +# Edit Caddyfile +sudo nano /etc/caddy/Caddyfile + +# Validate configuration +caddy validate --config /etc/caddy/Caddyfile + +# Reload configuration (zero downtime) +sudo systemctl reload caddy +``` + +### Monitoring + +```bash +# Check Caddy status +sudo systemctl status caddy + +# View Caddy logs +sudo journalctl -u caddy -f + +# View access logs +sudo tail -f /var/log/caddy/cmc-production.log +sudo tail -f /var/log/caddy/cmc-staging.log +``` + +### SSL Certificates + +Caddy handles SSL automatically! To check certificates: + +```bash +# List certificates +sudo ls -la /var/lib/caddy/.local/share/caddy/certificates/ + +# Force certificate renewal (rarely needed) +sudo systemctl stop caddy +sudo rm -rf /var/lib/caddy/.local/share/caddy/certificates/* +sudo systemctl start caddy +``` + +## Container Port Mapping + +| Service | Container Port | Host Port | Access | +|---------|---------------|-----------|---------| +| cmc-php-staging | 80 | 8091 | localhost only | +| cmc-go-staging | 8080 | 8092 | localhost only | +| cmc-db-staging | 3306 | 3307 | localhost only | +| cmc-php-production | 80 | 8093 | localhost only | +| cmc-go-production | 8080 | 8094 | localhost only | +| cmc-db-production | 3306 | - | internal only | + +## Monitoring and Maintenance + +### Health Checks + +```bash +# Check all containers +docker ps + +# Check application health +curl -I https://cmc.springupsoftware.com +curl -I https://staging.cmc.springupsoftware.com + +# Internal health checks (from server) +curl http://localhost:8094/api/v1/health # Production Go +curl http://localhost:8092/api/v1/health # Staging Go +``` + +### Database Backups + +Same backup scripts work: + +```bash +# Manual backup +./scripts/backup-db.sh production +./scripts/backup-db.sh staging + +# Automated backups +sudo crontab -e +# Add: +# 0 2 * * * /home/cmc/cmc-sales/scripts/backup-db.sh production +# 0 3 * * * /home/cmc/cmc-sales/scripts/backup-db.sh staging +``` + +## Security Benefits with Caddy + +1. **Automatic HTTPS**: No manual certificate management +2. **Modern TLS**: Always up-to-date TLS configuration +3. **OCSP Stapling**: Enabled by default +4. **Security Headers**: Easy to configure +5. **Rate Limiting**: Built-in support + +## Troubleshooting + +### Caddy Issues + +```bash +# Check Caddy configuration +caddy validate --config /etc/caddy/Caddyfile + +# Check Caddy service +sudo systemctl status caddy +sudo journalctl -u caddy -n 100 + +# Test reverse proxy +curl -v http://localhost:8094/api/v1/health +``` + +### Container Issues + +```bash +# Check container logs +docker compose -f docker-compose.caddy-production.yml logs -f + +# Restart specific service +docker compose -f docker-compose.caddy-production.yml restart cmc-go-production +``` + +### SSL Issues + +```bash +# Caddy automatically handles SSL, but if issues arise: +# 1. Check DNS is resolving correctly +dig cmc.springupsoftware.com + +# 2. Check Caddy can reach Let's Encrypt +sudo journalctl -u caddy | grep -i acme + +# 3. Ensure ports 80 and 443 are open +sudo ufw status +``` + +## Advantages of Caddy Setup + +1. **Simpler Configuration**: Caddyfile is more readable than nginx +2. **Automatic HTTPS**: No certbot or lego needed +3. **Zero-Downtime Reloads**: Config changes without dropping connections +4. **Better Performance**: More efficient than nginx for this use case +5. **Native Rate Limiting**: Built-in without additional modules +6. **Automatic Certificate Renewal**: No cron jobs needed + +## Migration from Nginx + +If migrating from the nginx setup: + +1. Stop nginx containers: `docker compose -f docker-compose.proxy.yml down` +2. Install and configure Caddy +3. Start new containers with caddy compose files +4. Update DNS if needed +5. Monitor logs during transition + +## File Structure + +``` +/home/cmc/cmc-sales/ +├── docker-compose.caddy-staging.yml +├── docker-compose.caddy-production.yml +├── Caddyfile +├── credentials/ +│ ├── staging/ +│ └── production/ +├── scripts/ +│ ├── backup-db.sh +│ ├── restore-db.sh +│ ├── install-caddy.sh +│ └── setup-caddy-auth.sh +└── .env files + +/etc/caddy/ +└── Caddyfile (deployed config) + +/var/log/caddy/ +├── cmc-production.log +└── cmc-staging.log +``` \ No newline at end of file diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md index 1b73be5b..959b64a3 100644 --- a/DEPLOYMENT.md +++ b/DEPLOYMENT.md @@ -45,8 +45,8 @@ Ensure these DNS records point to your server: ### 1. Clone Repository ```bash -cd /opt -sudo git clone cmc-sales +cd /home/cmc +git clone git@code.springupsoftware.com:cmc/cmc-sales.git cmc-sales sudo chown -R $USER:$USER cmc-sales cd cmc-sales ``` @@ -58,7 +58,7 @@ cd cmc-sales cp .env.staging go-app/.env.staging cp .env.production go-app/.env.production -# Edit with actual passwords +# Edit with actual passwords -- up to this. nano .env.staging nano .env.production @@ -94,7 +94,7 @@ go run cmd/auth/main.go docker compose -f docker-compose.proxy.yml up -d # Setup SSL certificates using Lego -./scripts/setup-lego-certs.sh admin@springupsoftware.com +./scripts/setup-lego-certs.sh accounts@springupsoftware.com # Verify certificates ./scripts/lego-list-certs.sh @@ -128,8 +128,14 @@ docker compose -f docker-compose.staging.yml up -d # Start production environment docker compose -f docker-compose.production.yml up -d +# Wait for services to be ready +sleep 10 + # Start reverse proxy (after both environments are running) docker compose -f docker-compose.proxy.yml up -d + +# Or use the make command for full stack deployment +make full-stack ``` ### Updating Applications diff --git a/app/config/bootstrap.php b/app/config/bootstrap.php index 6b9502fc..35497bd2 100755 --- a/app/config/bootstrap.php +++ b/app/config/bootstrap.php @@ -43,4 +43,6 @@ * */ //EOF + +require_once(dirname(__FILE__) . '/php7_compat.php'); ?> \ No newline at end of file diff --git a/app/config/php7_compat.php b/app/config/php7_compat.php new file mode 100644 index 00000000..3bab09f6 --- /dev/null +++ b/app/config/php7_compat.php @@ -0,0 +1,96 @@ + Date: Fri, 8 Aug 2025 13:31:27 +1000 Subject: [PATCH 09/17] Giant changes to make it work on php7 --- Dockerfile.ubuntu-php | 6 +- app/.DS_Store | Bin 0 -> 6148 bytes app/config/database.php | 17 +- app/config/database_stg.php | 8 +- app/config/php7_compat.php | 8 + app/webroot/.DS_Store | Bin 0 -> 8196 bytes app/webroot/test_setup.php | 111 ++++++++++ cake/console/error.php | 2 +- cake/console/libs/console.php | 2 +- cake/console/libs/schema.php | 4 +- cake/console/libs/shell.php | 8 +- cake/console/libs/tasks/controller.php | 2 +- cake/console/libs/tasks/project.php | 8 +- cake/console/libs/tasks/view.php | 2 +- cake/dispatcher.php | 6 +- cake/libs/cache.php | 8 +- cake/libs/cache/file.php | 2 +- cake/libs/cache/memcache.php | 2 +- cake/libs/class_registry.php | 6 +- cake/libs/configure.php | 12 +- cake/libs/controller/component.php | 6 +- cake/libs/controller/components/acl.php | 6 +- cake/libs/controller/components/auth.php | 2 +- cake/libs/controller/components/cookie.php | 2 +- cake/libs/controller/components/email.php | 4 +- .../controller/components/request_handler.php | 2 +- cake/libs/controller/components/security.php | 2 +- cake/libs/controller/controller.php | 6 +- cake/libs/controller/scaffold.php | 2 +- cake/libs/debugger.php | 4 +- cake/libs/error.php | 6 +- cake/libs/file.php | 4 +- cake/libs/flay.php | 2 +- cake/libs/folder.php | 2 +- cake/libs/i18n.php | 6 +- cake/libs/inflector.php | 4 +- cake/libs/l10n.php | 2 +- cake/libs/magic_db.php | 10 +- cake/libs/model/behavior.php | 6 +- cake/libs/model/connection_manager.php | 8 +- cake/libs/model/datasources/datasource.php | 2 +- cake/libs/model/schema.php | 6 +- cake/libs/multibyte.php | 4 +- cake/libs/object.php | 5 +- cake/libs/overloadable_php4.php | 4 +- cake/libs/overloadable_php5.php | 4 +- cake/libs/router.php | 4 +- cake/libs/security.php | 4 +- cake/libs/session.php | 2 +- cake/libs/set.php | 2 +- cake/libs/socket.php | 2 +- cake/libs/string.php | 4 +- cake/libs/validation.php | 4 +- cake/libs/view/helpers/cache.php | 2 +- cake/libs/view/helpers/js.php | 2 +- cake/libs/view/helpers/xml.php | 4 +- cake/libs/view/view.php | 4 +- cake/libs/xml.php | 8 +- cake/tests/cases/console/cake.test.php | 12 +- cake/tests/cases/console/libs/acl.test.php | 4 +- cake/tests/cases/console/libs/api.test.php | 4 +- cake/tests/cases/console/libs/schema.test.php | 18 +- cake/tests/cases/console/libs/shell.test.php | 4 +- .../cases/console/libs/tasks/extract.test.php | 4 +- .../cases/console/libs/tasks/test.test.php | 4 +- cake/tests/cases/dispatcher.test.php | 98 ++++----- cake/tests/cases/libs/cake_test_case.test.php | 14 +- .../cases/libs/cake_test_fixture.test.php | 24 +-- .../cases/libs/code_coverage_manager.test.php | 4 +- .../cases/libs/controller/component.test.php | 48 ++--- .../libs/controller/components/acl.test.php | 10 +- .../libs/controller/components/auth.test.php | 22 +- .../libs/controller/components/email.test.php | 4 +- .../controller/components/security.test.php | 2 +- .../controller/components/session.test.php | 48 ++--- .../cases/libs/controller/controller.test.php | 86 ++++---- .../controller/controller_merge_vars.test.php | 14 +- .../libs/controller/pages_controller.test.php | 2 +- .../cases/libs/controller/scaffold.test.php | 18 +- cake/tests/cases/libs/error.test.php | 4 +- cake/tests/cases/libs/file.test.php | 24 +-- cake/tests/cases/libs/folder.test.php | 60 +++--- cake/tests/cases/libs/http_socket.test.php | 4 +- cake/tests/cases/libs/l10n.test.php | 8 +- cake/tests/cases/libs/magic_db.test.php | 4 +- cake/tests/cases/libs/model/behavior.test.php | 4 +- .../cases/libs/model/behaviors/acl.test.php | 16 +- .../libs/model/behaviors/containable.test.php | 2 +- .../libs/model/behaviors/translate.test.php | 44 ++-- .../cases/libs/model/behaviors/tree.test.php | 120 +++++------ .../model/datasources/dbo/dbo_mysql.test.php | 8 +- .../model/datasources/dbo/dbo_oracle.test.php | 2 +- .../datasources/dbo/dbo_postgres.test.php | 12 +- .../model/datasources/dbo/dbo_sqlite.test.php | 4 +- .../model/datasources/dbo_source.test.php | 60 +++--- cake/tests/cases/libs/model/db_acl.test.php | 8 +- .../cases/libs/model/model_delete.test.php | 24 +-- .../libs/model/model_integration.test.php | 58 +++--- .../cases/libs/model/model_read.test.php | 94 ++++----- .../libs/model/model_validation.test.php | 4 +- .../cases/libs/model/model_write.test.php | 118 +++++------ cake/tests/cases/libs/model/schema.test.php | 2 +- cake/tests/cases/libs/object.test.php | 4 +- cake/tests/cases/libs/sanitize.test.php | 4 +- cake/tests/cases/libs/session.test.php | 2 +- cake/tests/cases/libs/test_manager.test.php | 8 +- .../cases/libs/view/helpers/ajax.test.php | 12 +- .../cases/libs/view/helpers/form.test.php | 12 +- .../cases/libs/view/helpers/html.test.php | 4 +- .../libs/view/helpers/javascript.test.php | 12 +- .../cases/libs/view/helpers/number.test.php | 2 +- .../libs/view/helpers/paginator.test.php | 10 +- .../cases/libs/view/helpers/rss.test.php | 4 +- .../cases/libs/view/helpers/xml.test.php | 4 +- cake/tests/cases/libs/view/theme.test.php | 2 +- cake/tests/cases/libs/view/view.test.php | 8 +- cake/tests/cases/libs/xml.test.php | 32 +-- cake/tests/lib/cake_test_case.php | 6 +- cake/tests/lib/cake_test_fixture.php | 4 +- cake/tests/lib/code_coverage_manager.php | 8 +- cake/tests/lib/test_manager.php | 44 ++-- .../components/other_component.php | 2 +- .../components/plugins_component.php | 2 +- .../components/test_plugin_component.php | 2 +- .../test_plugin_other_component.php | 2 +- conf/nginx-proxy.conf | 6 +- docker-compose.caddy-staging-ubuntu.yml | 14 +- docker-compose.proxy.yml | 68 ------ index.php | 6 + scripts/backup-db.sh | 56 +++++ scripts/debug-php-container.sh | 57 +++++ scripts/deploy-staging-caddy.sh | 127 ++++++++++++ scripts/fix-cakephp-compatibility.sh | 145 +++++++++++++ scripts/fix-cakephp-php7.sh | 16 ++ scripts/install-caddy.sh | 50 +++++ scripts/lego-list-certs.sh | 23 +++ scripts/lego-obtain-cert.sh | 50 +++++ scripts/lego-renew-cert.sh | 64 ++++++ scripts/manage-staging-caddy.sh | 194 ++++++++++++++++++ scripts/quick-rebuild-staging.sh | 26 +++ scripts/restore-db.sh | 78 +++++++ scripts/setup-caddy-auth.sh | 42 ++++ scripts/setup-lego-certs.sh | 56 +++++ scripts/setup-staging-native.sh | 149 ++++++++++++++ scripts/test-php-setup.sh | 77 +++++++ 145 files changed, 2144 insertions(+), 845 deletions(-) create mode 100644 app/.DS_Store create mode 100644 app/webroot/.DS_Store create mode 100644 app/webroot/test_setup.php delete mode 100644 docker-compose.proxy.yml create mode 100755 scripts/backup-db.sh create mode 100755 scripts/debug-php-container.sh create mode 100755 scripts/deploy-staging-caddy.sh create mode 100755 scripts/fix-cakephp-compatibility.sh create mode 100755 scripts/fix-cakephp-php7.sh create mode 100755 scripts/install-caddy.sh create mode 100755 scripts/lego-list-certs.sh create mode 100755 scripts/lego-obtain-cert.sh create mode 100755 scripts/lego-renew-cert.sh create mode 100755 scripts/manage-staging-caddy.sh create mode 100755 scripts/quick-rebuild-staging.sh create mode 100755 scripts/restore-db.sh create mode 100755 scripts/setup-caddy-auth.sh create mode 100755 scripts/setup-lego-certs.sh create mode 100755 scripts/setup-staging-native.sh create mode 100755 scripts/test-php-setup.sh diff --git a/Dockerfile.ubuntu-php b/Dockerfile.ubuntu-php index cb5d7837..e92fffd1 100644 --- a/Dockerfile.ubuntu-php +++ b/Dockerfile.ubuntu-php @@ -65,8 +65,12 @@ RUN chown -R www-data:www-data /var/www/cmc-sales \ # Set working directory WORKDIR /var/www/cmc-sales -# Copy application (will be overridden by volume mount) +# Copy CakePHP core and application +COPY cake/ /var/www/cmc-sales/cake/ COPY app/ /var/www/cmc-sales/app/ +COPY vendors/ /var/www/cmc-sales/vendors/ +COPY index.php /var/www/cmc-sales/ +COPY *.sh /var/www/cmc-sales/ # Expose port 80 EXPOSE 80 diff --git a/app/.DS_Store b/app/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..9e09c8d19f7e10af5ac6ede482cd13625d0dd00b GIT binary patch literal 6148 zcmeHK%}T>S5Z-O8O({YS3VK`cS};Lt4_-p8FJMFuDz%|OgE3o@)Er77cYPsW#OHBl zcOz7D@FZeqVDrt+&+g6#*&oIjAI_&PV>V;Vf`-UZsSz~Sx*8@Jk*hHzlPnL4Y!<{d z1N}u4uD#6)7P5e)u=>yS%K$uY!7Prl+;QG{quJWnY+IJqwQl_fS@`)RpJ&5KdX2pc zDdV8hC&6VD7Grz+R3`Z(O2SknMAHyLZmyzaDvP0aJDQR4g$-4E%%v+#duqM9*NUQEeUY!Rs^nTZky2<68nz81xL5 z8o>j?bt<4v<>raObvoFEiSrDW8g)A3YGxS6%v?QQxSAd8LWMK#X{0YPKn$!h(9~TU z&;K*{WojS!t0~kY28e-w#sF`P{Lv7KGH2_z^6;z`(C(n2U|fj`2 'cmc', 'prefix' => '', ); + + function __construct() { + // Use environment-specific database settings if APP_ENV is set + if (isset($_ENV['APP_ENV']) && $_ENV['APP_ENV'] == 'staging') { + $this->default = array( + 'driver' => 'mysql', + 'persistent' => false, + 'host' => 'db-staging', + 'login' => 'cmc_staging', + 'password' => 'staging_password', + 'database' => 'cmc_staging', + 'prefix' => '', + ); + } + } } diff --git a/app/config/database_stg.php b/app/config/database_stg.php index 1ee8c813..e0888f2b 100644 --- a/app/config/database_stg.php +++ b/app/config/database_stg.php @@ -5,10 +5,10 @@ var $default = array( 'driver' => 'mysql', 'persistent' => false, - 'host' => '172.17.0.1', - 'login' => 'staging', - 'password' => 'stagingmoopwoopVerySecure', - 'database' => 'staging', + 'host' => 'db-staging', + 'login' => 'cmc_staging', + 'password' => 'staging_password', + 'database' => 'cmc_staging', 'prefix' => '', ); } diff --git a/app/config/php7_compat.php b/app/config/php7_compat.php index 3bab09f6..639f68a2 100644 --- a/app/config/php7_compat.php +++ b/app/config/php7_compat.php @@ -93,4 +93,12 @@ if (!function_exists('mysql_connect')) { function mysql_real_escape_string($unescaped_string, $link_identifier = null) { return mysqli_real_escape_string($link_identifier, $unescaped_string); } +} + +// Create alias for Object class to fix PHP 7 reserved word issue +// This should be included AFTER CakePHP's Object class is defined +function create_object_alias() { + if (class_exists('CakeObject') && !class_exists('Object', false)) { + class_alias('CakeObject', 'Object'); + } } \ No newline at end of file diff --git a/app/webroot/.DS_Store b/app/webroot/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..3e71061e36612cfaf9b50dc42a81d5baac2fc11d GIT binary patch literal 8196 zcmeHMTWl0n7(U;$z?p&4X(`(ly0WpNSPPT_1uT;74a&8KZD}d!I=eH_k?Bm`ncaef zSff5@)R=gSCKBW2!3Rmapou2x119K$52i6<)E6T@s8JvFMgKErmP>&rgOV^One(0h zKj%M}|9t(T?_{g9$ZU^>DniQ%h*vhWH( zD6RluqOvXugsBMA5l%^@8cL9+gwhnz6$8?o^r@&_I>IT5(wrf>d>|Sb(G3OR=+u8I zY|fCD80WDEVh>#E0TDhGY=W8WKyLEF`@3WNL0j8bP%0{C&7Q+KpUdycjCqrpzzB+d zw^7(9q(RSfa^m3bCC$s0x3AmS)wgx$bk+Q7U8~jVhD)|@=NxNj(l&#!y@sE+T+?DG1+@mF>Y!_kTcK5=KGDeaW| z=@oJxE^3!ULGX zLwFcZ;5j^x7w{t9z}t8S@8V;e#%K5(-{MD{#ZUMHe<@W;wW2FEO0BY3S*FluJdu=g zR18bGoGa~Aib9;CBKkz99JyRnBsXvAzc!-c%sdeXHMI-s7TzF&qoXr@jzW@jWu9Hg z-;lBw?P*BaFhpi@Em7alxM;DK93oCzhi67vIr{WDg1vlNv|f_ZlKL!Sy%cX+O5$u{ zycBP3NhWngKgp%IVr5d(D=3WA>Bjnogw~?1RaG5fN9)#WnqEl(rH10hJ4j?AmZjX) zO+AV5_!mTdi+#X8VW-(N5%nzlndtd9IOd~{Xn8Z1;Wo5lIZ<;xZbxTG&n-mGZP<=M z>>+~gC5q-@;ULCfqW~X4NYe*Hnm&Rj@f4oMGk6xq@iJb)t9T8s;{-m$DM`F@blg@Z zqC|Xpo{ptV!F4?MAZg0vy|{5KT}=;E$j%$Y{lD+Z-~X@X6ym;P55yk$pFM!e-b`;d zP2x%~VR6?^(Q^+yB8hfW5CakePHP Setup Test"; + +// Test 1: PHP Version +echo "

PHP Information

"; +echo "

PHP Version: " . PHP_VERSION . "

"; +echo "

Server API: " . php_sapi_name() . "

"; + +// Test 2: Required Extensions +echo "

PHP Extensions

"; +$extensions = ['mysql', 'mysqli', 'gd', 'curl', 'mbstring']; +foreach ($extensions as $ext) { + $loaded = extension_loaded($ext); + echo "

$ext: " . ($loaded ? '✓ Loaded' : '✗ Not Loaded') . "

"; +} + +// Test 3: CakePHP Constants +echo "

CakePHP Constants

"; +$constants = ['ROOT', 'APP_DIR', 'CAKE_CORE_INCLUDE_PATH', 'WWW_ROOT']; +foreach ($constants as $const) { + if (defined($const)) { + echo "

$const: " . constant($const) . "

"; + } else { + echo "

$const: ✗ Not defined

"; + } +} + +// Test 4: File System +echo "

File System

"; +$paths = [ + '/var/www/cmc-sales', + '/var/www/cmc-sales/cake', + '/var/www/cmc-sales/app', + '/var/www/cmc-sales/app/webroot' +]; + +foreach ($paths as $path) { + $exists = file_exists($path); + $readable = is_readable($path); + echo "

$path: " . + ($exists ? '✓ Exists' : '✗ Missing') . + ($readable ? ', ✓ Readable' : ', ✗ Not readable') . "

"; +} + +// Test 5: CakePHP Core +echo "

CakePHP Core Test

"; +$cake_bootstrap = '/var/www/cmc-sales/cake/bootstrap.php'; +if (file_exists($cake_bootstrap)) { + echo "

CakePHP Bootstrap: ✓ Found at $cake_bootstrap

"; + + // Try to include it + try { + if (!defined('CAKE_CORE_INCLUDE_PATH')) { + define('CAKE_CORE_INCLUDE_PATH', '/var/www/cmc-sales'); + } + if (!defined('ROOT')) { + define('ROOT', '/var/www/cmc-sales'); + } + if (!defined('APP_DIR')) { + define('APP_DIR', 'app'); + } + if (!defined('DS')) { + define('DS', DIRECTORY_SEPARATOR); + } + + echo "

Include Test: Ready to include CakePHP

"; + // Note: We don't actually include it here to avoid conflicts + + } catch (Exception $e) { + echo "

Include Test: ✗ Error - " . $e->getMessage() . "

"; + } +} else { + echo "

CakePHP Bootstrap: ✗ Not found

"; +} + +// Test 6: Database +echo "

Database Test

"; +$db_host = $_ENV['DB_HOST'] ?? 'db-staging'; +$db_user = $_ENV['DB_USER'] ?? 'cmc_staging'; +$db_pass = $_ENV['DB_PASSWORD'] ?? ''; +$db_name = $_ENV['DB_NAME'] ?? 'cmc_staging'; + +echo "

DB Host: $db_host

"; +echo "

DB User: $db_user

"; +echo "

DB Name: $db_name

"; + +if (function_exists('mysqli_connect')) { + $conn = @mysqli_connect($db_host, $db_user, $db_pass, $db_name); + if ($conn) { + echo "

Database Connection: ✓ Connected

"; + mysqli_close($conn); + } else { + echo "

Database Connection: ✗ Failed - " . mysqli_connect_error() . "

"; + } +} else { + echo "

Database Connection: ✗ MySQLi not available

"; +} + +echo "

Server Information

"; +echo "
";
+echo "Document Root: " . $_SERVER['DOCUMENT_ROOT'] . "\n";
+echo "Script Name: " . $_SERVER['SCRIPT_NAME'] . "\n";
+echo "Working Directory: " . getcwd() . "\n";
+echo "
"; + +echo "

Generated at: " . date('Y-m-d H:i:s') . "

"; +?> \ No newline at end of file diff --git a/cake/console/error.php b/cake/console/error.php index 9c88a40b..c47367a1 100755 --- a/cake/console/error.php +++ b/cake/console/error.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.console */ -class ErrorHandler extends Object { +class ErrorHandler extends CakeObject { /** * Standard output stream. * diff --git a/cake/console/libs/console.php b/cake/console/libs/console.php index 19b07509..5afd5ed4 100755 --- a/cake/console/libs/console.php +++ b/cake/console/libs/console.php @@ -64,7 +64,7 @@ class ConsoleShell extends Shell { foreach ($this->models as $model) { $class = Inflector::camelize(r('.php', '', $model)); $this->models[$model] = $class; - $this->{$class} =& new $class(); + $this->{$class} = new $class(); } $this->out('Model classes:'); $this->out('--------------'); diff --git a/cake/console/libs/schema.php b/cake/console/libs/schema.php index 36974eb5..43c86b5e 100755 --- a/cake/console/libs/schema.php +++ b/cake/console/libs/schema.php @@ -79,7 +79,7 @@ class SchemaShell extends Shell { $connection = $this->params['connection']; } - $this->Schema =& new CakeSchema(compact('name', 'path', 'file', 'connection')); + $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection')); } /** * Override main @@ -138,7 +138,7 @@ class SchemaShell extends Shell { $content['file'] = $this->params['file']; if ($snapshot === true) { - $Folder =& new Folder($this->Schema->path); + $Folder = new Folder($this->Schema->path); $result = $Folder->read(); $numToUse = false; diff --git a/cake/console/libs/shell.php b/cake/console/libs/shell.php index eed6bff8..e847fb53 100755 --- a/cake/console/libs/shell.php +++ b/cake/console/libs/shell.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.console.libs */ -class Shell extends Object { +class Shell extends CakeObject { /** * An instance of the ShellDispatcher object that loaded this script * @@ -200,7 +200,7 @@ class Shell extends Object { */ function _loadDbConfig() { if (config('database') && class_exists('DATABASE_CONFIG')) { - $this->DbConfig =& new DATABASE_CONFIG(); + $this->DbConfig = new DATABASE_CONFIG(); return true; } $this->err('Database config could not be loaded'); @@ -222,7 +222,7 @@ class Shell extends Object { } if ($this->uses === true && App::import('Model', 'AppModel')) { - $this->AppModel =& new AppModel(false, false, false); + $this->AppModel = new AppModel(false, false, false); return true; } @@ -290,7 +290,7 @@ class Shell extends Object { } else { $this->taskNames[] = $taskName; if (!PHP5) { - $this->{$taskName} =& new $taskClass($this->Dispatch); + $this->{$taskName} = new $taskClass($this->Dispatch); } else { $this->{$taskName} = new $taskClass($this->Dispatch); } diff --git a/cake/console/libs/tasks/controller.php b/cake/console/libs/tasks/controller.php index 736522a8..e5e6d852 100755 --- a/cake/console/libs/tasks/controller.php +++ b/cake/console/libs/tasks/controller.php @@ -252,7 +252,7 @@ class ControllerTask extends Shell { exit; } $actions = null; - $modelObj =& new $currentModelName(); + $modelObj = new $currentModelName(); $controllerPath = $this->_controllerPath($controllerName); $pluralName = $this->_pluralName($currentModelName); $singularName = Inflector::variable($currentModelName); diff --git a/cake/console/libs/tasks/project.php b/cake/console/libs/tasks/project.php index f7a0c302..d61734a8 100755 --- a/cake/console/libs/tasks/project.php +++ b/cake/console/libs/tasks/project.php @@ -192,7 +192,7 @@ class ProjectTask extends Shell { * @access public */ function securitySalt($path) { - $File =& new File($path . 'config' . DS . 'core.php'); + $File = new File($path . 'config' . DS . 'core.php'); $contents = $File->read(); if (preg_match('/([\\t\\x20]*Configure::write\\(\\\'Security.salt\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { if (!class_exists('Security')) { @@ -216,7 +216,7 @@ class ProjectTask extends Shell { */ function corePath($path) { if (dirname($path) !== CAKE_CORE_INCLUDE_PATH) { - $File =& new File($path . 'webroot' . DS . 'index.php'); + $File = new File($path . 'webroot' . DS . 'index.php'); $contents = $File->read(); if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { $result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents); @@ -227,7 +227,7 @@ class ProjectTask extends Shell { return false; } - $File =& new File($path . 'webroot' . DS . 'test.php'); + $File = new File($path . 'webroot' . DS . 'test.php'); $contents = $File->read(); if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { $result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents); @@ -248,7 +248,7 @@ class ProjectTask extends Shell { * @access public */ function cakeAdmin($name) { - $File =& new File(CONFIGS . 'core.php'); + $File = new File(CONFIGS . 'core.php'); $contents = $File->read(); if (preg_match('%([/\\t\\x20]*Configure::write\(\'Routing.admin\',[\\t\\x20\'a-z]*\\);)%', $contents, $match)) { $result = str_replace($match[0], "\t" . 'Configure::write(\'Routing.admin\', \''.$name.'\');', $contents); diff --git a/cake/console/libs/tasks/view.php b/cake/console/libs/tasks/view.php index cd60df61..bc3b9ad2 100755 --- a/cake/console/libs/tasks/view.php +++ b/cake/console/libs/tasks/view.php @@ -290,7 +290,7 @@ class ViewTask extends Shell { $content = $this->getContent(); } $filename = $this->path . $this->controllerPath . DS . Inflector::underscore($action) . '.ctp'; - $Folder =& new Folder($this->path . $this->controllerPath, true); + $Folder = new Folder($this->path . $this->controllerPath, true); $errors = $Folder->errors(); if (empty($errors)) { $path = $Folder->slashTerm($Folder->pwd()); diff --git a/cake/dispatcher.php b/cake/dispatcher.php index ca147f30..d8765bf0 100755 --- a/cake/dispatcher.php +++ b/cake/dispatcher.php @@ -37,7 +37,7 @@ App::import('Core', array('Router', 'Controller')); * @package cake * @subpackage cake.cake */ -class Dispatcher extends Object { +class Dispatcher extends CakeObject { /** * Base URL * @@ -456,7 +456,7 @@ class Dispatcher extends Object { $params = $this->_restructureParams($params, true); } $this->params = $params; - $controller =& new $ctrlClass(); + $controller = new $ctrlClass(); } return $controller; } @@ -679,7 +679,7 @@ class Dispatcher extends Object { App::import('Core', 'View'); } $controller = null; - $view =& new View($controller, false); + $view = new View($controller, false); return $view->renderCache($filename, getMicrotime()); } } diff --git a/cake/libs/cache.php b/cake/libs/cache.php index aabd2795..6a3c2ce6 100755 --- a/cake/libs/cache.php +++ b/cake/libs/cache.php @@ -29,7 +29,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Cache extends Object { +class Cache extends CakeObject { /** * Cache engine to use * @@ -68,7 +68,7 @@ class Cache extends Object { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] =& new Cache(); + $instance[0] = new Cache(); } return $instance[0]; } @@ -148,7 +148,7 @@ class Cache extends Object { if ($_this->__loadEngine($name) === false) { return false; } - $_this->_Engine[$name] =& new $cacheClass(); + $_this->_Engine[$name] = new $cacheClass(); } if ($_this->_Engine[$name]->init($settings)) { @@ -406,7 +406,7 @@ class Cache extends Object { * @package cake * @subpackage cake.cake.libs */ -class CacheEngine extends Object { +class CacheEngine extends CakeObject { /** * settings of current engine instance * diff --git a/cake/libs/cache/file.php b/cake/libs/cache/file.php index abbd5a0e..fecf9794 100755 --- a/cake/libs/cache/file.php +++ b/cake/libs/cache/file.php @@ -86,7 +86,7 @@ class FileEngine extends CacheEngine { if (!class_exists('File')) { require LIBS . 'file.php'; } - $this->__File =& new File($this->settings['path'] . DS . 'cake'); + $this->__File = new File($this->settings['path'] . DS . 'cake'); } if (DIRECTORY_SEPARATOR === '\\') { diff --git a/cake/libs/cache/memcache.php b/cake/libs/cache/memcache.php index 2d70a6e8..5c4bbeb3 100755 --- a/cake/libs/cache/memcache.php +++ b/cake/libs/cache/memcache.php @@ -73,7 +73,7 @@ class MemcacheEngine extends CacheEngine { } if (!isset($this->__Memcache)) { $return = false; - $this->__Memcache =& new Memcache(); + $this->__Memcache = new Memcache(); foreach ($this->settings['servers'] as $server) { $parts = explode(':', $server); $host = $parts[0]; diff --git a/cake/libs/class_registry.php b/cake/libs/class_registry.php index 5ff5ec32..5b97257f 100755 --- a/cake/libs/class_registry.php +++ b/cake/libs/class_registry.php @@ -65,7 +65,7 @@ class ClassRegistry { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] =& new ClassRegistry(); + $instance[0] = new ClassRegistry(); } return $instance[0]; } @@ -137,7 +137,7 @@ class ClassRegistry { } if (class_exists($class) || App::import($type, $pluginPath . $class)) { - ${$class} =& new $class($settings); + ${$class} = new $class($settings); } elseif ($type === 'Model') { if ($plugin && class_exists($plugin . 'AppModel')) { $appModel = $plugin . 'AppModel'; @@ -145,7 +145,7 @@ class ClassRegistry { $appModel = 'AppModel'; } $settings['name'] = $class; - ${$class} =& new $appModel($settings); + ${$class} = new $appModel($settings); } if (!isset(${$class})) { diff --git a/cake/libs/configure.php b/cake/libs/configure.php index c9056d28..42c16de5 100755 --- a/cake/libs/configure.php +++ b/cake/libs/configure.php @@ -31,7 +31,7 @@ * @subpackage cake.cake.libs * @link http://book.cakephp.org/view/42/The-Configuration-Class */ -class Configure extends Object { +class Configure extends CakeObject { /** * List of additional path(s) where model files reside. * @@ -133,7 +133,7 @@ class Configure extends Object { static function &getInstance($boot = true) { static $instance = array(); if (!$instance) { - $instance[0] =& new Configure(); + $instance[0] = new Configure(); $instance[0]->__loadBootstrap($boot); } return $instance[0]; @@ -223,7 +223,7 @@ class Configure extends Object { require LIBS . 'folder.php'; } $items = array(); - $Folder =& new Folder($path); + $Folder = new Folder($path); $contents = $Folder->read(false, true); if (is_array($contents)) { @@ -717,7 +717,7 @@ class Configure extends Object { * @package cake * @subpackage cake.cake.libs */ -class App extends Object { +class App extends CakeObject { /** * Paths to search for files. * @@ -903,7 +903,7 @@ class App extends Object { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] =& new App(); + $instance[0] = new App(); $instance[0]->__map = Cache::read('file_map', '_cake_core_'); } return $instance[0]; @@ -943,7 +943,7 @@ class App extends Object { if (!class_exists('Folder')) { require LIBS . 'folder.php'; } - $Folder =& new Folder(); + $Folder = new Folder(); $directories = $Folder->tree($path, false, 'dir'); $this->__paths[$path] = $directories; } diff --git a/cake/libs/controller/component.php b/cake/libs/controller/component.php index c40571cd..4cb46a0e 100755 --- a/cake/libs/controller/component.php +++ b/cake/libs/controller/component.php @@ -28,7 +28,7 @@ * @subpackage cake.cake.libs.controller * @link http://book.cakephp.org/view/62/Components */ -class Component extends Object { +class Component extends CakeObject { /** * Contains various controller variable information (plugin, name, base). * @@ -234,9 +234,9 @@ class Component extends Object { } } else { if ($componentCn === 'SessionComponent') { - $object->{$component} =& new $componentCn($base); + $object->{$component} = new $componentCn($base); } else { - $object->{$component} =& new $componentCn(); + $object->{$component} = new $componentCn(); } $object->{$component}->enabled = true; $this->_loaded[$component] =& $object->{$component}; diff --git a/cake/libs/controller/components/acl.php b/cake/libs/controller/components/acl.php index d68c61f0..b2e4ad2d 100755 --- a/cake/libs/controller/components/acl.php +++ b/cake/libs/controller/components/acl.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.controller.components */ -class AclComponent extends Object { +class AclComponent extends CakeObject { /** * Instance of an ACL class * @@ -56,7 +56,7 @@ class AclComponent extends Object { trigger_error(sprintf(__('Could not find %s.', true), $name), E_USER_WARNING); } } - $this->_Instance =& new $name(); + $this->_Instance = new $name(); $this->_Instance->initialize($this); } /** @@ -157,7 +157,7 @@ class AclComponent extends Object { * @subpackage cake.cake.libs.controller.components * @abstract */ -class AclBase extends Object { +class AclBase extends CakeObject { /** * This class should never be instantiated, just subclassed. * diff --git a/cake/libs/controller/components/auth.php b/cake/libs/controller/components/auth.php index 1aa37e52..0d0c65ca 100755 --- a/cake/libs/controller/components/auth.php +++ b/cake/libs/controller/components/auth.php @@ -36,7 +36,7 @@ App::import(array('Router', 'Security')); * @package cake * @subpackage cake.cake.libs.controller.components */ -class AuthComponent extends Object { +class AuthComponent extends CakeObject { /** * Maintains current user login state. * diff --git a/cake/libs/controller/components/cookie.php b/cake/libs/controller/components/cookie.php index 56713f5c..1e0a063d 100755 --- a/cake/libs/controller/components/cookie.php +++ b/cake/libs/controller/components/cookie.php @@ -37,7 +37,7 @@ App::import('Core', 'Security'); * @subpackage cake.cake.libs.controller.components * */ -class CookieComponent extends Object { +class CookieComponent extends CakeObject { /** * The name of the cookie. * diff --git a/cake/libs/controller/components/email.php b/cake/libs/controller/components/email.php index b2e2ea42..b45ae072 100755 --- a/cake/libs/controller/components/email.php +++ b/cake/libs/controller/components/email.php @@ -35,7 +35,7 @@ * */ App::import('Core', 'Multibyte'); -class EmailComponent extends Object{ +class EmailComponent extends CakeObject{ /** * Recipient of the email * @@ -671,7 +671,7 @@ class EmailComponent extends Object{ function __smtp() { App::import('Core', array('Socket')); - $this->__smtpConnection =& new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->smtpOptions)); + $this->__smtpConnection = new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->smtpOptions)); if (!$this->__smtpConnection->connect()) { $this->smtpError = $this->__smtpConnection->lastError(); diff --git a/cake/libs/controller/components/request_handler.php b/cake/libs/controller/components/request_handler.php index efca6b2c..999e4ea2 100755 --- a/cake/libs/controller/components/request_handler.php +++ b/cake/libs/controller/components/request_handler.php @@ -36,7 +36,7 @@ if (!defined('REQUEST_MOBILE_UA')) { * @subpackage cake.cake.libs.controller.components * */ -class RequestHandlerComponent extends Object { +class RequestHandlerComponent extends CakeObject { /** * The layout that will be switched to for Ajax requests * diff --git a/cake/libs/controller/components/security.php b/cake/libs/controller/components/security.php index 96d14025..d5963a86 100755 --- a/cake/libs/controller/components/security.php +++ b/cake/libs/controller/components/security.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.controller.components */ -class SecurityComponent extends Object { +class SecurityComponent extends CakeObject { /** * The controller method that will be called if this request is black-hole'd * diff --git a/cake/libs/controller/controller.php b/cake/libs/controller/controller.php index 6a582bfc..528c8d71 100755 --- a/cake/libs/controller/controller.php +++ b/cake/libs/controller/controller.php @@ -38,7 +38,7 @@ App::import('Core', array('Component', 'View')); * @link http://book.cakephp.org/view/49/Controllers * */ -class Controller extends Object { +class Controller extends CakeObject { /** * The name of this controller. Controller names are plural, named after the model they manipulate. * @@ -335,7 +335,7 @@ class Controller extends Object { } $this->modelClass = Inflector::classify($this->name); $this->modelKey = Inflector::underscore($this->modelClass); - $this->Component =& new Component(); + $this->Component = new Component(); $childMethods = get_class_methods($this); $parentMethods = get_class_methods('Controller'); @@ -776,7 +776,7 @@ class Controller extends Object { $this->set('cakeDebug', $this); } - $View =& new $viewClass($this); + $View = new $viewClass($this); if (!empty($this->modelNames)) { $models = array(); diff --git a/cake/libs/controller/scaffold.php b/cake/libs/controller/scaffold.php index 165e2b56..cf4be9a2 100755 --- a/cake/libs/controller/scaffold.php +++ b/cake/libs/controller/scaffold.php @@ -35,7 +35,7 @@ * @package cake * @subpackage cake.cake.libs.controller */ -class Scaffold extends Object { +class Scaffold extends CakeObject { /** * Controller object * diff --git a/cake/libs/debugger.php b/cake/libs/debugger.php index f80d05c2..2079e4c1 100755 --- a/cake/libs/debugger.php +++ b/cake/libs/debugger.php @@ -43,7 +43,7 @@ * @subpackage cake.cake.libs * @link http://book.cakephp.org/view/460/Using-the-Debugger-Class */ -class Debugger extends Object { +class Debugger extends CakeObject { /** * A list of errors generated by the application. * @@ -105,7 +105,7 @@ class Debugger extends Object { } if (!$instance) { - $instance[0] =& new Debugger(); + $instance[0] = new Debugger(); if (Configure::read() > 0) { Configure::version(); // Make sure the core config is loaded $instance[0]->helpPath = Configure::read('Cake.Debugger.HelpPath'); diff --git a/cake/libs/error.php b/cake/libs/error.php index e8db8276..4647bba6 100755 --- a/cake/libs/error.php +++ b/cake/libs/error.php @@ -66,7 +66,7 @@ class CakeErrorController extends AppController { * @package cake * @subpackage cake.cake.libs */ -class ErrorHandler extends Object { +class ErrorHandler extends CakeObject { /** * Controller instance. * @@ -86,9 +86,9 @@ class ErrorHandler extends Object { if ($__previousError != array($method, $messages)) { $__previousError = array($method, $messages); - $this->controller =& new CakeErrorController(); + $this->controller = new CakeErrorController(); } else { - $this->controller =& new Controller(); + $this->controller = new Controller(); $this->controller->viewPath = 'errors'; } diff --git a/cake/libs/file.php b/cake/libs/file.php index b57cb4c7..f00fd827 100755 --- a/cake/libs/file.php +++ b/cake/libs/file.php @@ -38,7 +38,7 @@ if (!class_exists('Folder')) { * @package cake * @subpackage cake.cake.libs */ -class File extends Object { +class File extends CakeObject { /** * Folder object of the File * @@ -93,7 +93,7 @@ class File extends Object { */ function __construct($path, $create = false, $mode = 0755) { parent::__construct(); - $this->Folder =& new Folder(dirname($path), $create, $mode); + $this->Folder = new Folder(dirname($path), $create, $mode); if (!is_dir($path)) { $this->name = basename($path); } diff --git a/cake/libs/flay.php b/cake/libs/flay.php index ed23cf7f..9362830f 100755 --- a/cake/libs/flay.php +++ b/cake/libs/flay.php @@ -39,7 +39,7 @@ if (!class_exists('Object')) { * @package cake * @subpackage cake.cake.libs */ -class Flay extends Object{ +class Flay extends CakeObject{ /** * Text to be parsed. * diff --git a/cake/libs/folder.php b/cake/libs/folder.php index 28f32672..3b108a93 100755 --- a/cake/libs/folder.php +++ b/cake/libs/folder.php @@ -37,7 +37,7 @@ if (!class_exists('Object')) { * @package cake * @subpackage cake.cake.libs */ -class Folder extends Object { +class Folder extends CakeObject { /** * Path to Folder. * diff --git a/cake/libs/i18n.php b/cake/libs/i18n.php index 6e21ca5c..31e04834 100755 --- a/cake/libs/i18n.php +++ b/cake/libs/i18n.php @@ -36,7 +36,7 @@ App::import('Core', 'l10n'); * @package cake * @subpackage cake.cake.libs */ -class I18n extends Object { +class I18n extends CakeObject { /** * Instance of the I10n class for localization * @@ -106,8 +106,8 @@ class I18n extends Object { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] =& new I18n(); - $instance[0]->l10n =& new L10n(); + $instance[0] = new I18n(); + $instance[0]->l10n = new L10n(); } return $instance[0]; } diff --git a/cake/libs/inflector.php b/cake/libs/inflector.php index 71f07b4e..5caf467c 100755 --- a/cake/libs/inflector.php +++ b/cake/libs/inflector.php @@ -45,7 +45,7 @@ if (!class_exists('Set')) { * @subpackage cake.cake.libs * @link http://book.cakephp.org/view/491/Inflector */ -class Inflector extends Object { +class Inflector extends CakeObject { /** * Pluralized words. * @@ -128,7 +128,7 @@ class Inflector extends Object { static $instance = array(); if (!$instance) { - $instance[0] =& new Inflector(); + $instance[0] = new Inflector(); if (file_exists(CONFIGS.'inflections.php')) { include(CONFIGS.'inflections.php'); $instance[0]->__pluralRules = $pluralRules; diff --git a/cake/libs/l10n.php b/cake/libs/l10n.php index 95f66c25..6cb8a3fe 100755 --- a/cake/libs/l10n.php +++ b/cake/libs/l10n.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs */ -class L10n extends Object { +class L10n extends CakeObject { /** * The language for current locale * diff --git a/cake/libs/magic_db.php b/cake/libs/magic_db.php index 73b16017..e039b7d9 100755 --- a/cake/libs/magic_db.php +++ b/cake/libs/magic_db.php @@ -31,7 +31,7 @@ if (!class_exists('File')) { * @package cake.tests * @subpackage cake.tests.cases.libs */ -class MagicDb extends Object { +class MagicDb extends CakeObject { /** * Holds the parsed MagicDb for this class instance * @@ -53,7 +53,7 @@ class MagicDb extends Object { if (is_array($magicDb) || strpos($magicDb, '# FILE_ID DB') === 0) { $data = $magicDb; } else { - $File =& new File($magicDb); + $File = new File($magicDb); if (!$File->exists()) { return false; } @@ -158,7 +158,7 @@ class MagicDb extends Object { } $matches = array(); - $MagicFileResource =& new MagicFileResource($file); + $MagicFileResource = new MagicFileResource($file); foreach ($this->db['database'] as $format) { $magic = $format[0]; $match = $MagicFileResource->test($magic); @@ -178,7 +178,7 @@ class MagicDb extends Object { * @package cake.tests * @subpackage cake.tests.cases.libs */ -class MagicFileResource extends Object{ +class MagicFileResource extends CakeObject{ /** * undocumented variable * @@ -202,7 +202,7 @@ class MagicFileResource extends Object{ */ function __construct($file) { if (file_exists($file)) { - $this->resource =& new File($file); + $this->resource = new File($file); } else { $this->resource = $file; } diff --git a/cake/libs/model/behavior.php b/cake/libs/model/behavior.php index fdbc64e3..881b070e 100755 --- a/cake/libs/model/behavior.php +++ b/cake/libs/model/behavior.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.model */ -class ModelBehavior extends Object { +class ModelBehavior extends CakeObject { /** * Contains configuration settings for use with individual model objects. This * is used because if multiple models use this Behavior, each will use the same @@ -204,7 +204,7 @@ class ModelBehavior extends Object { * @package cake * @subpackage cake.cake.libs.model */ -class BehaviorCollection extends Object { +class BehaviorCollection extends CakeObject { /** * Stores a reference to the attached name * @@ -283,7 +283,7 @@ class BehaviorCollection extends Object { if (PHP5) { $this->{$name} = new $class; } else { - $this->{$name} =& new $class; + $this->{$name} = new $class; } ClassRegistry::addObject($class, $this->{$name}); } diff --git a/cake/libs/model/connection_manager.php b/cake/libs/model/connection_manager.php index 32f16984..68f304d1 100755 --- a/cake/libs/model/connection_manager.php +++ b/cake/libs/model/connection_manager.php @@ -35,7 +35,7 @@ config('database'); * @package cake * @subpackage cake.cake.libs.model */ -class ConnectionManager extends Object { +class ConnectionManager extends CakeObject { /** * Holds a loaded instance of the Connections object * @@ -63,7 +63,7 @@ class ConnectionManager extends Object { */ function __construct() { if (class_exists('DATABASE_CONFIG')) { - $this->config =& new DATABASE_CONFIG(); + $this->config = new DATABASE_CONFIG(); } } /** @@ -77,7 +77,7 @@ class ConnectionManager extends Object { static $instance = array(); if (!$instance) { - $instance[0] =& new ConnectionManager(); + $instance[0] = new ConnectionManager(); } return $instance[0]; @@ -103,7 +103,7 @@ class ConnectionManager extends Object { $conn = $connections[$name]; $class = $conn['classname']; $_this->loadDataSource($name); - $_this->_dataSources[$name] =& new $class($_this->config->{$name}); + $_this->_dataSources[$name] = new $class($_this->config->{$name}); $_this->_dataSources[$name]->configKeyName = $name; } else { trigger_error(sprintf(__("ConnectionManager::getDataSource - Non-existent data source %s", true), $name), E_USER_ERROR); diff --git a/cake/libs/model/datasources/datasource.php b/cake/libs/model/datasources/datasource.php index b1b2baef..f9cfc515 100755 --- a/cake/libs/model/datasources/datasource.php +++ b/cake/libs/model/datasources/datasource.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.model.datasources */ -class DataSource extends Object { +class DataSource extends CakeObject { /** * Are we connected to the DataSource? * diff --git a/cake/libs/model/schema.php b/cake/libs/model/schema.php index d0368992..1faa073b 100755 --- a/cake/libs/model/schema.php +++ b/cake/libs/model/schema.php @@ -29,7 +29,7 @@ App::import('Model', 'ConnectionManager'); * @package cake * @subpackage cake.cake.libs.model */ -class CakeSchema extends Object { +class CakeSchema extends CakeObject { /** * Name of the App Schema * @@ -158,7 +158,7 @@ class CakeSchema extends Object { } if (class_exists($class)) { - $Schema =& new $class($options); + $Schema = new $class($options); return $Schema; } @@ -354,7 +354,7 @@ class CakeSchema extends Object { $out .="}\n"; - $File =& new File($path . DS . $file, true); + $File = new File($path . DS . $file, true); $header = '$Id'; $content = ""; $content = $File->prepare($content); diff --git a/cake/libs/multibyte.php b/cake/libs/multibyte.php index 724b6592..9dc9c9b6 100755 --- a/cake/libs/multibyte.php +++ b/cake/libs/multibyte.php @@ -241,7 +241,7 @@ if (!function_exists('mb_encode_mimeheader')) { * @package cake * @subpackage cake.cake.libs */ -class Multibyte extends Object { +class Multibyte extends CakeObject { /** * Holds the case folding values * @@ -274,7 +274,7 @@ class Multibyte extends Object { static $instance = array(); if (!$instance) { - $instance[0] =& new Multibyte(); + $instance[0] = new Multibyte(); } return $instance[0]; } diff --git a/cake/libs/object.php b/cake/libs/object.php index 61c0896c..1519e76f 100755 --- a/cake/libs/object.php +++ b/cake/libs/object.php @@ -34,7 +34,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Object { +class CakeObject { /** * Log object * @@ -295,4 +295,7 @@ class Object { } } } + +// Note: In PHP 7+, 'Object' is a reserved class name +// All classes that extend Object should now extend CakeObject instead ?> \ No newline at end of file diff --git a/cake/libs/overloadable_php4.php b/cake/libs/overloadable_php4.php index b60411c5..0a6ff9df 100755 --- a/cake/libs/overloadable_php4.php +++ b/cake/libs/overloadable_php4.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Overloadable extends Object { +class Overloadable extends CakeObject { /** * Constructor. * @@ -88,7 +88,7 @@ Overloadable::overload('Overloadable'); * @package cake * @subpackage cake.cake.libs */ -class Overloadable2 extends Object { +class Overloadable2 extends CakeObject { /** * Constructor * diff --git a/cake/libs/overloadable_php5.php b/cake/libs/overloadable_php5.php index 906b6b37..347f7c9c 100755 --- a/cake/libs/overloadable_php5.php +++ b/cake/libs/overloadable_php5.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Overloadable extends Object { +class Overloadable extends CakeObject { /** * Overload implementation. No need for implementation in PHP5. * @@ -60,7 +60,7 @@ class Overloadable extends Object { * * @package cake */ -class Overloadable2 extends Object { +class Overloadable2 extends CakeObject { /** * Overload implementation. No need for implementation in PHP5. * diff --git a/cake/libs/router.php b/cake/libs/router.php index 0b2b3b61..65520c7c 100755 --- a/cake/libs/router.php +++ b/cake/libs/router.php @@ -37,7 +37,7 @@ if (!class_exists('Object')) { * @package cake * @subpackage cake.cake.libs */ -class Router extends Object { +class Router extends CakeObject { /** * Array of routes * @@ -170,7 +170,7 @@ class Router extends Object { static $instance = array(); if (!$instance) { - $instance[0] =& new Router(); + $instance[0] = new Router(); $instance[0]->__admin = Configure::read('Routing.admin'); } return $instance[0]; diff --git a/cake/libs/security.php b/cake/libs/security.php index 15ec7c1b..fc610c1e 100755 --- a/cake/libs/security.php +++ b/cake/libs/security.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Security extends Object { +class Security extends CakeObject { /** * Default hash method * @@ -50,7 +50,7 @@ class Security extends Object { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] =& new Security; + $instance[0] = new Security; } return $instance[0]; } diff --git a/cake/libs/session.php b/cake/libs/session.php index c90318c9..a2ae2511 100755 --- a/cake/libs/session.php +++ b/cake/libs/session.php @@ -46,7 +46,7 @@ if (!class_exists('Security')) { * @package cake * @subpackage cake.cake.libs */ -class CakeSession extends Object { +class CakeSession extends CakeObject { /** * True if the Session is still valid * diff --git a/cake/libs/set.php b/cake/libs/set.php index 2afb7156..8e54b15d 100755 --- a/cake/libs/set.php +++ b/cake/libs/set.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Set extends Object { +class Set extends CakeObject { /** * Deprecated * diff --git a/cake/libs/socket.php b/cake/libs/socket.php index c5c945aa..487d0911 100755 --- a/cake/libs/socket.php +++ b/cake/libs/socket.php @@ -31,7 +31,7 @@ App::import('Core', 'Validation'); * @package cake * @subpackage cake.cake.libs */ -class CakeSocket extends Object { +class CakeSocket extends CakeObject { /** * Object description * diff --git a/cake/libs/string.php b/cake/libs/string.php index 286017bd..2f8950ea 100755 --- a/cake/libs/string.php +++ b/cake/libs/string.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class String extends Object { +class String extends CakeObject { /** * Gets a reference to the String object instance * @@ -42,7 +42,7 @@ class String extends Object { static $instance = array(); if (!$instance) { - $instance[0] =& new String(); + $instance[0] = new String(); } return $instance[0]; } diff --git a/cake/libs/validation.php b/cake/libs/validation.php index be0d20c2..f519fec0 100755 --- a/cake/libs/validation.php +++ b/cake/libs/validation.php @@ -52,7 +52,7 @@ * @subpackage cake.cake.libs * @since CakePHP v 1.2.0.3830 */ -class Validation extends Object { +class Validation extends CakeObject { /** * Set the the value of methods $check param. * @@ -119,7 +119,7 @@ class Validation extends Object { static $instance = array(); if (!$instance) { - $instance[0] =& new Validation(); + $instance[0] = new Validation(); } return $instance[0]; } diff --git a/cake/libs/view/helpers/cache.php b/cake/libs/view/helpers/cache.php index d8e60b12..39814a0c 100755 --- a/cake/libs/view/helpers/cache.php +++ b/cake/libs/view/helpers/cache.php @@ -252,7 +252,7 @@ class CacheHelper extends AppHelper { '; } - $file .= '$controller =& new ' . $this->controllerName . 'Controller(); + $file .= '$controller = new ' . $this->controllerName . 'Controller(); $controller->plugin = $this->plugin = \''.$this->plugin.'\'; $controller->helpers = $this->helpers = unserialize(\'' . serialize($this->helpers) . '\'); $controller->base = $this->base = \'' . $this->base . '\'; diff --git a/cake/libs/view/helpers/js.php b/cake/libs/view/helpers/js.php index 15e25099..e372e9f2 100755 --- a/cake/libs/view/helpers/js.php +++ b/cake/libs/view/helpers/js.php @@ -136,7 +136,7 @@ class JsHelper extends Overloadable2 { } $func .= "'" . Router::url($url) . "'"; - $ajax =& new AjaxHelper(); + $ajax = new AjaxHelper(); $func .= ", " . $ajax->__optionsForAjax($options) . ")"; if (isset($options['before'])) { diff --git a/cake/libs/view/helpers/xml.php b/cake/libs/view/helpers/xml.php index 6377a526..bd8434dc 100755 --- a/cake/libs/view/helpers/xml.php +++ b/cake/libs/view/helpers/xml.php @@ -46,7 +46,7 @@ class XmlHelper extends AppHelper { */ function __construct() { parent::__construct(); - $this->Xml =& new Xml(); + $this->Xml = new Xml(); $this->Xml->options(array('verifyNs' => false)); } /** @@ -155,7 +155,7 @@ class XmlHelper extends AppHelper { */ function serialize($data, $options = array()) { $options += array('attributes' => false, 'format' => 'attributes'); - $data =& new Xml($data, $options); + $data = new Xml($data, $options); return $data->toString($options + array('header' => false)); } } diff --git a/cake/libs/view/view.php b/cake/libs/view/view.php index 1ed8c01c..a5d8d57d 100755 --- a/cake/libs/view/view.php +++ b/cake/libs/view/view.php @@ -34,7 +34,7 @@ App::import('Core', array('Helper', 'ClassRegistry')); * @package cake * @subpackage cake.cake.libs.view */ -class View extends Object { +class View extends CakeObject { /** * Path parts for creating links in views. * @@ -745,7 +745,7 @@ class View extends Object { return false; } } - $loaded[$helper] =& new $helperCn($options); + $loaded[$helper] = new $helperCn($options); $vars = array( 'base', 'webroot', 'here', 'params', 'action', 'data', 'themeWeb', 'plugin' ); diff --git a/cake/libs/xml.php b/cake/libs/xml.php index 0d91825b..7daa6684 100755 --- a/cake/libs/xml.php +++ b/cake/libs/xml.php @@ -34,7 +34,7 @@ App::import('Core', 'Set'); * @subpackage cake.cake.libs * @since CakePHP v .0.10.3.1400 */ -class XmlNode extends Object { +class XmlNode extends CakeObject { /** * Name of node * @@ -147,7 +147,7 @@ class XmlNode extends Object { * @return object XmlNode */ function &createNode($name = null, $value = null, $namespace = false) { - $node =& new XmlNode($name, $value, $namespace); + $node = new XmlNode($name, $value, $namespace); $node->setParent($this); return $node; } @@ -161,7 +161,7 @@ class XmlNode extends Object { * @return object XmlElement */ function &createElement($name = null, $value = null, $attributes = array(), $namespace = false) { - $element =& new XmlElement($name, $value, $attributes, $namespace); + $element = new XmlElement($name, $value, $attributes, $namespace); $element->setParent($this); return $element; } @@ -1398,7 +1398,7 @@ class XmlManager { static $instance = array(); if (!$instance) { - $instance[0] =& new XmlManager(); + $instance[0] = new XmlManager(); } return $instance[0]; } diff --git a/cake/tests/cases/console/cake.test.php b/cake/tests/cases/console/cake.test.php index 6eda913f..86e22f85 100755 --- a/cake/tests/cases/console/cake.test.php +++ b/cake/tests/cases/console/cake.test.php @@ -151,7 +151,7 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testParseParams() { - $Dispatcher =& new TestShellDispatcher(); + $Dispatcher = new TestShellDispatcher(); $params = array( '/cake/1.2.x.x/cake/console/cake.php', @@ -423,7 +423,7 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testBuildPaths() { - $Dispatcher =& new TestShellDispatcher(); + $Dispatcher = new TestShellDispatcher(); $result = $Dispatcher->shellPaths; $expected = array( @@ -444,13 +444,13 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testDispatch() { - $Dispatcher =& new TestShellDispatcher(array('sample')); + $Dispatcher = new TestShellDispatcher(array('sample')); $this->assertPattern('/This is the main method called from SampleShell/', $Dispatcher->stdout); - $Dispatcher =& new TestShellDispatcher(array('test_plugin_two.example')); + $Dispatcher = new TestShellDispatcher(array('test_plugin_two.example')); $this->assertPattern('/This is the main method called from TestPluginTwo.ExampleShell/', $Dispatcher->stdout); - $Dispatcher =& new TestShellDispatcher(array('test_plugin_two.welcome', 'say_hello')); + $Dispatcher = new TestShellDispatcher(array('test_plugin_two.welcome', 'say_hello')); $this->assertPattern('/This is the say_hello method called from TestPluginTwo.WelcomeShell/', $Dispatcher->stdout); } /** @@ -460,7 +460,7 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testHelpCommand() { - $Dispatcher =& new TestShellDispatcher(); + $Dispatcher = new TestShellDispatcher(); $expected = "/ CORE(\\\|\/)tests(\\\|\/)test_app(\\\|\/)plugins(\\\|\/)test_plugin(\\\|\/)vendors(\\\|\/)shells:"; $expected .= "\n\t example"; diff --git a/cake/tests/cases/console/libs/acl.test.php b/cake/tests/cases/console/libs/acl.test.php index f27a6943..6f7f1154 100755 --- a/cake/tests/cases/console/libs/acl.test.php +++ b/cake/tests/cases/console/libs/acl.test.php @@ -84,8 +84,8 @@ class AclShellTest extends CakeTestCase { * @access public */ function startTest() { - $this->Dispatcher =& new TestAclShellMockShellDispatcher(); - $this->Task =& new MockAclShell($this->Dispatcher); + $this->Dispatcher = new TestAclShellMockShellDispatcher(); + $this->Task = new MockAclShell($this->Dispatcher); $this->Task->Dispatch =& $this->Dispatcher; $this->Task->params['datasource'] = 'test_suite'; } diff --git a/cake/tests/cases/console/libs/api.test.php b/cake/tests/cases/console/libs/api.test.php index b5568fce..cc60aecf 100755 --- a/cake/tests/cases/console/libs/api.test.php +++ b/cake/tests/cases/console/libs/api.test.php @@ -62,8 +62,8 @@ class ApiShellTest extends CakeTestCase { * @access public */ function startTest() { - $this->Dispatcher =& new ApiShellMockShellDispatcher(); - $this->Shell =& new MockApiShell($this->Dispatcher); + $this->Dispatcher = new ApiShellMockShellDispatcher(); + $this->Shell = new MockApiShell($this->Dispatcher); $this->Shell->Dispatch =& $this->Dispatcher; } /** diff --git a/cake/tests/cases/console/libs/schema.test.php b/cake/tests/cases/console/libs/schema.test.php index 063910db..48573fcf 100755 --- a/cake/tests/cases/console/libs/schema.test.php +++ b/cake/tests/cases/console/libs/schema.test.php @@ -124,8 +124,8 @@ class SchemaShellTest extends CakeTestCase { * @access public */ function startTest() { - $this->Dispatcher =& new TestSchemaShellMockShellDispatcher(); - $this->Shell =& new MockSchemaShell($this->Dispatcher); + $this->Dispatcher = new TestSchemaShellMockShellDispatcher(); + $this->Shell = new MockSchemaShell($this->Dispatcher); $this->Shell->Dispatch =& $this->Dispatcher; } @@ -193,9 +193,9 @@ class SchemaShellTest extends CakeTestCase { * @return void **/ function testDumpWithFileWriting() { - $file =& new File(APP . 'config' . DS . 'sql' . DS . 'i18n.php'); + $file = new File(APP . 'config' . DS . 'sql' . DS . 'i18n.php'); $contents = $file->read(); - $file =& new File(TMP . 'tests' . DS . 'i18n.php'); + $file = new File(TMP . 'tests' . DS . 'i18n.php'); $file->write($contents); $this->Shell->params = array('name' => 'i18n'); @@ -204,7 +204,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->Schema->path = TMP . 'tests'; $this->Shell->dump(); - $sql =& new File(TMP . 'tests' . DS . 'i18n.sql'); + $sql = new File(TMP . 'tests' . DS . 'i18n.sql'); $contents = $sql->read(); $this->assertPattern('/DROP TABLE/', $contents); $this->assertPattern('/CREATE TABLE `i18n`/', $contents); @@ -228,7 +228,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->path = TMP; $this->Shell->params['file'] = 'schema.php'; $this->Shell->args = array('snapshot'); - $this->Shell->Schema =& new MockSchemaCakeSchema(); + $this->Shell->Schema = new MockSchemaCakeSchema(); $this->Shell->Schema->setReturnValue('read', array('schema data')); $this->Shell->Schema->setReturnValue('write', true); @@ -249,7 +249,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->args = array(); $this->Shell->setReturnValue('in', 'q'); - $this->Shell->Schema =& new MockSchemaCakeSchema(); + $this->Shell->Schema = new MockSchemaCakeSchema(); $this->Shell->Schema->path = TMP; $this->Shell->Schema->expectNever('read'); @@ -269,7 +269,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->setReturnValue('in', 'o'); $this->Shell->expectAt(1, 'out', array(new PatternExpectation('/Schema file:\s[a-z\.]+\sgenerated/'))); - $this->Shell->Schema =& new MockSchemaCakeSchema(); + $this->Shell->Schema = new MockSchemaCakeSchema(); $this->Shell->Schema->path = TMP; $this->Shell->Schema->setReturnValue('read', array('schema data')); $this->Shell->Schema->setReturnValue('write', true); @@ -341,7 +341,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->setReturnValue('in', 'y'); $this->Shell->run(); - $article =& new Model(array('name' => 'Article', 'ds' => 'test_suite')); + $article = new Model(array('name' => 'Article', 'ds' => 'test_suite')); $fields = $article->schema(); $this->assertTrue(isset($fields['summary'])); diff --git a/cake/tests/cases/console/libs/shell.test.php b/cake/tests/cases/console/libs/shell.test.php index b832088e..c7114535 100755 --- a/cake/tests/cases/console/libs/shell.test.php +++ b/cake/tests/cases/console/libs/shell.test.php @@ -95,8 +95,8 @@ class ShellTest extends CakeTestCase { * @access public */ function setUp() { - $this->Dispatcher =& new TestShellMockShellDispatcher(); - $this->Shell =& new TestShell($this->Dispatcher); + $this->Dispatcher = new TestShellMockShellDispatcher(); + $this->Shell = new TestShell($this->Dispatcher); } /** * tearDown method diff --git a/cake/tests/cases/console/libs/tasks/extract.test.php b/cake/tests/cases/console/libs/tasks/extract.test.php index d393a527..6ae11c64 100755 --- a/cake/tests/cases/console/libs/tasks/extract.test.php +++ b/cake/tests/cases/console/libs/tasks/extract.test.php @@ -59,8 +59,8 @@ class ExtractTaskTest extends CakeTestCase { * @access public */ function setUp() { - $this->Dispatcher =& new TestExtractTaskMockShellDispatcher(); - $this->Task =& new ExtractTask($this->Dispatcher); + $this->Dispatcher = new TestExtractTaskMockShellDispatcher(); + $this->Task = new ExtractTask($this->Dispatcher); } /** * tearDown method diff --git a/cake/tests/cases/console/libs/tasks/test.test.php b/cake/tests/cases/console/libs/tasks/test.test.php index 548f2960..0449893b 100755 --- a/cake/tests/cases/console/libs/tasks/test.test.php +++ b/cake/tests/cases/console/libs/tasks/test.test.php @@ -63,8 +63,8 @@ class TestTaskTest extends CakeTestCase { * @access public */ function setUp() { - $this->Dispatcher =& new TestTestTaskMockShellDispatcher(); - $this->Task =& new MockTestTask($this->Dispatcher); + $this->Dispatcher = new TestTestTaskMockShellDispatcher(); + $this->Task = new MockTestTask($this->Dispatcher); $this->Task->Dispatch =& $this->Dispatcher; } /** diff --git a/cake/tests/cases/dispatcher.test.php b/cake/tests/cases/dispatcher.test.php index 613c8949..f761eaa0 100755 --- a/cake/tests/cases/dispatcher.test.php +++ b/cake/tests/cases/dispatcher.test.php @@ -544,7 +544,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithoutZerosAndEmptyPost() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/params1/params2/params3"); $this->assertIdentical($test['controller'], 'testcontroller'); $this->assertIdentical($test['action'], 'testaction'); @@ -561,7 +561,7 @@ class DispatcherTest extends CakeTestCase { */ function testParseParamsReturnsPostedData() { $_POST['testdata'] = "My Posted Content"; - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $test = $Dispatcher->parseParams("/"); $this->assertTrue($test['form'], "Parsed URL not returning post data"); $this->assertIdentical($test['form']['testdata'], "My Posted Content"); @@ -573,7 +573,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithSingleZero() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/1/0/23"); $this->assertIdentical($test['controller'], 'testcontroller'); $this->assertIdentical($test['action'], 'testaction'); @@ -588,7 +588,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithManySingleZeros() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/0/0/0/0/0/0"); $this->assertPattern('/\\A(?:0)\\z/', $test['pass'][0]); $this->assertPattern('/\\A(?:0)\\z/', $test['pass'][1]); @@ -604,7 +604,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithManyZerosInEachSectionOfUrl() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/000/0000/00000/000000/000000/0000000"); $this->assertPattern('/\\A(?:000)\\z/', $test['pass'][0]); $this->assertPattern('/\\A(?:0000)\\z/', $test['pass'][1]); @@ -620,7 +620,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/01/0403/04010/000002/000030/0000400"); $this->assertPattern('/\\A(?:01)\\z/', $test['pass'][0]); $this->assertPattern('/\\A(?:0403)\\z/', $test['pass'][1]); @@ -641,7 +641,7 @@ class DispatcherTest extends CakeTestCase { Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); $_GET = array('coffee' => 'life', 'sleep' => 'sissies'); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $uri = 'posts/home/?coffee=life&sleep=sissies'; $result = $Dispatcher->parseParams($uri); $this->assertPattern('/posts/', $result['controller']); @@ -649,7 +649,7 @@ class DispatcherTest extends CakeTestCase { $this->assertTrue(isset($result['url']['sleep'])); $this->assertTrue(isset($result['url']['coffee'])); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $uri = '/?coffee=life&sleep=sissy'; $result = $Dispatcher->parseParams($uri); $this->assertPattern('/pages/', $result['controller']); @@ -712,7 +712,7 @@ class DispatcherTest extends CakeTestCase { ), )); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $result = $Dispatcher->parseParams('/'); $expected = array( @@ -830,7 +830,7 @@ class DispatcherTest extends CakeTestCase { ) ) ); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $result = $Dispatcher->parseParams('/'); $expected = array( 'Document' => array( @@ -895,7 +895,7 @@ class DispatcherTest extends CakeTestCase { ) ); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $result = $Dispatcher->parseParams('/'); $expected = array( @@ -917,7 +917,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testGetUrl() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $Dispatcher->base = '/app/webroot/index.php'; $uri = '/app/webroot/index.php/posts/add'; $result = $Dispatcher->getUrl($uri); @@ -933,7 +933,7 @@ class DispatcherTest extends CakeTestCase { $_GET['url'] = array(); Configure::write('App.base', '/control'); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $Dispatcher->baseUrl(); $uri = '/control/students/browse'; $result = $Dispatcher->getUrl($uri); @@ -941,7 +941,7 @@ class DispatcherTest extends CakeTestCase { $this->assertEqual($expected, $result); $_GET['url'] = array(); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $Dispatcher->base = ''; $uri = '/?/home'; $result = $Dispatcher->getUrl($uri); @@ -956,7 +956,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testBaseUrlAndWebrootWithModRewrite() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $Dispatcher->base = false; $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches'; @@ -1037,7 +1037,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('App.base', '/control'); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $result = $Dispatcher->baseUrl(); $expected = '/control'; $this->assertEqual($expected, $result); @@ -1051,7 +1051,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['DOCUMENT_ROOT'] = '/var/www/abtravaff/html'; $_SERVER['SCRIPT_FILENAME'] = '/var/www/abtravaff/html/newaffiliate/index.php'; $_SERVER['PHP_SELF'] = '/newaffiliate/index.php'; - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $result = $Dispatcher->baseUrl(); $expected = '/newaffiliate'; $this->assertEqual($expected, $result); @@ -1065,7 +1065,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testBaseUrlAndWebrootWithBaseUrl() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); Configure::write('App.dir', 'app'); @@ -1134,7 +1134,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testBaseUrlAndWebrootWithBase() { - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $Dispatcher->base = '/app'; $result = $Dispatcher->baseUrl(); $expected = '/app'; @@ -1164,7 +1164,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testMissingController() { - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_controller/home/param:value/param2:value2'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); @@ -1183,7 +1183,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testPrivate() { - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_pages/_protected/param:value/param2:value2'; @@ -1205,7 +1205,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testMissingAction() { - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_pages/home/param:value/param2:value2'; @@ -1220,7 +1220,7 @@ class DispatcherTest extends CakeTestCase { ))); $this->assertEqual($expected, $controller); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_pages/redirect/param:value/param2:value2'; @@ -1242,7 +1242,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testDispatch() { - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'pages/home/param:value/param2:value2'; @@ -1269,7 +1269,7 @@ class DispatcherTest extends CakeTestCase { unset($Dispatcher); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('App.baseUrl','/timesheets/index.php'); $url = 'timesheets'; @@ -1296,7 +1296,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testDispatchWithArray() { - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'pages/home/param:value/param2:value2'; @@ -1316,7 +1316,7 @@ class DispatcherTest extends CakeTestCase { */ function testAdminDispatch() { $_POST = array(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('Routing.admin', 'admin'); Configure::write('App.baseUrl','/cake/repo/branches/1.2.x.x/index.php'); $url = 'admin/test_dispatch_pages/index/param:value/param2:value2'; @@ -1349,7 +1349,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Router::connect('/my_plugin/:controller/*', array('plugin'=>'my_plugin', 'controller'=>'pages', 'action'=>'display')); $Dispatcher->base = false; @@ -1397,7 +1397,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Router::connect('/my_plugin/:controller/:action/*', array('plugin'=>'my_plugin', 'controller'=>'pages', 'action'=>'display')); $Dispatcher->base = false; @@ -1434,7 +1434,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add/param:value/param2:value2'; @@ -1455,7 +1455,7 @@ class DispatcherTest extends CakeTestCase { Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; /* Simulates the Route for a real plugin, installed in APP/plugins */ @@ -1483,7 +1483,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('Routing.admin', 'admin'); Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'admin/my_plugin/add/5/param:value/param2:value2'; @@ -1503,7 +1503,7 @@ class DispatcherTest extends CakeTestCase { Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $controller = $Dispatcher->dispatch('admin/articles_test', array('return' => 1)); @@ -1536,21 +1536,21 @@ class DispatcherTest extends CakeTestCase { Router::reload(); Router::connect('/my_plugin/:controller/:action/*', array('plugin'=>'my_plugin')); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/my_plugin/add'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); $this->assertFalse(isset($controller->params['pass'][0])); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/my_plugin/add/0'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); $this->assertTrue(isset($controller->params['pass'][0])); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add'; @@ -1558,14 +1558,14 @@ class DispatcherTest extends CakeTestCase { $this->assertFalse(isset($controller->params['pass'][0])); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add/0'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); $this->assertIdentical('0',$controller->params['pass'][0]); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add/1'; @@ -1583,7 +1583,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/not_here/param:value/param2:value2'; @@ -1599,7 +1599,7 @@ class DispatcherTest extends CakeTestCase { $this->assertIdentical($expected, $controller); Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/param:value/param2:value2'; @@ -1627,7 +1627,7 @@ class DispatcherTest extends CakeTestCase { Router::reload(); Router::connect('/admin/:controller/:action/*', array('prefix'=>'admin'), array('controller', 'action')); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $Dispatcher->base = false; $url = 'test_dispatch_pages/admin_index/param:value/param2:value2'; @@ -1648,7 +1648,7 @@ class DispatcherTest extends CakeTestCase { * @return void **/ function testTestPluginDispatch() { - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $_back = Configure::read('pluginPaths'); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); $url = '/test_plugin/tests/index'; @@ -1668,7 +1668,7 @@ class DispatcherTest extends CakeTestCase { */ function testChangingParamsFromBeforeFilter() { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); $url = 'some_posts/index/param:value/param2:value2'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); @@ -1707,7 +1707,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); Configure::write('vendorPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS)); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Configure::write('debug', 0); ob_start(); @@ -1777,7 +1777,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)); - $dispatcher =& new Dispatcher(); + $dispatcher = new Dispatcher(); $dispatcher->base = false; $url = '/'; @@ -1902,7 +1902,7 @@ class DispatcherTest extends CakeTestCase { Router::mapResources('Posts'); $_SERVER['REQUEST_METHOD'] = 'POST'; - $dispatcher =& new Dispatcher(); + $dispatcher = new Dispatcher(); $dispatcher->base = false; $result = $dispatcher->parseParams('/posts'); @@ -1956,7 +1956,7 @@ class DispatcherTest extends CakeTestCase { "/index.php/%22%3E%3Ch1%20onclick=%22alert('xss');%22%3Eheya%3C/h1%3E" ); - $dispatcher =& new Dispatcher(); + $dispatcher = new Dispatcher(); $result = $dispatcher->baseUrl(); $expected = '/index.php/h1 onclick=alert(xss);heya'; $this->assertEqual($result, $expected); @@ -1968,7 +1968,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testEnvironmentDetection() { - $dispatcher =& new Dispatcher(); + $dispatcher = new Dispatcher(); $environments = array( 'IIS' => array( @@ -2077,7 +2077,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher =& new TestDispatcher(); + $Dispatcher = new TestDispatcher(); Router::connect('/myalias/:action/*', array('controller' => 'my_controller', 'action' => null)); $Dispatcher->base = false; diff --git a/cake/tests/cases/libs/cake_test_case.test.php b/cake/tests/cases/libs/cake_test_case.test.php index 895eaaf4..56fa70d8 100755 --- a/cake/tests/cases/libs/cake_test_case.test.php +++ b/cake/tests/cases/libs/cake_test_case.test.php @@ -78,8 +78,8 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function setUp() { - $this->Case =& new SubjectCakeTestCase(); - $reporter =& new MockCakeHtmlReporter(); + $this->Case = new SubjectCakeTestCase(); + $reporter = new MockCakeHtmlReporter(); $this->Case->setReporter($reporter); $this->Reporter = $reporter; } @@ -265,7 +265,7 @@ class CakeTestCaseTest extends CakeTestCase { $this->assertEqual($result, array('var' => 'string')); $db =& ConnectionManager::getDataSource('test_suite'); - $fixture =& new PostFixture(); + $fixture = new PostFixture(); $fixture->create($db); $result = $this->Case->testAction('/tests_apps_posts/add', array('return' => 'vars')); @@ -321,7 +321,7 @@ class CakeTestCaseTest extends CakeTestCase { ConnectionManager::create('cake_test_case', $config); $db2 =& ConnectionManager::getDataSource('cake_test_case'); - $fixture =& new PostFixture($db2); + $fixture = new PostFixture($db2); $fixture->create($db2); $fixture->insert($db2); @@ -349,7 +349,7 @@ class CakeTestCaseTest extends CakeTestCase { ConnectionManager::create('cake_test_case', $config); $db =& ConnectionManager::getDataSource('cake_test_case'); - $fixture =& new PostFixture($db); + $fixture = new PostFixture($db); $fixture->create($db); $fixture->insert($db); @@ -399,8 +399,8 @@ class CakeTestCaseTest extends CakeTestCase { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS)); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); - $Dispatcher =& new CakeTestDispatcher(); - $Case =& new CakeDispatcherMockTestCase(); + $Dispatcher = new CakeTestDispatcher(); + $Case = new CakeDispatcherMockTestCase(); $Case->expectOnce('startController'); $Case->expectOnce('endController'); diff --git a/cake/tests/cases/libs/cake_test_fixture.test.php b/cake/tests/cases/libs/cake_test_fixture.test.php index d5844bc6..a3c64608 100755 --- a/cake/tests/cases/libs/cake_test_fixture.test.php +++ b/cake/tests/cases/libs/cake_test_fixture.test.php @@ -125,7 +125,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function setUp() { - $this->criticDb =& new FixtureMockDboSource(); + $this->criticDb = new FixtureMockDboSource(); $this->criticDb->fullDebug = true; } /** @@ -144,23 +144,23 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testInit() { - $Fixture =& new CakeTestFixtureTestFixture(); + $Fixture = new CakeTestFixtureTestFixture(); unset($Fixture->table); $Fixture->init(); $this->assertEqual($Fixture->table, 'fixture_tests'); $this->assertEqual($Fixture->primaryKey, 'id'); - $Fixture =& new CakeTestFixtureTestFixture(); + $Fixture = new CakeTestFixtureTestFixture(); $Fixture->primaryKey = 'my_random_key'; $Fixture->init(); $this->assertEqual($Fixture->primaryKey, 'my_random_key'); $this->_initDb(); - $Source =& new CakeTestFixtureTestFixture(); + $Source = new CakeTestFixtureTestFixture(); $Source->create($this->db); $Source->insert($this->db); - $Fixture =& new CakeTestFixtureImportFixture(); + $Fixture = new CakeTestFixtureImportFixture(); $expected = array('id', 'name', 'created'); $this->assertEqual(array_keys($Fixture->fields), $expected); @@ -174,7 +174,7 @@ class CakeTestFixtureTest extends CakeTestCase { $Fixture->init(); $this->assertEqual(count($Fixture->records), count($Source->records)); - $Fixture =& new CakeTestFixtureImportFixture(); + $Fixture = new CakeTestFixtureImportFixture(); $Fixture->fields = $Fixture->records = null; $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test_suite'); $Fixture->init(); @@ -201,13 +201,13 @@ class CakeTestFixtureTest extends CakeTestCase { ConnectionManager::create('new_test_suite', array_merge($testSuiteConfig, array('prefix' => 'new_' . $testSuiteConfig['prefix']))); $newTestSuiteDb =& ConnectionManager::getDataSource('new_test_suite'); - $Source =& new CakeTestFixtureTestFixture(); + $Source = new CakeTestFixtureTestFixture(); $Source->create($newTestSuiteDb); $Source->insert($newTestSuiteDb); $defaultDb->config = $newTestSuiteDb->config; - $Fixture =& new CakeTestFixtureDefaultImportFixture(); + $Fixture = new CakeTestFixtureDefaultImportFixture(); $Fixture->fields = $Fixture->records = null; $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite'); $Fixture->init(); @@ -227,7 +227,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testCreate() { - $Fixture =& new CakeTestFixtureTestFixture(); + $Fixture = new CakeTestFixtureTestFixture(); $this->criticDb->expectAtLeastOnce('execute'); $this->criticDb->expectAtLeastOnce('createSchema'); $return = $Fixture->create($this->criticDb); @@ -245,7 +245,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testInsert() { - $Fixture =& new CakeTestFixtureTestFixture(); + $Fixture = new CakeTestFixtureTestFixture(); $this->criticDb->setReturnValue('insertMulti', true); $this->criticDb->expectAtLeastOnce('insertMulti'); @@ -260,7 +260,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testDrop() { - $Fixture =& new CakeTestFixtureTestFixture(); + $Fixture = new CakeTestFixtureTestFixture(); $this->criticDb->setReturnValueAt(0, 'execute', true); $this->criticDb->expectAtLeastOnce('execute'); $this->criticDb->expectAtLeastOnce('dropSchema'); @@ -280,7 +280,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testTruncate() { - $Fixture =& new CakeTestFixtureTestFixture(); + $Fixture = new CakeTestFixtureTestFixture(); $this->criticDb->expectAtLeastOnce('truncate'); $Fixture->truncate($this->criticDb); $this->assertTrue($this->criticDb->fullDebug); diff --git a/cake/tests/cases/libs/code_coverage_manager.test.php b/cake/tests/cases/libs/code_coverage_manager.test.php index 9a1e6c41..ef18aff5 100755 --- a/cake/tests/cases/libs/code_coverage_manager.test.php +++ b/cake/tests/cases/libs/code_coverage_manager.test.php @@ -158,7 +158,7 @@ class CodeCoverageManagerTest extends CakeTestCase { * @package cake * @subpackage cake.tests.cases.libs */ - class Set extends Object { + class Set extends CakeObject { /** * Value of the Set object. * @@ -315,7 +315,7 @@ PHP; * @package cake * @subpackage cake.tests.cases.libs */ - class Set extends Object { + class Set extends CakeObject { /** * Value of the Set object. * diff --git a/cake/tests/cases/libs/controller/component.test.php b/cake/tests/cases/libs/controller/component.test.php index e3f78b28..4013c6b1 100755 --- a/cake/tests/cases/libs/controller/component.test.php +++ b/cake/tests/cases/libs/controller/component.test.php @@ -72,7 +72,7 @@ if (!class_exists('AppController')) { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class ParamTestComponent extends Object { +class ParamTestComponent extends CakeObject { /** * name property * @@ -133,7 +133,7 @@ class ComponentTestController extends AppController { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class AppleComponent extends Object { +class AppleComponent extends CakeObject { /** * components property * @@ -165,7 +165,7 @@ class AppleComponent extends Object { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class OrangeComponent extends Object { +class OrangeComponent extends CakeObject { /** * components property * @@ -202,7 +202,7 @@ class OrangeComponent extends Object { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class BananaComponent extends Object { +class BananaComponent extends CakeObject { /** * testField property * @@ -227,7 +227,7 @@ class BananaComponent extends Object { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class MutuallyReferencingOneComponent extends Object { +class MutuallyReferencingOneComponent extends CakeObject { /** * components property * @@ -242,7 +242,7 @@ class MutuallyReferencingOneComponent extends Object { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class MutuallyReferencingTwoComponent extends Object { +class MutuallyReferencingTwoComponent extends CakeObject { /** * components property * @@ -257,7 +257,7 @@ class MutuallyReferencingTwoComponent extends Object { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class SomethingWithEmailComponent extends Object { +class SomethingWithEmailComponent extends CakeObject { /** * components property * @@ -302,19 +302,19 @@ class ComponentTest extends CakeTestCase { * @return void */ function testLoadComponents() { - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('RequestHandler'); - $Component =& new Component(); + $Component = new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->RequestHandler, 'RequestHandlerComponent')); - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->plugin = 'test_plugin'; $Controller->components = array('RequestHandler', 'TestPluginComponent'); - $Component =& new Component(); + $Component = new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->RequestHandler, 'RequestHandlerComponent')); @@ -325,19 +325,19 @@ class ComponentTest extends CakeTestCase { )); $this->assertFalse(isset($Controller->TestPluginOtherComponent)); - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('Security'); - $Component =& new Component(); + $Component = new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->Security, 'SecurityComponent')); $this->assertTrue(is_a($Controller->Security->Session, 'SessionComponent')); - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('Security', 'Cookie', 'RequestHandler'); - $Component =& new Component(); + $Component = new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->Security, 'SecurityComponent')); @@ -351,7 +351,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testNestedComponentLoading() { - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('Apple'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -370,7 +370,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testComponentStartup() { - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('Apple'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -390,7 +390,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testMultipleComponentInitialize() { - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('Orange', 'Banana'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -409,7 +409,7 @@ class ComponentTest extends CakeTestCase { return; } - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('ParamTest' => array('test' => 'value', 'flag'), 'Apple'); $Controller->constructClasses(); @@ -424,7 +424,7 @@ class ComponentTest extends CakeTestCase { $this->assertEqual($Controller->ParamTest->flag, true); //Settings are merged from app controller and current controller. - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array( 'ParamTest' => array('test' => 'value'), 'Orange' => array('ripeness' => 'perfect') @@ -443,7 +443,7 @@ class ComponentTest extends CakeTestCase { * @return void **/ function testComponentParamsNoDuplication() { - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('Orange' => array('setting' => array('itemx'))); $Controller->constructClasses(); @@ -457,7 +457,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testMutuallyReferencingComponents() { - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('MutuallyReferencingOne'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -481,7 +481,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testSomethingReferencingEmailComponent() { - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->components = array('SomethingWithEmail'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -510,7 +510,7 @@ class ComponentTest extends CakeTestCase { function testDoubleLoadingOfSessionComponent() { $this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController'); - $Controller =& new ComponentTestController(); + $Controller = new ComponentTestController(); $Controller->uses = array(); $Controller->components = array('Session'); $Controller->constructClasses(); diff --git a/cake/tests/cases/libs/controller/components/acl.test.php b/cake/tests/cases/libs/controller/components/acl.test.php index 755d7ae1..f33eeef0 100755 --- a/cake/tests/cases/libs/controller/components/acl.test.php +++ b/cake/tests/cases/libs/controller/components/acl.test.php @@ -165,10 +165,10 @@ class DbAclTwoTest extends DbAcl { * @return void */ function __construct() { - $this->Aro =& new AroTwoTest(); - $this->Aro->Permission =& new PermissionTwoTest(); - $this->Aco =& new AcoTwoTest(); - $this->Aro->Permission =& new PermissionTwoTest(); + $this->Aro = new AroTwoTest(); + $this->Aro->Permission = new PermissionTwoTest(); + $this->Aco = new AcoTwoTest(); + $this->Aro->Permission = new PermissionTwoTest(); } } /** @@ -200,7 +200,7 @@ class AclComponentTest extends CakeTestCase { * @return void */ function startTest() { - $this->Acl =& new AclComponent(); + $this->Acl = new AclComponent(); } /** * before method diff --git a/cake/tests/cases/libs/controller/components/auth.test.php b/cake/tests/cases/libs/controller/components/auth.test.php index 481b2dd5..3bf3358f 100755 --- a/cake/tests/cases/libs/controller/components/auth.test.php +++ b/cake/tests/cases/libs/controller/components/auth.test.php @@ -445,7 +445,7 @@ class AuthTest extends CakeTestCase { Configure::write('Acl.database', 'test_suite'); Configure::write('Acl.classname', 'DbAcl'); - $this->Controller =& new AuthTestController(); + $this->Controller = new AuthTestController(); $this->Controller->Component->init($this->Controller); ClassRegistry::addObject('view', new View($this->Controller)); @@ -509,7 +509,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testLogin() { - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $user['id'] = 1; $user['username'] = 'mariano'; $user['password'] = Security::hash(Configure::read('Security.salt') . 'cake'); @@ -580,7 +580,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeFalse() { - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); $this->Controller->Auth->userModel = 'AuthUser'; @@ -605,7 +605,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeController() { - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); $this->Controller->Auth->userModel = 'AuthUser'; @@ -628,7 +628,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeModel() { - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); @@ -653,7 +653,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeCrud() { - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); @@ -951,7 +951,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testEmptyUsernameOrPassword() { - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $user['id'] = 1; $user['username'] = 'mariano'; $user['password'] = Security::hash(Configure::read('Security.salt') . 'cake'); @@ -981,7 +981,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testInjection() { - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $this->AuthUser->id = 2; $this->AuthUser->saveField('password', Security::hash(Configure::read('Security.salt') . 'cake')); @@ -1086,7 +1086,7 @@ class AuthTest extends CakeTestCase { 'argSeparator' => ':', 'namedArgs' => array() ))); - $this->AuthUser =& new AuthUser(); + $this->AuthUser = new AuthUser(); $user = array( 'id' => 1, 'username' => 'felix', 'password' => Security::hash(Configure::read('Security.salt') . 'cake' @@ -1131,7 +1131,7 @@ class AuthTest extends CakeTestCase { function testCustomField() { Router::reload(); - $this->AuthUserCustomField =& new AuthUserCustomField(); + $this->AuthUserCustomField = new AuthUserCustomField(); $user = array( 'id' => 1, 'email' => 'harking@example.com', 'password' => Security::hash(Configure::read('Security.salt') . 'cake' @@ -1208,7 +1208,7 @@ class AuthTest extends CakeTestCase { } ob_start(); - $Dispatcher =& new Dispatcher(); + $Dispatcher = new Dispatcher(); $Dispatcher->dispatch('/ajax_auth/add', array('return' => 1)); $result = ob_get_clean(); $this->assertEqual("Ajax!\nthis is the test element", $result); diff --git a/cake/tests/cases/libs/controller/components/email.test.php b/cake/tests/cases/libs/controller/components/email.test.php index 8baf95e4..44feb8db 100755 --- a/cake/tests/cases/libs/controller/components/email.test.php +++ b/cake/tests/cases/libs/controller/components/email.test.php @@ -181,7 +181,7 @@ class EmailComponentTest extends CakeTestCase { $this->_appEncoding = Configure::read('App.encoding'); Configure::write('App.encoding', 'UTF-8'); - $this->Controller =& new EmailTestController(); + $this->Controller = new EmailTestController(); restore_error_handler(); @$this->Controller->Component->init($this->Controller); @@ -470,7 +470,7 @@ TEXTBLOC; $this->skipIf(!@fsockopen('localhost', 25), '%s No SMTP server running on localhost'); $this->Controller->EmailTest->reset(); - $socket =& new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->Controller->EmailTest->smtpOptions)); + $socket = new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->Controller->EmailTest->smtpOptions)); $this->Controller->EmailTest->setConnectionSocket($socket); $this->assertTrue($this->Controller->EmailTest->getConnectionSocket()); diff --git a/cake/tests/cases/libs/controller/components/security.test.php b/cake/tests/cases/libs/controller/components/security.test.php index f744f2dc..fe2a2df9 100755 --- a/cake/tests/cases/libs/controller/components/security.test.php +++ b/cake/tests/cases/libs/controller/components/security.test.php @@ -137,7 +137,7 @@ class SecurityComponentTest extends CakeTestCase { * @return void */ function setUp() { - $this->Controller =& new SecurityTestController(); + $this->Controller = new SecurityTestController(); $this->Controller->Component->init($this->Controller); $this->Controller->Security =& $this->Controller->TestSecurity; $this->Controller->Security->blackHoleCallback = 'fail'; diff --git a/cake/tests/cases/libs/controller/components/session.test.php b/cake/tests/cases/libs/controller/components/session.test.php index b79f043c..25802217 100755 --- a/cake/tests/cases/libs/controller/components/session.test.php +++ b/cake/tests/cases/libs/controller/components/session.test.php @@ -107,20 +107,20 @@ class SessionComponentTest extends CakeTestCase { */ function testSessionAutoStart() { Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->__active); $this->assertFalse($Session->__started); $Session->startup(new SessionTestController()); Configure::write('Session.start', true); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertTrue($Session->__active); $this->assertFalse($Session->__started); $Session->startup(new SessionTestController()); $this->assertTrue(isset($_SESSION)); $Object = new Object(); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $Session->start(); $expected = $Session->id(); @@ -137,14 +137,14 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionInitialize() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertEqual($Session->__bare, 0); $Session->initialize(new SessionTestController()); $this->assertEqual($Session->__bare, 0); - $sessionController =& new SessionTestController(); + $sessionController = new SessionTestController(); $sessionController->params['bare'] = 1; $Session->initialize($sessionController); $this->assertEqual($Session->__bare, 1); @@ -156,14 +156,14 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionActivate() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertTrue($Session->__active); $this->assertNull($Session->activate()); $this->assertTrue($Session->__active); Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->__active); $this->assertNull($Session->activate()); $this->assertTrue($Session->__active); @@ -177,7 +177,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionValid() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertTrue($Session->valid()); @@ -185,17 +185,17 @@ class SessionComponentTest extends CakeTestCase { $this->assertFalse($Session->valid()); Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->__active); $this->assertFalse($Session->valid()); Configure::write('Session.start', true); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $Session->time = $Session->read('Config.time') + 1; $this->assertFalse($Session->valid()); Configure::write('Session.checkAgent', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $Session->time = $Session->read('Config.time') + 1; $this->assertFalse($Session->valid()); Configure::write('Session.checkAgent', true); @@ -207,12 +207,12 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionError() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->error()); Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->__active); $this->assertFalse($Session->error()); Configure::write('Session.start', true); @@ -224,7 +224,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionReadWrite() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->read('Test')); @@ -251,7 +251,7 @@ class SessionComponentTest extends CakeTestCase { $Session->del('Test'); Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->write('Test', 'some value')); $Session->write('Test', 'some value'); $this->assertFalse($Session->read('Test')); @@ -264,7 +264,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionDel() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->del('Test')); @@ -272,7 +272,7 @@ class SessionComponentTest extends CakeTestCase { $this->assertTrue($Session->del('Test')); Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $Session->write('Test', 'some value'); $this->assertFalse($Session->del('Test')); Configure::write('Session.start', true); @@ -284,7 +284,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionDelete() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->delete('Test')); @@ -292,7 +292,7 @@ class SessionComponentTest extends CakeTestCase { $this->assertTrue($Session->delete('Test')); Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $Session->write('Test', 'some value'); $this->assertFalse($Session->delete('Test')); Configure::write('Session.start', true); @@ -304,7 +304,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionCheck() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertFalse($Session->check('Test')); @@ -313,7 +313,7 @@ class SessionComponentTest extends CakeTestCase { $Session->delete('Test'); Configure::write('Session.start', false); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $Session->write('Test', 'some value'); $this->assertFalse($Session->check('Test')); Configure::write('Session.start', true); @@ -325,7 +325,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionFlash() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertNull($Session->read('Message.flash')); @@ -351,7 +351,7 @@ class SessionComponentTest extends CakeTestCase { */ function testSessionId() { unset($_SESSION); - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $this->assertNull($Session->id()); } /** @@ -361,7 +361,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionDestroy() { - $Session =& new SessionComponent(); + $Session = new SessionComponent(); $Session->write('Test', 'some value'); $this->assertEqual($Session->read('Test'), 'some value'); diff --git a/cake/tests/cases/libs/controller/controller.test.php b/cake/tests/cases/libs/controller/controller.test.php index 8c7b3204..90baed20 100755 --- a/cake/tests/cases/libs/controller/controller.test.php +++ b/cake/tests/cases/libs/controller/controller.test.php @@ -328,7 +328,7 @@ class TestController extends AppController { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class TestComponent extends Object { +class TestComponent extends CakeObject { /** * beforeRedirect method * @@ -380,7 +380,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testConstructClasses() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->modelClass = 'ControllerPost'; $Controller->passedArgs[] = '1'; $Controller->constructClasses(); @@ -388,7 +388,7 @@ class ControllerTest extends CakeTestCase { unset($Controller); - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->constructClasses(); @@ -404,7 +404,7 @@ class ControllerTest extends CakeTestCase { ); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('TestPlugin.TestPluginPost'); $Controller->constructClasses(); @@ -422,7 +422,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testAliasName() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('NameTest'); $Controller->constructClasses(); @@ -439,7 +439,7 @@ class ControllerTest extends CakeTestCase { */ function testPersistent() { Configure::write('Cache.disable', false); - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->modelClass = 'ControllerPost'; $Controller->persistModel = true; $Controller->constructClasses(); @@ -458,7 +458,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testPaginate() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); @@ -519,7 +519,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testPaginateExtraParams() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); @@ -551,7 +551,7 @@ class ControllerTest extends CakeTestCase { $this->assertEqual($Controller->ControllerPost->lastQuery['limit'], 12); $this->assertEqual($paging['options']['limit'], 12); - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('ControllerPaginateModel'); $Controller->params['url'] = array(); $Controller->constructClasses(); @@ -578,7 +578,7 @@ class ControllerTest extends CakeTestCase { * @access public */ function testPaginatePassedArgs() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('ControllerPost'); $Controller->passedArgs[] = array('1', '2', '3'); $Controller->params['url'] = array(); @@ -610,7 +610,7 @@ class ControllerTest extends CakeTestCase { * @return void **/ function testPaginateSpecialType() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); @@ -631,7 +631,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testDefaultPaginateParams() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->modelClass = 'ControllerPost'; $Controller->params['url'] = array(); $Controller->paginate = array('order' => 'ControllerPost.id DESC'); @@ -648,7 +648,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testFlash() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->flash('this should work', '/flash'); $result = $Controller->output; @@ -678,7 +678,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testControllerSet() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->set('variable_with_underscores', null); $this->assertTrue(array_key_exists('variable_with_underscores', $Controller->viewVars)); @@ -713,7 +713,7 @@ class ControllerTest extends CakeTestCase { function testRender() { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)); - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->viewPath = 'posts'; $result = $Controller->render('index'); @@ -744,7 +744,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testToBeInheritedGuardmethods() { - $Controller =& new Controller(); + $Controller = new Controller(); $this->assertTrue($Controller->_beforeScaffold('')); $this->assertTrue($Controller->_afterScaffoldSave('')); $this->assertTrue($Controller->_afterScaffoldSaveError('')); @@ -806,8 +806,8 @@ class ControllerTest extends CakeTestCase { App::import('Helper', 'Cache'); foreach ($codes as $code => $msg) { - $MockController =& new MockController(); - $MockController->Component =& new Component(); + $MockController = new MockController(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array("HTTP/1.1 {$code} {$msg}")); $MockController->expectAt(1, 'header', array('Location: http://cakephp.org')); @@ -816,8 +816,8 @@ class ControllerTest extends CakeTestCase { $this->assertFalse($MockController->autoRender); } foreach ($codes as $code => $msg) { - $MockController =& new MockController(); - $MockController->Component =& new Component(); + $MockController = new MockController(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array("HTTP/1.1 {$code} {$msg}")); $MockController->expectAt(1, 'header', array('Location: http://cakephp.org')); @@ -826,24 +826,24 @@ class ControllerTest extends CakeTestCase { $this->assertFalse($MockController->autoRender); } - $MockController =& new MockController(); - $MockController->Component =& new Component(); + $MockController = new MockController(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array('Location: http://www.example.org/users/login')); $MockController->expectCallCount('header', 1); $MockController->redirect('http://www.example.org/users/login', null, false); - $MockController =& new MockController(); - $MockController->Component =& new Component(); + $MockController = new MockController(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently')); $MockController->expectAt(1, 'header', array('Location: http://www.example.org/users/login')); $MockController->expectCallCount('header', 2); $MockController->redirect('http://www.example.org/users/login', 301, false); - $MockController =& new MockController(); + $MockController = new MockController(); $MockController->components = array('MockTest'); - $MockController->Component =& new Component(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', null); $MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently')); @@ -851,9 +851,9 @@ class ControllerTest extends CakeTestCase { $MockController->expectCallCount('header', 2); $MockController->redirect('http://cakephp.org', 301, false); - $MockController =& new MockController(); + $MockController = new MockController(); $MockController->components = array('MockTest'); - $MockController->Component =& new Component(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org'); $MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently')); @@ -861,17 +861,17 @@ class ControllerTest extends CakeTestCase { $MockController->expectCallCount('header', 2); $MockController->redirect('http://cakephp.org', 301, false); - $MockController =& new MockController(); + $MockController = new MockController(); $MockController->components = array('MockTest'); - $MockController->Component =& new Component(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', false); $MockController->expectNever('header'); $MockController->redirect('http://cakephp.org', 301, false); - $MockController =& new MockController(); + $MockController = new MockController(); $MockController->components = array('MockTest', 'MockTestB'); - $MockController->Component =& new Component(); + $MockController->Component = new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org'); $MockController->MockTestB->setReturnValue('beforeRedirect', 'http://bakery.cakephp.org'); @@ -891,7 +891,7 @@ class ControllerTest extends CakeTestCase { return; } - $TestController =& new TestController(); + $TestController = new TestController(); $TestController->constructClasses(); $testVars = get_class_vars('TestController'); @@ -914,7 +914,7 @@ class ControllerTest extends CakeTestCase { $this->assertEqual(count(array_diff($TestController->uses, $uses)), 0); $this->assertEqual(count(array_diff_assoc(Set::normalize($TestController->components), Set::normalize($components))), 0); - $TestController =& new AnotherTestController(); + $TestController = new AnotherTestController(); $TestController->constructClasses(); $appVars = get_class_vars('AppController'); @@ -927,7 +927,7 @@ class ControllerTest extends CakeTestCase { $this->assertFalse(isset($TestController->ControllerPost)); - $TestController =& new ControllerCommentsController(); + $TestController = new ControllerCommentsController(); $TestController->constructClasses(); $appVars = get_class_vars('AppController'); @@ -950,7 +950,7 @@ class ControllerTest extends CakeTestCase { if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) { return; } - $TestController =& new TestController(); + $TestController = new TestController(); $expected = array('foo'); $TestController->components = array('Cookie' => $expected); $TestController->constructClasses(); @@ -963,7 +963,7 @@ class ControllerTest extends CakeTestCase { * @return void **/ function testMergeVarsNotGreedy() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->components = array(); $Controller->uses = array(); $Controller->constructClasses(); @@ -977,7 +977,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testReferer() { - $Controller =& new Controller(); + $Controller = new Controller(); $_SERVER['HTTP_REFERER'] = 'http://cakephp.org'; $result = $Controller->referer(null, false); $expected = 'http://cakephp.org'; @@ -1023,7 +1023,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testSetAction() { - $TestController =& new TestController(); + $TestController = new TestController(); $TestController->setAction('index', 1, 2); $expected = array('testId' => 1, 'test2Id' => 2); $this->assertidentical($TestController->data, $expected); @@ -1035,7 +1035,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testUnimplementedIsAuthorized() { - $TestController =& new TestController(); + $TestController = new TestController(); $TestController->isAuthorized(); $this->assertError(); } @@ -1046,7 +1046,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testValidateErrors() { - $TestController =& new TestController(); + $TestController = new TestController(); $TestController->constructClasses(); $this->assertFalse($TestController->validateErrors()); $this->assertEqual($TestController->validate(), 0); @@ -1067,7 +1067,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testPostConditions() { - $Controller =& new Controller(); + $Controller = new Controller(); $data = array( @@ -1132,7 +1132,7 @@ class ControllerTest extends CakeTestCase { */ function testRequestHandlerPrefers(){ Configure::write('debug', 2); - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->components = array("RequestHandler"); $Controller->modelClass='ControllerPost'; $Controller->params['url']['ext'] = 'rss'; diff --git a/cake/tests/cases/libs/controller/controller_merge_vars.test.php b/cake/tests/cases/libs/controller/controller_merge_vars.test.php index b405d3ec..b7cf274c 100755 --- a/cake/tests/cases/libs/controller/controller_merge_vars.test.php +++ b/cake/tests/cases/libs/controller/controller_merge_vars.test.php @@ -53,7 +53,7 @@ if (!class_exists('AppController')) { * * @package cake.tests.cases.libs.controller **/ -class MergeVarComponent extends Object { +class MergeVarComponent extends CakeObject { } @@ -139,7 +139,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testComponentParamMergingNoDuplication() { - $Controller =& new MergeVariablesController(); + $Controller = new MergeVariablesController(); $Controller->constructClasses(); $expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false)); @@ -151,7 +151,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testComponentMergingWithRedeclarations() { - $Controller =& new MergeVariablesController(); + $Controller = new MergeVariablesController(); $Controller->components['MergeVar'] = array('remote', 'redirect' => true); $Controller->constructClasses(); @@ -164,7 +164,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testHelperSettingMergingNoDuplication() { - $Controller =& new MergeVariablesController(); + $Controller = new MergeVariablesController(); $Controller->constructClasses(); $expected = array('MergeVar' => array('format' => 'html', 'terse')); @@ -176,7 +176,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testMergeVarsWithPlugin() { - $Controller =& new MergePostsController(); + $Controller = new MergePostsController(); $Controller->components = array('Email' => array('ports' => 'open')); $Controller->plugin = 'MergeVarPlugin'; $Controller->constructClasses(); @@ -194,7 +194,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { ); $this->assertEqual($Controller->helpers, $expected, 'Helpers are unexpected %s'); - $Controller =& new MergePostsController(); + $Controller = new MergePostsController(); $Controller->components = array(); $Controller->plugin = 'MergeVarPlugin'; $Controller->constructClasses(); @@ -212,7 +212,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testMergeVarsNotGreedy() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->components = array(); $Controller->uses = array(); $Controller->constructClasses(); diff --git a/cake/tests/cases/libs/controller/pages_controller.test.php b/cake/tests/cases/libs/controller/pages_controller.test.php index 66980e74..53aef113 100755 --- a/cake/tests/cases/libs/controller/pages_controller.test.php +++ b/cake/tests/cases/libs/controller/pages_controller.test.php @@ -67,7 +67,7 @@ class PagesControllerTest extends CakeTestCase { } Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)); - $Pages =& new PagesController(); + $Pages = new PagesController(); $Pages->viewPath = 'posts'; $Pages->display('index'); diff --git a/cake/tests/cases/libs/controller/scaffold.test.php b/cake/tests/cases/libs/controller/scaffold.test.php index 72cab3eb..c22822bd 100755 --- a/cake/tests/cases/libs/controller/scaffold.test.php +++ b/cake/tests/cases/libs/controller/scaffold.test.php @@ -262,7 +262,7 @@ class ScaffoldViewTest extends CakeTestCase { * @return void */ function startTest() { - $this->Controller =& new ScaffoldMockController(); + $this->Controller = new ScaffoldMockController(); } /** * endTest method @@ -284,7 +284,7 @@ class ScaffoldViewTest extends CakeTestCase { Configure::write('Routing.admin', 'admin'); $this->Controller->action = 'index'; - $ScaffoldView =& new TestScaffoldView($this->Controller); + $ScaffoldView = new TestScaffoldView($this->Controller); $result = $ScaffoldView->testGetFilename('index'); $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'index.ctp'; $this->assertEqual($result, $expected); @@ -328,11 +328,11 @@ class ScaffoldViewTest extends CakeTestCase { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS)); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); - $Controller =& new ScaffoldMockController(); + $Controller = new ScaffoldMockController(); $Controller->scaffold = 'admin'; $Controller->viewPath = 'posts'; $Controller->action = 'admin_edit'; - $ScaffoldView =& new TestScaffoldView($Controller); + $ScaffoldView = new TestScaffoldView($Controller); $result = $ScaffoldView->testGetFilename('admin_edit'); $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp'; $this->assertEqual($result, $expected); @@ -341,12 +341,12 @@ class ScaffoldViewTest extends CakeTestCase { $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp'; $this->assertEqual($result, $expected); - $Controller =& new ScaffoldMockController(); + $Controller = new ScaffoldMockController(); $Controller->scaffold = 'admin'; $Controller->viewPath = 'tests'; $Controller->plugin = 'test_plugin'; $Controller->action = 'admin_add'; - $ScaffoldView =& new TestScaffoldView($Controller); + $ScaffoldView = new TestScaffoldView($Controller); $result = $ScaffoldView->testGetFilename('admin_add'); $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS .'test_plugin' . DS . 'views' . DS . 'tests' . DS . 'scaffold.edit.ctp'; @@ -595,7 +595,7 @@ class ScaffoldTest extends CakeTestCase { * @return void */ function startTest() { - $this->Controller =& new ScaffoldMockController(); + $this->Controller = new ScaffoldMockController(); } /** * endTest method @@ -634,7 +634,7 @@ class ScaffoldTest extends CakeTestCase { $this->Controller->controller = 'scaffold_mock'; $this->Controller->base = '/'; $this->Controller->constructClasses(); - $Scaffold =& new TestScaffoldMock($this->Controller, $params); + $Scaffold = new TestScaffoldMock($this->Controller, $params); $result = $Scaffold->getParams(); $this->assertEqual($result['action'], 'admin_edit'); } @@ -664,7 +664,7 @@ class ScaffoldTest extends CakeTestCase { $this->Controller->controller = 'scaffold_mock'; $this->Controller->base = '/'; $this->Controller->constructClasses(); - $Scaffold =& new TestScaffoldMock($this->Controller, $params); + $Scaffold = new TestScaffoldMock($this->Controller, $params); $result = $Scaffold->controller->viewVars; $this->assertEqual($result['singularHumanName'], 'Scaffold Mock'); diff --git a/cake/tests/cases/libs/error.test.php b/cake/tests/cases/libs/error.test.php index e3d233e1..550fb1ef 100755 --- a/cake/tests/cases/libs/error.test.php +++ b/cake/tests/cases/libs/error.test.php @@ -36,7 +36,7 @@ if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) { * @package cake * @subpackage cake.tests.cases.libs */ -class BlueberryComponent extends Object { +class BlueberryComponent extends CakeObject { /** * testName property * @@ -261,7 +261,7 @@ class ErrorHandlerTest extends CakeTestCase { $this->assertPattern("/'\/test_error'<\/strong>/", $result); ob_start(); - $TestErrorHandler =& new TestErrorHandler('error404', array('message' => 'Page not found')); + $TestErrorHandler = new TestErrorHandler('error404', array('message' => 'Page not found')); ob_get_clean(); ob_start(); $TestErrorHandler->error404(array( diff --git a/cake/tests/cases/libs/file.test.php b/cake/tests/cases/libs/file.test.php index f0d64a7b..ad668e1b 100755 --- a/cake/tests/cases/libs/file.test.php +++ b/cake/tests/cases/libs/file.test.php @@ -47,7 +47,7 @@ class FileTest extends CakeTestCase { */ function testBasic() { $file = __FILE__; - $this->File =& new File($file); + $this->File = new File($file); $result = $this->File->pwd(); $expecting = $file; @@ -209,7 +209,7 @@ class FileTest extends CakeTestCase { */ function testCreate() { $tmpFile = TMP.'tests'.DS.'cakephp.file.test.tmp'; - $File =& new File($tmpFile, true, 0777); + $File = new File($tmpFile, true, 0777); $this->assertTrue($File->exists()); } /** @@ -219,7 +219,7 @@ class FileTest extends CakeTestCase { * @return void */ function testOpeningNonExistantFileCreatesIt() { - $someFile =& new File(TMP . 'some_file.txt', false); + $someFile = new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertEqual($someFile->read(), ''); $someFile->close(); @@ -252,7 +252,7 @@ class FileTest extends CakeTestCase { * @return void */ function testReadable() { - $someFile =& new File(TMP . 'some_file.txt', false); + $someFile = new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertTrue($someFile->readable()); $someFile->close(); @@ -265,7 +265,7 @@ class FileTest extends CakeTestCase { * @return void */ function testWritable() { - $someFile =& new File(TMP . 'some_file.txt', false); + $someFile = new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertTrue($someFile->writable()); $someFile->close(); @@ -278,7 +278,7 @@ class FileTest extends CakeTestCase { * @return void */ function testExecutable() { - $someFile =& new File(TMP . 'some_file.txt', false); + $someFile = new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertFalse($someFile->executable()); $someFile->close(); @@ -291,7 +291,7 @@ class FileTest extends CakeTestCase { * @return void */ function testLastAccess() { - $someFile =& new File(TMP . 'some_file.txt', false); + $someFile = new File(TMP . 'some_file.txt', false); $this->assertFalse($someFile->lastAccess()); $this->assertTrue($someFile->open()); $this->assertEqual($someFile->lastAccess(), time()); @@ -305,7 +305,7 @@ class FileTest extends CakeTestCase { * @return void */ function testLastChange() { - $someFile =& new File(TMP . 'some_file.txt', false); + $someFile = new File(TMP . 'some_file.txt', false); $this->assertFalse($someFile->lastChange()); $this->assertTrue($someFile->open('r+')); $this->assertEqual($someFile->lastChange(), time()); @@ -328,7 +328,7 @@ class FileTest extends CakeTestCase { unlink($tmpFile); } - $TmpFile =& new File($tmpFile); + $TmpFile = new File($tmpFile); $this->assertFalse(file_exists($tmpFile)); $this->assertFalse(is_resource($TmpFile->handle)); @@ -358,7 +358,7 @@ class FileTest extends CakeTestCase { unlink($tmpFile); } - $TmpFile =& new File($tmpFile); + $TmpFile = new File($tmpFile); $this->assertFalse(file_exists($tmpFile)); $fragments = array('CakePHP\'s', ' test suite', ' was here ...', ''); @@ -386,13 +386,13 @@ class FileTest extends CakeTestCase { if (!file_exists($tmpFile)) { touch($tmpFile); } - $TmpFile =& new File($tmpFile); + $TmpFile = new File($tmpFile); $this->assertTrue(file_exists($tmpFile)); $result = $TmpFile->delete(); $this->assertTrue($result); $this->assertFalse(file_exists($tmpFile)); - $TmpFile =& new File('/this/does/not/exist'); + $TmpFile = new File('/this/does/not/exist'); $result = $TmpFile->delete(); $this->assertFalse($result); } diff --git a/cake/tests/cases/libs/folder.test.php b/cake/tests/cases/libs/folder.test.php index 6fad570d..a3915a09 100755 --- a/cake/tests/cases/libs/folder.test.php +++ b/cake/tests/cases/libs/folder.test.php @@ -40,7 +40,7 @@ class FolderTest extends CakeTestCase { */ function testBasic() { $path = dirname(__FILE__); - $Folder =& new Folder($path); + $Folder = new Folder($path); $result = $Folder->pwd(); $this->assertEqual($result, $path); @@ -66,7 +66,7 @@ class FolderTest extends CakeTestCase { $path = dirname(dirname(__FILE__)); $inside = dirname($path) . DS; - $Folder =& new Folder($path); + $Folder = new Folder($path); $result = $Folder->pwd(); $this->assertEqual($result, $path); @@ -91,7 +91,7 @@ class FolderTest extends CakeTestCase { */ function testOperations() { $path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'libs' . DS . 'templates' . DS . 'skel'; - $Folder =& new Folder($path); + $Folder = new Folder($path); $result = is_dir($Folder->pwd()); $this->assertTrue($result); @@ -150,7 +150,7 @@ class FolderTest extends CakeTestCase { $result = $Folder->delete(); $this->assertTrue($result); - $Folder =& new Folder('non-existent'); + $Folder = new Folder('non-existent'); $result = $Folder->pwd(); $this->assertNull($result); } @@ -164,7 +164,7 @@ class FolderTest extends CakeTestCase { $this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s Folder permissions tests not supported on Windows'); $path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'libs' . DS . 'templates' . DS . 'skel'; - $Folder =& new Folder($path); + $Folder = new Folder($path); $subdir = 'test_folder_new'; $new = TMP . $subdir; @@ -174,7 +174,7 @@ class FolderTest extends CakeTestCase { $this->assertTrue($Folder->create($new . DS . 'test2')); $filePath = $new . DS . 'test1.php'; - $File =& new File($filePath); + $File = new File($filePath); $this->assertTrue($File->create()); $copy = TMP . 'test_folder_copy'; @@ -200,7 +200,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testZeroAsDirectory() { - $Folder =& new Folder(TMP); + $Folder = new Folder(TMP); $new = TMP . '0'; $this->assertTrue($Folder->create($new)); @@ -222,7 +222,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFolderRead() { - $Folder =& new Folder(TMP); + $Folder = new Folder(TMP); $expected = array('cache', 'logs', 'sessions', 'tests'); $result = $Folder->read(true, true); @@ -240,7 +240,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFolderTree() { - $Folder =& new Folder(); + $Folder = new Folder(); $expected = array( array( TEST_CAKE_CORE_INCLUDE_PATH . 'config', @@ -380,7 +380,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testInCakePath() { - $Folder =& new Folder(); + $Folder = new Folder(); $Folder->cd(ROOT); $path = 'C:\\path\\to\\file'; $result = $Folder->inCakePath($path); @@ -404,7 +404,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFind() { - $Folder =& new Folder(); + $Folder = new Folder(); $Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH . 'config'); $result = $Folder->find(); $expected = array('config.php', 'paths.php'); @@ -456,7 +456,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFindRecursive() { - $Folder =& new Folder(); + $Folder = new Folder(); $Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH); $result = $Folder->findRecursive('(config|paths)\.php'); $expected = array( @@ -476,7 +476,7 @@ class FolderTest extends CakeTestCase { $Folder->cd(TMP); $Folder->mkdir($Folder->pwd() . DS . 'testme'); $Folder->cd('testme'); - $File =& new File($Folder->pwd() . DS . 'paths.php'); + $File = new File($Folder->pwd() . DS . 'paths.php'); $File->create(); $Folder->cd(TMP . 'sessions'); $result = $Folder->findRecursive('paths\.php'); @@ -484,7 +484,7 @@ class FolderTest extends CakeTestCase { $this->assertIdentical($result, $expected); $Folder->cd(TMP . 'testme'); - $File =& new File($Folder->pwd() . DS . 'my.php'); + $File = new File($Folder->pwd() . DS . 'my.php'); $File->create(); $Folder->cd($Folder->pwd() . '/../..'); @@ -515,7 +515,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testConstructWithNonExistantPath() { - $Folder =& new Folder(TMP . 'config_non_existant', true); + $Folder = new Folder(TMP . 'config_non_existant', true); $this->assertTrue(is_dir(TMP . 'config_non_existant')); $Folder->cd(TMP); $Folder->delete($Folder->pwd() . 'config_non_existant'); @@ -527,10 +527,10 @@ class FolderTest extends CakeTestCase { * @return void */ function testDirSize() { - $Folder =& new Folder(TMP . 'config_non_existant', true); + $Folder = new Folder(TMP . 'config_non_existant', true); $this->assertEqual($Folder->dirSize(), 0); - $File =& new File($Folder->pwd() . DS . 'my.php', true, 0777); + $File = new File($Folder->pwd() . DS . 'my.php', true, 0777); $File->create(); $File->write('something here'); $File->close(); @@ -547,7 +547,7 @@ class FolderTest extends CakeTestCase { */ function testDelete() { $path = TMP . 'folder_delete_test'; - $Folder =& new Folder($path, true); + $Folder = new Folder($path, true); touch(TMP . 'folder_delete_test' . DS . 'file1'); touch(TMP . 'folder_delete_test' . DS . 'file2'); @@ -593,35 +593,35 @@ class FolderTest extends CakeTestCase { touch($file1); touch($file2); - $Folder =& new Folder($folder1); + $Folder = new Folder($folder1); $result = $Folder->copy($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); $this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php')); - $Folder =& new Folder($folder3); + $Folder = new Folder($folder3); $Folder->delete(); - $Folder =& new Folder($folder1); + $Folder = new Folder($folder1); $result = $Folder->copy($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); $this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php')); - $Folder =& new Folder($folder3); + $Folder = new Folder($folder3); $Folder->delete(); new Folder($folder3, true); new Folder($folder3 . DS . 'folder2', true); file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched'); - $Folder =& new Folder($folder1); + $Folder = new Folder($folder1); $result = $Folder->copy($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); $this->assertEqual(file_get_contents($folder3 . DS . 'folder2' . DS . 'file2.php'), 'untouched'); - $Folder =& new Folder($path); + $Folder = new Folder($path); $Folder->delete(); } /** @@ -651,7 +651,7 @@ class FolderTest extends CakeTestCase { touch($file1); touch($file2); - $Folder =& new Folder($folder1); + $Folder = new Folder($folder1); $result = $Folder->move($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); @@ -661,7 +661,7 @@ class FolderTest extends CakeTestCase { $this->assertFalse(file_exists($folder2)); $this->assertFalse(file_exists($file2)); - $Folder =& new Folder($folder3); + $Folder = new Folder($folder3); $Folder->delete(); new Folder($folder1, true); @@ -669,7 +669,7 @@ class FolderTest extends CakeTestCase { touch($file1); touch($file2); - $Folder =& new Folder($folder1); + $Folder = new Folder($folder1); $result = $Folder->move($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); @@ -679,7 +679,7 @@ class FolderTest extends CakeTestCase { $this->assertFalse(file_exists($folder2)); $this->assertFalse(file_exists($file2)); - $Folder =& new Folder($folder3); + $Folder = new Folder($folder3); $Folder->delete(); new Folder($folder1, true); @@ -690,7 +690,7 @@ class FolderTest extends CakeTestCase { touch($file2); file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched'); - $Folder =& new Folder($folder1); + $Folder = new Folder($folder1); $result = $Folder->move($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); @@ -699,7 +699,7 @@ class FolderTest extends CakeTestCase { $this->assertFalse(file_exists($folder2)); $this->assertFalse(file_exists($file2)); - $Folder =& new Folder($path); + $Folder = new Folder($path); $Folder->delete(); } } diff --git a/cake/tests/cases/libs/http_socket.test.php b/cake/tests/cases/libs/http_socket.test.php index b3fa948b..c169ce27 100755 --- a/cake/tests/cases/libs/http_socket.test.php +++ b/cake/tests/cases/libs/http_socket.test.php @@ -58,8 +58,8 @@ class HttpSocketTest extends CakeTestCase { Mock::generatePartial('HttpSocket', 'TestHttpSocketRequests', array('read', 'write', 'connect', 'request')); } - $this->Socket =& new TestHttpSocket(); - $this->RequestSocket =& new TestHttpSocketRequests(); + $this->Socket = new TestHttpSocket(); + $this->RequestSocket = new TestHttpSocketRequests(); } /** * We use this function to clean up after the test case was executed diff --git a/cake/tests/cases/libs/l10n.test.php b/cake/tests/cases/libs/l10n.test.php index 48df8fa3..8a3a32bb 100755 --- a/cake/tests/cases/libs/l10n.test.php +++ b/cake/tests/cases/libs/l10n.test.php @@ -39,7 +39,7 @@ class L10nTest extends CakeTestCase { * @return void */ function testGet() { - $l10n =& new L10n(); + $l10n = new L10n(); // Catalog Entry $l10n->get('en'); @@ -124,7 +124,7 @@ class L10nTest extends CakeTestCase { $__SERVER = $_SERVER; $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'inexistent,en-ca'; - $l10n =& new L10n(); + $l10n = new L10n(); $l10n->get(); $result = $l10n->language; $expected = 'English (Canadian)'; @@ -175,7 +175,7 @@ class L10nTest extends CakeTestCase { * @return void */ function testMap() { - $l10n =& new L10n(); + $l10n = new L10n(); $result = $l10n->map(array('afr', 'af')); $expected = array('afr' => 'af', 'af' => 'afr'); @@ -496,7 +496,7 @@ class L10nTest extends CakeTestCase { * @return void */ function testCatalog() { - $l10n =& new L10n(); + $l10n = new L10n(); $result = $l10n->catalog(array('af')); $expected = array( diff --git a/cake/tests/cases/libs/magic_db.test.php b/cake/tests/cases/libs/magic_db.test.php index 3eba7eb4..e383faf1 100755 --- a/cake/tests/cases/libs/magic_db.test.php +++ b/cake/tests/cases/libs/magic_db.test.php @@ -43,7 +43,7 @@ class MagicDbTest extends UnitTestCase { * @access public */ function setUp() { - $this->Db =& new MagicDb(); + $this->Db = new MagicDb(); } /** * MagicDb::analyze should properly detect the file type and output additional info as requested. @@ -158,7 +158,7 @@ class MagicDbTest extends UnitTestCase { * @package cake * @subpackage cake.tests.cases.libs */ -class MagicDbTestData extends Object { +class MagicDbTestData extends CakeObject { /** * Base64 encoded data * diff --git a/cake/tests/cases/libs/model/behavior.test.php b/cake/tests/cases/libs/model/behavior.test.php index 727316a2..374741a9 100755 --- a/cake/tests/cases/libs/model/behavior.test.php +++ b/cake/tests/cases/libs/model/behavior.test.php @@ -983,7 +983,7 @@ class BehaviorTest extends CakeTestCase { * @return void */ function testBehaviorTrigger() { - $Apple =& new Apple(); + $Apple = new Apple(); $Apple->Behaviors->attach('Test'); $Apple->Behaviors->attach('Test2'); $Apple->Behaviors->attach('Test3'); @@ -1057,7 +1057,7 @@ class BehaviorTest extends CakeTestCase { * @return void **/ function testBehaviorAttachAndDetach() { - $Sample =& new Sample(); + $Sample = new Sample(); $Sample->actsAs = array('Test3' => array('bar'), 'Test2' => array('foo', 'bar')); $Sample->Behaviors->init($Sample->alias, $Sample->actsAs); $Sample->Behaviors->attach('Test2'); diff --git a/cake/tests/cases/libs/model/behaviors/acl.test.php b/cake/tests/cases/libs/model/behaviors/acl.test.php index 3ca1974e..f58a6730 100755 --- a/cake/tests/cases/libs/model/behaviors/acl.test.php +++ b/cake/tests/cases/libs/model/behaviors/acl.test.php @@ -210,8 +210,8 @@ class AclBehaviorTestCase extends CakeTestCase { function startTest() { Configure::write('Acl.database', 'test_suite'); - $this->Aco =& new Aco(); - $this->Aro =& new Aro(); + $this->Aco = new Aco(); + $this->Aro = new Aro(); } /** * tearDown method @@ -230,12 +230,12 @@ class AclBehaviorTestCase extends CakeTestCase { * @access public */ function testSetup() { - $User =& new AclUser(); + $User = new AclUser(); $this->assertTrue(isset($User->Behaviors->Acl->settings['User'])); $this->assertEqual($User->Behaviors->Acl->settings['User']['type'], 'requester'); $this->assertTrue(is_object($User->Aro)); - $Post =& new AclPost(); + $Post = new AclPost(); $this->assertTrue(isset($Post->Behaviors->Acl->settings['Post'])); $this->assertEqual($Post->Behaviors->Acl->settings['Post']['type'], 'controlled'); $this->assertTrue(is_object($Post->Aco)); @@ -247,7 +247,7 @@ class AclBehaviorTestCase extends CakeTestCase { * @access public */ function testAfterSave() { - $Post =& new AclPost(); + $Post = new AclPost(); $data = array( 'Post' => array( 'author_id' => 1, @@ -271,7 +271,7 @@ class AclBehaviorTestCase extends CakeTestCase { ); $this->Aro->save($aroData); - $Person =& new AclPerson(); + $Person = new AclPerson(); $data = array( 'AclPerson' => array( 'name' => 'Trent', @@ -304,7 +304,7 @@ class AclBehaviorTestCase extends CakeTestCase { ) ); $this->Aro->save($aroData); - $Person =& new AclPerson(); + $Person = new AclPerson(); $data = array( 'AclPerson' => array( 'name' => 'Trent', @@ -349,7 +349,7 @@ class AclBehaviorTestCase extends CakeTestCase { * @access public */ function testNode() { - $Person =& new AclPerson(); + $Person = new AclPerson(); $aroData = array( 'Aro' => array( 'model' => 'AclPerson', diff --git a/cake/tests/cases/libs/model/behaviors/containable.test.php b/cake/tests/cases/libs/model/behaviors/containable.test.php index ca16f318..58f0276b 100755 --- a/cake/tests/cases/libs/model/behaviors/containable.test.php +++ b/cake/tests/cases/libs/model/behaviors/containable.test.php @@ -3123,7 +3123,7 @@ class ContainableBehaviorTest extends CakeTestCase { * @return void */ function testPaginate() { - $Controller =& new Controller(); + $Controller = new Controller(); $Controller->uses = array('Article'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); diff --git a/cake/tests/cases/libs/model/behaviors/translate.test.php b/cake/tests/cases/libs/model/behaviors/translate.test.php index 3ec69f02..36b60180 100755 --- a/cake/tests/cases/libs/model/behaviors/translate.test.php +++ b/cake/tests/cases/libs/model/behaviors/translate.test.php @@ -70,22 +70,22 @@ class TranslateBehaviorTest extends CakeTestCase { * @return void */ function testTranslateModel() { - $TestModel =& new Tag(); + $TestModel = new Tag(); $TestModel->translateTable = 'another_i18n'; $TestModel->Behaviors->attach('Translate', array('title')); $this->assertEqual($TestModel->translateModel()->name, 'I18nModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'another_i18n'); - $TestModel =& new User(); + $TestModel = new User(); $TestModel->Behaviors->attach('Translate', array('title')); $this->assertEqual($TestModel->translateModel()->name, 'I18nModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'i18n'); - $TestModel =& new TranslatedArticle(); + $TestModel = new TranslatedArticle(); $this->assertEqual($TestModel->translateModel()->name, 'TranslateArticleModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'article_i18n'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $this->assertEqual($TestModel->translateModel()->name, 'TranslateTestModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'i18n'); } @@ -98,7 +98,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleFalsePlain() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = false; $result = $TestModel->read(null, 1); @@ -122,7 +122,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleFalseAssociations() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = false; $TestModel->unbindTranslation(); $translations = array('title' => 'Title', 'content' => 'Content'); @@ -176,7 +176,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleSingle() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'eng'; $result = $TestModel->read(null, 1); $expected = array( @@ -231,7 +231,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleSingleWithConditions() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'eng'; $result = $TestModel->find('all', array('conditions' => array('slug' => 'first_translated'))); $expected = array( @@ -270,7 +270,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleSingleAssociations() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'eng'; $TestModel->unbindTranslation(); $translations = array('title' => 'Title', 'content' => 'Content'); @@ -330,7 +330,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleMultiple() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = array('deu', 'eng', 'cze'); $delete = array( array('locale' => 'deu'), @@ -393,7 +393,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMissingTranslation() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'rus'; $result = $TestModel->read(null, 1); $this->assertFalse($result); @@ -420,7 +420,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testTranslatedFindList() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'deu'; $TestModel->displayField = 'title'; $result = $TestModel->find('list', array('recursive' => 1)); @@ -453,7 +453,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testReadSelectedFields() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'eng'; $result = $TestModel->find('all', array('fields' => array('slug', 'TranslatedItem.content'))); $expected = array( @@ -488,7 +488,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testSaveCreate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'spa'; $data = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4', 'content' => 'Contenido #4'); $TestModel->create($data); @@ -506,7 +506,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testSaveUpdate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'spa'; $oldData = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4'); $TestModel->create($oldData); @@ -528,7 +528,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMultipleCreate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'deu'; $data = array( 'slug' => 'new_translated', @@ -566,7 +566,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMultipleUpdate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'eng'; $TestModel->validate['title'] = 'notEmpty'; $data = array('TranslatedItem' => array( @@ -608,7 +608,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMixedCreateUpdateWithArrayLocale() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = array('cze', 'deu'); $data = array('TranslatedItem' => array( 'id' => 1, @@ -647,7 +647,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testValidation() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $TestModel->locale = 'eng'; $TestModel->validate['title'] = '/Only this title/'; $data = array('TranslatedItem' => array( @@ -678,7 +678,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testAttachDetach() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel =& new TranslatedItem(); + $TestModel = new TranslatedItem(); $Behavior =& $this->Model->Behaviors->Translate; $TestModel->unbindTranslation(); @@ -728,7 +728,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testAnotherTranslateTable() { $this->loadFixtures('Translate', 'TranslatedItem', 'TranslateTable'); - $TestModel =& new TranslatedItemWithTable(); + $TestModel = new TranslatedItemWithTable(); $TestModel->locale = 'eng'; $result = $TestModel->read(null, 1); $expected = array( @@ -751,7 +751,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testTranslateWithAssociations() { $this->loadFixtures('TranslateArticle', 'TranslatedArticle', 'User', 'Comment', 'ArticlesTag', 'Tag'); - $TestModel =& new TranslatedArticle(); + $TestModel = new TranslatedArticle(); $TestModel->locale = 'eng'; $recursive = $TestModel->recursive; diff --git a/cake/tests/cases/libs/model/behaviors/tree.test.php b/cake/tests/cases/libs/model/behaviors/tree.test.php index 2d030cb4..592d6de5 100755 --- a/cake/tests/cases/libs/model/behaviors/tree.test.php +++ b/cake/tests/cases/libs/model/behaviors/tree.test.php @@ -60,7 +60,7 @@ class NumberTreeTest extends CakeTestCase { */ function testInitialize() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->find('count'); @@ -77,7 +77,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidLeft() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -103,7 +103,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidRight() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -129,7 +129,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidParent() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -154,7 +154,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectNoneExistantParent() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -177,7 +177,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRecoverFromMissingParent() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -200,7 +200,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidParents() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->updateAll(array($parentField => null)); @@ -222,7 +222,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidLftsRghts() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->updateAll(array($leftField => 0, $rightField => 0)); @@ -243,7 +243,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectEqualLftsRghts() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(1, 3); $result = $this->Tree->findByName('1.1'); @@ -270,7 +270,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddOrphan() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); @@ -289,7 +289,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddMiddle() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data= $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id')); @@ -322,7 +322,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddInvalid() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -346,7 +346,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddNotIndexedByModel() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->save(array('name' => 'testAddNotIndexed', $parentField => null)); @@ -365,7 +365,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMovePromote() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -391,7 +391,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveWithWhitelist() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -418,7 +418,7 @@ class NumberTreeTest extends CakeTestCase { */ function testInsertWithWhitelist() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->whitelist = array('name', $parentField); @@ -436,7 +436,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveBefore() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -464,7 +464,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveAfter() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -492,7 +492,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDemoteInvalid() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -525,7 +525,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveInvalid() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -551,7 +551,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveSelfInvalid() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -577,7 +577,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUpSuccess() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2'), array('id')); @@ -598,7 +598,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUpFail() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.1')); @@ -620,7 +620,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUp2() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -650,7 +650,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUpFirst() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -680,7 +680,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDownSuccess() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id')); @@ -701,7 +701,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDownFail() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2')); @@ -722,7 +722,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDownLast() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -752,7 +752,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDown2() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -782,7 +782,7 @@ class NumberTreeTest extends CakeTestCase { */ function testSaveNoMove() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -812,7 +812,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveToRootAndMoveUp() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(1, 1); $data = $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id')); $this->Tree->id = $data[$modelClass]['id']; @@ -836,7 +836,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDelete() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -871,7 +871,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemove() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); $result = $this->Tree->findByName('1.1'); @@ -903,7 +903,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveLastTopParent() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -936,7 +936,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveNoChildren() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -970,7 +970,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveAndDelete() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1002,7 +1002,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveAndDeleteNoChildren() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1034,7 +1034,7 @@ class NumberTreeTest extends CakeTestCase { */ function testChildren() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1. Root')); @@ -1062,7 +1062,7 @@ class NumberTreeTest extends CakeTestCase { */ function testCountChildren() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1. Root')); @@ -1082,7 +1082,7 @@ class NumberTreeTest extends CakeTestCase { */ function testGetParentNode() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2.2')); @@ -1100,7 +1100,7 @@ class NumberTreeTest extends CakeTestCase { */ function testGetPath() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2.2')); @@ -1120,7 +1120,7 @@ class NumberTreeTest extends CakeTestCase { */ function testNoAmbiguousColumn() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); @@ -1152,7 +1152,7 @@ class NumberTreeTest extends CakeTestCase { */ function testReorderTree() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(3, 3); $nodes = $this->Tree->find('list', array('order' => $leftField)); @@ -1180,7 +1180,7 @@ class NumberTreeTest extends CakeTestCase { */ function testGenerateTreeListWithSelfJoin() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); @@ -1197,7 +1197,7 @@ class NumberTreeTest extends CakeTestCase { */ function testArraySyntax() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(3, 3); $this->assertIdentical($this->Tree->childCount(2), $this->Tree->childCount(array('id' => 2))); $this->assertIdentical($this->Tree->getParentNode(2), $this->Tree->getParentNode(array('id' => 2))); @@ -1237,7 +1237,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testStringScope() { - $this->Tree =& new FlagTree(); + $this->Tree = new FlagTree(); $this->Tree->initialize(2, 3); $this->Tree->id = 1; @@ -1273,7 +1273,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testArrayScope() { - $this->Tree =& new FlagTree(); + $this->Tree = new FlagTree(); $this->Tree->initialize(2, 3); $this->Tree->id = 1; @@ -1309,7 +1309,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testMoveUpWithScope() { - $this->Ad =& new Ad(); + $this->Ad = new Ad(); $this->Ad->Behaviors->attach('Tree', array('scope'=>'Campaign')); $this->Ad->moveUp(6); @@ -1325,7 +1325,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testMoveDownWithScope() { - $this->Ad =& new Ad(); + $this->Ad = new Ad(); $this->Ad->Behaviors->attach('Tree', array('scope' => 'Campaign')); $this->Ad->moveDown(6); @@ -1342,7 +1342,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testTranslatingTree() { - $this->Tree =& new FlagTree(); + $this->Tree = new FlagTree(); $this->Tree->cacheQueries = false; $this->Tree->translateModel = 'TranslateTreeTestModel'; $this->Tree->Behaviors->attach('Translate', array('name')); @@ -1441,10 +1441,10 @@ class ScopedTreeTest extends NumberTreeTest { */ function testAliasesWithScopeInTwoTreeAssociations() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); - $this->TreeTwo =& new NumberTreeTwo(); + $this->TreeTwo = new NumberTreeTwo(); $record = $this->Tree->find('first'); @@ -1522,7 +1522,7 @@ class AfterTreeTest extends NumberTreeTest { * @return void */ function testAftersaveCallback() { - $this->Tree =& new AfterTree(); + $this->Tree = new AfterTree(); $expected = array('AfterTree' => array('name' => 'Six and One Half Changed in AfterTree::afterSave() but not in database', 'parent_id' => 6, 'lft' => 11, 'rght' => 12)); $result = $this->Tree->save(array('AfterTree' => array('name' => 'Six and One Half', 'parent_id' => 6))); @@ -1594,7 +1594,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testMovePromote() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -1620,7 +1620,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testMoveWithWhitelist() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -1647,7 +1647,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testRemoveNoChildren() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1681,7 +1681,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testRemoveAndDeleteNoChildren() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1713,7 +1713,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testChildren() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1. Root')); @@ -1741,7 +1741,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testNoAmbiguousColumn() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); @@ -1773,7 +1773,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testGenerateTreeListWithSelfJoin() { extract($this->settings); - $this->Tree =& new $modelClass(); + $this->Tree = new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php index 691a86c1..447db40d 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php @@ -371,7 +371,7 @@ class DboMysqlTest extends CakeTestCase { function testIndexOnMySQL4Output() { $name = $this->db->fullTableName('simple'); - $mockDbo =& new QueryMockDboMysql($this); + $mockDbo = new QueryMockDboMysql($this); $columnData = array( array('0' => array( 'Table' => 'with_compound_keys', @@ -512,7 +512,7 @@ class DboMysqlTest extends CakeTestCase { App::import('Core', 'Schema'); $this->db->cacheSources = $this->db->testing = false; - $schema1 =& new CakeSchema(array( + $schema1 = new CakeSchema(array( 'name' => 'AlterTest1', 'connection' => 'test_suite', 'altertest' => array( @@ -523,7 +523,7 @@ class DboMysqlTest extends CakeTestCase { ))); $this->db->query($this->db->createSchema($schema1)); - $schema2 =& new CakeSchema(array( + $schema2 = new CakeSchema(array( 'name' => 'AlterTest2', 'connection' => 'test_suite', 'altertest' => array( @@ -543,7 +543,7 @@ class DboMysqlTest extends CakeTestCase { $this->assertEqual($schema2->tables['altertest']['indexes'], $indexes); // Change three indexes, delete one and add another one - $schema3 =& new CakeSchema(array( + $schema3 = new CakeSchema(array( 'name' => 'AlterTest3', 'connection' => 'test_suite', 'altertest' => array( diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php index 6b835890..fabb5039 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php @@ -103,7 +103,7 @@ class DboOracleTest extends CakeTestCase { */ function testName() { $Db = $this->db; - #$Db =& new DboOracle($config = null, $autoConnect = false); + #$Db = new DboOracle($config = null, $autoConnect = false); $r = $Db->name($Db->name($Db->name('foo.last_update_date'))); $e = 'foo.last_update_date'; diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php index aec59ba4..aa2ddcac 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php @@ -415,7 +415,7 @@ class DboPostgresTest extends CakeTestCase { ªºnh˚ºO^∏…®[Ó“‚ÅfıÌ≥∫F!Eœ(π∑T6`¬tΩÆ0ì»rTÎ`»Ñ« ]≈åp˝)=¿Ô0∆öVÂmˇˆ„ø~¯ÁÔ∏b*fc»‡Îı„Ú}∆tœs∂Y∫ÜaÆ˙X∏~<ÿ·Ù vé1‹p¿TD∆ÔîÄ“úhˆ*Ú€îe)K –p¨ÚJ3Ÿ∞ã>ÊuNê°“√Ü ‹Ê9iÙ0˙AAEÍ ˙`∂£\'ûce•åƒX›ŸÁ´1SK{qdá"tÏ[wQ#SµBe∞∑µó…ÌV`B"Ñ≥„!è_Óφ-º*ºú¿Ë0ˆeê∂´ë+HFj…‡zvHÓN|ÔL÷ûñ3õÜ$z%sá…pÎóV38âs Çoµ•ß3†<9B·¨û~¢3)ÂxóÿÁCÕòÆ ∫Í=»ÿSπS;∆~±êÆTEp∑óÈ÷ÀuìDHÈ $ÉõæÜjû§"≤ÃONM®RËíRr{õS ∏Ê™op±W;ÂUÔP∫kÔˇflTæ∑óflË” ÆC©Ô[≥◊HÁ˚¨hê"ÆbF?ú%h˙ˇ4xèÕ(ó2ÙáíM])Ñd|=fë-cI0ñL¢kÖêk‰Rƒ«ıÄWñ8mO3∏&√æËX¯Hó—ì]yF2»–˜ádàà‡‹Çο„≥7mªHAS∑¶.;Œx(1}_kd©.fidç48M\'àáªCp^Krí<ɉXÓıïl!Ì$N<ı∞B»G]…∂Ó¯>˛ÔbõÒπÀ•:ôO@È$pÖu‹Ê´-QqV ?V≥JÆÍqÛX8(lπï@zgÖ}Fe<ˇ‡Sñ“ÿ˜ê?6‡L∫Oß~µ–?ËeäÚ®YîÕ =Ü=¢DÁu*GvBk;)L¬N«î:flö∂≠ÇΩq„Ñm하Ë∂‚"û≥§:±≤i^ΩÑ!)Wıyŧôá„RÄ÷Òôc’≠—s™rı‚Pdêãh˘ßHVç5fifiÈF€çÌÛuçÖ/M=gëµ±ÿGû1coÔuñæ‘z®.õ∑7ÉÏÜÆ,°’H†ÍÉÌ∂7e º® íˆ⁄◊øNWK”ÂYµ‚ñé;µ¶gV-fl>µtË¥áßN2 ¯¶BaP-)eW.àôt^∏1›C∑Ö?L„&”5’4jvã–ªZ ÷+4% ´0l…»ú^°´© ûiπ∑é®óܱÒÿ‰ïˆÌ–dˆ◊Æ19rQ=Í|ı•rMæ¬;ò‰Y‰é9.” ‹˝V«ã¯∏,+ë®j*¡·/'; - $model =& new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite')); + $model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite')); $model->save(compact('data')); $result = $model->find('first'); @@ -528,7 +528,7 @@ class DboPostgresTest extends CakeTestCase { * @return void */ function testAlterSchema() { - $Old =& new CakeSchema(array( + $Old = new CakeSchema(array( 'connection' => 'test_suite', 'name' => 'AlterPosts', 'alter_posts' => array( @@ -543,7 +543,7 @@ class DboPostgresTest extends CakeTestCase { )); $this->db->query($this->db->createSchema($Old)); - $New =& new CakeSchema(array( + $New = new CakeSchema(array( 'connection' => 'test_suite', 'name' => 'AlterPosts', 'alter_posts' => array( @@ -575,7 +575,7 @@ class DboPostgresTest extends CakeTestCase { function testAlterIndexes() { $this->db->cacheSources = false; - $schema1 =& new CakeSchema(array( + $schema1 = new CakeSchema(array( 'name' => 'AlterTest1', 'connection' => 'test_suite', 'altertest' => array( @@ -587,7 +587,7 @@ class DboPostgresTest extends CakeTestCase { )); $this->db->query($this->db->createSchema($schema1)); - $schema2 =& new CakeSchema(array( + $schema2 = new CakeSchema(array( 'name' => 'AlterTest2', 'connection' => 'test_suite', 'altertest' => array( @@ -609,7 +609,7 @@ class DboPostgresTest extends CakeTestCase { $this->assertEqual($schema2->tables['altertest']['indexes'], $indexes); // Change three indexes, delete one and add another one - $schema3 =& new CakeSchema(array( + $schema3 = new CakeSchema(array( 'name' => 'AlterTest3', 'connection' => 'test_suite', 'altertest' => array( diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php index 2f1ea4ad..1732ce19 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php @@ -210,7 +210,7 @@ class DboSqliteTest extends CakeTestCase { * @return void **/ function testDescribe() { - $Model =& new Model(array('name' => 'User', 'ds' => 'test_suite', 'table' => 'users')); + $Model = new Model(array('name' => 'User', 'ds' => 'test_suite', 'table' => 'users')); $result = $this->db->describe($Model); $expected = array( 'id' => array( @@ -256,7 +256,7 @@ class DboSqliteTest extends CakeTestCase { function testDescribeWithUuidPrimaryKey() { $tableName = 'uuid_tests'; $this->db->query("CREATE TABLE {$tableName} (id VARCHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)"); - $Model =& new Model(array('name' => 'UuidTest', 'ds' => 'test_suite', 'table' => 'uuid_tests')); + $Model = new Model(array('name' => 'UuidTest', 'ds' => 'test_suite', 'table' => 'uuid_tests')); $result = $this->db->describe($Model); $expected = array( 'type' => 'string', diff --git a/cake/tests/cases/libs/model/datasources/dbo_source.test.php b/cake/tests/cases/libs/model/datasources/dbo_source.test.php index 4da90c9b..28a9d1d7 100755 --- a/cake/tests/cases/libs/model/datasources/dbo_source.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo_source.test.php @@ -1209,13 +1209,13 @@ class DboSourceTest extends CakeTestCase { }"); } - $this->testDb =& new DboTest($this->__config); + $this->testDb = new DboTest($this->__config); $this->testDb->cacheSources = false; $this->testDb->startQuote = '`'; $this->testDb->endQuote = '`'; Configure::write('debug', 1); $this->debug = Configure::read('debug'); - $this->Model =& new TestModel(); + $this->Model = new TestModel(); } /** * endTest method @@ -1239,7 +1239,7 @@ class DboSourceTest extends CakeTestCase { $test =& ConnectionManager::create('quoteTest', $config); $test->simulated = array(); - $this->Model =& new Article2(array('alias' => 'Article', 'ds' => 'quoteTest')); + $this->Model = new Article2(array('alias' => 'Article', 'ds' => 'quoteTest')); $this->Model->setDataSource('quoteTest'); $this->assertEqual($this->Model->escapeField(), '`Article`.`id`'); @@ -1277,11 +1277,11 @@ class DboSourceTest extends CakeTestCase { */ function testGenerateAssociationQuerySelfJoin() { $this->startTime = microtime(true); - $this->Model =& new Article2(); + $this->Model = new Article2(); $this->_buildRelatedModels($this->Model); $this->_buildRelatedModels($this->Model->Category2); - $this->Model->Category2->ChildCat =& new Category2(); - $this->Model->Category2->ParentCat =& new Category2(); + $this->Model->Category2->ChildCat = new Category2(); + $this->Model->Category2->ParentCat = new Category2(); $queryData = array(); @@ -1305,7 +1305,7 @@ class DboSourceTest extends CakeTestCase { $query = $this->testDb->generateAssociationQuery($this->Model->Category2, $null, null, null, null, $queryData, false, $null); $this->assertPattern('/^SELECT\s+(.+)FROM(.+)`Category2`\.`group_id`\s+=\s+`Group`\.`id`\)\s+LEFT JOIN(.+)WHERE\s+1 = 1\s*$/', $query); - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1366,10 +1366,10 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateInnerJoinAssociationQuery() { - $this->Model =& new TestModel9(); + $this->Model = new TestModel9(); $test =& ConnectionManager::create('test2', $this->__config); $this->Model->setDataSource('test2'); - $this->Model->TestModel8 =& new TestModel8(); + $this->Model->TestModel8 = new TestModel8(); $this->Model->TestModel8->setDataSource('test2'); $this->testDb->read($this->Model, array('recursive' => 1)); @@ -1389,7 +1389,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding() { - $this->Model =& new TestModel8(); + $this->Model = new TestModel8(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1416,7 +1416,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding() { - $this->Model =& new TestModel9(); + $this->Model = new TestModel9(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1442,7 +1442,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQuerySelfJoinWithConditions() { - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1462,7 +1462,7 @@ class DboSourceTest extends CakeTestCase { $this->assertPattern('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result); $this->assertPattern('/\s+WHERE\s+(?:\()?`TestModel4Parent`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result); - $this->Featured2 =& new Featured2(); + $this->Featured2 = new Featured2(); $this->Featured2->schema(); $this->Featured2->bindModel(array( @@ -1503,7 +1503,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasOne() { - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1535,7 +1535,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasOneWithConditions() { - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1564,7 +1564,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryBelongsTo() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1595,7 +1595,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryBelongsToWithConditions() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1626,7 +1626,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasMany() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1655,7 +1655,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithLimit() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1694,7 +1694,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithConditions() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1722,7 +1722,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithOffsetAndLimit() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1759,7 +1759,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithPageAndLimit() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1795,7 +1795,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithFields() { - $this->Model =& new TestModel5(); + $this->Model = new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1920,7 +1920,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToMany() { - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1950,7 +1950,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToManyWithConditions() { - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1978,7 +1978,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit() { - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -2014,7 +2014,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit() { - $this->Model =& new TestModel4(); + $this->Model = new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -2058,7 +2058,7 @@ class DboSourceTest extends CakeTestCase { } elseif (isset($assocData['className'])) { $className = $assocData['className']; } - $model->$className =& new $className(); + $model->$className = new $className(); $model->$className->schema(); } } @@ -2631,7 +2631,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testConditionsWithModel() { - $this->Model =& new Article2(); + $this->Model = new Article2(); $result = $this->testDb->conditions(array('Article2.viewed >=' => 0), true, true, $this->Model); $expected = " WHERE `Article2`.`viewed` >= 0"; @@ -3128,7 +3128,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testSchema() { - $Schema =& new CakeSchema(); + $Schema = new CakeSchema(); $Schema->tables = array('table' => array(), 'anotherTable' => array()); $this->expectError(); diff --git a/cake/tests/cases/libs/model/db_acl.test.php b/cake/tests/cases/libs/model/db_acl.test.php index 82d4d15a..57ba2b00 100755 --- a/cake/tests/cases/libs/model/db_acl.test.php +++ b/cake/tests/cases/libs/model/db_acl.test.php @@ -224,10 +224,10 @@ class DbAclTest extends DbAcl { * @return void */ function __construct() { - $this->Aro =& new DbAroTest(); - $this->Aro->Permission =& new DbPermissionTest(); - $this->Aco =& new DbAcoTest(); - $this->Aro->Permission =& new DbPermissionTest(); + $this->Aro = new DbAroTest(); + $this->Aro->Permission = new DbPermissionTest(); + $this->Aco = new DbAcoTest(); + $this->Aro->Permission = new DbPermissionTest(); } } /** diff --git a/cake/tests/cases/libs/model/model_delete.test.php b/cake/tests/cases/libs/model/model_delete.test.php index 6d30d2bd..cdaa97b4 100755 --- a/cake/tests/cases/libs/model/model_delete.test.php +++ b/cake/tests/cases/libs/model/model_delete.test.php @@ -42,7 +42,7 @@ class ModelDeleteTest extends BaseModelTest { function testDeleteHabtmReferenceWithConditions() { $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio'); - $Portfolio =& new Portfolio(); + $Portfolio = new Portfolio(); $Portfolio->hasAndBelongsToMany['Item']['conditions'] = array('ItemsPortfolio.item_id >' => 1); $result = $Portfolio->find('first', array( @@ -131,7 +131,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDeleteArticleBLinks() { $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); - $TestModel =& new ArticleB(); + $TestModel = new ArticleB(); $result = $TestModel->ArticlesTag->find('all'); $expected = array( @@ -160,8 +160,8 @@ class ModelDeleteTest extends BaseModelTest { function testDeleteDependentWithConditions() { $this->loadFixtures('Cd','Book','OverallFavorite'); - $Cd =& new Cd(); - $OverallFavorite =& new OverallFavorite(); + $Cd = new Cd(); + $OverallFavorite = new OverallFavorite(); $Cd->del(1); @@ -187,7 +187,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDel() { $this->loadFixtures('Article'); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->del(2); $this->assertTrue($result); @@ -232,7 +232,7 @@ class ModelDeleteTest extends BaseModelTest { // make sure deleting a non-existent record doesn't break save() // ticket #6293 $this->loadFixtures('Uuid'); - $Uuid =& new Uuid(); + $Uuid = new Uuid(); $data = array( 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3', '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8', @@ -266,7 +266,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDeleteAll() { $this->loadFixtures('Article'); - $TestModel =& new Article(); + $TestModel = new Article(); $data = array('Article' => array( 'user_id' => 2, @@ -407,7 +407,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testRecursiveDel() { $this->loadFixtures('Article', 'Comment', 'Attachment'); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->del(2); $this->assertTrue($result); @@ -442,7 +442,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDependentExclusiveDelete() { $this->loadFixtures('Article', 'Comment'); - $TestModel =& new Article10(); + $TestModel = new Article10(); $result = $TestModel->find('all'); $this->assertEqual(count($result[0]['Comment']), 4); @@ -460,7 +460,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDeleteLinks() { $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->ArticlesTag->find('all'); $expected = array( @@ -508,7 +508,7 @@ class ModelDeleteTest extends BaseModelTest { function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() { $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); - $ThePaper =& new ThePaper(); + $ThePaper = new ThePaper(); $ThePaper->id = 1; $ThePaper->save(array('Monkey' => array(2, 3))); @@ -528,7 +528,7 @@ class ModelDeleteTest extends BaseModelTest { )); $this->assertEqual($result['Monkey'], $expected); - $ThePaper =& new ThePaper(); + $ThePaper = new ThePaper(); $ThePaper->id = 2; $ThePaper->save(array('Monkey' => array(2, 3))); diff --git a/cake/tests/cases/libs/model/model_integration.test.php b/cake/tests/cases/libs/model/model_integration.test.php index e213187b..475101f5 100755 --- a/cake/tests/cases/libs/model/model_integration.test.php +++ b/cake/tests/cases/libs/model/model_integration.test.php @@ -42,7 +42,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testPkInHabtmLinkModelArticleB() { $this->loadFixtures('Article', 'Tag'); - $TestModel2 =& new ArticleB(); + $TestModel2 = new ArticleB(); $this->assertEqual($TestModel2->ArticlesTag->primaryKey, 'article_id'); } /** @@ -73,22 +73,22 @@ class ModelIntegrationTest extends BaseModelTest { function testPkInHabtmLinkModel() { //Test Nonconformant Models $this->loadFixtures('Content', 'ContentAccount', 'Account'); - $TestModel =& new Content(); + $TestModel = new Content(); $this->assertEqual($TestModel->ContentAccount->primaryKey, 'iContentAccountsId'); //test conformant models with no PK in the join table $this->loadFixtures('Article', 'Tag'); - $TestModel2 =& new Article(); + $TestModel2 = new Article(); $this->assertEqual($TestModel2->ArticlesTag->primaryKey, 'article_id'); //test conformant models with PK in join table $this->loadFixtures('Item', 'Portfolio', 'ItemsPortfolio'); - $TestModel3 =& new Portfolio(); + $TestModel3 = new Portfolio(); $this->assertEqual($TestModel3->ItemsPortfolio->primaryKey, 'id'); //test conformant models with PK in join table - join table contains extra field $this->loadFixtures('JoinA', 'JoinB', 'JoinAB'); - $TestModel4 =& new JoinA(); + $TestModel4 = new JoinA(); $this->assertEqual($TestModel4->JoinAsJoinB->primaryKey, 'id'); } @@ -100,7 +100,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testDynamicBehaviorAttachment() { $this->loadFixtures('Apple'); - $TestModel =& new Apple(); + $TestModel = new Apple(); $this->assertEqual($TestModel->Behaviors->attached(), array()); $TestModel->Behaviors->attach('Tree', array('left' => 'left_field', 'right' => 'right_field')); @@ -148,7 +148,7 @@ class ModelIntegrationTest extends BaseModelTest { } $this->loadFixtures('Article', 'Tag', 'ArticlesTag', 'User', 'Comment'); - $TestModel =& new Article(); + $TestModel = new Article(); $expected = array( array( @@ -535,7 +535,7 @@ class ModelIntegrationTest extends BaseModelTest { **/ function testDeconstructFieldsTime() { $this->loadFixtures('Apple'); - $TestModel =& new Apple(); + $TestModel = new Apple(); $data = array(); $data['Apple']['mytime']['hour'] = ''; @@ -621,7 +621,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testDeconstructFieldsDateTime() { $this->loadFixtures('Apple'); - $TestModel =& new Apple(); + $TestModel = new Apple(); //test null/empty values first $data['Apple']['created']['year'] = ''; @@ -849,7 +849,7 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testInvalidAssociation() { - $TestModel =& new ValidationTest1(); + $TestModel = new ValidationTest1(); $this->assertNull($TestModel->getAssociated('Foo')); } /** @@ -875,7 +875,7 @@ class ModelIntegrationTest extends BaseModelTest { **/ function testResetOfExistsOnCreate() { $this->loadFixtures('Article'); - $Article =& new Article(); + $Article = new Article(); $Article->id = 1; $Article->saveField('title', 'Reset me'); $Article->delete(); @@ -897,7 +897,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testPluginAssociations() { $this->loadFixtures('TestPluginArticle', 'User', 'TestPluginComment'); - $TestModel =& new TestPluginArticle(); + $TestModel = new TestPluginArticle(); $result = $TestModel->find('all'); $expected = array( @@ -1063,7 +1063,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testAutoConstructAssociations() { $this->loadFixtures('User', 'ArticleFeatured'); - $TestModel =& new AssociationTest1(); + $TestModel = new AssociationTest1(); $result = $TestModel->hasAndBelongsToMany; $expected = array('AssociationTest2' => array( @@ -1079,8 +1079,8 @@ class ModelIntegrationTest extends BaseModelTest { $this->assertEqual($result, $expected); // Tests related to ticket https://trac.cakephp.org/ticket/5594 - $TestModel =& new ArticleFeatured(); - $TestFakeModel =& new ArticleFeatured(array('table' => false)); + $TestModel = new ArticleFeatured(); + $TestFakeModel = new ArticleFeatured(array('table' => false)); $expected = array( 'User' => array( @@ -1195,7 +1195,7 @@ class ModelIntegrationTest extends BaseModelTest { $this->assertEqual('test_suite', $TestModel->useDbConfig); //deprecated but test it anyway - $NewVoid =& new TheVoid(null, false, 'other'); + $NewVoid = new TheVoid(null, false, 'other'); $this->assertEqual('other', $NewVoid->useDbConfig); } /** @@ -1205,13 +1205,13 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testColumnTypeFetching() { - $model =& new Test(); + $model = new Test(); $this->assertEqual($model->getColumnType('id'), 'integer'); $this->assertEqual($model->getColumnType('notes'), 'text'); $this->assertEqual($model->getColumnType('updated'), 'datetime'); $this->assertEqual($model->getColumnType('unknown'), null); - $model =& new Article(); + $model = new Article(); $this->assertEqual($model->getColumnType('User.created'), 'datetime'); $this->assertEqual($model->getColumnType('Tag.id'), 'integer'); $this->assertEqual($model->getColumnType('Article.id'), 'integer'); @@ -1223,7 +1223,7 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testHabtmUniqueKey() { - $model =& new Item(); + $model = new Item(); $this->assertFalse($model->hasAndBelongsToMany['Portfolio']['unique']); } /** @@ -1233,17 +1233,17 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testIdentity() { - $TestModel =& new Test(); + $TestModel = new Test(); $result = $TestModel->alias; $expected = 'Test'; $this->assertEqual($result, $expected); - $TestModel =& new TestAlias(); + $TestModel = new TestAlias(); $result = $TestModel->alias; $expected = 'TestAlias'; $this->assertEqual($result, $expected); - $TestModel =& new Test(array('alias' => 'AnotherTest')); + $TestModel = new Test(array('alias' => 'AnotherTest')); $result = $TestModel->alias; $expected = 'AnotherTest'; $this->assertEqual($result, $expected); @@ -1256,7 +1256,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testWithAssociation() { $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - $TestModel =& new Something(); + $TestModel = new Something(); $result = $TestModel->SomethingElse->find('all'); $expected = array( @@ -1508,7 +1508,7 @@ class ModelIntegrationTest extends BaseModelTest { function testFindSelfAssociations() { $this->loadFixtures('Person'); - $TestModel =& new Person(); + $TestModel = new Person(); $TestModel->recursive = 2; $result = $TestModel->read(null, 1); $expected = array( @@ -1616,7 +1616,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testDynamicAssociations() { $this->loadFixtures('Article', 'Comment'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->hasOne = array(); $TestModel->hasMany['Comment'] = array_merge($TestModel->hasMany['Comment'], array( @@ -1723,11 +1723,11 @@ class ModelIntegrationTest extends BaseModelTest { */ function testCreation() { $this->loadFixtures('Article'); - $TestModel =& new Test(); + $TestModel = new Test(); $result = $TestModel->create(); $expected = array('Test' => array('notes' => 'write some notes here')); $this->assertEqual($result, $expected); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->schema(); if (isset($this->db->columns['primary_key']['length'])) { @@ -1777,12 +1777,12 @@ class ModelIntegrationTest extends BaseModelTest { $this->assertEqual($result, $expected); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->create(); $expected = array('Article' => array('published' => 'N')); $this->assertEqual($result, $expected); - $FeaturedModel =& new Featured(); + $FeaturedModel = new Featured(); $data = array( 'article_featured_id' => 1, 'category_id' => 1, diff --git a/cake/tests/cases/libs/model/model_read.test.php b/cake/tests/cases/libs/model/model_read.test.php index a2fd76f8..ae163386 100755 --- a/cake/tests/cases/libs/model/model_read.test.php +++ b/cake/tests/cases/libs/model/model_read.test.php @@ -89,8 +89,8 @@ class ModelReadTest extends BaseModelTest { } $this->loadFixtures('Project', 'Product', 'Thread', 'Message', 'Bid'); - $Thread =& new Thread(); - $Product =& new Product(); + $Thread = new Thread(); + $Product = new Product(); $result = $Thread->find('all', array( 'group' => 'Thread.project_id', @@ -245,7 +245,7 @@ class ModelReadTest extends BaseModelTest { */ function testOldQuery() { $this->loadFixtures('Article'); - $Article =& new Article(); + $Article = new Article(); $query = 'SELECT title FROM '; $query .= $this->db->fullTableName('articles'); @@ -280,7 +280,7 @@ class ModelReadTest extends BaseModelTest { */ function testPreparedQuery() { $this->loadFixtures('Article'); - $Article =& new Article(); + $Article = new Article(); $this->db->_queryCache = array(); $finalQuery = 'SELECT title, published FROM '; @@ -361,7 +361,7 @@ class ModelReadTest extends BaseModelTest { */ function testParameterMismatch() { $this->loadFixtures('Article'); - $Article =& new Article(); + $Article = new Article(); $query = 'SELECT * FROM ' . $this->db->fullTableName('articles'); $query .= ' WHERE ' . $this->db->fullTableName('articles'); @@ -389,7 +389,7 @@ class ModelReadTest extends BaseModelTest { } $this->loadFixtures('Article'); - $Article =& new Article(); + $Article = new Article(); $query = 'SELECT * FROM ? WHERE ? = ? AND ? = ?'; $param = array( @@ -411,7 +411,7 @@ class ModelReadTest extends BaseModelTest { */ function testRecursiveUnbind() { $this->loadFixtures('Apple', 'Sample'); - $TestModel =& new Apple(); + $TestModel = new Apple(); $TestModel->recursive = 2; $result = $TestModel->find('all'); @@ -3032,7 +3032,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllThreaded() { $this->loadFixtures('Category'); - $TestModel =& new Category(); + $TestModel = new Category(); $result = $TestModel->find('threaded'); $expected = array( @@ -3508,7 +3508,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindNeighbors() { $this->loadFixtures('User', 'Article'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->id = 1; $result = $TestModel->find('neighbors', array('fields' => array('id'))); @@ -3664,7 +3664,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindNeighboursLegacy() { $this->loadFixtures('User', 'Article'); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->findNeighbours(null, 'Article.id', '2'); $expected = array( @@ -3714,7 +3714,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindCombinedRelations() { $this->loadFixtures('Apple', 'Sample'); - $TestModel =& new Apple(); + $TestModel = new Apple(); $result = $TestModel->find('all'); @@ -3990,13 +3990,13 @@ class ModelReadTest extends BaseModelTest { */ function testSaveEmpty() { $this->loadFixtures('Thread'); - $TestModel =& new Thread(); + $TestModel = new Thread(); $data = array(); $expected = $TestModel->save($data); $this->assertFalse($expected); } // function testBasicValidation() { - // $TestModel =& new ValidationTest1(); + // $TestModel = new ValidationTest1(); // $TestModel->testing = true; // $TestModel->set(array('title' => '', 'published' => 1)); // $this->assertEqual($TestModel->invalidFields(), array('title' => 'This field cannot be left blank')); @@ -4020,7 +4020,7 @@ class ModelReadTest extends BaseModelTest { function testFindAllWithConditionInChildQuery() { $this->loadFixtures('Basket', 'FilmFile'); - $TestModel =& new Basket(); + $TestModel = new Basket(); $recursive = 3; $result = $TestModel->find('all', compact('conditions', 'recursive')); @@ -4063,7 +4063,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllWithConditionsHavingMixedDataTypes() { $this->loadFixtures('Article'); - $TestModel =& new Article(); + $TestModel = new Article(); $expected = array( array( 'Article' => array( @@ -4143,7 +4143,7 @@ class ModelReadTest extends BaseModelTest { */ function testBindUnbind() { $this->loadFixtures('User', 'Comment', 'FeatureSet'); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->hasMany; $expected = array(); @@ -4547,7 +4547,7 @@ class ModelReadTest extends BaseModelTest { $this->assertEqual($result, $expected); - $TestModel2 =& new DeviceType(); + $TestModel2 = new DeviceType(); $expected = array( 'className' => 'FeatureSet', @@ -4602,7 +4602,7 @@ class ModelReadTest extends BaseModelTest { */ function testBindMultipleTimes() { $this->loadFixtures('User', 'Comment', 'Article'); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->hasMany; $expected = array(); @@ -4790,7 +4790,7 @@ class ModelReadTest extends BaseModelTest { */ function testAssociationAfterFind() { $this->loadFixtures('Post', 'Author', 'Comment'); - $TestModel =& new Post(); + $TestModel = new Post(); $result = $TestModel->find('all'); $expected = array( array( @@ -4850,7 +4850,7 @@ class ModelReadTest extends BaseModelTest { $this->assertEqual($result, $expected); unset($TestModel); - $Author =& new Author(); + $Author = new Author(); $Author->Post->bindModel(array( 'hasMany' => array( 'Comment' => array( @@ -4917,7 +4917,7 @@ class ModelReadTest extends BaseModelTest { 'DocumentDirectory' ); - $DeviceType =& new DeviceType(); + $DeviceType = new DeviceType(); $DeviceType->recursive = 2; $result = $DeviceType->read(null, 1); @@ -5006,7 +5006,7 @@ class ModelReadTest extends BaseModelTest { */ function testHabtmRecursiveBelongsTo() { $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio', 'Syfile', 'Image'); - $Portfolio =& new Portfolio(); + $Portfolio = new Portfolio(); $result = $Portfolio->find(array('id' => 2), null, null, 3); $expected = array( @@ -5064,7 +5064,7 @@ class ModelReadTest extends BaseModelTest { */ function testHabtmFinderQuery() { $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); - $Article =& new Article(); + $Article = new Article(); $sql = $this->db->buildStatement( array( @@ -5112,7 +5112,7 @@ class ModelReadTest extends BaseModelTest { */ function testHabtmLimitOptimization() { $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->hasAndBelongsToMany['Tag']['limit'] = 2; $result = $TestModel->read(null, 2); @@ -5182,7 +5182,7 @@ class ModelReadTest extends BaseModelTest { */ function testHasManyLimitOptimization() { $this->loadFixtures('Project', 'Thread', 'Message', 'Bid'); - $Project =& new Project(); + $Project = new Project(); $Project->recursive = 3; $result = $Project->find('all'); @@ -5296,7 +5296,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllRecursiveSelfJoin() { $this->loadFixtures('Home', 'AnotherArticle', 'Advertisement'); - $TestModel =& new Home(); + $TestModel = new Home(); $TestModel->recursive = 2; $result = $TestModel->find('all'); @@ -5412,7 +5412,7 @@ class ModelReadTest extends BaseModelTest { 'MyProduct' ); - $MyUser =& new MyUser(); + $MyUser = new MyUser(); $MyUser->recursive = 2; $result = $MyUser->find('all'); @@ -5473,7 +5473,7 @@ class ModelReadTest extends BaseModelTest { */ function testReadFakeThread() { $this->loadFixtures('CategoryThread'); - $TestModel =& new CategoryThread(); + $TestModel = new CategoryThread(); $fullDebug = $this->db->fullDebug; $this->db->fullDebug = true; @@ -5537,7 +5537,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindFakeThread() { $this->loadFixtures('CategoryThread'); - $TestModel =& new CategoryThread(); + $TestModel = new CategoryThread(); $fullDebug = $this->db->fullDebug; $this->db->fullDebug = true; @@ -5601,7 +5601,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllFakeThread() { $this->loadFixtures('CategoryThread'); - $TestModel =& new CategoryThread(); + $TestModel = new CategoryThread(); $fullDebug = $this->db->fullDebug; $this->db->fullDebug = true; @@ -5821,7 +5821,7 @@ class ModelReadTest extends BaseModelTest { */ function testConditionalNumerics() { $this->loadFixtures('NumericArticle'); - $NumericArticle =& new NumericArticle(); + $NumericArticle = new NumericArticle(); $data = array('title' => '12345abcde'); $result = $NumericArticle->find($data); $this->assertTrue(!empty($result)); @@ -5839,7 +5839,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAll() { $this->loadFixtures('User'); - $TestModel =& new User(); + $TestModel = new User(); $TestModel->cacheQueries = false; $result = $TestModel->find('all'); @@ -6069,7 +6069,7 @@ class ModelReadTest extends BaseModelTest { function testGenerateFindList() { $this->loadFixtures('Article', 'Apple', 'Post', 'Author', 'User'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->displayField = 'title'; $result = $TestModel->find('list', array( @@ -6204,7 +6204,7 @@ class ModelReadTest extends BaseModelTest { )); $this->assertEqual($result, $expected); - $TestModel =& new Apple(); + $TestModel = new Apple(); $expected = array( 1 => 'Red Apple 1', 2 => 'Bright Red Apple', @@ -6218,7 +6218,7 @@ class ModelReadTest extends BaseModelTest { $this->assertEqual($TestModel->find('list'), $expected); $this->assertEqual($TestModel->Parent->find('list'), $expected); - $TestModel =& new Post(); + $TestModel = new Post(); $result = $TestModel->find('list', array( 'fields' => 'Post.title' )); @@ -6299,7 +6299,7 @@ class ModelReadTest extends BaseModelTest { )); $this->assertEqual($result, $expected); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->find('list', array( 'fields' => array('User.user', 'User.password') )); @@ -6311,7 +6311,7 @@ class ModelReadTest extends BaseModelTest { ); $this->assertEqual($result, $expected); - $TestModel =& new ModifiedAuthor(); + $TestModel = new ModifiedAuthor(); $result = $TestModel->find('list', array( 'fields' => array('Author.id', 'Author.user') )); @@ -6331,7 +6331,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindField() { $this->loadFixtures('User'); - $TestModel =& new User(); + $TestModel = new User(); $TestModel->id = 1; $result = $TestModel->field('user'); @@ -6360,7 +6360,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindUnique() { $this->loadFixtures('User'); - $TestModel =& new User(); + $TestModel = new User(); $this->assertFalse($TestModel->isUnique(array( 'user' => 'nate' @@ -6383,7 +6383,7 @@ class ModelReadTest extends BaseModelTest { function testFindCount() { $this->loadFixtures('User', 'Project'); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->find('count'); $this->assertEqual($result, 4); @@ -6412,7 +6412,7 @@ class ModelReadTest extends BaseModelTest { return; } $this->loadFixtures('Project'); - $TestModel =& new Project(); + $TestModel = new Project(); $TestModel->create(array('name' => 'project')) && $TestModel->save(); $TestModel->create(array('name' => 'project')) && $TestModel->save(); $TestModel->create(array('name' => 'project')) && $TestModel->save(); @@ -6432,7 +6432,7 @@ class ModelReadTest extends BaseModelTest { } $this->loadFixtures('Project'); $db = ConnectionManager::getDataSource('test_suite'); - $TestModel =& new Project(); + $TestModel = new Project(); $result = $TestModel->find('count', array('conditions' => array( $db->expression('Project.name = \'Project 3\'') @@ -6452,7 +6452,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindMagic() { $this->loadFixtures('User'); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->findByUser('mariano'); $expected = array( @@ -6483,7 +6483,7 @@ class ModelReadTest extends BaseModelTest { */ function testRead() { $this->loadFixtures('User', 'Article'); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->read(); $this->assertFalse($result); @@ -6571,7 +6571,7 @@ class ModelReadTest extends BaseModelTest { 'Featured', 'ArticleFeatured' ); - $TestModel =& new User(); + $TestModel = new User(); $result = $TestModel->bindModel(array('hasMany' => array('Article')), false); $this->assertTrue($result); @@ -6683,7 +6683,7 @@ class ModelReadTest extends BaseModelTest { 'Featured', 'Category' ); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->find('all', array('conditions' => array('Article.user_id' => 1))); $expected = array( @@ -6989,7 +6989,7 @@ class ModelReadTest extends BaseModelTest { */ function testRecursiveFindAllWithLimit() { $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag', 'Comment', 'Attachment'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->hasMany['Comment']['limit'] = 2; diff --git a/cake/tests/cases/libs/model/model_validation.test.php b/cake/tests/cases/libs/model/model_validation.test.php index b4dcf22f..0911c933 100755 --- a/cake/tests/cases/libs/model/model_validation.test.php +++ b/cake/tests/cases/libs/model/model_validation.test.php @@ -40,7 +40,7 @@ class ModelValidationTest extends BaseModelTest { * @return void */ function testValidationParams() { - $TestModel =& new ValidationTest1(); + $TestModel = new ValidationTest1(); $TestModel->validate['title'] = array( 'rule' => 'customValidatorWithParams', 'required' => true @@ -81,7 +81,7 @@ class ModelValidationTest extends BaseModelTest { * @return void */ function testInvalidFieldsWithFieldListParams() { - $TestModel =& new ValidationTest1(); + $TestModel = new ValidationTest1(); $TestModel->validate = $validate = array( 'title' => array( 'rule' => 'customValidator', diff --git a/cake/tests/cases/libs/model/model_write.test.php b/cake/tests/cases/libs/model/model_write.test.php index 3d023ce1..c41b981d 100755 --- a/cake/tests/cases/libs/model/model_write.test.php +++ b/cake/tests/cases/libs/model/model_write.test.php @@ -95,7 +95,7 @@ class ModelWriteTest extends BaseModelTest { function testSaveDateAsFirstEntry() { $this->loadFixtures('Article'); - $Article =& new Article(); + $Article = new Article(); $data = array( 'Article' => array( @@ -124,7 +124,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUnderscoreFieldSave() { $this->loadFixtures('UnderscoreField'); - $UnderscoreField =& new UnderscoreField(); + $UnderscoreField = new UnderscoreField(); $currentCount = $UnderscoreField->find('count'); $this->assertEqual($currentCount, 3); @@ -152,7 +152,7 @@ class ModelWriteTest extends BaseModelTest { $this->skipIf($this->db->config['driver'] == 'sqlite'); $this->loadFixtures('Uuid'); - $TestModel =& new Uuid(); + $TestModel = new Uuid(); $TestModel->save(array('title' => 'Test record')); $result = $TestModel->findByTitle('Test record'); @@ -174,7 +174,7 @@ class ModelWriteTest extends BaseModelTest { '%s SQLite uses loose typing, this operation is unsupported' ); $this->loadFixtures('DataTest'); - $TestModel =& new DataTest(); + $TestModel = new DataTest(); $TestModel->create(array()); $TestModel->save(); @@ -190,7 +190,7 @@ class ModelWriteTest extends BaseModelTest { */ function testNonNumericHabtmJoinKey() { $this->loadFixtures('Post', 'Tag', 'PostsTag'); - $Post =& new Post(); + $Post = new Post(); $Post->bind('Tag', array('type' => 'hasAndBelongsToMany')); $Post->Tag->primaryKey = 'tag'; @@ -287,7 +287,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testAllowSimulatedFields() { - $TestModel =& new ValidationTest1(); + $TestModel = new ValidationTest1(); $TestModel->create(array( 'title' => 'foo', @@ -316,7 +316,7 @@ class ModelWriteTest extends BaseModelTest { Configure::write('Cache.disable', false); $this->loadFixtures('OverallFavorite'); - $OverallFavorite =& new OverallFavorite(); + $OverallFavorite = new OverallFavorite(); touch(CACHE . 'views' . DS . 'some_dir_overallfavorites_index.php'); touch(CACHE . 'views' . DS . 'some_dir_overall_favorites_index.php'); @@ -345,8 +345,8 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithCounterCache() { $this->loadFixtures('Syfile', 'Item'); - $TestModel =& new Syfile(); - $TestModel2 =& new Item(); + $TestModel = new Syfile(); + $TestModel2 = new Item(); $result = $TestModel->findById(1); $this->assertIdentical($result['Syfile']['item_count'], null); @@ -486,11 +486,11 @@ class ModelWriteTest extends BaseModelTest { $this->loadFixtures('CategoryThread'); $this->db->query('ALTER TABLE '. $this->db->fullTableName('category_threads') . " ADD COLUMN child_count INTEGER"); - $Category =& new CategoryThread(); + $Category = new CategoryThread(); $result = $Category->updateAll(array('CategoryThread.name' => "'updated'"), array('CategoryThread.parent_id' => 5)); $this->assertTrue($result); - $Category =& new CategoryThread(); + $Category = new CategoryThread(); $Category->belongsTo['ParentCategory']['counterCache'] = 'child_count'; $Category->updateCounterCache(array('parent_id' => 5)); $result = Set::extract($Category->find('all', array('conditions' => array('CategoryThread.id' => 5))), '{n}.CategoryThread.child_count'); @@ -505,8 +505,8 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithCounterCacheScope() { $this->loadFixtures('Syfile', 'Item'); - $TestModel =& new Syfile(); - $TestModel2 =& new Item(); + $TestModel = new Syfile(); + $TestModel2 = new Item(); $TestModel2->belongsTo['Syfile']['counterCache'] = true; $TestModel2->belongsTo['Syfile']['counterScope'] = array('published' => true); @@ -543,7 +543,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testValidatesBackwards() { - $TestModel =& new TestValidate(); + $TestModel = new TestValidate(); $TestModel->validate = array( 'user_id' => VALID_NUMBER, @@ -608,7 +608,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testValidates() { - $TestModel =& new TestValidate(); + $TestModel = new TestValidate(); $TestModel->validate = array( 'user_id' => 'numeric', @@ -961,7 +961,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveField() { $this->loadFixtures('Article'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->id = 1; $result = $TestModel->saveField('title', 'New First Article'); @@ -1012,7 +1012,7 @@ class ModelWriteTest extends BaseModelTest { $this->assertFalse($result); $this->loadFixtures('Node', 'Dependency'); - $Node =& new Node(); + $Node = new Node(); $Node->set('id', 1); $result = $Node->read(); $this->assertEqual(Set::extract('/ParentNode/name', $result), array('Second')); @@ -1037,7 +1037,7 @@ class ModelWriteTest extends BaseModelTest { 'ArticlesTag', 'Attachment' ); - $TestModel =& new User(); + $TestModel = new User(); $data = array('User' => array( 'user' => 'user', @@ -1047,7 +1047,7 @@ class ModelWriteTest extends BaseModelTest { $this->assertFalse($result); $this->assertTrue(!empty($TestModel->validationErrors)); - $TestModel =& new Article(); + $TestModel = new Article(); $data = array('Article' => array( 'user_id' => '', @@ -1250,7 +1250,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithSet() { $this->loadFixtures('Article'); - $TestModel =& new Article(); + $TestModel = new Article(); // Create record we will be updating later @@ -1377,7 +1377,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithNonExistentFields() { $this->loadFixtures('Article'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->recursive = -1; $data = array( @@ -1445,7 +1445,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveHabtm() { $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->findById(2); $expected = array( @@ -1916,7 +1916,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveHabtmCustomKeys() { $this->loadFixtures('Story', 'StoriesTag', 'Tag'); - $Story =& new Story(); + $Story = new Story(); $data = array( 'Story' => array('story' => '1'), @@ -1966,7 +1966,7 @@ class ModelWriteTest extends BaseModelTest { */ function testHabtmSaveKeyResolution() { $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); - $ThePaper =& new ThePaper(); + $ThePaper = new ThePaper(); $ThePaper->id = 1; $ThePaper->save(array('Monkey' => array(2, 3))); @@ -2055,7 +2055,7 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationOfEmptyRecord() { $this->loadFixtures('Author'); - $TestModel =& new Author(); + $TestModel = new Author(); $this->assertEqual($TestModel->find('count'), 4); $TestModel->deleteAll(true, false, false); @@ -2073,7 +2073,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testCreateWithPKFiltering() { - $TestModel =& new Article(); + $TestModel = new Article(); $data = array( 'id' => 5, 'user_id' => 2, @@ -2170,8 +2170,8 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationWithMultipleData() { $this->loadFixtures('Article', 'Comment'); - $Article =& new Article(); - $Comment =& new Comment(); + $Article = new Article(); + $Comment = new Comment(); $articles = $Article->find('all', array( 'fields' => array('id','title'), @@ -2341,8 +2341,8 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationWithMultipleDataSameModel() { $this->loadFixtures('Article'); - $Article =& new Article(); - $SecondaryArticle =& new Article(); + $Article = new Article(); + $SecondaryArticle = new Article(); $result = $Article->field('title', array('id' => 1)); $this->assertEqual($result, 'First Article'); @@ -2399,8 +2399,8 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationWithMultipleDataSameModelManualInstances() { $this->loadFixtures('PrimaryModel'); - $Primary =& new PrimaryModel(); - $Secondary =& new PrimaryModel(); + $Primary = new PrimaryModel(); + $Secondary = new PrimaryModel(); $result = $Primary->field('primary_name', array('id' => 1)); $this->assertEqual($result, 'Primary Name Existing'); @@ -2437,7 +2437,7 @@ class ModelWriteTest extends BaseModelTest { */ function testRecordExists() { $this->loadFixtures('User'); - $TestModel =& new User(); + $TestModel = new User(); $this->assertFalse($TestModel->exists()); $TestModel->read(null, 1); @@ -2447,7 +2447,7 @@ class ModelWriteTest extends BaseModelTest { $TestModel->id = 4; $this->assertTrue($TestModel->exists()); - $TestModel =& new TheVoid(); + $TestModel = new TheVoid(); $this->assertFalse($TestModel->exists()); $TestModel->id = 5; $this->assertFalse($TestModel->exists()); @@ -2460,7 +2460,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUpdateExisting() { $this->loadFixtures('User', 'Article', 'Comment'); - $TestModel =& new User(); + $TestModel = new User(); $TestModel->create(); $TestModel->save(array( @@ -2481,8 +2481,8 @@ class ModelWriteTest extends BaseModelTest { $this->assertEqual($result['User']['user'], 'updated user'); $this->assertEqual($result['User']['password'], 'some password'); - $Article =& new Article(); - $Comment =& new Comment(); + $Article = new Article(); + $Comment = new Comment(); $data = array( 'Comment' => array( 'id' => 1, @@ -2507,7 +2507,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUpdateMultiple() { $this->loadFixtures('Comment', 'Article', 'User', 'CategoryThread'); - $TestModel =& new Comment(); + $TestModel = new Comment(); $result = Set::extract($TestModel->find('all'), '{n}.Comment.user_id'); $expected = array('2', '4', '1', '1', '1', '2'); $this->assertEqual($result, $expected); @@ -2540,7 +2540,7 @@ class ModelWriteTest extends BaseModelTest { */ function testHabtmUuidWithUuidId() { $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolio'); - $TestModel =& new Uuidportfolio(); + $TestModel = new Uuidportfolio(); $data = array('Uuidportfolio' => array('name' => 'Portfolio 3')); $data['Uuiditem']['Uuiditem'] = array('483798c8-c7cc-430e-8cf9-4fcc40cf8569'); @@ -2558,7 +2558,7 @@ class ModelWriteTest extends BaseModelTest { **/ function testHabtmSavingWithNoPrimaryKeyUuidJoinTable() { $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); - $Fruit =& new Fruit(); + $Fruit = new Fruit(); $data = array( 'Fruit' => array( 'color' => 'Red', @@ -2581,7 +2581,7 @@ class ModelWriteTest extends BaseModelTest { **/ function testHabtmSavingWithNoPrimaryKeyUuidJoinTableNoWith() { $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); - $Fruit =& new FruitNoWith(); + $Fruit = new FruitNoWith(); $data = array( 'Fruit' => array( 'color' => 'Red', @@ -2606,7 +2606,7 @@ class ModelWriteTest extends BaseModelTest { */ function testHabtmUuidWithNumericId() { $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolioNumericid'); - $TestModel =& new Uuiditem(); + $TestModel = new Uuiditem(); $data = array('Uuiditem' => array('name' => 'Item 7', 'published' => 0)); $data['Uuidportfolio']['Uuidportfolio'] = array('480af662-eb8c-47d3-886b-230540cf8569'); @@ -2742,7 +2742,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAll() { $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel =& new Post(); + $TestModel = new Post(); $result = $TestModel->find('all'); $this->assertEqual(count($result), 3); @@ -2827,7 +2827,7 @@ class ModelWriteTest extends BaseModelTest { ))); $this->assertEqual($result, $expected); - $TestModel =& new Comment(); + $TestModel = new Comment(); $ts = date('Y-m-d H:i:s'); $result = $TestModel->saveAll(array( 'Comment' => array( @@ -2894,7 +2894,7 @@ class ModelWriteTest extends BaseModelTest { 'comment' => 'Article comment', 'user_id' => 1 ))); - $Article =& new Article(); + $Article = new Article(); $result = $Article->saveAll($data); $this->assertTrue($result); @@ -2927,7 +2927,7 @@ class ModelWriteTest extends BaseModelTest { ) ); - $Something =& new Something(); + $Something = new Something(); $result = $Something->saveAll($data); $this->assertTrue($result); $result = $Something->read(); @@ -3079,7 +3079,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllAtomic() { $this->loadFixtures('Article', 'User'); - $TestModel =& new Article(); + $TestModel = new Article(); $result = $TestModel->saveAll(array( 'Article' => array( @@ -3152,7 +3152,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllHasMany() { $this->loadFixtures('Article', 'Comment'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); $result = $TestModel->saveAll(array( @@ -3228,7 +3228,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllHasManyValidation() { $this->loadFixtures('Article', 'Comment'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); $TestModel->Comment->validate = array('comment' => 'notEmpty'); @@ -3268,7 +3268,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllTransaction() { $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel =& new Post(); + $TestModel = new Post(); $TestModel->validate = array('title' => 'notEmpty'); $data = array( @@ -3465,7 +3465,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllValidation() { $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel =& new Post(); + $TestModel = new Post(); $data = array( array( @@ -3656,7 +3656,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testSaveAllValidationOnly() { - $TestModel =& new Comment(); + $TestModel = new Comment(); $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); $data = array( @@ -3671,7 +3671,7 @@ class ModelWriteTest extends BaseModelTest { $result = $TestModel->saveAll($data, array('validate' => 'only')); $this->assertFalse($result); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->validate = array('title' => 'notEmpty'); $result = $TestModel->saveAll( array( @@ -3708,7 +3708,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testSaveAllValidateFirst() { - $model =& new Article(); + $model = new Article(); $model->deleteAll(true); $model->Comment->validate = array('comment' => 'notEmpty'); @@ -3787,7 +3787,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUpdateWithCalculation() { $this->loadFixtures('DataTest'); - $model =& new DataTest(); + $model = new DataTest(); $result = $model->saveAll(array( array('count' => 5, 'float' => 1.1), array('count' => 3, 'float' => 1.2), @@ -3815,7 +3815,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllHasManyValidationOnly() { $this->loadFixtures('Article', 'Comment'); - $TestModel =& new Article(); + $TestModel = new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); $TestModel->Comment->validate = array('comment' => 'notEmpty'); @@ -3892,7 +3892,7 @@ class ModelWriteTest extends BaseModelTest { */ function testFindAllForeignKey() { $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll =& new ProductUpdateAll(); + $ProductUpdateAll = new ProductUpdateAll(); $conditions = array('Group.name' => 'group one'); @@ -3956,7 +3956,7 @@ class ModelWriteTest extends BaseModelTest { */ function testProductUpdateAll() { $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll =& new ProductUpdateAll(); + $ProductUpdateAll = new ProductUpdateAll(); $conditions = array('Group.name' => 'group one'); @@ -4002,7 +4002,7 @@ class ModelWriteTest extends BaseModelTest { */ function testProductUpdateAllWithoutForeignKey() { $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll =& new ProductUpdateAll(); + $ProductUpdateAll = new ProductUpdateAll(); $conditions = array('Group.name' => 'group one'); diff --git a/cake/tests/cases/libs/model/schema.test.php b/cake/tests/cases/libs/model/schema.test.php index fc35f5c1..209c5d24 100755 --- a/cake/tests/cases/libs/model/schema.test.php +++ b/cake/tests/cases/libs/model/schema.test.php @@ -480,7 +480,7 @@ class CakeSchemaTest extends CakeTestCase { $db =& ConnectionManager::getDataSource('test_suite'); $db->cacheSources = false; - $Schema =& new CakeSchema(array( + $Schema = new CakeSchema(array( 'connection' => 'test_suite', 'testdescribes' => array( 'id' => array('type' => 'integer', 'key' => 'primary'), diff --git a/cake/tests/cases/libs/object.test.php b/cake/tests/cases/libs/object.test.php index 743d88da..896c47be 100755 --- a/cake/tests/cases/libs/object.test.php +++ b/cake/tests/cases/libs/object.test.php @@ -154,7 +154,7 @@ class RequestActionPersistentController extends Controller { * @package cake * @subpackage cake.tests.cases.libs */ -class TestObject extends Object { +class TestObject extends CakeObject { /** * firstName property * @@ -392,7 +392,7 @@ class ObjectTest extends CakeTestCase { @unlink(CACHE . 'persistent' . DS . 'testmodel.php'); - $model =& new ObjectTestModel(); + $model = new ObjectTestModel(); $expected = ClassRegistry::keys(); ClassRegistry::flush(); diff --git a/cake/tests/cases/libs/sanitize.test.php b/cake/tests/cases/libs/sanitize.test.php index 1899f16c..3048613f 100755 --- a/cake/tests/cases/libs/sanitize.test.php +++ b/cake/tests/cases/libs/sanitize.test.php @@ -405,7 +405,7 @@ class SanitizeTest extends CakeTestCase { function testFormatColumns() { $this->loadFixtures('DataTest', 'Article'); - $this->DataTest =& new SanitizeDataTest(array('alias' => 'DataTest')); + $this->DataTest = new SanitizeDataTest(array('alias' => 'DataTest')); $data = array('DataTest' => array( 'id' => 'z', 'count' => '12a', @@ -424,7 +424,7 @@ class SanitizeTest extends CakeTestCase { $result = $this->DataTest->data; $this->assertEqual($result, $expected); - $this->Article =& new SanitizeArticle(array('alias' => 'Article')); + $this->Article = new SanitizeArticle(array('alias' => 'Article')); $data = array('Article' => array( 'id' => 'ZB', 'user_id' => '12', diff --git a/cake/tests/cases/libs/session.test.php b/cake/tests/cases/libs/session.test.php index f74d626f..ca208b0c 100755 --- a/cake/tests/cases/libs/session.test.php +++ b/cake/tests/cases/libs/session.test.php @@ -63,7 +63,7 @@ class SessionTest extends CakeTestCase { * @return void */ function setUp() { - $this->Session =& new CakeSession(); + $this->Session = new CakeSession(); $this->Session->start(); $this->Session->_checkValid(); } diff --git a/cake/tests/cases/libs/test_manager.test.php b/cake/tests/cases/libs/test_manager.test.php index b8eb5de2..2c4c4129 100755 --- a/cake/tests/cases/libs/test_manager.test.php +++ b/cake/tests/cases/libs/test_manager.test.php @@ -41,8 +41,8 @@ class TestManagerTest extends CakeTestCase { * @access public */ function setUp() { - $this->Sut =& new TestManager(); - $this->Reporter =& new CakeHtmlReporter(); + $this->Sut = new TestManager(); + $this->Reporter = new CakeHtmlReporter(); } /** * testRunAllTests method @@ -51,11 +51,11 @@ class TestManagerTest extends CakeTestCase { * @access public */ function testRunAllTests() { - $folder =& new Folder($this->Sut->_getTestsPath()); + $folder = new Folder($this->Sut->_getTestsPath()); $extension = str_replace('.', '\.', TestManager::getExtension('test')); $out = $folder->findRecursive('.*' . $extension); - $reporter =& new CakeHtmlReporter(); + $reporter = new CakeHtmlReporter(); $list = TestManager::runAllTests($reporter, true); $this->assertEqual(count($out), count($list)); diff --git a/cake/tests/cases/libs/view/helpers/ajax.test.php b/cake/tests/cases/libs/view/helpers/ajax.test.php index 439846e0..2d32d45a 100755 --- a/cake/tests/cases/libs/view/helpers/ajax.test.php +++ b/cake/tests/cases/libs/view/helpers/ajax.test.php @@ -166,12 +166,12 @@ class AjaxHelperTest extends CakeTestCase { */ function setUp() { Router::reload(); - $this->Ajax =& new TestAjaxHelper(); - $this->Ajax->Html =& new HtmlHelper(); - $this->Ajax->Form =& new FormHelper(); - $this->Ajax->Javascript =& new JavascriptHelper(); + $this->Ajax = new TestAjaxHelper(); + $this->Ajax->Html = new HtmlHelper(); + $this->Ajax->Form = new FormHelper(); + $this->Ajax->Javascript = new JavascriptHelper(); $this->Ajax->Form->Html =& $this->Ajax->Html; - $view =& new View(new AjaxTestController()); + $view = new View(new AjaxTestController()); ClassRegistry::addObject('view', $view); ClassRegistry::addObject('PostAjaxTest', new PostAjaxTest()); } @@ -832,7 +832,7 @@ class AjaxHelperTest extends CakeTestCase { */ function testAfterRender() { $oldXUpdate = env('HTTP_X_UPDATE'); - $this->Ajax->Javascript =& new TestJavascriptHelper(); + $this->Ajax->Javascript = new TestJavascriptHelper(); $_SERVER['HTTP_X_UPDATE'] = 'secondDiv myDiv anotherDiv'; $result = $this->Ajax->div('myDiv'); diff --git a/cake/tests/cases/libs/view/helpers/form.test.php b/cake/tests/cases/libs/view/helpers/form.test.php index af00110f..c82f7b04 100755 --- a/cake/tests/cases/libs/view/helpers/form.test.php +++ b/cake/tests/cases/libs/view/helpers/form.test.php @@ -601,10 +601,10 @@ class FormHelperTest extends CakeTestCase { parent::setUp(); Router::reload(); - $this->Form =& new FormHelper(); - $this->Form->Html =& new HtmlHelper(); - $this->Controller =& new ContactTestController(); - $this->View =& new View($this->Controller); + $this->Form = new FormHelper(); + $this->Form->Html = new HtmlHelper(); + $this->Controller = new ContactTestController(); + $this->View = new View($this->Controller); ClassRegistry::addObject('view', $view); ClassRegistry::addObject('Contact', new Contact()); @@ -4348,11 +4348,11 @@ class FormHelperTest extends CakeTestCase { **/ function testFileUploadOnOtherModel() { ClassRegistry::removeObject('view'); - $controller =& new Controller(); + $controller = new Controller(); $controller->name = 'ValidateUsers'; $controller->uses = array('ValidateUser'); $controller->constructClasses(); - $view =& new View($controller, true); + $view = new View($controller, true); $this->Form->create('ValidateUser', array('type' => 'file')); $result = $this->Form->file('ValidateProfile.city'); diff --git a/cake/tests/cases/libs/view/helpers/html.test.php b/cake/tests/cases/libs/view/helpers/html.test.php index 52dd5cba..cfeee928 100755 --- a/cake/tests/cases/libs/view/helpers/html.test.php +++ b/cake/tests/cases/libs/view/helpers/html.test.php @@ -90,8 +90,8 @@ class HtmlHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Html =& new HtmlHelper(); - $view =& new View(new TheHtmlTestController()); + $this->Html = new HtmlHelper(); + $view = new View(new TheHtmlTestController()); ClassRegistry::addObject('view', $view); $this->_appEncoding = Configure::read('App.encoding'); $this->_asset = Configure::read('Asset'); diff --git a/cake/tests/cases/libs/view/helpers/javascript.test.php b/cake/tests/cases/libs/view/helpers/javascript.test.php index 7ebad00e..84c6a5cf 100755 --- a/cake/tests/cases/libs/view/helpers/javascript.test.php +++ b/cake/tests/cases/libs/view/helpers/javascript.test.php @@ -114,10 +114,10 @@ class JavascriptTest extends CakeTestCase { * @return void */ function startTest() { - $this->Javascript =& new JavascriptHelper(); - $this->Javascript->Html =& new HtmlHelper(); - $this->Javascript->Form =& new FormHelper(); - $this->View =& new TheView(new TheJsTestController()); + $this->Javascript = new JavascriptHelper(); + $this->Javascript->Html = new HtmlHelper(); + $this->Javascript->Form = new FormHelper(); + $this->View = new TheView(new TheJsTestController()); ClassRegistry::addObject('view', $this->View); } /** @@ -140,10 +140,10 @@ class JavascriptTest extends CakeTestCase { * @return void */ function testConstruct() { - $Javascript =& new JavascriptHelper(array('safe')); + $Javascript = new JavascriptHelper(array('safe')); $this->assertTrue($Javascript->safe); - $Javascript =& new JavascriptHelper(array('safe' => false)); + $Javascript = new JavascriptHelper(array('safe' => false)); $this->assertFalse($Javascript->safe); } /** diff --git a/cake/tests/cases/libs/view/helpers/number.test.php b/cake/tests/cases/libs/view/helpers/number.test.php index ccc54540..20d667a4 100755 --- a/cake/tests/cases/libs/view/helpers/number.test.php +++ b/cake/tests/cases/libs/view/helpers/number.test.php @@ -46,7 +46,7 @@ class NumberHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Number =& new NumberHelper(); + $this->Number = new NumberHelper(); } /** * tearDown method diff --git a/cake/tests/cases/libs/view/helpers/paginator.test.php b/cake/tests/cases/libs/view/helpers/paginator.test.php index 3b8817ab..319d69d9 100755 --- a/cake/tests/cases/libs/view/helpers/paginator.test.php +++ b/cake/tests/cases/libs/view/helpers/paginator.test.php @@ -60,11 +60,11 @@ class PaginatorHelperTest extends CakeTestCase { ) ) ); - $this->Paginator->Html =& new HtmlHelper(); - $this->Paginator->Ajax =& new AjaxHelper(); - $this->Paginator->Ajax->Html =& new HtmlHelper(); - $this->Paginator->Ajax->Javascript =& new JavascriptHelper(); - $this->Paginator->Ajax->Form =& new FormHelper(); + $this->Paginator->Html = new HtmlHelper(); + $this->Paginator->Ajax = new AjaxHelper(); + $this->Paginator->Ajax->Html = new HtmlHelper(); + $this->Paginator->Ajax->Javascript = new JavascriptHelper(); + $this->Paginator->Ajax->Form = new FormHelper(); Configure::write('Routing.admin', ''); Router::reload(); diff --git a/cake/tests/cases/libs/view/helpers/rss.test.php b/cake/tests/cases/libs/view/helpers/rss.test.php index 0f49570f..6b73692b 100755 --- a/cake/tests/cases/libs/view/helpers/rss.test.php +++ b/cake/tests/cases/libs/view/helpers/rss.test.php @@ -39,8 +39,8 @@ class RssHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Rss =& new RssHelper(); - $this->Rss->Time =& new TimeHelper(); + $this->Rss = new RssHelper(); + $this->Rss->Time = new TimeHelper(); $this->Rss->beforeRender(); $manager =& XmlManager::getInstance(); diff --git a/cake/tests/cases/libs/view/helpers/xml.test.php b/cake/tests/cases/libs/view/helpers/xml.test.php index c7b1bae7..721e8b90 100755 --- a/cake/tests/cases/libs/view/helpers/xml.test.php +++ b/cake/tests/cases/libs/view/helpers/xml.test.php @@ -34,7 +34,7 @@ App::import('Helper', 'Xml'); * @package cake * @subpackage cake.tests.cases.libs.view.helpers */ -class TestXml extends Object { +class TestXml extends CakeObject { /** * content property * @@ -76,7 +76,7 @@ class XmlHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Xml =& new XmlHelper(); + $this->Xml = new XmlHelper(); $this->Xml->beforeRender(); $manager =& XmlManager::getInstance(); $manager->namespaces = array(); diff --git a/cake/tests/cases/libs/view/theme.test.php b/cake/tests/cases/libs/view/theme.test.php index eeb5dd88..ce3cafe6 100755 --- a/cake/tests/cases/libs/view/theme.test.php +++ b/cake/tests/cases/libs/view/theme.test.php @@ -123,7 +123,7 @@ class TestThemeView extends ThemeView { * @return void */ function cakeError($method, $messages) { - $error =& new ThemeViewTestErrorHandler($method, $messages); + $error = new ThemeViewTestErrorHandler($method, $messages); return $error; } } diff --git a/cake/tests/cases/libs/view/view.test.php b/cake/tests/cases/libs/view/view.test.php index 103a4b73..62d1454a 100755 --- a/cake/tests/cases/libs/view/view.test.php +++ b/cake/tests/cases/libs/view/view.test.php @@ -164,7 +164,7 @@ class TestView extends View { * @return void */ function cakeError($method, $messages) { - $error =& new ViewTestErrorHandler($method, $messages); + $error = new ViewTestErrorHandler($method, $messages); return $error; } } @@ -541,7 +541,7 @@ class ViewTest extends CakeTestCase { **/ function testHelperCallbackTriggering() { $this->PostsController->helpers = array('Html', 'CallbackMock'); - $View =& new TestView($this->PostsController); + $View = new TestView($this->PostsController); $loaded = array(); $View->loaded = $View->loadHelpers($loaded, $this->PostsController->helpers); $View->loaded['CallbackMock']->expectOnce('beforeRender'); @@ -558,7 +558,7 @@ class ViewTest extends CakeTestCase { */ function testBeforeLayout() { $this->PostsController->helpers = array('TestAfter', 'Html'); - $View =& new View($this->PostsController); + $View = new View($this->PostsController); $out = $View->render('index'); $this->assertEqual($View->loaded['testAfter']->property, 'Valuation'); } @@ -572,7 +572,7 @@ class ViewTest extends CakeTestCase { $this->PostsController->helpers = array('TestAfter', 'Html'); $this->PostsController->set('variable', 'values'); - $View =& new View($this->PostsController); + $View = new View($this->PostsController); ClassRegistry::addObject('afterView', $View); $content = 'This is my view output'; diff --git a/cake/tests/cases/libs/xml.test.php b/cake/tests/cases/libs/xml.test.php index acff6c89..bb15e96e 100755 --- a/cake/tests/cases/libs/xml.test.php +++ b/cake/tests/cases/libs/xml.test.php @@ -39,7 +39,7 @@ class XmlTest extends CakeTestCase { * @return void */ function setUp() { - $manager =& new XmlManager(); + $manager = new XmlManager(); $manager->namespaces = array(); } /** @@ -111,7 +111,7 @@ class XmlTest extends CakeTestCase { array('Status' => array('id' => 2)) ) ); - $result =& new Xml($data, array('format' => 'tags')); + $result = new Xml($data, array('format' => 'tags')); $expected = '12'; $this->assertIdentical($result->toString(), $expected); @@ -123,27 +123,27 @@ class XmlTest extends CakeTestCase { * @return void **/ function testSerializationOfBooleanAndBooleanishValues() { - $xml =& new Xml(array('data' => array('example' => false))); + $xml = new Xml(array('data' => array('example' => false))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean values incorrectly handled. %s'); - $xml =& new Xml(array('data' => array('example' => true))); + $xml = new Xml(array('data' => array('example' => true))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean values incorrectly handled. %s'); - $xml =& new Xml(array('data' => array('example' => null))); + $xml = new Xml(array('data' => array('example' => null))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean values incorrectly handled. %s'); - $xml =& new Xml(array('data' => array('example' => 0))); + $xml = new Xml(array('data' => array('example' => 0))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean-ish values incorrectly handled. %s'); - $xml =& new Xml(array('data' => array('example' => 1))); + $xml = new Xml(array('data' => array('example' => 1))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean-ish values incorrectly handled. %s'); @@ -334,7 +334,7 @@ class XmlTest extends CakeTestCase { * @return void */ function testCloneNode() { - $node =& new XmlNode('element', 'myValue'); + $node = new XmlNode('element', 'myValue'); $twin =& $node->cloneNode(); $this->assertEqual($node, $twin); } @@ -359,7 +359,7 @@ class XmlTest extends CakeTestCase { 'Industry' => array('id' => 2, 'name' => 'Education'), ) ); - $xml =& new Xml($input, array('format' => 'tags')); + $xml = new Xml($input, array('format' => 'tags')); $node =& $xml->children[0]->children[0]; $nextSibling =& $node->nextSibling(); @@ -392,7 +392,7 @@ class XmlTest extends CakeTestCase { 'Industry' => array('id' => 2, 'name' => 'Education'), ) ); - $xml =& new Xml($input, array('format' => 'tags')); + $xml = new Xml($input, array('format' => 'tags')); $node =& $xml->children[0]->children[1]; $prevSibling =& $node->previousSibling(); @@ -407,7 +407,7 @@ class XmlTest extends CakeTestCase { * @return void */ function testAddAndRemoveAttributes() { - $node =& new XmlElement('myElement', 'superValue'); + $node = new XmlElement('myElement', 'superValue'); $this->assertTrue(empty($node->attributes)); $attrs = array( @@ -418,12 +418,12 @@ class XmlTest extends CakeTestCase { $node->addAttribute($attrs); $this->assertEqual($node->attributes, $attrs); - $node =& new XmlElement('myElement', 'superValue'); + $node = new XmlElement('myElement', 'superValue'); $node->addAttribute('test', 'value'); $this->assertTrue(isset($node->attributes['test'])); - $node =& new XmlElement('myElement', 'superValue'); - $obj =& new StdClass(); + $node = new XmlElement('myElement', 'superValue'); + $obj = new StdClass(); $obj->class = 'info'; $obj->id = 'primaryInfoBox'; $node->addAttribute($obj); @@ -774,7 +774,7 @@ class XmlTest extends CakeTestCase { varchar(45) '; - $xml =& new XML($filledValue); + $xml = new XML($filledValue); $expected = array( 'Method' => array( 'name' => 'set_user_settings', @@ -798,7 +798,7 @@ class XmlTest extends CakeTestCase { '; - $xml =& new XML($emptyValue); + $xml = new XML($emptyValue); $expected = array( 'Method' => array( 'name' => 'set_user_settings', diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index f642e36a..13e172a4 100755 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -239,7 +239,7 @@ class CakeTestCase extends UnitTestCase { $this->_actionFixtures = array(); foreach ($models as $model) { - $fixture =& new CakeTestFixture($this->db); + $fixture = new CakeTestFixture($this->db); $fixture->name = $model['model'] . 'Test'; $fixture->table = $model['table']; @@ -335,7 +335,7 @@ class CakeTestCase extends UnitTestCase { $return = $params['return']; $params = array_diff_key($params, array('data' => null, 'method' => null, 'return' => null)); - $dispatcher =& new CakeTestDispatcher(); + $dispatcher = new CakeTestDispatcher(); $dispatcher->testCase($this); if ($return != 'result') { @@ -770,7 +770,7 @@ class CakeTestCase extends UnitTestCase { if (isset($fixtureFile)) { require_once($fixtureFile); $fixtureClass = Inflector::camelize($fixture) . 'Fixture'; - $this->_fixtures[$this->fixtures[$index]] =& new $fixtureClass($this->db); + $this->_fixtures[$this->fixtures[$index]] = new $fixtureClass($this->db); $this->_fixtureClassMap[Inflector::camelize($fixture)] = $this->fixtures[$index]; } } diff --git a/cake/tests/lib/cake_test_fixture.php b/cake/tests/lib/cake_test_fixture.php index cd12f9a3..faba01fa 100755 --- a/cake/tests/lib/cake_test_fixture.php +++ b/cake/tests/lib/cake_test_fixture.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.tests.lib */ -class CakeTestFixture extends Object { +class CakeTestFixture extends CakeObject { /** * Name of the object * @@ -81,7 +81,7 @@ class CakeTestFixture extends Object { ClassRegistry::config(array('ds' => 'test_suite')); ClassRegistry::flush(); } elseif (isset($import['table'])) { - $model =& new Model(null, $import['table'], $import['connection']); + $model = new Model(null, $import['table'], $import['connection']); $db =& ConnectionManager::getDataSource($import['connection']); $db->cacheSources = false; $model->useDbConfig = $import['connection']; diff --git a/cake/tests/lib/code_coverage_manager.php b/cake/tests/lib/code_coverage_manager.php index 1000c675..511b9c9d 100755 --- a/cake/tests/lib/code_coverage_manager.php +++ b/cake/tests/lib/code_coverage_manager.php @@ -78,7 +78,7 @@ class CodeCoverageManager { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] =& new CodeCoverageManager(); + $instance[0] = new CodeCoverageManager(); } return $instance[0]; } @@ -477,10 +477,10 @@ class CodeCoverageManager { break; } } - $testManager =& new TestManager(); + $testManager = new TestManager(); $testFile = str_replace(array('/', $testManager->_testExtension), array(DS, '.php'), $file); - $folder =& new Folder(); + $folder = new Folder(); $folder->cd(ROOT . DS . CAKE_TESTS_LIB); $contents = $folder->ls(); @@ -506,7 +506,7 @@ class CodeCoverageManager { */ function __testObjectFilesFromGroupFile($groupFile, $isApp = true) { $manager = CodeCoverageManager::getInstance(); - $testManager =& new TestManager(); + $testManager = new TestManager(); $path = TESTS . 'groups'; diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index d614ed6d..c49e19b2 100755 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -77,15 +77,15 @@ class TestManager { * @access public */ function runAllTests(&$reporter, $testing = false) { - $manager =& new TestManager(); + $manager = new TestManager(); $testCases =& $manager->_getTestFileList($manager->_getTestsPath()); if ($manager->appTest) { - $test =& new GroupTest('All App Tests'); + $test = new GroupTest('All App Tests'); } else if ($manager->pluginTest) { - $test =& new GroupTest('All ' . Inflector::humanize($manager->pluginTest) . ' Plugin Tests'); + $test = new GroupTest('All ' . Inflector::humanize($manager->pluginTest) . ' Plugin Tests'); } else { - $test =& new GroupTest('All Core Tests'); + $test = new GroupTest('All Core Tests'); } if ($testing) { @@ -107,7 +107,7 @@ class TestManager { * @access public */ function runTestCase($testCaseFile, &$reporter, $testing = false) { - $manager =& new TestManager(); + $manager = new TestManager(); $testCaseFileWithPath = $manager->_getTestsPath() . DS . $testCaseFile; @@ -120,7 +120,7 @@ class TestManager { return true; } - $test =& new GroupTest("Individual test case: " . $testCaseFile); + $test = new GroupTest("Individual test case: " . $testCaseFile); $test->addTestFile($testCaseFileWithPath); return $test->run($reporter); } @@ -133,7 +133,7 @@ class TestManager { * @access public */ function runGroupTest($groupTestName, &$reporter) { - $manager =& new TestManager(); + $manager = new TestManager(); $filePath = $manager->_getTestsPath('groups') . DS . strtolower($groupTestName) . $manager->_groupExtension; if (!file_exists($filePath)) { @@ -141,7 +141,7 @@ class TestManager { } require_once $filePath; - $test =& new GroupTest($groupTestName . ' group test'); + $test = new GroupTest($groupTestName . ' group test'); foreach ($manager->_getGroupTestClassNames($filePath) as $groupTest) { $testCase = new $groupTest(); $test->addTestCase($testCase); @@ -160,7 +160,7 @@ class TestManager { * @access public */ function addTestCasesFromDirectory(&$groupTest, $directory = '.') { - $manager =& new TestManager(); + $manager = new TestManager(); $testCases =& $manager->_getTestFileList($directory); foreach ($testCases as $testCase) { $groupTest->addTestFile($testCase); @@ -175,7 +175,7 @@ class TestManager { * @access public */ function addTestFile(&$groupTest, $file) { - $manager =& new TestManager(); + $manager = new TestManager(); if (file_exists($file.'.test.php')) { $file .= '.test.php'; @@ -190,7 +190,7 @@ class TestManager { * @access public */ function &getTestCaseList() { - $manager =& new TestManager(); + $manager = new TestManager(); $return = $manager->_getTestCaseList($manager->_getTestsPath()); return $return; } @@ -222,7 +222,7 @@ class TestManager { * @access public */ function &getGroupTestList() { - $manager =& new TestManager(); + $manager = new TestManager(); $return = $manager->_getTestGroupList($manager->_getTestsPath('groups')); return $return; } @@ -360,7 +360,7 @@ class TestManager { * @access public */ function getExtension($type = 'test') { - $manager =& new TestManager(); + $manager = new TestManager(); if ($type == 'test') { return $manager->_testExtension; } @@ -380,7 +380,7 @@ class CliTestManager extends TestManager { * @access public */ function &getGroupTestList() { - $manager =& new CliTestManager(); + $manager = new CliTestManager(); $groupTests =& $manager->_getTestGroupList($manager->_getTestsPath('groups')); $buffer = "Available Group Test:\n"; @@ -395,7 +395,7 @@ class CliTestManager extends TestManager { * @access public */ function &getTestCaseList() { - $manager =& new CliTestManager(); + $manager = new CliTestManager(); $testCases =& $manager->_getTestCaseList($manager->_getTestsPath()); $buffer = "Available Test Cases:\n"; @@ -438,7 +438,7 @@ class TextTestManager extends TestManager { * @access public */ function &getGroupTestList() { - $manager =& new TextTestManager(); + $manager = new TextTestManager(); $groupTests =& $manager->_getTestGroupList($manager->_getTestsPath('groups')); $buffer = "Core Test Groups:\n"; @@ -465,7 +465,7 @@ class TextTestManager extends TestManager { * @access public */ function &getTestCaseList() { - $manager =& new TextTestManager(); + $manager = new TextTestManager(); $testCases =& $manager->_getTestCaseList($manager->_getTestsPath()); $buffer = "Core Test Cases:\n"; @@ -526,7 +526,7 @@ class HtmlTestManager extends TestManager { */ function &getGroupTestList() { $urlExtra = ''; - $manager =& new HtmlTestManager(); + $manager = new HtmlTestManager(); $groupTests =& $manager->_getTestGroupList($manager->_getTestsPath('groups')); $buffer = "

Core Test Groups:

\n
    "; @@ -554,7 +554,7 @@ class HtmlTestManager extends TestManager { */ function &getTestCaseList() { $urlExtra = ''; - $manager =& new HtmlTestManager(); + $manager = new HtmlTestManager(); $testCases =& $manager->_getTestCaseList($manager->_getTestsPath()); $buffer = "

    Core Test Cases:

    \n
      "; @@ -599,10 +599,10 @@ if (function_exists('caketestsgetreporter')) { switch (CAKE_TEST_OUTPUT) { case CAKE_TEST_OUTPUT_HTML: require_once CAKE_TESTS_LIB . 'cake_reporter.php'; - $Reporter =& new CakeHtmlReporter(); + $Reporter = new CakeHtmlReporter(); break; default: - $Reporter =& new TextReporter(); + $Reporter = new TextReporter(); break; } } @@ -732,7 +732,7 @@ if (function_exists('caketestsgetreporter')) { if (!class_exists('dispatcher')) { require CAKE . 'dispatcher.php'; } - $dispatch =& new Dispatcher(); + $dispatch = new Dispatcher(); $dispatch->baseUrl(); define('BASE', $dispatch->webroot); $baseUrl = BASE; diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php index ab3cb7b2..c10ec835 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class OtherComponentComponent extends Object { +class OtherComponentComponent extends CakeObject { } ?> \ No newline at end of file diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php index 6a80527d..3fd81a56 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class PluginsComponentComponent extends Object { +class PluginsComponentComponent extends CakeObject { var $components = array('TestPlugin.OtherComponent'); } ?> \ No newline at end of file diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php index 23a462bf..0e6690a2 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class TestPluginComponentComponent extends Object { +class TestPluginComponentComponent extends CakeObject { var $components = array('TestPlugin.TestPluginOtherComponent'); } ?> \ No newline at end of file diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php index 560e0702..ac480a7a 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class TestPluginOtherComponentComponent extends Object { +class TestPluginOtherComponentComponent extends CakeObject { } ?> \ No newline at end of file diff --git a/conf/nginx-proxy.conf b/conf/nginx-proxy.conf index e1652854..ba92a2c6 100644 --- a/conf/nginx-proxy.conf +++ b/conf/nginx-proxy.conf @@ -44,14 +44,14 @@ http { ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; - # Upstream servers + # Upstream servers (using external container names) upstream cmc_staging { - server nginx-staging:80; + server cmc-nginx-staging:80; keepalive 32; } upstream cmc_production { - server nginx-production:80; + server cmc-nginx-production:80; keepalive 32; } diff --git a/docker-compose.caddy-staging-ubuntu.yml b/docker-compose.caddy-staging-ubuntu.yml index 08635661..538e571c 100644 --- a/docker-compose.caddy-staging-ubuntu.yml +++ b/docker-compose.caddy-staging-ubuntu.yml @@ -12,9 +12,21 @@ services: ports: - "127.0.0.1:8091:80" volumes: - - ./app:/var/www/cmc-sales/app + # Mount specific app directories while preserving cake core + - ./app/config:/var/www/cmc-sales/app/config + - ./app/controllers:/var/www/cmc-sales/app/controllers + - ./app/models:/var/www/cmc-sales/app/models + - ./app/views:/var/www/cmc-sales/app/views + - ./app/vendors:/var/www/cmc-sales/app/vendors + - ./app/webroot/css:/var/www/cmc-sales/app/webroot/css + - ./app/webroot/js:/var/www/cmc-sales/app/webroot/js + - ./app/webroot/img:/var/www/cmc-sales/app/webroot/img - staging_pdf_data:/var/www/cmc-sales/app/webroot/pdf - staging_attachments_data:/var/www/cmc-sales/app/webroot/attachments_files + # Mount cake directory to ensure CakePHP core is available + - ./cake:/var/www/cmc-sales/cake + - ./vendors:/var/www/cmc-sales/vendors + - ./index.php:/var/www/cmc-sales/index.php restart: unless-stopped environment: - APP_ENV=staging diff --git a/docker-compose.proxy.yml b/docker-compose.proxy.yml deleted file mode 100644 index 616270ab..00000000 --- a/docker-compose.proxy.yml +++ /dev/null @@ -1,68 +0,0 @@ -# Main reverse proxy for both staging and production -version: '3.8' - -services: - nginx-proxy: - image: nginx:latest - container_name: cmc-nginx-proxy - ports: - - "80:80" - - "443:443" - volumes: - - ./conf/nginx-proxy.conf:/etc/nginx/nginx.conf - - lego_certificates:/etc/ssl/certs:ro - - lego_acme_challenge:/var/www/acme-challenge:ro - restart: unless-stopped - depends_on: - - nginx-staging - - nginx-production - networks: - - proxy-network - - cmc-staging-network - - cmc-production-network - - lego: - image: goacme/lego:latest - container_name: cmc-lego - volumes: - - lego_certificates:/data/certificates - - lego_accounts:/data/accounts - - lego_acme_challenge:/data/acme-challenge - - ./scripts:/scripts:ro - environment: - - LEGO_DISABLE_CNAME=true - command: sleep infinity - restart: unless-stopped - networks: - - proxy-network - - # Import staging services - nginx-staging: - extends: - file: docker-compose.staging.yml - service: nginx-staging - networks: - - proxy-network - - cmc-staging-network - - # Import production services - nginx-production: - extends: - file: docker-compose.production.yml - service: nginx-production - networks: - - proxy-network - - cmc-production-network - -volumes: - lego_certificates: - lego_accounts: - lego_acme_challenge: - -networks: - proxy-network: - driver: bridge - cmc-staging-network: - external: true - cmc-production-network: - external: true \ No newline at end of file diff --git a/index.php b/index.php index c6a3a1b1..7e3c92de 100755 --- a/index.php +++ b/index.php @@ -52,6 +52,12 @@ require CORE_PATH . 'cake' . DS . 'basics.php'; $TIME_START = getMicrotime(); require CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php'; + + // Load PHP 7 compatibility early + if (file_exists(APP_DIR . DS . 'config' . DS . 'php7_compat.php')) { + require APP_DIR . DS . 'config' . DS . 'php7_compat.php'; + } + require LIBS . 'object.php'; require LIBS . 'inflector.php'; require LIBS . 'configure.php'; diff --git a/scripts/backup-db.sh b/scripts/backup-db.sh new file mode 100755 index 00000000..9094d9db --- /dev/null +++ b/scripts/backup-db.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +# Database backup script for CMC Sales +# Usage: ./scripts/backup-db.sh [staging|production] + +set -e + +ENVIRONMENT=${1:-production} +BACKUP_DIR="/var/backups/cmc-sales" +DATE=$(date +%Y%m%d-%H%M%S) + +# Create backup directory if it doesn't exist +mkdir -p "$BACKUP_DIR" + +case $ENVIRONMENT in + staging) + CONTAINER="cmc-db-staging" + DB_NAME="cmc_staging" + DB_USER="cmc_staging" + BACKUP_FILE="$BACKUP_DIR/backup_staging_${DATE}.sql.gz" + ;; + production) + CONTAINER="cmc-db-production" + DB_NAME="cmc" + DB_USER="cmc" + BACKUP_FILE="$BACKUP_DIR/backup_production_${DATE}.sql.gz" + ;; + *) + echo "Usage: $0 [staging|production]" + exit 1 + ;; +esac + +echo "Creating backup for $ENVIRONMENT environment..." +echo "Container: $CONTAINER" +echo "Database: $DB_NAME" +echo "Output: $BACKUP_FILE" + +# Create backup +docker exec -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ + $CONTAINER \ + mysqldump --single-transaction --routines --triggers --user=$DB_USER $DB_NAME | \ + gzip > "$BACKUP_FILE" + +# Verify backup was created +if [ -f "$BACKUP_FILE" ]; then + BACKUP_SIZE=$(stat -f%z "$BACKUP_FILE" 2>/dev/null || stat -c%s "$BACKUP_FILE" 2>/dev/null) + echo "Backup created successfully: $BACKUP_FILE (${BACKUP_SIZE} bytes)" + + # Clean up old backups (keep last 7 days) + find "$BACKUP_DIR" -name "backup_${ENVIRONMENT}_*.sql.gz" -type f -mtime +7 -delete + echo "Old backups cleaned up (kept last 7 days)" +else + echo "ERROR: Backup file was not created!" + exit 1 +fi \ No newline at end of file diff --git a/scripts/debug-php-container.sh b/scripts/debug-php-container.sh new file mode 100755 index 00000000..324dd1df --- /dev/null +++ b/scripts/debug-php-container.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +# Debug script for PHP container segfault issues + +echo "=== PHP Container Debug Script ===" +echo "" + +# Check if container exists +echo "1. Checking for existing containers..." +docker ps -a | grep cmc-php-staging + +# Get detailed logs +echo "" +echo "2. Getting container logs..." +docker logs cmc-php-staging --tail 50 2>&1 | tee php-debug.log + +# Check container exit status +echo "" +echo "3. Checking container exit status..." +docker inspect cmc-php-staging --format='{{.State.ExitCode}} {{.State.Error}}' 2>/dev/null || echo "Container not found" + +# Try running with different commands to isolate the issue +echo "" +echo "4. Testing different startup commands..." + +# Test 1: Just run bash +echo " Test 1: Running bash shell..." +docker run --rm -it --name cmc-php-test1 \ + --platform linux/amd64 \ + -v $(pwd):/debug \ + ghcr.io/kzrl/ubuntu:lucid \ + bash -c "echo 'Container started successfully'" + +# Test 2: Check Apache installation +echo "" +echo " Test 2: Testing with Apache installation..." +docker run --rm -it --name cmc-php-test2 \ + --platform linux/amd64 \ + -e DEBIAN_FRONTEND=noninteractive \ + ghcr.io/kzrl/ubuntu:lucid \ + bash -c "sed -i 's/archive/old-releases/' /etc/apt/sources.list && apt-get update && apt-get -y install apache2 && echo 'Apache installed successfully'" + +# Test 3: Build with alternative command +echo "" +echo "5. Building with debug mode..." +docker build --platform linux/amd64 --progress=plain -t cmc-php-debug -f Dockerfile.debug . 2>&1 | tee build-debug.log + +echo "" +echo "Debug information saved to:" +echo " - php-debug.log" +echo " - build-debug.log" +echo "" +echo "Common segfault causes:" +echo " 1. Platform incompatibility (ARM vs x86)" +echo " 2. Corrupted base image" +echo " 3. Memory issues" +echo " 4. Incompatible package versions" \ No newline at end of file diff --git a/scripts/deploy-staging-caddy.sh b/scripts/deploy-staging-caddy.sh new file mode 100755 index 00000000..438394f0 --- /dev/null +++ b/scripts/deploy-staging-caddy.sh @@ -0,0 +1,127 @@ +#!/bin/bash + +# Deployment script for staging environment with Caddy and containers +# This script deploys the containerized staging environment + +set -e + +echo "=== CMC Sales Staging Deployment with Caddy ===" +echo "" + +# Check if running as root for Caddy operations +if [ "$EUID" -eq 0 ]; then + SUDO="" +else + SUDO="sudo" + echo "Note: You may be prompted for sudo password for Caddy operations" +fi + +# 1. Check prerequisites +echo "Checking prerequisites..." + +# Check if Caddy is installed +if ! command -v caddy &> /dev/null; then + echo "ERROR: Caddy is not installed. Please run ./scripts/install-caddy.sh first" + exit 1 +fi + +# Check if Docker is installed +if ! command -v docker &> /dev/null; then + echo "ERROR: Docker is not installed" + exit 1 +fi + +# Check if docker-compose is available +if ! docker compose version &> /dev/null; then + echo "ERROR: Docker Compose is not available" + exit 1 +fi + +# 2. Create necessary directories +echo "Creating directories..." +$SUDO mkdir -p /var/log/caddy +$SUDO chown caddy:caddy /var/log/caddy + +# 3. Stop existing services if running +echo "Checking for existing services..." +if docker ps | grep -q "cmc-.*-staging"; then + echo "Stopping existing staging containers..." + docker compose -f docker-compose.caddy-staging.yml down +fi + +# 4. Build and start containers +echo "Building and starting staging containers..." +docker compose -f docker-compose.caddy-staging.yml build --no-cache +docker compose -f docker-compose.caddy-staging.yml up -d + +# Wait for containers to be ready +echo "Waiting for containers to be ready..." +sleep 10 + +# 5. Check container health +echo "Checking container health..." +docker ps --filter "name=staging" + +# Test internal endpoints +echo "" +echo "Testing internal endpoints..." +echo -n "PHP container: " +curl -s -o /dev/null -w "%{http_code}" http://localhost:8091 || echo "Failed" +echo "" +echo -n "Go container: " +curl -s -o /dev/null -w "%{http_code}" http://localhost:8092/api/v1/health || echo "Failed" +echo "" + +# 6. Deploy Caddy configuration +echo "Deploying Caddy configuration..." + +# Backup existing Caddyfile +if [ -f /etc/caddy/Caddyfile ]; then + $SUDO cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.backup.$(date +%Y%m%d-%H%M%S) +fi + +# Copy new Caddyfile +$SUDO cp Caddyfile.staging-containers /etc/caddy/Caddyfile.staging + +# Validate configuration +echo "Validating Caddy configuration..." +caddy validate --config /etc/caddy/Caddyfile.staging + +# 7. Update Caddy to use staging config +echo "Updating Caddy configuration..." +$SUDO cp /etc/caddy/Caddyfile.staging /etc/caddy/Caddyfile + +# Reload Caddy +echo "Reloading Caddy..." +$SUDO systemctl reload caddy + +# 8. Final health check +echo "" +echo "Performing final health check..." +sleep 5 + +# Test public endpoint +echo -n "Public HTTPS endpoint: " +if curl -s -o /dev/null -w "%{http_code}" https://staging.cmc.springupsoftware.com/health; then + echo " - OK" +else + echo " - Failed (this is normal if DNS is not set up yet)" +fi + +# 9. Show status +echo "" +echo "=== Deployment Complete ===" +echo "" +echo "Container Status:" +docker compose -f docker-compose.caddy-staging.yml ps +echo "" +echo "Caddy Status:" +$SUDO systemctl status caddy --no-pager | head -n 10 +echo "" +echo "Access staging at: https://staging.cmc.springupsoftware.com" +echo "Basic auth: Use credentials configured in Caddyfile" +echo "" +echo "Logs:" +echo " Caddy: sudo journalctl -u caddy -f" +echo " Containers: docker compose -f docker-compose.caddy-staging.yml logs -f" +echo " Access log: sudo tail -f /var/log/caddy/staging.cmc.springupsoftware.com.log" \ No newline at end of file diff --git a/scripts/fix-cakephp-compatibility.sh b/scripts/fix-cakephp-compatibility.sh new file mode 100755 index 00000000..2168a67c --- /dev/null +++ b/scripts/fix-cakephp-compatibility.sh @@ -0,0 +1,145 @@ +#!/bin/bash + +# Script to fix CakePHP 1.2.5 compatibility issues with newer PHP versions + +echo "=== CakePHP 1.2.5 Compatibility Fixes ===" +echo "" + +# Check if we're in the right directory +if [ ! -d "app/config" ]; then + echo "ERROR: Run this script from the CMC Sales root directory" + exit 1 +fi + +echo "Creating compatibility fixes..." + +# 1. Create a compatibility helper for PHP 7+ if it doesn't exist +mkdir -p app/config/patches + +cat > app/config/patches/php7_compatibility.php << 'EOF' +> app/config/bootstrap.php + echo "// PHP 7+ Compatibility" >> app/config/bootstrap.php + echo "if (version_compare(PHP_VERSION, '7.0.0') >= 0) {" >> app/config/bootstrap.php + echo " require_once(dirname(__FILE__) . '/patches/php7_compatibility.php');" >> app/config/bootstrap.php + echo "}" >> app/config/bootstrap.php + echo "Added compatibility include to bootstrap.php" +fi + +# 3. Fix common CakePHP core issues +echo "Checking for common issues..." + +# Fix Object::cakeError if it exists +if [ -f "cake/libs/object.php" ]; then + # Backup original + cp cake/libs/object.php cake/libs/object.php.bak + + # Fix call-time pass-by-reference + sed -i 's/&\$this->/\$this->/g' cake/libs/object.php + echo "Fixed cake/libs/object.php" +fi + +# 4. Create a test script +cat > app/webroot/test_php.php << 'EOF' +PHP Compatibility Test"; +echo "

      PHP Version: " . PHP_VERSION . "

      "; +echo "

      MySQL Extension: " . (function_exists('mysql_connect') || function_exists('mysqli_connect') ? 'Available' : 'Not Available') . "

      "; +echo "

      GD Extension: " . (extension_loaded('gd') ? 'Loaded' : 'Not Loaded') . "

      "; +echo "

      Error Reporting: " . error_reporting() . "

      "; +echo "

      CakePHP Constants:

      "; +echo "
      ";
      +if (defined('ROOT')) echo "ROOT: " . ROOT . "\n";
      +if (defined('APP_DIR')) echo "APP_DIR: " . APP_DIR . "\n";
      +if (defined('CAKE_CORE_INCLUDE_PATH')) echo "CAKE_CORE_INCLUDE_PATH: " . CAKE_CORE_INCLUDE_PATH . "\n";
      +echo "
      "; +phpinfo(); +EOF + +echo "" +echo "Compatibility fixes applied!" +echo "" +echo "Test your PHP setup at: http://localhost:8091/test_php.php" +echo "" +echo "If you still have issues:" +echo "1. Check error logs: docker logs cmc-php-staging" +echo "2. Try PHP 5.6 version: docker compose -f docker-compose.caddy-staging-php56.yml up -d" +echo "3. Use the original Dockerfile with fixes" \ No newline at end of file diff --git a/scripts/fix-cakephp-php7.sh b/scripts/fix-cakephp-php7.sh new file mode 100755 index 00000000..16ee13d3 --- /dev/null +++ b/scripts/fix-cakephp-php7.sh @@ -0,0 +1,16 @@ +#!/bin/bash + +# Fix CakePHP for PHP 7 compatibility + +echo "Fixing CakePHP for PHP 7 compatibility..." + +# Fix =& new syntax in cake directory +echo "Fixing deprecated =& new syntax..." +find cake -name "*.php" -type f -exec perl -i -pe 's/=&\s*new/= new/g' {} \; + +# Fix extends Object to extends CakeObject +echo "Fixing Object class inheritance..." +find cake -name "*.php" -type f -exec perl -i -pe 's/extends Object/extends CakeObject/g' {} \; + +echo "CakePHP PHP 7 compatibility fixes applied!" +echo "Note: This is a bulk fix and may need manual verification for edge cases." \ No newline at end of file diff --git a/scripts/install-caddy.sh b/scripts/install-caddy.sh new file mode 100755 index 00000000..85e5c967 --- /dev/null +++ b/scripts/install-caddy.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +# Caddy installation script for Debian 12 +# Usage: sudo ./scripts/install-caddy.sh + +set -e + +if [ "$EUID" -ne 0 ]; then + echo "Please run as root (use sudo)" + exit 1 +fi + +echo "Installing Caddy web server on Debian 12..." + +# Install dependencies +apt update +apt install -y debian-keyring debian-archive-keyring apt-transport-https curl + +# Add Caddy GPG key +curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg + +# Add Caddy repository +curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list + +# Update and install Caddy +apt update +apt install -y caddy + +# Create directories +mkdir -p /etc/caddy +mkdir -p /var/log/caddy +mkdir -p /var/lib/caddy + +# Set permissions +chown caddy:caddy /var/log/caddy +chown caddy:caddy /var/lib/caddy + +# Enable and start Caddy service +systemctl enable caddy +systemctl stop caddy # We'll configure it first + +echo "Caddy installed successfully!" +echo "" +echo "Next steps:" +echo "1. Copy your Caddyfile to /etc/caddy/Caddyfile" +echo "2. Update the basicauth passwords in Caddyfile" +echo "3. Start Caddy with: sudo systemctl start caddy" +echo "4. Check status with: sudo systemctl status caddy" +echo "" +echo "Generate password hash with: caddy hash-password" \ No newline at end of file diff --git a/scripts/lego-list-certs.sh b/scripts/lego-list-certs.sh new file mode 100755 index 00000000..65e9f539 --- /dev/null +++ b/scripts/lego-list-certs.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# Lego SSL certificate listing script for CMC Sales +# Usage: ./scripts/lego-list-certs.sh + +set -e + +echo "Listing SSL certificates managed by Lego..." + +# Check if lego container is running +if ! docker ps | grep -q "cmc-lego"; then + echo "ERROR: Lego container is not running. Please start it first with 'make proxy'" + exit 1 +fi + +# List all certificates +docker exec cmc-lego lego \ + --path="/data" \ + list + +echo "" +echo "Certificate files in container:" +docker exec cmc-lego find /data/certificates -name "*.crt" -o -name "*.key" | sort \ No newline at end of file diff --git a/scripts/lego-obtain-cert.sh b/scripts/lego-obtain-cert.sh new file mode 100755 index 00000000..6f936108 --- /dev/null +++ b/scripts/lego-obtain-cert.sh @@ -0,0 +1,50 @@ +#!/bin/bash + +# Lego SSL certificate obtainment script for CMC Sales +# Usage: ./scripts/lego-obtain-cert.sh [domain] [email] + +set -e + +DOMAIN=${1} +EMAIL=${2} + +if [ -z "$DOMAIN" ] || [ -z "$EMAIL" ]; then + echo "Usage: $0 " + echo "Example: $0 cmc.springupsoftware.com admin@springupsoftware.com" + exit 1 +fi + +echo "Obtaining SSL certificate for domain: $DOMAIN" +echo "Email: $EMAIL" + +# Check if lego container is running +if ! docker ps | grep -q "cmc-lego"; then + echo "ERROR: Lego container is not running. Please start it first with 'make proxy'" + exit 1 +fi + +# Run lego to obtain certificate +docker exec cmc-lego lego \ + --email="$EMAIL" \ + --domains="$DOMAIN" \ + --http \ + --http.webroot="/data/acme-challenge" \ + --path="/data" \ + --accept-tos \ + run + +if [ $? -eq 0 ]; then + echo "Certificate obtained successfully for $DOMAIN" + + # Copy certificates to the expected nginx locations + docker exec cmc-lego cp "/data/certificates/$DOMAIN.crt" "/data/certificates/$DOMAIN.crt" + docker exec cmc-lego cp "/data/certificates/$DOMAIN.key" "/data/certificates/$DOMAIN.key" + + # Reload nginx + docker exec cmc-nginx-proxy nginx -s reload + + echo "Nginx reloaded with new certificate" +else + echo "ERROR: Failed to obtain certificate for $DOMAIN" + exit 1 +fi \ No newline at end of file diff --git a/scripts/lego-renew-cert.sh b/scripts/lego-renew-cert.sh new file mode 100755 index 00000000..f319ac52 --- /dev/null +++ b/scripts/lego-renew-cert.sh @@ -0,0 +1,64 @@ +#!/bin/bash + +# Lego SSL certificate renewal script for CMC Sales +# Usage: ./scripts/lego-renew-cert.sh [domain] + +set -e + +DOMAIN=${1} + +if [ -z "$DOMAIN" ]; then + echo "Usage: $0 " + echo "Example: $0 cmc.springupsoftware.com" + echo "" + echo "Or run without domain to renew all certificates:" + echo "$0 all" + exit 1 +fi + +echo "Renewing SSL certificate(s)..." + +# Check if lego container is running +if ! docker ps | grep -q "cmc-lego"; then + echo "ERROR: Lego container is not running. Please start it first with 'make proxy'" + exit 1 +fi + +if [ "$DOMAIN" = "all" ]; then + echo "Renewing all certificates..." + # Renew all certificates + docker exec cmc-lego lego \ + --http \ + --http.webroot="/data/acme-challenge" \ + --path="/data" \ + renew \ + --days=30 +else + echo "Renewing certificate for domain: $DOMAIN" + # Renew specific domain + docker exec cmc-lego lego \ + --domains="$DOMAIN" \ + --http \ + --http.webroot="/data/acme-challenge" \ + --path="/data" \ + renew \ + --days=30 +fi + +if [ $? -eq 0 ]; then + echo "Certificate renewal completed successfully" + + # Reload nginx to use new certificates + docker exec cmc-nginx-proxy nginx -s reload + echo "Nginx reloaded with renewed certificates" + + # Show certificate info + echo "" + echo "Certificate information:" + docker exec cmc-lego lego \ + --path="/data" \ + list +else + echo "ERROR: Certificate renewal failed" + exit 1 +fi \ No newline at end of file diff --git a/scripts/manage-staging-caddy.sh b/scripts/manage-staging-caddy.sh new file mode 100755 index 00000000..1f355a95 --- /dev/null +++ b/scripts/manage-staging-caddy.sh @@ -0,0 +1,194 @@ +#!/bin/bash + +# Management script for staging environment with Caddy and containers + +set -e + +COMPOSE_FILE="docker-compose.caddy-staging.yml" + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +function show_help { + echo "CMC Sales Staging Management (Caddy + Containers)" + echo "" + echo "Usage: $0 [command]" + echo "" + echo "Commands:" + echo " status Show status of all services" + echo " start Start staging containers" + echo " stop Stop staging containers" + echo " restart Restart staging containers" + echo " logs Show container logs" + echo " caddy-logs Show Caddy logs" + echo " backup Backup staging database" + echo " shell-php Enter PHP container shell" + echo " shell-go Enter Go container shell" + echo " shell-db Enter database shell" + echo " update Pull latest code and rebuild" + echo " clean Stop and remove containers" + echo "" +} + +function check_status { + echo -e "${GREEN}=== Service Status ===${NC}" + echo "" + + # Caddy status + echo -e "${YELLOW}Caddy Status:${NC}" + if systemctl is-active --quiet caddy; then + echo -e " ${GREEN}● Caddy is running${NC}" + echo -n " Config: " + caddy version + else + echo -e " ${RED}● Caddy is not running${NC}" + fi + echo "" + + # Container status + echo -e "${YELLOW}Container Status:${NC}" + docker compose -f $COMPOSE_FILE ps + echo "" + + # Port status + echo -e "${YELLOW}Port Status:${NC}" + sudo netstat -tlnp | grep -E ":(80|443|8091|8092|3307) " | grep LISTEN || echo " No staging ports found" + echo "" + + # Health checks + echo -e "${YELLOW}Health Checks:${NC}" + echo -n " PHP container (8091): " + curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8091 || echo "Failed" + echo -n " Go container (8092): " + curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8092/api/v1/health || echo "Failed" + echo -n " Public HTTPS: " + curl -s -o /dev/null -w "%{http_code}\n" https://staging.cmc.springupsoftware.com/health || echo "Not accessible" +} + +function start_services { + echo -e "${GREEN}Starting staging services...${NC}" + docker compose -f $COMPOSE_FILE up -d + echo "Waiting for services to be ready..." + sleep 10 + check_status +} + +function stop_services { + echo -e "${YELLOW}Stopping staging services...${NC}" + docker compose -f $COMPOSE_FILE stop +} + +function restart_services { + echo -e "${YELLOW}Restarting staging services...${NC}" + docker compose -f $COMPOSE_FILE restart + echo "Waiting for services to be ready..." + sleep 10 + check_status +} + +function show_logs { + echo -e "${GREEN}Showing container logs (Ctrl+C to exit)...${NC}" + docker compose -f $COMPOSE_FILE logs -f +} + +function show_caddy_logs { + echo -e "${GREEN}Showing Caddy logs (Ctrl+C to exit)...${NC}" + sudo journalctl -u caddy -f +} + +function backup_database { + echo -e "${GREEN}Backing up staging database...${NC}" + ./scripts/backup-db.sh staging +} + +function shell_php { + echo -e "${GREEN}Entering PHP container shell...${NC}" + docker exec -it cmc-php-staging /bin/bash +} + +function shell_go { + echo -e "${GREEN}Entering Go container shell...${NC}" + docker exec -it cmc-go-staging /bin/sh +} + +function shell_db { + echo -e "${GREEN}Entering database shell...${NC}" + docker exec -it cmc-db-staging mysql -u cmc_staging -p cmc_staging +} + +function update_deployment { + echo -e "${GREEN}Updating staging deployment...${NC}" + + # Pull latest code + echo "Pulling latest code..." + git pull origin main + + # Rebuild containers + echo "Rebuilding containers..." + docker compose -f $COMPOSE_FILE build --no-cache + + # Restart services + echo "Restarting services..." + docker compose -f $COMPOSE_FILE up -d + + echo "Waiting for services to be ready..." + sleep 10 + check_status +} + +function clean_deployment { + echo -e "${RED}WARNING: This will remove all staging containers and volumes!${NC}" + read -p "Are you sure? (yes/no): " confirm + if [ "$confirm" = "yes" ]; then + docker compose -f $COMPOSE_FILE down -v + echo "Staging environment cleaned" + else + echo "Cancelled" + fi +} + +# Main script logic +case "$1" in + status) + check_status + ;; + start) + start_services + ;; + stop) + stop_services + ;; + restart) + restart_services + ;; + logs) + show_logs + ;; + caddy-logs) + show_caddy_logs + ;; + backup) + backup_database + ;; + shell-php) + shell_php + ;; + shell-go) + shell_go + ;; + shell-db) + shell_db + ;; + update) + update_deployment + ;; + clean) + clean_deployment + ;; + *) + show_help + ;; +esac \ No newline at end of file diff --git a/scripts/quick-rebuild-staging.sh b/scripts/quick-rebuild-staging.sh new file mode 100755 index 00000000..9bcfaadf --- /dev/null +++ b/scripts/quick-rebuild-staging.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +# Quick rebuild script for staging + +echo "=== Quick Staging Rebuild ===" + +# Stop containers +echo "Stopping containers..." +docker compose -f docker-compose.caddy-staging-ubuntu.yml down + +# Remove old images +echo "Cleaning up..." +docker system prune -f + +# Build and start +echo "Building and starting..." +docker compose -f docker-compose.caddy-staging-ubuntu.yml build --no-cache +docker compose -f docker-compose.caddy-staging-ubuntu.yml up -d + +# Wait for startup +echo "Waiting for containers to start..." +sleep 15 + +# Test +echo "Testing setup..." +./scripts/test-php-setup.sh \ No newline at end of file diff --git a/scripts/restore-db.sh b/scripts/restore-db.sh new file mode 100755 index 00000000..61fda52d --- /dev/null +++ b/scripts/restore-db.sh @@ -0,0 +1,78 @@ +#!/bin/bash + +# Database restore script for CMC Sales +# Usage: ./scripts/restore-db.sh [staging|production] + +set -e + +ENVIRONMENT=${1} +BACKUP_FILE=${2} + +if [ -z "$ENVIRONMENT" ] || [ -z "$BACKUP_FILE" ]; then + echo "Usage: $0 [staging|production] " + echo "Example: $0 staging /var/backups/cmc-sales/backup_staging_20240101-120000.sql.gz" + exit 1 +fi + +if [ ! -f "$BACKUP_FILE" ]; then + echo "ERROR: Backup file not found: $BACKUP_FILE" + exit 1 +fi + +case $ENVIRONMENT in + staging) + CONTAINER="cmc-db-staging" + DB_NAME="cmc_staging" + DB_USER="cmc_staging" + ;; + production) + CONTAINER="cmc-db-production" + DB_NAME="cmc" + DB_USER="cmc" + ;; + *) + echo "ERROR: Invalid environment. Use 'staging' or 'production'" + exit 1 + ;; +esac + +echo "WARNING: This will COMPLETELY REPLACE the $ENVIRONMENT database!" +echo "Container: $CONTAINER" +echo "Database: $DB_NAME" +echo "Backup file: $BACKUP_FILE" +echo "" +read -p "Are you sure you want to continue? (yes/no): " confirm + +if [ "$confirm" != "yes" ]; then + echo "Restore cancelled." + exit 0 +fi + +echo "Creating backup of current database before restore..." +CURRENT_BACKUP="/tmp/pre_restore_backup_${ENVIRONMENT}_$(date +%Y%m%d-%H%M%S).sql.gz" +docker exec -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ + $CONTAINER \ + mysqldump --single-transaction --routines --triggers --user=$DB_USER $DB_NAME | \ + gzip > "$CURRENT_BACKUP" +echo "Current database backed up to: $CURRENT_BACKUP" + +echo "Restoring database from: $BACKUP_FILE" + +# Drop and recreate database +docker exec -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_ROOT_PASSWORD | cut -d= -f2)" \ + $CONTAINER \ + mysql --user=root -e "DROP DATABASE IF EXISTS $DB_NAME; CREATE DATABASE $DB_NAME;" + +# Restore from backup +if [[ "$BACKUP_FILE" == *.gz ]]; then + gunzip < "$BACKUP_FILE" | docker exec -i -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ + $CONTAINER \ + mysql --user=$DB_USER $DB_NAME +else + docker exec -i -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ + $CONTAINER \ + mysql --user=$DB_USER $DB_NAME < "$BACKUP_FILE" +fi + +echo "Database restore completed successfully!" +echo "Previous database backed up to: $CURRENT_BACKUP" \ No newline at end of file diff --git a/scripts/setup-caddy-auth.sh b/scripts/setup-caddy-auth.sh new file mode 100755 index 00000000..fa401cb8 --- /dev/null +++ b/scripts/setup-caddy-auth.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +# Setup Caddy basic authentication +# Usage: ./scripts/setup-caddy-auth.sh + +set -e + +echo "Setting up Caddy basic authentication..." +echo "" + +# Get username +read -p "Enter username (default: admin): " username +username=${username:-admin} + +# Get password +read -s -p "Enter password: " password +echo "" +read -s -p "Confirm password: " password_confirm +echo "" + +if [ "$password" != "$password_confirm" ]; then + echo "Passwords do not match!" + exit 1 +fi + +# Generate password hash +echo "" +echo "Generating password hash..." +hash=$(caddy hash-password --plaintext "$password") + +echo "" +echo "Authentication setup complete!" +echo "" +echo "Add this to your Caddyfile basicauth section:" +echo " $username $hash" +echo "" +echo "Example:" +echo " basicauth /* {" +echo " $username $hash" +echo " }" +echo "" +echo "You can add multiple users by adding more lines in the basicauth block." \ No newline at end of file diff --git a/scripts/setup-lego-certs.sh b/scripts/setup-lego-certs.sh new file mode 100755 index 00000000..022c7c29 --- /dev/null +++ b/scripts/setup-lego-certs.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +# Initial setup script for Lego SSL certificates +# Usage: ./scripts/setup-lego-certs.sh + +set -e + +EMAIL=${1} + +if [ -z "$EMAIL" ]; then + echo "Usage: $0 " + echo "Example: $0 admin@springupsoftware.com" + exit 1 +fi + +echo "Setting up SSL certificates for CMC Sales using Lego" +echo "Email: $EMAIL" + +# Ensure proxy is running +if ! docker ps | grep -q "cmc-lego"; then + echo "Starting proxy services..." + docker compose -f docker-compose.proxy.yml up -d + echo "Waiting for services to be ready..." + sleep 10 +fi + +# Obtain certificate for production domain +echo "" +echo "=== Obtaining certificate for production domain ===" +./scripts/lego-obtain-cert.sh cmc.springupsoftware.com "$EMAIL" + +# Obtain certificate for staging domain +echo "" +echo "=== Obtaining certificate for staging domain ===" +./scripts/lego-obtain-cert.sh staging.cmc.springupsoftware.com "$EMAIL" + +echo "" +echo "=== Certificate setup complete ===" +echo "" +echo "Certificates obtained for:" +echo " - cmc.springupsoftware.com" +echo " - staging.cmc.springupsoftware.com" +echo "" +echo "Testing HTTPS endpoints..." + +# Test the endpoints +sleep 5 +echo "Testing production HTTPS..." +curl -I https://cmc.springupsoftware.com/health || echo "Production endpoint not yet accessible" + +echo "Testing staging HTTPS..." +curl -I https://staging.cmc.springupsoftware.com/health || echo "Staging endpoint not yet accessible" + +echo "" +echo "SSL setup complete! Remember to set up auto-renewal in cron:" +echo "0 2 * * * /opt/cmc-sales/scripts/lego-renew-cert.sh all" \ No newline at end of file diff --git a/scripts/setup-staging-native.sh b/scripts/setup-staging-native.sh new file mode 100755 index 00000000..a744a390 --- /dev/null +++ b/scripts/setup-staging-native.sh @@ -0,0 +1,149 @@ +#!/bin/bash + +# Setup script for running staging environment natively with Caddy +# This runs PHP and Go applications directly on the host + +set -e + +if [ "$EUID" -ne 0 ]; then + echo "Please run as root (use sudo)" + exit 1 +fi + +echo "Setting up CMC Sales staging environment (native)..." + +# 1. Install dependencies +echo "Installing dependencies..." +apt update +apt install -y \ + php7.4-fpm \ + php7.4-mysql \ + php7.4-gd \ + php7.4-curl \ + php7.4-mbstring \ + php7.4-xml \ + php7.4-zip \ + mariadb-server \ + golang-go \ + git \ + supervisor + +# 2. Create directories +echo "Creating directories..." +mkdir -p /var/www/cmc-sales-staging +mkdir -p /var/log/cmc-staging +mkdir -p /var/run/cmc-staging +mkdir -p /etc/cmc-staging + +# 3. Clone or copy application +echo "Setting up application code..." +if [ -d "/home/cmc/cmc-sales" ]; then + cp -r /home/cmc/cmc-sales/* /var/www/cmc-sales-staging/ +else + echo "Please clone the repository to /home/cmc/cmc-sales first" + exit 1 +fi + +# 4. Setup PHP-FPM pool for staging +echo "Configuring PHP-FPM..." +cat > /etc/php/7.4/fpm/pool.d/staging.conf << 'EOF' +[staging] +user = www-data +group = www-data +listen = /run/php/php7.4-fpm-staging.sock +listen.owner = www-data +listen.group = caddy +listen.mode = 0660 + +pm = dynamic +pm.max_children = 10 +pm.start_servers = 2 +pm.min_spare_servers = 1 +pm.max_spare_servers = 3 +pm.max_requests = 500 + +; Environment variables +env[APP_ENV] = staging +env[DB_HOST] = localhost +env[DB_PORT] = 3307 +env[DB_NAME] = cmc_staging +env[DB_USER] = cmc_staging + +; PHP settings +php_admin_value[error_log] = /var/log/cmc-staging/php-error.log +php_admin_flag[log_errors] = on +php_admin_value[memory_limit] = 256M +php_admin_value[upload_max_filesize] = 50M +php_admin_value[post_max_size] = 50M +EOF + +# 5. Setup MariaDB for staging +echo "Configuring MariaDB..." +mysql -e "CREATE DATABASE IF NOT EXISTS cmc_staging;" +mysql -e "CREATE USER IF NOT EXISTS 'cmc_staging'@'localhost' IDENTIFIED BY '${DB_PASSWORD_STAGING:-staging_password}';" +mysql -e "GRANT ALL PRIVILEGES ON cmc_staging.* TO 'cmc_staging'@'localhost';" +mysql -e "FLUSH PRIVILEGES;" + +# 6. Setup Go application service +echo "Setting up Go application service..." +cat > /etc/systemd/system/cmc-go-staging.service << 'EOF' +[Unit] +Description=CMC Go Application - Staging +After=network.target mariadb.service + +[Service] +Type=simple +User=www-data +Group=www-data +WorkingDirectory=/var/www/cmc-sales-staging/go-app +Environment="PORT=8092" +Environment="APP_ENV=staging" +Environment="DB_HOST=localhost" +Environment="DB_PORT=3306" +Environment="DB_USER=cmc_staging" +Environment="DB_NAME=cmc_staging" +ExecStart=/usr/local/bin/cmc-go-staging +Restart=always +RestartSec=10 + +[Install] +WantedBy=multi-user.target +EOF + +# 7. Build Go application +echo "Building Go application..." +cd /var/www/cmc-sales-staging/go-app +go mod download +go build -o /usr/local/bin/cmc-go-staging cmd/server/main.go + +# 8. Set permissions +echo "Setting permissions..." +chown -R www-data:www-data /var/www/cmc-sales-staging +chmod -R 755 /var/www/cmc-sales-staging +chmod -R 777 /var/www/cmc-sales-staging/app/tmp +chmod -R 777 /var/www/cmc-sales-staging/app/webroot/pdf +chmod -R 777 /var/www/cmc-sales-staging/app/webroot/attachments_files + +# 9. Create Caddy user in www-data group +usermod -a -G www-data caddy + +# 10. Copy Caddyfile +cp /home/cmc/cmc-sales/Caddyfile.staging-native /etc/caddy/Caddyfile + +# 11. Start services +echo "Starting services..." +systemctl restart php7.4-fpm +systemctl enable cmc-go-staging +systemctl start cmc-go-staging +systemctl reload caddy + +echo "" +echo "Staging environment setup complete!" +echo "" +echo "Next steps:" +echo "1. Set database password: export DB_PASSWORD_STAGING='your_password'" +echo "2. Update /etc/caddy/Caddyfile with correct database password" +echo "3. Import database: mysql cmc_staging < backup.sql" +echo "4. Restart services: systemctl restart caddy cmc-go-staging" +echo "" +echo "Access staging at: https://staging.cmc.springupsoftware.com" \ No newline at end of file diff --git a/scripts/test-php-setup.sh b/scripts/test-php-setup.sh new file mode 100755 index 00000000..e744f94a --- /dev/null +++ b/scripts/test-php-setup.sh @@ -0,0 +1,77 @@ +#!/bin/bash + +# Test script to verify PHP container setup + +echo "=== Testing PHP Container Setup ===" +echo "" + +# Test 1: Check if containers are running +echo "1. Checking container status..." +docker ps | grep -E "(cmc-php-staging|cmc-go-staging|cmc-db-staging)" || echo "No staging containers running" +echo "" + +# Test 2: Test PHP container response +echo "2. Testing PHP container (port 8091)..." +response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8091/ 2>/dev/null) +if [ "$response" = "200" ]; then + echo "✓ PHP container responding (HTTP $response)" +else + echo "✗ PHP container not responding (HTTP $response)" + echo "Checking PHP container logs..." + docker logs cmc-php-staging --tail 20 +fi +echo "" + +# Test 3: Test Go container response +echo "3. Testing Go container (port 8092)..." +response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8092/api/v1/health 2>/dev/null) +if [ "$response" = "200" ]; then + echo "✓ Go container responding (HTTP $response)" +else + echo "✗ Go container not responding (HTTP $response)" +fi +echo "" + +# Test 4: Check database connection +echo "4. Testing database connection..." +if docker exec cmc-db-staging mysql -u cmc_staging -pcmc_staging -e "SELECT 1;" cmc_staging &>/dev/null; then + echo "✓ Database connection working" +else + echo "✗ Database connection failed" +fi +echo "" + +# Test 5: Test CakePHP specific endpoint +echo "5. Testing CakePHP structure..." +response=$(curl -s http://localhost:8091/test_php.php 2>/dev/null | head -n 5) +if [[ $response == *"PHP"* ]]; then + echo "✓ CakePHP structure accessible" + echo "Sample response: $(echo "$response" | tr '\n' ' ' | cut -c1-100)..." +else + echo "✗ CakePHP structure issue" + # Check if we can at least get a response + curl -v http://localhost:8091/ 2>&1 | head -n 20 +fi +echo "" + +# Test 6: Check file permissions +echo "6. Checking file permissions in container..." +docker exec cmc-php-staging ls -la /var/www/cmc-sales/ | head -n 10 +echo "" + +# Test 7: Check CakePHP core files +echo "7. Checking CakePHP core files..." +if docker exec cmc-php-staging test -f /var/www/cmc-sales/cake/bootstrap.php; then + echo "✓ CakePHP core files present" +else + echo "✗ CakePHP core files missing" + docker exec cmc-php-staging find /var/www/cmc-sales -name "*.php" | head -n 10 +fi +echo "" + +echo "Test complete!" +echo "" +echo "If issues persist:" +echo "- Check logs: docker logs cmc-php-staging" +echo "- Rebuild: make restart-staging" +echo "- Check volumes: docker volume ls | grep staging" \ No newline at end of file From 97dbeb6a1c9b0f498e01c696fc9a0369dc3466a6 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Fri, 8 Aug 2025 13:39:37 +1000 Subject: [PATCH 10/17] Revert "Giant changes to make it work on php7" This reverts commit 144a7a0fb1e7c90cb7d06a11d35eaee353e86561. --- Dockerfile.ubuntu-php | 6 +- app/.DS_Store | Bin 6148 -> 0 bytes app/config/database.php | 17 +- app/config/database_stg.php | 8 +- app/config/php7_compat.php | 8 - app/webroot/.DS_Store | Bin 8196 -> 0 bytes app/webroot/test_setup.php | 111 ---------- cake/console/error.php | 2 +- cake/console/libs/console.php | 2 +- cake/console/libs/schema.php | 4 +- cake/console/libs/shell.php | 8 +- cake/console/libs/tasks/controller.php | 2 +- cake/console/libs/tasks/project.php | 8 +- cake/console/libs/tasks/view.php | 2 +- cake/dispatcher.php | 6 +- cake/libs/cache.php | 8 +- cake/libs/cache/file.php | 2 +- cake/libs/cache/memcache.php | 2 +- cake/libs/class_registry.php | 6 +- cake/libs/configure.php | 12 +- cake/libs/controller/component.php | 6 +- cake/libs/controller/components/acl.php | 6 +- cake/libs/controller/components/auth.php | 2 +- cake/libs/controller/components/cookie.php | 2 +- cake/libs/controller/components/email.php | 4 +- .../controller/components/request_handler.php | 2 +- cake/libs/controller/components/security.php | 2 +- cake/libs/controller/controller.php | 6 +- cake/libs/controller/scaffold.php | 2 +- cake/libs/debugger.php | 4 +- cake/libs/error.php | 6 +- cake/libs/file.php | 4 +- cake/libs/flay.php | 2 +- cake/libs/folder.php | 2 +- cake/libs/i18n.php | 6 +- cake/libs/inflector.php | 4 +- cake/libs/l10n.php | 2 +- cake/libs/magic_db.php | 10 +- cake/libs/model/behavior.php | 6 +- cake/libs/model/connection_manager.php | 8 +- cake/libs/model/datasources/datasource.php | 2 +- cake/libs/model/schema.php | 6 +- cake/libs/multibyte.php | 4 +- cake/libs/object.php | 5 +- cake/libs/overloadable_php4.php | 4 +- cake/libs/overloadable_php5.php | 4 +- cake/libs/router.php | 4 +- cake/libs/security.php | 4 +- cake/libs/session.php | 2 +- cake/libs/set.php | 2 +- cake/libs/socket.php | 2 +- cake/libs/string.php | 4 +- cake/libs/validation.php | 4 +- cake/libs/view/helpers/cache.php | 2 +- cake/libs/view/helpers/js.php | 2 +- cake/libs/view/helpers/xml.php | 4 +- cake/libs/view/view.php | 4 +- cake/libs/xml.php | 8 +- cake/tests/cases/console/cake.test.php | 12 +- cake/tests/cases/console/libs/acl.test.php | 4 +- cake/tests/cases/console/libs/api.test.php | 4 +- cake/tests/cases/console/libs/schema.test.php | 18 +- cake/tests/cases/console/libs/shell.test.php | 4 +- .../cases/console/libs/tasks/extract.test.php | 4 +- .../cases/console/libs/tasks/test.test.php | 4 +- cake/tests/cases/dispatcher.test.php | 98 ++++----- cake/tests/cases/libs/cake_test_case.test.php | 14 +- .../cases/libs/cake_test_fixture.test.php | 24 +-- .../cases/libs/code_coverage_manager.test.php | 4 +- .../cases/libs/controller/component.test.php | 48 ++--- .../libs/controller/components/acl.test.php | 10 +- .../libs/controller/components/auth.test.php | 22 +- .../libs/controller/components/email.test.php | 4 +- .../controller/components/security.test.php | 2 +- .../controller/components/session.test.php | 48 ++--- .../cases/libs/controller/controller.test.php | 86 ++++---- .../controller/controller_merge_vars.test.php | 14 +- .../libs/controller/pages_controller.test.php | 2 +- .../cases/libs/controller/scaffold.test.php | 18 +- cake/tests/cases/libs/error.test.php | 4 +- cake/tests/cases/libs/file.test.php | 24 +-- cake/tests/cases/libs/folder.test.php | 60 +++--- cake/tests/cases/libs/http_socket.test.php | 4 +- cake/tests/cases/libs/l10n.test.php | 8 +- cake/tests/cases/libs/magic_db.test.php | 4 +- cake/tests/cases/libs/model/behavior.test.php | 4 +- .../cases/libs/model/behaviors/acl.test.php | 16 +- .../libs/model/behaviors/containable.test.php | 2 +- .../libs/model/behaviors/translate.test.php | 44 ++-- .../cases/libs/model/behaviors/tree.test.php | 120 +++++------ .../model/datasources/dbo/dbo_mysql.test.php | 8 +- .../model/datasources/dbo/dbo_oracle.test.php | 2 +- .../datasources/dbo/dbo_postgres.test.php | 12 +- .../model/datasources/dbo/dbo_sqlite.test.php | 4 +- .../model/datasources/dbo_source.test.php | 60 +++--- cake/tests/cases/libs/model/db_acl.test.php | 8 +- .../cases/libs/model/model_delete.test.php | 24 +-- .../libs/model/model_integration.test.php | 58 +++--- .../cases/libs/model/model_read.test.php | 94 ++++----- .../libs/model/model_validation.test.php | 4 +- .../cases/libs/model/model_write.test.php | 118 +++++------ cake/tests/cases/libs/model/schema.test.php | 2 +- cake/tests/cases/libs/object.test.php | 4 +- cake/tests/cases/libs/sanitize.test.php | 4 +- cake/tests/cases/libs/session.test.php | 2 +- cake/tests/cases/libs/test_manager.test.php | 8 +- .../cases/libs/view/helpers/ajax.test.php | 12 +- .../cases/libs/view/helpers/form.test.php | 12 +- .../cases/libs/view/helpers/html.test.php | 4 +- .../libs/view/helpers/javascript.test.php | 12 +- .../cases/libs/view/helpers/number.test.php | 2 +- .../libs/view/helpers/paginator.test.php | 10 +- .../cases/libs/view/helpers/rss.test.php | 4 +- .../cases/libs/view/helpers/xml.test.php | 4 +- cake/tests/cases/libs/view/theme.test.php | 2 +- cake/tests/cases/libs/view/view.test.php | 8 +- cake/tests/cases/libs/xml.test.php | 32 +-- cake/tests/lib/cake_test_case.php | 6 +- cake/tests/lib/cake_test_fixture.php | 4 +- cake/tests/lib/code_coverage_manager.php | 8 +- cake/tests/lib/test_manager.php | 44 ++-- .../components/other_component.php | 2 +- .../components/plugins_component.php | 2 +- .../components/test_plugin_component.php | 2 +- .../test_plugin_other_component.php | 2 +- conf/nginx-proxy.conf | 6 +- docker-compose.caddy-staging-ubuntu.yml | 14 +- docker-compose.proxy.yml | 68 ++++++ index.php | 6 - scripts/backup-db.sh | 56 ----- scripts/debug-php-container.sh | 57 ----- scripts/deploy-staging-caddy.sh | 127 ------------ scripts/fix-cakephp-compatibility.sh | 145 ------------- scripts/fix-cakephp-php7.sh | 16 -- scripts/install-caddy.sh | 50 ----- scripts/lego-list-certs.sh | 23 --- scripts/lego-obtain-cert.sh | 50 ----- scripts/lego-renew-cert.sh | 64 ------ scripts/manage-staging-caddy.sh | 194 ------------------ scripts/quick-rebuild-staging.sh | 26 --- scripts/restore-db.sh | 78 ------- scripts/setup-caddy-auth.sh | 42 ---- scripts/setup-lego-certs.sh | 56 ----- scripts/setup-staging-native.sh | 149 -------------- scripts/test-php-setup.sh | 77 ------- 145 files changed, 845 insertions(+), 2144 deletions(-) delete mode 100644 app/.DS_Store delete mode 100644 app/webroot/.DS_Store delete mode 100644 app/webroot/test_setup.php create mode 100644 docker-compose.proxy.yml delete mode 100755 scripts/backup-db.sh delete mode 100755 scripts/debug-php-container.sh delete mode 100755 scripts/deploy-staging-caddy.sh delete mode 100755 scripts/fix-cakephp-compatibility.sh delete mode 100755 scripts/fix-cakephp-php7.sh delete mode 100755 scripts/install-caddy.sh delete mode 100755 scripts/lego-list-certs.sh delete mode 100755 scripts/lego-obtain-cert.sh delete mode 100755 scripts/lego-renew-cert.sh delete mode 100755 scripts/manage-staging-caddy.sh delete mode 100755 scripts/quick-rebuild-staging.sh delete mode 100755 scripts/restore-db.sh delete mode 100755 scripts/setup-caddy-auth.sh delete mode 100755 scripts/setup-lego-certs.sh delete mode 100755 scripts/setup-staging-native.sh delete mode 100755 scripts/test-php-setup.sh diff --git a/Dockerfile.ubuntu-php b/Dockerfile.ubuntu-php index e92fffd1..cb5d7837 100644 --- a/Dockerfile.ubuntu-php +++ b/Dockerfile.ubuntu-php @@ -65,12 +65,8 @@ RUN chown -R www-data:www-data /var/www/cmc-sales \ # Set working directory WORKDIR /var/www/cmc-sales -# Copy CakePHP core and application -COPY cake/ /var/www/cmc-sales/cake/ +# Copy application (will be overridden by volume mount) COPY app/ /var/www/cmc-sales/app/ -COPY vendors/ /var/www/cmc-sales/vendors/ -COPY index.php /var/www/cmc-sales/ -COPY *.sh /var/www/cmc-sales/ # Expose port 80 EXPOSE 80 diff --git a/app/.DS_Store b/app/.DS_Store deleted file mode 100644 index 9e09c8d19f7e10af5ac6ede482cd13625d0dd00b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK%}T>S5Z-O8O({YS3VK`cS};Lt4_-p8FJMFuDz%|OgE3o@)Er77cYPsW#OHBl zcOz7D@FZeqVDrt+&+g6#*&oIjAI_&PV>V;Vf`-UZsSz~Sx*8@Jk*hHzlPnL4Y!<{d z1N}u4uD#6)7P5e)u=>yS%K$uY!7Prl+;QG{quJWnY+IJqwQl_fS@`)RpJ&5KdX2pc zDdV8hC&6VD7Grz+R3`Z(O2SknMAHyLZmyzaDvP0aJDQR4g$-4E%%v+#duqM9*NUQEeUY!Rs^nTZky2<68nz81xL5 z8o>j?bt<4v<>raObvoFEiSrDW8g)A3YGxS6%v?QQxSAd8LWMK#X{0YPKn$!h(9~TU z&;K*{WojS!t0~kY28e-w#sF`P{Lv7KGH2_z^6;z`(C(n2U|fj`2 'cmc', 'prefix' => '', ); - - function __construct() { - // Use environment-specific database settings if APP_ENV is set - if (isset($_ENV['APP_ENV']) && $_ENV['APP_ENV'] == 'staging') { - $this->default = array( - 'driver' => 'mysql', - 'persistent' => false, - 'host' => 'db-staging', - 'login' => 'cmc_staging', - 'password' => 'staging_password', - 'database' => 'cmc_staging', - 'prefix' => '', - ); - } - } } diff --git a/app/config/database_stg.php b/app/config/database_stg.php index e0888f2b..1ee8c813 100644 --- a/app/config/database_stg.php +++ b/app/config/database_stg.php @@ -5,10 +5,10 @@ var $default = array( 'driver' => 'mysql', 'persistent' => false, - 'host' => 'db-staging', - 'login' => 'cmc_staging', - 'password' => 'staging_password', - 'database' => 'cmc_staging', + 'host' => '172.17.0.1', + 'login' => 'staging', + 'password' => 'stagingmoopwoopVerySecure', + 'database' => 'staging', 'prefix' => '', ); } diff --git a/app/config/php7_compat.php b/app/config/php7_compat.php index 639f68a2..3bab09f6 100644 --- a/app/config/php7_compat.php +++ b/app/config/php7_compat.php @@ -93,12 +93,4 @@ if (!function_exists('mysql_connect')) { function mysql_real_escape_string($unescaped_string, $link_identifier = null) { return mysqli_real_escape_string($link_identifier, $unescaped_string); } -} - -// Create alias for Object class to fix PHP 7 reserved word issue -// This should be included AFTER CakePHP's Object class is defined -function create_object_alias() { - if (class_exists('CakeObject') && !class_exists('Object', false)) { - class_alias('CakeObject', 'Object'); - } } \ No newline at end of file diff --git a/app/webroot/.DS_Store b/app/webroot/.DS_Store deleted file mode 100644 index 3e71061e36612cfaf9b50dc42a81d5baac2fc11d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMTWl0n7(U;$z?p&4X(`(ly0WpNSPPT_1uT;74a&8KZD}d!I=eH_k?Bm`ncaef zSff5@)R=gSCKBW2!3Rmapou2x119K$52i6<)E6T@s8JvFMgKErmP>&rgOV^One(0h zKj%M}|9t(T?_{g9$ZU^>DniQ%h*vhWH( zD6RluqOvXugsBMA5l%^@8cL9+gwhnz6$8?o^r@&_I>IT5(wrf>d>|Sb(G3OR=+u8I zY|fCD80WDEVh>#E0TDhGY=W8WKyLEF`@3WNL0j8bP%0{C&7Q+KpUdycjCqrpzzB+d zw^7(9q(RSfa^m3bCC$s0x3AmS)wgx$bk+Q7U8~jVhD)|@=NxNj(l&#!y@sE+T+?DG1+@mF>Y!_kTcK5=KGDeaW| z=@oJxE^3!ULGX zLwFcZ;5j^x7w{t9z}t8S@8V;e#%K5(-{MD{#ZUMHe<@W;wW2FEO0BY3S*FluJdu=g zR18bGoGa~Aib9;CBKkz99JyRnBsXvAzc!-c%sdeXHMI-s7TzF&qoXr@jzW@jWu9Hg z-;lBw?P*BaFhpi@Em7alxM;DK93oCzhi67vIr{WDg1vlNv|f_ZlKL!Sy%cX+O5$u{ zycBP3NhWngKgp%IVr5d(D=3WA>Bjnogw~?1RaG5fN9)#WnqEl(rH10hJ4j?AmZjX) zO+AV5_!mTdi+#X8VW-(N5%nzlndtd9IOd~{Xn8Z1;Wo5lIZ<;xZbxTG&n-mGZP<=M z>>+~gC5q-@;ULCfqW~X4NYe*Hnm&Rj@f4oMGk6xq@iJb)t9T8s;{-m$DM`F@blg@Z zqC|Xpo{ptV!F4?MAZg0vy|{5KT}=;E$j%$Y{lD+Z-~X@X6ym;P55yk$pFM!e-b`;d zP2x%~VR6?^(Q^+yB8hfW5CakePHP Setup Test"; - -// Test 1: PHP Version -echo "

      PHP Information

      "; -echo "

      PHP Version: " . PHP_VERSION . "

      "; -echo "

      Server API: " . php_sapi_name() . "

      "; - -// Test 2: Required Extensions -echo "

      PHP Extensions

      "; -$extensions = ['mysql', 'mysqli', 'gd', 'curl', 'mbstring']; -foreach ($extensions as $ext) { - $loaded = extension_loaded($ext); - echo "

      $ext: " . ($loaded ? '✓ Loaded' : '✗ Not Loaded') . "

      "; -} - -// Test 3: CakePHP Constants -echo "

      CakePHP Constants

      "; -$constants = ['ROOT', 'APP_DIR', 'CAKE_CORE_INCLUDE_PATH', 'WWW_ROOT']; -foreach ($constants as $const) { - if (defined($const)) { - echo "

      $const: " . constant($const) . "

      "; - } else { - echo "

      $const: ✗ Not defined

      "; - } -} - -// Test 4: File System -echo "

      File System

      "; -$paths = [ - '/var/www/cmc-sales', - '/var/www/cmc-sales/cake', - '/var/www/cmc-sales/app', - '/var/www/cmc-sales/app/webroot' -]; - -foreach ($paths as $path) { - $exists = file_exists($path); - $readable = is_readable($path); - echo "

      $path: " . - ($exists ? '✓ Exists' : '✗ Missing') . - ($readable ? ', ✓ Readable' : ', ✗ Not readable') . "

      "; -} - -// Test 5: CakePHP Core -echo "

      CakePHP Core Test

      "; -$cake_bootstrap = '/var/www/cmc-sales/cake/bootstrap.php'; -if (file_exists($cake_bootstrap)) { - echo "

      CakePHP Bootstrap: ✓ Found at $cake_bootstrap

      "; - - // Try to include it - try { - if (!defined('CAKE_CORE_INCLUDE_PATH')) { - define('CAKE_CORE_INCLUDE_PATH', '/var/www/cmc-sales'); - } - if (!defined('ROOT')) { - define('ROOT', '/var/www/cmc-sales'); - } - if (!defined('APP_DIR')) { - define('APP_DIR', 'app'); - } - if (!defined('DS')) { - define('DS', DIRECTORY_SEPARATOR); - } - - echo "

      Include Test: Ready to include CakePHP

      "; - // Note: We don't actually include it here to avoid conflicts - - } catch (Exception $e) { - echo "

      Include Test: ✗ Error - " . $e->getMessage() . "

      "; - } -} else { - echo "

      CakePHP Bootstrap: ✗ Not found

      "; -} - -// Test 6: Database -echo "

      Database Test

      "; -$db_host = $_ENV['DB_HOST'] ?? 'db-staging'; -$db_user = $_ENV['DB_USER'] ?? 'cmc_staging'; -$db_pass = $_ENV['DB_PASSWORD'] ?? ''; -$db_name = $_ENV['DB_NAME'] ?? 'cmc_staging'; - -echo "

      DB Host: $db_host

      "; -echo "

      DB User: $db_user

      "; -echo "

      DB Name: $db_name

      "; - -if (function_exists('mysqli_connect')) { - $conn = @mysqli_connect($db_host, $db_user, $db_pass, $db_name); - if ($conn) { - echo "

      Database Connection: ✓ Connected

      "; - mysqli_close($conn); - } else { - echo "

      Database Connection: ✗ Failed - " . mysqli_connect_error() . "

      "; - } -} else { - echo "

      Database Connection: ✗ MySQLi not available

      "; -} - -echo "

      Server Information

      "; -echo "
      ";
      -echo "Document Root: " . $_SERVER['DOCUMENT_ROOT'] . "\n";
      -echo "Script Name: " . $_SERVER['SCRIPT_NAME'] . "\n";
      -echo "Working Directory: " . getcwd() . "\n";
      -echo "
      "; - -echo "

      Generated at: " . date('Y-m-d H:i:s') . "

      "; -?> \ No newline at end of file diff --git a/cake/console/error.php b/cake/console/error.php index c47367a1..9c88a40b 100755 --- a/cake/console/error.php +++ b/cake/console/error.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.console */ -class ErrorHandler extends CakeObject { +class ErrorHandler extends Object { /** * Standard output stream. * diff --git a/cake/console/libs/console.php b/cake/console/libs/console.php index 5afd5ed4..19b07509 100755 --- a/cake/console/libs/console.php +++ b/cake/console/libs/console.php @@ -64,7 +64,7 @@ class ConsoleShell extends Shell { foreach ($this->models as $model) { $class = Inflector::camelize(r('.php', '', $model)); $this->models[$model] = $class; - $this->{$class} = new $class(); + $this->{$class} =& new $class(); } $this->out('Model classes:'); $this->out('--------------'); diff --git a/cake/console/libs/schema.php b/cake/console/libs/schema.php index 43c86b5e..36974eb5 100755 --- a/cake/console/libs/schema.php +++ b/cake/console/libs/schema.php @@ -79,7 +79,7 @@ class SchemaShell extends Shell { $connection = $this->params['connection']; } - $this->Schema = new CakeSchema(compact('name', 'path', 'file', 'connection')); + $this->Schema =& new CakeSchema(compact('name', 'path', 'file', 'connection')); } /** * Override main @@ -138,7 +138,7 @@ class SchemaShell extends Shell { $content['file'] = $this->params['file']; if ($snapshot === true) { - $Folder = new Folder($this->Schema->path); + $Folder =& new Folder($this->Schema->path); $result = $Folder->read(); $numToUse = false; diff --git a/cake/console/libs/shell.php b/cake/console/libs/shell.php index e847fb53..eed6bff8 100755 --- a/cake/console/libs/shell.php +++ b/cake/console/libs/shell.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.console.libs */ -class Shell extends CakeObject { +class Shell extends Object { /** * An instance of the ShellDispatcher object that loaded this script * @@ -200,7 +200,7 @@ class Shell extends CakeObject { */ function _loadDbConfig() { if (config('database') && class_exists('DATABASE_CONFIG')) { - $this->DbConfig = new DATABASE_CONFIG(); + $this->DbConfig =& new DATABASE_CONFIG(); return true; } $this->err('Database config could not be loaded'); @@ -222,7 +222,7 @@ class Shell extends CakeObject { } if ($this->uses === true && App::import('Model', 'AppModel')) { - $this->AppModel = new AppModel(false, false, false); + $this->AppModel =& new AppModel(false, false, false); return true; } @@ -290,7 +290,7 @@ class Shell extends CakeObject { } else { $this->taskNames[] = $taskName; if (!PHP5) { - $this->{$taskName} = new $taskClass($this->Dispatch); + $this->{$taskName} =& new $taskClass($this->Dispatch); } else { $this->{$taskName} = new $taskClass($this->Dispatch); } diff --git a/cake/console/libs/tasks/controller.php b/cake/console/libs/tasks/controller.php index e5e6d852..736522a8 100755 --- a/cake/console/libs/tasks/controller.php +++ b/cake/console/libs/tasks/controller.php @@ -252,7 +252,7 @@ class ControllerTask extends Shell { exit; } $actions = null; - $modelObj = new $currentModelName(); + $modelObj =& new $currentModelName(); $controllerPath = $this->_controllerPath($controllerName); $pluralName = $this->_pluralName($currentModelName); $singularName = Inflector::variable($currentModelName); diff --git a/cake/console/libs/tasks/project.php b/cake/console/libs/tasks/project.php index d61734a8..f7a0c302 100755 --- a/cake/console/libs/tasks/project.php +++ b/cake/console/libs/tasks/project.php @@ -192,7 +192,7 @@ class ProjectTask extends Shell { * @access public */ function securitySalt($path) { - $File = new File($path . 'config' . DS . 'core.php'); + $File =& new File($path . 'config' . DS . 'core.php'); $contents = $File->read(); if (preg_match('/([\\t\\x20]*Configure::write\\(\\\'Security.salt\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { if (!class_exists('Security')) { @@ -216,7 +216,7 @@ class ProjectTask extends Shell { */ function corePath($path) { if (dirname($path) !== CAKE_CORE_INCLUDE_PATH) { - $File = new File($path . 'webroot' . DS . 'index.php'); + $File =& new File($path . 'webroot' . DS . 'index.php'); $contents = $File->read(); if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { $result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents); @@ -227,7 +227,7 @@ class ProjectTask extends Shell { return false; } - $File = new File($path . 'webroot' . DS . 'test.php'); + $File =& new File($path . 'webroot' . DS . 'test.php'); $contents = $File->read(); if (preg_match('/([\\t\\x20]*define\\(\\\'CAKE_CORE_INCLUDE_PATH\\\',[\\t\\x20\'A-z0-9]*\\);)/', $contents, $match)) { $result = str_replace($match[0], "\t\tdefine('CAKE_CORE_INCLUDE_PATH', '" . CAKE_CORE_INCLUDE_PATH . "');", $contents); @@ -248,7 +248,7 @@ class ProjectTask extends Shell { * @access public */ function cakeAdmin($name) { - $File = new File(CONFIGS . 'core.php'); + $File =& new File(CONFIGS . 'core.php'); $contents = $File->read(); if (preg_match('%([/\\t\\x20]*Configure::write\(\'Routing.admin\',[\\t\\x20\'a-z]*\\);)%', $contents, $match)) { $result = str_replace($match[0], "\t" . 'Configure::write(\'Routing.admin\', \''.$name.'\');', $contents); diff --git a/cake/console/libs/tasks/view.php b/cake/console/libs/tasks/view.php index bc3b9ad2..cd60df61 100755 --- a/cake/console/libs/tasks/view.php +++ b/cake/console/libs/tasks/view.php @@ -290,7 +290,7 @@ class ViewTask extends Shell { $content = $this->getContent(); } $filename = $this->path . $this->controllerPath . DS . Inflector::underscore($action) . '.ctp'; - $Folder = new Folder($this->path . $this->controllerPath, true); + $Folder =& new Folder($this->path . $this->controllerPath, true); $errors = $Folder->errors(); if (empty($errors)) { $path = $Folder->slashTerm($Folder->pwd()); diff --git a/cake/dispatcher.php b/cake/dispatcher.php index d8765bf0..ca147f30 100755 --- a/cake/dispatcher.php +++ b/cake/dispatcher.php @@ -37,7 +37,7 @@ App::import('Core', array('Router', 'Controller')); * @package cake * @subpackage cake.cake */ -class Dispatcher extends CakeObject { +class Dispatcher extends Object { /** * Base URL * @@ -456,7 +456,7 @@ class Dispatcher extends CakeObject { $params = $this->_restructureParams($params, true); } $this->params = $params; - $controller = new $ctrlClass(); + $controller =& new $ctrlClass(); } return $controller; } @@ -679,7 +679,7 @@ class Dispatcher extends CakeObject { App::import('Core', 'View'); } $controller = null; - $view = new View($controller, false); + $view =& new View($controller, false); return $view->renderCache($filename, getMicrotime()); } } diff --git a/cake/libs/cache.php b/cake/libs/cache.php index 6a3c2ce6..aabd2795 100755 --- a/cake/libs/cache.php +++ b/cake/libs/cache.php @@ -29,7 +29,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Cache extends CakeObject { +class Cache extends Object { /** * Cache engine to use * @@ -68,7 +68,7 @@ class Cache extends CakeObject { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] = new Cache(); + $instance[0] =& new Cache(); } return $instance[0]; } @@ -148,7 +148,7 @@ class Cache extends CakeObject { if ($_this->__loadEngine($name) === false) { return false; } - $_this->_Engine[$name] = new $cacheClass(); + $_this->_Engine[$name] =& new $cacheClass(); } if ($_this->_Engine[$name]->init($settings)) { @@ -406,7 +406,7 @@ class Cache extends CakeObject { * @package cake * @subpackage cake.cake.libs */ -class CacheEngine extends CakeObject { +class CacheEngine extends Object { /** * settings of current engine instance * diff --git a/cake/libs/cache/file.php b/cake/libs/cache/file.php index fecf9794..abbd5a0e 100755 --- a/cake/libs/cache/file.php +++ b/cake/libs/cache/file.php @@ -86,7 +86,7 @@ class FileEngine extends CacheEngine { if (!class_exists('File')) { require LIBS . 'file.php'; } - $this->__File = new File($this->settings['path'] . DS . 'cake'); + $this->__File =& new File($this->settings['path'] . DS . 'cake'); } if (DIRECTORY_SEPARATOR === '\\') { diff --git a/cake/libs/cache/memcache.php b/cake/libs/cache/memcache.php index 5c4bbeb3..2d70a6e8 100755 --- a/cake/libs/cache/memcache.php +++ b/cake/libs/cache/memcache.php @@ -73,7 +73,7 @@ class MemcacheEngine extends CacheEngine { } if (!isset($this->__Memcache)) { $return = false; - $this->__Memcache = new Memcache(); + $this->__Memcache =& new Memcache(); foreach ($this->settings['servers'] as $server) { $parts = explode(':', $server); $host = $parts[0]; diff --git a/cake/libs/class_registry.php b/cake/libs/class_registry.php index 5b97257f..5ff5ec32 100755 --- a/cake/libs/class_registry.php +++ b/cake/libs/class_registry.php @@ -65,7 +65,7 @@ class ClassRegistry { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] = new ClassRegistry(); + $instance[0] =& new ClassRegistry(); } return $instance[0]; } @@ -137,7 +137,7 @@ class ClassRegistry { } if (class_exists($class) || App::import($type, $pluginPath . $class)) { - ${$class} = new $class($settings); + ${$class} =& new $class($settings); } elseif ($type === 'Model') { if ($plugin && class_exists($plugin . 'AppModel')) { $appModel = $plugin . 'AppModel'; @@ -145,7 +145,7 @@ class ClassRegistry { $appModel = 'AppModel'; } $settings['name'] = $class; - ${$class} = new $appModel($settings); + ${$class} =& new $appModel($settings); } if (!isset(${$class})) { diff --git a/cake/libs/configure.php b/cake/libs/configure.php index 42c16de5..c9056d28 100755 --- a/cake/libs/configure.php +++ b/cake/libs/configure.php @@ -31,7 +31,7 @@ * @subpackage cake.cake.libs * @link http://book.cakephp.org/view/42/The-Configuration-Class */ -class Configure extends CakeObject { +class Configure extends Object { /** * List of additional path(s) where model files reside. * @@ -133,7 +133,7 @@ class Configure extends CakeObject { static function &getInstance($boot = true) { static $instance = array(); if (!$instance) { - $instance[0] = new Configure(); + $instance[0] =& new Configure(); $instance[0]->__loadBootstrap($boot); } return $instance[0]; @@ -223,7 +223,7 @@ class Configure extends CakeObject { require LIBS . 'folder.php'; } $items = array(); - $Folder = new Folder($path); + $Folder =& new Folder($path); $contents = $Folder->read(false, true); if (is_array($contents)) { @@ -717,7 +717,7 @@ class Configure extends CakeObject { * @package cake * @subpackage cake.cake.libs */ -class App extends CakeObject { +class App extends Object { /** * Paths to search for files. * @@ -903,7 +903,7 @@ class App extends CakeObject { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] = new App(); + $instance[0] =& new App(); $instance[0]->__map = Cache::read('file_map', '_cake_core_'); } return $instance[0]; @@ -943,7 +943,7 @@ class App extends CakeObject { if (!class_exists('Folder')) { require LIBS . 'folder.php'; } - $Folder = new Folder(); + $Folder =& new Folder(); $directories = $Folder->tree($path, false, 'dir'); $this->__paths[$path] = $directories; } diff --git a/cake/libs/controller/component.php b/cake/libs/controller/component.php index 4cb46a0e..c40571cd 100755 --- a/cake/libs/controller/component.php +++ b/cake/libs/controller/component.php @@ -28,7 +28,7 @@ * @subpackage cake.cake.libs.controller * @link http://book.cakephp.org/view/62/Components */ -class Component extends CakeObject { +class Component extends Object { /** * Contains various controller variable information (plugin, name, base). * @@ -234,9 +234,9 @@ class Component extends CakeObject { } } else { if ($componentCn === 'SessionComponent') { - $object->{$component} = new $componentCn($base); + $object->{$component} =& new $componentCn($base); } else { - $object->{$component} = new $componentCn(); + $object->{$component} =& new $componentCn(); } $object->{$component}->enabled = true; $this->_loaded[$component] =& $object->{$component}; diff --git a/cake/libs/controller/components/acl.php b/cake/libs/controller/components/acl.php index b2e4ad2d..d68c61f0 100755 --- a/cake/libs/controller/components/acl.php +++ b/cake/libs/controller/components/acl.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.controller.components */ -class AclComponent extends CakeObject { +class AclComponent extends Object { /** * Instance of an ACL class * @@ -56,7 +56,7 @@ class AclComponent extends CakeObject { trigger_error(sprintf(__('Could not find %s.', true), $name), E_USER_WARNING); } } - $this->_Instance = new $name(); + $this->_Instance =& new $name(); $this->_Instance->initialize($this); } /** @@ -157,7 +157,7 @@ class AclComponent extends CakeObject { * @subpackage cake.cake.libs.controller.components * @abstract */ -class AclBase extends CakeObject { +class AclBase extends Object { /** * This class should never be instantiated, just subclassed. * diff --git a/cake/libs/controller/components/auth.php b/cake/libs/controller/components/auth.php index 0d0c65ca..1aa37e52 100755 --- a/cake/libs/controller/components/auth.php +++ b/cake/libs/controller/components/auth.php @@ -36,7 +36,7 @@ App::import(array('Router', 'Security')); * @package cake * @subpackage cake.cake.libs.controller.components */ -class AuthComponent extends CakeObject { +class AuthComponent extends Object { /** * Maintains current user login state. * diff --git a/cake/libs/controller/components/cookie.php b/cake/libs/controller/components/cookie.php index 1e0a063d..56713f5c 100755 --- a/cake/libs/controller/components/cookie.php +++ b/cake/libs/controller/components/cookie.php @@ -37,7 +37,7 @@ App::import('Core', 'Security'); * @subpackage cake.cake.libs.controller.components * */ -class CookieComponent extends CakeObject { +class CookieComponent extends Object { /** * The name of the cookie. * diff --git a/cake/libs/controller/components/email.php b/cake/libs/controller/components/email.php index b45ae072..b2e2ea42 100755 --- a/cake/libs/controller/components/email.php +++ b/cake/libs/controller/components/email.php @@ -35,7 +35,7 @@ * */ App::import('Core', 'Multibyte'); -class EmailComponent extends CakeObject{ +class EmailComponent extends Object{ /** * Recipient of the email * @@ -671,7 +671,7 @@ class EmailComponent extends CakeObject{ function __smtp() { App::import('Core', array('Socket')); - $this->__smtpConnection = new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->smtpOptions)); + $this->__smtpConnection =& new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->smtpOptions)); if (!$this->__smtpConnection->connect()) { $this->smtpError = $this->__smtpConnection->lastError(); diff --git a/cake/libs/controller/components/request_handler.php b/cake/libs/controller/components/request_handler.php index 999e4ea2..efca6b2c 100755 --- a/cake/libs/controller/components/request_handler.php +++ b/cake/libs/controller/components/request_handler.php @@ -36,7 +36,7 @@ if (!defined('REQUEST_MOBILE_UA')) { * @subpackage cake.cake.libs.controller.components * */ -class RequestHandlerComponent extends CakeObject { +class RequestHandlerComponent extends Object { /** * The layout that will be switched to for Ajax requests * diff --git a/cake/libs/controller/components/security.php b/cake/libs/controller/components/security.php index d5963a86..96d14025 100755 --- a/cake/libs/controller/components/security.php +++ b/cake/libs/controller/components/security.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.controller.components */ -class SecurityComponent extends CakeObject { +class SecurityComponent extends Object { /** * The controller method that will be called if this request is black-hole'd * diff --git a/cake/libs/controller/controller.php b/cake/libs/controller/controller.php index 528c8d71..6a582bfc 100755 --- a/cake/libs/controller/controller.php +++ b/cake/libs/controller/controller.php @@ -38,7 +38,7 @@ App::import('Core', array('Component', 'View')); * @link http://book.cakephp.org/view/49/Controllers * */ -class Controller extends CakeObject { +class Controller extends Object { /** * The name of this controller. Controller names are plural, named after the model they manipulate. * @@ -335,7 +335,7 @@ class Controller extends CakeObject { } $this->modelClass = Inflector::classify($this->name); $this->modelKey = Inflector::underscore($this->modelClass); - $this->Component = new Component(); + $this->Component =& new Component(); $childMethods = get_class_methods($this); $parentMethods = get_class_methods('Controller'); @@ -776,7 +776,7 @@ class Controller extends CakeObject { $this->set('cakeDebug', $this); } - $View = new $viewClass($this); + $View =& new $viewClass($this); if (!empty($this->modelNames)) { $models = array(); diff --git a/cake/libs/controller/scaffold.php b/cake/libs/controller/scaffold.php index cf4be9a2..165e2b56 100755 --- a/cake/libs/controller/scaffold.php +++ b/cake/libs/controller/scaffold.php @@ -35,7 +35,7 @@ * @package cake * @subpackage cake.cake.libs.controller */ -class Scaffold extends CakeObject { +class Scaffold extends Object { /** * Controller object * diff --git a/cake/libs/debugger.php b/cake/libs/debugger.php index 2079e4c1..f80d05c2 100755 --- a/cake/libs/debugger.php +++ b/cake/libs/debugger.php @@ -43,7 +43,7 @@ * @subpackage cake.cake.libs * @link http://book.cakephp.org/view/460/Using-the-Debugger-Class */ -class Debugger extends CakeObject { +class Debugger extends Object { /** * A list of errors generated by the application. * @@ -105,7 +105,7 @@ class Debugger extends CakeObject { } if (!$instance) { - $instance[0] = new Debugger(); + $instance[0] =& new Debugger(); if (Configure::read() > 0) { Configure::version(); // Make sure the core config is loaded $instance[0]->helpPath = Configure::read('Cake.Debugger.HelpPath'); diff --git a/cake/libs/error.php b/cake/libs/error.php index 4647bba6..e8db8276 100755 --- a/cake/libs/error.php +++ b/cake/libs/error.php @@ -66,7 +66,7 @@ class CakeErrorController extends AppController { * @package cake * @subpackage cake.cake.libs */ -class ErrorHandler extends CakeObject { +class ErrorHandler extends Object { /** * Controller instance. * @@ -86,9 +86,9 @@ class ErrorHandler extends CakeObject { if ($__previousError != array($method, $messages)) { $__previousError = array($method, $messages); - $this->controller = new CakeErrorController(); + $this->controller =& new CakeErrorController(); } else { - $this->controller = new Controller(); + $this->controller =& new Controller(); $this->controller->viewPath = 'errors'; } diff --git a/cake/libs/file.php b/cake/libs/file.php index f00fd827..b57cb4c7 100755 --- a/cake/libs/file.php +++ b/cake/libs/file.php @@ -38,7 +38,7 @@ if (!class_exists('Folder')) { * @package cake * @subpackage cake.cake.libs */ -class File extends CakeObject { +class File extends Object { /** * Folder object of the File * @@ -93,7 +93,7 @@ class File extends CakeObject { */ function __construct($path, $create = false, $mode = 0755) { parent::__construct(); - $this->Folder = new Folder(dirname($path), $create, $mode); + $this->Folder =& new Folder(dirname($path), $create, $mode); if (!is_dir($path)) { $this->name = basename($path); } diff --git a/cake/libs/flay.php b/cake/libs/flay.php index 9362830f..ed23cf7f 100755 --- a/cake/libs/flay.php +++ b/cake/libs/flay.php @@ -39,7 +39,7 @@ if (!class_exists('Object')) { * @package cake * @subpackage cake.cake.libs */ -class Flay extends CakeObject{ +class Flay extends Object{ /** * Text to be parsed. * diff --git a/cake/libs/folder.php b/cake/libs/folder.php index 3b108a93..28f32672 100755 --- a/cake/libs/folder.php +++ b/cake/libs/folder.php @@ -37,7 +37,7 @@ if (!class_exists('Object')) { * @package cake * @subpackage cake.cake.libs */ -class Folder extends CakeObject { +class Folder extends Object { /** * Path to Folder. * diff --git a/cake/libs/i18n.php b/cake/libs/i18n.php index 31e04834..6e21ca5c 100755 --- a/cake/libs/i18n.php +++ b/cake/libs/i18n.php @@ -36,7 +36,7 @@ App::import('Core', 'l10n'); * @package cake * @subpackage cake.cake.libs */ -class I18n extends CakeObject { +class I18n extends Object { /** * Instance of the I10n class for localization * @@ -106,8 +106,8 @@ class I18n extends CakeObject { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] = new I18n(); - $instance[0]->l10n = new L10n(); + $instance[0] =& new I18n(); + $instance[0]->l10n =& new L10n(); } return $instance[0]; } diff --git a/cake/libs/inflector.php b/cake/libs/inflector.php index 5caf467c..71f07b4e 100755 --- a/cake/libs/inflector.php +++ b/cake/libs/inflector.php @@ -45,7 +45,7 @@ if (!class_exists('Set')) { * @subpackage cake.cake.libs * @link http://book.cakephp.org/view/491/Inflector */ -class Inflector extends CakeObject { +class Inflector extends Object { /** * Pluralized words. * @@ -128,7 +128,7 @@ class Inflector extends CakeObject { static $instance = array(); if (!$instance) { - $instance[0] = new Inflector(); + $instance[0] =& new Inflector(); if (file_exists(CONFIGS.'inflections.php')) { include(CONFIGS.'inflections.php'); $instance[0]->__pluralRules = $pluralRules; diff --git a/cake/libs/l10n.php b/cake/libs/l10n.php index 6cb8a3fe..95f66c25 100755 --- a/cake/libs/l10n.php +++ b/cake/libs/l10n.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs */ -class L10n extends CakeObject { +class L10n extends Object { /** * The language for current locale * diff --git a/cake/libs/magic_db.php b/cake/libs/magic_db.php index e039b7d9..73b16017 100755 --- a/cake/libs/magic_db.php +++ b/cake/libs/magic_db.php @@ -31,7 +31,7 @@ if (!class_exists('File')) { * @package cake.tests * @subpackage cake.tests.cases.libs */ -class MagicDb extends CakeObject { +class MagicDb extends Object { /** * Holds the parsed MagicDb for this class instance * @@ -53,7 +53,7 @@ class MagicDb extends CakeObject { if (is_array($magicDb) || strpos($magicDb, '# FILE_ID DB') === 0) { $data = $magicDb; } else { - $File = new File($magicDb); + $File =& new File($magicDb); if (!$File->exists()) { return false; } @@ -158,7 +158,7 @@ class MagicDb extends CakeObject { } $matches = array(); - $MagicFileResource = new MagicFileResource($file); + $MagicFileResource =& new MagicFileResource($file); foreach ($this->db['database'] as $format) { $magic = $format[0]; $match = $MagicFileResource->test($magic); @@ -178,7 +178,7 @@ class MagicDb extends CakeObject { * @package cake.tests * @subpackage cake.tests.cases.libs */ -class MagicFileResource extends CakeObject{ +class MagicFileResource extends Object{ /** * undocumented variable * @@ -202,7 +202,7 @@ class MagicFileResource extends CakeObject{ */ function __construct($file) { if (file_exists($file)) { - $this->resource = new File($file); + $this->resource =& new File($file); } else { $this->resource = $file; } diff --git a/cake/libs/model/behavior.php b/cake/libs/model/behavior.php index 881b070e..fdbc64e3 100755 --- a/cake/libs/model/behavior.php +++ b/cake/libs/model/behavior.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.model */ -class ModelBehavior extends CakeObject { +class ModelBehavior extends Object { /** * Contains configuration settings for use with individual model objects. This * is used because if multiple models use this Behavior, each will use the same @@ -204,7 +204,7 @@ class ModelBehavior extends CakeObject { * @package cake * @subpackage cake.cake.libs.model */ -class BehaviorCollection extends CakeObject { +class BehaviorCollection extends Object { /** * Stores a reference to the attached name * @@ -283,7 +283,7 @@ class BehaviorCollection extends CakeObject { if (PHP5) { $this->{$name} = new $class; } else { - $this->{$name} = new $class; + $this->{$name} =& new $class; } ClassRegistry::addObject($class, $this->{$name}); } diff --git a/cake/libs/model/connection_manager.php b/cake/libs/model/connection_manager.php index 68f304d1..32f16984 100755 --- a/cake/libs/model/connection_manager.php +++ b/cake/libs/model/connection_manager.php @@ -35,7 +35,7 @@ config('database'); * @package cake * @subpackage cake.cake.libs.model */ -class ConnectionManager extends CakeObject { +class ConnectionManager extends Object { /** * Holds a loaded instance of the Connections object * @@ -63,7 +63,7 @@ class ConnectionManager extends CakeObject { */ function __construct() { if (class_exists('DATABASE_CONFIG')) { - $this->config = new DATABASE_CONFIG(); + $this->config =& new DATABASE_CONFIG(); } } /** @@ -77,7 +77,7 @@ class ConnectionManager extends CakeObject { static $instance = array(); if (!$instance) { - $instance[0] = new ConnectionManager(); + $instance[0] =& new ConnectionManager(); } return $instance[0]; @@ -103,7 +103,7 @@ class ConnectionManager extends CakeObject { $conn = $connections[$name]; $class = $conn['classname']; $_this->loadDataSource($name); - $_this->_dataSources[$name] = new $class($_this->config->{$name}); + $_this->_dataSources[$name] =& new $class($_this->config->{$name}); $_this->_dataSources[$name]->configKeyName = $name; } else { trigger_error(sprintf(__("ConnectionManager::getDataSource - Non-existent data source %s", true), $name), E_USER_ERROR); diff --git a/cake/libs/model/datasources/datasource.php b/cake/libs/model/datasources/datasource.php index f9cfc515..b1b2baef 100755 --- a/cake/libs/model/datasources/datasource.php +++ b/cake/libs/model/datasources/datasource.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs.model.datasources */ -class DataSource extends CakeObject { +class DataSource extends Object { /** * Are we connected to the DataSource? * diff --git a/cake/libs/model/schema.php b/cake/libs/model/schema.php index 1faa073b..d0368992 100755 --- a/cake/libs/model/schema.php +++ b/cake/libs/model/schema.php @@ -29,7 +29,7 @@ App::import('Model', 'ConnectionManager'); * @package cake * @subpackage cake.cake.libs.model */ -class CakeSchema extends CakeObject { +class CakeSchema extends Object { /** * Name of the App Schema * @@ -158,7 +158,7 @@ class CakeSchema extends CakeObject { } if (class_exists($class)) { - $Schema = new $class($options); + $Schema =& new $class($options); return $Schema; } @@ -354,7 +354,7 @@ class CakeSchema extends CakeObject { $out .="}\n"; - $File = new File($path . DS . $file, true); + $File =& new File($path . DS . $file, true); $header = '$Id'; $content = ""; $content = $File->prepare($content); diff --git a/cake/libs/multibyte.php b/cake/libs/multibyte.php index 9dc9c9b6..724b6592 100755 --- a/cake/libs/multibyte.php +++ b/cake/libs/multibyte.php @@ -241,7 +241,7 @@ if (!function_exists('mb_encode_mimeheader')) { * @package cake * @subpackage cake.cake.libs */ -class Multibyte extends CakeObject { +class Multibyte extends Object { /** * Holds the case folding values * @@ -274,7 +274,7 @@ class Multibyte extends CakeObject { static $instance = array(); if (!$instance) { - $instance[0] = new Multibyte(); + $instance[0] =& new Multibyte(); } return $instance[0]; } diff --git a/cake/libs/object.php b/cake/libs/object.php index 1519e76f..61c0896c 100755 --- a/cake/libs/object.php +++ b/cake/libs/object.php @@ -34,7 +34,7 @@ * @package cake * @subpackage cake.cake.libs */ -class CakeObject { +class Object { /** * Log object * @@ -295,7 +295,4 @@ class CakeObject { } } } - -// Note: In PHP 7+, 'Object' is a reserved class name -// All classes that extend Object should now extend CakeObject instead ?> \ No newline at end of file diff --git a/cake/libs/overloadable_php4.php b/cake/libs/overloadable_php4.php index 0a6ff9df..b60411c5 100755 --- a/cake/libs/overloadable_php4.php +++ b/cake/libs/overloadable_php4.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Overloadable extends CakeObject { +class Overloadable extends Object { /** * Constructor. * @@ -88,7 +88,7 @@ Overloadable::overload('Overloadable'); * @package cake * @subpackage cake.cake.libs */ -class Overloadable2 extends CakeObject { +class Overloadable2 extends Object { /** * Constructor * diff --git a/cake/libs/overloadable_php5.php b/cake/libs/overloadable_php5.php index 347f7c9c..906b6b37 100755 --- a/cake/libs/overloadable_php5.php +++ b/cake/libs/overloadable_php5.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Overloadable extends CakeObject { +class Overloadable extends Object { /** * Overload implementation. No need for implementation in PHP5. * @@ -60,7 +60,7 @@ class Overloadable extends CakeObject { * * @package cake */ -class Overloadable2 extends CakeObject { +class Overloadable2 extends Object { /** * Overload implementation. No need for implementation in PHP5. * diff --git a/cake/libs/router.php b/cake/libs/router.php index 65520c7c..0b2b3b61 100755 --- a/cake/libs/router.php +++ b/cake/libs/router.php @@ -37,7 +37,7 @@ if (!class_exists('Object')) { * @package cake * @subpackage cake.cake.libs */ -class Router extends CakeObject { +class Router extends Object { /** * Array of routes * @@ -170,7 +170,7 @@ class Router extends CakeObject { static $instance = array(); if (!$instance) { - $instance[0] = new Router(); + $instance[0] =& new Router(); $instance[0]->__admin = Configure::read('Routing.admin'); } return $instance[0]; diff --git a/cake/libs/security.php b/cake/libs/security.php index fc610c1e..15ec7c1b 100755 --- a/cake/libs/security.php +++ b/cake/libs/security.php @@ -32,7 +32,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Security extends CakeObject { +class Security extends Object { /** * Default hash method * @@ -50,7 +50,7 @@ class Security extends CakeObject { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] = new Security; + $instance[0] =& new Security; } return $instance[0]; } diff --git a/cake/libs/session.php b/cake/libs/session.php index a2ae2511..c90318c9 100755 --- a/cake/libs/session.php +++ b/cake/libs/session.php @@ -46,7 +46,7 @@ if (!class_exists('Security')) { * @package cake * @subpackage cake.cake.libs */ -class CakeSession extends CakeObject { +class CakeSession extends Object { /** * True if the Session is still valid * diff --git a/cake/libs/set.php b/cake/libs/set.php index 8e54b15d..2afb7156 100755 --- a/cake/libs/set.php +++ b/cake/libs/set.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class Set extends CakeObject { +class Set extends Object { /** * Deprecated * diff --git a/cake/libs/socket.php b/cake/libs/socket.php index 487d0911..c5c945aa 100755 --- a/cake/libs/socket.php +++ b/cake/libs/socket.php @@ -31,7 +31,7 @@ App::import('Core', 'Validation'); * @package cake * @subpackage cake.cake.libs */ -class CakeSocket extends CakeObject { +class CakeSocket extends Object { /** * Object description * diff --git a/cake/libs/string.php b/cake/libs/string.php index 2f8950ea..286017bd 100755 --- a/cake/libs/string.php +++ b/cake/libs/string.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.libs */ -class String extends CakeObject { +class String extends Object { /** * Gets a reference to the String object instance * @@ -42,7 +42,7 @@ class String extends CakeObject { static $instance = array(); if (!$instance) { - $instance[0] = new String(); + $instance[0] =& new String(); } return $instance[0]; } diff --git a/cake/libs/validation.php b/cake/libs/validation.php index f519fec0..be0d20c2 100755 --- a/cake/libs/validation.php +++ b/cake/libs/validation.php @@ -52,7 +52,7 @@ * @subpackage cake.cake.libs * @since CakePHP v 1.2.0.3830 */ -class Validation extends CakeObject { +class Validation extends Object { /** * Set the the value of methods $check param. * @@ -119,7 +119,7 @@ class Validation extends CakeObject { static $instance = array(); if (!$instance) { - $instance[0] = new Validation(); + $instance[0] =& new Validation(); } return $instance[0]; } diff --git a/cake/libs/view/helpers/cache.php b/cake/libs/view/helpers/cache.php index 39814a0c..d8e60b12 100755 --- a/cake/libs/view/helpers/cache.php +++ b/cake/libs/view/helpers/cache.php @@ -252,7 +252,7 @@ class CacheHelper extends AppHelper { '; } - $file .= '$controller = new ' . $this->controllerName . 'Controller(); + $file .= '$controller =& new ' . $this->controllerName . 'Controller(); $controller->plugin = $this->plugin = \''.$this->plugin.'\'; $controller->helpers = $this->helpers = unserialize(\'' . serialize($this->helpers) . '\'); $controller->base = $this->base = \'' . $this->base . '\'; diff --git a/cake/libs/view/helpers/js.php b/cake/libs/view/helpers/js.php index e372e9f2..15e25099 100755 --- a/cake/libs/view/helpers/js.php +++ b/cake/libs/view/helpers/js.php @@ -136,7 +136,7 @@ class JsHelper extends Overloadable2 { } $func .= "'" . Router::url($url) . "'"; - $ajax = new AjaxHelper(); + $ajax =& new AjaxHelper(); $func .= ", " . $ajax->__optionsForAjax($options) . ")"; if (isset($options['before'])) { diff --git a/cake/libs/view/helpers/xml.php b/cake/libs/view/helpers/xml.php index bd8434dc..6377a526 100755 --- a/cake/libs/view/helpers/xml.php +++ b/cake/libs/view/helpers/xml.php @@ -46,7 +46,7 @@ class XmlHelper extends AppHelper { */ function __construct() { parent::__construct(); - $this->Xml = new Xml(); + $this->Xml =& new Xml(); $this->Xml->options(array('verifyNs' => false)); } /** @@ -155,7 +155,7 @@ class XmlHelper extends AppHelper { */ function serialize($data, $options = array()) { $options += array('attributes' => false, 'format' => 'attributes'); - $data = new Xml($data, $options); + $data =& new Xml($data, $options); return $data->toString($options + array('header' => false)); } } diff --git a/cake/libs/view/view.php b/cake/libs/view/view.php index a5d8d57d..1ed8c01c 100755 --- a/cake/libs/view/view.php +++ b/cake/libs/view/view.php @@ -34,7 +34,7 @@ App::import('Core', array('Helper', 'ClassRegistry')); * @package cake * @subpackage cake.cake.libs.view */ -class View extends CakeObject { +class View extends Object { /** * Path parts for creating links in views. * @@ -745,7 +745,7 @@ class View extends CakeObject { return false; } } - $loaded[$helper] = new $helperCn($options); + $loaded[$helper] =& new $helperCn($options); $vars = array( 'base', 'webroot', 'here', 'params', 'action', 'data', 'themeWeb', 'plugin' ); diff --git a/cake/libs/xml.php b/cake/libs/xml.php index 7daa6684..0d91825b 100755 --- a/cake/libs/xml.php +++ b/cake/libs/xml.php @@ -34,7 +34,7 @@ App::import('Core', 'Set'); * @subpackage cake.cake.libs * @since CakePHP v .0.10.3.1400 */ -class XmlNode extends CakeObject { +class XmlNode extends Object { /** * Name of node * @@ -147,7 +147,7 @@ class XmlNode extends CakeObject { * @return object XmlNode */ function &createNode($name = null, $value = null, $namespace = false) { - $node = new XmlNode($name, $value, $namespace); + $node =& new XmlNode($name, $value, $namespace); $node->setParent($this); return $node; } @@ -161,7 +161,7 @@ class XmlNode extends CakeObject { * @return object XmlElement */ function &createElement($name = null, $value = null, $attributes = array(), $namespace = false) { - $element = new XmlElement($name, $value, $attributes, $namespace); + $element =& new XmlElement($name, $value, $attributes, $namespace); $element->setParent($this); return $element; } @@ -1398,7 +1398,7 @@ class XmlManager { static $instance = array(); if (!$instance) { - $instance[0] = new XmlManager(); + $instance[0] =& new XmlManager(); } return $instance[0]; } diff --git a/cake/tests/cases/console/cake.test.php b/cake/tests/cases/console/cake.test.php index 86e22f85..6eda913f 100755 --- a/cake/tests/cases/console/cake.test.php +++ b/cake/tests/cases/console/cake.test.php @@ -151,7 +151,7 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testParseParams() { - $Dispatcher = new TestShellDispatcher(); + $Dispatcher =& new TestShellDispatcher(); $params = array( '/cake/1.2.x.x/cake/console/cake.php', @@ -423,7 +423,7 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testBuildPaths() { - $Dispatcher = new TestShellDispatcher(); + $Dispatcher =& new TestShellDispatcher(); $result = $Dispatcher->shellPaths; $expected = array( @@ -444,13 +444,13 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testDispatch() { - $Dispatcher = new TestShellDispatcher(array('sample')); + $Dispatcher =& new TestShellDispatcher(array('sample')); $this->assertPattern('/This is the main method called from SampleShell/', $Dispatcher->stdout); - $Dispatcher = new TestShellDispatcher(array('test_plugin_two.example')); + $Dispatcher =& new TestShellDispatcher(array('test_plugin_two.example')); $this->assertPattern('/This is the main method called from TestPluginTwo.ExampleShell/', $Dispatcher->stdout); - $Dispatcher = new TestShellDispatcher(array('test_plugin_two.welcome', 'say_hello')); + $Dispatcher =& new TestShellDispatcher(array('test_plugin_two.welcome', 'say_hello')); $this->assertPattern('/This is the say_hello method called from TestPluginTwo.WelcomeShell/', $Dispatcher->stdout); } /** @@ -460,7 +460,7 @@ class ShellDispatcherTest extends UnitTestCase { * @return void */ function testHelpCommand() { - $Dispatcher = new TestShellDispatcher(); + $Dispatcher =& new TestShellDispatcher(); $expected = "/ CORE(\\\|\/)tests(\\\|\/)test_app(\\\|\/)plugins(\\\|\/)test_plugin(\\\|\/)vendors(\\\|\/)shells:"; $expected .= "\n\t example"; diff --git a/cake/tests/cases/console/libs/acl.test.php b/cake/tests/cases/console/libs/acl.test.php index 6f7f1154..f27a6943 100755 --- a/cake/tests/cases/console/libs/acl.test.php +++ b/cake/tests/cases/console/libs/acl.test.php @@ -84,8 +84,8 @@ class AclShellTest extends CakeTestCase { * @access public */ function startTest() { - $this->Dispatcher = new TestAclShellMockShellDispatcher(); - $this->Task = new MockAclShell($this->Dispatcher); + $this->Dispatcher =& new TestAclShellMockShellDispatcher(); + $this->Task =& new MockAclShell($this->Dispatcher); $this->Task->Dispatch =& $this->Dispatcher; $this->Task->params['datasource'] = 'test_suite'; } diff --git a/cake/tests/cases/console/libs/api.test.php b/cake/tests/cases/console/libs/api.test.php index cc60aecf..b5568fce 100755 --- a/cake/tests/cases/console/libs/api.test.php +++ b/cake/tests/cases/console/libs/api.test.php @@ -62,8 +62,8 @@ class ApiShellTest extends CakeTestCase { * @access public */ function startTest() { - $this->Dispatcher = new ApiShellMockShellDispatcher(); - $this->Shell = new MockApiShell($this->Dispatcher); + $this->Dispatcher =& new ApiShellMockShellDispatcher(); + $this->Shell =& new MockApiShell($this->Dispatcher); $this->Shell->Dispatch =& $this->Dispatcher; } /** diff --git a/cake/tests/cases/console/libs/schema.test.php b/cake/tests/cases/console/libs/schema.test.php index 48573fcf..063910db 100755 --- a/cake/tests/cases/console/libs/schema.test.php +++ b/cake/tests/cases/console/libs/schema.test.php @@ -124,8 +124,8 @@ class SchemaShellTest extends CakeTestCase { * @access public */ function startTest() { - $this->Dispatcher = new TestSchemaShellMockShellDispatcher(); - $this->Shell = new MockSchemaShell($this->Dispatcher); + $this->Dispatcher =& new TestSchemaShellMockShellDispatcher(); + $this->Shell =& new MockSchemaShell($this->Dispatcher); $this->Shell->Dispatch =& $this->Dispatcher; } @@ -193,9 +193,9 @@ class SchemaShellTest extends CakeTestCase { * @return void **/ function testDumpWithFileWriting() { - $file = new File(APP . 'config' . DS . 'sql' . DS . 'i18n.php'); + $file =& new File(APP . 'config' . DS . 'sql' . DS . 'i18n.php'); $contents = $file->read(); - $file = new File(TMP . 'tests' . DS . 'i18n.php'); + $file =& new File(TMP . 'tests' . DS . 'i18n.php'); $file->write($contents); $this->Shell->params = array('name' => 'i18n'); @@ -204,7 +204,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->Schema->path = TMP . 'tests'; $this->Shell->dump(); - $sql = new File(TMP . 'tests' . DS . 'i18n.sql'); + $sql =& new File(TMP . 'tests' . DS . 'i18n.sql'); $contents = $sql->read(); $this->assertPattern('/DROP TABLE/', $contents); $this->assertPattern('/CREATE TABLE `i18n`/', $contents); @@ -228,7 +228,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->path = TMP; $this->Shell->params['file'] = 'schema.php'; $this->Shell->args = array('snapshot'); - $this->Shell->Schema = new MockSchemaCakeSchema(); + $this->Shell->Schema =& new MockSchemaCakeSchema(); $this->Shell->Schema->setReturnValue('read', array('schema data')); $this->Shell->Schema->setReturnValue('write', true); @@ -249,7 +249,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->args = array(); $this->Shell->setReturnValue('in', 'q'); - $this->Shell->Schema = new MockSchemaCakeSchema(); + $this->Shell->Schema =& new MockSchemaCakeSchema(); $this->Shell->Schema->path = TMP; $this->Shell->Schema->expectNever('read'); @@ -269,7 +269,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->setReturnValue('in', 'o'); $this->Shell->expectAt(1, 'out', array(new PatternExpectation('/Schema file:\s[a-z\.]+\sgenerated/'))); - $this->Shell->Schema = new MockSchemaCakeSchema(); + $this->Shell->Schema =& new MockSchemaCakeSchema(); $this->Shell->Schema->path = TMP; $this->Shell->Schema->setReturnValue('read', array('schema data')); $this->Shell->Schema->setReturnValue('write', true); @@ -341,7 +341,7 @@ class SchemaShellTest extends CakeTestCase { $this->Shell->setReturnValue('in', 'y'); $this->Shell->run(); - $article = new Model(array('name' => 'Article', 'ds' => 'test_suite')); + $article =& new Model(array('name' => 'Article', 'ds' => 'test_suite')); $fields = $article->schema(); $this->assertTrue(isset($fields['summary'])); diff --git a/cake/tests/cases/console/libs/shell.test.php b/cake/tests/cases/console/libs/shell.test.php index c7114535..b832088e 100755 --- a/cake/tests/cases/console/libs/shell.test.php +++ b/cake/tests/cases/console/libs/shell.test.php @@ -95,8 +95,8 @@ class ShellTest extends CakeTestCase { * @access public */ function setUp() { - $this->Dispatcher = new TestShellMockShellDispatcher(); - $this->Shell = new TestShell($this->Dispatcher); + $this->Dispatcher =& new TestShellMockShellDispatcher(); + $this->Shell =& new TestShell($this->Dispatcher); } /** * tearDown method diff --git a/cake/tests/cases/console/libs/tasks/extract.test.php b/cake/tests/cases/console/libs/tasks/extract.test.php index 6ae11c64..d393a527 100755 --- a/cake/tests/cases/console/libs/tasks/extract.test.php +++ b/cake/tests/cases/console/libs/tasks/extract.test.php @@ -59,8 +59,8 @@ class ExtractTaskTest extends CakeTestCase { * @access public */ function setUp() { - $this->Dispatcher = new TestExtractTaskMockShellDispatcher(); - $this->Task = new ExtractTask($this->Dispatcher); + $this->Dispatcher =& new TestExtractTaskMockShellDispatcher(); + $this->Task =& new ExtractTask($this->Dispatcher); } /** * tearDown method diff --git a/cake/tests/cases/console/libs/tasks/test.test.php b/cake/tests/cases/console/libs/tasks/test.test.php index 0449893b..548f2960 100755 --- a/cake/tests/cases/console/libs/tasks/test.test.php +++ b/cake/tests/cases/console/libs/tasks/test.test.php @@ -63,8 +63,8 @@ class TestTaskTest extends CakeTestCase { * @access public */ function setUp() { - $this->Dispatcher = new TestTestTaskMockShellDispatcher(); - $this->Task = new MockTestTask($this->Dispatcher); + $this->Dispatcher =& new TestTestTaskMockShellDispatcher(); + $this->Task =& new MockTestTask($this->Dispatcher); $this->Task->Dispatch =& $this->Dispatcher; } /** diff --git a/cake/tests/cases/dispatcher.test.php b/cake/tests/cases/dispatcher.test.php index f761eaa0..613c8949 100755 --- a/cake/tests/cases/dispatcher.test.php +++ b/cake/tests/cases/dispatcher.test.php @@ -544,7 +544,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithoutZerosAndEmptyPost() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/params1/params2/params3"); $this->assertIdentical($test['controller'], 'testcontroller'); $this->assertIdentical($test['action'], 'testaction'); @@ -561,7 +561,7 @@ class DispatcherTest extends CakeTestCase { */ function testParseParamsReturnsPostedData() { $_POST['testdata'] = "My Posted Content"; - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $test = $Dispatcher->parseParams("/"); $this->assertTrue($test['form'], "Parsed URL not returning post data"); $this->assertIdentical($test['form']['testdata'], "My Posted Content"); @@ -573,7 +573,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithSingleZero() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/1/0/23"); $this->assertIdentical($test['controller'], 'testcontroller'); $this->assertIdentical($test['action'], 'testaction'); @@ -588,7 +588,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithManySingleZeros() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/0/0/0/0/0/0"); $this->assertPattern('/\\A(?:0)\\z/', $test['pass'][0]); $this->assertPattern('/\\A(?:0)\\z/', $test['pass'][1]); @@ -604,7 +604,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithManyZerosInEachSectionOfUrl() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/000/0000/00000/000000/000000/0000000"); $this->assertPattern('/\\A(?:000)\\z/', $test['pass'][0]); $this->assertPattern('/\\A(?:0000)\\z/', $test['pass'][1]); @@ -620,7 +620,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $test = $Dispatcher->parseParams("/testcontroller/testaction/01/0403/04010/000002/000030/0000400"); $this->assertPattern('/\\A(?:01)\\z/', $test['pass'][0]); $this->assertPattern('/\\A(?:0403)\\z/', $test['pass'][1]); @@ -641,7 +641,7 @@ class DispatcherTest extends CakeTestCase { Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display')); $_GET = array('coffee' => 'life', 'sleep' => 'sissies'); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $uri = 'posts/home/?coffee=life&sleep=sissies'; $result = $Dispatcher->parseParams($uri); $this->assertPattern('/posts/', $result['controller']); @@ -649,7 +649,7 @@ class DispatcherTest extends CakeTestCase { $this->assertTrue(isset($result['url']['sleep'])); $this->assertTrue(isset($result['url']['coffee'])); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $uri = '/?coffee=life&sleep=sissy'; $result = $Dispatcher->parseParams($uri); $this->assertPattern('/pages/', $result['controller']); @@ -712,7 +712,7 @@ class DispatcherTest extends CakeTestCase { ), )); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $result = $Dispatcher->parseParams('/'); $expected = array( @@ -830,7 +830,7 @@ class DispatcherTest extends CakeTestCase { ) ) ); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $result = $Dispatcher->parseParams('/'); $expected = array( 'Document' => array( @@ -895,7 +895,7 @@ class DispatcherTest extends CakeTestCase { ) ); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $result = $Dispatcher->parseParams('/'); $expected = array( @@ -917,7 +917,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testGetUrl() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $Dispatcher->base = '/app/webroot/index.php'; $uri = '/app/webroot/index.php/posts/add'; $result = $Dispatcher->getUrl($uri); @@ -933,7 +933,7 @@ class DispatcherTest extends CakeTestCase { $_GET['url'] = array(); Configure::write('App.base', '/control'); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $Dispatcher->baseUrl(); $uri = '/control/students/browse'; $result = $Dispatcher->getUrl($uri); @@ -941,7 +941,7 @@ class DispatcherTest extends CakeTestCase { $this->assertEqual($expected, $result); $_GET['url'] = array(); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $Dispatcher->base = ''; $uri = '/?/home'; $result = $Dispatcher->getUrl($uri); @@ -956,7 +956,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testBaseUrlAndWebrootWithModRewrite() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $Dispatcher->base = false; $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches'; @@ -1037,7 +1037,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('App.base', '/control'); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $result = $Dispatcher->baseUrl(); $expected = '/control'; $this->assertEqual($expected, $result); @@ -1051,7 +1051,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['DOCUMENT_ROOT'] = '/var/www/abtravaff/html'; $_SERVER['SCRIPT_FILENAME'] = '/var/www/abtravaff/html/newaffiliate/index.php'; $_SERVER['PHP_SELF'] = '/newaffiliate/index.php'; - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $result = $Dispatcher->baseUrl(); $expected = '/newaffiliate'; $this->assertEqual($expected, $result); @@ -1065,7 +1065,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testBaseUrlAndWebrootWithBaseUrl() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); Configure::write('App.dir', 'app'); @@ -1134,7 +1134,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testBaseUrlAndWebrootWithBase() { - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $Dispatcher->base = '/app'; $result = $Dispatcher->baseUrl(); $expected = '/app'; @@ -1164,7 +1164,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testMissingController() { - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_controller/home/param:value/param2:value2'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); @@ -1183,7 +1183,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testPrivate() { - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_pages/_protected/param:value/param2:value2'; @@ -1205,7 +1205,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testMissingAction() { - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_pages/home/param:value/param2:value2'; @@ -1220,7 +1220,7 @@ class DispatcherTest extends CakeTestCase { ))); $this->assertEqual($expected, $controller); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'some_pages/redirect/param:value/param2:value2'; @@ -1242,7 +1242,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testDispatch() { - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'pages/home/param:value/param2:value2'; @@ -1269,7 +1269,7 @@ class DispatcherTest extends CakeTestCase { unset($Dispatcher); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('App.baseUrl','/timesheets/index.php'); $url = 'timesheets'; @@ -1296,7 +1296,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testDispatchWithArray() { - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('App.baseUrl','/index.php'); $url = 'pages/home/param:value/param2:value2'; @@ -1316,7 +1316,7 @@ class DispatcherTest extends CakeTestCase { */ function testAdminDispatch() { $_POST = array(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('Routing.admin', 'admin'); Configure::write('App.baseUrl','/cake/repo/branches/1.2.x.x/index.php'); $url = 'admin/test_dispatch_pages/index/param:value/param2:value2'; @@ -1349,7 +1349,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Router::connect('/my_plugin/:controller/*', array('plugin'=>'my_plugin', 'controller'=>'pages', 'action'=>'display')); $Dispatcher->base = false; @@ -1397,7 +1397,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Router::connect('/my_plugin/:controller/:action/*', array('plugin'=>'my_plugin', 'controller'=>'pages', 'action'=>'display')); $Dispatcher->base = false; @@ -1434,7 +1434,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add/param:value/param2:value2'; @@ -1455,7 +1455,7 @@ class DispatcherTest extends CakeTestCase { Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; /* Simulates the Route for a real plugin, installed in APP/plugins */ @@ -1483,7 +1483,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('Routing.admin', 'admin'); Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'admin/my_plugin/add/5/param:value/param2:value2'; @@ -1503,7 +1503,7 @@ class DispatcherTest extends CakeTestCase { Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $controller = $Dispatcher->dispatch('admin/articles_test', array('return' => 1)); @@ -1536,21 +1536,21 @@ class DispatcherTest extends CakeTestCase { Router::reload(); Router::connect('/my_plugin/:controller/:action/*', array('plugin'=>'my_plugin')); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/my_plugin/add'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); $this->assertFalse(isset($controller->params['pass'][0])); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/my_plugin/add/0'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); $this->assertTrue(isset($controller->params['pass'][0])); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add'; @@ -1558,14 +1558,14 @@ class DispatcherTest extends CakeTestCase { $this->assertFalse(isset($controller->params['pass'][0])); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add/0'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); $this->assertIdentical('0',$controller->params['pass'][0]); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/add/1'; @@ -1583,7 +1583,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/not_here/param:value/param2:value2'; @@ -1599,7 +1599,7 @@ class DispatcherTest extends CakeTestCase { $this->assertIdentical($expected, $controller); Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'my_plugin/param:value/param2:value2'; @@ -1627,7 +1627,7 @@ class DispatcherTest extends CakeTestCase { Router::reload(); Router::connect('/admin/:controller/:action/*', array('prefix'=>'admin'), array('controller', 'action')); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $Dispatcher->base = false; $url = 'test_dispatch_pages/admin_index/param:value/param2:value2'; @@ -1648,7 +1648,7 @@ class DispatcherTest extends CakeTestCase { * @return void **/ function testTestPluginDispatch() { - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $_back = Configure::read('pluginPaths'); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); $url = '/test_plugin/tests/index'; @@ -1668,7 +1668,7 @@ class DispatcherTest extends CakeTestCase { */ function testChangingParamsFromBeforeFilter() { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); $url = 'some_posts/index/param:value/param2:value2'; $controller = $Dispatcher->dispatch($url, array('return' => 1)); @@ -1707,7 +1707,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); Configure::write('vendorPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS)); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Configure::write('debug', 0); ob_start(); @@ -1777,7 +1777,7 @@ class DispatcherTest extends CakeTestCase { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)); - $dispatcher = new Dispatcher(); + $dispatcher =& new Dispatcher(); $dispatcher->base = false; $url = '/'; @@ -1902,7 +1902,7 @@ class DispatcherTest extends CakeTestCase { Router::mapResources('Posts'); $_SERVER['REQUEST_METHOD'] = 'POST'; - $dispatcher = new Dispatcher(); + $dispatcher =& new Dispatcher(); $dispatcher->base = false; $result = $dispatcher->parseParams('/posts'); @@ -1956,7 +1956,7 @@ class DispatcherTest extends CakeTestCase { "/index.php/%22%3E%3Ch1%20onclick=%22alert('xss');%22%3Eheya%3C/h1%3E" ); - $dispatcher = new Dispatcher(); + $dispatcher =& new Dispatcher(); $result = $dispatcher->baseUrl(); $expected = '/index.php/h1 onclick=alert(xss);heya'; $this->assertEqual($result, $expected); @@ -1968,7 +1968,7 @@ class DispatcherTest extends CakeTestCase { * @return void */ function testEnvironmentDetection() { - $dispatcher = new Dispatcher(); + $dispatcher =& new Dispatcher(); $environments = array( 'IIS' => array( @@ -2077,7 +2077,7 @@ class DispatcherTest extends CakeTestCase { $_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php'; Router::reload(); - $Dispatcher = new TestDispatcher(); + $Dispatcher =& new TestDispatcher(); Router::connect('/myalias/:action/*', array('controller' => 'my_controller', 'action' => null)); $Dispatcher->base = false; diff --git a/cake/tests/cases/libs/cake_test_case.test.php b/cake/tests/cases/libs/cake_test_case.test.php index 56fa70d8..895eaaf4 100755 --- a/cake/tests/cases/libs/cake_test_case.test.php +++ b/cake/tests/cases/libs/cake_test_case.test.php @@ -78,8 +78,8 @@ class CakeTestCaseTest extends CakeTestCase { * @return void */ function setUp() { - $this->Case = new SubjectCakeTestCase(); - $reporter = new MockCakeHtmlReporter(); + $this->Case =& new SubjectCakeTestCase(); + $reporter =& new MockCakeHtmlReporter(); $this->Case->setReporter($reporter); $this->Reporter = $reporter; } @@ -265,7 +265,7 @@ class CakeTestCaseTest extends CakeTestCase { $this->assertEqual($result, array('var' => 'string')); $db =& ConnectionManager::getDataSource('test_suite'); - $fixture = new PostFixture(); + $fixture =& new PostFixture(); $fixture->create($db); $result = $this->Case->testAction('/tests_apps_posts/add', array('return' => 'vars')); @@ -321,7 +321,7 @@ class CakeTestCaseTest extends CakeTestCase { ConnectionManager::create('cake_test_case', $config); $db2 =& ConnectionManager::getDataSource('cake_test_case'); - $fixture = new PostFixture($db2); + $fixture =& new PostFixture($db2); $fixture->create($db2); $fixture->insert($db2); @@ -349,7 +349,7 @@ class CakeTestCaseTest extends CakeTestCase { ConnectionManager::create('cake_test_case', $config); $db =& ConnectionManager::getDataSource('cake_test_case'); - $fixture = new PostFixture($db); + $fixture =& new PostFixture($db); $fixture->create($db); $fixture->insert($db); @@ -399,8 +399,8 @@ class CakeTestCaseTest extends CakeTestCase { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS)); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); - $Dispatcher = new CakeTestDispatcher(); - $Case = new CakeDispatcherMockTestCase(); + $Dispatcher =& new CakeTestDispatcher(); + $Case =& new CakeDispatcherMockTestCase(); $Case->expectOnce('startController'); $Case->expectOnce('endController'); diff --git a/cake/tests/cases/libs/cake_test_fixture.test.php b/cake/tests/cases/libs/cake_test_fixture.test.php index a3c64608..d5844bc6 100755 --- a/cake/tests/cases/libs/cake_test_fixture.test.php +++ b/cake/tests/cases/libs/cake_test_fixture.test.php @@ -125,7 +125,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function setUp() { - $this->criticDb = new FixtureMockDboSource(); + $this->criticDb =& new FixtureMockDboSource(); $this->criticDb->fullDebug = true; } /** @@ -144,23 +144,23 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testInit() { - $Fixture = new CakeTestFixtureTestFixture(); + $Fixture =& new CakeTestFixtureTestFixture(); unset($Fixture->table); $Fixture->init(); $this->assertEqual($Fixture->table, 'fixture_tests'); $this->assertEqual($Fixture->primaryKey, 'id'); - $Fixture = new CakeTestFixtureTestFixture(); + $Fixture =& new CakeTestFixtureTestFixture(); $Fixture->primaryKey = 'my_random_key'; $Fixture->init(); $this->assertEqual($Fixture->primaryKey, 'my_random_key'); $this->_initDb(); - $Source = new CakeTestFixtureTestFixture(); + $Source =& new CakeTestFixtureTestFixture(); $Source->create($this->db); $Source->insert($this->db); - $Fixture = new CakeTestFixtureImportFixture(); + $Fixture =& new CakeTestFixtureImportFixture(); $expected = array('id', 'name', 'created'); $this->assertEqual(array_keys($Fixture->fields), $expected); @@ -174,7 +174,7 @@ class CakeTestFixtureTest extends CakeTestCase { $Fixture->init(); $this->assertEqual(count($Fixture->records), count($Source->records)); - $Fixture = new CakeTestFixtureImportFixture(); + $Fixture =& new CakeTestFixtureImportFixture(); $Fixture->fields = $Fixture->records = null; $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test_suite'); $Fixture->init(); @@ -201,13 +201,13 @@ class CakeTestFixtureTest extends CakeTestCase { ConnectionManager::create('new_test_suite', array_merge($testSuiteConfig, array('prefix' => 'new_' . $testSuiteConfig['prefix']))); $newTestSuiteDb =& ConnectionManager::getDataSource('new_test_suite'); - $Source = new CakeTestFixtureTestFixture(); + $Source =& new CakeTestFixtureTestFixture(); $Source->create($newTestSuiteDb); $Source->insert($newTestSuiteDb); $defaultDb->config = $newTestSuiteDb->config; - $Fixture = new CakeTestFixtureDefaultImportFixture(); + $Fixture =& new CakeTestFixtureDefaultImportFixture(); $Fixture->fields = $Fixture->records = null; $Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite'); $Fixture->init(); @@ -227,7 +227,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testCreate() { - $Fixture = new CakeTestFixtureTestFixture(); + $Fixture =& new CakeTestFixtureTestFixture(); $this->criticDb->expectAtLeastOnce('execute'); $this->criticDb->expectAtLeastOnce('createSchema'); $return = $Fixture->create($this->criticDb); @@ -245,7 +245,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testInsert() { - $Fixture = new CakeTestFixtureTestFixture(); + $Fixture =& new CakeTestFixtureTestFixture(); $this->criticDb->setReturnValue('insertMulti', true); $this->criticDb->expectAtLeastOnce('insertMulti'); @@ -260,7 +260,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testDrop() { - $Fixture = new CakeTestFixtureTestFixture(); + $Fixture =& new CakeTestFixtureTestFixture(); $this->criticDb->setReturnValueAt(0, 'execute', true); $this->criticDb->expectAtLeastOnce('execute'); $this->criticDb->expectAtLeastOnce('dropSchema'); @@ -280,7 +280,7 @@ class CakeTestFixtureTest extends CakeTestCase { * @return void */ function testTruncate() { - $Fixture = new CakeTestFixtureTestFixture(); + $Fixture =& new CakeTestFixtureTestFixture(); $this->criticDb->expectAtLeastOnce('truncate'); $Fixture->truncate($this->criticDb); $this->assertTrue($this->criticDb->fullDebug); diff --git a/cake/tests/cases/libs/code_coverage_manager.test.php b/cake/tests/cases/libs/code_coverage_manager.test.php index ef18aff5..9a1e6c41 100755 --- a/cake/tests/cases/libs/code_coverage_manager.test.php +++ b/cake/tests/cases/libs/code_coverage_manager.test.php @@ -158,7 +158,7 @@ class CodeCoverageManagerTest extends CakeTestCase { * @package cake * @subpackage cake.tests.cases.libs */ - class Set extends CakeObject { + class Set extends Object { /** * Value of the Set object. * @@ -315,7 +315,7 @@ PHP; * @package cake * @subpackage cake.tests.cases.libs */ - class Set extends CakeObject { + class Set extends Object { /** * Value of the Set object. * diff --git a/cake/tests/cases/libs/controller/component.test.php b/cake/tests/cases/libs/controller/component.test.php index 4013c6b1..e3f78b28 100755 --- a/cake/tests/cases/libs/controller/component.test.php +++ b/cake/tests/cases/libs/controller/component.test.php @@ -72,7 +72,7 @@ if (!class_exists('AppController')) { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class ParamTestComponent extends CakeObject { +class ParamTestComponent extends Object { /** * name property * @@ -133,7 +133,7 @@ class ComponentTestController extends AppController { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class AppleComponent extends CakeObject { +class AppleComponent extends Object { /** * components property * @@ -165,7 +165,7 @@ class AppleComponent extends CakeObject { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class OrangeComponent extends CakeObject { +class OrangeComponent extends Object { /** * components property * @@ -202,7 +202,7 @@ class OrangeComponent extends CakeObject { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class BananaComponent extends CakeObject { +class BananaComponent extends Object { /** * testField property * @@ -227,7 +227,7 @@ class BananaComponent extends CakeObject { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class MutuallyReferencingOneComponent extends CakeObject { +class MutuallyReferencingOneComponent extends Object { /** * components property * @@ -242,7 +242,7 @@ class MutuallyReferencingOneComponent extends CakeObject { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class MutuallyReferencingTwoComponent extends CakeObject { +class MutuallyReferencingTwoComponent extends Object { /** * components property * @@ -257,7 +257,7 @@ class MutuallyReferencingTwoComponent extends CakeObject { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class SomethingWithEmailComponent extends CakeObject { +class SomethingWithEmailComponent extends Object { /** * components property * @@ -302,19 +302,19 @@ class ComponentTest extends CakeTestCase { * @return void */ function testLoadComponents() { - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('RequestHandler'); - $Component = new Component(); + $Component =& new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->RequestHandler, 'RequestHandlerComponent')); - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->plugin = 'test_plugin'; $Controller->components = array('RequestHandler', 'TestPluginComponent'); - $Component = new Component(); + $Component =& new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->RequestHandler, 'RequestHandlerComponent')); @@ -325,19 +325,19 @@ class ComponentTest extends CakeTestCase { )); $this->assertFalse(isset($Controller->TestPluginOtherComponent)); - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('Security'); - $Component = new Component(); + $Component =& new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->Security, 'SecurityComponent')); $this->assertTrue(is_a($Controller->Security->Session, 'SessionComponent')); - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('Security', 'Cookie', 'RequestHandler'); - $Component = new Component(); + $Component =& new Component(); $Component->init($Controller); $this->assertTrue(is_a($Controller->Security, 'SecurityComponent')); @@ -351,7 +351,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testNestedComponentLoading() { - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('Apple'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -370,7 +370,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testComponentStartup() { - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('Apple'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -390,7 +390,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testMultipleComponentInitialize() { - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('Orange', 'Banana'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -409,7 +409,7 @@ class ComponentTest extends CakeTestCase { return; } - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('ParamTest' => array('test' => 'value', 'flag'), 'Apple'); $Controller->constructClasses(); @@ -424,7 +424,7 @@ class ComponentTest extends CakeTestCase { $this->assertEqual($Controller->ParamTest->flag, true); //Settings are merged from app controller and current controller. - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array( 'ParamTest' => array('test' => 'value'), 'Orange' => array('ripeness' => 'perfect') @@ -443,7 +443,7 @@ class ComponentTest extends CakeTestCase { * @return void **/ function testComponentParamsNoDuplication() { - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('Orange' => array('setting' => array('itemx'))); $Controller->constructClasses(); @@ -457,7 +457,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testMutuallyReferencingComponents() { - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('MutuallyReferencingOne'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -481,7 +481,7 @@ class ComponentTest extends CakeTestCase { * @return void */ function testSomethingReferencingEmailComponent() { - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->components = array('SomethingWithEmail'); $Controller->constructClasses(); $Controller->Component->initialize($Controller); @@ -510,7 +510,7 @@ class ComponentTest extends CakeTestCase { function testDoubleLoadingOfSessionComponent() { $this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController'); - $Controller = new ComponentTestController(); + $Controller =& new ComponentTestController(); $Controller->uses = array(); $Controller->components = array('Session'); $Controller->constructClasses(); diff --git a/cake/tests/cases/libs/controller/components/acl.test.php b/cake/tests/cases/libs/controller/components/acl.test.php index f33eeef0..755d7ae1 100755 --- a/cake/tests/cases/libs/controller/components/acl.test.php +++ b/cake/tests/cases/libs/controller/components/acl.test.php @@ -165,10 +165,10 @@ class DbAclTwoTest extends DbAcl { * @return void */ function __construct() { - $this->Aro = new AroTwoTest(); - $this->Aro->Permission = new PermissionTwoTest(); - $this->Aco = new AcoTwoTest(); - $this->Aro->Permission = new PermissionTwoTest(); + $this->Aro =& new AroTwoTest(); + $this->Aro->Permission =& new PermissionTwoTest(); + $this->Aco =& new AcoTwoTest(); + $this->Aro->Permission =& new PermissionTwoTest(); } } /** @@ -200,7 +200,7 @@ class AclComponentTest extends CakeTestCase { * @return void */ function startTest() { - $this->Acl = new AclComponent(); + $this->Acl =& new AclComponent(); } /** * before method diff --git a/cake/tests/cases/libs/controller/components/auth.test.php b/cake/tests/cases/libs/controller/components/auth.test.php index 3bf3358f..481b2dd5 100755 --- a/cake/tests/cases/libs/controller/components/auth.test.php +++ b/cake/tests/cases/libs/controller/components/auth.test.php @@ -445,7 +445,7 @@ class AuthTest extends CakeTestCase { Configure::write('Acl.database', 'test_suite'); Configure::write('Acl.classname', 'DbAcl'); - $this->Controller = new AuthTestController(); + $this->Controller =& new AuthTestController(); $this->Controller->Component->init($this->Controller); ClassRegistry::addObject('view', new View($this->Controller)); @@ -509,7 +509,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testLogin() { - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $user['id'] = 1; $user['username'] = 'mariano'; $user['password'] = Security::hash(Configure::read('Security.salt') . 'cake'); @@ -580,7 +580,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeFalse() { - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); $this->Controller->Auth->userModel = 'AuthUser'; @@ -605,7 +605,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeController() { - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); $this->Controller->Auth->userModel = 'AuthUser'; @@ -628,7 +628,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeModel() { - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); @@ -653,7 +653,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testAuthorizeCrud() { - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $user = $this->AuthUser->find(); $this->Controller->Session->write('Auth', $user); @@ -951,7 +951,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testEmptyUsernameOrPassword() { - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $user['id'] = 1; $user['username'] = 'mariano'; $user['password'] = Security::hash(Configure::read('Security.salt') . 'cake'); @@ -981,7 +981,7 @@ class AuthTest extends CakeTestCase { * @return void */ function testInjection() { - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $this->AuthUser->id = 2; $this->AuthUser->saveField('password', Security::hash(Configure::read('Security.salt') . 'cake')); @@ -1086,7 +1086,7 @@ class AuthTest extends CakeTestCase { 'argSeparator' => ':', 'namedArgs' => array() ))); - $this->AuthUser = new AuthUser(); + $this->AuthUser =& new AuthUser(); $user = array( 'id' => 1, 'username' => 'felix', 'password' => Security::hash(Configure::read('Security.salt') . 'cake' @@ -1131,7 +1131,7 @@ class AuthTest extends CakeTestCase { function testCustomField() { Router::reload(); - $this->AuthUserCustomField = new AuthUserCustomField(); + $this->AuthUserCustomField =& new AuthUserCustomField(); $user = array( 'id' => 1, 'email' => 'harking@example.com', 'password' => Security::hash(Configure::read('Security.salt') . 'cake' @@ -1208,7 +1208,7 @@ class AuthTest extends CakeTestCase { } ob_start(); - $Dispatcher = new Dispatcher(); + $Dispatcher =& new Dispatcher(); $Dispatcher->dispatch('/ajax_auth/add', array('return' => 1)); $result = ob_get_clean(); $this->assertEqual("Ajax!\nthis is the test element", $result); diff --git a/cake/tests/cases/libs/controller/components/email.test.php b/cake/tests/cases/libs/controller/components/email.test.php index 44feb8db..8baf95e4 100755 --- a/cake/tests/cases/libs/controller/components/email.test.php +++ b/cake/tests/cases/libs/controller/components/email.test.php @@ -181,7 +181,7 @@ class EmailComponentTest extends CakeTestCase { $this->_appEncoding = Configure::read('App.encoding'); Configure::write('App.encoding', 'UTF-8'); - $this->Controller = new EmailTestController(); + $this->Controller =& new EmailTestController(); restore_error_handler(); @$this->Controller->Component->init($this->Controller); @@ -470,7 +470,7 @@ TEXTBLOC; $this->skipIf(!@fsockopen('localhost', 25), '%s No SMTP server running on localhost'); $this->Controller->EmailTest->reset(); - $socket = new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->Controller->EmailTest->smtpOptions)); + $socket =& new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->Controller->EmailTest->smtpOptions)); $this->Controller->EmailTest->setConnectionSocket($socket); $this->assertTrue($this->Controller->EmailTest->getConnectionSocket()); diff --git a/cake/tests/cases/libs/controller/components/security.test.php b/cake/tests/cases/libs/controller/components/security.test.php index fe2a2df9..f744f2dc 100755 --- a/cake/tests/cases/libs/controller/components/security.test.php +++ b/cake/tests/cases/libs/controller/components/security.test.php @@ -137,7 +137,7 @@ class SecurityComponentTest extends CakeTestCase { * @return void */ function setUp() { - $this->Controller = new SecurityTestController(); + $this->Controller =& new SecurityTestController(); $this->Controller->Component->init($this->Controller); $this->Controller->Security =& $this->Controller->TestSecurity; $this->Controller->Security->blackHoleCallback = 'fail'; diff --git a/cake/tests/cases/libs/controller/components/session.test.php b/cake/tests/cases/libs/controller/components/session.test.php index 25802217..b79f043c 100755 --- a/cake/tests/cases/libs/controller/components/session.test.php +++ b/cake/tests/cases/libs/controller/components/session.test.php @@ -107,20 +107,20 @@ class SessionComponentTest extends CakeTestCase { */ function testSessionAutoStart() { Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->__active); $this->assertFalse($Session->__started); $Session->startup(new SessionTestController()); Configure::write('Session.start', true); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertTrue($Session->__active); $this->assertFalse($Session->__started); $Session->startup(new SessionTestController()); $this->assertTrue(isset($_SESSION)); $Object = new Object(); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $Session->start(); $expected = $Session->id(); @@ -137,14 +137,14 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionInitialize() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertEqual($Session->__bare, 0); $Session->initialize(new SessionTestController()); $this->assertEqual($Session->__bare, 0); - $sessionController = new SessionTestController(); + $sessionController =& new SessionTestController(); $sessionController->params['bare'] = 1; $Session->initialize($sessionController); $this->assertEqual($Session->__bare, 1); @@ -156,14 +156,14 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionActivate() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertTrue($Session->__active); $this->assertNull($Session->activate()); $this->assertTrue($Session->__active); Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->__active); $this->assertNull($Session->activate()); $this->assertTrue($Session->__active); @@ -177,7 +177,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionValid() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertTrue($Session->valid()); @@ -185,17 +185,17 @@ class SessionComponentTest extends CakeTestCase { $this->assertFalse($Session->valid()); Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->__active); $this->assertFalse($Session->valid()); Configure::write('Session.start', true); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $Session->time = $Session->read('Config.time') + 1; $this->assertFalse($Session->valid()); Configure::write('Session.checkAgent', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $Session->time = $Session->read('Config.time') + 1; $this->assertFalse($Session->valid()); Configure::write('Session.checkAgent', true); @@ -207,12 +207,12 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionError() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->error()); Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->__active); $this->assertFalse($Session->error()); Configure::write('Session.start', true); @@ -224,7 +224,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionReadWrite() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->read('Test')); @@ -251,7 +251,7 @@ class SessionComponentTest extends CakeTestCase { $Session->del('Test'); Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->write('Test', 'some value')); $Session->write('Test', 'some value'); $this->assertFalse($Session->read('Test')); @@ -264,7 +264,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionDel() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->del('Test')); @@ -272,7 +272,7 @@ class SessionComponentTest extends CakeTestCase { $this->assertTrue($Session->del('Test')); Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $Session->write('Test', 'some value'); $this->assertFalse($Session->del('Test')); Configure::write('Session.start', true); @@ -284,7 +284,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionDelete() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->delete('Test')); @@ -292,7 +292,7 @@ class SessionComponentTest extends CakeTestCase { $this->assertTrue($Session->delete('Test')); Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $Session->write('Test', 'some value'); $this->assertFalse($Session->delete('Test')); Configure::write('Session.start', true); @@ -304,7 +304,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionCheck() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertFalse($Session->check('Test')); @@ -313,7 +313,7 @@ class SessionComponentTest extends CakeTestCase { $Session->delete('Test'); Configure::write('Session.start', false); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $Session->write('Test', 'some value'); $this->assertFalse($Session->check('Test')); Configure::write('Session.start', true); @@ -325,7 +325,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionFlash() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertNull($Session->read('Message.flash')); @@ -351,7 +351,7 @@ class SessionComponentTest extends CakeTestCase { */ function testSessionId() { unset($_SESSION); - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $this->assertNull($Session->id()); } /** @@ -361,7 +361,7 @@ class SessionComponentTest extends CakeTestCase { * @return void */ function testSessionDestroy() { - $Session = new SessionComponent(); + $Session =& new SessionComponent(); $Session->write('Test', 'some value'); $this->assertEqual($Session->read('Test'), 'some value'); diff --git a/cake/tests/cases/libs/controller/controller.test.php b/cake/tests/cases/libs/controller/controller.test.php index 90baed20..8c7b3204 100755 --- a/cake/tests/cases/libs/controller/controller.test.php +++ b/cake/tests/cases/libs/controller/controller.test.php @@ -328,7 +328,7 @@ class TestController extends AppController { * @package cake * @subpackage cake.tests.cases.libs.controller */ -class TestComponent extends CakeObject { +class TestComponent extends Object { /** * beforeRedirect method * @@ -380,7 +380,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testConstructClasses() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->modelClass = 'ControllerPost'; $Controller->passedArgs[] = '1'; $Controller->constructClasses(); @@ -388,7 +388,7 @@ class ControllerTest extends CakeTestCase { unset($Controller); - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->constructClasses(); @@ -404,7 +404,7 @@ class ControllerTest extends CakeTestCase { ); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('TestPlugin.TestPluginPost'); $Controller->constructClasses(); @@ -422,7 +422,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testAliasName() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('NameTest'); $Controller->constructClasses(); @@ -439,7 +439,7 @@ class ControllerTest extends CakeTestCase { */ function testPersistent() { Configure::write('Cache.disable', false); - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->modelClass = 'ControllerPost'; $Controller->persistModel = true; $Controller->constructClasses(); @@ -458,7 +458,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testPaginate() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); @@ -519,7 +519,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testPaginateExtraParams() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); @@ -551,7 +551,7 @@ class ControllerTest extends CakeTestCase { $this->assertEqual($Controller->ControllerPost->lastQuery['limit'], 12); $this->assertEqual($paging['options']['limit'], 12); - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('ControllerPaginateModel'); $Controller->params['url'] = array(); $Controller->constructClasses(); @@ -578,7 +578,7 @@ class ControllerTest extends CakeTestCase { * @access public */ function testPaginatePassedArgs() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('ControllerPost'); $Controller->passedArgs[] = array('1', '2', '3'); $Controller->params['url'] = array(); @@ -610,7 +610,7 @@ class ControllerTest extends CakeTestCase { * @return void **/ function testPaginateSpecialType() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('ControllerPost', 'ControllerComment'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); @@ -631,7 +631,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testDefaultPaginateParams() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->modelClass = 'ControllerPost'; $Controller->params['url'] = array(); $Controller->paginate = array('order' => 'ControllerPost.id DESC'); @@ -648,7 +648,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testFlash() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->flash('this should work', '/flash'); $result = $Controller->output; @@ -678,7 +678,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testControllerSet() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->set('variable_with_underscores', null); $this->assertTrue(array_key_exists('variable_with_underscores', $Controller->viewVars)); @@ -713,7 +713,7 @@ class ControllerTest extends CakeTestCase { function testRender() { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)); - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->viewPath = 'posts'; $result = $Controller->render('index'); @@ -744,7 +744,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testToBeInheritedGuardmethods() { - $Controller = new Controller(); + $Controller =& new Controller(); $this->assertTrue($Controller->_beforeScaffold('')); $this->assertTrue($Controller->_afterScaffoldSave('')); $this->assertTrue($Controller->_afterScaffoldSaveError('')); @@ -806,8 +806,8 @@ class ControllerTest extends CakeTestCase { App::import('Helper', 'Cache'); foreach ($codes as $code => $msg) { - $MockController = new MockController(); - $MockController->Component = new Component(); + $MockController =& new MockController(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array("HTTP/1.1 {$code} {$msg}")); $MockController->expectAt(1, 'header', array('Location: http://cakephp.org')); @@ -816,8 +816,8 @@ class ControllerTest extends CakeTestCase { $this->assertFalse($MockController->autoRender); } foreach ($codes as $code => $msg) { - $MockController = new MockController(); - $MockController->Component = new Component(); + $MockController =& new MockController(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array("HTTP/1.1 {$code} {$msg}")); $MockController->expectAt(1, 'header', array('Location: http://cakephp.org')); @@ -826,24 +826,24 @@ class ControllerTest extends CakeTestCase { $this->assertFalse($MockController->autoRender); } - $MockController = new MockController(); - $MockController->Component = new Component(); + $MockController =& new MockController(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array('Location: http://www.example.org/users/login')); $MockController->expectCallCount('header', 1); $MockController->redirect('http://www.example.org/users/login', null, false); - $MockController = new MockController(); - $MockController->Component = new Component(); + $MockController =& new MockController(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently')); $MockController->expectAt(1, 'header', array('Location: http://www.example.org/users/login')); $MockController->expectCallCount('header', 2); $MockController->redirect('http://www.example.org/users/login', 301, false); - $MockController = new MockController(); + $MockController =& new MockController(); $MockController->components = array('MockTest'); - $MockController->Component = new Component(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', null); $MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently')); @@ -851,9 +851,9 @@ class ControllerTest extends CakeTestCase { $MockController->expectCallCount('header', 2); $MockController->redirect('http://cakephp.org', 301, false); - $MockController = new MockController(); + $MockController =& new MockController(); $MockController->components = array('MockTest'); - $MockController->Component = new Component(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org'); $MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently')); @@ -861,17 +861,17 @@ class ControllerTest extends CakeTestCase { $MockController->expectCallCount('header', 2); $MockController->redirect('http://cakephp.org', 301, false); - $MockController = new MockController(); + $MockController =& new MockController(); $MockController->components = array('MockTest'); - $MockController->Component = new Component(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', false); $MockController->expectNever('header'); $MockController->redirect('http://cakephp.org', 301, false); - $MockController = new MockController(); + $MockController =& new MockController(); $MockController->components = array('MockTest', 'MockTestB'); - $MockController->Component = new Component(); + $MockController->Component =& new Component(); $MockController->Component->init($MockController); $MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org'); $MockController->MockTestB->setReturnValue('beforeRedirect', 'http://bakery.cakephp.org'); @@ -891,7 +891,7 @@ class ControllerTest extends CakeTestCase { return; } - $TestController = new TestController(); + $TestController =& new TestController(); $TestController->constructClasses(); $testVars = get_class_vars('TestController'); @@ -914,7 +914,7 @@ class ControllerTest extends CakeTestCase { $this->assertEqual(count(array_diff($TestController->uses, $uses)), 0); $this->assertEqual(count(array_diff_assoc(Set::normalize($TestController->components), Set::normalize($components))), 0); - $TestController = new AnotherTestController(); + $TestController =& new AnotherTestController(); $TestController->constructClasses(); $appVars = get_class_vars('AppController'); @@ -927,7 +927,7 @@ class ControllerTest extends CakeTestCase { $this->assertFalse(isset($TestController->ControllerPost)); - $TestController = new ControllerCommentsController(); + $TestController =& new ControllerCommentsController(); $TestController->constructClasses(); $appVars = get_class_vars('AppController'); @@ -950,7 +950,7 @@ class ControllerTest extends CakeTestCase { if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) { return; } - $TestController = new TestController(); + $TestController =& new TestController(); $expected = array('foo'); $TestController->components = array('Cookie' => $expected); $TestController->constructClasses(); @@ -963,7 +963,7 @@ class ControllerTest extends CakeTestCase { * @return void **/ function testMergeVarsNotGreedy() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->components = array(); $Controller->uses = array(); $Controller->constructClasses(); @@ -977,7 +977,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testReferer() { - $Controller = new Controller(); + $Controller =& new Controller(); $_SERVER['HTTP_REFERER'] = 'http://cakephp.org'; $result = $Controller->referer(null, false); $expected = 'http://cakephp.org'; @@ -1023,7 +1023,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testSetAction() { - $TestController = new TestController(); + $TestController =& new TestController(); $TestController->setAction('index', 1, 2); $expected = array('testId' => 1, 'test2Id' => 2); $this->assertidentical($TestController->data, $expected); @@ -1035,7 +1035,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testUnimplementedIsAuthorized() { - $TestController = new TestController(); + $TestController =& new TestController(); $TestController->isAuthorized(); $this->assertError(); } @@ -1046,7 +1046,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testValidateErrors() { - $TestController = new TestController(); + $TestController =& new TestController(); $TestController->constructClasses(); $this->assertFalse($TestController->validateErrors()); $this->assertEqual($TestController->validate(), 0); @@ -1067,7 +1067,7 @@ class ControllerTest extends CakeTestCase { * @return void */ function testPostConditions() { - $Controller = new Controller(); + $Controller =& new Controller(); $data = array( @@ -1132,7 +1132,7 @@ class ControllerTest extends CakeTestCase { */ function testRequestHandlerPrefers(){ Configure::write('debug', 2); - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->components = array("RequestHandler"); $Controller->modelClass='ControllerPost'; $Controller->params['url']['ext'] = 'rss'; diff --git a/cake/tests/cases/libs/controller/controller_merge_vars.test.php b/cake/tests/cases/libs/controller/controller_merge_vars.test.php index b7cf274c..b405d3ec 100755 --- a/cake/tests/cases/libs/controller/controller_merge_vars.test.php +++ b/cake/tests/cases/libs/controller/controller_merge_vars.test.php @@ -53,7 +53,7 @@ if (!class_exists('AppController')) { * * @package cake.tests.cases.libs.controller **/ -class MergeVarComponent extends CakeObject { +class MergeVarComponent extends Object { } @@ -139,7 +139,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testComponentParamMergingNoDuplication() { - $Controller = new MergeVariablesController(); + $Controller =& new MergeVariablesController(); $Controller->constructClasses(); $expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false)); @@ -151,7 +151,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testComponentMergingWithRedeclarations() { - $Controller = new MergeVariablesController(); + $Controller =& new MergeVariablesController(); $Controller->components['MergeVar'] = array('remote', 'redirect' => true); $Controller->constructClasses(); @@ -164,7 +164,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testHelperSettingMergingNoDuplication() { - $Controller = new MergeVariablesController(); + $Controller =& new MergeVariablesController(); $Controller->constructClasses(); $expected = array('MergeVar' => array('format' => 'html', 'terse')); @@ -176,7 +176,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testMergeVarsWithPlugin() { - $Controller = new MergePostsController(); + $Controller =& new MergePostsController(); $Controller->components = array('Email' => array('ports' => 'open')); $Controller->plugin = 'MergeVarPlugin'; $Controller->constructClasses(); @@ -194,7 +194,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { ); $this->assertEqual($Controller->helpers, $expected, 'Helpers are unexpected %s'); - $Controller = new MergePostsController(); + $Controller =& new MergePostsController(); $Controller->components = array(); $Controller->plugin = 'MergeVarPlugin'; $Controller->constructClasses(); @@ -212,7 +212,7 @@ class ControllerMergeVarsTestCase extends CakeTestCase { * @return void **/ function testMergeVarsNotGreedy() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->components = array(); $Controller->uses = array(); $Controller->constructClasses(); diff --git a/cake/tests/cases/libs/controller/pages_controller.test.php b/cake/tests/cases/libs/controller/pages_controller.test.php index 53aef113..66980e74 100755 --- a/cake/tests/cases/libs/controller/pages_controller.test.php +++ b/cake/tests/cases/libs/controller/pages_controller.test.php @@ -67,7 +67,7 @@ class PagesControllerTest extends CakeTestCase { } Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)); - $Pages = new PagesController(); + $Pages =& new PagesController(); $Pages->viewPath = 'posts'; $Pages->display('index'); diff --git a/cake/tests/cases/libs/controller/scaffold.test.php b/cake/tests/cases/libs/controller/scaffold.test.php index c22822bd..72cab3eb 100755 --- a/cake/tests/cases/libs/controller/scaffold.test.php +++ b/cake/tests/cases/libs/controller/scaffold.test.php @@ -262,7 +262,7 @@ class ScaffoldViewTest extends CakeTestCase { * @return void */ function startTest() { - $this->Controller = new ScaffoldMockController(); + $this->Controller =& new ScaffoldMockController(); } /** * endTest method @@ -284,7 +284,7 @@ class ScaffoldViewTest extends CakeTestCase { Configure::write('Routing.admin', 'admin'); $this->Controller->action = 'index'; - $ScaffoldView = new TestScaffoldView($this->Controller); + $ScaffoldView =& new TestScaffoldView($this->Controller); $result = $ScaffoldView->testGetFilename('index'); $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'index.ctp'; $this->assertEqual($result, $expected); @@ -328,11 +328,11 @@ class ScaffoldViewTest extends CakeTestCase { Configure::write('viewPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS)); Configure::write('pluginPaths', array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)); - $Controller = new ScaffoldMockController(); + $Controller =& new ScaffoldMockController(); $Controller->scaffold = 'admin'; $Controller->viewPath = 'posts'; $Controller->action = 'admin_edit'; - $ScaffoldView = new TestScaffoldView($Controller); + $ScaffoldView =& new TestScaffoldView($Controller); $result = $ScaffoldView->testGetFilename('admin_edit'); $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp'; $this->assertEqual($result, $expected); @@ -341,12 +341,12 @@ class ScaffoldViewTest extends CakeTestCase { $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp'; $this->assertEqual($result, $expected); - $Controller = new ScaffoldMockController(); + $Controller =& new ScaffoldMockController(); $Controller->scaffold = 'admin'; $Controller->viewPath = 'tests'; $Controller->plugin = 'test_plugin'; $Controller->action = 'admin_add'; - $ScaffoldView = new TestScaffoldView($Controller); + $ScaffoldView =& new TestScaffoldView($Controller); $result = $ScaffoldView->testGetFilename('admin_add'); $expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS .'test_plugin' . DS . 'views' . DS . 'tests' . DS . 'scaffold.edit.ctp'; @@ -595,7 +595,7 @@ class ScaffoldTest extends CakeTestCase { * @return void */ function startTest() { - $this->Controller = new ScaffoldMockController(); + $this->Controller =& new ScaffoldMockController(); } /** * endTest method @@ -634,7 +634,7 @@ class ScaffoldTest extends CakeTestCase { $this->Controller->controller = 'scaffold_mock'; $this->Controller->base = '/'; $this->Controller->constructClasses(); - $Scaffold = new TestScaffoldMock($this->Controller, $params); + $Scaffold =& new TestScaffoldMock($this->Controller, $params); $result = $Scaffold->getParams(); $this->assertEqual($result['action'], 'admin_edit'); } @@ -664,7 +664,7 @@ class ScaffoldTest extends CakeTestCase { $this->Controller->controller = 'scaffold_mock'; $this->Controller->base = '/'; $this->Controller->constructClasses(); - $Scaffold = new TestScaffoldMock($this->Controller, $params); + $Scaffold =& new TestScaffoldMock($this->Controller, $params); $result = $Scaffold->controller->viewVars; $this->assertEqual($result['singularHumanName'], 'Scaffold Mock'); diff --git a/cake/tests/cases/libs/error.test.php b/cake/tests/cases/libs/error.test.php index 550fb1ef..e3d233e1 100755 --- a/cake/tests/cases/libs/error.test.php +++ b/cake/tests/cases/libs/error.test.php @@ -36,7 +36,7 @@ if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) { * @package cake * @subpackage cake.tests.cases.libs */ -class BlueberryComponent extends CakeObject { +class BlueberryComponent extends Object { /** * testName property * @@ -261,7 +261,7 @@ class ErrorHandlerTest extends CakeTestCase { $this->assertPattern("/'\/test_error'<\/strong>/", $result); ob_start(); - $TestErrorHandler = new TestErrorHandler('error404', array('message' => 'Page not found')); + $TestErrorHandler =& new TestErrorHandler('error404', array('message' => 'Page not found')); ob_get_clean(); ob_start(); $TestErrorHandler->error404(array( diff --git a/cake/tests/cases/libs/file.test.php b/cake/tests/cases/libs/file.test.php index ad668e1b..f0d64a7b 100755 --- a/cake/tests/cases/libs/file.test.php +++ b/cake/tests/cases/libs/file.test.php @@ -47,7 +47,7 @@ class FileTest extends CakeTestCase { */ function testBasic() { $file = __FILE__; - $this->File = new File($file); + $this->File =& new File($file); $result = $this->File->pwd(); $expecting = $file; @@ -209,7 +209,7 @@ class FileTest extends CakeTestCase { */ function testCreate() { $tmpFile = TMP.'tests'.DS.'cakephp.file.test.tmp'; - $File = new File($tmpFile, true, 0777); + $File =& new File($tmpFile, true, 0777); $this->assertTrue($File->exists()); } /** @@ -219,7 +219,7 @@ class FileTest extends CakeTestCase { * @return void */ function testOpeningNonExistantFileCreatesIt() { - $someFile = new File(TMP . 'some_file.txt', false); + $someFile =& new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertEqual($someFile->read(), ''); $someFile->close(); @@ -252,7 +252,7 @@ class FileTest extends CakeTestCase { * @return void */ function testReadable() { - $someFile = new File(TMP . 'some_file.txt', false); + $someFile =& new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertTrue($someFile->readable()); $someFile->close(); @@ -265,7 +265,7 @@ class FileTest extends CakeTestCase { * @return void */ function testWritable() { - $someFile = new File(TMP . 'some_file.txt', false); + $someFile =& new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertTrue($someFile->writable()); $someFile->close(); @@ -278,7 +278,7 @@ class FileTest extends CakeTestCase { * @return void */ function testExecutable() { - $someFile = new File(TMP . 'some_file.txt', false); + $someFile =& new File(TMP . 'some_file.txt', false); $this->assertTrue($someFile->open()); $this->assertFalse($someFile->executable()); $someFile->close(); @@ -291,7 +291,7 @@ class FileTest extends CakeTestCase { * @return void */ function testLastAccess() { - $someFile = new File(TMP . 'some_file.txt', false); + $someFile =& new File(TMP . 'some_file.txt', false); $this->assertFalse($someFile->lastAccess()); $this->assertTrue($someFile->open()); $this->assertEqual($someFile->lastAccess(), time()); @@ -305,7 +305,7 @@ class FileTest extends CakeTestCase { * @return void */ function testLastChange() { - $someFile = new File(TMP . 'some_file.txt', false); + $someFile =& new File(TMP . 'some_file.txt', false); $this->assertFalse($someFile->lastChange()); $this->assertTrue($someFile->open('r+')); $this->assertEqual($someFile->lastChange(), time()); @@ -328,7 +328,7 @@ class FileTest extends CakeTestCase { unlink($tmpFile); } - $TmpFile = new File($tmpFile); + $TmpFile =& new File($tmpFile); $this->assertFalse(file_exists($tmpFile)); $this->assertFalse(is_resource($TmpFile->handle)); @@ -358,7 +358,7 @@ class FileTest extends CakeTestCase { unlink($tmpFile); } - $TmpFile = new File($tmpFile); + $TmpFile =& new File($tmpFile); $this->assertFalse(file_exists($tmpFile)); $fragments = array('CakePHP\'s', ' test suite', ' was here ...', ''); @@ -386,13 +386,13 @@ class FileTest extends CakeTestCase { if (!file_exists($tmpFile)) { touch($tmpFile); } - $TmpFile = new File($tmpFile); + $TmpFile =& new File($tmpFile); $this->assertTrue(file_exists($tmpFile)); $result = $TmpFile->delete(); $this->assertTrue($result); $this->assertFalse(file_exists($tmpFile)); - $TmpFile = new File('/this/does/not/exist'); + $TmpFile =& new File('/this/does/not/exist'); $result = $TmpFile->delete(); $this->assertFalse($result); } diff --git a/cake/tests/cases/libs/folder.test.php b/cake/tests/cases/libs/folder.test.php index a3915a09..6fad570d 100755 --- a/cake/tests/cases/libs/folder.test.php +++ b/cake/tests/cases/libs/folder.test.php @@ -40,7 +40,7 @@ class FolderTest extends CakeTestCase { */ function testBasic() { $path = dirname(__FILE__); - $Folder = new Folder($path); + $Folder =& new Folder($path); $result = $Folder->pwd(); $this->assertEqual($result, $path); @@ -66,7 +66,7 @@ class FolderTest extends CakeTestCase { $path = dirname(dirname(__FILE__)); $inside = dirname($path) . DS; - $Folder = new Folder($path); + $Folder =& new Folder($path); $result = $Folder->pwd(); $this->assertEqual($result, $path); @@ -91,7 +91,7 @@ class FolderTest extends CakeTestCase { */ function testOperations() { $path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'libs' . DS . 'templates' . DS . 'skel'; - $Folder = new Folder($path); + $Folder =& new Folder($path); $result = is_dir($Folder->pwd()); $this->assertTrue($result); @@ -150,7 +150,7 @@ class FolderTest extends CakeTestCase { $result = $Folder->delete(); $this->assertTrue($result); - $Folder = new Folder('non-existent'); + $Folder =& new Folder('non-existent'); $result = $Folder->pwd(); $this->assertNull($result); } @@ -164,7 +164,7 @@ class FolderTest extends CakeTestCase { $this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s Folder permissions tests not supported on Windows'); $path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'libs' . DS . 'templates' . DS . 'skel'; - $Folder = new Folder($path); + $Folder =& new Folder($path); $subdir = 'test_folder_new'; $new = TMP . $subdir; @@ -174,7 +174,7 @@ class FolderTest extends CakeTestCase { $this->assertTrue($Folder->create($new . DS . 'test2')); $filePath = $new . DS . 'test1.php'; - $File = new File($filePath); + $File =& new File($filePath); $this->assertTrue($File->create()); $copy = TMP . 'test_folder_copy'; @@ -200,7 +200,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testZeroAsDirectory() { - $Folder = new Folder(TMP); + $Folder =& new Folder(TMP); $new = TMP . '0'; $this->assertTrue($Folder->create($new)); @@ -222,7 +222,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFolderRead() { - $Folder = new Folder(TMP); + $Folder =& new Folder(TMP); $expected = array('cache', 'logs', 'sessions', 'tests'); $result = $Folder->read(true, true); @@ -240,7 +240,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFolderTree() { - $Folder = new Folder(); + $Folder =& new Folder(); $expected = array( array( TEST_CAKE_CORE_INCLUDE_PATH . 'config', @@ -380,7 +380,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testInCakePath() { - $Folder = new Folder(); + $Folder =& new Folder(); $Folder->cd(ROOT); $path = 'C:\\path\\to\\file'; $result = $Folder->inCakePath($path); @@ -404,7 +404,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFind() { - $Folder = new Folder(); + $Folder =& new Folder(); $Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH . 'config'); $result = $Folder->find(); $expected = array('config.php', 'paths.php'); @@ -456,7 +456,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testFindRecursive() { - $Folder = new Folder(); + $Folder =& new Folder(); $Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH); $result = $Folder->findRecursive('(config|paths)\.php'); $expected = array( @@ -476,7 +476,7 @@ class FolderTest extends CakeTestCase { $Folder->cd(TMP); $Folder->mkdir($Folder->pwd() . DS . 'testme'); $Folder->cd('testme'); - $File = new File($Folder->pwd() . DS . 'paths.php'); + $File =& new File($Folder->pwd() . DS . 'paths.php'); $File->create(); $Folder->cd(TMP . 'sessions'); $result = $Folder->findRecursive('paths\.php'); @@ -484,7 +484,7 @@ class FolderTest extends CakeTestCase { $this->assertIdentical($result, $expected); $Folder->cd(TMP . 'testme'); - $File = new File($Folder->pwd() . DS . 'my.php'); + $File =& new File($Folder->pwd() . DS . 'my.php'); $File->create(); $Folder->cd($Folder->pwd() . '/../..'); @@ -515,7 +515,7 @@ class FolderTest extends CakeTestCase { * @return void */ function testConstructWithNonExistantPath() { - $Folder = new Folder(TMP . 'config_non_existant', true); + $Folder =& new Folder(TMP . 'config_non_existant', true); $this->assertTrue(is_dir(TMP . 'config_non_existant')); $Folder->cd(TMP); $Folder->delete($Folder->pwd() . 'config_non_existant'); @@ -527,10 +527,10 @@ class FolderTest extends CakeTestCase { * @return void */ function testDirSize() { - $Folder = new Folder(TMP . 'config_non_existant', true); + $Folder =& new Folder(TMP . 'config_non_existant', true); $this->assertEqual($Folder->dirSize(), 0); - $File = new File($Folder->pwd() . DS . 'my.php', true, 0777); + $File =& new File($Folder->pwd() . DS . 'my.php', true, 0777); $File->create(); $File->write('something here'); $File->close(); @@ -547,7 +547,7 @@ class FolderTest extends CakeTestCase { */ function testDelete() { $path = TMP . 'folder_delete_test'; - $Folder = new Folder($path, true); + $Folder =& new Folder($path, true); touch(TMP . 'folder_delete_test' . DS . 'file1'); touch(TMP . 'folder_delete_test' . DS . 'file2'); @@ -593,35 +593,35 @@ class FolderTest extends CakeTestCase { touch($file1); touch($file2); - $Folder = new Folder($folder1); + $Folder =& new Folder($folder1); $result = $Folder->copy($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); $this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php')); - $Folder = new Folder($folder3); + $Folder =& new Folder($folder3); $Folder->delete(); - $Folder = new Folder($folder1); + $Folder =& new Folder($folder1); $result = $Folder->copy($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); $this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php')); - $Folder = new Folder($folder3); + $Folder =& new Folder($folder3); $Folder->delete(); new Folder($folder3, true); new Folder($folder3 . DS . 'folder2', true); file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched'); - $Folder = new Folder($folder1); + $Folder =& new Folder($folder1); $result = $Folder->copy($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); $this->assertEqual(file_get_contents($folder3 . DS . 'folder2' . DS . 'file2.php'), 'untouched'); - $Folder = new Folder($path); + $Folder =& new Folder($path); $Folder->delete(); } /** @@ -651,7 +651,7 @@ class FolderTest extends CakeTestCase { touch($file1); touch($file2); - $Folder = new Folder($folder1); + $Folder =& new Folder($folder1); $result = $Folder->move($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); @@ -661,7 +661,7 @@ class FolderTest extends CakeTestCase { $this->assertFalse(file_exists($folder2)); $this->assertFalse(file_exists($file2)); - $Folder = new Folder($folder3); + $Folder =& new Folder($folder3); $Folder->delete(); new Folder($folder1, true); @@ -669,7 +669,7 @@ class FolderTest extends CakeTestCase { touch($file1); touch($file2); - $Folder = new Folder($folder1); + $Folder =& new Folder($folder1); $result = $Folder->move($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); @@ -679,7 +679,7 @@ class FolderTest extends CakeTestCase { $this->assertFalse(file_exists($folder2)); $this->assertFalse(file_exists($file2)); - $Folder = new Folder($folder3); + $Folder =& new Folder($folder3); $Folder->delete(); new Folder($folder1, true); @@ -690,7 +690,7 @@ class FolderTest extends CakeTestCase { touch($file2); file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched'); - $Folder = new Folder($folder1); + $Folder =& new Folder($folder1); $result = $Folder->move($folder3); $this->assertTrue($result); $this->assertTrue(file_exists($folder3 . DS . 'file1.php')); @@ -699,7 +699,7 @@ class FolderTest extends CakeTestCase { $this->assertFalse(file_exists($folder2)); $this->assertFalse(file_exists($file2)); - $Folder = new Folder($path); + $Folder =& new Folder($path); $Folder->delete(); } } diff --git a/cake/tests/cases/libs/http_socket.test.php b/cake/tests/cases/libs/http_socket.test.php index c169ce27..b3fa948b 100755 --- a/cake/tests/cases/libs/http_socket.test.php +++ b/cake/tests/cases/libs/http_socket.test.php @@ -58,8 +58,8 @@ class HttpSocketTest extends CakeTestCase { Mock::generatePartial('HttpSocket', 'TestHttpSocketRequests', array('read', 'write', 'connect', 'request')); } - $this->Socket = new TestHttpSocket(); - $this->RequestSocket = new TestHttpSocketRequests(); + $this->Socket =& new TestHttpSocket(); + $this->RequestSocket =& new TestHttpSocketRequests(); } /** * We use this function to clean up after the test case was executed diff --git a/cake/tests/cases/libs/l10n.test.php b/cake/tests/cases/libs/l10n.test.php index 8a3a32bb..48df8fa3 100755 --- a/cake/tests/cases/libs/l10n.test.php +++ b/cake/tests/cases/libs/l10n.test.php @@ -39,7 +39,7 @@ class L10nTest extends CakeTestCase { * @return void */ function testGet() { - $l10n = new L10n(); + $l10n =& new L10n(); // Catalog Entry $l10n->get('en'); @@ -124,7 +124,7 @@ class L10nTest extends CakeTestCase { $__SERVER = $_SERVER; $_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'inexistent,en-ca'; - $l10n = new L10n(); + $l10n =& new L10n(); $l10n->get(); $result = $l10n->language; $expected = 'English (Canadian)'; @@ -175,7 +175,7 @@ class L10nTest extends CakeTestCase { * @return void */ function testMap() { - $l10n = new L10n(); + $l10n =& new L10n(); $result = $l10n->map(array('afr', 'af')); $expected = array('afr' => 'af', 'af' => 'afr'); @@ -496,7 +496,7 @@ class L10nTest extends CakeTestCase { * @return void */ function testCatalog() { - $l10n = new L10n(); + $l10n =& new L10n(); $result = $l10n->catalog(array('af')); $expected = array( diff --git a/cake/tests/cases/libs/magic_db.test.php b/cake/tests/cases/libs/magic_db.test.php index e383faf1..3eba7eb4 100755 --- a/cake/tests/cases/libs/magic_db.test.php +++ b/cake/tests/cases/libs/magic_db.test.php @@ -43,7 +43,7 @@ class MagicDbTest extends UnitTestCase { * @access public */ function setUp() { - $this->Db = new MagicDb(); + $this->Db =& new MagicDb(); } /** * MagicDb::analyze should properly detect the file type and output additional info as requested. @@ -158,7 +158,7 @@ class MagicDbTest extends UnitTestCase { * @package cake * @subpackage cake.tests.cases.libs */ -class MagicDbTestData extends CakeObject { +class MagicDbTestData extends Object { /** * Base64 encoded data * diff --git a/cake/tests/cases/libs/model/behavior.test.php b/cake/tests/cases/libs/model/behavior.test.php index 374741a9..727316a2 100755 --- a/cake/tests/cases/libs/model/behavior.test.php +++ b/cake/tests/cases/libs/model/behavior.test.php @@ -983,7 +983,7 @@ class BehaviorTest extends CakeTestCase { * @return void */ function testBehaviorTrigger() { - $Apple = new Apple(); + $Apple =& new Apple(); $Apple->Behaviors->attach('Test'); $Apple->Behaviors->attach('Test2'); $Apple->Behaviors->attach('Test3'); @@ -1057,7 +1057,7 @@ class BehaviorTest extends CakeTestCase { * @return void **/ function testBehaviorAttachAndDetach() { - $Sample = new Sample(); + $Sample =& new Sample(); $Sample->actsAs = array('Test3' => array('bar'), 'Test2' => array('foo', 'bar')); $Sample->Behaviors->init($Sample->alias, $Sample->actsAs); $Sample->Behaviors->attach('Test2'); diff --git a/cake/tests/cases/libs/model/behaviors/acl.test.php b/cake/tests/cases/libs/model/behaviors/acl.test.php index f58a6730..3ca1974e 100755 --- a/cake/tests/cases/libs/model/behaviors/acl.test.php +++ b/cake/tests/cases/libs/model/behaviors/acl.test.php @@ -210,8 +210,8 @@ class AclBehaviorTestCase extends CakeTestCase { function startTest() { Configure::write('Acl.database', 'test_suite'); - $this->Aco = new Aco(); - $this->Aro = new Aro(); + $this->Aco =& new Aco(); + $this->Aro =& new Aro(); } /** * tearDown method @@ -230,12 +230,12 @@ class AclBehaviorTestCase extends CakeTestCase { * @access public */ function testSetup() { - $User = new AclUser(); + $User =& new AclUser(); $this->assertTrue(isset($User->Behaviors->Acl->settings['User'])); $this->assertEqual($User->Behaviors->Acl->settings['User']['type'], 'requester'); $this->assertTrue(is_object($User->Aro)); - $Post = new AclPost(); + $Post =& new AclPost(); $this->assertTrue(isset($Post->Behaviors->Acl->settings['Post'])); $this->assertEqual($Post->Behaviors->Acl->settings['Post']['type'], 'controlled'); $this->assertTrue(is_object($Post->Aco)); @@ -247,7 +247,7 @@ class AclBehaviorTestCase extends CakeTestCase { * @access public */ function testAfterSave() { - $Post = new AclPost(); + $Post =& new AclPost(); $data = array( 'Post' => array( 'author_id' => 1, @@ -271,7 +271,7 @@ class AclBehaviorTestCase extends CakeTestCase { ); $this->Aro->save($aroData); - $Person = new AclPerson(); + $Person =& new AclPerson(); $data = array( 'AclPerson' => array( 'name' => 'Trent', @@ -304,7 +304,7 @@ class AclBehaviorTestCase extends CakeTestCase { ) ); $this->Aro->save($aroData); - $Person = new AclPerson(); + $Person =& new AclPerson(); $data = array( 'AclPerson' => array( 'name' => 'Trent', @@ -349,7 +349,7 @@ class AclBehaviorTestCase extends CakeTestCase { * @access public */ function testNode() { - $Person = new AclPerson(); + $Person =& new AclPerson(); $aroData = array( 'Aro' => array( 'model' => 'AclPerson', diff --git a/cake/tests/cases/libs/model/behaviors/containable.test.php b/cake/tests/cases/libs/model/behaviors/containable.test.php index 58f0276b..ca16f318 100755 --- a/cake/tests/cases/libs/model/behaviors/containable.test.php +++ b/cake/tests/cases/libs/model/behaviors/containable.test.php @@ -3123,7 +3123,7 @@ class ContainableBehaviorTest extends CakeTestCase { * @return void */ function testPaginate() { - $Controller = new Controller(); + $Controller =& new Controller(); $Controller->uses = array('Article'); $Controller->passedArgs[] = '1'; $Controller->params['url'] = array(); diff --git a/cake/tests/cases/libs/model/behaviors/translate.test.php b/cake/tests/cases/libs/model/behaviors/translate.test.php index 36b60180..3ec69f02 100755 --- a/cake/tests/cases/libs/model/behaviors/translate.test.php +++ b/cake/tests/cases/libs/model/behaviors/translate.test.php @@ -70,22 +70,22 @@ class TranslateBehaviorTest extends CakeTestCase { * @return void */ function testTranslateModel() { - $TestModel = new Tag(); + $TestModel =& new Tag(); $TestModel->translateTable = 'another_i18n'; $TestModel->Behaviors->attach('Translate', array('title')); $this->assertEqual($TestModel->translateModel()->name, 'I18nModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'another_i18n'); - $TestModel = new User(); + $TestModel =& new User(); $TestModel->Behaviors->attach('Translate', array('title')); $this->assertEqual($TestModel->translateModel()->name, 'I18nModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'i18n'); - $TestModel = new TranslatedArticle(); + $TestModel =& new TranslatedArticle(); $this->assertEqual($TestModel->translateModel()->name, 'TranslateArticleModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'article_i18n'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $this->assertEqual($TestModel->translateModel()->name, 'TranslateTestModel'); $this->assertEqual($TestModel->translateModel()->useTable, 'i18n'); } @@ -98,7 +98,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleFalsePlain() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = false; $result = $TestModel->read(null, 1); @@ -122,7 +122,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleFalseAssociations() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = false; $TestModel->unbindTranslation(); $translations = array('title' => 'Title', 'content' => 'Content'); @@ -176,7 +176,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleSingle() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'eng'; $result = $TestModel->read(null, 1); $expected = array( @@ -231,7 +231,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleSingleWithConditions() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'eng'; $result = $TestModel->find('all', array('conditions' => array('slug' => 'first_translated'))); $expected = array( @@ -270,7 +270,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleSingleAssociations() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'eng'; $TestModel->unbindTranslation(); $translations = array('title' => 'Title', 'content' => 'Content'); @@ -330,7 +330,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testLocaleMultiple() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = array('deu', 'eng', 'cze'); $delete = array( array('locale' => 'deu'), @@ -393,7 +393,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMissingTranslation() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'rus'; $result = $TestModel->read(null, 1); $this->assertFalse($result); @@ -420,7 +420,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testTranslatedFindList() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'deu'; $TestModel->displayField = 'title'; $result = $TestModel->find('list', array('recursive' => 1)); @@ -453,7 +453,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testReadSelectedFields() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'eng'; $result = $TestModel->find('all', array('fields' => array('slug', 'TranslatedItem.content'))); $expected = array( @@ -488,7 +488,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testSaveCreate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'spa'; $data = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4', 'content' => 'Contenido #4'); $TestModel->create($data); @@ -506,7 +506,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testSaveUpdate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'spa'; $oldData = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4'); $TestModel->create($oldData); @@ -528,7 +528,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMultipleCreate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'deu'; $data = array( 'slug' => 'new_translated', @@ -566,7 +566,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMultipleUpdate() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'eng'; $TestModel->validate['title'] = 'notEmpty'; $data = array('TranslatedItem' => array( @@ -608,7 +608,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testMixedCreateUpdateWithArrayLocale() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = array('cze', 'deu'); $data = array('TranslatedItem' => array( 'id' => 1, @@ -647,7 +647,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testValidation() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $TestModel->locale = 'eng'; $TestModel->validate['title'] = '/Only this title/'; $data = array('TranslatedItem' => array( @@ -678,7 +678,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testAttachDetach() { $this->loadFixtures('Translate', 'TranslatedItem'); - $TestModel = new TranslatedItem(); + $TestModel =& new TranslatedItem(); $Behavior =& $this->Model->Behaviors->Translate; $TestModel->unbindTranslation(); @@ -728,7 +728,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testAnotherTranslateTable() { $this->loadFixtures('Translate', 'TranslatedItem', 'TranslateTable'); - $TestModel = new TranslatedItemWithTable(); + $TestModel =& new TranslatedItemWithTable(); $TestModel->locale = 'eng'; $result = $TestModel->read(null, 1); $expected = array( @@ -751,7 +751,7 @@ class TranslateBehaviorTest extends CakeTestCase { function testTranslateWithAssociations() { $this->loadFixtures('TranslateArticle', 'TranslatedArticle', 'User', 'Comment', 'ArticlesTag', 'Tag'); - $TestModel = new TranslatedArticle(); + $TestModel =& new TranslatedArticle(); $TestModel->locale = 'eng'; $recursive = $TestModel->recursive; diff --git a/cake/tests/cases/libs/model/behaviors/tree.test.php b/cake/tests/cases/libs/model/behaviors/tree.test.php index 592d6de5..2d030cb4 100755 --- a/cake/tests/cases/libs/model/behaviors/tree.test.php +++ b/cake/tests/cases/libs/model/behaviors/tree.test.php @@ -60,7 +60,7 @@ class NumberTreeTest extends CakeTestCase { */ function testInitialize() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->find('count'); @@ -77,7 +77,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidLeft() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -103,7 +103,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidRight() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -129,7 +129,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidParent() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -154,7 +154,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectNoneExistantParent() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -177,7 +177,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRecoverFromMissingParent() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $result = $this->Tree->findByName('1.1'); @@ -200,7 +200,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidParents() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->updateAll(array($parentField => null)); @@ -222,7 +222,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectInvalidLftsRghts() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->updateAll(array($leftField => 0, $rightField => 0)); @@ -243,7 +243,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDetectEqualLftsRghts() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(1, 3); $result = $this->Tree->findByName('1.1'); @@ -270,7 +270,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddOrphan() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null))); @@ -289,7 +289,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddMiddle() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data= $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id')); @@ -322,7 +322,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddInvalid() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -346,7 +346,7 @@ class NumberTreeTest extends CakeTestCase { */ function testAddNotIndexedByModel() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->save(array('name' => 'testAddNotIndexed', $parentField => null)); @@ -365,7 +365,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMovePromote() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -391,7 +391,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveWithWhitelist() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -418,7 +418,7 @@ class NumberTreeTest extends CakeTestCase { */ function testInsertWithWhitelist() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->whitelist = array('name', $parentField); @@ -436,7 +436,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveBefore() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -464,7 +464,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveAfter() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -492,7 +492,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDemoteInvalid() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -525,7 +525,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveInvalid() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -551,7 +551,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveSelfInvalid() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -577,7 +577,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUpSuccess() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2'), array('id')); @@ -598,7 +598,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUpFail() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.1')); @@ -620,7 +620,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUp2() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -650,7 +650,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveUpFirst() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -680,7 +680,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDownSuccess() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id')); @@ -701,7 +701,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDownFail() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2')); @@ -722,7 +722,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDownLast() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -752,7 +752,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveDown2() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -782,7 +782,7 @@ class NumberTreeTest extends CakeTestCase { */ function testSaveNoMove() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(1, 10); $data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id')); @@ -812,7 +812,7 @@ class NumberTreeTest extends CakeTestCase { */ function testMoveToRootAndMoveUp() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(1, 1); $data = $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id')); $this->Tree->id = $data[$modelClass]['id']; @@ -836,7 +836,7 @@ class NumberTreeTest extends CakeTestCase { */ function testDelete() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -871,7 +871,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemove() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); $result = $this->Tree->findByName('1.1'); @@ -903,7 +903,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveLastTopParent() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -936,7 +936,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveNoChildren() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -970,7 +970,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveAndDelete() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1002,7 +1002,7 @@ class NumberTreeTest extends CakeTestCase { */ function testRemoveAndDeleteNoChildren() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1034,7 +1034,7 @@ class NumberTreeTest extends CakeTestCase { */ function testChildren() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1. Root')); @@ -1062,7 +1062,7 @@ class NumberTreeTest extends CakeTestCase { */ function testCountChildren() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1. Root')); @@ -1082,7 +1082,7 @@ class NumberTreeTest extends CakeTestCase { */ function testGetParentNode() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2.2')); @@ -1100,7 +1100,7 @@ class NumberTreeTest extends CakeTestCase { */ function testGetPath() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1.2.2')); @@ -1120,7 +1120,7 @@ class NumberTreeTest extends CakeTestCase { */ function testNoAmbiguousColumn() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); @@ -1152,7 +1152,7 @@ class NumberTreeTest extends CakeTestCase { */ function testReorderTree() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(3, 3); $nodes = $this->Tree->find('list', array('order' => $leftField)); @@ -1180,7 +1180,7 @@ class NumberTreeTest extends CakeTestCase { */ function testGenerateTreeListWithSelfJoin() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); @@ -1197,7 +1197,7 @@ class NumberTreeTest extends CakeTestCase { */ function testArraySyntax() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(3, 3); $this->assertIdentical($this->Tree->childCount(2), $this->Tree->childCount(array('id' => 2))); $this->assertIdentical($this->Tree->getParentNode(2), $this->Tree->getParentNode(array('id' => 2))); @@ -1237,7 +1237,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testStringScope() { - $this->Tree = new FlagTree(); + $this->Tree =& new FlagTree(); $this->Tree->initialize(2, 3); $this->Tree->id = 1; @@ -1273,7 +1273,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testArrayScope() { - $this->Tree = new FlagTree(); + $this->Tree =& new FlagTree(); $this->Tree->initialize(2, 3); $this->Tree->id = 1; @@ -1309,7 +1309,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testMoveUpWithScope() { - $this->Ad = new Ad(); + $this->Ad =& new Ad(); $this->Ad->Behaviors->attach('Tree', array('scope'=>'Campaign')); $this->Ad->moveUp(6); @@ -1325,7 +1325,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testMoveDownWithScope() { - $this->Ad = new Ad(); + $this->Ad =& new Ad(); $this->Ad->Behaviors->attach('Tree', array('scope' => 'Campaign')); $this->Ad->moveDown(6); @@ -1342,7 +1342,7 @@ class ScopedTreeTest extends NumberTreeTest { * @return void */ function testTranslatingTree() { - $this->Tree = new FlagTree(); + $this->Tree =& new FlagTree(); $this->Tree->cacheQueries = false; $this->Tree->translateModel = 'TranslateTreeTestModel'; $this->Tree->Behaviors->attach('Translate', array('name')); @@ -1441,10 +1441,10 @@ class ScopedTreeTest extends NumberTreeTest { */ function testAliasesWithScopeInTwoTreeAssociations() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); - $this->TreeTwo = new NumberTreeTwo(); + $this->TreeTwo =& new NumberTreeTwo(); $record = $this->Tree->find('first'); @@ -1522,7 +1522,7 @@ class AfterTreeTest extends NumberTreeTest { * @return void */ function testAftersaveCallback() { - $this->Tree = new AfterTree(); + $this->Tree =& new AfterTree(); $expected = array('AfterTree' => array('name' => 'Six and One Half Changed in AfterTree::afterSave() but not in database', 'parent_id' => 6, 'lft' => 11, 'rght' => 12)); $result = $this->Tree->save(array('AfterTree' => array('name' => 'Six and One Half', 'parent_id' => 6))); @@ -1594,7 +1594,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testMovePromote() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -1620,7 +1620,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testMoveWithWhitelist() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $this->Tree->id = null; @@ -1647,7 +1647,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testRemoveNoChildren() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1681,7 +1681,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testRemoveAndDeleteNoChildren() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $initialCount = $this->Tree->find('count'); @@ -1713,7 +1713,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testChildren() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->initialize(2, 2); $data = $this->Tree->find(array($modelClass . '.name' => '1. Root')); @@ -1741,7 +1741,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testNoAmbiguousColumn() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); @@ -1773,7 +1773,7 @@ class UuidTreeTest extends NumberTreeTest { */ function testGenerateTreeListWithSelfJoin() { extract($this->settings); - $this->Tree = new $modelClass(); + $this->Tree =& new $modelClass(); $this->Tree->bindModel(array('belongsTo' => array('Dummy' => array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false); $this->Tree->initialize(2, 2); diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php index 447db40d..691a86c1 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_mysql.test.php @@ -371,7 +371,7 @@ class DboMysqlTest extends CakeTestCase { function testIndexOnMySQL4Output() { $name = $this->db->fullTableName('simple'); - $mockDbo = new QueryMockDboMysql($this); + $mockDbo =& new QueryMockDboMysql($this); $columnData = array( array('0' => array( 'Table' => 'with_compound_keys', @@ -512,7 +512,7 @@ class DboMysqlTest extends CakeTestCase { App::import('Core', 'Schema'); $this->db->cacheSources = $this->db->testing = false; - $schema1 = new CakeSchema(array( + $schema1 =& new CakeSchema(array( 'name' => 'AlterTest1', 'connection' => 'test_suite', 'altertest' => array( @@ -523,7 +523,7 @@ class DboMysqlTest extends CakeTestCase { ))); $this->db->query($this->db->createSchema($schema1)); - $schema2 = new CakeSchema(array( + $schema2 =& new CakeSchema(array( 'name' => 'AlterTest2', 'connection' => 'test_suite', 'altertest' => array( @@ -543,7 +543,7 @@ class DboMysqlTest extends CakeTestCase { $this->assertEqual($schema2->tables['altertest']['indexes'], $indexes); // Change three indexes, delete one and add another one - $schema3 = new CakeSchema(array( + $schema3 =& new CakeSchema(array( 'name' => 'AlterTest3', 'connection' => 'test_suite', 'altertest' => array( diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php index fabb5039..6b835890 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_oracle.test.php @@ -103,7 +103,7 @@ class DboOracleTest extends CakeTestCase { */ function testName() { $Db = $this->db; - #$Db = new DboOracle($config = null, $autoConnect = false); + #$Db =& new DboOracle($config = null, $autoConnect = false); $r = $Db->name($Db->name($Db->name('foo.last_update_date'))); $e = 'foo.last_update_date'; diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php index aa2ddcac..aec59ba4 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_postgres.test.php @@ -415,7 +415,7 @@ class DboPostgresTest extends CakeTestCase { ªºnh˚ºO^∏…®[Ó“‚ÅfıÌ≥∫F!Eœ(π∑T6`¬tΩÆ0ì»rTÎ`»Ñ« ]≈åp˝)=¿Ô0∆öVÂmˇˆ„ø~¯ÁÔ∏b*fc»‡Îı„Ú}∆tœs∂Y∫ÜaÆ˙X∏~<ÿ·Ù vé1‹p¿TD∆ÔîÄ“úhˆ*Ú€îe)K –p¨ÚJ3Ÿ∞ã>ÊuNê°“√Ü ‹Ê9iÙ0˙AAEÍ ˙`∂£\'ûce•åƒX›ŸÁ´1SK{qdá"tÏ[wQ#SµBe∞∑µó…ÌV`B"Ñ≥„!è_Óφ-º*ºú¿Ë0ˆeê∂´ë+HFj…‡zvHÓN|ÔL÷ûñ3õÜ$z%sá…pÎóV38âs Çoµ•ß3†<9B·¨û~¢3)ÂxóÿÁCÕòÆ ∫Í=»ÿSπS;∆~±êÆTEp∑óÈ÷ÀuìDHÈ $ÉõæÜjû§"≤ÃONM®RËíRr{õS ∏Ê™op±W;ÂUÔP∫kÔˇflTæ∑óflË” ÆC©Ô[≥◊HÁ˚¨hê"ÆbF?ú%h˙ˇ4xèÕ(ó2ÙáíM])Ñd|=fë-cI0ñL¢kÖêk‰Rƒ«ıÄWñ8mO3∏&√æËX¯Hó—ì]yF2»–˜ádàà‡‹Çο„≥7mªHAS∑¶.;Œx(1}_kd©.fidç48M\'àáªCp^Krí<ɉXÓıïl!Ì$N<ı∞B»G]…∂Ó¯>˛ÔbõÒπÀ•:ôO@È$pÖu‹Ê´-QqV ?V≥JÆÍqÛX8(lπï@zgÖ}Fe<ˇ‡Sñ“ÿ˜ê?6‡L∫Oß~µ–?ËeäÚ®YîÕ =Ü=¢DÁu*GvBk;)L¬N«î:flö∂≠ÇΩq„Ñm하Ë∂‚"û≥§:±≤i^ΩÑ!)Wıyŧôá„RÄ÷Òôc’≠—s™rı‚Pdêãh˘ßHVç5fifiÈF€çÌÛuçÖ/M=gëµ±ÿGû1coÔuñæ‘z®.õ∑7ÉÏÜÆ,°’H†ÍÉÌ∂7e º® íˆ⁄◊øNWK”ÂYµ‚ñé;µ¶gV-fl>µtË¥áßN2 ¯¶BaP-)eW.àôt^∏1›C∑Ö?L„&”5’4jvã–ªZ ÷+4% ´0l…»ú^°´© ûiπ∑é®óܱÒÿ‰ïˆÌ–dˆ◊Æ19rQ=Í|ı•rMæ¬;ò‰Y‰é9.” ‹˝V«ã¯∏,+ë®j*¡·/'; - $model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite')); + $model =& new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite')); $model->save(compact('data')); $result = $model->find('first'); @@ -528,7 +528,7 @@ class DboPostgresTest extends CakeTestCase { * @return void */ function testAlterSchema() { - $Old = new CakeSchema(array( + $Old =& new CakeSchema(array( 'connection' => 'test_suite', 'name' => 'AlterPosts', 'alter_posts' => array( @@ -543,7 +543,7 @@ class DboPostgresTest extends CakeTestCase { )); $this->db->query($this->db->createSchema($Old)); - $New = new CakeSchema(array( + $New =& new CakeSchema(array( 'connection' => 'test_suite', 'name' => 'AlterPosts', 'alter_posts' => array( @@ -575,7 +575,7 @@ class DboPostgresTest extends CakeTestCase { function testAlterIndexes() { $this->db->cacheSources = false; - $schema1 = new CakeSchema(array( + $schema1 =& new CakeSchema(array( 'name' => 'AlterTest1', 'connection' => 'test_suite', 'altertest' => array( @@ -587,7 +587,7 @@ class DboPostgresTest extends CakeTestCase { )); $this->db->query($this->db->createSchema($schema1)); - $schema2 = new CakeSchema(array( + $schema2 =& new CakeSchema(array( 'name' => 'AlterTest2', 'connection' => 'test_suite', 'altertest' => array( @@ -609,7 +609,7 @@ class DboPostgresTest extends CakeTestCase { $this->assertEqual($schema2->tables['altertest']['indexes'], $indexes); // Change three indexes, delete one and add another one - $schema3 = new CakeSchema(array( + $schema3 =& new CakeSchema(array( 'name' => 'AlterTest3', 'connection' => 'test_suite', 'altertest' => array( diff --git a/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php b/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php index 1732ce19..2f1ea4ad 100755 --- a/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo/dbo_sqlite.test.php @@ -210,7 +210,7 @@ class DboSqliteTest extends CakeTestCase { * @return void **/ function testDescribe() { - $Model = new Model(array('name' => 'User', 'ds' => 'test_suite', 'table' => 'users')); + $Model =& new Model(array('name' => 'User', 'ds' => 'test_suite', 'table' => 'users')); $result = $this->db->describe($Model); $expected = array( 'id' => array( @@ -256,7 +256,7 @@ class DboSqliteTest extends CakeTestCase { function testDescribeWithUuidPrimaryKey() { $tableName = 'uuid_tests'; $this->db->query("CREATE TABLE {$tableName} (id VARCHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)"); - $Model = new Model(array('name' => 'UuidTest', 'ds' => 'test_suite', 'table' => 'uuid_tests')); + $Model =& new Model(array('name' => 'UuidTest', 'ds' => 'test_suite', 'table' => 'uuid_tests')); $result = $this->db->describe($Model); $expected = array( 'type' => 'string', diff --git a/cake/tests/cases/libs/model/datasources/dbo_source.test.php b/cake/tests/cases/libs/model/datasources/dbo_source.test.php index 28a9d1d7..4da90c9b 100755 --- a/cake/tests/cases/libs/model/datasources/dbo_source.test.php +++ b/cake/tests/cases/libs/model/datasources/dbo_source.test.php @@ -1209,13 +1209,13 @@ class DboSourceTest extends CakeTestCase { }"); } - $this->testDb = new DboTest($this->__config); + $this->testDb =& new DboTest($this->__config); $this->testDb->cacheSources = false; $this->testDb->startQuote = '`'; $this->testDb->endQuote = '`'; Configure::write('debug', 1); $this->debug = Configure::read('debug'); - $this->Model = new TestModel(); + $this->Model =& new TestModel(); } /** * endTest method @@ -1239,7 +1239,7 @@ class DboSourceTest extends CakeTestCase { $test =& ConnectionManager::create('quoteTest', $config); $test->simulated = array(); - $this->Model = new Article2(array('alias' => 'Article', 'ds' => 'quoteTest')); + $this->Model =& new Article2(array('alias' => 'Article', 'ds' => 'quoteTest')); $this->Model->setDataSource('quoteTest'); $this->assertEqual($this->Model->escapeField(), '`Article`.`id`'); @@ -1277,11 +1277,11 @@ class DboSourceTest extends CakeTestCase { */ function testGenerateAssociationQuerySelfJoin() { $this->startTime = microtime(true); - $this->Model = new Article2(); + $this->Model =& new Article2(); $this->_buildRelatedModels($this->Model); $this->_buildRelatedModels($this->Model->Category2); - $this->Model->Category2->ChildCat = new Category2(); - $this->Model->Category2->ParentCat = new Category2(); + $this->Model->Category2->ChildCat =& new Category2(); + $this->Model->Category2->ParentCat =& new Category2(); $queryData = array(); @@ -1305,7 +1305,7 @@ class DboSourceTest extends CakeTestCase { $query = $this->testDb->generateAssociationQuery($this->Model->Category2, $null, null, null, null, $queryData, false, $null); $this->assertPattern('/^SELECT\s+(.+)FROM(.+)`Category2`\.`group_id`\s+=\s+`Group`\.`id`\)\s+LEFT JOIN(.+)WHERE\s+1 = 1\s*$/', $query); - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1366,10 +1366,10 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateInnerJoinAssociationQuery() { - $this->Model = new TestModel9(); + $this->Model =& new TestModel9(); $test =& ConnectionManager::create('test2', $this->__config); $this->Model->setDataSource('test2'); - $this->Model->TestModel8 = new TestModel8(); + $this->Model->TestModel8 =& new TestModel8(); $this->Model->TestModel8->setDataSource('test2'); $this->testDb->read($this->Model, array('recursive' => 1)); @@ -1389,7 +1389,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding() { - $this->Model = new TestModel8(); + $this->Model =& new TestModel8(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1416,7 +1416,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding() { - $this->Model = new TestModel9(); + $this->Model =& new TestModel9(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1442,7 +1442,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQuerySelfJoinWithConditions() { - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1462,7 +1462,7 @@ class DboSourceTest extends CakeTestCase { $this->assertPattern('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result); $this->assertPattern('/\s+WHERE\s+(?:\()?`TestModel4Parent`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result); - $this->Featured2 = new Featured2(); + $this->Featured2 =& new Featured2(); $this->Featured2->schema(); $this->Featured2->bindModel(array( @@ -1503,7 +1503,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasOne() { - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1535,7 +1535,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasOneWithConditions() { - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1564,7 +1564,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryBelongsTo() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1595,7 +1595,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryBelongsToWithConditions() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1626,7 +1626,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasMany() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1655,7 +1655,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithLimit() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1694,7 +1694,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithConditions() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1722,7 +1722,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithOffsetAndLimit() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1759,7 +1759,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithPageAndLimit() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1795,7 +1795,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasManyWithFields() { - $this->Model = new TestModel5(); + $this->Model =& new TestModel5(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1920,7 +1920,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToMany() { - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1950,7 +1950,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToManyWithConditions() { - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -1978,7 +1978,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit() { - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -2014,7 +2014,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit() { - $this->Model = new TestModel4(); + $this->Model =& new TestModel4(); $this->Model->schema(); $this->_buildRelatedModels($this->Model); @@ -2058,7 +2058,7 @@ class DboSourceTest extends CakeTestCase { } elseif (isset($assocData['className'])) { $className = $assocData['className']; } - $model->$className = new $className(); + $model->$className =& new $className(); $model->$className->schema(); } } @@ -2631,7 +2631,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testConditionsWithModel() { - $this->Model = new Article2(); + $this->Model =& new Article2(); $result = $this->testDb->conditions(array('Article2.viewed >=' => 0), true, true, $this->Model); $expected = " WHERE `Article2`.`viewed` >= 0"; @@ -3128,7 +3128,7 @@ class DboSourceTest extends CakeTestCase { * @return void */ function testSchema() { - $Schema = new CakeSchema(); + $Schema =& new CakeSchema(); $Schema->tables = array('table' => array(), 'anotherTable' => array()); $this->expectError(); diff --git a/cake/tests/cases/libs/model/db_acl.test.php b/cake/tests/cases/libs/model/db_acl.test.php index 57ba2b00..82d4d15a 100755 --- a/cake/tests/cases/libs/model/db_acl.test.php +++ b/cake/tests/cases/libs/model/db_acl.test.php @@ -224,10 +224,10 @@ class DbAclTest extends DbAcl { * @return void */ function __construct() { - $this->Aro = new DbAroTest(); - $this->Aro->Permission = new DbPermissionTest(); - $this->Aco = new DbAcoTest(); - $this->Aro->Permission = new DbPermissionTest(); + $this->Aro =& new DbAroTest(); + $this->Aro->Permission =& new DbPermissionTest(); + $this->Aco =& new DbAcoTest(); + $this->Aro->Permission =& new DbPermissionTest(); } } /** diff --git a/cake/tests/cases/libs/model/model_delete.test.php b/cake/tests/cases/libs/model/model_delete.test.php index cdaa97b4..6d30d2bd 100755 --- a/cake/tests/cases/libs/model/model_delete.test.php +++ b/cake/tests/cases/libs/model/model_delete.test.php @@ -42,7 +42,7 @@ class ModelDeleteTest extends BaseModelTest { function testDeleteHabtmReferenceWithConditions() { $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio'); - $Portfolio = new Portfolio(); + $Portfolio =& new Portfolio(); $Portfolio->hasAndBelongsToMany['Item']['conditions'] = array('ItemsPortfolio.item_id >' => 1); $result = $Portfolio->find('first', array( @@ -131,7 +131,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDeleteArticleBLinks() { $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); - $TestModel = new ArticleB(); + $TestModel =& new ArticleB(); $result = $TestModel->ArticlesTag->find('all'); $expected = array( @@ -160,8 +160,8 @@ class ModelDeleteTest extends BaseModelTest { function testDeleteDependentWithConditions() { $this->loadFixtures('Cd','Book','OverallFavorite'); - $Cd = new Cd(); - $OverallFavorite = new OverallFavorite(); + $Cd =& new Cd(); + $OverallFavorite =& new OverallFavorite(); $Cd->del(1); @@ -187,7 +187,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDel() { $this->loadFixtures('Article'); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->del(2); $this->assertTrue($result); @@ -232,7 +232,7 @@ class ModelDeleteTest extends BaseModelTest { // make sure deleting a non-existent record doesn't break save() // ticket #6293 $this->loadFixtures('Uuid'); - $Uuid = new Uuid(); + $Uuid =& new Uuid(); $data = array( 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3', '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8', @@ -266,7 +266,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDeleteAll() { $this->loadFixtures('Article'); - $TestModel = new Article(); + $TestModel =& new Article(); $data = array('Article' => array( 'user_id' => 2, @@ -407,7 +407,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testRecursiveDel() { $this->loadFixtures('Article', 'Comment', 'Attachment'); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->del(2); $this->assertTrue($result); @@ -442,7 +442,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDependentExclusiveDelete() { $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article10(); + $TestModel =& new Article10(); $result = $TestModel->find('all'); $this->assertEqual(count($result[0]['Comment']), 4); @@ -460,7 +460,7 @@ class ModelDeleteTest extends BaseModelTest { */ function testDeleteLinks() { $this->loadFixtures('Article', 'ArticlesTag', 'Tag'); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->ArticlesTag->find('all'); $expected = array( @@ -508,7 +508,7 @@ class ModelDeleteTest extends BaseModelTest { function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() { $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); - $ThePaper = new ThePaper(); + $ThePaper =& new ThePaper(); $ThePaper->id = 1; $ThePaper->save(array('Monkey' => array(2, 3))); @@ -528,7 +528,7 @@ class ModelDeleteTest extends BaseModelTest { )); $this->assertEqual($result['Monkey'], $expected); - $ThePaper = new ThePaper(); + $ThePaper =& new ThePaper(); $ThePaper->id = 2; $ThePaper->save(array('Monkey' => array(2, 3))); diff --git a/cake/tests/cases/libs/model/model_integration.test.php b/cake/tests/cases/libs/model/model_integration.test.php index 475101f5..e213187b 100755 --- a/cake/tests/cases/libs/model/model_integration.test.php +++ b/cake/tests/cases/libs/model/model_integration.test.php @@ -42,7 +42,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testPkInHabtmLinkModelArticleB() { $this->loadFixtures('Article', 'Tag'); - $TestModel2 = new ArticleB(); + $TestModel2 =& new ArticleB(); $this->assertEqual($TestModel2->ArticlesTag->primaryKey, 'article_id'); } /** @@ -73,22 +73,22 @@ class ModelIntegrationTest extends BaseModelTest { function testPkInHabtmLinkModel() { //Test Nonconformant Models $this->loadFixtures('Content', 'ContentAccount', 'Account'); - $TestModel = new Content(); + $TestModel =& new Content(); $this->assertEqual($TestModel->ContentAccount->primaryKey, 'iContentAccountsId'); //test conformant models with no PK in the join table $this->loadFixtures('Article', 'Tag'); - $TestModel2 = new Article(); + $TestModel2 =& new Article(); $this->assertEqual($TestModel2->ArticlesTag->primaryKey, 'article_id'); //test conformant models with PK in join table $this->loadFixtures('Item', 'Portfolio', 'ItemsPortfolio'); - $TestModel3 = new Portfolio(); + $TestModel3 =& new Portfolio(); $this->assertEqual($TestModel3->ItemsPortfolio->primaryKey, 'id'); //test conformant models with PK in join table - join table contains extra field $this->loadFixtures('JoinA', 'JoinB', 'JoinAB'); - $TestModel4 = new JoinA(); + $TestModel4 =& new JoinA(); $this->assertEqual($TestModel4->JoinAsJoinB->primaryKey, 'id'); } @@ -100,7 +100,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testDynamicBehaviorAttachment() { $this->loadFixtures('Apple'); - $TestModel = new Apple(); + $TestModel =& new Apple(); $this->assertEqual($TestModel->Behaviors->attached(), array()); $TestModel->Behaviors->attach('Tree', array('left' => 'left_field', 'right' => 'right_field')); @@ -148,7 +148,7 @@ class ModelIntegrationTest extends BaseModelTest { } $this->loadFixtures('Article', 'Tag', 'ArticlesTag', 'User', 'Comment'); - $TestModel = new Article(); + $TestModel =& new Article(); $expected = array( array( @@ -535,7 +535,7 @@ class ModelIntegrationTest extends BaseModelTest { **/ function testDeconstructFieldsTime() { $this->loadFixtures('Apple'); - $TestModel = new Apple(); + $TestModel =& new Apple(); $data = array(); $data['Apple']['mytime']['hour'] = ''; @@ -621,7 +621,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testDeconstructFieldsDateTime() { $this->loadFixtures('Apple'); - $TestModel = new Apple(); + $TestModel =& new Apple(); //test null/empty values first $data['Apple']['created']['year'] = ''; @@ -849,7 +849,7 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testInvalidAssociation() { - $TestModel = new ValidationTest1(); + $TestModel =& new ValidationTest1(); $this->assertNull($TestModel->getAssociated('Foo')); } /** @@ -875,7 +875,7 @@ class ModelIntegrationTest extends BaseModelTest { **/ function testResetOfExistsOnCreate() { $this->loadFixtures('Article'); - $Article = new Article(); + $Article =& new Article(); $Article->id = 1; $Article->saveField('title', 'Reset me'); $Article->delete(); @@ -897,7 +897,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testPluginAssociations() { $this->loadFixtures('TestPluginArticle', 'User', 'TestPluginComment'); - $TestModel = new TestPluginArticle(); + $TestModel =& new TestPluginArticle(); $result = $TestModel->find('all'); $expected = array( @@ -1063,7 +1063,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testAutoConstructAssociations() { $this->loadFixtures('User', 'ArticleFeatured'); - $TestModel = new AssociationTest1(); + $TestModel =& new AssociationTest1(); $result = $TestModel->hasAndBelongsToMany; $expected = array('AssociationTest2' => array( @@ -1079,8 +1079,8 @@ class ModelIntegrationTest extends BaseModelTest { $this->assertEqual($result, $expected); // Tests related to ticket https://trac.cakephp.org/ticket/5594 - $TestModel = new ArticleFeatured(); - $TestFakeModel = new ArticleFeatured(array('table' => false)); + $TestModel =& new ArticleFeatured(); + $TestFakeModel =& new ArticleFeatured(array('table' => false)); $expected = array( 'User' => array( @@ -1195,7 +1195,7 @@ class ModelIntegrationTest extends BaseModelTest { $this->assertEqual('test_suite', $TestModel->useDbConfig); //deprecated but test it anyway - $NewVoid = new TheVoid(null, false, 'other'); + $NewVoid =& new TheVoid(null, false, 'other'); $this->assertEqual('other', $NewVoid->useDbConfig); } /** @@ -1205,13 +1205,13 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testColumnTypeFetching() { - $model = new Test(); + $model =& new Test(); $this->assertEqual($model->getColumnType('id'), 'integer'); $this->assertEqual($model->getColumnType('notes'), 'text'); $this->assertEqual($model->getColumnType('updated'), 'datetime'); $this->assertEqual($model->getColumnType('unknown'), null); - $model = new Article(); + $model =& new Article(); $this->assertEqual($model->getColumnType('User.created'), 'datetime'); $this->assertEqual($model->getColumnType('Tag.id'), 'integer'); $this->assertEqual($model->getColumnType('Article.id'), 'integer'); @@ -1223,7 +1223,7 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testHabtmUniqueKey() { - $model = new Item(); + $model =& new Item(); $this->assertFalse($model->hasAndBelongsToMany['Portfolio']['unique']); } /** @@ -1233,17 +1233,17 @@ class ModelIntegrationTest extends BaseModelTest { * @return void */ function testIdentity() { - $TestModel = new Test(); + $TestModel =& new Test(); $result = $TestModel->alias; $expected = 'Test'; $this->assertEqual($result, $expected); - $TestModel = new TestAlias(); + $TestModel =& new TestAlias(); $result = $TestModel->alias; $expected = 'TestAlias'; $this->assertEqual($result, $expected); - $TestModel = new Test(array('alias' => 'AnotherTest')); + $TestModel =& new Test(array('alias' => 'AnotherTest')); $result = $TestModel->alias; $expected = 'AnotherTest'; $this->assertEqual($result, $expected); @@ -1256,7 +1256,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testWithAssociation() { $this->loadFixtures('Something', 'SomethingElse', 'JoinThing'); - $TestModel = new Something(); + $TestModel =& new Something(); $result = $TestModel->SomethingElse->find('all'); $expected = array( @@ -1508,7 +1508,7 @@ class ModelIntegrationTest extends BaseModelTest { function testFindSelfAssociations() { $this->loadFixtures('Person'); - $TestModel = new Person(); + $TestModel =& new Person(); $TestModel->recursive = 2; $result = $TestModel->read(null, 1); $expected = array( @@ -1616,7 +1616,7 @@ class ModelIntegrationTest extends BaseModelTest { */ function testDynamicAssociations() { $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = $TestModel->hasOne = array(); $TestModel->hasMany['Comment'] = array_merge($TestModel->hasMany['Comment'], array( @@ -1723,11 +1723,11 @@ class ModelIntegrationTest extends BaseModelTest { */ function testCreation() { $this->loadFixtures('Article'); - $TestModel = new Test(); + $TestModel =& new Test(); $result = $TestModel->create(); $expected = array('Test' => array('notes' => 'write some notes here')); $this->assertEqual($result, $expected); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->schema(); if (isset($this->db->columns['primary_key']['length'])) { @@ -1777,12 +1777,12 @@ class ModelIntegrationTest extends BaseModelTest { $this->assertEqual($result, $expected); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->create(); $expected = array('Article' => array('published' => 'N')); $this->assertEqual($result, $expected); - $FeaturedModel = new Featured(); + $FeaturedModel =& new Featured(); $data = array( 'article_featured_id' => 1, 'category_id' => 1, diff --git a/cake/tests/cases/libs/model/model_read.test.php b/cake/tests/cases/libs/model/model_read.test.php index ae163386..a2fd76f8 100755 --- a/cake/tests/cases/libs/model/model_read.test.php +++ b/cake/tests/cases/libs/model/model_read.test.php @@ -89,8 +89,8 @@ class ModelReadTest extends BaseModelTest { } $this->loadFixtures('Project', 'Product', 'Thread', 'Message', 'Bid'); - $Thread = new Thread(); - $Product = new Product(); + $Thread =& new Thread(); + $Product =& new Product(); $result = $Thread->find('all', array( 'group' => 'Thread.project_id', @@ -245,7 +245,7 @@ class ModelReadTest extends BaseModelTest { */ function testOldQuery() { $this->loadFixtures('Article'); - $Article = new Article(); + $Article =& new Article(); $query = 'SELECT title FROM '; $query .= $this->db->fullTableName('articles'); @@ -280,7 +280,7 @@ class ModelReadTest extends BaseModelTest { */ function testPreparedQuery() { $this->loadFixtures('Article'); - $Article = new Article(); + $Article =& new Article(); $this->db->_queryCache = array(); $finalQuery = 'SELECT title, published FROM '; @@ -361,7 +361,7 @@ class ModelReadTest extends BaseModelTest { */ function testParameterMismatch() { $this->loadFixtures('Article'); - $Article = new Article(); + $Article =& new Article(); $query = 'SELECT * FROM ' . $this->db->fullTableName('articles'); $query .= ' WHERE ' . $this->db->fullTableName('articles'); @@ -389,7 +389,7 @@ class ModelReadTest extends BaseModelTest { } $this->loadFixtures('Article'); - $Article = new Article(); + $Article =& new Article(); $query = 'SELECT * FROM ? WHERE ? = ? AND ? = ?'; $param = array( @@ -411,7 +411,7 @@ class ModelReadTest extends BaseModelTest { */ function testRecursiveUnbind() { $this->loadFixtures('Apple', 'Sample'); - $TestModel = new Apple(); + $TestModel =& new Apple(); $TestModel->recursive = 2; $result = $TestModel->find('all'); @@ -3032,7 +3032,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllThreaded() { $this->loadFixtures('Category'); - $TestModel = new Category(); + $TestModel =& new Category(); $result = $TestModel->find('threaded'); $expected = array( @@ -3508,7 +3508,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindNeighbors() { $this->loadFixtures('User', 'Article'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->id = 1; $result = $TestModel->find('neighbors', array('fields' => array('id'))); @@ -3664,7 +3664,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindNeighboursLegacy() { $this->loadFixtures('User', 'Article'); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->findNeighbours(null, 'Article.id', '2'); $expected = array( @@ -3714,7 +3714,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindCombinedRelations() { $this->loadFixtures('Apple', 'Sample'); - $TestModel = new Apple(); + $TestModel =& new Apple(); $result = $TestModel->find('all'); @@ -3990,13 +3990,13 @@ class ModelReadTest extends BaseModelTest { */ function testSaveEmpty() { $this->loadFixtures('Thread'); - $TestModel = new Thread(); + $TestModel =& new Thread(); $data = array(); $expected = $TestModel->save($data); $this->assertFalse($expected); } // function testBasicValidation() { - // $TestModel = new ValidationTest1(); + // $TestModel =& new ValidationTest1(); // $TestModel->testing = true; // $TestModel->set(array('title' => '', 'published' => 1)); // $this->assertEqual($TestModel->invalidFields(), array('title' => 'This field cannot be left blank')); @@ -4020,7 +4020,7 @@ class ModelReadTest extends BaseModelTest { function testFindAllWithConditionInChildQuery() { $this->loadFixtures('Basket', 'FilmFile'); - $TestModel = new Basket(); + $TestModel =& new Basket(); $recursive = 3; $result = $TestModel->find('all', compact('conditions', 'recursive')); @@ -4063,7 +4063,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllWithConditionsHavingMixedDataTypes() { $this->loadFixtures('Article'); - $TestModel = new Article(); + $TestModel =& new Article(); $expected = array( array( 'Article' => array( @@ -4143,7 +4143,7 @@ class ModelReadTest extends BaseModelTest { */ function testBindUnbind() { $this->loadFixtures('User', 'Comment', 'FeatureSet'); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->hasMany; $expected = array(); @@ -4547,7 +4547,7 @@ class ModelReadTest extends BaseModelTest { $this->assertEqual($result, $expected); - $TestModel2 = new DeviceType(); + $TestModel2 =& new DeviceType(); $expected = array( 'className' => 'FeatureSet', @@ -4602,7 +4602,7 @@ class ModelReadTest extends BaseModelTest { */ function testBindMultipleTimes() { $this->loadFixtures('User', 'Comment', 'Article'); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->hasMany; $expected = array(); @@ -4790,7 +4790,7 @@ class ModelReadTest extends BaseModelTest { */ function testAssociationAfterFind() { $this->loadFixtures('Post', 'Author', 'Comment'); - $TestModel = new Post(); + $TestModel =& new Post(); $result = $TestModel->find('all'); $expected = array( array( @@ -4850,7 +4850,7 @@ class ModelReadTest extends BaseModelTest { $this->assertEqual($result, $expected); unset($TestModel); - $Author = new Author(); + $Author =& new Author(); $Author->Post->bindModel(array( 'hasMany' => array( 'Comment' => array( @@ -4917,7 +4917,7 @@ class ModelReadTest extends BaseModelTest { 'DocumentDirectory' ); - $DeviceType = new DeviceType(); + $DeviceType =& new DeviceType(); $DeviceType->recursive = 2; $result = $DeviceType->read(null, 1); @@ -5006,7 +5006,7 @@ class ModelReadTest extends BaseModelTest { */ function testHabtmRecursiveBelongsTo() { $this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio', 'Syfile', 'Image'); - $Portfolio = new Portfolio(); + $Portfolio =& new Portfolio(); $result = $Portfolio->find(array('id' => 2), null, null, 3); $expected = array( @@ -5064,7 +5064,7 @@ class ModelReadTest extends BaseModelTest { */ function testHabtmFinderQuery() { $this->loadFixtures('Article', 'Tag', 'ArticlesTag'); - $Article = new Article(); + $Article =& new Article(); $sql = $this->db->buildStatement( array( @@ -5112,7 +5112,7 @@ class ModelReadTest extends BaseModelTest { */ function testHabtmLimitOptimization() { $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->hasAndBelongsToMany['Tag']['limit'] = 2; $result = $TestModel->read(null, 2); @@ -5182,7 +5182,7 @@ class ModelReadTest extends BaseModelTest { */ function testHasManyLimitOptimization() { $this->loadFixtures('Project', 'Thread', 'Message', 'Bid'); - $Project = new Project(); + $Project =& new Project(); $Project->recursive = 3; $result = $Project->find('all'); @@ -5296,7 +5296,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllRecursiveSelfJoin() { $this->loadFixtures('Home', 'AnotherArticle', 'Advertisement'); - $TestModel = new Home(); + $TestModel =& new Home(); $TestModel->recursive = 2; $result = $TestModel->find('all'); @@ -5412,7 +5412,7 @@ class ModelReadTest extends BaseModelTest { 'MyProduct' ); - $MyUser = new MyUser(); + $MyUser =& new MyUser(); $MyUser->recursive = 2; $result = $MyUser->find('all'); @@ -5473,7 +5473,7 @@ class ModelReadTest extends BaseModelTest { */ function testReadFakeThread() { $this->loadFixtures('CategoryThread'); - $TestModel = new CategoryThread(); + $TestModel =& new CategoryThread(); $fullDebug = $this->db->fullDebug; $this->db->fullDebug = true; @@ -5537,7 +5537,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindFakeThread() { $this->loadFixtures('CategoryThread'); - $TestModel = new CategoryThread(); + $TestModel =& new CategoryThread(); $fullDebug = $this->db->fullDebug; $this->db->fullDebug = true; @@ -5601,7 +5601,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAllFakeThread() { $this->loadFixtures('CategoryThread'); - $TestModel = new CategoryThread(); + $TestModel =& new CategoryThread(); $fullDebug = $this->db->fullDebug; $this->db->fullDebug = true; @@ -5821,7 +5821,7 @@ class ModelReadTest extends BaseModelTest { */ function testConditionalNumerics() { $this->loadFixtures('NumericArticle'); - $NumericArticle = new NumericArticle(); + $NumericArticle =& new NumericArticle(); $data = array('title' => '12345abcde'); $result = $NumericArticle->find($data); $this->assertTrue(!empty($result)); @@ -5839,7 +5839,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindAll() { $this->loadFixtures('User'); - $TestModel = new User(); + $TestModel =& new User(); $TestModel->cacheQueries = false; $result = $TestModel->find('all'); @@ -6069,7 +6069,7 @@ class ModelReadTest extends BaseModelTest { function testGenerateFindList() { $this->loadFixtures('Article', 'Apple', 'Post', 'Author', 'User'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->displayField = 'title'; $result = $TestModel->find('list', array( @@ -6204,7 +6204,7 @@ class ModelReadTest extends BaseModelTest { )); $this->assertEqual($result, $expected); - $TestModel = new Apple(); + $TestModel =& new Apple(); $expected = array( 1 => 'Red Apple 1', 2 => 'Bright Red Apple', @@ -6218,7 +6218,7 @@ class ModelReadTest extends BaseModelTest { $this->assertEqual($TestModel->find('list'), $expected); $this->assertEqual($TestModel->Parent->find('list'), $expected); - $TestModel = new Post(); + $TestModel =& new Post(); $result = $TestModel->find('list', array( 'fields' => 'Post.title' )); @@ -6299,7 +6299,7 @@ class ModelReadTest extends BaseModelTest { )); $this->assertEqual($result, $expected); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->find('list', array( 'fields' => array('User.user', 'User.password') )); @@ -6311,7 +6311,7 @@ class ModelReadTest extends BaseModelTest { ); $this->assertEqual($result, $expected); - $TestModel = new ModifiedAuthor(); + $TestModel =& new ModifiedAuthor(); $result = $TestModel->find('list', array( 'fields' => array('Author.id', 'Author.user') )); @@ -6331,7 +6331,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindField() { $this->loadFixtures('User'); - $TestModel = new User(); + $TestModel =& new User(); $TestModel->id = 1; $result = $TestModel->field('user'); @@ -6360,7 +6360,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindUnique() { $this->loadFixtures('User'); - $TestModel = new User(); + $TestModel =& new User(); $this->assertFalse($TestModel->isUnique(array( 'user' => 'nate' @@ -6383,7 +6383,7 @@ class ModelReadTest extends BaseModelTest { function testFindCount() { $this->loadFixtures('User', 'Project'); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->find('count'); $this->assertEqual($result, 4); @@ -6412,7 +6412,7 @@ class ModelReadTest extends BaseModelTest { return; } $this->loadFixtures('Project'); - $TestModel = new Project(); + $TestModel =& new Project(); $TestModel->create(array('name' => 'project')) && $TestModel->save(); $TestModel->create(array('name' => 'project')) && $TestModel->save(); $TestModel->create(array('name' => 'project')) && $TestModel->save(); @@ -6432,7 +6432,7 @@ class ModelReadTest extends BaseModelTest { } $this->loadFixtures('Project'); $db = ConnectionManager::getDataSource('test_suite'); - $TestModel = new Project(); + $TestModel =& new Project(); $result = $TestModel->find('count', array('conditions' => array( $db->expression('Project.name = \'Project 3\'') @@ -6452,7 +6452,7 @@ class ModelReadTest extends BaseModelTest { */ function testFindMagic() { $this->loadFixtures('User'); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->findByUser('mariano'); $expected = array( @@ -6483,7 +6483,7 @@ class ModelReadTest extends BaseModelTest { */ function testRead() { $this->loadFixtures('User', 'Article'); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->read(); $this->assertFalse($result); @@ -6571,7 +6571,7 @@ class ModelReadTest extends BaseModelTest { 'Featured', 'ArticleFeatured' ); - $TestModel = new User(); + $TestModel =& new User(); $result = $TestModel->bindModel(array('hasMany' => array('Article')), false); $this->assertTrue($result); @@ -6683,7 +6683,7 @@ class ModelReadTest extends BaseModelTest { 'Featured', 'Category' ); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->find('all', array('conditions' => array('Article.user_id' => 1))); $expected = array( @@ -6989,7 +6989,7 @@ class ModelReadTest extends BaseModelTest { */ function testRecursiveFindAllWithLimit() { $this->loadFixtures('Article', 'User', 'Tag', 'ArticlesTag', 'Comment', 'Attachment'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->hasMany['Comment']['limit'] = 2; diff --git a/cake/tests/cases/libs/model/model_validation.test.php b/cake/tests/cases/libs/model/model_validation.test.php index 0911c933..b4dcf22f 100755 --- a/cake/tests/cases/libs/model/model_validation.test.php +++ b/cake/tests/cases/libs/model/model_validation.test.php @@ -40,7 +40,7 @@ class ModelValidationTest extends BaseModelTest { * @return void */ function testValidationParams() { - $TestModel = new ValidationTest1(); + $TestModel =& new ValidationTest1(); $TestModel->validate['title'] = array( 'rule' => 'customValidatorWithParams', 'required' => true @@ -81,7 +81,7 @@ class ModelValidationTest extends BaseModelTest { * @return void */ function testInvalidFieldsWithFieldListParams() { - $TestModel = new ValidationTest1(); + $TestModel =& new ValidationTest1(); $TestModel->validate = $validate = array( 'title' => array( 'rule' => 'customValidator', diff --git a/cake/tests/cases/libs/model/model_write.test.php b/cake/tests/cases/libs/model/model_write.test.php index c41b981d..3d023ce1 100755 --- a/cake/tests/cases/libs/model/model_write.test.php +++ b/cake/tests/cases/libs/model/model_write.test.php @@ -95,7 +95,7 @@ class ModelWriteTest extends BaseModelTest { function testSaveDateAsFirstEntry() { $this->loadFixtures('Article'); - $Article = new Article(); + $Article =& new Article(); $data = array( 'Article' => array( @@ -124,7 +124,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUnderscoreFieldSave() { $this->loadFixtures('UnderscoreField'); - $UnderscoreField = new UnderscoreField(); + $UnderscoreField =& new UnderscoreField(); $currentCount = $UnderscoreField->find('count'); $this->assertEqual($currentCount, 3); @@ -152,7 +152,7 @@ class ModelWriteTest extends BaseModelTest { $this->skipIf($this->db->config['driver'] == 'sqlite'); $this->loadFixtures('Uuid'); - $TestModel = new Uuid(); + $TestModel =& new Uuid(); $TestModel->save(array('title' => 'Test record')); $result = $TestModel->findByTitle('Test record'); @@ -174,7 +174,7 @@ class ModelWriteTest extends BaseModelTest { '%s SQLite uses loose typing, this operation is unsupported' ); $this->loadFixtures('DataTest'); - $TestModel = new DataTest(); + $TestModel =& new DataTest(); $TestModel->create(array()); $TestModel->save(); @@ -190,7 +190,7 @@ class ModelWriteTest extends BaseModelTest { */ function testNonNumericHabtmJoinKey() { $this->loadFixtures('Post', 'Tag', 'PostsTag'); - $Post = new Post(); + $Post =& new Post(); $Post->bind('Tag', array('type' => 'hasAndBelongsToMany')); $Post->Tag->primaryKey = 'tag'; @@ -287,7 +287,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testAllowSimulatedFields() { - $TestModel = new ValidationTest1(); + $TestModel =& new ValidationTest1(); $TestModel->create(array( 'title' => 'foo', @@ -316,7 +316,7 @@ class ModelWriteTest extends BaseModelTest { Configure::write('Cache.disable', false); $this->loadFixtures('OverallFavorite'); - $OverallFavorite = new OverallFavorite(); + $OverallFavorite =& new OverallFavorite(); touch(CACHE . 'views' . DS . 'some_dir_overallfavorites_index.php'); touch(CACHE . 'views' . DS . 'some_dir_overall_favorites_index.php'); @@ -345,8 +345,8 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithCounterCache() { $this->loadFixtures('Syfile', 'Item'); - $TestModel = new Syfile(); - $TestModel2 = new Item(); + $TestModel =& new Syfile(); + $TestModel2 =& new Item(); $result = $TestModel->findById(1); $this->assertIdentical($result['Syfile']['item_count'], null); @@ -486,11 +486,11 @@ class ModelWriteTest extends BaseModelTest { $this->loadFixtures('CategoryThread'); $this->db->query('ALTER TABLE '. $this->db->fullTableName('category_threads') . " ADD COLUMN child_count INTEGER"); - $Category = new CategoryThread(); + $Category =& new CategoryThread(); $result = $Category->updateAll(array('CategoryThread.name' => "'updated'"), array('CategoryThread.parent_id' => 5)); $this->assertTrue($result); - $Category = new CategoryThread(); + $Category =& new CategoryThread(); $Category->belongsTo['ParentCategory']['counterCache'] = 'child_count'; $Category->updateCounterCache(array('parent_id' => 5)); $result = Set::extract($Category->find('all', array('conditions' => array('CategoryThread.id' => 5))), '{n}.CategoryThread.child_count'); @@ -505,8 +505,8 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithCounterCacheScope() { $this->loadFixtures('Syfile', 'Item'); - $TestModel = new Syfile(); - $TestModel2 = new Item(); + $TestModel =& new Syfile(); + $TestModel2 =& new Item(); $TestModel2->belongsTo['Syfile']['counterCache'] = true; $TestModel2->belongsTo['Syfile']['counterScope'] = array('published' => true); @@ -543,7 +543,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testValidatesBackwards() { - $TestModel = new TestValidate(); + $TestModel =& new TestValidate(); $TestModel->validate = array( 'user_id' => VALID_NUMBER, @@ -608,7 +608,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testValidates() { - $TestModel = new TestValidate(); + $TestModel =& new TestValidate(); $TestModel->validate = array( 'user_id' => 'numeric', @@ -961,7 +961,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveField() { $this->loadFixtures('Article'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->id = 1; $result = $TestModel->saveField('title', 'New First Article'); @@ -1012,7 +1012,7 @@ class ModelWriteTest extends BaseModelTest { $this->assertFalse($result); $this->loadFixtures('Node', 'Dependency'); - $Node = new Node(); + $Node =& new Node(); $Node->set('id', 1); $result = $Node->read(); $this->assertEqual(Set::extract('/ParentNode/name', $result), array('Second')); @@ -1037,7 +1037,7 @@ class ModelWriteTest extends BaseModelTest { 'ArticlesTag', 'Attachment' ); - $TestModel = new User(); + $TestModel =& new User(); $data = array('User' => array( 'user' => 'user', @@ -1047,7 +1047,7 @@ class ModelWriteTest extends BaseModelTest { $this->assertFalse($result); $this->assertTrue(!empty($TestModel->validationErrors)); - $TestModel = new Article(); + $TestModel =& new Article(); $data = array('Article' => array( 'user_id' => '', @@ -1250,7 +1250,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithSet() { $this->loadFixtures('Article'); - $TestModel = new Article(); + $TestModel =& new Article(); // Create record we will be updating later @@ -1377,7 +1377,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveWithNonExistentFields() { $this->loadFixtures('Article'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->recursive = -1; $data = array( @@ -1445,7 +1445,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveHabtm() { $this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'ArticlesTag'); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->findById(2); $expected = array( @@ -1916,7 +1916,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveHabtmCustomKeys() { $this->loadFixtures('Story', 'StoriesTag', 'Tag'); - $Story = new Story(); + $Story =& new Story(); $data = array( 'Story' => array('story' => '1'), @@ -1966,7 +1966,7 @@ class ModelWriteTest extends BaseModelTest { */ function testHabtmSaveKeyResolution() { $this->loadFixtures('Apple', 'Device', 'ThePaperMonkies'); - $ThePaper = new ThePaper(); + $ThePaper =& new ThePaper(); $ThePaper->id = 1; $ThePaper->save(array('Monkey' => array(2, 3))); @@ -2055,7 +2055,7 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationOfEmptyRecord() { $this->loadFixtures('Author'); - $TestModel = new Author(); + $TestModel =& new Author(); $this->assertEqual($TestModel->find('count'), 4); $TestModel->deleteAll(true, false, false); @@ -2073,7 +2073,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testCreateWithPKFiltering() { - $TestModel = new Article(); + $TestModel =& new Article(); $data = array( 'id' => 5, 'user_id' => 2, @@ -2170,8 +2170,8 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationWithMultipleData() { $this->loadFixtures('Article', 'Comment'); - $Article = new Article(); - $Comment = new Comment(); + $Article =& new Article(); + $Comment =& new Comment(); $articles = $Article->find('all', array( 'fields' => array('id','title'), @@ -2341,8 +2341,8 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationWithMultipleDataSameModel() { $this->loadFixtures('Article'); - $Article = new Article(); - $SecondaryArticle = new Article(); + $Article =& new Article(); + $SecondaryArticle =& new Article(); $result = $Article->field('title', array('id' => 1)); $this->assertEqual($result, 'First Article'); @@ -2399,8 +2399,8 @@ class ModelWriteTest extends BaseModelTest { */ function testCreationWithMultipleDataSameModelManualInstances() { $this->loadFixtures('PrimaryModel'); - $Primary = new PrimaryModel(); - $Secondary = new PrimaryModel(); + $Primary =& new PrimaryModel(); + $Secondary =& new PrimaryModel(); $result = $Primary->field('primary_name', array('id' => 1)); $this->assertEqual($result, 'Primary Name Existing'); @@ -2437,7 +2437,7 @@ class ModelWriteTest extends BaseModelTest { */ function testRecordExists() { $this->loadFixtures('User'); - $TestModel = new User(); + $TestModel =& new User(); $this->assertFalse($TestModel->exists()); $TestModel->read(null, 1); @@ -2447,7 +2447,7 @@ class ModelWriteTest extends BaseModelTest { $TestModel->id = 4; $this->assertTrue($TestModel->exists()); - $TestModel = new TheVoid(); + $TestModel =& new TheVoid(); $this->assertFalse($TestModel->exists()); $TestModel->id = 5; $this->assertFalse($TestModel->exists()); @@ -2460,7 +2460,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUpdateExisting() { $this->loadFixtures('User', 'Article', 'Comment'); - $TestModel = new User(); + $TestModel =& new User(); $TestModel->create(); $TestModel->save(array( @@ -2481,8 +2481,8 @@ class ModelWriteTest extends BaseModelTest { $this->assertEqual($result['User']['user'], 'updated user'); $this->assertEqual($result['User']['password'], 'some password'); - $Article = new Article(); - $Comment = new Comment(); + $Article =& new Article(); + $Comment =& new Comment(); $data = array( 'Comment' => array( 'id' => 1, @@ -2507,7 +2507,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUpdateMultiple() { $this->loadFixtures('Comment', 'Article', 'User', 'CategoryThread'); - $TestModel = new Comment(); + $TestModel =& new Comment(); $result = Set::extract($TestModel->find('all'), '{n}.Comment.user_id'); $expected = array('2', '4', '1', '1', '1', '2'); $this->assertEqual($result, $expected); @@ -2540,7 +2540,7 @@ class ModelWriteTest extends BaseModelTest { */ function testHabtmUuidWithUuidId() { $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolio'); - $TestModel = new Uuidportfolio(); + $TestModel =& new Uuidportfolio(); $data = array('Uuidportfolio' => array('name' => 'Portfolio 3')); $data['Uuiditem']['Uuiditem'] = array('483798c8-c7cc-430e-8cf9-4fcc40cf8569'); @@ -2558,7 +2558,7 @@ class ModelWriteTest extends BaseModelTest { **/ function testHabtmSavingWithNoPrimaryKeyUuidJoinTable() { $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); - $Fruit = new Fruit(); + $Fruit =& new Fruit(); $data = array( 'Fruit' => array( 'color' => 'Red', @@ -2581,7 +2581,7 @@ class ModelWriteTest extends BaseModelTest { **/ function testHabtmSavingWithNoPrimaryKeyUuidJoinTableNoWith() { $this->loadFixtures('UuidTag', 'Fruit', 'FruitsUuidTag'); - $Fruit = new FruitNoWith(); + $Fruit =& new FruitNoWith(); $data = array( 'Fruit' => array( 'color' => 'Red', @@ -2606,7 +2606,7 @@ class ModelWriteTest extends BaseModelTest { */ function testHabtmUuidWithNumericId() { $this->loadFixtures('Uuidportfolio', 'Uuiditem', 'UuiditemsUuidportfolioNumericid'); - $TestModel = new Uuiditem(); + $TestModel =& new Uuiditem(); $data = array('Uuiditem' => array('name' => 'Item 7', 'published' => 0)); $data['Uuidportfolio']['Uuidportfolio'] = array('480af662-eb8c-47d3-886b-230540cf8569'); @@ -2742,7 +2742,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAll() { $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); + $TestModel =& new Post(); $result = $TestModel->find('all'); $this->assertEqual(count($result), 3); @@ -2827,7 +2827,7 @@ class ModelWriteTest extends BaseModelTest { ))); $this->assertEqual($result, $expected); - $TestModel = new Comment(); + $TestModel =& new Comment(); $ts = date('Y-m-d H:i:s'); $result = $TestModel->saveAll(array( 'Comment' => array( @@ -2894,7 +2894,7 @@ class ModelWriteTest extends BaseModelTest { 'comment' => 'Article comment', 'user_id' => 1 ))); - $Article = new Article(); + $Article =& new Article(); $result = $Article->saveAll($data); $this->assertTrue($result); @@ -2927,7 +2927,7 @@ class ModelWriteTest extends BaseModelTest { ) ); - $Something = new Something(); + $Something =& new Something(); $result = $Something->saveAll($data); $this->assertTrue($result); $result = $Something->read(); @@ -3079,7 +3079,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllAtomic() { $this->loadFixtures('Article', 'User'); - $TestModel = new Article(); + $TestModel =& new Article(); $result = $TestModel->saveAll(array( 'Article' => array( @@ -3152,7 +3152,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllHasMany() { $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); $result = $TestModel->saveAll(array( @@ -3228,7 +3228,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllHasManyValidation() { $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); $TestModel->Comment->validate = array('comment' => 'notEmpty'); @@ -3268,7 +3268,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllTransaction() { $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); + $TestModel =& new Post(); $TestModel->validate = array('title' => 'notEmpty'); $data = array( @@ -3465,7 +3465,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllValidation() { $this->loadFixtures('Post', 'Author', 'Comment', 'Attachment'); - $TestModel = new Post(); + $TestModel =& new Post(); $data = array( array( @@ -3656,7 +3656,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testSaveAllValidationOnly() { - $TestModel = new Comment(); + $TestModel =& new Comment(); $TestModel->Attachment->validate = array('attachment' => 'notEmpty'); $data = array( @@ -3671,7 +3671,7 @@ class ModelWriteTest extends BaseModelTest { $result = $TestModel->saveAll($data, array('validate' => 'only')); $this->assertFalse($result); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->validate = array('title' => 'notEmpty'); $result = $TestModel->saveAll( array( @@ -3708,7 +3708,7 @@ class ModelWriteTest extends BaseModelTest { * @return void */ function testSaveAllValidateFirst() { - $model = new Article(); + $model =& new Article(); $model->deleteAll(true); $model->Comment->validate = array('comment' => 'notEmpty'); @@ -3787,7 +3787,7 @@ class ModelWriteTest extends BaseModelTest { */ function testUpdateWithCalculation() { $this->loadFixtures('DataTest'); - $model = new DataTest(); + $model =& new DataTest(); $result = $model->saveAll(array( array('count' => 5, 'float' => 1.1), array('count' => 3, 'float' => 1.2), @@ -3815,7 +3815,7 @@ class ModelWriteTest extends BaseModelTest { */ function testSaveAllHasManyValidationOnly() { $this->loadFixtures('Article', 'Comment'); - $TestModel = new Article(); + $TestModel =& new Article(); $TestModel->belongsTo = $TestModel->hasAndBelongsToMany = array(); $TestModel->Comment->validate = array('comment' => 'notEmpty'); @@ -3892,7 +3892,7 @@ class ModelWriteTest extends BaseModelTest { */ function testFindAllForeignKey() { $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll = new ProductUpdateAll(); + $ProductUpdateAll =& new ProductUpdateAll(); $conditions = array('Group.name' => 'group one'); @@ -3956,7 +3956,7 @@ class ModelWriteTest extends BaseModelTest { */ function testProductUpdateAll() { $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll = new ProductUpdateAll(); + $ProductUpdateAll =& new ProductUpdateAll(); $conditions = array('Group.name' => 'group one'); @@ -4002,7 +4002,7 @@ class ModelWriteTest extends BaseModelTest { */ function testProductUpdateAllWithoutForeignKey() { $this->loadFixtures('ProductUpdateAll', 'GroupUpdateAll'); - $ProductUpdateAll = new ProductUpdateAll(); + $ProductUpdateAll =& new ProductUpdateAll(); $conditions = array('Group.name' => 'group one'); diff --git a/cake/tests/cases/libs/model/schema.test.php b/cake/tests/cases/libs/model/schema.test.php index 209c5d24..fc35f5c1 100755 --- a/cake/tests/cases/libs/model/schema.test.php +++ b/cake/tests/cases/libs/model/schema.test.php @@ -480,7 +480,7 @@ class CakeSchemaTest extends CakeTestCase { $db =& ConnectionManager::getDataSource('test_suite'); $db->cacheSources = false; - $Schema = new CakeSchema(array( + $Schema =& new CakeSchema(array( 'connection' => 'test_suite', 'testdescribes' => array( 'id' => array('type' => 'integer', 'key' => 'primary'), diff --git a/cake/tests/cases/libs/object.test.php b/cake/tests/cases/libs/object.test.php index 896c47be..743d88da 100755 --- a/cake/tests/cases/libs/object.test.php +++ b/cake/tests/cases/libs/object.test.php @@ -154,7 +154,7 @@ class RequestActionPersistentController extends Controller { * @package cake * @subpackage cake.tests.cases.libs */ -class TestObject extends CakeObject { +class TestObject extends Object { /** * firstName property * @@ -392,7 +392,7 @@ class ObjectTest extends CakeTestCase { @unlink(CACHE . 'persistent' . DS . 'testmodel.php'); - $model = new ObjectTestModel(); + $model =& new ObjectTestModel(); $expected = ClassRegistry::keys(); ClassRegistry::flush(); diff --git a/cake/tests/cases/libs/sanitize.test.php b/cake/tests/cases/libs/sanitize.test.php index 3048613f..1899f16c 100755 --- a/cake/tests/cases/libs/sanitize.test.php +++ b/cake/tests/cases/libs/sanitize.test.php @@ -405,7 +405,7 @@ class SanitizeTest extends CakeTestCase { function testFormatColumns() { $this->loadFixtures('DataTest', 'Article'); - $this->DataTest = new SanitizeDataTest(array('alias' => 'DataTest')); + $this->DataTest =& new SanitizeDataTest(array('alias' => 'DataTest')); $data = array('DataTest' => array( 'id' => 'z', 'count' => '12a', @@ -424,7 +424,7 @@ class SanitizeTest extends CakeTestCase { $result = $this->DataTest->data; $this->assertEqual($result, $expected); - $this->Article = new SanitizeArticle(array('alias' => 'Article')); + $this->Article =& new SanitizeArticle(array('alias' => 'Article')); $data = array('Article' => array( 'id' => 'ZB', 'user_id' => '12', diff --git a/cake/tests/cases/libs/session.test.php b/cake/tests/cases/libs/session.test.php index ca208b0c..f74d626f 100755 --- a/cake/tests/cases/libs/session.test.php +++ b/cake/tests/cases/libs/session.test.php @@ -63,7 +63,7 @@ class SessionTest extends CakeTestCase { * @return void */ function setUp() { - $this->Session = new CakeSession(); + $this->Session =& new CakeSession(); $this->Session->start(); $this->Session->_checkValid(); } diff --git a/cake/tests/cases/libs/test_manager.test.php b/cake/tests/cases/libs/test_manager.test.php index 2c4c4129..b8eb5de2 100755 --- a/cake/tests/cases/libs/test_manager.test.php +++ b/cake/tests/cases/libs/test_manager.test.php @@ -41,8 +41,8 @@ class TestManagerTest extends CakeTestCase { * @access public */ function setUp() { - $this->Sut = new TestManager(); - $this->Reporter = new CakeHtmlReporter(); + $this->Sut =& new TestManager(); + $this->Reporter =& new CakeHtmlReporter(); } /** * testRunAllTests method @@ -51,11 +51,11 @@ class TestManagerTest extends CakeTestCase { * @access public */ function testRunAllTests() { - $folder = new Folder($this->Sut->_getTestsPath()); + $folder =& new Folder($this->Sut->_getTestsPath()); $extension = str_replace('.', '\.', TestManager::getExtension('test')); $out = $folder->findRecursive('.*' . $extension); - $reporter = new CakeHtmlReporter(); + $reporter =& new CakeHtmlReporter(); $list = TestManager::runAllTests($reporter, true); $this->assertEqual(count($out), count($list)); diff --git a/cake/tests/cases/libs/view/helpers/ajax.test.php b/cake/tests/cases/libs/view/helpers/ajax.test.php index 2d32d45a..439846e0 100755 --- a/cake/tests/cases/libs/view/helpers/ajax.test.php +++ b/cake/tests/cases/libs/view/helpers/ajax.test.php @@ -166,12 +166,12 @@ class AjaxHelperTest extends CakeTestCase { */ function setUp() { Router::reload(); - $this->Ajax = new TestAjaxHelper(); - $this->Ajax->Html = new HtmlHelper(); - $this->Ajax->Form = new FormHelper(); - $this->Ajax->Javascript = new JavascriptHelper(); + $this->Ajax =& new TestAjaxHelper(); + $this->Ajax->Html =& new HtmlHelper(); + $this->Ajax->Form =& new FormHelper(); + $this->Ajax->Javascript =& new JavascriptHelper(); $this->Ajax->Form->Html =& $this->Ajax->Html; - $view = new View(new AjaxTestController()); + $view =& new View(new AjaxTestController()); ClassRegistry::addObject('view', $view); ClassRegistry::addObject('PostAjaxTest', new PostAjaxTest()); } @@ -832,7 +832,7 @@ class AjaxHelperTest extends CakeTestCase { */ function testAfterRender() { $oldXUpdate = env('HTTP_X_UPDATE'); - $this->Ajax->Javascript = new TestJavascriptHelper(); + $this->Ajax->Javascript =& new TestJavascriptHelper(); $_SERVER['HTTP_X_UPDATE'] = 'secondDiv myDiv anotherDiv'; $result = $this->Ajax->div('myDiv'); diff --git a/cake/tests/cases/libs/view/helpers/form.test.php b/cake/tests/cases/libs/view/helpers/form.test.php index c82f7b04..af00110f 100755 --- a/cake/tests/cases/libs/view/helpers/form.test.php +++ b/cake/tests/cases/libs/view/helpers/form.test.php @@ -601,10 +601,10 @@ class FormHelperTest extends CakeTestCase { parent::setUp(); Router::reload(); - $this->Form = new FormHelper(); - $this->Form->Html = new HtmlHelper(); - $this->Controller = new ContactTestController(); - $this->View = new View($this->Controller); + $this->Form =& new FormHelper(); + $this->Form->Html =& new HtmlHelper(); + $this->Controller =& new ContactTestController(); + $this->View =& new View($this->Controller); ClassRegistry::addObject('view', $view); ClassRegistry::addObject('Contact', new Contact()); @@ -4348,11 +4348,11 @@ class FormHelperTest extends CakeTestCase { **/ function testFileUploadOnOtherModel() { ClassRegistry::removeObject('view'); - $controller = new Controller(); + $controller =& new Controller(); $controller->name = 'ValidateUsers'; $controller->uses = array('ValidateUser'); $controller->constructClasses(); - $view = new View($controller, true); + $view =& new View($controller, true); $this->Form->create('ValidateUser', array('type' => 'file')); $result = $this->Form->file('ValidateProfile.city'); diff --git a/cake/tests/cases/libs/view/helpers/html.test.php b/cake/tests/cases/libs/view/helpers/html.test.php index cfeee928..52dd5cba 100755 --- a/cake/tests/cases/libs/view/helpers/html.test.php +++ b/cake/tests/cases/libs/view/helpers/html.test.php @@ -90,8 +90,8 @@ class HtmlHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Html = new HtmlHelper(); - $view = new View(new TheHtmlTestController()); + $this->Html =& new HtmlHelper(); + $view =& new View(new TheHtmlTestController()); ClassRegistry::addObject('view', $view); $this->_appEncoding = Configure::read('App.encoding'); $this->_asset = Configure::read('Asset'); diff --git a/cake/tests/cases/libs/view/helpers/javascript.test.php b/cake/tests/cases/libs/view/helpers/javascript.test.php index 84c6a5cf..7ebad00e 100755 --- a/cake/tests/cases/libs/view/helpers/javascript.test.php +++ b/cake/tests/cases/libs/view/helpers/javascript.test.php @@ -114,10 +114,10 @@ class JavascriptTest extends CakeTestCase { * @return void */ function startTest() { - $this->Javascript = new JavascriptHelper(); - $this->Javascript->Html = new HtmlHelper(); - $this->Javascript->Form = new FormHelper(); - $this->View = new TheView(new TheJsTestController()); + $this->Javascript =& new JavascriptHelper(); + $this->Javascript->Html =& new HtmlHelper(); + $this->Javascript->Form =& new FormHelper(); + $this->View =& new TheView(new TheJsTestController()); ClassRegistry::addObject('view', $this->View); } /** @@ -140,10 +140,10 @@ class JavascriptTest extends CakeTestCase { * @return void */ function testConstruct() { - $Javascript = new JavascriptHelper(array('safe')); + $Javascript =& new JavascriptHelper(array('safe')); $this->assertTrue($Javascript->safe); - $Javascript = new JavascriptHelper(array('safe' => false)); + $Javascript =& new JavascriptHelper(array('safe' => false)); $this->assertFalse($Javascript->safe); } /** diff --git a/cake/tests/cases/libs/view/helpers/number.test.php b/cake/tests/cases/libs/view/helpers/number.test.php index 20d667a4..ccc54540 100755 --- a/cake/tests/cases/libs/view/helpers/number.test.php +++ b/cake/tests/cases/libs/view/helpers/number.test.php @@ -46,7 +46,7 @@ class NumberHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Number = new NumberHelper(); + $this->Number =& new NumberHelper(); } /** * tearDown method diff --git a/cake/tests/cases/libs/view/helpers/paginator.test.php b/cake/tests/cases/libs/view/helpers/paginator.test.php index 319d69d9..3b8817ab 100755 --- a/cake/tests/cases/libs/view/helpers/paginator.test.php +++ b/cake/tests/cases/libs/view/helpers/paginator.test.php @@ -60,11 +60,11 @@ class PaginatorHelperTest extends CakeTestCase { ) ) ); - $this->Paginator->Html = new HtmlHelper(); - $this->Paginator->Ajax = new AjaxHelper(); - $this->Paginator->Ajax->Html = new HtmlHelper(); - $this->Paginator->Ajax->Javascript = new JavascriptHelper(); - $this->Paginator->Ajax->Form = new FormHelper(); + $this->Paginator->Html =& new HtmlHelper(); + $this->Paginator->Ajax =& new AjaxHelper(); + $this->Paginator->Ajax->Html =& new HtmlHelper(); + $this->Paginator->Ajax->Javascript =& new JavascriptHelper(); + $this->Paginator->Ajax->Form =& new FormHelper(); Configure::write('Routing.admin', ''); Router::reload(); diff --git a/cake/tests/cases/libs/view/helpers/rss.test.php b/cake/tests/cases/libs/view/helpers/rss.test.php index 6b73692b..0f49570f 100755 --- a/cake/tests/cases/libs/view/helpers/rss.test.php +++ b/cake/tests/cases/libs/view/helpers/rss.test.php @@ -39,8 +39,8 @@ class RssHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Rss = new RssHelper(); - $this->Rss->Time = new TimeHelper(); + $this->Rss =& new RssHelper(); + $this->Rss->Time =& new TimeHelper(); $this->Rss->beforeRender(); $manager =& XmlManager::getInstance(); diff --git a/cake/tests/cases/libs/view/helpers/xml.test.php b/cake/tests/cases/libs/view/helpers/xml.test.php index 721e8b90..c7b1bae7 100755 --- a/cake/tests/cases/libs/view/helpers/xml.test.php +++ b/cake/tests/cases/libs/view/helpers/xml.test.php @@ -34,7 +34,7 @@ App::import('Helper', 'Xml'); * @package cake * @subpackage cake.tests.cases.libs.view.helpers */ -class TestXml extends CakeObject { +class TestXml extends Object { /** * content property * @@ -76,7 +76,7 @@ class XmlHelperTest extends CakeTestCase { * @return void */ function setUp() { - $this->Xml = new XmlHelper(); + $this->Xml =& new XmlHelper(); $this->Xml->beforeRender(); $manager =& XmlManager::getInstance(); $manager->namespaces = array(); diff --git a/cake/tests/cases/libs/view/theme.test.php b/cake/tests/cases/libs/view/theme.test.php index ce3cafe6..eeb5dd88 100755 --- a/cake/tests/cases/libs/view/theme.test.php +++ b/cake/tests/cases/libs/view/theme.test.php @@ -123,7 +123,7 @@ class TestThemeView extends ThemeView { * @return void */ function cakeError($method, $messages) { - $error = new ThemeViewTestErrorHandler($method, $messages); + $error =& new ThemeViewTestErrorHandler($method, $messages); return $error; } } diff --git a/cake/tests/cases/libs/view/view.test.php b/cake/tests/cases/libs/view/view.test.php index 62d1454a..103a4b73 100755 --- a/cake/tests/cases/libs/view/view.test.php +++ b/cake/tests/cases/libs/view/view.test.php @@ -164,7 +164,7 @@ class TestView extends View { * @return void */ function cakeError($method, $messages) { - $error = new ViewTestErrorHandler($method, $messages); + $error =& new ViewTestErrorHandler($method, $messages); return $error; } } @@ -541,7 +541,7 @@ class ViewTest extends CakeTestCase { **/ function testHelperCallbackTriggering() { $this->PostsController->helpers = array('Html', 'CallbackMock'); - $View = new TestView($this->PostsController); + $View =& new TestView($this->PostsController); $loaded = array(); $View->loaded = $View->loadHelpers($loaded, $this->PostsController->helpers); $View->loaded['CallbackMock']->expectOnce('beforeRender'); @@ -558,7 +558,7 @@ class ViewTest extends CakeTestCase { */ function testBeforeLayout() { $this->PostsController->helpers = array('TestAfter', 'Html'); - $View = new View($this->PostsController); + $View =& new View($this->PostsController); $out = $View->render('index'); $this->assertEqual($View->loaded['testAfter']->property, 'Valuation'); } @@ -572,7 +572,7 @@ class ViewTest extends CakeTestCase { $this->PostsController->helpers = array('TestAfter', 'Html'); $this->PostsController->set('variable', 'values'); - $View = new View($this->PostsController); + $View =& new View($this->PostsController); ClassRegistry::addObject('afterView', $View); $content = 'This is my view output'; diff --git a/cake/tests/cases/libs/xml.test.php b/cake/tests/cases/libs/xml.test.php index bb15e96e..acff6c89 100755 --- a/cake/tests/cases/libs/xml.test.php +++ b/cake/tests/cases/libs/xml.test.php @@ -39,7 +39,7 @@ class XmlTest extends CakeTestCase { * @return void */ function setUp() { - $manager = new XmlManager(); + $manager =& new XmlManager(); $manager->namespaces = array(); } /** @@ -111,7 +111,7 @@ class XmlTest extends CakeTestCase { array('Status' => array('id' => 2)) ) ); - $result = new Xml($data, array('format' => 'tags')); + $result =& new Xml($data, array('format' => 'tags')); $expected = '12'; $this->assertIdentical($result->toString(), $expected); @@ -123,27 +123,27 @@ class XmlTest extends CakeTestCase { * @return void **/ function testSerializationOfBooleanAndBooleanishValues() { - $xml = new Xml(array('data' => array('example' => false))); + $xml =& new Xml(array('data' => array('example' => false))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean values incorrectly handled. %s'); - $xml = new Xml(array('data' => array('example' => true))); + $xml =& new Xml(array('data' => array('example' => true))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean values incorrectly handled. %s'); - $xml = new Xml(array('data' => array('example' => null))); + $xml =& new Xml(array('data' => array('example' => null))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean values incorrectly handled. %s'); - $xml = new Xml(array('data' => array('example' => 0))); + $xml =& new Xml(array('data' => array('example' => 0))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean-ish values incorrectly handled. %s'); - $xml = new Xml(array('data' => array('example' => 1))); + $xml =& new Xml(array('data' => array('example' => 1))); $result = $xml->toString(false); $expected = ''; $this->assertEqual($result, $expected, 'Boolean-ish values incorrectly handled. %s'); @@ -334,7 +334,7 @@ class XmlTest extends CakeTestCase { * @return void */ function testCloneNode() { - $node = new XmlNode('element', 'myValue'); + $node =& new XmlNode('element', 'myValue'); $twin =& $node->cloneNode(); $this->assertEqual($node, $twin); } @@ -359,7 +359,7 @@ class XmlTest extends CakeTestCase { 'Industry' => array('id' => 2, 'name' => 'Education'), ) ); - $xml = new Xml($input, array('format' => 'tags')); + $xml =& new Xml($input, array('format' => 'tags')); $node =& $xml->children[0]->children[0]; $nextSibling =& $node->nextSibling(); @@ -392,7 +392,7 @@ class XmlTest extends CakeTestCase { 'Industry' => array('id' => 2, 'name' => 'Education'), ) ); - $xml = new Xml($input, array('format' => 'tags')); + $xml =& new Xml($input, array('format' => 'tags')); $node =& $xml->children[0]->children[1]; $prevSibling =& $node->previousSibling(); @@ -407,7 +407,7 @@ class XmlTest extends CakeTestCase { * @return void */ function testAddAndRemoveAttributes() { - $node = new XmlElement('myElement', 'superValue'); + $node =& new XmlElement('myElement', 'superValue'); $this->assertTrue(empty($node->attributes)); $attrs = array( @@ -418,12 +418,12 @@ class XmlTest extends CakeTestCase { $node->addAttribute($attrs); $this->assertEqual($node->attributes, $attrs); - $node = new XmlElement('myElement', 'superValue'); + $node =& new XmlElement('myElement', 'superValue'); $node->addAttribute('test', 'value'); $this->assertTrue(isset($node->attributes['test'])); - $node = new XmlElement('myElement', 'superValue'); - $obj = new StdClass(); + $node =& new XmlElement('myElement', 'superValue'); + $obj =& new StdClass(); $obj->class = 'info'; $obj->id = 'primaryInfoBox'; $node->addAttribute($obj); @@ -774,7 +774,7 @@ class XmlTest extends CakeTestCase { varchar(45) '; - $xml = new XML($filledValue); + $xml =& new XML($filledValue); $expected = array( 'Method' => array( 'name' => 'set_user_settings', @@ -798,7 +798,7 @@ class XmlTest extends CakeTestCase { '; - $xml = new XML($emptyValue); + $xml =& new XML($emptyValue); $expected = array( 'Method' => array( 'name' => 'set_user_settings', diff --git a/cake/tests/lib/cake_test_case.php b/cake/tests/lib/cake_test_case.php index 13e172a4..f642e36a 100755 --- a/cake/tests/lib/cake_test_case.php +++ b/cake/tests/lib/cake_test_case.php @@ -239,7 +239,7 @@ class CakeTestCase extends UnitTestCase { $this->_actionFixtures = array(); foreach ($models as $model) { - $fixture = new CakeTestFixture($this->db); + $fixture =& new CakeTestFixture($this->db); $fixture->name = $model['model'] . 'Test'; $fixture->table = $model['table']; @@ -335,7 +335,7 @@ class CakeTestCase extends UnitTestCase { $return = $params['return']; $params = array_diff_key($params, array('data' => null, 'method' => null, 'return' => null)); - $dispatcher = new CakeTestDispatcher(); + $dispatcher =& new CakeTestDispatcher(); $dispatcher->testCase($this); if ($return != 'result') { @@ -770,7 +770,7 @@ class CakeTestCase extends UnitTestCase { if (isset($fixtureFile)) { require_once($fixtureFile); $fixtureClass = Inflector::camelize($fixture) . 'Fixture'; - $this->_fixtures[$this->fixtures[$index]] = new $fixtureClass($this->db); + $this->_fixtures[$this->fixtures[$index]] =& new $fixtureClass($this->db); $this->_fixtureClassMap[Inflector::camelize($fixture)] = $this->fixtures[$index]; } } diff --git a/cake/tests/lib/cake_test_fixture.php b/cake/tests/lib/cake_test_fixture.php index faba01fa..cd12f9a3 100755 --- a/cake/tests/lib/cake_test_fixture.php +++ b/cake/tests/lib/cake_test_fixture.php @@ -30,7 +30,7 @@ * @package cake * @subpackage cake.cake.tests.lib */ -class CakeTestFixture extends CakeObject { +class CakeTestFixture extends Object { /** * Name of the object * @@ -81,7 +81,7 @@ class CakeTestFixture extends CakeObject { ClassRegistry::config(array('ds' => 'test_suite')); ClassRegistry::flush(); } elseif (isset($import['table'])) { - $model = new Model(null, $import['table'], $import['connection']); + $model =& new Model(null, $import['table'], $import['connection']); $db =& ConnectionManager::getDataSource($import['connection']); $db->cacheSources = false; $model->useDbConfig = $import['connection']; diff --git a/cake/tests/lib/code_coverage_manager.php b/cake/tests/lib/code_coverage_manager.php index 511b9c9d..1000c675 100755 --- a/cake/tests/lib/code_coverage_manager.php +++ b/cake/tests/lib/code_coverage_manager.php @@ -78,7 +78,7 @@ class CodeCoverageManager { function &getInstance() { static $instance = array(); if (!$instance) { - $instance[0] = new CodeCoverageManager(); + $instance[0] =& new CodeCoverageManager(); } return $instance[0]; } @@ -477,10 +477,10 @@ class CodeCoverageManager { break; } } - $testManager = new TestManager(); + $testManager =& new TestManager(); $testFile = str_replace(array('/', $testManager->_testExtension), array(DS, '.php'), $file); - $folder = new Folder(); + $folder =& new Folder(); $folder->cd(ROOT . DS . CAKE_TESTS_LIB); $contents = $folder->ls(); @@ -506,7 +506,7 @@ class CodeCoverageManager { */ function __testObjectFilesFromGroupFile($groupFile, $isApp = true) { $manager = CodeCoverageManager::getInstance(); - $testManager = new TestManager(); + $testManager =& new TestManager(); $path = TESTS . 'groups'; diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php index c49e19b2..d614ed6d 100755 --- a/cake/tests/lib/test_manager.php +++ b/cake/tests/lib/test_manager.php @@ -77,15 +77,15 @@ class TestManager { * @access public */ function runAllTests(&$reporter, $testing = false) { - $manager = new TestManager(); + $manager =& new TestManager(); $testCases =& $manager->_getTestFileList($manager->_getTestsPath()); if ($manager->appTest) { - $test = new GroupTest('All App Tests'); + $test =& new GroupTest('All App Tests'); } else if ($manager->pluginTest) { - $test = new GroupTest('All ' . Inflector::humanize($manager->pluginTest) . ' Plugin Tests'); + $test =& new GroupTest('All ' . Inflector::humanize($manager->pluginTest) . ' Plugin Tests'); } else { - $test = new GroupTest('All Core Tests'); + $test =& new GroupTest('All Core Tests'); } if ($testing) { @@ -107,7 +107,7 @@ class TestManager { * @access public */ function runTestCase($testCaseFile, &$reporter, $testing = false) { - $manager = new TestManager(); + $manager =& new TestManager(); $testCaseFileWithPath = $manager->_getTestsPath() . DS . $testCaseFile; @@ -120,7 +120,7 @@ class TestManager { return true; } - $test = new GroupTest("Individual test case: " . $testCaseFile); + $test =& new GroupTest("Individual test case: " . $testCaseFile); $test->addTestFile($testCaseFileWithPath); return $test->run($reporter); } @@ -133,7 +133,7 @@ class TestManager { * @access public */ function runGroupTest($groupTestName, &$reporter) { - $manager = new TestManager(); + $manager =& new TestManager(); $filePath = $manager->_getTestsPath('groups') . DS . strtolower($groupTestName) . $manager->_groupExtension; if (!file_exists($filePath)) { @@ -141,7 +141,7 @@ class TestManager { } require_once $filePath; - $test = new GroupTest($groupTestName . ' group test'); + $test =& new GroupTest($groupTestName . ' group test'); foreach ($manager->_getGroupTestClassNames($filePath) as $groupTest) { $testCase = new $groupTest(); $test->addTestCase($testCase); @@ -160,7 +160,7 @@ class TestManager { * @access public */ function addTestCasesFromDirectory(&$groupTest, $directory = '.') { - $manager = new TestManager(); + $manager =& new TestManager(); $testCases =& $manager->_getTestFileList($directory); foreach ($testCases as $testCase) { $groupTest->addTestFile($testCase); @@ -175,7 +175,7 @@ class TestManager { * @access public */ function addTestFile(&$groupTest, $file) { - $manager = new TestManager(); + $manager =& new TestManager(); if (file_exists($file.'.test.php')) { $file .= '.test.php'; @@ -190,7 +190,7 @@ class TestManager { * @access public */ function &getTestCaseList() { - $manager = new TestManager(); + $manager =& new TestManager(); $return = $manager->_getTestCaseList($manager->_getTestsPath()); return $return; } @@ -222,7 +222,7 @@ class TestManager { * @access public */ function &getGroupTestList() { - $manager = new TestManager(); + $manager =& new TestManager(); $return = $manager->_getTestGroupList($manager->_getTestsPath('groups')); return $return; } @@ -360,7 +360,7 @@ class TestManager { * @access public */ function getExtension($type = 'test') { - $manager = new TestManager(); + $manager =& new TestManager(); if ($type == 'test') { return $manager->_testExtension; } @@ -380,7 +380,7 @@ class CliTestManager extends TestManager { * @access public */ function &getGroupTestList() { - $manager = new CliTestManager(); + $manager =& new CliTestManager(); $groupTests =& $manager->_getTestGroupList($manager->_getTestsPath('groups')); $buffer = "Available Group Test:\n"; @@ -395,7 +395,7 @@ class CliTestManager extends TestManager { * @access public */ function &getTestCaseList() { - $manager = new CliTestManager(); + $manager =& new CliTestManager(); $testCases =& $manager->_getTestCaseList($manager->_getTestsPath()); $buffer = "Available Test Cases:\n"; @@ -438,7 +438,7 @@ class TextTestManager extends TestManager { * @access public */ function &getGroupTestList() { - $manager = new TextTestManager(); + $manager =& new TextTestManager(); $groupTests =& $manager->_getTestGroupList($manager->_getTestsPath('groups')); $buffer = "Core Test Groups:\n"; @@ -465,7 +465,7 @@ class TextTestManager extends TestManager { * @access public */ function &getTestCaseList() { - $manager = new TextTestManager(); + $manager =& new TextTestManager(); $testCases =& $manager->_getTestCaseList($manager->_getTestsPath()); $buffer = "Core Test Cases:\n"; @@ -526,7 +526,7 @@ class HtmlTestManager extends TestManager { */ function &getGroupTestList() { $urlExtra = ''; - $manager = new HtmlTestManager(); + $manager =& new HtmlTestManager(); $groupTests =& $manager->_getTestGroupList($manager->_getTestsPath('groups')); $buffer = "

      Core Test Groups:

      \n
        "; @@ -554,7 +554,7 @@ class HtmlTestManager extends TestManager { */ function &getTestCaseList() { $urlExtra = ''; - $manager = new HtmlTestManager(); + $manager =& new HtmlTestManager(); $testCases =& $manager->_getTestCaseList($manager->_getTestsPath()); $buffer = "

        Core Test Cases:

        \n
          "; @@ -599,10 +599,10 @@ if (function_exists('caketestsgetreporter')) { switch (CAKE_TEST_OUTPUT) { case CAKE_TEST_OUTPUT_HTML: require_once CAKE_TESTS_LIB . 'cake_reporter.php'; - $Reporter = new CakeHtmlReporter(); + $Reporter =& new CakeHtmlReporter(); break; default: - $Reporter = new TextReporter(); + $Reporter =& new TextReporter(); break; } } @@ -732,7 +732,7 @@ if (function_exists('caketestsgetreporter')) { if (!class_exists('dispatcher')) { require CAKE . 'dispatcher.php'; } - $dispatch = new Dispatcher(); + $dispatch =& new Dispatcher(); $dispatch->baseUrl(); define('BASE', $dispatch->webroot); $baseUrl = BASE; diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php index c10ec835..ab3cb7b2 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/other_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class OtherComponentComponent extends CakeObject { +class OtherComponentComponent extends Object { } ?> \ No newline at end of file diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php index 3fd81a56..6a80527d 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/plugins_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class PluginsComponentComponent extends CakeObject { +class PluginsComponentComponent extends Object { var $components = array('TestPlugin.OtherComponent'); } ?> \ No newline at end of file diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php index 0e6690a2..23a462bf 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class TestPluginComponentComponent extends CakeObject { +class TestPluginComponentComponent extends Object { var $components = array('TestPlugin.TestPluginOtherComponent'); } ?> \ No newline at end of file diff --git a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php index ac480a7a..560e0702 100755 --- a/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php +++ b/cake/tests/test_app/plugins/test_plugin/controllers/components/test_plugin_other_component.php @@ -24,7 +24,7 @@ * @lastmodified $Date$ * @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License */ -class TestPluginOtherComponentComponent extends CakeObject { +class TestPluginOtherComponentComponent extends Object { } ?> \ No newline at end of file diff --git a/conf/nginx-proxy.conf b/conf/nginx-proxy.conf index ba92a2c6..e1652854 100644 --- a/conf/nginx-proxy.conf +++ b/conf/nginx-proxy.conf @@ -44,14 +44,14 @@ http { ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; - # Upstream servers (using external container names) + # Upstream servers upstream cmc_staging { - server cmc-nginx-staging:80; + server nginx-staging:80; keepalive 32; } upstream cmc_production { - server cmc-nginx-production:80; + server nginx-production:80; keepalive 32; } diff --git a/docker-compose.caddy-staging-ubuntu.yml b/docker-compose.caddy-staging-ubuntu.yml index 538e571c..08635661 100644 --- a/docker-compose.caddy-staging-ubuntu.yml +++ b/docker-compose.caddy-staging-ubuntu.yml @@ -12,21 +12,9 @@ services: ports: - "127.0.0.1:8091:80" volumes: - # Mount specific app directories while preserving cake core - - ./app/config:/var/www/cmc-sales/app/config - - ./app/controllers:/var/www/cmc-sales/app/controllers - - ./app/models:/var/www/cmc-sales/app/models - - ./app/views:/var/www/cmc-sales/app/views - - ./app/vendors:/var/www/cmc-sales/app/vendors - - ./app/webroot/css:/var/www/cmc-sales/app/webroot/css - - ./app/webroot/js:/var/www/cmc-sales/app/webroot/js - - ./app/webroot/img:/var/www/cmc-sales/app/webroot/img + - ./app:/var/www/cmc-sales/app - staging_pdf_data:/var/www/cmc-sales/app/webroot/pdf - staging_attachments_data:/var/www/cmc-sales/app/webroot/attachments_files - # Mount cake directory to ensure CakePHP core is available - - ./cake:/var/www/cmc-sales/cake - - ./vendors:/var/www/cmc-sales/vendors - - ./index.php:/var/www/cmc-sales/index.php restart: unless-stopped environment: - APP_ENV=staging diff --git a/docker-compose.proxy.yml b/docker-compose.proxy.yml new file mode 100644 index 00000000..616270ab --- /dev/null +++ b/docker-compose.proxy.yml @@ -0,0 +1,68 @@ +# Main reverse proxy for both staging and production +version: '3.8' + +services: + nginx-proxy: + image: nginx:latest + container_name: cmc-nginx-proxy + ports: + - "80:80" + - "443:443" + volumes: + - ./conf/nginx-proxy.conf:/etc/nginx/nginx.conf + - lego_certificates:/etc/ssl/certs:ro + - lego_acme_challenge:/var/www/acme-challenge:ro + restart: unless-stopped + depends_on: + - nginx-staging + - nginx-production + networks: + - proxy-network + - cmc-staging-network + - cmc-production-network + + lego: + image: goacme/lego:latest + container_name: cmc-lego + volumes: + - lego_certificates:/data/certificates + - lego_accounts:/data/accounts + - lego_acme_challenge:/data/acme-challenge + - ./scripts:/scripts:ro + environment: + - LEGO_DISABLE_CNAME=true + command: sleep infinity + restart: unless-stopped + networks: + - proxy-network + + # Import staging services + nginx-staging: + extends: + file: docker-compose.staging.yml + service: nginx-staging + networks: + - proxy-network + - cmc-staging-network + + # Import production services + nginx-production: + extends: + file: docker-compose.production.yml + service: nginx-production + networks: + - proxy-network + - cmc-production-network + +volumes: + lego_certificates: + lego_accounts: + lego_acme_challenge: + +networks: + proxy-network: + driver: bridge + cmc-staging-network: + external: true + cmc-production-network: + external: true \ No newline at end of file diff --git a/index.php b/index.php index 7e3c92de..c6a3a1b1 100755 --- a/index.php +++ b/index.php @@ -52,12 +52,6 @@ require CORE_PATH . 'cake' . DS . 'basics.php'; $TIME_START = getMicrotime(); require CORE_PATH . 'cake' . DS . 'config' . DS . 'paths.php'; - - // Load PHP 7 compatibility early - if (file_exists(APP_DIR . DS . 'config' . DS . 'php7_compat.php')) { - require APP_DIR . DS . 'config' . DS . 'php7_compat.php'; - } - require LIBS . 'object.php'; require LIBS . 'inflector.php'; require LIBS . 'configure.php'; diff --git a/scripts/backup-db.sh b/scripts/backup-db.sh deleted file mode 100755 index 9094d9db..00000000 --- a/scripts/backup-db.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash - -# Database backup script for CMC Sales -# Usage: ./scripts/backup-db.sh [staging|production] - -set -e - -ENVIRONMENT=${1:-production} -BACKUP_DIR="/var/backups/cmc-sales" -DATE=$(date +%Y%m%d-%H%M%S) - -# Create backup directory if it doesn't exist -mkdir -p "$BACKUP_DIR" - -case $ENVIRONMENT in - staging) - CONTAINER="cmc-db-staging" - DB_NAME="cmc_staging" - DB_USER="cmc_staging" - BACKUP_FILE="$BACKUP_DIR/backup_staging_${DATE}.sql.gz" - ;; - production) - CONTAINER="cmc-db-production" - DB_NAME="cmc" - DB_USER="cmc" - BACKUP_FILE="$BACKUP_DIR/backup_production_${DATE}.sql.gz" - ;; - *) - echo "Usage: $0 [staging|production]" - exit 1 - ;; -esac - -echo "Creating backup for $ENVIRONMENT environment..." -echo "Container: $CONTAINER" -echo "Database: $DB_NAME" -echo "Output: $BACKUP_FILE" - -# Create backup -docker exec -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ - $CONTAINER \ - mysqldump --single-transaction --routines --triggers --user=$DB_USER $DB_NAME | \ - gzip > "$BACKUP_FILE" - -# Verify backup was created -if [ -f "$BACKUP_FILE" ]; then - BACKUP_SIZE=$(stat -f%z "$BACKUP_FILE" 2>/dev/null || stat -c%s "$BACKUP_FILE" 2>/dev/null) - echo "Backup created successfully: $BACKUP_FILE (${BACKUP_SIZE} bytes)" - - # Clean up old backups (keep last 7 days) - find "$BACKUP_DIR" -name "backup_${ENVIRONMENT}_*.sql.gz" -type f -mtime +7 -delete - echo "Old backups cleaned up (kept last 7 days)" -else - echo "ERROR: Backup file was not created!" - exit 1 -fi \ No newline at end of file diff --git a/scripts/debug-php-container.sh b/scripts/debug-php-container.sh deleted file mode 100755 index 324dd1df..00000000 --- a/scripts/debug-php-container.sh +++ /dev/null @@ -1,57 +0,0 @@ -#!/bin/bash - -# Debug script for PHP container segfault issues - -echo "=== PHP Container Debug Script ===" -echo "" - -# Check if container exists -echo "1. Checking for existing containers..." -docker ps -a | grep cmc-php-staging - -# Get detailed logs -echo "" -echo "2. Getting container logs..." -docker logs cmc-php-staging --tail 50 2>&1 | tee php-debug.log - -# Check container exit status -echo "" -echo "3. Checking container exit status..." -docker inspect cmc-php-staging --format='{{.State.ExitCode}} {{.State.Error}}' 2>/dev/null || echo "Container not found" - -# Try running with different commands to isolate the issue -echo "" -echo "4. Testing different startup commands..." - -# Test 1: Just run bash -echo " Test 1: Running bash shell..." -docker run --rm -it --name cmc-php-test1 \ - --platform linux/amd64 \ - -v $(pwd):/debug \ - ghcr.io/kzrl/ubuntu:lucid \ - bash -c "echo 'Container started successfully'" - -# Test 2: Check Apache installation -echo "" -echo " Test 2: Testing with Apache installation..." -docker run --rm -it --name cmc-php-test2 \ - --platform linux/amd64 \ - -e DEBIAN_FRONTEND=noninteractive \ - ghcr.io/kzrl/ubuntu:lucid \ - bash -c "sed -i 's/archive/old-releases/' /etc/apt/sources.list && apt-get update && apt-get -y install apache2 && echo 'Apache installed successfully'" - -# Test 3: Build with alternative command -echo "" -echo "5. Building with debug mode..." -docker build --platform linux/amd64 --progress=plain -t cmc-php-debug -f Dockerfile.debug . 2>&1 | tee build-debug.log - -echo "" -echo "Debug information saved to:" -echo " - php-debug.log" -echo " - build-debug.log" -echo "" -echo "Common segfault causes:" -echo " 1. Platform incompatibility (ARM vs x86)" -echo " 2. Corrupted base image" -echo " 3. Memory issues" -echo " 4. Incompatible package versions" \ No newline at end of file diff --git a/scripts/deploy-staging-caddy.sh b/scripts/deploy-staging-caddy.sh deleted file mode 100755 index 438394f0..00000000 --- a/scripts/deploy-staging-caddy.sh +++ /dev/null @@ -1,127 +0,0 @@ -#!/bin/bash - -# Deployment script for staging environment with Caddy and containers -# This script deploys the containerized staging environment - -set -e - -echo "=== CMC Sales Staging Deployment with Caddy ===" -echo "" - -# Check if running as root for Caddy operations -if [ "$EUID" -eq 0 ]; then - SUDO="" -else - SUDO="sudo" - echo "Note: You may be prompted for sudo password for Caddy operations" -fi - -# 1. Check prerequisites -echo "Checking prerequisites..." - -# Check if Caddy is installed -if ! command -v caddy &> /dev/null; then - echo "ERROR: Caddy is not installed. Please run ./scripts/install-caddy.sh first" - exit 1 -fi - -# Check if Docker is installed -if ! command -v docker &> /dev/null; then - echo "ERROR: Docker is not installed" - exit 1 -fi - -# Check if docker-compose is available -if ! docker compose version &> /dev/null; then - echo "ERROR: Docker Compose is not available" - exit 1 -fi - -# 2. Create necessary directories -echo "Creating directories..." -$SUDO mkdir -p /var/log/caddy -$SUDO chown caddy:caddy /var/log/caddy - -# 3. Stop existing services if running -echo "Checking for existing services..." -if docker ps | grep -q "cmc-.*-staging"; then - echo "Stopping existing staging containers..." - docker compose -f docker-compose.caddy-staging.yml down -fi - -# 4. Build and start containers -echo "Building and starting staging containers..." -docker compose -f docker-compose.caddy-staging.yml build --no-cache -docker compose -f docker-compose.caddy-staging.yml up -d - -# Wait for containers to be ready -echo "Waiting for containers to be ready..." -sleep 10 - -# 5. Check container health -echo "Checking container health..." -docker ps --filter "name=staging" - -# Test internal endpoints -echo "" -echo "Testing internal endpoints..." -echo -n "PHP container: " -curl -s -o /dev/null -w "%{http_code}" http://localhost:8091 || echo "Failed" -echo "" -echo -n "Go container: " -curl -s -o /dev/null -w "%{http_code}" http://localhost:8092/api/v1/health || echo "Failed" -echo "" - -# 6. Deploy Caddy configuration -echo "Deploying Caddy configuration..." - -# Backup existing Caddyfile -if [ -f /etc/caddy/Caddyfile ]; then - $SUDO cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.backup.$(date +%Y%m%d-%H%M%S) -fi - -# Copy new Caddyfile -$SUDO cp Caddyfile.staging-containers /etc/caddy/Caddyfile.staging - -# Validate configuration -echo "Validating Caddy configuration..." -caddy validate --config /etc/caddy/Caddyfile.staging - -# 7. Update Caddy to use staging config -echo "Updating Caddy configuration..." -$SUDO cp /etc/caddy/Caddyfile.staging /etc/caddy/Caddyfile - -# Reload Caddy -echo "Reloading Caddy..." -$SUDO systemctl reload caddy - -# 8. Final health check -echo "" -echo "Performing final health check..." -sleep 5 - -# Test public endpoint -echo -n "Public HTTPS endpoint: " -if curl -s -o /dev/null -w "%{http_code}" https://staging.cmc.springupsoftware.com/health; then - echo " - OK" -else - echo " - Failed (this is normal if DNS is not set up yet)" -fi - -# 9. Show status -echo "" -echo "=== Deployment Complete ===" -echo "" -echo "Container Status:" -docker compose -f docker-compose.caddy-staging.yml ps -echo "" -echo "Caddy Status:" -$SUDO systemctl status caddy --no-pager | head -n 10 -echo "" -echo "Access staging at: https://staging.cmc.springupsoftware.com" -echo "Basic auth: Use credentials configured in Caddyfile" -echo "" -echo "Logs:" -echo " Caddy: sudo journalctl -u caddy -f" -echo " Containers: docker compose -f docker-compose.caddy-staging.yml logs -f" -echo " Access log: sudo tail -f /var/log/caddy/staging.cmc.springupsoftware.com.log" \ No newline at end of file diff --git a/scripts/fix-cakephp-compatibility.sh b/scripts/fix-cakephp-compatibility.sh deleted file mode 100755 index 2168a67c..00000000 --- a/scripts/fix-cakephp-compatibility.sh +++ /dev/null @@ -1,145 +0,0 @@ -#!/bin/bash - -# Script to fix CakePHP 1.2.5 compatibility issues with newer PHP versions - -echo "=== CakePHP 1.2.5 Compatibility Fixes ===" -echo "" - -# Check if we're in the right directory -if [ ! -d "app/config" ]; then - echo "ERROR: Run this script from the CMC Sales root directory" - exit 1 -fi - -echo "Creating compatibility fixes..." - -# 1. Create a compatibility helper for PHP 7+ if it doesn't exist -mkdir -p app/config/patches - -cat > app/config/patches/php7_compatibility.php << 'EOF' -> app/config/bootstrap.php - echo "// PHP 7+ Compatibility" >> app/config/bootstrap.php - echo "if (version_compare(PHP_VERSION, '7.0.0') >= 0) {" >> app/config/bootstrap.php - echo " require_once(dirname(__FILE__) . '/patches/php7_compatibility.php');" >> app/config/bootstrap.php - echo "}" >> app/config/bootstrap.php - echo "Added compatibility include to bootstrap.php" -fi - -# 3. Fix common CakePHP core issues -echo "Checking for common issues..." - -# Fix Object::cakeError if it exists -if [ -f "cake/libs/object.php" ]; then - # Backup original - cp cake/libs/object.php cake/libs/object.php.bak - - # Fix call-time pass-by-reference - sed -i 's/&\$this->/\$this->/g' cake/libs/object.php - echo "Fixed cake/libs/object.php" -fi - -# 4. Create a test script -cat > app/webroot/test_php.php << 'EOF' -PHP Compatibility Test"; -echo "

          PHP Version: " . PHP_VERSION . "

          "; -echo "

          MySQL Extension: " . (function_exists('mysql_connect') || function_exists('mysqli_connect') ? 'Available' : 'Not Available') . "

          "; -echo "

          GD Extension: " . (extension_loaded('gd') ? 'Loaded' : 'Not Loaded') . "

          "; -echo "

          Error Reporting: " . error_reporting() . "

          "; -echo "

          CakePHP Constants:

          "; -echo "
          ";
          -if (defined('ROOT')) echo "ROOT: " . ROOT . "\n";
          -if (defined('APP_DIR')) echo "APP_DIR: " . APP_DIR . "\n";
          -if (defined('CAKE_CORE_INCLUDE_PATH')) echo "CAKE_CORE_INCLUDE_PATH: " . CAKE_CORE_INCLUDE_PATH . "\n";
          -echo "
          "; -phpinfo(); -EOF - -echo "" -echo "Compatibility fixes applied!" -echo "" -echo "Test your PHP setup at: http://localhost:8091/test_php.php" -echo "" -echo "If you still have issues:" -echo "1. Check error logs: docker logs cmc-php-staging" -echo "2. Try PHP 5.6 version: docker compose -f docker-compose.caddy-staging-php56.yml up -d" -echo "3. Use the original Dockerfile with fixes" \ No newline at end of file diff --git a/scripts/fix-cakephp-php7.sh b/scripts/fix-cakephp-php7.sh deleted file mode 100755 index 16ee13d3..00000000 --- a/scripts/fix-cakephp-php7.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash - -# Fix CakePHP for PHP 7 compatibility - -echo "Fixing CakePHP for PHP 7 compatibility..." - -# Fix =& new syntax in cake directory -echo "Fixing deprecated =& new syntax..." -find cake -name "*.php" -type f -exec perl -i -pe 's/=&\s*new/= new/g' {} \; - -# Fix extends Object to extends CakeObject -echo "Fixing Object class inheritance..." -find cake -name "*.php" -type f -exec perl -i -pe 's/extends Object/extends CakeObject/g' {} \; - -echo "CakePHP PHP 7 compatibility fixes applied!" -echo "Note: This is a bulk fix and may need manual verification for edge cases." \ No newline at end of file diff --git a/scripts/install-caddy.sh b/scripts/install-caddy.sh deleted file mode 100755 index 85e5c967..00000000 --- a/scripts/install-caddy.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash - -# Caddy installation script for Debian 12 -# Usage: sudo ./scripts/install-caddy.sh - -set -e - -if [ "$EUID" -ne 0 ]; then - echo "Please run as root (use sudo)" - exit 1 -fi - -echo "Installing Caddy web server on Debian 12..." - -# Install dependencies -apt update -apt install -y debian-keyring debian-archive-keyring apt-transport-https curl - -# Add Caddy GPG key -curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg - -# Add Caddy repository -curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | tee /etc/apt/sources.list.d/caddy-stable.list - -# Update and install Caddy -apt update -apt install -y caddy - -# Create directories -mkdir -p /etc/caddy -mkdir -p /var/log/caddy -mkdir -p /var/lib/caddy - -# Set permissions -chown caddy:caddy /var/log/caddy -chown caddy:caddy /var/lib/caddy - -# Enable and start Caddy service -systemctl enable caddy -systemctl stop caddy # We'll configure it first - -echo "Caddy installed successfully!" -echo "" -echo "Next steps:" -echo "1. Copy your Caddyfile to /etc/caddy/Caddyfile" -echo "2. Update the basicauth passwords in Caddyfile" -echo "3. Start Caddy with: sudo systemctl start caddy" -echo "4. Check status with: sudo systemctl status caddy" -echo "" -echo "Generate password hash with: caddy hash-password" \ No newline at end of file diff --git a/scripts/lego-list-certs.sh b/scripts/lego-list-certs.sh deleted file mode 100755 index 65e9f539..00000000 --- a/scripts/lego-list-certs.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash - -# Lego SSL certificate listing script for CMC Sales -# Usage: ./scripts/lego-list-certs.sh - -set -e - -echo "Listing SSL certificates managed by Lego..." - -# Check if lego container is running -if ! docker ps | grep -q "cmc-lego"; then - echo "ERROR: Lego container is not running. Please start it first with 'make proxy'" - exit 1 -fi - -# List all certificates -docker exec cmc-lego lego \ - --path="/data" \ - list - -echo "" -echo "Certificate files in container:" -docker exec cmc-lego find /data/certificates -name "*.crt" -o -name "*.key" | sort \ No newline at end of file diff --git a/scripts/lego-obtain-cert.sh b/scripts/lego-obtain-cert.sh deleted file mode 100755 index 6f936108..00000000 --- a/scripts/lego-obtain-cert.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/bash - -# Lego SSL certificate obtainment script for CMC Sales -# Usage: ./scripts/lego-obtain-cert.sh [domain] [email] - -set -e - -DOMAIN=${1} -EMAIL=${2} - -if [ -z "$DOMAIN" ] || [ -z "$EMAIL" ]; then - echo "Usage: $0 " - echo "Example: $0 cmc.springupsoftware.com admin@springupsoftware.com" - exit 1 -fi - -echo "Obtaining SSL certificate for domain: $DOMAIN" -echo "Email: $EMAIL" - -# Check if lego container is running -if ! docker ps | grep -q "cmc-lego"; then - echo "ERROR: Lego container is not running. Please start it first with 'make proxy'" - exit 1 -fi - -# Run lego to obtain certificate -docker exec cmc-lego lego \ - --email="$EMAIL" \ - --domains="$DOMAIN" \ - --http \ - --http.webroot="/data/acme-challenge" \ - --path="/data" \ - --accept-tos \ - run - -if [ $? -eq 0 ]; then - echo "Certificate obtained successfully for $DOMAIN" - - # Copy certificates to the expected nginx locations - docker exec cmc-lego cp "/data/certificates/$DOMAIN.crt" "/data/certificates/$DOMAIN.crt" - docker exec cmc-lego cp "/data/certificates/$DOMAIN.key" "/data/certificates/$DOMAIN.key" - - # Reload nginx - docker exec cmc-nginx-proxy nginx -s reload - - echo "Nginx reloaded with new certificate" -else - echo "ERROR: Failed to obtain certificate for $DOMAIN" - exit 1 -fi \ No newline at end of file diff --git a/scripts/lego-renew-cert.sh b/scripts/lego-renew-cert.sh deleted file mode 100755 index f319ac52..00000000 --- a/scripts/lego-renew-cert.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/bin/bash - -# Lego SSL certificate renewal script for CMC Sales -# Usage: ./scripts/lego-renew-cert.sh [domain] - -set -e - -DOMAIN=${1} - -if [ -z "$DOMAIN" ]; then - echo "Usage: $0 " - echo "Example: $0 cmc.springupsoftware.com" - echo "" - echo "Or run without domain to renew all certificates:" - echo "$0 all" - exit 1 -fi - -echo "Renewing SSL certificate(s)..." - -# Check if lego container is running -if ! docker ps | grep -q "cmc-lego"; then - echo "ERROR: Lego container is not running. Please start it first with 'make proxy'" - exit 1 -fi - -if [ "$DOMAIN" = "all" ]; then - echo "Renewing all certificates..." - # Renew all certificates - docker exec cmc-lego lego \ - --http \ - --http.webroot="/data/acme-challenge" \ - --path="/data" \ - renew \ - --days=30 -else - echo "Renewing certificate for domain: $DOMAIN" - # Renew specific domain - docker exec cmc-lego lego \ - --domains="$DOMAIN" \ - --http \ - --http.webroot="/data/acme-challenge" \ - --path="/data" \ - renew \ - --days=30 -fi - -if [ $? -eq 0 ]; then - echo "Certificate renewal completed successfully" - - # Reload nginx to use new certificates - docker exec cmc-nginx-proxy nginx -s reload - echo "Nginx reloaded with renewed certificates" - - # Show certificate info - echo "" - echo "Certificate information:" - docker exec cmc-lego lego \ - --path="/data" \ - list -else - echo "ERROR: Certificate renewal failed" - exit 1 -fi \ No newline at end of file diff --git a/scripts/manage-staging-caddy.sh b/scripts/manage-staging-caddy.sh deleted file mode 100755 index 1f355a95..00000000 --- a/scripts/manage-staging-caddy.sh +++ /dev/null @@ -1,194 +0,0 @@ -#!/bin/bash - -# Management script for staging environment with Caddy and containers - -set -e - -COMPOSE_FILE="docker-compose.caddy-staging.yml" - -# Colors for output -RED='\033[0;31m' -GREEN='\033[0;32m' -YELLOW='\033[1;33m' -NC='\033[0m' # No Color - -function show_help { - echo "CMC Sales Staging Management (Caddy + Containers)" - echo "" - echo "Usage: $0 [command]" - echo "" - echo "Commands:" - echo " status Show status of all services" - echo " start Start staging containers" - echo " stop Stop staging containers" - echo " restart Restart staging containers" - echo " logs Show container logs" - echo " caddy-logs Show Caddy logs" - echo " backup Backup staging database" - echo " shell-php Enter PHP container shell" - echo " shell-go Enter Go container shell" - echo " shell-db Enter database shell" - echo " update Pull latest code and rebuild" - echo " clean Stop and remove containers" - echo "" -} - -function check_status { - echo -e "${GREEN}=== Service Status ===${NC}" - echo "" - - # Caddy status - echo -e "${YELLOW}Caddy Status:${NC}" - if systemctl is-active --quiet caddy; then - echo -e " ${GREEN}● Caddy is running${NC}" - echo -n " Config: " - caddy version - else - echo -e " ${RED}● Caddy is not running${NC}" - fi - echo "" - - # Container status - echo -e "${YELLOW}Container Status:${NC}" - docker compose -f $COMPOSE_FILE ps - echo "" - - # Port status - echo -e "${YELLOW}Port Status:${NC}" - sudo netstat -tlnp | grep -E ":(80|443|8091|8092|3307) " | grep LISTEN || echo " No staging ports found" - echo "" - - # Health checks - echo -e "${YELLOW}Health Checks:${NC}" - echo -n " PHP container (8091): " - curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8091 || echo "Failed" - echo -n " Go container (8092): " - curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8092/api/v1/health || echo "Failed" - echo -n " Public HTTPS: " - curl -s -o /dev/null -w "%{http_code}\n" https://staging.cmc.springupsoftware.com/health || echo "Not accessible" -} - -function start_services { - echo -e "${GREEN}Starting staging services...${NC}" - docker compose -f $COMPOSE_FILE up -d - echo "Waiting for services to be ready..." - sleep 10 - check_status -} - -function stop_services { - echo -e "${YELLOW}Stopping staging services...${NC}" - docker compose -f $COMPOSE_FILE stop -} - -function restart_services { - echo -e "${YELLOW}Restarting staging services...${NC}" - docker compose -f $COMPOSE_FILE restart - echo "Waiting for services to be ready..." - sleep 10 - check_status -} - -function show_logs { - echo -e "${GREEN}Showing container logs (Ctrl+C to exit)...${NC}" - docker compose -f $COMPOSE_FILE logs -f -} - -function show_caddy_logs { - echo -e "${GREEN}Showing Caddy logs (Ctrl+C to exit)...${NC}" - sudo journalctl -u caddy -f -} - -function backup_database { - echo -e "${GREEN}Backing up staging database...${NC}" - ./scripts/backup-db.sh staging -} - -function shell_php { - echo -e "${GREEN}Entering PHP container shell...${NC}" - docker exec -it cmc-php-staging /bin/bash -} - -function shell_go { - echo -e "${GREEN}Entering Go container shell...${NC}" - docker exec -it cmc-go-staging /bin/sh -} - -function shell_db { - echo -e "${GREEN}Entering database shell...${NC}" - docker exec -it cmc-db-staging mysql -u cmc_staging -p cmc_staging -} - -function update_deployment { - echo -e "${GREEN}Updating staging deployment...${NC}" - - # Pull latest code - echo "Pulling latest code..." - git pull origin main - - # Rebuild containers - echo "Rebuilding containers..." - docker compose -f $COMPOSE_FILE build --no-cache - - # Restart services - echo "Restarting services..." - docker compose -f $COMPOSE_FILE up -d - - echo "Waiting for services to be ready..." - sleep 10 - check_status -} - -function clean_deployment { - echo -e "${RED}WARNING: This will remove all staging containers and volumes!${NC}" - read -p "Are you sure? (yes/no): " confirm - if [ "$confirm" = "yes" ]; then - docker compose -f $COMPOSE_FILE down -v - echo "Staging environment cleaned" - else - echo "Cancelled" - fi -} - -# Main script logic -case "$1" in - status) - check_status - ;; - start) - start_services - ;; - stop) - stop_services - ;; - restart) - restart_services - ;; - logs) - show_logs - ;; - caddy-logs) - show_caddy_logs - ;; - backup) - backup_database - ;; - shell-php) - shell_php - ;; - shell-go) - shell_go - ;; - shell-db) - shell_db - ;; - update) - update_deployment - ;; - clean) - clean_deployment - ;; - *) - show_help - ;; -esac \ No newline at end of file diff --git a/scripts/quick-rebuild-staging.sh b/scripts/quick-rebuild-staging.sh deleted file mode 100755 index 9bcfaadf..00000000 --- a/scripts/quick-rebuild-staging.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -# Quick rebuild script for staging - -echo "=== Quick Staging Rebuild ===" - -# Stop containers -echo "Stopping containers..." -docker compose -f docker-compose.caddy-staging-ubuntu.yml down - -# Remove old images -echo "Cleaning up..." -docker system prune -f - -# Build and start -echo "Building and starting..." -docker compose -f docker-compose.caddy-staging-ubuntu.yml build --no-cache -docker compose -f docker-compose.caddy-staging-ubuntu.yml up -d - -# Wait for startup -echo "Waiting for containers to start..." -sleep 15 - -# Test -echo "Testing setup..." -./scripts/test-php-setup.sh \ No newline at end of file diff --git a/scripts/restore-db.sh b/scripts/restore-db.sh deleted file mode 100755 index 61fda52d..00000000 --- a/scripts/restore-db.sh +++ /dev/null @@ -1,78 +0,0 @@ -#!/bin/bash - -# Database restore script for CMC Sales -# Usage: ./scripts/restore-db.sh [staging|production] - -set -e - -ENVIRONMENT=${1} -BACKUP_FILE=${2} - -if [ -z "$ENVIRONMENT" ] || [ -z "$BACKUP_FILE" ]; then - echo "Usage: $0 [staging|production] " - echo "Example: $0 staging /var/backups/cmc-sales/backup_staging_20240101-120000.sql.gz" - exit 1 -fi - -if [ ! -f "$BACKUP_FILE" ]; then - echo "ERROR: Backup file not found: $BACKUP_FILE" - exit 1 -fi - -case $ENVIRONMENT in - staging) - CONTAINER="cmc-db-staging" - DB_NAME="cmc_staging" - DB_USER="cmc_staging" - ;; - production) - CONTAINER="cmc-db-production" - DB_NAME="cmc" - DB_USER="cmc" - ;; - *) - echo "ERROR: Invalid environment. Use 'staging' or 'production'" - exit 1 - ;; -esac - -echo "WARNING: This will COMPLETELY REPLACE the $ENVIRONMENT database!" -echo "Container: $CONTAINER" -echo "Database: $DB_NAME" -echo "Backup file: $BACKUP_FILE" -echo "" -read -p "Are you sure you want to continue? (yes/no): " confirm - -if [ "$confirm" != "yes" ]; then - echo "Restore cancelled." - exit 0 -fi - -echo "Creating backup of current database before restore..." -CURRENT_BACKUP="/tmp/pre_restore_backup_${ENVIRONMENT}_$(date +%Y%m%d-%H%M%S).sql.gz" -docker exec -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ - $CONTAINER \ - mysqldump --single-transaction --routines --triggers --user=$DB_USER $DB_NAME | \ - gzip > "$CURRENT_BACKUP" -echo "Current database backed up to: $CURRENT_BACKUP" - -echo "Restoring database from: $BACKUP_FILE" - -# Drop and recreate database -docker exec -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_ROOT_PASSWORD | cut -d= -f2)" \ - $CONTAINER \ - mysql --user=root -e "DROP DATABASE IF EXISTS $DB_NAME; CREATE DATABASE $DB_NAME;" - -# Restore from backup -if [[ "$BACKUP_FILE" == *.gz ]]; then - gunzip < "$BACKUP_FILE" | docker exec -i -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ - $CONTAINER \ - mysql --user=$DB_USER $DB_NAME -else - docker exec -i -e MYSQL_PWD="$(docker exec $CONTAINER printenv | grep MYSQL_PASSWORD | cut -d= -f2)" \ - $CONTAINER \ - mysql --user=$DB_USER $DB_NAME < "$BACKUP_FILE" -fi - -echo "Database restore completed successfully!" -echo "Previous database backed up to: $CURRENT_BACKUP" \ No newline at end of file diff --git a/scripts/setup-caddy-auth.sh b/scripts/setup-caddy-auth.sh deleted file mode 100755 index fa401cb8..00000000 --- a/scripts/setup-caddy-auth.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/bash - -# Setup Caddy basic authentication -# Usage: ./scripts/setup-caddy-auth.sh - -set -e - -echo "Setting up Caddy basic authentication..." -echo "" - -# Get username -read -p "Enter username (default: admin): " username -username=${username:-admin} - -# Get password -read -s -p "Enter password: " password -echo "" -read -s -p "Confirm password: " password_confirm -echo "" - -if [ "$password" != "$password_confirm" ]; then - echo "Passwords do not match!" - exit 1 -fi - -# Generate password hash -echo "" -echo "Generating password hash..." -hash=$(caddy hash-password --plaintext "$password") - -echo "" -echo "Authentication setup complete!" -echo "" -echo "Add this to your Caddyfile basicauth section:" -echo " $username $hash" -echo "" -echo "Example:" -echo " basicauth /* {" -echo " $username $hash" -echo " }" -echo "" -echo "You can add multiple users by adding more lines in the basicauth block." \ No newline at end of file diff --git a/scripts/setup-lego-certs.sh b/scripts/setup-lego-certs.sh deleted file mode 100755 index 022c7c29..00000000 --- a/scripts/setup-lego-certs.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/bash - -# Initial setup script for Lego SSL certificates -# Usage: ./scripts/setup-lego-certs.sh - -set -e - -EMAIL=${1} - -if [ -z "$EMAIL" ]; then - echo "Usage: $0 " - echo "Example: $0 admin@springupsoftware.com" - exit 1 -fi - -echo "Setting up SSL certificates for CMC Sales using Lego" -echo "Email: $EMAIL" - -# Ensure proxy is running -if ! docker ps | grep -q "cmc-lego"; then - echo "Starting proxy services..." - docker compose -f docker-compose.proxy.yml up -d - echo "Waiting for services to be ready..." - sleep 10 -fi - -# Obtain certificate for production domain -echo "" -echo "=== Obtaining certificate for production domain ===" -./scripts/lego-obtain-cert.sh cmc.springupsoftware.com "$EMAIL" - -# Obtain certificate for staging domain -echo "" -echo "=== Obtaining certificate for staging domain ===" -./scripts/lego-obtain-cert.sh staging.cmc.springupsoftware.com "$EMAIL" - -echo "" -echo "=== Certificate setup complete ===" -echo "" -echo "Certificates obtained for:" -echo " - cmc.springupsoftware.com" -echo " - staging.cmc.springupsoftware.com" -echo "" -echo "Testing HTTPS endpoints..." - -# Test the endpoints -sleep 5 -echo "Testing production HTTPS..." -curl -I https://cmc.springupsoftware.com/health || echo "Production endpoint not yet accessible" - -echo "Testing staging HTTPS..." -curl -I https://staging.cmc.springupsoftware.com/health || echo "Staging endpoint not yet accessible" - -echo "" -echo "SSL setup complete! Remember to set up auto-renewal in cron:" -echo "0 2 * * * /opt/cmc-sales/scripts/lego-renew-cert.sh all" \ No newline at end of file diff --git a/scripts/setup-staging-native.sh b/scripts/setup-staging-native.sh deleted file mode 100755 index a744a390..00000000 --- a/scripts/setup-staging-native.sh +++ /dev/null @@ -1,149 +0,0 @@ -#!/bin/bash - -# Setup script for running staging environment natively with Caddy -# This runs PHP and Go applications directly on the host - -set -e - -if [ "$EUID" -ne 0 ]; then - echo "Please run as root (use sudo)" - exit 1 -fi - -echo "Setting up CMC Sales staging environment (native)..." - -# 1. Install dependencies -echo "Installing dependencies..." -apt update -apt install -y \ - php7.4-fpm \ - php7.4-mysql \ - php7.4-gd \ - php7.4-curl \ - php7.4-mbstring \ - php7.4-xml \ - php7.4-zip \ - mariadb-server \ - golang-go \ - git \ - supervisor - -# 2. Create directories -echo "Creating directories..." -mkdir -p /var/www/cmc-sales-staging -mkdir -p /var/log/cmc-staging -mkdir -p /var/run/cmc-staging -mkdir -p /etc/cmc-staging - -# 3. Clone or copy application -echo "Setting up application code..." -if [ -d "/home/cmc/cmc-sales" ]; then - cp -r /home/cmc/cmc-sales/* /var/www/cmc-sales-staging/ -else - echo "Please clone the repository to /home/cmc/cmc-sales first" - exit 1 -fi - -# 4. Setup PHP-FPM pool for staging -echo "Configuring PHP-FPM..." -cat > /etc/php/7.4/fpm/pool.d/staging.conf << 'EOF' -[staging] -user = www-data -group = www-data -listen = /run/php/php7.4-fpm-staging.sock -listen.owner = www-data -listen.group = caddy -listen.mode = 0660 - -pm = dynamic -pm.max_children = 10 -pm.start_servers = 2 -pm.min_spare_servers = 1 -pm.max_spare_servers = 3 -pm.max_requests = 500 - -; Environment variables -env[APP_ENV] = staging -env[DB_HOST] = localhost -env[DB_PORT] = 3307 -env[DB_NAME] = cmc_staging -env[DB_USER] = cmc_staging - -; PHP settings -php_admin_value[error_log] = /var/log/cmc-staging/php-error.log -php_admin_flag[log_errors] = on -php_admin_value[memory_limit] = 256M -php_admin_value[upload_max_filesize] = 50M -php_admin_value[post_max_size] = 50M -EOF - -# 5. Setup MariaDB for staging -echo "Configuring MariaDB..." -mysql -e "CREATE DATABASE IF NOT EXISTS cmc_staging;" -mysql -e "CREATE USER IF NOT EXISTS 'cmc_staging'@'localhost' IDENTIFIED BY '${DB_PASSWORD_STAGING:-staging_password}';" -mysql -e "GRANT ALL PRIVILEGES ON cmc_staging.* TO 'cmc_staging'@'localhost';" -mysql -e "FLUSH PRIVILEGES;" - -# 6. Setup Go application service -echo "Setting up Go application service..." -cat > /etc/systemd/system/cmc-go-staging.service << 'EOF' -[Unit] -Description=CMC Go Application - Staging -After=network.target mariadb.service - -[Service] -Type=simple -User=www-data -Group=www-data -WorkingDirectory=/var/www/cmc-sales-staging/go-app -Environment="PORT=8092" -Environment="APP_ENV=staging" -Environment="DB_HOST=localhost" -Environment="DB_PORT=3306" -Environment="DB_USER=cmc_staging" -Environment="DB_NAME=cmc_staging" -ExecStart=/usr/local/bin/cmc-go-staging -Restart=always -RestartSec=10 - -[Install] -WantedBy=multi-user.target -EOF - -# 7. Build Go application -echo "Building Go application..." -cd /var/www/cmc-sales-staging/go-app -go mod download -go build -o /usr/local/bin/cmc-go-staging cmd/server/main.go - -# 8. Set permissions -echo "Setting permissions..." -chown -R www-data:www-data /var/www/cmc-sales-staging -chmod -R 755 /var/www/cmc-sales-staging -chmod -R 777 /var/www/cmc-sales-staging/app/tmp -chmod -R 777 /var/www/cmc-sales-staging/app/webroot/pdf -chmod -R 777 /var/www/cmc-sales-staging/app/webroot/attachments_files - -# 9. Create Caddy user in www-data group -usermod -a -G www-data caddy - -# 10. Copy Caddyfile -cp /home/cmc/cmc-sales/Caddyfile.staging-native /etc/caddy/Caddyfile - -# 11. Start services -echo "Starting services..." -systemctl restart php7.4-fpm -systemctl enable cmc-go-staging -systemctl start cmc-go-staging -systemctl reload caddy - -echo "" -echo "Staging environment setup complete!" -echo "" -echo "Next steps:" -echo "1. Set database password: export DB_PASSWORD_STAGING='your_password'" -echo "2. Update /etc/caddy/Caddyfile with correct database password" -echo "3. Import database: mysql cmc_staging < backup.sql" -echo "4. Restart services: systemctl restart caddy cmc-go-staging" -echo "" -echo "Access staging at: https://staging.cmc.springupsoftware.com" \ No newline at end of file diff --git a/scripts/test-php-setup.sh b/scripts/test-php-setup.sh deleted file mode 100755 index e744f94a..00000000 --- a/scripts/test-php-setup.sh +++ /dev/null @@ -1,77 +0,0 @@ -#!/bin/bash - -# Test script to verify PHP container setup - -echo "=== Testing PHP Container Setup ===" -echo "" - -# Test 1: Check if containers are running -echo "1. Checking container status..." -docker ps | grep -E "(cmc-php-staging|cmc-go-staging|cmc-db-staging)" || echo "No staging containers running" -echo "" - -# Test 2: Test PHP container response -echo "2. Testing PHP container (port 8091)..." -response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8091/ 2>/dev/null) -if [ "$response" = "200" ]; then - echo "✓ PHP container responding (HTTP $response)" -else - echo "✗ PHP container not responding (HTTP $response)" - echo "Checking PHP container logs..." - docker logs cmc-php-staging --tail 20 -fi -echo "" - -# Test 3: Test Go container response -echo "3. Testing Go container (port 8092)..." -response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8092/api/v1/health 2>/dev/null) -if [ "$response" = "200" ]; then - echo "✓ Go container responding (HTTP $response)" -else - echo "✗ Go container not responding (HTTP $response)" -fi -echo "" - -# Test 4: Check database connection -echo "4. Testing database connection..." -if docker exec cmc-db-staging mysql -u cmc_staging -pcmc_staging -e "SELECT 1;" cmc_staging &>/dev/null; then - echo "✓ Database connection working" -else - echo "✗ Database connection failed" -fi -echo "" - -# Test 5: Test CakePHP specific endpoint -echo "5. Testing CakePHP structure..." -response=$(curl -s http://localhost:8091/test_php.php 2>/dev/null | head -n 5) -if [[ $response == *"PHP"* ]]; then - echo "✓ CakePHP structure accessible" - echo "Sample response: $(echo "$response" | tr '\n' ' ' | cut -c1-100)..." -else - echo "✗ CakePHP structure issue" - # Check if we can at least get a response - curl -v http://localhost:8091/ 2>&1 | head -n 20 -fi -echo "" - -# Test 6: Check file permissions -echo "6. Checking file permissions in container..." -docker exec cmc-php-staging ls -la /var/www/cmc-sales/ | head -n 10 -echo "" - -# Test 7: Check CakePHP core files -echo "7. Checking CakePHP core files..." -if docker exec cmc-php-staging test -f /var/www/cmc-sales/cake/bootstrap.php; then - echo "✓ CakePHP core files present" -else - echo "✗ CakePHP core files missing" - docker exec cmc-php-staging find /var/www/cmc-sales -name "*.php" | head -n 10 -fi -echo "" - -echo "Test complete!" -echo "" -echo "If issues persist:" -echo "- Check logs: docker logs cmc-php-staging" -echo "- Rebuild: make restart-staging" -echo "- Check volumes: docker volume ls | grep staging" \ No newline at end of file From e469e14ae1f341de0d151bf0482d1e82bacc3fa6 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Mon, 18 Aug 2025 21:10:33 +1000 Subject: [PATCH 11/17] Add tailscale auth --- app/config/core.php | 22 ++++++++ app/controllers/app_controller.php | 86 ++++++++++++++++++++++++++++-- 2 files changed, 105 insertions(+), 3 deletions(-) diff --git a/app/config/core.php b/app/config/core.php index 697aed6b..6cd40776 100644 --- a/app/config/core.php +++ b/app/config/core.php @@ -183,6 +183,28 @@ Configure::write('Security.salt', 'uiPxR3MzVXAID5zucbxLdxP4TX33buPoCWZr4JfroGoaE Configure::write('Acl.classname', 'DbAcl'); Configure::write('Acl.database', 'default'); +/** + * Tailscale Authentication Configuration + * + * Enable Tailscale HTTP header authentication support + * When enabled, the system will check for Tailscale authentication headers + * before falling back to HTTP Basic Auth + */ +Configure::write('Tailscale.enabled', true); + +/** + * Auto-create users from Tailscale authentication + * When enabled, users authenticated via Tailscale headers will be + * automatically created if they don't exist in the database + */ +Configure::write('Tailscale.autoCreateUsers', false); + +/** + * Default access level for auto-created Tailscale users + * Options: 'user', 'manager', 'admin' + */ +Configure::write('Tailscale.defaultAccessLevel', 'user'); + diff --git a/app/controllers/app_controller.php b/app/controllers/app_controller.php index abe9925e..b7597452 100755 --- a/app/controllers/app_controller.php +++ b/app/controllers/app_controller.php @@ -10,8 +10,66 @@ class AppController extends Controller { var $helpers = array('Javascript', 'Time', 'Html', 'Form'); function beforeFilter() { - // Find the user that matches the HTTP basic auth user - $user = $this->User->find('first', array('recursive' => 0, 'conditions' => array('User.username'=>$_SERVER["PHP_AUTH_USER"]))); + $user = null; + + // Check if Tailscale authentication is enabled + if (Configure::read('Tailscale.enabled')) { + // Check for Tailscale authentication headers + $tailscaleLogin = isset($_SERVER['HTTP_TAILSCALE_USER_LOGIN']) ? $_SERVER['HTTP_TAILSCALE_USER_LOGIN'] : null; + $tailscaleName = isset($_SERVER['HTTP_TAILSCALE_USER_NAME']) ? $_SERVER['HTTP_TAILSCALE_USER_NAME'] : null; + + if ($tailscaleLogin) { + // Try to find user by email address from Tailscale header + $user = $this->User->find('first', array( + 'recursive' => 0, + 'conditions' => array('User.email' => $tailscaleLogin) + )); + + // If user not found and auto-creation is enabled, create a new user + if (!$user && Configure::read('Tailscale.autoCreateUsers')) { + // Parse the name + $firstName = ''; + $lastName = ''; + if ($tailscaleName) { + $nameParts = explode(' ', $tailscaleName); + $firstName = $nameParts[0]; + if (count($nameParts) > 1) { + array_shift($nameParts); + $lastName = implode(' ', $nameParts); + } + } + + $userData = array( + 'User' => array( + 'email' => $tailscaleLogin, + 'username' => $tailscaleLogin, + 'first_name' => $firstName, + 'last_name' => $lastName, + 'type' => 'user', + 'access_level' => Configure::read('Tailscale.defaultAccessLevel'), + 'enabled' => 1, + 'by_vault' => 0 + ) + ); + $this->User->create(); + if ($this->User->save($userData)) { + $user = $this->User->find('first', array( + 'recursive' => 0, + 'conditions' => array('User.id' => $this->User->id) + )); + } + } + } + } + + // Fall back to HTTP basic auth if no Tailscale auth or user not found + if (!$user && isset($_SERVER["PHP_AUTH_USER"])) { + $user = $this->User->find('first', array( + 'recursive' => 0, + 'conditions' => array('User.username' => $_SERVER["PHP_AUTH_USER"]) + )); + } + $this->set("currentuser", $user); if($this->RequestHandler->isAjax()) { @@ -52,7 +110,29 @@ class AppController extends Controller { * @return array - the currently logged in user. */ function getCurrentUser() { - $user = $this->User->find('first', array('recursive' => 0, 'conditions' => array('User.username'=>$_SERVER["PHP_AUTH_USER"]))); + $user = null; + + // Check if Tailscale authentication is enabled + if (Configure::read('Tailscale.enabled')) { + $tailscaleLogin = isset($_SERVER['HTTP_TAILSCALE_USER_LOGIN']) ? $_SERVER['HTTP_TAILSCALE_USER_LOGIN'] : null; + + if ($tailscaleLogin) { + // Try to find user by email address from Tailscale header + $user = $this->User->find('first', array( + 'recursive' => 0, + 'conditions' => array('User.email' => $tailscaleLogin) + )); + } + } + + // Fall back to HTTP basic auth if no Tailscale auth or user not found + if (!$user && isset($_SERVER["PHP_AUTH_USER"])) { + $user = $this->User->find('first', array( + 'recursive' => 0, + 'conditions' => array('User.username' => $_SERVER["PHP_AUTH_USER"]) + )); + } + return $user; } From 923fdee657060274bb526178acb430c53cee2e5d Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Mon, 18 Aug 2025 21:47:48 +1000 Subject: [PATCH 12/17] Fix php logging to STDERR so Docker logs work --- Dockerfile | 4 ++++ app/controllers/app_controller.php | 13 +++++++++++++ conf/apache-vhost.conf | 8 ++++++++ conf/php.ini | 3 ++- 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 7d61532c..45a235d5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -57,5 +57,9 @@ RUN chmod +x /var/www/cmc-sales/run_vault.sh RUN chmod +x /var/www/cmc-sales/run_update_invoices.sh +# Ensure Apache error/access logs go to Docker stdout/stderr +RUN ln -sf /dev/stdout /var/log/apache2/access.log && \ + ln -sf /dev/stderr /var/log/apache2/error.log + # By default, simply start apache. CMD /usr/sbin/apache2ctl -D FOREGROUND diff --git a/app/controllers/app_controller.php b/app/controllers/app_controller.php index b7597452..3eeb28bc 100755 --- a/app/controllers/app_controller.php +++ b/app/controllers/app_controller.php @@ -19,6 +19,9 @@ class AppController extends Controller { $tailscaleName = isset($_SERVER['HTTP_TAILSCALE_USER_NAME']) ? $_SERVER['HTTP_TAILSCALE_USER_NAME'] : null; if ($tailscaleLogin) { + // Log Tailscale authentication attempt + error_log('[TAILSCALE_AUTH] Attempting authentication for: ' . $tailscaleLogin); + // Try to find user by email address from Tailscale header $user = $this->User->find('first', array( 'recursive' => 0, @@ -57,6 +60,9 @@ class AppController extends Controller { 'recursive' => 0, 'conditions' => array('User.id' => $this->User->id) )); + error_log('[TAILSCALE_AUTH] Created new user: ' . $tailscaleLogin); + } else { + error_log('[TAILSCALE_AUTH] Failed to create user: ' . $tailscaleLogin); } } } @@ -64,12 +70,19 @@ class AppController extends Controller { // Fall back to HTTP basic auth if no Tailscale auth or user not found if (!$user && isset($_SERVER["PHP_AUTH_USER"])) { + error_log('[BASIC_AUTH] Attempting authentication for: ' . $_SERVER["PHP_AUTH_USER"]); $user = $this->User->find('first', array( 'recursive' => 0, 'conditions' => array('User.username' => $_SERVER["PHP_AUTH_USER"]) )); } + if ($user) { + error_log('[AUTH_SUCCESS] User authenticated: ' . $user['User']['email']); + } else { + error_log('[AUTH_FAILED] No valid authentication found'); + } + $this->set("currentuser", $user); if($this->RequestHandler->isAjax()) { diff --git a/conf/apache-vhost.conf b/conf/apache-vhost.conf index 7f74ba40..e1820448 100644 --- a/conf/apache-vhost.conf +++ b/conf/apache-vhost.conf @@ -1,4 +1,12 @@ NameVirtualHost *:80 DocumentRoot /var/www/cmc-sales/app/webroot + +# Send Apache logs to stdout/stderr for Docker +ErrorLog /dev/stderr +CustomLog /dev/stdout combined + +# Ensure PHP errors are also logged +php_flag log_errors on +php_value error_log /dev/stderr diff --git a/conf/php.ini b/conf/php.ini index 15a17b3c..9250d1a4 100644 --- a/conf/php.ini +++ b/conf/php.ini @@ -633,7 +633,8 @@ html_errors = Off ; empty. ; http://php.net/error-log ; Example: -error_log = /var/log/php_errors.log +; For Docker: Send errors to stderr so they appear in docker logs +error_log = /dev/stderr ; Log errors to syslog (Event Log on NT, not valid in Windows 95). ;error_log = syslog From e211f58fc6ffc71ab186226061ef49b0f78155f1 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Mon, 18 Aug 2025 21:55:54 +1000 Subject: [PATCH 13/17] Debugging tailscale auth --- app/controllers/app_controller.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/app/controllers/app_controller.php b/app/controllers/app_controller.php index 3eeb28bc..f3059e20 100755 --- a/app/controllers/app_controller.php +++ b/app/controllers/app_controller.php @@ -14,6 +14,8 @@ class AppController extends Controller { // Check if Tailscale authentication is enabled if (Configure::read('Tailscale.enabled')) { + error_log('[TAILSCALE_AUTH] Checking Tailscale authentication headers'); + error_log($_SERVER); // Check for Tailscale authentication headers $tailscaleLogin = isset($_SERVER['HTTP_TAILSCALE_USER_LOGIN']) ? $_SERVER['HTTP_TAILSCALE_USER_LOGIN'] : null; $tailscaleName = isset($_SERVER['HTTP_TAILSCALE_USER_NAME']) ? $_SERVER['HTTP_TAILSCALE_USER_NAME'] : null; From cfefe25b9a7ceaf2636b874187de0a866bc4cad0 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Tue, 19 Aug 2025 17:42:15 +1000 Subject: [PATCH 14/17] Change Tailscale auth header var name Add deploy-production.sh --- app/controllers/app_controller.php | 56 ++++++-- deploy-production.sh | 203 +++++++++++++++++++++++++++++ 2 files changed, 247 insertions(+), 12 deletions(-) create mode 100755 deploy-production.sh diff --git a/app/controllers/app_controller.php b/app/controllers/app_controller.php index f3059e20..a3cd31c8 100755 --- a/app/controllers/app_controller.php +++ b/app/controllers/app_controller.php @@ -8,23 +8,34 @@ class AppController extends Controller { var $uses = array('User'); var $helpers = array('Javascript', 'Time', 'Html', 'Form'); + + // Define public actions that don't require authentication + var $allowedActions = array(); + function beforeFilter() { + + // Check if current action is allowed without authentication + if (in_array($this->action, $this->allowedActions)) { + error_log('[AUTH_BYPASS] Action ' . $this->action . ' allowed without authentication'); + return; + } $user = null; // Check if Tailscale authentication is enabled if (Configure::read('Tailscale.enabled')) { - error_log('[TAILSCALE_AUTH] Checking Tailscale authentication headers'); - error_log($_SERVER); - // Check for Tailscale authentication headers - $tailscaleLogin = isset($_SERVER['HTTP_TAILSCALE_USER_LOGIN']) ? $_SERVER['HTTP_TAILSCALE_USER_LOGIN'] : null; - $tailscaleName = isset($_SERVER['HTTP_TAILSCALE_USER_NAME']) ? $_SERVER['HTTP_TAILSCALE_USER_NAME'] : null; + error_log('[WEBAUTH] Checking web authentication headers'); + error_log('X-Webauth-User: ' . (isset($_SERVER['HTTP_X_WEBAUTH_USER']) ? $_SERVER['HTTP_X_WEBAUTH_USER'] : 'not set')); + error_log('X-Webauth-Name: ' . (isset($_SERVER['HTTP_X_WEBAUTH_NAME']) ? $_SERVER['HTTP_X_WEBAUTH_NAME'] : 'not set')); + // Check for web authentication headers + $tailscaleLogin = isset($_SERVER['HTTP_X_WEBAUTH_USER']) ? $_SERVER['HTTP_X_WEBAUTH_USER'] : null; + $tailscaleName = isset($_SERVER['HTTP_X_WEBAUTH_NAME']) ? $_SERVER['HTTP_X_WEBAUTH_NAME'] : null; if ($tailscaleLogin) { - // Log Tailscale authentication attempt - error_log('[TAILSCALE_AUTH] Attempting authentication for: ' . $tailscaleLogin); + // Log web authentication attempt + error_log('[WEBAUTH] Attempting authentication for: ' . $tailscaleLogin); - // Try to find user by email address from Tailscale header + // Try to find user by email address from web auth header $user = $this->User->find('first', array( 'recursive' => 0, 'conditions' => array('User.email' => $tailscaleLogin) @@ -62,9 +73,9 @@ class AppController extends Controller { 'recursive' => 0, 'conditions' => array('User.id' => $this->User->id) )); - error_log('[TAILSCALE_AUTH] Created new user: ' . $tailscaleLogin); + error_log('[WEBAUTH] Created new user: ' . $tailscaleLogin); } else { - error_log('[TAILSCALE_AUTH] Failed to create user: ' . $tailscaleLogin); + error_log('[WEBAUTH] Failed to create user: ' . $tailscaleLogin); } } } @@ -83,6 +94,27 @@ class AppController extends Controller { error_log('[AUTH_SUCCESS] User authenticated: ' . $user['User']['email']); } else { error_log('[AUTH_FAILED] No valid authentication found'); + + // Check if we have any authentication attempt (Web Auth or Basic Auth) + $hasAuthAttempt = (Configure::read('Tailscale.enabled') && isset($_SERVER['HTTP_X_WEBAUTH_USER'])) || + isset($_SERVER["PHP_AUTH_USER"]); + + // If there was an authentication attempt but it failed, return 401 + if ($hasAuthAttempt) { + header('HTTP/1.1 401 Unauthorized'); + header('Content-Type: text/plain'); + echo "Authentication failed. Invalid credentials or user not found."; + error_log('[AUTH_FAILED] Returning 401 Unauthorized'); + exit(); + } + + // If no authentication headers at all, request authentication + header('WWW-Authenticate: Basic realm="CMC Sales System"'); + header('HTTP/1.1 401 Unauthorized'); + header('Content-Type: text/plain'); + echo "Authentication required. Please provide valid credentials."; + error_log('[AUTH_FAILED] No authentication headers, requesting authentication'); + exit(); } $this->set("currentuser", $user); @@ -129,10 +161,10 @@ class AppController extends Controller { // Check if Tailscale authentication is enabled if (Configure::read('Tailscale.enabled')) { - $tailscaleLogin = isset($_SERVER['HTTP_TAILSCALE_USER_LOGIN']) ? $_SERVER['HTTP_TAILSCALE_USER_LOGIN'] : null; + $tailscaleLogin = isset($_SERVER['HTTP_X_WEBAUTH_USER']) ? $_SERVER['HTTP_X_WEBAUTH_USER'] : null; if ($tailscaleLogin) { - // Try to find user by email address from Tailscale header + // Try to find user by email address from web auth header $user = $this->User->find('first', array( 'recursive' => 0, 'conditions' => array('User.email' => $tailscaleLogin) diff --git a/deploy-production.sh b/deploy-production.sh new file mode 100755 index 00000000..8908f04c --- /dev/null +++ b/deploy-production.sh @@ -0,0 +1,203 @@ +#!/bin/bash + +# Production Deployment Script for CMC Sales +# This script deploys the application to sales.cmctechnologies.com.au +# Based on .gitlab-ci.yml deployment steps + +set -e # Exit on error + +# Color codes for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' # No Color + +# Configuration +PRODUCTION_HOST="cmc@sales.cmctechnologies.com.au" +PRODUCTION_DIR="/home/cmc/cmc-sales" +CURRENT_BRANCH=$(git branch --show-current) + +echo -e "${GREEN}========================================${NC}" +echo -e "${GREEN}CMC Sales Production Deployment Script${NC}" +echo -e "${GREEN}========================================${NC}" +echo "" + +# Check if we're on master branch +if [ "$CURRENT_BRANCH" != "master" ]; then + echo -e "${YELLOW}Warning: You are not on the master branch.${NC}" + echo -e "${YELLOW}Current branch: $CURRENT_BRANCH${NC}" + read -p "Do you want to continue deployment from $CURRENT_BRANCH? (y/N): " confirm + if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then + echo -e "${RED}Deployment cancelled.${NC}" + exit 1 + fi +fi + +# Check for uncommitted changes +if ! git diff-index --quiet HEAD --; then + echo -e "${YELLOW}Warning: You have uncommitted changes.${NC}" + git status --short + read -p "Do you want to continue? (y/N): " confirm + if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then + echo -e "${RED}Deployment cancelled.${NC}" + exit 1 + fi +fi + +# Get latest commit hash for build arg +COMMIT_HASH=$(git rev-parse --short HEAD) +echo -e "${GREEN}Deploying commit: $COMMIT_HASH${NC}" +echo "" + +# Push latest changes to origin +echo -e "${YELLOW}Step 1: Pushing latest changes to origin...${NC}" +git push origin $CURRENT_BRANCH +if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ Changes pushed successfully${NC}" +else + echo -e "${RED}✗ Failed to push changes${NC}" + exit 1 +fi +echo "" + +# SSH to production and execute deployment +echo -e "${YELLOW}Step 2: Connecting to production server...${NC}" +echo -e "${YELLOW}Executing deployment on $PRODUCTION_HOST${NC}" +echo "" + +ssh -T $PRODUCTION_HOST << 'ENDSSH' +set -e + +# Color codes for remote output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +NC='\033[0m' + +echo -e "${GREEN}Connected to production server${NC}" +echo "" + +# Navigate to project directory +echo -e "${YELLOW}Step 3: Navigating to project directory...${NC}" +cd /home/cmc/cmc-sales +pwd +echo "" + +# Pull latest changes +echo -e "${YELLOW}Step 4: Pulling latest changes from Git...${NC}" +git pull origin master +if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ Git pull successful${NC}" +else + echo -e "${RED}✗ Git pull failed${NC}" + exit 1 +fi +echo "" + +# Get commit hash for build +COMMIT_HASH=$(git rev-parse --short HEAD) +echo -e "${GREEN}Building from commit: $COMMIT_HASH${NC}" + +# Copy userpasswd file +echo -e "${YELLOW}Step 5: Copying userpasswd file...${NC}" +cp /home/cmc/cmc-sales/userpasswd /home/cmc/userpasswd +if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ userpasswd file copied${NC}" +else + echo -e "${RED}✗ Failed to copy userpasswd file${NC}" + exit 1 +fi +echo "" + +# Build Docker image +echo -e "${YELLOW}Step 6: Building Docker image...${NC}" +docker build --build-arg=COMMIT=$COMMIT_HASH . -t "cmc:latest" +if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ Docker image built successfully${NC}" +else + echo -e "${RED}✗ Docker build failed${NC}" + exit 1 +fi +echo "" + +# Stop existing container +echo -e "${YELLOW}Step 7: Stopping existing container...${NC}" +export ID=$(docker ps -q --filter ancestor=cmc:latest) +if [ ! -z "$ID" ]; then + docker kill $ID + echo -e "${GREEN}✓ Existing container stopped${NC}" + sleep 1 +else + echo -e "${YELLOW}No existing container found${NC}" +fi +echo "" + +# Run new container +echo -e "${YELLOW}Step 8: Starting new container...${NC}" +docker run -d --restart always -p 127.0.0.1:8888:80 \ + --mount type=bind,source=/mnt/vault/pdf,target=/var/www/cmc-sales/app/webroot/pdf \ + --mount type=bind,source=/mnt/vault/attachments_files,target=/var/www/cmc-sales/app/webroot/attachments_files \ + --mount type=bind,source=/mnt/vault/emails,target=/var/www/emails \ + --mount type=bind,source=/mnt/vault/vaultmsgs,target=/var/www/vaultmsgs \ + cmc:latest + +if [ $? -eq 0 ]; then + echo -e "${GREEN}✓ New container started successfully${NC}" +else + echo -e "${RED}✗ Failed to start new container${NC}" + exit 1 +fi +echo "" + +# Verify container is running +echo -e "${YELLOW}Step 9: Verifying deployment...${NC}" +sleep 2 +NEW_ID=$(docker ps -q --filter ancestor=cmc:latest) +if [ ! -z "$NEW_ID" ]; then + echo -e "${GREEN}✓ Container is running with ID: $NEW_ID${NC}" + docker ps --filter ancestor=cmc:latest --format "table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}" +else + echo -e "${RED}✗ Container is not running!${NC}" + exit 1 +fi +echo "" + +# Show recent logs +echo -e "${YELLOW}Step 10: Recent container logs:${NC}" +docker logs --tail 20 $NEW_ID +echo "" + +echo -e "${GREEN}========================================${NC}" +echo -e "${GREEN}✓ Deployment completed successfully!${NC}" +echo -e "${GREEN}========================================${NC}" + +ENDSSH + +if [ $? -eq 0 ]; then + echo "" + echo -e "${GREEN}========================================${NC}" + echo -e "${GREEN}✓ Production deployment successful!${NC}" + echo -e "${GREEN}========================================${NC}" + echo "" + echo -e "${GREEN}Application is running at:${NC}" + echo -e "${GREEN} Internal: http://127.0.0.1:8888${NC}" + echo -e "${GREEN} External: https://sales.cmctechnologies.com.au${NC}" + echo "" + echo -e "${YELLOW}To view live logs:${NC}" + echo " ssh $PRODUCTION_HOST 'docker logs -f \$(docker ps -q --filter ancestor=cmc:latest)'" + echo "" + echo -e "${YELLOW}To rollback if needed:${NC}" + echo " ssh $PRODUCTION_HOST 'docker run -d --restart always -p 127.0.0.1:8888:80 [previous-image-id]'" +else + echo "" + echo -e "${RED}========================================${NC}" + echo -e "${RED}✗ Deployment failed!${NC}" + echo -e "${RED}========================================${NC}" + echo "" + echo -e "${YELLOW}To check the status:${NC}" + echo " ssh $PRODUCTION_HOST 'docker ps -a'" + echo "" + echo -e "${YELLOW}To view logs:${NC}" + echo " ssh $PRODUCTION_HOST 'docker logs \$(docker ps -aq | head -1)'" + exit 1 +fi \ No newline at end of file From 37b474992b2ac3d9ab16ad066595d556e719458e Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Mon, 3 Nov 2025 21:30:04 +1100 Subject: [PATCH 15/17] Add colleen userpasswd --- userpasswd | 1 + 1 file changed, 1 insertion(+) diff --git a/userpasswd b/userpasswd index 9ad42166..b67e8298 100644 --- a/userpasswd +++ b/userpasswd @@ -7,3 +7,4 @@ haris:$apr1$7xqS6Oxx$3HeURNx9ceTV4WsaZEx2h1 despina:$apr1$wyWhXD4y$UHG9//5wMwI3bkccyAMgz1 richard:$apr1$3RMqU9gc$6iw/ZrIkSwU96YMqVr0/k. finley:$apr1$M4PiX6K/$k4/S5C.AMXPgpaRAirxKm0 +colleen:$apr1$7s9ifbAH$r1lgY1I23eqj0WminhxiU. From 8e373e677b53d20e1e733c560a3dece30b8313d0 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Mon, 3 Nov 2025 21:33:39 +1100 Subject: [PATCH 16/17] Fix colleen password --- userpasswd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/userpasswd b/userpasswd index b67e8298..55bbc828 100644 --- a/userpasswd +++ b/userpasswd @@ -7,4 +7,4 @@ haris:$apr1$7xqS6Oxx$3HeURNx9ceTV4WsaZEx2h1 despina:$apr1$wyWhXD4y$UHG9//5wMwI3bkccyAMgz1 richard:$apr1$3RMqU9gc$6iw/ZrIkSwU96YMqVr0/k. finley:$apr1$M4PiX6K/$k4/S5C.AMXPgpaRAirxKm0 -colleen:$apr1$7s9ifbAH$r1lgY1I23eqj0WminhxiU. +colleen:$apr1$IGceg/Fv$jNPRSUzEc14kbuJK43lvU. From 2ff54617845181e46750bbe6ff69ec4ed62dc037 Mon Sep 17 00:00:00 2001 From: Karl Cordes Date: Mon, 3 Nov 2025 21:41:34 +1100 Subject: [PATCH 17/17] Fix colleen passwd --- userpasswd | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/userpasswd b/userpasswd index 55bbc828..bd161598 100644 --- a/userpasswd +++ b/userpasswd @@ -7,4 +7,4 @@ haris:$apr1$7xqS6Oxx$3HeURNx9ceTV4WsaZEx2h1 despina:$apr1$wyWhXD4y$UHG9//5wMwI3bkccyAMgz1 richard:$apr1$3RMqU9gc$6iw/ZrIkSwU96YMqVr0/k. finley:$apr1$M4PiX6K/$k4/S5C.AMXPgpaRAirxKm0 -colleen:$apr1$IGceg/Fv$jNPRSUzEc14kbuJK43lvU. +colleen:$apr1$ovbofsZ8$599TtnM7WVv/5eGDZpWYo0