branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>package usecases import ( "path/filepath" "github.com/nugrohosam/gofilestatic/helpers" ) // StoreFile .. func StoreFile(file []byte, filePathRequsted, fileName, typeFile string) string { ext := filepath.Ext(fileName) randomFileName := helpers.MakeNameFile(filePathRequsted, ext) filePath := helpers.SetPath(filePathRequsted, randomFileName) secretImage := helpers.GetSecret(typeFile, ext) encrypted := helpers.Encrypt(filePath, secretImage) if err := helpers.StoreFile(file, filePath); err != nil { panic(err) } fileNameEncrypted := encrypted + ext return fileNameEncrypted } // GetFile .. func GetFile(fileNameEncrypted, typeFile string) (string, error) { ext := filepath.Ext(fileNameEncrypted) secretImage := helpers.GetSecret(typeFile, ext) pathFile := helpers.Decrypt(fileNameEncrypted, secretImage) storageFilePath := helpers.StoragePath(pathFile) return storageFilePath, nil } <file_sep>package helpers import ( validator "github.com/go-playground/validator/v10" ) // TransformValidations ... func TransformValidations(validationErrors validator.ValidationErrors) []map[string]interface{} { fieldsErrors := make([]map[string]interface{}, len(validationErrors)) for index, fieldErr := range validationErrors { fieldsErrors[index] = map[string]interface{}{ "key": fieldErr.Field(), "kind": fieldErr.ActualTag(), } } return fieldsErrors } // NewValidation .. func NewValidation() *validator.Validate { validate := validator.New() return validate } <file_sep># gofilestatic - Pre Requirement : - libreoffice - vips<file_sep>package usecases import ( "fmt" "path/filepath" "github.com/nugrohosam/gofilestatic/helpers" "github.com/nugrohosam/gofilestatic/services/infrastructure" "github.com/spf13/viper" ) // GetImageSpecificQuality .. func GetImageSpecificQuality(fileNameEncrypted, quality string) (string, error) { return get(quality, fileNameEncrypted) } func get(quality, fileNameEncrypted string) (string, error) { prefixCachePath := viper.GetString("quality.image." + quality + ".prefix") var err error for { filePathCache := prefixCachePath + fileNameEncrypted fileFullPathCache := helpers.CachePath(filePathCache) _, err = helpers.GetFileFromCache(filePathCache) if err == nil { return fileFullPathCache, nil } ext := filepath.Ext(fileNameEncrypted) secretImage := helpers.GetSecret("image", ext) pathFile := helpers.Decrypt(fileNameEncrypted, secretImage) fileData := helpers.GetFileDataStorage(pathFile) if helpers.InArray(quality, helpers.IMAGE_QUALITIES) { qualityCompression := viper.GetInt("quality.image." + quality + ".compression") sizePercentage := viper.GetInt("quality.image." + quality + ".size-percentage") fmt.Println(qualityCompression) fmt.Println(sizePercentage) infrastructure.CreateImageFromBlob(uint(qualityCompression), uint(sizePercentage), fileData, fileFullPathCache) } else { return "", err } } } <file_sep>package usecases import ( "path/filepath" "strings" "github.com/nugrohosam/gofilestatic/helpers" "github.com/nugrohosam/gofilestatic/services/infrastructure" ) // GetDocumentInImage .. func GetDocumentInImage(fileNameEncrypted string) (string, error) { return "", nil } // GetDocumentInPdf .. func GetDocumentInPdf(fileNameEncrypted string) (string, error) { extWithDots := filepath.Ext(fileNameEncrypted) ext := strings.ReplaceAll(extWithDots, ".", "") if ext == "pdf" { return GetFile(fileNameEncrypted, "document") } var err error for { filePathCache := strings.ReplaceAll(fileNameEncrypted, extWithDots, "") + ".pdf" fileFullPathCache := helpers.CachePath(filePathCache) _, err = helpers.GetFileFromCache(filePathCache) if err == nil { return fileFullPathCache, nil } ext := filepath.Ext(fileNameEncrypted) secretImage := helpers.GetSecret("document", ext) pathFile := helpers.Decrypt(fileNameEncrypted, secretImage) storageFilePath := helpers.StoragePath(pathFile) folderCache := helpers.CachePath("") err = infrastructure.CovertDocument("pdf", folderCache, storageFilePath) fileName := filepath.Base(pathFile) fileNameNewInPdf := strings.ReplaceAll(fileName, extWithDots, "") + ".pdf" filePathNowInCache := helpers.CachePath(fileNameNewInPdf) helpers.StorageMove(filePathNowInCache, fileFullPathCache) } } <file_sep>module github.com/nugrohosam/gofilestatic go 1.15 require ( github.com/fatih/structs v1.1.0 github.com/fsnotify/fsnotify v1.4.9 // indirect github.com/getsentry/sentry-go v0.9.0 github.com/gin-gonic/gin v1.6.3 github.com/go-errors/errors v1.0.1 github.com/go-playground/validator/v10 v10.4.0 github.com/golang/protobuf v1.4.3 // indirect github.com/google/go-cmp v0.5.4 // indirect github.com/google/uuid v1.1.5 github.com/pkg/errors v0.9.1 // indirect github.com/spf13/viper v1.7.1 github.com/stretchr/testify v1.6.1 // indirect github.com/thedevsaddam/govalidator v1.9.10 golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899 // indirect golang.org/x/sys v0.0.0-20201029080932-201ba4db2418 // indirect golang.org/x/text v0.3.3 // indirect golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect google.golang.org/protobuf v1.25.0 // indirect gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect gopkg.in/gographics/imagick.v3 v3.3.0 gopkg.in/yaml.v2 v2.3.0 // indirect ) <file_sep>.PHONY: build # This Makefile is a simple example that demonstrates usual steps to build a binary that can be run in the same # architecture that was compiled in. The "ldflags" in the build assure that any needed dependency is included in the # binary and no external dependencies are needed to run the service. GOSAMPLEAPI_VERSION=$(shell git describe --always --long --dirty --tags) BIN_NAME=app build: go build -a -ldflags="[pattern=]args list" -o ${BIN_NAME} @echo "You can now use ./${BIN_NAME}"<file_sep>package controllers import ( "io/ioutil" "net/http" "github.com/go-playground/validator/v10" "github.com/nugrohosam/gofilestatic/helpers" requests "github.com/nugrohosam/gofilestatic/services/http/requests/v1" "github.com/nugrohosam/gofilestatic/usecases" "github.com/gin-gonic/gin" ) // ImageHandlerUpload is use func ImageHandlerUpload() gin.HandlerFunc { return func(c *gin.Context) { var imageUpload requests.ImageUpload c.Bind(&imageUpload) validate := helpers.NewValidation() if err := validate.Struct(imageUpload); err != nil { validationErrors := err.(validator.ValidationErrors) fieldsErrors := helpers.TransformValidations(validationErrors) c.JSON(http.StatusBadRequest, helpers.ResponseErrValidation(fieldsErrors)) return } path, err := helpers.SaveFileRequest(imageUpload.File) if err != nil { c.JSON(http.StatusBadRequest, helpers.ResponseErr(err.Error())) return } imageBuff, err := ioutil.ReadFile(path) if err != nil { c.JSON(http.StatusBadRequest, helpers.ResponseErr(err.Error())) return } filePath := usecases.StoreFile(imageBuff, imageUpload.FilePath, imageUpload.File.Filename, "image") c.JSON(200, gin.H{ "status": true, "file_name": filePath, }) } } // ImageHandler is use func ImageHandler() gin.HandlerFunc { return func(c *gin.Context) { file := c.Param("file") quality := c.Param("quality") var filePath string if helpers.InArray(quality, helpers.IMAGE_QUALITIES) { if quality == helpers.IMAGE_ORIGINAL { filePath, _ = usecases.GetFile(file, "image") } else { filePath, _ = usecases.GetImageSpecificQuality(file, quality) } } else { c.Data(http.StatusNotFound, "Not Found", []byte("404 Not Found")) return } c.File(filePath) } } <file_sep>package infrastructure import ( "errors" "fmt" "os/exec" "path/filepath" "github.com/nugrohosam/gofilestatic/helpers" "github.com/spf13/viper" ) // CovertDocument .. func CovertDocument(format, folderPathDestination, filePath string) error { librelistFormatAllowed := viper.GetStringSlice("converter.libre.alowed-format") vipslistFormatAllowed := viper.GetStringSlice("converter.vips.alowed-format") if helpers.InArray(format, vipslistFormatAllowed) { fileName := filepath.Base(filePath) fileDestinationPath := helpers.SetPath(folderPathDestination, fileName) apps := viper.GetString("converter.vips.cmd") command := apps + " " + filePath + " " + fileDestinationPath cmd := exec.Command("bash", "-c", command) output, err := cmd.Output() fmt.Println(string(output)) return err } else if helpers.InArray(format, librelistFormatAllowed) { apps := viper.GetString("converter.libre.cmd") command := apps + " --headless --convert-to " + format + " --outdir " + folderPathDestination + " " + filePath cmd := exec.Command("bash", "-c", command) output, err := cmd.Output() fmt.Println(string(output)) return err } return errors.New("Format not supported") } <file_sep>package http import ( sentrygin "github.com/getsentry/sentry-go/gin" "github.com/gin-gonic/gin" "github.com/nugrohosam/gofilestatic/services/http/controllers" "github.com/nugrohosam/gofilestatic/services/http/exceptions" "github.com/spf13/viper" ) // Routes ... var Routes *gin.Engine // Serve using for listen to specific port func Serve() error { Prepare() port := viper.GetString("app.port") if err := Routes.Run(":" + port); err != nil { return err } return nil } // Prepare ... func Prepare() { Routes = gin.New() isDebug := viper.GetBool("debug") if !isDebug { Routes.Use(exceptions.Recovery500()) } Routes.Use(sentrygin.New(sentrygin.Options{ Repanic: true, })) v1 := Routes.Group("v1") image := v1.Group("image") { image.POST("", controllers.ImageHandlerUpload()) image.GET(":quality/:file", controllers.ImageHandler()) } document := v1.Group("document") { document.GET("in-image/:file", controllers.DocumentHandlerInImage()) document.GET("in-pdf/:file", controllers.DocumentHandlerInPdf()) document.GET("original/:file", controllers.DocumentHandlerGetFile()) document.POST("", controllers.DocumentHandlerUpload()) } } <file_sep>package validations import ( "strconv" "strings" "github.com/spf13/viper" "github.com/thedevsaddam/govalidator" ) // ShouldBeType .. type ShouldBeType struct { Key string Function func(string) govalidator.Options } // ValidateShouldBeString ... var ValidateShouldBeString = ShouldBeType{ Key: "should-be-string", Function: ImageValidation, } // ImageValidation .. func ImageValidation(attribute string) govalidator.Options { allowedFileExt := viper.GetStringSlice("rules.image.allowed-type") maxSize := viper.GetFloat64("rules.image.max") maxSizeInMB := int(1024 * 1024 * maxSize) ext := strings.Join(allowedFileExt, ",") fileAttribute := "file:" + attribute rules := govalidator.MapData{ fileAttribute: []string{("ext:" + ext), ("size:" + strconv.Itoa(maxSizeInMB)), ("mime:" + ext), "required"}, } messages := govalidator.MapData{ fileAttribute: []string{("ext:Only " + ext + " is allowed"), "required:Photo is required"}, } return govalidator.Options{ Rules: rules, // rules map, Messages: messages, } } <file_sep>package controllers import ( "github.com/nugrohosam/gofilestatic/helpers" requests "github.com/nugrohosam/gofilestatic/services/http/requests/v1" "github.com/nugrohosam/gofilestatic/usecases" "github.com/gin-gonic/gin" ) // DocumentHandlerGetFile is use func DocumentHandlerGetFile() gin.HandlerFunc { return func(c *gin.Context) { file := c.Param("file") filePath, _ := usecases.GetFile(file, "document") c.File(filePath) } } // DocumentHandlerUpload is use func DocumentHandlerUpload() gin.HandlerFunc { return func(c *gin.Context) { var documentUpload requests.DocumentUpload err := c.ShouldBind(&documentUpload) if err != nil { panic(err.Error()) } imageBuff, err := helpers.ReadFileRequest(documentUpload.File) filePath := usecases.StoreFile(imageBuff, documentUpload.FilePath, documentUpload.File.Filename, "document") c.JSON(200, gin.H{ "status": true, "file_name": filePath, }) } } // DocumentHandlerInImage is use func DocumentHandlerInImage() gin.HandlerFunc { return func(c *gin.Context) { file := c.Param("file") filePath, _ := usecases.GetDocumentInImage(file) c.File(filePath) } } // DocumentHandlerInPdf is use func DocumentHandlerInPdf() gin.HandlerFunc { return func(c *gin.Context) { file := c.Param("file") filePath, _ := usecases.GetDocumentInPdf(file) c.File(filePath) } } <file_sep>package helpers import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/hex" "fmt" "io" "io/ioutil" mathRand "math/rand" "mime/multipart" "os" "path/filepath" "reflect" "strings" "github.com/google/uuid" "github.com/spf13/viper" ) const modeCopyFile = "755" // MaxDepth .. const MaxDepth = 32 // Encrypt .. func Encrypt(stringToEncrypt string, keyString string) (encryptedString string) { //Since the key is in string, we need to convert decode it to bytes key, err := hex.DecodeString(keyString) if err != nil { panic(err) } plaintext := []byte(stringToEncrypt) //Create a new Cipher Block from the key block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } //Create a new GCM - https://en.wikipedia.org/wiki/Galois/Counter_Mode //https://golang.org/pkg/crypto/cipher/#NewGCM aesGCM, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } //Create a nonce. Nonce should be from GCM nonce := make([]byte, aesGCM.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { panic(err.Error()) } //Encrypt the data using aesGCM.Seal //Since we don't want to save the nonce somewhere else in this case, we add it as a prefix to the encrypted data. The first nonce argument in Seal is the prefix. ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil) return fmt.Sprintf("%x", ciphertext) } // MergeMap ... func MergeMap(dst, src map[string]interface{}) map[string]interface{} { return merge(dst, src, 0) } // merge func merge(dst, src map[string]interface{}, depth int) map[string]interface{} { if depth > MaxDepth { panic("too deep!") } for key, srcVal := range src { if dstVal, ok := dst[key]; ok { srcMap, srcMapOk := mapify(srcVal) dstMap, dstMapOk := mapify(dstVal) if srcMapOk && dstMapOk { srcVal = merge(dstMap, srcMap, depth+1) } } dst[key] = srcVal } return dst } // Decrypt .. func Decrypt(encryptedString string, keyString string) (decryptedString string) { key, _ := hex.DecodeString(keyString) enc, _ := hex.DecodeString(encryptedString) //Create a new Cipher Block from the key block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } //Create a new GCM aesGCM, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } //Get the nonce size nonceSize := aesGCM.NonceSize() //Extract the nonce from the encrypted data nonce, ciphertext := enc[:nonceSize], enc[nonceSize:] //Decrypt the data plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil) if err != nil { panic(err.Error()) } return fmt.Sprintf("%s", plaintext) } // GetFileFromStorage .. func GetFileFromStorage(filePath string) ([]byte, error) { storageUse := viper.GetString("storage.driver") rootPathUse := viper.GetString("storage.root-path") var data []byte var err error switch storageUse { case STORAGE_LOCAL: path := SetPath(rootPathUse, filePath) data, err = ioutil.ReadFile(path) case STORAGE_GOOGLE: case STORAGE_AWS: } return data, err } // DuplicateToCache .. func DuplicateToCache(fileToCopy []byte, filePath string) error { storageUse := viper.GetString("cache.driver") rootPathUse := viper.GetString("cache.root-path") var err error switch storageUse { case STORAGE_LOCAL: path := SetPath(rootPathUse, filePath) err = ioutil.WriteFile(path, fileToCopy, os.ModeTemporary) case STORAGE_GOOGLE: case STORAGE_AWS: } return err } // GetFileFromCache .. func GetFileFromCache(filePath string) ([]byte, error) { storageUse := viper.GetString("cache.driver") rootPathUse := viper.GetString("cache.root-path") var data []byte var err error switch storageUse { case STORAGE_LOCAL: path := SetPath(rootPathUse, filePath) data, err = ioutil.ReadFile(path) case STORAGE_GOOGLE: case STORAGE_AWS: } return data, err } // SetPath .. func SetPath(paths ...string) string { return strings.Join(paths, "/") } // StoragePath .. func StoragePath(filePath string) string { storageUse := viper.GetString("storage.driver") rootPathUse := viper.GetString("storage.root-path") var path string switch storageUse { case STORAGE_LOCAL: path = SetPath(rootPathUse, filePath) case STORAGE_GOOGLE: case STORAGE_AWS: } return path } // CachePath .. func CachePath(filePath string) string { storageUse := viper.GetString("cache.driver") rootPathUse := viper.GetString("cache.root-path") var path string switch storageUse { case STORAGE_LOCAL: path = SetPath(rootPathUse, filePath) case STORAGE_GOOGLE: case STORAGE_AWS: } return path } // StoreFile .. func StoreFile(file []byte, filePath string) error { storageUse := viper.GetString("storage.driver") rootPathUse := viper.GetString("storage.root-path") var err error switch storageUse { case STORAGE_LOCAL: path := SetPath(rootPathUse, filePath) folderOfFile := filepath.Dir(path) FolderCheckAndCreate(folderOfFile) err = ioutil.WriteFile(path, file, 0755) case STORAGE_GOOGLE: case STORAGE_AWS: } return err } // StorageMove .. func StorageMove(oldLocation, newLocation string) error { return os.Rename(oldLocation, newLocation) } // GetSecret .. func GetSecret(typeFile, ext string) string { secretImage := viper.GetString("file-secret." + typeFile + ext) if secretImage == "" { secretImage = viper.GetString("file-secret.other") } return secretImage } // InArray .. func InArray(str string, s []string) bool { for _, value := range s { if fmt.Sprintf("%v", value) == str { return true } } return false } // GetFileDataStorage .. func GetFileDataStorage(filePath string) []byte { storageUse := viper.GetString("storage.driver") rootPathUse := viper.GetString("storage.root-path") switch storageUse { case STORAGE_LOCAL: filePathStorage := SetPath(rootPathUse, filePath) fileData, _ := ioutil.ReadFile(filePathStorage) return fileData case STORAGE_GOOGLE: return nil case STORAGE_AWS: return nil default: return nil } } // RandomString .. func RandomString(n int) string { letterRunes := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]rune, n) for i := range b { b[i] = letterRunes[mathRand.Intn(len(letterRunes))] } return string(b) } // ReadFileRequest .. func ReadFileRequest(file *multipart.FileHeader) ([]byte, error) { src, err := file.Open() if err != nil { return nil, err } defer src.Close() dst := viper.GetString("temp.root-path") + "/" + RandomString(5) os.Mkdir(dst, 0755) filePath := dst + "/" + file.Filename out, err := os.Create(filePath) if err != nil { return nil, err } defer out.Close() _, err = io.Copy(out, src) return ioutil.ReadFile(filePath) } // SaveFileRequest .. func SaveFileRequest(file *multipart.FileHeader) (string, error) { src, err := file.Open() if err != nil { return "", err } defer src.Close() dst := viper.GetString("temp.root-path") + "/" + RandomString(5) os.Mkdir(dst, 0755) filePath := dst + "/" + file.Filename out, err := os.Create(filePath) if err != nil { return "", err } defer out.Close() _, err = io.Copy(out, src) return filePath, nil } // MakeNameFile .. func MakeNameFile(typeFile, ext string) string { secretFile := GetSecret("image", ext) uuidRandomString := uuid.MustParse(secretFile).String() return uuidRandomString + ext } // FolderCheckAndCreate .. func FolderCheckAndCreate(folderPath string) { info, err := os.Stat(folderPath) if !(os.IsExist(err) && info.Mode().IsDir() && info.Mode().IsRegular()) { os.MkdirAll(folderPath, os.ModePerm) } } // ReadMultipartFile .. func ReadMultipartFile(file *multipart.FileHeader) multipart.File { fileOpenned, err := file.Open() if err != nil { return fileOpenned } return fileOpenned } func mapify(i interface{}) (map[string]interface{}, bool) { value := reflect.ValueOf(i) if value.Kind() == reflect.Map { m := map[string]interface{}{} for _, k := range value.MapKeys() { m[k.String()] = value.MapIndex(k).Interface() } return m, true } return map[string]interface{}{}, false } <file_sep>#!/bin/bash echo "Start deploy in repo" rsync -avHP --exclude-from=.gitignore --exclude=.git -e "sshpass -p$DOMAINESIA_SSH_PASSWORD ssh -p$DOMAINESIA_SSH_PORT" ./ $DOMAINESIA_SSH_USER@$DOMAINESIA_SSH_HOST:/home/$DOMAINESIA_SSH_USER/$DOMAINESIA_SSH_FOLDER_PATH echo "Deployed in repo" echo "Start doing restart system" sshpass -p $DOMAINESIA_SSH_PASSWORD ssh -p $DOMAINESIA_SSH_PORT -o StrictHostKeyChecking=no -l $DOMAINESIA_SSH_USER $DOMAINESIA_SSH_HOST "cd /home/${DOMAINESIA_SSH_USER}/${DOMAINESIA_SSH_FOLDER_PATH}; ./deploy/domainesia/restart-app.sh" echo "restarted system"<file_sep>package v1 import "mime/multipart" // ImageUpload .. type ImageUpload struct { FilePath string `json:"filepath" form:"filepath" binding:"required"` File *multipart.FileHeader `json:"file" form:"file" binding:"required"` } <file_sep>package helpers // STORAGE_LOCAL .. const STORAGE_LOCAL = "local" // STORAGE_AWS .. const STORAGE_AWS = "aws" // STORAGE_GOOGLE .. const STORAGE_GOOGLE = "google" // IMAGE_LARGE_QUALITY .. const IMAGE_LARGE_QUALITY = "large" // IMAGE_ORIGINAL .. const IMAGE_ORIGINAL = "IMAGE_ORIGINAL" // IMAGE_VERY_LARGE_QUALITY .. const IMAGE_VERY_LARGE_QUALITY = "very-large" // IMAGE_MEDIUM_QUALITY .. const IMAGE_MEDIUM_QUALITY = "medium" // IMAGE_SMALL_QUALITY .. const IMAGE_SMALL_QUALITY = "small" // IMAGE_VERY_SMALL_QUALITY .. const IMAGE_VERY_SMALL_QUALITY = "very-small" var IMAGE_QUALITIES = []string{STORAGE_LOCAL, STORAGE_AWS, STORAGE_GOOGLE, IMAGE_LARGE_QUALITY, IMAGE_ORIGINAL, IMAGE_VERY_LARGE_QUALITY, IMAGE_MEDIUM_QUALITY, IMAGE_SMALL_QUALITY, IMAGE_VERY_SMALL_QUALITY} <file_sep>package infrastructure import ( "fmt" "io/ioutil" "os" "path/filepath" "github.com/nugrohosam/gofilestatic/helpers" "gopkg.in/gographics/imagick.v3/imagick" ) // CreateImage .. func CreateImage(quality uint, filePath, filePathDestination string) { imagick.Initialize() defer imagick.Terminate() mw := imagick.NewMagickWand() defer mw.Destroy() mw.ReadImage(filePath) mw.SetCompressionQuality(quality) fileDataCompressed := mw.GetImageBlob() folderOfFile := filepath.Dir(filePathDestination) helpers.FolderCheckAndCreate(folderOfFile) ioutil.WriteFile(filePathDestination, fileDataCompressed, 0744) } // CreateImageFromBlob .. func CreateImageFromBlob(quality uint, sizePrecentage uint, file []byte, filePathDestination string) { imagick.Initialize() defer imagick.Terminate() mw := imagick.NewMagickWand() defer mw.Destroy() mw.ReadImageBlob(file) sizedWidthFromPercentage := mw.GetImageWidth() * sizePrecentage / 100 sizedHeightFromPercentage := mw.GetImageHeight() * sizePrecentage / 100 fmt.Println(mw.GetImageWidth(), mw.GetImageHeight()) fmt.Println(sizedWidthFromPercentage, sizedHeightFromPercentage) mw.SetCompressionQuality(quality) mw.SetSize(sizedWidthFromPercentage, sizedHeightFromPercentage) fileDataCompressed := mw.GetImageBlob() folderOfFile := filepath.Dir(filePathDestination) helpers.FolderCheckAndCreate(folderOfFile) ioutil.WriteFile(filePathDestination, fileDataCompressed, 0744) } // ConvertImage .. func ConvertImage(imageType, filePath string) error { fileTmp, err := ioutil.TempFile("", filePath) if err != nil { return err } defer os.Remove(fileTmp.Name()) fileDataCompressed := fileTmp.Name() + "." + imageType _, err = imagick.ConvertImageCommand([]string{"convert", fileTmp.Name(), fileDataCompressed}) return err } <file_sep>package main import ( "bufio" "os" "path/filepath" "strings" httpConn "github.com/nugrohosam/gofilestatic/services/http" "github.com/nugrohosam/gofilestatic/services/infrastructure" "github.com/spf13/viper" ) func main() { loadConfigFile() infrastructure.PrepareSentry() runHTTP := func() { if err := httpConn.Serve(); err != nil { panic(err) } } go runHTTP() reader := bufio.NewReader(os.Stdin) reader.ReadString('\n') } func loadConfigFile() { viper.SetConfigType("yaml") viper.SetConfigName(".env") viper.AddConfigPath("./") if err := viper.ReadInConfig(); err != nil { panic(err) } // Load all files in config folders var files []string configFolderName := "config" root := "./" + configFolderName if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if info.Name() != configFolderName { files = append(files, info.Name()) } return nil }); err != nil { panic(err) } var nameConfig string for _, file := range files { nameConfig = strings.ReplaceAll(file, ".yaml", "") viper.SetConfigName(nameConfig) viper.AddConfigPath(root) if err := viper.MergeInConfig(); err != nil { panic(err) } } }
93e77ac91c439cff62989f979a4c0c6dcba48699
[ "Markdown", "Makefile", "Go", "Go Module", "Shell" ]
18
Go
nugrohosam/gofilestatic
e21422ccfab556c3a90dda2c3015b77c13b42021
af8fe32fcd44fa2e6d378e7f24bbcbf868fa98e1
refs/heads/master
<repo_name>drets/normalises<file_sep>/schema.sql -- psql --username=testuser test CREATE TABLE notes ( id serial primary key, property VARCHAR(20) NOT NULL, value VARCHAR(40) NOT NULL, created timestamp ); <file_sep>/readme.md 1. `createdb test` create db 2. create testuser and give a full power 3. `cat schema.sql | psql --username=testuser test` create table 4. `bower install` 5. `npm install` 6. `npm start` to watch files and build 7. `./node_modules/.bin/pulp run` run server on 8080
97fef72209cd155999bd7abc9957a41348b41eb9
[ "Markdown", "SQL" ]
2
SQL
drets/normalises
a635f30bc9166f1a68feb05d0169be5bcdb5908f
ae68a0e936515774b80039d667a443bf7213f256
refs/heads/main
<repo_name>bazen-teklehaymanot/wpf-net-sample<file_sep>/WpfNetSample/App.xaml.cs using Microsoft.Extensions.DependencyInjection; using System.Windows; namespace WpfNetSample { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { private async void Application_Startup(object sender, StartupEventArgs e) { await ServiceHost.Instance.StartAsync(); var mainWindow = ServiceHost.Instance.Services.GetService<MainWindow>(); mainWindow.Show(); } private async void Application_Exit(object sender, ExitEventArgs e) { using (ServiceHost.Instance) await ServiceHost.Instance.StopAsync(); } } } <file_sep>/WpfNetSample/ServiceHost.cs using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; namespace WpfNetSample { public interface IPersonService { Person GetPerson(); } public class PersonService : IPersonService { public Person GetPerson() => new Person { Name = "Walker", Age = 23 }; } public sealed class ServiceHost { private static readonly Lazy<IHost> _lazy = new Lazy<IHost>(() => CreatHost()); public static IHost Instance { get { return _lazy.Value; } } private static IHost CreatHost() { return new HostBuilder() .ConfigureAppConfiguration((context, configBuilder) => { configBuilder.SetBasePath(context.HostingEnvironment.ContentRootPath); configBuilder.AddJsonFile("appsettings.json", false); }) .ConfigureServices((context, services) => { services.AddTransient<IPersonService, PersonService>(); services.AddSingleton<MainWindow>(); }) .Build(); } } } <file_sep>/README.md # wpf-net-sample
86e4750f8e8cc57c0661615cf3cbeb6d8f40c033
[ "Markdown", "C#" ]
3
C#
bazen-teklehaymanot/wpf-net-sample
cdf5b45ca676b78f9415939fee3a65092c33e350
f2cd210fc128762b66b26310cd3386635304bad9
refs/heads/master
<file_sep>var express = require("express"); var path = __dirname + '/'; var app = express(); var router = express.Router(); var hbs = require("express-handlebars"); var db = require('./js/db'); app.use(express.static(path + 'public')) app.engine('hbs', hbs({ extname: 'hbs', defaultLayout: 'main-layout', layoutsDir: path + 'views/layouts/' })); app.set('views', path + 'views'); app.set('view engine', 'hbs'); ///// /// MISSOO ///// router.get("/",function(req,res){ res.render('index', {layout: false}); }); router.get("/misso",function(req,res){ res.render('misso/sissejuhatus', {layout: 'misso-layout.hbs'}); }); router.get("/misso/sissejuhatus",function(req,res){ res.render('misso/sissejuhatus', {layout: 'misso-layout.hbs'}); }); router.get("/misso/lugu",function(req,res){ res.render('misso/lugu', {layout: 'misso-layout.hbs'}); }); router.get("/misso/pildid",function(req,res){ res.render('misso/pildid', {layout: 'misso-layout.hbs'}); }); router.get("/misso/kaardid",function(req,res){ res.render('misso/kaardid', {layout: 'misso-layout.hbs'}); }); router.get("/misso/isikud", function(req, res, next) { db.getPeople("misso", function(err, people) { if (err) return next(err); res.render('misso/isikud', {layout: 'misso-layout.hbs', people} ); }); }); router.get("/misso/isik/:id_name", function(req, res, next) { db.getPersonById(req.params.id_name, function(err, person) { if (err) return next(err); res.render('misso/isik', {layout: 'misso-layout.hbs', person} ); }); }); router.get('/misso/rjm',function(req,res){ res.render('misso/rjm', {layout: 'misso-layout.hbs'}); }); router.get('/misso/agendid',function(req,res){ res.render('misso/agendid', {layout: 'misso-layout.hbs'}); }); router.get('/misso/malestus',function(req,res){ res.render('misso/malestus', {layout: 'misso-layout.hbs'}); }); router.get('/misso/lingid',function(req,res){ res.render('misso/lingid', {layout: 'misso-layout.hbs'}); }); router.get('/misso/raudvassar',function(req,res){ res.render('misso/raudvassar', {layout: 'misso-layout.hbs'}); }); router.get('/misso/arvo-pilt',function(req,res){ res.render('misso/arvo-pilt', {layout: 'misso-layout.hbs'}); }); ///// /// ROUGE ///// router.get('/rouge',function(req,res){ res.render('rouge/sissejuhatus', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/sissejuhatus',function(req,res){ res.render('rouge/sissejuhatus', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/metsavennad',function(req,res){ res.render('rouge/metsavennad', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/parteilased',function(req,res){ res.render('rouge/parteilased', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/elukaigud_metsaelu_alguseni',function(req,res){ res.render('rouge/elukaigud_metsaelu_alguseni', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/sundmused_uurimistoimikutes',function(req,res){ res.render('rouge/sundmused_uurimistoimikutes', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/elukaigud_metsaelu_lopuni',function(req,res){ res.render('rouge/elukaigud_metsaelu_lopuni', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/julgeoleku_tegutsemine',function(req,res){ res.render('rouge/julgeoleku_tegutsemine', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/propaganda_vs_toimikud',function(req,res){ res.render('rouge/propaganda_vs_toimikud', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/pildid',function(req,res){ res.render('rouge/pildid', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/kaardid',function(req,res){ res.render('rouge/kaardid', {layout: 'rouge-layout.hbs'}); }); router.get("/rouge/isikud", function(req, res, next) { db.getPeople("rouge", function(err, people) { if (err) return next(err); res.render('rouge/isikud', {layout: 'rouge-layout.hbs', people} ); }); }); router.get("/rouge/isik/:id_name", function(req, res, next) { db.getPersonById(req.params.id_name, function(err, person) { if (err) return next(err); res.render('rouge/isik', {layout: 'rouge-layout.hbs', person} ); }); }); router.get('/rouge/lingid',function(req,res){ res.render('rouge/lingid', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/aksel_sprenki_paevik',function(req,res){ res.render('rouge/aksel_sprenki_paevik', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/aksel_sprenki_paevik_umberkirjutis',function(req,res){ res.render('rouge/aksel_sprenki_paevik_umberkirjutis', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/koemetsa_hukkumine',function(req,res){ res.render('rouge/koemetsa_hukkumine', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/toomase_rahatasku',function(req,res){ res.render('rouge/toomase_rahatasku', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/pallo_luule',function(req,res){ res.render('rouge/pallo_luule', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/haanjamaa_monumendid',function(req,res){ res.render('rouge/haanjamaa_monumendid', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/morv_metsateel',function(req,res){ res.render('rouge/morv_metsateel', {layout: 'rouge-layout.hbs'}); }); router.get('/rouge/simo_pihlapuu_ulestahendused',function(req,res){ res.render('rouge/simo_pihlapuu_ulestahendused', {layout: 'rouge-layout.hbs'}); }); ///// /// LINNAMÄE-URVASTE-SANGASTE ///// router.get('/sangaste',function(req,res){ res.render('sangaste/sissejuhatus', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/sissejuhatus',function(req,res){ res.render('sangaste/sissejuhatus', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/olud',function(req,res){ res.render('sangaste/olud', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/elukaigud_enne_1944',function(req,res){ res.render('sangaste/elukaigud_enne_1944', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/elukaigud_1945_1946',function(req,res){ res.render('sangaste/elukaigud_1945_1946', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/elukaigud_1947_1948',function(req,res){ res.render('sangaste/elukaigud_1947_1948', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/elukaigud_1949_1953',function(req,res){ res.render('sangaste/elukaigud_1949_1953', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/elukaigud_1954_1959',function(req,res){ res.render('sangaste/elukaigud_1954_1959', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/rjm',function(req,res){ res.render('sangaste/rjm', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/pildid',function(req,res){ res.render('sangaste/pildid', {layout: 'sangaste-layout.hbs'}); }); router.get('/sangaste/kaardid',function(req,res){ res.render('sangaste/kaardid', {layout: 'sangaste-layout.hbs'}); }); router.get("/sangaste/isikud", function(req, res, next) { db.getPeople("sangaste", function(err, people) { if (err) return next(err); res.render('sangaste/isikud', {layout: 'sangaste-layout.hbs', people} ); }); }); router.get("/sangaste/isik/:id_name", function(req, res, next) { db.getPersonById(req.params.id_name, function(err, person) { if (err) return next(err); res.render('sangaste/isik', {layout: 'sangaste-layout.hbs', person} ); }); }); router.get('/sangaste/lingid',function(req,res){ res.render('sangaste/lingid', {layout: 'sangaste-layout.hbs'}); }); app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!') }) // START WEB SERVER app.use("/",router); app.listen(4000,function(){ console.log("Live at Port 4000"); }); <file_sep>window.addEventListener("hashchange",function(){console.log("Test")});<file_sep># metsavennad.ee Estonian site about forest brothers <EMAIL> <file_sep>window.addEventListener("hashchange", function () { console.log("Test") });<file_sep>var fs = require('fs'); var sqlite3 = require('sqlite3').verbose(); var db = new sqlite3.Database('db/metsavennad.sqlite'); console.info('Creating database.'); fs.readFile('db/people.sql', 'utf8', function (err, data) { if (err) throw err; console.log(data); db.exec(data, function (err) { if (err) throw err; console.info('Done.'); }); }); module.exports = { getPersonById: function (id_name, callback) { db.get("SELECT * FROM people WHERE id_name = $id_name", { $id_name: id_name }, callback ); }, getPeople: function(location, callback) { db.all("SELECT id_name, first_name, last_name FROM people WHERE location = $location", { $location: location }, callback ); } };
e9a9df33021315f67b4eccd5ef38882d07640032
[ "JavaScript", "Markdown" ]
5
JavaScript
madispuk/metsavennad.ee
9b2061fd4a4ec31ee0feb1ea166fc654a6c89015
4a23a6cff43ed15b346794d5d1116f483c69c880
refs/heads/main
<file_sep>#!/bin/python3 """ Two friends Anna and Brian, are deciding how to split the bill at a dinner. Each will only pay for the items they consume. Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct. For example, assume the bill has the following prices: bill = [2, 4, 6]. Anna declines to eat item k = bill[2] which costs 6. If Brian calculates the bill correctly, Anna will pay (2 + 4)/2 = 3. If he includes the cost of bill[2], he will calculate (2 + 4 + 6)/2 = 6. In the second case, he should refund 3 to Anna. Complete the bonAppetit function in the editor below. It should print Bon Appetit if the bill is fairly split. Otherwise, it should print the integer amount of money that Brian owes Anna. bonAppetit has the following parameter(s): bill: an array of integers representing the cost of each item ordered k: an integer representing the zero-based index of the item Anna doesn't eat b: the amount of money that Anna contributed to the bill """ def bonAppetit(bill, k, b): bActual = (sum(bill) - bill[k])/2 if b == bActual: print("Bon Appetit") else: print(int(b - bActual)) if __name__ == '__main__': nk = input().rstrip().split() n = int(nk[0]) k = int(nk[1]) bill = list(map(int, input().rstrip().split())) b = int(input().strip()) bonAppetit(bill, k, b) <file_sep>""" A teacher asks the class to open their books to a page number. A student can either start turning pages from the front of the book or from the back of the book. They always turn pages one at a time. When they open the book, page 1 is always on the right side. When they flip page 1, they see pages 2 and 3. Each page except the last page will always be printed on both sides. The last page may only be printed on the front, given the length of the book. If the book is n pages long, and a student wants to turn to page p, what is the minimum number of pages to turn? They can start at the beginning or the end of the book. Given n and p, find and print the minimum number of pages that must be turned in order to arrive at page p. Complete the pageCount function in the editor below. It should return an integer representing the minimum number of pages to turn. pageCount has the following parameter(s): int n: the number of pages in the book int p: the page number to turn to """ #!/bin/python3 import os def pageCount(n, p): if p == 1 or p == n or (n % 2 != 0 and p == n-1): return 0 else: min_page = 1 a = 2 ini = 1 if n % 2 == 0: end = n else: end = n - 1 while (ini + a) < p < (end - a): ini += a end -= a min_page += 1 return min_page if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) p = int(input()) result = pageCount(n, p) fptr.write(str(result) + '\n') fptr.close() <file_sep>import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) __________) (____) ---.__(___) ''' options = [rock, paper, scissors] user_chose = int(input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\n")) print(options[user_chose]) computer_chose = random.randint(0,2) print(f"\nComputer chose ::\n{options[computer_chose]}") user_win_pair = [(0, 2), (1, 0), (2, 1)] if (user_chose, computer_chose) in user_win_pair: print("You win!") elif user_chose == computer_chose: print("It's a draw...") else: print("You lose!!!") <file_sep># Program to print the substring containing maximum number of vowels and if two substrings # contains equal number of vowels in a string the print the first one. And if the string doesn't # contain any vowels print "Not found!". def findSubstring(s, k): # s = Input string and k = integer/the size of substring vowels = {"a", "e", "i", "o", "u"} var = k countdict = {} if any(i in s for i in vowels) and len(s) >= k: for i in range(len(s)): count = 0 if len(s[i:var]) == k: for j in s[i:var]: if j in vowels: count += 1 countdict[s[i:var]] = count var += 1 else: break maxval = countdict[list(countdict.keys())[0]] item = list(countdict.keys())[0] for j in countdict.keys(): if maxval < countdict[j]: maxval = countdict[j] item = j print(item) else: print("Not found!") if "__main__" == __name__: findSubstring("iiiurreee", 2) <file_sep>#!/bin/python3 """ We define a magic square to be an n x n matrix of distinct positive integers from 1 to n^2 where the sum of any row, column, or diagonal of length n is always equal to the same number: the magic constant. You will be given a 3 x 3 matrix s of integers in the inclusive range [1, 9]. We can convert any digit a to any other digit b in the range [1, 9] at cost of |a - b|. Given s, convert it into a magic square at minimal cost. Print this cost on a new line. Note: The resulting magic square must contain distinct integers in the inclusive range [1, 9]. Complete the formingMagicSquare function in the editor below. It should return an integer representing the minimal total cost of converting the input square to a magic square. formingMagicSquare has the following parameter(s): int s[3][3]: a 3 x 3 array of integers """ # import os # def formingMagicSquare(s): # cost = 0 # return cost # # # if __name__ == '__main__': # fptr = open(os.environ['OUTPUT_PATH'], 'w') # s = [] # for _ in range(3): # s.append(list(map(int, input().rstrip().split()))) # result = formingMagicSquare(s) # fptr.write(str(result) + '\n') # fptr.close() L = [ [5, 3, 4], [1, 5, 8], [6, 4, 2] ] n = 3 i = 0 items_count = [0]*9 for j in range(n): print(L[i][j], end=" ") if j == n-1: i += 1 while i < n: print(L[i][j], end=" "), i += 1 i -= 1 if i == n-1: j -= 1 while j > -1: print(L[i][j], end=" "), j -= 1 j = 0 i -= 1 while i > -1: print(L[i][j], end=" "), i -= 1 <file_sep>import tkinter as tk """ You need three elements : 1. An Entry widget called ent_temperature to enter the Fahrenheit value 2. A Label widget called lbl_result to display the Celsius result 3. A Button widget called btn_convert that reads the value from the Entry widget, converts it from Fahrenheit to Celsius, and sets the text of the Label widget to the result when clicked. """ def fahrenheit_to_celsius(): """Convert the value for Fahrenheit to Celsius and insert the result into lbl_result. """ fahrenheit = ent_temperature.get() celsius = (5/9) * (float(fahrenheit) - 32) lbl_result["text"] = f"{round(celsius, 2)} \N{DEGREE CELSIUS}" # Set-up the window window = tk.Tk() window.title("Temperature Converter") window.resizable(width=False, height=False) # Create the Fahrenheit entry frame with an Entry widget and label in it frm_entry = tk.Frame(master=window) ent_temperature = tk.Entry(master=frm_entry, width=10) lbl_temp = tk.Label(master=frm_entry, text="\N{DEGREE FAHRENHEIT}") """ ent_temperature is where the user will enter the Fahrenheit value. lbl_temp is used to label ent_temperature with the Fahrenheit symbol. frm_entry is a container that groups ent_temperature and lbl_temp together. You want lbl_temp to be placed directly to the right of ent_temperature. You can lay them out in the frm_entry using the .grid() geometry manager with one row and two columns. You’ve set the sticky parameter to "e" for ent_temperature so that it always sticks to the right-most edge of its grid cell. You also set sticky to "w" for lbl_temp to keep it stuck to the left-most edge of its grid cell. This ensures that lbl_temp is always located immediately to the right of ent_temperature. """ ent_temperature.grid(row=0, column=0, sticky="e") lbl_temp.grid(row=0, column=1, sticky="w") # Create the conversion Button and result display Label btn_convert = tk.Button( master=window, text="\N{RIGHTWARDS BLACK ARROW}", command=fahrenheit_to_celsius ) lbl_result = tk.Label(master=window, text="\N{DEGREE CELSIUS}") # Set-up the layout using the .grid() geometry manager frm_entry.grid(row=0, column=0, padx=10) btn_convert.grid(row=0, column=1, pady=10) lbl_result.grid(row=0, column=2, padx=10) # Run the application window.mainloop() # e1 = tk.Entry() # e1.pack() # l1 = tk.Label(text="F") # l1.pack() # b1 = tk.Button(master=conversion_F_to_C(e1), text="Convert") window.mainloop() <file_sep>#!/bin/python3 """ Given a chocolate bar, two children, Lily and Ron, are determining how to share it. Each of the squares has an integer on it. Lily decides to share a contiguous segment of the bar selected such that: The length of the segment matches Ron's birth month, and, The sum of the integers on the squares is equal to his birth day. You must determine how many ways she can divide the chocolate. Consider the chocolate bar as an array of squares, s = [2,2,1,3,2]. She wants to find segments summing to Ron's birth day, d = 4 with a length equalling his birth month, m = 2. In this case, there are two segments meeting her criteria: [2, 2] and [1, 3]. Complete the birthday function in the editor below. It should return an integer denoting the number of ways Lily can divide the chocolate bar. birthday has the following parameter(s): s: an array of integers, the numbers on each of the squares of chocolate d: an integer, Ron's birth day m: an integer, Ron's birth month """ import math import os import random import re import sys def birthday(s, d, m): count = 0 var = m i = 0 while len(s) - i >= m: total = 0 for j in s[i:var]: total += j if total == d: count += 1 i += 1 var += 1 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) s = list(map(int, input().rstrip().split())) dm = input().rstrip().split() d = int(dm[0]) m = int(dm[1]) result = birthday(s, d, m) fptr.write(str(result) + '\n') fptr.close() <file_sep># CONSTANTS G = 6.67*(10**(-11)) E = 8.85*(10**(-12)) # noinspection NonAsciiCharacters π = 3.141592654 ######################################## print("Gravitational Force") m1 = int(input("Enter mass of object 1 (in kg) : ")) m2 = int(input("Enter mass of object 2 (in kg) : ")) r = int(input("Enter distance between their centers : ")) F = G*m1*m2/(r**2) print(f" => {F} kg\u00b2/m\u00b2") print("Electrostatic Force") q1 = int(input("Enter charge of object 1 (in coulomb) : ")) q2 = int(input("Enter charge of object 2 (in coulomb) : ")) r = int(input("Enter distance between their centers : ")) C = 1/(4*π*E) F = C*q1*q2/(r**2) print(f" => {F} C\u00b2/m\u00b2")<file_sep>import tkinter as tk from tkinter.filedialog import askopenfilename, asksaveasfilename """ There are three essential elements in the application : 1. A Button widget called btn_open for opening a file for editing 2. A Button widget called btn_save for saving a file 3. A TextBox widget called txt_edit for creating and editing the text file The three widgets will be arranged so that the two buttons are on the left-hand side of the window, and the text box is on the right-hand side. The whole window should have a minimum height of 800 pixels, and txt_edit should have a minimum width of 800 pixels. The whole layout should be responsive so that if the window is resized, then txt_edit is resized as well. The width of the Frame holding the buttons should not change, however. """ def open_file(): """Open a file for editing.""" # Use the askopenfilename dialog from the tkinter. # filedialog module to display a file open dialog and store the selected file path to filepath. filepath = askopenfilename( filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")] ) # Check to see if the user closes the dialog box or clicks the Cancel button. # If so, then filepath will be None, and the function will return without executing # any of the code to read the file and set the text of txt_edit if not filepath: return txt_edit.delete(1.0, tk.END) # Clears the current contents of txt_edit using .delete(). # Open the selected file with open(filepath, "r") as input_file: text = input_file.read() # .read() its contents before storing the text as a string. txt_edit.insert(tk.END, text) # Assigns the string text to txt_edit using .insert(). # Sets the title of the window so that it contains the path of the open file. window.title(f"Text Editor - {filepath}") def save_file(): """Save the current file as a new file.""" # Use the asksaveasfilename dialog box to get the desired save location from the user. # The selected file path is stored in the filepath variable. filepath = asksaveasfilename( defaultextension="txt", filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")], ) # Check to see if the user closes the dialog box or clicks the Cancel button. # If so, then filepath will be None, and the function will return without # executing any of the code to save the text to a file. if not filepath: return # Creates a new file at the selected file path. with open(filepath, "w") as output_file: # Extracts the text from txt_edit with .get() method and assigns it to the variable text. text = txt_edit.get(1.0, tk.END) output_file.write(text) # Writes text to the output file. # Updates the title of the window so that the new file path is displayed in the window title. window.title(f"Text Editor - {filepath}") window = tk.Tk() window.title("Text Editor(BASIC)") """ To set the minimum sizes for the window and txt_edit, you can set the minsize parameters of the window methods .rowconfigure() and .columnconfigure() to 800. To handle resizing, you can set the weight parameters of these methods to 1. """ # set the row and column configurations. window.rowconfigure(0, minsize=800, weight=1) """ The first argument is 0, which sets the height of the first row to 800 pixels and makes sure that the height of the row grows proportionally to the height of the window. There’s only one row in the application layout, so these settings apply to the entire window. """ window.columnconfigure(1, minsize=800, weight=1) """ Here, you use .columnconfigure() to set the width and weight attributes of the column with index 1 to 800 and 1, Remember, row and column indices are zero-based, so these settings apply only to the second column. By configuring just the second column, the text box will expand and contract naturally when the window is resized, while the column containing the buttons will remain at a fixed width. """ # create the four widgets you’ll need for the text box, the frame, and the open and save buttons. # In order to get both buttons into the same column, you’ll need to create a Frame widget called fr_buttons. txt_edit = tk.Text(window) fr_buttons = tk.Frame(window, relief=tk.RAISED, bd=2) btn_open = tk.Button(fr_buttons, text="Open", command=open_file) btn_save = tk.Button(fr_buttons, text="Save As...", command=save_file) btn_open.grid(row=0, column=0, sticky="ew", padx=5, pady=5) btn_save.grid(row=1, column=0, sticky="ew", padx=5) """ The above two lines of code create a grid with two rows and one column in the fr_buttons frame since both btn_open and btn_save have their master attribute set to fr_buttons. btn_open is put in the first row and btn_save in the second row so that btn_open appears above btn_save in the layout Both btn_open and btn_save have their sticky attributes set to "ew", which forces the buttons to expand horizontally in both directions and fill the entire frame. This makes sure both buttons are the same size. You place 5 pixels of padding around each button by setting the padx and pady parameters to 5. Only btn_open has vertical padding. Since it’s on top, the vertical padding offsets the button down from the top of the window a bit and makes sure that there’s a small gap between it and btn_save. """ fr_buttons.grid(row=0, column=0, sticky="ns") txt_edit.grid(row=0, column=1, sticky="nsew") """ These two lines of code create a grid with one row and two columns for window. You place fr_buttons in the first column and txt_edit in the second column so that fr_buttons appears to the left of txt_edit in the window layout. The sticky parameter for fr_buttons is set to "ns", which forces the whole frame to expand vertically and fill the entire height of its column. txt_edit fills its entire grid cell because you set its sticky parameter to "nsew", which forces it to expand in every direction. """ window.mainloop() <file_sep>#!/bin/python3 """ Marie invented a Time Machine and wants to test it by time-traveling to visit Russia on the Day of the Programmer (the 256th day of the year) during a year in the inclusive range from 1700 to 2700. From 1700 to 1917, Russia's official calendar was the Julian calendar; since 1919 they used the Gregorian calendar system. The transition from the Julian to Gregorian calendar system occurred in 1918, when the next day after January 31st was February 14th. This means that in 1918, February 14th was the 32nd day of the year in Russia. In both calendar systems, February is the only month with a variable amount of days; it has 29 days during a leap year, and 28 days during all other years. In the Julian calendar, leap years are divisible by 4; in the Gregorian calendar, leap years are either of the following: Divisible by 400. Divisible by 4 and not divisible by 100. Given a year, y, find the date of the 256th day of that year according to the official Russian calendar during that year. Then print it in the format dd.mm.yyyy, where dd is the two-digit day, mm is the two-digit month, and yyyy is y. Complete the dayOfProgrammer function in the editor below. It should return a string representing the date of the 256th day of the year given. dayOfProgrammer has the following parameter(s): year: an integer """ import os def dayOfProgrammer(year): if 1700 <= year <= 1917: if year % 4 == 0: return year if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') year = int(input().strip()) result = dayOfProgrammer(year) fptr.write(result + '\n') fptr.close() <file_sep>from random import sample from time import time def test_kana(opt, kana): mac_ch = sample((list(kana)), k=(len(list(kana)))) result_dict = {"correct": 0, "incorrect": 0, "total_time": 0.00, "average_time": 0.00} for i in range(len(mac_ch)): inp = "" if opt == "1" or opt == "4": start_time = time() inp = (input(f"{kana[mac_ch[i]]} -> ")).lower().strip() finish_time = time() - start_time result_dict["total_time"] += finish_time elif opt == "2" or opt == "5": start_time = time() inp = input(f"{mac_ch[i]} -> ") finish_time = time() - start_time result_dict["total_time"] += finish_time if (inp == mac_ch[i] and (opt == "1" or opt == "4")) or ( inp == kana[mac_ch[i]] and (opt == "2" or opt == "5")): result_dict["correct"] += 1 elif (inp != mac_ch[i] and (opt == "1" or opt == "4")) or ( inp != kana[mac_ch[i]] and (opt == "2" or opt == "5")): result_dict["incorrect"] += 1 if len(kana) > 1: result_dict["average_time"] = result_dict["total_time"] / len(kana) elif len(kana) == 1: result_dict["average_time"] = result_dict["total_time"] return result_dict def results(r): print("Your result ::") print(f'Correct answers = {r["correct"]}') print(f'Incorrect answers = {r["incorrect"]}') print(f'Total Time Taken = {r["total_time"]} seconds') print(f'Average Time Taken = {r["average_time"]} seconds') def word_check(word_dict): mac_ch = sample((list(word_dict.keys())), k=(len(word_dict.keys()))) result_dict = {"correct": 0, "incorrect": 0, "total_time": 0.00, "average_time": 0.00} for i in range(len(mac_ch)): print(f"{mac_ch[i]}") start_time = time() inp_rom = (input(f"\tIN RŌMAJI -> ")).lower().strip() inp_eng = (input(f"\tIN ENGLISH -> ")).lower().strip() finish_time = time() - start_time result_dict["total_time"] += finish_time print() if (inp_rom == word_dict[mac_ch[i]]["Rōmaji"]) and (inp_eng in word_dict[mac_ch[i]]["English"]): result_dict["correct"] += 1 elif (inp_rom != word_dict[mac_ch[i]]["Rōmaji"]) or (inp_eng not in word_dict[mac_ch[i]]["English"]): result_dict["incorrect"] += 1 if len(word_dict) > 1: result_dict["average_time"] = result_dict["total_time"] / len(word_dict) elif len(word_dict) == 1: result_dict["average_time"] = result_dict["total_time"] return result_dict class Japanese: def __init__(self): self.hiragana = { "a": "あ ", "i": "い", "u": "う", "e": "え", "o": "お", "ka": "か", "ki": "き", "ku": "く", "ke": "け", "ko": "こ", "sa": "さ", "shi": "し", "su": "す", "se": "せ", "so": "そ", "ta": "た", "chi": "ち", "tsu": "つ", "te": "て", "to": "と", "na": "な", "ni": "に", "nu": "ぬ", "ne": "ね", "no": "の", "ha": "は", "hi": "ひ", "fu": "ふ", "he": "へ", "ho": "ほ", "ma": "ま", "mi": "み", "mu": "む", "me": "め", "mo": "も", "ya": "や", "yu": "ゆ", "yo": "よ", "ra": "ら", "ri": "り", "ru": "る", "re": "れ", "ro": "ろ", "wa": "わ", "wo": "を", "n": "ん", } self.hiragana_example_words = { "あき": {"Rōmaji": "aki", "English": ["autumn", "fall"]}, "あり": {"Rōmaji": "ari", "English": ["ant"]}, "あい": {"Rōmaji": "ai", "English": ["love"]}, "あし": {"Rōmaji": "ashi", "English": ["foot", "leg"]}, "いし": {"Rōmaji": "ishi", "English": ["stone"]}, "いるか": {"Rōmaji": "iruka", "English": ["dolphin"]}, # "いぬ": {"Rōmaji": "inu", "English": ["dog"]}, # "いす": {"Rōmaji": "isu", "English": ["chair"]}, # "うし": {"Rōmaji": "ushi", "English": ["cow"]}, # "うま": {"Rōmaji": "uma", "English": ["horse"]}, # "うさぎ": {"Rōmaji": "usagi", "English": ["rabbit"]}, # "うみ": {"Rōmaji": "umi", "English": ["ocean"]}, # "え": {"Rōmaji": "e", "English": ["picture"]}, # "えび": {"Rōmaji": "ebi", "English": ["shrimp"]}, # "えさ": {"Rōmaji": "esa", "English": ["pet food"]}, # "えいが": {"Rōmaji": "eiga", "English": ["movie"]}, # "おに": {"Rōmaji": "oni", "English": ["demon"]}, # "およぐ": {"Rōmaji": "oyogu", "English": ["to swim"]}, # "おちゃ": {"Rōmaji": "ocha", "English": ["tea"]}, # "おりがみ": {"Rōmaji": "origami", "English": ["origami"]}, # "かい": {"Rōmaji": "kai", "English": ["shell"]}, # "かえる": {"Rōmaji": "kaeru", "English": ["frog"]}, # "かさ": {"Rōmaji": "kasa", "English": ["umbrella"]}, # "がっこう": {"Rōmaji": "gakkō", "English": ["school"]}, # "きのこ": {"Rōmaji": "kinoko", "English": ["mushroom"]}, # "きつね": {"Rōmaji": "kitsune", "English": ["fox"]}, # "ぎんこう": {"Rōmaji": "ginkō", "English": ["bank"]}, # "ぎゅうにゅう": {"Rōmaji": "gyūnyū", "English": ["milk"]}, # "くま": {"Rōmaji": "kuma", "English": ["bear"]}, # "くも": {"Rōmaji": "kumo", "English": ["spider"]}, # "くるま": {"Rōmaji": "kuruma", "English": ["car"]}, # "ぐん": {"Rōmaji": "gun", "English": ["military"]}, # "けん": {"Rōmaji": "ken", "English": ["sword"]}, # "けしごむ": {"Rōmaji": "keshigomu", "English": ["eraser"]}, # "けいさつ": {"Rōmaji": "keisatsu", "English": ["police"]}, # "げいしゃ": {"Rōmaji": "geisha", "English": ["geisha"]}, # "こうえん": {"Rōmaji": "kōen", "English": ["park"]}, # "こい": {"Rōmaji": "koi", "English": ["romantic love"]}, # "ごみ": {"Rōmaji": "gomi", "English": ["garbage", "trash"]}, # "ごきぶり": {"Rōmaji": "gokiburi", "English": ["cockroach"]}, } self.katakana = { "a": "ア", "i": "イ", "u": "ウ", "e": "エ", "o": "オ", "ka": "カ", "ki": "キ", "ku": "ク", "ke": "ケ", "ko": "コ", "sa": "サ", "shi": "シ", "su": "ス", "se": "セ", "so": "ソ", "ta": "タ", "chi": "チ", "tsu": "ツ", "te": "テ", "to": "ト", "na": "ナ", "ni": "ニ", "nu": "ヌ", "ne": "ネ", "no": "ノ", "ha": "ハ", "hi": "ヒ", "fu": "フ", "he": "ヘ", "ho": "ホ", "ma": "マ", "mi": "ミ", "mu": "ム", "me": "メ", "mo": "モ", "ya": "ヤ", "yu": "ユ", "yo": "ヨ", "ra": "ラ", "ri": "リ", "ru": "ル", "re": "レ", "ro": "ロ", "wa": "ワ", "wo": "ヲ", "n": "ン" } self.katakana_example_words = { "あき": {"Rōmaji": "aki", "English": ["autumn", "fall"]}, "あり": {"Rōmaji": "ari", "English": ["ant"]}, "あい": {"Rōmaji": "ai", "English": ["love"]}, "あし": {"Rōmaji": "ashi", "English": ["foot", "leg"]}, "いし": {"Rōmaji": "ishi", "English": ["stone"]}, "いるか": {"Rōmaji": "iruka", "English": ["dolphin"]}, "いぬ": {"Rōmaji": "inu", "English": ["dog"]}, "いす": {"Rōmaji": "isu", "English": ["chair"]}, "うし": {"Rōmaji": "ushi", "English": ["cow"]}, "うま": {"Rōmaji": "uma", "English": ["horse"]}, "うさぎ": {"Rōmaji": "usagi", "English": ["rabbit"]}, "うみ": {"Rōmaji": "umi", "English": ["ocean"]}, "え": {"Rōmaji": "e", "English": ["picture"]}, "えび": {"Rōmaji": "ebi", "English": ["shrimp"]}, "えさ": {"Rōmaji": "esa", "English": ["pet food"]}, "えいが": {"Rōmaji": "eiga", "English": ["movie"]}, "おに": {"Rōmaji": "oni", "English": ["demon"]}, "およぐ": {"Rōmaji": "oyogu", "English": ["to swim"]}, "おちゃ": {"Rōmaji": "ocha", "English": ["tea"]}, "おりがみ": {"Rōmaji": "origami", "English": ["origami"]}, "かい": {"Rōmaji": "kai", "English": ["shell"]}, "かえる": {"Rōmaji": "kaeru", "English": ["frog"]}, "かさ": {"Rōmaji": "kasa", "English": ["umbrella"]}, "がっこう": {"Rōmaji": "gakkō", "English": ["school"]}, "きのこ": {"Rōmaji": "kinoko", "English": ["mushroom"]}, "きつね": {"Rōmaji": "kitsune", "English": ["fox"]}, "ぎんこう": {"Rōmaji": "ginkō", "English": ["bank"]}, "ぎゅうにゅう": {"Rōmaji": "gyūnyū", "English": ["milk"]}, "くま": {"Rōmaji": "kuma", "English": ["bear"]}, "くも": {"Rōmaji": "kumo", "English": ["spider"]}, "くるま": {"Rōmaji": "kuruma", "English": ["car"]}, "ぐん": {"Rōmaji": "gun", "English": ["military"]}, "けん": {"Rōmaji": "ken", "English": ["sword"]}, "けしごむ": {"Rōmaji": "keshigomu", "English": ["eraser"]}, "けいさつ": {"Rōmaji": "keisatsu", "English": ["police"]}, "げいしゃ": {"Rōmaji": "geisha", "English": ["geisha"]}, "こうえん": {"Rōmaji": "kōen", "English": ["park"]}, "こい": {"Rōmaji": "koi", "English": ["romantic love"]}, "ごみ": {"Rōmaji": "gomi", "English": ["garbage", "trash"]}, "ごきぶり": {"Rōmaji": "gokiburi", "English": ["cockroach"]}, } def menu(self): while True: print() print("_" * 101) print("Choose any one of the following options ::") print("1-> Test_1 : Rōmaji for Hiragana\n2-> Test_2 : Hiragana for Rōmaji" "\n3-> Test_3 : Hiragana words\n4-> Test_4 : Rōmaji for Katakana" "\n5-> Test_5 : Katakana for Rōmaji\n6-> Test_6 : Katakana words" "\n7-> Exit") opt = input(">>> ") if opt == "1": results(test_kana("1", self.hiragana)) elif opt == "2": results(test_kana("2", self.hiragana)) elif opt == "3": results(word_check(self.hiragana_example_words)) elif opt == "4": results(test_kana("4", self.katakana)) elif opt == "5": results(test_kana("5", self.katakana)) elif opt == "6": results(word_check(self.katakana_example_words)) elif opt == "7": print("Thank you for playing!!!\nSEE YOU SOON......") exit(0) else: print("Please enter a valid option!!!") self.menu() if __name__ == "__main__": obj = Japanese() obj.menu() <file_sep>#!/bin/python3 """ Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first, assuming the mouse does not move and the cats travel at equal speed. If the cats arrive at the same time, the mouse will be allowed to move and it will escape while they fight. You are given q queries in the form of x, y and z representing the respective positions for cats A and B, and for mouse C. Complete the function catAndMouse to return the appropriate answer to each query, which will be printed on a new line. If cat A catches the mouse first, print Cat A. If cat B catches the mouse first, print Cat B. If both cats reach the mouse at the same time, print Mouse C as the two cats fight and mouse escapes. Complete the catAndMouse function in the editor below. It should return a string representing either 'Cat A', 'Cat B', or 'Mouse C'. catAndMouse has the following parameter(s): int x: Cat A's position int y: Cat B's position int z: Mouse C's position """ import os def catAndMouse(x, y, z): if abs(x - z) < abs(y - z): return "Cat A" elif abs(x - z) > abs(y - z): return "Cat B" else: return "Mouse C" if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input()) for q_itr in range(q): xyz = input().split() x = int(xyz[0]) y = int(xyz[1]) z = int(xyz[2]) result = catAndMouse(x, y, z) fptr.write(result + '\n') fptr.close() <file_sep>""" Sammy runs a famous burger shop where he prepares one burger at a time since it has a secret ingredient. In a normal shop the customers are served by first come first serve policy. Sammy thought though this is fair to customer but he wanted to maximize his profits so he devised an alternative mechanism. There were hundreds of burger in his catalog, all of which took different amount of time to cook because of different cooking style. He wanted to reduce the time which a customer spends waiting on an average. So, if he has some pool of orders at any point of time then he can choose any order to serve provided he meets his goal of reducing the amount of time customer is waiting. The waiting time starts as soon as customer places an order and the time at which he receives his order. Since the customer uses in store app to place the order hence two customers can also place the order at the same time. Let's say we have three customers who come at time t=0, t=1, & t=2 respectively, and the time needed to cook their burgers is 3, 9 and 6 respectively. If Sammy applies first-come, first-served rule, then the waiting time of three customers is 3, 11, & 16 respectively. The average waiting time in this case is (3 + 11 + 16) / 3 = 10. This is not an optimized solution. After serving the first customer at time t=4, Sammy can choose to serve the third customer. In that case, the waiting time will be 3, 7, & 17 respectively. Hence the average waiting time is (3 + 7 + 17) / 3 = 9. Input Format : The first line contains an integer N, which is the number of customers. In the next N lines, the ith line contains two space separated numbers Ti and Li. Ti is the time when ith customer order a burger, and Li is the time required to cook that burger. The ith customer is not the customer arriving at the arrival time. The order of entry can be in any order i.e. entry of t5 can be before t1. Constraints : 1 ≤ N ≤ 10^5 0 ≤ Ti ≤ 10^9 1 ≤ Li ≤ 10^9 """<file_sep>""" You have been asked to help study the population of birds migrating across the continent. Each type of bird you are interested in will be identified by an integer value. Each time a particular kind of bird is spotted, its id number will be added to your array of sightings. You would like to be able to find out which type of bird is most common given a list of sightings. Your task is to print the type number of that bird and if two or more types of birds are equally common, choose the type with the smallest ID number. Complete the migratoryBirds function in the editor below. It should return the lowest type number of the most frequently sighted bird. migratoryBirds has the following parameter(s): arr: an array of integers representing types of birds sighted """ #!/bin/python3 import math import os import random import re import sys def migratoryBirds(arr): bird_sightings_count = {"1": 0, "2": 0, "3": 0, "4": 0, "5": 0} for i in arr: bird_sightings_count[str(i)] += 1 max_value = bird_sightings_count["1"] max_type = "1" for i in bird_sightings_count.keys(): if max_value < bird_sightings_count[i]: max_value = bird_sightings_count[i] max_type = i return max_type if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') arr_count = int(input().strip()) arr = list(map(int, input().rstrip().split())) result = migratoryBirds(arr) fptr.write(str(result) + '\n') fptr.close() <file_sep>from time import time from random import randint def menu(): print("Choose any one of the following options ::") print("1.> 1 Question\n2.> 5 Question Series\n3.> 10 Question Series\n4.> Exit") opt = input(">>> ") if opt == "1": return 1 elif opt == "2": return 5 elif opt == "3": return 10 elif opt == "4": print("Thank you for playing!!!\nSEE YOU SOON......") exit(0) else: print("Please enter a valid option!!!") menu() def table_start(n): result_dict = {"correct": 0, "incorrect": 0, "total_time": 0.00, "average_time": 0.00} for i in range(n): a = randint(2, 9) b = randint(1, 11) start_time = time() ans1 = int(input(f"{a} X {b} = ")) finish_time = time() - start_time result_dict["total_time"] += finish_time if a * b == ans1: result_dict["correct"] += 1 else: result_dict["incorrect"] += 1 if n > 1: result_dict["average_time"] = result_dict["total_time"]/n elif n == 1: result_dict["average_time"] = result_dict["total_time"] return result_dict def results(r): print("Your result ::") print(f'Correct answers = {r["correct"]}') print(f'Incorrect answers = {r["incorrect"]}') print(f'Total Time Taken = {r["total_time"]} seconds') print(f'Average Time Taken = {r["average_time"]} seconds') def table_tester(): result = table_start(menu()) results(result) if __name__ == "__main__": table_tester() <file_sep>#!/bin/python3 """ You are given an array of n integers, ar = [ar[0], ar[1],...., ar[n - 1]], and a positive integer, k. Find and print the number of (i, j) pairs where i < j and ar[i] + ar[j] is divisible by k. Complete the divisibleSumPairs function in the editor below. It should return the integer count of pairs meeting the criteria. divisibleSumPairs has the following parameter(s): n: the integer length of array ar ar: an array of integers k: the integer to divide the pair sum by """ import os def divisibleSumPairs(n, k, ar): pair_count = 0 i = 0 while n - i >= 2: for j in range(i+1, n): if (ar[i] + ar[j]) % k == 0: pair_count += 1 i += 1 return pair_count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nk = input().split() n = int(nk[0]) k = int(nk[1]) ar = list(map(int, input().rstrip().split())) result = divisibleSumPairs(n, k, ar) fptr.write(str(result) + '\n') fptr.close() <file_sep># Py_Programs_1 Only For Persional Use. <file_sep>import tkinter as tk window = tk.Tk() # A window is an instance of Tkinter’s Tk class. greeting = tk.Label(text="Hello, Tkinter") # Use the tk.Label class to add some text to a window # The window you created earlier doesn’t change. # You just created a Label widget, but you haven’t added it to the window yet. # There are several ways to add widgets to a window. # Right now, you can use the Label widget’s .pack() method greeting.pack() """ Label widgets are used to display text or images. The text displayed by a Label widget can’t be edited by the user. It’s for display purposes only. Label widgets display text with the default system text color and the default system text background color. These are typically black and white, respectively, but you may see different colors if you have changed these settings in your operating system. """ label = tk.Label( text="<NAME>", # foreground="white", # Set the text color to white background="#34A2FE", # Set the background color to black width=20, height=20 ) label.pack() """ It may seem strange that the label in the window isn’t square even though the width and height are both set to 10. This is because the width and height are measured in text units. One horizontal text unit is determined by the width of the character "0", or the number zero, in the default system font. Similarly, one vertical text unit is determined by the height of the character "0" """ window.mainloop() # window.mainloop() tells Python to run the Tkinter event loop. # This method listens for events, such as button clicks or keypresses, and # blocks any code that comes after it from running until the window it’s called on is closed. <file_sep>#!/bin/python3 """ Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates the number of times she breaks her season record for most points and least points in a game. Points scored in the first game establish her record for the season, and she begins counting from there. Complete the breakingRecords function in the editor below. It must return an integer array containing the numbers of times she broke her records. Index 0 is for breaking most points records, and index 1 is for breaking least points records. breakingRecords has the following parameter(s): scores: an array of integers """ import os def breakingRecords(scores): season_result_count = [0, 0] # 0 = breaking most points records # 1 = breaking least points records min_point = max_point = scores[0] for i in scores: if i > max_point: season_result_count[0] += 1 max_point = i elif i < min_point: season_result_count[1] += 1 min_point = i return season_result_count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) scores = list(map(int, input().rstrip().split())) result = breakingRecords(scores) fptr.write(' '.join(map(str, result))) fptr.write('\n') fptr.close()
d443ee6e756cfec0f3e47e0f178abed9a9a9e201
[ "Markdown", "Python" ]
19
Python
Hacker-BlackHATS/Py_Programs_1
4a5116a19e26ccea2eeca977189376f0e1747c27
5e7ee2d028d3cc1ae8b3c59563eaf5cef4d85f25
refs/heads/master
<file_sep>import { Badge, Divider } from 'material-ui' import SearchIcon from 'material-ui/svg-icons/action/search' import PropTypes from 'prop-types' import React, { Component } from 'react' import _ from 'underscore' import * as BooksApi from '../../BooksAPI' import '../../css/Fonts.css' import ResultItem from '../item/ResultItem' const style = { input: { width: '80%', padding: '15px', margin: '30px 10%', display: 'inline-block', border: '2px solid #ccc', borderRadius: '5px', boxSizing: 'border-box', fontSize: '20px', fontFamily: '\'Gloria Hallelujah\', cursive', outline: 'none' }, h3Style: { fontFamily: '\'Gloria Hallelujah\', cursive', fontSize: 'xx-large', marginLeft: '10px' }, badge: { fontSize: 'large', top: 40, backgroundColor: '#f0f7fc', fontFamily: '\'Gloria Hallelujah\', cursive' }, emptyResult: { left: '50%', textAlign: 'center', fontFamily: '\'Gloria Hallelujah\', cursive', fontSize: '20px', span: { display: 'inline-block', marginRight: '10px' } }, ul: { listStyleType: 'none' }, divider: { backgroundColor: '#1d1508' } } class SearchPage extends Component { static propTypes = { updateShelf: PropTypes.func.isRequired, updateBook: PropTypes.func.isRequired } state = { query: '', searchResult: [], isLoading: false, isEmpty: false } removeWhiteSpaces = (str) => { return str.replace(/ {2}/g, ' ').trim() } handleInputChange = (e) => { const {value} = e.target this.setState({query: value}) this.populateResults(value) } populateResults = _.debounce(query => { const queryCleaned = this.removeWhiteSpaces(query) if (queryCleaned === '') { this.setState({searchResult: [], isEmpty: false, isLoading: false}) return } this.setState({isLoading: true}) BooksApi.search(queryCleaned) .then(response => { if (queryCleaned !== this.removeWhiteSpaces(this.state.query)) return const emptyResponse = !!response.error const searchResult = emptyResponse ? [] : response searchResult.forEach(book => { let shelf = this.props.updateShelf(book) book.shelf = shelf ? shelf : '' }) this.setState({searchResult: searchResult, isEmpty: emptyResponse, isLoading: false}) }) }, 600) render () { const {query, searchResult, isLoading, isEmpty} = this.state const ownedBooks = searchResult.filter(book => book.shelf !== '') const newBooks = searchResult.filter(book => book.shelf === '') return ( <div> <input type='text' placeholder='Search books by title' value={query} onChange={this.handleInputChange} style={style.input} /> {isLoading && <div className='spinner'/> } {isEmpty && !isLoading && <div style={style.emptyResult}> <p>No results found!</p> <div> <span style={style.emptyResult.span}>Trying searching something else!</span> <SearchIcon color="#1d1508"/> </div> </div> } {!isLoading && !isEmpty && <div> {ownedBooks.length > 0 && <div> <Badge primary={true} badgeContent={ownedBooks.length} badgeStyle={style.badge} > <h3 style={style.h3Style}>Already Owned</h3> </Badge> <ul style={style.ul}> {ownedBooks.map(book => ( <li key={book.id}> <ResultItem book={book} updateBook={this.props.updateBook}/> </li> ))} </ul> <Divider inset={true} style={style.divider}/> </div> } {newBooks.length > 0 && <div> <Badge primary={true} badgeContent={newBooks.length} badgeStyle={style.badge} > <h3 style={style.h3Style}>Newly Fetched</h3> </Badge> <ul style={style.ul}> {newBooks.map(book => ( <li key={book.id}> <ResultItem book={book} updateBook={this.props.updateBook} /> </li> ))} </ul> </div> } </div> } </div> ) } } export default SearchPage<file_sep>import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme' import getMuiTheme from 'material-ui/styles/getMuiTheme' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import React from 'react' import ReactDOM from 'react-dom' import { BrowserRouter } from 'react-router-dom' import App from './App' import './css/index.css' import './css/hover-min.css' ReactDOM.render( <MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}> <BrowserRouter> <App/> </BrowserRouter> </MuiThemeProvider>, document.getElementById('root') ) <file_sep>import Badge from 'material-ui/Badge' import PropTypes from 'prop-types' import React, { Component } from 'react' import '../../css/Fonts.css' import Book from '../book/Book' const style = { title: { marginBottom: '20px' }, h3Style: { fontFamily: '\'Gloria Hallelujah\', cursive', fontSize: 'x-large', marginLeft: '10px', }, books: { marginLeft: '45px', }, badge: { fontSize: 'large', top: 40, backgroundColor: '#f0f7fc', fontFamily: '\'Gloria Hallelujah\', cursive' } } class Shelf extends Component { static propTypes = { title: PropTypes.string.isRequired, books: PropTypes.array.isRequired, updateBook: PropTypes.func.isRequired } render () { const {title, books, updateBook} = this.props books.sort((thisObj, thatObj) => { if (thisObj.title > thatObj.title) { return 1 } if (thisObj.title < thatObj.title) { return -1 } return 0 }) return ( <div> <div style={style.title}> <Badge primary={true} badgeContent={books.length} badgeStyle={style.badge} > <h3 style={style.h3Style}>{title}</h3> </Badge> </div> <div style={style.books}> {books.map(book => ( <Book key={book.id} data={book} updateBook={updateBook} /> ))} </div> </div> ) } } export default Shelf<file_sep>import { IconButton } from 'material-ui' import ArrowBack from 'material-ui/svg-icons/navigation/arrow-back' import React, { Component } from 'react' import { Link } from 'react-router-dom' import * as BooksApi from '../../BooksAPI' import InfoTemplate from '../infoTemplate/InfoTemplate' const style = { error: { textAlign: 'center', fontFamily: '\'Gamja Flower\', cursive', color: '#1d1202', position: 'relative', top: '20%' } } class BookInfo extends Component { state = { book: {}, isLoading: false, error: false } componentDidMount () { const bookId = this.props.match.params.id this.setState({isLoading: true}) BooksApi.get(bookId) .then(book => { this.setState({book: book, isLoading: false, error: false}) }) .catch(() => { this.setState({book: {}, isLoading: false, error: true}) }) } render () { const {book, isLoading, error} = this.state let content if (error) { content = ( <div style={style.error}> <h1>So terribly sorry. </h1> <h2>Book not found! <i className="em-svg em-cry"/></h2> <Link to="/"> <IconButton className='hvr-backward' tooltip="Go back home"> <ArrowBack color="#1d1202"/> </IconButton> </Link> </div> ) } else if (isLoading) { content = <div style={{marginTop: '100px'}} className='spinner'/> } else { content = <InfoTemplate book={book}/> } return content } } export default BookInfo<file_sep>import Divider from 'material-ui/Divider' import React, { Component } from 'react' import { Route } from 'react-router-dom' import * as BooksApi from './BooksAPI' import BookInfo from './components/bookInfo/BookInfo' import Header from './components/header/Header' import SearchPage from './components/searchPage/SearchPage' import Shelf from './components/shelf/Shelf' const shelves = [ { title: 'Currently Reading', id: 'currentlyReading' }, { title: 'Want to Read', id: 'wantToRead' }, { title: 'Read', id: 'read' } ] class App extends Component { state = { books: [] } componentDidMount () { BooksApi.getAll().then(books => { this.setState({books: books}) }) } updateBook = (book, shelf) => { book.shelf = shelf BooksApi.update(book, shelf).then(() => { this.setState(prevState => ({ books: prevState.books.filter(prevBook => prevBook.id !== book.id).concat([book]) }) ) }) } updateShelf = (book) => { const found = this.state.books.find(myBook => myBook.id === book.id) return found ? found.shelf : null } render () { const {books} = this.state return ( <div className="app"> <Header/> <Route exact path="/" render={() => ( <div> {shelves.map(shelf => ( <div key={shelf.id}> <Shelf title={shelf.title} books={books.filter(book => book.shelf === `${shelf.id}`)} updateBook={this.updateBook} /> <Divider inset={true} style={{backgroundColor: '#1d1508'}}/> </div> ))} </div> )}> </Route> <Route path="/search" render={() => ( <SearchPage updateShelf={this.updateShelf} updateBook={this.updateBook}/> )}/> <Route path="/book/:id" component={BookInfo}/> </div> ) } } export default App
7676617c9c2e87731ccff0af5b92a98b3c4bf19f
[ "JavaScript" ]
5
JavaScript
PedroNigrisVasconcellos/react-my-reads
94f97b2de9f4d88cf9f21583d9de02815c644a7e
df9d5948192d3aa9d8e9fdce8156043f93f10e0c
refs/heads/master
<repo_name>peterldowns/peterdowns.com<file_sep>/projects/emotionet/src/utils.js // Saving node positions var Dump = function() {}; Dump.prototype.print = function() { console.log('var saved =', JSON.stringify(this)); }; var Save = function(s) { var saved = new Dump(); saved.camera = { x: s.camera.x, y: s.camera.y, ratio: s.camera.ratio, }; saved.nodes = {} s.graph.nodes().forEach(function(node) { saved.nodes[node.id] = { x: node.x, y: node.y, size: node.size, }; }); return saved; }; var Load = function(s, dump) { s.camera.x = dump.camera.x; s.camera.y = dump.camera.y; s.camera.ratio = dump.camera.ratio; s.graph.nodes().forEach(function(node) { var old = dump.nodes[node.id]; node.x = old.x; node.y = old.y; node.size = old.size; node['read_cam0:size'] = old['read_cam0:size']; node['read_cam0:x'] = old['read_cam0:x']; node['read_cam0:y'] = old['read_cam0:y']; }); } // Small zooms var zout = function(s, x) { s.camera.ratio += (x || 0.05); s.refresh(); } var zin = function(s, x) { s.camera.ratio -= (x || 0.05); s.refresh(); } <file_sep>/projects/emotionet/src/walker.js var anim_length = 0; var disp_length = 16 * 1000; var pause = 2 * 1000; var hl_len = 4 * 1000; var DISPLAY = document.getElementById('display'); var IMG = display.children[0].children[0]; DISPLAY.show = function(node, callback) { CONTAINER.className = 'off'; setTimeout(function() { //DISPLAY.style = 'background-image: url(' + largeURL(node.id) + ')'; IMG.src = largeURL(node.id); DISPLAY.className = 'on'; setTimeout(callback || function() {}, anim_length); }, anim_length); }; DISPLAY.hide = function(callback) { DISPLAY.className = 'off'; setTimeout(function() { CONTAINER.className = 'on'; IMG.src = null; setTimeout((callback || function() {}), anim_length); }, anim_length); }; function highlight(s, node, cb) { HL_PREV = HL_NEXT; HL_EDGE = null; s.refresh(); setTimeout(cb || function() {}, hl_len); } function showNode(s, node, cb) { DISPLAY.show(node, delay(true, disp_length, function() { DISPLAY.hide(cb); }) ) } var subtract = function(arr, x) { var out = []; arr.forEach(function(el) { if (el === x) { return; } out.push(el); }); if (out.indexOf(x) !== -1) { throw "Failed to remove x"; } return out; }; var randomElement = function(arr) { return arr[Math.floor(Math.random() * arr.length)]; } var delay = function(wrap, t, f) { var x = function() { return setTimeout(f, t); }; if (wrap) { return x; } else { return x(); } } var SCHEDULE = []; var nextEdge = function(currentNode) { if (SCHEDULE.length === 0) { // TODO: pull this in from the current node; SCHEDULE = randomElement(hamiltonians[currentNode.id]).slice(1); } var target = SCHEDULE[0]; SCHEDULE = SCHEDULE.slice(1); return EDGES_BY_SOURCE[currentNode.id][target]; } var current; var WALK = function(s) { current = randomElement(subtract(NODES, current)); HL_NEXT = current; s.refresh(); var edge = null; var cycle = function() { highlight(s, current, function() { showNode(s, current, function() { setTimeout(function() { edge = nextEdge(current); HL_EDGE = edge; HL_PREV = current; if (current === NODES_BY_ID[edge.target]) { current = NODES_BY_ID[edge.source]; } else { current = NODES_BY_ID[edge.target]; } HL_NEXT = current; s.refresh(); delay(false, hl_len, cycle); }, hl_len); }); }); }; cycle(); }; <file_sep>/update-prod.sh #/bin/bash ssh artemis 'cd ~/project-hosting/peterdowns.com && git pull origin master' <file_sep>/Makefile .phony: generate generate: - ./generate.py <file_sep>/projects/emotionet/tools/genpaths.py #!/usr/bin/env python # coding: utf-8 import random def new_path(): return (tuple(), set()) def add_to_path(path, item): return (path[0] + (item,), path[1] | {item,}) def find_paths(edges, start, end, path=None): if start not in edges: raise Exception('missing node: {}'.format(start)) if path is None: path = new_path() path = add_to_path(path, start) unvisited_neighbors = list(edges[start] - path[1] - {end}) if not unvisited_neighbors and len(path[0]) == len(edges) - 1: yield path[0] random.shuffle(unvisited_neighbors) for neighbor in unvisited_neighbors: for p in find_paths(edges, neighbor, end, path): yield p def sample_hamiltonians(edges, num_samples_per_start_node=5000): cycles = {} nodes = list(edges.keys()) random.shuffle(nodes) for n, node in enumerate(nodes): cycles[node] = [] for i, path in enumerate(find_paths(edges, node, node)): if i > num_samples_per_start_node: # break cycles[node].append(path) print('Done with node {}/{}: {}'.format(n+1, len(nodes), node)) return cycles if __name__ == '__main__': from edges import edges import json cycles = sample_hamiltonians(edges, 100) with open('src/paths.js', 'w') as fout: fout.write('var hamiltonians = %s' % json.dumps(cycles, indent=2)) print('Done.') <file_sep>/projects/emotionet/src/emotionet.js var tags = [ 'hap', //py 'mel', //ancholy 'bor', //edom 'pas', //sion 'won', //der 'env', //y 'con', //tendedness 'nos', //talgia 'cur', //iosity 'tir', //ed ]; var tagsByFile = { '2016-12-30 02.48.30.jpg' : 'won env con', '2017-01-01 10.28.57.jpg' : 'hap won con nos', '2017-01-01 11.00.41.jpg' : 'mel won', '2017-01-03 05.18.30.jpg' : 'hap won pas con', '2017-01-03 06.20.50-2.jpg': 'hap won nos', '2017-01-04 00.44.30.jpg' : 'hap pas won tir', '2017-01-08 11.31.04.jpg' : 'mel pas env', '2017-01-08 11.59.51.jpg' : 'mel bor won', '2017-01-08 12.14.09.jpg' : 'hap cur tir', '2017-01-09 09.57.19.jpg' : 'bor won cur tir', '2017-01-10 07.07.55.jpg' : 'hap con nos cur tir', '2017-01-10 07.44.14.jpg' : 'hap mel pas won nos', '2017-01-17 09.39.42.jpg' : 'mel pas cur env', '2017-01-18 01.59.01.jpg' : 'won con', '2017-01-18 19.28.05.jpg' : 'hap mel con nos tir', '2017-01-19 21.29.30.jpg' : 'mel cur', '2017-01-19 22.35.13.jpg' : 'mel pas won', '2017-01-20 00.15.45.jpg' : 'hap won con tir', '2017-01-20 01.16.51.jpg' : 'bor tir', '2017-01-20 20.48.38.jpg' : 'hap won cur', '2017-01-21 19.18.37.jpg' : 'hap pas env cur', '2017-01-22 20.27.07.jpg' : 'pas nos', '2017-01-24 06.44.03.jpg' : 'mel env tir', '2017-01-25 10.21.31.jpg' : 'bor tir', '2017-01-28 00.12.08.jpg' : 'bor cur', '2017-02-03 01.04.28.jpg' : 'hap env cur', '2017-02-03 03.53.17.jpg' : 'mel tir', '2017-02-03 03.59.58.jpg' : 'won cur', '2017-02-03 07.35.13.jpg' : 'env nos cur', '2017-02-03 09.51.26.jpg' : 'bor tir', '2017-02-03 10.15.58.jpg' : 'hap cur tir', '2017-02-03 10.17.48.jpg' : 'mel pas won tir', }; var smallURL = function(filename) { return './photos/small/' + encodeURIComponent(filename); }; var largeURL = function(filename) { return './photos/large/' + encodeURIComponent(filename); }; var urls = []; Object.keys(tagsByFile).forEach(function(filename) { urls.push(smallURL(filename)); urls.push(largeURL(filename)); }); var filesByTag = {}; Object.keys(tagsByFile).forEach(function(filename) { var tags = tagsByFile[filename]; tags.split(' ').forEach(function(tag) { filesByTag[tag] = filesByTag[tag] || []; filesByTag[tag].push(filename); }); }); var edges = []; var edgeKey = function(file1, file2) { var sorted = [file1, file2].sort(); return sorted[0] + ' / ' + sorted[1]; } var edgeFiles = function(key) { return key.split(' / '); } var _edgeDedup = {}; var edgesByNode = {}; Object.keys(filesByTag).forEach(function(tag) { if (tag.length === 0) return; var filenames = filesByTag[tag]; for (var i = 0; i < filenames.length; i++) { var outer_file = filenames[i]; for (var j = i + 1; j < filenames.length; j++) { var inner_file = filenames[j]; if (inner_file === outer_file) { throw "BROKEN"; } _edgeDedup[edgeKey(outer_file, inner_file)] = true; } } }); Object.keys(_edgeDedup).forEach(function(edgeKey) { edges.push(edgeFiles(edgeKey)); }); /* EDGES_BY_NODE = {}; edges.forEach(function(edge) { [edge[0], edge[1]].forEach(function(node, i) { if (!EDGES_BY_NODE[node]) { EDGES_BY_NODE[node] = []; } EDGES_BY_NODE[node].push(edge[1-i]); }); }); console.log(EDGES_BY_NODE) */ <file_sep>/generate.py #!/usr/bin/env python # coding: utf-8 from mustache import template _enc_errors = 'xmlcharrefreplace' # How to treat unicode characters when writing # HTML content. _index = './index.html' # file at which to store the homepage / archive @template('templates/index.html') def render_index(): return {'index': True}, {} def _write(f, html): f.write(unicode(html).encode(errors=_enc_errors)) def main(): print 'Writing homepage -> {}'.format(_index) with open(_index, 'w') as fout: _write(fout, render_index()) if __name__=='__main__': main() <file_sep>/deploy.sh ssh artemis 'cd project-hosting/peterdowns.com && git pull origin master' <file_sep>/projects/emotionet/README.md Todo: - [ ] Keypress to skip forward in time - [ ] Configurable animation speed - [ ] General code cleanup - [ ] Animate drawing the lines between nodes - [ ] Different line colors for different edge types - [ ] Hamiltonian walks instead of pure markov - or, fake this by marking visited nodes as unvisitable, and add an escape clause if the thing gets stuck
1a0b23a8e12ea20362b47e8d1522a43170232a9c
[ "JavaScript", "Markdown", "Makefile", "Python", "Shell" ]
9
JavaScript
peterldowns/peterdowns.com
2f9998577b2ca01666f8d37535d651f0eb47758b
70f7ce08d3ecfd0bdd9e77babcda3ee320eff39a
refs/heads/master
<file_sep>let hallo = function(str){ str="Hallo + "+str; }; let welt="Welt"; hallo(welt); console.log(welt); //Objekte let halloObject= function(obj){ obj.name="Halo "+obj.name; }; let o ={ name: "Welt" }; halloObject(o); console.log(o); //Objekte2 let halloObject1= function(obj){ obj=null; }; let o1 ={ name: "Welt" }; halloObject(o1); console.log(o1); //Beispiele let obj2={value: 10}; function increase(obj2){ obj2.value++; } increase(obj2); console.log(obj2)<file_sep>function hello(name){ console.log("Hallo " + name+"! "); } hello("<NAME>");<file_sep>console.log("ich bin die hallo.js - Datei"); let data ={ name: "Welt" }; module.exports = data; let data1 ={ name:function(){ return "Welt"; } }; module.exports = data1; let data2={ name: function(){ return "Welt"; } }; let data4={ name: function(prefix){ return prefix+"Welt"; } }; <file_sep> // Tick // let counter = 10; let logTick = true; let seconds = 10; // Tick Tack // let timer = setInterval(() => { console.log(counter); if(logTick){ console.log("tick"); } else { console.log("tack"); } logTick = !logTick; counter = counter-1; }, 1000*seconds+100); <file_sep>console.log("<NAME>! "); require("./hallo"); let data = require("./hallo.js"); console.log(data); const data1=require("./hallo.js"); console.log(data1); const data2 = require("./hallo.js"); console.log(data2.name()); const data4 = require("./hallo.js"); console.log(data4.name("Hallo ")); require("./unterordner/appunterordner.js");<file_sep>function Person(vorname, nachname){ this.vorname=vorname; this.nachname= nachname; } Person.prototype.getName=function(){ return this.vorname+" "+this.nachname }; let hans = new Person("Hans", "Müller"); console.log(hans.getName()); //Objektorientierung function Person2(vorname2, nachname2){ this.vorname2=vorname2; this.nachname2= nachname2; } Person2.prototype.getName=function(){ return this.vorname2+" "+this.nachname2 }; let hans2 = new Person2("Hans", "Müller"); //console.log(hans2.getName()); let p={ vorname:"Erik", nachname:"Müller" }; p.__proto__=Person2.prototype; console.log(p.getName()); <file_sep> console.log("ich bin ein unterordner app.js");
9ee9e3618bef4963111b29f4de32dbbcd8290bf1
[ "JavaScript" ]
7
JavaScript
1819-2bhitm-syt/assignment01-livecoding-replay-HaasJulian
935cc755a994e74257c207cbe2dfbf24d7016ac8
35f4df28888171edca26dd65b1176eaf75a67837
refs/heads/master
<repo_name>tfabworks/pxt-tfabconnect-beta<file_sep>/README.md # TFabConnect(beta version) ![tfabconnect top](https://tfabworks.com/wp-content/uploads/tfabconnect-pct-768x590.jpg) ## 概要 - micro:bitのセンサーの値をインターネット上に時間情報と共に蓄積する事が出来ます - 蓄積したデータを時系列のグラフにする事が出来ます - グラフを出先からスマホで確認する事が出来ます - 遠隔地に設置したmicro:bit同士で通信を行う事が出来ます - IoT体験授業で使われる事を想定した設計をしています - 先生の事前準備不要:追加でWi-Fiアクセスポイントを用意する必要はありません - 追加コスト不要:追加でWi-Fi接続用周辺機器を購入する必要はありません ## 仕組み - MakeCode側でTFabConnect専用ブロックを使い「クラウド変数」に対して読み書きを行います ![tfabconnect_blocks](https://beta.tfabconnect.com/img/contrivance_block.png) - 読み書きの指示は、WebUSBを通じてダッシュボードがクラウド上のデータベースとやりとりを行います ![tfabconnect_daiagram](https://beta.tfabconnect.com/img/contrivance_figure_beta.png) ## 用意する物 - micro:bit - USBケーブル - PC(WebUSBが使えるChromeブラウザが使える事) ## 使い方 ### センサーの値をクラウド上に蓄積してブラウザで時系列変化のグラフを描く 1. クラウド変数に書き込むプログラムを作ってmicro:bitにダらウンロード 1. http://tfab.jp/connect-b にアクセスをし編集をクリック 1. クラウド変数xに明るさの値を書き込む 1. micro:bitにダウンロード 1. ダッシュボードにアクセスして micro:bitからの書き込みをクラウド上のデータベースに接続して蓄積開始 1. https://beta.tfabconnect.com/dashboard/ にアクセス 1. 初めての場合は規約を読みとりあえず「一時利用」を選択 1. 左上のmicro:bitのイラストの下にあるグループ選択を「無名のグループ」にしてコンセントのアイコンをクリック 1. 時系列グラフの参照 1. クラウド変数一覧の「x」のグラフアイコンをクリック 1. グラフ下の自動更新をクリックし、micro:bitの明るさとグラフが連動する事を確認 ### 描いたグラフを出先から参照出来らるようにする 1. 「無名のグループ」の「設定」を開き「グラフ公開」を許可にする 1. クラウド変数一覧の「x」のグラフアイコンをクリック 1. 「グラフの公開」をクリック 1. スマートフォンでQRコードを読み込み、URLを開く ### 離れたmicro:bit 同士で通信を行う 同じグループに参加すると同じ変数に読み書きを行えるようになります。 1. グループを作る 1. ダッシュボードにアクセス 1. 左メニューの「+」マークをクリック 1. 新しいグループを作成します 1. グループに招待する 1. 作成したグループの「メンバー」をクリック 1. 「メンバー追加」をクリック 1. ワンタイムグループトークン(6桁の数字)が表示されるのでメモをします 1. グループに参加する 1. 左メニューの「+」マークをクリック 1. 「グループへ参加」をクリック 1. メモをしたワンタイムグループトークンを入力します 1. プログラムを作る 1. あとは、お互いで同じクラウド変数名に対して読み書きを行うプログラムを作成。 1. micro:bitをグループ接続する 1. 左上のmicro:bitのイラストの下にあるグループ選択を作成したグループ名にしてコンセントのアイコンをクリック ## 関連リンク TFabConnect β トップページ:https://beta.tfabconnect.com/ <file_sep>/test.ts basic.showIcon(IconNames.No) <file_sep>/main.ts enum Choice { //% block="year" year, //% block="month" month, //% block="day" day, //% block="hour" hour, //% block="minute" minute, //% block="second" second, //% block="UnixTime" UnixTime } enum Pm { //% block="+" p, //% block="-" m } enum Tz_h { //% block="0" zero, //% block="1" one, //% block="2" two, //% block="3" three, //% block="4" four, //% block="5" five, //% block="6" six, //% block="7" seven, //% block="8" eight, //% block="9" nine, //% block="10" ten, //% block="11" eleven, //% block="12" twelve } enum Tz_m { //% block="0" zero, //% block="15" fifteen, //% block="30" thirty, //% block="45" fourty_five } //% weight=2 color=#3276f4 icon="\uf0c2" namespace TFabConnectBeta { let writeWaitTime = 1000; let readWaitTime = 3000; let _; let unixtime_init = 0; let unixtime_current = 0; let running_init = 0; let running_current = 0; let kvs: { [key: string]: number; } = {}; let diff_sec = 0; let serial_initialized = false; let time_initialized = false; /** * Initialize micro:bit for TfabConnect. Initialize the serial-port and the date. */ function serialInitialize(): void { serial.redirect( SerialPin.USB_TX, SerialPin.USB_RX, BaudRate.BaudRate9600 ) serial.writeString("\r\n"); // ヌル文字をいったんクリア _ = serial.readString(); // 受信バッファのゴミ除去 basic.pause(100); } function timeInitialize(): void { if (unixtime_init <= 0) { unixtime_init = readValue("__now"); } if (time_initialized == false) { running_init = Math.trunc(input.runningTime() / 1000); time_initialized = true; } } /** * Sets this cloud-variable to be equal to the input number. * @param varName name of Cloud-Variable, eg: * @param value write value to Cloud-Variable */ //% blockId=serial_writeid_value block="set cloud-variable %varName| to %value|" //% weight=100 export function writeValue(varName: string, value: number): void { if (serial_initialized == false) { serialInitialize(); serial_initialized = true; } let csv = '' + input.runningTime() + ',' + control.deviceSerialNumber() + ',w,' + varName + ',' + value; let hash = computeHash(csv); serial.writeLine(csv + ',' + hash); basic.pause(writeWaitTime); } /** * Read the number from cloud-variable. * @param varName name of Cloud-Variable, eg: */ //% blockId=serial_result block="cloud-variable%varName|" //% weight=90 export function readValue(varName: string) { if (serial_initialized == false) { serialInitialize(); serial_initialized = true; } let receiveNumber; let csv = '' + input.runningTime() + ',' + control.deviceSerialNumber() + ',r,' + varName + ',0' let hash = computeHash(csv); serial.writeLine(csv + ',' + hash); basic.pause(readWaitTime); let str = serial.readString(); receiveNumber = parseFloat(str); if (str == "" || str == "err") { let v = kvs[varName]; if (!kvs[varName]) { return 0; } return v; } kvs[varName] = receiveNumber; return receiveNumber; } function getcurrenttime() { if (time_initialized == false) { timeInitialize(); } if (unixtime_init <= 0) { basic.showIcon(IconNames.No); timeInitialize(); } running_current = Math.trunc(input.runningTime() / 1000); unixtime_current = unixtime_init + (running_current - running_init); return unixtime_current; } function sec2date(sec: number) { //変数定義 let t = []; let y = 0; let m = 0; let d = 0; let n = 0; let cnt = 0; const sec365 = 31536000; const sec366 = 31622400; let i = 0; let unix_show = Math.trunc(sec); //時差補正 //sec += 32400; //日本時間の例 sec += diff_sec //yearを求める let sec_y = sec; while (sec_y > sec365) { if (cnt % 4 == 2) { sec_y -= sec366; cnt += 1; } else { sec_y -= sec365; cnt += 1; } } y = 1970 + cnt; if (y % 4 == 0 && sec_y >= 5097600 && sec_y <= 5183999) {// 閏日 m = 2; d = 29; let amaridays = Math.trunc(sec_y / 86400); let hour_pre = ((sec_y / 86400) - amaridays) * 24; let hour = Math.abs(hour_pre); let hour_show = Math.trunc(hour_pre); let min_pre = hour_pre + 9 + ""; let min = parseFloat('0.' + min_pre.split(".")[1]) * 60; let min_int = Math.trunc(Math.round(min * 10000000000) / 10000000000); let sec = (min - min_int) * 60; let sec_int = Math.trunc(Math.round(sec * 10000000000) / 10000000000); let y_int = Math.trunc(y); const x = [y_int, m, d, hour_show, min_int, sec_int, unix_show]; return x; } else {//うるう日以外 let amaridays = Math.trunc(sec_y / 86400); if (y % 4 == 0) {//うるう年のうるう日以外 t = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]; for (i = 0; i < 14; i++) { if (amaridays < t[i]) { d = amaridays - t[i - 1] + 1; break; } } m = i; let hour_pre = ((sec_y / 86400) - amaridays) * 24; let hour = Math.abs(hour_pre); let hour_show = Math.trunc(hour_pre); let min_pre = hour_pre + 9 + ""; let min = parseFloat('0.' + min_pre.split(".")[1]) * 60; let min_int = Math.trunc(Math.round(min * 10000000000) / 10000000000); let sec = (min - min_int) * 60; let sec_int = Math.trunc(Math.round(sec * 10000000000) / 10000000000); let y_int = Math.trunc(y); const x = [y_int, m, d, hour_show, min_int, sec_int, unix_show]; return x; } else {//通常年 t = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]; for (i = 0; i < 14; i++) { if (amaridays < t[i]) { d = amaridays - t[i - 1] + 1; break; } } m = i; let hour_pre = ((sec_y / 86400) - amaridays) * 24; let hour = Math.abs(hour_pre); let hour_show = Math.trunc(hour_pre); let min_pre = hour_pre + 9 + ""; let min = parseFloat('0.' + min_pre.split(".")[1]) * 60; let min_int = Math.trunc(Math.round(min * 10000000000) / 10000000000); let sec = (min - min_int) * 60; let sec_int = Math.trunc(Math.round(sec * 10000000000) / 10000000000); let y_int = Math.trunc(y); const x = [y_int, m, d, hour_show, min_int, sec_int, unix_show]; return x; } } } // https://github.com/microsoft/pxt-radio-blockchain/blob/master/main.ts // MIT Lincense // Copyright (c) Microsoft Corporation. All rights reserved. // https://github.com/microsoft/pxt-radio-blockchain/blob/master/LICENSE function computeHash(str: string) { let s = "" + str /** * dbj2 hashing, http://www.cse.yorku.ca/~oz/hash.html */ let hash = 5381; for (let i = 0; i < s.length; i++) { let c = s.charCodeAt(i); hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } return hash & 0xffff; } /** * Get the date. * @param choice */ //% blockId=watch_time block="time %Choice" //% weight=80 export function time(choice: Choice) { let result = sec2date(getcurrenttime()); switch (choice) { case Choice.year: return result[0]; case Choice.month: return result[1]; case Choice.day: return result[2]; case Choice.hour: return result[3]; case Choice.minute: return result[4]; case Choice.second: return result[5]; case Choice.UnixTime: return result[6]; default: return 0; } } /** * Set the time difference from Greenwich Mean Time. * @param pm * @param tz_h * @param tz_m */ //% blockId=Tz_initialize block="set Timezone %Pm| %Tz_h| hour %Tz_m minute" //% weight=70 export function Tzsetting(pm: Pm, tz_h: Tz_h, tz_m: Tz_m): void { switch (tz_h) { case Tz_h.twelve: diff_sec += 43200 break case Tz_h.eleven: diff_sec += 39600 break case Tz_h.ten: diff_sec += 36000 break case Tz_h.nine: diff_sec += 32400 break case Tz_h.eight: diff_sec += 28800 break case Tz_h.seven: diff_sec += 25200 break case Tz_h.six: diff_sec += 21600 break case Tz_h.five: diff_sec += 18000 break case Tz_h.four: diff_sec += 14400 break case Tz_h.three: diff_sec += 10800 break case Tz_h.two: diff_sec += 7200 break case Tz_h.one: diff_sec += 3600 break case Tz_h.zero: diff_sec += 0 break default: diff_sec += 0 break } switch (tz_m) { case Tz_m.zero: diff_sec += 0 break case Tz_m.fifteen: diff_sec += 900 break case Tz_m.thirty: diff_sec += 1800 break case Tz_m.fourty_five: diff_sec += 2700 break default: diff_sec += 0 break } switch (pm) { case Pm.m: diff_sec = -diff_sec break default: diff_sec += 0 break } } }
ac97863726b0733b1901c24cd3fcc20cc414fd79
[ "Markdown", "TypeScript" ]
3
Markdown
tfabworks/pxt-tfabconnect-beta
2ee50a33c489bbb2bccfb8d378744aeb25cac9f3
f3bd3b46a90952c79d95ab3a608e2c38532ed8a0
refs/heads/master
<file_sep>/** * Created by josephawwal on 28/05/17. */ const Blog = () => <h2>Company Blog</h2> export default Blog
df495a7343427b6acd839cd3f42a81824dd90b0d
[ "JavaScript" ]
1
JavaScript
Yunas09/JS-Periode-6-Finish
eb153f9533bf6b4cb2ed9e0e178d6b8c5ef4d3ec
ee9ce473509ed41f4de6a0b96783ededebbfb3ba
refs/heads/master
<repo_name>lhamot/rah<file_sep>/rah/doc.cpp // // Copyright (c) 2019 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /// @struct rah::pipeable /// @brief Allow to call a custom function when called whith the 'pipe' syntax on a range /// @see rah::make_pipeable /// @fn rah::make_pipeable(MakeRange&& make_range) /// @brief Call to create a "pipeable" function (UFCS style in c++) /// /// @section create_pipeable How to create : /// @snippet test.cpp make_pipeable create /// @section use_pipeable How to use : /// @snippet test.cpp make_pipeable use /// @fn rah::make_iterator_range(I b, I e) /// @brief Create a rah::iterator_range with two given iterators /// @struct rah::iterator_facade /// @brief Inerit to make an iterator /// /// @tparam I is the type of iterator which inerit from iterator_facade /// @tparam R is the type returned by dereferencing the iterator (It can be a reference type or not) /// @tparam C is the iterator category (std::forward_iterator_tag, std::bidirectional_iterator_tag, std::random_access_iterator_tag) /// @struct rah::iterator_facade<I, R, std::output_iterator_tag> /// @brief Inerit to make an appendable range /// /// Required to implement : /// @code{cpp} /// template<typename V> void put(V&& value) const; /// @endcode /// @see rah::back_inserter /// @see rah::stream_inserter /// @struct rah::iterator_facade<I, R, std::forward_iterator_tag> /// @brief Inerit to make a forward_iterator /// /// Required to implement : /// @code{cpp} /// void increment(); /// reference dereference() const; /// bool equal(this_type other) const; /// @endcode /// @see rah::view::gererate_iterator /// @struct rah::iterator_facade<I, R, std::bidirectional_iterator_tag> /// @brief Inerit to make a bidirectional iterator /// /// Required to implement : /// @code{cpp} /// void increment(); /// void decrement(); /// reference dereference() const; /// bool equal(this_type other) const; /// @endcode /// @see rah::view::zip_iterator /// @struct rah::iterator_facade<I, R, std::random_access_iterator_tag> /// @brief Inerit to make a random access iterator /// /// Required to implement : /// @code{cpp} /// void increment(); /// void advance(intptr_t val); /// void decrement(); /// auto distance_to(this_type other); /// reference dereference() const; /// bool equal(this_type other) const; /// @endcode /// @see rah::view::iota_iterator /// @fn rah::view::ints(T, T) /// @brief Generate a range of monotonically increasing ints. When used without arguments, it generates the quasi-infinite range [0,1,2,3...]. It can also be called with a lower bound, or with a lower and upper bound (exclusive). [lower, uppder[ /// /// @snippet test.cpp ints /// @fn rah::view::closed_ints(T, T) /// @brief Generate a range of monotonically increasing ints. When used without arguments, it generates the quasi-infinite range [0,1,2,3...]. It can also be called with a lower bound, or with a lower and upper bound (inclusive). [lower, uppder] /// /// @snippet test.cpp closed_ints /// @fn rah::view::iota(T, T, T) /// @brief Generate a range of sequential integers, increasing by a defined step /// /// @snippet test.cpp iota /// @fn rah::view::repeat(V&&) /// @brief Generate an infinite range of the given value /// /// @snippet test.cpp repeat /// @fn rah::view::generate(F&& func) /// @brief Create an infinite range, repetitively calling func /// /// @snippet test.cpp generate /// @fn rah::view::generate_n(F&& func, size_t count) /// @brief Create a range of N elemnts, repetitively calling func /// /// @snippet test.cpp generate_n /// @fn rah::view::all(R&& range) /// @brief Create a view on the whole range /// @fn rah::view::all() /// @brief Create a view on the whole range /// @remark pipeable syntax /// @fn rah::view::transform(R&& range, F&& func) /// @brief Create a view applying a transformation to each element of the input range /// /// @snippet test.cpp rah::view::transform /// @fn rah::view::transform(F&& func) /// @brief Create a view applying a transformation to each element of the input range /// @remark pipeable syntax /// /// @snippet test.cpp rah::view::transform_pipeable /// @fn rah::view::take(R&& range, size_t count) /// @brief Given a source @b range and an integral @b count, return a range consisting of the first count elements from the source range, or the complete range if it has fewer elements. /// /// @snippet test.cpp take /// @fn rah::view::take(size_t count) /// @brief Given a source @b range and an integral @b count, return a range consisting of the first count elements from the source range, or the complete range if it has fewer elements. /// @remark pipeable syntax /// /// @snippet test.cpp take_pipeable /// @fn rah::view::drop(R&& range, size_t count) /// @brief Given a source range and an integral count, return a range consisting of all but the first count elements from the source range, or an empty range if it has fewer elements. /// /// @snippet test.cpp drop /// @fn rah::view::drop(size_t count) /// @brief Given a source range and an integral count, return a range consisting of all but the first count elements from the source range, or an empty range if it has fewer elements. /// @remark pipeable syntax /// /// @snippet test.cpp drop_pipeable /// @fn rah::view::drop_exactly(R&& range, size_t count) /// @brief Given a source range and an integral count, return a range consisting of all but the first count elements from the source range. The source range must have at least that many elements. /// /// @snippet test.cpp drop_exactly /// @fn rah::view::drop_exactly(size_t count) /// @brief Given a source range and an integral count, return a range consisting of all but the first count elements from the source range. The source range must have at least that many elements. /// @remark pipeable syntax /// /// @snippet test.cpp drop_exactly_pipeable /// @fn rah::view::sliding(R&& range, size_t n) /// @brief Given a range and a count n, place a window over the first n elements of the underlying range. Return the contents of that window as the first element of the adapted range, then slide the window forward one element at a time until hitting the end of the underlying range. /// /// @snippet test.cpp sliding /// @fn rah::view::sliding(size_t n) /// @brief Given a range and a count n, place a window over the first n elements of the underlying range. Return the contents of that window as the first element of the adapted range, then slide the window forward one element at a time until hitting the end of the underlying range. /// @remark pipeable syntax /// /// @snippet test.cpp sliding_pipeable /// @fn rah::view::counted(I&& it, size_t n, decltype(++it, 0) = 0) /// @brief Given an iterator @b it and a count @b n, create a range that starts at @b it and includes the next @b n elements. /// /// @snippet test.cpp counted /// @fn rah::view::counted(size_t count) /// @brief Given an iterator @b it and a count @b n, create a range that starts at @b it and includes the next @b n elements. /// @remark pipeable syntax /// /// @snippet test.cpp counted_pipeable /// @fn rah::view::unbounded(I&& it) /// @brief Given an iterator, return an infinite range that begins at that position. /// /// @snippet test.cpp unbounded /// @fn rah::view::slice(R&& range, intptr_t begin, intptr_t end) /// @brief Create a view that is a sub-range of a range /// /// @snippet test.cpp slice /// @fn rah::view::slice(intptr_t begin, intptr_t end) /// @brief Create a view that is a sub-range of a range /// @remark pipeable syntax /// /// @snippet test.cpp slice_pipeable /// @fn rah::view::stride(R&& range, size_t step) /// @brief Create a view consisting of every Nth element, starting with the first /// /// @snippet test.cpp stride /// @fn rah::view::stride(size_t step) /// @brief Create a view consisting of every Nth element, starting with the first /// @remark pipeable syntax /// /// @snippet test.cpp stride_pipeable /// @fn rah::view::reverse(R&& range) /// @brief Create a view that traverses the source range in reverse order /// /// @snippet test.cpp reverse /// @fn rah::view::reverse() /// @brief Create a view that traverses the source range in reverse order /// @remark pipeable syntax /// /// @snippet test.cpp retro_pipeable /// @fn rah::view::zip(R&&... _ranges) /// @brief Given N ranges, return a new range where Mth element is the result of calling std::make_tuple on the Mth elements of all N ranges. /// /// The resulting range has the size of the smaller of the sub-ranges /// /// @snippet test.cpp zip /// @fn rah::view::chunk(R&& range, size_t step) /// @brief Create a view where each element is a range of N elements of the input range /// /// @snippet test.cpp chunk /// @fn rah::view::chunk(size_t step) /// @brief Create a view where each element is a range of N elements of the input range /// @remark pipeable syntax /// /// @snippet test.cpp chunk_pipeable /// @fn rah::view::filter(R&& range, F&& func) /// @brief Create a view with only elements which are filtered /// /// @snippet test.cpp filter /// @fn rah::view::filter(F&& func) /// @brief Create a view with only elements which are filtered /// @remark pipeable syntax /// /// @snippet test.cpp filter_pipeable /// @fn rah::view::concat(R1&& range1, R2&& range2) /// @brief Create a view that is the concatenation of 2 ranges /// /// @snippet test.cpp concat /// @fn rah::view::concat(R&& rightRange) /// @brief Create a view that is the concatenation of 2 ranges /// @remark pipeable syntax /// /// @snippet test.cpp concat_pipeable /// @fn rah::view::enumerate(R&& range) /// @brief Pair each element of a range with its index. /// /// @snippet test.cpp enumerate /// @fn rah::view::enumerate() /// @brief Pair each element of a range with its index. /// @remark pipeable syntax /// /// @snippet test.cpp enumerate_pipeable /// @fn rah::view::map_value(R&& range) /// @brief Given a range of std::pair-std::tuple, create a view consisting of just the first element of the pair. /// /// @snippet test.cpp map_value /// @fn rah::view::map_value() /// @brief Given a range of std::pair-std::tuple, create a view consisting of just the first element of the pair. /// @remark pipeable syntax /// /// @snippet test.cpp map_value_pipeable /// @fn rah::view::map_key(R&& range) /// @brief Given a range of std::pair-std::tuple, create a view consisting of just the second element of the pair. /// /// @snippet test.cpp map_key /// @fn rah::view::map_key() /// @brief Given a range of std::pair-std::tuple, create a view consisting of just the second element of the pair. /// @remark pipeable syntax /// /// @snippet test.cpp map_key_pipeable /// @fn rah::view::single(V&& value) /// @brief Given value, create a view containing one element /// /// @snippet test.cpp single /// @fn rah::view::join(R&& range_of_ranges) /// @brief Given a range of ranges, join them into a flattened sequence of elements. /// /// @snippet test.cpp join /// @fn rah::view::join() /// @brief Given a range of ranges, join them into a flattened sequence of elements. /// @remark pipeable syntax /// /// @snippet test.cpp join_pipeable /// @fn rah::view::cycle(R&& range) /// @brief Returns an infinite range that endlessly repeats the source range. /// /// @snippet test.cpp cycle /// @fn rah::view::cycle() /// @brief Returns an infinite range that endlessly repeats the source range. /// @remark pipeable syntax /// /// @snippet test.cpp cycle_pipeable /// @fn rah::view::for_each(R&& range, F&& func) /// @brief Lazily applies an unary function to each element in the source range /// that returns another range (possibly empty), flattening the result. /// /// @snippet test.cpp for_each /// @fn rah::view::for_each(F&& func) /// @brief Lazily applies an unary function to each element in the source range /// that returns another range (possibly empty), flattening the result. /// @remark pipeable syntax /// /// @snippet test.cpp for_each_pipeable /*! \mainpage rah - A range (header only) library for C++ * * # What is a range * A range is anything that can be iterate. Typically in C++ something is a range if we can call `begin(range)` and `end(range)` on it. * * # How to create a range * In **rah** this is done by `rah::iterator_range`. * Two way to create an iterator_range: * - `rah::iterator_range<iterator_type>(begin_iter, end_iter);` * - `rah::make_iterator_range (begin_iter, end_iter);` * * # What is a view * A view is a range returned by a function an which doesn't modify it's input range.\n * The computing is often done in a "lazy" way, that is to say at the moment of iteration.\n * There is two kind of view: * - Views which take a range and give a modified view on it: * - Example: `rah::view::filter`, `rah::view::transform` * - Generators * - Example: `rah::view::iota`, `rah::view::generate` * * # How to make a view * - To make a view you have to create an iterator. * - For example the rah::view::filter view is an rah::iterator_range of rah::view::filter_iterator. * - Then you have to create a function taking a range and parameters (or no range for generator) * * @code{.cpp} template<typename R> auto reverse(R&& range) { return make_iterator_range( std::make_reverse_iterator(end(range)), std::make_reverse_iterator(begin(range))); } * @endcode * - Then you can add a pipeable version of the function * * @code{.cpp} auto reverse() { return make_pipeable([=](auto&& range) {return reverse(range); }); } * @endcode * * # How to make an iterator * There is in **rah** an helper to create iterators: `rah::iterator_facade` * There are three kind of `rah::iterator_facade`: * - rah::iterator_facade<I, R, std::forward_iterator_tag> * - For an example : rah::view::generate_iterator * - rah::iterator_facade<I, R, std::bidirectional_iterator_tag > * - For an example : rah::view::zip_iterator * - rah::iterator_facade<I, R, std::random_access_iterator_tag> * - For an example : rah::view::iota_iterator * * # How to make a pipeable view or algorithm * * Use the rah::make_pipeable function. * ## How to create a pipeable : * @snippet test.cpp make_pipeable create * ## How to use a pipeable : * @snippet test.cpp make_pipeable use * */ <file_sep>/rah/test.cpp // // Copyright (c) 2019 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "rah.hpp" #ifdef MSVC #pragma warning(push, 0) #endif #include <iostream> #include <vector> #include <map> #include <list> #include <forward_list> #include <ciso646> #include <sstream> #include <random> #include <atomic> #include <set> #ifdef MSVC #pragma warning(pop) #endif template<typename A, typename B, typename C, typename D> bool operator == (std::tuple<A, B> a, std::pair<D, C> b) { return std::get<0>(a) == std::get<0>(b) && std::get<1>(a) == std::get<1>(b); } template<typename A, typename B, typename C, typename D> bool operator == (std::pair<A, B> a, std::tuple<D, C> b) { return std::get<0>(a) == std::get<0>(b) && std::get<1>(a) == std::get<1>(b); } auto PairEqual = [](auto ab) {return std::get<0>(ab) == std::get<1>(ab); }; #undef assert #define assert(CONDITION) \ { \ std::cout << __LINE__ << " assert : " << #CONDITION << std::endl; \ if (CONDITION) \ std::cout << "OK" << std::endl; \ else \ {std::cout << "NOT OK" << std::endl; abort(); } \ } #define EQUAL_RANGE(RANGE, IL) \ { \ std::cout << "assert : " << #RANGE << " == " << #IL << std::endl; \ if (rah::view::zip(RANGE, IL) | rah::all_of(PairEqual)) \ std::cout << "OK" << std::endl; \ else \ {std::cout << "NOT OK" << std::endl; abort(); } \ } template<typename T> using il = std::initializer_list<T>; auto print_elt = [](auto&& elt) { (std::cout << std::forward<decltype(elt)>(elt)) << " "; }; template<typename... Args> std::ostream& operator << (std::ostream& os, std::tuple<Args...> tup) { ::rah::view::details::for_each(tup, print_elt); return os; } namespace test { template< class T > constexpr bool is_reference_v = std::is_reference<T>::value; template< class T > constexpr bool is_rvalue_reference_v = std::is_rvalue_reference<T>::value; } template<typename T> struct WhatIsIt; /// [make_pipeable create] auto test_count(int i) { return rah::make_pipeable([=](auto&& range) { return std::count(begin(range), end(range), i); }); } /// [make_pipeable create] template<typename R, typename = std::enable_if_t<rah::is_range<R>::value>> void toto(R&&) {} template<typename V> auto toto(std::initializer_list<V> il) { return toto(rah::make_iterator_range(begin(il), end(il))); } bool is_odd(int val) { return val % 2 == 0; } template<typename T> struct WhatIs; // Test creation of a custom iterator struct CustomGenerator : rah::iterator_facade<CustomGenerator, int, RAH_STD::forward_iterator_tag> { int y = 1; void increment() { y *= 2; } auto dereference() const { return y; } bool equal(CustomGenerator) const { return y > 10; } }; auto customGenerate() { return rah::iterator_range<CustomGenerator>{}; } int main() { { std::vector<int> vec{ 0, 1, 2, 2, 3 }; toto(vec); toto({ 0, 1, 2, 2, 3 }); } { /// [make_pipeable use] std::vector<int> vec{ 0, 1, 2, 2, 3 }; assert((vec | test_count(2)) == 2); /// [make_pipeable use] } // *********************************** views ************************************************** { std::vector<int> result; int value = 20; for (int i : rah::view::single(value)) result.push_back(i); assert(result == std::vector<int>({ 20 })); } { /// [single] std::vector<int> result; for (int i : rah::view::single(20)) result.push_back(i); assert(result == std::vector<int>({ 20 })); /// [single] } { /// [ints] std::vector<int> result; for (int i : rah::view::ints(10, 15)) result.push_back(i); assert(result == std::vector<int>({ 10, 11, 12, 13, 14 })); /// [ints] } { /// [closed_ints] std::vector<int> result; for (int i : rah::view::closed_ints(10, 14)) result.push_back(i); assert(result == std::vector<int>({ 10, 11, 12, 13, 14 })); /// [closed_ints] } { std::vector<int> result; for (int i : rah::view::ints(10) | rah::view::slice(2, 5)) result.push_back(i); assert(result == std::vector<int>({ 12, 13, 14 })); } { std::vector<size_t> result; for (size_t i : rah::view::ints() | rah::view::slice(2, 5)) result.push_back(i); assert(result == std::vector<size_t>({ 2, 3, 4 })); } { /// [iota] std::vector<int> result; for (int i : rah::view::iota(10, 19, 2)) result.push_back(i); assert(result == std::vector<int>({ 10, 12, 14, 16, 18 })); /// [iota] } { std::vector<int> result; for (int i : rah::view::iota(-5, 5, 2)) result.push_back(i); assert(result == std::vector<int>({ -5, -3, -1, 1, 3 })); } { std::vector<int> result; for (int i : rah::view::iota(-15, -6, 2)) result.push_back(i); assert(result == std::vector<int>({ -15, -13, -11, -9, -7 })); } { /// [join] std::vector<std::vector<int>> in = { { }, {0, 1}, { }, {2, 3, 4}, { 5}, {}, }; auto range = rah::view::join(in); std::vector<int> result; std::copy(begin(range), end(range), std::back_inserter(result)); assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5 })); /// [join] } //{ // // Test join on a range of rvalue // auto range = rah::view::iota(0, 6) // | rah::view::transform([](int i) {return std::vector<int>(1, i); }) // | rah::view::join(); // std::vector<int> result; // std::copy(begin(range), end(range), std::back_inserter(result)); // assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5 })); //} { /// [join_pipeable] std::vector<std::vector<int>> in = { {0, 1}, { }, {2, 3, 4}, { 5}, {}, }; auto range = in | rah::view::join(); std::vector<int> result; std::copy(begin(range), end(range), std::back_inserter(result)); assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5 })); /// [join_pipeable] } { /// [for_each] auto createRange = [](int i) { return rah::view::repeat(char('a' + i)) | rah::view::counted(i); }; auto range = rah::view::for_each(rah::view::iota(0, 5), createRange); std::string result; std::copy(begin(range), end(range), std::back_inserter(result)); assert(result == "bccdddeeee"); /// [for_each] } { /// [for_each_pipeable] auto range = rah::view::ints(0, 3) | rah::view::for_each([&](int z) { return rah::view::ints(3, 6) | rah::view::for_each([&, z](int y) { return rah::view::ints(6, 9) | rah::view::for_each([&, y, z](int x) { return rah::view::single(x + y * 3 + z * 9); }); }); }); assert(equal(range, rah::view::ints(15, 42))); /// [for_each_pipeable] } { size_t count = 0; size_t count2 = 0; size_t count3 = 0; auto range = rah::view::ints(0, 3) | rah::view::for_each([&](int z) { ++count; return rah::view::ints(3, 6) | rah::view::for_each([&, z](int y) { ++count2; return rah::view::ints(6, 9) | rah::view::for_each([&, y, z](int x) { ++count3; return rah::view::single(x + y * 3 + z * 9); }); }); }); assert(equal(range, rah::view::ints(15, 42))); assert(count == 3); assert(count2 == 9); assert(count3 == 27); } { size_t xSize = 2; size_t ySize = 3; auto xyIndexes = [=](size_t y) { return rah::view::zip( rah::view::repeat(y), rah::view::iota<size_t>(0, xSize) ); }; auto range = rah::view::iota<size_t>(0, ySize) | rah::view::for_each(xyIndexes); std::vector<std::tuple<size_t, size_t>> result; std::copy(begin(range), end(range), std::back_inserter(result)); assert(result == (std::vector<std::tuple<size_t, size_t>>{ { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 }, { 2, 0 }, { 2, 1 } })); size_t zSize = 4; auto xyzIndexes = [=](size_t z) { return rah::view::zip( rah::view::repeat(z), rah::view::iota<size_t>(0, ySize) | rah::view::for_each(xyIndexes) ); }; auto flattenTuple = [](auto&& z_yx) { using namespace std; return std::make_tuple( get<0>(z_yx), get<0>(get<1>(z_yx)), get<1>(get<1>(z_yx)) ); }; auto rangeZYX = rah::view::iota<size_t>(0, zSize) | rah::view::for_each(xyzIndexes) | rah::view::transform(flattenTuple); std::vector<std::tuple<size_t, size_t, size_t>> resultZYX; std::copy(begin(rangeZYX), end(rangeZYX), std::back_inserter(resultZYX)); assert(resultZYX == (std::vector<std::tuple<size_t, size_t, size_t>>{ { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 }, { 0, 1, 1 }, { 0, 2, 0 }, { 0, 2, 1 }, { 1, 0, 0 }, { 1, 0, 1 }, { 1, 1, 0 }, { 1, 1, 1 }, { 1, 2, 0 }, { 1, 2, 1 }, { 2, 0, 0 }, { 2, 0, 1 }, { 2, 1, 0 }, { 2, 1, 1 }, { 2, 2, 0 }, { 2, 2, 1 }, { 3, 0, 0 }, { 3, 0, 1 }, { 3, 1, 0 }, { 3, 1, 1 }, { 3, 2, 0 }, { 3, 2, 1 } })); } { /// [generate] int y = 1; auto gen = rah::view::generate([&y]() mutable { auto prev = y; y *= 2; return prev; }); std::vector<int> gen_copy; std::copy_n(begin(gen), 4, std::back_inserter(gen_copy)); assert(gen_copy == std::vector<int>({ 1, 2, 4, 8 })); /// [generate] } { /// [generate_n] std::vector<int> result; int y = 1; for (int i : rah::view::generate_n(4, [&y]() mutable { auto prev = y; y *= 2; return prev; })) result.push_back(i); assert(result == std::vector<int>({ 1, 2, 4, 8 })); /// [generate_n] } { /// [cycle] std::vector<int> in{ 0, 1, 2 }; auto cy = rah::view::cycle(in); std::vector<int> out; std::copy_n(begin(cy), 8, std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 0, 1, 2, 0, 1 })); /// [cycle] } { std::vector<int> in{ 0, 1, 2 }; auto cy = rah::view::cycle(in) | rah::view::reverse(); std::vector<int> out; std::copy_n(begin(cy), 8, std::back_inserter(out)); assert(out == std::vector<int>({ 2, 1, 0, 2, 1, 0, 2, 1 })); } { /// [cycle_pipeable] std::vector<int> in{ 0, 1, 2 }; auto cy = in | rah::view::cycle(); std::vector<int> out; std::copy_n(begin(cy), 8, std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 0, 1, 2, 0, 1 })); /// [cycle_pipeable] } { std::vector<int> in{ 0, 1, 2 }; auto cy = rah::view::cycle(in) | rah::view::counted(8); std::vector<int> out; std::copy(begin(cy), end(cy), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 0, 1, 2, 0, 1 })); } { /// [repeat] std::vector<int> out; auto range = rah::view::repeat(42); std::copy_n(begin(range), 5, std::back_inserter(out)); assert(out == std::vector<int>({ 42, 42, 42, 42, 42 })); /// [repeat] } { /// [take] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = rah::view::take(in, 5); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4 })); auto range2 = rah::view::take(in, 1000); std::vector<int> out2; std::copy(begin(range2), end(range2), std::back_inserter(out2)); assert(out2 == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })); /// [take] } { /// [take_pipeable] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = in | rah::view::take(5); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4 })); auto range2 = in | rah::view::take(1000); std::vector<int> out2; std::copy(begin(range2), end(range2), std::back_inserter(out2)); assert(out2 == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })); /// [take_pipeable] } { /// [drop] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = rah::view::drop(in, 6); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 6, 7, 8, 9 })); /// [drop] } { /// [drop_pipeable] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = in | rah::view::drop(6); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 6, 7, 8, 9 })); /// [drop_pipeable] } { std::vector<int> in{ 0, 1, 2 }; auto range = rah::view::drop(in, 6); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out.empty()); } { /// [drop_exactly] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = rah::view::drop_exactly(in, 6); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 6, 7, 8, 9 })); /// [drop_exactly] } { /// [drop_exactly_pipeable] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = in | rah::view::drop_exactly(6); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 6, 7, 8, 9 })); /// [drop_exactly_pipeable] } { /// [sliding] std::vector<int> in{ 0, 1, 2, 3, 4, 5 }; std::vector<std::vector<int>> out; for (auto subRange : rah::view::sliding(in, 3)) { out.emplace_back(); std::copy(begin(subRange), end(subRange), std::back_inserter(out.back())); } assert(out == (std::vector<std::vector<int>>{ { 0, 1, 2 }, { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 } })); /// [sliding] } { std::vector<int> in{ 0, 1, 2, 3, 4, 5 }; std::vector<std::vector<int>> out; for (auto subRange : in | rah::view::cycle() | rah::view::sliding(3) | rah::view::take(in.size()) ) { out.emplace_back(); std::copy(begin(subRange), end(subRange), std::back_inserter(out.back())); } assert(out == (std::vector<std::vector<int>>{ { 0, 1, 2 }, { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 }, { 4, 5, 0 }, { 5, 0, 1 }, })); } { /// [sliding_pipeable] std::vector<int> in{ 0, 1, 2, 3, 4, 5 }; std::vector<std::vector<int>> out; for (auto subRange : in | rah::view::sliding(3)) { out.emplace_back(); std::copy(begin(subRange), end(subRange), std::back_inserter(out.back())); } assert(out == (std::vector<std::vector<int>>{ { 0, 1, 2 }, { 1, 2, 3 }, { 2, 3, 4 }, { 3, 4, 5 } })); /// [sliding_pipeable] } { std::vector<int> in{ 0, 1, 2, 3 }; std::vector<std::vector<int>> out; for (auto subRange : rah::view::sliding(in, 4)) { out.emplace_back(); std::copy(begin(subRange), end(subRange), std::back_inserter(out.back())); } assert(out == (std::vector<std::vector<int>>{ {0, 1, 2, 3}})); } { std::vector<int> in{ 0, 1 }; std::vector<std::vector<int>> out; for (auto subRange : rah::view::sliding(in, 4)) { out.emplace_back(); std::copy(begin(subRange), end(subRange), std::back_inserter(out.back())); } assert(out == (std::vector<std::vector<int>>{})); } { std::vector<int> in{ 0, 1, 2, 3 }; std::vector<std::vector<int>> out; for (auto subRange : rah::view::sliding(in, 0)) { out.emplace_back(); std::copy(begin(subRange), end(subRange), std::back_inserter(out.back())); } assert(out == (std::vector<std::vector<int>>{})); } { std::vector<int> in{ 0, 1, 2, 3 }; std::vector<std::vector<int>> out; for (auto subRange : in | rah::view::sliding(1)) { out.emplace_back(); std::copy(begin(subRange), end(subRange), std::back_inserter(out.back())); } assert(out == (std::vector<std::vector<int>>{ {0}, { 1 }, { 2 }, { 3 }, })); } { /// [counted] std::vector<int> in{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; auto range = rah::view::counted(in.begin(), 5); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4 })); /// [counted] } { /// [unbounded] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = rah::view::unbounded(in.begin()); std::vector<int> out; std::copy_n(begin(range), 5, std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4 })); /// [unbounded] } { std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = rah::view::unbounded(in.begin()) | rah::view::slice(0, 5); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4 })); } { int in[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = rah::view::unbounded((int const*const)std::begin(in)) | rah::view::slice(0, 5); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4 })); } { /// [counted_pipeable] std::vector<int> in{ 0, 1, 2, 3, 4, 5 }; auto range = in | rah::view::counted(9); std::vector<int> out; auto a = begin(range); auto b = end(range); volatile auto dist = std::distance(a, b); (void)dist; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4, 5 })); /// [counted_pipeable] } { /// [counted_iterator] std::vector<int> in{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; auto range = rah::view::counted(in.begin(), 5); std::vector<int> out; std::copy(begin(range), end(range), std::back_inserter(out)); assert(out == std::vector<int>({ 0, 1, 2, 3, 4 })); /// [counted_iterator] } // Test all EQUAL_RANGE((il<int>{0, 1, 2, 3} | rah::view::all()), (il<int>{ 0, 1, 2, 3 })); int intTab[] = { 0, 1, 2, 3 }; EQUAL_RANGE((intTab | rah::view::all()), (il<int>{ 0, 1, 2, 3 })); // Test transform { /// [rah::view::transform] std::vector<int> vec{ 0, 1, 2, 3 }; std::vector<int> result; for (int i : rah::view::transform(vec, [](auto a) {return a * 2; })) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4, 6 })); /// [rah::view::transform] } { std::vector<int> vec{ 0, 1, 2, 3 }; std::vector<int> result; auto valueSelector = [](auto a) {return a * 2; }; auto selectedValuesRange = rah::view::transform(vec, valueSelector); auto bounds = std::minmax_element(begin(selectedValuesRange), end(selectedValuesRange)); auto min = *bounds.first; assert(min == 0); auto max = *bounds.second; assert(max == 6); // 3 * 2 } { /// [rah::view::transform_pipeable] std::vector<int> vec{ 0, 1, 2, 3 }; std::vector<int> result; for (int i : vec | rah::view::transform([](auto a) {return a * 2; })) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4, 6 })); /// [rah::view::transform_pipeable] } { /// [slice] std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; std::vector<int> result; for (int i : rah::view::slice(vec, 2, 6)) result.push_back(i); assert(result == std::vector<int>({ 2, 3, 4, 5 })); std::vector<int> result2; for (int i : rah::view::slice(vec, rah::End - 6, rah::End - 2)) result2.push_back(i); assert(result2 == std::vector<int>({ 2, 3, 4, 5 })); /// [slice] } { /// [slice_pipeable] std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; std::vector<int> result; for (int i : vec | rah::view::slice(2, 6)) result.push_back(i); assert(result == std::vector<int>({ 2, 3, 4, 5 })); /// [slice_pipeable] } { /// [stride] std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; std::vector<int> result; for (int i : rah::view::stride(vec, 2)) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4, 6 })); /// [stride] } { /// [stride_pipeable] std::vector<int> vec{ 0, 1, 2, 3, 4, 5, 6, 7 }; std::vector<int> result; for (int i : vec | rah::view::stride(2)) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4, 6 })); /// [stride_pipeable] } { /// [reverse] std::vector<int> vec{ 0, 1, 2, 3 }; std::vector<int> result; for (int i : rah::view::reverse(vec)) result.push_back(i); assert(result == std::vector<int>({ 3, 2, 1, 0 })); /// [reverse] } { /// [reverse_pipeable] std::vector<int> vec{ 0, 1, 2, 3 }; std::vector<int> result; for (int i : vec | rah::view::reverse()) result.push_back(i); assert(result == std::vector<int>({ 3, 2, 1, 0 })); /// [reverse_pipeable] } { /// [zip] std::vector<int> inputA{ 1, 2, 3, 4 }; std::vector<double> inputB{ 2.5, 4.5, 6.5, 8.5 }; std::vector<char> inputC{ 'a', 'b', 'c', 'd', 'e', 'f', 'g' }; std::vector<std::tuple<int, double, char>> result; for (auto a_b_c : rah::view::zip(inputA, inputB, inputC)) result.emplace_back(a_b_c); assert(result == (std::vector<std::tuple<int, double, char>>{ { 1, 2.5, 'a' }, { 2, 4.5, 'b' }, { 3, 6.5, 'c' }, { 4, 8.5, 'd' } })); /// [zip] } { std::vector<int> inputA{ 1, 2, 3, 4 }; std::vector<bool> inputB{ false, true, true, false }; auto range = rah::view::zip(inputA, inputB) | rah::view::filter([](auto a_b) {return std::get<1>(a_b); }); assert(rah::equal(range, std::vector<std::tuple<int, bool>>({ {2, true}, { 3, true } }))); } { /// [chunk] std::vector<int> vec_01234{ 0, 1, 2, 3, 4 }; std::vector<std::vector<int>> result; for (auto elts : rah::view::chunk(vec_01234, 2)) result.emplace_back(begin(elts), end(elts)); assert(result == std::vector<std::vector<int>>({ {0, 1}, { 2, 3 }, { 4 } })); /// [chunk] } { /// [chunk_pipeable] std::vector<int> vec_01234{ 0, 1, 2, 3, 4 }; std::vector<std::vector<int>> result; for (auto elts : vec_01234 | rah::view::chunk(2)) result.emplace_back(begin(elts), end(elts)); assert(result == std::vector<std::vector<int>>({ {0, 1}, { 2, 3 }, { 4 } })); /// [chunk_pipeable] } { /// [filter] std::vector<int> vec_01234{ 0, 1, 2, 3, 4 }; std::vector<int> result; for (int i : rah::view::filter(vec_01234, [](auto a) {return a % 2 == 0; })) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4 })); /// [filter] } { std::vector<int> vec_01234{ 0, 1, 2, 3, 4 }; std::vector<int> result; for (int i : rah::view::filter(vec_01234, &is_odd)) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4 })); } { enum class Tutu { a, b, c, d, e }; std::vector<Tutu> vec_01234{ Tutu::a, Tutu::b, Tutu::c, Tutu::d, Tutu::e }; std::vector<Tutu> result; for (Tutu i : rah::view::filter(vec_01234, [](Tutu a) {return a != Tutu::c; })) result.push_back(i); assert(result == std::vector<Tutu>({ Tutu::a, Tutu::b, Tutu::d, Tutu::e })); } { int vec_01234[] = { 0, 1, 2, 3, 4 }; std::vector<int> result; for (int i : rah::view::filter(vec_01234, [](auto a) {return a % 2 == 0; })) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4 })); } { std::vector<std::vector<int>> vec_01234 = { {0}, {1}, {2}, {3}, {4}, }; std::vector<bool> vec_bool = { true, true, true, true, true, }; std::vector<std::vector<int>> result; for (auto&& i : rah::view::zip(vec_01234, vec_bool) | rah::view::filter([](auto&& a) {return std::get<0>(a).front() % 2 == 0; })) result.push_back(std::get<0>(i)); assert(result == (std::vector<std::vector<int>>{ { 0 }, { 2 }, { 4 } })); assert(vec_01234 == (std::vector<std::vector<int>>{ { 0 }, { 1 }, { 2 }, { 3 }, { 4 }})); } { /// [filter_pipeable] std::vector<int> vec_01234{ 0, 1, 2, 3, 4 }; std::vector<int> result; for (int i : vec_01234 | rah::view::filter([](auto a) {return a % 2 == 0; })) result.push_back(i); assert(result == std::vector<int>({ 0, 2, 4 })); /// [filter_pipeable] } { // test filter with the first elements filtered auto range1 = rah::view::ints(1, 10) | rah::view::filter([](auto&& val) {return val % 2 == 0; }); assert(rah::none_of(range1, [](auto v) { return (v % 2) == 1; })); // test generate + filter auto range2 = rah::view::generate_n(100, []() {return rand(); }) | rah::view::filter([](auto&& val) { return val % 2 == 0; }); assert(rah::none_of(range2, [](auto v) { return (v % 2) == 1; })); // Can create some compilation issue about lambda copy auto range3 = rah::view::ints(0, 5) | rah::view::for_each([](auto) { return rah::view::generate_n(5, []() {return rand(); }) | rah::view::filter([](auto&& val) {return val % 2 == 0; }); }); assert(rah::none_of(range3, [](auto v) { return (v % 2) == 1; })); } { /// [concat] std::vector<int> inputA{ 0, 1, 2, 3 }; std::vector<int> inputB{ 4, 5, 6 }; std::vector<int> inputC{ 7, 8, 9, 10, 11 }; { std::vector<int> result; for (int i : rah::view::concat(inputA)) result.push_back(i); assert(result == std::vector<int>({ 0, 1, 2, 3 })); } { std::vector<int> result; for (int i : rah::view::concat(inputA, inputB)) result.push_back(i); assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6 })); } { std::vector<int> result; for (int i : rah::view::concat(inputA, inputB, inputC)) result.push_back(i); assert(result == std::vector<int>({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 })); } /// [concat] } { std::vector<int> inputA{ }; std::vector<int> inputB{ 1, 2, 3, 4}; { std::vector<int> result; for (int i : rah::view::concat(inputA, inputB)) result.push_back(i); assert(result == std::vector<int>({ 1, 2, 3, 4 })); } { std::vector<int> result; for (int i : rah::view::concat(inputA, inputB)) result.push_back(i); assert(result == std::vector<int>({ 1, 2, 3, 4 })); } { std::vector<int> result; for (int i : rah::view::concat(inputA, inputA)) result.push_back(i); assert(result == std::vector<int>({ })); } } { /// [enumerate] std::vector<int> input{ 4, 5, 6, 7 }; std::vector<std::tuple<size_t, int>> result; for (auto i_value : rah::view::enumerate(input)) result.emplace_back(i_value); assert(result == (std::vector<std::tuple<size_t, int>>{ { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } })); /// [enumerate] } { /// [enumerate_pipeable] std::vector<int> input{ 4, 5, 6, 7 }; std::vector<std::tuple<size_t, int>> result; for (auto i_value : input | rah::view::enumerate()) result.emplace_back(i_value); assert(result == (std::vector<std::tuple<size_t, int>>{ { 0, 4 }, { 1, 5 }, { 2, 6 }, { 3, 7 } })); /// [enumerate_pipeable] } { /// [map_value] std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } }; std::vector<double> result; for (double value : rah::view::map_value(input)) result.push_back(value); assert(result == (std::vector<double>{ 1.5, 2.5, 3.5, 4.5 })); /// [map_value] } /*{ // This can't work since enumerate return an rvalue pairs since map_key want an lvalue bool bools[] = { false, true, true, false, false, true }; auto range = bools | rah::view::enumerate() | rah::view::filter([](auto&& index_bool) {return std::get<1>(index_bool); }) | rah::view::map_key(); std::vector<size_t> ref; std::copy(begin(range), end(range), std::back_inserter(ref)); assert(ref == (std::vector<size_t>{1, 2, 5})); }*/ { /// [map_value_pipeable] std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } }; std::vector<double> result; for (double value : input | rah::view::map_value()) result.push_back(value); assert(result == (std::vector<double>{ 1.5, 2.5, 3.5, 4.5 })); /// [map_value_pipeable] } { /// [map_key] std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } }; std::vector<int> result; for (int key : rah::view::map_key(input)) result.push_back(key); assert(result == (std::vector<int>{ 1, 2, 3, 4 })); /// [map_key] } { /// [map_key_pipeable] std::map<int, double> input{ {1, 1.5}, { 2, 2.5 }, { 3, 3.5 }, { 4, 4.5 } }; std::vector<int> result; for (int key : input | rah::view::map_key()) result.push_back(key); assert(result == (std::vector<int>{ 1, 2, 3, 4 })); /// [map_key_pipeable] } { /// [view::set_difference] std::vector<int> in1 = {1, 2, 3, 4, 5, 6}; std::vector<int> in2 = { 2, 4, 6, 7, 8, 9, 10 }; std::vector<int> out; for (int val : rah::view::set_difference(in1, in2)) out.push_back(val); assert(out == std::vector<int>({1, 3, 5})); /// [view::set_difference] } { /// view::set_difference auto test_set_difference = [](std::vector<int> const& in1, std::vector<int> const& in2, std::vector<int> const& expected) { std::vector<int> out; for (int val : rah::view::set_difference(in1, in2)) out.push_back(val); assert(out == expected); }; test_set_difference({}, { 2, 4, 6, 7, 8, 9, 10 }, {}); test_set_difference({ 1, 2, 3, 4, 5, 6 }, { }, { 1, 2, 3, 4, 5, 6 }); test_set_difference({ 1, 2, 3, 4, 5, 6, 7 }, {2, 4, 6}, { 1, 3, 5, 7 }); test_set_difference({ 1, 2, 4, 6 }, {3, 5, 7}, { 1, 2, 4, 6 }); test_set_difference({ 1, 2, 4, 6 }, { 1, 2, 4, 6 }, {}); test_set_difference({ 1, 2, 4, 6, 7, 8, 9 }, { 1, 2, 4, 6 }, {7, 8, 9}); for (int x = 0; x < 100; ++x) { std::vector<int> in1; std::vector<int> in2; size_t const size1 = rand() % 100; size_t const size2 = rand() % 100; for (size_t i = 0; i < size1; ++i) in1.push_back(rand() % 100); for (size_t i = 0; i < size2; ++i) in2.push_back(rand() % 100); rah::sort(in1); rah::sort(in2); std::vector<int> outRef; std::set_difference(begin(in1), end(in1), begin(in2), end(in2), std::back_inserter(outRef)); std::vector<int> out; for (int val : in1 | rah::view::set_difference(in2)) out.push_back(val); assert(out == outRef); } } // *********************************** algos ************************************************** { /// [rah::equal_range] std::vector<int> vecIn1{ 1, 2, 2, 3, 4 }; { std::vector<int> out; for (int i : rah::equal_range(vecIn1, 0)) out.push_back(i); assert(out == std::vector<int>({ })); } { std::vector<int> out; for (int i : rah::equal_range(vecIn1, 1)) out.push_back(i); assert(out == std::vector<int>({ 1 })); } { std::vector<int> out; for (int i : rah::equal_range(vecIn1, 2)) out.push_back(i); assert(out == std::vector<int>({ 2, 2 })); } /// [rah::equal_range] } { /// [rah::equal_range_pipeable] std::vector<int> vecIn1{ 1, 2, 2, 3, 4 }; { std::vector<int> out; for (int i : vecIn1 | rah::equal_range(0)) out.push_back(i); assert(out == std::vector<int>({ })); } { std::vector<int> out; for (int i : vecIn1 | rah::equal_range(1)) out.push_back(i); assert(out == std::vector<int>({ 1 })); } { std::vector<int> out; for (int i : vecIn1 | rah::equal_range(2)) out.push_back(i); assert(out == std::vector<int>({ 2, 2 })); } /// [rah::equal_range_pipeable] } { /// [rah::equal_range_pred_0] struct S { int value; char test; bool operator==(S rhs) const { return value == rhs.value && test == rhs.test; } }; struct FindS { bool operator()(S s, int val) const { return s.value < val; } bool operator()(int val, S s) const { return val < s.value; } }; /// [rah::equal_range_pred_0] { /// [rah::equal_range_pred] std::vector<S> vecIn1{ {1, 'a'}, {2, 'b'}, {2, 'c'}, {3, 'd'}, {4, 'e'} }; { std::vector<S> out; for (S i : rah::equal_range(vecIn1, 0, FindS{})) out.push_back(i); assert(out == std::vector<S>({ })); } { std::vector<S> out; for (S i : rah::equal_range(vecIn1, 1, FindS{})) out.push_back(i); assert(out == std::vector<S>({ {1, 'a'} })); } { std::vector<S> out; for (S i : rah::equal_range(vecIn1, 2, FindS{})) out.push_back(i); assert(out == std::vector<S>({ {2, 'b'}, {2, 'c'} })); } /// [rah::equal_range_pred] } { /// [rah::equal_range_pred_pipeable] std::vector<S> vecIn1{ {1, 'a'}, {2, 'b'}, {2, 'c'}, {3, 'd'}, {4, 'e'} }; { std::vector<S> out; for (S i : vecIn1 | rah::equal_range(0, FindS{})) out.push_back(i); assert(out == std::vector<S>({ })); } { std::vector<S> out; for (S i : vecIn1 | rah::equal_range(1, FindS{})) out.push_back(i); assert(out == std::vector<S>({ {1, 'a'} })); } { std::vector<S> out; for (S i : vecIn1 | rah::equal_range(2, FindS{})) out.push_back(i); assert(out == std::vector<S>({ {2, 'b'}, {2, 'c'} })); } /// [rah::equal_range_pred_pipeable] } } { /// [rah::binary_search] std::vector<int> vecIn1{ 1, 2, 2, 3, 4 }; assert(not rah::binary_search(vecIn1, 0)); assert(rah::binary_search(vecIn1, 1)); assert(rah::binary_search(vecIn1, 2)); /// [rah::binary_search] } { /// [rah::binary_search_pipeable] std::vector<int> vecIn1{ 1, 2, 2, 3, 4 }; assert(not (vecIn1 | rah::binary_search(0))); assert(vecIn1 | rah::binary_search(1)); assert(vecIn1 | rah::binary_search(2)); /// [rah::binary_search_pipeable] } { std::vector<int> vecIn1{ 0, 1, 2, 3 }; std::vector<int> vecOut{ 0, 0, 0, 0 }; rah::transform(vecIn1, vecOut, [](int a) {return a + 1; }); assert(vecOut == std::vector<int>({ 1, 2, 3, 4 })); } { /// [rah::transform3] std::vector<int> vecIn1{ 0, 1, 2, 3 }; std::vector<int> vecOut; rah::transform(vecIn1, rah::back_inserter(vecOut), [](int a) {return a + 1; }); assert(vecOut == std::vector<int>({ 1, 2, 3, 4 })); /// [rah::transform3] } { /// [rah::transform4] std::vector<int> vecIn1{ 0, 1, 2, 3 }; std::vector<int> vecIn2{ 4, 3, 2, 1 }; std::vector<int> vecOut; rah::transform(vecIn1, vecIn2, rah::back_inserter(vecOut), [](int a, int b) {return a + b; }); assert(vecOut == std::vector<int>({ 4, 4, 4, 4 })); /// [rah::transform4] } assert((rah::view::iota(0, 0) | rah::reduce(0, [](auto a, auto b) {return a + b; })) == 0); { /// [rah::reduce] std::vector<int> vecIn1{ 1, 2, 3, 4 }; assert(rah::reduce(vecIn1, 0, [](auto a, auto b) {return a + b; }) == 10); /// [rah::reduce] } { /// [rah::reduce_pipeable] std::vector<int> vecIn1{ 1, 2, 3, 4 }; assert((vecIn1 | rah::reduce(0, [](auto a, auto b) {return a + b; })) == 10); /// [rah::reduce_pipeable] } /// [rah::any_of] assert(rah::any_of( std::initializer_list<int>{ 3, 0, 1, 3, 4, 6 }, [](auto a) {return a == 3; }) ); /// [rah::any_of] /// [rah::any_of_pipeable] assert(( std::initializer_list<int>{0, 1, 2, 3, 4, 6} | rah::any_of([](auto a) {return a == 3; }) )); /// [rah::any_of_pipeable] assert((std::initializer_list<int>{3, 0, 1, 3, 4, 6} | rah::any_of([](auto a) {return a == 3; }))); assert((std::initializer_list<int>{2, 0, 1, 2, 4, 6} | rah::any_of([](auto a) {return a == 3; })) == false); /// [rah::all_of] assert(rah::all_of( std::initializer_list<int>{ 4, 4, 4, 4 }, [](auto a) {return a == 4; }) ); /// [rah::all_of] assert(rah::all_of(std::initializer_list<int>{ 4, 4, 3, 4 }, [](auto a) {return a == 4; }) == false); assert((std::initializer_list<int>{ 4, 4, 4, 4 } | rah::all_of([](auto a) {return a == 4; }))); /// [rah::all_of_pipeable] assert(( std::initializer_list<int>{ 4, 4, 3, 4 } | rah::all_of([](auto a) {return a == 4; }) ) == false); /// [rah::all_of_pipeable] /// [rah::none_of] assert((rah::none_of( std::initializer_list<int>{7, 8, 9, 10}, [](auto a) {return a == 11; }) )); /// [rah::none_of] assert((std::initializer_list<int>{7, 8, 9, 10} | rah::none_of([](auto a) {return a == 11; }))); /// [rah::none_of_pipeable] assert(( std::initializer_list<int>{7, 8, 9, 10, 11} | rah::none_of([](auto a) {return a == 11; }) ) == false); /// [rah::none_of_pipeable] /// [rah::count] assert(rah::count(std::initializer_list<int>{ 4, 4, 4, 3 }, 3) == 1); /// [rah::count] /// [rah::count_pipeable] assert((std::initializer_list<int>{ 4, 4, 4, 3 } | rah::count(4)) == 3); /// [rah::count_pipeable] /// [rah::count_if] assert(rah::count_if(std::initializer_list<int>{ 4, 4, 4, 3 }, [](auto a) {return a == 4; }) == 3); /// [rah::count_if] /// [rah::count_if_pipeable] assert((std::initializer_list<int>{ 4, 4, 4, 3 } | rah::count_if([](auto a) {return a == 3; })) == 1); /// [rah::count_if_pipeable] { /// [rah::for_each] std::vector<int> testFE{ 4, 4, 4, 4 }; rah::for_each(testFE, [](auto& value) {return ++value; }); EQUAL_RANGE(testFE, std::initializer_list<int>({ 5, 5, 5, 5 })); /// [rah::for_each] } { /// [rah::for_each_pipeable] std::vector<int> testFE{ 4, 4, 4, 4 }; testFE | rah::for_each([](auto& value) {return ++value; }); EQUAL_RANGE(testFE, std::initializer_list<int>({ 5, 5, 5, 5 })); /// [rah::for_each_pipeable] } { /// [rah::to_container_pipeable] std::vector<std::pair<int, char>> in1{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } }; std::map<int, char> map_4a_5b_6c_7d = in1 | rah::to_container<std::map<int, char>>(); assert( map_4a_5b_6c_7d == (std::map<int, char>{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } }) ); std::list<int> in2{ 4, 5, 6, 7 }; std::vector<int> out = in2 | rah::to_container<std::vector<int>>(); assert(out == (std::vector<int>{ 4, 5, 6, 7 })); /// [rah::to_container_pipeable] } { /// [rah::to_container] std::vector<std::pair<int, char>> in1{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } }; std::map<int, char> map_4a_5b_6c_7d = rah::to_container<std::map<int, char>>(in1); assert( map_4a_5b_6c_7d == (std::map<int, char>{ {4, 'a'}, { 5, 'b' }, { 6, 'c' }, { 7, 'd' } }) ); std::list<int> in2{ 4, 5, 6, 7 }; std::vector<int> out = rah::to_container<std::vector<int>>(in2); assert(out == (std::vector<int>{ 4, 5, 6, 7 })); /// [rah::to_container] } { /// [rah::mismatch] std::vector<int> in1 = { 1, 2, 3, 4 }; std::vector<int> in2 = { 1, 2, 42, 42 }; auto r1_r2 = rah::mismatch(in1, in2); std::vector<int> out1; std::vector<int> out2; std::copy(std::get<0>(r1_r2), end(in1), std::back_inserter(out1)); std::copy(std::get<1>(r1_r2), end(in2), std::back_inserter(out2)); assert(out1 == std::vector<int>({ 3, 4 })); assert(out2 == std::vector<int>({ 42, 42 })); /// [rah::mismatch] } { /// [rah::find] std::vector<int> in{ 1, 2, 3, 4 }; auto iter = rah::find(in, 3); assert( (rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 }))) ); /// [rah::find] } { /// [rah::find_pipeable] std::vector<int> in{ 1, 2, 3, 4 }; auto iter = in | rah::find(3); assert( (rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 }))) ); /// [rah::find_pipeable] } { /// [rah::find_if] std::vector<int> in{ 1, 2, 3, 4 }; auto iter = rah::find_if(in, [](int i) {return i == 3; }); assert( (rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 }))) ); /// [rah::find_if] } { /// [rah::find_if_pipeable] std::vector<int> in{ 1, 2, 3, 4 }; auto iter = in | rah::find_if([](int i) {return i == 3; }); assert( (rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 }))) ); /// [rah::find_if_pipeable] } { /// [rah::find_if_not] std::vector<int> in{ 1, 2, 3, 4 }; auto iter = rah::find_if_not(in, [](int i) {return i < 3; }); assert((rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 })))); /// [rah::find_if_not] } { /// [rah::find_if_not_pipeable] std::vector<int> in{ 1, 2, 3, 4 }; auto iter = in | rah::find_if_not([](int i) {return i < 3; }); assert((rah::make_iterator_range(iter, end(in)) | rah::equal(std::initializer_list<int>({ 3, 4 })))); /// [rah::find_if_not_pipeable] } { /// [rah::max_element] std::vector<int> in{ 1, 5, 3, 4 }; auto iter = rah::max_element(in); assert(*iter == 5); /// [rah::max_element] } { /// [rah::max_element_pipeable] std::vector<int> in{ 1, 5, 3, 4 }; auto iter = in | rah::max_element(); assert(*iter == 5); /// [rah::max_element_pipeable] } { /// [rah::max_element_pred] std::vector<std::pair<int, int>> in{ {100, 3}, {0, 5}, {0, 1}, {0, 4} }; auto iter = rah::max_element(in, [](auto&& a, auto& b) {return a.second < b.second; }); assert(*iter == (std::pair<int, int>{0, 5})); /// [rah::max_element_pred] } { /// [rah::max_element_pred_pipeable] std::vector<std::pair<int, int>> in{ {100, 3}, {0, 5}, {0, 1}, {0, 4} }; auto iter = in | rah::max_element([](auto&& a, auto& b) {return a.second < b.second; }); assert(*iter == (std::pair<int, int>{0, 5})); /// [rah::max_element_pred_pipeable] } { /// [rah::min_element] std::vector<int> in{ 1, -5, 3, 4 }; auto iter = rah::min_element(in); assert(*iter == -5); /// [rah::min_element] } { /// [rah::min_element_pipeable] std::vector<int> in{ 1, -5, 3, 4 }; auto iter = in | rah::min_element(); assert(*iter == -5); /// [rah::min_element_pipeable] } { /// [rah::min_element_pred] std::vector<std::pair<int, int>> in{ {-100, 3}, {0, -5}, {0, 1}, {0, 4} }; auto iter = rah::min_element(in, [](auto&& a, auto& b) {return a.second < b.second; }); assert(*iter == (std::pair<int, int>{0, -5})); /// [rah::min_element_pred] } { /// [rah::min_element_pred_pipeable] std::vector<std::pair<int, int>> in{ {-100, 3}, {0, -5}, {0, 1}, {0, 4} }; auto iter = in | rah::min_element([](auto&& a, auto& b) {return a.second < b.second; }); assert(*iter == (std::pair<int, int>{0, -5})); /// [rah::min_element_pred_pipeable] } { /// [rah::size] std::vector<int> vec3{ 1, 2, 3 }; assert(rah::size(vec3) == 3); /// [rah::size] } { /// [rah::size_pipeable] std::vector<int> vec3{ 1, 2, 3 }; assert((vec3 | rah::size()) == 3); /// [rah::size_pipeable] } { /// [rah::equal] std::vector<int> in1{ 1, 2, 3 }; std::vector<int> in2{ 1, 2, 3 }; std::vector<int> in3{ 11, 12, 13 }; assert(rah::equal(in1, in2)); assert(rah::equal(in1, in3) == false); /// [rah::equal] } { /// [rah::equal_pipeable] std::vector<int> in1{ 1, 2, 3 }; std::vector<int> in2{ 1, 2, 3 }; std::vector<int> in3{ 11, 12, 13 }; assert(in1 | rah::equal(in2)); assert(not (in1 | rah::equal(in3))); /// [rah::equal_pipeable] } /// [rah::empty] assert(not (rah::empty(std::vector<int>{ 1, 2, 3 }))); assert(rah::empty(std::vector<int>())); /// [rah::empty] /// [rah::empty_pipeable] assert(not (std::vector<int>{ 1, 2, 3 } | rah::empty())); assert(std::vector<int>() | rah::empty()); /// [rah::empty_pipeable] { /// [rah::copy] std::vector<int> in{ 1, 2, 3 }; std::vector<int> out{ 0, 0, 0, 4, 5 }; // std::vector<int> out{ 0, 0 }; // Trigger an assert assert(rah::make_iterator_range(rah::copy(in, out), end(out)) | rah::equal(std::initializer_list<int>({ 4, 5 }))); assert(out == (std::vector<int>{ 1, 2, 3, 4, 5 })); /// [rah::copy] } { /// [rah::copy_pipeable] std::vector<int> in{ 1, 2, 3 }; std::vector<int> out{ 0, 0, 0, 4, 5 }; auto iter = in | rah::copy(out); assert((rah::make_iterator_range(iter, end(out)) | rah::equal(std::initializer_list<int>{ 4, 5 }))); assert(out == (std::vector<int>{ 1, 2, 3, 4, 5 })); /// [rah::copy_pipeable] } { /// [rah::copy_if] std::vector<int> in{ 1, 2, 3, 4 }; std::vector<int> out{ 0, 0, 5, 6 }; assert(rah::make_iterator_range(rah::copy_if(in, out, [](int i) {return i % 2 == 0; }), end(out)) | rah::equal(std::initializer_list<int>({ 5, 6 }))); assert(out == (std::vector<int>{ 2, 4, 5, 6 })); /// [rah::copy_if] } { /// [rah::copy_if_pipeable] std::vector<int> in{ 1, 2, 3, 4 }; std::vector<int> out{ 0, 0, 5, 6 }; assert(rah::make_iterator_range(in | rah::copy_if(out, [](int i) {return i % 2 == 0; }), end(out)) | rah::equal(std::initializer_list<int>({ 5, 6 }))); assert(out == (std::vector<int>{ 2, 4, 5, 6 })); /// [rah::copy_if_pipeable] } { /// [rah::fill] std::vector<int> out{ 0, 0, 0, 4, 5 }; rah::fill(out, 42); assert(out == (std::vector<int>{ 42, 42, 42, 42, 42 })); /// [rah::fill] } { /// [rah::fill_pipeable] std::vector<int> out{ 0, 0, 0, 4, 5 }; out | rah::fill(42); assert(out == (std::vector<int>{ 42, 42, 42, 42, 42 })); /// [rah::fill_pipeable] } { std::vector<int> out{ 0, 0, 0, 4, 5 }; out | rah::view::counted(3) | rah::fill(42); assert(out == (std::vector<int>{ 42, 42, 42, 4, 5 })); } { /// [rah::back_inserter] std::vector<int> in{ 1, 2, 3 }; std::vector<int> out; rah::copy(in, rah::back_inserter(out)); assert(out == std::vector<int>({ 1, 2, 3 })); /// [rah::back_inserter] } { /// [rah::back_insert] std::vector<int> in{ 1, 2, 3 }; std::vector<int> out{ 10 }; rah::back_insert(in, out); assert(out == (std::vector<int>{ 10, 1, 2, 3 })); /// [rah::back_insert] } { /// [rah::back_insert_pipeable] std::vector<int> in{ 1, 2, 3 }; std::vector<int> out{ 10 }; in | rah::back_insert(out); assert(out == (std::vector<int>{ 10, 1, 2, 3 })); /// [rah::back_insert_pipeable] } { std::vector<int> in{ 1, 2, 3 }; std::vector<int> out; in | rah::copy(rah::back_inserter(out)); assert(out == (std::vector<int>{ 1, 2, 3 })); } { // Test rah::inserter std::vector<int> in{ 1, 3, 5 }; std::set<int> out{ 2, 4 }; in | rah::copy(rah::inserter(out, end(out))); assert(out == (std::set<int>{ 1, 2, 3, 4, 5 })); } { /// [rah::stream_inserter] std::string in("Test"); std::stringstream out; in | rah::copy(rah::stream_inserter(out)); assert(out.str() == in); /// [rah::stream_inserter] } { /// [rah::remove_if] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto range_to_erase_begin = rah::remove_if(in, [](auto a) {return a < 4; }); in.erase(range_to_erase_begin, end(in)); std::sort(in.begin(), in.end()); assert(in == std::vector<int>({4, 5})); /// [rah::remove_if] } { /// [rah::remove_if_pipeable] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto range_to_erase_begin = in | rah::remove_if([](int a) {return a < 4; }); in.erase(range_to_erase_begin, end(in)); std::sort(in.begin(), in.end()); assert(in == std::vector<int>({ 4, 5 })); /// [rah::remove_if_pipeable] } { /// [rah::remove] std::vector<int> in{ 1, 2, 1, 3, 1 }; auto range_to_erase_begin = rah::remove(in, 1); in.erase(range_to_erase_begin, end(in)); std::sort(in.begin(), in.end()); assert(in == std::vector<int>({ 2, 3 })); /// [rah::remove] } { /// [rah::remove_pipeable] std::vector<int> in{ 1, 2, 1, 3, 1 }; auto range_to_erase_begin = in | rah::remove(1); in.erase(range_to_erase_begin, end(in)); std::sort(in.begin(), in.end()); assert(in == std::vector<int>({ 2, 3 })); /// [rah::remove_pipeable] } { /// [rah::partition] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto boundary = rah::partition(in, [](auto a) {return a >= 4; }); assert(boundary == in.begin() + 2); std::sort(in.begin(), boundary); std::sort(boundary, in.end()); assert(in == std::vector<int>({ 4, 5, 1, 2, 3 })); /// [rah::partition] } { /// [rah::partition_pipeable] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto boundary = in | rah::partition([](auto a) {return a >= 4; }); assert(boundary == in.begin() + 2); std::sort(in.begin(), boundary); std::sort(boundary, in.end()); assert(in == std::vector<int>({ 4, 5, 1, 2, 3 })); /// [rah::partition_pipeable] } { /// [rah::stable_partition] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto boundary = rah::stable_partition(in, [](auto a) {return a >= 4; }); assert(boundary == in.begin() + 2); assert(in == std::vector<int>({ 4, 5, 1, 2, 3 })); /// [rah::stable_partition] } { /// [rah::stable_partition_pipeable] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto boundary = in | rah::stable_partition([](auto a) {return a >= 4; }); assert(boundary == in.begin() + 2); assert(in == std::vector<int>({ 4, 5, 1, 2, 3 })); /// [rah::stable_partition_pipeable] } { /// [rah::erase] std::vector<int> in{ 1, 2, 3, 4, 5 }; rah::erase(in, rah::make_iterator_range(begin(in), begin(in) + 3)); assert(in == std::vector<int>({ 4, 5 })); /// [rah::erase] } { /// [rah::erase_pipeable] std::vector<int> in{ 1, 2, 3, 4, 5 }; in | rah::erase(rah::make_iterator_range(begin(in), begin(in) + 3)); assert(in == std::vector<int>({ 4, 5 })); /// [rah::erase_pipeable] } { /// [rah::erase_remove_if] std::vector<int> in{ 1, 2, 3, 4, 5 }; in | rah::erase(rah::make_iterator_range(in | rah::remove_if([](int a) {return a < 4; }), end(in))); assert(in == std::vector<int>({ 4, 5 })); /// [rah::erase_remove_if] } { /// [rah::sort] std::vector<int> in{ 2, 1, 5, 3, 4 }; rah::sort(in); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::sort] } { /// [rah::sort_pipeable] std::vector<int> in{ 2, 1, 5, 3, 4 }; in | rah::sort(); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::sort_pipeable] } { /// [rah::sort_pred] std::vector<int> in{ 2, 1, 5, 3, 4 }; rah::sort(in, [](auto a, auto b) {return a < b; }); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::sort_pred] } { /// [rah::sort_pred_pipeable] std::vector<int> in{ 2, 1, 5, 3, 4 }; in | rah::sort([](auto a, auto b) {return a < b; }); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::sort_pred_pipeable] } /// [rah::stable_sort] struct CmpA { int a; int b; bool operator<(CmpA rhs) const { return a < rhs.a; } bool operator==(CmpA rhs) const { return a == rhs.a && b == rhs.b; } }; { std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } }; rah::stable_sort(in); assert(in == std::vector<CmpA>({ { 1, 1 }, { 2, 1 }, { 2, 2 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 } })); } /// [rah::stable_sort] { std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } }; /// [rah::stable_sort_pipeable] in | rah::stable_sort(); assert(in == std::vector<CmpA>({ { 1, 1 }, { 2, 1 }, { 2, 2 }, { 4, 1 }, { 4, 2 }, { 4, 3 }, { 4, 4 } })); /// [rah::stable_sort_pipeable] } { /// [rah::stable_sort_pred] std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } }; rah::stable_sort(in, [](CmpA l, CmpA r) { return l.b < r.b; }); assert(in == std::vector<CmpA>({ { 4, 1 }, { 2, 1 }, { 1, 1 }, { 4, 2 }, { 2, 2 }, { 4, 3 }, { 4, 4 } })); /// [rah::stable_sort_pred] } { /// [rah::stable_sort_pred_pipeable] std::vector<CmpA> in{ { 4, 1 }, { 2, 1 }, { 4, 2 }, { 1, 1 }, { 4, 3 }, { 2, 2 }, { 4, 4 } }; in | rah::stable_sort([](CmpA l, CmpA r) { return l.b < r.b; }); assert(in == std::vector<CmpA>({ { 4, 1 }, { 2, 1 }, { 1, 1 }, { 4, 2 }, { 2, 2 }, { 4, 3 }, { 4, 4 } })); /// [rah::stable_sort_pred_pipeable] } { /// [rah::shuffle] std::random_device rd; std::mt19937 g(rd()); std::vector<int> in{ 1, 2, 3, 4, 5, 6 }; rah::shuffle(in, g); /// [rah::shuffle] } { /// [rah::shuffle_pipeable] std::random_device rd; std::mt19937 g(rd()); std::vector<int> in{ 1, 2, 3, 4, 5, 6 }; in | rah::shuffle(g); /// [rah::shuffle_pipeable] } { /// [rah::unique] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; in.erase(rah::unique(in), end(in)); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::unique] } { /// [rah::unique_pipeable] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; in.erase(in | rah::unique(), end(in)); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::unique_pipeable] } { /// [rah::unique_pred] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; in.erase(rah::unique(in, [](auto a, auto b) {return a == b; }), end(in)); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::unique_pred] } { /// [rah::unique_pred_pipeable] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; in.erase(in | rah::unique([](auto a, auto b) {return a == b; }), end(in)); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::unique_pred_pipeable] } { /// [rah::set_difference] std::vector<int> in1{ 1, 3, 4 }; std::vector<int> in2{ 1, 2, 3 }; std::vector<int> out{ 0, 0, 0, 0 }; rah::set_difference(in1, in2, out); assert(out == std::vector<int>({4, 0, 0, 0})); /// [rah::set_difference] } { /// [rah::set_intersection] std::vector<int> in1{ 1, 3, 4 }; std::vector<int> in2{ 1, 2, 3 }; std::vector<int> out{ 0, 0, 0, 0 }; rah::set_intersection(in1, in2, out); assert(out == std::vector<int>({ 1, 3, 0, 0 })); /// [rah::set_intersection] } { /// [rah::action::unique] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; auto&& result = rah::action::unique(in); assert(&result == &in); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::action::unique] } { /// [rah::action::unique_pipeable] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; auto&& result = in | rah::action::unique(); assert(&result == &in); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::action::unique_pipeable] } { /// [rah::action::unique_pred] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; auto&& result = rah::action::unique(in, [](auto a, auto b) {return a == b; }); assert(&result == &in); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::action::unique_pred] } { /// [rah::action::unique_pred_pipeable] std::vector<int> in{ 2, 1, 1, 1, 5, 3, 3, 4 }; auto&& result = in | rah::action::unique([](auto a, auto b) {return a == b; }); assert(&result == &in); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); /// [rah::action::unique_pred_pipeable] } { /// [rah::action::remove_if] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto&& result = rah::action::remove_if(in, [](auto a) {return a < 4; }); assert(&result == &in); assert(in == std::vector<int>({ 4, 5 })); /// [rah::action::remove_if] } { /// [rah::action::remove_if_pipeable] std::vector<int> in{ 1, 2, 3, 4, 5 }; auto&& result = in | rah::action::remove_if([](int a) {return a < 4; }); assert(&result == &in); assert(in == std::vector<int>({ 4, 5 })); /// [rah::action::remove_if_pipeable] } { /// [rah::action::remove] std::vector<int> in{ 1, 2, 1, 3, 1 }; auto&& result = rah::action::remove(in, 1); assert(&result == &in); assert(in == std::vector<int>({ 2, 3 })); /// [rah::action::remove] } { /// [rah::action::remove_pipeable] std::vector<int> in{ 1, 2, 1, 3, 1 }; auto&& result = in | rah::action::remove(1); assert(&result == &in); assert(in == std::vector<int>({ 2, 3 })); /// [rah::action::remove_pipeable] } { /// [rah::action::sort] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = rah::action::sort(in); assert(&result == &in); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::action::sort] } { /// [rah::action::sort_pipeable] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = in | rah::action::sort(); assert(&result == &in); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::action::sort_pipeable] } { /// [rah::action::sort_pred] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = rah::action::sort(in, [](auto a, auto b) {return a < b; }); assert(&result == &in); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::action::sort_pred] } { /// [rah::action::sort_pred_pipeable] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = in | rah::action::sort([](auto a, auto b) {return a < b; }); assert(&result == &in); assert(in == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::action::sort_pred_pipeable] } { /// [rah::action::shuffle] std::random_device rd; std::mt19937 g(rd()); std::vector<int> in{ 1, 2, 3, 4, 5, 6 }; assert(&rah::action::shuffle(in, g) == &in); /// [rah::action::shuffle] } { /// [rah::action::shuffle_pipeable] std::random_device rd; std::mt19937 g(rd()); std::vector<int> in{ 1, 2, 3, 4, 5, 6 }; assert(&(in | rah::action::shuffle(g)) == &in); /// [rah::action::shuffle_pipeable] } { /// [rah::view::sort] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = rah::view::sort(in); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); assert(result == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::view::sort] } { std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = in | rah::view::transform([](int& i) ->const int& {return i; }) | rah::view::sort() | rah::to_container<std::vector<int>>(); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); assert(result == std::vector<int>({ 1, 2, 3, 4, 5 })); } { /// [rah::view::sort_pipeable] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = in | rah::view::sort(); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); assert(result == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::view::sort_pipeable] } { /// [rah::view::sort_pred] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = rah::view::sort(in, [](auto a, auto b) {return a < b; }); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); assert(result == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::view::sort_pred] } { /// [rah::view::sort_pred_pipeable] std::vector<int> in{ 2, 1, 5, 3, 4 }; auto&& result = in | rah::view::sort([](auto a, auto b) {return a < b; }); assert(in == std::vector<int>({ 2, 1, 5, 3, 4 })); assert(result == std::vector<int>({ 1, 2, 3, 4, 5 })); /// [rah::view::sort_pred_pipeable] } { auto&& sorted = rah::view::iota(0, 10, 2) | rah::view::sort([](auto a, auto b) {return b < a; }); auto&& result = sorted | rah::view::transform([](auto v) {return v - 10; }) | rah::to_container<std::vector<int>>(); assert(result == std::vector<int>({ -2, -4, -6, -8, -10 })); } { /// [rah::actions::fill] std::vector<int> out{ 0, 0, 0, 4, 5 }; assert(rah::action::fill(out, 42) == (std::vector<int>{ 42, 42, 42, 42, 42 })); /// [rah::actions::fill] } // ********************************* test return ref and non-ref ****************************** using namespace rah; using namespace rah::view; using namespace std; struct Elt { int member; bool operator==(Elt elt) const { return member == elt.member; } }; // Test return reference { std::vector<Elt> vec = { {0}, { 1 }, { 2 }, { 3 }, { 4 } }; auto& r = vec; for (auto iter = begin(r), end_iter = end(r); iter != end_iter; ++iter) { iter->member = 42; // Check for mutability } EQUAL_RANGE(r, (il<Elt>({ {42}, { 42 }, { 42 }, { 42 }, { 42 } }))); for (auto&& elt : r) { static_assert(test::is_reference_v<decltype(elt)>, "elt is expected to be a reference"); elt.member = 78; // Check for mutability } EQUAL_RANGE(r, (il<Elt>({ {78}, { 78 }, { 78 }, { 78 }, { 78 } }))); } { std::vector<int> vec(5); for (int& i : vec | rah::view::transform([](int& i) ->int& {return i;})) i = 42; // Check for mutability EQUAL_RANGE(vec, (il<int>({ 42, 42, 42, 42, 42 }))); } // Test return non-reference { std::vector<int> constVect{ 0, 1, 2, 3 }; EQUAL_RANGE( constVect | transform([](auto a) {return a * 2; }), il<int>({ 0, 2, 4, 6 }) ); std::vector<Elt> vec = { {1} }; auto r_copy = vec | transform([](auto a) {return Elt{ a.member + 1 }; }); for (auto iter = begin(r_copy), end_iter = end(r_copy); iter != end_iter; ++iter) { assert(iter->member == 2); // Check for mutability assert((*iter).member == 2); // Check for mutability static_assert(test::is_rvalue_reference_v<decltype(*iter)> || (not test::is_reference_v<decltype(*iter)>), "*iter is not expected to be a reference"); } for (auto&& elt : r_copy) { assert(elt.member == 2); // Check for mutability static_assert(test::is_rvalue_reference_v<decltype(elt)> || (not test::is_reference_v<decltype(elt)>), "elt is not expected to be a reference"); } auto r_ref = vec | transform([](auto a) {return a.member; }); for (auto iter = begin(r_ref), end_iter = end(r_ref); iter != end_iter; ++iter) { assert(*iter == 1); // Check for mutability static_assert(test::is_rvalue_reference_v<decltype(*iter)> || (not test::is_reference_v<decltype(*iter)>), "*iter is not expected to be a reference"); } for (auto&& elt : r_ref) { assert(elt == 1); // Check for mutability static_assert(test::is_rvalue_reference_v<decltype(elt)> || (not test::is_reference_v<decltype(elt)>), "elt is not expected to be a reference"); } } // **************************** divers compination test *************************************** { auto genRange = [](size_t i) {return rah::view::zip(rah::view::repeat(i), rah::view::iota<size_t>(0, 3)); }; auto globalRange = rah::view::iota<size_t>(0, 4) | rah::view::transform(genRange) | rah::view::join(); EQUAL_RANGE(globalRange, (il<std::pair<size_t, size_t>>{ {0, 0}, { 0, 1 }, { 0, 2 }, {1, 0}, { 1, 1 }, { 1, 2 }, {2, 0}, { 2, 1 }, { 2, 2 }, {3, 0}, { 3, 1 }, { 3, 2 } })); } EQUAL_RANGE( (iota(0, 3) | transform([](auto i) {return i * 2; }) | enumerate()), (il<std::pair<size_t, int>>{ {0, 0}, { 1, 2 }, { 2, 4 } }) ); std::vector<char> vec_abcd{ 'a', 'b', 'c', 'd' }; EQUAL_RANGE( (vec_abcd | transform([](char i) {return i + 1; }) | enumerate()), (il<std::pair<size_t, char>>{ {0, 'b'}, { 1, 'c' }, { 2, 'd' }, { 3, 'e' } }) ); EQUAL_RANGE( (iota(0, 3000, 3) | transform([](auto i) {return i * 2; }) | enumerate() | slice(10, 13)), (il<std::pair<size_t, int>>{ {10, 60}, { 11, 66 }, { 12, 72 } }) ); EQUAL_RANGE( (zip(vec_abcd, iota(0, 4))), (il<std::tuple<char, int>>{ {'a', 0}, { 'b', 1 }, { 'c', 2 }, { 'd', 3 } }) ); EQUAL_RANGE( (iota(0, 100) | slice(0, 20) | stride(3)), (il<int>{0, 3, 6, 9, 12, 15, 18}) ); EQUAL_RANGE( (iota(10, 15) | reverse()), (il<int>{14, 13, 12, 11, 10}) ); EQUAL_RANGE( (iota(0, 100) | slice(10, 15) | reverse()), (il<int>{14, 13, 12, 11, 10}) ); EQUAL_RANGE( (iota(10, 15) | enumerate() | reverse()), (il<std::tuple<size_t, int>>{ {4, 14}, { 3, 13 }, { 2, 12 }, { 1, 11 }, { 0, 10 }}) ); EQUAL_RANGE( (iota(0, 100) | enumerate() | slice(10, 15)), (il<std::tuple<size_t, int>>{ {10, 10}, { 11, 11 }, { 12, 12 }, { 13, 13 }, { 14, 14 } }) ); EQUAL_RANGE( (iota(0, 100) | enumerate() | slice(10, 15) | reverse()), (il<std::tuple<size_t, int>>{ {14, 14}, { 13, 13 }, { 12, 12 }, { 11, 11 }, { 10, 10 } }) ); EQUAL_RANGE( // test slice in bidirectional iterator (iota(0, 10) | filter([](int i) {return i % 2 == 0; }) | slice(1, End - 1)), (il<int>{ 2, 4, 6 }) ); { // Can't compile because generate_n create a forward iterator range // int y = 1; // EQUAL_RANGE( // test slice in forward iterator // (rah::view::generate_n(4, [&y]() mutable { auto prev = y; y *= 2; return prev; }) | slice(1, End - 1)), // (il<int>{ 2, 4 }) // ); } { // Test creation of a custom iterator auto gen = customGenerate(); std::vector<int> gen_copy; std::copy(begin(gen), end(gen), std::back_inserter(gen_copy)); EQUAL_RANGE(gen_copy, il<int>({ 1, 2, 4, 8 })); } { using namespace rah; using namespace rah::view; int const width = 5; int const height = 6; int const start = 8; int startX = start % width; int startY = start / width; int const end = 22; int endX = end % width; int endY = end / width; auto getRangeX = [=](int y) { if (y == startY) return std::make_tuple(y, ints(startX, width)); else if (y == endY) return std::make_tuple(y, ints(0, endX)); else return std::make_tuple(y, ints(0, width)); }; std::vector<std::atomic<int>> test(width * height); auto updateRaw = [&](auto&& y_xRange) { auto y = std::get<0>(y_xRange); auto xRange = std::get<1>(y_xRange); for (int x : xRange) ++test[x + y * width]; }; for (int ySelector : ints(0, 3)) { auto range = iota(startY + ySelector, endY + 1, 3) | transform(getRangeX); rah::for_each(range, updateRaw); } assert(all_of(test | slice(0, start), [](auto&& val) {return val == 0; })); assert(all_of(test | slice(start, end), [](auto&& val) {return val == 1; })); assert(all_of(test | slice(end, rah::End), [](auto&& val) {return val == 0; })); } std::cout << "ALL TEST OK" << std::endl; return 0; } <file_sep>/README.md # rah **rah** is **ra**nge, **h**eader-only, "single-file" C++14/17 library. ## What is a range library? A range is anything that can be iterated. Typically in C++ something is a range if we can call `begin(range)` and `end(range)` on it. A range library allows to create ranges and algorithms using them. ## Why a new range library? Yes there are some great range libraries in C++, like [range-v3](https://github.com/ericniebler/range-v3) and [boost::range](http://www.boost.org/doc/libs/1_70_0/libs/range). **rah** is not as complete as those libraries, but the goal of **rah** is to be "single file" and easy to integrate, read and understand. **rah** was designed with code simplicity as top priority. ## What is inside rah - Namespace `rah` contains a subset of usual algorithms present in `<algorithm>`, but useable in a range fashion - More algorithms will be added soon ```cpp // Usual code with STL std::cout << std::count(range.begin(), range.end(), 2); // Using range algorithm std::cout << rah::count(range, 2); ``` - `rah::view` contains functions to create ranges, actually doing work only when iterated (lazy), saving some memory and simplifying the code, especially when wanting to chain algorithms. ```cpp // Usual code with STL std::vector<int> ints; ints.resize(10); std::iota(range.begin(), range.end(), 0); std::vector<int> even; std::copy_if(ints.begin(), ints.end(), std::back_inserter(even), [](int a) {return a % 2 == 0;}); std::vector<int> values; std::transform(even.begin(), even.end(), std::back_inserter(values), [](int a) {return a * 2;}); for(int i: values) std::cout << i << std::endl; // Using range algorithms auto values = rah::view::transform( rah::view::filter( rah::view::iota(0, 10), [](int a) {return a % 2 == 0;}) [](int a) {return a * 2;}); for(int i: values) // The job in done here, without memory allocation std::cout << i << std::endl; ``` - Most of views have a *pipeable* version, making theme easier to write and read. ```cpp // Using pipeable range algorithms auto values = rah::view::iota(0, 10) | rah::view::filter([](int a) {return a % 2 == 0;}) | rah::view::transform([](int a) {return a * 2;}); for(int i: values) // The job in done here, without memory allocation std::cout << i << std::endl; ``` ## License rah is licensed under the [Boost Software License](http://www.boost.org/LICENSE_1_0.txt) ## Documentation You can find the doc [here](https://lhamot.github.io/rah/html/index.html) ## Supported Compilers - On Windows - Visual Studio 2015 (stdcpp14) - Visual Studio 2017 (stdcpp14 and stdcpp17) - clang 7 (-std=c++14 and -std=c++17) - On Linux - clang 4 and 5 (-std=c++14 and -std=c++17) - gcc 7,8 and 9 (-std=c++14 and -std=c++17) ## Continuous integration ### Linux [![Build Status](https://travis-ci.org/lhamot/rah.svg?branch=master)](https://travis-ci.org/lhamot/rah) ### Windows [![Build status](https://ci.appveyor.com/api/projects/status/kn9yeci2isl6njla/branch/master?svg=true)](https://ci.appveyor.com/project/lhamot/rah/branch/master) ## How to use? - Just include the `rah.hpp` file in your project - range version of STL algorithms are in the **rah** namespace - Views are in **rah::view** namespace - Read the [doc](https://lhamot.github.io/rah/html/index.html) ## The future of **rah** - Wrap more std algorithms - Add more ranges <file_sep>/rah/rah.hpp // // Copyright (c) 2019 <NAME> // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include <cassert> #include <ciso646> #ifndef RAH_DONT_USE_STD #ifdef MSVC #pragma warning(push, 0) #endif #include <type_traits> #include <iterator> #include <tuple> #include <algorithm> #include <numeric> #include <vector> #include <array> #ifdef MSVC #pragma warning(pop) #endif #ifndef RAH_STD #define RAH_STD std #endif #else #include "rah_custom_std.hpp" #endif #ifndef RAH_NAMESPACE #define RAH_NAMESPACE rah #endif namespace RAH_STD { template<class T, std::size_t Extent> class span; } namespace RAH_NAMESPACE { constexpr intptr_t End = -1; ///< Used with rah::view::slice to point to the end // **************************** range traits ****************************************************** template<class T, size_t N> T* begin(T(&array)[N]) { return (T*)array; } template<class T, size_t N> T* end(T(&array)[N]) noexcept { return array + N; } template<typename Container, typename Check = int> struct has_member_begin_end { static constexpr bool value = false; }; template<typename Container> struct has_member_begin_end< Container, decltype( std::declval<Container>().begin(), std::declval<Container>().end(), 0)> { static constexpr bool value = true; }; template< class T > constexpr bool has_member_begin_end_v = has_member_begin_end<T>::value; template<typename Container, typename Check = int> struct has_free_begin_end { static constexpr bool value = false; }; template<typename Container> struct has_free_begin_end< Container, decltype( begin(std::declval<Container>()), end(std::declval<Container>()), 0)> { static constexpr bool value = true; }; template< class T > constexpr bool has_free_begin_end_v = has_free_begin_end<T>::value; template<class T, size_t N> T* rah_begin(T(&array)[N]) { return (T*)array; } template<class T, size_t N> T* rah_end(T(&array)[N]) noexcept { return array + N; } /// Call the member begin if it exists /// This avoid some ADL fail when using conteners with mixed namespaces template<class Container, std::enable_if_t<has_member_begin_end_v<Container>, int> = 0> auto rah_begin(Container&& container) { return container.begin(); } /// Call the member end if it exists template<class Container, std::enable_if_t<has_member_begin_end_v<Container>, int> = 0> auto rah_end(Container&& container) { return container.end(); } /// Call the free begin if there is no member begin template< class Container, std::enable_if_t<has_free_begin_end_v<Container> and not has_member_begin_end_v<Container>, int> = 0> auto rah_begin(Container&& container) { return begin(container); } /// Call the free end if there is no member end template< class Container, std::enable_if_t<has_free_begin_end_v<Container> and not has_member_begin_end_v<Container>, int> = 0> auto rah_end(Container&& container) { return end(container); } /// Used in decltype to get an instance of a type template<typename T> T& fake() { return *((RAH_STD::remove_reference_t<T>*)nullptr); } template<typename T> using range_begin_type_t = decltype(rah_begin(fake<T>())); template<typename T> using range_end_type_t = decltype(rah_end(fake<T>())); template<typename T> using range_ref_type_t = decltype(*rah_begin(fake<T>())); template<typename T> using range_value_type_t = RAH_STD::remove_reference_t<range_ref_type_t<T>>; template<typename R> using range_iter_categ_t = typename RAH_STD::iterator_traits<range_begin_type_t<R>>::iterator_category; template<typename R, typename = int> struct is_range { static constexpr bool value = false; }; template<typename R> struct is_range <R, decltype(rah_begin(fake<R>()), rah_end(fake<R>()), 0)> { static constexpr bool value = true; }; RAH_STD::output_iterator_tag get_common_iterator_tag(RAH_STD::output_iterator_tag, RAH_STD::output_iterator_tag); RAH_STD::forward_iterator_tag get_common_iterator_tag(RAH_STD::forward_iterator_tag, RAH_STD::forward_iterator_tag); RAH_STD::bidirectional_iterator_tag get_common_iterator_tag(RAH_STD::bidirectional_iterator_tag, RAH_STD::bidirectional_iterator_tag); RAH_STD::random_access_iterator_tag get_common_iterator_tag(RAH_STD::random_access_iterator_tag, RAH_STD::random_access_iterator_tag); template<typename A, typename B> using common_iterator_tag = decltype(get_common_iterator_tag(A{}, B{})); // ******************************** iterator_range ************************************************ template<typename I> struct iterator_range { I begin_iter; I end_iter; I begin() const { return begin_iter; } I begin() { return begin_iter; } I end() const { return end_iter; } I end() { return end_iter; } }; template<typename I> auto make_iterator_range(I b, I e) { return iterator_range<I>{b, e}; } /// Get the begin iterator of the range template<typename I> I begin(iterator_range<I>& r) { return r.begin_iter; } /// Get the "past the" end iterator of the range template<typename I> I end(iterator_range<I>& r) { return r.end_iter; } /// Get the begin iterator of the range template<typename I> I begin(iterator_range<I> const& r) { return r.begin_iter; } /// Get the "past the" end iterator of the range template<typename I> I end(iterator_range<I> const& r) { return r.end_iter; } // **************************************** pipeable ********************************************** template<typename Func> struct pipeable { Func func; }; template<typename MakeRange> auto make_pipeable(MakeRange&& make_range) { return pipeable<MakeRange>{ make_range }; } template<typename R, typename MakeRange> auto operator | (R&& range, pipeable<MakeRange> const& adapter) ->decltype(adapter.func(RAH_STD::forward<R>(range))) { return adapter.func(RAH_STD::forward<R>(range)); } // ************************************ iterator_facade ******************************************* namespace details { // Small optional impl for C++14 compilers template<typename T> struct optional { optional() = default; optional(optional const& other) { if (other.has_value()) { new(getPtr()) T(other.get()); is_allocated_ = true; } } optional& operator = (optional const& other) { if (has_value()) { if (other.has_value()) { // Handle the case where T is not copy assignable reset(); new(getPtr()) T(other.get()); is_allocated_ = true; } else reset(); } else { if (other.has_value()) { new(getPtr()) T(other.get()); is_allocated_ = true; } } return *this; } optional& operator = (optional&& other) noexcept { if (has_value()) { if (other.has_value()) { // A lambda with const capture is not move assignable reset(); new(getPtr()) T(RAH_STD::move(other.get())); is_allocated_ = true; } else reset(); } else { if (other.has_value()) { new(getPtr()) T(RAH_STD::move(other.get())); is_allocated_ = true; } } return *this; } optional(T const& other) { new(getPtr()) T(other); is_allocated_ = true; } optional& operator=(T const& other) { reset(); new(getPtr()) T(other); is_allocated_ = true; return *this; } optional& operator=(T&& other) { reset(); new(getPtr()) T(RAH_STD::move(other)); is_allocated_ = true; return *this; } ~optional() { reset(); } bool has_value() const { return is_allocated_; } void reset() { if (is_allocated_) { destruct_value(); is_allocated_ = false; } } T& get() { assert(is_allocated_); return *getPtr(); } T const& get() const { assert(is_allocated_); return *getPtr(); } T& operator*() { return get(); } T const& operator*() const { return get(); } T* operator->() { assert(is_allocated_); return getPtr(); } T const* operator->() const { assert(is_allocated_); return getPtr(); } private: T* getPtr() { return (T*)&value_; } T const* getPtr() const { return (T const*)&value_; } void destruct_value() { get().~T(); } RAH_STD::aligned_storage_t<sizeof(T), RAH_STD::alignment_of<T>::value> value_{}; bool is_allocated_ = false; }; } template<typename I, typename R, typename C> struct iterator_facade; #define RAH_SELF (*static_cast<I*>(this)) #define RAH_SELF_CONST (*static_cast<I const*>(this)) template<typename I, typename R> struct iterator_facade<I, R, RAH_STD::forward_iterator_tag> { template <class Reference> struct pointer_type { using type = RAH_NAMESPACE::details::optional<Reference>; template<typename Ref> static type to_pointer(Ref&& ref) { return RAH_STD::forward<Ref>(ref); } }; template <class T> struct pointer_type<T&> // "real" references { using type = T*; template<typename Ref> static type to_pointer(Ref&& ref) { return &ref; } }; using iterator_category = RAH_STD::forward_iterator_tag; using value_type = RAH_STD::remove_reference_t<R>; using difference_type = intptr_t; using pointer = typename pointer_type<R>::type; using reference = R; static_assert(not RAH_STD::is_reference<value_type>::value, "value_type can't be a reference"); auto& operator++() { RAH_SELF.increment(); return *this; } reference operator*() const { static_assert(RAH_STD::is_same<decltype(RAH_SELF_CONST.dereference()), reference>::value, ""); return RAH_SELF_CONST.dereference(); } auto operator->() const { return pointer_type<R>::to_pointer(RAH_SELF_CONST.dereference()); } bool operator!=(I const& other) const { return not RAH_SELF_CONST.equal(other); } bool operator==(I const& other) const { return RAH_SELF_CONST.equal(other); } }; template<typename I, typename R> struct iterator_facade<I, R, RAH_STD::output_iterator_tag> { using iterator_category = RAH_STD::forward_iterator_tag; using value_type = RAH_STD::remove_reference_t<R>; using difference_type = intptr_t; using pointer = value_type*; using reference = R; static_assert(not RAH_STD::is_reference<value_type>::value, "value_type can't be a reference"); auto& operator++() { return *this; } auto& operator*() const { return *this; } bool operator!=(I const& other) const { return true; } bool operator==(I const& other) const { return false; } template<typename V> auto operator=(V&& value) const { RAH_SELF_CONST.put(RAH_STD::forward<V>(value)); return RAH_SELF_CONST; } }; template<typename I, typename R> struct iterator_facade<I, R, RAH_STD::bidirectional_iterator_tag> : iterator_facade<I, R, RAH_STD::forward_iterator_tag> { using iterator_category = RAH_STD::bidirectional_iterator_tag; auto& operator--() { RAH_SELF.decrement(); return *this; } }; template<typename I, typename R> struct iterator_facade<I, R, RAH_STD::random_access_iterator_tag> : iterator_facade<I, R, RAH_STD::bidirectional_iterator_tag> { using iterator_category = RAH_STD::random_access_iterator_tag; auto& operator+=(intptr_t increment) { RAH_SELF.advance(increment); return *this; } auto operator+(intptr_t increment) { auto iter = RAH_SELF; iter.advance(increment); return iter; } auto& operator-=(intptr_t increment) { RAH_SELF.advance(-increment); return *this; } auto operator-(intptr_t increment) { auto iter = RAH_SELF; iter.advance(-increment); return iter; } auto operator-(I const& other) const { return RAH_SELF_CONST.distance_to(other); } bool operator<(I const& other) const { return RAH_SELF_CONST.distance_to(other) < 0; } bool operator<=(I const& other) const { return RAH_SELF_CONST.distance_to(other) <= 0; } bool operator>(I const& other) const { return RAH_SELF_CONST.distance_to(other) > 0; } bool operator>=(I const& other) const { return RAH_SELF_CONST.distance_to(other) >= 0; } auto operator[](intptr_t increment) const { return *(RAH_SELF_CONST + increment); } }; #undef RAH_SELF #ifdef RAH_DONT_USE_STD // If rah is binded to an other standard library, learn to use std iterators anyway. template<typename I, typename R> struct iterator_facade<I, R, std::forward_iterator_tag> : iterator_facade<I, R, RAH_STD::forward_iterator_tag> {}; template<typename I, typename R> struct iterator_facade<I, R, std::output_iterator_tag> : iterator_facade<I, R, RAH_STD::output_iterator_tag> {}; template<typename I, typename R> struct iterator_facade<I, R, std::bidirectional_iterator_tag> : iterator_facade<I, R, RAH_STD::bidirectional_iterator_tag> {}; template<typename I, typename R> struct iterator_facade<I, R, std::random_access_iterator_tag> : iterator_facade<I, R, RAH_STD::random_access_iterator_tag> {}; #endif // ********************************** back_inserter *********************************************** /// @see rah::back_inserter template<typename C> struct back_insert_iterator : iterator_facade<back_insert_iterator<C>, range_ref_type_t<C>, RAH_STD::output_iterator_tag> { C* container_; back_insert_iterator(C& container) : container_(&container) { } template<typename V> void put(V&& value) const { container_->emplace_back(value); } }; /// @brief Make a range which insert into the back of the a container /// /// @snippet test.cpp rah::back_inserter template<typename C> auto back_inserter(C&& container) { using Container = RAH_STD::remove_reference_t<C>; auto begin = back_insert_iterator<Container>(container); auto end = back_insert_iterator<Container>(container); return RAH_NAMESPACE::make_iterator_range(begin, end); } // ********************************** inserter *********************************************** /// @see rah::back_inserter template<typename C> struct insert_iterator : iterator_facade<insert_iterator<C>, range_ref_type_t<C>, RAH_STD::output_iterator_tag> { C* container_; using Iterator = RAH_NAMESPACE::range_begin_type_t<C>; Iterator iter_; template<typename I> insert_iterator(C& container, I&& iter) : container_(&container), iter_(RAH_STD::forward<I>(iter)){ } template<typename V> void put(V&& value) const { container_->insert(iter_, value); } }; /// @brief Make a range which insert into the back of the a container /// /// @snippet test.cpp rah::back_inserter template<typename C, typename I> auto inserter(C&& container, I&& iter) { using Container = RAH_STD::remove_reference_t<C>; auto begin = insert_iterator<Container>(container, RAH_STD::forward<I>(iter)); auto end = insert_iterator<Container>(container, RAH_STD::forward<I>(iter)); return RAH_NAMESPACE::make_iterator_range(begin, end); } /// Apply the '<' operator on two values of any type struct is_lesser { template<typename A, typename B> bool operator()(A&& a, B&& b) { return a < b; } }; namespace view { // ********************************** all ********************************************************* template<typename R> auto all(R&& range) { static_assert(not RAH_STD::is_rvalue_reference_v<R&&>, "Can't call 'all' on a rvalue container"); return iterator_range<range_begin_type_t<R>>{rah_begin(range), rah_end(range)}; } template<typename I> auto all(std::initializer_list<I> range) { return iterator_range<decltype(rah_begin(range))>{rah_begin(range), rah_end(range)}; } template<typename I, std::size_t E> auto all(RAH_STD::span<I, E>&& range) { return iterator_range<decltype(rah_begin(range))>{rah_begin(range), rah_end(range)}; } template<typename I> auto all(iterator_range<I>&& range) -> decltype(std::move(range)) { return std::move(range); } template<typename I> iterator_range<I> const& all(iterator_range<I> const& range) { return range; } inline auto all() { return make_pipeable([=](auto&& range) { return all(RAH_STD::forward<decltype(range)>(range)); }); } // ******************************************* take *********************************************** template<typename I> struct take_iterator : iterator_facade< take_iterator<I>, decltype(*fake<I>()), typename RAH_STD::iterator_traits<I>::iterator_category > { I iter_; size_t count_ = size_t(); take_iterator() = default; take_iterator(I iter, size_t count) : iter_(iter), count_(count) {} void increment() { ++iter_; ++count_; } void advance(intptr_t off) { iter_ += off; count_ += off; } void decrement() { --iter_; --count_; } auto distance_to(take_iterator const& r) const { return RAH_STD::min<intptr_t>(iter_ - r.iter_, count_ - r.count_); } auto dereference() const -> decltype(*iter_) { return *iter_; } bool equal(take_iterator const& r) const { return count_ == r.count_ || iter_ == r.iter_; } }; template<typename R> auto take(R&& range, size_t count) { using iterator = take_iterator<range_begin_type_t<R>>; auto view = all(RAH_STD::forward<R>(range)); iterator iter1(rah_begin(view), 0); iterator iter2(rah_end(view), count); return make_iterator_range(iter1, iter2); } inline auto take(size_t count) { return make_pipeable([=](auto&& range) { return take(RAH_STD::forward<decltype(range)>(range), count); }); } // ******************************************* sliding ******************************************** template<typename I> struct sliding_iterator : iterator_facade< sliding_iterator<I>, iterator_range<I>, typename RAH_STD::iterator_traits<I>::iterator_category > { // Actually store a closed range [begin, last] // to avoid to exceed the end iterator of the underlying range I subRangeBegin_; I subRangeLast_; sliding_iterator() = default; sliding_iterator(I subRangeBegin, I subRangeLast) : subRangeBegin_(subRangeBegin) , subRangeLast_(subRangeLast) { } void increment() { ++subRangeBegin_; ++subRangeLast_; } void advance(intptr_t off) { subRangeBegin_ += off; subRangeLast_ += off; } void decrement() { --subRangeBegin_; --subRangeLast_; } auto distance_to(sliding_iterator const& r) const { return subRangeBegin_ - r.subRangeBegin_; } auto dereference() const { I endIter = subRangeLast_; ++endIter; return make_iterator_range(subRangeBegin_, endIter); } bool equal(sliding_iterator const& r) const { return subRangeBegin_ == r.subRangeBegin_; } }; template<typename R> auto sliding(R&& range, size_t n) { size_t const closedSubRangeSize = n - 1; auto view = all(RAH_STD::forward<R>(range)); auto const rangeEnd = rah_end(view); using iterator = sliding_iterator<range_begin_type_t<R>>; auto subRangeBegin = rah_begin(view); auto subRangeLast = subRangeBegin; for (size_t i = 0; i != closedSubRangeSize; ++i) { if (subRangeLast == rangeEnd) return make_iterator_range(iterator(rangeEnd, rangeEnd), iterator(rangeEnd, rangeEnd)); ++subRangeLast; } auto endSubRangeBegin = rangeEnd; RAH_STD::advance(endSubRangeBegin, -intptr_t(n - 1)); iterator iter1(subRangeBegin, subRangeLast); iterator iter2(endSubRangeBegin, rangeEnd); return make_iterator_range(iter1, iter2); } inline auto sliding(size_t n) { return make_pipeable([=](auto&& range) { return sliding(RAH_STD::forward<decltype(range)>(range), n); }); } // ******************************************* drop_exactly *************************************** template<typename R> auto drop_exactly(R&& range, size_t count) { auto view = all(RAH_STD::forward<R>(range)); auto iter1 = rah_begin(view); auto iter2 = rah_end(view); RAH_STD::advance(iter1, count); return make_iterator_range(iter1, iter2); } inline auto drop_exactly(size_t count) { return make_pipeable([=](auto&& range) { return drop_exactly(RAH_STD::forward<decltype(range)>(range), count); }); } // ******************************************* drop *********************************************** template<typename R> auto drop(R&& range, size_t count) { auto view = all(RAH_STD::forward<R>(range)); auto iter1 = rah_begin(view); auto iter2 = rah_end(view); for(size_t i = 0; i < count; ++i) { if (iter1 == iter2) break; ++iter1; } return make_iterator_range(iter1, iter2); } inline auto drop(size_t count) { return make_pipeable([=](auto&& range) { return drop(RAH_STD::forward<decltype(range)>(range), count); }); } // ******************************************* counted ******************************************** template<typename I> struct counted_iterator : iterator_facade< counted_iterator<I>, decltype(*fake<I>()), typename RAH_STD::iterator_traits<I>::iterator_category > { I iter_; size_t count_ = size_t(); counted_iterator() = default; counted_iterator(I iter, size_t count) : iter_(iter), count_(count) {} void increment() { ++iter_; ++count_; } void advance(intptr_t off) { iter_ += off; count_ += off; } void decrement() { --iter_; --count_; } auto distance_to(counted_iterator const& r) const { return count_ - r.count_; } auto dereference() const -> decltype(*iter_) { return *iter_; } bool equal(counted_iterator const& r) const { return count_ == r.count_; } }; template<typename I> auto counted(I&& it, size_t n, decltype(++it, 0) = 0) { using iterator = counted_iterator<RAH_STD::remove_reference_t<I>>; iterator iter1(it, 0); iterator iter2(it, n); return make_iterator_range(iter1, iter2); } /// @cond // Obsolete template<typename R> auto counted(R&& range, size_t n, decltype(rah_begin(range), 0) = 0) { return take(range, n); } inline auto counted(size_t n) { return make_pipeable([=](auto&& range) { return take(RAH_STD::forward<decltype(range)>(range), n); }); } /// @endcond // ******************************************* unbounded ****************************************** template<typename I> struct unbounded_iterator : iterator_facade< unbounded_iterator<I>, decltype(*fake<I>()), typename RAH_STD::iterator_traits<I>::iterator_category > { I iter_; bool end_; unbounded_iterator() = default; unbounded_iterator(I iter, bool end) : iter_(iter), end_(end) {} void increment() { ++iter_; } void advance(intptr_t off) { iter_ += off; } void decrement() { --iter_; } auto distance_to(unbounded_iterator const& r) const { if (end_) { if (r.end_) return intptr_t{}; else return RAH_STD::numeric_limits<intptr_t>::min(); } else { if (r.end_) return RAH_STD::numeric_limits<intptr_t>::max(); else return iter_ - r.iter_; } } auto dereference() const -> decltype(*iter_) { return *iter_; } bool equal(unbounded_iterator const& r) const { return end_? r.end_: (r.end_? false: r.iter_ == iter_); } }; template<typename I> auto unbounded(I&& it) { using iterator = unbounded_iterator<RAH_STD::remove_reference_t<I>>; iterator iter1(it, false); iterator iter2(it, true); return make_iterator_range(iter1, iter2); } // ********************************** ints ******************************************************** /// @see rah::ints template<typename T = size_t> struct ints_iterator : iterator_facade<ints_iterator<T>, T, RAH_STD::random_access_iterator_tag> { T val_ = T(); ints_iterator() = default; ints_iterator(T val) : val_(val) {} void increment() { ++val_; } void advance(intptr_t value) { val_ += T(value); } void decrement() { --val_; } auto distance_to(ints_iterator const& other) const { return (val_ - other.val_); } auto dereference() const { return val_; } bool equal(ints_iterator const& other) const { return val_ == other.val_; } }; template<typename T = size_t> auto ints(T b = 0, T e = RAH_STD::numeric_limits<T>::max()) { return iterator_range<ints_iterator<T>>{ b, e}; } template<typename T = size_t> auto closed_ints(T b = 0, T e = RAH_STD::numeric_limits<T>::max() - 1) { return iterator_range<ints_iterator<T>>{ b, e + 1}; } // ********************************** iota ******************************************************** /// @see rah::iota template<typename T = size_t> struct iota_iterator : iterator_facade<iota_iterator<T>, T, RAH_STD::random_access_iterator_tag> { T val_ = T(); T step_ = T(1); iota_iterator() = default; iota_iterator(T val, T step) : val_(val), step_(step) {} void increment() { val_ += step_; } void advance(intptr_t value) { val_ += T(step_ * value); } void decrement() { val_ -= step_; } auto distance_to(iota_iterator const& other) const { return (val_ - other.val_) / step_; } auto dereference() const { return val_; } bool equal(iota_iterator const& other) const { return val_ == other.val_; } }; template<typename T = size_t> auto iota(T b, T e, T step = 1) { assert(step != 0); auto diff = (e - b); diff = ((diff + (step - 1)) / step) * step; return iterator_range<iota_iterator<T>>{ { b, step}, { b + diff, step }}; } // ********************************** repeat ****************************************************** /// @see rah::repeat template<typename V> struct repeat_iterator : iterator_facade<repeat_iterator<V>, V const&, RAH_STD::forward_iterator_tag> { V val_ = V(); repeat_iterator() = default; template<typename U> repeat_iterator(U val) : val_(RAH_STD::forward<U>(val)) {} void increment() { } void advance(intptr_t value) { } void decrement() { } V const& dereference() const { return val_; } bool equal(repeat_iterator const&) const { return false; } }; template<typename V> auto repeat(V&& value) { return iterator_range<repeat_iterator<RAH_STD::remove_const_t<RAH_STD::remove_reference_t<V>>>>{ { value}, { value }}; } // ********************************** join ******************************************************** template<typename R> struct join_iterator : iterator_facade<join_iterator<R>, range_ref_type_t<range_ref_type_t<R>>, RAH_STD::forward_iterator_tag> { using Iterator1 = range_begin_type_t<R>; using SubRangeType = RAH_STD::remove_reference_t<decltype(all(*fake<Iterator1>()))>; using Iterator2 = range_begin_type_t<decltype(*fake<Iterator1>())>; Iterator1 rangeIter_; Iterator1 rangeEnd_; Iterator2 subRangeIter; Iterator2 subRangeEnd; join_iterator() = default; template<typename SR> join_iterator(Iterator1 rangeIter, Iterator1 rangeEnd, SR&& subRange) : rangeIter_(rangeIter) , rangeEnd_(rangeEnd) , subRangeIter(rah_begin(subRange)) , subRangeEnd(rah_end(subRange)) { if (rangeIter_ == rangeEnd_) return; next_valid(); } join_iterator(Iterator1 rangeIter, Iterator1 rangeEnd) : rangeIter_(rangeIter) , rangeEnd_(rangeEnd) { } void next_valid() { while (subRangeIter == subRangeEnd) { ++rangeIter_; if (rangeIter_ == rangeEnd_) return; else { auto view = all(*rangeIter_); subRangeIter = rah_begin(view); subRangeEnd = rah_end(view); } } } void increment() { ++subRangeIter; next_valid(); } auto dereference() const ->decltype(*subRangeIter) { return *subRangeIter; } bool equal(join_iterator const& other) const { if (rangeIter_ == rangeEnd_) return rangeIter_ == other.rangeIter_; else return rangeIter_ == other.rangeIter_ && subRangeIter == other.subRangeIter; } }; template<typename R> auto join(R&& range_of_ranges) { auto rangeRef = RAH_NAMESPACE::view::all(range_of_ranges); using join_iterator_type = join_iterator<decltype(rangeRef)>; auto rangeBegin = rah_begin(rangeRef); auto rangeEnd = rah_end(rangeRef); if (empty(rangeRef)) { join_iterator_type b(rangeBegin, rangeEnd); join_iterator_type e(rangeEnd, rangeEnd); return make_iterator_range(b, e); } else { auto firstSubRange = all(*rangeBegin); join_iterator_type b( rangeBegin, rangeEnd, RAH_STD::forward<decltype(firstSubRange)>(firstSubRange)); join_iterator_type e(rangeEnd, rangeEnd); return make_iterator_range(b, e); } } inline auto join() { return make_pipeable([](auto&& range) {return join(range); }); } // ********************************** cycle ******************************************************** template<typename R> struct cycle_iterator : iterator_facade< cycle_iterator<R>, range_ref_type_t<R>, common_iterator_tag<RAH_STD::bidirectional_iterator_tag, range_iter_categ_t<R>>> { R range_; using Iterator = range_begin_type_t<R>; Iterator beginIter_; Iterator endIter_; Iterator iter_; int64_t cycleIndex_; cycle_iterator() = default; template<typename U> explicit cycle_iterator(U&& range, Iterator iter, int64_t cycleIndex) : range_(RAH_STD::forward<U>(range)) , beginIter_(rah_begin(range_)) , endIter_(rah_end(range_)) , iter_(iter) , cycleIndex_(cycleIndex) { } void increment() { ++iter_; while (iter_ == endIter_) { iter_ = rah_begin(range_); ++cycleIndex_; } } void decrement() { while (iter_ == beginIter_) { iter_ = rah_end(range_); --cycleIndex_; } --iter_; } auto dereference() const ->decltype(*iter_) { return *iter_; } bool equal(cycle_iterator const& other) const { return cycleIndex_ == other.cycleIndex_ and iter_ == other.iter_; } }; template<typename R> auto cycle(R&& range) { auto rangeRef = range | RAH_NAMESPACE::view::all(); using iterator_type = cycle_iterator<RAH_STD::remove_reference_t<decltype(rangeRef)>>; auto view = all(RAH_STD::forward<R>(range)); iterator_type beginIter(rangeRef, rah_begin(view), 0); iterator_type endIter(rangeRef, rah_end(view), -1); return make_iterator_range(beginIter, endIter); } inline auto cycle() { return make_pipeable([](auto&& range) {return cycle(range); }); } // ********************************** generate **************************************************** /// @see rah::generate template<typename F> struct generate_iterator : iterator_facade<generate_iterator<F>, decltype(fake<F>()()), RAH_STD::forward_iterator_tag> { mutable RAH_NAMESPACE::details::optional<F> func_; generate_iterator() = default; generate_iterator(F const& func) : func_(func) {} void increment() { } auto dereference() const { return (*func_)(); } bool equal(generate_iterator const&) const { return false; } }; template<typename F> auto generate(F&& func) { using Functor = RAH_STD::remove_cv_t<RAH_STD::remove_reference_t<F>>; return iterator_range<generate_iterator<Functor>>{ { func}, { func }}; } template<typename F> auto generate_n(size_t count, F&& func) { return generate(RAH_STD::forward<F>(func)) | take(count); } // ******************************************* transform ****************************************** template<typename R, typename F> struct transform_iterator : iterator_facade< transform_iterator<R, F>, decltype(fake<F>()(fake<range_ref_type_t<R>>())), range_iter_categ_t<R> > { range_begin_type_t<R> iter_; RAH_NAMESPACE::details::optional<F> func_; transform_iterator() = default; transform_iterator(range_begin_type_t<R> const& iter, F const& func) : iter_(iter), func_(func) {} void increment() { ++iter_; } void advance(intptr_t off) { iter_ += off; } void decrement() { --iter_; } auto distance_to(transform_iterator const& r) const { return iter_ - r.iter_; } auto dereference() const -> decltype((*func_)(*iter_)) { return (*func_)(*iter_); } bool equal(transform_iterator const& r) const { return iter_ == r.iter_; } }; template<typename R, typename F> auto transform(R&& range, F&& func) { using Functor = RAH_STD::remove_cv_t<RAH_STD::remove_reference_t<F>>; using iterator = transform_iterator<RAH_STD::remove_reference_t<R>, Functor>; auto view = all(RAH_STD::forward<R>(range)); auto iter1 = rah_begin(view); auto iter2 = rah_end(view); return iterator_range<iterator>{ { iter1, func }, { iter2, func } }; } template<typename F> auto transform(F&& func) { return make_pipeable([=](auto&& range) { return transform(RAH_STD::forward<decltype(range)>(range), func); }); } // ******************************************* set_difference ************************************* template<typename InputIt1, typename InputIt2> struct set_difference_iterator : iterator_facade< set_difference_iterator<InputIt1, InputIt2>, typename RAH_STD::iterator_traits<InputIt1>::reference, RAH_STD::forward_iterator_tag > { InputIt1 first1_; InputIt1 last1_; InputIt2 first2_; InputIt2 last2_; set_difference_iterator() = default; set_difference_iterator(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) : first1_(first1) , last1_(last1) , first2_(first2), last2_(last2) { next_value(); } void next_value() { while (first2_ != last2_ and first1_ != last1_) { if (*first1_ < *first2_) break; else if (*first1_ == *first2_) { ++first1_; ++first2_; } else ++first2_; } } void increment() { ++first1_; next_value(); } auto dereference() const -> decltype(*first1_) { return *first1_; } bool equal(set_difference_iterator const& r) const { return first1_ == r.first1_; } }; template<typename R1, typename R2> auto set_difference(R1&& range1, R2&& range2) { using Iter1 = range_begin_type_t<R1>; using Iter2 = range_begin_type_t<R2>; using Iterator = set_difference_iterator<Iter1, Iter2>; auto view1 = all(RAH_STD::forward<R1>(range1)); auto view2 = all(RAH_STD::forward<R2>(range2)); return iterator_range<Iterator>{ { Iterator(rah_begin(view1), rah_end(view1), rah_begin(view2), rah_end(view2)) }, { Iterator(rah_end(view1), rah_end(view1), rah_end(view2), rah_end(view2)) }, }; } template<typename R2> auto set_difference(R2&& range2) { return make_pipeable([r2 = range2 | view::all()](auto&& range) {return set_difference(range, r2); }); } // ********************************** for_each **************************************************** template<typename R, typename F> auto for_each(R&& range, F&& func) { return range | RAH_NAMESPACE::view::transform(func) | RAH_NAMESPACE::view::join(); } template<typename F> inline auto for_each(F&& func) { return make_pipeable([=](auto&& range) { return RAH_NAMESPACE::view::for_each(RAH_STD::forward<decltype(range)>(range), func); }); } // ***************************************** slice ************************************************ template<typename R> auto slice(R&& range, intptr_t begin_idx, intptr_t end_idx) { static_assert(not RAH_STD::is_same<range_iter_categ_t<R>, RAH_STD::forward_iterator_tag>::value, "Can't use slice on non-bidirectional iterators. Try to use view::drop and view::take"); auto findIter = [](auto b, auto e, intptr_t idx) { if (idx < 0) { idx += 1; RAH_STD::advance(e, idx); return e; } else { RAH_STD::advance(b, idx); return b; } }; auto view = all(RAH_STD::forward<R>(range)); auto b_in = rah_begin(view); auto e_in = rah_end(view); auto b_out = findIter(b_in, e_in, begin_idx); auto e_out = findIter(b_in, e_in, end_idx); return iterator_range<decltype(b_out)>{ {b_out}, { e_out } }; } inline auto slice(intptr_t begin, intptr_t end) { return make_pipeable([=](auto&& range) { return slice(RAH_STD::forward<decltype(range)>(range), begin, end); }); } // ***************************************** stride *********************************************** template<typename R> struct stride_iterator : iterator_facade<stride_iterator<R>, range_ref_type_t<R>, range_iter_categ_t<R>> { range_begin_type_t<R> iter_; range_end_type_t<R> end_; size_t step_; stride_iterator() = default; stride_iterator(range_begin_type_t<R> const& iter, range_end_type_t<R> const& end, size_t step) : iter_(iter), end_(end), step_(step) {} auto increment() { for (size_t i = 0; i < step_ && iter_ != end_; ++i) ++iter_; } auto decrement() { for (size_t i = 0; i < step_; ++i) --iter_; } void advance(intptr_t value) { iter_ += step_ * value; } auto dereference() const -> decltype(*iter_) { return *iter_; } bool equal(stride_iterator const& other) const { return iter_ == other.iter_; } auto distance_to(stride_iterator const other) const { return (iter_ - other.iter_) / step_; } }; template<typename R> auto stride(R&& range, size_t step) { auto view = all(RAH_STD::forward<R>(range)); auto iter = rah_begin(view); auto endIter = rah_end(view); return iterator_range<stride_iterator<RAH_STD::remove_reference_t<R>>>{ { iter, endIter, step}, { endIter, endIter, step }}; } inline auto stride(size_t step) { return make_pipeable([=](auto&& range) { return stride(RAH_STD::forward<decltype(range)>(range), step); }); } // ***************************************** retro ************************************************ // Use reverse instead of retro template<typename R> [[deprecated]] auto retro(R&& range) { auto view = all(RAH_STD::forward<R>(range)); return make_iterator_range( RAH_STD::make_reverse_iterator(rah_end(view)), RAH_STD::make_reverse_iterator(rah_begin(view))); } // Use reverse instead of retro [[deprecated]] inline auto retro() { return make_pipeable([=](auto&& range) { return retro(RAH_STD::forward<decltype(range)>(range)); }); } // ***************************************** reverse ********************************************** template<typename R> auto reverse(R&& range) { auto view = all(RAH_STD::forward<R>(range)); return make_iterator_range( RAH_STD::make_reverse_iterator(rah_end(view)), RAH_STD::make_reverse_iterator(rah_begin(view))); } inline auto reverse() { return make_pipeable([=](auto&& range) { return reverse(RAH_STD::forward<decltype(range)>(range)); }); } // ********************************** single ****************************************************** template<typename V> auto single(V&& value) { return repeat(value) | take(1); } // *************************** zip **************************************************************** /// \cond PRIVATE namespace details { template <typename Tuple, typename F, size_t ...Indices> void for_each_impl(Tuple&& tuple, F&& f, RAH_STD::index_sequence<Indices...>) { using swallow = int[]; (void)swallow { 1, (f(RAH_STD::get<Indices>(RAH_STD::forward<Tuple>(tuple))), void(), int{})... }; } template <typename Tuple, typename F> void for_each(Tuple&& tuple, F&& f) { constexpr size_t N = RAH_STD::tuple_size<RAH_STD::remove_reference_t<Tuple>>::value; for_each_impl(RAH_STD::forward<Tuple>(tuple), RAH_STD::forward<F>(f), RAH_STD::make_index_sequence<N>{}); } template <class F, typename... Args, size_t... Is> auto transform_each_impl(const RAH_STD::tuple<Args...>& t, F&& f, RAH_STD::index_sequence<Is...>) { return RAH_STD::make_tuple( f(RAH_STD::get<Is>(t))... ); } template <class F, typename... Args> auto transform_each(const RAH_STD::tuple<Args...>& t, F&& f) { return transform_each_impl( t, RAH_STD::forward<F>(f), RAH_STD::make_index_sequence<sizeof...(Args)>{}); } template <typename... Args, size_t... Is> auto deref_impl(const RAH_STD::tuple<Args...>& t, RAH_STD::index_sequence<Is...>) { return RAH_STD::tuple<typename RAH_STD::iterator_traits<Args>::reference...>( (*RAH_STD::get<Is>(t))... ); } template <typename... Args> auto deref(const RAH_STD::tuple<Args...>& t) { return deref_impl(t, RAH_STD::make_index_sequence<sizeof...(Args)>{}); } template <size_t Index> struct Equal { template <typename... Args> bool operator()(RAH_STD::tuple<Args...> const& a, RAH_STD::tuple<Args...> const& b) const { return (RAH_STD::get<Index - 1>(a) == RAH_STD::get<Index - 1>(b)) || Equal<Index - 1>{}(a, b); } }; template<> struct Equal<0> { template <typename... Args> bool operator()(RAH_STD::tuple<Args...> const&, RAH_STD::tuple<Args...> const&) const { return false; } }; template <typename... Args> auto equal(RAH_STD::tuple<Args...> const& a, RAH_STD::tuple<Args...> const& b) { return Equal<sizeof...(Args)>{}(a, b); } } // namespace details /// \endcond template<typename IterTuple> struct zip_iterator : iterator_facade< zip_iterator<IterTuple>, decltype(details::deref(fake<IterTuple>())), RAH_STD::bidirectional_iterator_tag > { IterTuple iters_; zip_iterator() = default; zip_iterator(IterTuple const& iters) : iters_(iters) {} void increment() { details::for_each(iters_, [](auto& iter) { ++iter; }); } void advance(intptr_t val) { for_each(iters_, [val](auto& iter) { iter += val; }); } void decrement() { details::for_each(iters_, [](auto& iter) { --iter; }); } auto dereference() const { return details::deref(iters_); } auto distance_to(zip_iterator const& other) const { return RAH_STD::get<0>(iters_) - RAH_STD::get<0>(other.iters_); } bool equal(zip_iterator const& other) const { return details::equal(iters_, other.iters_); } }; template<typename ...R> auto zip(R&&... _ranges) { auto views = RAH_STD::make_tuple(all(RAH_STD::forward<R>(_ranges))...); auto iterTup = details::transform_each(views, [](auto&& v){ return rah_begin(v);}); auto endTup = details::transform_each(views, [](auto&& v){ return rah_end(v);}); return iterator_range<zip_iterator<decltype(iterTup)>>{ { iterTup }, { endTup }}; } // ************************************ chunk ***************************************************** template<typename R> struct chunk_iterator : iterator_facade<chunk_iterator<R>, iterator_range<range_begin_type_t<R>>, RAH_STD::forward_iterator_tag> { range_begin_type_t<R> iter_; range_begin_type_t<R> iter2_; range_end_type_t<R> end_; size_t step_; chunk_iterator() = default; chunk_iterator( range_begin_type_t<R> const& iter, range_begin_type_t<R> const& iter2, range_end_type_t<R> const& end, size_t step = 0) : iter_(iter), iter2_(iter2), end_(end), step_(step) { } void increment() { iter_ = iter2_; for (size_t i = 0; i != step_ and iter2_ != end_; ++i) ++iter2_; } auto dereference() const { return make_iterator_range(iter_, iter2_); } bool equal(chunk_iterator const& other) const { return iter_ == other.iter_; } }; template<typename R> auto chunk(R&& range, size_t step) { auto view = all(RAH_STD::forward<R>(range)); auto iter = rah_begin(view); auto endIter = rah_end(view); using iterator = chunk_iterator<RAH_STD::remove_reference_t<R>>; iterator begin = { iter, iter, endIter, step }; begin.increment(); return iterator_range<iterator>{ { begin }, { endIter, endIter, endIter, step }}; } inline auto chunk(size_t step) { return make_pipeable([=](auto&& range) { return chunk(RAH_STD::forward<decltype(range)>(range), step); }); } // ***************************************** filter *********************************************** template<typename R, typename F> struct filter_iterator : iterator_facade<filter_iterator<R, F>, range_ref_type_t<R>, RAH_STD::bidirectional_iterator_tag> { using Iterator = range_begin_type_t<R>; Iterator begin_; Iterator iter_; range_end_type_t<R> end_; RAH_NAMESPACE::details::optional<F> func_; typename RAH_STD::iterator_traits<range_begin_type_t<R>>::pointer value_pointer_; // Get a pointer to the pointed value, // OR a pointer to a copy of the pointed value (when not a reference iterator) template <class I> struct get_pointer { static auto get(I const& iter) { return iter.operator->(); } }; template <class V> struct get_pointer<V*> { static auto get(V* ptr) { return ptr; } }; filter_iterator() = default; filter_iterator( range_begin_type_t<R> const& begin, range_begin_type_t<R> const& iter, range_end_type_t<R> const& end, F func) : begin_(begin), iter_(iter), end_(end), func_(func) { next_value(); } void next_value() { while (iter_ != end_ && not (*func_)(*(value_pointer_ = get_pointer<Iterator>::get(iter_)))) { assert(iter_ != end_); ++iter_; } } void increment() { ++iter_; next_value(); } void decrement() { do { --iter_; } while (not (*func_)(*iter_) && iter_ != begin_); } auto dereference() const -> decltype(*iter_) { return *value_pointer_; } bool equal(filter_iterator const& other) const { return iter_ == other.iter_; } }; template<typename R, typename P> auto filter(R&& range, P&& pred) { auto view = all(RAH_STD::forward<R>(range)); auto iter = rah_begin(view); auto endIter = rah_end(view); using Predicate = RAH_STD::remove_cv_t<RAH_STD::remove_reference_t<P>>; return iterator_range<filter_iterator<RAH_STD::remove_reference_t<R>, Predicate>>{ { iter, iter, endIter, pred }, { iter, endIter, endIter, pred } }; } template<typename P> auto filter(P&& pred) { return make_pipeable([=](auto&& range) { return filter(RAH_STD::forward<decltype(range)>(range), pred); }); } // ***************************************** concat *********************************************** template<typename IterPair, typename V> struct concat_iterator : iterator_facade<concat_iterator<IterPair, V>, V, RAH_STD::forward_iterator_tag> { IterPair iter_; IterPair end_; size_t range_index_; concat_iterator() = default; concat_iterator(IterPair const& iter, IterPair const& end, size_t range_index) : iter_(iter), end_(end), range_index_(range_index) { if (range_index == 0) { if(RAH_STD::get<0>(iter_) == RAH_STD::get<0>(end_)) range_index_ = 1; } } void increment() { if (range_index_ == 0) { auto& i = RAH_STD::get<0>(iter_); ++i; if (i == RAH_STD::get<0>(end_)) range_index_ = 1; } else ++RAH_STD::get<1>(iter_); } auto dereference() const -> decltype(*RAH_STD::get<0>(iter_)) { if (range_index_ == 0) return *RAH_STD::get<0>(iter_); else return *RAH_STD::get<1>(iter_); } bool equal(concat_iterator const& other) const { if (range_index_ != other.range_index_) return false; if (range_index_ == 0) return RAH_STD::get<0>(iter_) == RAH_STD::get<0>(other.iter_); else return RAH_STD::get<1>(iter_) == RAH_STD::get<1>(other.iter_); } }; /// @brief return the same range template<typename R1> auto concat(R1&& range1) { return RAH_STD::forward<R1>(range1); } template<typename R1, typename R2> auto concat(R1&& range1, R2&& range2) { auto view1 = all(RAH_STD::forward<R1>(range1)); auto view2 = all(RAH_STD::forward<R2>(range2)); auto begin_range1 = RAH_STD::make_pair(rah_begin(view1), rah_begin(view2)); auto begin_range2 = RAH_STD::make_pair(rah_end(view1), rah_end(view2)); auto end_range1 = RAH_STD::make_pair(rah_end(view1), rah_end(view2)); auto end_range2 = RAH_STD::make_pair(rah_end(view1), rah_end(view2)); return iterator_range< concat_iterator< RAH_STD::pair<range_begin_type_t<R1>, range_begin_type_t<R2>>, range_ref_type_t<R1>>> { { begin_range1, begin_range2, 0 }, { end_range1, end_range2, 1 }, }; } /// @see rah::view::concat(R1&& range1, R2&& range2) template<typename R1, typename R2, typename ...Ranges> auto concat(R1&& range1, R2&& range2, Ranges&&... ranges) { return concat(concat(RAH_STD::forward<R1>(range1), RAH_STD::forward<R2>(range2)), ranges...); } // *************************** enumerate ********************************************************** template<typename R> auto enumerate(R&& range) { auto view = all(RAH_STD::forward<R>(range)); size_t const dist = RAH_STD::distance(rah_begin(view), rah_end(view)); return zip(iota(size_t(0), dist), view); } inline auto enumerate() { return make_pipeable([=](auto&& range) { return enumerate(RAH_STD::forward<decltype(range)>(range)); }); } // ****************************** map_value ******************************************************** template<size_t I> struct get_tuple_elt { template<typename T> auto operator()(T&& nvp) const -> decltype(RAH_STD::get<I>(RAH_STD::forward<decltype(nvp)>(nvp))) { static_assert(not RAH_STD::is_rvalue_reference<decltype(nvp)>::value, "map_value/map_key only apply only apply on lvalue pairs. " "Pairs from map are ok but for generated pairs, prefer use view::tranform"); return RAH_STD::get<I>(RAH_STD::forward<decltype(nvp)>(nvp)); } }; template<typename R> auto map_value(R&& range) { return transform(RAH_STD::forward<R>(range), get_tuple_elt<1>{}); } inline auto map_value() { return make_pipeable([=](auto&& range) { return map_value(RAH_STD::forward<decltype(range)>(range)); }); } // ****************************** map_key ********************************************************** template<typename R> auto map_key(R&& range) { return RAH_NAMESPACE::view::transform(RAH_STD::forward<R>(range), get_tuple_elt<0>{}); } inline auto map_key() { return make_pipeable([=](auto&& range) { return map_key(RAH_STD::forward<decltype(range)>(range)); }); } // *********************************** sort ******************************************************* /// @brief Make a sorted view of a range /// @return A view that is sorted /// @remark This view is not lasy. The sorting is computed immediately. /// /// @snippet test.cpp rah::view::sort /// @snippet test.cpp rah::view::sort_pred template<typename R, typename P = is_lesser, typename = RAH_STD::enable_if_t<is_range<R>::value>> auto sort(R&& range, P&& pred = {}) { using value_type = range_value_type_t<R>; using Container = typename RAH_STD::vector<RAH_STD::remove_cv_t<value_type>>; Container result; auto view = all(RAH_STD::forward<R>(range)); result.reserve(RAH_STD::distance(rah_begin(view), rah_end(view))); RAH_STD::copy(rah_begin(view), rah_end(view), RAH_STD::back_inserter(result)); RAH_STD::sort(rah_begin(result), rah_end(result), pred); return result; } /// @brief Make a sorted view of a range /// @return A view that is sorted /// @remark This view is not lasy. The sorting is computed immediately. /// @remark pipeable syntax /// /// @snippet test.cpp rah::view::sort_pipeable /// @snippet test.cpp rah::view::sort_pred_pipeable template<typename P = is_lesser, typename = RAH_STD::enable_if_t<not is_range<P>::value>> auto sort(P&& pred = {}) { return make_pipeable([=](auto&& range) { return view::sort(RAH_STD::forward<decltype(range)>(range), pred); }); } } // namespace view // ****************************************** empty *********************************************** /// @brief Check if the range if empty /// /// @snippet test.cpp rah::empty template<typename R> bool empty(R&& range) { return rah_begin(range) == rah_end(range); } /// @brief Check if the range if empty /// @remark pipeable syntax /// /// @snippet test.cpp rah::empty_pipeable inline auto empty() { return make_pipeable([](auto&& range) {return empty(range); }); } // ****************************************** equal_range *********************************************** /// @brief Returns a range containing all elements equivalent to value in the range /// /// @snippet test.cpp rah::equal_range template<typename R, typename V> auto equal_range(R&& range, V&& value, RAH_STD::enable_if_t<is_range<R>::value, int> = 0) { auto view = view::all(RAH_STD::forward<R>(range)); auto pair = RAH_STD::equal_range(rah_begin(view), rah_end(view), RAH_STD::forward<V>(value)); return make_iterator_range(RAH_STD::get<0>(pair), RAH_STD::get<1>(pair)); } /// @brief Returns a range containing all elements equivalent to value in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::equal_range_pipeable template<typename V> auto equal_range(V&& value) { return make_pipeable([=](auto&& range) { return equal_range(RAH_STD::forward<decltype(range)>(range), value); }); } /// @brief Returns a range containing all elements equivalent to value in the range /// /// @snippet test.cpp rah::equal_range_pred_0 /// @snippet test.cpp rah::equal_range_pred template<typename R, typename V, typename P> auto equal_range(R&& range, V&& value, P&& pred) { auto view = view::all(RAH_STD::forward<R>(range)); auto pair = RAH_STD::equal_range(rah_begin(view), rah_end(view), RAH_STD::forward<V>(value), RAH_STD::forward<P>(pred)); return make_iterator_range(RAH_STD::get<0>(pair), RAH_STD::get<1>(pair)); } /// @brief Returns a range containing all elements equivalent to value in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::equal_range_pred_0 /// @snippet test.cpp rah::equal_range_pred_pipeable template<typename V, typename P> auto equal_range(V&& value, P&& pred, RAH_STD::enable_if_t<!is_range<V>::value, int> = 0) { return make_pipeable([=](auto&& range) { return equal_range(RAH_STD::forward<decltype(range)>(range), value, pred); }); } // ****************************************** binary_search *********************************************** /// @brief Checks if an element equivalent to value appears within the range /// /// @snippet test.cpp rah::binary_search template<typename R, typename V> auto binary_search(R&& range, V&& value) { return RAH_STD::binary_search(rah_begin(range), rah_end(range), RAH_STD::forward<V>(value)); } /// @brief Checks if an element equivalent to value appears within the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::binary_search_pipeable template<typename V> auto binary_search(V&& value) { return make_pipeable([=](auto&& range) { return binary_search(RAH_STD::forward<decltype(range)>(range), value); }); } // ****************************************** transform ******************************************* /// @brief Applies the given function unary_op to the range rangeIn and stores the result in the range rangeOut /// /// @snippet test.cpp rah::transform3 template<typename RI, typename RO, typename F> auto transform(RI&& rangeIn, RO&& rangeOut, F&& unary_op) { return RAH_STD::transform(rah_begin(rangeIn), rah_end(rangeIn), rah_begin(rangeOut), RAH_STD::forward<F>(unary_op)); } /// @brief The binary operation binary_op is applied to pairs of elements from two ranges /// /// @snippet test.cpp rah::transform4 template<typename RI1, typename RI2, typename RO, typename F> auto transform(RI1&& rangeIn1, RI2&& rangeIn2, RO&& rangeOut, F&& binary_op) { return RAH_STD::transform( rah_begin(rangeIn1), rah_end(rangeIn1), rah_begin(rangeIn2), rah_begin(rangeOut), RAH_STD::forward<F>(binary_op)); } // ********************************************* reduce ******************************************* /// @brief Executes a reducer function on each element of the range, resulting in a single output value /// /// @snippet test.cpp rah::reduce template<typename R, typename I, typename F> auto reduce(R&& range, I&& init, F&& reducer) { return RAH_STD::accumulate(rah_begin(range), rah_end(range), RAH_STD::forward<I>(init), RAH_STD::forward<F>(reducer)); } /// @brief Executes a reducer function on each element of the range, resulting in a single output value /// @remark pipeable syntax /// /// @snippet test.cpp rah::reduce_pipeable template<typename I, typename F> auto reduce(I&& init, F&& reducer) { return make_pipeable([=](auto&& range) { return reduce(RAH_STD::forward<decltype(range)>(range), init, reducer); }); } // ************************* any_of ******************************************* /// @brief Checks if unary predicate pred returns true for at least one element in the range /// /// @snippet test.cpp rah::any_of template<typename R, typename F> bool any_of(R&& range, F&& pred) { return RAH_STD::any_of(rah_begin(range), rah_end(range), RAH_STD::forward<F>(pred)); } /// @brief Checks if unary predicate pred returns true for at least one element in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::any_of_pipeable template<typename P> auto any_of(P&& pred) { return make_pipeable([=](auto&& range) { return any_of(RAH_STD::forward<decltype(range)>(range), pred); }); } // ************************* all_of ******************************************* /// @brief Checks if unary predicate pred returns true for all elements in the range /// /// @snippet test.cpp rah::all_of template<typename R, typename P> bool all_of(R&& range, P&& pred) { return RAH_STD::all_of(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Checks if unary predicate pred returns true for all elements in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::all_of_pipeable template<typename P> auto all_of(P&& pred) { return make_pipeable([=](auto&& range) { return all_of(RAH_STD::forward<decltype(range)>(range), pred); }); } // ************************* none_of ******************************************* /// @brief Checks if unary predicate pred returns true for no elements in the range /// /// @snippet test.cpp rah::none_of template<typename R, typename P> bool none_of(R&& range, P&& pred) { return RAH_STD::none_of(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Checks if unary predicate pred returns true for no elements in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::none_of_pipeable template<typename P> auto none_of(P&& pred) { return make_pipeable([=](auto&& range) { return none_of(RAH_STD::forward<decltype(range)>(range), pred); }); } // ************************* count **************************************************************** /// @brief Counts the elements that are equal to value /// /// @snippet test.cpp rah::count template<typename R, typename V> auto count(R&& range, V&& value) { return RAH_STD::count(rah_begin(range), rah_end(range), RAH_STD::forward<V>(value)); } /// @brief Counts the elements that are equal to value /// @remark pipeable syntax /// /// @snippet test.cpp rah::count_pipeable template<typename V> auto count(V&& value) { return make_pipeable([=](auto&& range) { return count(RAH_STD::forward<decltype(range)>(range), value); }); } /// @brief Counts elements for which predicate pred returns true /// @remark pipeable syntax /// /// @snippet test.cpp rah::count_if template<typename R, typename P> auto count_if(R&& range, P&& pred) { return RAH_STD::count_if(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Counts elements for which predicate pred returns true /// /// @snippet test.cpp rah::count_if_pipeable template<typename P> auto count_if(P&& pred) { return make_pipeable([=](auto&& range) { return count_if(RAH_STD::forward<decltype(range)>(range), pred); }); } // ************************* foreach ************************************************************** /// @brief Applies the given function func to each element of the range /// /// @snippet test.cpp rah::for_each template<typename R, typename F> auto for_each(R&& range, F&& func) { return ::RAH_STD::for_each(rah_begin(range), rah_end(range), RAH_STD::forward<F>(func)); } /// @brief Applies the given function func to each element of the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::for_each_pipeable template<typename F> auto for_each(F&& func) { return make_pipeable([=](auto&& range) { return for_each(RAH_STD::forward<decltype(range)>(range), func); }); } // ***************************** to_container ***************************************************** /// @brief Return a container of type C, filled with the content of range /// /// @snippet test.cpp rah::to_container template<typename C, typename R> auto to_container(R&& range) { return C(rah_begin(range), rah_end(range)); } /// @brief Return a container of type C, filled with the content of range /// @remark pipeable syntax /// /// @snippet test.cpp rah::to_container_pipeable template<typename C> auto to_container() { return make_pipeable([=](auto&& range) { return to_container<C>(RAH_STD::forward<decltype(range)>(range)); }); } // ************************* mismatch ************************************************************* /// @brief Finds the first position where two ranges differ /// /// @snippet test.cpp rah::mismatch template<typename R1, typename R2> auto mismatch(R1&& range1, R2&& range2) { return RAH_STD::mismatch(rah_begin(range1), rah_end(range1), rah_begin(range2), rah_end(range2)); } // ****************************************** find ************************************************ /// @brief Finds the first element equal to value /// /// @snippet test.cpp rah::find template<typename R, typename V> auto find(R&& range, V&& value) { return RAH_STD::find(rah_begin(range), rah_end(range), RAH_STD::forward<V>(value)); } /// @brief Finds the first element equal to value /// @remark pipeable syntax /// /// @snippet test.cpp rah::find_pipeable template<typename V> auto find(V&& value) { return make_pipeable([=](auto&& range) { return find(RAH_STD::forward<decltype(range)>(range), value); }); } /// @brief Finds the first element satisfying specific criteria /// /// @snippet test.cpp rah::find_if template<typename R, typename P> auto find_if(R&& range, P&& pred) { return RAH_STD::find_if(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Finds the first element satisfying specific criteria /// @remark pipeable syntax /// /// @snippet test.cpp rah::find_if_pipeable template<typename P> auto find_if(P&& pred) { return make_pipeable([=](auto&& range) { return find_if(RAH_STD::forward<decltype(range)>(range), pred); }); } /// @brief Finds the first element not satisfying specific criteria /// /// @snippet test.cpp rah::find_if_not template<typename R, typename P> auto find_if_not(R&& range, P&& pred) { return RAH_STD::find_if_not(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Finds the first element not satisfying specific criteria /// @remark pipeable syntax /// /// @snippet test.cpp rah::find_if_not_pipeable template<typename P> auto find_if_not(P&& pred) { return make_pipeable([=](auto&& range) { return find_if_not(RAH_STD::forward<decltype(range)>(range), pred); }); } // ************************************* max_element ********************************************** /// @brief Finds the greatest element in the range /// /// @snippet test.cpp rah::max_element template<typename R, RAH_STD::enable_if_t<is_range<R>::value, int> = 0> auto max_element(R&& range) { return RAH_STD::max_element(rah_begin(range), rah_end(range)); } /// @brief Finds the greatest element in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::max_element_pipeable inline auto max_element() { return make_pipeable([=](auto&& range) { return max_element(RAH_STD::forward<decltype(range)>(range)); }); } /// @brief Finds the greatest element in the range /// /// @snippet test.cpp rah::max_element_pred template<typename R, typename P> auto max_element(R&& range, P&& pred) { return RAH_STD::max_element(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Finds the greatest element in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::max_element_pred_pipeable template<typename P, RAH_STD::enable_if_t<!is_range<P>::value, int> = 0> auto max_element(P&& pred) { return make_pipeable([=](auto&& range) { return max_element(RAH_STD::forward<decltype(range)>(range), pred); }); } // ************************************* min_element ********************************************** /// @brief Finds the smallest element in the range /// /// @snippet test.cpp rah::min_element template<typename R, RAH_STD::enable_if_t<is_range<R>::value, int> = 0> auto min_element(R&& range) { return RAH_STD::min_element(rah_begin(range), rah_end(range)); } /// @brief Finds the smallest element in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::min_element_pipeable inline auto min_element() { return make_pipeable([=](auto&& range) { return min_element(RAH_STD::forward<decltype(range)>(range)); }); } /// @brief Finds the smallest element in the range /// /// @snippet test.cpp rah::min_element_pred template<typename R, typename P> auto min_element(R&& range, P&& pred) { return RAH_STD::min_element(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Finds the smallest element in the range /// @remark pipeable syntax /// /// @snippet test.cpp rah::min_element_pred_pipeable template<typename P, RAH_STD::enable_if_t<!is_range<P>::value, int> = 0> auto min_element(P&& pred) { return make_pipeable([=](auto&& range) { return min_element(RAH_STD::forward<decltype(range)>(range), pred); }); } // *************************************** copy *************************************************** /// @brief Copy in range into an other /// @return The part of out after the copied part /// /// @snippet test.cpp rah::copy template<typename R1, typename R2> auto copy(R1&& in, R2&& out) { return RAH_STD::copy(rah_begin(in), rah_end(in), rah_begin(out)); } /// @brief Copy in range into an other /// @return The part of out after the copied part /// @remark pipeable syntax /// /// @snippet test.cpp rah::copy_pipeable template<typename R2> auto copy(R2&& out) { auto all_out = out | RAH_NAMESPACE::view::all(); return make_pipeable([=](auto&& in) {return copy(in, all_out); }); } // *************************************** fill *************************************************** /// @brief Assigns the given value to the elements in the range [first, last) /// /// @snippet test.cpp rah::copy template<typename R1, typename V> auto fill(R1&& in, V&& value) { return RAH_STD::fill(rah_begin(in), rah_end(in), value); } /// @brief Assigns the given value to the elements in the range [first, last) /// @remark pipeable syntax /// /// @snippet test.cpp rah::copy_pipeable template<typename V> auto fill(V&& value) { return make_pipeable([=](auto&& out) {return fill(out, value); }); } // *************************************** back_insert *************************************************** /// @brief Insert *in* in back of *front* /// /// @snippet test.cpp rah::back_insert template<typename R1, typename R2> auto back_insert(R1&& in, R2&& out) { return copy(in, RAH_NAMESPACE::back_inserter(out)); } /// @brief Insert *in* in back of *front* /// @remark pipeable syntax /// /// @snippet test.cpp rah::back_insert_pipeable template<typename R2> auto back_insert(R2&& out) { return make_pipeable([&](auto&& in) {return back_insert(in, out); }); } // *************************************** copy_if *************************************************** /// @brief Copies the elements for which the predicate pred returns true /// @return The part of out after the copied part /// /// @snippet test.cpp rah::copy_if template<typename R1, typename R2, typename P> auto copy_if(R1&& in, R2&& out, P&& pred) { return RAH_STD::copy_if(rah_begin(in), rah_end(in), rah_begin(out), RAH_STD::forward<P>(pred)); } /// @brief Copies the elements for which the predicate pred returns true /// @return The part of out after the copied part /// @remark pipeable syntax /// /// @snippet test.cpp rah::copy_if_pipeable template<typename R2, typename P> auto copy_if(R2&& out, P&& pred) { auto all_out = out | RAH_NAMESPACE::view::all(); return make_pipeable([=](auto&& in) {return copy_if(in, all_out, pred); }); } // *************************************** size *************************************************** /// @brief Get the size of range /// /// @snippet test.cpp rah::size template<typename R> auto size(R&& range) { return RAH_STD::distance(rah_begin(range), rah_end(range)); } /// @brief Get the size of range /// @remark pipeable syntax /// /// @snippet test.cpp rah::size_pipeable inline auto size() { return make_pipeable([=](auto&& range) { return size(RAH_STD::forward<decltype(range)>(range)); }); } // *************************************** equal ************************************************** /// @brief Determines if two sets of elements are the same /// /// @snippet test.cpp rah::equal template<typename R1, typename R2> auto equal(R1&& range1, R2&& range2) { #ifdef EASTL_VERSION return RAH_STD::identical(rah_begin(range1), rah_end(range1), rah_begin(range2), rah_end(range2)); #else return RAH_STD::equal(rah_begin(range1), rah_end(range1), rah_begin(range2), rah_end(range2)); #endif } /// @brief Determines if two sets of elements are the same /// @remark pipeable syntax /// /// @snippet test.cpp rah::equal_pipeable template<typename R1> auto equal(R1&& range2) { auto all_range2 = range2 | RAH_NAMESPACE::view::all(); return make_pipeable([=](auto&& range1) { return equal(RAH_STD::forward<decltype(range1)>(range1), all_range2); }); } // *********************************** stream_inserter ******************************************** template<typename S> struct stream_inserter_iterator : iterator_facade<stream_inserter_iterator<S>, typename S::char_type, RAH_STD::output_iterator_tag> { S* stream_ = nullptr; stream_inserter_iterator() = default; stream_inserter_iterator(S& stream) : stream_(&stream) { } template<typename V> void put(V&& value) const { (*stream_) << value; } }; /// @brief Make a range which output to a stream /// /// @snippet test.cpp rah::stream_inserter template<typename S> auto stream_inserter(S&& stream) { using Stream = RAH_STD::remove_reference_t<S>; auto begin = stream_inserter_iterator<Stream>(stream); auto end = stream_inserter_iterator<Stream>(stream); return RAH_NAMESPACE::make_iterator_range(begin, end); } // *********************************** remove_if ************************************************** /// @brief Keep at the begining of the range only elements for which pred(elt) is false\n /// @return Return the (end) part of the range to erase. /// /// @snippet test.cpp rah::remove_if template<typename R, typename P> auto remove_if(R&& range, P&& pred) { return RAH_STD::remove_if(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @brief Keep at the begining of the range only elements for which pred(elt) is false\n /// @return The (end) part of the range to erase. /// @remark pipeable syntax /// /// @snippet test.cpp rah::remove_if_pipeable template<typename P> auto remove_if(P&& pred) { return make_pipeable([=](auto&& range) { return remove_if(RAH_STD::forward<decltype(range)>(range), pred); }); } // *********************************** remove ***************************************************** /// @brief Keep at the begining of the range only elements not equal to value\n /// @return Return iterator to the part of the range to erase. /// /// @snippet test.cpp rah::remove template<typename R, typename V> auto remove(R&& range, V&& value) { return RAH_STD::remove(rah_begin(range), rah_end(range), RAH_STD::forward<V>(value)); } /// @brief Keep at the begining of the range only elements not equal to value\n /// @return Return iterator to the part of the range to erase. /// @remark pipeable syntax /// /// @snippet test.cpp rah::remove_pipeable template<typename V> auto remove(V&& value) { return make_pipeable([=](auto&& range) { return remove(RAH_STD::forward<decltype(range)>(range), value); }); } // *********************************** partition ************************************************** /// @brief Reorders the elements in the @b range in such a way that all elements for which the /// predicate @b pred returns `true` precede the elements for which predicate @b pred returns `false`. /// Relative order of the elements is not preserved. /// @return Iterator to the first element of the second group. /// /// @snippet test.cpp rah::partition template<typename R, typename P> auto partition(R&& range, P&& pred) { return RAH_STD::partition(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @see rah::partition(R&&, P&&) /// @remark pipeable syntax /// /// @snippet test.cpp rah::partition_pipeable template<typename P> auto partition(P&& pred) { return make_pipeable([=](auto&& range) { return partition(RAH_STD::forward<decltype(range)>(range), pred); }); } // *********************************** stable_partition ******************************************* /// @brief Reorders the elements in the @b range in such a way that all elements for which /// the predicate @b pred returns `true` precede the elements for which predicate @b pred returns false. /// Relative order of the elements is preserved. /// @return Iterator to the first element of the second group. /// /// @snippet test.cpp rah::stable_partition template<typename R, typename P> auto stable_partition(R&& range, P&& pred) { return RAH_STD::stable_partition(rah_begin(range), rah_end(range), RAH_STD::forward<P>(pred)); } /// @see rah::stable_partition(R&&, P&&) /// @remark pipeable syntax /// /// @snippet test.cpp rah::stable_partition_pipeable template<typename P> auto stable_partition(P&& pred) { return make_pipeable([=](auto&& range) { return stable_partition(RAH_STD::forward<decltype(range)>(range), pred); }); } // *********************************** erase ****************************************************** /// @brief Erase a sub-range of a given container /// @return A view on the resulting container /// /// @snippet test.cpp rah::erase template<typename C, typename R> auto erase(C&& container, R&& subrange) { container.erase(rah_begin(subrange), rah_end(subrange)); return container | RAH_NAMESPACE::view::all(); } /// @brief Erase a sub-range of a given container /// @return A view on the resulting container /// @remark pipeable syntax /// /// @snippet test.cpp rah::erase_pipeable template<typename R> auto erase(R&& range) { auto all_range = range | RAH_NAMESPACE::view::all(); return make_pipeable([=](auto&& cont) { return RAH_NAMESPACE::erase(cont, all_range); }); } // *********************************** sort ******************************************************* /// @brief Sort a range in place, using the given predicate. /// /// @snippet test.cpp rah::sort /// @snippet test.cpp rah::sort_pred template<typename R, typename P = is_lesser, typename = RAH_STD::enable_if_t<is_range<R>::value>> void sort(R& range, P&& pred = {}) { RAH_STD::sort(rah_begin(range), rah_end(range), pred); } /// @brief Sort a range in place, using the given predicate. /// @remark pipeable syntax /// /// @snippet test.cpp rah::sort_pipeable /// @snippet test.cpp rah::sort_pred_pipeable template<typename P = is_lesser, typename = RAH_STD::enable_if_t<not is_range<P>::value>> auto sort(P&& pred = {}) { return make_pipeable([=](auto& range) { return sort(range, pred); }); } // *********************************** stable_sort ************************************************ /// @brief Sorts the elements in the range in ascending order. The order of equivalent elements is guaranteed to be preserved. /// /// @snippet test.cpp rah::stable_sort /// @snippet test.cpp rah::stable_sort_pred template<typename R, typename P = is_lesser, typename = RAH_STD::enable_if_t<is_range<R>::value>> void stable_sort(R& range, P&& pred = {}) { RAH_STD::stable_sort(rah_begin(range), rah_end(range), pred); } /// @brief Sorts the elements in the range in ascending order. The order of equivalent elements is guaranteed to be preserved. /// @remark pipeable syntax /// /// @snippet test.cpp rah::stable_sort_pipeable /// @snippet test.cpp rah::stable_sort_pred_pipeable template<typename P = is_lesser, typename = RAH_STD::enable_if_t<not is_range<P>::value>> auto stable_sort(P&& pred = {}) { return make_pipeable([=](auto& range) { return stable_sort(range, pred); }); } // *********************************** shuffle ******************************************************* /// @brief Reorders the elements in the given range such that each possible permutation of those elements has equal probability of appearance. /// /// @snippet test.cpp rah::shuffle template<typename R, typename URBG> void shuffle(R& range, URBG&& g) { RAH_STD::shuffle(rah_begin(range), rah_end(range), RAH_STD::forward<URBG>(g)); } /// @brief Reorders the elements in the given range such that each possible permutation of those elements has equal probability of appearance. /// @remark pipeable syntax /// /// @snippet test.cpp rah::shuffle_pipeable template<typename URBG> auto shuffle(URBG&& g) { return make_pipeable([&g](auto& range) { return RAH_NAMESPACE::shuffle(range, g); }); } // *********************************** unique ***************************************************** /// Apply the '==' operator on two values of any type struct is_equal { template<typename A, typename B> bool operator()(A&& a, B&& b) { return a == b; } }; /// @brief Remove all but first successuve values which are equals. Without resizing the range. /// @return The end part of the range, which have to be remove. /// /// @snippet test.cpp rah::unique /// @snippet test.cpp rah::unique_pred template<typename R, typename P = is_equal, typename = RAH_STD::enable_if_t<is_range<R>::value>> auto unique(R&& range, P&& pred = {}) { return RAH_STD::unique(rah_begin(range), rah_end(range), pred); } /// @brief Remove all but first successive values which are equals. Without resizing the range. /// @return The end part of the range, which have to be remove. /// @remark pipeable syntax /// /// @snippet test.cpp rah::unique_pipeable /// @snippet test.cpp rah::unique_pred_pipeable template<typename P = is_equal, typename = RAH_STD::enable_if_t<not is_range<P>::value>> auto unique(P&& pred = {}) { return make_pipeable([=](auto&& range) { return unique(RAH_STD::forward<decltype(range)>(range), pred); }); } // *********************************** set_difference ************************************************ /// @brief Copies the elements from the sorted range in1 which are not found in the sorted range in2 to the range out /// The resulting range is also sorted. /// /// @snippet test.cpp rah::set_difference template<typename IN1, typename IN2, typename OUT_> void set_difference(IN1&& in1, IN2&& in2, OUT_&& out) { RAH_STD::set_difference( rah_begin(in1), rah_end(in1), rah_begin(in2), rah_end(in2), rah_begin(out)); } // *********************************** set_intersection ************************************************ /// @brief Copies the elements from the sorted range in1 which are also found in the sorted range in2 to the range out /// The resulting range is also sorted. /// /// @snippet test.cpp rah::set_intersection template<typename IN1, typename IN2, typename OUT_> void set_intersection(IN1&& in1, IN2&& in2, OUT_&& out) { RAH_STD::set_intersection( rah_begin(in1), rah_end(in1), rah_begin(in2), rah_end(in2), rah_begin(out)); } namespace action { // *********************************** unique ***************************************************** /// @brief Remove all but first successive values which are equals. /// @return Reference to container /// /// @snippet test.cpp rah::action::unique /// @snippet test.cpp rah::action::unique_pred template<typename C, typename P = is_equal, typename = RAH_STD::enable_if_t<is_range<C>::value>> auto&& unique(C&& container, P&& pred = {}) { container.erase(RAH_NAMESPACE::unique(container, pred), container.end()); return RAH_STD::forward<C>(container); } /// @brief Remove all but first successuve values which are equals. /// @return Reference to container /// @remark pipeable syntax /// /// @snippet test.cpp rah::action::unique_pipeable /// @snippet test.cpp rah::action::unique_pred_pipeable template<typename P = is_equal, typename = RAH_STD::enable_if_t<not is_range<P>::value>> auto unique(P&& pred = {}) { return make_pipeable([=](auto&& range) -> auto&& { return action::unique(RAH_STD::forward<decltype(range)>(range), pred); }); } // *********************************** remove_if ************************************************** /// @brief Keep only elements for which pred(elt) is false\n /// @return reference to the container /// /// @snippet test.cpp rah::action::remove_if template<typename C, typename P> auto&& remove_if(C&& container, P&& pred) { container.erase(RAH_NAMESPACE::remove_if(container, RAH_STD::forward<P>(pred)), container.end()); return RAH_STD::forward<C>(container); } /// @brief Keep only elements for which pred(elt) is false\n /// @return reference to the container /// @remark pipeable syntax /// /// @snippet test.cpp rah::action::remove_if_pipeable template<typename P> auto remove_if(P&& pred) { return make_pipeable([=](auto&& range) -> auto&& { return remove_if(RAH_STD::forward<decltype(range)>(range), pred); }); } // *********************************** remove ***************************************************** /// @brief Keep only elements not equal to @b value /// @return reference to the container /// /// @snippet test.cpp rah::action::remove template<typename C, typename V> auto&& remove(C&& container, V&& value) { container.erase(RAH_NAMESPACE::remove(container, RAH_STD::forward<V>(value)), container.end()); return RAH_STD::forward<C>(container); } /// @brief Keep only elements not equal to @b value /// @return reference to the container /// @remark pipeable syntax /// /// @snippet test.cpp rah::action::remove_pipeable template<typename V> auto remove(V&& value) { return make_pipeable([=](auto&& range) -> auto&& { return remove(RAH_STD::forward<decltype(range)>(range), value); }); } // *********************************** sort ******************************************************* /// @brief Sort a range in place, using the given predicate. /// @return reference to container /// /// @snippet test.cpp rah::action::sort /// @snippet test.cpp rah::action::sort_pred template<typename C, typename P = is_lesser, typename = RAH_STD::enable_if_t<is_range<C>::value>> auto&& sort(C&& container, P&& pred = {}) { RAH_NAMESPACE::sort(container, pred); return RAH_STD::forward<C>(container); } /// @brief Sort a range in place, using the given predicate. /// @return reference to container /// @remark pipeable syntax /// /// @snippet test.cpp rah::action::sort_pipeable /// @snippet test.cpp rah::action::sort_pred_pipeable template<typename P = is_lesser, typename = RAH_STD::enable_if_t<not is_range<P>::value>> auto sort(P&& pred = {}) { return make_pipeable([=](auto&& range) -> auto&& { return action::sort(RAH_STD::forward<decltype(range)>(range), pred); }); } // *********************************** shuffle ******************************************************* /// @brief Reorders the elements in the given range such that each possible permutation of those elements has equal probability of appearance. /// @return reference to container /// /// @snippet test.cpp rah::action::shuffle template<typename C, typename URBG> auto&& shuffle(C&& container, URBG&& g) { URBG gen = RAH_STD::forward<URBG>(g); RAH_NAMESPACE::shuffle(container, gen); return RAH_STD::forward<C>(container); } /// @brief Reorders the elements in the given range such that each possible permutation of those elements has equal probability of appearance. /// @return reference to container /// @remark pipeable syntax /// /// @snippet test.cpp rah::action::shuffle_pipeable template<typename URBG> auto shuffle(URBG&& g) { return make_pipeable([&](auto&& range) -> auto&& { return action::shuffle(RAH_STD::forward<decltype(range)>(range), g); }); } // *************************************** fill *************************************************** /// @brief Assigns the given value to the elements in the range [first, last) /// /// @snippet test.cpp rah::copy template<typename R1, typename V> auto fill(R1&& in, V&& value) { RAH_STD::fill(rah_begin(in), rah_end(in), value); return RAH_STD::forward<R1>(in); } /// @brief Assigns the given value to the elements in the range [first, last) /// @remark pipeable syntax /// /// @snippet test.cpp rah::copy_pipeable template<typename V> auto fill(V&& value) { return make_pipeable([=](auto&& out) {return RAH_NAMESPACE::action::fill(out, value); }); } } // namespace action } // namespace rah
f6e6d4dc3873aa3ba4ae015b4925b8765eacfb02
[ "Markdown", "C++" ]
4
C++
lhamot/rah
56496be4a14794b6a2ec9c0ce4fd296505995bcd
20764d1a78a1b723e234f0990ebaf1b8c1b3b58f
refs/heads/master
<file_sep><?php namespace Test\Unit; use PHPUnit\Framework\TestCase; use App\Domains\Candidato\Candidato; use App\Domains\Candidato\Diploma; use App\Domains\Inscricao\Models\Inscricao; class InscricaoTest extends TestCase { private $inscricao; public function setUp(): void { $candidato = new Candidato('Felipe', new Diploma('UNILAB')); $this->inscricao = new Inscricao($candidato); $this->inscricao->salvar(); } public function testConfirmarInscricao() { $this->inscricao->confirmar(); $this->assertTrue($this->inscricao->estarConfirmada()); } public function testNaoConfirmarInscricaoNaoFinalizada() { $this->expectException(\DomainException::class); $this->expectExceptionMessage('Finalize o processo de inscrição'); $inscricao = new Inscricao(new Candidato('Felipe')); $inscricao->salvar(); $inscricao->confirmar(); } public function testDeferirInscricao() { $this->inscricao->confirmar(); $this->inscricao->deferir(); $this->assertTrue($this->inscricao->estarDeferida()); } public function testNaoDeferirInscricaoNaoConfirmada() { $this->expectException(\DomainException::class); // $this->expectExceptionMessage('Finalize o processo de inscrição'); $this->inscricao->deferir(); } public function testNaoIndeferirInscricaoNaoConfirmada() { $this->expectException(\DomainException::class); // $this->expectExceptionMessage('Finalize o processo de inscrição'); $this->inscricao->indeferir(); } public function testIndeferirInscricao() { $this->inscricao->confirmar(); $this->inscricao->indeferir(); $this->assertTrue($this->inscricao->estarIndeferida()); } public function testDeferirUmaInscricaoindeferida() { $this->inscricao->confirmar(); $this->inscricao->indeferir(); $this->inscricao->deferir(); $this->assertTrue($this->inscricao->estarDeferida()); } public function testIndeferirUmaInscricaoDeferida() { $this->inscricao->confirmar(); $this->inscricao->deferir(); $this->inscricao->indeferir(); $this->assertTrue($this->inscricao->estarIndeferida()); } public function testAprovarInscricaoDeferida() { $this->inscricao->confirmar(); $this->inscricao->deferir(); $this->inscricao->aprovar(); $this->assertTrue($this->inscricao->estarAprovada()); } /** @dataProvider inscricoesNaoDeferidas */ public function testNaoAprovarInscricoesNaoDeferidas(array $inscricoes) { foreach ($inscricoes as $inscricao) { $this->expectException(\DomainException::class); // $this->expectExceptionMessage('Finalize o processo de inscrição'); $inscricao->aprovar(); } } public function inscricoesNaoDeferidas() { $candidato = new Candidato('Felipe', new Diploma('UNILAB')); $pendente = new Inscricao($candidato); $pendente->salvar(); $confirmada = (new Inscricao($candidato)) ->salvar() ->confirmar(); $indeferida = (new Inscricao($candidato)) ->salvar() ->confirmar() ->indeferir(); return [ [ "naodeferidas" => [ $pendente, $confirmada, $indeferida ] ] ]; } } <file_sep><?php namespace App\Domains\Inscricao\States; use App\Domains\Inscricao\States\StateInscricao; use App\Domains\Inscricao\Enums\StatusInscricaoEnum; class InscricaoAprovada extends StateInscricao { public function getId(): int { return StatusInscricaoEnum::APROVADA(); } } <file_sep><?php namespace App\Domains\Inscricao\Services; use App\Domains\Inscricao\Models\Inscricao; use App\Domains\Inscricao\States\StateIncricaoInterface; class InscricaoService { private Inscricao $inscricao; public function __construct(Inscricao $inscricao = null) { $this->inscricao = $inscricao; } public function AlterarStatus(StateIncricaoInterface $state): InscricaoService { //salva o novo status no banco $this->inscricao->alterarState($state); return $this; } } <file_sep><?php namespace App\Domains\Inscricao\States; use App\Domains\Inscricao\Models\Inscricao; use App\Domains\Inscricao\States\StateIncricaoInterface; abstract class StateInscricao implements StateIncricaoInterface { protected Inscricao $inscricao; public function __construct(Inscricao $inscricao = null) { $this->inscricao = $inscricao; } abstract public function getId(): int; public function confirmarInscricao(): void { throw new \DomainException('Estado invalido'); } public function deferirInscricao(): void { throw new \DomainException('Estado invalido'); } public function indeferirInscricao(): void { throw new \DomainException('Estado invalido'); } public function aprovarInscricao(): void { throw new \DomainException('Estado invalido'); } } <file_sep><?php namespace App\Domains\Inscricao\States; use App\Domains\Inscricao\Models\Inscricao; use App\Domains\Inscricao\States\StateInscricao; use App\Domains\Inscricao\Enums\StatusInscricaoEnum; use App\Domains\Inscricao\Services\InscricaoService; class InscricaoConfirmada extends StateInscricao { private $service; public function __construct(Inscricao $inscricao) { parent::__construct($inscricao); $this->service = new InscricaoService($inscricao); } public function getId(): int { return StatusInscricaoEnum::CONFIRMADA(); } public function deferirInscricao(): void { $this->service->AlterarStatus(new InscricaoDeferida($this->inscricao)); } public function indeferirInscricao(): void { $this->service->AlterarStatus(new InscricaoIndeferida($this->inscricao)); } } <file_sep><?php namespace App\Domains\Inscricao\Models; use DateTimeImmutable; use App\Domains\Candidato\Candidato; use App\Domains\Inscricao\States\InscricaoPendente; use App\Domains\Inscricao\Enums\StatusInscricaoEnum; use App\Domains\Inscricao\Services\GeradorNumeroInscricao; use App\Domains\Inscricao\States\StateIncricaoInterface as State; class Inscricao { private string $numero; private Candidato $candidato; private DateTimeImmutable $data; private ?State $state; private ?int $id; public function __construct( Candidato $candidato, ?State $state = null, ?int $id = null, ?DateTimeImmutable $data = null ) { $this->candidato = $candidato; $this->data = $data ?? new DateTimeImmutable(); $this->state = $state ?? new InscricaoPendente($this); $this->id = $id; } public function deferir(): Inscricao { $this->state->deferirInscricao(); return $this; } public function indeferir(): Inscricao { $this->state->indeferirInscricao(); return $this; } public function aprovar(): Inscricao { $this->state->aprovarInscricao(); return $this; } public function confirmar(): Inscricao { $this->state->confirmarInscricao(); return $this; } public function salvar(): Inscricao { if (!$this->id) { $this->id = rand(1, 10000); } return $this; } public function estarFinalizada(): bool { return $this->candidato->possuiDisploma(); } public function estarPendente(): bool { return $this->state->getId() === StatusInscricaoEnum::PEDENTE(); } public function estarConfirmada(): bool { return $this->state->getId() === StatusInscricaoEnum::CONFIRMADA(); } public function estarDeferida(): bool { return $this->state->getId() === StatusInscricaoEnum::DEFERIDA(); } public function estarIndeferida(): bool { return $this->state->getId() === StatusInscricaoEnum::INDEFERIDA(); } public function estarAprovada(): bool { return $this->state->getId() === StatusInscricaoEnum::APROVADA(); } public function alterarState(State $novoState): void { $this->state = $novoState; } public function gerarNumero(): void { if (!empty($this->numero)) { throw new \DomainException('Número de inscrição do candidato já foi gerado.'); } $this->numero = new GeradorNumeroInscricao($this); } public function getCandidato(): Candidato { return $this->candidato; } public function getData(): DateTimeImmutable { return $this->data; } public function getState(): State { return $this->state; } public function getNumero(): string { return $this->numero; } public function getId(): int { return $this->id; } } <file_sep><?php namespace App\Domains\Candidato; class Diploma { private string $instituicao; public function __construct(string $instituicao) { $this->instituicao = $instituicao; } public function getInstituicao() { return $this->instituicao; } } <file_sep><?php namespace App\Domains\Inscricao\Enums; class StatusInscricaoEnum { /** @var int */ private const PEDENTE = 1; /** @var int */ private const CONFIRMADA = 2; /** @var int */ private const DEFERIDA = 3; /** @var int */ private const INDEFERIDA = 4; /** @var int */ private const APROVADA = 5; public static function PEDENTE() { return self::PEDENTE; } public static function CONFIRMADA() { return self::CONFIRMADA; } public static function DEFERIDA() { return self::DEFERIDA; } public static function INDEFERIDA() { return self::INDEFERIDA; } public static function APROVADA() { return self::APROVADA; } } <file_sep><?php namespace App\Domains\Inscricao\States; use App\Domains\Inscricao\States\StateInscricao; use App\Domains\Inscricao\Enums\StatusInscricaoEnum; class InscricaoPendente extends StateInscricao { public function getId(): int { return StatusInscricaoEnum::PEDENTE(); } public function confirmarInscricao(): void { if(!$this->inscricao->estarFinalizada()){ throw new \DomainException('Finalize o processo de inscrição'); } $this->inscricao->gerarNumero(); $this->inscricao->salvar(); $this->inscricao->alterarState(new InscricaoConfirmada($this->inscricao)); } } <file_sep><?php namespace App\Domains\Inscricao\States; interface StateIncricaoInterface { public function getId(): int; public function confirmarInscricao(): void; public function deferirInscricao(): void; public function indeferirInscricao(): void; public function aprovarInscricao(): void; } <file_sep><?php namespace App\Domains\Candidato; class Candidato { private string $nome; private ?Diploma $diploma; public function __construct(string $nome, ?Diploma $diploma = null) { $this->nome = $nome; $this->diploma = $diploma; } public function getNome(): string { return $this->nome; } public function possuiDisploma() { return !is_null($this->diploma); } public function adicionarDiploma(Diploma $diploma): Candidato { $this->diploma = $diploma; return $this; } } <file_sep><?php namespace App\Domains\Inscricao\States; use App\Domains\Inscricao\States\StateInscricao; use App\Domains\Inscricao\States\InscricaoDeferida; use App\Domains\Inscricao\Enums\StatusInscricaoEnum; use App\Domains\Inscricao\Services\InscricaoService; class InscricaoIndeferida extends StateInscricao { public function getId(): int { return StatusInscricaoEnum::INDEFERIDA(); } public function deferirInscricao(): void { $service = new InscricaoService($this->inscricao); $service->AlterarStatus(new InscricaoDeferida($this->inscricao)); } } <file_sep><?php namespace App\Domains\Inscricao\States; use App\Domains\Inscricao\Models\Inscricao; use App\Domains\Inscricao\States\StateInscricao; use App\Domains\Inscricao\Enums\StatusInscricaoEnum; use App\Domains\Inscricao\Services\InscricaoService; class InscricaoDeferida extends StateInscricao { private $service; public function __construct(Inscricao $inscricao) { parent::__construct($inscricao); $this->service = new InscricaoService($inscricao); } public function getId(): int { return StatusInscricaoEnum::DEFERIDA(); } public function indeferirInscricao(): void { $this->service->AlterarStatus(new InscricaoIndeferida($this->inscricao)); } public function aprovarInscricao(): void { $this->service->AlterarStatus(new InscricaoAprovada($this->inscricao)); } } <file_sep><?php namespace App\Domains\Inscricao\Services; use DateTime; use App\Domains\Inscricao\Models\Inscricao; class GeradorNumeroInscricao { private Inscricao $inscricao; public function __construct(Inscricao $inscricao) { $this->inscricao = $inscricao; } public function __toString() { //Formato do numero de inscrição (12 digitos): yyssuuuuuuid //Os 2 primeiros digitos são ano de inscrição //Seguido dos segundos (2 digitos) e microsegundos (6 digitos) da hora de inscrição //e finalizado com os 2 digitos do id da inscrição $timestamp = new DateTime(); //preenche com zero a esquerda caso o id da inscrição seja menor que dois digitos $id = trim(str_pad(substr($this->inscricao->getId(), 0, 2), 2, "0", STR_PAD_LEFT)); $numero = trim($timestamp->format('ysu')); $numero.= $id; return trim($numero); } }
693b6b53d3226039cd2770c97373c94444d7819a
[ "PHP" ]
14
PHP
lfelipels/state_pattern_exemple
72c2dc2581e04019b7b2b6aad6b7dc0951d8ca4a
d075e5c89e2302c946b5a0fde14bcaa0abf572c7
refs/heads/main
<repo_name>project-k-io/TheLCRGame<file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Views/WinnerListView.xaml.cs using System.Windows; using System.Windows.Controls; using ProjectK.Games.LCR.ViewModels; namespace ProjectK.Games.LCR.Views { /// <summary> /// Interaction logic for WinnerListView.xaml /// </summary> public partial class WinnerListView : UserControl { private SimulatorViewModel _simulator; public WinnerListView() { InitializeComponent(); Loaded += OnLoaded; } private void OnLoaded(object sender, RoutedEventArgs e) { if (DataContext is SimulatorViewModel model) { _simulator = model; _simulator.DrawCharts += OnDrawCharts; } } private void OnDrawCharts() { PlayerList.ScrollIntoView(PlayerList.SelectedItem); } } } <file_sep>/README.md # TheLCRGame The LCR Game - WPF Code Challenge ![image](https://user-images.githubusercontent.com/17842209/137667576-ac386b52-b847-48c1-85f2-764fac2cda66.png) Executable [LCRGame.zip](https://github.com/projectk-io/TheLCRGame/files/7361763/LCRGame.zip) <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Models/GameModel.cs  namespace ProjectK.Games.LCR.Models { public class GameModel: IPoint<int> { public const int NoWinner = -1; public int Turns { get; set; } public int Index { get; set; } public int? Winner { get; set; } public override string ToString() { return $"[Index={Index,3}, Turns={Turns,3}, Winner={Winner,2}]"; } public void Reset() { Turns = 0; Winner = null; } public int X => Index; public int Y => Turns; } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.ViewModels/PlayerViewModel.cs using System; using System.Collections.Generic; using GalaSoft.MvvmLight; using ProjectK.Games.LCR.Models; namespace ProjectK.Games.LCR.ViewModels { public class PlayerViewModel: ViewModelBase { public const int MaxNumberOfChips = 3; #region Fields private int _index; private bool _winner; private int _numberOfWins; #endregion #region Properties public int NumberOfChips { get; set; } = MaxNumberOfChips; public bool Active { get; set; } = true; public int Index { get => _index; set => Set(ref _index, value); } public bool Winner { get => _winner; set => Set(ref _winner, value); } public int NumberOfWins { get => _numberOfWins; set => Set(ref _numberOfWins, value); } #endregion public override string ToString() { return $"[Index={Index}, Chips={NumberOfChips}, Active={Active}]"; } public List<DiceSide> Roll(Random rnd) { var numberOfRollingDices = NumberOfChips > MaxNumberOfChips ? MaxNumberOfChips : NumberOfChips; var dice = new DiceModel(); var sides = new List<DiceSide>(); for (var index = 0; index < numberOfRollingDices; index++) { dice.Roll(rnd); sides.Add(dice.RolledSide); } return sides; } public void Reset() { NumberOfChips = MaxNumberOfChips; Active = true; Winner = false; } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Views/SimulatorView.xaml.cs using System.Windows.Controls; namespace ProjectK.Games.LCR.Views { /// <summary> /// Interaction logic for SimulatorView.xaml /// </summary> public partial class SimulatorView : UserControl { public SimulatorView() { InitializeComponent(); } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Models/DiceModel.cs using System; namespace ProjectK.Games.LCR.Models { public class DiceModel { public DiceSide[] Sides { get; set; } = { DiceSide.Left, DiceSide.Center, DiceSide.Right, DiceSide.Dot, DiceSide.Dot, DiceSide.Dot }; public DiceSide RolledSide { get; set; } = DiceSide.None; public void Roll(Random rnd) { var index = rnd.Next(0, 5); RolledSide = Sides[index]; } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Models/DiceSide.cs namespace ProjectK.Games.LCR.Models { public enum DiceSide { None, Left, Center, Right, Dot } }<file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Models/GenericExtensions.cs using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectK.Games.LCR.Models { public static class GenericExtensions { public static bool IsNullOrEmpty<T>(this IList<T> items) { return items == null || items.Count == 0; } public static int GetNextItemIndex2<T>(this IList<T> items, int index) { return index > 0 ? index - 1 : items.Count - 1; } public static int GetPrevItemIndex<T>(this IList<T> items, int index) { return index < items.Count - 1 ? index + 1 : 0; } public static T GetNextItem<T>(this IList<T> items, int index) { return items[items.GetNextItemIndex2(index)]; } public static T GetPrevItem<T>(this IList<T> items, int index) { return items[items.GetPrevItemIndex(index)]; } public static bool IsLast<T>(this IList<T> items, T item) { return items.IndexOf(item) == items.Count-1; } public static string ToText<T>(this IList<T> items) { var sb = new StringBuilder(); foreach (var item in items) { sb.Append(item); if (!items.IsLast(item)) sb.Append(','); } return sb.ToString(); } public static List<double> GetAxisCenters(double n1, double n2, int n, int delta) { var step = (n2 - n1) / n; var points = new List<double>(); for (var i = 0; i <= n; i += delta) { var center = n1 + step * i; points.Add(center); } return points; } public static List<(double x, double y)> GetPoints(this List<IPoint<int>> points, (double x1, double y1, double x2, double y2) rect, (int x, int y) count) { var xCenters = GetAxisCenters(rect.x1, rect.x2, count.x, 1); var yCenters = GetAxisCenters(rect.y1, rect.y2, count.y, 1); var drawPoints = new List<(double x, double y)>(); foreach (var point in points) { var x = xCenters[point.X]; var y = yCenters[point.Y]; drawPoints.Add((x, y)); } return drawPoints; } public static List<(double x, double y)> GetPoints(this List<GameModel> games, (double x1, double y1, double x2, double y2) rect, (int x, int y) count) { var drawPoints = games.Cast<IPoint<int>>().ToList().GetPoints(rect, count); return drawPoints; } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Views/GameChartView.xaml.cs using System.Collections.Generic; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using ProjectK.Games.LCR.Models; using ProjectK.Games.LCR.ViewModels; namespace ProjectK.Games.LCR.Views { /// <summary> /// Interaction logic for GameChartView.xaml /// </summary> public partial class GameChartView : UserControl { private SimulatorViewModel _simulator; public GameChartView() { InitializeComponent(); Loaded += async(s,e) => await OnLoaded(s, e); } private async Task OnLoaded(object sender, RoutedEventArgs e) { if (DataContext is SimulatorViewModel model) { _simulator = model; _simulator.Dispatcher = a => Dispatcher.BeginInvoke(a); _simulator.DrawAxes += OnDrawAxes; _simulator.DrawCharts += OnDrawCharts; await _simulator.OnPlay(); } } private void OnDrawAxes() { Draw(); } private void OnDrawCharts() { Draw(true); } private void Draw(bool drawCharts = false) { canvas.Children.Clear(); var c = canvas; var offset = 100; var r = new Rect(offset, offset, c.ActualWidth - 2 * offset, c.ActualHeight - 2 * offset); (double x1, double y1, double x2, double y2) rect = (r.X, r.Bottom, r.Width, r.Top); if (_simulator != null) { (int x, int y) count = (_simulator.NumberOfGames, _simulator.NumberOfTurns + 10); DrawAxis(rect, count); if (drawCharts) { DrawChart(rect, count); DrawAverage(rect, count.y); DrawShortest(rect, count); DrawLongest(rect, count); } DrawGameNotation(rect); DrawLabels(rect); } } private void DrawLabels((double x1, double y1, double x2, double y2) rect) { var point = new Point((rect.x2 - rect.x1) / 2, rect.y1); canvas.DrawText(point, (0, 20), Brushes.Black, 28, "Games"); var point2 = new Point(rect.x1, (rect.y1 - rect.y2) / 2); canvas.DrawText(point2, (-80, 0), Brushes.Black, 28, "Turns", 270); } void DrawAxis((double x1, double y1, double x2, double y2) rect, (int x, int y) count) { var (xPoints, xLabels) = CanvasExtensions.GetAxisX(rect.x1, rect.x2, rect.y1, count.x, 1); var (yPoints, yLabels) = CanvasExtensions.GetAxisY(rect.y1, rect.y2, rect.x1, count.y, 1); canvas.DrawLine(xPoints, Colors.Black); canvas.DrawAxisLabels(xLabels, (-15, 10)); canvas.DrawLine(yPoints, Colors.Black); canvas.DrawAxisLabels(yLabels, (-30, -10)); } void DrawChart((double x1, double y1, double x2, double y2) rect, (int x, int y) count) { var games = _simulator.Games; var drawPoints = games.GetPoints(rect, count); var points = drawPoints.ToPoints(); canvas.DrawLine(points, Colors.Red); } void DrawAverage((double x1, double y1, double x2, double y2) rect, int yCount) { if (_simulator.AverageLengthGame == null) return; var yCenters = GenericExtensions.GetAxisCenters(rect.y1, rect.y2, yCount, 1); var y = yCenters[_simulator.AverageLengthGame.Value]; var p1 = new Point(rect.x1, y); var p2 = new Point(rect.x2, y); var points = new List<Point> { p1, p2 }; canvas.DrawLine(points, Colors.Green); } void DrawShortest((double x1, double y1, double x2, double y2) rect, (int x, int y) count) { var game = _simulator.GetShortestLengthGame(); if (game == null) return; (int x, int y) index = (game.Index, game.Turns); var text = $"Shortest ({game.Turns})"; canvas.DrawPointAndText(rect, count, index, (-10, 0), (-40, 20), text, Brushes.BlueViolet); } void DrawLongest((double x1, double y1, double x2, double y2) rect, (int x, int y) count) { var game = _simulator.GetLongestLengthGame(); if(game == null) return; (int x, int y) index = (game.Index, game.Turns); var text = $"Longest ({game.Turns})"; canvas.DrawPointAndText(rect, count, index, (-10, -20), (-40, -60), text, Brushes.Gold); } private void DrawGameNotation((double x1, double y1, double x2, double y2) rect) { var p1 = new Point(rect.x2 - 100, rect.y2 - 20); var p2 = new Point(p1.X + 50, p1.Y); var points = new List<Point>() { p1, p2 }; canvas.DrawLine(points, Colors.Red); canvas.DrawText(p2, (10, -20), Brushes.Black, 22, "Game"); var p3 = new Point(p1.X, p1.Y + 40); var p4 = new Point(p2.X, p2.Y + 40); var points2 = new List<Point>() { p3, p4 }; canvas.DrawLine(points2, Colors.Green); canvas.DrawText(p4, (10, -20), Brushes.Black, 22, "Average"); } protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) { base.OnRenderSizeChanged(sizeInfo); Draw(); } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Models/GameSettings.cs namespace ProjectK.Games.LCR.Models { public class GameSettings { public int NumberOfPlayers { get; set; } public int NumberOfGames { get; set; } public override string ToString() { return $"{NumberOfPlayers} players x {NumberOfGames} games"; } } }<file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Views/GameSettingsView.xaml.cs using System.Windows.Controls; namespace ProjectK.Games.LCR.Views { /// <summary> /// Interaction logic for GameSettingsView.xaml /// </summary> public partial class GameSettingsView : UserControl { public GameSettingsView() { InitializeComponent(); } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.ViewModels/SimulatorViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text.Json.Serialization; using System.Threading.Tasks; using System.Windows.Input; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using ProjectK.Games.LCR.Models; namespace ProjectK.Games.LCR.ViewModels { public class SimulatorViewModel : ViewModelBase { public Action DrawAxes { get; set; } public Action DrawCharts { get; set; } public Action<Action> Dispatcher { get; set; } #region Fields private readonly ObservableCollection<PlayerViewModel> _players = new(); private readonly List<GameModel> _games = new(); private readonly Random _random = new(); private int _numberOfPlayers; private int _numberOfGames; private int? _selectedPresetGameIndex; private int? _shortestLengthGameIndex; private int? _longestLengthGameIndex; private int? _averageLengthGame; private int _selectedPlayerIndex; private bool _isRunning = false; #endregion #region Properties public int? SelectedPresetGameIndex { get => _selectedPresetGameIndex; set => Set(ref _selectedPresetGameIndex, value); } public int NumberOfPlayers { get => _numberOfPlayers; set => Set(ref _numberOfPlayers, value); } public int NumberOfGames { get => _numberOfGames; set => Set(ref _numberOfGames, value); } public int? ShortestLengthGameIndex { get => _shortestLengthGameIndex; set => Set(ref _shortestLengthGameIndex, value); } public int? LongestLengthGameIndex { get => _longestLengthGameIndex; set => Set(ref _longestLengthGameIndex, value); } public int? AverageLengthGame { get => _averageLengthGame; set => Set(ref _averageLengthGame, value); } public int SelectedPlayerIndex { get => _selectedPlayerIndex; set => Set(ref _selectedPlayerIndex, value); } public List<GameSettings> PresetGames { get; set; } = new() { new GameSettings { NumberOfPlayers = 3, NumberOfGames = 100 }, new GameSettings { NumberOfPlayers = 4, NumberOfGames = 100 }, new GameSettings { NumberOfPlayers = 5, NumberOfGames = 100 }, new GameSettings { NumberOfPlayers = 5, NumberOfGames = 1000 }, new GameSettings { NumberOfPlayers = 5, NumberOfGames = 10000 }, new GameSettings { NumberOfPlayers = 6, NumberOfGames = 100 }, new GameSettings { NumberOfPlayers = 7, NumberOfGames = 100 }, }; public int NumberOfTurns { get; set; } public ObservableCollection<PlayerViewModel> Players => _players; public List<GameModel> Games => _games; public bool IsRunning { get => _isRunning; set => Set(ref _isRunning, value); } #endregion #region Commands public ICommand PlayCommand { get; set; } public ICommand CancelCommand { get; set; } #endregion public GameModel GetShortestLengthGame() { var games = Games; if (games.Count == 0) return null; if (ShortestLengthGameIndex == null) return null; var game = games[ShortestLengthGameIndex.Value]; return game; } public GameModel GetLongestLengthGame() { var games = Games; if (games.Count == 0) return null; if (LongestLengthGameIndex == null) return null; var game = games[LongestLengthGameIndex.Value]; return game; } public SimulatorViewModel() { // Init PropertyChanged += async (s,e) => await OnPropertyChanged(s,e); // Set Commands PlayCommand = new RelayCommand(async () => await OnPlay()); CancelCommand = new RelayCommand(OnCancel); // Update Settings SelectedPresetGameIndex = 0; } private async Task OnPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(SelectedPresetGameIndex): OnPresetChanged(); break; case nameof(NumberOfPlayers): CreatePlayers(NumberOfPlayers); break; case nameof(NumberOfGames): CreateGames(NumberOfGames); break; } } private void OnPresetChanged() { if (SelectedPresetGameIndex == null) return; var selectedGame = PresetGames[SelectedPresetGameIndex.Value]; NumberOfPlayers = selectedGame.NumberOfPlayers; NumberOfGames = selectedGame.NumberOfGames; ShortestLengthGameIndex = null; LongestLengthGameIndex = null; AverageLengthGame = null; DrawAxes?.Invoke(); } private void CreateGames(int count) { // Logger.LogDebug($"Create {count} games."); _games.Clear(); for (var i = 0; i < count; i++) { _games.Add(new GameModel { Index = i }); } } private void CreatePlayers(int count) { // Logger.LogDebug($"Create {count} players."); _players.Clear(); for (var i = 0; i < count; i++) { _players.Add(new PlayerViewModel { Index = i }); } } private void ResetPlayers() { // Logger.LogDebug("Reset players"); foreach (var player in _players) { player.Reset(); } } private void ResetNumberOfWins() { // Logger.LogDebug("Reset players"); foreach (var player in _players) { player.NumberOfWins = 0; } } private void ResetGames() { // Logger.LogDebug("Reset games"); foreach (var game in _games) { game.Reset(); } } public async Task OnPlay() { IsRunning = true; await Play(); Analyze(); DrawCharts?.Invoke(); IsRunning = false; } private void OnCancel() { IsRunning = false; } public async Task Play() { Logger.LogDebug($"Game Started"); Logger.LogDebug($"Players={NumberOfPlayers}, Games={NumberOfGames}"); var rnd = _random; ResetGames(); ResetNumberOfWins(); DrawCharts?.Invoke(); foreach (var game in _games) { ResetPlayers(); bool onlyOnePlayerHasChips = false; while (!onlyOnePlayerHasChips) { foreach (var player in _players) { if(!IsRunning) return; game.Turns++; var finished = await Task.Run(() => Play(player, rnd)); if (finished) { game.Winner = player.Index; onlyOnePlayerHasChips = true; break; } } } // Logger.LogDebug($"Game={game}"); } Logger.LogDebug($"Game Finished"); } private bool Play(PlayerViewModel player, Random rnd) { // if player doesn't have chips and it's his play, he is out if (player.NumberOfChips == 0) player.Active = false; // check if we have only one active player var activePlayers = _players.Where(item => item.Active).ToList(); if (activePlayers.Count == 1) { activePlayers[0].NumberOfWins++; return true; } // skip not active players if (!player.Active) return false; var activePlayerIndex = activePlayers.IndexOf(player); var leftPlayer = activePlayers.GetNextItem(activePlayerIndex); var rightPlayer = activePlayers.GetPrevItem(activePlayerIndex); var sides = player.Roll(rnd); foreach (var side in sides) { switch (side) { case DiceSide.Dot: break; case DiceSide.Left: leftPlayer.NumberOfChips++; player.NumberOfChips--; break; case DiceSide.Right: rightPlayer.NumberOfChips++; player.NumberOfChips--; break; case DiceSide.Center: player.NumberOfChips--; break; } } return false; } public void Analyze() { var shortestLengthTurns = int.MaxValue; int shortestLengthGameIndex = 0; var longestLengthTurns = int.MinValue; int longestLengthGameIndex = 0; var totalTurnsLength = 0; NumberOfTurns = 0; foreach (var game in _games) { var turns = game.Turns; totalTurnsLength += turns; if (turns < shortestLengthTurns) { shortestLengthTurns = turns; shortestLengthGameIndex = game.Index; } else if (turns > longestLengthTurns) { longestLengthTurns = turns; longestLengthGameIndex = game.Index; } } // Find winner PlayerViewModel winner = null; foreach (var player in Players) { if (winner == null) { winner = player; continue; } if (player.NumberOfWins > winner.NumberOfWins) { winner = player; } } if (winner != null) { winner.Winner = true; SelectedPlayerIndex = winner.Index; } NumberOfTurns = longestLengthTurns; ShortestLengthGameIndex = shortestLengthGameIndex; LongestLengthGameIndex = longestLengthGameIndex; if (!_games.IsNullOrEmpty()) { AverageLengthGame = totalTurnsLength / _games.Count; } } public List<(double x, double y)> DrawChart2((double x1, double y1, double x2, double y2) rect, (int x, int y) count) { var xCenters = GenericExtensions.GetAxisCenters(rect.x1, rect.x2, count.x, 1); var yCenters = GenericExtensions.GetAxisCenters(rect.y1, rect.y2, count.y, 1); var games = Games; var points = new List<(double x, double y)>(); foreach (var game in games) { var x = xCenters[game.Index]; var y = yCenters[game.Turns]; points.Add((x, y)); } return points; } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.WinApp/AppViewModel.cs using ProjectK.Games.LCR.ViewModels; namespace ProjectK.Games.LCR.WinApp { public class AppViewModel: SimulatorViewModel { public string AppName { get; set; } public string Title { get; set; } public string Version { get; set; } public AppViewModel() { AppName = "The LCR Game"; Version = "1.0.0"; Title = $"{AppName} {Version}"; } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Views/PlayerView.xaml.cs using System.Windows.Controls; namespace ProjectK.Games.LCR.Views { /// <summary> /// Interaction logic for PlayerView.xaml /// </summary> public partial class PlayerView : UserControl { public PlayerView() { InitializeComponent(); } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Views/CanvasExtensions.cs using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using ProjectK.Games.LCR.Models; namespace ProjectK.Games.LCR.Views { public static class CanvasExtensions { public static void DrawLine(this Canvas canvas, List<Point> points, Color color) { canvas.DrawLine(points.ToArray(), color); } public static void DrawLine(this Canvas canvas, Point[] points, Color color) { var line = new Polyline(); var collection = new PointCollection(); foreach (var p in points) { collection.Add(p); } line.Points = collection; line.Stroke = new SolidColorBrush(color); line.StrokeThickness = 2; canvas.Children.Add(line); } public static void DrawText(this Canvas canvas, Point point, (int x, int y) offset, SolidColorBrush brush, double fontSize, string text, double angle = 0) { canvas.DrawText((point.X, point.Y), offset, brush, fontSize, text, angle); } public static void DrawText(this Canvas canvas, (double x, double y) point, (int x, int y) offset, SolidColorBrush brush, double fontSize, string text, double angle = 0) { var textBlock = new TextBlock { Foreground = brush, Text = text, FontSize = fontSize, LayoutTransform = new RotateTransform(angle) }; Canvas.SetLeft(textBlock, point.x + offset.x); Canvas.SetTop(textBlock, point.y + offset.y); canvas.Children.Add(textBlock); } public static (List<Point> points, List<(Point point, int index)> labels) GetAxisY(double y1, double y2, double x, int n, int width) { int delta = n > 10 ? n / 10 : 1; var centers = GenericExtensions.GetAxisCenters(y1, y2, n, delta); var axis = new List<Point>(); var labels = new List<(Point point, int index)>(); for (var i = 0; i < centers.Count; i++) { var y = centers[i]; var point = new Point(x, y); var (point1, point2) = point.GetYPointLine(width); axis.AddRange(new[] { point, point1, point, point2, point }); var index = i * delta; labels.Add((point1, index)); } return (axis, labels); } public static (List<Point> points, List<(Point point, int index)> labels) GetAxisX(double x1, double x2, double y, int n, int height) { int delta = n > 10 ? n / 10 : 1; var centers = GenericExtensions.GetAxisCenters(x1, x2, n, delta); var axis = new List<Point>(); var labels = new List<(Point point, int index)>(); for (var i = 0; i < centers.Count; i++) { var x = centers[i]; var point = new Point(x, y); var (point1, point2) = point.GetXPointLine(height); axis.AddRange(new[] { point, point1, point, point2, point }); var index = i * delta; labels.Add((point2, index)); } return (axis, labels); } public static void DrawAxisLabels(this Canvas canvas, List<(Point point, int index)> labels, (int x, int y) offset) { foreach (var (point, index) in labels) { canvas.DrawText(point, offset, Brushes.Black, 14, index.ToString()); } } public static (Point left, Point right) GetYPointLine(this Point center, int width) { var left = new Point(center.X - width, center.Y); var right = new Point(center.X + width, center.Y); return (left, right); } public static (Point top, Point bottom) GetXPointLine(this Point center, int height) { var top = new Point(center.X, center.Y - height); var bottom = new Point(center.X, center.Y + height); return (top, bottom); } public static void DrawPointAndText(this Canvas canvas, (double x1, double y1, double x2, double y2) rect, (int x, int y) count, (int x, int y) index, (int x, int y) pointOffset, (int x, int y) textOffset, string text, SolidColorBrush brush ) { var xCenters = GenericExtensions.GetAxisCenters(rect.x1, rect.x2, count.x, 1); var yCenters = GenericExtensions.GetAxisCenters(rect.y1, rect.y2, count.y, 1); var (x, y) = (xCenters[index.x], yCenters[index.y]); var width = 10; var ellipse = new Ellipse { Stroke = brush, Fill = brush, Width = width * 2, Height = width * 2 }; Canvas.SetLeft(ellipse, x + pointOffset.x); Canvas.SetTop(ellipse, y + pointOffset.y); // Text var textBlock = new TextBlock { Text = text, FontStyle = FontStyles.Italic, FontWeight = FontWeights.DemiBold, Foreground = brush, FontSize = 22 }; Canvas.SetLeft(textBlock, x + textOffset.x); Canvas.SetTop(textBlock, y + textOffset.y); canvas.Children.Add(ellipse); canvas.Children.Add(textBlock); } public static List<Point> ToPoints(this List<(double x, double y)> drawPoints) { var points = drawPoints.Select(p => new Point(p.x, p.y)).ToList(); return points; } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Models/Logger.cs using System.Diagnostics; namespace ProjectK.Games.LCR.Models { public class Logger { public static void LogDebug(string text) { Debug.WriteLine(text); } } } <file_sep>/ProjectK.Games.LCR/ProjectK.Games.LCR.Models/IPoint.cs namespace ProjectK.Games.LCR.Models { public interface IPoint<T> { T X { get; } T Y { get; } } }
e1acc684b8f6c16707cc84fda10d38e0a0db2a3d
[ "Markdown", "C#" ]
17
C#
project-k-io/TheLCRGame
f43f373c70de5e4d14164f616fce9a1d9e62a8cd
0c83b39c61e800ff5d6bdc4251f3a6756410050b
refs/heads/master
<file_sep>SELECT HACK.HACKER_ID, HACK.NAME, CHAL.C_CHAL FROM HACKERS HACK JOIN ( SELECT HACKER_ID, COUNT(CHALLENGE_ID) AS C_CHAL FROM CHALLENGES GROUP BY HACKER_ID ) CHAL ON HACK.HACKER_ID = CHAL.HACKER_ID WHERE CHAL.C_CHAL NOT IN ( SELECT A.C_CHAL FROM ( SELECT HACKER_ID, COUNT(CHALLENGE_ID) AS C_CHAL FROM CHALLENGES GROUP BY HACKER_ID ) A GROUP BY A.C_CHAL HAVING COUNT(A.HACKER_ID) > 1 AND A.C_CHAL != (SELECT MAX(COUNT(CHALLENGE_ID)) FROM CHALLENGES GROUP BY HACKER_ID) ) ORDER BY CHAL.C_CHAL DESC, HACK.HACKER_ID; <file_sep>-- A = INS -- B = OUTS SELECT B.ANIMAL_ID, B.NAME FROM ANIMAL_OUTS B LEFT OUTER JOIN ANIMAL_INS A ON B.ANIMAL_ID = A.ANIMAL_ID WHERE A.ANIMAL_ID IS NULL ORDER BY B.ANIMAL_ID <file_sep>/* https://www.hackerrank.com/challenges/full-score/problem Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */ SELECT H.hacker_id, H.name FROM Hackers H, Challenges C, Difficulty D, Submissions S WHERE H.hacker_id = S.hacker_id AND C.challenge_id = S.challenge_id AND C.difficulty_level = D.difficulty_level AND S.score = D.score GROUP BY (H.hacker_id, H.name) HAVING COUNT(H.hacker_id) > 1 ORDER BY COUNT(c.challenge_id) DESC, H.hacker_id;<file_sep>import java.util.*; class Solution { public int solution(int[] people, int limit) { ArrayList<Integer> peoples = new ArrayList<>(); int answer = 0; int left = 0; int right = people.length - 1; Arrays.sort(people); for(int i = 0; i < people.length; i++){ peoples.add(people[i]); } while (left < right){ if(peoples.get(left) + peoples.get(right) > limit){ right--; } else { left++; right--; } if(left == right){ answer++; } answer++; } return answer; } } // import java.util.*; // class Solution { // public int solution(int[] people, int limit) { // ArrayList<Integer> peoples = new ArrayList<>(); // int answer = 0; // int left = 0; // int right = people.length - 1; // Arrays.sort(people); // for(int i = 0; i < people.length; i++){ // peoples.add(people[i]); // } // // System.out.println(peoples); // // 정렬후 // // 투포인터 left, right // // left는 움직이지않고. // // right는 가져와서 left + right < 100 인 경우에 같이빼준다. // // right에서 부터 다음 left를 찾아 left + right 해준다. // int i = 0; // while(true){ // if(i >= right){ // System.out.println("i 와 j가 같다. 탈출"); // break; // } // for(int j = right; j > i; j--){ // System.out.println(i + " 와 " + j + " 비교"); // if(i == j){ // System.out.println("돌다가 i와 j가 같아졌다. 삭제 : " + peoples.get(i)); // peoples.remove(i); // answer++; // right--; // break; // } // if(peoples.get(i) + peoples.get(j) > limit){ // right--; // } else{ // System.out.println("둘의 합이 limit 보다 작다" + peoples.get(i) + " " + peoples.get(j)); // peoples.remove(i); // peoples.remove(j-1); // right -= 2; // answer++; // break; // } // } // } // System.out.println(peoples.size()); // answer += peoples.size(); // return answer; // } // } <file_sep>-- 코드를 입력하세요 select distinct(m.CART_ID) From (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME='Milk') m, (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME='Yogurt') y where m.CART_ID = y.CART_ID order by m.CART_ID; -- 다시 풀기 SELECT distinct(t1.CART_ID) FROM (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME = 'Milk') t1, (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME = 'Yogurt') t2 WHERE t1.CART_ID = t2.CART_ID ORDER BY t1.CART_ID;<file_sep>import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { public static int N, M, V; public static boolean[] visited; public static ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>(); public static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); V = Integer.parseInt(st.nextToken()); for (int i = 0; i <= N; i++) { graph.add(new ArrayList<Integer>()); } for (int i = 0; i < M; i++) { st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); // 양방향 그래프 graph.get(a).add(b); graph.get(b).add(a); } // 단, 방문할 수 있는 정점이 여러 개인 경우에는 정점 번호가 작은 것을 먼저 방문 for (int i = 1; i <= N; i++) { Collections.sort(graph.get(i)); } visited = new boolean[N + 1]; dfs(V); sb.append("\n"); visited = new boolean[N + 1]; // 방문처리 초기화 bfs(V); System.out.println(sb); } // DFS 함수 정의 public static void dfs(int V) { if (visited[V]) { return; } visited[V] = true; sb.append(V).append(" "); for (int i = 0; i < graph.get(V).size(); i++) { dfs(graph.get(V).get(i)); } } // BFS 함수 정의 public static void bfs(int V) { Queue<Integer> q = new LinkedList<Integer>(); q.add(V); visited[V] = true; while (!q.isEmpty()) { int now = q.poll(); sb.append(now).append(" "); for (int i = 0; i < graph.get(now).size(); i++) { if (!visited[graph.get(now).get(i)]) { // 방문하지 않았다면 visited[graph.get(now).get(i)] = true; q.add(graph.get(now).get(i)); } } } } } <file_sep>-- 코드를 입력하세요 -- SELECT MIN(DATETIME) FROM ANIMAL_INS; SELECT DATETIME FROM (SELECT DATETIME FROM ANIMAL_INS ORDER BY DATETIME) WHERE ROWNUM = 1; <file_sep>SELECT NAME, DATETIME FROM ( SELECT INS.NAME, INS.DATETIME FROM ANIMAL_INS INS LEFT JOIN ANIMAL_OUTS OUTS ON INS.ANIMAL_ID = OUTS.ANIMAL_ID WHERE OUTS.ANIMAL_ID IS NULL ORDER BY INS.DATETIME ) WHERE ROWNUM <= 3 <file_sep>import java.util.*; class Solution { public int solution(int n, int[] lost, int[] reserve) { int answer = 0; ArrayList<Integer> lostli = new ArrayList<>(); ArrayList<Integer> reserveli = new ArrayList<>(); Arrays.sort(lost); Arrays.sort(reserve); int i = 0; int j = 0; while(i < lost.length && j < reserve.length){ if(lost[i] == reserve[j]){ i++; j++; }else if(lost[i] < reserve[j]){ lostli.add(lost[i++]); }else{ reserveli.add(reserve[j++]); } } while(i != lost.length){ lostli.add(lost[i++]); } while(j != reserve.length){ reserveli.add(reserve[j++]); } answer += n - lostli.size(); // 1잃어버림 2여분 3잃어버림 4여분 5잃어버림 int k = 0; while(k < lostli.size()){ if(lostli.get(k) == 1){ if(reserveli.contains(2)){ answer++; reserveli.remove(reserveli.indexOf(2)); } }else if(lostli.get(k) == n){ if(reserveli.contains(n-1)){ answer++; reserveli.remove(reserveli.indexOf(n-1)); } }else{ if(reserveli.contains(lostli.get(k)-1)){ answer++; reserveli.remove(reserveli.indexOf(lostli.get(k)-1)); }else if(reserveli.contains(lostli.get(k)+1)){ answer++; reserveli.remove(reserveli.indexOf(lostli.get(k)+1)); } } k++; } return answer; } }<file_sep>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Main { static ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); static BufferedWriter bw; static boolean[] visited; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int V = Integer.parseInt(st.nextToken()); for(int i = 0; i <= N; i++) { graph.add(new ArrayList<Integer>()); } for (int i = 0; i < M; i++){ st = new StringTokenizer(br.readLine()); int first = Integer.parseInt(st.nextToken()); int second = Integer.parseInt(st.nextToken()); graph.get(first).add(second); graph.get(second).add(first); } for (int i = 1; i <= N; i++){ Collections.sort(graph.get(i)); } visited = new boolean[N+1]; dfs(V); bw.newLine(); visited = new boolean[N+1]; Queue<Integer> qu = new LinkedList<>(); qu.offer(V); visited[V] = true; while(!qu.isEmpty()){ int x = qu.poll(); bw.write(x + " "); for(int i = 0; i < graph.get(x).size(); i++){ int y = graph.get(x).get(i); if(!visited[y]){ qu.offer(y); visited[y] = true; } } } br.close(); bw.flush(); bw.close(); } static void dfs(int index) throws IOException{ // 종료 조건 if(visited[index]){ return; } visited[index] = true; bw.write(index + " "); // 재귀 for(int i = 0; i < graph.get(index).size(); i++){ int x = graph.get(index).get(i); if(!visited[x]){ dfs(x); } } } } <file_sep>-- 코드를 입력하세요 SELECT NAME, DATETIME FROM ( SELECT NAME, DATETIME FROM ANIMAL_INS I WHERE I.ANIMAL_ID NOT IN (SELECT ANIMAL_ID FROM ANIMAL_OUTS) ORDER BY I.DATETIME ) WHERE ROWNUM <= 3;<file_sep>import java.util.*; class Solution { public long solution(String expression) { long answer = 0; boolean[] used = new boolean[3]; char[][] ops = {{ '+', '-', '*' }, {'+', '*', '-'}, { '-', '+', '*' }, {'-', '*', '+'}, { '*', '-', '+' }, {'*', '+', '-'}}; for(int i = 0; i < ops.length; i++) { answer = Math.max(answer, convert(expression,ops[i])); } return answer; } public long convert(String exp, char[] ops) { String[] numbers = exp.split("[*+-]+"); String[] op = exp.split("[0-9]+"); ArrayList<Long> li_nums = new ArrayList(); ArrayList<Character> li_op = new ArrayList(); for (int i = 0; i < numbers.length; i++) { li_nums.add(Long.parseLong(numbers[i])); } for (int i = 0; i < op.length; i++) { if (!op[i].equals("")) { li_op.add(op[i].charAt(0)); } } for (int i = 0; i < 3; i++) { char now_op = ops[i]; int r = 0; for (int j = 0; j < li_op.size(); j++) { if (li_op.get(j) == now_op) { int idx = j - r; if (now_op == '-') { long sum = li_nums.remove(idx) - li_nums.remove(idx); li_nums.add(idx, sum); r++; } else if (now_op == '+') { long sum = li_nums.remove(idx) + li_nums.remove(idx); li_nums.add(idx, sum); r++; } else { long sum = li_nums.remove(idx) * li_nums.remove(idx); li_nums.add(idx, sum); r++; } } } while (li_op.contains(now_op)) { li_op.remove((Object)now_op); } } return Math.abs(li_nums.get(0)); } }<file_sep>-- 코드를 입력하세요 SELECT I.ANIMAL_ID, I.NAME FROM ANIMAL_INS I, ANIMAL_OUTS O WHERE I.ANIMAL_ID = O.ANIMAL_ID ORDER BY (O.DATETIME - I.DATETIME) DESC FETCH FIRST 2 ROWS ONLY -- 이런 것도 있네요. -- SELECT ANIMAL_ID, NAME -- FROM ( -- SELECT O.ANIMAL_ID, O.NAME, O.DATETIME -- FROM ANIMAL_INS I, ANIMAL_OUTS O -- WHERE I.ANIMAL_ID = O.ANIMAL_ID -- ORDER BY O.DATETIME-I.DATETIME DESC -- 보호기간이 가장 길었던 -- ) -- WHERE ROWNUM <= 2;<file_sep>-- 코드를 입력하세요 SELECT O.ANIMAL_ID, O.NAME FROM ANIMAL_INS I, ANIMAL_OUTS O WHERE I.ANIMAL_ID = O.ANIMAL_ID AND I.DATETIME > O.DATETIME ORDER BY I.DATETIME;<file_sep>-- 코드를 입력하세요 SELECT NAME, DATETIME from (select NAME, DATETIME from ANIMAL_INS where ANIMAL_ID not in (select ANIMAL_ID from ANIMAL_OUTS) order by DATETIME) where rownum <= 3;<file_sep>select h.h_id, hc.name from(select sb.hacker_id h_id, count(sb.hacker_id) cnt from(select challenge_id, score sc from difficulty d, challenges c where c.difficulty_level = d.difficulty_level group by challenge_id, score) s, submissions sb where s.sc = sb.score and s.challenge_id = sb.challenge_id group by sb.hacker_id having count(sb.hacker_id) > 1) h, hackers hc where h.h_id = hc.hacker_id order by h.cnt desc, h.h_id;<file_sep>SELECT CASE WHEN B.GRADE < 8 THEN NULL ELSE A.NAME END, B.GRADE, A.MARKS FROM STUDENTS A JOIN GRADES B ON A.MARKS BETWEEN B.MIN_MARK AND MAX_MARK ORDER BY B.GRADE DESC, A.NAME; <file_sep>-- 코드를 입력하세요 SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE LOWER(NAME) LIKE '%el%' AND ANIMAL_TYPE = 'Dog' ORDER BY NAME;<file_sep>import java.util.*; class Solution { public int solution(String name) { int answer = 0; int n = name.length(); int[] arr = new int[n]; int max, temp; max = temp = 0; for(int i = 0; i < n; i++){ arr[i] = Math.min(name.charAt(i)-'A','Z'-name.charAt(i)+1); answer += arr[i]; if(arr[i] == 0){ temp++; }else{ max = Math.max(max,temp); temp = 0; } } if(max == 0){ // A가 하나도 없는 경우 answer += n-1; }else{ StringBuilder sb = new StringBuilder(); for(int i = 0; i < max; i++){ sb.append("A"); } int idx = name.indexOf(sb.toString()); // 가장 긴 연속된 A의 시작점 //BBAB AAAAAAA BB // idx //(idx-2)*2 = BBA 왕복 // +1 = B에 한번 가는 if(n-1 > (idx-1)*2+(n-(idx+max))){ answer+= (idx-1)*2+(n-(idx+max)); }else{ answer += n-1; } } System.out.println(Arrays.toString(arr)); return answer; } }<file_sep>SELECT ANIMAL_ID,NAME FROM ANIMAL_INS ORDER BY ANIMAL_ID;<file_sep>select t1.animal_id,t1.name From (SELECT ins.animal_id, ins.name from ANIMAL_INS ins, animal_outs outs where ins.animal_id = outs.animal_id order by (outs.datetime - ins.datetime) desc) t1 where rownum <= 2;<file_sep>import java.util.*; class Solution { static int[] move_x = {0,0,1,-1}; static int[] move_y = {1,-1,0,0}; public int[] solution(int m, int n, int[][] picture) { int numberOfArea = 0; int maxSizeOfOneArea = 0; boolean[][] visited = new boolean[m][n]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(picture[i][j] == 0){ visited[i][j] = true; } } } for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(!visited[i][j]){ numberOfArea++; Deque<Pair> q = new ArrayDeque(); q.add(new Pair(i,j,picture[i][j])); visited[i][j] = true; int temp = 0; while(!q.isEmpty()){ Pair now = q.poll(); temp++; for(int k = 0; k < 4; k++){ int next_x = now.x+move_x[k]; int next_y = now.y+move_y[k]; if(0 <= next_x && next_x < m && 0 <= next_y && next_y < n && picture[next_x][next_y] == now.val && !visited[next_x][next_y]){ q.add(new Pair(next_x,next_y,now.val)); visited[next_x][next_y] = true; } } } maxSizeOfOneArea = Math.max(temp,maxSizeOfOneArea); } } } int[] answer = new int[2]; answer[0] = numberOfArea; answer[1] = maxSizeOfOneArea; return answer; } static class Pair{ int x,y,val; public Pair(int x, int y, int val){ this.x = x; this.y = y; this.val = val; } } }<file_sep>import java.util.*; class Solution { public int solution(String[][] clothes) { int answer = 1; HashMap<String,Integer> map = new HashMap<>(); for(int i = 0; i < clothes.length; i++) { map.put(clothes[i][1], map.getOrDefault(clothes[i][1], 0)+1); } if(map.size() == 1) { answer = map.get(clothes[0][1]); }else { for(String str : map.keySet()) { answer *= (map.get(str)+1); } answer--; } return answer; } } // 이전 풀이 /*import java.util.*; class Solution { public int solution(String[][] clothes) { int answer = 1, cnt = 0; HashMap<String,Integer> map = new HashMap<>(); for(int i = 0; i < clothes.length;i++){ String cate = clothes[i][1]; if(map.putIfAbsent(cate,1) != null){ map.replace(cate,map.get(cate)+1); }else{ cnt++; } } if(cnt == 1){ answer = map.get(clothes[0][1]); }else{ // 종류 2개 이상 for(String str : map.keySet()){ answer *= (map.get(str)+1); } answer--; } return answer; } } */<file_sep>-- 코드를 입력하세요 SELECT O.ANIMAL_ID, O.ANIMAL_TYPE, O.NAME FROM ANIMAL_INS I, ANIMAL_OUTS O WHERE I.ANIMAL_ID = O.ANIMAL_ID AND I.SEX_UPON_INTAKE LIKE '%Intact%' AND O.SEX_UPON_OUTCOME NOT LIKE '%Intact%' ORDER BY O.ANIMAL_ID;<file_sep>SELECT NAME , COUNT(NAME) FROM ANIMAL_INS GROUP BY NAME HAVING NAME IS NOT NULL AND COUNT(NAME) > 1 ORDER BY NAME; <file_sep>SELECT ANIMAL_ID,NAME, TO_CHAR(DATETIME,'yyyy-MM-dd') as ³¯Â¥ From ANIMAL_INS order by ANIMAL_ID;<file_sep>/* Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */ SET SERVEROUTPUT ON; DECLARE I NUMBER; J NUMBER; BEGIN FOR I IN REVERSE 1..20 LOOP FOR J IN 1..I LOOP DBMS_OUTPUT.PUT('* '); END LOOP; DBMS_OUTPUT.NEW_LINE; END LOOP; END; /<file_sep>/* https://www.hackerrank.com/challenges/challenges/problem https://ysyblog.tistory.com/202 Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */ SELECT h.hacker_id, h.name, COUNT(*) FROM Hackers h, Challenges c WHERE h.hacker_id = c.hacker_id GROUP BY (h.hacker_id, h.name) HAVING COUNT(*) = ( SELECT MAX(COUNT(*)) FROM Challenges GROUP BY hacker_id ) OR COUNT(*) IN ( SELECT cnt FROM ( SELECT COUNT(*) cnt FROM Challenges GROUP BY hacker_id ) GROUP BY cnt HAVING COUNT(cnt) = 1 ) ORDER BY COUNT(*) DESC, h.hacker_id;<file_sep>class Solution { public int[] solution(int brown, int yellow) { int[] answer = new int[2]; int brHeight = 3; int brWidth = 3; int yeHeight = 0; int yeWidth = 0; while(true){ yeHeight = brHeight - 2; yeWidth = (brown - (brHeight * 2)) / 2; brWidth = yeWidth + 2; if (yellow == yeHeight * yeWidth){ break; } brHeight++; } answer[0] = brWidth; answer[1] = brHeight; return answer; } } <file_sep>SELECT A.HACKER_ID, A.NAME, B.SCORE FROM HACKERS A JOIN ( SELECT HACKER_ID, SUM(SCORE) AS SCORE FROM ( SELECT HACKER_ID, MAX(SCORE) AS SCORE FROM SUBMISSIONS GROUP BY HACKER_ID, CHALLENGE_ID ) GROUP BY HACKER_ID HAVING SUM(SCORE) > 0 ) B ON A.HACKER_ID = B.HACKER_ID ORDER BY B.SCORE DESC, A.HACKER_ID; <file_sep>class Solution { public int solution(String name) { // 못 품 // https://hellodavid.tistory.com/4 int answer = 0; int len = name.length(); // 제일 짧은 좌, 우 이동은 그냥 맨 오른쪽으로 이동할 때 int min = len - 1; for(int i =0; i < len; i++) { // 조이스틱 상, 하 이동 char c = name.charAt(i); int mov = (c - 'A' < 'Z' - c + 1) ? (c - 'A') : ('Z' - c + 1); answer += mov; // 조이스틱 좌, 우 이동 int nextIndex = i + 1; // 다음 단어가 A이고, 단어가 끝나기 전까지 nextIndex 증가 while(nextIndex < len && name.charAt(nextIndex) == 'A') nextIndex++; min = Math.min(min, (i * 2) + len - nextIndex); } answer += min; return answer; } }<file_sep>import java.util.*; class Solution { public int[] solution(int[] array, int[][] commands) { int[] answer = new int[commands.length]; for(int i = 0; i < commands.length; i++){ int[] temp = new int[1+commands[i][1]-commands[i][0]]; for(int j = 0; j < temp.length;j++){ temp[j] = array[commands[i][0]-1+j]; } Arrays.sort(temp); answer[i] = temp[commands[i][2]-1]; } return answer; } }<file_sep>import java.util.*; class Solution { public int solution(int[] scoville, int K) { int answer = 0; PriorityQueue<Integer> heap = new PriorityQueue<>(); for (int k : scoville){ heap.offer(k); } while(heap.size() > 1){ if(heap.peek() < K){ heap.offer(heap.poll() + (heap.poll() * 2)); answer++; } else { break; } } if(heap.size() == 1 && heap.peek() < K){ answer=-1; } return answer; } } <file_sep>class Solution { public int solution(String name) { int answer = 0; int len = name.length(); // 맨오른쪽으로 하나씩 이동할 때 (초기값) int min = len - 1; // JAACBZ // i는 다음에 움직여야할 위치 // 다음에 움직여야할 위치가 왼쪽으로 갈 때와 오른쪽으로 갈때 를 비교해서 방향을 정한다. for(int i = 0; i < len; i++){ char word = name.charAt(i); answer += (word-'A' <= 'Z' - word + 1) ? word-'A' : 'Z' - word + 1; int nextIndex = i + 1; while(nextIndex < len && name.charAt(nextIndex) == 'A'){ nextIndex++; } min = Math.min(min, (i * 2) + len - nextIndex); } answer += min; return answer; } } // 참조 : https://hellodavid.tistory.com/4 <file_sep>import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static int n; public static int[][] players; public static int[] lineUp = new int[10]; public static boolean[] visited = new boolean[10]; public static int answer = 0; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; n = Integer.parseInt(br.readLine()); players = new int[n + 1][10]; for (int i = 1; i <= n; i++) { st = new StringTokenizer(br.readLine()); for (int j = 1; j <= 9; j++) { players[i][j] = Integer.parseInt(st.nextToken()); } } // 1번 선수 4번 타자 지명 lineUp[4] = 1; visited[4] = true; // 타자 순번 지정 makeOrder(2); System.out.println(answer); } public static void makeOrder(int depth) { if (depth == 10) { playBaseBall(); // 야구게임시작 return; } for (int i = 1; i <= 9; i++) { if (!visited[i]) { visited[i] = true; lineUp[i] = depth; makeOrder(depth + 1); visited[i] = false; } } } public static void playBaseBall() { int score = 0; int startPlayer = 1; // 이닝시작타자순번 boolean[] base; // base에 있는 타자 // n번째 이닝 for (int i = 1; i <= n; i++) { int out = 0; // 아웃된 사람 수 base = new boolean[4]; // base 초기화 // 아웃카운트가 3개일 때까지 반복 finish: while (true) { for (int j = startPlayer; j <= 9; j++) { int hit = players[i][lineUp[j]]; // j번째 타자의 행동 if (hit == 0) { // 아웃 out++; } // 1루타 else if (hit == 1) { for (int k = 3; k >= 1; k--) { if (base[k]) { if (k == 3) { // 3루에 있는 선수 홈으로 score++; base[k] = false; continue; } // 1, 2루에 있는 선수들 진루 base[k] = false; base[k + 1] = true; } } base[1] = true; // 홈에서 1루로 진루 } // 2루타 else if (hit == 2) { for (int k = 3; k >= 1; k--) { if (base[k]) { if (k == 3 || k == 2) { // 3루, 2루 선수 홈으로 score++; base[k] = false; continue; } // 1루에 있는 선수 진루 base[k] = false; base[k + 2] = true; } } base[2] = true; // 홈에서 2루로 진루 } // 3루타 else if (hit == 3) { for (int k = 3; k >= 1; k--) { if (base[k]) { // 홈 제외 모든 선수 홈으로 score++; base[k] = false; } } base[3] = true; // 홈에서 3루로 진루 } // 홈런 else if (hit == 4) { for (int k = 3; k >= 1; k--) { if (base[k]) { // 주자들 모두 홈으로 score++; base[k] = false; } } score++; // 홈런 타자 1점 추가 } if (out == 3) { // 아웃 카운트가 3개면 // 다음 이닝 시작타자 설정 startPlayer = j + 1; if (startPlayer == 10) { startPlayer = 1; } break finish; } } // End for // 이닝이 다 끝나서 1번부터 시작 startPlayer = 1; } // End while } // End for answer = Math.max(answer, score); } // End playBaseBall } <file_sep>import java.util.*; class Solution { public int solution(int N, int number) { HashSet<Integer>[] set = new HashSet[9]; for(int i = 1; i < 9; i++){ set[i] = new HashSet<Integer>(); } set[1].add(N); if(N == number){ return 1; } for(int i = 2; i < 9; i++){ // N을 i번 붙여서 만드는 케이스 StringBuilder sb = new StringBuilder(); for(int j = 0; j < i; j++){ sb.append(N); } int addNum = Integer.parseInt(sb.toString()); if(addNum == number){ return i; } set[i].add(addNum); // 1,1 2개 사용 // 1,2 3개 사용 // 2,2 1,3 4개 사용 // 1,4 2,3 5개 사용 // 1,5, 2,4, 3,3 6개 사용 for(int j = 1; j <= i/2; j++){ Iterator iter1 = set[i-j].iterator(); // 기존에 만들어진 수에 사칙 연산 추가 while(iter1.hasNext()){ int now = (int)iter1.next(); Iterator iter2 = set[j].iterator(); while(iter2.hasNext()){ int now2 = (int)iter2.next(); set[i].add(now+now2); set[i].add(now*now2); if(now2 != 0) set[i].add(now/now2); set[i].add(now-now2); if(now != 0) set[i].add(now2/now); set[i].add(now2-now); } } if(set[i].contains(number)){ return i; } } } return -1; } }<file_sep>SELECT ANIMAL_TYPE,NVL(NAME,'No name'),SEX_UPON_INTAKE from ANIMAL_INS order by ANIMAL_ID;<file_sep>import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int computer = Integer.parseInt(br.readLine()); int n = Integer.parseInt(br.readLine()); int[][] map = new int[computer][computer]; for(int i = 0; i < n; i++){ st = new StringTokenizer(br.readLine()); int x = Integer.parseInt(st.nextToken())-1; int y = Integer.parseInt(st.nextToken())-1; map[x][y] = 1; map[y][x] = 1; } boolean[] visited = new boolean[computer]; int answer = 0; ArrayDeque<Integer>q = new ArrayDeque<>(); q.add(0); visited[0] = true; while(!q.isEmpty()){ int now = q.poll(); for(int i = 0; i < computer; i++){ if(!visited[i] && map[now][i] == 1){ q.add(i); visited[i] = true; answer++; } } } System.out.println(answer); } }<file_sep>SELECT ins.ANIMAL_ID, ANIMAL_TYPE, NAME FROM ANIMAL_INS ins, (SELECT ANIMAL_ID FROM ANIMAL_OUTS WHERE SEX_UPON_OUTCOME like '%Neutered%' or SEX_UPON_OUTCOME like '%Spayed%') outs WHERE SEX_UPON_INTAKE like '%Intact%' and ins.ANIMAL_ID = outs.ANIMAL_ID order by ins.ANIMAL_ID; -- review SELECT T1.ANIMAL_ID, ANIMAL_TYPE, NAME FROM (SELECT ANIMAL_ID FROM ANIMAL_INS WHERE SEX_UPON_INTAKE LIKE 'Intact%') T1, ANIMAL_OUTS T2 WHERE T1.ANIMAL_ID = T2.ANIMAL_ID AND SEX_UPON_OUTCOME NOT LIKE 'Intact%' ORDER BY T1.ANIMAL_ID; <file_sep>SELECT ANIMAL_ID, NAME, DATETIME FROM ANIMAL_INS ORDER BY NAME, DATETIME DESC; <file_sep>import java.util.*; class Solution { static boolean[] visited; public int solution(int n, int[][] computers) { int answer = 0; visited = new boolean[n]; for(int i = 0; i < computers.length; i++){ if(visited[i]){ continue; } rec(computers,i); answer++; } return answer; } static void rec(int[][] computers, int start){ for(int i = 0; i < computers[start].length; i++){ if(i == start){ continue; } if(computers[start][i] == 0){ continue; } if(!visited[i] && computers[start][i] == 1){ visited[i] = true; rec(computers,i); } } } }<file_sep>SELECT CART_ID FROM (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME IN 'Yogurt' GROUP BY CART_ID) WHERE CART_ID IN (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME IN 'Milk' GROUP BY CART_ID) ORDER BY CART_ID; <file_sep>/* https://www.hackerrank.com/challenges/contest-leaderboard/problem Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */ SELECT hacker_id, name, SUM(score) FROM ( SELECT S.hacker_id AS hacker_id, H.name AS name, MAX(S.score) AS score FROM Submissions S, Hackers H WHERE S.hacker_id = H.hacker_id GROUP BY (S.hacker_id, H.name, S.challenge_id) ) GROUP BY (hacker_id, name) HAVING SUM(score) != 0 ORDER BY SUM(score) DESC, hacker_id; <file_sep>import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); int[][] map = new int[N][N]; for(int i = 0; i < N; i++) { String str = br.readLine(); for(int j = 0; j < N; j++) { map[i][j] = str.charAt(j)-'0'; } } ArrayList<Integer> arr = new ArrayList<Integer>(); boolean[][] visited = new boolean[N][N]; int[] mx = {-1,1,0,0}; int[] my = {0,0,1,-1}; for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { if(!visited[i][j] && map[i][j] == 1) { ArrayDeque<Integer> q = new ArrayDeque<Integer>(); q.add(i); q.add(j); int cnt = 1; visited[i][j] = true; while(!q.isEmpty()) { int x = q.poll(); int y = q.poll(); for(int k = 0; k < 4; k++) { int next_x = x+mx[k]; int next_y = y+my[k]; if(next_x <0 || next_x >= N || next_y < 0 || next_y >= N) { continue; } if(!visited[next_x][next_y] && map[next_x][next_y] == 1) { visited[next_x][next_y] = true; q.add(next_x); q.add(next_y); cnt++; } } } arr.add(cnt); } } } arr.sort(null); System.out.println(arr.size()); for(int i = 0; i < arr.size(); i++) { System.out.println(arr.get(i)); } } }<file_sep>SELECT ANIMAL_ID, NAME FROM ( SELECT A.ANIMAL_ID, A.NAME, (B.DATETIME - A.DATETIME) AS DATETIME FROM ANIMAL_INS A JOIN ANIMAL_OUTS B ON A.ANIMAL_ID = B.ANIMAL_ID ORDER BY DATETIME DESC ) WHERE ROWNUM < 3 <file_sep>SELECT * FROM ANIMAL_INS ORDER BY ANIMAL_ID;<file_sep>import java.util.*; class Solution { public int solution(String[][] clothes) { int answer = clothes.length; // 옷 종류가 1개이면 그냥 갯수 반환 Map<String, ArrayList<String>> wears = new HashMap<>(); for(int i=0; i < clothes.length; i++) { String[] cloth = clothes[i]; if(!wears.containsKey(cloth[1])) { wears.put(cloth[1], new ArrayList<String>()); } wears.get(cloth[1]).add(cloth[0]); } if(wears.size() > 1) { // 2개 이상의 종류가 있다면 int result = 1; for(String key : wears.keySet()) { // 모든 종류의 옷 int n = wears.get(key).size(); result *= n + 1; // 경우의 수 *= (다른 종류 옷의 갯수 + 그 옷 선택 안한 경우) } answer = result - 1; // 다 안입었을 경우 뺴기 } return answer; } }<file_sep>/* https://bbeomgeun.tistory.com/66 Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */ SELECT W.id, WP.age, W.coins_needed, W.power FROM Wands W, Wands_Property WP, ( SELECT code, min(coins_needed) as coins_needed, power FROM Wands GROUP BY (code, power) ) M WHERE W.code = WP.code AND W.code = M.code AND WP.code = M.code AND W.coins_needed = M.coins_needed AND WP.is_evil = 0 ORDER BY W.power DESC, WP.age DESC;<file_sep>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { static int result = 0; static boolean[] visited; static ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; int N = Integer.parseInt(br.readLine()); int M = Integer.parseInt(br.readLine()); visited = new boolean[N+1]; for(int i = 0; i <= N; i++){ graph.add(new ArrayList<Integer>()); } for(int i = 0; i < M; i++){ st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); graph.get(a).add(b); graph.get(b).add(a); } // dfs 실행 dfs(1); result--; bw.write(result + ""); br.close(); bw.flush(); bw.close(); } static void dfs(int depth){ // 종료조건 if(visited[depth]){ return; } // 재귀 visited[depth] = true; result++; for(int i = 0; i < graph.get(depth).size(); i++){ dfs(graph.get(depth).get(i)); } } } <file_sep>select case when grade <= 7 then NULL else s.name end cname ,grade, s.marks from grades g, students s where g.min_mark <= s.marks and s.marks <= max_mark order by grade desc, s.name;<file_sep>SELECT W.ID, P.AGE, A.COIN, W.POWER FROM WANDS W , WANDS_PROPERTY P , (SELECT CODE, MIN(COINS_NEEDED) AS COIN, POWER FROM WANDS GROUP BY CODE, POWER) A WHERE W.CODE = A.CODE AND W.POWER = A.POWER AND W.COINS_NEEDED = A.COIN AND W.CODE = P.CODE AND P.IS_EVIL = 0 ORDER BY W.POWER DESC, P.AGE DESC; <file_sep>import java.util.*; class Node { int x, y; public Node(int x, int y) { this.x = x; this.y = y; } } class Solution { public int solution(int n, int[][] computers) { // 질문하기 봄.. int answer = 0; // 1인 곳 bfs for(int i=0; i < n; i++) { for(int j=0; j < n; j++) { if(computers[i][j] == 1) { bfs(computers, i, j, n); answer++; } } } return answer; } public static void bfs(int[][] computers, int i, int j, int n) { HashSet<Integer> visited = new HashSet<>(); Queue<Node> q = new LinkedList<>(); q.add(new Node(i, j)); // 연결된 노드 처리 while(!q.isEmpty()) { // a -> b Node node = q.remove(); int x = node.x; int y = node.y; visited.add(y); // b -> c for(int k=0; k < n; k++) { if(computers[y][k] == 1) { if(!visited.contains(k)) q.add(new Node(y, k)); computers[y][k] = 0; } } } } }<file_sep>class Solution { public static int n; public static int target; public static int answer = Integer.MAX_VALUE; public int solution(int N, int number) { // 못 품 // https://velog.io/@jwkim/DFS-n-expression n = N; target = number; dfs(0, 0); return answer == Integer.MAX_VALUE ? -1 : answer; } public void dfs(int count, int prev) { if(count > 8) { answer = -1; return; } if(prev == target) { System.out.print(count + " "); answer = Math.min(answer, count); return; } int tempN = n; for(int i=0; i < 8 - count; i++) { int newCount = count + i + 1; dfs(newCount, prev + tempN); dfs(newCount, prev - tempN); dfs(newCount, prev / tempN); dfs(newCount, prev * tempN); tempN = tempN * 10 + n; } } }<file_sep>SELECT ins.ANIMAL_ID, ins.NAME FROM ANIMAL_INS ins, ANIMAL_OUTS outs Where ins.ANIMAL_ID = outs.ANIMAL_ID and ins.DATETIME > outs.DATETIME ORDER BY ins.DATETIME<file_sep>// 참고 : https://fbtmdwhd33.tistory.com/225 class Solution { static int numberOfArea; static int maxSizeOfOneArea; static int temp_cnt = 0; static int[] dx = {-1, 1, 0, 0}; static int[] dy = {0, 0, -1, 1}; public static void dfs(int x, int y, int[][] picture, boolean[][] visited){ if(visited[x][y]) return; visited[x][y] = true; temp_cnt++; for(int i = 0; i < 4; i++){ int nx = x + dx[i]; int ny = y + dy[i]; if(nx < 0 || nx >= picture.length || ny < 0 || ny >= picture[0].length) continue; if(picture[x][y] == picture[nx][ny] && !visited[nx][ny]){ dfs(nx, ny, picture, visited); } } } public int[] solution(int m, int n, int[][] picture) { int numberOfArea = 0; int maxSizeOfOneArea = 0; int[] answer = new int[2]; answer[0] = numberOfArea; answer[1] = maxSizeOfOneArea; boolean[][] visited = new boolean[m][n]; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(picture[i][j] != 0 && !visited[i][j]){ numberOfArea++; dfs(i, j, picture, visited); } if(temp_cnt > maxSizeOfOneArea) maxSizeOfOneArea = temp_cnt; temp_cnt = 0; } } answer[0] = numberOfArea; answer[1] = maxSizeOfOneArea; return answer; } } <file_sep>SELECT ANIMAL_ID, NAME, CASE WHEN SEX_UPON_INTAKE LIKE '%Neutered%' OR SEX_UPON_INTAKE LIKE '%Spayed%' THEN 'O' ELSE 'X' END 중성화 FROM ANIMAL_INS ORDER BY ANIMAL_ID; <file_sep>SELECT ANIMAL_ID, NAME FROM ANIMAL_INS WHERE ANIMAL_TYPE = 'Dog' AND UPPER(NAME) LIKE '%EL%' ORDER BY NAME; <file_sep>import java.util.*; class Solution { public int[] solution(int[] answers) { int[] answer; int[] scores = new int[3]; int[] pattern1 = {1, 2, 3, 4, 5}; // 5 int[] pattern2 = {2, 1, 2, 3, 2, 4, 2, 5}; // 8 int[] pattern3 = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5}; // 10 ArrayList<Integer> listAnswer = new ArrayList<>(); for (int i = 0; i < answers.length; i++){ int ans = answers[i]; if (ans == pattern1[i % 5]){ scores[0]++; } if (ans == pattern2[i % 8]){ scores[1]++; } if (ans == pattern3[i % 10]){ scores[2]++; } } int max = Math.max(scores[0], Math.max(scores[1], scores[2])); for(int i = 0; i < scores.length; i++){ if(max == scores[i]){ listAnswer.add(i+1); } } answer = listAnswer.stream().mapToInt(i->i).toArray(); return answer; } } <file_sep>import java.io.*; import java.util.*; public class Main { static int[][] player; static int answer; static int N; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; N = Integer.parseInt(br.readLine()); player = new int[N][9]; for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < 9; j++) { player[i][j] = Integer.parseInt(st.nextToken()); } } boolean[] visited = new boolean[9]; visited[0] = true; play(visited, 0, new int[9]); System.out.println(answer); } static void play(boolean[] visited, int depth, int[] arr) { if (depth == 9) { // 선수 배치 완료 int out = 0; int score = 0; int idx = 0; int round = 0; int[] ground = new int[4]; while (round < N) { while (out < 3) { if (player[round][arr[idx % 9]] == 0) { out++; } else { if (player[round][arr[idx % 9]] == 1) { // 안타 for (int i = 2; i >= 0; i--) { if (ground[i] == 1) { ground[i + 1]++; ground[i]--; } } ground[0]++; } else if (player[round][arr[idx % 9]] == 2) { // 2루타 for (int i = 2; i >= 0; i--) { if (ground[i] == 1) { if (i + 2 >= 3) { ground[3]++; ground[i]--; } else { ground[i + 2]++; ground[i]--; } } } ground[1]++; } else if (player[round][arr[idx % 9]] == 3) { // 3루타 for (int i = 2; i >= 0; i--) { if (ground[i] == 1) { ground[3]++; ground[i]--; } } ground[2]++; } else if (player[round][arr[idx % 9]] == 4) { for (int i = 2; i >= 0; i--) { if (ground[i] == 1) { ground[3]++; ground[i]--; } } ground[3]++; } score += ground[3]; ground[3] = 0; } idx++; } round++; out = 0; ground = new int[4]; } if (score > answer) { answer = score; } return; } if (depth == 3) { arr[depth] = 0; play(visited, depth + 1, arr); } else { for (int i = 0; i < 9; i++) { if (!visited[i]) { visited[i] = true; arr[depth] = i; play(visited, depth + 1, arr); visited[i] = false; } } } } } <file_sep>SELECT ID, NAME, HOST_ID FROM PLACES WHERE HOST_ID in (SELECT HOST_ID FROM PLACES GROUP BY HOST_ID HAVING count(HOST_ID) > 1) Order by ID<file_sep>SELECT ANIMAL_ID,NAME ,CASE when SEX_UPON_INTAKE like '%Neutered%' then 'O' when SEX_UPON_INTAKE like'%Spayed%' then 'O' else 'X' end AS Áß¼ºÈ­ From ANIMAL_INS Order by ANIMAL_ID;<file_sep>-- 코드를 입력하세요 -- SELECT HOST_ID FROM PLACES GROUP BY HOST_ID HAVING COUNT(HOST_ID) > 1 SELECT ID, NAME, HOST_ID FROM PLACES WHERE HOST_ID IN ( SELECT HOST_ID FROM PLACES GROUP BY HOST_ID HAVING COUNT(HOST_ID) > 1 ) ORDER BY ID;<file_sep>import java.util.*; class Solution { public int solution(int[] citations) { // https://en.wikipedia.org/wiki/H-index 내용 // 먼저 f 의 값을 가장 큰 값에서 가장 낮은 값으로 정렬합니다. // 그런 다음 f 가 위치 보다 크거나 같은 마지막 위치를 찾습니다 ( h를 이 위치라고 함). int answer = 0; // 초기 값 0으로 설정 int n = citations.length; // 논문 수 // 내림차순 정렬 Integer[] f = Arrays.stream(citations).boxed().toArray(Integer[]::new); Arrays.sort(f, Collections.reverseOrder()); // 예시 // f(x):h-index -> f(x-1):h-index+1 -> f(x-2):h-index+2 -> ... // 10:1 -> 8:2 -> 5:3 -> 4:(4) -> 3:5 → h -index=4 for(int i=0, hIndex = 1; i < n; i++, hIndex++) { if(f[i] >= hIndex) answer = hIndex; else break; } return answer; } }<file_sep>SELECT city.name from city, country where city.countrycode = country.code and continent = 'Africa';<file_sep>import java.util.*; class Solution { public int solution(int n, int[][] edge) { int answer = 1; ArrayList<Integer>[] g = new ArrayList[n+1]; for(int i = 1; i < n+1; i++){ g[i] = new ArrayList<>(); } for(int i = 0; i < edge.length; i++){ g[edge[i][0]].add(edge[i][1]); g[edge[i][1]].add(edge[i][0]); } boolean[] visited = new boolean[n+1]; visited[1] = true; Deque<Node> q = new ArrayDeque<>(); q.add(new Node(1,0)); int max_depth = 0; while(!q.isEmpty()){ Node now = q.poll(); for(int i : g[now.v]){ if(!visited[i]){ visited[i] = true; if(max_depth < now.depth+1){ max_depth = now.depth+1; answer = 1; }else if(max_depth == now.depth+1){ answer++; } q.add(new Node(i,now.depth+1)); } } } return answer; } static public class Node{ int v, depth; public Node(int v, int depth){ this.v = v; this.depth = depth; } } }<file_sep>-- INS = ANIMAL_INS -- OUTS = ANIMAL_OUTS SELECT INS.ANIMAL_ID, INS.ANIMAL_TYPE, INS.NAME FROM (SELECT ANIMAL_ID, ANIMAL_TYPE, NAME FROM ANIMAL_INS WHERE SEX_UPON_INTAKE LIKE 'Intact%') INS LEFT JOIN ANIMAL_OUTS OUTS ON INS.ANIMAL_ID = OUTS.ANIMAL_ID WHERE OUTS.SEX_UPON_OUTCOME NOT LIKE 'Intact%' ORDER BY INS.ANIMAL_ID ------------------------------------------------------ SELECT A.ANIMAL_ID, A.ANIMAL_TYPE, A.NAME FROM (SELECT ANIMAL_ID, ANIMAL_TYPE, NAME FROM ANIMAL_INS WHERE SEX_UPON_INTAKE LIKE ('Intact%')) A JOIN (SELECT ANIMAL_ID FROM ANIMAL_OUTS WHERE SEX_UPON_OUTCOME NOT LIKE ('Intact%')) B ON A.ANIMAL_ID = B.ANIMAL_ID; <file_sep>-- 코드를 입력하세요 SELECT CART_ID FROM CART_PRODUCTS WHERE CART_ID IN (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME = 'Yogurt') AND CART_ID IN (SELECT CART_ID FROM CART_PRODUCTS WHERE NAME = 'Milk') GROUP BY CART_ID ORDER BY CART_ID;<file_sep>SELECT A.HACKER_ID, B.NAME FROM ( SELECT SUB.HACKER_ID AS HACKER_ID, COUNT(*) AS CHALNUM FROM SUBMISSIONS SUB JOIN CHALLENGES CHAL ON SUB.CHALLENGE_ID = CHAL.CHALLENGE_ID JOIN DIFFICULTY DIFF ON CHAL.DIFFICULTY_LEVEL = DIFF.DIFFICULTY_LEVEL WHERE SUB.SCORE = DIFF.SCORE GROUP BY SUB.HACKER_ID HAVING COUNT(*) > 1 ) A JOIN HACKERS B ON A.HACKER_ID = B.HACKER_ID ORDER BY A.CHALNUM DESC, A.HACKER_ID; <file_sep>import java.util.*; class Node implements Comparable<Node> { private int index; private int distance; public Node(int index, int distance) { this.index = index; this.distance = distance; } public int getIndex() { return this.index; } public int getDistance() { return this.distance; } // 거리(비용)가 짧은 것이 높은 우선순위를 가지도록 설정 @Override public int compareTo(Node other) { if (this.distance < other.distance) { return -1; } return 1; } } class Solution { public static final int INF = (int) 1e9; // 무한을 의미하는 값으로 10억을 설정 public static int[] d; public static ArrayList<ArrayList<Node>> graph = new ArrayList<>();; public int solution(int n, int[][] edge) { int answer = 0; // 최단 거리 테이블 만들기 d = new int[n+1]; Arrays.fill(d, INF); // 그래프 초기화 for (int i = 0; i < n+1; i++) { graph.add(new ArrayList<Node>()); } for(int i=0; i < edge.length; i++) { graph.get(edge[i][0]).add(new Node(edge[i][1], 1)); graph.get(edge[i][1]).add(new Node(edge[i][0], 1)); } dijkstra(1); int max_val = 0; int cnt = 0; for(int i=1; i < d.length; i++) { if(max_val < d[i]) { // 최댓값 갱신 cnt = 1; max_val = d[i]; } else if(max_val == d[i]) { // 최댓값 카운트 cnt++; } } answer = cnt; return answer; } public static void dijkstra(int start) { PriorityQueue<Node> pq = new PriorityQueue<>(); // 시작 노드로 가기 위한 최단 경로는 0으로 설정하여, 큐에 삽입 pq.offer(new Node(start, 0)); d[start] = 0; while(!pq.isEmpty()) { // 큐가 비어있지 않다면 // 가장 최단 거리가 짧은 노드에 대한 정보 꺼내기 Node node = pq.poll(); int dist = node.getDistance(); // 현재 노드까지의 비용 int now = node.getIndex(); // 현재 노드 // 현재 노드가 이미 처리된 적이 있는 노드라면 무시 if (d[now] < dist) continue; // 현재 노드와 연결된 다른 인접한 노드들을 확인 for (int i = 0; i < graph.get(now).size(); i++) { int cost = d[now] + graph.get(now).get(i).getDistance(); // 현재 노드를 거쳐서, 다른 노드로 이동하는 거리가 더 짧은 경우 if (cost < d[graph.get(now).get(i).getIndex()]) { d[graph.get(now).get(i).getIndex()] = cost; pq.offer(new Node(graph.get(now).get(i).getIndex(), cost)); } } } } }<file_sep>SELECT COUNT(ANIMAL_ID) FROM ANIMAL_INS; <file_sep>SELECT CITY.NAME FROM CITY, COUNTRY WHERE CITY.CountryCode = COUNTRY.Code AND COUNTRY.CONTINENT = 'Africa';<file_sep>import java.util.*; class Solution { public int solution(int[] people, int limit) { int answer = 0; int peolen = people.length; // 사람 수 int left = 0; // 낮은 몸무게 int right = people.length-1; // 높은 몸무게 Arrays.sort(people); // 몸무게 오른차순 정렬 // 투 포인터 문제 while(left < right) { int sumVal = people[left] + people[right]; if(sumVal <= limit) { left++; right--; } else { right--; } answer++; if(left == right) { answer++; } } return answer; } }<file_sep> select h.hacker_id, h.name, cnt from (select hacker_id, count(challenge_id) cnt from challenges group by hacker_id) tb, hackers h where h.hacker_id = tb.hacker_id and cnt not in ( select distinct(t1.cnt) from (select hacker_id, count(challenge_id) cnt from challenges group by hacker_id) t1, (select hacker_id, count(challenge_id) cnt from challenges group by hacker_id) t2 where t1.hacker_id != t2.hacker_id and t1.cnt = t2.cnt and t1.cnt < (select max(count(challenge_id)) m_cnt from challenges group by hacker_id)) order by cnt desc, hacker_id;<file_sep>/* https://www.hackerrank.com/challenges/the-report/problem 참고 https://mirwebma.tistory.com/17 https://gent.tistory.com/311 Enter your query here. Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error. */ SELECT CASE WHEN grade >= 8 THEN name ELSE 'NULL' END AS name, grade, marks FROM Students, Grades WHERE Students.marks >= Grades.Min_Mark AND Students.marks <= Grades.Max_Mark ORDER BY grade DESC, name;<file_sep>SELECT CITY.NAME FROM CITY JOIN COUNTRY CON ON CITY.COUNTRYCODE = CON.CODE WHERE CON.CONTINENT = 'Africa'; <file_sep>-- A : ANIMAL_INS -- B : ANIMAL_OUT SELECT A.ANIMAL_ID, A.NAME FROM ANIMAL_INS A JOIN ANIMAL_OUTS B ON A.ANIMAL_ID = B.ANIMAL_ID WHERE A.DATETIME > B.DATETIME ORDER BY A.DATETIME <file_sep>import java.io.*; import java.util.*; public class Main { static int N; static int total; static int tempHouse; static boolean[][] graph; static boolean[][] visited; static int[] dx = { -1, 1, 0, 0 }; // 상하좌우 static int[] dy = { 0, 0, -1, 1 }; // 상하좌우 static ArrayList<Integer> house = new ArrayList<>(); public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); N = Integer.parseInt(br.readLine()); visited = new boolean[N+1][N+1]; // 그래프 초기화 graph = new boolean[N+1][N+1]; for(int i = 0; i < N; i++){ String row = br.readLine(); for(int j = 0; j < N; j++){ if (row.charAt(j) == '0'){ graph[i+1][j+1] = false; } else if (row.charAt(j) == '1'){ graph[i+1][j+1] = true; } } } for(int i = 1; i <= N; i++){ for(int j = 1; j<= N; j++){ if(!visited[i][j] && graph[i][j]){ total++; tempHouse = 0; dfs(i, j); house.add(tempHouse); } } } Collections.sort(house); bw.write(total +"\n"); for(int i = 0; i < house.size(); i++){ bw.write(house.get(i) + "\n"); } // // 테스트 출력 // for(int i = 1; i <= N; i++){ // for(int j = 1; j<= N; j++){ // System.out.print(graph[i][j]); // } // System.out.println(); // } br.close(); bw.flush(); bw.close(); } // 연결된 상하좌우 경로를 방문 처리 및 개수를 세어줌 static void dfs(int x, int y){ // 종료조건 - 상하좌우 잘 고려해야함 if (x > N || x < 1 || y > N || y < 1){ return; } if (visited[x][y] || !graph[x][y]){ return; } // 재귀 visited[x][y] = true; tempHouse++; for(int i = 0; i < 4; i++){ dfs(x + dx[i], y + dy[i]); } } } <file_sep>-- 코드를 입력하세요 SELECT DISTINCT(Y.CART_ID) FROM ( SELECT CART_ID FROM CART_PRODUCTS WHERE NAME = 'Yogurt' ) Y, ( SELECT CART_ID FROM CART_PRODUCTS WHERE NAME = 'Milk' ) M WHERE Y.CART_ID = M.CART_ID ORDER BY CART_ID; <file_sep>class Solution { public int solution(int n, int[] lost, int[] reserve) { int answer = 0; int[] all = new int[n]; for(int i : reserve) // 여분의 체육복 all[i-1]++; for(int i : lost) // 도난당한 체육복 all[i-1]--; for(int i=0; i < n; i++) { if(all[i] < 0) { // 체육복이 없다면 if(0 <= i - 1 && all[i-1] > 0) { // 인덱스[1 ~ n-1] 범위이면서 이전 학생이 체육복이 있다면, 체육복 빌림 all[i]++; all[i-1]--; } else if(i + 1 < n && all[i+1] > 0) { // 인덱스[0 ~ n-2] 범위이면서 다음 학생이 체육복이 있다면, 체육복 빌림 all[i]++; all[i+1]--; } } } for(int suit : all) { // 0이상이면 체육복 있다. if(suit >= 0) answer++; } return answer; } }<file_sep>select c,l from(select min(city) c, length(city) l from station group by length(city) order by length(city))t where rownum = 1 or l = (select max(length(city)) from station); <file_sep>SELECT ANIMAL_TYPE, NVL(NAME, 'No name'), SEX_UPON_INTAKE FROM ANIMAL_INS ORDER BY ANIMAL_ID <file_sep>SELECT CITY, LENGTH(CITY) FROM ( SELECT CITY, LENGTH(CITY) FROM STATION WHERE LENGTH(CITY) = ( SELECT MIN(LENGTH(CITY)) FROM STATION ) ORDER BY CITY ) WHERE ROWNUM = 1 UNION SELECT CITY, LENGTH(CITY) FROM ( SELECT CITY, LENGTH(CITY) FROM STATION WHERE LENGTH(CITY) = ( SELECT MAX(LENGTH(CITY)) FROM STATION ) ORDER BY CITY ) WHERE ROWNUM = 1; <file_sep>class Solution { public int[] solution(int rows, int columns, int[][] queries) { int[] answer = new int[queries.length]; int[][] map = createMap(rows, columns); for(int i=0; i < queries.length; i++) { int x1 = queries[i][0]; int y1 = queries[i][1]; int x2 = queries[i][2]; int y2 = queries[i][3]; answer[i] = rotate(map, x1, y1, x2, y2); } return answer; } public static int[][] createMap(int rows, int columns) { int[][] map = new int[rows+1][columns+1]; int cnt = 1; for (int i = 1; i <= rows; i++) { for (int j = 1; j <= columns; j++) { map[i][j] = cnt++; } } return map; } public static int rotate(int[][] map, int x1, int y1, int x2, int y2) { int temp = map[x1][y1]; int min = temp; // 왼쪽 for(int i=x1; i < x2; i++) { map[i][y1] = map[i+1][y1]; min = Math.min(min, map[i][y1]); } // 아래 for(int i=y1; i < y2; i++) { map[x2][i] = map[x2][i+1]; min = Math.min(min, map[x2][i]); } // 오른쪽 for(int i=x2; i > x1; i--) { map[i][y2] = map[i-1][y2]; min = Math.min(min, map[i][y2]); } // 위쪽 for(int i=y2; i > y1; i--) { map[x1][i] = map[x1][i-1]; min = Math.min(min, map[x1][i]); } map[x1][y1+1] = temp; return min; } }<file_sep>import java.util.*; class Solution { public int solution(int[] citations) { int answer = 0; Arrays.sort(citations); if(citations[0] > citations.length){ // 제일 적은 인용 수가 citations의 길이보다 길 때 return citations.length; }else{ // h-index의 최대값은 citations의 길이보다 작다. // for(int i = citations.length-1 ; i >= citations[0]+1; i--){ for(int i = citations.length-1 ; i >= 1; i--){ if( citations[citations.length-i] >= i){ return i; } } } return answer; } }<file_sep>SELECT SUM(CITY.POPULATION) FROM CITY JOIN COUNTRY CON ON CITY.COUNTRYCODE = CON.CODE GROUP BY CON.CONTINENT HAVING CON.CONTINENT = 'Asia'; <file_sep>import java.util.*; // 참고 : https://iamheesoo.github.io/blog/algo-prog49191 // 숏코드 : https://in-intuition.tistory.com/25 class Solution { public int solution(int n, int[][] results) { int answer = 0; int INF = 7; int m = results.length; int[][] fw = new int[n+1][n+1]; // 모든 경로 INF로 채우기 for(int[] arr : fw) { Arrays.fill(arr, INF); } // 한방향 그래프의 승리 결과 채우기 for(int[] result:results){ int win = result[0]; int lose = result[1]; fw[win][lose] = 1; } // 최단 경로 저장 // k : 거쳐가는 꼭짓점 // i : 출발하는 꼭짓점 // j : 도착하는 꼭짓점 for(int k=1;k<=n;k++){ for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(fw[i][j]>fw[i][k]+fw[k][j]){ fw[i][j]=fw[i][k]+fw[k][j]; } } } } // 선수 i는 나를 제외한 n-1명과 방문할 수 있어야 승패를 알 수 있다. boolean[] flag = new boolean[n+1]; Arrays.fill(flag, true); for(int i = 1; i <= n; i++){ for(int j = 1; j <= n; j++){ if(i==j) continue; if(fw[i][j] == INF && fw[j][i] == INF){ flag[i] = false; break; } } } for(int i = 1; i < flag.length; i++){ if(flag[i]) answer++; } return answer; } } <file_sep>Select ANIMAL_ID, NAME FROM ANIMAL_OUTS WHERE ANIMAL_ID not in (Select ANIMAL_ID FROM ANIMAL_INS ) ORDER by ANIMAL_ID;<file_sep>SELECT ID, NAME, HOST_ID FROM PLACES WHERE HOST_ID IN ( SELECT HOST_ID FROM PLACES GROUP BY HOST_ID HAVING COUNT(*) > 1 ) ORDER BY ID; <file_sep>select to_char(dateTime,'hh24') as hour, count(*) from ANIMAL_OUTS group by to_char(datetime,'hh24') having to_char(dateTime,'hh24') >'08' and to_char(dateTime,'hh24') <'20' order by hour;<file_sep>import java.io.*; import java.util.*; public class Main { static int[][] h_move = { { 0, 1 }, { 1, 1 } }; static int[][] v_move = { { 1, 0 }, { 1, 1 } }; static int[][] c_move = { { 0, 1 }, { 1, 0 }, { 1, 1 } }; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int N = Integer.parseInt(br.readLine()); int[][] map = new int[N][N]; for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < N; j++) { map[i][j] = Integer.parseInt(st.nextToken()); } } Deque<Integer> q = new ArrayDeque<Integer>(); q.add(0); // i q.add(1); // j q.add(0); // 가로 0 세로 1 대각 2 int answer = 0; if(map[N-1][N-1] == 1) { q.removeAll(q); } while (!q.isEmpty()) { int now_i = q.poll(); int now_j = q.poll(); int before_dir = q.poll(); if (before_dir == 0) { for (int i = 0; i < h_move.length; i++) { int next_i = now_i + h_move[i][0]; int next_j = now_j + h_move[i][1]; if (0 <= next_i && next_i < N && next_j < N && 0 <= next_j && map[next_i][next_j] != 1) { if (i == 1 && (map[next_i - 1][next_j] == 1 || map[next_i][next_j - 1] == 1)) { continue; } if (next_i == N - 1 && next_j == N - 1) { answer++; } else { q.add(next_i); q.add(next_j); q.add(i * 2); } } } } else if (before_dir == 1) { for (int i = 0; i < v_move.length; i++) { int next_i = now_i + v_move[i][0]; int next_j = now_j + v_move[i][1]; if (0 <= next_i && next_i < N && next_j < N && 0 <= next_j && map[next_i][next_j] != 1) { if (i == 1 && (map[next_i - 1][next_j] == 1 || map[next_i][next_j - 1] == 1)) { continue; } if (next_i == N - 1 && next_j == N - 1) { answer++; } else { q.add(next_i); q.add(next_j); q.add(i + 1); } } } } else { for (int i = 0; i < c_move.length; i++) { int next_i = now_i + c_move[i][0]; int next_j = now_j + c_move[i][1]; if (0 <= next_i && next_i < N && next_j < N && 0 <= next_j && map[next_i][next_j] != 1) { if (i == 2 && (map[next_i - 1][next_j] == 1 || map[next_i][next_j - 1] == 1)) { continue; } if (next_i == N - 1 && next_j == N - 1) { answer++; } else { q.add(next_i); q.add(next_j); q.add(i); } } } } } System.out.println(answer); } } <file_sep>SELECT NAME, DATETIME FROM ANIMAL_INS ORDER BY ANIMAL_ID DESC; <file_sep>SELECT COUNT(NAME) FROM (SELECT NAME FROM ANIMAL_INS GROUP BY NAME) <file_sep>SELECT DATETIME FROM (SELECT DATETIME FROM ANIMAL_INS ORDER BY DATETIME DESC) WHERE ROWNUM = 1; <file_sep>import java.util.*; class Solution { public int[] solution(int[] array, int[][] commands) { ArrayList<Integer> list = new ArrayList<>(); for(int i = 0; i < commands.length; i++){ int start = commands[i][0]-1; int end = commands[i][1]; int index = commands[i][2]-1; int[] temp = Arrays.copyOfRange(array, start, end); Arrays.sort(temp); list.add(temp[index]); } int[] answer = list.stream().mapToInt(i -> i).toArray(); return answer; } }
9a25f2cbc153b9d47bbcfd8734f1ee0a4104bab0
[ "Java", "SQL" ]
94
SQL
Hyundai-TEAM01/CodingTest
25c9130843ed009afaae5dfd1f6badc311ede5c8
ccff3889416466a13de3fb4286fc0ea72498fbcf
refs/heads/master
<repo_name>andytow/surtidores<file_sep>/surtidores.php <html> <head> <meta http-equiv="Content-Language" content="es-ar"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <link rel="shortcut icon" href="favicon.ico"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="<KEY>" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700,800" rel="stylesheet"> <style> body { font-family: Montserrat; font-size: 14px; background-color:#FFF; } </style> <body> <br> <div class="container" style="width: 480px;"> <?php //create array of data to be posted require('qs_functions.php'); $c = qsrequest("c"); //combustible $post_data['optionsRadios'] = $c; $post_data['idproducto'] = $c; $post_data['bandera'] = ''; //traverse array and prepare data for posting (key1=value1) foreach ( $post_data as $key => $value) { $post_items[] = $key . '=' . $value; } //create the final string to be posted using implode() $post_string = implode ('&', $post_items); //echo $post_string; //create cURL connection $curl_connection = curl_init('https://preciosensurtidor.minem.gob.ar/estacionesdeservicio/mapa-busqueda'); //set options curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); //curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1); //set data to be posted curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string); //perform our request $result = curl_exec($curl_connection); //show information regarding the request //print_r(curl_getinfo($curl_connection)); //echo curl_errno($curl_connection) . '-' . //curl_error($curl_connection); //echo $result; function findVar($var, $url){ $data = $url; if(strpos($data, $var) == false) return false; $len = strlen($var) + 2; $start = strpos($data, $var." = [") + $len; $stop = strpos($data, ";", $start); $val = substr($data, $start, ($stop-$start)); return $val; } $variable = "var aEmpresas"; $url = $result; $value = findVar($variable, $url); $healthy = array("\"precios\":{\"" . $c ."\":{", "}}"); $yummy = array("", ""); $newphrase = str_replace($healthy, $yummy, $value); //echo $newphrase; $ip = getenv("REMOTE_ADDR"); $ipreplace = array("."); $ipreplaced = array(""); $newip = str_replace($ipreplace, $ipreplaced, $ip); $rand = rand (); $datajson = $newip . '-' . $rand . '.json'; $datacsv = $newip . '-' . $rand . '.csv'; $fp = fopen('output/' . $datajson,"wb"); fwrite($fp,$newphrase); fclose($fp); //close the connection curl_close($curl_connection); function jsonToCSV($jfilename, $cfilename) { if (($json = file_get_contents($jfilename)) == false) die('Error reading json file...'); $data = json_decode($json, true); $fp = fopen($cfilename, 'w'); $header = false; foreach ($data as $row) { if (empty($header)) { $header = array_keys($row); fputcsv($fp, $header); $header = array_flip($header); } fputcsv($fp, array_merge($header, $row)); } fclose($fp); return; } $json_filename = 'output/' . $datajson; $csv_filename = 'output/' . $datacsv; jsonToCSV($json_filename, $csv_filename); echo '<h4>Conversi&oacute;n de precios de surtidores exitosa. <a href="' . $csv_filename . '" target="_blank">Descargar csv</a>.</h4><br><p>Su archivo estar&aacute; disponible por 24 horas.</p>.'; echo '<h5><a href="javascript:history.back()" target="_top">Volver</a></h5>'; ?> </div> </body> </html><file_sep>/output/readme.md Esta carpeta guardará los archivos json y csv para descarga <file_sep>/README.md # surtidores Scraper de precios de surtidores del Ministerio de Energía y Minería de la República Argentina (https://preciosensurtidor.minem.gob.ar/estacionesdeservicio/mapa-busqueda). Convierte json de la web de MinEM en archivos csv
47feb2ce7c99068e3138202ba71b971e63425aef
[ "Markdown", "PHP" ]
3
PHP
andytow/surtidores
00d9775515d6f7834be640b259f063f036ffabf6
7669864263e5f246f42233d25bceb78b633ea02f
refs/heads/master
<repo_name>giserh/AlteryxTools<file_sep>/RecordCountReporter/RecordCountReporter/RecordCountReporter.py import AlteryxPythonSDK as Sdk import xml.etree.ElementTree as Et class AyxPlugin: def __init__(self, n_tool_id: int, alteryx_engine: object, output_anchor_mgr: object): # Default properties self.n_tool_id: int = n_tool_id self.alteryx_engine: Sdk.AlteryxEngine = alteryx_engine self.output_anchor_mgr: Sdk.OutputAnchorManager = output_anchor_mgr # Custom properties self.TextLabel: str = None self.TextValue: str = None self.input: IncomingInterface = None self.Details: Sdk.OutputAnchor = None self.Count: Sdk.OutputAnchor = None def pi_init(self, str_xml: str): # Getting the dataName data property from the Gui.html self.TextLabel = Et.fromstring(str_xml).find('TextLabel').text if 'TextLabel' in str_xml else None self.TextValue = Et.fromstring(str_xml).find('TextValue').text if 'TextValue' in str_xml else None if self.TextLabel is None: self.display_error_msg("Enter a name for the output fields") if self.TextValue is None: self.display_error_msg("Enter a label describing the output") # Getting the output anchor from Config.xml by the output connection name self.Details = self.output_anchor_mgr.get_output_anchor('Details') self.Count = self.output_anchor_mgr.get_output_anchor('Count') def pi_add_incoming_connection(self, str_type: str, str_name: str) -> object: self.input = IncomingInterface(self) return self.input def pi_add_outgoing_connection(self, str_name: str) -> bool: return True def pi_push_all_records(self, n_record_limit: int) -> bool: self.alteryx_engine.output_message(self.n_tool_id, Sdk.EngineMessageType.error, 'Missing Incoming Connection.') return False def pi_close(self, b_has_errors: bool): self.Count.assert_close() self.Details.assert_close() def display_error_msg(self, msg_string: str): self.alteryx_engine.output_message(self.n_tool_id, Sdk.EngineMessageType.error, msg_string) class IncomingInterface: def __init__(self, parent: AyxPlugin): # Default properties self.parent: AyxPlugin = parent self.records: int = 0 # Custom properties source = "Record Count Reporter (" + str(self.parent.n_tool_id) + ")" self.CountRecord = Sdk.RecordInfo(self.parent.alteryx_engine) self.IdField: Sdk.Field = self.CountRecord.add_field("Id", Sdk.FieldType.int16, 0, 0, source, '') self.LabelField: Sdk.Field = self.CountRecord.add_field(self.parent.TextLabel, Sdk.FieldType.v_wstring, 256, 0, source, '') self.CountField: Sdk.Field = self.CountRecord.add_field(self.parent.TextLabel + "_Count", Sdk.FieldType.int64, 0, 0, source, '') self.CountCreator: Sdk.RecordCreator = self.CountRecord.construct_record_creator() def ii_init(self, record_info_in: Sdk.RecordInfo) -> bool: # Make sure the user provided a field to parse if self.parent.TextLabel is None: self.parent.display_error_msg('Enter a name for the output fields') return False if self.parent.TextValue is None: self.parent.display_error_msg("Enter a label describing the output") return False self.parent.Details.init(record_info_in) return True def ii_push_record(self, in_record: Sdk.RecordRef) -> bool: self.records = self.records + 1 self.parent.Details.push_record(in_record) return True def ii_update_progress(self, d_percent: float): # Inform the Alteryx engine of the tool's progress. self.parent.alteryx_engine.output_tool_progress(self.parent.n_tool_id, d_percent) # Inform the outgoing connections of the tool's progress. self.parent.Count.update_progress(0) self.parent.Details.update_progress(d_percent) def ii_close(self): self.parent.Details.close() self.parent.Count.init(self.CountRecord) self.CountCreator.reset() self.IdField.set_from_int32(self.CountCreator, 1) self.LabelField.set_from_string(self.CountCreator, self.parent.TextValue) self.CountField.set_from_int64(self.CountCreator, self.records) output = self.CountCreator.finalize_record() self.parent.Count.push_record(output) self.parent.Count.update_progress(1.0) self.parent.Count.close()
e013a3f07b2add9b9187603c1d96fd5f91278617
[ "Python" ]
1
Python
giserh/AlteryxTools
dc36f42968f18c33cf09a6be596a8df5188484e8
00612a2aa41ab0d606b224453bf1bd64ee03d19d
refs/heads/master
<file_sep>import numpy as np np.set_printoptions(threshold=np.nan) import matplotlib.pyplot as plt """ The activation/transfer function """ def activation_function(a): return a / float(1 + abs(a)) """ The derivative of the activation/transfer function """ def act_function_deriv(a): return 1 / float((1 + abs(a))) ** 2 """ Compute the mean squared error on the predicted values and the targetvalues """ def MSE(data, t): return 1 / float(2 * len(data)) * sum((t[i] - data[i]) ** 2\ for i, d in enumerate(data)) #TODO add bias class NeuralNetwork(object): def __init__(self, numInput,numOutput,steps): self.numInput = numInput self.numHidden = None self.numOutput = numOutput self.training_X = None self.training_Y = None self.validation_X = None self.validation_Y = None self.weights_1 = None self.weights_2 = None self.steps = steps self.eps = None self.act = np.vectorize(activation_function) self.actprime = np.vectorize(act_function_deriv) self.startingWeights_1 = None self.startingWeights_2 = None self.InitializeData("sincTrain25.dt","sincValidate10.dt") def InitializeData(self,trainfile, validatefile): training_set = np.loadtxt(trainfile) validation_set = np.loadtxt(validatefile) num_features = len(training_set[0])-1 self.training_X = np.delete(training_set, num_features, axis=1) training_Y = training_set[:,num_features] validation_Y = validation_set[:,num_features] self.validation_X = np.delete(validation_set, num_features, axis=1) self.validation_Y = validation_Y.reshape(len(validation_set),1) self.training_Y = training_Y.reshape(len(training_set),1) def initializeWeights(self): print "initializing weights" self.weights_1 = np.random.randn(self.numInput+1,self.numHidden) #self.weights_2 = np.random.randn(self.numHidden,self.numOutput+1) self.weights_2 = np.random.randn(self.numHidden+2,self.numOutput) self.startingWeights_1 = self.weights_1 self.startingWeights_2 = self.weights_2 def forwardPropagation(self,train): if (train): X = self.training_X else: X = self.validation_X X = np.hstack((X, np.ones((X.shape[0], 1), dtype=X.dtype))) Z_2 = np.dot(X,self.weights_1) a_2 = self.act(Z_2) a_2_1 = np.hstack((a_2, np.ones((a_2.shape[0], 2), dtype=a_2.dtype))) #print a_2 #print a_2.shape #print self.weights_2.shape Z_3 = np.dot(a_2_1,self.weights_2) yhat = self.act(Z_3) return yhat, Z_2, a_2_1, Z_3 def backwardPropagation(self): y_hat, Z_2, a_2, Z_3 = self.forwardPropagation(True) y_hat_val, _, _, _ = self.forwardPropagation(False) delta_3 = np.multiply(-(self.training_Y-y_hat), self.actprime(Z_3)) weights_2 = self.weights_2[:2] dj_dw_2 = np.dot(a_2.T, delta_3) delta_2 = np.dot(delta_3,weights_2.T) * self.actprime(Z_2) dj_dw_1 = np.dot(self.training_X.T,delta_2) self.weights_1 = self.weights_1 - (np.dot(self.eps,dj_dw_1)) self.weights_2 = self.weights_2 - (np.dot(self.eps,dj_dw_2)) return MSE(y_hat,self.training_Y),MSE(y_hat_val,self.validation_Y) def train(self): errorList = [] valList = [] for _ in range(self.steps): train_error, val_error = self.backwardPropagation() errorList.append(train_error) valList.append(val_error) return errorList,valList def main(self): test = [(2, [0.01])] for numHidden, eps_ in test: self.numHidden = numHidden self.initializeWeights() errorList = [] valList_ = [] for eps in eps_: self.eps = eps errors_list, valList = self.train() errorList.append(errors_list) valList_.append(valList) e = np.array(errorList).reshape(1,self.steps,1) v = np.array(valList_).reshape(1,self.steps,1) print "End train error: " + str(e[0][-1]) print "End valid error: " + str(v[0][-1]) #if (v[0][-1]) < 0.020: #print e.shape #print len(errorList) #print v.shape self.plot(e,v,eps_) def plot(self,errors_list,valList,eps_): for index, err in enumerate(errors_list): plt.plot(range(len(err)), err, label="Train: " + str(eps_[index])) plt.plot(range(len(err)), valList[index] , label="Val: " +\ str(eps_[index])) plt.gca().set_yscale('log') plt.rc('text', usetex=True) plt.rc('font', family='Computer Modern',size=12) plt.xlabel(r'\textit{Iterations} ($\epsilon$)') plt.ylabel(r'\textit{MSE') header = "Hidden units: " + str(self.numHidden) plt.title(header) plt.legend(loc=1,prop={'size':10}) title = "img/rates-"+str(self.numHidden)+str("-")+str(self.eps)+str("-")+str(self.steps)+str(".png") plt.plot() plt.show() for i in range(0,10): NN = NeuralNetwork(1,1,3200) NN.main()<file_sep>from __future__ import division import numpy as np import math import matplotlib import matplotlib.pyplot as plt filename = "IrisTrainML.dt" def prepareData(filename): data = np.loadtxt(open(filename,"rb"),delimiter=" ") numberOfPixels = len(data[0])-1 removedData = [] for i in range(len(data)): if data[i][2] != 2: removedData.append(data[i]) data = np.array(removedData) features = np.delete(data, numberOfPixels, axis=1) newData = np.ones([len(features),1]) features = np.concatenate((newData,features),axis=1) targetvalues = data[:,2] for i in range(len(targetvalues)): if targetvalues[i] == 0: targetvalues[i] = -1 return features,targetvalues def sigmoid(inX): return 1.0/(1+np.exp(-inX)) def gradDesc(dataMatIn,classLabels): dataMatrix = np.mat(dataMatIn) alpha = 0.1 maxCycles = 10000 labelMat = np.mat(classLabels).transpose() m,n = np.shape(dataMatrix) weights = np.zeros((n,1)) for k in range(maxCycles): grad = 0 for n in range(len(dataMatrix)): grad += (classLabels[n] * dataMatrix[n])/ \ (1 + math.exp(classLabels[n].transpose() * weights.transpose() * dataMatrix[n].transpose())) gradient = ((-1/len(dataMatrix))*grad).transpose() weights = weights + alpha * -gradient return weights def plot(features,label): fig = plt.figure() ax = fig.add_subplot(111) colors = ['red','green'] ax.scatter(features[:,0],features[:,1],c=label, cmap=matplotlib.colors.ListedColormap(colors)) plt.show() def main(): features, targetvalues = prepareData(filename) weights = gradDesc(features,targetvalues) print "Weights are: " + str(weights) regressed = (weights.transpose() * features.transpose()) regressed = np.array(regressed) error = 0 for i in range(len(features)): if sigmoid(regressed[0][i]) > 0.5: predicted = 1 else: predicted = -1 if predicted != targetvalues[i]: error += 1 errorTrain = error/len(features) print "iterations: 10000" print "step size : 0.01" print "Emperical training error: " + str(errorTrain) featuresTest, targetvaluesTest = prepareData("IrisTestML.dt") regressedTest = (weights.transpose() * featuresTest.transpose()) regressedTest = np.array(regressedTest) errorTest = 0 for i in range(len(featuresTest)): if sigmoid(regressedTest[0][i]) > 0.5: predictedTest = 1 else: predictedTest = -1 if predictedTest != targetvaluesTest[i]: errorTest += 1 errorTest = errorTest/len(featuresTest) print "iterations: 10000" print "step size : 0.01" print "Emperical training error: " + str(errorTest) main()<file_sep>import matplotlib.pyplot as plt import sys from numpy import loadtxt, array, sqrt, sin, average, zeros from numpy import subtract, dot, add, mean, var, arange, delete from numpy.random import rand, seed, sample from copy import copy """ Retrieve data and target values for the training and validation set """ def prepareData(trainfile, validatefile): training_set = loadtxt(trainfile) validation_set = loadtxt(validatefile) num_features = len(training_set[0])-1 TrainData = delete(training_set, num_features, axis=1) TrainTarget = training_set[:,num_features] ValidateData = delete(validation_set, num_features, axis=1) ValidateTarget = validation_set[:,num_features] return TrainData,TrainTarget,ValidateData,ValidateTarget TrainData,TrainTarget,ValidateData,ValidateTarget = \ prepareData("sincTrain25.dt","sincValidate10.dt") seed(10) trainInterval = arange(-10, 10, 0.05, dtype='float64') """ Calculates the linear model target value based on the given weights and bias. Used for hidden units, when firing towards the output unit """ def calc_output(hidden_data, weight, bias): #print hidden_data + [bias] return dot(weight, hidden_data + [bias]) """ Caluclates the linear model of the data, and applies the activation function /transfer function """ def calc_hidden(data, weight, bias): return activation_function(weight[0] * data + weight[1] * bias) """ The activation/transfer function """ def activation_function(a): return a / float(1 + abs(a)) """ The derivative of the activation/transfer function """ def act_function_deriv(a): return 1 / float((1 + abs(a))) ** 2 """ Compute feed-forward network. For each entry point in the data, the hidden values of a is calculated based on the each input, the output for each entry is then calculated using the activation function """ def feedForward(data, weights_m, weights_k, num_input=1,\ num_output=1): prediction = [] for x in data: # for each data entry hidden_data = [] for h_unit in xrange(num_hidden): # call activation function, with weights for hidden neurons hidden_data.append(calc_hidden(x, weights_m[h_unit],1)) #print weights_m print weights_k # get output using the weights from the output neurons prediction.append(calc_output(hidden_data, weights_k, 1)) return prediction """ Compute the mean squared error on the predicted values and the targetvalues """ def MSE(data, t): return 1 / float(2 * len(data)) * sum((t[i] - data[i]) ** 2\ for i, d in enumerate(data)) """ Inner derivative using sum rule """ def delta_k(predicted, target): return predicted - target """ Outer derivative using chain rule """ def delta_j(a, weight, delta_k): return act_function_deriv(a) * sum([weight * data_k for k, data_k\ in enumerate(delta_k)]) def backPropagation(learning_rate,weights_m,weights_k,verify=False,steps=4000): valData = ValidateData valTarget = ValidateTarget train = TrainData target = TrainTarget if verify: train = train[:10] target = target[:10] errors = []; val_errors = [] p = 1 steps = 1 for _ in xrange(steps): if p % steps == 0: sys.stdout.write('\r'+"") sys.stdout.flush() else: if p % (steps/100.0) == 0: b = (str(int(float(p) / steps * 100)) + " %") sys.stdout.write('\r'+str(b)) sys.stdout.flush() predicted = feedForward(train, weights_m, weights_k) predicted_interval = feedForward(trainInterval, weights_m,\ weights_k) predicted_validation = feedForward(valData, weights_m, weights_k) d_hidden = [] d_out = [] for i, data in enumerate(train): dK = delta_k(predicted[i], target[i]) dJs = [] list_zj = [] for j in xrange(num_hidden): aj = weights_m[j][0] * data + weights_m[j][1] * 1 list_zj.append(activation_function(aj)) dJs.append(delta_j(aj, weights_k[0][j], [dK])) d_hidden.append(dot(array(dJs), array([[data, 1]]))) list_zj.append(array([activation_function(1)])) d_out.append(dK * array(list_zj)) avg_dhidden = average(d_hidden, axis=0) avg_dout = average(d_out, axis=0).flatten() weights_m = subtract(weights_m, (learning_rate * avg_dhidden)) weights_k = subtract(weights_k, (learning_rate * avg_dout)) errors.append(MSE(predicted, target)) val_errors.append(MSE(predicted_validation,valTarget)) p += 1 return errors,val_errors, predicted_interval, avg_dhidden, avg_dout def gradient_verify(weights_k, weights_m, e=0.00000001): data = TrainData[:10] data_target = TrainTarget[:10] error_matrix_md = zeros(weights_m.shape) error_matrix_km = zeros(weights_k.shape) errors, _, _, _, _ = backPropagation(-1,\ weights_m, weights_k,True,1) for i in xrange(weights_m.shape[1]): for j in xrange(len(weights_m)): cpy_weight_md = copy(weights_m) cpy_weight_md[j][i] += e e_errors, _, _, _, _ = backPropagation(-1,\ cpy_weight_md, weights_k,True,1) error_matrix_md[j][i] = (e_errors[0][0] - errors[0][0]) / e for i in xrange(weights_k.shape[1]): cpy_weight_km = copy(weights_k) cpy_weight_km[0][i] += e e_errors, _, _, _, _ = backPropagation(-1,\ weights_m, cpy_weight_km,True,1) error_matrix_km[0][i] = (e_errors[0][0] - errors[0][0]) / e return error_matrix_md, error_matrix_km def main(iterations): test = [(2, [0.1])] twoPlot = [] global num_hidden for num_hidden, learning_rates in test: print "Number of hidden: " + str(num_hidden) # weights to hidden layers weights_m = sample([num_hidden, 2]) # weights from hidden to output weights_k = sample([1, num_hidden + 1]) #error_matrix_md, error_matrix_km = gradient_verify(weights_k, weights_m) #_, _, _, avg_dhidden, avg_dout = backPropagation(-1, weights_m,\ # weights_k,True,1) # gradient verification, values should be within 10^-8 #print subtract(error_matrix_md, avg_dhidden) #print subtract(error_matrix_km, avg_dout) errors_list = [];errors_list_validate = []; data_list = [] for learning_rate in learning_rates: print "Learning Rate: " +str(learning_rate) errors, val_errors, data, _, _ = \ backPropagation(learning_rate, weights_m, weights_k,False,iterations) errors_list.append(errors) errors_list_validate.append(val_errors) data_list.append(data) if learning_rate == 0.1: twoPlot.append(errors) """ plt.gca().set_yscale('log') # Plot of all learning rates and validation errors for index, err in enumerate(errors_list): plt.plot(range(len(err)), err, label="Train: " +\ str(learning_rates[index])) plt.plot(range(len(err)), errors_list_validate[index] , label="Val: " +\ str(learning_rates[index])) plt.rc('text', usetex=True) plt.rc('font', family='Computer Modern',size=12) plt.xlabel(r'\textit{Iterations} ($\epsilon$)') plt.ylabel(r'\textit{MSE') header = "Hidden units: " + str(num_hidden) plt.title(header) plt.legend(loc=1,prop={'size':10}) title = "img/rates-"+str(num_hidden)+str("-")+str(learning_rates)+str("-")+str(iterations)+str(".png") plt.savefig(title) plt.close() # Plot of interval for index, da in enumerate(data_list): plt.plot(trainInterval, da, label="Learning rate: " +\ str(learning_rates[index])) plt.plot(trainInterval, eval('sin(trainInterval)/trainInterval'\ .format(trainInterval)), label="sin(x)/x") plt.rc('text', usetex=True) plt.rc('font', family='Computer Modern',size=12) #plt.xlabel(r'\textit{Iterations} ($\epsilon$)') #plt.ylabel(r'\textit{MSE') plt.scatter(TrainData, TrainTarget, label="Training Data") plt.scatter(ValidateData,ValidateTarget, label="Validation Data",color='red') plt.legend(loc=1,prop={'size':10}) header = "Hidden units: " + str(num_hidden) plt.title(header) title = "img/interval"+str(num_hidden)+str("-")+str(learning_rates)+str(".png") plt.savefig(title) plt.close() # Plot of 2 and 20 plt.gca().set_yscale('log') for index, err in enumerate(twoPlot): if index == 0: labelhere = "2 hidden: " else: labelhere = "20 hidden: " plt.plot(range(len(err)), err, label=labelhere + str(0.1)) plt.xlabel(r'\textit{Iterations} ($\epsilon$)') plt.ylabel(r'\textit{MSE') plt.legend(loc=1) title = "img/twoplots"+str(num_hidden)+str("-")+str(learning_rates)+str(".png") plt.savefig(title) plt.close() """ main(1)<file_sep>from svmutil import * import numpy as np def prepareData_(Data): numFeatures = Data.shape[1]-1 targetvalues = Data[:,numFeatures] features = np.delete(Data, numFeatures, axis=1) return(targetvalues,features) def Norm(train,test): Data = np.loadtxt(train) test = np.loadtxt(test) (testval,testdata) = prepareData_(test) (val,dataSet) = prepareData_(Data) mean = np.sum(dataSet,axis=0)/len(Data) variance = (np.sum((dataSet - mean)**2,axis=0)/len(Data)) meanTrain = mean; varTrain = variance std = np.sqrt(variance) normalizedTest = (testdata - mean) / np.sqrt(variance) normalizedData = (dataSet - mean) / np.sqrt(variance) meanTest = np.mean(normalizedTest,axis=0) varTest = np.var(normalizedTest,axis=0) return normalizedTest,testval,normalizedData,val # for each pair gamma, c, perform 5 cross valdation def svm(dat_x,dat_y,val_x,val_y,norm,c,g): prob = svm_problem(dat_y,dat_x) param = svm_parameter('-s 0 -t 2 -c %f -g %f -q' % (c,g)) m = svm_train(prob, param) p_labels, p_acc, p_vals = svm_predict(val_y, val_x, m) return p_acc[0] def removeRest(i,listofarrays): trainingset = [] validation = listofarrays[i] for j in range(len(listofarrays)): if i != j: trainingset.append(listofarrays[j]) assert len(listofarrays) == 5, "Not implemented for sizes != 5" comb= np.vstack([trainingset[0],trainingset[1],trainingset[2],\ trainingset[3]]) return (validation,comb) def generaretSplits(Data,splits): folds = np.array_split(Data,splits) combList = [] for i in range(len(folds)): combList.append(removeRest(i,folds)) return combList def single_pass(x,y,x_val,y_val): C_min, C_max = -2,8 gamma_min, gamma_max = -6,4 C = [10**n for n in range(C_min,C_max)] gamma = [10**n for n in range(gamma_min,gamma_max)] # keep track of best result to determine the best zeroList = [] best_res = 0 best_c = 0 best_g = 0 mat = np.zeros([len(C),len(gamma)]) for n, c in enumerate(C): for m,g in enumerate(gamma): result = svm(x,y,x_val,y_val,False,c,g) mat[n,m] = result if result > best_res: best_res = result best_g = g best_c = c return mat,best_res,(best_c,best_g) def crossValidate(splits,norm): matlist = [] Train = np.loadtxt("parkinsonsTrainStatML.dt") (y,x) = prepareData_(Train) if norm: (_,_,x,y) = Norm("parkinsonsTrainStatML.dt","parkinsonsTestStatML.dt") folds = generaretSplits(x,splits) y = y.reshape(len(y),1) yfolds = generaretSplits(y,splits) bestRes = 0 bestCg = 0 for i in range(len(folds)): val = folds[i][0] train = folds[i][1] target_val = yfolds[i][0] target_train = yfolds[i][1] x_val = val.tolist() x_train = train.tolist() y_val = target_val.tolist() y_val = list_(y_val) y_train = target_train.tolist() y_train = list_(y_train) mat,result, cg = single_pass(x_train,y_train,x_val,y_val) matlist.append(np.array(mat)) if result > bestRes: bestRes = result bestCg = cg return matlist,bestRes,bestCg def getAvg(listr): C_min, C_max = -2,8 gamma_min, gamma_max = -6,4 C = [10**n for n in range(C_min,C_max)] gamma = [10**n for n in range(gamma_min,gamma_max)] n,m = listr[0].shape summed_arr = np.zeros([n,m]) for arr in listr: summed_arr = np.add(summed_arr,arr) summed_arr = summed_arr / 5.0 biggest = 0 index = 0 for i in range(n): for j in range(m): if summed_arr[i][j] > biggest: biggest = summed_arr[i][j] index = (i,j) q,w = index return index,biggest def list_(inp): retList = [] for i in range(len(inp)): retList.append(inp[i][0]) return retList def test(norm): mat,b, _ = crossValidate(5,norm) (c,g), error = getAvg(mat) c = 1 g = 0.1 Data = np.loadtxt("parkinsonsTrainStatML.dt") DataVal = np.loadtxt("parkinsonsTestStatML.dt") (y,x) = prepareData_(Data) (y_val,x_val) = prepareData_(DataVal) if norm: (x_val,y_val,x,y) = Norm("parkinsonsTrainStatML.dt",\ "parkinsonsTestStatML.dt") (y_,x_) = (y,x) x = x.tolist() y = y.tolist() y_val = y_val.tolist() x_val = x_val.tolist() result = (svm(x,y,x_val,y_val,False,c,g)) return 1- (float(result)/100),(c,g) def main(): a,(c,g) = test(False) b, (c1,g1) = test(True) print "hyperparameter c: " + str(c) print "hyperparameter g: " + str(g) print "Generalization error, raw data: " + str(a) print "Generalization error, norm data: " + str(b)<file_sep>import numpy as np from numpy import linalg as LA import matplotlib import matplotlib.pyplot as plt import plotly.plotly as py import plotly.graph_objs as go import kmeans as km """ Load the data and remove targetValues """ def prepareData(filename): data = np.loadtxt(open(filename,"rb"),delimiter=",") numberOfPixels = len(data[0])-1 features = np.delete(data, numberOfPixels, axis=1) targetValues = data[:,numberOfPixels] return (features,targetValues) """ Transform datalabels into shapes of trafficsigns """ def assignLabels(target): shapevalues = [] for i in range(len(target)): if (target[i] < 11) or (target[i] > 31)\ or (target[i] == 15) or (target[i] == 16) or (target[i] ==17): shapevalues.append(0) elif target[i] == 12: shapevalues.append(2) elif target[i] == 13: shapevalues.append(3) elif target[i] == 14: shapevalues.append(4) elif target[i] == 11 or (target[i] > 18 or target[i] < 32): shapevalues.append(1) return shapevalues """ Compute the k principle components """ def getPCA(filename,k): # seperate features and targetvalues features,targetValues = prepareData(filename) # determine the shapes of each signs shapes_signs = assignLabels(targetValues) # calculate the mean of the input data meanVals = np.mean(features, axis=0) meanRemoved = features - meanVals # compute the covarinace matrix of the meanless data covMat = np.cov(meanRemoved,rowvar=0) # get teh eigenvalues and eigenvectors eigVals,eigVects = np.linalg.eig(np.mat(covMat)) eigVals = np.real(eigVals); eigVects = np.real(eigVects) # sort the eigenvalues eigValInd = np.argsort(eigVals) topvalList = eigVals[eigValInd][::-1] # plot eigenspectrum plotSpectrum(topvalList) eigValInd = eigValInd[:-(k+1):-1] sortFeat = targetValues[eigValInd] # get principle components by retreiving the top k eigenvectors principleComponents = eigVects[:,eigValInd] percentile = 0 eigenSum = np.sum(eigVals) for i in range(len(topvalList)): percentile += np.real(topvalList[i]) percent = percentile / eigenSum if percentile/eigenSum > 0.90: component = i print "90 percent of the variance explained at component: " + str(i+1) break z = np.dot(meanRemoved,principleComponents) x = z[:,0] y = z[:,1] plot(x,y,shapes_signs,meanRemoved,principleComponents) """ Function for plotting the projected data and the 4 clusters """ def plot(x,y,label,meanRemoved,principleComponents): for i in range(1): fig = plt.figure() ax = fig.add_subplot(111) c = ['red','green','blue','orange','black','yellow'] m = ['o','^','D','v','8'] al = [0.45,1,1,1,1,1] for j in range(len(x)): ax.scatter(x[j],y[j],c=c[label[j]],marker=m[label[j]],alpha=al[label[j]]) #clusters = km.kMeans(meanRemoved,4) #reducedClusters = np.dot(clusters,principleComponents) #x1 = reducedClusters[:,0] #y1 = reducedClusters[:,1] #cluster = ax.scatter(x1,y1,label='Clusters',c='green',s=700,marker='.') #plt.legend(handles=[cluster],loc=3) #plt.savefig('kmeansAndTwpPCA') plt.show() """ Function for plotting the eigenspectrum """ def plotSpectrum(yvals): xvals = [x for x in range(len(yvals))] p1, = plt.plot(xvals,yvals,label='Average loss') plt.title("Eigenspectrum") plt.yscale('log') plt.xlabel('Principle Components') plt.ylabel('Eigenvalues') plt.savefig('eigenSpectrum') #plt.show()<file_sep>import numpy as np import math filename = "ML2016TrafficSignsTrain.csv" """ Get Euclidean distance """ def dist_euclid(vec1, vec2): return np.sqrt(np.sum(np.power(vec1-vec2,2))) """ Initialize the k clusters to have the first k datapoints """ def initialize_centroids(features,k): centroidList = [] for i in range(k): centroidList.append(features[i]) return centroidList """ Assign the clusters random starting points of the datapoints """ def initialize_centroids_random(features,k): centroidList = [] indexlist= [] for i in range(k): index = np.random.randint(0, len(features)) centroidList.append(features[index]) indexlist.append(index) return centroidList """ Perform k-means clustering for the input data and k clusters, returns the position of these clusters """ def kMeans(data,k): features = data centroidList = np.array(initialize_centroids(features,k)) moving = True j = 1 while moving: belongsToCentroid = [] # create a list for each centroid, containing points closest to for i in range(len(centroidList)): belongsToCentroid.append([]) # use dictionary instead for p in range(len(features)): lowestDist = float("inf") picked_centroid = -1 # for each point in the dataset, calculate distance to each centroid # add to centroid list with lowest distance for c in range(len(centroidList)): distance_to_centroid = dist_euclid(features[p],centroidList[c]) if distance_to_centroid < lowestDist: # update lowest distance lowestDist = distance_to_centroid picked_centroid = c # add point to centroid list belongsToCentroid[picked_centroid].append(features[p]) # array holds for each centroid the points closest to it newarray = np.array(belongsToCentroid) meandif = [] for centr in range(len(newarray)): centrmean = np.mean(newarray[centr],axis=0) prevMean = np.sum(centroidList[centr]) centroidList[centr] = centrmean meandif.append(abs(prevMean - np.sum(centroidList[centr]))) if (all(x == 0.0 for x in meandif)): moving = False j += 1 return centroidList<file_sep>import matplotlib import matplotlib.pyplot as plt import numpy as np import operator import math from array import array def prepareData_(Data): numFeatures = Data.shape[1]-1 targetvalues = Data[:,numFeatures] features = np.delete(Data, numFeatures, axis=1) return(targetvalues,features) # calculates the weights of the linear regression def standRegres(xArr,yArr): xMat = np.mat(xArr); yMat = np.mat(yArr).T xTx = xMat.T*xMat if np.linalg.det(xTx) == 0.0: print "This matrix is singular, cannot do inverse" return ws = xTx.I * (xMat.T*yMat) return ws # takes a filename and returns the weights and the RMSE of the dataset def linRegs(filename): Data = np.loadtxt(filename) print Data (Y,X) = prepareData_(Data) newData = np.ones([len(X),1]) X = X.reshape((len(X), 1)) X = np.concatenate((newData,X),axis=1) Y = Y.reshape(1,len(Y)) weights = standRegres(X,Y) #1 bias (aka offset or intercept) parameter: error = MSE(X,Y,weights) print error return (weights,error) # calculates the root mean squared error of a dataset and a linear model def MSE(X,Y,weights): error = 0 numdata = len(X) yHat = X*weights for i in range(numdata): error += (yHat[i]-Y[0][i])**2 return error / numdata # plots the linear regression of a dataset def plot(filename): Data = np.loadtxt(filename) fig = plt.figure() ax = fig.add_subplot(111) (weights,error) = linRegs(filename) x = Data[:,0] y = Data[:,1] x = x.reshape((6, 1)) y = y.reshape((6,1)) p1, = plt.plot(x, y, '.',label='Data') p2, = plt.plot(x, (1*weights[0] + x* weights[1]),\ '-',label='Linear Regression') plt.ylabel('y') plt.xlabel('x') plt.legend(handles=[p1, p2],loc=2) plt.show() def main(): weights,error = linRegs("DanWood.dt") print "Assignment 5: \n" print "Weights = " + str(weights[0]) + " " + str(weights[1]) print "RMSE error on whole dataset = " + str(error) main()<file_sep>import matplotlib import matplotlib.pyplot as plt import numpy as np import operator import math from array import array # Calculates the distance vector from a point to the rest of the points # in the data. Sorts this list and gets the closest k neighbours # then decides which target the k neighbours vote on. def getKNNLoss(testData,setData,k): loss = 0 testTargets,testFeatures = prepareData_(testData) setTargets,setFeatures = prepareData_(setData) for i in range(len(testData)): yhat = findKNN(testFeatures[i],setFeatures,setTargets,k) if yhat != testTargets[i]: loss += 1 return (float(loss)/len(testData)) # Takes an input feature a trainingset and targets for these datapoints # computes the predictive valie i.e. the class attribute of the majority of # the k-nearest neighbours def findKNN(x,feats,targets,k): distanceArray = getDistanceMat(x,feats) sortedIndecies = distanceArray.argsort() classifiercount = {} for i in range(k): votetarget = targets[sortedIndecies[i]] classifiercount[votetarget] = classifiercount.get(votetarget,0)+1 sortedclassifiercount = max(classifiercount.iteritems(), key=operator.itemgetter(1))[0] return sortedclassifiercount # Calculate the euclidean distance between two vectors def getDistanceTwoPoints(x,xi): inner = 0 for i in range(len(x)): inner += (x[i] - xi[i])**2 return math.sqrt(inner) # Calculate the distance vector for a point and a vector of points def getDistanceMat(x,Mat): returnArray = np.zeros(len(Mat)) for i in range(len(Mat)): returnArray[i] = getDistanceTwoPoints(x,Mat[i]) return returnArray # returns targetvalues and features of a dataset. Assumes that the features # is at the last column def prepareData_(Data): numFeatures = Data.shape[1]-1 targetvalues = Data[:,numFeatures] features = np.delete(Data, numFeatures, axis=1) return(targetvalues,features) # takes a list of arrays and an index i. Removes the ith dataset and uses this # for validation, merges the rest into the training data. def removeRest(i,listofarrays): trainingset = [] validation = listofarrays[i] for j in range(len(listofarrays)): if i != j: trainingset.append(listofarrays[j]) comb= np.vstack([trainingset[0],trainingset[1],trainingset[2],trainingset[3]]) return (comb,validation) # shuffles the data randomly, split data into n partitions def split(Data,splits): np.take(Data,np.random.permutation(Data.shape[0]),axis=0,out=Data) return np.split(Data,splits) # perform cross validation def crossValidate(filename,splits,flag): kvals = [x for x in range(26) if x&1 != 0] missAvgList = [] if flag == True: Data = np.loadtxt(filename) else: Data = filename folds = split(Data,splits) kcountMisses = {} for k in kvals: kcountMisses[k] = 0 for i in range(len(folds)): (trainingset,validation) = removeRest(i,folds) (Val_targetvalues, Val_features) = prepareData_(validation) (Train_targetvalues, Train_features) = prepareData_(trainingset) for j in range(len(Val_features)): yhat = findKNN(Val_features[j],Train_features,Train_targetvalues,k) if yhat != Val_targetvalues[j]: kcountMisses[k] += 1 kcountMisses[k] = (kcountMisses[k] / float(splits)) / len(Val_features) missAvgList.append(kcountMisses[k]) return missAvgList # perform normalization of test set with respect to values of trainingset def autoNorm(training,test): Data = np.loadtxt(training) test = np.loadtxt(test) (testval,testdata) = prepareData_(test) (val,dataSet) = prepareData_(Data) mean = np.sum(dataSet,axis=0)/len(Data) variance = (np.sum((dataSet - mean)**2,axis=0)/len(Data)) meanTrain = mean; varTrain = variance std = np.sqrt(variance) normalizedTest = (testdata - mean) / np.sqrt(variance) normalizedData = (dataSet - mean) / np.sqrt(variance) meanTest = np.mean(normalizedTest,axis=0) varTest = np.var(normalizedTest,axis=0) return normalizedTest,normalizedData,meanTrain,varTrain,meanTest,varTest # plot dataset def plot(filename,norm): Data = np.loadtxt(filename) label = Data[:,2] if norm == True: (Data) = autoNorm(filename) fig = plt.figure() ax = fig.add_subplot(111) colors = ['red','green','blue'] ax.scatter(Data[:,0],Data[:,1],c=label, cmap=matplotlib.colors.ListedColormap(colors)) plt.show() # perform cross validation on normalized data def getNormCrossValidation(): kvals = [x for x in range(26) if x&1 != 0] Dat = np.loadtxt("IrisTrainML.dt") numFeatures = Dat.shape[1]-1 targetvalues = Dat[:,numFeatures] jib,Data = autoNorm("IrisTrainML.dt","IrisTrainML.dt") print Data.shape print targetvalues.shape targetvalues = targetvalues.reshape(100,1) data = np.append(Data,targetvalues,axis=1) miss = crossValidate(data,5,False) return miss def plotcrossvalidation(): kvals = [x for x in range(26) if x&1 != 0] miss = getNormCrossValidation() p1, = plt.plot(kvals,miss,label='Average loss') plt.legend(handles=[p1],loc=1) plt.ylabel('Average loss over 5 folds') plt.xlabel('k') plt.show() return miss def printCross(crossValres): kvals = [x for x in range(26) if x&1 != 0] for i in range(len(crossValres)): print "k = " + str(kvals[i]) + ": " + str(crossValres[i]) # Main function for running assignment 1.1 def main(): ks = [1,3,5] trainingData = np.loadtxt("IrisTrainML.dt") testData = np.loadtxt("IrisTestML.dt") print "Assignment 1.1: \n" for k in ks: loss = getKNNLoss(trainingData,trainingData,k) loss1 = getKNNLoss(testData,trainingData,k) print "Loss for k = " + str(k) + " Training data: " + str(loss)\ + " Test data: " + str(loss1) print "\n" print "Assignment 1.2: \n" miss = crossValidate("IrisTrainML.dt",5,True) print "Result of performing crossvalidate:" printCross(miss) (dattest,dattrain,meanTrain,varTrain,meanTest,varTest) =\ autoNorm("IrisTrainML.dt", "IrisTestML.dt") print "\n" print "Assignment 1.3 \n" print "Mean of training data: " + str(meanTrain) print "Variance of training data " + str(varTrain) print "Mean of test data " + str(meanTest) print "variance of test data " + str(varTest) main()
108b824c22d3c1f724238baf01663d2eeab65111
[ "Python" ]
8
Python
chrisdawgr/ml
1ed29eac9a44ff13fec49e4f92000eec50460f3a
45336b3fa965a7e2b9000aa7f1db7c53de9c9f96
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { public function showHome() { return view('frontend.home'); } public function showProductsByCategory($slug) { $data=[]; $data['slug']=$slug; return view('frontend.category',$data); } public function showAbout() { return view('about'); } } <file_sep><?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //Route ::get('/',function(){ // return view ('index'); //}); Route::get('/','HomeController@showHome')->name('home'); Route::get('/category/{slug}','HomeController@showProductsByCategory')->name('category'); Route::get('/about','HomeController@showAbout')->name('about'); Route::get('/register','User@showRegister')->name('register'); Route::get('/login','User@showLogin')->name('login'); //group route..... //Route::group(['prefix'=>'admin'],function (){ // Route::get('/create',''); // Route::get('/lists',''); // Route::get('/dashboard',''); // Route::get('/users/1',''); //}); <file_sep><?php namespace App\Http\Controllers; use App\Http\Controllers\HomeController; class User { public function showRegister() { //return view('register'); echo "Register"; } public function showLogin() { //return view('login'); echo"Login"; } }
a8d3fdb16c3f83fb986e0f03e159f054acd689b4
[ "PHP" ]
3
PHP
abdullah733/ppi_ecommerce-project-using-laravel-5.8
9dab367a8d08dd30dae22872366fc50dd3486193
8e5182ac845bb435b03923a92d2aa50abd72e5e6
refs/heads/master
<file_sep> // option 3 wala thingy $('.option3 .but').on("click",function(){ // $('.option3 .but').removeClass("selected"); $(this).toggleClass("selected"); $(this).next().toggleClass("goBold"); // console.log("i am a barbie girl..."); }); // three option thing $('.butthurt .but').on("click",function(){ if(($(".butthurt .but.selected").length<=2) || ($(".butthurt .but.selected").length==0)){ $(this).toggleClass("selected"); } else { $(this).removeClass("selected"); } }); // number and comma thingy. $('input.number').keyup(function(event) { if(event.which >= 37 && event.which <= 40) return; $(this).val(function(index, value) { return value .replace(/\D/g, "") .replace(/\B(?=(\d{3})+(?!\d))/g, ",") ; }); }); // Shuffiling slides // array variable var arr=[1,2,3,4]; var count=0; $('.main').text(count+1); var arr2=shuffle(arr); arr2.push(5); arr2.unshift(0); check(); var sCount=1; function shuffle(array) { var currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } function check(){ if(count==0) { $('.pre').hide(); } else { $('.next').show(); $('.pre').show(); $('.skip.overr').show(); if(count==5){ $('.next').hide(); $('.skip.overr').hide(); // $('.form-thing').slick({ // }); } } } $('.next').on("click",function(){ addd(); }); $('.skip').on("click",function(){ addd(); }); $('.pre').on("click",function(){ rem(); }); $('.form-thing').on('swipe', function(event, slick, direction){ if(direction=='right') { console.log("wow-right"); if(sCount!=1 || count!=0){ rem(); } } else if(direction=='left') { console.log("wow-left"); console.log("Scount "+sCount); console.log("count "+count); if(1){ addd(); } } }); function addd(){ if(sCount>=6 || count>=5) { console.log("dont work ! "); } else { count++; $('.form-thing').slick('slickGoTo',arr2[count]); sCount++; $('.main').text(sCount); check(); console.log("Scount "+sCount); console.log("count "+count); } } function rem(){ count--; $('.form-thing').slick('slickGoTo',arr2[count]); sCount--; $('.main').text(sCount); check(); console.log("Scount "+ sCount); console.log("count "+ count); } // final shit upload to firebase and change some shit // $('submi').on("click",function(){ // $('.sheet-5').html('<h2 class="f-36">Thanks, got it!</h2><h2>You\'ll hear from us within next 48 hours</h2><a href="#" class="cta">Browse bikes of your prefference</a>'); // post(); // }); $( "#Fomr" ).submit(function( event ) { event.preventDefault(); if($('.Num').val()!='') { $('.form-thing').hide(); $('.sheet-6').show() $('.load').addClass('animated slideInUp'); $('.pre').hide(); update(); } }); function update(){ console.log("update has been called : "); var ref = new Firebase("https://landingwa.firebaseio.com/main"); ref.push({ Year:$('#Age').val(), Travel:$('#travel').val(), Budget: $('.number').val(), Important:$('.butthurt .selected').text(), Type:$('.option3 p.goBold').text(), Name:$('.Fname').val(), Number:$('.Num').val(), Time:Firebase.ServerValue.TIMESTAMP, }); }
3f78c929377a852be7c7eae836ca6f1620aa0b7b
[ "JavaScript" ]
1
JavaScript
Sarabpreet/Lead-Generation-Landing-Page
b9419c113700b954d64c0826fefa2871808c3104
6647d00badfb3a0203777befdeca44584c1eceb6
refs/heads/master
<repo_name>mferrais/photCodes<file_sep>/photCodes/fileCrop.py import numpy as np field = 341 field = 340 field = 342 field = 344 field = 345 field = 347 field = 346 telescope = 'TS' telescope = 'TN' night = '20171127' night = '20171202' cut1 = 0 cut2 = 47145 cut1 = 47144 cut2 = 119110 #------------------------------------------------------------------------------ if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder folder += str(field) fname = '/h.runout1Crop' data = np.loadtxt(folder+fname)[cut1:cut2-1] print(data.shape) fname += '_' + str(field) + '_' + str(night) np.savetxt(folder + fname, data, fmt=['%10.0f','%10.4f','%10.4f','%10.4f']) print('File saved with name' + fname ) <file_sep>/photCodes/graphPhot.py import numpy as np, matplotlib.pyplot as plt, rtPhot as rtp from scipy.stats import sigmaclip from scipy.interpolate import UnivariateSpline from astroML.filters import savitzky_golay from astroML.time_series import MultiTermFit #--------------------------------------- ap = 3 ap = 18 ap = 1 ap = 13 ap = 2 field = 341 field = 342 field = 344 field = 347 field = 340 field = 343 field = 346 field = 348 field = 345 fieldExt = 'n2' fieldExt = 'n1' fieldExt = '_20171214' fieldExt = '_20171215' fieldExt = '_20171219' fieldExt = '_20171213' fieldExt = '' telescope = 'TS' telescope = 'TN' telescope = 'TNandTS' obs = 'jm' obs = 'obs2' obs = 'aij' obs = 'obs1' obs = 'obs1B' obs = 'obs1V' obs = 'obs1R' obs = 'obs1I' obs = 'obs2BVRI' obs = 'obs1BVRI' obs = 'obs1Bracc' obs = 'obs2Bracc' obs = 'obs2Iracc' obs = '18' obs = 'BVRIracc' obs = 'obs1And2' obs = '20171214VR' obs = '20171215IB' obs = 'obs123' obs = 'racc' obs = 'all' filt = 12 filt = 15 filt = 13 filt = 'BVRI' filt = 'IB' filt = 14 night = '20171218' night = '20171207' night = '20171202' night = '20171214' night = '20171215' night = '20171219' night = '20171213' clean = True clean = False fileOut = True fileOut = False if field == 340: Filter = 'R' title = '596 Scheila' subtitle = '3 - 4 Jun 2017, TRAPPIST South' ProtPos = 0.61, 1.035 tShift = 0.005 bShift = 2*tShift nights = ['20170602', '20170603', 'old'] nights = ['20170602TS', '20170603TS'] lList = [690,870] # uncleaned lList = [690,753] # last cleaned lList = [673,1445-673] # jm cleaned lList = [690,1426-690] # last cleaned ap3 lList = [1344,3072-1344] # w596_weighted lList = [673,1534-673] # last cleaned ap2 lList = [690,1443-690] # last cleaned ap2 Prot = 16.0 Prot = 15.84400,730,783 Prot = 15.848 Prot = 15.793 elif field == 342: Filter = 'R' title = '476 Hedwig' subtitle = '19 - 12 Jul 2017, TRAPPIST South' ProtPos = 0.25, 1.065 tShift = 0.005 bShift = 0.01 nights = ['20170618', '20170628', '20170709', '20170711'] Prot = 27.33 Prot = 27.336 lList = [720,46,522,161] elif field == 343: Filter = 'V' title = '3122 Florence' ProtPos = 0.6, 1.09 tShift = 0.01 bShift = 2*tShift Prot = 2.3685 Prot = 2.3581 if telescope == 'TS': subtitle = '4 Sep 2017, TRAPPIST South' nights = ['20170618','20170618','20170618','20170618','20170618','20170618'] lList = [69, 74, 67, 43, 50, 60] elif telescope == 'TN': subtitle = '4 Sep 2017, TRAPPIST North' nights = ['20170603TN','20170603TN','20170603TN','20170603TN','20170603TN','20170603TN','20170603TN','20170603TN'] nights = ['20170903TN'] lList = [78, 55, 50, 67, 100, 100, 73, 60] lList = [580] elif telescope == 'TNandTS': subtitle = '4 Sep 2017, TRAPPIST North and TRAPPIST South' nights = ['20170903TN','20170903TS','20170903TS','20170903TS','20170903TS','20170903TS','20170903TS'] nights = ['20170903TN','20170903TS','20170903TS','20170903TS','20170903TS'] nights = ['20170903TN','20170903TS'] nights = ['V20170903TN','V20170903TS','I20170903TN'] lList = [583, 56, 57, 55, 100] lList = [583, 268] lList = [583, 268, 18] elif field == 344: Filter = 'R' title = '24 Themis' subtitle = '8 - 9 Nov 2017, TRAPPIST South and 9 Nov 2017, TRAPPIST North' subtitle = '21-24 Sep + 8-9 Nov 2017, TRAPPIST South and 9 Nov 2017, TRAPPIST North' ProtPos = 0.2, 1.065 tShift = 0.005 bShift = 2*tShift nights = ['20171107', '20171108'] nights = ['20171108'] nights = ['20171107TS', '20171108TS', '20171108TN'] nights = ['20170920TS','20170921TS', '20170922TS', '20170923TS'] nights = ['20170920TS', '20170921TS', '20170922TS', '20170923TS', '20171107TS', '20171108TS', '20171108TN'] MFtimes = [2458066.4485532409] # 344 20171109 TN Prot = 8.374 lList = [707,699] lList = [76] lList = [707,699,76] lList = [700,698,62] lList = [255,315,308,362] lList = [255,315,308,362,707,699,664] lList = [255,315,308,362,701,699,651] # cleaned 1 lList = [255,315,308,362,698,698,628] # cleaned 2 elif field == 345: Filter = ' ' title = '89 Julia' ProtPos = 0.2, 0.94 tShift = 0.01 bShift = 2*tShift Prot = 11.38834 Prot = 11.387 Prot = 11.3844 if obs == 'obs1': MFTimes = [0.6] subtitle = '20 - 30 Sep 2017, TRAPPIST South' nights = ['20170920','20170921','20170922','20170930'] lList = [553,537,619,726] elif obs == 'all': subtitle = '20 - 30 Sep 2017, TRAPPIST South ; 27 Nov - 24 Dec 2017 TRAPPIST North' nights = ['V20170920TS','V20170921TS','V20170922TS','V20170930TS','R20171127TN','R20171202TN','R20171207TN','R20171223TN'] lList = [553,537,619,726,522,478,604,418] if obs == 'racc' and night == '20171202': subtitle = '2 Dec TRAPPIST North' nights = ['20171202TN'] lList = [478] elif field == 346: Filter = 'R' title = '31 Euphrosyne' ProtPos = 0.6, 1.04 tShift = 0.005 bShift = tShift*2 if obs == 'obs1And2': #MFTimes = [0.6] subtitle = '07 Nov - 02 Dec 2017, TRAPPIST North' nights = ['20171107TN','20171127TN','20171202TN'] lList = [374-15,261,365] if obs == 'obs123': subtitle = '07 Nov - 08 Dec 2017, TRAPPIST North' nights = ['20171107TN','20171127TN','20171202TN','20171207TN'] lList = [359,261,365,864] if obs == 'racc' and night == '20171207': subtitle = '7 Dec TRAPPIST North' nights = ['20171207TN'] lList = [1000] lList = [864] Prot = 5.53 Prot = 5.57991 Prot = 5.529597 Prot = 5.52874 Prot = 5.5312 elif field == 347: Filter = 'R' title = '20 Massalia' ProtPos = 0.4, 1.3 tShift = 0.01 tShift = 0.05 bShift = 2*tShift if obs == 'all': MFTimes = [2458068.636574,2458068.810945,2458076.787568] subtitle = '11 + 18 Nov 2017, TRAPPIST South and TRAPPIST North' nights = ['20171110TN','20171110TS','20171118TN','20171118TS'] lList = [700,729,700,783] lList = [600,729,700,783] Prot = 8.098 elif field == 348: Filter = '' title = '3200 Phaethon' ProtPos = 0.4, 1.075 ProtPos = 0.4, 1.2 tShift = 0.01 bShift = 2*tShift if obs == 'obs1R': nights = ['R1','R2','R3','R4','R5'] lList = [46, 50, 48, 50, 48] elif obs == 'obs1V': nights = ['V1','V2','V3','V4','V5','V6'] lList = [41, 40, 40, 45, 35, 35] elif obs == 'obs1B': nights = ['B1','B2','B3','B4','B5','B6'] lList = [22, 24, 27, 24, 24, 21] elif obs == 'obs1I': nights = ['I1','I2','I3','I4','I5','I6'] lList = [41, 40, 40, 40, 40, 35] elif obs == 'obs1BVRI' or obs == 'BVRIracc': subtitle = '9 Dec 2017, TRAPPIST North' nights = ['B','V','R','I'] lList = [142,236,242,236] elif obs == 'obs2BVRI': subtitle = '10 Dec 2017, TRAPPIST North' nights = ['B','V','R','I'] lList = [122,205,225,210] elif obs == 'obs1Bracc': subtitle = '9 Dec 2017, TRAPPIST North' nights = ['B'] lList = [142] elif obs == 'obs2Iracc': subtitle = '10 Dec 2017, TRAPPIST North' nights = ['B'] nights = ['V'] nights = ['R'] nights = ['I'] lList = [122] # B lList = [205] # V lList = [225] # R lList = [210] # I elif obs == 'racc' and night == '20171218Not': subtitle = '18 Dec 2017, TRAPPIST North' nights = ['R'] lList = [294] # R elif obs == 'racc' and night == '20171218': Filter = ' R ' subtitle = '18 and 19 Dec 2017, TRAPPIST North' nights = ['20171218TN','20171219TN'] lList = [368,299] # R elif obs == 'racc' and night == '20171219': Filter = ' R ' subtitle = '19 Dec 2017, TRAPPIST North' nights = ['20171219TN'] lList = [299] # R elif obs == 'racc' and night == '20171213': Filter = 'R' subtitle = '13 Dec 2017, TRAPPIST North' nights = ['20171213TN',] lList = [1353] # R lList = [1346] # R elif obs == 'racc' and night == '20171214': subtitle = '14 Dec 2017, TRAPPIST North' nights = ['B20171214TN'] nights = ['I20171214TN'] nights = ['V20171214TN'] nights = ['B','V','R','I'] lList = [24] # B - I lList = [460] # V lList = [360] # R lList = [24,460,360,24] # BVRI elif obs == '20171214VR': Filter = '' subtitle = '14 Dec 2017, TRAPPIST North' nights = ['R20171214TN','V20171214TN'] lList = [369,496] elif obs == '20171213R': Filter = 'R' subtitle = '13 Dec 2017, TRAPPIST North' nights = ['20171213TN'] lList = [1350] elif obs == 'racc' and night == '20171215': subtitle = '15 Dec 2017, TRAPPIST North' nights = ['I20171215TN','B20171215TN'] lList = [444,368] # IB elif obs == '20171215IB' and night == '20171215': subtitle = '15 Dec 2017, TRAPPIST North' nights = ['I20171215TN','B20171215TN'] lList = [447,405] # IB Prot = 3.603957 wsSG = 601 ffOrder = 7 #binning binData = True binData = False binW = 2 # bin width in minutes nStart = 1 gLine = True gLine = False correction = True correction = False yAxisLim = (0.5, 1.5) yAxisLim = (0.85, 1.15) yAxisLim = (0.9, 1.10) yAxisLim = (12.2, 12.7) setylim = True setylim = False setToMag = True setToMag = False showMF = True showMF = False if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" #clean win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN fo if telescope == 'TNandTS': folder = "/media/marin/TRAPPIST3/northAndSouth/" #---------------- folder += str(field) + fieldExt +'/' plt.style.use('bmh') #fname = '/' + str(field) + '_diff_ap' + str(ap) + 'Damit.txt' if clean: #cleaned data fname = str(field) + '_diff_ap' + str(ap) + '_clean.txt' #elif obs == 'obs1': # fname = '/'+str(field)+'_diff_ap'+str(ap)+'_'+telescope+obs+'.txt' elif obs == 'all': # uncleaned data fname = str(field) + '_diff_ap' + str(ap) + '.dat' elif obs == 'aij': fname = 'AIJ/03122AIJ.txt' elif obs == 'BVRIracc': fname = str(field)+'_'+telescope+'_'+night+'_'+str(ap)+'_BVRI'+'.mag' elif obs == 'racc': fname = str(field)+'_'+telescope+'_'+night+'_'+str(ap)+'_'+str(filt) if setToMag: fname += '.mag' else: fname += '.flux' else: #fname = '/'+str(field)+'_diff_ap'+str(ap)+'_'+telescope+obs+'.txt' fname = str(field)+'_diff_ap'+str(ap)+'_'+telescope+obs+'.dat' data = np.loadtxt(folder + fname) time = data[:,0] astDiffFlux = data[:,1] astFluxErr = data[:,2] if obs == 'jm': setToMag = True folder = '/home/marin/Downloads/Fwd_Scheila_LC/' fname = 'w596_weighted.txt' data = np.loadtxt(folder + fname) time = data[:,0] astDiffFlux = data[:,1] nPts = len(astDiffFlux) print(fname) print(str(nPts) + ' nPts') #----- detrend ---------------------------------------------------------------- """ # fit a straight line to correct trend due to phase angle changes l0 = 0 for i in range(len(nights)): li = lList[i] flux, t= astDiffFlux[l0:l0+li], time[l0:l0+li] spl = UnivariateSpline(t, flux,k=3) detrendFlux = flux / spl(t) plt.plot(t,flux,'C0.', t,spl(t),'k--', t,detrendFlux,'C1.') plt.show() ''' pfit = np.poly1d(np.polyfit(t, flux, 2)) detrendFlux = flux / pfit(t) plt.plot(t,flux,'.', t,pfit(t),'k--', t,detrendFlux,'.') plt.show() ''' astDiffFlux[l0:l0+li] = detrendFlux l0 +=li #astDiffFlux[l0:l0+li] -= np.mean(astDiffFlux[l0:l0+li]) astDiffFlux = data[:,1] """ """ # use the overlaping part in JD of two LC to match their fluxes l0 = lList[0] f1, time1 = astDiffFlux[0:l0], time[0:l0] for i in range(1, len(nights)): li = lList[i] f2, time2 = astDiffFlux[l0:l0+li], time[l0:l0+li] shift = rtp.meanShift(f1, f2, time1, time2) astDiffFlux[l0:l0+li] += shift l0 += li print(str(shift) + ' : shift ' + nights[i]) astDiffFlux /= np.mean(astDiffFlux) """ #----- Correction ------------------------------------------------------------- i = 0 ind = [] for l in lList: i += l ind.append(i) print(ind, 'ind') if correction: if field == 343: #astDiffFlux = -2.5 * np.log10(astDiffFlux) print(field,obs) astDiffFlux[ind[1]:ind[2]] -= 0.065 elif field == 344 and obs == 'all': print(field,obs) astDiffFlux[:ind[0]] -= 0.0035 astDiffFlux[ind[3]:ind[4]] += 0.015 astDiffFlux[ind[4]:ind[5]] += 0.010 astDiffFlux[2685+250:] += 0.01 elif field == 345: print(field,obs) astDiffFlux[:ind[0]] -= 0.0 astDiffFlux[ind[0]:ind[1]] -= 0.0 astDiffFlux[ind[1]:ind[2]] -= 0.0 astDiffFlux[ind[2]:ind[3]] -= 0.0 astDiffFlux[ind[3]:ind[4]] -= 0.0 astDiffFlux[ind[4]:ind[5]] -= 0.0 astDiffFlux[ind[5]:ind[6]] -= 0.0 astDiffFlux[ind[6]:ind[7]] -= 0.0 elif field == 346: print(field,obs) elif field == 347: print(field,obs) astDiffFlux[ind[0]:ind[1]] += 0.016 astDiffFlux[ind[1]:ind[2]] -= 0.019 astDiffFlux[ind[2]:ind[3]] -= 0.010 elif field == 348 and obs == 'obs1B': print(field,obs) elif field == 348 and obs == 'racc' and not setToMag and night == '20171214': print(field,obs) elif field == 348 and obs == 'racc' and setToMag and night == '20171214': print(field,obs) astDiffFlux[:ind[0]] += 13 - np.mean(astDiffFlux[:ind[0]]) astDiffFlux[ind[0]:ind[1]] += 13 - np.mean(astDiffFlux[ind[0]:ind[1]]) astDiffFlux[ind[1]:ind[2]] += 13 - np.mean(astDiffFlux[ind[1]:ind[2]]) astDiffFlux[ind[2]:ind[3]] += 13 - np.mean(astDiffFlux[ind[2]:ind[3]]) elif field == 348 and obs == '20171214VR': print(field,obs) astDiffFlux[ind[0]:ind[1]] += 0.04 elif field == 348 and obs == 'racc' and setToMag and night == '20171215': print(field,obs) astDiffFlux[ind[0]:ind[1]] += 0.0 elif field == 348 and obs == '20171215IB' and night == '20171215': print(field,obs) astDiffFlux[ind[0]:ind[1]] -= 0.0 if setToMag: #astDiffFlux -= np.mean(astDiffFlux) bob = 'bob' else: astDiffFlux /= np.mean(astDiffFlux) #----- data smoothing --------------------------------------------------------- """ span = 10 for i in xrange(nPts): pts = astDiffFlux[i] mean = np.mean(astDiffFlux[i-span:i+span]) fluxSmooth = savitzky_golay(astDiffFlux, window_size=201, order=4) plt.plot(time,astDiffFlux,'C1.', time,fluxSmooth,'k.') plt.show() """ #------ Data Binning ---------------------------------------------------------- # index list i = 0 ind = [] for l in lList: i += l ind.append(i) print(lList, 'lList') if binData: oldTime, oldAstDiffFlux, = time, astDiffFlux oldAstFluxErr = astFluxErr astDiffFlux = rtp.binning(astDiffFlux, time, binW, ind)[0] astFluxErr = rtp.binning(astFluxErr, time, binW, ind)[0] resBin = rtp.binWeighted(time, time, oldAstFluxErr, binW, ind) time, lList = resBin[0], resBin[1] print(len(time), ' new nPts') print(lList, 'new lList') # phase nind = [0] + ind t0 = time[nind[nStart-1]] if field == 347: t0 = 2458068.423936 if field == 348: t0 = 2458097.280053 ProtJD = Prot/24. phase = [((t - t0)/ProtJD) % 1. for t in time] d = 60 if binData: nind = [0] + ind t0 = oldTime[nind[nStart-1]] if field == 347: t0 = 2458068.423936 ProtJD = Prot/24. oldPhase = [((t - t0)/ProtJD) % 1. for t in oldTime] fluxByPhase = [f for _,f in sorted(zip(oldPhase,oldAstDiffFlux))] errByPhase = [f for _,f in sorted(zip(oldPhase,oldAstFluxErr))] timeByPhase = [f for _,f in sorted(zip(oldPhase,oldTime))] sortedPhase = sorted(oldPhase) sortedPhaseBin = sorted(rtp.binning(oldPhase, oldTime, binW, ind)[0]) fluxByPhaseBin = rtp.binWeighted(fluxByPhase,oldTime,oldAstFluxErr,binW,ind)[0] weights = [ 1./(err**2) for err in errByPhase] pfit = np.poly1d(np.polyfit(sortedPhase, fluxByPhase, deg=d, w=weights)) fitCurve = pfit(sortedPhase) strCurve = fluxByPhase / fitCurve else: fluxByPhase = [f for _,f in sorted(zip(phase,astDiffFlux))] errByPhase = [f for _,f in sorted(zip(phase,astFluxErr))] sortedPhase = sorted(phase) sortedPhaseBin = sorted(rtp.binning(phase, time, binW, ind)[0]) fluxByPhaseBin = rtp.binWeighted(fluxByPhase, time, astFluxErr,binW, ind)[0] weights = [ 1./(err**2) for err in errByPhase] pfit = np.poly1d(np.polyfit(sortedPhase, fluxByPhase, deg=d, w=weights)) fitCurve = pfit(sortedPhase) strCurve = fluxByPhase / fitCurve fluxByPhaseSG = savitzky_golay(fluxByPhase, window_size=wsSG, order=4) #----- Fourier Fit ------------------------------------------------------------ omega = 2 * np.pi / Prot * 24. mtf = MultiTermFit(omega, ffOrder) mtf.fit(time, astDiffFlux, astFluxErr) phaseFit, fluxFit, phasedTime = mtf.predict(1000, return_phased_times=True) phaseFit -= phasedTime[0] phasedTime -= phasedTime[0] phasedTime = [1+t if t < 0 else t for t in phasedTime] phaseFit = [1+t if t < 0 else t for t in phaseFit] plt.errorbar(phasedTime, astDiffFlux, astFluxErr, fmt='.k', ecolor='gray', lw=1, ms=4, capsize=1.5) plt.plot(phaseFit, fluxFit, 'b.', lw=10, label='order = '+str(ffOrder)) plt.xlabel('Rotational Phase') plt.ylabel('Relative ' + Filter + ' Flux') plt.suptitle(title, y=0.945, fontsize=18) plt.title(subtitle, fontsize=10) if setToMag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') if setylim: plt.ylim(yAxisLim) plt.xlim(-0.01, 1.01) plt.tick_params(direction='in', right='on',top='on', bottom='on') plt.text(ProtPos[0], ProtPos[1], 'Prot = '+str(Prot)+' h', fontsize=12) plt.text(ProtPos[0], ProtPos[1]-tShift, 'Zero time = '+str('%.6f' % t0)+' JD', fontsize=12) plt.minorticks_on() plt.legend(loc='best') plt.show() #---- saving on file ---------------------------------------------------------- if fileOut and binData: print('Warning : data are binned !') if fileOut and not binData: print('* File has been saved on folder : ' + folder) print('With name: ' + fname) data = np.dstack((time, astDiffFlux, astFluxErr))[0] np.savetxt(folder + fname, data, fmt=['%10.6f','%.6e','%.2e']) """ ind = [0] + ind TScount = 0 TNcount = 0 for night in nights: count = TScount + TNcount if night[-1] == 'S': TScount += 1 fnameN = fname[:-4] + '_' + night[-02:]+'obs'+str(TScount)+'_FM.dat' else: TNcount += 1 fnameN = fname[:-4] + '_' + night[-2:]+'obs'+str(TNcount)+'_FM.dat' print('* Night file has been saved on folder : ' + folder) print('With name: ' + fnameN) dataN = data[ind[count]:ind[count+1]] magN = -2.5 * np.log10(dataN[:,1]) magErrN = -2.5 * np.log10(dataN[:,2]) dataN = np.dstack((dataN[:,0], dataN[:,1], dataN[:,2], magN, magErrN))[0] np.savetxt(folder + fnameN, dataN, fmt=['%10.6f','%.6e','%.2e','%.6e','%.2e']) """ #------- Graphs --------------------------------------------------------------- #astDiffFlux = -2.5 * np.log10(astDiffFlux) """ u = np.arange(len(sortedPhaseBin)) plt.plot(u, sortedPhaseBin, '.') plt.show() """ months = {'01':'Jan','02':'Feb','03':'Mar','04':'Apr','05':'May','06':'Jun', '07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'} colors = ['C0.','C1.','C2v','C3*','C4.','C5.','C6.','C7.'] colors = ['C0p','C1.','C2^','C3*','C4h','C5v','C6s','C7x'] colors = ['C0p','C1,','C2,','C3*','C4h','C5v','C6s','C7x'] colors = ['C0.','C1.','C2.','C3.','C4.','C5.','C6.','C7.','C8.','C9.'] colors = ['#0082c8','#3cb44b','#f58231','#800000'] # BVRI colors mark = ['p','.','^','*','h','v','s','x'] colors = ['b','g','r','#800000'] # BVRI colors colors = ['r','g'] # RV colors colors = ['#800000','b'] # IB colors colors = ['C0','C1','C2','C3','C4','C5','C6','C7','C8','C9'] markDot = ['.' for c in colors] mark = ['h','s','v','p'] mark = ['h','o','v','p','s'] mark = markDot colorsLine = ['C0-','C1-','C2-','C3-','C4-','C5-','C6-','C7-'] labels = [] for i in range(len(nights)): if len(nights[0]) == 10: label = nights[i][-2:] + ' ' + nights[i][0:4] + ' ' label += months[str(nights[i][4:6])]+' '+str(int(nights[i][-4:-2])) #label += months[str(nights[i][4:6])]+' '+str(int(nights[i][-4:-2])) labels.append(label) elif len(nights[0]) == 11: label = nights[i][-2:] + ' ' + nights[i][1:5] + ' ' label += months[str(nights[i][5:7])]+' ' label += str(int(nights[i][-4:-2]))+' ('+nights[i][0] + ')' labels.append(label) else: labels.append(nights[i]) # Plot the whole phased curve lab = ''.join([n + ', ' for n in labels]) #plt.plot(sortedPhase, fluxByPhase, colors[1], label=lab) plt.plot(sortedPhaseBin, fluxByPhaseBin, 'C1.', label=lab) #plt.plot(sortedPhaseBin, fluxByPhaseBin, colors[1]) plt.xlabel('Rotational Phase') plt.ylabel('Relative ' + Filter + ' Flux') plt.suptitle(title, y=0.945, fontsize=18) plt.title(subtitle, fontsize=10) if setToMag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') if setylim: plt.ylim(yAxisLim) plt.xlim(-0.01, 1.01) plt.tick_params(direction='in', right='on',top='on', bottom='on') plt.text(ProtPos[0], ProtPos[1], 'Prot = '+str(Prot)+' h', fontsize=12) plt.text(ProtPos[0], ProtPos[1]-tShift, 'Zero time = '+str('%.6f' % t0)+' JD', fontsize=12) plt.text(ProtPos[0],ProtPos[1]-bShift,'Bin = '+str(binW)+' min', fontsize=12) plt.plot(sortedPhase, fluxByPhaseSG, 'k.', label='Savitzky_Golay') plt.legend(loc='best') plt.show() """ # test fit plt.plot(sortedPhase, fluxByPhase, 'r.', label='flux') plt.plot(sortedPhase, fitCurve, 'k-', label='fitted curve') plt.plot(sortedPhase, strCurve, 'b.', label='redressed curve') plt.xlabel('Rotational Phase') plt.ylabel('Relative ' + Filter + ' Flux') plt.suptitle(title, y=0.945, fontsize=18) plt.title(subtitle, fontsize=10) plt.legend(loc='best') if setToMag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') if setylim: plt.ylim(yAxisLim) plt.xlim(-0.01, 1.01) plt.tick_params(direction='in', right='on',top='on', bottom='on') plt.text(ProtPos[0], ProtPos[1], 'Prot = '+str(Prot)+' h', fontsize=12) plt.text(ProtPos[0], ProtPos[1]-tShift, 'Zero time = '+str('%.6f' % t0)+' JD', fontsize=12) plt.text(ProtPos[0],ProtPos[1]-bShift,'Bin = '+str(binW)+' min', fontsize=12) plt.show() """ # Plot flux or mag in a sequential way l0 = 0 for i in range(len(nights)): li = lList[i] plt.plot(np.arange(li)+l0+1, astDiffFlux[l0:li+l0], '.', label=labels[i]) l0 += li plt.xlabel('n') plt.ylabel('Relative ' + Filter + ' Flux') if setToMag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') plt.title('Sequential plot') plt.legend() plt.show() """ # Plot error in a sequential way l0 = 0 for i in range(len(nights)): li = lList[i] plt.plot(np.arange(li)+l0+1, astFluxErr[l0:li+l0], '.', label=labels[i]) l0 += li plt.xlabel('n') plt.ylabel('error') plt.title('Error sequential plot') plt.legend() plt.show() """ # Plot flux or mag vs rotational phase l0 = 0 if gLine: colors = colorsLine for i in range(len(nights)): li = lList[i] plt.plot(phase[l0:li+l0], astDiffFlux[l0:li+l0], color=colors[i], marker=mark[i], linestyle='None' ,label=labels[i]) #plt.plot(phase[l0:li+l0], astDiffFlux[l0:li+l0], colors[i]) #plt.errorbar(phase[l0:li+l0], astDiffFlux[l0:li+l0] # , yerr=astFluxErr[l0:li+l0], fmt=colors[i]) l0 += li plt.xlabel('Rotational Phase') plt.ylabel('Relative ' + Filter + ' Flux') plt.suptitle(title, y=0.945, fontsize=18) plt.title(subtitle, fontsize=10) if setylim: plt.ylim(yAxisLim) if setToMag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') plt.xlim(-0.01, 1.01) plt.tick_params(direction='in', right='on',top='on', bottom='on') plt.text(ProtPos[0], ProtPos[1], 'Prot = '+str(Prot)+' h', fontsize=12) plt.text(ProtPos[0], ProtPos[1]-tShift, 'Zero time = '+str('%.6f' % t0)+' JD', fontsize=12) if binData: plt.text(ProtPos[0],ProtPos[1]-bShift,'Bin = '+str(binW)+' min', fontsize=12) if showMF: MFphases = [(t - t0)/ProtJD % 1. for t in MFTimes] for i in range(len(MFphases)): x1, x2 = MFphases[i], MFphases[i] plt.plot((x1,x2),(min(astDiffFlux),max(astDiffFlux)),colorsLine[i]) ''' d = 2458132 u = np.arange(d+0.3,d+0.4,0.001) phaseT = [((t - t0)/ProtJD) % 1. for t in u] plt.plot(phaseT, [1 for x in phaseT], 'k.') ''' plt.plot(sortedPhase, fluxByPhaseSG, 'k.', label='Savitzky_Golay') plt.legend(loc='best') plt.show() ### Plot flux or mag vs JD + Error ############################################ """ plt.figure(1) plt.subplot(211) #ax1 = plt.subplot(211) l0 = 0 for i in range(len(nights)): li = lList[i] plt.plot(time[l0:li+l0]-2450000, astDiffFlux[l0:li+l0], color=colors[i], marker=markDot[i], linestyle='None' ,label=labels[i]) #plt.plot(time[l0:li+l0]-2450000, astDiffFlux[l0:li+l0],'.') l0 += li #plt.xlabel('Julian Day - 2450000') plt.ylabel('Relative ' + Filter + ' Flux') plt.suptitle(title, y=0.945, fontsize=18) plt.title(subtitle, fontsize=10) plt.legend(loc='best') if setylim: plt.ylim(yAxisLim) if setToMag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') #plt.setp(ax1.get_xticklabels(), visible=False) plt.subplot(212) #ax2 = plt.subplot(212, sharex=ax1) l0 = 0 for i in range(len(nights)): li = lList[i] plt.plot(time[l0:li+l0]-2450000, astFluxErr[l0:li+l0], color=colors[i], marker=markDot[i], linestyle='None' ,label=labels[i]) #plt.plot(time[l0:li+l0]-2450000, astFluxErr[l0:li+l0], '.') l0 += li plt.xlabel('Julian Day - 2450000') plt.ylabel('Error') #plt.setp(ax2.get_xticklabels()) #plt.subplots_adjust(left=0.2, wspace=0.8, top=0.8) plt.legend(loc='best') """ ############### f, (ax1, ax2) = plt.subplots(2, 1, sharex='all', gridspec_kw = {'height_ratios':[3, 1]}) l0 = 0 for i in range(len(nights)): li = lList[i] ax1.scatter(time[l0:li+l0]-2450000, astDiffFlux[l0:li+l0], color=colors[i], marker=mark[i], linestyle='None' ,label=labels[i]) #ax1.plot(time[l0:li+l0]-2450000, astDiffFlux[l0:li+l0],'.') l0 += li ax1.set_ylabel('Relative ' + Filter + ' Flux') plt.suptitle(title, y=0.935, fontsize=18) ax1.set_title(subtitle, fontsize=10) ax1.legend(loc='best') ax2.set_ylabel('Flux Error') if setylim: ax1.set_ylim(yAxisLim) if setToMag: ax1.invert_yaxis() ax1.set_ylabel('Differential ' + Filter + ' Mag ') ax2.set_ylabel('Mag Error') # error l0 = 0 for i in range(len(nights)): li = lList[i] ax2.plot(time[l0:li+l0]-2450000, astFluxErr[l0:li+l0], color=colors[i], marker=mark[i], linestyle='None' ,label=labels[i]) #ax2.plot(time[l0:li+l0]-2450000, astFluxErr[l0:li+l0], '.') l0 += li ax2.set_xlabel('Julian Day - 2450000') ax1.minorticks_on() #ax2.legend(loc='best') plt.show() """ s = 2 plt.figure(1) plt.subplot(221) l0 = 0 for i in range(0,len(nights)-s): li = lList[i] plt.plot(time[l0:li+l0]-2450000, astDiffFlux[l0:li+l0],'.',label=labels[i]) l0 += li plt.xlabel('Julian Day - 2450000') plt.ylabel('Relative ' + Filter + ' Flux') plt.title(title+' - 11 Novembre') plt.legend(loc='best') if setylim: plt.ylim(yAxisLim) if setToMag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') plt.subplot(222) l0 = sum(lList[:s]) for i in range(s,len(nights)): li = lList[i] plt.plot(time[l0:li+l0]-2450000, astDiffFlux[l0:li+l0],'.',label=labels[i]) l0 += li plt.xlabel('Julian Day - 2450000') plt.ylabel('Relative ' + Filter + ' Flux') plt.title(title+' - 19 Novembre') plt.legend(loc='best') if setylim: plt.ylim(yAxisLim) if mag: plt.gca().invert_yaxis() plt.ylabel('Differential ' + Filter + ' Mag ') plt.subplot(223) l0 = 0 for i in range(0,len(nights)-s): li = lList[i] plt.plot(time[l0:li+l0]-2450000, astFluxErr[l0:li+l0], '.',label=labels[i]) l0 += li plt.xlabel('Julian Day - 2450000') plt.ylabel('Error') plt.legend(loc='best') plt.subplot(224) l0 = sum(lList[:s]) for i in range(s,len(nights)): li = lList[i] plt.plot(time[l0:li+l0]-2450000, astFluxErr[l0:li+l0], '.',label=labels[i]) l0 += li plt.xlabel('Julian Day - 2450000') plt.ylabel('Error') plt.legend(loc='best') plt.show() """ <file_sep>/photCodes/rawConcat.py import numpy as np #--------------------------------------- field = 341 field = 340 field = 342 field = 344 field = 347 telescope = 'TS' telescope = 'TN' obs = 'obs1' obs = 'obs2' if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN fo if telescope == 'TNandTS': folder = "/media/marin/TRAPPIST3/northAndSouth/" #--------------------------------------- folder += str(field) apList = [1,2,3] fnameL = ['/' + str(field) + '_raw_ap' + str(ap) + '_' + telescope+obs + '.txt' for ap in apList] datas = [np.loadtxt(folder+fname) for fname in fnameL] dataRaw = np.dstack((datas[0][:,0], datas[0][:,1], datas[1][:,1], datas[2][:,1]))[0] fnameRaw = '/' + str(field) + '_raw' + '_' + telescope+obs + '.txt' print('Raw file has been saved on folder : ' + folder) print('With name: ' + fnameRaw[1:]) np.savetxt(folder + fnameRaw, dataRaw) <file_sep>/photCodes/updateLog.py import glob from astropy.io import fits """ Update WCS Status on TRAP.log so those images who had their WCS corrected can be used in photometry. Remember to do ! sh TRAPall3.sh after to update TRAPall3.log """ tele = 'TS' tele = 'TN' year = 2017 jd1 = 8085 jd2 = 8091 binn = 1 # image binning if tele == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/r" # TS folder pattern = 'TRAP.' + str(year) + '-' + '*' histInd = 1 if tele == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/r" # TN folder pattern = 'TROP.' + str(year) + '-' + '*' histInd = 2 #------------------------------------------------------------------------------ folder += str(year) + '/' + str(jd1)+'_'+str(jd2)+'_B'+str(binn)+'R11'+ '/' print(folder+pattern, 'fold + patt') fnames = sorted(glob.glob(folder + pattern)) nIm = len(fnames) print(str(nIm)+ ' images found') logFile = folder + 'TRAP.log' with open(logFile, 'r') as f: log = f.readlines()[1:] print(str(len(log)) + ' lines on log file') log = [x.strip().split() for x in log] nbrCorrWCS = 0 nbrNoWCS = 0 print('-----') for i in xrange(nIm): fname = fnames[i] hdulist = fits.open(fname) header = hdulist[0].header try: wcsOk = header['HISTORY'][histInd] if log[i][-7] == 'NO': log[i][-7], log[i][-6] = 'WCS', 'OK' nbrCorrWCS += 1 except IndexError: print('NO WCS : ' + fname[54:]) print('-----') nbrNoWCS += 1 hdulist.close() if i%1000 == 0: print(str(i)+' images checked over '+str(nIm)) log = [' '.join(line) for line in log] print(len(log)) print('No WCS to Ok : ' + str(nbrCorrWCS)) print('No WCS : ' + str(nbrNoWCS)) newLogName = folder+'TRAP.logTmp' newLog = open(newLogName, 'w') textList = map(lambda x: x+"\n", log) textList.insert(0, '\n') newLog.writelines(textList) newLog.close() print('updated log saved as TRAP.logTMP') <file_sep>/photCodes/rtPhot.py import numpy as np, matplotlib.pyplot as plt #------ formatPhot ------------------------------------------------------------ def inAllIm(listID): """search the stars detected on all images, via their IDs""" inAll = listID[0] # we start with the IDs of the first image newInAll = [] for IDs in listID: for ID in IDs: if ID in inAll: newInAll.append(ID) inAll = newInAll newInAll = [] return inAll #------ plotPhot -------------------------------------------------------------- def getMeanCmag(data, ap, nCstar, badID): """ Compute for each images the mean magnitude off all the comparison stars, except for those whose ID is in the list badID (variable stars) """ meanCmag = [] for line in data: magLine, index = [], 1 for i in xrange(5 + ap, 5 + ap + 3*nCstar, 3): if index not in badID: magLine.append(line[i]) index += 1 meanCmag.append(np.mean(magLine)) return np.array(meanCmag) def getSumCfluxArea(data, ap, nCstar, badID): """ Compute for each images the flux sum of all the comparison stars, except for those whose ID is in the list badID (variable stars) """ sumCflux = [] sumCarea = [] for line in data: fluxLine, areaLine, index = [], [], 1 i1 = 5 + ap + 6*(nCstar+1) for i in xrange(i1, i1 + 3*nCstar, 3): if index not in badID: fluxLine.append(line[i]) areaLine.append(line[i + 3*(nCstar+1)]) index += 1 sumCflux.append(np.sum(fluxLine)) sumCarea.append(np.sum(areaLine)) return np.array(sumCflux), np.array(sumCarea) def getMeanCstarMsky(data, nCstar, badID, gain): """ Compute for each images the mean background level for all comp stars """ meanMsky = [] lenLine = len(data[0]) for line in data: mskyLine, index = [], 1 for i in xrange(4 + 12*(nCstar+1), lenLine): if index not in badID: mskyLine.append(line[i]*gain) index += 1 meanMsky.append(np.mean(mskyLine)) return np.array(meanMsky) def seeCstars(data, ap, nCstar, corrTime, meanCmag): """ Plot raw and diff mag of each comp stars one by one""" for i in xrange(nCstar): cStarRawMag = data[:, 5 + ap + i*3] cStarDiffMag = cStarRawMag - meanCmag plt.plot(corrTime, cStarRawMag - np.mean(cStarRawMag), '.r', label='rawMag') plt.plot(corrTime, cStarDiffMag - np.mean(cStarDiffMag) + 0.2, '.k', label='diffMag') plt.title(str(i+1)) plt.gca().invert_yaxis() plt.legend() plt.show() def seeTenByTenCstars(data, ap, nCstar, corrTime, meanCmag): """ Plot raw and diff mag of each comp stars 10 by 10""" for i in xrange(0, nCstar, 10): for j in xrange(10): cStarRawMag = data[:, 5 + ap + (i+j)*3] cStarDiffMag = cStarRawMag - meanCmag plt.plot(corrTime, cStarRawMag - np.mean(cStarRawMag) + j, '.r') plt.plot(corrTime, cStarDiffMag - np.mean(cStarDiffMag) + j + 0.5, '.k') plt.title(str(i)) plt.show() #----- concatPhot + graphPhot ------------------------------------------------- def binning(listToBin, time, binT, nightLen): """ bin listToBin binT by binT """ tmpList, listBinned, newNightLen = [], [], [] tmpt0 = time[0] for i in xrange(len(listToBin)): c1, c3 = len(tmpList) == 0, i not in nightLen if (c1 or abs(tmpt0-time[i]) < binT/1440.) and c3: tmpList.append(listToBin[i]) else: listBinned.append(np.mean(tmpList)) tmpList = [listToBin[i]] tmpt0 = time[i] if i in nightLen: newNightLen.append(len(listBinned)-sum(newNightLen)) newNightLen.append(len(listBinned)-sum(newNightLen)) return listBinned, newNightLen def binWeighted(listToBin, time, fluxErr, binT, nightLen): """ Bin datas in listToBin together in a time span given by binT, separated in several nights given by nightLen and using a weighted average using the flux errors """ tmpList, tmpErr, listBinned, newNightLen = [], [], [], [] tmpt0 = time[0] for i in xrange(1,len(listToBin)): c1, c3 = len(tmpList) == 0, i not in nightLen if (c1 or abs(tmpt0-time[i]) < binT/1440.) and c3: tmpList.append(listToBin[i]) tmpErr.append(fluxErr[i]) else: #listBinned.append(np.average(tmpList, weights=tmpErr)) tmpErr = [1./x**2 for x in tmpErr] listBinned.append(np.average(tmpList, weights=tmpErr)) tmpList = [listToBin[i]] tmpt0 = time[i] tmpErr = [fluxErr[i]] if i in nightLen: newNightLen.append(len(listBinned)-sum(newNightLen)) newNightLen.append(len(listBinned)-sum(newNightLen)) return np.asarray(listBinned), newNightLen #----- concatPhot ------------------------------------------------------------- def getRawData(nightL, folder, field, ap): ''' stack togethere raw datas from different night in the array data ''' folderL = [folder + '/' + night + '/' for night in nightL] fnameL = [str(field) + '_' + night + '_raw_ap' + str(ap) + '.dat' for night in nightL] datas = [np.loadtxt(folder+fname) for folder,fname in zip(folderL,fnameL)] data = np.vstack(datas) return data def getData(nightL, folder, field, ap): ''' stack togethere datas from different night in the array data In datas the nights are kept separated ''' folderL = [folder + '/' + night + '/' for night in nightL] fnameL = [str(field) + '_' + night + '_diff_ap' + str(ap) + '.dat' for night in nightL] datas = [np.loadtxt(folder+fname) for folder,fname in zip(folderL,fnameL)] """ #normalization for i in range(len(nights)): datas[i][:,2] /= np.mean(datas[i][:,2]) """ data = np.vstack(datas) return data, datas def bridgeMatching(f1,f2,fracc): """Match 2 consecutive field of the same obs night using a third field overlaping both """ f1Time, f2Time, fraccTime = f1[:,0], f2[:,0], fracc[:,0] f1Flux, f2Flux, fraccFlux = f1[:,4], f2[:,4], fracc[:,4] l1 = len(f1Flux) jd1racc, jd2racc = fraccTime[0], fraccTime[-1] jdf1, n1 = f1Time[0], 0 while jdf1 != jd1racc: n1 += 1 jdf1 = f1Time[n1] jdf2, n2 = f2Time[0], 0 while jdf2 != jd2racc: n2 += 1 jdf2 = f2Time[n2] f1Fluxcut, fraccFluxcut1 = f1Flux[n1:],fraccFlux[0:l1-n1] meanf1Flux = np.mean(f1Flux) meanf2Flux = np.mean(f2Flux) f1fraccDist = [] d = 0.02 while len(f1fraccDist) < 5 and d <= 1: f1fraccDist = [yracc-y1 for y1,yracc in zip(f1Fluxcut, fraccFluxcut1) if abs(y1-meanf1Flux)<d] d += 0.02 print('d1='+str(d-0.02)) f1Shift = np.mean(f1fraccDist[1:]) print(str(len(f1fraccDist))+' : len f1fraccDist') f2Fluxcut, fraccFluxcut2 = f2Flux[:n2], fraccFlux[l1-n1:] f2fraccDist = [] d = 0.02 while len(f2fraccDist) < 5 and d <= 1: f2fraccDist = [yracc-y2 for y2,yracc in zip(f2Fluxcut, fraccFluxcut2) if abs(y2-meanf2Flux)<d] d += 0.02 print('d2='+str(d-0.02)) f2Shift = np.mean(f2fraccDist[1:]) print(str(len(f2fraccDist))+' : len f2fraccDist') return f1Shift, f2Shift def meanShift(f1, f2, time1, time2): """ Compute mean shift between f1 and f2 """ shifts, m1, m2 = [], np.mean(f1), np.mean(f2) sign, i = 1, 0 if len(f1) > len(f2): # we want len f1 < f2, same for time1 and time2 f1, f2 = f2, f1 time1, time2 = time2, time1 sign = -1 while i < len(f1): t1 = time1[i] deltaTime = [abs(t2-t1) for t2 in time2] i2 = deltaTime.index(min(deltaTime)) if abs(f1[i]-m1) < 0.1 and abs(f2[i2]-m2) < 0.1: shifts.append(f1[i] - f2[i2]) i += 1 return np.mean(shifts) # --- if racc Data used --- def getAstData(refData, field, ID): ''' Get adjusted data from the raccord script refData : id = id number from iraf scripts - (field * 1e5) ''' idAll = refData[:,0] - (field * 1e5) timeAll = refData[:,1] magAll = refData[:,2] errAll = refData[:,3] time = [] mag = [] merr = [] for i in xrange(len(idAll)): if idAll[i] == float(ID): time.append(timeAll[i]) mag.append(magAll[i]) merr.append(errAll[i]) time, mag, merr = np.array(time), np.array(mag), np.array(merr) flux, ferr = pow(10, -mag/2.5), 10*merr return np.array((time, mag, merr, flux, ferr)) def getAstDataRacc(refData, field, ID): ''' Get adjusted data from the raccord script refData : id = id number from iraf scripts - (field * 1e5) ''' idFiltAll = refData[:,0] idAll = refData[:,1] - (field * 1e5) timeAll = refData[:,2] magAll = refData[:,4] errAll = refData[:,5] time = [] mag = [] merr = [] filtId = [] for i in xrange(len(idAll)): if idAll[i] == float(ID): time.append(timeAll[i]) mag.append(magAll[i]) merr.append(errAll[i]) filtId.append(idFiltAll[i]) time, mag, merr, filtId = np.array(time), np.array(mag), \ np.array(merr), np.array(filtId) flux, ferr = pow(10, -mag/2.5), 10*merr return np.array((time, mag, merr, flux, ferr, filtId)) #---- multiple places --------------------------------------------------------- def lightTimeCorrection(fname, time): "Compute light time correction using asteroid topocentric distance" c_au = (299792458. * 24*3600)/149597870700. # speed of light [au/JD] brol1 = np.loadtxt(fname) topoRange = brol1[:,3] #target topocentric range, [au] topoTime = brol1[:,0] # time for topo range # light travel time correction, in JD : lightTimeCorrVal = [d/c_au for d in topoRange] lightTimeCorrFull = [] for t in time: deltaTime = [abs(tt - t) for tt in topoTime] if deltaTime[0] > 1: deltaTime = [abs(x-2450000) for x in deltaTime] minDt = min(deltaTime) if minDt > 0.1: print deltaTime raise ValueError('time diff too big : '+str(minDt) +\ ', t: '+ str(t) + ', file: ' + fname ) index = deltaTime.index(minDt) lightTimeCorrFull.append(lightTimeCorrVal[index]) ltcTime = time - lightTimeCorrFull # corrected time return ltcTime <file_sep>/photCodes/rtPlotPhot.py #--- Functions ---------------------------------------------------------------- def getMeanCmag(data, nCstar, badID): """ Compute for each images the mean magnitude off all the comparison stars, except for those whose ID is in the list badID (variable stars) """ meanCmag = [] for line in data: magLine, index = [], 1 for i in xrange(5 + ap, 5 + ap + 3*nCstar, 3): if index not in badID: magLine.append(line[i]) index += 1 meanCmag.append(np.mean(magLine)) return np.array(meanCmag) def getSumCfluxOLDWAY(data, nCstar, badID): """ Compute for each images the (flux/expTime) sum off all the comparison stars, except for those whose ID is in the list badID (variable stars) """ sumCflux = [] for line in data: fluxLine, index = [], 1 for i in xrange(5 + ap, 5 + ap + 3*nCstar, 3): if index not in badID: fluxLine.append(pow(10, 0.4*(25-line[i]))) index += 1 sumCflux.append(np.sum(fluxLine)) return np.array(sumCflux) def getSumCflux(data, nCstar, badID): """ Compute for each images the flux sum of all the comparison stars, except for those whose ID is in the list badID (variable stars) """ sumCflux = [] for line in data: fluxLine, index = [], 1 i1 = 5 + ap + 6*(nCstar+1) for i in xrange(i1, i1 + 3*nCstar, 3): if index not in badID: fluxLine.append(line[i]) index += 1 sumCflux.append(np.sum(fluxLine)) return np.array(sumCflux) def getSumCfluxArea(data, nCstar, badID): """ Compute for each images the flux sum of all the comparison stars, except for those whose ID is in the list badID (variable stars) """ sumCflux = [] sumCarea = [] for line in data: fluxLine, areaLine, index = [], [], 1 i1 = 5 + ap + 6*(nCstar+1) for i in xrange(i1, i1 + 3*nCstar, 3): if index not in badID: fluxLine.append(line[i]) areaLine.append(line[i + 3*(nCstar+1)]) index += 1 sumCflux.append(np.sum(fluxLine)) sumCarea.append(np.sum(areaLine)) return np.array(sumCflux), np.array(sumCarea) def getMeanCstarMsky(data, nCstar, badID): """ Compute for each images the mean background level for all comp stars """ meanMsky = [] lenLine = len(data[0]) for line in data: mskyLine, index = [], 1 for i in xrange(4 + 12*(nCstar+1), lenLine): if index not in badID: mskyLine.append(line[i]*gain) index += 1 meanMsky.append(np.mean(mskyLine)) return np.array(meanMsky) def compMagAndFluxMean(data, nCstar, badID): """ Compute for each images the mean magnitude/flux sum off all the comparison stars, except for those whose ID is in the list badID (variable stars) """ meanCmag = [] sumCflux = [] for line in data: magLine, fluxLine = [], [] index = 1 for i in xrange(5 + ap, 5 + ap + 3*nCstar, 3): if index not in badID: mag = line[i] magLine.append(mag) fluxLine.append(pow(10, 0.4*(25-mag))) index += 1 meanCmag.append(np.mean(magLine)) sumCflux.append(np.sum(fluxLine)) return np.array(meanCmag), np.array(sumCflux) def seeCstars(data, nCstar, badID): """ Plot raw and diff mag of each comp stars one by one""" for i in xrange(nCstar): cStarRawMag = data[:, 5 + ap + i*3] cStarDiffMag = cStarRawMag - meanCmag plt.plot(corrTime, cStarRawMag - np.mean(cStarRawMag), '.r', label='rawMag') plt.plot(corrTime, cStarDiffMag - np.mean(cStarDiffMag) + 1, '.k', label='diffMag') plt.title(str(i+1)) plt.gca().invert_yaxis() plt.legend() plt.show() def seeTenByTenCstars(): """ Plot raw and diff mag of each comp stars 10 by 10""" for i in xrange(0, nCstar, 10): for j in xrange(10): cStarRawMag = data[:, 5 + ap + (i+j)*3] cStarDiffMag = cStarRawMag - meanCmag plt.plot(corrTime, cStarRawMag - np.mean(cStarRawMag) + j, '.r') plt.plot(corrTime, cStarDiffMag - np.mean(cStarDiffMag) + j + 0.5, '.k') plt.title(str(i)) p*lt.legend() plt.show() def meanDiffCstarAll(): cStarDiffMagSumAll = np.zeros_like(data[:, 5 + ap]) for i in xrange(nCstar): cStarDiffMagSumAll += data[:, 5 + ap + i*3] - meanCmag cStarDiffMagSumAll /= nCstar plt.plot(corrTime, cStarDiffMagSumAll - np.mean(cStarDiffMagSumAll), '.b') tStar = data[:, 5 + ap + 3] - meanCmag #random star in comp star set plt.plot(corrTime, tStar - np.mean(tStar), '.g') plt.plot(corrTime, meanCmag - np.mean(meanCmag), '.r') def meanDiffCstarGood(): cStarDiffMagSum = np.zeros_like(data[:, 5 + ap]) for i in xrange(nCstar): if i+1 not in badID: cStarDiffMagSum += data[:, 5 + ap + i*3] - meanCmag cStarDiffMagSum /= (nCstar-len(badID)) plt.plot(corrTime, cStarDiffMagSum - np.mean(cStarDiffMagSum), '.k') plt.show() <file_sep>/photCodes/checkCompStars.py import numpy as np, rtPhot as rtp, matplotlib.pyplot as plt #--------------------------------------- field = 346 field = 345 field = 348 fieldExt = '_20171214' fieldExt = '_20171215' fieldExt = '_20171213' night = '20171219' night = '20171207' night = '20171202' night = '20171214' night = '20171215' night = '20171213' telescope = 'TS' telescope = 'TN' ap = 2 ap = 3 ap = 18 ap = 13 filt = 13 filt = 15 filt = 12 filt = 14 fileSize = 'big' fileSize = 'small' m = 10000 fname = str(field)+'_'+telescope+'_'+night+'_'+str(ap)+'_'+str(filt)+'.hout1' fname = str(field)+'_'+telescope+'_'+night+'_'+str(ap)+'_'+str(filt)+'.arc' if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder #------------------------------------------------------------------------------ folder += str(field)+fieldExt+'/' print('folder : '+folder) print('fname : '+fname) arcData = np.loadtxt(folder + fname) allID = arcData[:,1] - field*1e5 print(len(allID)) IDs = [] for ID in allID: if ID not in IDs: IDs.append(ID) print(len(IDs)) print(IDs[0] == 1.0) if IDs[0] == 1.0: IDs = IDs[1:] print(len(IDs)) def seeTenByTenCstars(datas, m): ''' Plot raw and diff mag of each comp stars 10 by 10''' n = len(datas) for i in xrange(0, n, m): for j in xrange(m): if i+j < n: data = datas[i+j] mag = data[1] #mag -= (np.mean(mag)-(j+1)) mag -= (np.mean(mag)-(j/20.)) plt.plot(data[0], mag, '.-') plt.title(str(i)) plt.show() def methodSmallFile(m): print('small file method') datas = [rtp.getAstDataRacc(arcData, field, ID)[:2] for ID in IDs] print(len(datas)) seeTenByTenCstars(datas, m) def methodBigFile(m): print('big file method') n = len(IDs) for i in xrange(0, n, m): for j in xrange(m): if i+j >= n: break data = rtp.getAstDataRacc(arcData, field, IDs[i+j])[:2] mag = data[1] - (np.mean(data[1])-(j+1)) plt.plot(data[0], mag, '.-') plt.title(str(i)) plt.show() if fileSize == 'small': methodSmallFile(m) elif fileSize == 'big': methodBigFile(m) <file_sep>/photCodes/sortFilt.py import numpy as np, glob, os, errno from shutil import copyfile """ Sort photometry output files by filter in dedicated folder. """ #--- set things here ---------------------------------------------------------- year = 2017 field = 348 fieldExt = 'raccBVRI_obs1' fieldExt = '_20171213' fieldExt = '_20171214' fieldExt = '_20171215' night = '20171210' night = '20171209' night = '20171213' night = '20171214' night = '20171215' telescope = 'TS' telescope = 'TN' pattern = str(field) + '_' + str(year) + '-' + "*" if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder #----------------------------------------------------------------------------- folder += str(field) + fieldExt + '/' + night filterIDtoName = {'12.0':'B','13.0':'V','14.0':'R','15.0':'I'} filterIDbool = {'12.0':False,'13.0':False,'14.0':False,'15.0':False} fnames = sorted(glob.glob(folder + '/' + pattern)) nIm = len(fnames) if nIm == 0: raise ValueError('No files found ! Check files path: \n' + \ folder + '\n and pattern: \n' + pattern) print(str(field) + ' : field') print(night + ' : night') print(str(nIm) + ' : nIm') def checkFiltFolder(filtFolder): if not os.path.exists(filtFolder): try: os.makedirs(filtFolder) except OSError as e: if e.errno != errno.EEXIST: raise i = 1 for fname in fnames: try: IDs = np.loadtxt(fname)[:,-1] except ValueError: print('INDEF found') filt = filterIDtoName[str(IDs[0])] filtFolder = folder + filt if not filterIDbool[str(IDs[0])]: checkFiltFolder(filtFolder) filterIDbool[str(IDs[0])] = True copyfile(fname,folder+filt+'/'+fname[-23:]) if i%10 == 0: print(str(i) + ' / '+ str(nIm)) i += 1 print('DONE') <file_sep>/photCodes/FluxToMag.py import numpy as np data = np.loadtxt('/media/marin/TRAPPIST3/troppist/pho/348_20171214/348_TN_20171214_13_13.mag') mag = data[:,1] flux = pow(10, -mag/2.5) flux /= np.mean(flux) data[:,1] = flux np.savetxt('/media/marin/TRAPPIST3/troppist/pho/348_20171214/348_TN_20171214_13_13.fluxTest', data, fmt=['%10.6f','%.6e','%.2e','%10.0f']) <file_sep>/photCodes/formatPhot.py import numpy as np, glob, os, sys import matplotlib.pyplot as plt import rtPhot as rtp """ Get together datas generated by the IRAF phot functions in a unique file, and select only the star present on all images """ #--- set things here ---------------------------------------------------------- year = 2017 field = 341 field = 342 field = 340 field = 344 field = 347 field = 350 field = 343 field = 346 field = 345 field = 348 fieldExt = '_20171214/20171214V/V' fieldExt = '_20171213/20171213R/R' fieldExt = '_20171215/20171215B/B' fieldExt = '_20171219/20171219R/R' night = '20170621' night = '20170618' night = '20170628' night = '20170709' night = '20170711' night = '20170603' night = '20170602' night = '20170930' night = '20170921' night = '20170922' night = '20170923' night = '20171108' night = '20171110' night = '20170920' night = '20171118' night = '20171107' night = '20171202' night = '20171127' night = '20170903' night = '20170903I' night = '20171209B' night = 'I45' night = '20171223' night = '20171207' night = '20171218' night = '20171209' night = '20171214B' night = 'R56' night = 'V1' night = str(sys.argv[1]) nightExt = '_20171215' nightExt = '' nightExt = '_20171219' telescope = 'TS' telescope = 'TN' # only for racc file: h.runout1Crop if night == '20170603' and field == 340: lastj = 314610 else : lastj = 0 pattern = str(field) + '_' + str(year) + '-' + "*" if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder #----------------------------------------------------------------------------- folder += str(field) + fieldExt + '/' + night + '/' destFolder = folder outputFname = str(field) + nightExt + '_' + night + '.dat' fnames = sorted(glob.glob(folder + pattern)) nIm = len(fnames) if nIm == 0: raise ValueError('No files found ! Check files path: \n' + folder + '\n and pattern: \n' + pattern) print(str(field) + ' : field') print(night + ' : night') print(str(nIm) + ' : nIm') time = [] airmass = [] listID = [] itime = [] msky = [] aperture1 = [] aperture2 = [] aperture3 = [] errAp1 = [] errAp2 = [] errAp3 = [] flux1 = [] flux2 = [] flux3 = [] area1 = [] area2 = [] area3 = [] # Fill list above with datas from all images for the night badIm = 0 for fname in fnames: #print(fname) try: imData = np.loadtxt(fname) except ValueError: print('INDEF found') listID.append(imData[:,2]) if imData[:,2][0] != 1.0: badIm += 1 print(fname) print(imData[:,2][0]) dfname = fname[0:-24-len(night)] + fname[-23:] os.rename(fname, dfname) airmass.append(imData[0][-2]) time.append(imData[0][-3]) itime.append(imData[:,-4]) msky.append(imData[:,-8]) aperture1.append(imData[:,4]) errAp1.append(imData[:,5]) aperture2.append(imData[:,6]) errAp2.append(imData[:,7]) aperture3.append(imData[:,8]) errAp3.append(imData[:,9]) flux1.append(imData[:,10]) flux2.append(imData[:,11]) flux3.append(imData[:,12]) area1.append(imData[:,13]) area2.append(imData[:,14]) area3.append(imData[:,15]) print('--') print(str(badIm) + ' : badIm') compStarsID = rtp.inAllIm(listID) # list of comp star ID + target ID print(str(len(compStarsID)-1) + ' : len compStarsID') #----- if using racc data ----- """ raccName = 'h.runout1Crop' raccName = '346_TN_20171207_2_14.arc' ''' def refStarsID(refData): time = refData[:,3] print time.shape allID = refData[:,2] t = time[0] IDs = [] j = 0 for i in xrange(690,870): ID = [] while (abs(time[j] - t) < 0.00001): ID.append(allID[j]) j += 1 IDs.append(ID) if 34000030.0 in ID : print 'yess' else : print 'nooo' t = time[j] return IDs ''' def refStarsIDALLold(refData): time = refData[:,1] print(str(time.shape) + ' : time.shape') allID = refData[:,0] - (field*1e5) t = time[lastj] IDs = [] j = lastj for i in xrange(nIm): ID = [] while (j < nbrRefLine) and (abs(time[j] - t) < 0.00001): ID.append(allID[j]) j += 1 IDs.append(ID) if j < nbrRefLine: t = time[j] print(str(j) + ' : j') print(str(len(IDs)) + 'len IDs') return IDs def refStarsIDALL(refData): time = refData[:,2] print(str(time.shape) + ' : time.shape') allID = refData[:,1] - (field*1e5) print allID[0], 'allid0' t = time[lastj] IDs = [] j = lastj for i in xrange(nIm): ID = [] while (j < nbrRefLine) and (abs(time[j] - t) < 0.00001): ID.append(allID[j]) j += 1 IDs.append(ID) if j < nbrRefLine: t = time[j] print(str(j) + ' : j') print(str(len(IDs)) + 'len IDs') return IDs ''' refStarsData = np.loadtxt(folder[:-9]+'h.out1cro') print refStarsData.shape tmpRefIDlist = refStarsID(refStarsData) ''' #refStarsData = np.loadtxt(folder[:-9]+'raccName) refStarsData = np.loadtxt(folder+raccName) nbrRefLine = refStarsData.shape[0] tmpRefIDlist = refStarsIDALL(refStarsData) refStarsID = rtp.inAllIm(tmpRefIDlist) print('----------------------------------------------------------') print(refStarsID) print('----------------------------------------------------------') print(compStarsID) print('----------------------------------------------------------') refAndCompStarsID = rtp.inAllIm([refStarsID,compStarsID]) #print(refAndCompStarsID) print(str(len(refAndCompStarsID)) + ' : len of ref and compStarsID') compStarsID = [1] + refAndCompStarsID # only IDs ok for racc and phot are kept print compStarsID """ # ----------------------------- nStars = len(compStarsID) print(str(nStars-1) + ' : number of stars present on all images') print('--') #----- get phot data ---------------------------------------------------------- # create an array of nIm lines, with on each lines : # time, airmass, expTime, mag, merr, flux, area, msky # for aperture 1,2,3 and for the target and then all comparison stars newData = np.empty((nIm, 3 + 12*nStars + nStars)) print(str(newData.shape) + ' : newData shape') for i in xrange(nIm): newData[i][0], newData[i][1] = time[i], airmass[i] newData[i][2] = itime[i][0] IDs = listID[i] index = 0 for j in xrange(len(IDs)): # for each line (each stars detected in image) if IDs[j] in compStarsID: newData[i][3+3*index] = aperture1[i][j] newData[i][4+3*index] = aperture2[i][j] newData[i][5+3*index] = aperture3[i][j] newData[i][3+3*(index+nStars)] = errAp1[i][j] newData[i][4+3*(index+nStars)] = errAp2[i][j] newData[i][5+3*(index+nStars)] = errAp3[i][j] newData[i][3+3*(index+(2*nStars))] = flux1[i][j] newData[i][4+3*(index+(2*nStars))] = flux2[i][j] newData[i][5+3*(index+(2*nStars))] = flux3[i][j] newData[i][3+3*(index+(3*nStars))] = area1[i][j] newData[i][4+3*(index+(3*nStars))] = area2[i][j] newData[i][5+3*(index+(3*nStars))] = area3[i][j] newData[i][3+index+12*nStars] = msky[i][j] index += 1 #--- saving on file ----------------------------------------------------------- print('*** Output file has been saved on folder : ' + destFolder) print('*** With name: ' + outputFname) np.savetxt(destFolder + outputFname, newData) <file_sep>/photCodes/concatPhot.py import numpy as np, matplotlib.pyplot as plt, rtPhot as rtp #--------------------------------------- ap = 3 ap = 2 ap = 1 field = 342 field = 341 field = 340 field = 344 field = 347 field = 343 field = 346 field = 345 field = 348 fieldExt = '_20171214/20171214V/V' fieldExt = '_20171214/20171214R/R' fieldExt = '_20171213/20171213R/R' fieldExt = '_20171215/20171215B/B' fieldExt = '_20171219/20171219R/R' obs = 'obs1And2' obs = 'obs1V' obs = 'obs2B' obs = 'obs2V' obs = 'obs2R' obs = 'obs2I' obs = 'obs2' obs = 'obs3' obs = '20171214V' obs = '20171214R' obs = '20171215B' obs = '20171219R' telescope = 'TS' telescope = 'TN' fileOut = False fileOut = True if field == 340: # 596 Scheila nights = ['20170602', '20170603'] Prot = 15.844 elif field == 342: # 476 Hedwig nights = ['20170618', '20170628', '20170709', '20170711'] Prot = 27.33 elif field == 343: # 476 Hedwig nights = ['1','2','2bis','3','4','5','6','7'] nights = ['1','2','3','4'] nights = ['20170903I'] Prot = 2.358 elif field == 345: # 89 Julia Prot = 11.387 if telescope == 'TS' and obs == 'obs1': nights = ['20170920', '20170921', '20170922', '20170930'] elif telescope == 'TN' and obs == 'obs1': nights = ['20171127', '20171202'] elif telescope == 'TN' and obs == 'obs2': nights = ['20171223'] elif telescope == 'TN' and obs == 'obs3': nights = ['20171207','20171223'] elif field == 346: # 31 Euprhosine if telescope == 'TN' and obs == 'obs1': nights = ['20171107'] elif telescope == 'TN' and obs == 'obs2': nights = ['20171127','20171202'] elif telescope == 'TN' and obs == 'obs1And2': nights = ['20171107','20171127','20171202'] if telescope == 'TN' and obs == 'obs3': nights = ['20171207'] Prot = 5.53 elif field == 344: # 24 Themis if telescope == 'TS' and obs == 'obs1': nights = ['20170920', '20170921', '20170922', '20170923'] # TS elif telescope == 'TS' and obs == 'obs2': nights = ['20171107', '20171108'] elif telescope == 'TN' and obs == 'obs1': nights = ['20171108'] Prot = 8.374 elif field == 347: # 20 Massalia if telescope == 'TS' and obs == 'obs1': nights = ['20171110'] elif telescope == 'TS' and obs == 'obs2': nights = ['20171118'] elif telescope == 'TN' and obs == 'obs1': nights = ['20171110'] elif telescope == 'TN' and obs == 'obs2': nights = ['20171118'] Prot = 8.098 elif field == 348: # 3200 phaethon if telescope == 'TN' and obs == 'obs2B': nights = ['B1','B2','B3','B4','B5','B6'] nightsRacc = ['B12','B23','B34','B45','B56'] elif telescope == 'TN' and obs == 'obs2R': nights = ['R1','R2','R3','R4','R5'] nightsRacc = ['R12','R23','R34','R45'] elif telescope == 'TN' and obs == 'obs2V': nights = ['V1','V2','V3','V4','V5'] nightsRacc = ['V12','V23','V34','V45'] elif telescope == 'TN' and obs == 'obs2I': nights = ['I1','I2','I3','I4','I5'] nightsRacc = ['I12','I23','I34','I45'] elif telescope == 'TN' and obs == '20171213R': nights = ['R1','R2','R3','R4','R5','R6','R7','R8','R9','R10','R11','R12','R13','R14'] nightsRacc = ['RR12','RR23','RR34','RR45','RR56','RR67','RR78','RR89','RR910','RR1011','RR1112','RR1213','RR1314'] elif telescope == 'TN' and obs == '20171214R': nights = ['R1','R2','R3','R4','R5','R6'] nightsRacc = ['R12','R23','R34','R45','R56'] elif telescope == 'TN' and obs == '20171214V': nights = ['V1','V2','V3','V4','V5','V6','V7','V8'] nightsRacc = ['V12','V23','V34','V45','V56','V67','V78'] elif telescope == 'TN' and obs == '20171215I': nights = ['I1','I2','I3','I4','I5','I6','I7'] nightsRacc = ['II12','II23','II34','II45','II56','II67'] elif telescope == 'TN' and obs == '20171215B': nights = ['B1','B2','B3','B4','B5','B6','B7'] nightsRacc = ['BB12','BB23','BB34','BB45','BB56','BB67'] elif telescope == 'TN' and obs == '20171219R': nights = ['R1','R2','R3','R4','R5'] nightsRacc = ['RR12','RR23','RR34','RR45'] Prot = 3.603957 yAxisLim = (0.90, 1.10) yAxisLim = (0.5, 1.5) ylim = True ylim = False stdID = 1752 # 342 ? stdID = 165 # 344 TS obs1 binData = True binData = False binW = 2 # bin width in minutes matching = False matching = True Correction = True Correction = False if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder #------------------------------------------------------------------------------ folder += str(field) + fieldExt plt.style.use('bmh') getDataRes = rtp.getData(nights, folder, field, ap) data, datas = getDataRes[0], getDataRes[1] print(data.shape) lList = [datai.shape[0] for datai in datas] # list of night's len print(lList) ######### CORR ################## if Correction: print('CORRECTION') #data[:,4][18:420] -= 0.02 #data[:,4][:605] += 0.039 #data[:,4][320:] -= 0.04 #data[:,4][384:] -= 0.04 ################################# time = data[:, 0] airmass = data[:, 1] astDiffMag = data[:, 2] astMagErr = data[:, 3] astDiffFlux = data[:, 4] astFluxErr = data[:, 5] nIm = len(data) astDiffFlux /= np.mean(astDiffFlux) #astDiffFlux -= np.mean(astDiffFlux) #----- field matching --------------------------------------------------------- if matching: getDataResRacc = rtp.getData(nightsRacc, folder, field, ap) datasRacc = getDataResRacc[1] lListRacc = [datai.shape[0] for datai in datasRacc] # list of night's len print(lListRacc, 'lList datasRacc') l0 = 0 for i in range(len(nights)-1): print('---'+str(i+1)) f1Shift, f2Shift = rtp.bridgeMatching(datas[i],datas[i+1],datasRacc[i]) l1, l2 = len(datas[i]), len(datas[i+1]) print('---'+str(f1Shift)+' '+str(f2Shift)) astDiffFlux[l0+l1:l0+l1+l2] += (-f1Shift + f2Shift) datas[i+1][:,4] += (-f1Shift + f2Shift) datasRacc[i][:,4] += -f1Shift l0 += l1 astDiffFlux /= np.mean(astDiffFlux) #----Phase computation -------------------------------------------------------- t0 = time[0] Porb_JD = Prot/24. print(Porb_JD, 'PorbJD') phase = [((t - t0)/Porb_JD) % 1. for t in time] oldPhase = phase oldlList = lList #------ Data Binning ---------------------------------------------------------- print(lList, 'lList') if binData: oldAstFluxErr = astFluxErr airmass = rtp.binning(airmass, time, binW, lList)[0] astDiffMag = rtp.binning(astDiffMag, time, binW, lList)[0] astMagErr = rtp.binning(astMagErr, time, binW, lList)[0] astDiffFlux = rtp.binning(astDiffFlux, time, binW, lList)[0] astFluxErr = rtp.binning(astFluxErr, time, binW, lList)[0] phase = rtp.binning(phase, time, binW, lList)[0] resBin = rtp.binWeighted(time, time, oldAstFluxErr, binW, lList) time, lList = resBin[0], resBin[1] #----- get data from racc script ---------------------------------------------- """ refStarsData = np.loadtxt(folder + '/h.runout1Crop') astData = rtp.getAstData(refStarsData, field, 1) ''' ratioCorr = 0.953844443843 i1, i2 = lList[-1], lList[-2] astData[3][-i1:] /= np.mean(astData[3][-i1:]) astData[3][-i1:] *= (np.mean(astData[3][-i1-i2:-i1]) * ratioCorr) #astData[3][-i1:] *= (np.mean(astData[3][-i1-i2:-i1]) * ratioCorr) ''' ''' n12 = np.loadtxt(folder + '/h.runout1Crop12') n23 = np.loadtxt(folder + '/h.runout1Crop23') n34 = np.loadtxt(folder + '/h.runout1Crop34') ast12 = rtp.getAstData(refStarsData, field, 1) ast23 = rtp.getAstData(refStarsData, field, 1) ast12 = rtp.getAstData(refStarsData, field, 1) ''' refAstMag = astData[1] refAstFlux = astData[3] # choose flux or mag: astPhot = refAstFlux astPhot = refAstMag print(len(astPhot)) astPhot /= np.mean(astPhot) plt.plot(astData[0], astPhot, '.') plt.show() t0T = astData[0][0] phaseT = [((t - t0T)/Porb_JD) % 1. for t in astData[0]] plt.plot(phaseT, astPhot, '.') plt.xlim((0,1)) plt.show() n1 = astPhot[:619] ############### n2 = astPhot[619:] ############### mn1, mn2 = np.mean(n1), np.mean(n2) print(mn1, mn2, mn2 / mn1) astData[3] /= np.mean(astPhot[:lList[0]])# normalization to first night mean #----- plot std star LC, phase curve of phot and racc data -------------------- # std star check stdStarData = rtp.getAstData(refStarsData, field, stdID) stdStarFlux = stdStarData[3] if len(stdStarFlux) ==0: print('Not a valid std ID - std ID not found') else : stdStarFlux /= np.mean(stdStarFlux) stdStarTime = stdStarData[0] print(len(stdStarFlux), 'len std flux') plt.plot(stdStarTime, stdStarFlux, '.', label='stdStarFlux') plt.ylim((0.95,1.05)) plt.legend() plt.show() # Plot flux or mag vs rotational phase RACC l0 = 0 for i in range(len(nights)): li = oldlList[i] plt.plot(oldPhase[l0:li+l0], astPhot[l0:li+l0], '.', label=nights[i]) l0 += li plt.xlabel('Rotational Phase') plt.ylabel('Differential Flux') plt.title('phase LC of adjusted data RACC') plt.legend() plt.xlim((0,1)) if ylim: plt.ylim(yAxisLim) plt.show() # Plot flux or mag vs rotational phase PHOT l0 = 0 for i in range(len(nights)): li = lList[i] #plt.plot(phase[l0:li+l0], astDiffMag[l0:li+l0], '.', label=nights[i]) # mag plt.plot(phase[l0:li+l0], astDiffFlux[l0:li+l0], '.', label=nights[i]) # flux l0 += li #plt.gca().invert_yaxis() # invert mag axis plt.xlabel('Rotational Phase') #plt.ylabel('$\Delta$ Rmag') plt.ylabel('Differential Flux') plt.title('phase LC of non adjusted data PHOT') plt.legend() plt.xlim((0,1)) if ylim: plt.ylim(yAxisLim) plt.show() # ----- Night shifting -------------------------------------------------------- nightsRacc = [] nightsPhot = [] l0 = 0 oldl0 = 0 for i in range(len(nights)): li = lList[i] oldli = oldlList[i] nightsRacc.append(astPhot[oldl0:oldl0+oldli]) nightsPhot.append(astDiffFlux[l0:l0+li]) l0 += li oldl0 += oldli meanNightsRacc = [np.mean(night) for night in nightsRacc] meanNightsPhot = [np.mean(night) for night in nightsPhot] ratiosRacc = [mnR / meanNightsRacc[0] for mnR in meanNightsRacc] print(ratiosRacc, 'ratiosRacc') colors = ['C0.','C1.','C2.','C3.','C4.','C5.','C6.','C7.'] l0 = 0 for i in range(len(nights)): li = oldlList[i] u = np.arange(l0,l0+li) plt.plot(u, nightsRacc[i], colors[i], label=nights[i]) plt.plot(u, [meanNightsRacc[i] for e in u], colors[i]+'-') l0 += li plt.title('racc') plt.legend() if ylim: plt.ylim(yAxisLim) plt.show() l0 = 0 for i in range(len(nights)): li = lList[i] u = np.arange(l0,l0+li) plt.plot(u, nightsPhot[i], colors[i], label=nights[i]) plt.plot(u, [meanNightsPhot[i] for e in u], colors[i]+'-') l0 += li plt.title('before shift') plt.legend() if ylim: plt.ylim(yAxisLim) plt.show() # shift all night except first one l0 = lList[0] for i in range(len(nights)-1): li = lList[i+1] data[:,4][l0:l0+li] *= ratiosRacc[i+1] l0 += li # update of phot nights mean and nightsPhot l0 = 0 meanNightsPhot = [] for i in range(len(nights)): li = lList[i] meanNightsPhot.append(np.mean(data[:,4][l0:l0+li])) nightsPhot.append(astDiffFlux[l0:l0+li]) l0 += li l0 = 0 for i in range(len(nights)): li = lList[i] u = np.arange(l0,l0+li) plt.plot(u, nightsPhot[i], colors[i], label=nights[i]) plt.plot(u, [meanNightsPhot[i] for e in u], colors[i]+'-') l0 += li plt.title('after shift') plt.legend() if ylim: plt.ylim(yAxisLim) plt.show() ratiosPhot = [mnP / meanNightsPhot[0] for mnP in meanNightsPhot] print(ratiosPhot, 'ratiosPhot') # renormalization of the whole curve to 1 data[:,4] /= np.mean(data[:,4]) """ #----- saving on file: --------------------------------------------------- if fileOut and binData: print('Warning : data are binned, files not saved !') fnameOut = '/' + str(field) + '_diff_ap' + str(ap) +'_' +telescope+obs + '.dat' if fileOut and not binData: print('* Full output file has been saved on folder : ' + folder) print('With name: ' + fnameOut[1:-4]+'_full.dat') #np.savetxt(folder + fnameOut, data) np.savetxt(folder + fnameOut[:-4]+'_full.dat', data, fmt=['%10.6f','%10.4f','%.6e','%.2e','%.6e','%.2e']) print('* Output file has been saved on folder : ' + folder) print('With name: ' + fnameOut[1:]) dataFlux = np.dstack((data[:,0],data[:,4],data[:,5]))[0] np.savetxt(folder + fnameOut, dataFlux, fmt=['%10.6f','%.6e','%.2e']) # raw file: fnameRaw = '/' + str(field) + '_raw_ap' + str(ap) + '_'+telescope+ obs + '.dat' dataRaw = rtp.getRawData(nights, folder, field, ap) if fileOut and not binData: print('* Raw file has been saved on folder : ' + folder) print('With name: ' + fnameRaw[1:]) np.savetxt(folder + fnameRaw, dataRaw) #----- Graphs --------------------------------------------------------------- # Plot flux or mag in a sequential way l0 = 0 for i in range(len(nights)): li = lList[i] plt.plot(np.arange(li)+l0, astDiffFlux[l0:li+l0], '.', label=nights[i]) l0 += li plt.xlabel('n') plt.ylabel('Differential Flux') plt.title('Sequential LC') plt.legend() plt.show() # Plot flux error in a sequential way l0 = 0 for i in range(len(nights)): li = lList[i] plt.plot(np.arange(li)+l0, astFluxErr[l0:li+l0], '.', label=nights[i]) l0 += li plt.xlabel('n') plt.ylabel('error') plt.title('Error on flux') plt.legend() plt.show() # Plot flux or mag vs time in JD l0 = 0 for i in range(len(nights)): li = lList[i] plt.plot(time[l0:li+l0], astDiffFlux[l0:li+l0], '.', label=nights[i]) l0 += li if matching: for i in range(len(nightsRacc)): plt.plot(datasRacc[i][:,0], datasRacc[i][:,4], 'k,', label=nightsRacc[i]) plt.xlabel('JD time') plt.ylabel('Differential Flux') plt.title('JD time LC') plt.legend() plt.show() # Plot flux or mag vs rotational phase l0 = 0 for i in range(len(nights)): li = lList[i] #plt.plot(phase[l0:li+l0], astDiffMag[l0:li+l0], '.', label=nights[i]) # mag plt.plot(phase[l0:li+l0], astDiffFlux[l0:li+l0], '.', label=nights[i]) # flux l0 += li #plt.gca().invert_yaxis() # invert mag axis plt.xlabel('Rotational Phase') #plt.ylabel('$\Delta$ Rmag') plt.ylabel('Differential Flux') plt.title('phase LC of shifted data') plt.legend() plt.xlim((0,1)) if ylim: plt.ylim(yAxisLim) plt.show() <file_sep>/photCodes/ltc.py import numpy as np, matplotlib.pyplot as plt, rtPhot as rtp """ Compute and apply light time correction to individual files """ ap = 3 ap = 2 ap = 1 fileOut = False fileOut = True telescope = 'TS' field = 343 night = '20170903' distFname = 'brol1_' + str(field) distFname = 'brol1_' + str(field) + '_' + night if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" #clean win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder folder += str(field) +'/' fname = 'AIJ/03122AIJ.txtcorr' data = np.loadtxt(folder + fname) time = data[:,0] astDiffFlux = data[:,1] astFluxErr = data[:,2] #astDiffFlux /= np.mean(astDiffFlux) #----- Light travel time correction --------------------------------------- c_au = (299792458. * 24*3600)/149597870700. # speed of light [au/JD] if len(distFname) == 18: distFolder = folder else: distFolder = folder[:-2] distFolder = '/media/marin/TRAPPIST3/trappist/pho/343/' + night +'/' brol1 = np.loadtxt(distFolder + distFname) topoRange = brol1[:,3] #target topocentric range, [au] topoTime = brol1[:,0] # time for topo range # light travel time correction, in JD : lightTimeCorrVal = [d/c_au for d in topoRange] lightTimeCorrFull = [] for t in time: deltaTime = [abs(tt - t) for tt in topoTime] minDt = min(deltaTime) if minDt > 1 and abs(minDt-2450000) > 1: raise ValueError('time diff too big : '+str(minDt)) index = deltaTime.index(minDt) lightTimeCorrFull.append(lightTimeCorrVal[index]) corrTime = time - lightTimeCorrFull # corrected time print(time[0],corrTime[0]) u = np.arange(len(time)) plt.plot(u, time, '.', label='time') plt.plot(u, corrTime, '.', label='corrTime') plt.legend() plt.show() #---- saving on file --------------------------------------------------------- if fileOut: print('* File has been saved on folder : ' + folder) print('With name: ' + fname) data = np.dstack((corrTime, astDiffFlux, astFluxErr))[0] np.savetxt(folder + fname, data, fmt=['%10.6f','%.6e','%.2e']) <file_sep>/photCodes/fieldMakin.py import numpy as np, glob, os, errno from shutil import copyfile #--- set things here ---------------------------------------------------------- year = 2017 field = 348 field = '348_20171214' field = '348_20171213' field = '348_20171215' field = '348_20171219' night = '20171214B' night = 'R56' night = '20171214V' night = '20171213R' night = '20171215B' night = '20171219R' filt = 'V' filt = 'I' filt = 'B' filt = 'R' telescope = 'TS' telescope = 'TN' nbrImField = 62 nbrImField = 60 pattern = str(field[:3]) + '_' + str(year) + '-' + "*" if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder #----------------------------------------------------------------------------- folder += str(field) + '/' + night + '/' destFolder = folder fnames = sorted(glob.glob(folder + pattern)) nIm = len(fnames) if nIm == 0: raise ValueError('No files found ! Check files path: \n' + folder + '\n and pattern: \n' + pattern) print(str(field) + ' : field') print(night + ' : night') print(str(nIm) + ' : nIm') r = nIm % nbrImField if r != 0: nbrFolder = int(nIm/nbrImField) + 1 else: nbrFolder = int(nIm/nbrImField) print(str(nbrFolder) + ' : nbrFolder') def createFolder(nFolder): if not os.path.exists(nFolder): try: os.makedirs(nFolder) except OSError as e: if e.errno != errno.EEXIST: raise createFolder(folder+filt) i = 1 n = 0 oldFolderRacc = '' newFolderRacc = '' halfNIF = int(nbrImField / 2) print r, nIm-(r/2) for fname in fnames: if n % nbrImField == 0: newFolder = folder+filt+'/'+filt+str(i) createFolder(newFolder) if i < nbrFolder: oldFolderRacc = newFolderRacc newFolderRacc = folder+filt+'/'+filt+filt+str(i)+str(i+1) createFolder(newFolderRacc) print(i) i += 1 copyfile(fname,newFolder+'/'+fname[-23:]) if n > halfNIF and n < nIm-(r/2) and n % nbrImField > halfNIF: copyfile(fname,newFolderRacc+'/'+fname[-23:]) elif n > halfNIF and n < nIm-(r/2) and n % nbrImField < halfNIF: if i == nbrFolder + 1: oldFolderRacc = newFolderRacc copyfile(fname,oldFolderRacc+'/'+fname[-23:]) n += 1 <file_sep>/README.md # photCodes code to analyse photometry data of asteroids <file_sep>/photCodes/photForRacc.py import numpy as np, glob, os.path as op #--------------------------------------- year = 2017 field = 341 field = 342 field = 340 field = 344 field = 347 field = 343 field = 346 field = 345 field = 348 folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder #--------------------------------------- pattern = '/' + str(field) + '_' + str(year) + '-' + "*" folder += str(field) destFolder = folder + 'racc/' print(folder) print(destFolder) if not op.isdir(destFolder): raise ValueError('/'+str(field)+'racc' + ' folder does not exist') formatData = ['%10.3f','%10.3f','%10.0f','%10.0f','%10.3f','%10.3f','%10.3f', '%10.3f','%10.3f','%10.3f','%10.10f','%10.6f','%10.0f'] fnames = sorted(glob.glob(folder + pattern)) nIm = len(fnames) if nIm == 0: raise ValueError('No files found ! Check files path: \n' + \ folder + '\n and pattern: \n' + pattern) i = 1 for fname in fnames: data = np.loadtxt(fname) data = np.hstack((data[:,0:10], data[:,-3:])) np.savetxt(destFolder + fname[len(fname)-23:], data, fmt=formatData ) if i%10 == 0: print(str(i) + ' / '+ str(nIm)) i += 1 print('DONE') <file_sep>/photCodes/raccFormat.py import numpy as np, rtPhot as rtp #--------------------------------------- field = 346 field = 345 field = 348 fieldExt = 'n2' fieldExt = 'n4' fieldExt = 'n1' fieldExt = '_20171219' fieldExt = '' fieldExt = '_20171214' fieldExt = '_20171215' fieldExt = '_20171213' fieldExt = '_20171218' telescope = 'TS' telescope = 'TN' night = '20171219' night = '20171207' night = '20171202' night = '20171214' night = '20171215' night = '20171213' night = '20171218' ap = 2 ap = 3 ap = 18 ap = 13 filt = 13 filt = 15 filt = 12 filt = 14 #-------------------------------- #fname = 'h.runout1Crop' #fname = str(field)+'_'+'racc_ap'+str(ap)+'_'+telescope+obs+'_'+night+'.arc' fname = str(field)+'_'+telescope+'_'+night+'_'+str(ap)+'_'+str(filt)+'.arc' #fnameOut = str(field)+'_'+'racc_ap'+str(ap)+'_'+telescope+obs+'_'+night fnameOut = str(field)+'_'+telescope+'_'+night+'_'+str(ap)+'_'+str(filt) idObject = 1 fileOut = True if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder if telescope == 'TN': folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder #------------------------------------------------------------------------------ folder += str(field)+fieldExt+'/' distFname = folder + '/' + night + '/' + 'brol1_' + str(field) + '_' + night distFname = folder + '/' + 'brol1_' + str(field) + '_' + night print('folder : '+folder) print('fname : '+fname) refStarsData = np.loadtxt(folder + fname) # get time, mag, magerr, flux, fluxerr, filtID of the object astData = rtp.getAstDataRacc(refStarsData, field, idObject) astData[0] += 2450000 astData[0] = rtp.lightTimeCorrection(distFname,astData[0]) # time is LTC #astDataMag = np.dstack((astData[0],astData[1],astData[2]))[0] #astDataFlux = np.dstack((astData[0],astData[3],astData[4]))[0] #astData = np.dstack((astData[0],astData[1],astData[2],astData[3],astData[4]))[0] astDataMag = np.dstack((astData[0],astData[1],astData[2],astData[5]))[0] astData[3] /= np.mean(astData[3]) astDataFlux = np.dstack((astData[0],astData[3],astData[4],astData[5]))[0] print astData.shape if fileOut: np.savetxt(folder + fnameOut+'.mag', astDataMag, fmt=['%10.6f','%.6e','%.2e','%10.0f']) print('With name: ' + fnameOut+'.mag') print('*** MAG file has been saved on folder : ' + folder) np.savetxt(folder + fnameOut+'.flux', astDataFlux, fmt=['%10.6f','%.6e','%.2e','%10.0f']) print('*** FLUX file has been saved on folder : ' + folder) print('With name: ' + fnameOut+'.flux') <file_sep>/photCodes/plotPhot.py import numpy as np, matplotlib.pyplot as plt, rtPhot as rtp, sys """ Do differential photometry. Input files have time, airmass, raw mag, raw flux. Light time corrected time, differential flux and or mag and errors are computed. """ #--- set things here ---------------------------------------------------------- #choice of aperture = 1, 2 or 3 ap = 2 ap = 3 ap = 1 fileOut = False fileOut = True showCstars = True showCstars = False showCstars10 = True showCstars10 = False graph = True graph = False field = 341 field = 340 field = 342 field = 344 field = 343 field = 347 field = 346 field = 345 field = 348 fieldExt = '_20171214' fieldExt = '_20171214/20171214V/V' fieldExt = '_20171213/20171213R/R' fieldExt = '_20171215/20171215B/B' fieldExt = '_20171219/20171219R/R' telescope = 'TS' telescope = 'TN' night = '20171127' night = '20171118' night = '20170903R' night = '4' night = '20171223' night = '20171207' night = '20171202' night = 'R56' night = str(sys.argv[1]) nightExt = '_20171213' nightExt = '_20171215' nightExt = '_20171219' #------------------------ # to do : files with those bad ID # ID of stars that are variable: if night == '20170709' and field == 342: badID = [249,309,310,321,331,363,369,456,639,1141] # 00476 elif night == '20170711' and field == 342: badID = [441,475,590,717,1138,1148,1171,1374,1428,1462,1589,1629,1710, 1729,1799] # 00476 elif night == '20170618' and field == 342: badID = [42,44,149,170,174,177,230,252,461,534,543,666,611,656,705,735, 745,757,777,830,840,913,945,981,992,1008,1011,1013,1020,1123, 1145,1197,1200,1336,1361,1383] # 00476 elif night == '20170628' and field == 342: badID = [577,793] # 00476 elif night == '20170602' and field == 340: badID = [3,34,35] # 00596 elif night == '20170603' and field == 340: badID = [4,6,26,52,55,56,59,84,91,92,99,111,128,133,141,150] # 00596 elif night == '20170920' and field == 344: badID = [47,68] elif night == '20170921' and field == 345: badID = [23,24,26,48] elif night == '20170930' and field == 345: badID = [12,15,17] elif night == '20170922' and field == 344: badID = [48,53,61,66] elif night == '20170923' and field == 344: badID = [1,5,34,39,45,47,73] elif night == '20171107' and field == 344: badID = [12] elif night == '20171127' and field == 346: badID = [12,40,66,83,91,96] elif night == '20171207' and field == 346: badID = np.arange(40) badID = [] elif night == '20171110' and field == 347: if telescope == 'TS': badID = [137,380] badID = [94,101,232,282,355,373] badID =[94,230,280,318] else: badID = [] elif night == '20171118' and field == 347: if telescope == 'TS': badID = [28,83,150,190,193,267,342,353,425] elif telescope == 'TN': badID = [11,13] else: badID = [] else: badID = [] #badID = np.concatenate((np.arange(4,8),np.arange(14,18),np.arange(31,39))) #badID = np.concatenate((np.arange(4,9) ,np.arange(13,31))) #badID = np.arange(13,18) print badID print('No badID. Check field, telescope and night?') #------------------------ distFname = 'brol1_' + str(field) + '_' + night distFname = 'brol1_' + str(field) #**** telescope characteristics *** D = 60 # telescope diameter in cm if telescope == 'TS': folder = "E:/trappist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/trappist/pho/" # TS folder h = 2315 # altitude in m RON = 12. # ReadOutNoise in el343 gain = 1.1 # Gain in electron per ADU elif telescope == 'TN': ### to change !!! ### folder = "E:/troppist/pho/" # win TS folder folder = "/media/marin/TRAPPIST3/troppist/pho/" # TN folder h = 2751 RON = 12 gain = 1.1 #----------------------------------------------------------------------------- # load data from folder+fname as an array. Contain a line for each images with: # otime, airmass, itime, m1, m2, m3, merr1, merr2, merr3, f1, f2, f3, # area1, area2, area3, msky # for target and each comp stars folder += str(field) + fieldExt + '/' + night +'/' fname = str(field) + fieldExt + '_' + night + '.dat' fname = str(field) + nightExt + '_' + night + '.dat' # load data from folder + fname as as array. Contain in each lines: time, # airmass and mag for target and all comparison stars on the image data = np.loadtxt(folder + fname) nCstar = (len(data[0])-6) / 13 # number of comparison stars print(len(data[0])-6, (len(data[0])-6) / 13., nCstar, 'test nCstar') time = data[:, 0] airmass = data[:, 1] itime = data[:, 2] astMsky = data[:, 3 + 12*(nCstar+1)] * gain astArea = data[:, 2 + ap + 9*(nCstar+1)] # target raw mag: astRawMag = data[:, 2 + ap] astMagErr = data[:, 2 + ap + 3*(nCstar+1)] # target raw flux: astRawFlux = data[:, 2 + ap + 6*(nCstar+1)] #----- Error computation of each measurements ----------------------------- scintillation = [0.09 * D**(-2/3.) * x**(1.75) * (2*it)**(-1/2.) * np.exp(-h/8000.) for x, it in zip(airmass, itime)] astNoise = [Ft + (Ft * sc)**2 + npix * (bg+RON**2) for Ft,sc,npix,bg in zip(astRawFlux, scintillation, astArea, astMsky)] cStarsSumFluxArea = rtp.getSumCfluxArea(data, ap, nCstar, badID) cStarsSumFlux = cStarsSumFluxArea[0] # sum of comp star flux cStarsSumArea = cStarsSumFluxArea[1] # sum of comp star areas # mean of all comp star background : cStarsMsky = rtp.getMeanCstarMsky(data, nCstar, badID, gain) cStarsNoise = [Fc + (Fc * sc)**2 + ncNpix * (bg+RON**2) for Fc,sc,ncNpix,bg in zip(cStarsSumFlux, scintillation, cStarsSumArea, cStarsMsky)] astFluxErr = [np.sqrt((Nt/(Ft**2)) + (Nc/(Fc**2))) for Nt,Ft,Nc,Fc in zip(astNoise, astRawFlux, cStarsNoise, cStarsSumFlux)] print("%.4f" % np.mean(astFluxErr), ' : mean flux error') nIm = len(data) print('nbr of images = ' + str(nIm)) print('nbr of comp stars = ', nCstar, ', nbr of bad stars = ', len(badID)) #----- Light travel time correction --------------------------------------- if len(distFname) == 10+len(night): distFolder = folder print distFolder else: distFolder = folder[:-len(night)-1] corrTime = rtp.lightTimeCorrection(distFolder+distFname, time) ''' u = np.arange(len(time)) plt.plot(u, time, '.', label='time') plt.plot(u, corrTime, '.', label='corrTime') plt.legend() plt.show() ''' #------ differential mag and fluxes ------------------------------------------- #----- mag ----- # mean of all comp star mag for each images: zeroMag = 15 meanCmag = rtp.getMeanCmag(data, ap, nCstar, badID) astDiffMag = astRawMag - meanCmag # differential mag of target #offset = zeroMag - np.mean(meanCmag) #astDiffMag -= offset #astDiffMag -= np.mean(astDiffMag) #----- flux ----- astDiffFlux = [float(Ft) / Fc for Ft, Fc in zip(astRawFlux, cStarsSumFlux)] astDiffFlux /= np.mean(astDiffFlux) # normalization to 1 """ zeroMag = 25 zeroMagOffset = 15 zeroFlux = pow(10, -0.4*(zeroMag-25)) meancStarsSumFlux = cStarsSumFlux / nCstar astDiffFlux = astRawFlux / meancStarsSumFlux astDiffMag = -2.5 * np.log10(astDiffFlux) + zeroMag meanCstarsMags = -2.5 * np.log10(np.mean(meancStarsSumFlux)) + zeroMag offset = zeroMagOffset - meanCstarsMags astDiffMag += offset astDiffFlux = pow(10, -0.4*(astDiffMag-zeroMag)) """ #astDiffFlux = astDiffMag #print offset, np.mean(astDiffMag) """ astDiffFlux = np.asarray(astDiffFlux) astDiffFlux /= float(nCstar) cStarMeanFluxes = cStarsSumFlux / nCstar cStarMeanFluxAll = np.mean(cStarMeanFluxes) print cStarMeanFluxAll f0 = 50000.0 fluxCoeff = f0 / cStarMeanFluxAll print fluxCoeff astDiffFlux *= fluxCoeff """ """ print cStarMeanFluxAll * nCstar astDiffFlux = np.asarray(astDiffFlux) astDiffFlux *= nCstar """ """ astDiffFlux = np.asarray(astDiffFlux) cStarMeanSumFlux = np.mean(cStarsSumFlux) astDiffFlux *= cStarMeanSumFlux """ #----- saving on file --------------------------------------------------------- dataOut = np.dstack((corrTime, airmass, astDiffMag, astMagErr, astDiffFlux, astFluxErr))[0] fnameOut = str(field) + '_' + night + '_diff_ap' + str(ap) + '.dat' # Write corrTime, airmass, diff mag of target and mag error, # diff flux of targer and error on flux, on a new file if fileOut: print('* Output file has been saved on folder : ' + folder) print('With name: ' + fnameOut) np.savetxt(folder + fnameOut, dataOut) #write file for unmatched night ready to go dataOut = np.dstack((corrTime, astDiffFlux, astFluxErr))[0] fnameOut = str(field) + '_' + night + '_ap' + str(ap) + '.dat' if fileOut: print('* File for unmatched data has been saved on folder : ' + folder) print('With name: ' + fnameOut) np.savetxt(folder + fnameOut, dataOut, fmt=['%10.6f','%.6e','%.2e']) # write uncorrected time and raw flux dataRaw = np.dstack((time, astRawMag))[0] fnameRaw = str(field) + '_' + night + '_raw_ap' + str(ap) + '.dat' if fileOut: print('* Raw file has been saved on folder : ' + folder) print('With name: ' + fnameRaw) np.savetxt(folder + fnameRaw, dataRaw) #--- Graphs ------------------------------------------------------------------ if showCstars10 : rtp.seeTenByTenCstars(data, ap, nCstar, corrTime, meanCmag) if showCstars : rtp.seeCstars(data, ap, nCstar, corrTime, meanCmag) ''' for i in xrange(nCstar + 1): error = data[:, (nCstar+1)*3 + 1 + ap + i*3] plt.plot(corrTime, error, '.r', label='error') plt.title(str(i+1)) plt.legend() plt.show() ''' ''' plt.plot(corrTime, airmass, 'k.') plt.plot(corrTime, data[:, 4 + ap + 0*3]-np.mean(data[:, 4 + ap + 0*3]), 'r.') plt.show() ''' if graph: plt.plot(time, astFluxErr, 'r.', label='astFluxErr') plt.legend() plt.show() plt.plot(corrTime, astMagErr, 'r.', label='astMagErr') plt.legend() plt.show() plt.plot(corrTime, astRawMag, 'r.', label='astRawMag') plt.plot(corrTime, meanCmag, 'b.', label='meanCstarsMag') plt.gca().invert_yaxis() plt.legend() plt.show() ''' plt.plot(corrTime, astDiffMag, 'k.', label='diffMag') plt.gca().invert_yaxis() plt.legend() plt.show() ''' u = np.arange(len(astDiffFlux))+1 cStarMeanFluxes = cStarsSumFlux / nCstar cStarMeanFluxes /= np.mean(cStarMeanFluxes) plt.plot(u, astDiffFlux, 'k.', label='astDiffFlux') plt.plot(u, cStarMeanFluxes, 'r.') plt.xlabel('n') plt.ylabel('differential flux') plt.legend() plt.show() plt.plot(corrTime, astDiffFlux, 'k.', label='astDiffFlux') plt.errorbar(corrTime, astDiffFlux, yerr=astFluxErr, fmt='k.', ecolor='gray') plt.xlabel('time') plt.ylabel('differential flux') plt.legend() plt.show() <file_sep>/photCodes/mossLC.py import numpy as np, matplotlib.pyplot as plt, glob #----------------- def plotLC(fname, shift=0, Format = 'k.'): """ Plot LC """ data = np.loadtxt(fname) data[:,1] += shift plt.errorbar(data[:,0], data[:,1], data[:,2], fmt=Format, ecolor='gray', lw=1, ms=4, capsize=1.5, label=fname[-14:-4]) #----------------- folder = '/media/marin/TRAPPIST3/troppist/pho/348Moss/' """ night = '20171213' night = '20171214b2' plotLC(folder+night+'.txt') plt.legend() plt.gca().invert_yaxis() plt.show() """ pattern = '201712*' fnames = sorted(glob.glob(folder + pattern)) col=['C0.','C1.','C2.','C3.','C4.','C5.','C6.','C7.','C8.','C9.', 'C0.','C1.','C2.','C3.','C4.','C5.','C6.','C7.','C8.','C9.'] for i in range(len(fnames)): fname = fnames[i] plotLC(fname, Format=col[i]) plt.legend() plt.gca().invert_yaxis() plt.show() #------------------- night1 = '20171213' night2 = '20171213b' plotLC(folder+night1+'.txt') plotLC(folder+night2+'.txt', -0.12) plt.gca().invert_yaxis() plt.legend() plt.show()
150a648d342f113bf441f9df2a9b39dd94252307
[ "Markdown", "Python" ]
18
Python
mferrais/photCodes
85c500a6a23724345ffa4390e42d9e658c0e148a
52e46e1f46da4c6e41a44774b468d77f156179c2
refs/heads/master
<file_sep> # ................................................................. # NOTES : # # ................................................................. # Imports librairie standard import tkinter import tkinter.messagebox as messagebox import os # Imports Tiers import pygame.mixer # Imports locaux # ................................................................. # Constantes # ................................................................. # Classes class ProgrammeFenetre(): # ................................................................. # Constructeur & méthodes spéciales def __init__(self): # Variables liées à la config de Tkinter self.racine_tk = tkinter.Tk() self.fenetre_largeur = 0 self.fenetre_hauteur = 0 # Variables utilisées pour les contrôles self.variable_champ_de_saisie = tkinter.StringVar() self.variable_champ_de_saisie.set("") # Police d'écriture / affichage du texte self.police_texte = ("Arial", 24) # Initialisation de pygame.mixer pygame.mixer.init(frequency = 44100, size = -16, channels = 1, buffer = 2**12) self.canal_son = pygame.mixer.Channel(0) self.son = None # ................................................................. # Propriétés # ................................................................. # Méthodes def lancer_fenetre(self): # Largeur de la fenêtre. self.fenetre_largeur = self.racine_tk.winfo_screenwidth() * 0.8 # retire * 0.x pour le fullscreen self.fenetre_hauteur = self.racine_tk.winfo_screenheight() * 0.6 # retire * 0.y pour le fullscreen # self.racine_tk.attributes("-fullscreen", True) # dé-commente pour mettre en fullscreen # Lie la touche "Echap" à l'arrêt de la fenêtre self.racine_tk.bind("<Escape>", lambda x: self.racine_tk.destroy()) # Création d'un Canvas (zone de dessin). canvas = tkinter.Canvas(self.racine_tk, width=self.fenetre_largeur, height=self.fenetre_hauteur) canvas.create_rectangle(0, 0, self.fenetre_largeur, self.fenetre_hauteur, fill="green") # Création d'une Frame (cadre) pour contenir les contrôles (labels, champs de saisie, etc). cadre = tkinter.Frame(self.racine_tk) # Création d'un Label. label = tkinter.Label(cadre, text="Ecrire quelque chose:") label.configure(font=self.police_texte) # Création d'une Entry (champ de saisie). champ_de_saisie = tkinter.Entry(cadre, textvariable=self.variable_champ_de_saisie, width=30) champ_de_saisie.configure(font=self.police_texte) champ_de_saisie.focus_set() # Lie la touche "Entrer" avec la fonction pour traiter le contenu du champ. champ_de_saisie.bind('<Return>', lambda event: self.traitement_champ_de_saisie()) # Ajoute le cadre au canvas, en le plaçant au milieu de la fenêtre. canvas.create_window(self.fenetre_largeur/2, self.fenetre_hauteur/2, window=cadre) # Ajout d'un bouton (fait la même chose que la touche "Entrer" dans le champ de saisie) bouton = tkinter.Button(cadre, text="Valider", command=self.traitement_champ_de_saisie) bouton.configure(font=self.police_texte) # Packs (validation graphique des différents éléments). # cadre.pack() # inutile, mais je ne sais pas pourquoi. label.pack() champ_de_saisie.pack() bouton.pack() canvas.pack(side="top", fill="both") # Boucle principale de la fenêtre. self.racine_tk.mainloop() def traitement_champ_de_saisie(self): # Récupération du contenu du champ de saisie. contenu_champ_de_saisie = self.variable_champ_de_saisie.get() # Affichage du contenu print(f"contenu du champ de saisie: {contenu_champ_de_saisie}") # affichage console. # messagebox.showinfo(title="Info", message=f"contenu du champ de saisie: {contenu_champ_de_saisie}") # affichage boîte de dialogue. # Traitement du contenu # Note: c'est juste un exemple par rapport à ce que tu m'as dis (jouer un son), après tu gères ça comme tu veux ;-). # Commandes possibles: # 'jouer <nom_fichier.extension>': charge et joue un son. # 'pause': met en pause le son joué. # 'reprendre': remet en lecture le son joué. # 'reset': remet à zéro le son joué. # 'rejouer': rejoue le dernier son (à utiliser après 'reset'). # 'volume <intensite_volume>': modifie le volume avec l'intensité choisie (entre 0.0 et 1.0). # Récupèration des mots du champ de saisie mots = [] if " " in contenu_champ_de_saisie: # s'il y a un ou plusieurs espaces => plusieurs mots. mots = contenu_champ_de_saisie.split(" ") else: # pas d'espaces => un seul mot. mots = [contenu_champ_de_saisie] # Interprêtation du premier mot et action en fonction. if mots[0] == "jouer": dossier_sons = "D:\\200_Programmation\\100_EspaceYourself\\100-DEV_PilotageSalle\\tests\\serveur\\services\\ressources\\" nom_fichier = mots[1] chemin_fichier = f"{dossier_sons}{nom_fichier}" if os.path.exists(chemin_fichier): # vérifie si le fichier existe. print(f"Chargement du fichier '{nom_fichier}'.") else: print(f"Le fichier '{nom_fichier}' est introuvable.") self.son = pygame.mixer.Sound(chemin_fichier) self.canal_son.play(self.son) elif mots[0] == "pause": self.canal_son.pause() elif mots[0] == "reprendre": self.canal_son.unpause() elif mots[0] == "reset": self.canal_son.stop() elif mots[0] == "rejouer": self.canal_son.play(self.son) elif mots[0] == "volume": volume_texte = mots[1] volume = float(volume_texte) self.canal_son.set_volume(volume) # Vide le champ de saisie. self.variable_champ_de_saisie.set("") # commente si tu veux le laisser rempli # ................................................................. # Lancement du programme def main(): programme = ProgrammeFenetre() programme.lancer_fenetre() main()
74560701b6ddc7504044e752f4781e2287c615a2
[ "Python" ]
1
Python
SuperBlueLight/Exemple_Tkinter
d90037de1ade4a95cea6d3dbc51313751a96d4c9
c29da0b71321a16a99d5fcf76f02f4e04981ff0c
refs/heads/master
<repo_name>valentine217/pingxiang<file_sep>/js/agency.js /*! * Start Bootstrap - Agnecy Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // Add/REMOVE row in table, id: mdf-tr $("#mdf-tr").click(function(){ $('#order-table tbody').append('\ <tr class="order-row-content added">\ <td class="lalign"><div contenteditable>XXXX</div></td>\ <td><div contenteditable>X</div>元</td>\ <td><div contenteditable>X</div>年</td>\ <td><div contenteditable>X</div>元</td>\ <td><div contenteditable>X</div></td>\ <td><div>X</div>元</td>\ <td><div contenteditable>X</div>件</td>\ <td><div contenteditable>YYYY/MM/YY</div></td>\ <td><div contenteditable>XX</div></td>\ </tr> '); }); // hide or display ranking in nav $(".ranking-show").click(function(){ $(this).closest("p").next().toggle(); $(this).closest("p").next().next().toggle(); }); // change css when nav scrool $(window).scroll(function() { if ($(document).scrollTop() > 300) { console.log("down"); $( ".navbar-default .nav li a").css("color","#FCF8EC"); $( ".navbar-default .nav li p").css("color","#FCF8EC"); } else { console.log("up"); $( ".navbar-default .nav li a").css("color","transparent"); $( ".navbar-default .nav li p").css("color","transparent"); } }); /* image slider */ $(document).ready(function(){ console.log("what the fuck"); var slideCount = $('#slider ul li').length; var slideWidth = $('#slider ul li').width(); var slideHeight = $('#slider ul li').height(); var sliderUlWidth = slideCount * slideWidth; $('#slider').css({ width: slideWidth, height: slideHeight }); $('#slider ul').css({ width: sliderUlWidth, marginLeft: - slideWidth }); $('#slider ul li:last-child').prependTo('#slider ul'); function moveLeft() { $('#slider ul').animate({ left: + slideWidth }, 200, function () { $('#slider ul li:last-child').prependTo('#slider ul'); $('#slider ul').css('left', ''); }); }; function moveRight() { $('#slider ul').animate({ left: - slideWidth }, 200, function () { $('#slider ul li:first-child').appendTo('#slider ul'); $('#slider ul').css('left', ''); }); }; $('#slider a.control_prev').click(function () { moveLeft(); }); $('#slider a.control_next').click(function () { moveRight(); }); });
97c709f81831b514b8a4afd9557a6bcc26a91106
[ "JavaScript" ]
1
JavaScript
valentine217/pingxiang
e29a3374617052af848f8406ded14e6c066739b6
31e883e702f44b648682f4107df4cd17dcb75920
refs/heads/master
<file_sep>package me.liujin.douyinhooker import android.app.Application import android.content.Context import android.util.Log import de.robv.android.xposed.IXposedHookLoadPackage import de.robv.android.xposed.callbacks.XC_LoadPackage import de.robv.android.xposed.XC_MethodHook import de.robv.android.xposed.XposedHelpers import de.robv.android.xposed.XposedBridge class DouyinHook : IXposedHookLoadPackage { companion object { val TAG = DouyinHook::class.java.simpleName } override fun handleLoadPackage(lpparam: XC_LoadPackage.LoadPackageParam) { // 修改地区 XposedBridge.hookAllMethods( android.telephony.TelephonyManager::class.java, "getSimCountryIso", object : XC_MethodHook() { override fun afterHookedMethod(param: MethodHookParam) { val country = PreferenceUtils.region() param.result = country Log.d(TAG, "Change country to: $country") } } ) if (lpparam.packageName.equals("com.ss.android.ugc.trill")) { Log.d(TAG, "Douyin found!") XposedHelpers.findAndHookMethod(Application::class.java, "attach", Context::class.java, object : XC_MethodHook() { override fun afterHookedMethod(parentParam: MethodHookParam) { Log.d(TAG, "After attach application.") val classLoader = (parentParam.args[0] as Context).classLoader val aweme: Class<*>? = classLoader.loadClass("com.ss.android.ugc.aweme.feed.model.Aweme") val clazz: Class<*>? = classLoader.loadClass("com.ss.android.ugc.trill.share.a.c") val likeListenerClass: Class<*>? = classLoader.loadClass("com.ss.android.ugc.aweme.feed.ui.at\$1") val atClass: Class<*>? = classLoader.loadClass("com.ss.android.ugc.aweme.feed.ui.at") var shareObj: Any? = null if (aweme != null && clazz != null && likeListenerClass != null) { // 去水印,下载更快,文件更小,清晰度不变 if (PreferenceUtils.isDisabledWatermark()) { XposedHelpers.findAndHookMethod(clazz, "share", aweme, String::class.java, Boolean::class.java, object : XC_MethodHook() { override fun beforeHookedMethod(param: MethodHookParam) { Log.d(TAG, "Hook before share.") Log.d(TAG, "Param[0]: ${param.args[0]}\nParam[1]: ${param.args[1]}\nParam[2]: ${param.args[2]}") param.args[2] = true shareObj = param.thisObject as Any } }) } else { XposedHelpers.findAndHookMethod(clazz, "share", aweme, String::class.java, Boolean::class.java, object : XC_MethodHook() { override fun beforeHookedMethod(param: MethodHookParam) { Log.d(TAG, "Hook before share.") Log.d(TAG, "Param[0]: ${param.args[0]}\nParam[1]: ${param.args[1]}\nParam[2]: ${param.args[2]}") shareObj = param.thisObject as Any } }) } // 点赞自动下载视频 if (PreferenceUtils.autosave()) { XposedHelpers.findAndHookMethod(atClass, "handleDiggClick", aweme, object : XC_MethodHook() { override fun beforeHookedMethod(diggParam: MethodHookParam) { Log.d(TAG, "Hook before atClass.handleDiggClick.") Log.d(TAG, "Param[0]: ${diggParam.args[0]}") val shareMethod = clazz.getMethod("share", aweme, Boolean::class.java) shareMethod.invoke(shareObj, diggParam.args[0], false) } }) } } } }) } } }<file_sep>package me.liujin.douyinhooker import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceFragment class PrefFragment : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onSharedPreferenceChanged(preferences: SharedPreferences, key: String) { when (key) { getString(R.string.settings_region_list_pref) -> { findPreference(key).summary = preferences.getString(key, "") } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.settings) val key = getString(R.string.settings_region_list_pref) val currentRegion = findPreference(key) currentRegion.summary = preferenceManager.sharedPreferences.getString(key, "") } override fun onStart() { super.onStart() preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onStop() { preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onStop() } }<file_sep>package me.liujin.douyinhooker import de.robv.android.xposed.XSharedPreferences object PreferenceUtils { val REGION = "region" val ISDISABLEDWATERMARK = "isDisabledWatermark" val AUTOSAVE = "autosave" private var intance: XSharedPreferences? = null fun getIntance(): XSharedPreferences? { if (intance == null) { intance = XSharedPreferences("me.liujin.douyinhooker") intance!!.makeWorldReadable() } else { intance!!.reload() } return intance } fun region(): String? { return getIntance()!!.getString(REGION, "") } fun isDisabledWatermark(): Boolean { return getIntance()!!.getBoolean(ISDISABLEDWATERMARK, true) } fun autosave(): Boolean { return getIntance()!!.getBoolean(AUTOSAVE, true) } }<file_sep>![logo](app/src/main/res/mipmap-xxhdpi/ic_launcher.png) ## DouyinHooker (TikTok 助手) Xposed module for TikTok v4.9.8 ## 声明 本项目仅供学习交流,请勿用于商业用途。 本项目从未以任何形式提供收费服务,请抄袭项目盈利者自重! ## 特性 - 突破锁区,支持修改地区 - 去水印保存视频(清晰度不变的情况下保存更快、文件更小) - 点赞自动保存视频 ## 使用说明 - 需要配合 VirtualXposed 使用,免 root (测试通过版本:v0.16.1) - 需要配合 TikTok 抖音国际版使用(测试通过版本:v4.9.8) - 每次修改设置后,需要重启 TikTok 才能生效 - 启用“点赞自动保存视频”功能后,需要先手动操作一次保存视频,然后功能才能生效 ## 非技术人员使用说明 直接到网盘下载 APK 安装即可,记得先启动插件,有问题进群交流(关注公众号即可获取网盘地址和交流群) ## 欢迎关注我的个人公众号 ![](https://raw.githubusercontent.com/coolzilj/WechatSnsViewer/master/screenshots/qrcode.png)
6fdaaba0ecd13e335d4216e062226ee8bfb180a5
[ "Markdown", "Kotlin" ]
4
Kotlin
wurenxing/DouyinHooker
76cb985a6489850b1cfaab39e7b89ed895c63801
d00621565e6255b5001e2a54b06f28b14ac1ece8
refs/heads/master
<file_sep>class OrderItemsController < ApplicationController include CurrentCart before_action :set_cart, only: [:create, :update, :destroy] before_action :set_order_item, only: [:show, :edit, :update, :destroy] def create product = Product.find(params[:product_id]) @order_item = @cart.add_product(product.id) @order_item.save end def update if order_item_params[:quantity].to_i == 0 @order_item.destroy else @order_item.update(order_item_params) end end private def set_order_item @order_item = @cart.order_items.find(params[:id]) end def order_item_params params.require(:order_item).permit(:quantity, :product_id) end end <file_sep>module CurrentCart extend ActiveSupport::Concern private # Set cart, when record not found it will be rescued. # It will create new Cart object and that cart_id will be stored in session def set_cart @cart = Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound @cart = Cart.create session[:cart_id] = @cart.id end end <file_sep>class OrderItem < ApplicationRecord belongs_to :product belongs_to :cart belongs_to :order, optional: true # Returns the total_price of order_item def total_price product.price * quantity end end <file_sep>class Cart < ApplicationRecord # When cart is destroyed the order_items are also deleted associated with cart has_many :order_items, dependent: :destroy # Adds order_item to the cart, increments found order_item # otherwise builds new OrderItem def add_product(product_id) current_item = order_items.find_by(product_id: product_id) if current_item current_item.quantity += 1 else current_item = order_items.build(product_id: product_id) end current_item end # Returns the sum of total_price of order_items # Array::sum() = Array class method def total_price order_items.to_a.sum do |order_item| order_item.total_price end end end <file_sep>class AddProductIdCartIdOrderIdToOrderItems < ActiveRecord::Migration[5.0] def change add_column :order_items, :product_id, :integer add_column :order_items, :cart_id, :integer add_column :order_items, :order_id, :integer add_index :order_items, :product_id add_index :order_items, :cart_id add_index :order_items, :order_id end end <file_sep>class CartsController < ApplicationController def destroy Cart.find(session[:cart_id]).destroy if session[:cart_id] session[:cart_id] = nil end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) users = User.create([ { email: "<EMAIL>", user: "<NAME>", }, { email: "<EMAIL>", user: "<NAME>"}]) products = Product.create([ { name:"Rain boots", description: "Great nice looking yellow rainboots. They are never too small!", image_url: "http://all-that-is-interesting.com/wordpress/wp-content/uploads/2014/09/uselessobjectsboots.jpg", price: 200.00}, { name:"Coocking pan", description: "Used for.. uhm... ", image_url: "http://a2.files.airows.com/image/upload/c_fit,cs_srgb,dpr_1.0,q_80,w_620/MTI5MDAwNDMzNjU3MTA0Mzk0.jpg ", price: 15.00}, { name:"Never empty watering can", description: "Its never emtpy.", image_url: "http://static.boredpanda.com/blog/wp-content/uploads/2014/08/useless-object-design-the-unusable-katerina-kamprani-3.jpg", price: 10.00}, { name:"Chair", description: "Most comfortable chair", image_url: "http://canyouactually.com/wp-content/uploads/2368.jpg ", price: 400.00}, ]) <file_sep># README # GIT and DEIS Git: https://github.com/ijscoman1337/useless_shop Deis: DATABASE_URL=postgres://kevin:MLRuzpLVvY1bFV6WyGif@10.115.246.38:5432/hack_firewall # USERSTORY 1 Treintje komt op de website om te kijken wat ze kan kopen. Ze hoopt dat ze er relatief snel achter kan komen. Ze gaat naar de website en ziet dat ze hier een leuk kade kan kopen voor haar oom. Ze vindt de producten en zou het liefst een boodschappenlijstje maken. Ze voegt wat producten toe aan haar shopping cart en wil een keuze maken welk product ze gaat kopen. Ze weet nog niet zeker wat ze wil kopen. Misschien kan ze een mooie top 3 maken waar ze dan uiteindelijk het perfecte kado uit kan selecteren en kopen. # Treintje komt op de website om iets te kopen. Todo nummer 1 Benodigdheden: Landing page - Products * Model: Product has_and_belongs_to_many :orders * Database full of products 1. Product name 2. Product price 3. Description 4. Image_url * Controller of products 1. index 2. show * Views 1. Index 2. show - Add to Cart * Button "Add to cart" (session) 1. Add to array of products - Navbar * Home * Shopping Cart # Ze hoopt dat ze er relatief snel achter kan komen wat ze # allemaal op de website kan doen. Todo nummer 2. - Navbar * Sign up/Login 1. Just the button - products - Footer * Contact us * Facebook * KVK * Adress # Kijken in de shopping cart - Model: Order has_and_belongs_to_many :products belongs_to :user - Show page shopping cart * Name of products * Number of products * Price per products NOG NIET AF # Doorgaan naar kopen NOG NIET AF <file_sep>Rails.application.routes.draw do root 'products#index' devise_for :users resources :order_items, only: [:create, :update, :destroy] resources :products, only: [:index] resources :users resource :cart, only: [:destroy] end <file_sep> class ProductsController < ApplicationController def index @products = Product.all end def show end private def products_params params.require(:product).permit(:name, :price, :description, :image_url) end end <file_sep>class ApplicationController < ActionController::Base protect_from_forgery with: :exception # Accessible to all controllers def current_order if !session[:order_id].nil? Order.find(session[order_id]) else Order.new end end end
54fa236a37142cfc3f86c7a1655caac278b08a77
[ "Markdown", "Ruby" ]
11
Ruby
ijscoman1337/useless_shop
774baf90313523842f2bb669b54a24154e146fb3
451692df3f85ce2509bde44b530e6f024edff292
refs/heads/master
<file_sep>package com.kh.myapp.util; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; public class XMLParser { protected static Document docInstance; protected static String XMLURL; public static void nomalize() { docInstance.getDocumentElement().normalize(); } public static Element getDocumentElement() { return docInstance.getDocumentElement(); } public static Element getElementById(String elementId) { return docInstance.getElementById(elementId); } public static NodeList getElementsByTagName(String tagname) { return docInstance.getElementsByTagName(tagname); } public static void getInstance() throws Exception { if (XMLURL.isEmpty()) { throw new Exception("URL�� �������� �ʾҽ��ϴ�"); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(XMLURL); docInstance = doc; } public static void setURL(String url) throws Exception { XMLURL = url; } } <file_sep>package com.kh.myapp; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.web.WebAppConfiguration; import com.kh.myapp.board.dao.BoardDAO; import com.kh.myapp.board.dto.BoardDTO; @WebAppConfiguration @ExtendWith(SpringExtension.class) @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"}) class BoardTest { private static Logger logger = LoggerFactory.getLogger(LoginTest.class); @Inject BoardDAO bdao; // 글작성 // @Test //@Disabled // void write() { // BoardDTO boardDTO = new BoardDTO(); // boardDTO.setBid("<EMAIL>"); // boardDTO.setBnickname("관리자"); // boardDTO.setBtitle("테스트"); // boardDTO.setBcontent("테스트중입니다"); // boolean success = bdao.write(boardDTO); // logger.info("글작성 성공?"+success); // } // 글수정 @Test @Disabled void modify() { BoardDTO boardDTO = new BoardDTO(); boardDTO.setBnum(10); boardDTO.setBtitle("글작성 테스트^^"); boardDTO.setBcontent("글작성테스트중입니다^^*"); boolean success = bdao.modify(boardDTO); logger.info("글수정 성공?"+success); } // 글삭제 @Test @Disabled void delete() { boolean success = bdao.delete("10"); logger.info("글삭제 성공?"+success); } // 글보기 @Test //@Disabled void view() { BoardDTO boardDTO = bdao.view("1002"); logger.info(boardDTO.toString()); } // // 글목록 페이징 // @Test @Disabled // void list() { // List<BoardDTO> list = bdao.list(1, 5); // logger.info(list.toString()); // } // 게시글 총계 @Test @Disabled void totalRec() { int cnt = bdao.totalRec(); logger.info("총게시글수:"+cnt); } // 검색 목록 @Test @Disabled void searchList() { // int startRecord = 1; // int endRecord = 7; // String searchType = "N"; // String keyword = "터21"; List<BoardDTO> slist = bdao.searchList(1, 20, "I", "test2"); logger.info("목록:"+slist); } // 검색 총계 @Test @Disabled void searchTotalRec() { int cnt = bdao.searchTotalRec("TC", "트22"); logger.info("검색 총계:"+cnt); } // 추천 비추천 @Test @Disabled void goodOrBad() { BoardDTO bdto = new BoardDTO(); bdto.setBnum(1002); int cnt = bdao.goodOrBad("1002", "good"); logger.info("추천"+cnt); } @Test @Disabled void goodOrBadLog() { boolean success = false; int cnt = bdao.goodOrBadLog("B", "1", "<EMAIL>", "G"); if(cnt>0) {success = true;} logger.info("처리건수"+cnt); } } <file_sep>package com.kh.myapp.board.service; import java.util.List; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.ui.Model; import com.kh.myapp.board.dao.BoardDAO; import com.kh.myapp.board.dto.BoardDTO; import com.kh.myapp.member.dto.MemberDTO; import com.kh.myapp.product.dto.filesDTO; import com.kh.myapp.util.FindCriteria; import com.kh.myapp.util.PageCriteria; import com.kh.myapp.util.RecordCriteria; @Service public class BoardSvcImpl implements BoardSvc { private static final Logger logger = LoggerFactory.getLogger(BoardSvcImpl.class); @Inject BoardDAO bdao; // 글작성 @Override public int write(BoardDTO boardDTO) { return bdao.write(boardDTO); } // 글수정 @Override public boolean modify(BoardDTO boardDTO) { return bdao.modify(boardDTO); } // 글삭제 @Override public boolean delete(String bnum) { return bdao.delete(bnum); } @Override public boolean insertInsertedFile(filesDTO filesdto) { return bdao.insertInsertedFile(filesdto); } // 글보기 @Override public BoardDTO view(String bnum) { return bdao.view(bnum); } // 게시글 목록(기본) @Override public List<BoardDTO> list() { return bdao.list(); } // 게시글 목록(페이징) @Override public List<BoardDTO> list(int startRec, int endRec, String best) { return bdao.list(startRec, endRec, best); } // 게시글 총계 @Override public int totalRec() { return bdao.totalRec(); } // 검색 목록 @Override public List<BoardDTO> searchList(int startRecord, int endRecord, String searchType, String keyword) { return bdao.searchList(startRecord, endRecord, searchType, keyword); } // 글목록 페이징, 검색 @Override public void list(HttpServletRequest request, Model model) { int NUM_PER_PAGE = 9; // 한페이지에 보여줄 레코드수 int PAGE_NUM_PER_PAGE = 10; // 한페이지에 보여줄 페이지수 int reqPage = 0; // 요청페이지 int totalRec = 0; // 전체레코드수 int bestCount = 0; String searchType = null; // 검색타입 String keyword = null; // 검색어 PageCriteria pc = null; RecordCriteria rc = null; // 검색조건이 없는 경우의 레코드 시작,종료페이지 FindCriteria fc = null; // 검색조건이 있는 경우의 레코드 시작,종료페이지 List<BoardDTO> alist = null; // String id = ((MemberDTO)request.getSession().getAttribute("user")).getId(); // 요청페이지가 없는경우 1페이지로 이동 if (request.getParameter("reqPage")==null || request.getParameter("reqPage")=="") { reqPage = 1; } else { reqPage = Integer.parseInt(request.getParameter("reqPage")); } logger.info("reqPage:"+reqPage); // 검색 매개값 체크(searchType, keyword) searchType = request.getParameter("searchType"); keyword = request.getParameter("keyword"); logger.info("검색어타입"+searchType); logger.info("검색어"+keyword); if ((keyword == null || keyword.trim().isEmpty()) && request.getParameter("best")==null) { // 검색조건이 없는 경우 rc = new RecordCriteria(reqPage,NUM_PER_PAGE); totalRec = bdao.totalRec(); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = bdao.list(rc.getStartRecord(), rc.getEndRecord(), ""); request.setAttribute("list", alist); request.setAttribute("pc", pc); } else if (request.getParameter("best") != null) { logger.info("검wer색어타입"+searchType); rc = new RecordCriteria(reqPage,NUM_PER_PAGE); totalRec = bdao.totalRec(); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = bdao.list(rc.getStartRecord(), rc.getEndRecord(), request.getParameter("best")); request.setAttribute("list", alist); request.setAttribute("pc", pc); } else { // 검색조건이 있는 경우 rc = new FindCriteria(reqPage,NUM_PER_PAGE,searchType,keyword); // 검색목록 총레코드수 반환 totalRec = bdao.searchTotalRec( ((FindCriteria)rc).getSearchType(), ((FindCriteria)rc).getKeyword() ); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = bdao.searchList( rc.getStartRecord(), rc.getEndRecord(), ((FindCriteria)rc).getSearchType(), ((FindCriteria)rc).getKeyword() ); } model.addAttribute("list", alist); model.addAttribute("pc", pc); } // 검색 총계 @Override public int searchTotalRec(String searchType, String keyword) { return bdao.searchTotalRec(searchType, keyword); } // 추천 비추천 @Override public int goodOrBad(String bnum, String goodOrBad) { return bdao.goodOrBad(bnum, goodOrBad); } // 인기글 @Override public List<BoardDTO> best() { return bdao.best(); } // 조회수 로그 @Override public void hitLog(String type, int num, String id) { bdao.hitLog(type, num, id); } // 추천 비추천 로그 @Override public int goodOrBadLog(String type, String num, String id, String goodOrBad) { return bdao.goodOrBadLog(type, num, id, goodOrBad); } @Override public void getMyList(HttpServletRequest request, Model model) { int NUM_PER_PAGE = 10; // 한페이지에 보여줄 레코드수 int PAGE_NUM_PER_PAGE = 10; // 한페이지에 보여줄 페이지수 int reqPage = 0; // 요청페이지 int totalRec = 0; // 전체레코드수 String searchType = null; // 검색타입 String keyword = null; // 검색어 PageCriteria pc = null; RecordCriteria rc = null; // 검색조건이 없는 경우의 레코드 시작,종료페이지 FindCriteria fc = null; // 검색조건이 있는 경우의 레코드 시작,종료페이지 List<BoardDTO> alist = null; String id = ((MemberDTO)request.getSession().getAttribute("user")).getId(); // 요청페이지가 없는경우 1페이지로 이동 if (request.getParameter("reqPage")==null || request.getParameter("reqPage")=="") { reqPage = 1; } else { reqPage = Integer.parseInt(request.getParameter("reqPage")); } logger.info("reqPage:"+reqPage); // 검색 매개값 체크(searchType, keyword) searchType = "I"; keyword = id; logger.info("검색어타입"+searchType); logger.info("검색어"+keyword); if (keyword == null || keyword.trim().isEmpty()) { // 검색조건이 없는 경우 rc = new RecordCriteria(reqPage,NUM_PER_PAGE); totalRec = bdao.totalRec(); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = bdao.list(rc.getStartRecord(), rc.getEndRecord(), ""); request.setAttribute("list", alist); request.setAttribute("pc", pc); } else { // 검색조건이 있는 경우 rc = new FindCriteria(reqPage,NUM_PER_PAGE,searchType,keyword); // 검색목록 총레코드수 반환 totalRec = bdao.searchTotalRec( ((FindCriteria)rc).getSearchType(), ((FindCriteria)rc).getKeyword() ); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = bdao.searchList( rc.getStartRecord(), rc.getEndRecord(), ((FindCriteria)rc).getSearchType(), ((FindCriteria)rc).getKeyword() ); } model.addAttribute("list", alist); model.addAttribute("pc", pc); } } <file_sep>package com.kh.myapp.product.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.ui.Model; import com.kh.myapp.board.dao.BoardDAOImplXML; import com.kh.myapp.product.dto.ProductDTO; import com.kh.myapp.product.dto.filesDTO; import com.kh.myapp.util.FindCriteria; import com.kh.myapp.util.PageCriteria; import com.kh.myapp.util.RecordCriteria;; @Repository public class ProductDAOImplXML implements ProductDAO { private static Logger logger = LoggerFactory.getLogger(ProductDAOImplXML.class); @Autowired private SqlSession sqlSession; @Override public void getProductList(Model model, HttpServletRequest request) throws Exception { int NUM_PER_PAGE = 10; // 한페이지에 보여줄 레코드수 int PAGE_NUM_PER_PAGE = 10; // 한페이지에 보여줄 페이지수 int reqPage = 0; // 요청페이지 int totalRec = 0; // 전체레코드수 String searchType = null; // 검색타입 String keyword = null; // 검색어 String searchType2 = null; // 검색타입 String keyword2 = null; // 검색어 PageCriteria pc = null; RecordCriteria rc = null; // 검색조건이 없는 경우의 레코드 시작,종료페이지 FindCriteria fc = null; // 검색조건이 있는 경우의 레코드 시작,종료페이지 List<ProductDTO> alist = null; // 요청페이지가 없는경우 1페이지로 이동 if (request.getParameter("reqPage")==null || request.getParameter("reqPage")=="") { reqPage = 1; } else { reqPage = Integer.parseInt(request.getParameter("reqPage")); } // 검색 매개값 체크(searchType, keyword) searchType = request.getParameter("sold"); keyword = request.getParameter("type"); searchType2 = request.getParameter("searchType"); keyword2 = request.getParameter("keyword"); Boolean isFilterEmpty = (keyword == null || keyword.trim().isEmpty()) && (searchType == null || searchType.trim().isEmpty()); Boolean isSearchEmpty = (keyword2 == null || keyword2.trim().isEmpty()) && (searchType2 == null || searchType2.trim().isEmpty()); if (isFilterEmpty && isSearchEmpty) { // 검색조건이 없는 경우 rc = new RecordCriteria(reqPage,NUM_PER_PAGE); totalRec = this.totalrec(); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = this.list(rc.getStartRecord(), rc.getEndRecord()); request.setAttribute("list", alist); request.setAttribute("pc", pc); } else if (!isFilterEmpty && isSearchEmpty) { // 검색조건이 있는 경우 rc = new RecordCriteria(reqPage, NUM_PER_PAGE); ProductDTO productdto = new ProductDTO(); if (!searchType.isEmpty()) { productdto.setPstore(searchType); } if (!keyword.isEmpty()) { productdto.setPgroup(keyword); } productdto.setStartRecord(rc.getStartRecord()); productdto.setEndRecord(rc.getEndRecord()); logger.info(productdto.toString()); // 검색목록 총레코드수 반환 totalRec = this.selectProductByOptionCount(productdto); logger.info(totalRec + "니미"); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = this.selectProductByOption(productdto); } else if(!isSearchEmpty) { // 검색조건이 있는 경우 rc = new RecordCriteria(reqPage, NUM_PER_PAGE); ProductDTO productdto = new ProductDTO(); if (searchType2.equals("ptitle")) { //productdto.setPtitle(keyword2); } if (searchType2.equals("pcontent")) { //productdto.setPcontent(keyword2); } productdto.setPcontent(keyword2); productdto.setStartRecord(rc.getStartRecord()); productdto.setEndRecord(rc.getEndRecord()); logger.info(productdto.toString()); // 검색목록 총레코드수 반환 totalRec = this.selectProductByOptionCount(productdto); logger.info(totalRec + "니미sdfsdf"); pc = new PageCriteria(rc,totalRec,PAGE_NUM_PER_PAGE); alist = this.selectProductByOption(productdto); } model.addAttribute("list", alist); model.addAttribute("pc", pc); } @Override public int insertProduct(ProductDTO productdto) { //int cnt = 0; return sqlSession.insert("productDAO.insertProduct", productdto); //if (cnt > 0) { // return true; //} //return false; } @Override public boolean deleteProduct(int product_srl) { int cnt = 0; cnt = sqlSession.delete("productDAO.deleteProduct", product_srl); if (cnt > 0) { return true; } return false; } @Override public boolean modifyProduct(ProductDTO productdto) { int cnt = 0; cnt = sqlSession.update("productDAO.modifyProduct", productdto); if (cnt > 0) { return true; } return false; } @Override public ProductDTO dispProduct(ProductDTO productdto) { ProductDTO pdto = sqlSession.selectOne("productDAO.dispProduct", productdto); return pdto; } @Override public List<ProductDTO> list(int startRec, int endRec) { Map<String,Object> map = new HashMap<>(); map.put("startRec", startRec); map.put("endRec", endRec); return sqlSession.selectList("productDAO.getProductList", map); } @Override public int totalrec() { return sqlSession.selectOne("productDAO.totalRec"); } @Override public boolean insertInsertedFile(filesDTO filesdto) { // TODO Auto-generated method stub int cnt = 0; cnt = sqlSession.insert("productDAO.insertInsertedFile", filesdto); if (cnt > 0) { return true; } return false; } @Override public List<ProductDTO> productList(ProductDTO productdto) { return sqlSession.selectList("productDAO.productdto", productdto); } @Override public List<ProductDTO> selectProductByOption(ProductDTO productdto) { return sqlSession.selectList("productDAO.selectProductByOption", productdto); } @Override public int selectProductByOptionCount(ProductDTO productdto) { return sqlSession.selectOne("productDAO.selectProductByOptionCount", productdto); } } <file_sep>package com.kh.myapp.board.dto; import java.sql.Timestamp; import lombok.Data; @Data public class RboardDTO { private int rnum; private int bnum; private String rid; private String rnickname; private Timestamp rcdate; private Timestamp rudate; private String rcontent; private int rgroup; private int rstep; private int rindent; private String isdel; private int rrnum; private RboardDTO rbdto; } <file_sep># Spring-team-project Spring Framework/Spring Security로 구현한 리뷰게시판 얼리어먹터(EARLY A MUKTER)입니다. 기능 ------------------ * 로그인/로그아웃 * 회원가입/탈퇴 * 회원정보수정 * 게시글 등록/수정/삭제/검색 * 댓글 등록/수정/삭제 * 제품 등록/수정/삭제(관리자기능) * SpringSecurity를 이용한 접근권한 제한 사용기술 ------------------ * Bootstrap4 * HTML5/CSS/JS * JQuery * Ajax/Restful * Mybatis * Oracle * Spring Framework/Spring Security 동영상시연 ------------------ https://youtu.be/6XmKY9j9rEg 보완계획 ------------------ * 지도API <file_sep>package com.kh.myapp.board.dto; import java.security.Timestamp; import java.sql.Date; import javax.persistence.Entity; import javax.servlet.http.HttpServletRequest; import javax.validation.constraints.Size; import org.springframework.ui.Model; import com.kh.myapp.util.PageCriteria; import com.kh.myapp.util.SecureLink; import lombok.Data; @Entity @Data public class BoardDTO { // Left Join private int target_srl; private String type; private String sourcename; private String originname; private String best; private int idx; private int bnum; // 글번호 @Size(min=4, max=30, message="제목은 4~100자내로 입력가능합니다.") private String btitle; // 글제목 private String bid; // 작성자아이디 private String bnickname; // 작성자닉네임 private Timestamp bcdate; // 작성일 private Timestamp budate; // 수정일 private int bgood; // 추천 private int bbad; // 비추천 private int bhit; // 조회수 private String bcontent; // 글내용 private String btype; // 게시판 타입 public boolean isThubmanilExist() { if (sourcename == null) { return false; } return true; } public String getImage() { if (sourcename == null) { return "".toString(); } else { int timeout = 5000; String uploadedImage = "/resources/upload/" + sourcename; String key = "34x378"; String plainKey = uploadedImage; String prefix = SecureLink.get(key, plainKey, timeout); return uploadedImage + "?t=" + prefix + "&c=" + timeout; } } public String getLink(PageCriteria pc) { return "/board/view?bnum=" + bnum + "&" + pc.makeSearchURL(pc.recordCriteria.reqPage); } } <file_sep>package com.kh.myapp.login; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import com.kh.myapp.member.dto.MemberDTO; @Repository public class LoginDAOImplXML implements LoginDAO { private static Logger logger = LoggerFactory.getLogger(LoginDAOImplXML.class); @Inject SqlSession sqlSession; // 회원 정보 존재 유무 @Override public boolean isExist(String id) { boolean success = false; int cnt = sqlSession.selectOne("mappers.login.isExist", id); if(cnt>0) {success = true;} return success; } // 정상회원 체크 @Override public boolean isMember(String id, String pw) { boolean success = false; Map<String,String> map = new HashMap<>(); map.put("id", id); map.put("pw", pw); int cnt = sqlSession.selectOne("mappers.login.isMember", map); if(cnt>0) {success = true;} return success; } // 로그인 @Override public MemberDTO login(String id, String pw) { Map<String,String> map = new HashMap<>(); map.put("id", id); map.put("pw", pw); MemberDTO mdto = sqlSession.selectOne("mappers.login.login", map); return mdto; } // 아이디 찾기 @Override public MemberDTO findId(String name, String phone) { Map<String,String> map = new HashMap<>(); map.put("name", name); map.put("phone", phone); MemberDTO mdto = sqlSession.selectOne("mappers.login.findId", map); return mdto; } // 비밀번호 찾기 @Override public MemberDTO findPw(String id, String phone, String birth) { Map<String,String> map = new HashMap<>(); map.put("id", id); map.put("phone", phone); map.put("birth", birth); MemberDTO mdto = sqlSession.selectOne("mappers.login.findPw", map); return mdto; } } <file_sep>package com.kh.myapp.util; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import net.jpountz.lz4.LZ4BlockInputStream; import net.jpountz.lz4.LZ4BlockOutputStream; public class LZ4 { // Compress File into Compressed File public static void LZ4compress(String filename, String lz4file){ byte[] buf = new byte[2048]; try { String outFilename = lz4file; LZ4BlockOutputStream out = new LZ4BlockOutputStream(new FileOutputStream(outFilename), 32*1024*1024); FileInputStream in = new FileInputStream(filename); int len; while((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } // Extract file into External directory public static void LZ4Uncompress(String lz4file, String filename){ byte[] buf = new byte[2048]; try { String outFilename = filename; LZ4BlockInputStream in = new LZ4BlockInputStream(new FileInputStream(lz4file)); FileOutputStream out = new FileOutputStream(outFilename); int len; while((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>package com.kh.myapp.common; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; public class LoginFailureHandler implements AuthenticationFailureHandler{ private String defaultFailureUrl; @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { request.setAttribute("errMsg", "아이디와 비밀번호가 일치하지 않습니다."); request.getRequestDispatcher(defaultFailureUrl).forward(request, response); } public String getDefaultFailureUrl() { return defaultFailureUrl; } public void setDefaultFailureUrl(String defaultFailureUrl) { this.defaultFailureUrl = defaultFailureUrl; } } <file_sep>package com.kh.myapp.controller; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.kh.myapp.board.dto.BoardDTO; import com.kh.myapp.member.dto.MemberDTO; import com.kh.myapp.product.dao.ProductDAO; import com.kh.myapp.product.dto.ProductDTO; import com.kh.myapp.product.dto.filesDTO; import com.kh.myapp.util.Code; import com.kh.myapp.util.storeData; @Controller @RequestMapping("/product") public class ProductController { private static Logger logger = LoggerFactory.getLogger(ProductController.class); // 업로드 경로 public static final String ROOT = "C:/upload-dir/"; @Autowired @Qualifier("productDAOImplXML") private ProductDAO pdo; // 제품목록 @RequestMapping(value = {"/list"}, method = {RequestMethod.GET,RequestMethod.POST}) public String List(Model model, HttpServletRequest request) throws Exception { logger.info("/list호출"); storeData storedata = new storeData(); model.addAttribute("product", storedata.getProductList()); model.addAttribute("store", storedata.getStoreList()); try { pdo.getProductList(model, request); } catch (Exception e) { e.printStackTrace(); } return "/product/list"; } // 제품등록 @RequestMapping(value = {"/writeForm"}, method = {RequestMethod.GET}) public String Write(Model model, HttpServletRequest request, HttpSession session) throws Exception { storeData storedata = new storeData(); model.addAttribute("product", storedata.getProductList()); model.addAttribute("store", storedata.getStoreList()); model.addAttribute("ProductDTO", new ProductDTO()); return "/product/writeForm"; } // 등록처리 @RequestMapping(value = {"/writeOk"}, method = {RequestMethod.POST}) public String List(HttpServletRequest request, @RequestParam("file") MultipartFile file, @ModelAttribute("ProductDTO") ProductDTO productDTO, BindingResult result, HttpSession session) throws Exception { if(result.hasErrors()) { logger.info(result.toString()); return "/product/writeForm"; } MemberDTO mdto = MemberDTO.current(); productDTO.setPid(mdto.getId()); productDTO.setPnickname(mdto.getNickname()); productDTO.setPname(mdto.getName()); pdo.insertProduct(productDTO); int currentIdx = productDTO.getIdx(); // 멀티파트 업로드 파일이 존재한다면 if (!file.isEmpty()) { try { // 경로가 존재하지 않는다면 폴더 생성 if (!Files.exists(Paths.get(ROOT))) { try { Files.createDirectories(Paths.get(ROOT)); } catch (IOException ioe) { ioe.printStackTrace(); } } // 원본 파일 이름 String source_filename = file.getOriginalFilename(); // 이미지 파일만 허가 if (source_filename.matches(".+(jpg|jpeg|png|gif)$")) { // 확장자 String extension = FilenameUtils.getExtension(source_filename); ServletContext context = request.getSession().getServletContext(); String appPath = context.getRealPath("/resources/upload"); logger.info(appPath); ServletContext sc = session.getServletContext(); String x = sc.getRealPath("/"); logger.info(x); // 파일 이름 생성 UUID uuid = UUID.randomUUID(); String filename = uuid.toString(); File fs = new File(appPath + filename + "." + extension); while(fs.isFile()) { fs = new File(appPath + filename + "." + extension); } filesDTO filesdto = new filesDTO(); filesdto.setType("product"); filesdto.setTarget_srl(currentIdx); filesdto.setSourcename(filename + "." + extension); filesdto.setOriginname(source_filename); boolean success = pdo.insertInsertedFile(filesdto); logger.info("파일 입력 성공:"+success); logger.info(appPath); // 파일 업로드 Files.copy(file.getInputStream(), Paths.get(appPath, filename + "." + extension)); } } catch (IOException | RuntimeException e) { } } return "redirect:/product/list"; } // 제품보기 @RequestMapping(value = {"/view/{pnum}"}, method = {RequestMethod.GET}) public String View(@PathVariable("pnum") String pnum, Model model, HttpServletRequest request, HttpSession session) { if (!pnum.isEmpty()) { ProductDTO productDTO = new ProductDTO(); productDTO.setPnum(Integer.parseInt(pnum)); model.addAttribute("productList", pdo.dispProduct(productDTO)); ProductDTO docDTO = (ProductDTO) model.asMap().get("productList"); if (!docDTO.getPgroup().isEmpty()) { model.addAttribute("relatedList", pdo.productList(docDTO)); } } storeData storedata = new storeData(); model.addAttribute("product", storedata.getProductList()); model.addAttribute("store", storedata.getStoreList()); model.addAttribute("ProductDTO", new ProductDTO()); return "/product/read"; } @RequestMapping(value = {"/delete"}, method = {RequestMethod.GET}) public String Delete(HttpServletRequest request) { int pnum = Integer.parseInt(request.getParameter("pnum")); boolean isDeleted = pdo.deleteProduct(pnum); if (isDeleted) { return "redirect:/product/list"; } else { return "redirect:/product/view/" + pnum; } } @RequestMapping(value = {"/modifyOk"}, method = {RequestMethod.POST}) public String Modify(HttpServletRequest request, @ModelAttribute("ProductDTO") ProductDTO productDTO) { int pnum = Integer.parseInt(request.getParameter("pnum")); logger.info(pnum + "pnum"); productDTO.setPnum(pnum); pdo.modifyProduct(productDTO); return "redirect:/product/list"; } @RequestMapping(value = {"/comment/list"}, method = {RequestMethod.POST}) public String getCommentList(HttpServletRequest request) { int pnum = Integer.parseInt(request.getParameter("pnum")); return ""; } }<file_sep>package com.kh.myapp.board.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import org.springframework.ui.Model; import com.kh.myapp.board.dto.BoardDTO; import com.kh.myapp.board.dto.CntLog; import com.kh.myapp.product.dto.filesDTO; @Repository public class BoardDAOImplXML implements BoardDAO { private static Logger logger = LoggerFactory.getLogger(BoardDAOImplXML.class); @Inject SqlSession sqlSession; @Override public boolean insertInsertedFile(filesDTO filesdto) { int cnt = 0; cnt = sqlSession.insert("productDAO.insertInsertedFile", filesdto); if (cnt > 0) { return true; } return false; } // 글작성 @Override public int write(BoardDTO boardDTO) { /*boolean success = false; int cnt = sqlSession.insert("mappers.board.write", boardDTO); if (cnt > 0) { success = true; } return success;*/ return sqlSession.insert("mappers.board.write", boardDTO); } // 글수정 @Override public boolean modify(BoardDTO boardDTO) { boolean success = false; int cnt = sqlSession.update("mappers.board.modify", boardDTO); if (cnt > 0) { success = true; } return success; } // 글삭제 @Override public boolean delete(String bnum) { boolean success = false; int cnt = sqlSession.delete("mappers.board.delete", bnum); if (cnt > 0) { success = true; } return success; } // 글보기 @Override public BoardDTO view(String bnum) { BoardDTO boardDTO = null; boardDTO = sqlSession.selectOne("mappers.board.view", bnum); // 조회수 로그 체크(게시판 타입,문서번호, 사용자아이디) int cnt = 0; cnt = hitLogChk(boardDTO.getBtype(),boardDTO.getBnum(), boardDTO.getBid(),"Y"); if (cnt == 0) { // 조회수 증가 updateHit(boardDTO.getBnum()); // 조회수 로그 입력(게시판 타입,문서번호, 사용자아이디) hitLog(boardDTO.getBtype(),boardDTO.getBnum(), boardDTO.getBid()); return boardDTO; } else { return boardDTO; } } // 조회수 로그 체크(게시판 타입,문서번호, 사용자아이디) private int hitLogChk(String type, int num, String id, String hitYn) { Map<String,Object> map = new HashMap<>(); map.put("type", type); map.put("num", num); map.put("id", id); map.put("hitYn", hitYn); return sqlSession.selectOne("hitLogChk", map); } // 조회수 증가 private void updateHit(int bnum) { sqlSession.update("mappers.board.updateHit", bnum); } //조회수 로그 등록 @Override public void hitLog(String type, int num, String id) { Map<String,Object> map = new HashMap<>(); map.put("type", type); map.put("num", num); map.put("id", id); sqlSession.insert("mappers.board.hitLog", map); } // 글목록 기본 @Override public List<BoardDTO> list() { return sqlSession.selectList("mappers.board.listOld"); } // 글목록 페이징 @Override public List<BoardDTO> list(int startRec, int endRec, String best) { Map<String,Object> map = new HashMap<>(); map.put("startRec", startRec); map.put("endRec", endRec); if (best != null) { map.put("best", best); } return sqlSession.selectList("mappers.board.list", map); } // 게시글 총계 @Override public int totalRec() { return sqlSession.selectOne("mappers.board.totalRec"); } // 검색목록 @Override public List<BoardDTO> searchList(int startRecord, int endRecord, String searchType, String keyword) { Map<String,Object> map = new HashMap<>(); map.put("startRecord", startRecord); map.put("endRecord", endRecord); map.put("searchType", searchType); map.put("keyword", keyword); return sqlSession.selectList("mappers.board.searchList", map); } // 검색 총계 @Override public int searchTotalRec(String searchType, String keyword) { Map<String,Object> map = new HashMap<>(); map.put("searchType", searchType); map.put("keyword", keyword); return sqlSession.selectOne("mappers.board.searchTotalRec", map); } // 추천 비추천 @Override public int goodOrBad(String bnum, String goodOrBad) { Map<String,Object> map = new HashMap<>(); map.put("bnum", bnum); map.put("goodOrBad", goodOrBad); return sqlSession.update("mappers.board.goodOrBad", map); } // 인기글 @Override public List<BoardDTO> best() { return sqlSession.selectList("mappers.board.best"); } // 추천 비추천 로그 @Override public int goodOrBadLog(String type, String num, String id, String goodOrBad) { Map<String,Object> map = new HashMap<>(); map.put("type", type); map.put("num", num); map.put("id", id); map.put("count_type", goodOrBad); return sqlSession.update("mappers.board.goodOrBadLog", map); } } <file_sep>package com.kh.myapp.board.service; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.ui.Model; import com.kh.myapp.board.dto.BoardDTO; import com.kh.myapp.board.dto.CntLog; import com.kh.myapp.product.dto.filesDTO; public interface BoardSvc { // 글작성 public int write(BoardDTO boardDTO); public boolean insertInsertedFile(filesDTO filesdto); // 글수정 public boolean modify(BoardDTO boardDTO); // 글삭제 public boolean delete(String bnum); // 글보기 public BoardDTO view(String bnum); // 추천 비추천 public int goodOrBad(String bnum, String goodOrBad); // 인기글 public List<BoardDTO> best(); // 조회수 로그 public void hitLog(String type, int bnum, String id); // 추천 비추천 로그 public int goodOrBadLog(String type, String num, String id, String goodOrBad); // 글목록 public List<BoardDTO> list(); public List<BoardDTO> list(int startRec, int endRec, String best); // 게시글 총계 public int totalRec(); // 검색목록 public List<BoardDTO> searchList(int startRecord, int endRecord, String searchType, String keyword); void list(HttpServletRequest request, Model model); void getMyList(HttpServletRequest request, Model model); // 검색 총계 public int searchTotalRec(String searchType, String keyword); } <file_sep>package com.kh.myapp.member.dto; import lombok.Data; @Data public class LoginMessage { private boolean isSuccess; private String Message; } <file_sep>package com.kh.myapp.product.dto; import java.sql.Timestamp; import lombok.Data; @Data public class RproductDTO { private int rnum; private int pnum; private String id; private String nickname; private Timestamp cdate; private Timestamp udate; private String content; } <file_sep>package com.kh.myapp.util; import java.util.ArrayList; public class storeData { public ArrayList<String> getStoreList() { ArrayList<String> sibal = new ArrayList<>(); sibal.add("CU"); sibal.add("GS25"); sibal.add("세븐일레븐"); sibal.add("이마트24"); sibal.add("MINISTOP"); sibal.add("스토리웨이"); sibal.add("개그스토리"); sibal.add("씨스페이스"); sibal.add("로그인"); return sibal; } public ArrayList<String> getProductList() { ArrayList<String> sibal = new ArrayList<>(); sibal.add("김밥"); sibal.add("삼각김밥"); sibal.add("라면"); sibal.add("도시락"); sibal.add("젤리"); sibal.add("초콜릿"); sibal.add("아이스크림"); sibal.add("음료"); sibal.add("주류"); sibal.add("휴지"); sibal.add("핫도그"); sibal.add("샌드위치"); sibal.add("햄버거"); sibal.add("피자"); sibal.add("치킨"); sibal.add("빵류"); sibal.add("토스트"); sibal.add("두부"); sibal.add("도너츠"); return sibal; } } <file_sep>package com.kh.myapp.member.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import org.springframework.ui.Model; import com.kh.myapp.board.dto.BoardDTO; import com.kh.myapp.member.dto.MemberDTO; @Repository public class MemberDAOImplXML implements MemberDAO { private static Logger logger = LoggerFactory.getLogger(MemberDAOImplXML.class); @Inject SqlSession sqlSession; // 회원가입 @Override public boolean insert(MemberDTO memberDTO) { logger.info("MemberDAOImplXML.insert 호출됨"); boolean success = false; int cnt = sqlSession.insert("mappers.member.memberInsert", memberDTO); if(cnt > 0) { success = true; } return success; } // 회원 정보 수정 @Override public boolean modify(MemberDTO memberDTO) { logger.info("MemberDAOImplXML.modify 호출됨"); boolean success = false; int cnt = sqlSession.update("mappers.member.memberUpdate", memberDTO); if(cnt > 0) { success = true; } return success; } // 회원 탈퇴 @Override public boolean delete(String id, String pw) { logger.info("MemberDAOImplXML.delete 호출됨"); boolean success = false; Map<String,String> map = new HashMap<>(); map.put("id", id); map.put("pw", pw); int cnt = sqlSession.delete("mappers.member.memberDelete", map); if(cnt > 0) { success = true; } return success; } // 회원 조회 @Override public MemberDTO getMember(String id) { logger.info("MemberDAOImplXML.getMember 호출됨"); MemberDTO memberDTO = null; memberDTO = sqlSession.selectOne("mappers.member.memberSelectOne", id); return memberDTO; } // 회원 목록 조회 @Override public List<MemberDTO> getMemberList() { List<MemberDTO> list = null; list = sqlSession.selectList("mappers.member.memberSelectList"); return list; } // 회원 활동 정지 @Override public boolean memberDenied(MemberDTO memberDTO) { logger.info("MemberDAOImplXML.memberDenied 호출됨"); boolean success = false; int cnt = sqlSession.update("mappers.member.memberDenied", memberDTO); if(cnt > 0) { success = true; } return success; } // 회원 목록 요청페이지 @Override public List<MemberDTO> list(int startRec, int endRec) throws Exception { Map<String,Object> map = new HashMap<>(); map.put("startRec", startRec); map.put("endRec", endRec); return sqlSession.selectList("mappers.member.list", map); } // 회원 검색 목록 @Override public List<MemberDTO> flist(int startRecord, int endRecord, String searchType, String keyword) throws Exception { Map<String,Object> map = new HashMap<>(); map.put("startRecord", startRecord); map.put("endRecord", endRecord); map.put("searchType", searchType); map.put("keyword", keyword); return sqlSession.selectList("mappers.member.flist", map); } // 회원 총계 @Override public int totalRec() throws Exception { return sqlSession.selectOne("mappers.member.totalRec"); } // 검색 총계 @Override public int searchTotalRec(String searchType, String keyword) throws Exception { Map<String,Object> map = new HashMap<>(); map.put("searchType", searchType); map.put("keyword", keyword); return sqlSession.selectOne("mappers.member.searchTotalRec", map); } } <file_sep>package com.kh.myapp.product.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.apache.ibatis.session.SqlSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import com.kh.myapp.board.dao.RboardDAOImplXML; import com.kh.myapp.product.dto.RproductDTO; @Repository(value="RproductDAOImplXML") public class RproductDAOImplXML implements RproductDAO { private static Logger logger = LoggerFactory.getLogger(RboardDAOImplXML.class); @Inject SqlSession sqlsession; //댓글 등록 @Override public int write(RproductDTO rpDTO) throws Exception { return sqlsession.insert("mappers.rproduct.write", rpDTO); } //댓글 목록 @Override public List<RproductDTO> list(String pnum) throws Exception { return sqlsession.selectList("mappers.rproduct.listOld", pnum); } @Override public List<RproductDTO> list(String pnum, int startRec, int endRec) throws Exception { Map<String,Object> map = new HashMap<>(); map.put("pnum", pnum); map.put("startRec", startRec); map.put("endRec", endRec); return sqlsession.selectList("mappers.rproduct.list", map); } //댓글 수정 @Override public int modify(RproductDTO rpDTO) throws Exception { return sqlsession.update("mappers.rproduct.modify", rpDTO); } //댓글 삭제 @Override public int delete(String rnum) throws Exception { return sqlsession.delete("mappers.rproduct.delete", rnum); } //댓글 총계 @Override public int replyTotalRec(String pnum) throws Exception { int cnt = 0; cnt = sqlsession.selectOne("mappers.rproduct.replyTotalRec", pnum); return cnt; } } <file_sep>package com.kh.myapp.util; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.util.Base64; import javax.xml.bind.DatatypeConverter; public class binaryEncryptor { public static String toHex(String arg) { return String.format("%040x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/))); } public static String binToHex(String s) { return new BigInteger(s, 2).toString(16); } public static String hexToBin(String s) { return new BigInteger(s, 16).toString(2); } public static String octToStr(String s) { return new BigInteger(s, 16).toString(10); } public static String strToOct(String s) { return new BigInteger(s, 10).toString(16); } public static String fromHex(String hex) throws UnsupportedEncodingException { hex = hex.replaceAll("^(00)+", ""); byte[] bytes = DatatypeConverter.parseHexBinary(hex); return new String(bytes, "UTF-8"); } public static String Decrypt(String plainText) { plainText = plainText.replaceAll("_", "-"); plainText = plainText.replaceAll("-", "/"); byte[] plainByte = Base64.getDecoder().decode(plainText.getBytes()); plainText = new String(plainByte); if (plainText.isEmpty()) return ""; plainText = octToStr(plainText); String bytes = ""; String queue = makePrefix(plainText, "Decrypt"); queue = queue(queue, "Decrypt"); String hexStr = binToHex(queue); try { bytes = fromHex(hexStr); return bytes; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return bytes; } public static int binaryStringToDecimal(String biString){ int n = biString.length(); int decimal = 0; for (int d = 0; d < n; d++){ // append a bit=0 (i.e. shift left) decimal = decimal << 1; // if biStr[d] is 1, flip last added bit=0 to 1 if (biString.charAt(d) == '1'){ decimal = decimal | 1; // e.g. dec = 110 | (00)1 = 111 } } return decimal; } public static int getBitCount(int i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); int xs = (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; return xs; } public static int getC64(int a, int b, int c, int d, int v, int r) { // Do a normal parallel bit count for a 64-bit integer, // but store all intermediate steps. // a = (v & 0x5555...) + ((v >> 1) & 0x5555...); a = v - ((v >> 1) & ~ 0xffffffff /3); // b = (a & 0x3333...) + ((a >> 2) & 0x3333...); b = (a & ~0xffffffff/5) + ((a >> 2) & ~0xffffffff/5); // c = (b & 0x0f0f...) + ((b >> 4) & 0x0f0f...); c = (b + (b >> 4)) & ~0xffffffff/0x11; // d = (c & 0x00ff...) + ((c >> 8) & 0x00ff...); d = (c + (c >> 8)) & ~0xffffffff/0x101; int t = (d >> 32) + (d >> 48); // Now do branchless select! int s = 64; if (r > t) {s -= 32; r -= t;} s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8)); t = (d >> (s - 16)) & 0xff; if (r > t) {s -= 16; r -= t;} s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8)); t = (c >> (s - 8)) & 0xf; if (r > t) {s -= 8; r -= t;} s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8)); t = (b >> (s - 4)) & 0x7; if (r > t) {s -= 4; r -= t;} s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8)); t = (a >> (s - 2)) & 0x3; if (r > t) {s -= 2; r -= t;} s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8)); t = (v >> (s - 1)) & 0x1; if (r > t) s--; s -= ((t - r) & 256) >> 8; s = 65 - s; return s; } public static String Encrypt(String plainText) { String hex = toHex(plainText); String bin = hexToBin(hex); int i = binaryStringToDecimal(bin); int isAccepted = ((i >> 4) % 6); System.out.println(isAccepted); if (isAccepted == 0 || isAccepted == 2) return ""; if (isAccepted < 0) return ""; String queue = queue(bin, "Encrypt"); queue = makePrefix(queue, "Encrypt"); queue = strToOct(queue); String encoded = Base64.getEncoder().encodeToString(queue.getBytes()); encoded = encoded.replaceAll("-", "_"); encoded = encoded.replaceAll("/", "-"); return encoded; } public static String makePrefix(String plainBin, String Mode) { String Result = null; switch (Mode) { case "Encrypt": Result = makePrefixEncrypt(plainBin); break; case "Decrypt": Result = makePrefixDecrypt(plainBin); break; default: break; } return Result; } protected static String makePrefixDecrypt(String plainBin) { String carry; String result = ""; int length; length = plainBin.length(); if (plainBin.substring(0, 1) == "0") { carry = plainBin.substring(1,2); result = new StringBuilder(plainBin).replace(1, 2, carry).toString(); result = new StringBuilder(result).replace(length - 1, length, carry).toString(); } if (result.isEmpty()) { return plainBin; } return result; } protected static String makePrefixEncrypt(String plainBin) { String result = ""; int length; length = plainBin.length(); if (length > 1 && plainBin.substring(0, 1) == plainBin.substring(length -1,length)) { result = "0" + plainBin.substring(0 ,1) + plainBin.substring(1, length - 1); } if (result.isEmpty()) { return plainBin; } return result; } protected static String queueDecrypt(String plainBin) { int length; int intVal; String result = ""; length = plainBin.length(); for (int i=0;i < length;i++) { // Get bit count intVal = Integer.parseInt(plainBin.substring(i, i+1)); // Count count to bit result += (intVal > 5) ? repeat("0", intVal - 5) : repeat("1", intVal); } return result; } public static String repeat(String str, int times) { return new String(new char[times]).replace("\0", str); } /* * Get binary bit count order by bit boolean (110001001 -> 28171) * FALSE => (5 + bit count) */ protected static String queueEncrypt(String plainBin) { String sStr = ""; int intVal = 0; int tmpVal = 0; int intBool; int length; intBool = -1; length = plainBin.length(); // Loop in bit for(int i=0;i <= length; i++) { if (i == length) { // Append last bit count String Prefix = (intBool == 0) ? Integer.toString(5 + tmpVal) : Integer.toString(tmpVal); sStr += Prefix; }else { // Get a bit intVal = Integer.parseInt(plainBin.substring(i, i + 1)); } if (intBool == -1) { // Set bit boolean type intBool = intVal; } else if ( (tmpVal > 3 && intVal == intBool) || (intVal != intBool) ) { /* * Append bit count * TRUE => (bit count) * FALSE => (5 + bit count) */ String Prefix = (intBool == 0) ? Integer.toString(5 + tmpVal) : Integer.toString(tmpVal); sStr += Prefix; // Empty bit count tmpVal = 0; // Set bit boolean type if (intVal != intBool) { intBool = intVal; } } // Count bit count ++tmpVal; } return sStr; } public static String intersect(String plainBin) { int carry; int length = plainBin.length(); int halfLength = (plainBin.length() / 2); String tmpVal; String result = ""; Float len = new Float(halfLength); for(int i=0;i<=len;i++) { carry = i % 2; if (carry == 1) { tmpVal = plainBin.substring(i, i+1); String replacementStr = plainBin.substring(length - 1, length); result = new StringBuilder(plainBin).replace(i, i + 1, replacementStr).toString(); result = new StringBuilder(plainBin).replace(i, i + 1, tmpVal).toString(); } } return result; } public static String queue(String plainBin, String Mode) { String Result = null; switch (Mode) { case "Encrypt": Result = queueEncrypt(plainBin); break; case "Decrypt": Result = queueDecrypt(plainBin); break; default: break; } return Result; } public static String ascii2hex(String ascii) { char[] ch = ascii.toCharArray(); StringBuilder builder = new StringBuilder(); for (char c : ch) { int i = (int) c; builder.append(Integer.toHexString(i).toUpperCase()); } return builder.toString(); } } <file_sep>package com.kh.myapp.product.dto; import java.io.File; import java.io.IOException; import java.sql.Date; import java.text.NumberFormat; import java.util.Locale; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import com.kh.myapp.util.Resizer; import com.kh.myapp.util.SecureLink; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ProductDTO { @Autowired ServletContext context; private int startRecord; private int endRecord; // Left Join private int target_srl; private String type; private String sourcename; private String originname; private char ptype; private int idx; private int pnum; private String pname; private String ptitle; private String pid; private String pnickname; private Date pcdate; private Date pudate; private int pgood; private int pbad; private int phit; private String pcontent; private String pgroup; private String pstore; private int price; private int regdate; private String allergy; public String getLink() { return "/product/view/" + pnum; } public String getImage() { if (sourcename == null) { return "".toString(); } else { int timeout = 5000; String uploadedImage = "/resources/upload/" + sourcename; String key = "34x378"; String plainKey = uploadedImage; String prefix = SecureLink.get(key, plainKey, timeout); return uploadedImage + "?t=" + prefix + "&c=" + timeout; } } public String getTitle() { if (ptitle == null) { return "제목없음"; } else { String title = null; if (ptitle.length() > 30) { title = ptitle.substring(0, 27) + "..."; } else { title = ptitle; } if (pgroup != null) { title = "[" + pgroup + "] " + title; } return title; } } public String getContent() { if (pcontent == null) { return "내용없음"; } else { String content = null; if (pcontent.length() > 50) { content = pcontent.substring(0, 47) + "..."; } else { content = pcontent; } return content; } } public ProductDTO(char ptype, int pnum, String pname, String ptitle, String pid, String pnickname, Date pcdate, Date pudate, int pgood, int pbad, int phit, String pcontent, String pgroup, String pstore, int price, int regdate, String allergy) { this.ptype = ptype; this.pnum = pnum; this.pname = pname; this.ptitle = ptitle; this.pid = pid; this.pnickname = pnickname; this.pcdate = pcdate; this.pudate = pudate; this.pgood = pgood; this.pbad = pbad; this.phit = phit; this.pcontent = pcontent; this.pgroup = pgroup; this.pstore = pstore; this.price = price; this.regdate = regdate; this.allergy = allergy; } } <file_sep>package com.kh.myapp.util; public class fileUploader { } <file_sep>package com.kh.myapp.member.service; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.ui.Model; import com.kh.myapp.board.dto.BoardDTO; import com.kh.myapp.member.dto.MemberDTO; public interface MemberSvc extends UserDetailsService{ // 회원가입 public boolean insert(MemberDTO memberDTO); // 회원 정보 수정 public boolean modify(MemberDTO memberDTO); // 회원 탈퇴 public boolean delete(String id, String pw); // 회원 조회 public MemberDTO getMember(String id); // 회원 목록 조회 public List<MemberDTO> getMemberList(); List<MemberDTO> list(int startRec, int endRec) throws Exception; // 회원 활동 정지 public boolean memberDenied(MemberDTO memberDTO); void list(HttpServletRequest request, Model model) throws Exception; // 회원 검색 목록, 페이징 List<MemberDTO> flist(int startRecord, int endRecord, String searchType, String keyword) throws Exception; // 회원 총계 int totalRec() throws Exception; // 회원 검색 총계 int searchTotalRec(String searchType, String keyword) throws Exception; }
cb8051c0d666d1208535a04f7827ff40f778720a
[ "Markdown", "Java" ]
22
Java
taehyeongkimme/spring-team-project
5f164ed21c219e665d90b82fc22c797613f04eb5
aafa03e80512e816037d26ae595cb66be82bf3e4
refs/heads/master
<repo_name>yhammoud/geneh-server<file_sep>/app/controllers/api_controller.rb class ApiController < ApplicationController require 'money' require 'monetize' require 'money/bank/google_currency' require 'net/http' require 'certified' def get_exchange_rate Money.default_bank = Money::Bank::GoogleCurrency.new dollar = 1.to_money(:USD) @geneh = dollar.exchange_to(:EGP).to_f render json: @geneh end Thread.new() do while true Money.default_bank = Money::Bank::GoogleCurrency.new dollar = 1.to_money(:USD) @geneh = dollar.exchange_to(:EGP).to_f if Rate.last.nil? Rate.create(rate: @geneh) else last = Rate.last.rate if last > @geneh diff = (last - @geneh).to_f @text = "USD-EGP currency exchange rate is now %.2f, it has decreased by %.2f" %[@geneh, diff] @rate = Rate.last @rate.update(rate: @geneh) @rate.save! parameters = { "app_id" => "154d00fa-354b-4bba-a55b-9715f13b856d", "contents" => { "en" => @text}, "included_segments" => ["All"] } # RestClient.post("https://onesignal.com/api/v1/notifications", parameters.to_json, :content_type => :json, :accept => :json) uri = URI.parse('https://onesignal.com/api/v1/notifications') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json', 'Authorization' => "Basic ZTYyNzRiODgtMDYxYi00NGJjLTg3ZjAtMTdmNWFhMzhkNmY1") request.body = parameters.as_json.to_json response = http.request(request) puts response.body elsif last < @geneh diff = (@geneh - last).to_f @text = "USD-EGP currency exchange rate is now %.2f, it has increased by %.2f" %[@geneh, diff] @rate = Rate.last @rate.update(rate: @geneh) @rate.save! parameters = { "app_id" => "154d00fa-354b-4bba-a55b-9715f13b856d", "contents" => { "en" => @text}, "included_segments" => ["All"] } # RestClient.post("https://onesignal.com/api/v1/notifications", parameters.to_json, :content_type => :json, :accept => :json) uri = URI.parse('https://onesignal.com/api/v1/notifications') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json', 'Authorization' => "Basic ZTYyNzRiODgtMDYxYi00NGJjLTg3ZjAtMTdmNWFhMzhkNmY1") request.body = parameters.as_json.to_json response = http.request(request) puts response.body end end sleep 30 end end end <file_sep>/config/routes.rb Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html root to: 'api#get_exchange_rate' get '/api/exchange_rate' => 'api#get_exchange_rate' get '/notifications/new' => 'notifications#new' post '/notifications/push' => 'notifications#push' end <file_sep>/app/controllers/notification_controller.rb class NotificationController < ApplicationController require 'net/http' require 'certified' def new end def push # if rate increased text = "" # if rate decreased text = params["notification_text"] parameters = { "app_id" => "0129211f-1969-4f48-9705-c4a2de2017ef", "contents" => { "en" => text}, "included_segments" => ["All"] } # RestClient.post("https://onesignal.com/api/v1/notifications", parameters.to_json, :content_type => :json, :accept => :json) uri = URI.parse('https://onesignal.com/api/v1/notifications') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json', 'Authorization' => "Basic YjRkZDY3N2QtOTIyYy00OTQ2LTgzM2EtOTY5NjJmZDkyOGNh") request.body = parameters.as_json.to_json response = http.request(request) puts response.body end end
9e4aa74e4b2e29bce21893188a7f8b6b7e0939cb
[ "Ruby" ]
3
Ruby
yhammoud/geneh-server
1870befef58ee2ec930267aa9c72234163098ca0
dbf9b05f4753467d0260453f31f086b42b364029
refs/heads/master
<repo_name>kabragaurav/Practice-C-CPP-Python-OOPS-DSA<file_sep>/OOPS/2/Solutions/2.cpp #include<iostream> using namespace std; class Student { private: char *correct; public: Student() { correct = new char[8]; correct[0] = 'C';correct[1] = 'A';correct[2] = 'B';correct[3] = 'D'; correct[4] = 'B';correct[5] = 'C';correct[6] = 'C';correct[7] = 'A'; } void getResult(char response[]) { int corr =0 , unanswered=0; for(int i=0;i<8;i++) { if(response[i]=='X') unanswered++; else if(response[i]==correct[i]) corr++; } cout<<"QUESTION "<<"reponse "<<"Correct "<<"Result "<<endl; for(int i=0;i<8;i++) { cout<<i<<" "<<response[i]<<" "<<correct[i]<<" "<<(response[i]==correct[i]?"Correct":(response[i]=='X'?"Unanswered":"Wrong"))<<endl; } cout<<"Correct ans "<<corr<<" wrong "<<8-corr-unanswered<<" unans "<<unanswered<<endl; } }; int main() { Student s; char resp[8]; cout<<"Enter response\n"; for(int i=0;i<8;i++) { cin>>resp[i]; } s.getResult(resp); } <file_sep>/OOPS/3/Solutions/SecondFifthAssignment.java /** A method named add () accepts an array of strings as its argument. It converts these to db values and returns their sum. The method generates a NumberFormatExeption if an element is incorrectly formatted. It can also throw and create a CustomException, RangeException, if an element is less than 0 or greater than 1.Write a program that illustrates how to declare and use this method. Invoke the method from main ().Catch any exceptions that are thrown and display an informative message for the user. Also provide a finally block to thank the user for using the program. */ class RangeException extends Throwable{ } class SecondFifthAssignment extends Exception{ static void add(String[] args){ Double sum = 0.0; Double db = 0.0; try{ for(int i=0;i<args.length;i++){ db = Double.parseDouble(args[i]); if(db<0.0 || db >1.0){ throw new RangeException(); } sum += db; } System.out.println(sum); } catch(NumberFormatException nfe){ System.out.println("nfe thrown"); } catch(RangeException re){ System.out.println("re thrown"); } finally { System.out.println("Thanks for using"); } } public static void main(String [] args){ add(args); } }<file_sep>/OOPS/1/Solutions/4.py from collections import defaultdict dc = defaultdict(float) class List: def __init__(self): self.ls = [int(x) for x in input().split()] self.k = int(input()) def process(self): for x in self.ls: dc[x] += 1 for key in list(dc.keys()): x = key diff = self.k-x if dc[diff]: print(True) print("Numbers are ",x," and ",diff) break else: print(False) l = List() l.process() ''' ELSE sort() and use binary search using namespace std; int main() { //code int T; cin>>T; while(T--) { int N,diff; cin>>N>>diff; vector<int> v; int num; for(int i=0;i<N;i++) { cin>>num; v.push_back(num); } bool flag=false; sort(v.begin(),v.end()); for(int i=0;i<=N-1;i++) { int x=v[i]; int next=diff-x; if(binary_search(v.begin()+i+1,v.end(),next)) { flag=true; cout<<"Yes"<<endl; break; } } if(flag==false) cout<<"No"<<endl; } return 0; } ''' <file_sep>/OOPS/4/Solutions/Amicable.py ''' Write a program in Java and Python to check whether two numbers are amicable or not. Both the number are generated by separate thread name of this thread is CSA and CSB. Amicable Number If two numbers are such that the sum of the perfect divisors of one number is equal to the other number and the sum of the perfect divisors of the other number is equal to the first number, then the numbers are called Amicable Numbers. The first few amicable pairs are: (220, 284), (1184, 1210), (2620, 2924), (5020, 5564), (6232, 6368) ''' import threading sum1,sum2 = 0,0 def amicable(num): sum = 0 for i in range(1,num): #starts from 0 if not mention 1 if num%i == 0: sum += i return sum def CS(lk,num): global sum1,sum2 lk.acquire() sum = amicable(num) if sum1 == 0: sum1 = sum else: sum2 = sum lk.release() lk = threading.Lock() x,y = [int(z) for z in input().split()] t1 = threading.Thread(target = CS, args = (lk,x)) t2 = threading.Thread(target = CS,args = (lk,y)) t1.start() t2.start() t1.join() t2.join() if sum1 == y and sum2 == x: print('amicable') else: print('unamicable') <file_sep>/OOPS/5/Solutions/2.java class Bank { public double deposit(double amount, double balance) { return amount+balance; } public double withdraw(double amount, double balance) { if(balance >= amount) return balance-amount; return 0.0; } } public class Main { public static void main(String [] args) { Bank b = new Bank(); System.out.println(b.deposit(99.99,00.01)); System.out.println(b.withdraw(99.99,00.01)); System.out.println(b.withdraw(00.01,99.99)); } }<file_sep>/OOPS/5/Solutions/4.py ''' We need to write the function to check the password entered is correct or not based on the following conditions. a) It must have atleast one lower case character and one digit. b) It must not have any Upper case characters and any special characters #c) length should be b/w 5-12. d) It should not have any same immediate patterns like abcanan1 : not acceptable coz of an an pattern abc11se: not acceptable, coz of pattern 11 123sd123 : acceptable, as not immediate pattern adfasdsdf : not acceptable, as no digits Aasdfasd12: not acceptable, as have uppercase character ''' while True: passwd = input('Password: ') lowBit = False digBit = False if len(passwd) < 5 and len(passwd) > 12: print('not accepted') continue for ch in passwd: if ch.isupper() or ch in ['~', ':', "'", '+', '[', '\\', '@', '^', '{', '%', '(', '-', '"', '*', '|', ',', '&', '<', '`', '}', '.', '_', '=', ']', '!', '>', ';', '?', '#', '$', ')', '/']: print('not accepted') continue if ch.islower(): lowBit = True elif ch.isdigit(): digBit = True if digBit == False or lowBit == False: print('not accepted') continue br = False for i in range(len(passwd)-1): for j in range(i,len(passwd)): #from i onwards pre = passwd[i:j+1] post = passwd[j+1:] ''' The index() method is similar to find() method for strings. The only difference is that find() method returns -1 if the substring is not found, whereas index() throws an exception. ''' if post.find(pre) == 0: print('not accepted : repeat',pre) br = True break if br == True: break <file_sep>/OOPS/3/Solutions/Chain.java /** Create a class that has static method main(),a(),b(),c() and d().The main() method invokes a() method a() invokes b(),method b() invokes c(),method c() invokes d().Method d() declares a local array with 10 elements and then attempts to access the element at position .therefore an ArrayIndexOutOfBoundsException is generated. Each method has a catch block for this type of exception and a finally block .The catch blocks in c() and d() contain a throw statement to propagate this exception to their caller. */ class Chain extends Exception{ static void a(){ try{ b(); } catch(ArrayIndexOutOfBoundsException aiobe){ } finally{ System.out.println("a() called"); } } static void b(){ try{ c(); } catch(ArrayIndexOutOfBoundsException aiobe){ throw aiobe; } finally{ System.out.println("b() called"); } } static void c(){ try{ d(); } catch(ArrayIndexOutOfBoundsException aiobe){ throw aiobe; } finally{ System.out.println("c() called"); } } static void d(){ int[] arr = {1,2,3,4,5,6,7,8,9,0}; try{ int t = arr[10]; } catch(ArrayIndexOutOfBoundsException aiobe){ throw aiobe; } finally{ System.out.println("d() called"); } } public static void main(String [] args){ try{ a(); } catch(ArrayIndexOutOfBoundsException aiobe){ } finally{ System.out.println("main() called"); } } }<file_sep>/OOPS/2/Solutions/p1_alternate_solution.java import java.util.*; class find{ static void maxRepeat(String s){ HashMap<Character, Integer> mp = new HashMap<Character, Integer>(); char[] s1 = s.toCharArray(); for (char c : s1) { if (mp.containsKey(c)){ mp.put(c, mp.get(c) + 1); } else{ mp.put(c, 1); } } System.out.println("Frequencies::"); for (Map.Entry entry : mp.entrySet()) { System.out.printlney() + " " + e(entry.getKntry.getValue()); } } } class p1{ public static void main(String[] args){ String s; char res; System.out.print("Enter String::"); Scanner scan=new Scanner(System.in); s=scan.nextLine(); find obj=new find(); obj.maxRepeat(s); } } <file_sep>/OOPS/5/Solutions/1.py class Product: def __init__(self): self.ProductID = 0 self.categoryID = 0 self.unitPrice = 0 class ElectricalProduct(Product): def __init__(self): super() voltageRange = 0 wattage = 0 def changer(self,wattage = 0, unitPrice = 0): self.wattage = wattage self.unitPrice = unitPrice def disp(self): return str(self.wattage)+" "+str(self.unitPrice) e = ElectricalProduct() e.changer(8,3.4) print(e.disp()) <file_sep>/OOPS/1/Solutions/1.cpp #include<iostream> using namespace std; class Data { int day,month,year; public: Data() { day = 12; month = 3; year = 1993; } Data(int day = 12,int month = 10,int year = 2000) { cout<<"Parameterised with default args\n"; this->day = day; this->month = month; this->year = year; } Data(const Data &data) { cout<<"Copy constructor\n"; day = data.day; month = data.month; year = data.year; } void showData() { cout<<this->day<<" "<<this->month<<" "<<this->year<<endl; } }; int main() { Data d2(9,9,1999); Data d3 = d2; d3.showData(); } <file_sep>/README.md # Author : <NAME> ## About This repository has been created to collect major study material references I referred to during my learning journey in C, C++, Java and Python under one roof. It also contains the material related to Object Oriented Programming (OOPS) and Data Structures & Algorithms(DSA).<br> Not all material is created by me but the codes are all mine. You might find a better approach or even a bug! I would be happy in that case if you contribute to the betterment of this repository by pointing this out.<br> Most material I studied in my 1st year has been lost as in those days I did not use to save each and every work. But whatever is there with me and is worth sharing is here now.<br> I welcome you to further add your articles.<br> ##### Note On Linux, odt files are supported. On Windows use Wordpad for opening and DONOT convert odt to docx. <file_sep>/OOPS/3/Solutions/Series.java /** Program calculates the sin(x) and cos(x) functions by computing the sin series and cos series functions using thread techniques. (sin(x) and cos(x) calculate using Math class). */ import java.util.*; import java.util.Scanner; class Series extends Thread{ void sine(double d1){ System.out.println(Math.sin(d1)); } void cosine(double d2){ System.out.println(Math.cos(d2)); } public void run(){ System.out.println("Enter x"); Scanner sc = new Scanner(System.in); double d = sc.nextDouble(); sine(d); cosine(d); } public static void main(String[] args){ Thread t = new Thread(new Series()); t.start(); try{ t.join(); } catch(Exception ex){} } } <file_sep>/OOPS/2/Solutions/stack-infix-parenth.cpp //evaluate fully parenthesized infix expr #include<iostream> #include<stack> #include<string> using namespace std; int main() { string str; cin>>str; stack<string> stk; for(int i=0;i<str.size();i++) { if(str[i]!=')') { //push stk.push(string(1,str[i])); } else { string b = stk.top(); stk.pop(); char oper = stk.top()[0]; stk.pop(); string a = stk.top(); stk.pop(); stk.pop(); int x = stoi(a); int y = stoi(b); switch(oper) { case '+': stk.push(to_string(a+b)); break; case '-': stk.push(to_string(a-b)); break; case '*': stk.push(to_string(a*b)); break; case '/': stk.push(to_string(a/b)); break; } } } cout<<stk.top(); } <file_sep>/OOPS/2/Solutions/4.py print(eval(input('Enter expression\n'))) <file_sep>/OOPS/1/Solutions/Student.java import java.util.Scanner; class Student { private int admno; private String Name; private float marksEng,marksMaths,marksSci,total; public void readData() { System.out.println("Enter admNo,name,3 subject marks"); Scanner sc = new Scanner(System.in); admno = sc.nextInt(); Name = sc.next(); if(Name.length() >20) Name = Name.substring(0,20); marksEng = sc.nextFloat(); marksMaths = sc.nextFloat(); marksSci = sc.nextFloat(); compute(); } public void compute() { total = marksEng+marksMaths+marksSci; } public void showData() { System.out.println("The data values..."); System.out.println(admno+" "+Name+" "+total); } } <file_sep>/OOPS/2/Solutions/Main.java import java.util.Scanner; class Player { String team,name; int globalSum; int score[]; static String highest; Player(String team,String name) { this.team = team; this.name = name; highest = ""; globalSum=0; score = new int[5]; } void getScore() { System.out.println("Enter 5 scores"); int sum = 0; Scanner sc= new Scanner(System.in); for(int i=0;i<5;i++) { score[i] = sc.nextInt(); sum += score[i]; } if(globalSum<sum) { globalSum = sum; highest = name; } System.out.println("TOTAL : "+sum+" AVG : "+sum/5.0); } static void high() { System.out.println(highest); } } public class Main { public static void main(String [] args) { for(int i=0;i<2;i++) { System.out.println("Enter details of players"); String team,name; Scanner sc = new Scanner(System.in); team = sc.next(); name = sc.next(); Player p = new Player(team,name); p.getScore(); } Player.high(); } } <file_sep>/OOPS/1/Solutions/3.cpp #include<iostream> #include<algorithm> using namespace std; class Student { private: int rollno; string Name; float marks[4]; float grade; public: void calculate() { cout<<"%\\ge marks : "; grade = (marks[0]+marks[1]+marks[2]+marks[3])/4.0; displayData(); } void readData() { again: cout<<"Enter rollno,name,4 subject marks\n"; cin>>rollno>>Name>>marks[0]>>marks[1]>>marks[2]>>marks[3]; if(Name.length()>20) goto again; calculate(); } void displayData() { cout<<"Details...\n"; cout<<rollno<<" "<<Name<<" "<<grade<<endl; } string getName() { return this->Name; } void sortStudents(Student stu[],int strength) { sort(stu,stu+strength,sortNow); } static bool sortNow(Student &a, Student &b) { return a.getName()<b.getName(); } }; int main() { int strength; cout<<"How many students?\n"; cin>>strength; Student stu[strength]; for(int i=0;i<strength;i++) { stu[i].readData(); } stu[0].sortStudents(stu,strength); cout<<"After sorting...\n"; for(int i=0;i<strength;i++) { stu[i].displayData(); } } <file_sep>/OOPS/1/Solutions/copy constructor.py ''' Like we used comparator fn in C++ for sort() as III argument in Python it is key keyword field ''' class I: def __init__(self): pass def __init__(self,name="",marks=""): self.name = name self.marks = marks def display(self): print(self.name,self.marks) print("How many objects?") num = int(input()) ls = [] for i in range(num): name = input("Name... ") marks = float(input("Marks... ")) ls.append(I(name,marks)) for item in ls: item.display() ls.sort(key = lambda x : x.name) for item in ls: item.display() <file_sep>/OOPS/4/Solutions/FatherSon.cpp #include<thread> #include<iostream> #include<unistd.h> using namespace std; int balance = 600; bool valueSet = false; void deposite(){ srand(time(0)); while(true){ while(valueSet); while(balance<=2000){ int r = rand()%200+1; balance += r; cout<<"Father : "<<r<<endl; sleep(1); } cout<<"-------- BALANCE : "<< balance <<" ----------\n"; valueSet = true; sleep(2); } } void withdraw(){ srand(time(0)); while(true){ while(!valueSet); while(balance>=500){ int r = rand()%150+1; balance -= r; cout<<"Son : "<<r<<endl; sleep(1); } cout<<"-------- BALANCE : "<< balance <<" ----------\n"; valueSet = false; sleep(2); } } int main(){ thread father(deposite); thread son(withdraw); father.join(); son.join(); } <file_sep>/OOPS/2/Solutions/1.cpp #include<iostream> #include<vector> #include<string> #include<utility> #include<algorithm> using namespace std; bool mySort(pair<char,int> &a,pair<char,int> &b) { if(a.second==b.second) return a.first<b.first; return a.second>b.second; } int main() { string str; getline(cin,str); vector<pair<char,int> > v; for(int i=0;i<26;i++) { v.push_back(make_pair('A'+i,0)); } for(int i=0;i<str.length();i++) { if(str[i]>='A' && str[i]<='Z') { v[str[i]-'A'].second++; } } sort(v.begin(),v.end(),mySort); cout<<v[0].first<<endl; }
23e8b6ca5928aa7c1d2f4f40e3967447e3a9f114
[ "Markdown", "Java", "Python", "C++" ]
20
C++
kabragaurav/Practice-C-CPP-Python-OOPS-DSA
338a032379e939f32e0255ccff01448dc09f66f5
e7f87a626d3d620fdcf05f87e1e747d55bd32e90
refs/heads/master
<file_sep>#include "VisualizacaoBarragem.h" /*! \class VisualizacaoBarragem \previouspage PainelVisualizacaoOpenGL \contentspage \nextpage VisualizacaoMapa \brief Class prototype. Not in use. */ VisualizacaoBarragem::VisualizacaoBarragem(VisualizacaoMapa *viMapa){ proporcaoVisualizacao = 2; //identificar o corte para a visualizacao barragem conter //somente a necessario perante a proporcao int iMinimo,jMinimo,iMaximo,jMaximo; iMinimo = 0; jMinimo = 0; iMaximo = 0; jMaximo = 0; } <file_sep> #include "Inundacao.h" #include <fstream> #include<cstdlib> #include<math.h> #include<QDate> #include <janelaprincipal.h> /*! \class Inundacao \previouspage Fluxo \contentspage \nextpage janelabarragem \startpage All Classes \brief Class to create the resorvoir, with the dam and flooded cells */ /*! \class PontoZ \brief Class to create point to represent a cell */ /*! \variable Inundacao::matrizEstados \brief a pointer to pointer representing the matrix of states of cell. If cell are dam, flooded, drainage network or nothing */ /*! \variable Inundacao::posicaoBarragem \brief a cell representing by a point to identify the dam position */ /*! \variable Inundacao::posicaoBarragem \brief a cell representing by a point to identify the the position downstream the dam position */ /*! \variable Inundacao::vetorNormalABarragem \brief a point to describe the final point of the dam`s normal vector. The start point is the dam position. with this point we can calculate the direction of the dam use simple math calcs. */ /*! \variable Inundacao::nLinhas \brief the number of lines of MDE */ /*! \variable Inundacao::nColunas \brief the number of columns of MDE */ /*! \variable Inundacao::tamanhoMaximoDaBarragem \brief the maximum value of dam extent. Its not used in the algorithm yet */ /*! \variable Inundacao::volumeAgua \brief the value of current resorvoir`s volume. */ /*! \variable Inundacao::volumeAlvo \brief the value volume required by user to construct the reservoir. */ /*! \variable Inundacao::nivelAgua \brief the value of current high of the water generated by the flooding */ /*! \variable Inundacao::areaLaminaAgua \brief the value of the flooded area in the reservoir */ /*! \variable Inundacao::areaBarragemTocada \brief the value of the area for the dam */ /*! \variable Inundacao::comprimentoBarragemTocada \brief the value of the dam`s extent */ /*! \fn Inundacao::Inundacao(Inundacao const& inundacaoCopia) \brief Copy Constructor. Creates an object receiving attributes from inundacaoCopia */ Inundacao::Inundacao(Inundacao const& inundacaoCopia){ this->nLinhas = inundacaoCopia.nLinhas; this->nColunas = inundacaoCopia.nColunas; //======================================================== //===========Constroi e inicializa matrizes=============== this->matrizEstados = new short int*[nLinhas]; for(int i=0; i<nLinhas; ++i) { matrizEstados[i] = new short int[nColunas]; for(int j=0; j<nColunas ; ++j) matrizEstados[i][j] = inundacaoCopia.matrizEstados[i][j]; } this->visitado = new bool*[nLinhas]; for(int i=0; i<nLinhas; ++i) { visitado[i] = new bool[nColunas]; //Inicializa valores da matriz for(int j=0; j<nColunas; ++j) visitado[i][j] = inundacaoCopia.visitado[i][j]; } //======================================================== //======================================================== //===Inicializa variáveis=== volumeAgua = inundacaoCopia.volumeAgua; areaLaminaAgua = inundacaoCopia.areaLaminaAgua; areaBarragemTocada = inundacaoCopia.areaBarragemTocada; comprimentoBarragemTocada = inundacaoCopia.comprimentoBarragemTocada; nivelAgua = inundacaoCopia.nivelAgua; posicaoBarragem.x = inundacaoCopia.posicaoBarragem.x; posicaoBarragem.y = inundacaoCopia.posicaoBarragem.y; posicaoBarragem.z = inundacaoCopia.posicaoBarragem.z; //Define valores iniciais volumeAlvo = inundacaoCopia.volumeAlvo; tamanhoMaximoDaBarragem = inundacaoCopia.tamanhoMaximoDaBarragem; } /*! \fn Inundacao::~Inundacao() \brief Destructor */ Inundacao::~Inundacao(){ try{ //liberando a memoria apontada pelos ponteiros for(int i = 0; i < nLinhas; i++){ delete []this->matrizEstados[i]; delete []this->visitado[i]; } delete []this->matrizEstados; delete []this->visitado; //previnindo que os ponteiros acessem memoria invalida this->matrizEstados = NULL; this->visitado = NULL; }catch(exception e){ QString erroMsg="Erro no destrutor da classe Inundacao"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } } /*! \fn Inundacao::Inundacao(int linhas, int colunas) \brief Constructor. Creates an object that have only the variables initialized, no reservoir is calculed yet. */ Inundacao::Inundacao(int linhas, int colunas) { this->nLinhas = linhas; this->nColunas = colunas; //======================================================== //===========Constroi e inicializa matrizes=============== this->matrizEstados = new short int*[nLinhas]; for(int i=0; i<nLinhas; ++i) { matrizEstados[i] = new short int[nColunas]; for(int j=0; j<nColunas ; ++j) matrizEstados[i][j] = 1; } this->visitado = new bool*[nLinhas]; for(int i=0; i<nLinhas; ++i) { visitado[i] = new bool[nColunas]; //Inicializa valores da matriz for(int j=0; j<nColunas; ++j) visitado[i][j] = false; } //======================================================== //======================================================== //===Inicializa variáveis=== volumeAgua = 0; areaLaminaAgua = 0; areaBarragemTocada = 0; comprimentoBarragemTocada = 0; nivelAgua = 0; posicaoBarragem.x = -1; posicaoBarragem.y = -1; posicaoBarragem.z = -1; //Define valores iniciais volumeAlvo = 30; tamanhoMaximoDaBarragem = 5; } /*! \fn Inundacao::permiteInundacaoEAumentaBarragem(PontoZ pontoAvaliado) \brief Function used to test if a point pontoAvaliado can be a flooded cell. If this point is in the same direction of the dam, it will grow up. If not the algorithm test if it can be or not a flooded cell. */ bool Inundacao::permiteInundacaoEAumentaBarragem(PontoZ pontoAvaliado){ //posicaoBarragem(p1) barragem fixa, posicaoAcimaBarragem(p2) vizinho mais a jusante do p1, pontoAvaliado(p3) elemento a ser testado //produto escalar produtoEscalar = p1p2.p1p3 // define o angulo entre os dois vetores int produtoEscalar = (vetorNormalABarragem.x)*(pontoAvaliado.x -posicaoBarragem.x) + (vetorNormalABarragem.y)*(pontoAvaliado.y - posicaoBarragem.y); visitado[pontoAvaliado.y][pontoAvaliado.x] = true; //se forem perpendiculares poe barragem no p3, ou seja produtoEscalar = 0 //e aumenta a barragem e retorna falso if(produtoEscalar == 0){ matrizEstados[pontoAvaliado.y][pontoAvaliado.x] = BARRAGEM; comprimentoBarragemTocada++; return false; }else //se produtoEscalar > 0 o angulo entre eles eh < 90 //retorna true //se produto escalar < 90 retorne false return produtoEscalar>0?true:false; } /*! \fn Inundacao::inicializaBarragem(int x, int y, int xAcima, int yAcima, short int** elevacoes,bool **rio,unsigned char**matrizDeDirecoes, int opVetorNormal,int valorVetorNormal,int valEp) \brief Initialize the variable needed to create the reservoir */ void Inundacao::inicializaBarragem(int x, int y, int xAcima, int yAcima, short int** elevacoes,bool **rio,unsigned char**matrizDeDirecoes, int opVetorNormal,int valorVetorNormal,int valEp) { posicaoBarragem.x = x; posicaoBarragem.y = y; posicaoBarragem.z = elevacoes[y][x]; defineVetorNormalABarragem(opVetorNormal,valorVetorNormal,elevacoes,rio,matrizDeDirecoes,valEp); posicaoAcimaBarragem.x = xAcima; posicaoAcimaBarragem.y = yAcima; posicaoAcimaBarragem.z = elevacoes[yAcima][xAcima]; for(int i=0;i<nLinhas;i++) for(int j=0;j<nColunas;j++) visitado[i][j] = false; filaProximosPontos = priority_queue< PontoZ >(); filaProximosPontos.push( posicaoAcimaBarragem ); visitado[posicaoAcimaBarragem.y][posicaoAcimaBarragem.x] = true; volumeAgua = 0; areaLaminaAgua = 0; areaBarragemTocada = 0; comprimentoBarragemTocada = 0; nivelAgua = posicaoAcimaBarragem.z-1; } /*! \fn Inundacao::marcaMontante(int xi, int yi, short int** matrizDeEstados, unsigned char** matrizDeDirecoes, short int** elevacoes,bool **rio,int opVetorNormal,int valorVetorNormal,int valEp) \brief Initialize the process of construct the dam */ void Inundacao::marcaMontante(int xi, int yi, short int** matrizDeEstados, unsigned char** matrizDeDirecoes, short int** elevacoes,bool **rio,int opVetorNormal,int valorVetorNormal,int valEp) { int x = proximoX(yi,xi); //Pega coordenada X do ponto para o qual (xi,yi) flui int y = proximoY(yi,xi); //Pega coordenada Y do ponto para o qual (xi,yi) flui inicializaBarragem(x,y,xi,yi,elevacoes,rio,matrizDeDirecoes,opVetorNormal, valorVetorNormal,valEp); QQueue<PontoZ> filaDePontos; filaDePontos.push_back(PontoZ(y,x,0)); //===Inicializa matriz de estados=== for(int i=0;i<nLinhas;i++) for(int j=0;j<nColunas;j++) matrizDeEstados[i][j] = 1; //Marca pontos vizinhos do ponto (x,y) while(!filaDePontos.empty()) { PontoZ p = filaDePontos.front(); filaDePontos.pop_front(); int i,j; i = p.y-1; j = p.x-1; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } i = p.y-1; j = p.x; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } i = p.y-1; j = p.x+1; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } i = p.y; j = p.x-1; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } i = p.y; j = p.x+1; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } i = p.y+1; j = p.x-1; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } i = p.y+1; j = p.x; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } i = p.y+1; j = p.x+1; if (i>=0 && j>=0 && i<nColunas && j<nLinhas && proximoY(i,j) == p.y && proximoX(i,j)==p.x) { //i,j fluem para p? matrizDeEstados[j][i] = AFLUENTE; filaDePontos.push_back(PontoZ(i,j,0)); } } marcaBarragem(matrizDeEstados); } /*! \fn Inundacao::marcaBarragem(short int **matrizDeEstados) \brief Mark the points in MDE that could be a dam cell */ void Inundacao::marcaBarragem(short int **matrizDeEstados){ //marcando a baragem apartir do ponto de insercao da mesma //identificando a direcao perpendicular int ebx,eby,ebxIni,ebyIni; int dx,dy; int i = posicaoBarragem.y; int j = posicaoBarragem.x; matrizDeEstados[i][j] = BARRAGEM; visitado[i][j] = true; comprimentoBarragemTocada = 1; int ax = vetorNormalABarragem.x; int ay = vetorNormalABarragem.y; if(vetorNormalABarragem.x*vetorNormalABarragem.y == 0){ if(vetorNormalABarragem.x == 0){ dy = 0; dx = 1; ebx = j; eby = i+1; }else{ dy = 1; dx = 0; ebx = j+1; eby = i; } }else{ if(vetorNormalABarragem.x*vetorNormalABarragem.y>0){ dx = 1; dy = -1; ebx = j+1; eby = i; }else{ dx = 1; dy = 1; ebx = j+1; eby = i; } } /* if(vetorNormalABarragem.x == 0){ dy = 0; dx = 1; ebx = j; eby = i+1; }else{ dx = (-1)*vetorNormalABarragem.x/abs(vetorNormalABarragem.x); ebx = j; } if(vetorNormalABarragem.y == 0){ dy = 1; dx = 0; ebx = j+1; eby = i; }else{ dy = vetorNormalABarragem.y/abs(vetorNormalABarragem.y); eby = i -dy; } */ ebxIni = ebx; ebyIni = eby; if(!(eby<0 || ebx<0 || eby>=nLinhas || ebx>=nColunas)){ matrizDeEstados[eby][ebx] = ACIMA_BARRAGEM; visitado[eby][ebx] = true; } //andar pelo terreno para dx,dy while(true){ i = i+dy; j = j+dx; ebx = ebx + dx; eby = eby +dy; //inserindo barragem imaginaria if(!(eby<0 || ebx<0 || eby>=nLinhas || ebx>=nColunas)){ matrizDeEstados[eby][ebx] = ACIMA_BARRAGEM; visitado[eby][ebx] = true; } //excede os limites da matriz if(i<0 || j<0 || i>=nLinhas || j>=nColunas ) break; matrizDeEstados[i][j] = BARRAGEM; visitado[i][j] = true; comprimentoBarragemTocada++; } i = posicaoBarragem.y; j = posicaoBarragem.x; ebx = ebxIni; eby = ebyIni; if(!(eby<0 || ebx<0 || eby>=nLinhas || ebx>=nColunas)){ matrizDeEstados[eby][ebx] = ACIMA_BARRAGEM; visitado[eby][ebx] = true; } //andar pelo terreno para -dx -dy while(true){ i = i-dy; j = j-dx; ebx = ebx - dx; eby = eby -dy; //inserindo marragem imaginaria if(!(eby<0 || ebx<0 || eby>=nLinhas || ebx>=nColunas)){ matrizDeEstados[eby][ebx] = ACIMA_BARRAGEM; visitado[eby][ebx] = true; } //excede os limites da matriz if(i<0 || j<0 || i>=nLinhas || j>=nColunas) break; matrizDeEstados[i][j] = BARRAGEM; visitado[i][j] = true; comprimentoBarragemTocada++; } } /*! \fn Inundacao::sobeNivelDeAgua(short int** matrizDeEstados, short int** elevacoes) \brief Rise the water`s level flooding cells generated new values for variable */ void Inundacao::sobeNivelDeAgua(short int** matrizDeEstados, short int** elevacoes) { if (filaProximosPontos.empty()) { return; } PontoZ p = filaProximosPontos.top(); int nivelAguaAntes = nivelAgua; nivelAgua = p.z; volumeAgua += (nivelAgua-nivelAguaAntes)*areaLaminaAgua; areaBarragemTocada += (nivelAgua-nivelAguaAntes)*comprimentoBarragemTocada; if (matrizDeEstados[p.y][p.x]==3) { //Erro ao colocar constante do define ACIMA_BARRAGEM comprimentoBarragemTocada++; } while(filaProximosPontos.top().z <= nivelAgua) { p = filaProximosPontos.top(); filaProximosPontos.pop(); areaLaminaAgua++; //inunda o cara e coloca os seus vizinhos na fila para serem inundados PontoZ auxParaAvaliar; { int i = -1+p.y; int j = p.x; auxParaAvaliar.x = j; auxParaAvaliar.y = i; if (!(i<0 || i>=nLinhas || j<0 || j>=nColunas || visitado[i][j]) /*&& ( permiteInundacaoEAumentaBarragem(auxParaAvaliar))*/) { filaProximosPontos.push( PontoZ(i,j,elevacoes[i][j]) ); visitado[i][j] = true; } } { int i = 1+p.y; int j = p.x; auxParaAvaliar.x = j; auxParaAvaliar.y = i; if ((!(i<0 || i>=nLinhas || j<0 || j>=nColunas || visitado[i][j])) /*&& ( permiteInundacaoEAumentaBarragem(auxParaAvaliar))*/) { filaProximosPontos.push( PontoZ(i,j,elevacoes[i][j]) ); visitado[i][j] = true; } } { int i = p.y; int j = -1+p.x; auxParaAvaliar.x = j; auxParaAvaliar.y = i; if ((!(i<0 || i>=nLinhas || j<0 || j>=nColunas || visitado[i][j])) /*&& ( permiteInundacaoEAumentaBarragem(auxParaAvaliar))*/) { filaProximosPontos.push( PontoZ(i,j,elevacoes[i][j]) ); visitado[i][j] = true; } } { int i = p.y; int j = 1+p.x; auxParaAvaliar.x = j; auxParaAvaliar.y = i; if (!(i<0 || i>=nLinhas || j<0 || j>=nColunas || visitado[i][j]) /*&& ( permiteInundacaoEAumentaBarragem(auxParaAvaliar))*/) { filaProximosPontos.push( PontoZ(i,j,elevacoes[i][j]) ); visitado[i][j] = true; } } if (matrizDeEstados[p.y][p.x]==3){ //Erro ao usar define ACIMA_BARRAGEM matrizDeEstados[p.y][p.x] = AGUA_BORDA_BARRAGEM; } else{ matrizDeEstados[p.y][p.x] = AGUA; } } } /*! \fn Inundacao::defineVetorNormalABarragem(int op,int val,short int **elevacoes,bool **rio,unsigned char**matrizDeDirecoes,int valEp) \brief Definy what function to call to calculate the dam`s normal vector */ //define qual funcao chamar para calculo do vetor normal void Inundacao::defineVetorNormalABarragem(int op,int val,short int **elevacoes,bool **rio,unsigned char**matrizDeDirecoes,int valEp){ //se for o algoritmo dos vizinhos if(op == 10){ vetorNormalPorMediaSimples(val,elevacoes,rio,matrizDeDirecoes); } if(op == 20) { vetorNormalPorDouglasPeucker(val,valEp,elevacoes,rio,matrizDeDirecoes); } if(op == 30){ vetorNormalPorMediaPonderada(val,elevacoes,rio,matrizDeDirecoes); } //direcoes manuais, //lembrado que é setado o par (x,y) para o vetor normal // e que o crescimento da barragem é +x pra direita e +y para baixo //direcao manual com dir =0 if(op == 101){ vetorNormalABarragem.x = 0; vetorNormalABarragem.y = 1; } //direcao manual com dir =45 if(op == 102){ vetorNormalABarragem.x = 1; vetorNormalABarragem.y = 1; } //direcao manual com dir =90 if(op == 103){ vetorNormalABarragem.x = 1; vetorNormalABarragem.y = 0; } //direcao manual com dir =135 if(op == 104){ vetorNormalABarragem.x = -1; vetorNormalABarragem.y = 1; } } /*! \fn Inundacao::criaListaParaDouglasPeucker(int numElementos,QList<PontoZ> &listaASerSimplificada,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes) \brief Definy what points in drainage network will be in the Douglas-Peucker algorithm */ //usa-se o algoritmo de douglas peucker para identificar o vetor //normal a barragem void Inundacao::criaListaParaDouglasPeucker(int numElementos,QList<PontoZ> &listaASerSimplificada,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes){ listaASerSimplificada.insert(0,posicaoBarragem); int j = posicaoBarragem.x; int i = posicaoBarragem.y; for(int nElem = 1;nElem<numElementos;nElem++){ //acha os oito vizinhos a montante que esta contido na rede de drenagem //i-1,j-1 if((i-1)>0 && (j-1)>0 && rio[i-1][j-1] && elevacoes[i][j]<=elevacoes[i-1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i -1)) ){ i = i-1; j = j-1; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); }else //i-1,j if((i-1)>0 && rio[i-1][j] && elevacoes[i][j]<=elevacoes[i-1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i -1))){ i = i-1; j = j; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); }else //i-1,j+1 if((i-1)>0 && (j+1)<nColunas && rio[i-1][j+1] && elevacoes[i][j]<=elevacoes[i-1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i -1))){ i = i-1; j = j+1; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); }else //i,j-1 if( (j-1)>0 && rio[i][j-1] && elevacoes[i][j]<=elevacoes[i][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i ))){ i = i; j = j-1; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); }else //i,j+1 if((j+1)<nColunas && rio[i][j+1] && elevacoes[i][j]<=elevacoes[i][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i ))){ i = i; j = j+1; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); }else //i+1,j-1 if((i+1)<nLinhas && (j-1)>0 && rio[i+1][j-1] && elevacoes[i][j]<=elevacoes[i+1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i +1))){ i = i+1; j = j-1; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); }else //i+1,j if((i+1)<nLinhas && rio[i+1][j] && elevacoes[i][j]<=elevacoes[i+1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i +1))){ i = i+1; j = j; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); }else //i+1,j+1 if((i+1)<nLinhas && (j+1)<nColunas && rio[i+1][j+1] && elevacoes[i][j]<=elevacoes[i+1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i +1))){ i = i+1; j = j+1; PontoZ aux(i,j,elevacoes[i][j]); listaASerSimplificada.insert(nElem,aux); } } } //pseudo codigo do algoritmo de douglas peucker //retirado do wikiepedia // function DouglasPeucker(PointList[], epsilon) // //Find the point with the maximum distance // dmax = 0 // index = 0 // for i = 2 to (length(PointList) - 1) // d = PerpendicularDistance(PointList[i], Line(PointList[1], PointList[end])) // if d > dmax // index = i // dmax = d // end // end // //If max distance is greater than epsilon, recursively simplify // if dmax >= epsilon // //Recursive call // recResults1[] = DouglasPeucker(PointList[1...index], epsilon) // recResults2[] = DouglasPeucker(PointList[index...end], epsilon) // // Build the result list // ResultList[] = {recResults1[1...end-1] recResults2[1...end]} // else // ResultList[] = {PointList[1], PointList[end]} // end // //Return the result // return ResultList[] // end /*! \fn Inundacao::algoritmoDouglasPeucker(QList<PontoZ> &lista,int epsilon,QList<PontoZ> &resultadoLista) \brief The Douglas-Peucker algorithm, used to simplify the isoline and obtain a vector to be the normal vector of the dam */ QList<PontoZ> Inundacao::algoritmoDouglasPeucker(QList<PontoZ> &lista,int epsilon,QList<PontoZ> &resultadoLista){ //achar o ponto com maxima distancia double dMax = 0; int iDMax = 0; for(int i= 1; i<(lista.size()-1);i++){ //definindo equacao da reta //usado a tecnica de determinante de matriz para achar os coeficientes int A,B,C; A = lista.at(0).y - lista.at(lista.size()-1).y ; B = -lista.at(0).x + lista.at(lista.size()-1).x; C = (lista.at(0).x)*(lista.at(lista.size()-1).y) - (lista.at(0).y)*(lista.at(lista.size()-1).x); //pontos a saber a distancia int xP = lista.at(i).x; int yP = lista.at(i).y; //equacao da distacia // d = |ax+by+c|/sqtr(a2+b2) double d = abs(A*xP+B*yP+C)/sqrt(pow(A,2)+pow(B,2)); //caso o corrente seja mais distante que o mais distante ate entao if(d>dMax){ dMax = d; iDMax = i; } } //If max distance is greater than epsilon, recursively simplify // if dmax >= epsilon // //Recursive call // recResults1[] = DouglasPeucker(PointList[1...index], epsilon) // recResults2[] = DouglasPeucker(PointList[index...end], epsilon) // // Build the result list // ResultList[] = {recResults1[1...end-1] recResults2[1...end]} // else // ResultList[] = {PointList[1], PointList[end]} // end // //Return the result // return ResultList[] // end if(dMax>=epsilon){ //chama duas chamadas recursivas do inicio ao ponto e do ponto ao fim QList<PontoZ> auxLista1 = lista.mid(0,iDMax);//do inicio a idMAx QList<PontoZ> auxLista2 = lista.mid(iDMax,-1);//ate o fim QList<PontoZ> resultadoListaRecursiva1 = algoritmoDouglasPeucker(auxLista1,epsilon, resultadoLista); QList<PontoZ> resultadoListaRecursiva2 = algoritmoDouglasPeucker(auxLista2,epsilon, resultadoLista); resultadoLista.append(resultadoListaRecursiva1); resultadoLista.append(resultadoListaRecursiva2); }else{ resultadoLista.append(lista.at(0)); resultadoLista.append(lista.at(lista.size()-1)); } return resultadoLista; } /*! \fn Inundacao::vetorNormalPorDouglasPeucker(int numElementos,int epsilon,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes) \brief Function to prepare and call Douglas-Peucker algorithm */ void Inundacao::vetorNormalPorDouglasPeucker(int numElementos,int epsilon,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes){ //prepara para iniciar o algoritmo de douglas peucker //criando-se a lista a ser simplificada QList<PontoZ> listaASerSimplificada; criaListaParaDouglasPeucker(numElementos,listaASerSimplificada,elevacoes,rio,matrizDeDirecoes); //usa-se o algoritmo de douglas peucker QList<PontoZ> resp; QList<PontoZ> listaSimplificada = algoritmoDouglasPeucker(listaASerSimplificada,epsilon,resp); //atraves da lista define o vetor perpendicular vetorNormalABarragem.x = listaSimplificada.at(1).x -listaSimplificada.at(0).x; vetorNormalABarragem.y = listaSimplificada.at(1).y -listaSimplificada.at(0).y; } //algoritmo para vetor normal da barragem com vizinhos mais praximo // a ideia do algoritmo é achar o vetor normal a barragem //usando-se os n vizinhos mais a montante /*! \fn Inundacao::vetorNormalPorVizinhanca(int viz,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes) \brief Function to calculate the dam`s normal vector by the simple sum of vector */ void Inundacao::vetorNormalPorMediaSimples(int viz,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes){ int numElementos = viz; // int j = posicaoBarragem.x; int i = posicaoBarragem.y; //acha os oito vizinhos a montante que esta contido na rede de drenagem //i-1,j-1 if((i-1)>0 && (j-1)>0 && rio[i-1][j-1] && elevacoes[i][j]<=elevacoes[i-1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i -1)) ){ i = i-1; j = j-1; }else //i-1,j if((i-1)>0 && rio[i-1][j] && elevacoes[i][j]<=elevacoes[i-1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i -1))){ i = i-1; j = j; }else //i-1,j+1 if((i-1)>0 && (j+1)<nColunas && rio[i-1][j+1] && elevacoes[i][j]<=elevacoes[i-1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i -1))){ i = i-1; j = j+1; }else //i,j-1 if( (j-1)>0 && rio[i][j-1] && elevacoes[i][j]<=elevacoes[i][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i ))){ i = i; j = j-1; }else //i,j+1 if((j+1)<nColunas && rio[i][j+1] && elevacoes[i][j]<=elevacoes[i][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i ))){ i = i; j = j+1; }else //i+1,j-1 if((i+1)<nLinhas && (j-1)>0 && rio[i+1][j-1] && elevacoes[i][j]<=elevacoes[i+1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i +1))){ i = i+1; j = j-1; }else //i+1,j if((i+1)<nLinhas && rio[i+1][j] && elevacoes[i][j]<=elevacoes[i+1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i +1))){ i = i+1; j = j; }else //i+1,j+1 if((i+1)<nLinhas && (j+1)<nColunas && rio[i+1][j+1] && elevacoes[i][j]<=elevacoes[i+1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i +1))){ i = i+1; j = j+1; } int respI = i - posicaoBarragem.y; int respJ = j - posicaoBarragem.x; for(int nElem = 1;nElem<numElementos;nElem++){ // //i-1,j-1 if((i-1)>0 && (j-1)>0 && rio[i-1][j-1] && elevacoes[i][j]<=elevacoes[i-1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i -1)) ){ i = i-1; j = j-1; }else //i-1,j if((i-1)>0 && rio[i-1][j] && elevacoes[i][j]<=elevacoes[i-1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i -1))){ i = i-1; j = j; }else //i-1,j+1 if((i-1)>0 && (j+1)<nColunas && rio[i-1][j+1] && elevacoes[i][j]<=elevacoes[i-1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i -1))){ i = i-1; j = j+1; }else //i,j-1 if( (j-1)>0 && rio[i][j-1] && elevacoes[i][j]<=elevacoes[i][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i ))){ i = i; j = j-1; }else //i,j+1 if((j+1)<nColunas && rio[i][j+1] && elevacoes[i][j]<=elevacoes[i][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i ))){ i = i; j = j+1; }else //i+1,j-1 if((i+1)<nLinhas && (j-1)>0 && rio[i+1][j-1] && elevacoes[i][j]<=elevacoes[i+1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i +1))){ i = i+1; j = j-1; }else //i+1,j if((i+1)<nLinhas && rio[i+1][j] && elevacoes[i][j]<=elevacoes[i+1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i +1))){ i = i+1; j = j; }else //i+1,j+1 if((i+1)<nLinhas && (j+1)<nColunas && rio[i+1][j+1] && elevacoes[i][j]<=elevacoes[i+1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i +1))){ i = i+1; j = j+1; } //atualiza variavel da soma de vetores para criar o vetor soma respI = respI + i -posicaoBarragem.y; respJ = respJ + j - posicaoBarragem.x; } vetorNormalABarragem.x = respI/numElementos; vetorNormalABarragem.y = respJ/numElementos; } void Inundacao::vetorNormalPorMediaPonderada(int viz,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes){ int numElementos = viz; int s = 0; int pesoVizinho = viz; // int j = posicaoBarragem.x; int i = posicaoBarragem.y; //acha os oito vizinhos a montante que esta contido na rede de drenagem //achando o primeiro //i-1,j-1 if((i-1)>0 && (j-1)>0 && rio[i-1][j-1] && elevacoes[i][j]<=elevacoes[i-1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i -1)) ){ i = i-1; j = j-1; }else //i-1,j if((i-1)>0 && rio[i-1][j] && elevacoes[i][j]<=elevacoes[i-1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i -1))){ i = i-1; j = j; }else //i-1,j+1 if((i-1)>0 && (j+1)<nColunas && rio[i-1][j+1] && elevacoes[i][j]<=elevacoes[i-1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i -1))){ i = i-1; j = j+1; }else //i,j-1 if( (j-1)>0 && rio[i][j-1] && elevacoes[i][j]<=elevacoes[i][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i ))){ i = i; j = j-1; }else //i,j+1 if((j+1)<nColunas && rio[i][j+1] && elevacoes[i][j]<=elevacoes[i][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i ))){ i = i; j = j+1; }else //i+1,j-1 if((i+1)<nLinhas && (j-1)>0 && rio[i+1][j-1] && elevacoes[i][j]<=elevacoes[i+1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i +1))){ i = i+1; j = j-1; }else //i+1,j if((i+1)<nLinhas && rio[i+1][j] && elevacoes[i][j]<=elevacoes[i+1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i +1))){ i = i+1; j = j; }else //i+1,j+1 if((i+1)<nLinhas && (j+1)<nColunas && rio[i+1][j+1] && elevacoes[i][j]<=elevacoes[i+1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i +1))){ i = i+1; j = j+1; } int respI = (i - posicaoBarragem.y)*pesoVizinho; int respJ = (j - posicaoBarragem.x)*pesoVizinho; s += pesoVizinho; pesoVizinho--; for(int nElem = 1;nElem<numElementos;nElem++){ // //i-1,j-1 if((i-1)>0 && (j-1)>0 && rio[i-1][j-1] && elevacoes[i][j]<=elevacoes[i-1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i -1)) ){ i = i-1; j = j-1; }else //i-1,j if((i-1)>0 && rio[i-1][j] && elevacoes[i][j]<=elevacoes[i-1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i -1))){ i = i-1; j = j; }else //i-1,j+1 if((i-1)>0 && (j+1)<nColunas && rio[i-1][j+1] && elevacoes[i][j]<=elevacoes[i-1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i -1))){ i = i-1; j = j+1; }else //i,j-1 if( (j-1)>0 && rio[i][j-1] && elevacoes[i][j]<=elevacoes[i][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i ))){ i = i; j = j-1; }else //i,j+1 if((j+1)<nColunas && rio[i][j+1] && elevacoes[i][j]<=elevacoes[i][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i ))){ i = i; j = j+1; }else //i+1,j-1 if((i+1)<nLinhas && (j-1)>0 && rio[i+1][j-1] && elevacoes[i][j]<=elevacoes[i+1][j-1] && (proximoX(i,j) != (j-1) || proximoY(i,j) != (i +1))){ i = i+1; j = j-1; }else //i+1,j if((i+1)<nLinhas && rio[i+1][j] && elevacoes[i][j]<=elevacoes[i+1][j] && (proximoX(i,j) != (j) || proximoY(i,j) != (i +1))){ i = i+1; j = j; }else //i+1,j+1 if((i+1)<nLinhas && (j+1)<nColunas && rio[i+1][j+1] && elevacoes[i][j]<=elevacoes[i+1][j+1] && (proximoX(i,j) != (j+1) || proximoY(i,j) != (i +1))){ i = i+1; j = j+1; } //atualiza variavel da soma de vetores para criar o vetor soma respI = respI + (i -posicaoBarragem.y)*pesoVizinho; respJ = respJ + (j - posicaoBarragem.x)*pesoVizinho; s += pesoVizinho; pesoVizinho--; } vetorNormalABarragem.x = respI/s; vetorNormalABarragem.y = respJ/s; } /*! \fn Inundacao::inunda(int posX, int posY, unsigned char** matrizDeDirecoes, short int** elevacoes,bool **rio,int opVetorNormal, int valorVetorNormal,int valEp) \brief Function that invoque the sequence of functions to create the reservoir */ //Invoca sequencia de funcções para realizar inundação void Inundacao::inunda(int posX, int posY, unsigned char** matrizDeDirecoes, short int** elevacoes,bool **rio,int opVetorNormal, int valorVetorNormal,int valEp){ //int x = proximoX(posY,posX); // int y = proximoY(posY,posX); try{ marcaMontante(posX,posY,matrizEstados, matrizDeDirecoes, elevacoes,rio, opVetorNormal,valorVetorNormal,valEp); }catch(exception e){ QString erroMsg="Erro no metodo marcaMontante da classe Inundacao"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } while(volumeAgua<volumeAlvo) { try{ sobeNivelDeAgua(matrizEstados, elevacoes); }catch(exception e){ QString erroMsg="Erro no metodo sobeNivelAgua da classe Inundacao"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } } try{ acertaTamanhoBarragem(matrizEstados); }catch(exception e){ QString erroMsg="Erro no metodo acertaTamanhoBarragem na classe Inundacao"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } } /*! \fn Inundacao::acertaTamanhoBarragem(short int **matrizDeEstados) \brief Definy the real cells that are dam`s cell. Eliminate cells that arent near a flooded cell. */ void Inundacao::acertaTamanhoBarragem(short int **matrizDeEstados){ int i = posicaoBarragem.y; int j = posicaoBarragem.x; int dx,dy; if(vetorNormalABarragem.x*vetorNormalABarragem.y == 0){ if(vetorNormalABarragem.x == 0){ dy = 0; dx = 1; }else{ dy = 1; dx = 0; } }else{ if(vetorNormalABarragem.x*vetorNormalABarragem.y>0){ dx = 1; dy = -1; }else{ dx = 1; dy = 1; } } //achar o j,i que nao contem mais vizinhos barragem com agua em volta //na direcao dx dy while(true){ //verificar os oito vizinhos // //i-1,j-1 if(((i-1)>0 && (j-1)>0) && (matrizDeEstados[i-1][j-1] == 5 ) ){ i = i+dy; j = j+dx; }else //i-1,j if((i-1)>0 && (matrizDeEstados[i-1][j] == 5 )){ i = i+dy; j = j+dx; }else //i-1,j+1 if((i-1)>0 && (j+1)<nColunas && (matrizDeEstados[i-1][j+1] == 5 )){ i = i+dy; j = j+dx; }else //i,j-1 if( (j-1)>0 && (matrizDeEstados[i][j-1] == 5 )){ i =i+dy; j = j+dx; }else //i,j+1 if((j+1)<nColunas && (matrizDeEstados[i][j+1] == 5 )){ i = i+dy; j = j+dx; }else //i+1,j-1 if((i+1)<nLinhas && (j-1)>0 && (matrizDeEstados[i+1][j-1] == 5 )){ i = i+dy; j = j+dx; }else //i+1,j if((i+1)<nLinhas && (matrizDeEstados[i+1][j] == 5 ) ){ i = i+dy; j = j+dx; }else //i+1,j+1 if((i+1)<nLinhas && (j+1)<nColunas && (matrizDeEstados[i+1][j+1] == 5 )){ i = i+dy; j = j+dx; }else{ break; } if(i < 0 || j<0 || i>=nLinhas || j>=nColunas){ break; } } //eliminando os pontos //eliminar para +dx e +dy while(true){ if(i<0 || j<0 || i>=nLinhas || j>= nColunas) break; matrizDeEstados[i][j] = 1; comprimentoBarragemTocada--; i = i+dy; j = j+dx; } //definindo o tanto corta na direcao -dx -dy da barragem... i = posicaoBarragem.y; j = posicaoBarragem.x; while(true){ //verificar os oito vizinhos // //i-1,j-1 if(((i-1)>0 && (j-1)>0) && (matrizDeEstados[i-1][j-1] == 5 ) ){ i = i-dy; j = j-dx; }else //i-1,j if((i-1)>0 && (matrizDeEstados[i-1][j] == 5 )){ i = i-dy; j = j-dx; }else //i-1,j+1 if((i-1)>0 && (j+1)<nColunas && (matrizDeEstados[i-1][j+1] == 5 )){ i = i-dy; j = j-dx; }else //i,j-1 if( (j-1)>0 && (matrizDeEstados[i][j-1] == 5 )){ i =i-dy; j = j-dx; }else //i,j+1 if((j+1)<nColunas && (matrizDeEstados[i][j+1] == 5 )){ i = i-dy; j = j-dx; }else //i+1,j-1 if((i+1)<nLinhas && (j-1)>0 && (matrizDeEstados[i+1][j-1] == 5 )){ i = i-dy; j = j-dx; }else //i+1,j if((i+1)<nLinhas && (matrizDeEstados[i+1][j] == 5 ) ){ i = i-dy; j = j-dx; }else //i+1,j+1 if((i+1)<nLinhas && (j+1)<nColunas && (matrizDeEstados[i+1][j+1] == 5 )){ i = i-dy; j = j-dx; }else{ break; } if(i < 0 || j<0 || i>=nLinhas || j>=nColunas) break; } //cortando na direcao -dx -dy while(true){ if(i<0 || j<0 || i>=nLinhas || j>= nColunas) break; matrizDeEstados[i][j] = 1; areaBarragemTocada--; comprimentoBarragemTocada--; i = i-dy; j = j-dx; } } /*! \fn Inundacao::getPosicaoBarragem() \brief Returns the dam position. */ PontoZ Inundacao::getPosicaoBarragem(){ return posicaoBarragem; } <file_sep>#include "painelvisualizacaobarragemopengl.h" #include <QKeyEvent> /*! \class PainelVisualizacaoBarragemOpenGL \previouspage painelvisualizacaobarragem2dopengl \contentspage \nextpage PainelVisualizacaoOpenGL \startpage All Classes \brief Class to create a opengl painel with dam 3D visualization */ PainelVisualizacaoBarragemOpenGL::PainelVisualizacaoBarragemOpenGL(QWidget *parent) : QGLWidget(parent) { setFormat(QGL::SingleBuffer/* DoubleBuffer */| QGL::DepthBuffer); posicaoCamera[0] = 0; posicaoCamera[1]= 0; posicaoCamera[2]= 0; normalCamera[0] = 0; normalCamera[1] = 1; normalCamera[2] = 0; direcaoCamera[0] = 0 ; direcaoCamera[1] = 0; direcaoCamera[2] = -1; } void PainelVisualizacaoBarragemOpenGL::carregandoInformacoes(VisualizacaoMapa *viMapa){ visualizacaoMapa = new VisualizacaoMapa(*viMapa); //defineOrtho(); updateGL(); } void PainelVisualizacaoBarragemOpenGL::defineOrtho(){ //setar o ortho com proporcao ao tamanho do mapa glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,30,30, 0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void PainelVisualizacaoBarragemOpenGL::keyPressEvent(QKeyEvent* kev){ GLdouble cos5 = 0.996; GLdouble sen5 = 0.087; double rotaX,rotaY,rotaZ; //rotacoes em torno de y //roda esquerda para direita if(kev->key() == Qt::Key_D){ rotaX = cos5 * posicaoCamera[0] - (-1) * sen5 * posicaoCamera[2]; rotaZ = cos5 * posicaoCamera[2] + (-1) * sen5 * posicaoCamera[0]; posicaoCamera[0] = rotaX; posicaoCamera[2] = rotaZ; //posição do vetor de view up rotaX = cos5 * normalCamera[0] - (-1) * sen5 * normalCamera[2]; rotaZ = cos5 * normalCamera[2] + (-1) * sen5 * normalCamera[0]; // normalCamera[0] = rotaX; // normalCamera[2] = rotaZ; } //roda esquerda para direita if(kev->key() == Qt::Key_A){ rotaX = cos5 * posicaoCamera[0] - sen5 * posicaoCamera[2]; rotaZ = cos5 * posicaoCamera[2] + sen5 * posicaoCamera[0]; posicaoCamera[0] = rotaX; posicaoCamera[2] = rotaZ; //posição do vetor de view up rotaX = cos5 * normalCamera[0] - sen5 * normalCamera[2]; rotaZ = cos5 * normalCamera[2] + sen5 * normalCamera[0]; // normalCamera[0] = rotaX; // normalCamera[2] = rotaZ; } //rotacoes em torno de x //roda baixo para cima if(kev->key() == Qt::Key_W){ rotaY = (cos5 * posicaoCamera[1] + sen5 *posicaoCamera[2]); rotaZ = cos5 * posicaoCamera[2] - sen5 * posicaoCamera[1]; posicaoCamera[1] = rotaY; posicaoCamera[2] = rotaZ; //posição do vetor de view up rotaY = cos5 * normalCamera[1] - (-1) * sen5 * normalCamera[2]; rotaZ = cos5 * normalCamera[2] + (-1) * sen5 * normalCamera[1]; // normalCamera[1] = rotaY; // normalCamera[2] = rotaZ; } //roda cima para baixo if(kev->key() == Qt::Key_S){ rotaY = cos5 * posicaoCamera[1] - sen5 * posicaoCamera[2]; rotaZ = cos5 * posicaoCamera[2] + sen5 * posicaoCamera[1]; posicaoCamera[1] = rotaY; posicaoCamera[2] = rotaZ; //posição do vetor de view up rotaY = cos5 * normalCamera[1] - sen5 * normalCamera[2]; rotaZ = cos5 * normalCamera[2] + sen5 * normalCamera[1]; // normalCamera[1] = rotaY; // normalCamera[2] = rotaZ; } double zMaisCamera = 1.5; double zMenosCamera = 0.5; if(kev->key() == Qt::Key_N){ posicaoCamera[0] = posicaoCamera[1] = posicaoCamera[2] *= zMaisCamera; } if(kev->key() == Qt::Key_F){ posicaoCamera[0] = posicaoCamera[1] = posicaoCamera[2] *= zMenosCamera; } updateGL(); } void PainelVisualizacaoBarragemOpenGL::initializeGL(){ qglClearColor(Qt::white); glShadeModel(GL_FLAT); glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); GLfloat luzAmbiente[4]={0.2,0.2,0.2,1.0}; GLfloat luzDifusa[4]={0.7,0.7,0.7,1.0}; // "cor" GLfloat luzEspecular[4]={1.0, 1.0, 1.0, 1.0};// "brilho" GLfloat posicaoLuz[4]={-700.0, 700.0, 700.0, 1.0}; // Capacidade de brilho do material GLfloat especularidade[4]={1.0,1.0,1.0,1.0}; GLint especMaterial = 60; // Especifica que a cor de fundo da janela será preta glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Habilita o modelo de colorização de Gouraud glShadeModel(GL_SMOOTH); // Define a refletância do material glMaterialfv(GL_FRONT,GL_SPECULAR, especularidade); // Define a concentração do brilho glMateriali(GL_FRONT,GL_SHININESS,especMaterial); // Ativa o uso da luz ambiente glLightModelfv(GL_LIGHT_MODEL_AMBIENT, luzAmbiente); // Define os parâmetros da luz de número 0 glLightfv(GL_LIGHT0, GL_AMBIENT, luzAmbiente); glLightfv(GL_LIGHT0, GL_DIFFUSE, luzDifusa ); glLightfv(GL_LIGHT0, GL_SPECULAR, luzEspecular ); glLightfv(GL_LIGHT0, GL_POSITION, posicaoLuz ); // Habilita a definição da cor do material a partir da cor corrente glEnable(GL_COLOR_MATERIAL); //Habilita o uso de iluminação glEnable(GL_LIGHTING); // Habilita a luz de número 0 glEnable(GL_LIGHT0); // Habilita o depth-buffering glEnable(GL_DEPTH_TEST); } void PainelVisualizacaoBarragemOpenGL::resizeGL(int w, int h){ double min = 10000000; double max = 0; for(int i = 0; i < visualizacaoMapa->mapa->getNLinhas();i++){ for(int j = 0; j < visualizacaoMapa->mapa->getNColunas();j++){ if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j] == visualizacaoMapa->mapa->getDadoInvalido()) continue; if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j]< min )min = visualizacaoMapa->mapa->matrizDeElevacoes[i][j]; if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j]> max )max = visualizacaoMapa->mapa->matrizDeElevacoes[i][j]; } } int w1 = visualizacaoMapa->mapa->getNColunas(); int h1 = visualizacaoMapa->mapa->getNLinhas(); direcaoCamera[0] = 0; direcaoCamera[1] = 0; direcaoCamera[2] = -1; posicaoCamera[0]= visualizacaoMapa->mapa->getNColunas()/2; posicaoCamera[1]= visualizacaoMapa->mapa->getNLinhas()/2; posicaoCamera[2] = visualizacaoMapa->mapa->matrizDeElevacoes[h1/2][w1/2]; normalCamera[0]= 0; normalCamera[1]= 1; normalCamera[2] = 0; glViewport(0, 0, this->width(), this->height()); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60,1, 1, 1000); //glOrtho(-w1,w1,-h1,h1,1,1000); } void PainelVisualizacaoBarragemOpenGL::desenhaTerreno(){ int xBarragemNaRede,yBarragemNaRede,zBarragemNaRede; //identificando min e max das cores double min = 10000000; double max = 0; for(int i = 0; i < visualizacaoMapa->mapa->getNLinhas();i++){ for(int j = 0; j < visualizacaoMapa->mapa->getNColunas();j++){ if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j] == visualizacaoMapa->mapa->getDadoInvalido()) continue; if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j]< min )min = visualizacaoMapa->mapa->matrizDeElevacoes[i][j]; if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j]> max )max = visualizacaoMapa->mapa->matrizDeElevacoes[i][j]; } } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); gluLookAt(posicaoCamera[0],posicaoCamera[1],posicaoCamera[2],direcaoCamera[0],direcaoCamera[1],direcaoCamera[2],normalCamera[0],normalCamera[1],normalCamera[2]); for(int i = 0; i < visualizacaoMapa->mapa->getNLinhas();i++){ for(int j = 0; j < visualizacaoMapa->mapa->getNColunas();j++){ GLfloat elevacao = visualizacaoMapa->mapa->matrizDeElevacoes[i][j]; //elevacao = elevacao - min + 0.3*(max-min); //dado invalido if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j] == visualizacaoMapa->mapa->getDadoInvalido()) continue; // ______ // /______/| // | | | // | 1___|_| 1 vert j,i // |/____|/ else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==2) { //barragem glColor3f(1.0f, 0.0f, 0.0); } //else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==3) { //acima_barragem // glColor3f(.5f, .5f, .5f); //} else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==4) {//água na borda da barragem glColor3f(0.0f, 0.75f, 1.0); } else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==5) { //água glColor3f(0.0f, 0.25f, 1.0); } else{ if(!visualizacaoMapa->fluxo->rio[i][j]) //Se não for rio, pinta cor normal, caso contrário, azul glColor3f(0,1-((visualizacaoMapa->mapa->matrizDeElevacoes[i][j] - min)/(max-min) ),(visualizacaoMapa->mapa->matrizDeElevacoes[i][j] - min)/(max-min)); else glColor3f(0,0,0); } //frontal glBegin(GL_QUAD_STRIP); glNormal3f(0,-1,0); glVertex3f(j,i+1,0); glVertex3f(j,i+1,elevacao); glVertex3f(j+1,i+1,elevacao); glVertex3f(j+1,i+1,0); glEnd(); //traseiro glBegin(GL_QUAD_STRIP); glNormal3f(0,1,0); glVertex3f(j,i,0); glVertex3f(j,i,elevacao); glVertex3f(j+1,i,elevacao); glVertex3f(j+1,i,0); glEnd(); //esquerdo glBegin(GL_QUAD_STRIP); glNormal3f(-1,0,0); glVertex3f(j,i,0); glVertex3f(j,i,elevacao); glVertex3f(j,i+1,elevacao); glVertex3f(j,i+1,0); glEnd(); //direito glBegin(GL_QUAD_STRIP); glNormal3f(1,0,0); glVertex3f(j+1,i+1,0); glVertex3f(j+1,i+1,elevacao); glVertex3f(j,i+1,elevacao); glVertex3f(j,i+1,0); glEnd(); //baixo glBegin(GL_QUAD_STRIP); glNormal3f(0,-0,-1); glVertex3f(j+1,i,0); glVertex3f(j,i,0); glVertex3f(j,i+1,0); glVertex3f(j+1,i+1,0); glEnd(); //cima glBegin(GL_QUAD_STRIP); glNormal3f(0,0,1); glVertex3f(j,i,elevacao); glVertex3f(j+1,i,elevacao); glVertex3f(j+1,i+1,elevacao); glVertex3f(j,i+1,elevacao); glEnd(); //desenha barragem if (visualizacaoMapa->inundacao->matrizEstados[i][j]==2){ if(visualizacaoMapa->inundacao->matrizEstados[i][j] == 1){ xBarragemNaRede = j; yBarragemNaRede = i; zBarragemNaRede = elevacao; } int altBarragem = visualizacaoMapa->inundacao->nivelAgua; //altBarragem = altBarragem + min - 0.3*(max-min); glColor3f(0.64f,0.42f,0.04f); //frontal glBegin(GL_QUAD_STRIP); glNormal3f(0,-1,0); glVertex3f(j,i+1,elevacao); glVertex3f(j,i+1,altBarragem); glVertex3f(j+1,i+1,altBarragem); glVertex3f(j+1,i+1,elevacao); glEnd(); //traseiro glBegin(GL_QUAD_STRIP); glNormal3f(0,1,0); glVertex3f(j,i,elevacao); glVertex3f(j,i,altBarragem); glVertex3f(j+1,i,altBarragem); glVertex3f(j+1,i,elevacao); glEnd(); //esquerdo glBegin(GL_QUAD_STRIP); glNormal3f(-1,0,0); glVertex3f(j,i,elevacao); glVertex3f(j,i,altBarragem); glVertex3f(j,i+1,altBarragem); glVertex3f(j,i+1,elevacao); glEnd(); //direito glBegin(GL_QUAD_STRIP); glNormal3f(1,0,0); glVertex3f(j+1,i+1,elevacao); glVertex3f(j+1,i+1,altBarragem); glVertex3f(j,i+1,altBarragem); glVertex3f(j,i+1,elevacao); glEnd(); //baixo glBegin(GL_QUAD_STRIP); glNormal3f(0,-0,-1); glVertex3f(j+1,i,elevacao); glVertex3f(j,i,elevacao); glVertex3f(j,i+1,elevacao); glVertex3f(j+1,i+1,elevacao); glEnd(); //cima glBegin(GL_QUAD_STRIP); glNormal3f(0,0,1); glVertex3f(j,i,altBarragem); glVertex3f(j+1,i,altBarragem); glVertex3f(j+1,i+1,altBarragem); glVertex3f(j,i+1,altBarragem); } } } // posicaoCamera[0]= 1.5*xBarragemNaRede; // posicaoCamera[1]= 1.5*yBarragemNaRede; // posicaoCamera[2] = 1.5*zBarragemNaRede; // gluLookAt(posicaoCamera[0],posicaoCamera[1],posicaoCamera[2],direcaoCamera[0],direcaoCamera[1],direcaoCamera[2],normalCamera[0],normalCamera[1],normalCamera[2]); } void PainelVisualizacaoBarragemOpenGL::paintGL(){ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); desenhaTerreno(); glFlush(); } <file_sep>#ifndef JANELACAMADAS_H #define JANELACAMADAS_H #include <QInputDialog> namespace Ui { class janelaCamadas; } class janelaCamadas : public QDialog { Q_OBJECT public: explicit janelaCamadas(QWidget *parent = 0); ~janelaCamadas(); //===metodo QStringList getValores(bool&);//sobescrito usado para obter os valores da janela private slots: private: //====atributos Ui::janelaCamadas *ui; }; #endif // JANELACAMADAS_H <file_sep>#include "painelvisualizacaoopengl.h" #include "math.h" #include "MapaMDE.h" #include "janelaprincipal.h" using namespace std; /*! \class PainelVisualizacaoOpenGL \previouspage PainelVisualizacaoBarragemOpenGL \contentspage \nextpage VisualizacaoMapa \startpage All Classes Class to create a opengl painel to show user the MDE */ /*! \variable PainelVisualizacaoOpenGL::posClickX \brief the value in axis-x for click position */ /*! \variable PainelVisualizacaoOpenGL::posClickY \brief the value in axis-y for click position */ /*! \variable PainelVisualizacaoOpenGL::corAlagamento \brief the color value for the flooded area */ /*! \variable PainelVisualizacaoOpenGL::corRedeDeDrenagem \brief the color value for the drainage network */ /*! \variable PainelVisualizacaoOpenGL::corMaiorElevacao \brief the color value for the higher cell`s elevation */ /*! \variable PainelVisualizacaoOpenGL::corMenorElevacao \brief the color value for the higher cell`s elevation */ /*! \variable PainelVisualizacaoOpenGL::corBarragem \brief the color value for the dam */ /*! \variable PainelVisualizacaoOpenGL::corPadraoAlagamento \brief the default color value for the flooded area */ /*! \variable PainelVisualizacaoOpenGL::corPadraoRedeDeDrenagem \brief the defaultcolor value for the drainage network */ /*! \variable PainelVisualizacaoOpenGL::corPadraoMaiorElevacao \brief the default color value for the higher cell`s elevation */ /*! \variable PainelVisualizacaoOpenGL::corPadraoMenorElevacao \brief the default color value for the higher cell`s elevation */ /*! \variable PainelVisualizacaoOpenGL::corPadraoBarragem \brief the color value for the dam */ /*! \variable PainelVisualizacaoOpenGL::mapaEstaCarregado \brief the flag to control if the MDE is open */ /*! \variable PainelVisualizacaoOpenGL::flagPinta \brief the flag to control the opengl painel need to be all painted or only Camadas painted. */ /*! \fn PainelVisualizacaoOpenGL::mouseMoveEvent(QMouseEvent *) Signal for mouseMoveEvent. The slot \l {JanelaPrincipal::trocaCoordenadas()}{JanelaPrincipal::trocaCoordenadas(QMouseEvent *)} and \l {JanelaPrincipal::movendoMouse()}{JanelaPrincipal::movendoMouse(QMouseEvent *)} catch this signal */ /*! \fn PainelVisualizacaoOpenGL::mousePressEvent ( QMouseEvent * event ) Signal for mousePressEvent. The slot \l {JanelaPrincipal::defineInundacao()}{JanelaPrincipal::defineInundacao(QMouseEvent *)} catch this signal */ /*! \fn PainelVisualizacaoOpenGL::keyPressEvent(QKeyEvent *) Signal for keyPressEvent. The slot \l {JanelaPrincipal::moveBarragem()}{JanelaPrincipal::moveBarragem(QKeyEvent *)} catch this signal */ /*! \fn PainelVisualizacaoOpenGL::mouseReleaseEvent(QMouseEvent*) Signal for mouseReleaseEvent. The slot \l {JanelaPrincipal::adicionandoPontosACamada()}{JanelaPrincipal::adicionandoPontosACamada(QKeyEvent *)} catch this signal */ /*! \fn PainelVisualizacaoOpenGL::PainelVisualizacaoOpenGL(QWidget *parent) Constructor */ PainelVisualizacaoOpenGL::PainelVisualizacaoOpenGL(QWidget *parent) : QGLWidget(parent) { setFormat(QGL::DoubleBuffer | QGL::DepthBuffer); corPadraoAlagamento.setRgb(0,0,255); corPadraoRedeDeDrenagem.setRgb(100,0,0); corPadraoMaiorElevacao.setRgb(0,255,0); corPadraoMenorElevacao.setRgb(205,150,0); corPadraoBarragem.setRgb(255,0,0); } /*! \overload PainelVisualizacaoOpenGL::initializeGL() Opengl functions needed. It is the init function of opengl painel */ void PainelVisualizacaoOpenGL::initializeGL(){ glClearColor(1.0f,1.0f,1.0f,.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glHint(GL_POINT_SMOOTH_HINT,GL_PERSPECTIVE_CORRECTION_HINT); posClickX = posClickY = -1; //visualizacaoMapa->marcaInicioX = visualizacaoMapa->marcaInicioY = visualizacaoMapa->marcaFinalX = visualizacaoMapa->marcaFinalY = -1; //visualizacaoMapa->marcouInicio = false; mapaEstaCarregado = false; flagPinta = true; setCoresPadrao(); } /*! \fn PainelVisualizacaoOpenGL::setCoresPadrao() Function to set the default colors to the color`s variable */ void PainelVisualizacaoOpenGL::setCoresPadrao(){ corAlagamento = (QColor(corPadraoAlagamento.name())); corAlagamento = QColor(corPadraoAlagamento.name()); corBarragem = QColor(corPadraoBarragem.name()); corMaiorElevacao = QColor(corPadraoMaiorElevacao.name()); corMenorElevacao = QColor(corPadraoMenorElevacao.name()); corRedeDeDrenagem = QColor(corPadraoRedeDeDrenagem.name()); } /*! \fn PainelVisualizacaoOpenGL::zoomMapa(int zoom) Function to update the zoom in the opengl painel */ void PainelVisualizacaoOpenGL::zoomMapa(int zoom){ visualizacaoMapa->setZoom(zoom); //Define novo tamanho do painel, faz a chamada do resizeGL this->resize(visualizacaoMapa->vetorDeZooms[0][zoom],visualizacaoMapa->vetorDeZooms[1][zoom]); updateGL(); } /*! \fn PainelVisualizacaoOpenGL::resizeGL(int width, int height) Opengl functions needed. For when painel is resized or changed */ void PainelVisualizacaoOpenGL::resizeGL(int width, int height){ glClearColor(1.0f,1.0f,1.0f,.0f); glClearDepth(1.0f); glViewport(0,0,width,height); //setar ponto para que contemple aumentar janela if(mapaEstaCarregado){ visualizacaoMapa->setTamanhoPonto(width,height); // setMouseTracking(true); } } /*! \fn PainelVisualizacaoOpenGL::defineOrtho() Function to definy the ortho of opengl painel */ void PainelVisualizacaoOpenGL::defineOrtho(){ //setar o ortho com proporcao ao tamanho do mapa glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,visualizacaoMapa->getProporcaoX(),visualizacaoMapa->getProporcaoY(), 0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } /*! \fn PainelVisualizacaoOpenGL::mudaCores(QStringList listaCores) Function to modify the color`s variable. The new colors is stored by its name in the list listaCores. */ void PainelVisualizacaoOpenGL::mudaCores(QStringList listaCores){ corAlagamento = QColor(listaCores.at(0)); corBarragem = QColor(listaCores.at(1)); corMaiorElevacao = QColor(listaCores.at(2)); corMenorElevacao = QColor(listaCores.at(3)); corRedeDeDrenagem = QColor(listaCores.at(4)); } /*! \fn PainelVisualizacaoOpenGL::carregandoMapa(const char *arquivo) Function to create and load a new MDE to show user. */ void PainelVisualizacaoOpenGL::carregandoMapa(const char *arquivo){ visualizacaoMapa = new VisualizacaoMapa(arquivo, this->width(), this->height()); defineOrtho(); mapaEstaCarregado = true; computaFluxo(); updateGL(); } /*! \fn PainelVisualizacaoOpenGL::computaFluxo() Function to call the function for calculate the flow */ void PainelVisualizacaoOpenGL::computaFluxo() { visualizacaoMapa->fluxo->calculaFluxo(visualizacaoMapa->getMapa()->matrizDeElevacoes,visualizacaoMapa->getMapa()->getDadoInvalido()); updateGL(); } /*! \fn PainelVisualizacaoOpenGL::pintaEixo() Function to draw a guidance axis */ void PainelVisualizacaoOpenGL::pintaEixo(){ glPointSize(5); glBegin(GL_POINTS); glColor3f(0,0,0); for(int i = 0; i<this->width();i++){ if(i == this->width()/2) glColor3f(1,0,0); glVertex2i(i,0); } for(int i = 0; i< this->height();i++){ if(i == this->height()/2) glColor3f(0,0,0); glVertex2i(0,i); } glColor3f(0,0,1); glVertex2i(0,this->height()); glVertex2i(this->width(),0); glEnd(); } /*! \fn PainelVisualizacaoOpenGL::getCorGradient(double gradientProporcao) Function to discovery a color from a gradient made by the maximum and minimum cell`s elevation */ QColor PainelVisualizacaoOpenGL::getCorGradient(double gradientProporcao){ int rMenor = corMaiorElevacao.red()<corMenorElevacao.red()?corMaiorElevacao.red():corMenorElevacao.red(); int gMenor = corMaiorElevacao.green()<corMenorElevacao.green()?corMaiorElevacao.green():corMenorElevacao.green(); int bMenor = corMaiorElevacao.blue()<corMenorElevacao.blue()?corMaiorElevacao.blue():corMenorElevacao.blue(); int red = rMenor + abs(corMaiorElevacao.red() - corMenorElevacao.red())*gradientProporcao; int green = gMenor + abs(corMaiorElevacao.green() - corMenorElevacao.green())*gradientProporcao; int blue = bMenor + abs(corMaiorElevacao.blue() - corMenorElevacao.blue() )*gradientProporcao; QColor resp(red,green,blue); return resp; } /*! \fn PainelVisualizacaoOpenGL::pintaCamadas() Function to draw only the Camadas in listaDeCamadas */ void PainelVisualizacaoOpenGL::pintaCamadas(){ glBegin(GL_POINTS) ; for(int it = 0; it< visualizacaoMapa->listaDeCamadas->size();it++){ Camada c = visualizacaoMapa->listaDeCamadas->at(it); if(!c.estaVisivel) continue; for(int j = 0; j < c.listaDePontos.size();j++){ glColor3f(((float)c.getCorCamada().toRgb().red())/255,((float)c.getCorCamada().toRgb().green()/255),((float)c.getCorCamada().toRgb().blue()/255)); glVertex2f(c.listaDePontos.at(j).getJ(),c.listaDePontos.at(j).getI()); } } glEnd(); } /*! \fn PainelVisualizacaoOpenGL::pintaTudo() Function to draw everything */ void PainelVisualizacaoOpenGL::pintaTudo(){ double min = visualizacaoMapa->mapa->minElev; double max = visualizacaoMapa->mapa->maxElev; //para o ponto deve haver um fator de correcao //pois o mesmo nao esta associando o valor que deveria na teoria ser o correto glPointSize(visualizacaoMapa->getTamanhoDoPonto()); glBegin(GL_POINTS) ; for(int i = 0; i < visualizacaoMapa->mapa->getNLinhas();i++){ for(int j = 0; j < visualizacaoMapa->mapa->getNColunas();j++){ if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j] == visualizacaoMapa->mapa->getDadoInvalido()){ glColor3f(1,1,1); if(visualizacaoMapa->fluxo->rio[i][j]) glColor3f(float(corRedeDeDrenagem.red())/255,(float)corRedeDeDrenagem.green()/255,(float)corRedeDeDrenagem.blue()/255); } else{ double gradientProporcao = (visualizacaoMapa->mapa->matrizDeElevacoes[i][j] - min)/(max-min); QColor corGradient = getCorGradient(gradientProporcao); if(visualizacaoMapa->inundacao->matrizEstados[i][j] == 1) if(!visualizacaoMapa->fluxo->rio[i][j]) //Se não for rio, pinta cor normal, caso contrário, azul glColor3f((float)corGradient.red()/255,(float)corGradient.green()/255,(float)corGradient.blue()/255); else glColor3f(float(corRedeDeDrenagem.red())/255,(float)corRedeDeDrenagem.green()/255,(float)corRedeDeDrenagem.blue()/255); else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==2) { //barragem glColor3f(float(corBarragem.red())/255,(float)corBarragem.green()/255,(float)corBarragem.blue()/255); } //else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==3) { //acima_barragem // glColor3f(.5f, .5f, .5f); //} else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==4) {//água na borda da barragem glColor3f(0.0f, 0.75f, 1.0); } else if (visualizacaoMapa->inundacao->matrizEstados[i][j]==5) { //água glColor3f(float(corAlagamento.red())/255,(float)corAlagamento.green()/255,(float)corAlagamento.blue()/255); } } // for(int it = 0; it< visualizacaoMapa->listaDeCamadas->size();it++){ // Camada c = visualizacaoMapa->listaDeCamadas->at(it); // if(!c.estaVisivel) continue; // if(c.pontos[i][j]) // glColor3f(((float)c.getCorCamada().toRgb().red())/255,((float)c.getCorCamada().toRgb().green()/255),((float)c.getCorCamada().toRgb().blue()/255)); // } glVertex2f(j,i); } } //imprimindo as camadas //nao eh o metodo mais eficiente, pois poderiamos varrer a matriz uma unica vez e // ir imprimindo as camadas pintaCamadas(); // for(int it = 0; it< visualizacaoMapa->listaDeCamadas->size();it++){ // Camada c = visualizacaoMapa->listaDeCamadas->at(it); // if(!c.estaVisivel) continue; // glColor3f(((float)c.getCorCamada().toRgb().red())/255,((float)c.getCorCamada().toRgb().green()/255),((float)c.getCorCamada().toRgb().blue()/255)); // for(int i = 0; i < visualizacaoMapa->mapa->getNLinhas();i++){ // for(int j = 0; j < visualizacaoMapa->mapa->getNColunas();j++){ // if(c.pontos[i][j]) // glVertex2f(j,i); // } // } // } glEnd() ; //teste imprimindo aonde setou mouse glBegin(GL_POINTS) ; //glPointSize(60); glColor3f(1,0,0); glVertex2f(posClickX,posClickY); glColor3f(1,1,1); glVertex2f(visualizacaoMapa->marcaInicioX,visualizacaoMapa->marcaInicioY); glColor3f(0.5f,0.5f,0.5f); glVertex2f(visualizacaoMapa->marcaFinalX,visualizacaoMapa->marcaFinalY); glEnd(); } /*! \fn PainelVisualizacaoOpenGL::paintGL() Opengl functions needed. For opengl painting. Decide here if it will paint all or a part of scenario. */ void PainelVisualizacaoOpenGL::paintGL(){ if(mapaEstaCarregado == true){ if(flagPinta){ glClearColor(1.0f,1.0f,1.0f,.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); pintaTudo(); } else{ glLoadIdentity(); pintaCamadas(); } }else{ glClearColor(1.0f,1.0f,1.0f,.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); } } <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelaopcaofb.ui' ** ** Created: Mon 1. Oct 19:01:30 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELAOPCAOFB_H #define UI_JANELAOPCAOFB_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QCheckBox> #include <QtGui/QDialog> #include <QtGui/QDialogButtonBox> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_janelaopcaofb { public: QDialogButtonBox *buttonBox; QGroupBox *groupBox; QWidget *layoutWidget; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label; QLineEdit *caixaEntradaPesoEB; QHBoxLayout *horizontalLayout_2; QLabel *label_2; QLineEdit *caixaEntradaPesoHB; QHBoxLayout *horizontalLayout_3; QLabel *label_3; QLineEdit *caixaEntradaPesoAB; QGroupBox *groupBox_2; QWidget *layoutWidget1; QVBoxLayout *verticalLayout_2; QHBoxLayout *horizontalLayout_4; QLabel *label_4; QLineEdit *caixaEntradaPesoC; QHBoxLayout *horizontalLayout_5; QLabel *label_5; QLineEdit *caixaEntradaPesoAA; QLabel *label_7; QCheckBox *checkBoxPadrao; void setupUi(QDialog *janelaopcaofb) { if (janelaopcaofb->objectName().isEmpty()) janelaopcaofb->setObjectName(QString::fromUtf8("janelaopcaofb")); janelaopcaofb->resize(286, 236); janelaopcaofb->setMinimumSize(QSize(286, 236)); janelaopcaofb->setMaximumSize(QSize(286, 16777215)); QIcon icon; icon.addFile(QString::fromUtf8("../imagens/logo3.png"), QSize(), QIcon::Normal, QIcon::Off); janelaopcaofb->setWindowIcon(icon); buttonBox = new QDialogButtonBox(janelaopcaofb); buttonBox->setObjectName(QString::fromUtf8("buttonBox")); buttonBox->setGeometry(QRect(64, 200, 157, 32)); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); groupBox = new QGroupBox(janelaopcaofb); groupBox->setObjectName(QString::fromUtf8("groupBox")); groupBox->setGeometry(QRect(6, 74, 133, 119)); layoutWidget = new QWidget(groupBox); layoutWidget->setObjectName(QString::fromUtf8("layoutWidget")); layoutWidget->setGeometry(QRect(14, 24, 113, 80)); verticalLayout = new QVBoxLayout(layoutWidget); verticalLayout->setSpacing(0); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); horizontalLayout = new QHBoxLayout(); horizontalLayout->setSpacing(6); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); label = new QLabel(layoutWidget); label->setObjectName(QString::fromUtf8("label")); horizontalLayout->addWidget(label); caixaEntradaPesoEB = new QLineEdit(layoutWidget); caixaEntradaPesoEB->setObjectName(QString::fromUtf8("caixaEntradaPesoEB")); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(caixaEntradaPesoEB->sizePolicy().hasHeightForWidth()); caixaEntradaPesoEB->setSizePolicy(sizePolicy); horizontalLayout->addWidget(caixaEntradaPesoEB); verticalLayout->addLayout(horizontalLayout); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setSpacing(22); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); label_2 = new QLabel(layoutWidget); label_2->setObjectName(QString::fromUtf8("label_2")); horizontalLayout_2->addWidget(label_2); caixaEntradaPesoHB = new QLineEdit(layoutWidget); caixaEntradaPesoHB->setObjectName(QString::fromUtf8("caixaEntradaPesoHB")); sizePolicy.setHeightForWidth(caixaEntradaPesoHB->sizePolicy().hasHeightForWidth()); caixaEntradaPesoHB->setSizePolicy(sizePolicy); horizontalLayout_2->addWidget(caixaEntradaPesoHB); verticalLayout->addLayout(horizontalLayout_2); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setSpacing(28); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); label_3 = new QLabel(layoutWidget); label_3->setObjectName(QString::fromUtf8("label_3")); horizontalLayout_3->addWidget(label_3); caixaEntradaPesoAB = new QLineEdit(layoutWidget); caixaEntradaPesoAB->setObjectName(QString::fromUtf8("caixaEntradaPesoAB")); sizePolicy.setHeightForWidth(caixaEntradaPesoAB->sizePolicy().hasHeightForWidth()); caixaEntradaPesoAB->setSizePolicy(sizePolicy); horizontalLayout_3->addWidget(caixaEntradaPesoAB); verticalLayout->addLayout(horizontalLayout_3); groupBox_2 = new QGroupBox(janelaopcaofb); groupBox_2->setObjectName(QString::fromUtf8("groupBox_2")); groupBox_2->setGeometry(QRect(148, 74, 131, 119)); layoutWidget1 = new QWidget(groupBox_2); layoutWidget1->setObjectName(QString::fromUtf8("layoutWidget1")); layoutWidget1->setGeometry(QRect(10, 38, 107, 52)); verticalLayout_2 = new QVBoxLayout(layoutWidget1); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); verticalLayout_2->setContentsMargins(0, 0, 0, 0); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setSpacing(15); horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4")); label_4 = new QLabel(layoutWidget1); label_4->setObjectName(QString::fromUtf8("label_4")); horizontalLayout_4->addWidget(label_4); caixaEntradaPesoC = new QLineEdit(layoutWidget1); caixaEntradaPesoC->setObjectName(QString::fromUtf8("caixaEntradaPesoC")); horizontalLayout_4->addWidget(caixaEntradaPesoC); verticalLayout_2->addLayout(horizontalLayout_4); horizontalLayout_5 = new QHBoxLayout(); horizontalLayout_5->setSpacing(23); horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5")); label_5 = new QLabel(layoutWidget1); label_5->setObjectName(QString::fromUtf8("label_5")); horizontalLayout_5->addWidget(label_5); caixaEntradaPesoAA = new QLineEdit(layoutWidget1); caixaEntradaPesoAA->setObjectName(QString::fromUtf8("caixaEntradaPesoAA")); horizontalLayout_5->addWidget(caixaEntradaPesoAA); verticalLayout_2->addLayout(horizontalLayout_5); label_7 = new QLabel(janelaopcaofb); label_7->setObjectName(QString::fromUtf8("label_7")); label_7->setGeometry(QRect(30, 12, 233, 57)); label_7->setAlignment(Qt::AlignCenter); label_7->setWordWrap(true); checkBoxPadrao = new QCheckBox(janelaopcaofb); checkBoxPadrao->setObjectName(QString::fromUtf8("checkBoxPadrao")); checkBoxPadrao->setGeometry(QRect(226, 206, 70, 17)); retranslateUi(janelaopcaofb); QObject::connect(buttonBox, SIGNAL(accepted()), janelaopcaofb, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), janelaopcaofb, SLOT(reject())); QMetaObject::connectSlotsByName(janelaopcaofb); } // setupUi void retranslateUi(QDialog *janelaopcaofb) { janelaopcaofb->setWindowTitle(QApplication::translate("janelaopcaofb", "Peso das caracter\303\255sticas", 0, QApplication::UnicodeUTF8)); groupBox->setTitle(QApplication::translate("janelaopcaofb", "Barragem", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("janelaopcaofb", "Extens\303\243o", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("janelaopcaofb", "Altura", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("janelaopcaofb", "\303\201rea", 0, QApplication::UnicodeUTF8)); groupBox_2->setTitle(QApplication::translate("janelaopcaofb", "Reservat\303\263rio", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("janelaopcaofb", "Volume", 0, QApplication::UnicodeUTF8)); label_5->setText(QApplication::translate("janelaopcaofb", "\303\201rea ", 0, QApplication::UnicodeUTF8)); label_7->setText(QApplication::translate("janelaopcaofb", "Dica: quanto maior o peso mais cr\303\255tica \303\251 a caracter\303\255stica. I.e. \303\251 mais importante (necess\303\241rio) que ap\303\263s gerar o reservat\303\263rio esta caracter\303\255stica tenha o seu valor mais baixo", 0, QApplication::UnicodeUTF8)); checkBoxPadrao->setText(QApplication::translate("janelaopcaofb", "Padr\303\243o", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class janelaopcaofb: public Ui_janelaopcaofb {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELAOPCAOFB_H <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelabarragem.ui' ** ** Created: Mon 1. Oct 21:22:54 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELABARRAGEM_H #define UI_JANELABARRAGEM_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QHeaderView> #include <QtGui/QSpinBox> #include "painelvisualizacaobarragemopengl.h" QT_BEGIN_NAMESPACE class Ui_janelabarragem { public: PainelVisualizacaoBarragemOpenGL *widget; QSpinBox *spinBoxPosicaoX; QSpinBox *spinBoxPosicaoY; QSpinBox *spinBoxPosicaoZ; QSpinBox *spinBoxDirecaoY; QSpinBox *spinBoxDirecaoX; QSpinBox *spinBoxDirecaoZ; QSpinBox *spinBoxNormalZ; QSpinBox *spinBoxNormalX; QSpinBox *spinBoxNormalY; void setupUi(QDialog *janelabarragem) { if (janelabarragem->objectName().isEmpty()) janelabarragem->setObjectName(QString::fromUtf8("janelabarragem")); janelabarragem->setEnabled(true); janelabarragem->resize(399, 426); janelabarragem->setModal(false); widget = new PainelVisualizacaoBarragemOpenGL(janelabarragem); widget->setObjectName(QString::fromUtf8("widget")); widget->setGeometry(QRect(20, 10, 351, 311)); widget->setMouseTracking(true); widget->setFocusPolicy(Qt::ClickFocus); widget->setAutoFillBackground(true); spinBoxPosicaoX = new QSpinBox(janelabarragem); spinBoxPosicaoX->setObjectName(QString::fromUtf8("spinBoxPosicaoX")); spinBoxPosicaoX->setGeometry(QRect(340, 350, 42, 22)); spinBoxPosicaoY = new QSpinBox(janelabarragem); spinBoxPosicaoY->setObjectName(QString::fromUtf8("spinBoxPosicaoY")); spinBoxPosicaoY->setGeometry(QRect(300, 330, 42, 22)); spinBoxPosicaoZ = new QSpinBox(janelabarragem); spinBoxPosicaoZ->setObjectName(QString::fromUtf8("spinBoxPosicaoZ")); spinBoxPosicaoZ->setGeometry(QRect(300, 370, 42, 22)); spinBoxPosicaoZ->setMaximum(1000); spinBoxDirecaoY = new QSpinBox(janelabarragem); spinBoxDirecaoY->setObjectName(QString::fromUtf8("spinBoxDirecaoY")); spinBoxDirecaoY->setGeometry(QRect(160, 330, 42, 22)); spinBoxDirecaoX = new QSpinBox(janelabarragem); spinBoxDirecaoX->setObjectName(QString::fromUtf8("spinBoxDirecaoX")); spinBoxDirecaoX->setGeometry(QRect(200, 350, 42, 22)); spinBoxDirecaoZ = new QSpinBox(janelabarragem); spinBoxDirecaoZ->setObjectName(QString::fromUtf8("spinBoxDirecaoZ")); spinBoxDirecaoZ->setGeometry(QRect(160, 370, 42, 22)); spinBoxNormalZ = new QSpinBox(janelabarragem); spinBoxNormalZ->setObjectName(QString::fromUtf8("spinBoxNormalZ")); spinBoxNormalZ->setGeometry(QRect(40, 370, 42, 22)); spinBoxNormalX = new QSpinBox(janelabarragem); spinBoxNormalX->setObjectName(QString::fromUtf8("spinBoxNormalX")); spinBoxNormalX->setGeometry(QRect(80, 350, 42, 22)); spinBoxNormalY = new QSpinBox(janelabarragem); spinBoxNormalY->setObjectName(QString::fromUtf8("spinBoxNormalY")); spinBoxNormalY->setGeometry(QRect(40, 330, 42, 22)); retranslateUi(janelabarragem); QMetaObject::connectSlotsByName(janelabarragem); } // setupUi void retranslateUi(QDialog *janelabarragem) { janelabarragem->setWindowTitle(QApplication::translate("janelabarragem", "Dialog", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class janelabarragem: public Ui_janelabarragem {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELABARRAGEM_H <file_sep>// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : VisualizacaoMapa.cpp // @ Date : 06/09/2011 // @ Author : // // #include "VisualizacaoMapa.h" #include "MapaMDE.h" #include "math.h" #include "fstream" #include <QDate> #include<janelaprincipal.h> /*! \class VisualizacaoMapa \previouspage PainelVisualizacaoOpenGL \nextpage All Classes \startpage All Classes \brief Class to represent a visualization of all contents in the process of creating a reservoir */ /*! \variable VisualizacaoMapa::mapa \brief a pointer to MapaMDE object. */ /*! \variable VisualizacaoMapa::fluxo \brief a pointer to Fluxo object. */ /*! \variable VisualizacaoMapa::inundacao \brief a pointer to Inundacao object. */ /*! \variable VisualizacaoMapa::listaDeCamadas \brief a list of Camada to hold the Camadas create by user */ /*! \variable VisualizacaoMapa::camadasSomadas \brief a pointer to pointer, representing a matrix of sum of Camadas to help in position algorithm */ /*! \variable VisualizacaoMapa::vetorDeZooms \brief a pointer to pointer, representig a matrix with the value of zooms possible in this MDE */ /*! \variable VisualizacaoMapa::marcaInicioX \brief the start position in axis-x of the drainage network's stretch */ /*! \variable VisualizacaoMapa::marcaFinalX \brief the end position in axis-x of the drainage network's stretch */ /*! \variable VisualizacaoMapa::marcaInicioY \brief the start position in axis-y of the drainage network's stretch */ /*! \variable VisualizacaoMapa::marcaFinalY \brief the end position in axis-y of the drainage network's stretch */ /*! \variable VisualizacaoMapa::marcouInicio \brief the flag to hold if user has marked the start position of drainage network's stretch */ /*! \variable VisualizacaoMapa::marcouFim \brief the flag to hold if user has marked the end position of drainage network's stretch */ /*! \variable VisualizacaoMapa::proporcaoZoom \brief an internal variable for the proportion of the zoom. It's used to definy the point size */ /*! \variable VisualizacaoMapa::constanteDeProporcaoZoom \brief the value for a constant variable used in proporcaoZoom */ /*! \variable VisualizacaoMapa::tamanhoDaBarraDeZoom \brief the size of zoom bar */ /*! \variable VisualizacaoMapa::maxPointSize \brief the maximum point's size */ /*! \variable VisualizacaoMapa::estaPreSalvo \brief the flag to control if this visualization is saved in Area de Projeto */ /*! \variable VisualizacaoMapa::pesoEBarragem \brief the value of the weight for dam's extent. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoHBarragem \brief the value of the weight for dam's high. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoAreaAlagada \brief the value of the weight for flooded area. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoVolume \brief the value of the weight for reservoir's volume. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoABarragem \brief the value of the weight for dam's area. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoCamadas \brief the value of the sum of cell's in camadasSomadas that are in the resorvoir. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoEBarragemPadrao \brief the default value of the weight for dam's extent. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoHBarragemPadrao \brief the default value of the weight for dam's high. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoAreaAlagadaPadrao \brief the default value of the weight for flooded area. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoVolumePadrao \brief the default value of the weight for reservoir's volume. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoABarragemPadrao \brief the default value of the weight for dam's area. Used in position algorithm */ /*! \variable VisualizacaoMapa::pesoCamadasPadrao \brief the default value of the sum of cell's in camadasSomadas that are in the resorvoir. Used in position algorithm */ /*! \variable VisualizacaoMapa::maxPontosABuscar \brief the maximun iteration for recursive functions */ /*! \fn VisualizacaoMapa::VisualizacaoMapa() Default Constructor. Creates a object with its pointers set to null */ VisualizacaoMapa::VisualizacaoMapa(){ mapa = NULL; fluxo = NULL; inundacao = NULL; vetorDeZooms = NULL; } /*! \fn VisualizacaoMapa::VisualizacaoMapa(const char *caminhoMapa, int largura, int altura) Constructor. Creates a object VisualizacaoMapa for the path caminhoMapa */ VisualizacaoMapa::VisualizacaoMapa(const char *caminhoMapa, int largura, int altura) { mapa = new MapaMDE(caminhoMapa); fluxo = new Fluxo(mapa->getNLinhas(),mapa->getNColunas()); inundacao = new Inundacao(mapa->getNLinhas(),mapa->getNColunas()); //setando as variaveis para valores padroes zoom = 0; //variaveis constantes de proporcoes constanteDeProporcaoZoom = 0.1; proporcaoTela = 1; proporcaoX = mapa->getNColunas()*proporcaoTela; proporcaoY = mapa->getNLinhas()*proporcaoTela; larguraTela = largura; alturaTela = altura; //===Define proporção de zoom e tamanho do ponto inicialmente=== proporcaoZoom = zoom*constanteDeProporcaoZoom +1; float fatorDeCorrecao = 1; tamanhoDoPonto = (larguraTela/proporcaoX) > (alturaTela/proporcaoY)?(larguraTela/proporcaoX):(alturaTela/proporcaoY) ; tamanhoDoPonto += fatorDeCorrecao; maxPointSize = 63; double maiorProporcao = 1.0*alturaTela/proporcaoY > 1.0*larguraTela/proporcaoX ? (double)alturaTela*1.0/proporcaoY : (double)larguraTela*1.0/proporcaoX; //===Define aqui o tamanho da barra de zoom em função do maior valor possivel para o ponto=== tamanhoDaBarraDeZoom = (maxPointSize/(maiorProporcao) - 1.0)/constanteDeProporcaoZoom; tamanhoDaBarraDeZoom = maxPointSize>tamanhoDaBarraDeZoom?tamanhoDaBarraDeZoom:maxPointSize-1; //===Define o tamanho do vetor de zooms em função do tamanho da barra=== tamanhoDaBarraDeZoom = 25; vetorDeZooms = new double *[2]; for(int i = 0;i < 2; i++) vetorDeZooms[i] = new double[tamanhoDaBarraDeZoom+1]; //===Inicializa o valor de cada zoom=== for(int i=0; i<=tamanhoDaBarraDeZoom ; i++) { vetorDeZooms[0][i] = larguraTela*(i*0.1+1); vetorDeZooms[1][i] = alturaTela*(i*0.1+1); } listaDeCamadas = new QList<Camada>(); estaPreSalvo = false; //sera definido que se buscara em maxPontosABuscar = this->fluxo->qtdeCelulasRio; pesoEBarragem = pesoEBarragemPadrao; pesoHBarragem = pesoHBarragemPadrao; pesoAreaAlagada = pesoAreaAlagadaPadrao; pesoVolume = pesoVolumePadrao; pesoABarragem = pesoABarragemPadrao; pesoCamadas = pesoCamadasPadrao; camadasSomadas = new short int*[mapa->getNLinhas()]; for(int i=0; i<mapa->getNLinhas(); ++i) { camadasSomadas[i] = new short int[mapa->getNColunas()]; for(int j=0; j<mapa->getNLinhas() ; ++j) camadasSomadas[i][j] = 0; } } /*! \overload VisualizacaoMapa::operator=(QList<Camada> const& listaCamada) Operator to set listaCamada to variable listaDeCamadas */ QList<Camada> &VisualizacaoMapa::operator=(QList<Camada> const& listaCamada){ if(listaDeCamadas == &listaCamada) return *listaDeCamadas; for( int it = 0 ; it< listaCamada.size();it++) listaDeCamadas->insert(it, listaCamada.at(it)); return *listaDeCamadas; } /*! \fn VisualizacaoMapa::insereCamada(Camada c) Function to insert Camada c in listaDeCamadas */ void VisualizacaoMapa::insereCamada(Camada c){ listaDeCamadas->push_back(c); } /*! \fn VisualizacaoMapa::getIndCamada(QString nome) Function to return the index of Camada named as nome in listaDeCamadas */ int VisualizacaoMapa::getIndCamada(QString nome){ for(int i = 0; i< listaDeCamadas->size();i++){ Camada c = listaDeCamadas->at(i); if( c.getNome() == nome) return i; } return -1; } /*! \overload VisualizacaoMapa::operator=(VisualizacaoMapa const& viMapa) Overloaded operator to assign the object viMapa to the current object(this) */ VisualizacaoMapa & VisualizacaoMapa::operator=(VisualizacaoMapa const& viMapa){ mapa = new MapaMDE(*viMapa.mapa); fluxo = new Fluxo(*viMapa.fluxo); inundacao = new Inundacao(*viMapa.inundacao); //setando as variaveis para valores padroes zoom = viMapa.zoom; //variaveis constantes de proporcoes constanteDeProporcaoZoom = viMapa.constanteDeProporcaoZoom; proporcaoTela = viMapa.proporcaoTela; proporcaoX = viMapa.proporcaoX; proporcaoY = viMapa.proporcaoY; larguraTela = viMapa.larguraTela; alturaTela = viMapa.alturaTela; //===Define proporção de zoom e tamanho do ponto inicialmente=== proporcaoZoom = viMapa.proporcaoZoom; tamanhoDoPonto = viMapa.tamanhoDoPonto; maxPointSize = viMapa.maxPointSize; //===Define aqui o tamanho da barra de zoom em função do maior valor possivel para o ponto=== tamanhoDaBarraDeZoom = viMapa.tamanhoDaBarraDeZoom; //===Define o tamanho do vetor de zooms em função do tamanho da barra=== vetorDeZooms = new double *[2]; for(int i = 0;i < 2; i++) vetorDeZooms[i] = new double[tamanhoDaBarraDeZoom+1]; //===Inicializa o valor de cada zoom=== for(int i=0; i<=tamanhoDaBarraDeZoom ; i++) { vetorDeZooms[0][i] = viMapa.vetorDeZooms[0][i]; vetorDeZooms[1][i] = viMapa.vetorDeZooms[1][i]; } estaPreSalvo = viMapa.estaPreSalvo; listaDeCamadas = new QList<Camada>(); for(int i = 0; i< viMapa.listaDeCamadas->size();i++) listaDeCamadas->insert(i,viMapa.listaDeCamadas->at(i)); maxPontosABuscar = viMapa.maxPontosABuscar; pesoEBarragem = viMapa.pesoEBarragem; pesoHBarragem = viMapa.pesoHBarragem; pesoAreaAlagada = viMapa.pesoAreaAlagada; pesoVolume = viMapa.pesoVolume; pesoABarragem =viMapa.pesoABarragem; pesoCamadas =viMapa.pesoCamadas; camadasSomadas = new short int*[mapa->getNLinhas()]; for(int i=0; i<mapa->getNLinhas(); ++i) { camadasSomadas[i] = new short int[mapa->getNColunas()]; for(int j=0; j<mapa->getNLinhas() ; ++j) camadasSomadas[i][j] = viMapa.camadasSomadas[i][j]; } return *this; } /*! \fn VisualizacaoMapa::VisualizacaoMapa(VisualizacaoMapa const &viMapa) Copy Constructor. Creates an object receiving attributes from viMapa */ VisualizacaoMapa::VisualizacaoMapa(VisualizacaoMapa const &viMapa){ mapa = new MapaMDE(*viMapa.mapa); fluxo = new Fluxo(*viMapa.fluxo); inundacao = new Inundacao(*viMapa.inundacao); //setando as variaveis para valores padroes zoom = 0; //variaveis constantes de proporcoes constanteDeProporcaoZoom = viMapa.constanteDeProporcaoZoom; proporcaoTela = viMapa.proporcaoTela; proporcaoX = viMapa.proporcaoX; proporcaoY = viMapa.proporcaoY; larguraTela = viMapa.larguraTela; alturaTela = viMapa.alturaTela; //===Define proporção de zoom e tamanho do ponto inicialmente=== proporcaoZoom = viMapa.proporcaoZoom; tamanhoDoPonto = viMapa.tamanhoDoPonto; maxPointSize = viMapa.maxPointSize; //===Define aqui o tamanho da barra de zoom em função do maior valor possivel para o ponto=== tamanhoDaBarraDeZoom = viMapa.tamanhoDaBarraDeZoom; //===Define o tamanho do vetor de zooms em função do tamanho da barra=== vetorDeZooms = new double *[2]; for(int i = 0;i < 2; i++) vetorDeZooms[i] = new double[tamanhoDaBarraDeZoom+1]; //===Inicializa o valor de cada zoom=== for(int i=0; i<=tamanhoDaBarraDeZoom ; i++) { vetorDeZooms[0][i] = viMapa.vetorDeZooms[0][i]; vetorDeZooms[1][i] = viMapa.vetorDeZooms[1][i]; } estaPreSalvo = viMapa.estaPreSalvo; listaDeCamadas = new QList<Camada>(); for(int i = 0; i< viMapa.listaDeCamadas->size();i++) listaDeCamadas->insert(i,viMapa.listaDeCamadas->at(i)); maxPontosABuscar = viMapa.maxPontosABuscar; pesoEBarragem = viMapa.pesoEBarragem; pesoHBarragem = viMapa.pesoHBarragem; pesoAreaAlagada = viMapa.pesoAreaAlagada; pesoVolume = viMapa.pesoVolume; pesoABarragem =viMapa.pesoABarragem; pesoCamadas =viMapa.pesoCamadas; camadasSomadas = new short int*[mapa->getNLinhas()]; for(int i=0; i<mapa->getNLinhas(); ++i) { camadasSomadas[i] = new short int[mapa->getNColunas()]; for(int j=0; j<mapa->getNLinhas() ; ++j) camadasSomadas[i][j] = viMapa.camadasSomadas[i][j]; } } /*! \fn VisualizacaoMapa::getMapa() Returns mapa */ MapaMDE *VisualizacaoMapa::getMapa() { return mapa; } /*! \fn VisualizacaoMapa::getZoom() Returns zoom */ int VisualizacaoMapa::getZoom() { return zoom; } /*! \fn VisualizacaoMapa::setZoom(int zoom) Function to set the zoom value */ void VisualizacaoMapa::setZoom(int zoom) { //aqui mexeremos nas variaveis quando ocorrer o zoom this->zoom = zoom; proporcaoZoom = zoom*constanteDeProporcaoZoom +1; setTamanhoPonto(larguraTela,alturaTela); } /*! \fn VisualizacaoMapa::setTamanhoPonto(int larguraTela, int alturaTela) Function to calculate and set the point size */ void VisualizacaoMapa::setTamanhoPonto(int larguraTela, int alturaTela){ float fatorDeCorrecao = 1; tamanhoDoPonto = (larguraTela/proporcaoX) > (alturaTela/proporcaoY)?(larguraTela*proporcaoZoom/proporcaoX):(alturaTela*proporcaoZoom/proporcaoY) ; tamanhoDoPonto = tamanhoDoPonto + fatorDeCorrecao; this->alturaTela = alturaTela; this->larguraTela = larguraTela; } /*! \fn VisualizacaoMapa::encontraPontosJusante(int x, int y,bool& encontrado, bool** matrizVisitados, int &pontosBuscados) Function to look for points(and creates the list of candidates to position the dam) until the end point of stretch drainage network is founded. */ void VisualizacaoMapa::encontraPontosJusante(int x, int y,bool& encontrado, bool** matrizVisitados, int &pontosBuscados){ if(pontosBuscados > this->fluxo->qtdeCelulasRio) throw pontosBuscados; if(x == marcaFinalX && y == marcaFinalY){ //Se encontrou ponto marcado como final, termina encontrado = true; return; } //Visita vizinhos em sentindo horário //A partir do vizinho superior esquerdo (x-1,y-1) //Vizinho (x-1,y-1) if(x-1>=0 && y-1>=0 && x-1<this->getMapa()->getNColunas() && y-1<this->getMapa()->getNLinhas()) if(fluxo->rio[y-1][x-1] && !matrizVisitados[y-1][x-1]){ matrizVisitados[y-1][x-1] = true; pontosBuscados++; encontraPontosJusante(x-1,y-1,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y-1][x-1] = false; } //Vizinho (x,y-1) if(x>=0 && y-1>=0 && x<getMapa()->getNColunas() && y-1<getMapa()->getNLinhas()) if(fluxo->rio[y-1][x] && !matrizVisitados[y-1][x]){ matrizVisitados[y-1][x] = true; pontosBuscados++; encontraPontosJusante(x,y-1,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y-1][x] = false; } //Vizinho (x+1,y-1) if(x+1>=0 && y-1>=0 && x+1<getMapa()->getNColunas() && y-1<getMapa()->getNLinhas()) if(fluxo->rio[y-1][x+1] && !matrizVisitados[y-1][x+1]){ matrizVisitados[y-1][x+1] = true; pontosBuscados++; encontraPontosJusante(x+1,y-1,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y-1][x+1] = false; } //Vizinho (x+1,y) if(x+1>=0 && y>=0 && x+1<getMapa()->getNColunas() && y<getMapa()->getNLinhas()) if(fluxo->rio[y][x+1] && !matrizVisitados[y][x+1]){ matrizVisitados[y][x+1] = true; pontosBuscados++; encontraPontosJusante(x+1,y,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y][x+1] = false; } //Vizinho (x+1,y+1) if(x+1>=0 && y+1>=0 && x+1<getMapa()->getNColunas() && y+1<getMapa()->getNLinhas()) if(fluxo->rio[y+1][x+1] && !matrizVisitados[y+1][x+1]){ matrizVisitados[y+1][x+1] = true; pontosBuscados++; encontraPontosJusante(x+1,y+1,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y+1][x+1] = false; } //Vizinho (x,y+1) if(x>=0 && y+1>=0 && x<getMapa()->getNColunas() && y+1<getMapa()->getNLinhas()) if(fluxo->rio[y+1][x]&& !matrizVisitados[y+1][x]){ matrizVisitados[y+1][x] = true; pontosBuscados++; encontraPontosJusante(x,y+1,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y+1][x] = false; } //Vizinho (x-1,y+1) if(x-1>=0 && y+1>=0 && x-1<getMapa()->getNColunas() && y+1<getMapa()->getNLinhas()) if(fluxo->rio[y+1][x-1]&& !matrizVisitados[y+1][x-1]){ matrizVisitados[y+1][x-1] = true; pontosBuscados++; encontraPontosJusante(x-1,y+1,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y+1][x-1] = false; } //Vizinho (x-1,y) if(x-1>=0 && y>=0 && x-1<getMapa()->getNColunas() && y<getMapa()->getNLinhas()) if(fluxo->rio[y][x-1] && !matrizVisitados[y][x-1]){ matrizVisitados[y][x-1] = true; pontosBuscados++; encontraPontosJusante(x-1,y,encontrado,matrizVisitados,pontosBuscados); if(encontrado) return; //Marca ponto como não pertencente ao caminho matrizVisitados[y][x-1] = false; } } /*! \fn VisualizacaoMapa::atualizaCamadasSomadas() Function to sum all Camadas in listaDeCamadas, cell by cell. The answer is seted in th matrix camadasSomadas */ void VisualizacaoMapa::atualizaCamadasSomadas(){ if(listaDeCamadas->isEmpty()) return; for(int i=0; i<mapa->getNLinhas(); ++i){ for(int j=0; j<mapa->getNLinhas() ; ++j){ for(int k = 0; k< listaDeCamadas->size();k++){ if(!listaDeCamadas->at(k).estaVisivel) continue; if(listaDeCamadas->at(k).pontos[i][j]){ Camada aux = listaDeCamadas->at(k); camadasSomadas[i][j] += (aux).getPeso(); } } } } } /*! \fn VisualizacaoMapa::getFuncaoObjetivo() Function to return the value of objective function with the weights. */ int VisualizacaoMapa::getFuncaoObjetivo(){ int resp ; atualizaPesoCamadas(); resp = pesoEBarragem*inundacao->comprimentoBarragemTocada + pesoHBarragem*inundacao->nivelAgua + pesoAreaAlagada*inundacao->areaLaminaAgua + pesoVolume*inundacao->volumeAgua + pesoABarragem*inundacao->areaBarragemTocada + pesoCamadas; return resp; } /*! \fn VisualizacaoMapa::~VisualizacaoMapa() Destructor. */ VisualizacaoMapa::~VisualizacaoMapa(){ try{ //CUIDADO if(camadasSomadas != NULL){ for(int i=0;i< mapa->getNLinhas() ;i++) delete []this->camadasSomadas[i]; delete []this->camadasSomadas; this->camadasSomadas = NULL; } cout<<"Tentando deletar visualizaçao"; if(mapa != NULL){ delete this->mapa; this->mapa = NULL; } if(fluxo != NULL){ delete this->fluxo; this->fluxo = NULL; } if(inundacao != NULL){ delete this->inundacao; this->inundacao = NULL; } if(vetorDeZooms != NULL){ for(int i=0;i< 2;i++) delete []this->vetorDeZooms[i]; delete []this->vetorDeZooms; this->vetorDeZooms = NULL; } if(listaDeCamadas != NULL){ delete listaDeCamadas; listaDeCamadas = NULL; } }catch(exception e){ QString erroMsg="Erro no destrutor da classe VisualizacaoMapa"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } } /*! \fn VisualizacaoMapa::getProporcaoZoom() Function to return the proportion of the zoom */ double VisualizacaoMapa::getProporcaoZoom(){ return proporcaoZoom; } /*! \fn VisualizacaoMapa::getProporcaoX() Function to return the proportion in axis-x for the opengl painel */ int VisualizacaoMapa::getProporcaoX(){ return proporcaoX; } /*! \fn VisualizacaoMapa::getProporcaoY() Function to return the proportion in axis-y for the opengl painel */ int VisualizacaoMapa::getProporcaoY(){ return proporcaoY; } /*! \fn VisualizacaoMapa::getTamanhoDoPonto() Function to return the size of the point */ int VisualizacaoMapa::getTamanhoDoPonto(){ return tamanhoDoPonto; } /*! \fn VisualizacaoMapa::atualizaPesos(int aa,int ab,int c,int eb,int hb) Function to update the value of the weights */ void VisualizacaoMapa::atualizaPesos(int aa,int ab,int c,int eb,int hb){ pesoAreaAlagada = aa; pesoABarragem = ab; pesoVolume = c; pesoEBarragem = eb; pesoHBarragem = hb; } /*! \fn VisualizacaoMapa::atualizaPesoCamadas() Function to update the value of the Camada`s weight. Calculate price of all flooded cell. */ void VisualizacaoMapa::atualizaPesoCamadas(){ pesoCamadas = 0; /* #define BARRAGEM 2; #define AFLUENTE 1; #define ACIMA_BARRAGEM 3; #define AGUA_BORDA_BARRAGEM 4; #define AGUA 5; */ if(listaDeCamadas->isEmpty())return; for(int i=0; i<mapa->getNLinhas(); ++i){ for(int j=0; j<mapa->getNLinhas() ; ++j){ if(camadasSomadas[i][j]!=0){ if(inundacao->matrizEstados[i][j] == 5 || inundacao->matrizEstados[i][j]==2) pesoCamadas += camadasSomadas[i][j]; } } } } /*! \fn VisualizacaoMapa::setInundacao(int posX, int posY,int op,int val,int valEp) Function to create a reservoir. */ void VisualizacaoMapa::setInundacao(int posX, int posY,int op,int val,int valEp){ inundacao->inunda(posX,posY,fluxo->direcao,mapa->matrizDeElevacoes,fluxo->rio,op,val,valEp); } <file_sep>#include "janelaopcaofb.h" #include "ui_janelaopcaofb.h" #include <QMessageBox> /*! \class janelaopcaofb \previouspage janelaOpcaoCor \contentspage \nextpage JanelaPrincipal \startpage All Classes \brief Class to create the window objective function option */ janelaopcaofb::janelaopcaofb(QWidget *parent) : QDialog(parent), ui(new Ui::janelaopcaofb) { ui->setupUi(this); } janelaopcaofb::~janelaopcaofb() { delete ui; } QStringList janelaopcaofb::getValores(bool &ok){ QStringList resp; int botaoApertado = exec(); if(botaoApertado == QDialog::Accepted){ ok = true; if(ui->checkBoxPadrao->isChecked()) return resp; bool conv1,conv2,conv3,conv4,conv5; QString a; ui->caixaEntradaPesoAA->text().toInt(&conv1,10); ui->caixaEntradaPesoAB->text().toInt(&conv2,10); ui->caixaEntradaPesoC->text().toInt(&conv3,10); ui->caixaEntradaPesoEB->text().toInt(&conv4,10); ui->caixaEntradaPesoHB->text().toInt(&conv5,10); if(!conv1 || !conv2 || !conv3 || !conv4 ||!conv5){ QMessageBox a; a.setText("Erro nos parāmetros"); a.exec(); ok = false; return resp; } resp.append(ui->caixaEntradaPesoAA->text()); resp.append(ui->caixaEntradaPesoAB->text()); resp.append(ui->caixaEntradaPesoC->text()); resp.append(ui->caixaEntradaPesoEB->text()); resp.append(ui->caixaEntradaPesoHB->text()); }else ok = false; return resp; } <file_sep>#include "janelabarragem.h" #include "ui_janelabarragem.h" /*! \class janelabarragem \previouspage Inundacao \contentspage All Classes \nextpage janelaBarragem2D \indexpage Fluxo \startpage All Classes \brief Class to create a window 3D view of reservoir and terrain */ /*! \fn janelabarragem::janelabarragem(VisualizacaoMapa *viMapa,QWidget *parent) : QDialog(parent), ui(new Ui::janelabarragem) \brief Constructor the painel with 3D view of reservoir */ janelabarragem::janelabarragem(VisualizacaoMapa *viMapa,QWidget *parent) : QDialog(parent), ui(new Ui::janelabarragem) { ui->setupUi(this); setWindowFlags(Qt::Window); //posicionado sempre no cantinho superior direito da tela do programa this->setGeometry((parent->x()+ parent->width())- this->width(),parent->y(),this->width(),this->height()); ui->widget->makeCurrent(); ui->widget->carregandoInformacoes(viMapa); ui->widget->updateGL(); } /*! \fn janelabarragem::~janelabarragem() \brief Destructor */ janelabarragem::~janelabarragem() { delete ui; } void janelabarragem::on_pushButton_clicked() { } void janelabarragem::on_pushButton_2_clicked() { } void janelabarragem::on_novoDireCamX_valueChanged(int arg1) { } void janelabarragem::on_spinBoxPosicaoX_valueChanged(int arg1) { ui->widget->posicaoCamera[0] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxPosicaoZ_valueChanged(int arg1) { ui->widget->posicaoCamera[2] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxPosicaoY_valueChanged(int arg1) { ui->widget->posicaoCamera[1] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxDirecaoX_valueChanged(int arg1) { ui->widget->direcaoCamera[0] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxDirecaoY_valueChanged(int arg1) { ui->widget->direcaoCamera[1] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxDirecaoZ_valueChanged(int arg1) { ui->widget->direcaoCamera[2] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxNormalY_valueChanged(int arg1) { ui->widget->normalCamera[1] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxNormalX_valueChanged(int arg1) { ui->widget->normalCamera[0] = arg1; ui->widget->updateGL(); } void janelabarragem::on_spinBoxNormalZ_valueChanged(int arg1) { ui->widget->normalCamera[2] = arg1; ui->widget->updateGL(); } <file_sep>#ifndef JANELABARRAGEM_H #define JANELABARRAGEM_H #include <QDialog> #include "VisualizacaoMapa.h" namespace Ui { class janelabarragem; } class janelabarragem : public QDialog { Q_OBJECT public: explicit janelabarragem(VisualizacaoMapa*,QWidget *parent = 0); ~janelabarragem(); private slots: //slots para os botoes... void on_pushButton_clicked();//botao ok void on_pushButton_2_clicked();//botao cancel void on_novoDireCamX_valueChanged(int arg1); void on_spinBoxPosicaoX_valueChanged(int arg1); void on_spinBoxPosicaoZ_valueChanged(int arg1); void on_spinBoxPosicaoY_valueChanged(int arg1); void on_spinBoxDirecaoX_valueChanged(int arg1); void on_spinBoxDirecaoY_valueChanged(int arg1); void on_spinBoxDirecaoZ_valueChanged(int arg1); void on_spinBoxNormalY_valueChanged(int arg1); void on_spinBoxNormalX_valueChanged(int arg1); void on_spinBoxNormalZ_valueChanged(int arg1); private: Ui::janelabarragem *ui; }; #endif // JANELABARRAGEM_H <file_sep>#include "painelvisualizacaobarragem2dopengl.h" /*! \class painelvisualizacaobarragem2dopengl \previouspage MapaMDE \contentspage \nextpage PainelVisualizacaoBarragemOpenGL \startpage All Classes \brief Class to create a opengl painel with dam 2D visualization */ painelvisualizacaobarragem2dopengl::painelvisualizacaobarragem2dopengl(QWidget *parent) : QGLWidget(parent) { setFormat(QGL::SingleBuffer | QGL::DepthBuffer); maxAltura = 0; minAltura = 10000000; proporcaoAltura = 0; this->visualizacaoMapa = NULL; } void painelvisualizacaobarragem2dopengl::defineBarragem(){ //caso a lista de pontos da barragem nao esteja vazia reiniciala if(!pontosDaBarragem.empty()){ pontosDaBarragem.clear(); maxAltura = 0; minAltura = 10000000; proporcaoAltura = 0; } for(int i = 0;i<visualizacaoMapa->mapa->getNLinhas();i++){ for(int j = 0;j<visualizacaoMapa->mapa->getNColunas();j++){ //se for barragem poe na lista if(visualizacaoMapa->mapa->matrizDeElevacoes[i][j] == visualizacaoMapa->mapa->getDadoInvalido()) continue; if(visualizacaoMapa->inundacao->matrizEstados[i][j] == 2){ Point pAux(i,j); pontosDaBarragem.insert(pontosDaBarragem.end(),pAux); if(maxAltura< visualizacaoMapa->mapa->matrizDeElevacoes[i][j]) maxAltura = visualizacaoMapa->mapa->matrizDeElevacoes[i][j]; if(minAltura > visualizacaoMapa->mapa->matrizDeElevacoes[i][j]) minAltura = visualizacaoMapa->mapa->matrizDeElevacoes[i][j]; } } } proporcaoAltura = (minAltura - int(maxAltura/minAltura)); proporcaoImpressao = ((maxAltura + int(maxAltura/minAltura)) - proporcaoAltura); } void painelvisualizacaobarragem2dopengl::carregandoInformacoes(VisualizacaoMapa *viMapa){ if(visualizacaoMapa != NULL){ delete visualizacaoMapa; this->visualizacaoMapa = NULL; } visualizacaoMapa = new VisualizacaoMapa(*viMapa); defineBarragem(); defineOrtho(); updateGL(); } void painelvisualizacaobarragem2dopengl::defineOrtho(){ glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0,50,50, 0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void painelvisualizacaobarragem2dopengl::initializeGL(){ glClearColor(1.0f,1.0f,1.0f,.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_ALWAYS); glHint(GL_POINT_SMOOTH_HINT,GL_PERSPECTIVE_CORRECTION_HINT); } void painelvisualizacaobarragem2dopengl::resizeGL(int w, int h){ glViewport(0,0,w,h); } void painelvisualizacaobarragem2dopengl::paintGL(){ glClearColor(1.0f,1.0f,1.0f,.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-(pontosDaBarragem.size()*0.1),pontosDaBarragem.size()*1.1,0, proporcaoImpressao); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //IMPRIMINDO barragem/ for(int i = 0; i<pontosDaBarragem.size();i++){ int iPonto = (pontosDaBarragem.at(i)).getI(); int jPonto = (pontosDaBarragem.at(i)).getJ(); int elevacao = visualizacaoMapa->mapa->matrizDeElevacoes[iPonto][jPonto]; if( visualizacaoMapa->inundacao->posicaoBarragem.x == jPonto && visualizacaoMapa->inundacao->posicaoBarragem.y == iPonto ) glColor3f(0,0,0); else glColor3f(0,1,0); glBegin(GL_QUADS); glVertex2f(i,0); glVertex2f(i,elevacao - proporcaoAltura); glVertex2f(i+1,elevacao - proporcaoAltura); glVertex2f(i+1,0); glEnd(); //defindo eixo if(i == 0 || (i == (pontosDaBarragem.size()-1)) ) glColor3f(1,0,0); else glColor3f(0,0,0); glBegin(GL_POINTS); glVertex2f(i,0); glEnd(); } } <file_sep>This is a master's degree project. Create under UFV-DPI master's degree program. This system defines the best position to construct a dam to supply a water scarcity in part of the drainage network. This system uses the RWFlood algorithm to calculate the drainage network. The grouping files is defined by QtCreator. In ./ProjetoHidro/docs has a lot of documents about classes in the system. contact <EMAIL> Developed by <NAME> <NAME>(assistant) Collaborators TARG/DPI TEAM <file_sep>#ifndef CAMADA_H #define CAMADA_H #include<QList> #include<QColor> class Point{ private: int i,j; public: Point(){ i = j = 0; } Point(int iN, int jN){ i = iN; j = jN; } Point(const Point &p){ i = p.i; j = p.j; } int getI() const{return i;} int getJ()const{return j;} bool operator==(const Point&p) const{ if(this->i == p.i && this->j == p.j) return true; else return false; } }; class Camada{ public: //====Construtores e destrutores Camada();//default Camada(QString,double,QColor,int nLinha,int nColun); Camada(Camada const &);//de copia ~Camada();//destrutor //====atributos bool **pontos;//define quais os pontos sao importantes(criticos) QList<Point> listaDePontos; //utilizada para guarda os pontos e ao pintar nao precisar percorrer toda a matriz int nLinhas; int nColunas; //TODO bool estaIncluidoNoAlgoritmo;//variavel que permite a camada estar no algoritmo ou nao bool estaVisivel;//é visível //=====metodos QString getNome(); void setNome(QString); double getPeso(); void setPeso(double); QColor getCorCamada(); void setCorCamada(QColor); bool getEstaIncluidoNoAlgoritmo(); void setEstaIncluidoNoAlgoritmo(bool); void alteraPonto(Point p,bool add); //====sobrecarga de operadores Camada& operator=(Camada const&);//de atribuicao bool operator==(Camada const&) const;//de igualdade private: //=====atributos QString nome; double peso; QColor corCamada; }; #endif // CAMADA_H <file_sep>#ifndef INUNDACAO_H #define INUNDACAO_H #include <QQueue> #include <Fluxo.h> #define proximoY(y,x) (y+ Fluxo::direcaoDeFluxo[ matrizDeDirecoes[y][x] ][0]) #define proximoX(y,x) (x+ Fluxo::direcaoDeFluxo[ matrizDeDirecoes[y][x] ][1]) //====Constantes==== #define BARRAGEM 2; #define AFLUENTE 1; #define ACIMA_BARRAGEM 3; #define AGUA_BORDA_BARRAGEM 4; #define AGUA 5; class PontoZ { public: int x,y; short int z; PontoZ(const short int y1, const short int x1,const short int z1) : x(x1),y(y1),z(z1) {} PontoZ(){x=-1; y=-1; z=-1;} // void operator=(PontoZ& outro) {this->x = outro.x; this->y = outro.y; this->z = outro.z;} bool operator<(const PontoZ &p1) const { return this->z > p1.z; } }; class Inundacao { public: //=====construtores Inundacao(); Inundacao(int , int ); Inundacao(Inundacao const&); ~Inundacao(); //=======atributos short int** matrizEstados; PontoZ posicaoBarragem; PontoZ posicaoAcimaBarragem; PontoZ vetorNormalABarragem; int nLinhas; int nColunas; int tamanhoMaximoDaBarragem; int volumeAgua; int volumeAlvo; int nivelAgua; int areaLaminaAgua; int areaBarragemTocada; int comprimentoBarragemTocada; //====Metodos==== bool permiteInundacaoEAumentaBarragem(PontoZ p3);//define se um ponto p3 deve ser inundado, barragem ou extravasou barragem void inicializaBarragem(int x, int y, int xAcima, int yAcima, short int** elevacoes,bool **rio,unsigned char**matrizDeDirecoes, int opVetorNormal,int valorVetorNormal,int valEp); void marcaMontante(int xi, int yi, short int** matrizDeEstados, unsigned char** matrizDeDirecoes, short int** elevacoes,bool **rio,int opVetorNormal,int valorVetorNormal,int valEp); void sobeNivelDeAgua(short int** matrizDeEstados, short int** elevacoes); void inunda(int posX, int posY, unsigned char** matrizDeDirecoes, short int** elevacoes,bool **rio,int opVetorNormal, int valorVetorNormal,int valEp); void defineVetorNormalABarragem(int op,int val,short int **elevacoes,bool **rio,unsigned char**matrizDeDirecoes,int valEp); void vetorNormalPorMediaSimples(int viz,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes); void vetorNormalPorMediaPonderada(int viz,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes); void vetorNormalPorDouglasPeucker(int numElementos,int epsilon,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes); void criaListaParaDouglasPeucker(int numElementos,QList<PontoZ> &listaASerSimplificada,short int **elevacoes,bool**rio,unsigned char**matrizDeDirecoes); QList<PontoZ> algoritmoDouglasPeucker(QList<PontoZ> & ,int,QList<PontoZ> &); void marcaBarragem(short int **matrizDeEstados);//marca os elementos que serao barragem de acordo com sua direcao void acertaTamanhoBarragem(short int **matrizDeEstados);//acerta a barragem com elementos apenas adjacente a inundacao PontoZ getPosicaoBarragem(); private: //====Atributos==== bool** visitado; priority_queue<PontoZ> filaProximosPontos; //fila contendo os proximos elementos a serem alagados }; #endif // INUNDACAO_H <file_sep>#ifndef PAINELVISUALIZACAOOPENGL_H #define PAINELVISUALIZACAOOPENGL_H #include <QGLWidget> #include <QMouseEvent> #include <MapaMDE.h> #include <VisualizacaoMapa.h> class PainelVisualizacaoOpenGL : public QGLWidget { Q_OBJECT public: //=====construtor explicit PainelVisualizacaoOpenGL(QWidget *parent = 0); //===atributos VisualizacaoMapa *visualizacaoMapa; int posClickX; int posClickY; QColor corAlagamento; QColor corRedeDeDrenagem; QColor corMaiorElevacao; QColor corMenorElevacao; QColor corBarragem;//cor dos elementos QColor corPadraoAlagamento; QColor corPadraoRedeDeDrenagem; QColor corPadraoMaiorElevacao; QColor corPadraoMenorElevacao; QColor corPadraoBarragem; bool mapaEstaCarregado;//verifica se mapa carregado na area de visualizacao bool flagPinta; //====metodos void zoomMapa(int zoom); void carregandoMapa(const char*); void pintaTudo(); void pintaEixo(); void pintaCamadas(); void computaFluxo(); //Esse método faz a chamada da função de cálculo de fluxo do objeto Fluxo. void mudaCores(QStringList);//muda as cores e vira uma lista de string //contendo em ordem alfabetica os elementos cuja a cor sera mudada void setCoresPadrao(); QColor getCorGradient(double gradientProporcao);//define a cor dentro do gradiente formado pela cor da maior e menor elevacao //====metodos opengl void defineOrtho(); protected: //====metodos opengl void initializeGL(); void resizeGL(int w, int h); void paintGL(); signals: //====signals que sao conectados a metodos na janela principal void mouseMoveEvent(QMouseEvent *); void mousePressEvent ( QMouseEvent * event ); void keyPressEvent(QKeyEvent *); void mouseReleaseEvent(QMouseEvent*); public slots: }; #endif // PAINELVISUALIZACAOOPENGL_H <file_sep>/**************************************************************************** ** Meta object code from reading C++ file 'janelaprincipal.h' ** ** Created: Mon 1. Oct 21:26:33 2012 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../janelaprincipal.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'janelaprincipal.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_JanelaPrincipal[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 38, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 17, 16, 16, 16, 0x09, 58, 49, 16, 16, 0x09, 88, 16, 16, 16, 0x09, 115, 16, 16, 16, 0x09, 143, 16, 16, 16, 0x09, 182, 16, 16, 16, 0x09, 215, 213, 16, 16, 0x09, 237, 16, 16, 16, 0x09, 270, 267, 16, 16, 0x09, 309, 267, 16, 16, 0x09, 340, 336, 16, 16, 0x09, 365, 213, 16, 16, 0x09, 418, 408, 403, 16, 0x09, 448, 16, 16, 16, 0x09, 479, 16, 16, 16, 0x08, 516, 16, 16, 16, 0x08, 551, 16, 16, 16, 0x08, 589, 16, 16, 16, 0x08, 615, 16, 16, 16, 0x08, 648, 16, 16, 16, 0x08, 674, 16, 16, 16, 0x08, 701, 16, 16, 16, 0x08, 725, 16, 16, 16, 0x08, 749, 16, 16, 16, 0x08, 771, 16, 16, 16, 0x08, 798, 16, 16, 16, 0x08, 831, 16, 16, 16, 0x08, 858, 16, 16, 16, 0x08, 884, 16, 16, 16, 0x08, 912, 16, 16, 16, 0x08, 947, 16, 16, 16, 0x08, 989, 16, 16, 16, 0x08, 1015, 16, 16, 16, 0x08, 1046, 16, 16, 16, 0x08, 1079, 16, 16, 16, 0x08, 1111, 16, 16, 16, 0x08, 1145, 16, 16, 16, 0x08, 1178, 16, 16, 16, 0x08, 0 // eod }; static const char qt_meta_stringdata_JanelaPrincipal[] = { "JanelaPrincipal\0\0on_actionAbrir_mapa_triggered()\0" "position\0on_barraZoom_sliderMoved(int)\0" "on_botaoZoomMais_clicked()\0" "on_botaoZoomMenos_clicked()\0" "on_botaoAtualizarFluxoMinimo_clicked()\0" "trocaCoordenadas(QMouseEvent*)\0,\0" "defineCamada(int,int)\0" "defineInundacao(QMouseEvent*)\0ev\0" "adicionandoPontosACamada(QMouseEvent*)\0" "movendoMouse(QMouseEvent*)\0kev\0" "moveBarragem(QKeyEvent*)\0" "imprimeBarragem(VisualizacaoMapa,int)\0" "bool\0posx,posy\0eEntruncamentoDeRios(int,int)\0" "exporCamada(QTableWidgetItem*)\0" "on_botaoAdicionarInundacao_clicked()\0" "on_botaoExcluirInundacao_clicked()\0" "on_botaoVisualizarInundacao_clicked()\0" "on_insereCamada_clicked()\0" "on_selecaoPontosCamada_clicked()\0" "on_radioButtonV_clicked()\0" "on_radioButtonDP_clicked()\0" "on_pushButton_clicked()\0moveZoomHorizontal(int)\0" "moveZoomVertical(int)\0on_actionSobre_triggered()\0" "on_actionFechar_mapa_triggered()\0" "on_actionCores_triggered()\0" "on_deletaCamada_clicked()\0" "on_botaoAlternaBC_clicked()\0" "on_actionFunc_Objetivo_triggered()\0" "on_caixaApresentaFuncaoObjetivo_clicked()\0" "on_radioButtonM_clicked()\0" "on_radioButtonManual_clicked()\0" "on_radioButtonManual45_clicked()\0" "on_radioButtonManual0_clicked()\0" "on_radioButtonManual135_clicked()\0" "on_radioButtonManual90_clicked()\0" "on_botaoFechaManual_clicked()\0" }; const QMetaObject JanelaPrincipal::staticMetaObject = { { &QMainWindow::staticMetaObject, qt_meta_stringdata_JanelaPrincipal, qt_meta_data_JanelaPrincipal, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &JanelaPrincipal::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *JanelaPrincipal::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *JanelaPrincipal::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_JanelaPrincipal)) return static_cast<void*>(const_cast< JanelaPrincipal*>(this)); return QMainWindow::qt_metacast(_clname); } int JanelaPrincipal::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: on_actionAbrir_mapa_triggered(); break; case 1: on_barraZoom_sliderMoved((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: on_botaoZoomMais_clicked(); break; case 3: on_botaoZoomMenos_clicked(); break; case 4: on_botaoAtualizarFluxoMinimo_clicked(); break; case 5: trocaCoordenadas((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 6: defineCamada((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 7: defineInundacao((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 8: adicionandoPontosACamada((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 9: movendoMouse((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 10: moveBarragem((*reinterpret_cast< QKeyEvent*(*)>(_a[1]))); break; case 11: imprimeBarragem((*reinterpret_cast< VisualizacaoMapa(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 12: { bool _r = eEntruncamentoDeRios((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = _r; } break; case 13: exporCamada((*reinterpret_cast< QTableWidgetItem*(*)>(_a[1]))); break; case 14: on_botaoAdicionarInundacao_clicked(); break; case 15: on_botaoExcluirInundacao_clicked(); break; case 16: on_botaoVisualizarInundacao_clicked(); break; case 17: on_insereCamada_clicked(); break; case 18: on_selecaoPontosCamada_clicked(); break; case 19: on_radioButtonV_clicked(); break; case 20: on_radioButtonDP_clicked(); break; case 21: on_pushButton_clicked(); break; case 22: moveZoomHorizontal((*reinterpret_cast< int(*)>(_a[1]))); break; case 23: moveZoomVertical((*reinterpret_cast< int(*)>(_a[1]))); break; case 24: on_actionSobre_triggered(); break; case 25: on_actionFechar_mapa_triggered(); break; case 26: on_actionCores_triggered(); break; case 27: on_deletaCamada_clicked(); break; case 28: on_botaoAlternaBC_clicked(); break; case 29: on_actionFunc_Objetivo_triggered(); break; case 30: on_caixaApresentaFuncaoObjetivo_clicked(); break; case 31: on_radioButtonM_clicked(); break; case 32: on_radioButtonManual_clicked(); break; case 33: on_radioButtonManual45_clicked(); break; case 34: on_radioButtonManual0_clicked(); break; case 35: on_radioButtonManual135_clicked(); break; case 36: on_radioButtonManual90_clicked(); break; case 37: on_botaoFechaManual_clicked(); break; default: ; } _id -= 38; } return _id; } QT_END_MOC_NAMESPACE <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelacamadas.ui' ** ** Created: Mon 1. Oct 19:01:29 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELACAMADAS_H #define UI_JANELACAMADAS_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QComboBox> #include <QtGui/QDialog> #include <QtGui/QDialogButtonBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_janelaCamadas { public: QWidget *layoutWidget; QVBoxLayout *verticalLayout_2; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label; QLineEdit *caixaEntradaNomeDaCamada; QHBoxLayout *horizontalLayout_2; QLabel *label_2; QLineEdit *caixaEntradaPesoDaCamada; QHBoxLayout *horizontalLayout_3; QLabel *label_3; QComboBox *caixaBoxCor; QDialogButtonBox *buttonBox; void setupUi(QDialog *janelaCamadas) { if (janelaCamadas->objectName().isEmpty()) janelaCamadas->setObjectName(QString::fromUtf8("janelaCamadas")); janelaCamadas->setWindowModality(Qt::ApplicationModal); janelaCamadas->resize(189, 130); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(janelaCamadas->sizePolicy().hasHeightForWidth()); janelaCamadas->setSizePolicy(sizePolicy); janelaCamadas->setMinimumSize(QSize(189, 130)); janelaCamadas->setMaximumSize(QSize(189, 130)); janelaCamadas->setAutoFillBackground(false); layoutWidget = new QWidget(janelaCamadas); layoutWidget->setObjectName(QString::fromUtf8("layoutWidget")); layoutWidget->setGeometry(QRect(10, 10, 172, 111)); verticalLayout_2 = new QVBoxLayout(layoutWidget); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); verticalLayout_2->setContentsMargins(0, 0, 0, 0); verticalLayout = new QVBoxLayout(); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); label = new QLabel(layoutWidget); label->setObjectName(QString::fromUtf8("label")); horizontalLayout->addWidget(label); caixaEntradaNomeDaCamada = new QLineEdit(layoutWidget); caixaEntradaNomeDaCamada->setObjectName(QString::fromUtf8("caixaEntradaNomeDaCamada")); horizontalLayout->addWidget(caixaEntradaNomeDaCamada); verticalLayout->addLayout(horizontalLayout); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setSpacing(10); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); label_2 = new QLabel(layoutWidget); label_2->setObjectName(QString::fromUtf8("label_2")); horizontalLayout_2->addWidget(label_2); caixaEntradaPesoDaCamada = new QLineEdit(layoutWidget); caixaEntradaPesoDaCamada->setObjectName(QString::fromUtf8("caixaEntradaPesoDaCamada")); horizontalLayout_2->addWidget(caixaEntradaPesoDaCamada); verticalLayout->addLayout(horizontalLayout_2); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); label_3 = new QLabel(layoutWidget); label_3->setObjectName(QString::fromUtf8("label_3")); horizontalLayout_3->addWidget(label_3); caixaBoxCor = new QComboBox(layoutWidget); caixaBoxCor->setObjectName(QString::fromUtf8("caixaBoxCor")); horizontalLayout_3->addWidget(caixaBoxCor); verticalLayout->addLayout(horizontalLayout_3); verticalLayout_2->addLayout(verticalLayout); buttonBox = new QDialogButtonBox(layoutWidget); buttonBox->setObjectName(QString::fromUtf8("buttonBox")); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); verticalLayout_2->addWidget(buttonBox); retranslateUi(janelaCamadas); QObject::connect(buttonBox, SIGNAL(accepted()), janelaCamadas, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), janelaCamadas, SLOT(reject())); QMetaObject::connectSlotsByName(janelaCamadas); } // setupUi void retranslateUi(QDialog *janelaCamadas) { janelaCamadas->setWindowTitle(QApplication::translate("janelaCamadas", "Camada", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("janelaCamadas", "Nome", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("janelaCamadas", "Peso", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("janelaCamadas", "Cor", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class janelaCamadas: public Ui_janelaCamadas {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELACAMADAS_H <file_sep>#ifndef PAINELVISUALIZACAOBARRAGEM2DOPENGL_H #define PAINELVISUALIZACAOBARRAGEM2DOPENGL_H #include<QGLWidget> #include<VisualizacaoMapa.h> #include<QList> class painelvisualizacaobarragem2dopengl : public QGLWidget { Q_OBJECT public: //====construtor explicit painelvisualizacaobarragem2dopengl(QWidget *parent = 0); //====atributos int maxAltura,minAltura,proporcaoAltura,proporcaoImpressao; VisualizacaoMapa *visualizacaoMapa; QList<Point> pontosDaBarragem; //===metodos void carregandoInformacoes(VisualizacaoMapa *viMapa); void defineBarragem(); protected: //===metodos opengl void defineOrtho(); void initializeGL(); void resizeGL(int w, int h); void paintGL(); }; #endif // PAINELVISUALIZACAOBARRAGEM2DOPENGL_H <file_sep>#include"Camada.h" #include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <QString> /*! \class Camada \previouspage All Classes \contentspage \nextpage Fluxo \startpage All Classes \brief Class for creating critical points. When calculating the best position of the dam, the algorithm can use these points to define regions where it is disadvantageous to have a reservoir. */ /*! \variable Camada::pontos \brief the a pointer to pointer, representing the matrix of critical points (I.e. the reservoir being at these points is (peso) disadvantageous ) */ /*! \variable Camada::nColunas \brief the number of lines in matrix */ /*! \variable Camada::nLinhas \brief the number of colluns in matrix */ /*! \variable Camada::estaIncluidoNoAlgoritmo \brief the value if this Camada is insert into algorithm dam positioning */ /*! \variable Camada::estaVisivel \brief the value if this Camada is actual showing to user */ /*! \variable Camada::listaDePontos \brief the list of critical points */ /*! \fn Camada::Camada() \brief Default constructor. Set default values to attributes */ Camada::Camada(){ nome = " "; peso = 1.0; pontos = NULL; corCamada.setRgb(1,0,0); nLinhas = nColunas = 0; estaVisivel = true; } /*! \overload Camada::operator=(Camada const& c) The current object camada receive the attributes from c */ Camada& Camada::operator=(Camada const& c){ nome = c.nome; corCamada = c.corCamada; peso = c.peso; nLinhas = c.nLinhas; nColunas = c.nColunas; pontos = new bool *[nLinhas]; for(int i = 0; i < nLinhas; i++){ pontos[i] = new bool[nColunas]; for(int j = 0; j<nColunas; j++) pontos[i][j] = c.pontos[i][j]; } estaVisivel = c.estaVisivel; estaIncluidoNoAlgoritmo = c.estaIncluidoNoAlgoritmo; for(int i = 0; i < c.listaDePontos.size(); i++) listaDePontos.append(c.listaDePontos.at(i)); return *this; } /*! \fn Camada::Camada(QString n, double p,QColor c,int nLinha,int nColun) Constructor. Construct an object (Camada) tha will have: nome = n peso = p cor = c */ Camada::Camada(QString n, double p,QColor c,int nLinha,int nColun){ nome = n; peso = p; corCamada = c; nLinhas = nLinha; nColunas = nColun; pontos = new bool *[nLinhas]; for(int i = 0; i < nLinhas; i++){ pontos[i] = new bool[nColunas]; for(int j = 0; j<nColunas; j++) pontos[i][j] = false; } estaVisivel = true; } /*! \fn Camada::Camada(Camada const &c) \brief Copy Constructor. Creates an object receiving attributes from c */ Camada::Camada(Camada const &c){ nome = c.nome; corCamada = c.corCamada; peso = c.peso; nLinhas = c.nLinhas; nColunas = c.nColunas; pontos = new bool *[nLinhas]; for(int i = 0; i < nLinhas; i++){ pontos[i] = new bool[nColunas]; for(int j = 0; j<nColunas; j++) pontos[i][j] = c.pontos[i][j]; } estaVisivel = c.estaVisivel; estaIncluidoNoAlgoritmo = c.estaIncluidoNoAlgoritmo; for(int i = 0; i < c.listaDePontos.size(); i++) listaDePontos.append(c.listaDePontos.at(i)); } /*! \fn Camada::~Camada() \brief Destructor */ Camada::~Camada(){ for(int i = 0; i < nLinhas; i++) delete [] pontos[i] ; delete pontos; } /*! \fn QString Camada::getNome() \brief Returns nome */ QString Camada::getNome(){ return nome; } /*! \fn void Camada::setNome(QString n) \brief Set n to nome */ void Camada::setNome(QString n){ nome = n; } /*! \fn double Camada::getPeso() \brief Returns peso */ double Camada::getPeso(){ return peso; } /*! \fn void Camada::setPeso(double p) \brief Set p to peso */ void Camada::setPeso(double p){ peso = p; } /*! \overload Camada::operator==(Camada const& c) const Return if two objects Camada are equal */ bool Camada::operator==(Camada const& c) const{ return (QString::compare(nome,c.nome,Qt::CaseInsensitive) == 0); } /*! \fn QColor Camada::getCorCamada() \brief Return cor */ QColor Camada::getCorCamada(){ return corCamada; } /*! \fn void Camada::setCorCamada(QColor c) \brief Set c to cor */ void Camada::setCorCamada(QColor c){ corCamada = c; } /*! \fn bool Camada::getEstaIncluidoNoAlgoritmo() \brief Return estaIncluidoNoAlgoritmo */ bool Camada::getEstaIncluidoNoAlgoritmo(){ return estaIncluidoNoAlgoritmo; } /*! \fn bool Camada::alteraPonto(Point p,bool add) \brief Change status of point p using add. Printed(add==true) or not */ void Camada::alteraPonto(Point p,bool add){ if(p.getI()<0||p.getI()<0||p.getI()>=nLinhas||p.getJ()>=nColunas) return; try{ if(add) listaDePontos.append(p); else listaDePontos.removeAt(listaDePontos.indexOf(p,0)); pontos[p.getI()][p.getJ()] = add; }catch(...){ int teste = 3; teste++; } } /*! \fn voi Camada::setEstaIncluidoNoAlgoritmo(bool op) \brief Set op to estaIncluidoNoAlgoritmo */ void Camada::setEstaIncluidoNoAlgoritmo(bool op){ estaIncluidoNoAlgoritmo = op; } <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelaopcaocor.ui' ** ** Created: Mon 1. Oct 19:01:30 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELAOPCAOCOR_H #define UI_JANELAOPCAOCOR_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QCheckBox> #include <QtGui/QComboBox> #include <QtGui/QDialog> #include <QtGui/QDialogButtonBox> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_janelaOpcaoCor { public: QGroupBox *groupBox; QDialogButtonBox *buttonBox_2; QWidget *layoutWidget; QVBoxLayout *verticalLayout; QHBoxLayout *horizontalLayout; QLabel *label; QComboBox *caixaCorMaiorElevacao; QHBoxLayout *horizontalLayout_3; QLabel *label_2; QComboBox *caixaCorMenorElevacao; QHBoxLayout *horizontalLayout_2; QLabel *label_3; QComboBox *caixaCorRedeDeDrenagem; QHBoxLayout *horizontalLayout_4; QLabel *label_4; QComboBox *caixaCorAlagamento; QHBoxLayout *horizontalLayout_5; QLabel *label_5; QComboBox *caixaCorBarragem; QCheckBox *corPadraoCaixa; void setupUi(QDialog *janelaOpcaoCor) { if (janelaOpcaoCor->objectName().isEmpty()) janelaOpcaoCor->setObjectName(QString::fromUtf8("janelaOpcaoCor")); janelaOpcaoCor->resize(292, 230); janelaOpcaoCor->setMinimumSize(QSize(292, 230)); janelaOpcaoCor->setMaximumSize(QSize(292, 230)); QIcon icon; icon.addFile(QString::fromUtf8("../imagens/logo3.png"), QSize(), QIcon::Normal, QIcon::Off); janelaOpcaoCor->setWindowIcon(icon); groupBox = new QGroupBox(janelaOpcaoCor); groupBox->setObjectName(QString::fromUtf8("groupBox")); groupBox->setGeometry(QRect(10, 10, 271, 211)); groupBox->setMinimumSize(QSize(271, 211)); buttonBox_2 = new QDialogButtonBox(groupBox); buttonBox_2->setObjectName(QString::fromUtf8("buttonBox_2")); buttonBox_2->setGeometry(QRect(10, 170, 161, 32)); buttonBox_2->setOrientation(Qt::Horizontal); buttonBox_2->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); layoutWidget = new QWidget(groupBox); layoutWidget->setObjectName(QString::fromUtf8("layoutWidget")); layoutWidget->setGeometry(QRect(20, 30, 231, 136)); verticalLayout = new QVBoxLayout(layoutWidget); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); horizontalLayout = new QHBoxLayout(); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); label = new QLabel(layoutWidget); label->setObjectName(QString::fromUtf8("label")); horizontalLayout->addWidget(label); caixaCorMaiorElevacao = new QComboBox(layoutWidget); caixaCorMaiorElevacao->setObjectName(QString::fromUtf8("caixaCorMaiorElevacao")); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(caixaCorMaiorElevacao->sizePolicy().hasHeightForWidth()); caixaCorMaiorElevacao->setSizePolicy(sizePolicy); horizontalLayout->addWidget(caixaCorMaiorElevacao); verticalLayout->addLayout(horizontalLayout); horizontalLayout_3 = new QHBoxLayout(); horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3")); label_2 = new QLabel(layoutWidget); label_2->setObjectName(QString::fromUtf8("label_2")); horizontalLayout_3->addWidget(label_2); caixaCorMenorElevacao = new QComboBox(layoutWidget); caixaCorMenorElevacao->setObjectName(QString::fromUtf8("caixaCorMenorElevacao")); sizePolicy.setHeightForWidth(caixaCorMenorElevacao->sizePolicy().hasHeightForWidth()); caixaCorMenorElevacao->setSizePolicy(sizePolicy); horizontalLayout_3->addWidget(caixaCorMenorElevacao); verticalLayout->addLayout(horizontalLayout_3); horizontalLayout_2 = new QHBoxLayout(); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); label_3 = new QLabel(layoutWidget); label_3->setObjectName(QString::fromUtf8("label_3")); horizontalLayout_2->addWidget(label_3); caixaCorRedeDeDrenagem = new QComboBox(layoutWidget); caixaCorRedeDeDrenagem->setObjectName(QString::fromUtf8("caixaCorRedeDeDrenagem")); sizePolicy.setHeightForWidth(caixaCorRedeDeDrenagem->sizePolicy().hasHeightForWidth()); caixaCorRedeDeDrenagem->setSizePolicy(sizePolicy); horizontalLayout_2->addWidget(caixaCorRedeDeDrenagem); verticalLayout->addLayout(horizontalLayout_2); horizontalLayout_4 = new QHBoxLayout(); horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4")); label_4 = new QLabel(layoutWidget); label_4->setObjectName(QString::fromUtf8("label_4")); horizontalLayout_4->addWidget(label_4); caixaCorAlagamento = new QComboBox(layoutWidget); caixaCorAlagamento->setObjectName(QString::fromUtf8("caixaCorAlagamento")); sizePolicy.setHeightForWidth(caixaCorAlagamento->sizePolicy().hasHeightForWidth()); caixaCorAlagamento->setSizePolicy(sizePolicy); horizontalLayout_4->addWidget(caixaCorAlagamento); verticalLayout->addLayout(horizontalLayout_4); horizontalLayout_5 = new QHBoxLayout(); horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5")); label_5 = new QLabel(layoutWidget); label_5->setObjectName(QString::fromUtf8("label_5")); horizontalLayout_5->addWidget(label_5); caixaCorBarragem = new QComboBox(layoutWidget); caixaCorBarragem->setObjectName(QString::fromUtf8("caixaCorBarragem")); sizePolicy.setHeightForWidth(caixaCorBarragem->sizePolicy().hasHeightForWidth()); caixaCorBarragem->setSizePolicy(sizePolicy); horizontalLayout_5->addWidget(caixaCorBarragem); verticalLayout->addLayout(horizontalLayout_5); corPadraoCaixa = new QCheckBox(groupBox); corPadraoCaixa->setObjectName(QString::fromUtf8("corPadraoCaixa")); corPadraoCaixa->setGeometry(QRect(180, 178, 91, 17)); retranslateUi(janelaOpcaoCor); QObject::connect(buttonBox_2, SIGNAL(accepted()), janelaOpcaoCor, SLOT(accept())); QObject::connect(buttonBox_2, SIGNAL(rejected()), janelaOpcaoCor, SLOT(reject())); QMetaObject::connectSlotsByName(janelaOpcaoCor); } // setupUi void retranslateUi(QDialog *janelaOpcaoCor) { janelaOpcaoCor->setWindowTitle(QApplication::translate("janelaOpcaoCor", "Mude as cores", 0, QApplication::UnicodeUTF8)); groupBox->setTitle(QApplication::translate("janelaOpcaoCor", "Cores", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("janelaOpcaoCor", "Maior Eleva\303\247\303\243o", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("janelaOpcaoCor", "Menor Eleva\303\247\303\243o", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("janelaOpcaoCor", "Rede de drenagem", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("janelaOpcaoCor", "Alagamento", 0, QApplication::UnicodeUTF8)); label_5->setText(QApplication::translate("janelaOpcaoCor", "Barragem", 0, QApplication::UnicodeUTF8)); corPadraoCaixa->setText(QApplication::translate("janelaOpcaoCor", "Cores Padr\303\243o", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class janelaOpcaoCor: public Ui_janelaOpcaoCor {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELAOPCAOCOR_H <file_sep>// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : Fluxo.h // @ Date : 19/09/2011 // @ Author : // // #if !defined(_FLUXO_H) #define _FLUXO_H #include<map> #include<queue> #include<iostream> using namespace std; class Fluxo { public: //===Construtores e destrutor======/// Fluxo(); Fluxo(int nLinhas, int nColunas); Fluxo(Fluxo const&);//de copia ~Fluxo();//destrutor //=========Atributos======//// unsigned char **direcao;//matriz que define a direcao de fluxo de cada celula int **fluxo;//define o fluxo acumulado bool **rio;//define se o elemento Ú rio ou nao int fluxoMinimo; int valorPadraoFluxo; int nLinhas; int nColunas; int qtdeCelulasRio; const static int limiteAltidude = 32768;//tamanho de um inteiro const static int processado = 255; typedef pair<int,int> ponto;//objeto que facilita o acesso para ser armazenado queue<ponto> vetorDeFilasDeNiveis[2*limiteAltidude];//armazena os pontos proximos a ser inundado const static int direcaoDeFluxo[129][2];//matriz que contem as direcoes de fluxo para num predefinido //valores de direcao de fluxo, localizacao de numeros pre-definidos /*1 2 4 128 8 64 32 16 Comeša por 1 sentido horario */ const static int dirEsquerdaCima = 1; const static int dirCima = 2; const static int dirDireitaCima = 4; const static int dirDireita = 8; const static int dirDireitaBaixo = 16; const static int dirBaixo = 32; const static int dirEsquerdaBaixo = 64; const static int dirEsquerda = 128; //====metodos void calculaFluxo(short int** elevacoes,int); private: //====metodos void setFluxo(short int** elevacoes); void setInundacao(short int** elevacoes); void setRio(short int**,int); }; #endif //_FLUXO_H <file_sep>#include "janelasobre.h" #include "ui_janelasobre.h" /*! \class janelasobre \previouspage JanelaPrincipal \contentspage \nextpage MapaMDE \startpage All Classes \brief Class to create the about window */ /*! \fn janelasobre::janelasobre(QWidget *parent) : QDialog(parent), ui(new Ui::janelasobre) \brief Constructor */ janelasobre::janelasobre(QWidget *parent) : QDialog(parent), ui(new Ui::janelasobre) { ui->setupUi(this); } /*! \fn janelasobre::~janelasobre() \brief Destructor */ janelasobre::~janelasobre() { delete ui; } <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelabarragem2d.ui' ** ** Created: Mon 1. Oct 21:22:54 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELABARRAGEM2D_H #define UI_JANELABARRAGEM2D_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QHeaderView> #include <QtGui/QTextEdit> #include "painelvisualizacaobarragem2dopengl.h" QT_BEGIN_NAMESPACE class Ui_janelaBarragem2D { public: painelvisualizacaobarragem2dopengl *widget; QTextEdit *textEdit1; QTextEdit *textEdit2; QTextEdit *textEdit3; void setupUi(QDialog *janelaBarragem2D) { if (janelaBarragem2D->objectName().isEmpty()) janelaBarragem2D->setObjectName(QString::fromUtf8("janelaBarragem2D")); janelaBarragem2D->resize(528, 479); QIcon icon; icon.addFile(QString::fromUtf8("../imagens/logo3.png"), QSize(), QIcon::Normal, QIcon::Off); janelaBarragem2D->setWindowIcon(icon); widget = new painelvisualizacaobarragem2dopengl(janelaBarragem2D); widget->setObjectName(QString::fromUtf8("widget")); widget->setGeometry(QRect(10, 10, 501, 361)); textEdit1 = new QTextEdit(janelaBarragem2D); textEdit1->setObjectName(QString::fromUtf8("textEdit1")); textEdit1->setGeometry(QRect(20, 380, 151, 91)); textEdit2 = new QTextEdit(janelaBarragem2D); textEdit2->setObjectName(QString::fromUtf8("textEdit2")); textEdit2->setGeometry(QRect(190, 380, 151, 91)); textEdit3 = new QTextEdit(janelaBarragem2D); textEdit3->setObjectName(QString::fromUtf8("textEdit3")); textEdit3->setGeometry(QRect(360, 380, 151, 91)); retranslateUi(janelaBarragem2D); QMetaObject::connectSlotsByName(janelaBarragem2D); } // setupUi void retranslateUi(QDialog *janelaBarragem2D) { janelaBarragem2D->setWindowTitle(QApplication::translate("janelaBarragem2D", "Visualiza\303\247\303\243o 2D", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class janelaBarragem2D: public Ui_janelaBarragem2D {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELABARRAGEM2D_H <file_sep>#include <QtGui/QApplication> #include "janelaprincipal.h" #include <iostream> using namespace std; /*! \page classes.html \title All Classes \previouspage VisualizacaoMapa \nextpage Camada The classes of the project are listed below. \generatelist classes */ int main(int argc, char *argv[]) { QList<Point> listaDePontos; for(int i = 0;i<6;i++){ Point aux(1,0); listaDePontos.append(aux); } QApplication a(argc, argv); JanelaPrincipal w; w.show(); return a.exec(); } <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelasobre.ui' ** ** Created: Mon 1. Oct 19:01:30 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELASOBRE_H #define UI_JANELASOBRE_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QDialogButtonBox> #include <QtGui/QFrame> #include <QtGui/QHeaderView> #include <QtGui/QLabel> QT_BEGIN_NAMESPACE class Ui_janelasobre { public: QDialogButtonBox *buttonBox; QFrame *line; QLabel *label; QLabel *label_2; QLabel *label_3; QLabel *label_4; QLabel *label_5; QLabel *label_6; QLabel *label_7; QLabel *label_8; QLabel *label_9; QLabel *label_10; QLabel *label_11; QLabel *label_12; QLabel *label_13; QLabel *label_14; void setupUi(QDialog *janelasobre) { if (janelasobre->objectName().isEmpty()) janelasobre->setObjectName(QString::fromUtf8("janelasobre")); janelasobre->resize(325, 273); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(janelasobre->sizePolicy().hasHeightForWidth()); janelasobre->setSizePolicy(sizePolicy); janelasobre->setMinimumSize(QSize(325, 273)); janelasobre->setMaximumSize(QSize(325, 273)); QIcon icon; icon.addFile(QString::fromUtf8("../imagens/logo3.png"), QSize(), QIcon::Normal, QIcon::Off); janelasobre->setWindowIcon(icon); buttonBox = new QDialogButtonBox(janelasobre); buttonBox->setObjectName(QString::fromUtf8("buttonBox")); buttonBox->setGeometry(QRect(250, 170, 71, 21)); buttonBox->setOrientation(Qt::Vertical); buttonBox->setStandardButtons(QDialogButtonBox::Close); line = new QFrame(janelasobre); line->setObjectName(QString::fromUtf8("line")); line->setGeometry(QRect(5, 193, 311, 20)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); label = new QLabel(janelasobre); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(10, 210, 46, 13)); label_2 = new QLabel(janelasobre); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(60, 210, 81, 61)); label_2->setPixmap(QPixmap(QString::fromUtf8("../imagens/brasaoUFVPequeno.png"))); label_3 = new QLabel(janelasobre); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(150, 210, 81, 61)); label_3->setPixmap(QPixmap(QString::fromUtf8("../imagens/brasaoDPI.png"))); label_4 = new QLabel(janelasobre); label_4->setObjectName(QString::fromUtf8("label_4")); label_4->setGeometry(QRect(50, 50, 231, 41)); label_4->setWordWrap(true); label_5 = new QLabel(janelasobre); label_5->setObjectName(QString::fromUtf8("label_5")); label_5->setGeometry(QRect(168, 76, 171, 16)); label_6 = new QLabel(janelasobre); label_6->setObjectName(QString::fromUtf8("label_6")); label_6->setGeometry(QRect(130, 110, 46, 13)); label_7 = new QLabel(janelasobre); label_7->setObjectName(QString::fromUtf8("label_7")); label_7->setGeometry(QRect(50, 100, 201, 16)); label_8 = new QLabel(janelasobre); label_8->setObjectName(QString::fromUtf8("label_8")); label_8->setGeometry(QRect(50, 170, 211, 16)); label_9 = new QLabel(janelasobre); label_9->setObjectName(QString::fromUtf8("label_9")); label_9->setGeometry(QRect(250, 190, 111, 91)); label_9->setPixmap(QPixmap(QString::fromUtf8("../imagens/logoCapes.png"))); label_10 = new QLabel(janelasobre); label_10->setObjectName(QString::fromUtf8("label_10")); label_10->setGeometry(QRect(50, 120, 221, 31)); label_10->setWordWrap(true); label_11 = new QLabel(janelasobre); label_11->setObjectName(QString::fromUtf8("label_11")); label_11->setGeometry(QRect(150, 150, 121, 16)); label_12 = new QLabel(janelasobre); label_12->setObjectName(QString::fromUtf8("label_12")); label_12->setGeometry(QRect(60, -10, 211, 81)); label_12->setPixmap(QPixmap(QString::fromUtf8("../imagens/nomeLogoGrande.png"))); label_13 = new QLabel(janelasobre); label_13->setObjectName(QString::fromUtf8("label_13")); label_13->setGeometry(QRect(150, 130, 131, 16)); label_14 = new QLabel(janelasobre); label_14->setObjectName(QString::fromUtf8("label_14")); label_14->setGeometry(QRect(250, 30, 46, 13)); retranslateUi(janelasobre); QObject::connect(buttonBox, SIGNAL(accepted()), janelasobre, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), janelasobre, SLOT(reject())); QMetaObject::connectSlotsByName(janelasobre); } // setupUi void retranslateUi(QDialog *janelasobre) { janelasobre->setWindowTitle(QApplication::translate("janelasobre", "Sobre", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("janelasobre", "Apoio:", 0, QApplication::UnicodeUTF8)); label_2->setText(QString()); label_3->setText(QString()); label_4->setText(QApplication::translate("janelasobre", "Reservoir Building - Sistema de posicionamento de barragens para cria\303\247\303\243o de reservat\303\263rios h\303\255dricos.", 0, QApplication::UnicodeUTF8)); label_5->setText(QApplication::translate("janelasobre", "Vers\303\243o Beta 1.0/2012", 0, QApplication::UnicodeUTF8)); label_6->setText(QString()); label_7->setText(QApplication::translate("janelasobre", "Laborat\303\263rio de pesquisa TARG/DPI-UFV", 0, QApplication::UnicodeUTF8)); label_8->setText(QApplication::translate("janelasobre", "Contato: <EMAIL>", 0, QApplication::UnicodeUTF8)); label_9->setText(QString()); label_10->setText(QApplication::translate("janelasobre", "Desenvolvedores: ", 0, QApplication::UnicodeUTF8)); label_11->setText(QApplication::translate("janelasobre", "Maur\303\255cio Gouv\303\252a Gruppi", 0, QApplication::UnicodeUTF8)); label_12->setText(QString()); label_13->setText(QApplication::translate("janelasobre", "<NAME>", 0, QApplication::UnicodeUTF8)); label_14->setText(QApplication::translate("janelasobre", "v.b.1.0", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class janelasobre: public Ui_janelasobre {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELASOBRE_H <file_sep>// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : MapaMDE.h // @ Date : 29/08/2011 // @ Author : // // #if !defined(_MAPAMDE_H) #define _MAPAMDE_H class MapaMDE { public: //====construtores e destrutores MapaMDE(const char * caminhoArquivo); MapaMDE(MapaMDE const &); MapaMDE(); ~MapaMDE(); // =====atributos short int **matrizDeElevacoes; int maxElev; int minElev; //====metodos int getNColunas(); int getNLinhas(); short int getResolucao(); short int getDadoInvalido(); char * getCaminhoArquivo(); char * getNomeArquivo(); private: // =====atributos int nColunas; int nLinhas; double tamanhoCelula; double yllcorner; double dadoInvalido; double xllcorner; char *caminhoArquivo; char *nomeArquivo; //===metodos void scannerAscii(const char * caminhoArquivo); void substituindoVirgurlaPonto(const char * caminhoArquivo); }; #endif //_MAPAMDE_H <file_sep><?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- Fluxo.cpp --> <title>Fluxo Class Reference</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> </head> <body class="offline narrow creator"> <li><a href="modules.html">Modules</a></li> <li>Fluxo</li> <link rel="prev" href="camada.html" /> <link rel="next" href="inundacao.html" /> <link rel="start" href="All Classes" /> <p class="naviNextPrevious headerNavi"> [Previous: <a href="camada.html">Camada</a>] [Next: <a href="inundacao.html">Inundacao</a>] </p><p/> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#public-types">Public Types</a></li> <li class="level1"><a href="#public-functions">Public Functions</a></li> <li class="level1"><a href="#public-variables">Public Variables</a></li> <li class="level1"><a href="#details">Detailed Description</a></li> </ul> </div> <h1 class="title">Fluxo Class Reference</h1> <!-- $$$Fluxo-brief --> <p>Class for create the drainage network, calculated by the flow directionand flow accumulation <a href="#details">More...</a></p> <!-- @@@Fluxo --> <pre class="highlightedCode brush: cpp"> #include &lt;Fluxo&gt;</pre><ul> <li><a href="fluxo-members.html">List of all members, including inherited members</a></li> </ul> <a name="public-types"></a> <h2>Public Types</h2> <table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> typedef </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#ponto-typedef">ponto</a></b></td></tr> </table> <a name="public-functions"></a> <h2>Public Functions</h2> <table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#Fluxo">Fluxo</a></b> ()</td></tr> <tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#Fluxo-2">Fluxo</a></b> ( int <i>nLinhas</i>, int <i>nColunas</i> )</td></tr> <tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#Fluxo-3">Fluxo</a></b> ( Fluxo const &amp; <i>fluxoCopia</i> )</td></tr> <tr><td class="memItemLeft rightAlign topAlign"> </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#dtor.Fluxo">~Fluxo</a></b> ()</td></tr> <tr><td class="memItemLeft rightAlign topAlign"> void </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#calculaFluxo">calculaFluxo</a></b> ( short int ** <i>elevacoes</i>, int <i>noData</i> )</td></tr> </table> <a name="public-variables"></a> <h2>Public Variables</h2> <table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> unsigned char ** </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#direcao-var">direcao</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> int ** </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#fluxo-var">fluxo</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> int </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#fluxoMinimo-var">fluxoMinimo</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> int </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#nColunas-var">nColunas</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> int </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#nLinhas-var">nLinhas</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> int </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#qtdeCelulasRio-var">qtdeCelulasRio</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> bool ** </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#rio-var">rio</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> int </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#valorPadraoFluxo-var">valorPadraoFluxo</a></b></td></tr> <tr><td class="memItemLeft rightAlign topAlign"> queue&lt;ponto&gt; </td><td class="memItemRight bottomAlign"><b><a href="fluxo.html#vetorDeFilasDeNiveis-var">vetorDeFilasDeNiveis</a></b> [2 * limiteAltidude]</td></tr> </table> <a name="details"></a> <!-- $$$Fluxo-description --> <div class="descr"> <h2>Detailed Description</h2> <p>Class for create the drainage network, calculated by the flow directionand flow accumulation</p> </div> <!-- @@@Fluxo --> <div class="types"> <h2>Member Type Documentation</h2> <!-- $$$ponto --> <h3 class="fn"><a name="ponto-typedef"></a>typedef Fluxo::ponto</h3> <p>the object to map a cell(point) of MDE easily.</p> <!-- @@@ponto --> </div> <div class="func"> <h2>Member Function Documentation</h2> <!-- $$$Fluxo[overload1]$$$Fluxo --> <h3 class="fn"><a name="Fluxo"></a>Fluxo::Fluxo ()</h3> <!-- @@@Fluxo --> <!-- $$$Fluxo$$$Fluxointint --> <h3 class="fn"><a name="Fluxo-2"></a>Fluxo::Fluxo ( int <i>nLinhas</i>, int <i>nColunas</i> )</h3> <p>Constructor. Creates an object that have only the variables initialized, no drainage network is calculed yet.</p> <!-- @@@Fluxo --> <!-- $$$Fluxo$$$FluxoFluxoconst& --> <h3 class="fn"><a name="Fluxo-3"></a>Fluxo::Fluxo ( Fluxo const &amp; <i>fluxoCopia</i> )</h3> <p>Copy Constructor. Creates an object receiving attributes from fluxoCopia</p> <!-- @@@Fluxo --> <!-- $$$~Fluxo[overload1]$$$~Fluxo --> <h3 class="fn"><a name="dtor.Fluxo"></a>Fluxo::~Fluxo ()</h3> <p>Destructor</p> <!-- @@@~Fluxo --> <!-- $$$calculaFluxo[overload1]$$$calculaFluxoshortint**int --> <h3 class="fn"><a name="calculaFluxo"></a>void Fluxo::calculaFluxo ( short int ** <i>elevacoes</i>, int <i>noData</i> )</h3> <p>function to calculated the drainage network.</p> <p>elevecoes is the matrix with cell`s elevation of terrain. noData is the value representing a invalid cell</p> <p>This function use three another private function: setInundacao to identify the flow direction of each cell. setFluxo to identify the flow accumalate of each cell. setRio to identify cells that are in drainage network.</p> <!-- @@@calculaFluxo --> </div> <div class="vars"> <h2>Member Variable Documentation</h2> <!-- $$$direcao --> <h3 class="fn"><a name="direcao-var"></a>unsigned char ** Fluxo::direcao</h3> <p>This variable holds the pointer to pointer, representing the matrix of flow direction.</p> <!-- @@@direcao --> <!-- $$$fluxo --> <h3 class="fn"><a name="fluxo-var"></a>int ** Fluxo::fluxo</h3> <p>This variable holds the pointer to pointer, representing the matrix of flow accumulation.</p> <!-- @@@fluxo --> <!-- $$$fluxoMinimo --> <h3 class="fn"><a name="fluxoMinimo-var"></a>int Fluxo::fluxoMinimo</h3> <p>This variable holds the minimum flow to consider a cell in the drainage network. Cell`s value in rio matrix above fluxoMinimo is considering a cell of network drainage.</p> <!-- @@@fluxoMinimo --> <!-- $$$nColunas --> <h3 class="fn"><a name="nColunas-var"></a>int Fluxo::nColunas</h3> <p>This variable holds the number of columns of MDE.</p> <!-- @@@nColunas --> <!-- $$$nLinhas --> <h3 class="fn"><a name="nLinhas-var"></a>int Fluxo::nLinhas</h3> <p>This variable holds the numbers of lines of MDE.</p> <!-- @@@nLinhas --> <!-- $$$qtdeCelulasRio --> <h3 class="fn"><a name="qtdeCelulasRio-var"></a>int Fluxo::qtdeCelulasRio</h3> <p>This variable holds the number of cells that are in drainage network.</p> <!-- @@@qtdeCelulasRio --> <!-- $$$rio --> <h3 class="fn"><a name="rio-var"></a>bool ** Fluxo::rio</h3> <p>This variable holds the pointer to pointer, representing the matrix river`s cells (drainage network).</p> <!-- @@@rio --> <!-- $$$valorPadraoFluxo --> <h3 class="fn"><a name="valorPadraoFluxo-var"></a>int Fluxo::valorPadraoFluxo</h3> <p>This variable holds the default value for fluxoMinimo.</p> <!-- @@@valorPadraoFluxo --> <!-- $$$vetorDeFilasDeNiveis --> <h3 class="fn"><a name="vetorDeFilasDeNiveis-var"></a>queue&lt;<a href="fluxo.html#ponto-typedef">ponto</a>&gt; Fluxo::vetorDeFilasDeNiveis [2 * limiteAltidude]</h3> <p>This variable holds the queue of ponto used to restore the nexts ponto that will be alagado.</p> <!-- @@@vetorDeFilasDeNiveis --> </div> <p class="naviNextPrevious footerNavi"> [Previous: <a href="camada.html">Camada</a>] [Next: <a href="inundacao.html">Inundacao</a>] </p> </body> </html> <file_sep>/**************************************************************************** ** Meta object code from reading C++ file 'janelabarragem.h' ** ** Created: Mon 1. Oct 21:26:39 2012 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../janelabarragem.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'janelabarragem.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_janelabarragem[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 12, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 16, 15, 15, 15, 0x08, 40, 15, 15, 15, 0x08, 71, 66, 15, 15, 0x08, 105, 66, 15, 15, 0x08, 142, 66, 15, 15, 0x08, 179, 66, 15, 15, 0x08, 216, 66, 15, 15, 0x08, 253, 66, 15, 15, 0x08, 290, 66, 15, 15, 0x08, 327, 66, 15, 15, 0x08, 363, 66, 15, 15, 0x08, 399, 66, 15, 15, 0x08, 0 // eod }; static const char qt_meta_stringdata_janelabarragem[] = { "janelabarragem\0\0on_pushButton_clicked()\0" "on_pushButton_2_clicked()\0arg1\0" "on_novoDireCamX_valueChanged(int)\0" "on_spinBoxPosicaoX_valueChanged(int)\0" "on_spinBoxPosicaoZ_valueChanged(int)\0" "on_spinBoxPosicaoY_valueChanged(int)\0" "on_spinBoxDirecaoX_valueChanged(int)\0" "on_spinBoxDirecaoY_valueChanged(int)\0" "on_spinBoxDirecaoZ_valueChanged(int)\0" "on_spinBoxNormalY_valueChanged(int)\0" "on_spinBoxNormalX_valueChanged(int)\0" "on_spinBoxNormalZ_valueChanged(int)\0" }; const QMetaObject janelabarragem::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_janelabarragem, qt_meta_data_janelabarragem, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &janelabarragem::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *janelabarragem::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *janelabarragem::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_janelabarragem)) return static_cast<void*>(const_cast< janelabarragem*>(this)); return QDialog::qt_metacast(_clname); } int janelabarragem::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: on_pushButton_clicked(); break; case 1: on_pushButton_2_clicked(); break; case 2: on_novoDireCamX_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: on_spinBoxPosicaoX_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 4: on_spinBoxPosicaoZ_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 5: on_spinBoxPosicaoY_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 6: on_spinBoxDirecaoX_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 7: on_spinBoxDirecaoY_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 8: on_spinBoxDirecaoZ_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 9: on_spinBoxNormalY_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 10: on_spinBoxNormalX_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 11: on_spinBoxNormalZ_valueChanged((*reinterpret_cast< int(*)>(_a[1]))); break; default: ; } _id -= 12; } return _id; } QT_END_MOC_NAMESPACE <file_sep>#include "janelacamadas.h" #include "ui_janelacamadas.h" /*! \class janelaCamadas \previouspage janelaBarragem2D \contentspage \nextpage janelaOpcaoCor \startpage All Classes \brief Class to create a window for inserting new camadas */ janelaCamadas::janelaCamadas(QWidget *parent) : QDialog(parent), ui(new Ui::janelaCamadas) { ui->setupUi(this); //inserir elementos na lista QStringList nomeDasCores = QColor::colorNames(); for (int i = 0; i < nomeDasCores.size(); ++i) { QColor color(nomeDasCores[i]); ui->caixaBoxCor->insertItem(i, nomeDasCores[i]); ui->caixaBoxCor->setItemData(i, color, Qt::DecorationRole); } } janelaCamadas::~janelaCamadas() { delete ui; } QStringList janelaCamadas::getValores(bool &ok){ //exec espera por uma acao do usuario int botaoApertado = exec(); QStringList parametrosResposta; if(botaoApertado == QDialog::Accepted){ ok = true; //inserindo os elementos da entrada parametrosResposta.push_back(ui->caixaEntradaNomeDaCamada->text()); parametrosResposta.push_back(ui->caixaEntradaPesoDaCamada->text()); //obtendo a cor selecionada QVariant corVariant = ui->caixaBoxCor->itemData(ui->caixaBoxCor->currentIndex(),Qt::DecorationRole); QColor cor = corVariant.value<QColor>(); parametrosResposta.push_back(cor.name()); ok = true; }else { ok = false; } return parametrosResposta; } <file_sep>#ifndef JANELAOPCAOCOR_H #define JANELAOPCAOCOR_H #include <QDialog> namespace Ui { class janelaOpcaoCor; } class janelaOpcaoCor : public QDialog { Q_OBJECT public: //====construtor e destrutor explicit janelaOpcaoCor(QWidget *parent = 0); ~janelaOpcaoCor(); //====metodo QStringList getValores(bool &ok);//sobescrito usado para obter os valores da janela private: //===atributo Ui::janelaOpcaoCor *ui; }; #endif // JANELAOPCAOCOR_H <file_sep>#include "janelaopcaocor.h" #include "ui_janelaopcaocor.h" /*! \class janelaOpcaoCor \previouspage janelaCamadas \contentspage \nextpage janelaopcaofb \startpage All Classes \brief Class to create the window color option */ janelaOpcaoCor::janelaOpcaoCor(QWidget *parent) : QDialog(parent), ui(new Ui::janelaOpcaoCor) { ui->setupUi(this); //inserir elementos na lista QStringList nomeDasCores = QColor::colorNames(); for (int i = 0; i < nomeDasCores.size(); ++i) { QColor color(nomeDasCores[i]); if(color.alpha() != 255 ) continue; ui->caixaCorAlagamento->insertItem(i, nomeDasCores[i]); ui->caixaCorAlagamento->setItemData(i, color, Qt::DecorationRole); } for (int i = 0; i < nomeDasCores.size(); ++i) { QColor color(nomeDasCores[i]); ui->caixaCorBarragem->insertItem(i, nomeDasCores[i]); ui->caixaCorBarragem->setItemData(i, color, Qt::DecorationRole); } for (int i = 0; i < nomeDasCores.size(); ++i) { QColor color(nomeDasCores[i]); ui->caixaCorMenorElevacao->insertItem(i, nomeDasCores[i]); ui->caixaCorMenorElevacao->setItemData(i, color, Qt::DecorationRole); } for (int i = 0; i < nomeDasCores.size(); ++i) { QColor color(nomeDasCores[i]); ui->caixaCorMaiorElevacao->insertItem(i, nomeDasCores[i]); ui->caixaCorMaiorElevacao->setItemData(i, color, Qt::DecorationRole); } for (int i = 0; i < nomeDasCores.size(); ++i) { QColor color(nomeDasCores[i]); ui->caixaCorRedeDeDrenagem->insertItem(i, nomeDasCores[i]); ui->caixaCorRedeDeDrenagem->setItemData(i, color, Qt::DecorationRole); } } janelaOpcaoCor::~janelaOpcaoCor() { delete ui; } QStringList janelaOpcaoCor::getValores(bool &ok){ //exec espera por uma acao do usuario int botaoApertado = exec(); QStringList parametrosResposta; if(botaoApertado == QDialog::Accepted){ ok = true; //artificio utilizado para setar cores default if(ui->corPadraoCaixa->isChecked()) return parametrosResposta; //obtendo a cor selecionada para alagamento QVariant corVariant = ui->caixaCorAlagamento->itemData(ui->caixaCorAlagamento->currentIndex(),Qt::DecorationRole); QColor cor = corVariant.value<QColor>(); parametrosResposta.push_back(cor.name()); //obtendo a cor selecionada para alagamento corVariant = ui->caixaCorBarragem->itemData(ui->caixaCorBarragem->currentIndex(),Qt::DecorationRole); cor = corVariant.value<QColor>(); parametrosResposta.push_back(cor.name()); //obtendo a cor selecionada para alagamento corVariant = ui->caixaCorMaiorElevacao->itemData(ui->caixaCorMaiorElevacao->currentIndex(),Qt::DecorationRole); cor = corVariant.value<QColor>(); parametrosResposta.push_back(cor.name()); //obtendo a cor selecionada para alagamento corVariant = ui->caixaCorMenorElevacao->itemData(ui->caixaCorMenorElevacao->currentIndex(),Qt::DecorationRole); cor = corVariant.value<QColor>(); parametrosResposta.push_back(cor.name()); //obtendo a cor selecionada para alagamento corVariant = ui->caixaCorRedeDeDrenagem->itemData(ui->caixaCorRedeDeDrenagem->currentIndex(),Qt::DecorationRole); cor = corVariant.value<QColor>(); parametrosResposta.push_back(cor.name()); ok = true; }else { if(botaoApertado == QDialog::Rejected) ok = false; else ok = true; } return parametrosResposta; } <file_sep>// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : Fluxo.cpp // @ Date : 19/09/2011 // @ Author : // // #include "Fluxo.h" #include<QString> #include<janelaprincipal.h> #include <QTime> /*! \class Fluxo \previouspage Camada \contentspage \nextpage Inundacao \startpage All Classes \brief Class for create the drainage network, calculated by the flow directionand flow accumulation */ /*! \variable Fluxo::direcao \brief the pointer to pointer, representing the matrix of flow direction */ /*! \variable Fluxo::fluxo \brief the pointer to pointer, representing the matrix of flow accumulation */ /*! \variable Fluxo::rio \brief the pointer to pointer, representing the matrix river`s cells (drainage network) */ /*! \variable Fluxo::fluxoMinimo \brief the minimum flow to consider a cell in the drainage network. Cell`s value in rio matrix above fluxoMinimo is considering a cell of network drainage */ /*! \variable Fluxo::valorPadraoFluxo \brief the default value for fluxoMinimo */ /*! \variable Fluxo::nLinhas \brief the numbers of lines of MDE */ /*! \variable Fluxo::nColunas \brief the number of columns of MDE */ /*! \variable Fluxo::qtdeCelulasRio \brief the number of cells that are in drainage network */ /*! \variable Fluxo::limiteAltidude number representing the maximum value of MDE cell`s elevation. Constant variable with value as 32768 */ /*! \variable Fluxo::processado \brief the representing that a cell have been processed. Constant variable with value as 255 */ /*! \typedef Fluxo::ponto \brief the object to map a cell(point) of MDE easily. */ /*! \variable Fluxo::vetorDeFilasDeNiveis \brief the queue of ponto used to restore the nexts ponto that will be alagado */ /*! \variable Fluxo::direcaoDeFluxo \brief the matrix with predefined directions to help discovery the flow direction of a cell. Is used the maped numbers below for cell and its neighbor 1 2 4 128 cell 8 64 32 16 */ /*! \variable Fluxo::dirEsquerdaCima \brief the constant value of left/up direction. Constant variable with value as 1 */ /*! \variable Fluxo::dirCima \brief the constant value of up direction. Constant variable with value as 2 */ /*! \variable const static int Fluxo::dirDireitaCima constant value of right/up direction. Constant variable with value as 4 */ /*! \variable Fluxo::dirDireita \brief the constant value of right direction. Constant variable with value as 8 */ /*! \variable Fluxo::dirDireitaBaixo \brief the constant value of right/down direction. Constant variable with value as 16 */ /*! \variable Fluxo::dirBaixo \brief the constant value of down direction. Constant variable with value as 32 */ /*! \variable Fluxo::dirEsquerdaBaixo \brief the constant value of left/down direction. Constant variable with value as 64 */ /*! \variable Fluxo::dirEsquerda \brief the constant value of left direction. Constant variable with value as 128 */ /*! \fn Fluxo::calculaFluxo(short int** elevacoes,int noData) \brief function to calculated the drainage network. elevecoes is the matrix with cell`s elevation of terrain. noData is the value representing a invalid cell This function use three another private function: setInundacao to identify the flow direction of each cell. setFluxo to identify the flow accumalate of each cell. setRio to identify cells that are in drainage network. */ void Fluxo::calculaFluxo(short int** elevacoes,int noData) { try { setInundacao(elevacoes); } catch (exception e) { QString erroMsg="Erro no método setInundacao da classe Fluxo"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } try { setFluxo(elevacoes); } catch (exception e) { QString erroMsg="Erro no método setFluxo da classe Fluxo"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } try { setRio(elevacoes,noData); } catch (exception e) { QString erroMsg="Erro no método da setRio classe Fluxo"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } /* ofstream saida("saidaDir.txt"); for(int i = 0; i < nLinhas; i++){ for(int j = 0; j< nColunas; j++){ switch(direcao[i][j]){ case 1: saida<<"ce "; break; case 2: saida<<" c "; break; case 4: saida<<"cd "; break; case 8: saida<<" d "; break; case 16: saida<<"bd "; break; case 32: saida<<" b "; break; case 64: saida<<"be"; break; case 128: saida<<" e "; break; } //saidaDir<<direcao[i][j]<<" "; } saida<<endl; } saida.close(); ofstream saidaFluxoAcumulado("saidaFluxo.txt"); for(int i = 0;i<nLinhas;i++){ for(int j= 0; j<nColunas;j++) saidaFluxoAcumulado<<fluxo[i][j]<<";"; saidaFluxoAcumulado<<endl; } saidaFluxoAcumulado.close(); */ } const int Fluxo::direcaoDeFluxo[129][2]={ {0,0},{-1,-1},{-1,0},{0,0},{-1,1},{0,0},{0,0},{0,0},{0,1},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1,1},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {1,-1},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}, {0,-1} }; /*! \fn Fluxo::Fluxo(Fluxo const& fluxoCopia) \brief Copy Constructor. Creates an object receiving attributes from fluxoCopia */ Fluxo::Fluxo(Fluxo const& fluxoCopia){ valorPadraoFluxo = fluxoCopia.valorPadraoFluxo; this->nColunas = fluxoCopia.nColunas; this->nLinhas = fluxoCopia.nLinhas; direcao = new unsigned char *[nLinhas]; fluxo = new int *[nLinhas]; rio = new bool *[nLinhas]; fluxoMinimo = fluxoCopia.fluxoMinimo; //inicializando vetores for(int i = 0; i < nLinhas; i++){ direcao[i] = new unsigned char [nColunas]; for(int j=0; j<nColunas;++j) direcao[i][j]= fluxoCopia.direcao[i][j]; fluxo[i] = new int [nColunas]; rio[i] = new bool [nColunas]; } for(int i = 0; i < nLinhas; i++){ for(int j=0; j< nColunas;j++){ fluxo[i][j] = fluxoCopia.fluxo[i][j] ; rio[i][j] = fluxoCopia.rio[i][j]; } } qtdeCelulasRio = fluxoCopia.qtdeCelulasRio; } /*! \fn Fluxo::~Fluxo() \brief Destructor */ Fluxo::~Fluxo(){ try{ //deletando vetores alocados dinamicamente for(int i = 0; i < nLinhas; i++){ delete []this->direcao[i]; delete []this->fluxo[i]; delete []this->rio[i]; } delete []this->direcao; delete []this->fluxo; delete []this->rio; //previndo que os ponteiros acessem memoria invalida this->direcao = NULL; this->fluxo = NULL; this->rio = NULL; }catch(exception e){ QString erroMsg="Erro no destrutor da classe Fluxo"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } } /*! \fn Fluxo::Fluxo(int nLinhas, int nColunas) \brief Constructor. Creates an object that have only the variables initialized, no drainage network is calculed yet. */ Fluxo::Fluxo(int nLinhas, int nColunas) { valorPadraoFluxo = nLinhas; direcao = new unsigned char *[nLinhas]; fluxo = new int *[nLinhas]; rio = new bool *[nLinhas]; //inicializando vetores for(int i = 0; i < nLinhas; i++){ direcao[i] = new unsigned char [nColunas]; for(int j=0; j<nColunas;++j) direcao[i][j]=0; fluxo[i] = new int [nColunas]; rio[i] = new bool [nColunas]; } this->nColunas = nColunas; this->nLinhas = nLinhas; qtdeCelulasRio = 0; } void Fluxo::setInundacao(short int** elevacoes) { //setando as bordas da matriz direcao com valores padroes for(int i = 0; i < this->nLinhas;i++){ //inserindo no vetor de filas os elementos da primeira e ultima coluna vetorDeFilasDeNiveis[elevacoes[i][0] + limiteAltidude].push(ponto(i,0)); //int auxA = elevacoes[i][this->nColunas - 1] + limiteAltidude; vetorDeFilasDeNiveis[elevacoes[i][this->nColunas - 1] + limiteAltidude].push(ponto(i,this->nColunas - 1)); direcao[i][0] = dirEsquerda; direcao[i][this->nColunas - 1] = dirDireita; } for(int i = 1; i < this->nColunas -1 ;i++){ //inserindo no vetor de filas os elementos da primeira e ultima linha vetorDeFilasDeNiveis[elevacoes[0][i] + limiteAltidude].push(ponto(0,i)); vetorDeFilasDeNiveis[elevacoes[this->nLinhas - 1][i] + limiteAltidude].push(ponto(this->nLinhas - 1,i)); direcao[0][i] = dirCima; direcao[this->nLinhas - 1][i] = dirBaixo; } //final setando bordas int nivelDoMar = (-1)*limiteAltidude; for(;nivelDoMar<limiteAltidude;nivelDoMar++){ //retirando os elementos da filas de elevecoes //assim estara retirando de forma ordenada while(!vetorDeFilasDeNiveis[nivelDoMar + limiteAltidude].empty()){ ponto p = vetorDeFilasDeNiveis[nivelDoMar+limiteAltidude].front(); vetorDeFilasDeNiveis[nivelDoMar+limiteAltidude].pop(); //verificando se esta nas bordas // recordando p.first = y e p.second = x int x = p.second; int y = p.first; if(x != 0 && y!=0) //vizinho esquerda cima if (direcao[y-1][x-1] == 0) { direcao[y-1][x-1] = dirDireitaBaixo; if ( elevacoes[ y-1][ x-1 ] <= nivelDoMar ) elevacoes[ y-1][x-1 ] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[ y-1][x-1 ]].push( ponto(y-1,x-1 ) ); } if(y != 0) //vizinho cima if (direcao[y-1][x] == 0) { direcao[y-1][x] = dirBaixo; if ( elevacoes[ y-1][ x ] <= nivelDoMar ) elevacoes[ y-1][x ] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[ y-1][x ]].push( ponto(y-1,x ) ); } if(x != (this->nColunas-1) && y!=0) //vizinho direita cima if (direcao[y-1][ x+1] == 0) { direcao[y-1][ x+1] = dirEsquerdaBaixo; if ( elevacoes[ y-1][ x+1 ] <= nivelDoMar ) elevacoes[ y-1][ x+1 ] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[ y-1][ x+1 ]].push( ponto(y-1, x+1 ) ); } if(x != (this->nColunas-1)) //vizinho direita if (direcao[y][x+1] == 0) { direcao[y][x+1] = dirEsquerda; if ( elevacoes[y][x+1] <= nivelDoMar ) elevacoes[y][x+1] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[y][x+1]].push( ponto(y,x+1 ) ); } if(x != (this->nColunas-1) && y!= (this->nLinhas-1)) //vizinho direita baixo if (direcao[y+1][x+1] == 0) { direcao[y+1][x+1] = dirEsquerdaCima; if ( elevacoes[y+1][x+1] <= nivelDoMar ) elevacoes[y+1][x+1] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[y+1][x+1]].push( ponto(y+1,x+1 ) ); } if(y!= (this->nLinhas-1)) //vizinho baixo if (direcao[y+1][x] == 0) { direcao[y+1][x] = dirCima; if ( elevacoes[y+1][x] <= nivelDoMar ) elevacoes[y+1][x] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[y+1][x]].push( ponto(y+1,x ) ); } if(x != 0 && y!= (this->nLinhas-1)) //vizinho esquerda baixo if (direcao[y+1][x-1] == 0) { direcao[y+1][x-1] = dirDireitaCima; if ( elevacoes[y+1][x-1] <= nivelDoMar ) elevacoes[y+1][x-1] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[y+1][x-1]].push( ponto(y+1,x-1 ) ); } if(x != 0) //vizinho esquerda if (direcao[y][x-1] == 0) { direcao[y][x-1] = dirDireita; if ( elevacoes[y][x-1] <= nivelDoMar ) elevacoes[y][x-1] = nivelDoMar; vetorDeFilasDeNiveis[ limiteAltidude +elevacoes[y][x-1]].push( ponto(y,x-1 ) ); } }//fim while }//fim for } void Fluxo::setFluxo(short int** elevacoes) { int **grauDeEntradaDeFluxo; grauDeEntradaDeFluxo = new int *[nLinhas]; for(int i=0; i<nLinhas; ++i){ grauDeEntradaDeFluxo[i] = new int [nColunas]; for(int j=0; j<nColunas; ++j) grauDeEntradaDeFluxo[i][j] = 0; } //Define quantidade de fluxo de entrada para cada ponto que recebe fluxo do ponto (i,j) for(int i=0;i<nLinhas;i++) for(int j=0;j<nColunas;j++) { fluxo[i][j] = 1; //Aproveita para inicializar o fluxo unsigned int ptDir = (unsigned int) direcao[i][j]; if (ptDir!=0) { //Teste para não acessar memória invalida ou fora da borda da matriz if (i+direcaoDeFluxo[ptDir][0] <0 || j+direcaoDeFluxo[ptDir][1] <0 || i+direcaoDeFluxo[ptDir][0] >=nLinhas || j+direcaoDeFluxo[ptDir][1] >=nLinhas ) continue; grauDeEntradaDeFluxo[ i+direcaoDeFluxo[ptDir][0] ][ j+direcaoDeFluxo[ptDir][1] ]++; } } for(int i=0;i<nLinhas;i++) for(int j=0;j<nColunas;j++) { ponto p(i,j); //Distribui o fluxo do ponto (i,j) ao vizinho de (i,j) que recebe seu fluxo while(grauDeEntradaDeFluxo[ p.first ][ p.second ]==0) { grauDeEntradaDeFluxo[ p.first ][ p.second ] = processado; //Marca ponto como processado unsigned int dirPt = (unsigned int)direcao[p.first][p.second]; ponto vizinho( p.first+direcaoDeFluxo[dirPt][0], p.second+direcaoDeFluxo[dirPt][1] ); //Evita acessar posição inválida if (vizinho.first <0 || vizinho.second <0 || vizinho.first >=nLinhas || vizinho.second >=nColunas ) break; //Incrementa fluxo e reduz grau de entrada do vizinho fluxo[ vizinho.first ][ vizinho.second ]+= fluxo[p.first][p.second]; grauDeEntradaDeFluxo[ vizinho.first ][ vizinho.second ]--; p = vizinho; //Repete processo para vizinho } } //Deleta grauDeEntradaDeFluxo for(int i=0;i< nLinhas;i++) delete []grauDeEntradaDeFluxo[i]; delete grauDeEntradaDeFluxo; } void Fluxo::setRio(short int** elevacoes,int noData) { //Se o usuário não definiu fluxo minimo, sera utilizado valor padrao if(fluxoMinimo==0) fluxoMinimo=valorPadraoFluxo; qtdeCelulasRio = 0; //ja foi inicializada mas apenas por garantia //Percorre a matriz de rio, marcando como true as posições cujo fluxo é maior que o valor definido por fluxo minimo for(int i=0; i<nLinhas; ++i) for(int j=0; j<nColunas; ++j) if(fluxo[i][j]>=fluxoMinimo && elevacoes[i][j] != noData){ rio[i][j]=true; qtdeCelulasRio++; } else rio[i][j]=false; } <file_sep>// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : VisualizacaoMapa.h // @ Date : 06/09/2011 // @ Author : // // #if !defined(_VISUALIZACAOMAPA_H) #define _VISUALIZACAOMAPA_H #include "MapaMDE.h" #include "Fluxo.h" #include "Inundacao.h" #include "Camada.h" #include "QColor" class VisualizacaoMapa { public: //===construtores e destrutor VisualizacaoMapa(); VisualizacaoMapa(const char *,int,int); VisualizacaoMapa(VisualizacaoMapa const&);//---construtor copia ~VisualizacaoMapa(); //---Destrutor VisualizacaoMapa& operator=(VisualizacaoMapa const&); //==========Atributos============ MapaMDE *mapa; Fluxo *fluxo; Inundacao *inundacao; QList<Camada> *listaDeCamadas;//lista contendo as camadas adicionadas pelo user short int **camadasSomadas;//camada unica que contem o valor da soma dos pesos da camada double **vetorDeZooms; int marcaInicioX; int marcaInicioY; //Guarda posicao inicial de marcação para barragem int marcaFinalX; int marcaFinalY; //Guarda posicao final de marcação para barragem bool marcouInicio; //Informa se o inicio do trecho ja foi marcado bool marcouFim;//Informa se o fim do trecho ja foi marcado double proporcaoZoom;//variavel que determina a proporcao do zoom atual para ser usado no tamanho do ponto entre outras coisas double constanteDeProporcaoZoom;//constante pra ser utilizada no proporcaoZoom int tamanhoDaBarraDeZoom; int maxPointSize;//tamanho maximo do ponto do opengl bool estaPreSalvo; //peso que sera utilizado para calcula a funcao objetivo int pesoEBarragem; int pesoHBarragem; int pesoAreaAlagada; int pesoVolume; int pesoABarragem; int pesoCamadas; const static int pesoEBarragemPadrao = 10; const static int pesoHBarragemPadrao = 10; const static int pesoAreaAlagadaPadrao = 10; const static int pesoVolumePadrao = 10; const static int pesoABarragemPadrao = 10; const static int pesoCamadasPadrao = 0; int maxPontosABuscar;//usado para limitar a busca em buscas com recursividade //==========Métodos============ int getFuncaoObjetivo();//retorna a funcao objetivo void atualizaCamadasSomadas();//atualiza a matriz de camadas somadas void atualizaPesoCamadas(); void atualizaPesos(int,int,int,int,int);//atualiza os pesos das características int getIndCamada (QString);//busca em listaDeCamada uma camada com o nome dado MapaMDE *getMapa(); double getProporcaoZoom(); int getZoom(),getTamanhoDoPonto(),getProporcaoX(),getProporcaoY(); void setTamanhoPonto(int ,int); void setZoom(int zoom); void setInundacao(int posX, int posY,int,int,int); void encontraPontosJusante(int x, int y,bool& , bool**,int &);//metodo recurso para definir os pontos a serem buscados void insereCamada(Camada); //===metodos sobescritos QList<Camada>& operator=(QList<Camada> const&); bool operator==(QList<Camada> const&); private: //===atributos QColor corMapa; double proporcaoTela; int proporcaoX; int proporcaoY; int tamanhoDoPonto; int larguraTela; int alturaTela; int zoom; }; #endif //_VISUALIZACAOMAPA_H <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelacamada.ui' ** ** Created: Tue 20. Mar 12:39:38 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELACAMADA_H #define UI_JANELACAMADA_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QDialogButtonBox> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> QT_BEGIN_NAMESPACE class Ui_Dialog { public: QDialogButtonBox *buttonBox; QLineEdit *caixaNomeDaCamada; QLabel *label; QLineEdit *caixaPesoDaCamada; QLabel *label_2; void setupUi(QDialog *Dialog) { if (Dialog->objectName().isEmpty()) Dialog->setObjectName(QString::fromUtf8("Dialog")); Dialog->resize(371, 171); buttonBox = new QDialogButtonBox(Dialog); buttonBox->setObjectName(QString::fromUtf8("buttonBox")); buttonBox->setGeometry(QRect(20, 130, 341, 32)); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); caixaNomeDaCamada = new QLineEdit(Dialog); caixaNomeDaCamada->setObjectName(QString::fromUtf8("caixaNomeDaCamada")); caixaNomeDaCamada->setGeometry(QRect(90, 10, 113, 20)); label = new QLabel(Dialog); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(20, 10, 46, 13)); caixaPesoDaCamada = new QLineEdit(Dialog); caixaPesoDaCamada->setObjectName(QString::fromUtf8("caixaPesoDaCamada")); caixaPesoDaCamada->setGeometry(QRect(90, 50, 113, 20)); label_2 = new QLabel(Dialog); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(20, 50, 46, 13)); retranslateUi(Dialog); QObject::connect(buttonBox, SIGNAL(accepted()), Dialog, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), Dialog, SLOT(reject())); QMetaObject::connectSlotsByName(Dialog); } // setupUi void retranslateUi(QDialog *Dialog) { Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("Dialog", "Nome", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("Dialog", "Peso", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class Dialog: public Ui_Dialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELACAMADA_H <file_sep>#ifndef JANELAOPCAOFB_H #define JANELAOPCAOFB_H #include <QDialog> namespace Ui { class janelaopcaofb; } class janelaopcaofb : public QDialog { Q_OBJECT public: explicit janelaopcaofb(QWidget *parent = 0); ~janelaopcaofb(); //metodos sobescrito QStringList getValores(bool &ok); private: Ui::janelaopcaofb *ui; }; #endif // JANELAOPCAOFB_H <file_sep>#ifndef PAINELVISUALIZACAOBARRAGEMOPENGL_H #define PAINELVISUALIZACAOBARRAGEMOPENGL_H #include <QGLWidget> #include "VisualizacaoMapa.h" class PainelVisualizacaoBarragemOpenGL : public QGLWidget { Q_OBJECT public: //===construtor explicit PainelVisualizacaoBarragemOpenGL(QWidget *parent = 0); //====atributo int posicaoCamera[3], normalCamera[3], direcaoCamera[3]; //=====metodos void carregandoInformacoes(VisualizacaoMapa *); void desenhaTerreno(); protected : //===metodos opengl void defineOrtho(); void initializeGL(); void resizeGL(int w, int h); void paintGL(); signals: public slots: void keyPressEvent(QKeyEvent *); private: VisualizacaoMapa *visualizacaoMapa; }; #endif // PAINELVISUALIZACAOBARRAGEMOPENGL_H <file_sep>/******************************************************************************** ** Form generated from reading UI file 'sobre.ui' ** ** Created: Fri 6. Jul 14:27:54 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_SOBRE_H #define UI_SOBRE_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QDialog> #include <QtGui/QFrame> #include <QtGui/QHeaderView> #include <QtGui/QLabel> QT_BEGIN_NAMESPACE class Ui_Dialog { public: QLabel *label; QLabel *label_2; QLabel *label_3; QFrame *line; QLabel *label_4; QLabel *label_5; QLabel *label_6; void setupUi(QDialog *Dialog) { if (Dialog->objectName().isEmpty()) Dialog->setObjectName(QString::fromUtf8("Dialog")); Dialog->resize(277, 238); label = new QLabel(Dialog); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(110, 0, 131, 121)); label->setWordWrap(true); label_2 = new QLabel(Dialog); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(110, 80, 131, 16)); label_3 = new QLabel(Dialog); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setGeometry(QRect(110, 140, 101, 16)); line = new QFrame(Dialog); line->setObjectName(QString::fromUtf8("line")); line->setGeometry(QRect(20, 160, 241, 20)); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); label_4 = new QLabel(Dialog); label_4->setObjectName(QString::fromUtf8("label_4")); label_4->setGeometry(QRect(110, 100, 121, 16)); label_5 = new QLabel(Dialog); label_5->setObjectName(QString::fromUtf8("label_5")); label_5->setGeometry(QRect(20, 180, 46, 13)); label_6 = new QLabel(Dialog); label_6->setObjectName(QString::fromUtf8("label_6")); label_6->setGeometry(QRect(60, 180, 71, 61)); label_6->setPixmap(QPixmap(QString::fromUtf8("../imagens/brasaoUFVPequeno.png"))); retranslateUi(Dialog); QMetaObject::connectSlotsByName(Dialog); } // setupUi void retranslateUi(QDialog *Dialog) { Dialog->setWindowTitle(QApplication::translate("Dialog", "Dialog", 0, QApplication::UnicodeUTF8)); label->setText(QApplication::translate("Dialog", "Sistema de posicionamento de barragens", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("Dialog", "Desenvolvido em 2012", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("Dialog", "Vers\303\243o Beta 1.0", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("Dialog", "TARG-Terrain", 0, QApplication::UnicodeUTF8)); label_5->setText(QApplication::translate("Dialog", "Apoio:", 0, QApplication::UnicodeUTF8)); label_6->setText(QString()); } // retranslateUi }; namespace Ui { class Dialog: public Ui_Dialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_SOBRE_H <file_sep>#ifndef JANELAPRINCIPAL_H #define JANELAPRINCIPAL_H #include <QMainWindow> #include <string> #include <VisualizacaoMapa.h> #include<janelacamadas.h> #include <fstream> #include<Camada.h> #include <janelabarragem.h> #include <janelabarragem2d.h> #include <QKeyEvent> #include <QTableWidgetItem> namespace Ui { class JanelaPrincipal; } class JanelaPrincipal : public QMainWindow { Q_OBJECT public: //===construtor e destrutor explicit JanelaPrincipal(QWidget *parent = 0); ~JanelaPrincipal(); //===atributos map<string,VisualizacaoMapa> mapeamentoAreaProjeto; //usado para expor elementos na area de projeto QStringList stringAreaProjeto;//usado como auxiliar do map para armazenar o nome dos elementos //posicao para os botoes de zoom isto permite que os mesmos andem ao mexer no slider int posXBotaoZoomMais; int posYBotaoZoomMais; int posXBotaoZoomMenos; int posYBotaoZoomMenos; int posXBarraZoom; int posYBarraZoom; //atrr flag bool escolhendoPontosCamada;//variavel que define se o botao do mouse esta segurado bool selecaoPontos;//define se o usuario esta adicionando ou subtraindo elementos da camada bool selecaoPontoBarragem;//define se o click deve ir para os metodos de adicionar pontos a camada ou seta posicao da barragem QList<Point> listaDePosicoesMouse;//lista utilizada para se criar os pontos continuos usa o ultimo(clicado) e o anterior bool pontosContinuos; //define se os pontos deve ser continuos const static QString urllog; //======Metodos void setaTelaPadrao();//reseta os campos void setaTamanhoBarraDeZoom();//define o tamanho da barragem cada mapa pode ter a sua void habilitandoBotoes();//habilita todos os botoes void desAbilitandoBotoes();//desabilita botoes que nao podem ser apertados sem o mapa estar carregado void atualizaCamposSaida();//atualiza o campo de saida apos os calculos void deletaListaComCamadas();//deleta elementos contido na lista de camadas exposta ao usuario void criaListaComCamadas();//preenche a lista de camadas exposta ao usuario void preenchePontosContinuo(Point ,Point,int);//o pc nao pega o mouse em todos os pontos, dai esse metodo fecha linha bool pontoDoRioMaisProximo(int posX, int posY, int raio);//ima pro mouse ir ao rio, facilitar ao clicar perto void criaVisualizacaoBarragem();//funcao que abre as janelas 2D ou 3D void preencheSolido(int posClickY,int posClickX,int indCamada,int numPreenchidos);//preenche um solido fechado desenhado da camada QPoint buscaMelhorPonto(VisualizacaoMapa,QList<QPoint>,double);//metodo que busca o melhor posicionamento de matriz void mousePressionadoParaCamada(QMouseEvent * ev);//metodo que tem os metodos a chamar ao se trabalhar com camada (nao é slot) void mousePressionadoParaBarragem(QMouseEvent * ev);//metodo que tem os metodos a chamar ao se trabalhar com barragem (nao é slot) int valorDirecaoVetorNormal();//metodo que obtem o valor da direcao alem de verficar se os campos foram todos preenchidos corretamentes protected slots: void on_actionAbrir_mapa_triggered(); void on_barraZoom_sliderMoved(int position); void on_botaoZoomMais_clicked(); void on_botaoZoomMenos_clicked(); void on_botaoAtualizarFluxoMinimo_clicked(); void trocaCoordenadas(QMouseEvent*); void defineCamada(int,int); void defineInundacao(QMouseEvent*); void adicionandoPontosACamada(QMouseEvent* ev); void movendoMouse(QMouseEvent* ev); void moveBarragem(QKeyEvent* kev); void imprimeBarragem(VisualizacaoMapa,int); bool eEntruncamentoDeRios(int posx, int posy); void exporCamada(QTableWidgetItem*); //void keyPressEvent(QKeyEvent*); private slots: void on_botaoAdicionarInundacao_clicked(); void on_botaoExcluirInundacao_clicked(); void on_botaoVisualizarInundacao_clicked(); void on_insereCamada_clicked(); void on_selecaoPontosCamada_clicked(); void on_radioButtonV_clicked(); void on_radioButtonDP_clicked(); void on_pushButton_clicked(); void moveZoomHorizontal(int); void moveZoomVertical(int); void on_actionSobre_triggered(); void on_actionFechar_mapa_triggered(); void on_actionCores_triggered(); void on_deletaCamada_clicked(); void on_botaoAlternaBC_clicked(); void on_actionFunc_Objetivo_triggered(); void on_caixaApresentaFuncaoObjetivo_clicked(); void on_radioButtonM_clicked(); void on_radioButtonManual_clicked(); void on_radioButtonManual45_clicked(); void on_radioButtonManual0_clicked(); void on_radioButtonManual135_clicked(); void on_radioButtonManual90_clicked(); void on_botaoFechaManual_clicked(); private: janelaCamadas *uiCamadas; //janela barragem visual 3D janelabarragem *uiBarragem; //janela de adicionar barragem janelaBarragem2D *uiBarragem2d;//janela perfil barragem 2D Ui::JanelaPrincipal *ui; }; #endif // JANELAPRINCIPAL_H <file_sep>#ifndef JANELASOBRE_H #define JANELASOBRE_H #include <QDialog> namespace Ui { class janelasobre; } class janelasobre : public QDialog { Q_OBJECT public: explicit janelasobre(QWidget *parent = 0); ~janelasobre(); private: Ui::janelasobre *ui; }; #endif // JANELASOBRE_H <file_sep>#include "janelabarragem2d.h" #include "ui_janelabarragem2d.h" /*! \class janelaBarragem2D \previouspage janelabarragem \contentspage \nextpage janelaCamadas \startpage All Classes \brief Class to create a window 2D view of the reservoir */ janelaBarragem2D::janelaBarragem2D(QWidget *parent) : QDialog(parent), ui(new Ui::janelaBarragem2D) { ui->setupUi(this); // setWindowFlags(Qt::WindowStaysOnTopHint); } void janelaBarragem2D::recarregandoMapa(VisualizacaoMapa *viMapa){ ui->widget->makeCurrent(); //CARREGANDO INFO DA BARRAGEM //ATUALIZA A LISTA ui->textEdit3->setText(ui->textEdit2->toPlainText()); ui->textEdit2->setText(ui->textEdit1->toPlainText()); QString infoBarragem = " Info Barragem "; QString altBarragem = "AlturaBarragem-"; QString areaAlagada = "Area Alagada-"; QString tamanhoBarragem = "Extensao Barragem-"; altBarragem += QString::number(viMapa->inundacao->nivelAgua); areaAlagada +=QString::number(viMapa->inundacao->areaLaminaAgua); tamanhoBarragem +=QString::number(viMapa->inundacao->comprimentoBarragemTocada); infoBarragem += "\n"; infoBarragem+=altBarragem +"\n"+ areaAlagada +"\n"+ tamanhoBarragem; ui->textEdit1->setText(infoBarragem); ui->widget->carregandoInformacoes(viMapa); } janelaBarragem2D::~janelaBarragem2D() { delete ui; } <file_sep>// // // Generated by StarUML(tm) C++ Add-In // // @ Project : Untitled // @ File Name : MapaMDE.cpp // @ Date : 29/08/2011 // @ Author : <NAME> // // #include "MapaMDE.h" #include <fstream> #include <iostream> #include <string> #include <cstdlib> #include <QString> #include <QDate> #include<janelaprincipal.h> using namespace std; /*! \class MapaMDE \previouspage janelasobre \nextpage painelvisualizacaobarragem2dopengl \startpage All Classes \indexpage All Classes \startpage All Classes \brief Class for create the MDE of terrain */ /*! \variable MapaMDE::matrizDeElevacoes \brief a pointer to pointer, representing a matrix of status of the cell. If it is dam, drainage network, flooded or nothing */ /*! \variable MapaMDE::maxElev \brief the maximum cell's elevation */ /*! \variable MapaMDE::minElev \brief the minimun cell's elevation */ /*! \fn MapaMDE::MapaMDE() \brief Constructor. Default Constructor. Do nothing */ MapaMDE::MapaMDE(){ } /*! \fn MapaMDE::~MapaMDE() \brief Destructor. */ MapaMDE::~MapaMDE(){ try{ //liberando memoria apontada pelos ponteiros for(int i = 0; i < nLinhas;i++) delete matrizDeElevacoes[i]; delete []matrizDeElevacoes; //previnindo que o ponteiro acesse memoria invalida matrizDeElevacoes = NULL; delete []caminhoArquivo; caminhoArquivo = NULL; delete [] nomeArquivo; nomeArquivo = NULL; }catch(exception e){ QString erroMsg="Erro no destrutor da classe MapaMDE"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } } /*! \fn MapaMDE::MapaMDE(MapaMDE const &mapaCopia) \brief Copy Constructor. Creates an object receiving attributes from mapaCopia */ MapaMDE::MapaMDE(MapaMDE const &mapaCopia){ nColunas = mapaCopia.nColunas; nLinhas = mapaCopia.nLinhas; dadoInvalido = mapaCopia.dadoInvalido; xllcorner = mapaCopia.xllcorner; yllcorner = mapaCopia.yllcorner; matrizDeElevacoes = new short int *[nLinhas]; for(int i = 0; i < nLinhas;i++) matrizDeElevacoes[i] = new short int[nColunas]; for(int i=0; i<nLinhas; i++) for(int j=0; j<nColunas; j++) matrizDeElevacoes[i][j] = mapaCopia.matrizDeElevacoes[i][j]; nomeArquivo = new char [30]; strcpy(nomeArquivo, mapaCopia.nomeArquivo); caminhoArquivo = new char[256]; strcpy(caminhoArquivo, mapaCopia.caminhoArquivo); maxElev = mapaCopia.maxElev; minElev = mapaCopia.minElev; } /*! \fn MapaMDE::MapaMDE(const char * caminhoArquivo ) \brief Constructor. Creates a object (MDE) for especified caminhoArquivo path */ MapaMDE::MapaMDE(const char * caminhoArquivo ) { //posteriormente pode-se ter como entrada //diversos outros formatos, porem por hora apenas //o asscii padrao do arcgis maxElev = 0; minElev = 999999; try { scannerAscii(caminhoArquivo); } catch (exception e) { QString erroMsg="Erro no método scannerAscii classe MapaMDE"; ofstream erro(JanelaPrincipal::urllog.toStdString().data()); erro<<"Erro ocorrido em: "; erro<< QDate::currentDate().toString("dd.MM.yyyy").toStdString(); erro<<endl; erro<<erroMsg.toStdString()<<endl; erro<<e.what()<<endl; erro.close(); } } /*! \fn MapaMDE::getNColunas() \brief Returns the number of columns */ int MapaMDE::getNColunas() { return nColunas; } /*! \fn MapaMDE::getNLinhas() Returns the number of lines */ int MapaMDE::getNLinhas() { return nLinhas; } /*! \fn MapaMDE::getResolucao() Returns the resolution of the cell */ short int MapaMDE::getResolucao() { return tamanhoCelula; } /*! \fn MapaMDE::getDadoInvalido() Returns the value of invalid data */ short int MapaMDE::getDadoInvalido() { return dadoInvalido; } /*! \fn MapaMDE::getCaminhoArquivo() Returns the full path of file contain the MDE */ char * MapaMDE::getCaminhoArquivo() { return caminhoArquivo; } /*! \fn MapaMDE::getNomeArquivo() Returns the name of the file MDE */ char * MapaMDE::getNomeArquivo() { return nomeArquivo; } /**este metodo se encarrega de fazer a leitura do arquivo ascii e atribui as os valores as variaveis **/ void MapaMDE::scannerAscii(const char * caminhoArquivo ) { ifstream entrada; entrada.open(caminhoArquivo,ifstream::in); //setando o nome e caminho do arquivo QString fileName (caminhoArquivo); this->caminhoArquivo = new char[262]; nomeArquivo = new char[30]; fileName = fileName.section("/",-1,-1); strcpy(nomeArquivo, fileName.toAscii().data()); strcpy(this->caminhoArquivo,caminhoArquivo); /*padrao de leitura ncols nrows xllcorner yllcorner cellsize NODATA_value */ //ignorando a leitura do escrito n cols entrada.ignore(256, ' '); entrada>>nColunas; //ignorando a leitura do escrito n linhas entrada.ignore(256, ' '); entrada>>nLinhas; //ignorando a leitura do escrito xllcorner entrada.ignore(256, ' '); entrada>>xllcorner; //ignorando a leitura do escrito yllcorner entrada.ignore(256, ' '); entrada>>yllcorner; //ignorando a leitura do escrito cellsize entrada.ignore(256, ' '); entrada>>tamanhoCelula; //ignorando a leitura do escrito noData entrada.ignore(256, ' '); entrada>>dadoInvalido; matrizDeElevacoes = new short int *[nLinhas]; for(int i = 0; i < nLinhas;i++) matrizDeElevacoes[i] = new short int[nColunas]; //ind i para linha j para coluna int i,j; i=j=0; while(i < nLinhas){//entrada.eof nao esta fazendo como o esperado //esquema para pular linhas if(j >= nColunas){ i++; j = 0; if(i>=nLinhas) break; } double auxLeitura; string auxTrocaVirgulaPonto; entrada>>auxTrocaVirgulaPonto; //trocando virgula por ponto unsigned int localVirgula = auxTrocaVirgulaPonto.find(","); if(localVirgula != string::npos){ auxTrocaVirgulaPonto = auxTrocaVirgulaPonto.replace(auxTrocaVirgulaPonto.find(","),0,"."); auxTrocaVirgulaPonto = auxTrocaVirgulaPonto.erase(auxTrocaVirgulaPonto.find(","),1); } auxLeitura = atof(auxTrocaVirgulaPonto.data()); //entrada>>auxLeitura; matrizDeElevacoes[i][j]=auxLeitura; if(auxLeitura <0) cout<<"teste"; if(matrizDeElevacoes[i][j] != dadoInvalido && matrizDeElevacoes[i][j]>0){ if(matrizDeElevacoes[i][j]>maxElev) maxElev = matrizDeElevacoes[i][j]; if(matrizDeElevacoes[i][j]<minElev) minElev = matrizDeElevacoes[i][j]; } j++; } entrada.close(); // ofstream saida("testandoEntrada.txt"); // for(int i = 0; i < nLinhas; i++){ // for(int j = 0; j< nColunas; j++) // saida<<matrizDeElevacoes[i][j]<<"-"; // saida<<endl; // } // saida.close(); } void MapaMDE::substituindoVirgurlaPonto(const char * caminhoArquivo){ // StreamReader ms = new StreamReader(caminhoArquivo); } <file_sep>#ifndef JANELABARRAGEM2D_H #define JANELABARRAGEM2D_H #include <QDialog> #include<VisualizacaoMapa.h> namespace Ui { class janelaBarragem2D; } class janelaBarragem2D : public QDialog { Q_OBJECT public: //==construtor e destrutor explicit janelaBarragem2D(QWidget *parent = 0); ~janelaBarragem2D(); //====metodos void recarregandoMapa(VisualizacaoMapa *viMapa); private: //===atributo Ui::janelaBarragem2D *ui; }; #endif // JANELABARRAGEM2D_H <file_sep>/******************************************************************************** ** Form generated from reading UI file 'janelaprincipal.ui' ** ** Created: Mon 1. Oct 21:22:53 2012 ** by: Qt User Interface Compiler version 4.7.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_JANELAPRINCIPAL_H #define UI_JANELAPRINCIPAL_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QCheckBox> #include <QtGui/QFormLayout> #include <QtGui/QGridLayout> #include <QtGui/QGroupBox> #include <QtGui/QHBoxLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QListView> #include <QtGui/QMainWindow> #include <QtGui/QMenu> #include <QtGui/QMenuBar> #include <QtGui/QPushButton> #include <QtGui/QRadioButton> #include <QtGui/QScrollArea> #include <QtGui/QSlider> #include <QtGui/QTabWidget> #include <QtGui/QTableWidget> #include <QtGui/QVBoxLayout> #include <QtGui/QWidget> #include "painelvisualizacaoopengl.h" QT_BEGIN_NAMESPACE class Ui_JanelaPrincipal { public: QAction *actionAbrir_mapa; QAction *actionExportar_mapa; QAction *actionSair; QAction *actionSalvar; QAction *actionSobre; QAction *actionFechar_mapa; QAction *actionCores; QAction *actionFunc_Objetivo; QWidget *centralWidget; QGridLayout *gridLayout; QFormLayout *formLayout; QGroupBox *groupBox; QTabWidget *tabWidget; QWidget *tab; QListView *listView; QPushButton *botaoAdicionarInundacao; QPushButton *botaoExcluirInundacao; QPushButton *botaoVisualizarInundacao; QWidget *tab_2; QPushButton *botaoAlternaBC; QTableWidget *camadaTableWidget; QPushButton *insereCamada; QPushButton *deletaCamada; QPushButton *selecaoPontosCamada; QGroupBox *groupBox_2; QLineEdit *campoEntradaCapacidadeDesejada; QLabel *label; QLabel *label_3; QLineEdit *campoEntradaLargMaxBarragem; QPushButton *botaoAtualizarFluxoMinimo; QLabel *label_2; QLineEdit *campoEntradaFluxoMinimo; QGroupBox *groupBox_3; QRadioButton *radioButtonV; QLineEdit *campoEntradaValorAlgoritmo; QLabel *label_7; QLineEdit *campoEntradaEpislonAlgoritmo; QLabel *label_10; QRadioButton *radioButtonM; QRadioButton *radioButtonManual; QGroupBox *widgetManual; QRadioButton *radioButtonManual0; QRadioButton *radioButtonManual45; QRadioButton *radioButtonManual90; QRadioButton *radioButtonManual135; QLabel *barragem90; QLabel *barragem0; QLabel *barragem45; QLabel *barragem135; QPushButton *botaoFechaManual; QRadioButton *radioButtonDP; QGroupBox *groupBox_7; QGridLayout *gridLayout_2; QScrollArea *scrollArea; PainelVisualizacaoOpenGL *widget; QSlider *barraZoom; QPushButton *botaoZoomMais; QPushButton *botaoZoomMenos; QFormLayout *formLayout_2; QGroupBox *groupBox_5; QLineEdit *campoSaidaCoordenadasBaseY; QLineEdit *campoSaidaCoordenadasBaseX; QLineEdit *campoSaidaCoordenadasY; QLineEdit *campoSaidaCoordenadasX; QLabel *label_19; QLabel *label_18; QWidget *layoutWidget; QHBoxLayout *horizontalLayout; QLabel *label_9; QCheckBox *caixaPreSalvo; QWidget *layoutWidget1; QHBoxLayout *horizontalLayout_2; QLabel *label_17; QLineEdit *campoSaidaFluxoMinimo; QWidget *layoutWidget2; QVBoxLayout *verticalLayout; QLabel *label_14; QLineEdit *campoSaidaNomeArquivo; QWidget *layoutWidget3; QVBoxLayout *verticalLayout_6; QLabel *label_15; QLineEdit *campoSaidaCaminhoArquivo; QCheckBox *checkBoxVisualiza2D; QCheckBox *checkBoxVisualiza3D; QGroupBox *groupBox_4; QGroupBox *groupBox_6; QWidget *layoutWidget4; QVBoxLayout *verticalLayout_4; QLabel *label_5; QLineEdit *campoSaidaAlturaBarragem; QWidget *layoutWidget5; QVBoxLayout *verticalLayout_7; QLabel *label_11; QLineEdit *campoSaidaAreaBarragem; QWidget *layoutWidget6; QVBoxLayout *verticalLayout_5; QLabel *label_4; QLineEdit *campoSaidaExtensaoBarragem; QGroupBox *groupBox_8; QWidget *layoutWidget7; QVBoxLayout *verticalLayout_3; QLabel *label_6; QLineEdit *campoSaidaCapacidadeTotal; QWidget *layoutWidget8; QVBoxLayout *verticalLayout_2; QLabel *label_8; QLineEdit *campoSaidaAreaLaminaDaAgua; QGroupBox *groupBox_9; QLineEdit *campoSaidaFuncaoObjetivo; QCheckBox *caixaApresentaFuncaoObjetivo; QMenuBar *menuBar; QMenu *menuTeste; QMenu *menuAjuda; QMenu *menuEdita; QMenu *menuOp_es; void setupUi(QMainWindow *JanelaPrincipal) { if (JanelaPrincipal->objectName().isEmpty()) JanelaPrincipal->setObjectName(QString::fromUtf8("JanelaPrincipal")); JanelaPrincipal->resize(1027, 650); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(JanelaPrincipal->sizePolicy().hasHeightForWidth()); JanelaPrincipal->setSizePolicy(sizePolicy); JanelaPrincipal->setMinimumSize(QSize(1027, 650)); JanelaPrincipal->setMaximumSize(QSize(1027, 650)); QIcon icon; icon.addFile(QString::fromUtf8("../imagens/logo3.png"), QSize(), QIcon::Normal, QIcon::Off); JanelaPrincipal->setWindowIcon(icon); JanelaPrincipal->setIconSize(QSize(160, 120)); actionAbrir_mapa = new QAction(JanelaPrincipal); actionAbrir_mapa->setObjectName(QString::fromUtf8("actionAbrir_mapa")); QIcon icon1; icon1.addFile(QString::fromUtf8("../imagens/iconeAbrir.png"), QSize(), QIcon::Normal, QIcon::Off); actionAbrir_mapa->setIcon(icon1); actionAbrir_mapa->setShortcutContext(Qt::ApplicationShortcut); actionExportar_mapa = new QAction(JanelaPrincipal); actionExportar_mapa->setObjectName(QString::fromUtf8("actionExportar_mapa")); actionExportar_mapa->setEnabled(false); actionExportar_mapa->setMenuRole(QAction::ApplicationSpecificRole); actionSair = new QAction(JanelaPrincipal); actionSair->setObjectName(QString::fromUtf8("actionSair")); actionSalvar = new QAction(JanelaPrincipal); actionSalvar->setObjectName(QString::fromUtf8("actionSalvar")); actionSalvar->setEnabled(false); actionSobre = new QAction(JanelaPrincipal); actionSobre->setObjectName(QString::fromUtf8("actionSobre")); actionFechar_mapa = new QAction(JanelaPrincipal); actionFechar_mapa->setObjectName(QString::fromUtf8("actionFechar_mapa")); actionFechar_mapa->setEnabled(false); actionCores = new QAction(JanelaPrincipal); actionCores->setObjectName(QString::fromUtf8("actionCores")); QIcon icon2; icon2.addFile(QString::fromUtf8("../imagens/iconePincel.png"), QSize(), QIcon::Normal, QIcon::Off); actionCores->setIcon(icon2); actionFunc_Objetivo = new QAction(JanelaPrincipal); actionFunc_Objetivo->setObjectName(QString::fromUtf8("actionFunc_Objetivo")); QIcon icon3; icon3.addFile(QString::fromUtf8("../imagens/iconeEngrenagem.png"), QSize(), QIcon::Normal, QIcon::Off); actionFunc_Objetivo->setIcon(icon3); centralWidget = new QWidget(JanelaPrincipal); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); gridLayout = new QGridLayout(centralWidget); gridLayout->setSpacing(6); gridLayout->setContentsMargins(11, 11, 11, 11); gridLayout->setObjectName(QString::fromUtf8("gridLayout")); formLayout = new QFormLayout(); formLayout->setSpacing(6); formLayout->setObjectName(QString::fromUtf8("formLayout")); formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); groupBox = new QGroupBox(centralWidget); groupBox->setObjectName(QString::fromUtf8("groupBox")); sizePolicy.setHeightForWidth(groupBox->sizePolicy().hasHeightForWidth()); groupBox->setSizePolicy(sizePolicy); groupBox->setMinimumSize(QSize(161, 320)); groupBox->setMaximumSize(QSize(161, 320)); groupBox->setFlat(false); groupBox->setCheckable(false); tabWidget = new QTabWidget(groupBox); tabWidget->setObjectName(QString::fromUtf8("tabWidget")); tabWidget->setEnabled(true); tabWidget->setGeometry(QRect(2, 7, 160, 300)); sizePolicy.setHeightForWidth(tabWidget->sizePolicy().hasHeightForWidth()); tabWidget->setSizePolicy(sizePolicy); tabWidget->setMinimumSize(QSize(160, 300)); tabWidget->setMaximumSize(QSize(160, 300)); tabWidget->setTabPosition(QTabWidget::West); tabWidget->setTabShape(QTabWidget::Rounded); tabWidget->setDocumentMode(true); tabWidget->setMovable(true); tab = new QWidget(); tab->setObjectName(QString::fromUtf8("tab")); sizePolicy.setHeightForWidth(tab->sizePolicy().hasHeightForWidth()); tab->setSizePolicy(sizePolicy); tab->setMinimumSize(QSize(160, 300)); tab->setMaximumSize(QSize(160, 300)); listView = new QListView(tab); listView->setObjectName(QString::fromUtf8("listView")); listView->setGeometry(QRect(3, 4, 128, 265)); sizePolicy.setHeightForWidth(listView->sizePolicy().hasHeightForWidth()); listView->setSizePolicy(sizePolicy); listView->setMinimumSize(QSize(128, 265)); listView->setMaximumSize(QSize(128, 265)); listView->setFrameShape(QFrame::WinPanel); listView->setLineWidth(3); listView->setTabKeyNavigation(true); listView->setIconSize(QSize(4, 1)); listView->setFlow(QListView::TopToBottom); listView->setLayoutMode(QListView::Batched); listView->setViewMode(QListView::ListMode); listView->setModelColumn(0); botaoAdicionarInundacao = new QPushButton(tab); botaoAdicionarInundacao->setObjectName(QString::fromUtf8("botaoAdicionarInundacao")); botaoAdicionarInundacao->setEnabled(false); botaoAdicionarInundacao->setGeometry(QRect(2, 272, 45, 23)); sizePolicy.setHeightForWidth(botaoAdicionarInundacao->sizePolicy().hasHeightForWidth()); botaoAdicionarInundacao->setSizePolicy(sizePolicy); botaoAdicionarInundacao->setMinimumSize(QSize(45, 23)); botaoAdicionarInundacao->setMaximumSize(QSize(45, 23)); botaoExcluirInundacao = new QPushButton(tab); botaoExcluirInundacao->setObjectName(QString::fromUtf8("botaoExcluirInundacao")); botaoExcluirInundacao->setEnabled(false); botaoExcluirInundacao->setGeometry(QRect(47, 272, 45, 23)); botaoExcluirInundacao->setMinimumSize(QSize(45, 23)); botaoExcluirInundacao->setMaximumSize(QSize(45, 23)); botaoVisualizarInundacao = new QPushButton(tab); botaoVisualizarInundacao->setObjectName(QString::fromUtf8("botaoVisualizarInundacao")); botaoVisualizarInundacao->setEnabled(false); botaoVisualizarInundacao->setGeometry(QRect(92, 272, 41, 23)); sizePolicy.setHeightForWidth(botaoVisualizarInundacao->sizePolicy().hasHeightForWidth()); botaoVisualizarInundacao->setSizePolicy(sizePolicy); botaoVisualizarInundacao->setMinimumSize(QSize(41, 23)); botaoVisualizarInundacao->setMaximumSize(QSize(41, 23)); tabWidget->addTab(tab, QString()); tab_2 = new QWidget(); tab_2->setObjectName(QString::fromUtf8("tab_2")); tab_2->setEnabled(true); botaoAlternaBC = new QPushButton(tab_2); botaoAlternaBC->setObjectName(QString::fromUtf8("botaoAlternaBC")); botaoAlternaBC->setEnabled(false); botaoAlternaBC->setGeometry(QRect(90, 272, 38, 23)); sizePolicy.setHeightForWidth(botaoAlternaBC->sizePolicy().hasHeightForWidth()); botaoAlternaBC->setSizePolicy(sizePolicy); botaoAlternaBC->setMinimumSize(QSize(38, 23)); botaoAlternaBC->setMaximumSize(QSize(38, 23)); QFont font; font.setFamily(QString::fromUtf8("ESRI Oil, Gas, & Water")); botaoAlternaBC->setFont(font); botaoAlternaBC->setAcceptDrops(false); botaoAlternaBC->setAutoFillBackground(false); botaoAlternaBC->setStyleSheet(QString::fromUtf8("")); botaoAlternaBC->setIconSize(QSize(19, 19)); botaoAlternaBC->setCheckable(false); botaoAlternaBC->setAutoExclusive(false); botaoAlternaBC->setAutoDefault(false); botaoAlternaBC->setDefault(false); botaoAlternaBC->setFlat(false); camadaTableWidget = new QTableWidget(tab_2); if (camadaTableWidget->columnCount() < 3) camadaTableWidget->setColumnCount(3); QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem(); camadaTableWidget->setHorizontalHeaderItem(0, __qtablewidgetitem); QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem(); camadaTableWidget->setHorizontalHeaderItem(1, __qtablewidgetitem1); QTableWidgetItem *__qtablewidgetitem2 = new QTableWidgetItem(); camadaTableWidget->setHorizontalHeaderItem(2, __qtablewidgetitem2); camadaTableWidget->setObjectName(QString::fromUtf8("camadaTableWidget")); camadaTableWidget->setEnabled(true); camadaTableWidget->setGeometry(QRect(3, 4, 128, 265)); sizePolicy.setHeightForWidth(camadaTableWidget->sizePolicy().hasHeightForWidth()); camadaTableWidget->setSizePolicy(sizePolicy); camadaTableWidget->setMinimumSize(QSize(128, 265)); camadaTableWidget->setMaximumSize(QSize(128, 265)); camadaTableWidget->setFocusPolicy(Qt::ClickFocus); camadaTableWidget->setFrameShape(QFrame::WinPanel); camadaTableWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); camadaTableWidget->setAutoScroll(false); camadaTableWidget->setAutoScrollMargin(1); camadaTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); camadaTableWidget->setTabKeyNavigation(true); camadaTableWidget->setSelectionMode(QAbstractItemView::SingleSelection); camadaTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); camadaTableWidget->setShowGrid(false); camadaTableWidget->setGridStyle(Qt::DotLine); camadaTableWidget->setRowCount(0); camadaTableWidget->setColumnCount(3); camadaTableWidget->horizontalHeader()->setDefaultSectionSize(49); camadaTableWidget->horizontalHeader()->setMinimumSectionSize(49); camadaTableWidget->verticalHeader()->setVisible(false); camadaTableWidget->verticalHeader()->setDefaultSectionSize(43); camadaTableWidget->verticalHeader()->setMinimumSectionSize(2); insereCamada = new QPushButton(tab_2); insereCamada->setObjectName(QString::fromUtf8("insereCamada")); insereCamada->setEnabled(false); insereCamada->setGeometry(QRect(2, 272, 25, 23)); sizePolicy.setHeightForWidth(insereCamada->sizePolicy().hasHeightForWidth()); insereCamada->setSizePolicy(sizePolicy); insereCamada->setMinimumSize(QSize(25, 23)); insereCamada->setMaximumSize(QSize(25, 23)); deletaCamada = new QPushButton(tab_2); deletaCamada->setObjectName(QString::fromUtf8("deletaCamada")); deletaCamada->setEnabled(false); deletaCamada->setGeometry(QRect(27, 272, 25, 23)); sizePolicy.setHeightForWidth(deletaCamada->sizePolicy().hasHeightForWidth()); deletaCamada->setSizePolicy(sizePolicy); deletaCamada->setMinimumSize(QSize(25, 23)); deletaCamada->setMaximumSize(QSize(25, 23)); selecaoPontosCamada = new QPushButton(tab_2); selecaoPontosCamada->setObjectName(QString::fromUtf8("selecaoPontosCamada")); selecaoPontosCamada->setEnabled(false); selecaoPontosCamada->setGeometry(QRect(52, 272, 38, 23)); sizePolicy.setHeightForWidth(selecaoPontosCamada->sizePolicy().hasHeightForWidth()); selecaoPontosCamada->setSizePolicy(sizePolicy); selecaoPontosCamada->setMinimumSize(QSize(38, 23)); selecaoPontosCamada->setMaximumSize(QSize(38, 23)); selecaoPontosCamada->setFont(font); selecaoPontosCamada->setAcceptDrops(false); selecaoPontosCamada->setAutoFillBackground(false); selecaoPontosCamada->setStyleSheet(QString::fromUtf8("")); QIcon icon4; icon4.addFile(QString::fromUtf8("../imagens/selecaoMais.png"), QSize(), QIcon::Normal, QIcon::Off); selecaoPontosCamada->setIcon(icon4); selecaoPontosCamada->setIconSize(QSize(19, 19)); selecaoPontosCamada->setCheckable(false); selecaoPontosCamada->setAutoExclusive(false); selecaoPontosCamada->setAutoDefault(false); selecaoPontosCamada->setDefault(false); selecaoPontosCamada->setFlat(false); tabWidget->addTab(tab_2, QString()); formLayout->setWidget(0, QFormLayout::LabelRole, groupBox); groupBox_2 = new QGroupBox(centralWidget); groupBox_2->setObjectName(QString::fromUtf8("groupBox_2")); groupBox_2->setEnabled(true); sizePolicy.setHeightForWidth(groupBox_2->sizePolicy().hasHeightForWidth()); groupBox_2->setSizePolicy(sizePolicy); groupBox_2->setMinimumSize(QSize(161, 177)); groupBox_2->setMaximumSize(QSize(161, 190)); groupBox_2->setBaseSize(QSize(0, 0)); campoEntradaCapacidadeDesejada = new QLineEdit(groupBox_2); campoEntradaCapacidadeDesejada->setObjectName(QString::fromUtf8("campoEntradaCapacidadeDesejada")); campoEntradaCapacidadeDesejada->setGeometry(QRect(10, 40, 140, 22)); label = new QLabel(groupBox_2); label->setObjectName(QString::fromUtf8("label")); label->setGeometry(QRect(10, 20, 151, 16)); label_3 = new QLabel(groupBox_2); label_3->setObjectName(QString::fromUtf8("label_3")); label_3->setEnabled(false); label_3->setGeometry(QRect(10, 70, 147, 16)); campoEntradaLargMaxBarragem = new QLineEdit(groupBox_2); campoEntradaLargMaxBarragem->setObjectName(QString::fromUtf8("campoEntradaLargMaxBarragem")); campoEntradaLargMaxBarragem->setEnabled(false); campoEntradaLargMaxBarragem->setGeometry(QRect(10, 90, 140, 22)); botaoAtualizarFluxoMinimo = new QPushButton(groupBox_2); botaoAtualizarFluxoMinimo->setObjectName(QString::fromUtf8("botaoAtualizarFluxoMinimo")); botaoAtualizarFluxoMinimo->setEnabled(false); botaoAtualizarFluxoMinimo->setGeometry(QRect(129, 140, 24, 24)); QFont font1; font1.setFamily(QString::fromUtf8("Wingdings 3")); font1.setPointSize(9); font1.setBold(true); font1.setItalic(false); font1.setWeight(75); font1.setStrikeOut(false); font1.setKerning(false); font1.setStyleStrategy(QFont::PreferAntialias); botaoAtualizarFluxoMinimo->setFont(font1); label_2 = new QLabel(groupBox_2); label_2->setObjectName(QString::fromUtf8("label_2")); label_2->setGeometry(QRect(10, 120, 76, 16)); campoEntradaFluxoMinimo = new QLineEdit(groupBox_2); campoEntradaFluxoMinimo->setObjectName(QString::fromUtf8("campoEntradaFluxoMinimo")); campoEntradaFluxoMinimo->setGeometry(QRect(10, 140, 111, 22)); formLayout->setWidget(1, QFormLayout::LabelRole, groupBox_2); groupBox_3 = new QGroupBox(centralWidget); groupBox_3->setObjectName(QString::fromUtf8("groupBox_3")); sizePolicy.setHeightForWidth(groupBox_3->sizePolicy().hasHeightForWidth()); groupBox_3->setSizePolicy(sizePolicy); groupBox_3->setMinimumSize(QSize(163, 100)); groupBox_3->setMaximumSize(QSize(163, 100)); radioButtonV = new QRadioButton(groupBox_3); radioButtonV->setObjectName(QString::fromUtf8("radioButtonV")); radioButtonV->setGeometry(QRect(10, 16, 55, 17)); QFont font2; font2.setFamily(QString::fromUtf8("MS Shell Dlg 2")); radioButtonV->setFont(font2); campoEntradaValorAlgoritmo = new QLineEdit(groupBox_3); campoEntradaValorAlgoritmo->setObjectName(QString::fromUtf8("campoEntradaValorAlgoritmo")); campoEntradaValorAlgoritmo->setGeometry(QRect(44, 68, 41, 20)); sizePolicy.setHeightForWidth(campoEntradaValorAlgoritmo->sizePolicy().hasHeightForWidth()); campoEntradaValorAlgoritmo->setSizePolicy(sizePolicy); label_7 = new QLabel(groupBox_3); label_7->setObjectName(QString::fromUtf8("label_7")); label_7->setGeometry(QRect(10, 70, 46, 13)); campoEntradaEpislonAlgoritmo = new QLineEdit(groupBox_3); campoEntradaEpislonAlgoritmo->setObjectName(QString::fromUtf8("campoEntradaEpislonAlgoritmo")); campoEntradaEpislonAlgoritmo->setGeometry(QRect(110, 68, 41, 20)); label_10 = new QLabel(groupBox_3); label_10->setObjectName(QString::fromUtf8("label_10")); label_10->setGeometry(QRect(94, 64, 51, 31)); label_10->setPixmap(QPixmap(QString::fromUtf8("../imagens/eLetra.png"))); label_10->setScaledContents(false); radioButtonM = new QRadioButton(groupBox_3); radioButtonM->setObjectName(QString::fromUtf8("radioButtonM")); radioButtonM->setGeometry(QRect(10, 38, 55, 17)); radioButtonManual = new QRadioButton(groupBox_3); radioButtonManual->setObjectName(QString::fromUtf8("radioButtonManual")); radioButtonManual->setGeometry(QRect(100, 16, 59, 17)); widgetManual = new QGroupBox(groupBox_3); widgetManual->setObjectName(QString::fromUtf8("widgetManual")); widgetManual->setEnabled(true); widgetManual->setGeometry(QRect(7, 36, 149, 61)); widgetManual->setAutoFillBackground(true); widgetManual->setFlat(true); radioButtonManual0 = new QRadioButton(widgetManual); radioButtonManual0->setObjectName(QString::fromUtf8("radioButtonManual0")); radioButtonManual0->setGeometry(QRect(112, 44, 31, 17)); radioButtonManual0->setLayoutDirection(Qt::RightToLeft); radioButtonManual45 = new QRadioButton(widgetManual); radioButtonManual45->setObjectName(QString::fromUtf8("radioButtonManual45")); radioButtonManual45->setGeometry(QRect(112, 0, 31, 17)); radioButtonManual45->setLayoutDirection(Qt::RightToLeft); radioButtonManual90 = new QRadioButton(widgetManual); radioButtonManual90->setObjectName(QString::fromUtf8("radioButtonManual90")); radioButtonManual90->setGeometry(QRect(6, 2, 31, 17)); radioButtonManual90->setLayoutDirection(Qt::LeftToRight); radioButtonManual135 = new QRadioButton(widgetManual); radioButtonManual135->setObjectName(QString::fromUtf8("radioButtonManual135")); radioButtonManual135->setGeometry(QRect(6, 44, 37, 17)); radioButtonManual135->setLayoutDirection(Qt::LeftToRight); barragem90 = new QLabel(widgetManual); barragem90->setObjectName(QString::fromUtf8("barragem90")); barragem90->setGeometry(QRect(48, 4, 77, 61)); barragem90->setPixmap(QPixmap(QString::fromUtf8("../imagens/barragem90.png"))); barragem0 = new QLabel(widgetManual); barragem0->setObjectName(QString::fromUtf8("barragem0")); barragem0->setGeometry(QRect(50, 10, 77, 47)); barragem0->setPixmap(QPixmap(QString::fromUtf8("../imagens/barragem0.png"))); barragem45 = new QLabel(widgetManual); barragem45->setObjectName(QString::fromUtf8("barragem45")); barragem45->setGeometry(QRect(48, 6, 77, 59)); barragem45->setPixmap(QPixmap(QString::fromUtf8("../imagens/barragem45.png"))); barragem135 = new QLabel(widgetManual); barragem135->setObjectName(QString::fromUtf8("barragem135")); barragem135->setGeometry(QRect(48, 12, 77, 47)); barragem135->setPixmap(QPixmap(QString::fromUtf8("../imagens/barragem135.png"))); barragem45->raise(); radioButtonManual0->raise(); radioButtonManual45->raise(); radioButtonManual90->raise(); radioButtonManual135->raise(); barragem90->raise(); barragem0->raise(); barragem135->raise(); botaoFechaManual = new QPushButton(groupBox_3); botaoFechaManual->setObjectName(QString::fromUtf8("botaoFechaManual")); botaoFechaManual->setGeometry(QRect(14, 16, 17, 16)); botaoFechaManual->setAutoFillBackground(false); QIcon icon5; icon5.addFile(QString::fromUtf8("../imagens/fechar.png"), QSize(), QIcon::Normal, QIcon::Off); botaoFechaManual->setIcon(icon5); radioButtonDP = new QRadioButton(groupBox_3); radioButtonDP->setObjectName(QString::fromUtf8("radioButtonDP")); radioButtonDP->setGeometry(QRect(100, 36, 55, 17)); radioButtonDP->setAutoExclusive(true); radioButtonDP->raise(); radioButtonV->raise(); campoEntradaValorAlgoritmo->raise(); label_7->raise(); campoEntradaEpislonAlgoritmo->raise(); label_10->raise(); radioButtonM->raise(); radioButtonManual->raise(); botaoFechaManual->raise(); widgetManual->raise(); formLayout->setWidget(2, QFormLayout::SpanningRole, groupBox_3); gridLayout->addLayout(formLayout, 0, 0, 1, 1); groupBox_7 = new QGroupBox(centralWidget); groupBox_7->setObjectName(QString::fromUtf8("groupBox_7")); groupBox_7->setMinimumSize(QSize(579, 529)); groupBox_7->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); groupBox_7->setFlat(false); gridLayout_2 = new QGridLayout(groupBox_7); gridLayout_2->setSpacing(6); gridLayout_2->setContentsMargins(11, 11, 11, 11); gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2")); scrollArea = new QScrollArea(groupBox_7); scrollArea->setObjectName(QString::fromUtf8("scrollArea")); QSizePolicy sizePolicy1(QSizePolicy::Expanding, QSizePolicy::Expanding); sizePolicy1.setHorizontalStretch(0); sizePolicy1.setVerticalStretch(0); sizePolicy1.setHeightForWidth(scrollArea->sizePolicy().hasHeightForWidth()); scrollArea->setSizePolicy(sizePolicy1); scrollArea->setMinimumSize(QSize(0, 0)); scrollArea->setBaseSize(QSize(700, 700)); scrollArea->setMouseTracking(true); scrollArea->setMidLineWidth(0); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); scrollArea->setWidgetResizable(false); widget = new PainelVisualizacaoOpenGL(); widget->setObjectName(QString::fromUtf8("widget")); widget->setGeometry(QRect(0, 0, 540, 527)); sizePolicy1.setHeightForWidth(widget->sizePolicy().hasHeightForWidth()); widget->setSizePolicy(sizePolicy1); widget->setMinimumSize(QSize(540, 510)); widget->setBaseSize(QSize(700, 700)); widget->setCursor(QCursor(Qt::ArrowCursor)); widget->setMouseTracking(true); barraZoom = new QSlider(widget); barraZoom->setObjectName(QString::fromUtf8("barraZoom")); barraZoom->setEnabled(false); barraZoom->setGeometry(QRect(11, 38, 10, 83)); sizePolicy.setHeightForWidth(barraZoom->sizePolicy().hasHeightForWidth()); barraZoom->setSizePolicy(sizePolicy); barraZoom->setAcceptDrops(true); barraZoom->setAutoFillBackground(false); barraZoom->setStyleSheet(QString::fromUtf8("gridline-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0, 0, 0, 255), stop:0.299435 rgba(0, 230, 0, 255), stop:0.429379 rgba(12, 245, 30, 255), stop:0.66 rgba(0, 200, 0, 255), stop:0.779661 rgba(0, 234, 0, 255), stop:1 rgba(0, 255, 0, 223));\n" "background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(0, 0, 0, 255), stop:0.299435 rgba(0, 230, 0, 255), stop:0.429379 rgba(12, 245, 30, 255), stop:0.66 rgba(0, 200, 0, 255), stop:0.779661 rgba(0, 234, 0, 255), stop:1 rgba(0, 255, 0, 223));\n" "border-color: rgb(170, 0, 0);\n" "border-bottom-color: rgb(170, 0, 0);\n" "border-left-color: rgb(170, 0, 0);\n" "border-right-color: rgb(170, 0, 0);")); barraZoom->setMinimum(0); barraZoom->setMaximum(22); barraZoom->setOrientation(Qt::Vertical); barraZoom->setTickPosition(QSlider::NoTicks); barraZoom->setTickInterval(4); botaoZoomMais = new QPushButton(widget); botaoZoomMais->setObjectName(QString::fromUtf8("botaoZoomMais")); botaoZoomMais->setEnabled(false); botaoZoomMais->setGeometry(QRect(8, 24, 16, 14)); sizePolicy.setHeightForWidth(botaoZoomMais->sizePolicy().hasHeightForWidth()); botaoZoomMais->setSizePolicy(sizePolicy); botaoZoomMais->setStyleSheet(QString::fromUtf8("")); botaoZoomMais->setIconSize(QSize(13, 13)); botaoZoomMais->setFlat(false); botaoZoomMenos = new QPushButton(widget); botaoZoomMenos->setObjectName(QString::fromUtf8("botaoZoomMenos")); botaoZoomMenos->setEnabled(false); botaoZoomMenos->setGeometry(QRect(8, 121, 16, 14)); sizePolicy.setHeightForWidth(botaoZoomMenos->sizePolicy().hasHeightForWidth()); botaoZoomMenos->setSizePolicy(sizePolicy); botaoZoomMenos->setIconSize(QSize(13, 13)); botaoZoomMenos->setFlat(false); scrollArea->setWidget(widget); gridLayout_2->addWidget(scrollArea, 0, 0, 1, 1); gridLayout->addWidget(groupBox_7, 0, 1, 1, 1); formLayout_2 = new QFormLayout(); formLayout_2->setSpacing(6); formLayout_2->setObjectName(QString::fromUtf8("formLayout_2")); formLayout_2->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); groupBox_5 = new QGroupBox(centralWidget); groupBox_5->setObjectName(QString::fromUtf8("groupBox_5")); sizePolicy.setHeightForWidth(groupBox_5->sizePolicy().hasHeightForWidth()); groupBox_5->setSizePolicy(sizePolicy); groupBox_5->setMinimumSize(QSize(241, 285)); groupBox_5->setMaximumSize(QSize(241, 285)); campoSaidaCoordenadasBaseY = new QLineEdit(groupBox_5); campoSaidaCoordenadasBaseY->setObjectName(QString::fromUtf8("campoSaidaCoordenadasBaseY")); campoSaidaCoordenadasBaseY->setEnabled(false); campoSaidaCoordenadasBaseY->setGeometry(QRect(120, 200, 81, 22)); campoSaidaCoordenadasBaseX = new QLineEdit(groupBox_5); campoSaidaCoordenadasBaseX->setObjectName(QString::fromUtf8("campoSaidaCoordenadasBaseX")); campoSaidaCoordenadasBaseX->setEnabled(false); campoSaidaCoordenadasBaseX->setGeometry(QRect(10, 200, 81, 22)); campoSaidaCoordenadasY = new QLineEdit(groupBox_5); campoSaidaCoordenadasY->setObjectName(QString::fromUtf8("campoSaidaCoordenadasY")); campoSaidaCoordenadasY->setEnabled(false); campoSaidaCoordenadasY->setGeometry(QRect(120, 250, 81, 22)); campoSaidaCoordenadasX = new QLineEdit(groupBox_5); campoSaidaCoordenadasX->setObjectName(QString::fromUtf8("campoSaidaCoordenadasX")); campoSaidaCoordenadasX->setEnabled(false); campoSaidaCoordenadasX->setGeometry(QRect(10, 250, 81, 22)); label_19 = new QLabel(groupBox_5); label_19->setObjectName(QString::fromUtf8("label_19")); label_19->setGeometry(QRect(10, 230, 83, 16)); label_18 = new QLabel(groupBox_5); label_18->setObjectName(QString::fromUtf8("label_18")); label_18->setGeometry(QRect(10, 180, 211, 16)); layoutWidget = new QWidget(groupBox_5); layoutWidget->setObjectName(QString::fromUtf8("layoutWidget")); layoutWidget->setGeometry(QRect(10, 150, 141, 24)); horizontalLayout = new QHBoxLayout(layoutWidget); horizontalLayout->setSpacing(5); horizontalLayout->setContentsMargins(11, 11, 11, 11); horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); horizontalLayout->setContentsMargins(0, 0, 0, 0); label_9 = new QLabel(layoutWidget); label_9->setObjectName(QString::fromUtf8("label_9")); horizontalLayout->addWidget(label_9); caixaPreSalvo = new QCheckBox(layoutWidget); caixaPreSalvo->setObjectName(QString::fromUtf8("caixaPreSalvo")); caixaPreSalvo->setEnabled(false); caixaPreSalvo->setCheckable(false); caixaPreSalvo->setChecked(false); horizontalLayout->addWidget(caixaPreSalvo); layoutWidget1 = new QWidget(groupBox_5); layoutWidget1->setObjectName(QString::fromUtf8("layoutWidget1")); layoutWidget1->setGeometry(QRect(10, 120, 151, 24)); horizontalLayout_2 = new QHBoxLayout(layoutWidget1); horizontalLayout_2->setSpacing(6); horizontalLayout_2->setContentsMargins(11, 11, 11, 11); horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2")); horizontalLayout_2->setContentsMargins(0, 0, 0, 0); label_17 = new QLabel(layoutWidget1); label_17->setObjectName(QString::fromUtf8("label_17")); horizontalLayout_2->addWidget(label_17); campoSaidaFluxoMinimo = new QLineEdit(layoutWidget1); campoSaidaFluxoMinimo->setObjectName(QString::fromUtf8("campoSaidaFluxoMinimo")); campoSaidaFluxoMinimo->setEnabled(false); horizontalLayout_2->addWidget(campoSaidaFluxoMinimo); layoutWidget2 = new QWidget(groupBox_5); layoutWidget2->setObjectName(QString::fromUtf8("layoutWidget2")); layoutWidget2->setGeometry(QRect(10, 20, 221, 41)); verticalLayout = new QVBoxLayout(layoutWidget2); verticalLayout->setSpacing(0); verticalLayout->setContentsMargins(11, 11, 11, 11); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); label_14 = new QLabel(layoutWidget2); label_14->setObjectName(QString::fromUtf8("label_14")); verticalLayout->addWidget(label_14); campoSaidaNomeArquivo = new QLineEdit(layoutWidget2); campoSaidaNomeArquivo->setObjectName(QString::fromUtf8("campoSaidaNomeArquivo")); campoSaidaNomeArquivo->setEnabled(false); verticalLayout->addWidget(campoSaidaNomeArquivo); layoutWidget3 = new QWidget(groupBox_5); layoutWidget3->setObjectName(QString::fromUtf8("layoutWidget3")); layoutWidget3->setGeometry(QRect(10, 70, 221, 41)); verticalLayout_6 = new QVBoxLayout(layoutWidget3); verticalLayout_6->setSpacing(0); verticalLayout_6->setContentsMargins(11, 11, 11, 11); verticalLayout_6->setObjectName(QString::fromUtf8("verticalLayout_6")); verticalLayout_6->setContentsMargins(0, 0, 0, 0); label_15 = new QLabel(layoutWidget3); label_15->setObjectName(QString::fromUtf8("label_15")); verticalLayout_6->addWidget(label_15); campoSaidaCaminhoArquivo = new QLineEdit(layoutWidget3); campoSaidaCaminhoArquivo->setObjectName(QString::fromUtf8("campoSaidaCaminhoArquivo")); campoSaidaCaminhoArquivo->setEnabled(false); verticalLayout_6->addWidget(campoSaidaCaminhoArquivo); formLayout_2->setWidget(1, QFormLayout::LabelRole, groupBox_5); checkBoxVisualiza2D = new QCheckBox(centralWidget); checkBoxVisualiza2D->setObjectName(QString::fromUtf8("checkBoxVisualiza2D")); checkBoxVisualiza2D->setEnabled(false); formLayout_2->setWidget(3, QFormLayout::LabelRole, checkBoxVisualiza2D); checkBoxVisualiza3D = new QCheckBox(centralWidget); checkBoxVisualiza3D->setObjectName(QString::fromUtf8("checkBoxVisualiza3D")); checkBoxVisualiza3D->setEnabled(false); formLayout_2->setWidget(4, QFormLayout::LabelRole, checkBoxVisualiza3D); groupBox_4 = new QGroupBox(centralWidget); groupBox_4->setObjectName(QString::fromUtf8("groupBox_4")); sizePolicy.setHeightForWidth(groupBox_4->sizePolicy().hasHeightForWidth()); groupBox_4->setSizePolicy(sizePolicy); groupBox_4->setMinimumSize(QSize(241, 240)); groupBox_4->setMaximumSize(QSize(241, 240)); groupBox_6 = new QGroupBox(groupBox_4); groupBox_6->setObjectName(QString::fromUtf8("groupBox_6")); groupBox_6->setGeometry(QRect(9, 18, 225, 97)); groupBox_6->setMinimumSize(QSize(225, 97)); groupBox_6->setMaximumSize(QSize(225, 97)); layoutWidget4 = new QWidget(groupBox_6); layoutWidget4->setObjectName(QString::fromUtf8("layoutWidget4")); layoutWidget4->setGeometry(QRect(119, 16, 101, 35)); verticalLayout_4 = new QVBoxLayout(layoutWidget4); verticalLayout_4->setSpacing(0); verticalLayout_4->setContentsMargins(11, 11, 11, 11); verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4")); verticalLayout_4->setContentsMargins(0, 0, 0, 0); label_5 = new QLabel(layoutWidget4); label_5->setObjectName(QString::fromUtf8("label_5")); verticalLayout_4->addWidget(label_5); campoSaidaAlturaBarragem = new QLineEdit(layoutWidget4); campoSaidaAlturaBarragem->setObjectName(QString::fromUtf8("campoSaidaAlturaBarragem")); campoSaidaAlturaBarragem->setEnabled(false); verticalLayout_4->addWidget(campoSaidaAlturaBarragem); layoutWidget5 = new QWidget(groupBox_6); layoutWidget5->setObjectName(QString::fromUtf8("layoutWidget5")); layoutWidget5->setGeometry(QRect(8, 54, 101, 35)); verticalLayout_7 = new QVBoxLayout(layoutWidget5); verticalLayout_7->setSpacing(0); verticalLayout_7->setContentsMargins(11, 11, 11, 11); verticalLayout_7->setObjectName(QString::fromUtf8("verticalLayout_7")); verticalLayout_7->setContentsMargins(0, 0, 0, 0); label_11 = new QLabel(layoutWidget5); label_11->setObjectName(QString::fromUtf8("label_11")); verticalLayout_7->addWidget(label_11); campoSaidaAreaBarragem = new QLineEdit(layoutWidget5); campoSaidaAreaBarragem->setObjectName(QString::fromUtf8("campoSaidaAreaBarragem")); campoSaidaAreaBarragem->setEnabled(false); verticalLayout_7->addWidget(campoSaidaAreaBarragem); layoutWidget6 = new QWidget(groupBox_6); layoutWidget6->setObjectName(QString::fromUtf8("layoutWidget6")); layoutWidget6->setGeometry(QRect(7, 16, 101, 35)); verticalLayout_5 = new QVBoxLayout(layoutWidget6); verticalLayout_5->setSpacing(0); verticalLayout_5->setContentsMargins(11, 11, 11, 11); verticalLayout_5->setObjectName(QString::fromUtf8("verticalLayout_5")); verticalLayout_5->setContentsMargins(0, 0, 0, 0); label_4 = new QLabel(layoutWidget6); label_4->setObjectName(QString::fromUtf8("label_4")); verticalLayout_5->addWidget(label_4); campoSaidaExtensaoBarragem = new QLineEdit(layoutWidget6); campoSaidaExtensaoBarragem->setObjectName(QString::fromUtf8("campoSaidaExtensaoBarragem")); campoSaidaExtensaoBarragem->setEnabled(false); campoSaidaExtensaoBarragem->setAcceptDrops(true); verticalLayout_5->addWidget(campoSaidaExtensaoBarragem); groupBox_8 = new QGroupBox(groupBox_4); groupBox_8->setObjectName(QString::fromUtf8("groupBox_8")); groupBox_8->setGeometry(QRect(9, 120, 225, 61)); layoutWidget7 = new QWidget(groupBox_8); layoutWidget7->setObjectName(QString::fromUtf8("layoutWidget7")); layoutWidget7->setGeometry(QRect(8, 18, 101, 35)); verticalLayout_3 = new QVBoxLayout(layoutWidget7); verticalLayout_3->setSpacing(0); verticalLayout_3->setContentsMargins(11, 11, 11, 11); verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3")); verticalLayout_3->setContentsMargins(0, 0, 0, 0); label_6 = new QLabel(layoutWidget7); label_6->setObjectName(QString::fromUtf8("label_6")); verticalLayout_3->addWidget(label_6); campoSaidaCapacidadeTotal = new QLineEdit(layoutWidget7); campoSaidaCapacidadeTotal->setObjectName(QString::fromUtf8("campoSaidaCapacidadeTotal")); campoSaidaCapacidadeTotal->setEnabled(false); verticalLayout_3->addWidget(campoSaidaCapacidadeTotal); layoutWidget8 = new QWidget(groupBox_8); layoutWidget8->setObjectName(QString::fromUtf8("layoutWidget8")); layoutWidget8->setGeometry(QRect(120, 18, 101, 35)); verticalLayout_2 = new QVBoxLayout(layoutWidget8); verticalLayout_2->setSpacing(0); verticalLayout_2->setContentsMargins(11, 11, 11, 11); verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2")); verticalLayout_2->setContentsMargins(0, 0, 0, 0); label_8 = new QLabel(layoutWidget8); label_8->setObjectName(QString::fromUtf8("label_8")); verticalLayout_2->addWidget(label_8); campoSaidaAreaLaminaDaAgua = new QLineEdit(layoutWidget8); campoSaidaAreaLaminaDaAgua->setObjectName(QString::fromUtf8("campoSaidaAreaLaminaDaAgua")); campoSaidaAreaLaminaDaAgua->setEnabled(false); verticalLayout_2->addWidget(campoSaidaAreaLaminaDaAgua); groupBox_9 = new QGroupBox(groupBox_4); groupBox_9->setObjectName(QString::fromUtf8("groupBox_9")); groupBox_9->setGeometry(QRect(9, 188, 225, 43)); campoSaidaFuncaoObjetivo = new QLineEdit(groupBox_9); campoSaidaFuncaoObjetivo->setObjectName(QString::fromUtf8("campoSaidaFuncaoObjetivo")); campoSaidaFuncaoObjetivo->setEnabled(false); campoSaidaFuncaoObjetivo->setGeometry(QRect(8, 18, 99, 20)); caixaApresentaFuncaoObjetivo = new QCheckBox(groupBox_9); caixaApresentaFuncaoObjetivo->setObjectName(QString::fromUtf8("caixaApresentaFuncaoObjetivo")); caixaApresentaFuncaoObjetivo->setEnabled(false); caixaApresentaFuncaoObjetivo->setGeometry(QRect(126, 20, 70, 17)); formLayout_2->setWidget(0, QFormLayout::LabelRole, groupBox_4); gridLayout->addLayout(formLayout_2, 0, 2, 1, 1); JanelaPrincipal->setCentralWidget(centralWidget); menuBar = new QMenuBar(JanelaPrincipal); menuBar->setObjectName(QString::fromUtf8("menuBar")); menuBar->setGeometry(QRect(0, 0, 1027, 21)); menuTeste = new QMenu(menuBar); menuTeste->setObjectName(QString::fromUtf8("menuTeste")); menuAjuda = new QMenu(menuBar); menuAjuda->setObjectName(QString::fromUtf8("menuAjuda")); menuEdita = new QMenu(menuBar); menuEdita->setObjectName(QString::fromUtf8("menuEdita")); menuEdita->setEnabled(true); menuOp_es = new QMenu(menuEdita); menuOp_es->setObjectName(QString::fromUtf8("menuOp_es")); JanelaPrincipal->setMenuBar(menuBar); #ifndef QT_NO_SHORTCUT label->setBuddy(campoEntradaCapacidadeDesejada); label_3->setBuddy(campoEntradaLargMaxBarragem); label_2->setBuddy(campoEntradaFluxoMinimo); #endif // QT_NO_SHORTCUT menuBar->addAction(menuTeste->menuAction()); menuBar->addAction(menuEdita->menuAction()); menuBar->addAction(menuAjuda->menuAction()); menuTeste->addAction(actionAbrir_mapa); menuTeste->addAction(actionFechar_mapa); menuTeste->addAction(actionExportar_mapa); menuTeste->addAction(actionSalvar); menuTeste->addAction(actionSair); menuAjuda->addAction(actionSobre); menuEdita->addAction(menuOp_es->menuAction()); menuOp_es->addAction(actionCores); menuOp_es->addAction(actionFunc_Objetivo); retranslateUi(JanelaPrincipal); QObject::connect(actionSair, SIGNAL(triggered()), JanelaPrincipal, SLOT(close())); tabWidget->setCurrentIndex(0); QMetaObject::connectSlotsByName(JanelaPrincipal); } // setupUi void retranslateUi(QMainWindow *JanelaPrincipal) { JanelaPrincipal->setWindowTitle(QApplication::translate("JanelaPrincipal", "Re-Build(Beta 1.0)", 0, QApplication::UnicodeUTF8)); actionAbrir_mapa->setText(QApplication::translate("JanelaPrincipal", "Abrir mapa...", 0, QApplication::UnicodeUTF8)); actionExportar_mapa->setText(QApplication::translate("JanelaPrincipal", "Exportar mapa...", 0, QApplication::UnicodeUTF8)); actionSair->setText(QApplication::translate("JanelaPrincipal", "Sair", 0, QApplication::UnicodeUTF8)); actionSalvar->setText(QApplication::translate("JanelaPrincipal", "Salvar", 0, QApplication::UnicodeUTF8)); actionSobre->setText(QApplication::translate("JanelaPrincipal", "Sobre", 0, QApplication::UnicodeUTF8)); actionFechar_mapa->setText(QApplication::translate("JanelaPrincipal", "Fechar mapa...", 0, QApplication::UnicodeUTF8)); actionCores->setText(QApplication::translate("JanelaPrincipal", "Cores", 0, QApplication::UnicodeUTF8)); actionFunc_Objetivo->setText(QApplication::translate("JanelaPrincipal", "Func.Objetivo", 0, QApplication::UnicodeUTF8)); groupBox->setTitle(QString()); #ifndef QT_NO_TOOLTIP tabWidget->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">\303\201rea de trabalho</span></p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_TOOLTIP tab->setToolTip(QApplication::translate("JanelaPrincipal", "\303\201rea destinada a armazenar os distintos reservat\303\263rios", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_TOOLTIP botaoAdicionarInundacao->setToolTip(QApplication::translate("JanelaPrincipal", "Adiciona o reservat\303\263rio corrente a \n" "\303\201rea de projeto", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP botaoAdicionarInundacao->setText(QApplication::translate("JanelaPrincipal", "+", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP botaoExcluirInundacao->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Exclui o reservat\303\263rio selecionado</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">da \303\201rea de Projeto</span></p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP botaoExcluirInundacao->setText(QApplication::translate("JanelaPrincipal", "-", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP botaoVisualizarInundacao->setToolTip(QApplication::translate("JanelaPrincipal", "Visualiza reservat\303\263rio selecionado\n" "da \303\201rea de Projeto", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP botaoVisualizarInundacao->setText(QApplication::translate("JanelaPrincipal", "->", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("JanelaPrincipal", "\303\201rea de Projeto", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP tab_2->setToolTip(QApplication::translate("JanelaPrincipal", "\303\201rea destinada a armazenar camadas de pontos \n" "cr\303\255ticos em um alagamento\n" "", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_TOOLTIP botaoAlternaBC->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'ESRI Oil, Gas, &amp; Water'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Adiciona/subtrair c\303\251lulas a camada corrente</p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP botaoAlternaBC->setText(QApplication::translate("JanelaPrincipal", "B", 0, QApplication::UnicodeUTF8)); QTableWidgetItem *___qtablewidgetitem = camadaTableWidget->horizontalHeaderItem(0); ___qtablewidgetitem->setText(QApplication::translate("JanelaPrincipal", "Nome", 0, QApplication::UnicodeUTF8)); QTableWidgetItem *___qtablewidgetitem1 = camadaTableWidget->horizontalHeaderItem(1); ___qtablewidgetitem1->setText(QApplication::translate("JanelaPrincipal", "Peso", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP camadaTableWidget->setToolTip(QString()); #endif // QT_NO_TOOLTIP #ifndef QT_NO_TOOLTIP insereCamada->setToolTip(QApplication::translate("JanelaPrincipal", "Adiciona uma camada", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP insereCamada->setText(QApplication::translate("JanelaPrincipal", "+", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP deletaCamada->setToolTip(QApplication::translate("JanelaPrincipal", "Exclui camada selecionada", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP deletaCamada->setText(QApplication::translate("JanelaPrincipal", "-", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP selecaoPontosCamada->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'ESRI Oil, Gas, &amp; Water'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Adiciona/subtrair c\303\251lulas a camada corrente</p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP selecaoPontosCamada->setText(QString()); tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("JanelaPrincipal", "Camadas", 0, QApplication::UnicodeUTF8)); groupBox_2->setTitle(QApplication::translate("JanelaPrincipal", "Par\303\242metros", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP campoEntradaCapacidadeDesejada->setToolTip(QApplication::translate("JanelaPrincipal", "Define a capacidade desejada para criar o reservat\303\263rio.", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP label->setText(QApplication::translate("JanelaPrincipal", "Capacidade desejada(m\302\263)", 0, QApplication::UnicodeUTF8)); label_3->setText(QApplication::translate("JanelaPrincipal", "<NAME>(m\302\262)", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP campoEntradaLargMaxBarragem->setToolTip(QApplication::translate("JanelaPrincipal", "Define o valor m\303\241ximo para a extens\303\243o da barragem.\n" "N\303\243o presente nesta vers\303\243o.", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_TOOLTIP botaoAtualizarFluxoMinimo->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'Wingdings 3'; font-size:9pt; font-weight:600; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'MS Shell Dlg 2'; font-size:8pt; font-weight:400;\">Atualiza fluxo m\303\255nimo</span></p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP #ifndef QT_NO_STATUSTIP botaoAtualizarFluxoMinimo->setStatusTip(QString()); #endif // QT_NO_STATUSTIP botaoAtualizarFluxoMinimo->setText(QApplication::translate("JanelaPrincipal", "Q", 0, QApplication::UnicodeUTF8)); label_2->setText(QApplication::translate("JanelaPrincipal", "Fluxo m\303\255nimo", 0, QApplication::UnicodeUTF8)); groupBox_3->setTitle(QApplication::translate("JanelaPrincipal", "Orienta\303\247ao Barragem", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP radioButtonV->setToolTip(QApplication::translate("JanelaPrincipal", "Orienta\303\247ao da barragem por soma dos vetores de vizinhos", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP radioButtonV->setText(QApplication::translate("JanelaPrincipal", "DIRMS", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP campoEntradaValorAlgoritmo->setToolTip(QApplication::translate("JanelaPrincipal", "P\303\242ramentro do algoritmo\n" "referente a quantidade de pontos\n" "sequenciais da rede de drenagem", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP label_7->setText(QApplication::translate("JanelaPrincipal", "N.Vizi.", 0, QApplication::UnicodeUTF8)); label_10->setText(QString()); #ifndef QT_NO_TOOLTIP radioButtonM->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Orienta\303\247\303\243o da barragem atrav\303\251s da dire\303\247\303\243o m\303\251dia dos vetores dos vizinhos</span></p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP radioButtonM->setText(QApplication::translate("JanelaPrincipal", "DIRMP", 0, QApplication::UnicodeUTF8)); radioButtonManual->setText(QApplication::translate("JanelaPrincipal", "Manual", 0, QApplication::UnicodeUTF8)); radioButtonManual0->setText(QApplication::translate("JanelaPrincipal", "0", 0, QApplication::UnicodeUTF8)); radioButtonManual45->setText(QApplication::translate("JanelaPrincipal", "45", 0, QApplication::UnicodeUTF8)); radioButtonManual90->setText(QApplication::translate("JanelaPrincipal", "90", 0, QApplication::UnicodeUTF8)); radioButtonManual135->setText(QApplication::translate("JanelaPrincipal", "135", 0, QApplication::UnicodeUTF8)); barragem90->setText(QString()); barragem0->setText(QString()); barragem45->setText(QString()); barragem135->setText(QString()); botaoFechaManual->setText(QString()); #ifndef QT_NO_TOOLTIP radioButtonDP->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Orienta\303\247\303\243o da barragem com uso do algoritmo de Douglas-Peucker</span></p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP radioButtonDP->setText(QApplication::translate("JanelaPrincipal", "DIRDP", 0, QApplication::UnicodeUTF8)); groupBox_7->setTitle(QApplication::translate("JanelaPrincipal", "Visualiza\303\247\303\243o", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP botaoZoomMais->setToolTip(QApplication::translate("JanelaPrincipal", "Zoom +", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP botaoZoomMais->setText(QApplication::translate("JanelaPrincipal", "+", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP botaoZoomMenos->setToolTip(QApplication::translate("JanelaPrincipal", "Zoom -", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP botaoZoomMenos->setText(QApplication::translate("JanelaPrincipal", "-", 0, QApplication::UnicodeUTF8)); groupBox_5->setTitle(QApplication::translate("JanelaPrincipal", "Infos do mapa corrente", 0, QApplication::UnicodeUTF8)); campoSaidaCoordenadasBaseY->setText(QString()); campoSaidaCoordenadasBaseX->setText(QString()); campoSaidaCoordenadasY->setText(QString()); campoSaidaCoordenadasX->setText(QString()); label_19->setText(QApplication::translate("JanelaPrincipal", "Coordenadas ", 0, QApplication::UnicodeUTF8)); label_18->setText(QApplication::translate("JanelaPrincipal", "Coordenadas da base da barragem:", 0, QApplication::UnicodeUTF8)); label_9->setText(QApplication::translate("JanelaPrincipal", "Pr\303\251-salvo:", 0, QApplication::UnicodeUTF8)); caixaPreSalvo->setText(QString()); label_17->setText(QApplication::translate("JanelaPrincipal", "Fluxo min.:", 0, QApplication::UnicodeUTF8)); campoSaidaFluxoMinimo->setText(QApplication::translate("JanelaPrincipal", "-", 0, QApplication::UnicodeUTF8)); label_14->setText(QApplication::translate("JanelaPrincipal", "Arquivo:", 0, QApplication::UnicodeUTF8)); campoSaidaNomeArquivo->setText(QString()); label_15->setText(QApplication::translate("JanelaPrincipal", "Caminho:", 0, QApplication::UnicodeUTF8)); campoSaidaCaminhoArquivo->setText(QString()); #ifndef QT_NO_TOOLTIP checkBoxVisualiza2D->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Vizualiza\303\247\303\243o da barragem 2D</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">N\303\243o dispon\303\255vel nesta vers\303\243o</span></p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP checkBoxVisualiza2D->setText(QApplication::translate("JanelaPrincipal", "Visualiza2D", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_TOOLTIP checkBoxVisualiza3D->setToolTip(QApplication::translate("JanelaPrincipal", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">Vizualiza\303\247\303\243o 3D da barragem</span></p>\n" "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:8pt;\">N\303\243o dispon\303\255vel nesta vers\303\243o</span></p></body></html>", 0, QApplication::UnicodeUTF8)); #endif // QT_NO_TOOLTIP checkBoxVisualiza3D->setText(QApplication::translate("JanelaPrincipal", "Visualiza3D", 0, QApplication::UnicodeUTF8)); groupBox_4->setTitle(QApplication::translate("JanelaPrincipal", "Resultados dos par\303\242metros correntes", 0, QApplication::UnicodeUTF8)); groupBox_6->setTitle(QApplication::translate("JanelaPrincipal", "Barragem", 0, QApplication::UnicodeUTF8)); label_5->setText(QApplication::translate("JanelaPrincipal", "Altura(m)", 0, QApplication::UnicodeUTF8)); campoSaidaAlturaBarragem->setText(QString()); label_11->setText(QApplication::translate("JanelaPrincipal", "\303\201rea(m\302\262)", 0, QApplication::UnicodeUTF8)); label_4->setText(QApplication::translate("JanelaPrincipal", "Extens\303\243o(m)", 0, QApplication::UnicodeUTF8)); #ifndef QT_NO_ACCESSIBILITY campoSaidaExtensaoBarragem->setAccessibleDescription(QString()); #endif // QT_NO_ACCESSIBILITY campoSaidaExtensaoBarragem->setText(QString()); groupBox_8->setTitle(QApplication::translate("JanelaPrincipal", "Reservat\303\263rio", 0, QApplication::UnicodeUTF8)); label_6->setText(QApplication::translate("JanelaPrincipal", "Capacidade(m\302\263)", 0, QApplication::UnicodeUTF8)); campoSaidaCapacidadeTotal->setText(QString()); label_8->setText(QApplication::translate("JanelaPrincipal", "\303\201rea(m\302\262)", 0, QApplication::UnicodeUTF8)); campoSaidaAreaLaminaDaAgua->setText(QString()); groupBox_9->setTitle(QApplication::translate("JanelaPrincipal", "Fun\303\247\303\243o Objetivo", 0, QApplication::UnicodeUTF8)); caixaApresentaFuncaoObjetivo->setText(QApplication::translate("JanelaPrincipal", "Apresenta", 0, QApplication::UnicodeUTF8)); menuTeste->setTitle(QApplication::translate("JanelaPrincipal", "Arquivo", 0, QApplication::UnicodeUTF8)); menuAjuda->setTitle(QApplication::translate("JanelaPrincipal", "Ajuda", 0, QApplication::UnicodeUTF8)); menuEdita->setTitle(QApplication::translate("JanelaPrincipal", "Edita", 0, QApplication::UnicodeUTF8)); menuOp_es->setTitle(QApplication::translate("JanelaPrincipal", "Op\303\247\303\265es", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class JanelaPrincipal: public Ui_JanelaPrincipal {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_JANELAPRINCIPAL_H
39a6672a9e6dfde55381a0b23bb40e9d736e5c8a
[ "HTML", "Text", "C++" ]
44
C++
rodolfo53821/ReBuild
f96f9230ddec09c806781b3ed232be0547cf002e
749fa33f64b2424ab397a056a41b9c94d14d4a4c
refs/heads/main
<repo_name>Mattacchione/fanta-msi<file_sep>/src/app/app.component.html <div class="container"> <div class="title"> <h1>FANTA WOLRDS 2022</h1> </div> <h3> Una volta fatta la formazione inseritela qua: <a style="background-color: white;" target="_blank" href="https://docs.google.com/forms/d/e/1FAIpQLSeHXfuH1nq9C1rAuJAEDw2Xfc4_CX1J7UGrKoWoGzsRHSiqFw/viewform">WORLDS FORM</a><br> Punteggio e regole: <a style="background-color: white;" target="_blank" href="https://docs.google.com/spreadsheets/d/1pPwGFhNCSpsckB43kj0X7ndz-eQHEi82kv4VxXMXC_I">PUNTI E REGOLE</a><br> </h3> <div> <h3>Regole</h3> <ul> <li>Massimo 3 giocatori per squadra, escluso il coach</li> <li>Non si può superare il massimo di crediti per la formazione</li> </ul> </div> <div [ngClass]="calculateCredit() >= 0 ? 'valid' : 'not-valid'"> <h2>Crediti disponibili {{calculateCredit()}}</h2> </div> <div class="pool"> <div> <label id="example-radio-group-label">Scegli il Toplaner</label> <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group" [(ngModel)]="comp.top" (change)="verifyComp()"> <mat-radio-button class="example-radio-button" *ngFor="let topOption of playerPoolTop" [value]="topOption"> {{topOption.player}} - {{topOption.team}} - {{topOption.value}} </mat-radio-button> </mat-radio-group> </div> <div> <label id="example-radio-group-label">Scegli il Jungler</label> <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group" [(ngModel)]="comp.jungle" (change)="verifyComp()"> <mat-radio-button class="example-radio-button" *ngFor="let jngOption of playerPoolJng" [value]="jngOption"> {{jngOption.player}} - {{jngOption.team}} - {{jngOption.value}} </mat-radio-button> </mat-radio-group> </div> <div> <label id="example-radio-group-label">Scegli il Midlaner</label> <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group" [(ngModel)]="comp.mid" (change)="verifyComp()"> <mat-radio-button class="example-radio-button" *ngFor="let midOption of playerPoolMid" [value]="midOption"> {{midOption.player}} - {{midOption.team}} - {{midOption.value}} </mat-radio-button> </mat-radio-group> </div> <div> <label id="example-radio-group-label">Scegli l'Adc</label> <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group" [(ngModel)]="comp.adc" (change)="verifyComp()"> <mat-radio-button class="example-radio-button" *ngFor="let adcOption of playerPoolAdc" [value]="adcOption"> {{adcOption.player}} - {{adcOption.team}} - {{adcOption.value}} </mat-radio-button> </mat-radio-group> </div> <div> <label id="example-radio-group-label">Scegli il Support</label> <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group" [(ngModel)]="comp.supp" (change)="verifyComp()"> <mat-radio-button class="example-radio-button" *ngFor="let suppOption of playerPoolSupp" [value]="suppOption"> {{suppOption.player}} - {{suppOption.team}} - {{suppOption.value}} </mat-radio-button> </mat-radio-group> </div> <div> <label id="example-radio-group-label">Scegli il Coach</label> <mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group" [(ngModel)]="comp.coach" (change)="verifyComp()"> <mat-radio-button class="example-radio-button" *ngFor="let coachOption of playerPoolCoach" [value]="coachOption"> {{coachOption.player}} - {{coachOption.team}} - {{coachOption.value}} </mat-radio-button> </mat-radio-group> </div> </div> <div class="comp"> <h3>La tua comp è: {{comp.top?.player}} - {{comp.jungle?.player}} - {{comp.mid?.player}} - {{comp.adc?.player}} - {{comp.supp?.player}} - {{comp.coach?.player}} </h3> <div> <!-- <button mat-raised-button color="primary" (click)="verifyComp()">Verifica</button> --> <button mat-raised-button color="primary" [cdkCopyToClipboard]="copy()" [disabled]="!validComp">Copia formazione</button> </div> </div> <div class="validation" [ngClass]="validComp ? 'valid' : 'not-valid'"> La tua comp è {{validComp ? 'VALIDA' : 'NON VALIDA - controlla di non aver superato i crediti massimi e di non aver messo più di 2 player per squadra'}} </div> </div><file_sep>/src/app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { playerPoolTop: any playerPoolJng: any playerPoolMid: any playerPoolAdc: any playerPoolSupp: any playerPoolCoach: any comp: any validComp: boolean pool = [ { "player": "Kingen", "team": "DRX", "value": 50, "role": "top" }, { "player": "Pyosik", "team": "DRX", "value": 50, "role": "jungle" }, { "player": "Zeka", "team": "DRX", "value": 50, "role": "mid" }, { "player": "Deft", "team": "DRX", "value": 50, "role": "adc" }, { "player": "BeryL", "team": "DRX", "value": 50, "role": "supp" }, { "player": "Mowgli", "team": "DRX", "value": 50, "role": "coach" }, { "player": "Zeus", "team": "T1", "value": 50, "role": "top" }, { "player": "Oner", "team": "T1", "value": 50, "role": "jungle" }, { "player": "Faker", "team": "T1", "value": 50, "role": "mid" }, { "player": "Gumayusi", "team": "T1", "value": 50, "role": "adc" }, { "player": "Keria", "team": "T1", "value": 50, "role": "supp" }, { "player": "Bengi", "team": "T1", "value": 50, "role": "coach" } ] constructor() { this.validComp = false this.comp = { top: {}, jungle: {}, mid: {}, adc: {}, supp: {}, coach: {} } this.playerPoolTop = [] this.playerPoolJng = [] this.playerPoolMid = [] this.playerPoolAdc = [] this.playerPoolSupp = [] this.playerPoolCoach = [] this.pool.forEach(player => { switch (player?.role) { case 'top': this.playerPoolTop.push(player) break; case 'jungle': this.playerPoolJng.push(player) break; case 'mid': this.playerPoolMid.push(player) break; case 'adc': this.playerPoolAdc.push(player) break; case 'supp': this.playerPoolSupp.push(player) break; case 'coach': this.playerPoolCoach.push(player) break; } }) this.playerPoolTop.sort((a, b) => { return b.value - a.value }) this.playerPoolJng.sort((a, b) => { return b.value - a.value }) this.playerPoolMid.sort((a, b) => { return b.value - a.value }) this.playerPoolAdc.sort((a, b) => { return b.value - a.value }) this.playerPoolSupp.sort((a, b) => { return b.value - a.value }) this.playerPoolCoach.sort((a, b) => { return b.value - a.value }) } ngOnInit(): void { } completedComp() { return !!this.comp.top?.value && !!this.comp.jungle?.value && !!this.comp.mid?.value && !!this.comp.adc?.value && !!this.comp.supp?.value && !!this.comp.coach?.value } calculateCredit() { const top = this.comp.top?.value ? this.comp.top?.value : 0 const jungle = this.comp.jungle?.value ? this.comp.jungle?.value : 0 const mid = this.comp.mid?.value ? this.comp.mid?.value : 0 const adc = this.comp.adc?.value ? this.comp.adc?.value : 0 const supp = this.comp.supp?.value ? this.comp.supp?.value : 0 const coach = this.comp.coach?.value ? this.comp.coach?.value : 0 let value = 300 - top - jungle - mid - adc - supp - coach return value } verifyComp() { if (this.completedComp()) { if (this.calculateCredit() <= 300 && this.calculateCredit() >= 0) { let edg = 0, dw = 0, mad = 0, psg = 0, fpx = 0, geng = 0, fnc = 0, hundred = 0, rng = 0, t1 = 0, rge = 0, tl = 0, c9 = 0, dfm = 0, hle = 0, lng = 0, drx = 0, byg = 0, eg = 0, sgb = 0, chf = 0, iw = 0, isg = 0, lll = 0, jdg = 0, tes = 0, g2 = 0, dwg = 0, t100 = 0, gam = 0, cfo = 0 for (const [key, value] of Object.entries(this.comp)) { if (key !== 'coach') { switch (value['team']) { case 'JDG': jdg++ break; case 'TES': tes++ break; case 'G2': g2++ break; case 'DWG': dwg++ break; case '100T': t100++ break; case 'GAM': gam++ break; case 'CFO': cfo++ break; case 'DRX': drx++ break; case 'BYG': byg++ break; case 'EG': eg++ break; case 'DRX': drx++ break; case 'SGB': sgb++ break; case 'CHF': chf++ break; case 'IW': iw++ break; case 'ISG': isg++ break; case 'LLL': lll++ break; case 'EDG': edg++ break; case 'DW': dw++ break; case 'MAD': mad++ break; case 'PSG': psg++ break; case 'FPX': fpx++ break; case 'GENG': geng++ break; case 'FNC': fnc++ break; case '100T': hundred++ break; case 'RNG': rng++ break; case 'T1': t1++ break; case 'RGE': rge++ break; case 'TL': tl++ break; case 'C9': c9++ break; case 'DFM': dfm++ break; case 'HLE': hle++ break; case 'LNG': lng++ break; } } } if (edg > 3 || dw > 3 || mad > 3 || psg > 3 || fpx > 3 || geng > 3 || fnc > 3 || hundred > 3 || rng > 3 || t1 > 3 || rge > 3 || tl > 3 || c9 > 3 || dfm > 3 || hle > 3 || lng > 3 || drx > 3 || byg > 3 || eg > 3 || sgb > 3 || chf > 3 || iw > 3 || isg > 3 || lll > 3 || jdg > 3 || tes > 3 || g2 > 3 || dwg > 3 || t100 > 3 || gam > 3 || cfo > 3) { this.validComp = false } else { this.validComp = true } } else { this.validComp = false } } } copy() { return String(this.comp.top?.player) + ' ' + String(this.comp.jungle?.player) + ' ' + String(this.comp.mid?.player) + ' ' + String(this.comp.adc?.player) + ' ' + String(this.comp.supp?.player) + ' ' + String(this.comp.coach?.player) } }
53844d9e2bb86db4476d5218937e7c28df47f769
[ "TypeScript", "HTML" ]
2
HTML
Mattacchione/fanta-msi
018b58aa047bdbe7d3f0b4e61ea95cd7341490ed
11ebe88bbbc69699886fc60454c4a8b9d52d26ff
refs/heads/master
<repo_name>bluetronics-India/4DOF-3D-Printed-Robotic-Arm<file_sep>/Firmwares/Geared_Version/robotArm/robotArm.ino #include "pinout.h" #include "robotGeometry.h" #include "interpolation.h" #include "fanControl.h" #include "rampsStepper.h" #include "queue.h" #include "command.h" RampsStepper stepperRotate(Z_STEP_PIN, Z_DIR_PIN, Z_ENABLE_PIN); RampsStepper stepperLower(Y_STEP_PIN, Y_DIR_PIN, Y_ENABLE_PIN); RampsStepper stepperHigher(X_STEP_PIN, X_DIR_PIN, X_ENABLE_PIN); RampsStepper stepperExtruder(E_STEP_PIN, E_DIR_PIN, E_ENABLE_PIN); FanControl fan(FAN_PIN); RobotGeometry geometry; Interpolation interpolator; Queue<Cmd> queue(255); //15 Command command; //configure gripper byj stepper boolean Direction = true; int Steps = 0; int steps_to_grip = 900; unsigned long last_time; unsigned long currentMillis; long time; // for Homing const int Z_HomeStep = 2850; // 2850 step to Home Rotation Stepper... rotate back CW after touching Z-min switch (to set Robotic arm rotation to 0 Degree) bool home_on_boot = true; // set it false if you not want to Home the robotic arm automatically during Boot. bool home_rotation_stepper = false; // enable it (set to true) if you want to home rotation stepper too... it requires end-switch mounted on rotation and attached to Z-min pin on RAMPS const int MaxDwell = 1200; const int OffDwell = 80; // Main stepper OFF-delay= 40minimum ; normal=80 ; base rotation needed more time int On_Dwell = MaxDwell; // Main stepper ON-delay= 120minimum ; normal=480; Home speed=600 void setup() { Serial.begin(9600); //various pins.. pinMode(HEATER_0_PIN , OUTPUT); pinMode(HEATER_1_PIN , OUTPUT); pinMode(LED_PIN , OUTPUT); //unused Stepper.. pinMode(E_STEP_PIN , OUTPUT); pinMode(E_DIR_PIN , OUTPUT); pinMode(E_ENABLE_PIN , OUTPUT); //unused Stepper.. pinMode(Q_STEP_PIN , OUTPUT); pinMode(Q_DIR_PIN , OUTPUT); pinMode(Q_ENABLE_PIN , OUTPUT); //GripperPins pinMode(STEPPER_GRIPPER_PIN_0, OUTPUT); pinMode(STEPPER_GRIPPER_PIN_1, OUTPUT); pinMode(STEPPER_GRIPPER_PIN_2, OUTPUT); pinMode(STEPPER_GRIPPER_PIN_3, OUTPUT); //reduction of steppers.. stepperHigher.setReductionRatio(32.0 / 9.0, 200 *16); //big gear: 32, small gear: 9, steps per rev: 200, microsteps: 16 stepperLower.setReductionRatio( 32.0 / 9.0, 200 *16); //(32.0 / 9.0, 200 * 16) stepperRotate.setReductionRatio(32.0 / 9.0, 200 *16); stepperExtruder.setReductionRatio(32.0 / 9.0, 200 * 16); //start positions.. stepperHigher.setPositionRad(PI / 2.0); //90° stepperLower.setPositionRad(0); // 0° stepperRotate.setPositionRad(0); // 0° stepperExtruder.setPositionRad(0); //enable and init.. if(home_on_boot) { Serial.println("Homing start..."); GoHome(); // Go to home position on boot Serial.println("Home Done."); } else { setStepperEnable(false); } interpolator.setInterpolation(0,19.5,134,0, 0,19.5,134,0); // interpolator.setInterpolation(0,120,120,0, 0,120,120,0); Serial.println("start"); } void setStepperEnable(bool enable) { stepperRotate.enable(enable); stepperLower.enable(enable); stepperHigher.enable(enable); stepperExtruder.enable(enable); fan.enable(enable); } void loop () { //update and Calculate all Positions, Geometry and Drive all Motors... interpolator.updateActualPosition(); geometry.set(interpolator.getXPosmm(), interpolator.getYPosmm(), interpolator.getZPosmm()); stepperRotate.stepToPositionRad(geometry.getRotRad()); stepperLower.stepToPositionRad (geometry.getLowRad()); stepperHigher.stepToPositionRad(geometry.getHighRad()); stepperExtruder.stepToPositionRad(interpolator.getEPosmm()); stepperRotate.update(); stepperLower.update(); stepperHigher.update(); //Serial.write("N1"); fan.update(); if (!queue.isFull()) { if (command.handleGcode()) { queue.push(command.getCmd()); printOk(); } } if ((!queue.isEmpty()) && interpolator.isFinished()) { executeCommand(queue.pop()); //Serial.println("N"); } if (millis() %500 <250) { digitalWrite(LED_PIN, HIGH); } else { digitalWrite(LED_PIN, LOW); } } void cmdMove(Cmd (&cmd)) { interpolator.setInterpolation(cmd.valueX, cmd.valueY, cmd.valueZ, cmd.valueE, cmd.valueF); } void cmdDwell(Cmd (&cmd)) { delay(int(cmd.valueT * 1000)); } void cmdGripperOn(Cmd (&cmd)) { Direction = true; for(int i = 1; i <= steps_to_grip; i++){ stepper(); delay(1); } } void cmdGripperOff(Cmd (&cmd)) { Direction = false; for(int i = 1; i <= steps_to_grip; i++){ stepper(); delay(1); } } void cmdStepperOn() { setStepperEnable(true); } void cmdStepperOff() { setStepperEnable(false); } void cmdFanOn() { fan.enable(true); } void cmdFanOff() { fan.enable(false); } void handleAsErr(Cmd (&cmd)) { printComment("Unknown Cmd " + String(cmd.id) + String(cmd.num) + " (queued)"); printFault(); } void executeCommand(Cmd cmd) { if (cmd.id == -1) { String msg = "parsing Error"; printComment(msg); handleAsErr(cmd); return; } if (cmd.valueX == NAN) { cmd.valueX = interpolator.getXPosmm(); } if (cmd.valueY == NAN) { cmd.valueY = interpolator.getYPosmm(); } if (cmd.valueZ == NAN) { cmd.valueZ = interpolator.getZPosmm(); } if (cmd.valueE == NAN) { cmd.valueE = interpolator.getEPosmm(); } //decide what to do if (cmd.id == 'G') { switch (cmd.num) { case 0: cmdMove(cmd); break; case 1: cmdMove(cmd); break; case 4: cmdDwell(cmd); break; case 28: GoHome(); break; // Added my me to Home the Robotic Arm on G28 command //case 21: break; //set to mm //case 90: cmdToAbsolute(); break; //case 91: cmdToRelative(); break; //case 92: cmdSetPosition(cmd); break; default: handleAsErr(cmd); } } else if (cmd.id == 'M') { switch (cmd.num) { //case 0: cmdEmergencyStop(); break; case 3: cmdGripperOn(cmd); break; case 5: cmdGripperOff(cmd); break; case 17: cmdStepperOn(); break; case 18: cmdStepperOff(); break; case 106: cmdFanOn(); break; case 107: cmdFanOff(); break; default: handleAsErr(cmd); } } else { handleAsErr(cmd); } } // Gripper Stepper Control void stepper(){ switch(Steps){ case 0: digitalWrite(STEPPER_GRIPPER_PIN_0, LOW); digitalWrite(STEPPER_GRIPPER_PIN_1, LOW); digitalWrite(STEPPER_GRIPPER_PIN_2, LOW); digitalWrite(STEPPER_GRIPPER_PIN_3, HIGH); break; case 1: digitalWrite(STEPPER_GRIPPER_PIN_0, LOW); digitalWrite(STEPPER_GRIPPER_PIN_1, LOW); digitalWrite(STEPPER_GRIPPER_PIN_2, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_3, HIGH); break; case 2: digitalWrite(STEPPER_GRIPPER_PIN_0, LOW); digitalWrite(STEPPER_GRIPPER_PIN_1, LOW); digitalWrite(STEPPER_GRIPPER_PIN_2, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_3, LOW); break; case 3: digitalWrite(STEPPER_GRIPPER_PIN_0, LOW); digitalWrite(STEPPER_GRIPPER_PIN_1, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_2, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_3, LOW); break; case 4: digitalWrite(STEPPER_GRIPPER_PIN_0, LOW); digitalWrite(STEPPER_GRIPPER_PIN_1, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_2, LOW); digitalWrite(STEPPER_GRIPPER_PIN_3, LOW); break; case 5: digitalWrite(STEPPER_GRIPPER_PIN_0, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_1, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_2, LOW); digitalWrite(STEPPER_GRIPPER_PIN_3, LOW); break; case 6: digitalWrite(STEPPER_GRIPPER_PIN_0, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_1, LOW); digitalWrite(STEPPER_GRIPPER_PIN_2, LOW); digitalWrite(STEPPER_GRIPPER_PIN_3, LOW); break; case 7: digitalWrite(STEPPER_GRIPPER_PIN_0, HIGH); digitalWrite(STEPPER_GRIPPER_PIN_1, LOW); digitalWrite(STEPPER_GRIPPER_PIN_2, LOW); digitalWrite(STEPPER_GRIPPER_PIN_3, HIGH); break; default: digitalWrite(STEPPER_GRIPPER_PIN_0, LOW); digitalWrite(STEPPER_GRIPPER_PIN_1, LOW); digitalWrite(STEPPER_GRIPPER_PIN_2, LOW); digitalWrite(STEPPER_GRIPPER_PIN_3, LOW); break; } SetDirection(); } void SetDirection(){ if(Direction==true){ Steps++;} if(Direction==false){ Steps--; } if(Steps>7){Steps=0;} if(Steps<0){Steps=7; } } /////////////////////////////////////////////////////////////////////// /////// Home function to home the robotic arm at limit Switches /////// /////////////////////////////////////////////////////////////////////// // Reset arm to HOME position Z_home, Y_home then X_home... this function is called when G28 command is issued void GoHome() { int bState; stepperHigher.enable(false); // disable Higher arm Stepper so that it do not block rotation of Lower arm while lower arm home // Lower arm Home stepperLower.enable(true); pinMode(Y_MIN_PIN,INPUT); digitalWrite(Y_DIR_PIN,HIGH); delayMicroseconds(5); // Enables the motor-Y to move the LOWER ARM CCW until hitted the Y-min_SW bState = digitalRead(Y_MIN_PIN); // read the input pin: while (bState==HIGH) // initally SW OPEN = High (Loop until limit switch is pressed) { digitalWrite(Y_STEP_PIN,HIGH); delayMicroseconds(On_Dwell); digitalWrite(Y_STEP_PIN,LOW); delayMicroseconds(OffDwell); bState = digitalRead(Y_MIN_PIN); } // Upper arm Home stepperHigher.enable(true); pinMode(X_MIN_PIN,INPUT); digitalWrite(X_DIR_PIN,HIGH); delayMicroseconds(5); // Enables the motor-X to move the UPPER ARM CCW until hitted the X-min_SW bState = digitalRead(X_MIN_PIN); // read the input pin: while (bState==HIGH) // assume initally SW OPEN = High (Loop until limit switch is pressed) { digitalWrite(X_STEP_PIN,HIGH); delayMicroseconds(On_Dwell); digitalWrite(X_STEP_PIN,LOW); delayMicroseconds(OffDwell); bState = digitalRead(X_MIN_PIN); } // Rotation Home if (home_rotation_stepper == true) // home Rotation stepper too if home_rotation_stepper is set to true. { // Rotation Home (It will Home towards Right Side (see from Front) towards 90 degree, hit the limit switch and then again move back to 0 Degree) stepperRotate.enable(true); pinMode(Z_MIN_PIN,INPUT); digitalWrite(Z_DIR_PIN,LOW); delayMicroseconds(5); // Enables the motor-Z to rotate the ARM Anti-Clock-Wise (see from Front) until hitted the Z-min_SW bState = digitalRead(Z_MIN_PIN); // read the input pin: while (bState==HIGH) // assume initally SW OPEN = High (Loop until limit switch is pressed) { digitalWrite(Z_STEP_PIN,HIGH); delayMicroseconds(On_Dwell); digitalWrite(Z_STEP_PIN,LOW); delayMicroseconds(OffDwell); bState = digitalRead(Z_MIN_PIN); } ZRot(HIGH, Z_HomeStep); // Enables the motor-Z to rotate the ARM CW --> HOME to go 0 Degree (Normal position) } interpolator.setInterpolation(0,19.5,134,0, 0,19.5,134,0); //Set Home Position to again X0 Y19.5 Z134 cmdStepperOn(); // M17 Gcode (Power on All Steppers) //Open Gripper when Home Direction = true; for(int i = 1; i <= steps_to_grip; i++){ stepper(); delay(1); } } void ZRot(boolean DIR, int STEP) { digitalWrite(Z_DIR_PIN,DIR); delayMicroseconds(5); // SET motor direction for (int i=1; i<=STEP; i++) { digitalWrite(Z_STEP_PIN,HIGH); delayMicroseconds(On_Dwell); digitalWrite(Z_STEP_PIN,LOW); delayMicroseconds(OffDwell); } }
13a67823017f310563d68fa597ed3a09371551b6
[ "C++" ]
1
C++
bluetronics-India/4DOF-3D-Printed-Robotic-Arm
bf821526da25be8128014cd75c4c72ea985b76a9
f80dd2df155f8f3e77a525b9bb1d1ac790582476
refs/heads/master
<file_sep>import './App.css'; function Home() { return ( <div class="color"> <div class="position-relative overflow-hidden p-3 p-md-5 m-md-3 text-center bg-light"> <div class="col-md-5 p-lg-5 mx-auto my-5"> <h1 class="display-4 font-weight-normal">Punny headline</h1> <p class="lead font-weight-normal">And an even wittier subheading to boot. Jumpstart your marketing efforts with this example based on Apple's marketing pages.</p> <a class="btn btn-outline-secondary" href="/">Coming soon</a> </div> <div class="product-device box-shadow d-none d-md-block"></div> <div class="product-device product-device-2 box-shadow d-none d-md-block"></div> </div> <div class="d-md-flex flex-md-equal w-100 my-md-3 pl-md-3"> <div class="bg-dark mr-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center text-white overflow-hidden"> <div class="my-3 py-3"> <h2 class="display-5">Another headline</h2> <p class="lead">And an even wittier subheading.</p> </div> <div class="bg-light box-shadow mx-auto" ></div> </div> <div class="bg-light mr-md-3 pt-3 px-3 pt-md-5 px-md-5 text-center overflow-hidden"> <div class="my-3 p-3"> <h2 class="display-5">Another headline</h2> <p class="lead">And an even wittier subheading.</p> </div> <div class="bg-dark box-shadow mx-auto" ></div> </div> </div> </div> ); } export default Home;<file_sep>import { useState } from 'react'; import './App.css'; import Sku from './sku'; //importo botstrap import 'bootstrap/dist/css/bootstrap.min.css'; function Description() { var [boolean, setBoolean] = useState(0); let gracias = "" if (boolean === true) { gracias = "Gracias por su comprar" } var [det, setDet] = useState(0); let detalleTitulo = "" let detalle = "" let detalle2 = "" if (det === true) { detalleTitulo = "Anteojos de sol Lentes Infinit Moscow" detalle ="Las lentes de sol INFINIT de alta protección están pensadas para realizar actividades al aire libre. Los cristales lentes de sol con filtro UV400 son capaces de bloquear el 100% los rayos solares UV400A y UV400B. Nuestro material orgánico de Policarbonato es de altísima resistencia a los impactos evitando roturas o accidentes oculares." detalle2="Los colores Mate pueden tener pequeños brillados que se ocasionan por la propia manipulación entre las piezas de producción. Esta superficie mate sutilmente aterciopelada debe tratarse con cuidado para evitar los brillados en la superficie. Los mismos no constituyen un defecto de fabricación." }else{ detalleTitulo = "" detalle = "" detalle2 = "" } return ( <div classDescription="App"> <header classDescription="App-header"> <img src="https://http2.mlstatic.com/D_NQ_NP_648063-MLA43691191417_102020-O.webp" alt="Girl in a jacket" width="500" height="100%" /> <Sku/> <button type="button" class="btn btn-primary" onClick={() => setBoolean(boolean = true )}>Comprar</button> <p>{gracias} </p> <div class="card bg-dark mb-3" > <button type="button" class="btn btn-primary" onClick={() => setDet(det = true || false )}>Detalle</button> <div class="card-body"> <h5 class="card-title">{detalleTitulo}</h5> <h3 class="card-text">{detalle}</h3> <h6>{detalle2} </h6> <h5> Medidas: </h5> <ol class="list-group list-group-numbered"> <li class="list-group-item list-group-item-dark">140mm (Ancho)</li> <li class="list-group-item list-group-item-dark">140mm (Largo patilla)</li> <li class="list-group-item list-group-item-dark">54mm (alto)</li> <li class="list-group-item list-group-item-dark">18mm ( puente)</li> </ol> </div> </div> </header> </div> ); } export default Description;<file_sep>import Amount from './Amount'; import './App.css'; import Description from './description'; import Price from './price'; function Name() { return ( <div className="App"> <header className="App-header"> <p> Nombre del producto: Lentes <Price/><Amount/> </p> <Description/> </header> </div> ); } export default Name;<file_sep>import './App.css'; function Amount() { return ( <div classAmount="App"> <header classAmount="App-header"> <p> Cantidad: 1000 Un </p> </header> </div> ); } export default Amount;<file_sep># Desarrollo en React JS <img src="https://www.vectorlogo.zone/logos/reactjs/reactjs-icon.svg" alt="babel" width="40" height="40"/> Aplicar y adaptar los conocimientos en programación web al desarrollo de aplicaciones SPA explotando las ventajas brindadas por `React` en cuanto al flujo de datos. ![Centro de e-Learning UTN - Facultad Regional Buenos Aires](https://assets.utnba.centrodeelearning.com/public-api/files/ac72554134105c72997e8beb577018fa/images) ## Trabajo práctico Unidad N° 3 (optativo) <img src="https://www.vectorlogo.zone/logos/reactjs/reactjs-icon.svg" alt="babel" width="40" height="40"/> **_Consigna:_** **Crear una aplicación con react cli llamada "myapp".** Desarrollar el maquetado de una pagina de detalle de un producto para un sitio de ecommerce, se deberán visualizar los siguientes datos: - Nombre - Descripción - Precio - SKU - Cantidad disponible - Realizar un maquetado con los datos, desarrollado con componentes. Agregar al mismo un botón "Comprar". Al hacer clic en dicho botón se deberá mostrar debajo del mismo un mensaje al usuario que diga: "Gracias por su compra". Enviar el contenido de la aplicación creada (exceptuando la carpeta node_modules) ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. <file_sep>import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom'; import './App.css'; import Footer from './footer'; import Home from './home'; import Menu from './menu'; import Name from './name'; import NotFoundPage from './noFoundPage'; function App() { return ( <Router> <Menu/> <Switch> <Router path="/product" exact> <Name /> </Router> <Route path="/" exact> <Home/> </Route> <Redirect from="/home" to="/" exact /> <Route path="*"> <NotFoundPage/> </Route> </Switch> <Footer/> </Router> ); } export default App;
2bed39a43d779cb4120ae2709041f8f44b6243fe
[ "JavaScript", "Markdown" ]
6
JavaScript
EricERodriguez/myapp
0bb6657c985085fd652e30caa4d3d3e1e14f7c5a
74f37a4324835af50218f2f0fb430dec7e68461e
refs/heads/master
<repo_name>losteracmer/wpcms<file_sep>/routes/index.js const express = require('express'); const router = express.Router(); const mysql = require('../common/mysql'); router.use('/getlist',(Request,Response)=>{ let sql = `SELECT customer_id ,real_name,mobile_1,mobile_2,festatus_id,machine_model,fe_model,DATE_FORMAT(last_time,'%Y-%m-%d') AS 'last_time', fe_periodicity - DATEDIFF(NOW(),last_time) AS "valid_time",customer_star,customer_area,address , allot_status,labour_name from service where (lazy_time<NOW() OR lazy_time IS NULL) AND customer_status = 0 ORDER BY DATE_ADD(last_time,INTERVAL fe_periodicity DAY)` mysql.query(sql).then(resset =>{ Response.send({ code:200, list:resset }) }).catch(error=>{ console.error("index list 错误:",error); Response.send({ code:500 }) }) }) router.use('/getlistajax',(Request,Response)=>{ let lazyshow = Request.query.lazyshow; let validshow = Request.query.validshow; let allotshow = Request.query.allotshow; let sqlpartV = ` and valid_time<=0 `; let sqlpartA = ` and allot_status is not null `; let sql = `SELECT customer_id ,real_name,mobile_1,mobile_2,festatus_id,machine_model,fe_model,DATE_FORMAT(last_time,'%Y-%m-%d') AS 'last_time', fe_periodicity - DATEDIFF(NOW(),last_time) AS "valid_time",customer_star,customer_area,address , allot_status,labour_name from service where (lazy_time<NOW() OR lazy_time IS NULL) ${validshow=='true'?'':sqlpartV}${allotshow=='true'?'':sqlpartA} AND customer_status = 0 ORDER BY DATE_ADD(last_time,INTERVAL fe_periodicity DAY)` if(lazyshow == 'true'){ sql = `SELECT customer_id ,real_name,mobile_1,mobile_2,festatus_id,machine_model,fe_model,DATE_FORMAT(last_time,'%Y-%m-%d') AS 'last_time', fe_periodicity - DATEDIFF(NOW(),last_time) AS "valid_time",customer_star,customer_area,address , allot_status,labour_name from service where lazy_time>NOW() ORDER BY DATE_ADD(last_time,INTERVAL fe_periodicity DAY)` } console.log(sql) mysql.query(sql).then(resset =>{ Response.send({ data:resset }) }).catch(error=>{ console.error("index list 错误:",error); Response.send({ code:500 }) }) }) router.use('/delayremind',(Request,Response)=>{ let delaytime = Request.query.delaytime; let fesid = Request.query.fesid; console.log('update delay time :',delaytime," ",fesid); let now = new Date() now.setDate(now.getDate()+delaytime*1); let sql = `UPDATE festatus set lazy_time = ? where festatus_id = ?`; let par = [now,fesid]; mysql.update(sql,par).then(result=>{ console.log("设置成功!"); Response.send({ code:200, msg:'设置成功' }) }).catch(error=>{ console.log("error:'",error); Response.send({ code:500, msg:'设置失败,服务器错误' }) }) }) router.use('/setlabour',(Request,Response)=>{ let labourId = Request.query.labourId; let fesid = Request.query.fesid; console.log(labourId,' ',fesid) let sql = `update festatus set allot_status = ? where festatus_id = ?`; let par = [labourId,fesid] mysql.update(sql,par).then(result=>{ console.log("派工成功!",result); Response.send({ code:200, msg:'派工成功' }) }).catch(error=>{ console.log("error:'",error); Response.send({ code:500, msg:'派工失败,服务器错误' }) }) }) router.use('/getcustomerid',(Request,Response)=>{ let fesid = Request.query.fesid; let sql = `select sales.customer_id from festatus,sales where festatus_id = ${fesid} and festatus.sale_id = sales.sale_id`; mysql.query(sql).then(resset=>{ if(resset.length == 0){ Response.send({ code:403, msg:'没有找到此用户' }) }else { Response.send({ code:200, customer_id :resset[0].customer_id }) } }).catch(error=>{ Response.send({ code:500, msg:'系统错误' }) }) }) router.use('/finished',(Request,Response)=>{ let fesid = Request.query.fesid; let finishTime = Request.query.finishtime||new Date(); console.log("finish time:",Request.query); let sql = `select * from festatus where festatus_id = ${fesid}`; mysql.query(sql).then(resset=>{ if(resset.length == 0){ Response.send({ code :403, msg:'没有找到这条记录' }) return; } let allot_status = resset[0].allot_status; console.log('finished allot_status :',allot_status); if(allot_status){ let sql2 = `insert into maintain(maintain_time,maintain_status,labour_id,maintain_for,maintain_record) values(?,?,?,?,?)`; let par = [finishTime,1,allot_status,fesid,'[record by system]']; mysql.insert(sql2,par).then(result =>{ Response.send({ code:200, msg:'以设置完成派工'+finishTime }) }) }else{ let sql2 = `insert into maintain(maintain_time,maintain_status,labour_id,maintain_for,maintain_record) values(?,?,?,?,?)`; let par = [finishTime,1,null,fesid,'by system']; mysql.insert(sql2,par).then(result =>{ Response.send({ code:200, msg:'由于未设置派工员工,设置为 默认 '+finishTime }) }) } }) }) module.exports =router; <file_sep>/README.md # wpcms 净水机客户管理系统 wpc 首页的 完成,没有刷新表格 数据库,工人删除后,fesstaus设为null 滤芯更换记录(总)list 配件维修list 配件设置页 用户详情页 增加购买订单 配件维修选项 更换配件 在用户那个页面,增加一个配件时间线, 是否要派工? 增加设置customer_detail 设置派工,手动完成派工 dosomething ? 客户 僵尸 回复 增加 最近更换时间 机器型号删除 用户详情 + 滤芯更换时间 !imortant 订单创建时,用户以更换滤芯无法 online 更改了触发器 设置auto_insert_festatus 选项 可以不自动添加 local : 更改 service 的视图 增加machine_code 修改 maintenance 视图 labour right join maintain on labour_id&& (对于没有员工的维修记录) 圆角列表、图文列表 不要图 ####更新 2019-4-6 完善app version 2 对新模式重构app 完成app后台接口 添加表 ```sql CREATE TABLE `wpcms`.`Untitled` ( `customer_maintain_id` int(32) NOT NULL AUTO_INCREMENT, `customer_id` bigint(64) NOT NULL, `labour_id` varchar(32) NOT NULL, `record` varchar(255) NULL, `maintain_time` datetime NOT NULL, PRIMARY KEY (`customer_maintain_id`), CONSTRAINT `customer_maintain_customer_id_fk` FOREIGN KEY (`customer_id`) REFERENCES `wpcms`.`customer` (`customer_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `customer_maintain_labour_id_fk` FOREIGN KEY (`labour_id`) REFERENCES `wpcms`.`labour` (`labour_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ); ``` 页面 每次 加载数据过多,没有交互信息显示 datatables 设置无内容字段 2019-5-3 增加功能 每个员工会有对应的滤芯持有数量,每次完成滤芯更换,持有数量会自动减一 此操作只适用于app 另外,基本放弃针对每个滤芯进行维护的模式,更改主页为客户维护 <file_sep>/test/map.js let amap = new Map() amap.set("sss","sst"); console.log(amap.get("sst")) //可见没有值 就会是undefined<file_sep>/utils/createncryptedPasswd.js const encode = require('./encode'); const random = require('./random'); const Base64 = require('./base64') //1.生成8位的随机数 let randomWord = random(false,8); let base64 = new Base64(); //2.对生成的随机数加密 let base64Random = base64.encode(randomWord); function createncryptedPasswd(password){ return encode(base64Random,password) } module.exports = createncryptedPasswd;<file_sep>/common/mysql.js var mysql = require('mysql'); var mysqlp = require('promise-mysql'); var mysqlConfig = require('../config.js').mysqlConfig; var pool = mysql.createPool(mysqlConfig); var pp = mysqlp.createPool(mysqlConfig); exports.connectionp = async function () { return await pp.getConnection(); } exports.connection = function(){ return new Promise(function (resolve,reject) { pool.getConnection((err,connection) =>{ if (err) { reject(err); }else { resolve(connection); } }) }) } //查询语句 exports.query = function(sql) { return new Promise(function(resolve, reject) { //创建连接池 pool.getConnection(function(err, connection) { if(err){ console.log('连接池错误',err) return; } connection.query(sql, function(err, result) { if (result) { resolve(result); } else { reject(err); } // 释放连接 connection.release(); }); }); }) } //更新 exports.update = function(sql,par) { return new Promise(function(resolve, reject) { pool.getConnection(function(err, connection) { connection.query(sql, par,function(err, result) { if (result) { resolve(result); } else { reject(err); } // 释放连接 connection.release(); }); }); }) } //插入 exports.insert = function(sql,par) { return new Promise(function(resolve, reject) { pool.getConnection(function(err, connection) { connection.query(sql, par,function(err, result) { if (result) { resolve(result); } else { reject(err); } // 释放连接 connection.release(); }); }); }) } exports.end = function(){ pool.end(); }<file_sep>/test/async.js var Delay_Time = function (ms) { return new Promise(function (resolve) { setTimeout(function () { resolve("完成啦") }, ms); }) } // async 函数 var Delay_Print = async function (ms) { let msg = await Delay_Time(ms) console.log(msg); return new Promise(function (resolve, reject) { reject("End"); }) } // 执行async函数后 Delay_Print(1000).then(function (resolve) { console.log(resolve); }) console.log("begin") function do1() { console.log("do1") } async function do2() { console.log("do2") } function add(x, y) { return new Promise((resolve, reject) => { resolve(x + y) }) } console.log(add(1, 2).then(s => { console.log(s); return new Promise() })); do2(); do1();<file_sep>/public/js/customer_maintain.js var Gsale_id = null; var Gindex_table = null; var Goption = { validshow: true, allotshow: false, lazyshow: true }; function setDelayTime() { //延迟提醒 ,就是更新 lastMaintain 时间,达到延迟提醒的作用 var delaytime = $("#delaytimeid").val(); //alert(delaytime) var sale_id = Gsale_id; $.ajax({ url: '/customermaintain/delayremind', data: { sale_id: sale_id, delaytime: delaytime }, success: function (data, textStatus) { if (data.code == 200) { //alert(data.msg) $("#delayremind").modal("hide"); toastr.success(data.msg); Gindex_table.ajax.reload(); } else { toastr.error(data.msg); } }, error: function (xhr, textStatus) { alert(JSON.stringify(xhr)); } }) } function setFinishTime() { var finishtime = $("#finishtimeid").val(); //alert(delaytime) var sale_id = Gsale_id; $.ajax({ url: '/customermaintain/finished', data: { sale_id: sale_id, finishtime, finishtime }, success: function (data, textStatus) { if (data.code == 200) { toastr.success(data.msg); Gindex_table.ajax.reload(); $("#setFinishTime").modal("hide"); } else { toastr.warning(data.msg) } }, error: function (error) { alert(error) } }) } function setDistribution() { var choseLabourObj = $("#choseLabourForm").serialize(); $.ajax({ url: '/customermaintain/setlabour' + "?" + choseLabourObj, data: { sale_id: Gsale_id }, success: function (data, textStatus) { if (data.code == 200) { toastr.success(data.msg); $("#choselabour").modal("hide"); Gindex_table.ajax.reload(); } else { toastr.error(data.msg); } }, error: function (xhr, textStatus) { console.error(xhr) } }) } function setEvent() { //console.log('设置事件'); //console.log($(".dropdown-item")) $("a.event").off(); //清空所有事件... $("a[data-event='delay']").bind('click', function () { var sale_id = $(this).parent().data('sale_id'); Gsale_id = sale_id; console.log("sale_id: " + sale_id); $("#delayremind").modal("show"); }) $("a[data-event='distribution']").bind('click', function () { var sale_id = $(this).parent().data('sale_id'); Gsale_id = sale_id; console.log("sale_id: " + sale_id); $.ajax({ url: '/labour/getlist', success: function (data, textStatus) { console.log('labour list 请求成功' + data); var lobourlistStr = template('labourListTemplate', data); $("#choselabourselect").html(lobourlistStr); }, error: function (xhr, textStatus) { } }) $("#choselabour").modal("show"); }) $("a[data-event='detail']").bind('click', function () { var sale_id = $(this).parent().data('sale_id'); $.ajax({ url: '/customermaintain/getcustomerid', data: { sale_id: sale_id }, success: function (data, textStatus) { if (data.code == 200) { toastr.success('正在跳转...') window.open('/customer_detail.html?customer_id=' + data.customer_id) //window.location.href = '/customer_detail.html?customer_id=' + data.customer_id; } else { toastr.warning(data.msg) } }, error: function (error) { alert(error) } }) }) $("a[data-event='finished']").bind('click', function () { var sale_id = $(this).parent().data('sale_id'); Gsale_id = sale_id; $("#setFinishTime").modal("show"); }) } function createButton(id) { //console.log('渲染完成') return `<td class="hidden-print"> <div class="btn-group"> <button type="button" class="btn btn-dark dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick=setEvent()> <i class="ti-settings"></i> </button> <div data-sale_id='${id}' class="dropdown-menu animated slideInUp" x-placement="bottom-start" style="position: absolute; will-change: transform; top: 0px; left: 0px; transform: translate3d(0px, 35px, 0px);"> <a class="dropdown-item detail event" href="javascript:void(0)" data-event='detail' data-etitle='客户详情'><i class='ti-eye'></i> </a> <a class="dropdown-item distribution event" href="javascript:void(0)" data-event='distribution' data-etitle='派工'><i class="ti-pencil-alt"></i> </a> <a class="dropdown-item delayevent event" href="javascript:void(0)" data-event='delay' id='delayevent' data-etitle='推迟半年'><i class="ti-na"></i> </a> </div> </div> </td>` }; function TableInit() { Gindex_table = $("#index_list_table").DataTable({ //dom: 'Bfrtip', //columnDefs:[{"targets":[11],"visible":false}], // buttons: [ // 'copy', 'csv', 'excel', 'pdf', 'print' // ], //分页效果 //"sPaginationType": "extStyle", processing: true, "destroy": true, buttons: [{ extend: 'print', text: '打印', exportOptions: { columns: [1, 2, 3, 4, 5, 6, 7] //visible:true //columns:$(".odd") } }, { extend: 'excel', text: '导出表格' }], ajax: { url: `/customermaintain/getlistajax?validshow=${Goption.validshow}&allotshow=${Goption.allotshow}&lazyshow=${Goption.lazyshow}`, }, //data: data.list, oLanguage: { "sSearch": "搜索", "sProcessing": "正在获取数据,请稍后...", "sLengthMenu": "显示 _MENU_ 条", "sZeroRecords": "没有内容", "sInfo": "从 _START_ 到 _END_ 条记录 总记录数为 _TOTAL_ 条", "sInfoEmpty": "记录数为0", "sInfoFiltered": "(全部记录数 _MAX_ 条)", "sInfoPostFix": "", "oPaginate": { "sFirst": "第一页", "sPrevious": "上一页", "sNext": "下一页", "sLast": "最后一页", } }, columns: [{ title: "星级", data: "customer_star" }, { title: "机器型号", data: "machine_model" }, { title: "更换次数", data: "maintain_sum" }, { title: "最近维护", data: "last_maintain" }, { title: "用户姓名", data: "real_name" }, { title: "联系方式", data: "mobile_1" }, { title: "地址", data: "address" }, { title: "派工", data: "labour_name" }, { title: '操作', data: 'sale_id', render: (data, type, full) => { return createButton(data) } } ] }) $('.buttons-copy, .buttons-csv, .buttons-print, .buttons-pdf, .buttons-excel').addClass( 'btn btn-cyan text-white mr-1'); //document.getElementById("list_body").innerHTML =lists; //customermaintain_list_table.rows.add(data.list); } $(document).ready(function () { //这里为了前台显示方便,设置的对调了一下 $("#validshow").bootstrapSwitch({ onSwitchChange: function (event, data) { console.log('switch change' + data); if (data) { $("#validshow").removeAttr("checked"); Goption.validshow = false; } else { $("#validshow").attr("checked", "checked"); Goption.validshow = true; } var allotshowStatus = $('#allotshow').attr('checked'); //Gindex_table.ajax.data = Goption; //console.log('重新加载url;'+`/customermaintain/getlistajax?validshow=${Goption.validshow}&allotshow=${Goption.allotshow}`) Gindex_table.ajax.url(`/customermaintain/getlistajax?validshow=${Goption.validshow}&allotshow=${Goption.allotshow}&lazyshow=${Goption.lazyshow}`).load(); } }) $("#allotshow").bootstrapSwitch({ onSwitchChange: function (event, data) { console.log('switch change' + data); if (data) { $("#allotshow").removeAttr("checked"); Goption.allotshow = true; } else { $("#allotshow").attr("checked", "checked"); Goption.allotshow = false; } var allotshowStatus = $('#allotshow').attr('checked'); //Gindex_table.ajax.data = Goption; //console.log('重新加载url;'+`/customermaintain/getlistajax?validshow=${Goption.validshow}&allotshow=${Goption.allotshow}`) Gindex_table.ajax.url(`/customermaintain/getlistajax?validshow=${Goption.validshow}&allotshow=${Goption.allotshow}&lazyshow=${Goption.lazyshow}`).load(); } }) $("#lazyshow").bootstrapSwitch({ onSwitchChange: function (event, data) { console.log('switch change' + data); if (data) { $("#lazyshow").removeAttr("checked"); Goption.lazyshow = false; } else { $("#lazyshow").attr("checked", "checked"); Goption.lazyshow = true; } var lazyshowStatus = $('#lazyshow').attr('checked'); //Gindex_table.ajax.data = Goption; //console.log('重新加载url;'+`/customermaintain/getlistajax?validshow=${Goption.validshow}&lazyshow=${Goption.allotshow}`) Gindex_table.ajax.url( `/customermaintain/getlistajax?validshow=${Goption.validshow}&allotshow=${Goption.allotshow}&lazyshow=${Goption.lazyshow}` ).load(); } }) // var validshowStatus = $('#validshow').attr('checked'); // console.log(validshowStatus) TableInit({ validshow: true, allotshow: true }); // $("input[name='delytime']").TouchSpin(); // var index_list_table = $("#index_list_table") })<file_sep>/routes/validation.js var express = require('express'); var router = express.Router(); const temporarycode = require('../utils/temporarycode'); router.use((Request,Response,Next)=>{ console.log("url:",Request.url," cookies",Request.cookies); var url = Request.url; if(url.startsWith("/assets")||url.startsWith("/dist")||url.startsWith("/img")||url.startsWith("/src")||url == '/admin_login.html'||url=='/login/login'||url.startsWith("/app")){ Next(); return; }else{ if(!Request.cookies){ Response.redirect('/admin_login.html'); console.log('未登录'); return; } if(!Request.cookies.login_status||!Request.cookies.admin){ Response.redirect('/admin_login.html'); console.log('未登录'); return; }else{ //console.log("以登录.."); temporarycode.check(Request.cookies.admin,Request.cookies.login_status,(flag)=>{ if(flag){ //console.log('身份验证成功..'); Next(); return; }else { console.log("身份验证失败",Request.cookies.admin,Request.cookies.login_status); Response.redirect('/admin_login.html'); } }) } } }) module.exports = router; <file_sep>/public/js/customer_detail.js var Gsale_id = null; function doBolckUI() { $.blockUI({ message: '<i class="fas fa-spin fa-sync text-white"></i><i class="text-white">提交请求中...</i>', overlayCSS: { backgroundColor: '#000', opacity: 0.5, cursor: 'wait' }, css: { color: '#333', border: 0, padding: 0, backgroundColor: 'transparent' }, }) } function getorder(pars) { console.log("getorder") $.ajax({ url: '/sales/customerorder', data: pars, success: function (data, textStatus) { var orderlistStr = template('orderListTemplate', data); $("#choseorderselect").html(orderlistStr); }, error: function (xhr, textStatus) { alert('网络异常') } }) } function getaccmaintain(pars) { //获取配件列表 //console.log("getaccmaintain"); $.ajax({ url: '/accessories/getlist', success: function (data, textStatus) { //console.log('accessories list 请求成功' + JSON.stringify(data)); var accessorieslistStr = template('accessoriesListTemplate', data); $("#choseaccessoriesselect").html(accessorieslistStr); }, error: function (xhr, textStatus) { alert('网络异常') } }) } //修改用户状态: function changeCustomerStatus(that) { let status = $(that).html(); console.log(status); alert(status); } function getCustomerFestatus(pars) { $.get("/customer/getfestatus", pars, function (data) { console.log("festatus:",data) /** * 将传来的滤芯按照不同的机器码区分,分别渲染到前台 * */ let allMachine = []; let sale_id = null; let machineIndex = 0; let oneMachine = []; for (let item of data.festatus) { console.log("其中一个item:",item) if (sale_id == null) { sale_id = item.sale_id; } else if (item.sale_id != sale_id) { machineIndex++; sale_id = item.sale_id; allMachine.push(oneMachine); oneMachine = []; } console.log("push 成功"); oneMachine.push(item); } if(oneMachine.length != 0) allMachine.push(oneMachine); console.log(allMachine); let templateStr = ""; for (let oneMachine of allMachine) { templateStr += template("festatusTableTemplate", { festatus: oneMachine, machine_model: oneMachine[0].machine_model }) } $("#festatusTable").html(templateStr) }) } function getCustomerOrder(pars){ $.ajax({ url: '/sales/customerorder' + '?' + pars, success: function (data, textStatus) { if (data.code == 200) { var orderTemplateStr = template('orderTemplate', data); $("#orderList").html(orderTemplateStr); } else { toastr.warning(data.msg); } } }) } //设置推迟时间 function setDelayTime() { var pars = window.location.href.split('?')[1]; //延迟提醒 ,就是更新 lastMaintain 时间,达到延迟提醒的作用 var delaytime = $("#delaytimeid").val(); //alert(delaytime) var sale_id = Gsale_id; $.ajax({ url: '/customermaintain/delayremind', data: { sale_id: sale_id, delaytime: delaytime }, success: function (data, textStatus) { if (data.code == 200) { //alert(data.msg) $("#delayremind").modal("hide"); toastr.success(data.msg); getCustomerOrder(pars); } else { toastr.error(data.msg); } }, error: function (xhr, textStatus) { alert(JSON.stringify(xhr)); } }) } $(document).ready(function () { var pars = window.location.href.split('?')[1]; //console.log('参数:' + pars); $.ajax({ url: '/customer/getdetail' + '?' + pars, success: function (data, textStatus) { //console.log('get data: ' + JSON.stringify(data)) if (data.code == 200) { var badge; if (data.detail.customer_status == 0) { badge = '<span id="customerStatus" class="badge badge-success badge-pill" click=changeCustomerStatus(this)> 正常</span>'; } else { badge = '<span id="customerStatus" class="badge badge-danger badge-pill"> 僵尸</span>'; } $("#real_name").html(data.detail.real_name + badge); $("#address").html(data.detail.address); $("#mobile_1").html(data.detail.mobile_1); $("#mobile_2").html(data.detail.mobile_2); $("#address").html(data.detail.address); $("#customer_avatarUrl").attr('src', data.detail.customer_avatarUrl); //input 内容更新 $("#p_real_name").val(data.detail.real_name); $("#p_mobile_1").val(data.detail.mobile_1) $("#p_mobile_2").val(data.detail.mobile_2) $("#p_address").val(data.detail.address) $("#p_customer_area").val(data.detail.customer_area) $("#p_customer_from").val(data.detail.customer_from) $("#p_remark").val(data.detail.remark) $(`input[name='customer_star'][value=${data.detail.customer_star}]`).attr('checked', true) } else if (data.code == 302) { window.location.href = data.href; } else { toastr.error(data.msg); } } }); //滤芯维修记录 $.ajax({ url: '/customer/maintenance' + '?' + pars, success: function (data, textStatus) { if (data.code == 200) { var maintenanceStr = template('maintenanceTemplate', data); $("#maintenance").html(maintenanceStr); } else { toastr.warning(data.msg); } } }) //配件维修记录 $.ajax({ url: '/customer/accmaintenance' + '?' + pars, success: function (data, textStatus) { if (data.code == 200) { var accmaintainStr = template('accmaintainTemplate', data); $("#accmaintain").html(accmaintainStr); } else { toastr.warning(data.msg); } } }) //用户订单 $.ajax({ url: '/sales/customerorder' + '?' + pars, success: function (data, textStatus) { if (data.code == 200) { var orderTemplateStr = template('orderTemplate', data); $("#orderList").html(orderTemplateStr); } else { toastr.warning(data.msg); } } }) //获取工人列表 $.ajax({ url: '/labour/getlist', success: function (data, textStatus) { //console.log('labour list 请求成功' + data); var lobourlistStr = template('labourListTemplate', data); $("#choselabourselect").html(lobourlistStr); }, error: function (xhr, textStatus) { alert('网络异常') } }) getCustomerFestatus(pars); // 获取 用户滤芯状态 getaccmaintain(pars); //获取此用户全部订单 getorder(pars); }) $(document).ready(function () { var pars = window.location.href.split('?')[1]; $("#updatebtn").on('click', function () { doBolckUI(); var formStr = $("#customerDetailForm").serialize(); console.log(typeof formStr); var pars = window.location.href.split('?')[1] console.log(formStr); $.ajax({ url: '/customer/change', type: "POST", data: formStr + "&" + pars, success: (data, textStatus) => { if (data.code == 200) { toastr.success(data.msg) } else { toastr.error(data.msg) } }, error: (error) => { toastr.error(JSON.stringify(error)); }, complete: () => { setTimeout(() => { $.unblockUI() }, 300); } }) }) $("#addAccmaintainBtn").on('click', function (that) { var addaccFormObj = $("#addAccmaintainForm").serialize(); $.ajax({ url: '/accessories/addmaintain', data: addaccFormObj, success: function (data, textStatus) { if (data.code == 200) { toastr.success(data.msg); getaccmaintain(window.location.href.split('?')[1]); } else { toastr.error(data.msg) } }, error: function (error) { alert('网络错误') } }) }) $("#accmaintain").on("click", ".doitbtn-makesucess", function (that) { var accmaintain_id = $(this).data('accmaintain_id'); $.ajax({ url: '/accessories/setaccmaintainfinish', data: { accmaintain_id: accmaintain_id }, success: function (data) { if (data.code == 200) { toastr.success(data.msg); //getaccmaintain(window.location.href.split('?')[1]); setTimeout(() => { window.location.reload(); }, 1300); } else { toastr.error(data.msg); } }, error: function (error) { toastr.error('网络异常'); } }) }) //修改客户状态 $("#real_name").on("click", "#customerStatus", function () { let status = $(this).text(); console.log(status) let setUrl = ""; //注意这里有一个空格 if(status == " 正常"){ setUrl = "/customer/setlazy"; }else { setUrl = "/customer/setunlazy" } let _confirm = confirm("确定将此客户设为"+(status == " 正常"?"僵尸":"正常")+"客户吗?"); if(_confirm){ doBolckUI(); $.ajax({ url:setUrl, data:pars, success:function(data){ if(data.code ==200){ toastr.success(data.msg); }else { toastr.error(data.msg); } }, complete:function(){ $.unblockUI(); } }) } }) $("#orderList").on("click", "button",function () { var sale_id = $(this).data("sale_id") Gsale_id = sale_id; console.log("sale_id: " + sale_id); $("#delayremind").modal("show"); }) //注册 input type date 事件 $("#festatusTable").on("blur", "input", function () { let finishtime = $(this).val() let _confim = confirm("确定更改时间:" + finishtime); if (_confim) { let festatus_id = $(this).attr("data-festatusId"); doBolckUI(); $.ajax({ url: '/customer/finished', data: { finishtime: finishtime, fesid: festatus_id }, success: function (data) { if (data.code == 200) { toastr.success(data.msg); } else { toastr.error(data.msg); } getCustomerFestatus(window.location.href.split('?')[1]); }, complete: function () { $.unblockUI(); } }) } }) })<file_sep>/routes/machine.js const express = require('express'); const router = express.Router(); const mysql = require('../common/mysql'); router.use("/getmachinelist",(Request,Response)=>{ let sql = `select * from machine order by machine_id desc`; mysql.query(sql).then(resset=>{ Response.send({ code:200, machinelist:resset }) }).catch(error=>{ console.error('get machine list error',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use('/getmachinefe',(Request,Response)=>{ let machine_id = Request.query.machine_id; let sql = `select * from machine2filterelement ,filterelement where filterelement.fe_id = machine2filterelement.fe_id and machine_id = ${machine_id}`; mysql.query(sql).then(resset=>{ if(resset.length == 0){ Response.send({ code:403, msg:'这个型号还没有滤芯', felist:resset }) }else{ Response.send({ code:200, felist:resset }) } }).catch(error=>{ console.error('get machine fe list error :',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use('/getfelist',(Request,Response)=>{ let sql = `select * from filterelement `; mysql.query(sql).then(resset=>{ Response.send({ code:200, felist:resset }) }).catch(error=>{ console.error('get machine list error',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use('/getaddfelist',(Request,Response)=>{ let machine_id= Request.query.machine_id; let sql = `select * from filterelement WHERE fe_id NOT IN (SELECT fe_id FROM machine2filterelement WHERE machine_id = ${machine_id})`; mysql.query(sql).then(resset=>{ Response.send({ code:200, felist:resset }) }).catch(error=>{ console.error('get machine list error',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use('/addfe',(Request,Response)=>{ let fe_model = Request.query.fe_model; let fe_periodicity = Request.query.fe_periodicity*1; //先查找有没有这个 let sql = `insert into filterelement(fe_model,fe_periodicity) values(?,?)`; let par = [fe_model,fe_periodicity]; mysql.insert(sql,par).then(result=>{ Response.send({ code:200, msg:'添加滤芯成功' }) }).catch(error=>{ console.error('add fe error:',error); Response.send({ code:500, msg:'服务器错误' }) }) }); router.use('/addmachine',(Request,Response)=>{ let machine_model = Request.query.machine_model; let machine_price = Request.query.machine_price*1; //先查找有没有这个 let sql = `insert into machine(machine_model,machine_price,come_time) values(?,?,?)`; let par = [machine_model,machine_price,new Date()]; mysql.insert(sql,par).then(result=>{ Response.send({ code:200, msg:'添加新机器成功' }) }).catch(error=>{ console.error('add machine error:',error); Response.send({ code:500, msg:'服务器错误' }) }) }); router.use('/addmachinefe',(Request,Response)=>{ let machine_id = Request.query.machine_id; let fe_id = Request.query.fe_id; //先查找有没有这个 let sql = `insert into machine2filterelement values(?,?)`; let par = [machine_id,fe_id]; mysql.insert(sql,par).then(result=>{ Response.send({ code:200, msg:'插入成功' }) }).catch(error=>{ console.error('add fe error:',error); Response.send({ code:500, msg:'该机器已经存在此滤芯' }) }) }); router.use('/deletemachinefe',(Request,Response)=>{ let machine_id = Request.query.machine_id; let fe_id = Request.query.fe_id; //先查找有没有这个 let sql = `delete from machine2filterelement where machine_id =? and fe_id = ?`; let par = [machine_id,fe_id]; mysql.insert(sql,par).then(result=>{ Response.send({ code:200, msg:'删除成功' }) }).catch(error=>{ console.error('delete machine fe error:',error); Response.send({ code:500, msg:"删除失败" }) }) }); router.use('/deletemachine',(Request,Response)=>{ let machine_id = Request.query.machine_id; //先查找有没有这个 let sql = `delete from machine where machine_id =? `; let par = [machine_id]; mysql.insert(sql,par).then(result=>{ Response.send({ code:200, msg:'删除成功' }) }).catch(error=>{ console.error('delete machine fe error:',error); Response.send({ code:500, msg:"删除失败" }) }) }); module.exports = router;<file_sep>/public/js/machine.js var Gmachine_id = null; function getAllMachine() { $.ajax({ url: '/machine/getmachinelist', success: function (data, textStatus) { if (data.code == 200) { var machineListStr = template('machineListTemplate', data); $("#machineList").html(machineListStr); } else { toastr.error(data.msg); } }, error: function (error) { toastr.error('网络连接失败...'); } }) } function getAllFe() { $.ajax({ url: '/machine/getfelist', success: function (data, textStatus) { console.log(JSON.stringify(data)) if (data.code == 200) { var feStr = template('feListTemplate', data); $("#feList").html(feStr); } else { toastr.error(data.msg); } }, error: function (error) { toastr.error('网络连接失败...'); } }) } function getMachineFe(machine_id){ $.ajax({ url: '/machine/getmachinefe', data: { machine_id: machine_id }, success: function (data, textStatus) { if (data.code == 200) { var feStr = template('machineFeListTemplate', data); $("#machineFeList").html(feStr); } else if(data.code==403){ var feStr = template('machineFeListTemplate', data); $("#machineFeList").html(feStr); toastr.warning(data.msg); } }, error: function (error) { toastr.error('网络故障...') } }) } function deleteFe(machine_id ,fe_id){ $.ajax({ url: 'machine/deletemachinefe', data: { machine_id, fe_id }, success: function (data, textStatus) { if (data.code == 200) { getMachineFe(machine_id); toastr.success(data.msg); } else{ toastr.error(data.msg); } }, error: function (error) { toastr.error('网络故障...') }, complete:function(){} }) } function deleteMachine(machine_id){ $.ajax({ url: '/machine/deletemachine', data: { machine_id }, success: function (data, textStatus) { if (data.code == 200) { toastr.success(data.msg); getAllMachine(); Gmachine_id = null; $("#deleteMachineBtn").hide(); $("#machineFeList").html(""); } else{ toastr.error(data.msg); } }, error: function (error) { toastr.error('网络故障...') }, complete:function(){} }) } $(document).ready(function () { getAllMachine(); getAllFe(); //获取机器滤芯 $('#machineCardList .card-body').on('click', '.card', function () { var machine_id = $(this).data('machine_id'); $(this).prevAll().removeClass('card-active'); $(this).nextAll().removeClass('card-active'); $(this).addClass('card-active'); Gmachine_id = machine_id; $("#deleteMachineBtn").show(); getMachineFe(machine_id); }) $("#machineFeList").on("click",".deleteBtn",function(){ let _confirm = confirm("确定删除这个滤芯?"); if(_confirm){ let fe_id = $(this).attr("data-fe_id"); deleteFe(Gmachine_id,fe_id); } }) //删除机器? $("#deleteMachineBtn").on("click",function(){ let _confirm = confirm("确定删除这个机器型号(危险操作)?"); if(_confirm){ deleteMachine(Gmachine_id); } }) $("#saveAddFeBtn").on('click', function () { console.log('click'); var fe_model = $("#p_fe_model").val(); var fe_periodicity = $("#p_fe_periodicity").val(); $.ajax({ url: '/machine/addfe', data: { fe_model, fe_periodicity }, success: function (data) { if (data.code == 200) { toastr.success(data.msg) $("#addFeModal").modal('hide'); getAllFe(); } else { toastr.error(data.msg) } }, error: function (data) { toastr.error('网络异常!'); } }) }) $("#saveAddMachineBtn").on('click', function () { console.log('click'); var machine_model = $("#p_machine_model").val(); var machine_price = $("#p_machine_price").val(); $.ajax({ url: '/machine/addmachine', data: { machine_model, machine_price }, success: function (data) { if (data.code == 200) { toastr.success(data.msg) $("#addMachineModal").modal('hide'); getAllMachine(); } else { toastr.error(data.msg) } }, error: function (data) { toastr.error('网络异常!'); } }) }) $("#addMachineFe").on('click',function(){ if(Gmachine_id == null){ toastr.warning("请选点击左侧机器,再进行添加操作"); return ; } var machine_id = Gmachine_id; $.ajax({ url:'/machine/getaddfelist', data:{ machine_id:machine_id }, success:function(data,textStatus){ //console.log(JSON.stringify(data)); if (data.code == 200) { var feListStr = template('MfeListTemplate',data); $("#chosefeselect").html(feListStr); $("#addMachineFeModal").modal('show'); } else { toastr.error(data.msg) } } }) }) $("#saveAddMachineFeBtn").on('click',function(){ var machine_id = Gmachine_id; var fe_id = $("#chosefeselect").val(); if(!fe_id){ return; } $.ajax({ url:"/machine/addmachinefe", data:{ machine_id, fe_id }, success:function(data){ if(data.code == 200){ toastr.success(data.msg); $("#addMachineFeModal").modal('hide'); getMachineFe(machine_id); }else { toastr.error(data.msg); } }, error:function(error){ toastr.error(data.msg); } }) }) })<file_sep>/test/await.js const mysql = require("../common/mysql") /** * 在正常的情况下,await后是一个Promise对象。如果不是就会立马转换成一个立即resolve的Promise对象。 */ async function d(){ let resset = await mysql.query("select * from admins;select * from admins") console.log(resset) let result = await 1+1; console.log(result) mysql.end(); } d() <file_sep>/test/Promise.js const mysql = require("../common/mysql") const fs = require('fs') function fetch(cb){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ try{ //resolve(cb); cb(); }catch(error){ reject(error,"失败") } },500); }) } // fetch(()=>{ // console.log("1s 后...."); // throw new Error("未知错误") // }).then(function(){ // console.log("成功执行"); // },function(reason,error){ // console.log("执行失败",reason,error) // throw new Error("ERROR") // }).catch((reason,error)=>{ // console.log("catch: ",reason) // }) function do1(){ return new Promise((res,rej)=>{ setTimeout(() => { rej("等待1s") console.log("--等待1s"); }, 1000); }) } function do2(){ // return new Promise((res,rej)=>{ // setTimeout(() => { // res("等待0.8s"); // console.log("--等待0.8s"); // }, 800); // }) return Promise.reject("手动创建 reject"); } // Promise.all([do1(),do2()]).then(resultArr =>{ // console.log(resultArr[0]); // console.log(resultArr[1]) // }) //当任何一个resolved 或者reject 完成时触发then方法 Promise.race([do1(),do2()]).then(result=>{ console.log(result); }).catch(error=>{ console.log('捕捉到了错误',error) }) <file_sep>/routes/app/login.js const express = require('express'); const router = express.Router(); const mysql = require('../../common/mysql'); router.use('/labourlogin',(Request,Response)=>{ console.log("app labour login"); let body = Request.body; let labour_id = body.labour_id; let labour_pw = body.labour_pw; let sql = `select * from labour where labour_id = '${labour_id}'`; mysql.query(sql).then(resset =>{ if(resset.length == 0){ Response.send({ code:403, msg:'没有找到此用户' }) return ; } if(resset[0].labour_pw == labour_pw){ Response.send({ code:200, msg:'登录成功', labour_id:resset[0].labour_id, labour_name:resset[0].labour_name, labour_avatarUrl :resset[0].labour_avatarUrl }) }else { Response.send({ code:403, msg:'密码错误:'+labour_pw }) } }) }) module.exports =router;<file_sep>/routes/app/maintenance.js var express = require('express'); var mysql = require("../../common/mysql"); var router = express.Router() var formidable = require('formidable') router.use('/maintenance',(Request,Response)=>{ let labour_id = Request.query.labour_id; if(!labour_id){ Response.send({ code:403, msg:'缺少参数' }) return ; } let sql = `SELECT customer_id ,real_name,mobile_1,mobile_2,festatus_id,machine_model,fe_model,DATE_FORMAT(last_time,'%Y-%m-%d') AS 'last_time', fe_periodicity - DATEDIFF(NOW(),last_time) AS "valid_time",customer_star,customer_area,address , allot_status,labour_name from service where allot_status = '${labour_id}' ` mysql.query(sql).then(resset=>{ Response.send({ code:200, maintenance:resset }) }).catch(error=>{ console.error('get maintenance error:',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use('/accmaintenance',(Request,Response)=>{ let labour_id = Request.query.labour_id; let sql = `select accessory_id,accessory_model,DATE_FORMAT(finish_time,'%Y-%m-%d %H:%i') AS 'finish_time',accmaintain_record,labour_name,sale_id,accessory_id ,accmaintain_status,accmaintain_id ,customer_id, address,real_name ,mobile_1,mobile_2,machine_model from accmaintenance where labour_id = '${labour_id}' and accmaintain_status = 0 order by finish_time desc`; mysql.query(sql).then(resset=>{ Response.send({ code:200, accmaintenance:resset }) }).catch(error=>{ console.error('get maintenance error:',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use('/finishedmaintenance',(Request,Response)=>{ let labour_id = Request.query.labour_id; if(!labour_id){ Response.send({ code:403, msg:'缺少参数' }) return ; } let beginTime = Request.query.beginTime; let endTime = Request.query.endTime; if(beginTime!="null"){ beginTime = new Date(beginTime); }else { beginTime = null; } if(endTime!="null"){ endTime = new Date(endTime); }else { endTime = null; } console.log("beginTime;",beginTime,"endTime:",endTime) let sql = `SELECT machine_id,DATE_FORMAT(maintain_time,'%Y-%m-%d %H:%i') AS 'maintain_time',maintain_status,labour_id,labour_name , festatus_id ,allot_status,customer_id,real_name,machine_code,maintain_record,address, machine_model ,labour_avatarUrl,fe_model,fe_id ,maintain_for ,sale_id,mobile_1,mobile_2,maintain_record from maintenance where labour_id = '${labour_id}' and maintain_status=1 ${beginTime&&endTime?"and maintain_time between '"+beginTime.toLocaleString()+"' and '"+endTime.toLocaleString()+"' ":""} order by maintain_time desc`; // console.log("sql", sql); mysql.query(sql).then(resset=>{ Response.send({ code:200, maintenance:resset }) }).catch(error=>{ console.error('get maintenance error:',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use('/finishedaccmaintenance',(Request,Response)=>{ let labour_id = Request.query.labour_id; let beginTime = Request.query.beginTime; let endTime = Request.query.endTime; if(beginTime!="null"){ beginTime = new Date(beginTime); }else { beginTime = null; } if(endTime!="null"){ endTime = new Date(endTime); }else { endTime = null; } let sql = `select accessory_id,accessory_model,DATE_FORMAT(finish_time,'%Y-%m-%d %H:%i') AS 'finish_time',accmaintain_record,labour_name,sale_id,accessory_id ,accmaintain_status,accmaintain_id ,customer_id, address,real_name ,mobile_1,mobile_2,machine_model from accmaintenance where labour_id = '${labour_id}' and accmaintain_status = 1 ${beginTime&&endTime?"and finish_time between '"+beginTime.toLocaleString()+"' and '"+endTime.toLocaleString()+"' ":""} order by finish_time desc`; console.log(sql) mysql.query(sql).then(resset=>{ Response.send({ code:200, accmaintenance:resset }) }).catch(error=>{ console.error('get maintenance error:',error); Response.send({ code:500, msg:'服务器错误' }) }) }) router.use("/storage", async (Request, Response) => { let labour_id = Request.query.labour_id; let sql = `select * from labourstorage ,filterelement where filterelement.fe_id = labourstorage.fe_id and labour_id = '${labour_id}' `; try { let resset = await mysql.query(sql); Response.send({ code: 200, labourStorageList: resset }) } catch (e) { console.log("ERROR storage",e) Response.send({ code: 500, msg: "服务器错误" }) } }); module.exports = router;<file_sep>/routes/login.js var express = require('express'); var router = express.Router(); var createCryptedPassword = require('../utils/createncryptedPasswd'); const encode = require('../utils/encode'); const mysql = require('../common/mysql'); const temporarycode = require('../utils/temporarycode'); router.use("/login", (Request, Response) => { console.log('adminLogin:', Request.query) let account = Request.body.account; let password = Request.body.password; //403, 数据错误 if (!account || !password) { Response.send({ code: 403, msg: "请输入用户名与密码" }); return false; } let sql = `SELECT * FROM admins WHERE account = '${account}'`; mysql.query(sql).then(resset => { if (resset.length > 0) { console.log(resset[0].password); //1.获取到的密码截取前面随机数通过base64加密的结果 let base64Random = resset[0].password.substring(0, 12); let lastPassword = encode(base64Random, password); if (resset[0].password === lastPassword) { let key = temporarycode.creat(account); //登录成功后,生成key返回给前台,并且每次都以key和account作为凭证进行操作 Response.cookie('login_status',key,{ expires: new Date(Date.now() + 100000000)}); Response.cookie('admin',account,{ expires: new Date(Date.now() + 100000000)}); Response.redirect('/index.html'); } else { Response.send({ code: 403, msg: "密码错误" }); } } else{ Response.send({ code:403, msg:"账号错误,请核对" }) } }).catch(error => { //404 数据库错误 console.log('登录异常', error) Response.send({ code: 500, msg: "程序员删库跑路了。。。" }); }) }) router.use('/getadminmsg',(Request,Response)=>{ let adminAccount = Request.cookies.admin; let sql = `select * from admins where account = '${adminAccount}'`; mysql.query(sql).then(resset=>{ if(resset.length == 0){ Response.send({ code:403, msg:'没找到该管理员账户,cookies过期 请重新登录' }) return; } Response.send({ code:200, adminMsg:resset[0] }) }).catch(error=>{ console.log('get admin msg error',error); Response.send({ code:500, msg:'服务器错误' }) }) }) module.exports=router;<file_sep>/routes/app/ChangeAvatarUrl.js var express = require('express'); var mysql = require("../../common/mysql"); var router = express.Router() var formidable = require('formidable') router.use('/avatar',(req,res) =>{ var formParse=new formidable.IncomingForm(); formParse.uploadDir='./public/img';//缓存地址 formParse.multiples=true;//设置为多文件上传 formParse.keepExtensions=true;//是否包含文件后缀 var uploadfiles=[]; //文件都将保存在files数组中 formParse.on('file', function (filed,file) { //console.log('frie文件:',filed,file); uploadfiles.push("/"+file.path.replace(/\\/g,'/')); }) formParse.parse(req,function(error,fields,files) { console.log('avatar file list',uploadfiles); if (error) { console.log("error" + error.message); res.send({ code:500, msg:'服务器错误' }) return; } let avatarUrl = uploadfiles[0]; let labour_id = fields.labour_id; let sql = `UPDATE labour SET labour_avatarurl = ? WHERE labour_id = ?` let par = [avatarUrl.substr(7),labour_id]; mysql.update(sql,par).then(result =>{ console.log("插入结果:",result); res.send({ code:200, msg:'更换头像成功' }) }).catch(error =>{ res.send({ code:500, msg:'服务器错误' }) }) }); }); module.exports = router;<file_sep>/config.js var mysqlConfig = { host: 'localhost', user: 'root', password: '<PASSWORD>', port: '3306', database: 'wpcms', multipleStatements: true, charset:'utf8mb4_general_ci' }; var machine_name2 = { "R-701":"R-701白" } var config = { //mysql的配置 mysqlConfig:mysqlConfig, //app version lastVersion:2, //机器名称映射表 machine_name2:machine_name2 } module.exports = config;<file_sep>/utils/temporarycode.js const random = require('./random') const mysql = require('../common/mysql') function creat(account){ let code = random(false,16); let sql = `UPDATE admins SET temporarycode = ? WHERE account = ?` let par = [code,account] mysql.update(sql,par).then(result=>{ console.log('更新临时码成功'); }).catch(error=>{ console.log('更新临时码失败',error) }) return code; } function check(account ,code,cb){ let sql = `SELECT * FROM admins WHERE account = '${account}' AND temporarycode = '${code}'` mysql.query(sql).then(resset=>{ if(resset.length > 0) cb(true); else cb(false); }) } exports.creat = creat; exports.check = check;<file_sep>/routes/app/finishmaintain.js let express = require('express'); let mysql = require("../../common/mysql"); let router = express.Router(); router.use('/maintenance', async (Request, Response) => { let labour_id = Request.query.labour_id; let maintain_record = Request.query.maintain_record; let festatus_id = Request.query.festatus_id; // let sql2 = `insert into maintain(maintain_time,maintain_status,labour_id,maintain_for,maintain_record) values(?,?,?,?,?)`; // let par = [new Date(), 1, labour_id, festatus_id, maintain_record]; // mysql.insert(sql2, par).then(result => { // Response.send({ // code: 200, // msg: '完成任务!' // }) // }).catch(error => { // console.log('app set maintain finish error:', error); // Response.send({ // code: 500, // msg: '服务器错误,稍后重试吧~' // }) // }) //做记录,并且同步storage 数量 let connection = await mysql.connectionp(); connection.beginTransaction(); try{ let sql2 = `insert into maintain(maintain_time,maintain_status,labour_id,maintain_for,maintain_record) values(?,?,?,?,?)`; let par = [new Date(), 1, labour_id, festatus_id, maintain_record]; let rr =await connection.query(sql2, par); console.log("rr:", rr); let sqlGetFeId = `select * from festatus where festatus_id = ?`; let festatus = await connection.query(sqlGetFeId,[festatus_id]); console.log(festatus); let fe_id = festatus[0].fe_id; let sqlSelect = `select * from labourstorage where labour_id = ? and fe_id = ? `; let labourstorages = await connection.query(sqlSelect, [labour_id, fe_id]); if(labourstorages.length === 0){ let sqlInsert = `insert into labourstorage (labour_id,fe_id,quantity) values(?,?,?)`; let result = await connection.query(sqlInsert,[labour_id,fe_id,0]); console.log("插入labourStorage result ", result); } let sqlUpdate = `update labourstorage set quantity = quantity + ? where labour_id = ? and fe_id = ?`; //这里是消耗掉一个,所以数量减1 let result2 = await connection.query(sqlUpdate, [-1, labour_id, fe_id]); let sqlLog = `insert into labourstoragechangelog(labour_id,fe_id,record_time,record_reason,change_sum) values(?,?,?,?,?)`; let result3 = await connection.query(sqlLog, [labour_id, fe_id, new Date(), "finish maintenance to " + festatus[0].sale_id +" record : "+ maintain_record, -1]); connection.commit(); Response.send({ code: 200, msg: '完成任务!' }) }catch (e) { console.log("事务出错: ",e); connection.rollback(); Response.send({ code: 500, msg: '服务器出错!' }) } }); router.use('/accmaintenance', (Request, Response) => { let labour_id = Request.query.labour_id; let accmaintain_record = Request.query.accmaintain_record; let accmaintain_id = Request.query.accmaintain_id; let sql = `update accmaintain set accmaintain_status = ? ,finish_time = ? ,accmaintain_record=? where accmaintain_id = ?`; let par = [1,new Date(),accmaintain_record,accmaintain_id]; mysql.update(sql,par).then(result =>{ Response.send({ code:200, msg:'完成任务!' }) }).catch(error=>{ console.error('app set finish accmaintain error:',error); Response.send({ code:500, msg:'服务器错误,稍后重试吧' }) }) }); /* 完成用户级别(订单级别)的维护。 */ router.use('/customer',async(Request, Response) =>{ let labour_id = Request.query.labour_id; let customer_id = Request.query.customer_id; let record = Request.query.record; //获取用户id ,将次用户所有订单 labour_id 志为空,时间更新 let sql1 = `UPDATE sales SET maintain_labour = NULL ,last_maintain = NOW() WHERE customer_id = ? `; let updateResult = await mysql.update(sql1,[customer_id]); let sql2 = `INSERT INTO customermaintain (customer_id,labour_id,maintain_time,record) VALUES(?,?,?,?)`; let par2 = [customer_id,labour_id,new Date(),record]; let insertResult = await mysql.insert(sql2,par2); console.log("插入结果",insertResult); //保存数据库 Response.send({ code:200, msg:"更新成功" }) }); module.exports = router;<file_sep>/common/db.js var mysql = require('mysql'); var dbconfig = { host:'localhost', user:'root', prot:3306, password:'123', database:'test' }; var pool = mysql.createPool(dbconfig); exports.query = (sql,cb) => { pool.getConnection((err,connection)=>{ connection.query(sql,(err,rows)=>{ cb(rows); connection.release(); }) }) }<file_sep>/test/string2date.js let str = '2028-1-1'; let date = new Date(str); console.log(str); console.log(date.getDay()); console.log(date.getTime() < new Date().getTime()); console.log(new Date('2018-1-1')>new Date('2019-1-1'))<file_sep>/app.js var createError = require('http-errors'); var express = require('express'); var path = require('path'); var cookieParser = require('cookie-parser'); var logger = require('morgan'); var indexRouter = require('./routes/index'); var usersRouter = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(logger('dev')); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); app.use(require('./routes/validation')); app.use(express.static(path.join(__dirname, 'public'))); app.use('/login',require('./routes/login')); app.use('/index',require('./routes/index')); app.use('/labour',require('./routes/labour')); app.use('/customer',require('./routes/customer')); app.use('/machine',require('./routes/machine')); app.use('/sales',require('./routes/sales')); app.use('/accessories',require('./routes/accessories')); app.use('/analysis',require('./routes/analysis')); app.use('/parsecustomer',require("./routes/parseCustomer")); app.use('/customermaintain',require("./routes/customerMaintain")); app.use('/navigation',require("./routes/navigation_html")); app.use('/app',require('./routes/wpcms_app')); // 未发现路由 app.use(function(req, res, next) { console.log('##########非访问:',req.url); res.redirect("/error-404.html"); }); // error handler app.use(function(err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error'); }); // app.listen(3000,function(error){ // if(error){ // console.log('监听错误') // }else { // console.log("正在监听3000"); // } // }) module.exports = app; <file_sep>/public/js/labour_detail.js function doBolckUI() { $.blockUI({ message: '<i class="fas fa-spin fa-sync text-white"></i><i class="text-white">提交请求中...</i>', overlayCSS: { backgroundColor: '#000', opacity: 0.5, cursor: 'wait' }, css: { color: '#333', border: 0, padding: 0, backgroundColor: 'transparent' }, }) } //全局 记录变量 var G_fe_id; function showAddNumberModel(fe_id) { console.log(fe_id); $("#addQuantityModal").modal("show"); G_fe_id = fe_id; } function addNewFE() { var pars = window.location.href.split('?')[1]; var objTo = document.getElementById('labourstragecontainter') var divtest = document.createElement("div"); divtest.setAttribute("class", "form-group"); $.ajax({ url:"/labour/getnotstoragefelist", data:pars, success:function (data) { if (data.code == 200) { let felistStr = ""; for (let i = 0; i < data.felist.length; i++) { felistStr += `<option value="${data.felist[i].fe_id}" selected>${data.felist[i].fe_model}</option>` } divtest.innerHTML = ` <form class="row"> <div class="col-sm-3"> <div class="form-group"> <select name="fe_model" class="select2 form-control custom-select" style="width: 100%; height:36px;"> ${felistStr} </select> </div> </div> <div class="col-sm-2"> <div class="form-group"> <input type="number" class="form-control" name="quantity" value="<%=item.quantity%>" name="quantity" placeholder="数量"> </div> </div> <div class="col-sm-1"> <div class="form-group"> <button class="btn btn-success" type="button" onclick="confirmNew(this)"> 确定 </button> </div> </div> </form> ` objTo.appendChild(divtest) } }, error: function (xhr, textStatus) { alert('网络异常') } }) } function confirmNew(that) { var pars = window.location.href.split('?')[1]; let labour_id = pars.split("=")[1]; let fe_id = $(that).parents("form.row").find(".select2").val(); let number = $(that).parents("form.row").find("input[name='quantity']").val(); console.log(fe_id); console.log(number); if(!number){ alert("请输入添加数量"); return ; } $.ajax({ url:"/labour/setLabourStorage", data:{ fe_id:fe_id, number:number, labour_id:labour_id }, success:function (data) { if (data.code == 200) { getLabourStorage(pars); } } }) } function getLabourStorage(pars) { $.ajax({ url: '/labour/storage', data: pars, success: function (data, textStatus) { if (data.code == 200) { var labourstorageListStr = template('labourstorageTemplate', data); $("#labourstragecontainter").html(labourstorageListStr); } else { alert(data.msg); } }, error: function (xhr, textStatus) { alert('网络异常') } }) } $(document).ready(function () { var pars = window.location.href.split('?')[1]; var labour_id = pars.split("=")[1]; console.log('参数:' + pars); //获取库存 getLabourStorage(pars); $.ajax({ url: '/labour/getdetail' + '?' + pars, success: function (data, textStatus) { console.log('get data: ' + JSON.stringify(data)) if (data.code == 200) { $("#labour_name").html(data.detail.labour_name); $("#labour_avatarUrl").attr('src', data.detail.labour_avatarUrl); //input 内容更新 } else if (data.code == 302) { window.location.href = data.href; } else { toastr.error(data.msg); } } }); //滤芯维修记录 $.ajax({ url: '/labour/maintenance' + '?' + pars, success: function (data, textStatus) { if (data.code == 200) { var maintenanceStr = template('maintenanceTemplate', data); $("#maintenance").html(maintenanceStr); } else { toastr.warning(data.msg); } } }) //配件维修记录 $.ajax({ url: '/labour/accmaintenance' + '?' + pars, success: function (data, textStatus) { if (data.code == 200) { var accmaintainStr = template('accmaintainTemplate', data); $("#accmaintain").html(accmaintainStr); } else { toastr.warning(data.msg); } } }) }); $(document).ready(function () { var pars = window.location.href.split('?')[1]; var labour_id = pars.split("=")[1]; $("#accmaintain").on("click", ".doitbtn-makesucess", function (that) { var accmaintain_id = $(this).data('accmaintain_id'); $.ajax({ url: '/accessories/setaccmaintainfinish', data: { accmaintain_id: accmaintain_id }, success: function (data) { if (data.code == 200) { toastr.success(data.msg); //getaccmaintain(window.location.href.split('?')[1]); setTimeout(() => { window.location.reload(); }, 1300); } else { toastr.error(data.msg); } }, error: function (error) { toastr.error('网络异常'); } }) }) $("#addQuantityBtn").on("click","",function (e) { let addRecord = $("#addRecord").val(); let addNumber = $("#addNumber").val(); console.log("addrecord:" + addRecord); console.log("addNumber:" + addNumber); $.ajax({ url: "/labour/addstorage", data:{ addRecord,addNumber,labour_id, fe_id: G_fe_id }, success:function (data) { if (data.code === 200) { toastr.success(data.msg); $("#addQuantityModal").modal("hide"); getLabourStorage(pars); }else { toastr.warning(data.msg); } }, error:function (err) { toastr.error("网络故障"); } }) }) });
f02364cb5578a0c9248583b61f40421787a42b45
[ "JavaScript", "Markdown" ]
24
JavaScript
losteracmer/wpcms
a64b0c511ce454f99c4ef2a546798c971fa08900
c9b79a3706eff40b4f0f29a108143505e3d6474b
refs/heads/master
<repo_name>ElectronicToast/NP-Compete<file_sep>/player.hpp #ifndef __PLAYER_H__ #define __PLAYER_H__ #include <iostream> #include "common.hpp" #include "board.hpp" using namespace std; // For random move AI #include <stdlib.h> #include <time.h> #include <algorithm> class Player { public: Player(Side side); ~Player(); Move *doMove(Move *opponentsMove, int msLeft); // Flag to tell if the player is running within the test_minimax context bool testingMinimax; Side playerSide; Side opponent; static const short heuristic_matrix[8][8]; Board * boardState; int alphaBetaScore(Board * board, Move * move, int alpha, int beta, int depth, Side side); int minimaxScore(Board * board, int depth, Side side); int getNaiveScore(Board * board, Move * m, Side side); int getMobilityScore(Board* board, Move * m, Side side); int getNumMoves(Board * board, Side side); vector <Move*> getPossibleMoves(Board* board, Side side); }; #endif <file_sep>/player.cpp #include "player.hpp" /* * Beep! - Ray */ /* * Hello! - Karthik */ #define USE_ABPRUNE true #define ABPRUNE_DEPTH 2 #define MINIMAX_DEPTH 2 #define STONES_WT 1 #define MOBILITY_WT -500 #define HEURISTIC_MAT_WT -1000 #define ENDGAME_STONES_WT -45 #define ENDGAME_MOBILITY_WT 0 #define ENDGAME_HEUR_MT_WT -1 /* * Constructor for the player; initialize everything here. The side your AI is * on (BLACK or WHITE) is passed in as "side". The constructor must finish * within 30 seconds. */ Player::Player(Side side) { if (USE_ABPRUNE) cerr << "Using alpha-beta pruning!" << endl; // Will be set to true in test_minimax.cpp. testingMinimax = false; // Set player and opponent sides playerSide = side; opponent = (side == BLACK) ? WHITE : BLACK; boardState = new Board(); } /* * Destructor for the player. */ Player::~Player() { } const short Player::heuristic_matrix[8][8] = {{120, -20, 20, 5, 5, 20, -20, 120}, {-20, -40, -5, -5, -5, -5, -40, -20}, {20, -5, 15, 3, 3, 15, -5, 20}, {5, -5, 3, 3, 3, 3, -5, 5}, {5, -5, 3, 3, 3, 3, -5, 5}, {20, -5, 15, 3, 3, 15, -5, 20}, {-20, -40, -5, -5, -5, -5, -40, -20}, {120, -20, 20, 5, 5, 20, -20, 120}}; /* * Compute the next move given the opponent's last move. Your AI is * expected to keep track of the board on its own. If this is the first move, * or if the opponent passed on the last move, then opponentsMove will be * nullptr. * * msLeft represents the time your AI has left for the total game, in * milliseconds. doMove() must take no longer than msLeft, or your AI will * be disqualified! An msLeft value of -1 indicates no time limit. * * The move returned must be legal; if there are no valid moves for your side, * return nullptr. */ Move *Player::doMove(Move *opponentsMove, int msLeft) { /* /////////////////////////////////////////////////// // RANDOM IMPLEMENTATION ////////////////////////// /////////////////////////////////////////////////// // Update internal board representation boardState->doMove(opponentsMove, opponent); // Make a random move vector<Move> possibleMoves; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { Move m(i, j); if (boardState->checkMove(&m, playerSide)) possibleMoves.push_back(m); } } if (possibleMoves.size() == 0) return nullptr; srand(time(NULL)); Move temp = possibleMoves[rand() % possibleMoves.size()]; Move * theMove = new Move(temp.getX(), temp.getY()); boardState->doMove(theMove, playerSide); return theMove; */ /////////////////////////////////////////////////// // HEURISTIC IMPLEMENTATION /////////////////////// /////////////////////////////////////////////////// /* boardState -> doMove(opponentsMove, opponent); if (!boardState->hasMoves(playerSide)) { return NULL; } Move * goodMove = NULL; int maxScore = -100; int currScore = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { Move * m = new Move(i, j); if (boardState->checkMove(m, playerSide)) { currScore = heuristic_matrix[i][j]; if (currScore > maxScore) { maxScore = currScore; goodMove = m; } else { delete m; } } } } boardState->doMove(goodMove, playerSide); return goodMove; */ /////////////////////////////////////////////////// // ALPHA-BETA IMPLEMENTATION ////////////////////// /////////////////////////////////////////////////// if (USE_ABPRUNE) { boardState -> doMove(opponentsMove, opponent); if (!boardState->hasMoves(playerSide)) return NULL; vector <Move *> possibleMoves = getPossibleMoves(boardState, playerSide); int score = 0; Move * goodMove = possibleMoves[0]; int maxScore = -10000000; if (possibleMoves.size() == 0) return NULL; else { for (unsigned int i = 1; i < possibleMoves.size(); i++) { score = alphaBetaScore(boardState, possibleMoves[i], -10000000, 10000000, ABPRUNE_DEPTH, playerSide); if (score > maxScore) { goodMove = possibleMoves[i]; maxScore = score; } } } for (unsigned int i = 0; i < possibleMoves.size(); i++) { if (possibleMoves[i] != goodMove) { delete possibleMoves[i]; } } boardState->doMove(goodMove, playerSide); return goodMove; } /////////////////////////////////////////////////// // MINIMAX IMPLEMENTATION ///////////////////////// /////////////////////////////////////////////////// if (testingMinimax) { boardState -> doMove(opponentsMove, opponent); if (!boardState->hasMoves(playerSide)) return NULL; vector <Move *> possibleMoves = getPossibleMoves(boardState, playerSide); int score = 0; Move * goodMove = possibleMoves[0]; int maxScore = getMobilityScore(boardState, goodMove, playerSide); if (possibleMoves.size() == 0) { return NULL; } else { for (unsigned int i = 1; i < possibleMoves.size(); i++) { score = minimaxScore(boardState, MINIMAX_DEPTH, playerSide); if (score > maxScore) { goodMove = possibleMoves[i]; maxScore = score; } } } for (unsigned int i = 0; i < possibleMoves.size(); i++) { if (possibleMoves[i] != goodMove) { delete possibleMoves[i]; } } boardState->doMove(goodMove, playerSide); return goodMove; } /////////////////////////////////////////////////// // HEURISTIC IMPLEMENTATION /////////////////////// /////////////////////////////////////////////////// else{ boardState -> doMove(opponentsMove, opponent); if (!boardState->hasMoves(playerSide)) { return NULL; } Move * goodMove = NULL; int maxScore = -100000; int currScore = 0; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { Move * m = new Move(i, j); if (boardState->checkMove(m, playerSide)) { Board * tempBoard = boardState->copy(); tempBoard->doMove(m, playerSide); currScore = (HEURISTIC_MAT_WT * heuristic_matrix[i][j]) + (STONES_WT * getNaiveScore(tempBoard, nullptr, playerSide)) + (MOBILITY_WT * getMobilityScore(tempBoard, nullptr, playerSide)); if (currScore > maxScore) { maxScore = currScore; goodMove = m; } else { delete m; } delete tempBoard; } } } boardState->doMove(goodMove, playerSide); return goodMove; } } int Player::alphaBetaScore(Board * board, Move * move, int alpha, int beta, int depth, Side side) { Board * newBoard = board->copy(); newBoard->doMove(move, side); Side other = (side == BLACK) ? WHITE : BLACK; vector <Move *> possibleMoves = getPossibleMoves(newBoard, other); int score = -10000000; int bestScore = 0; int cutoff = 5; int movesLeft = 64 - newBoard->numFreeSquares(); if (depth == 0) { if (movesLeft < cutoff) { score = ENDGAME_STONES_WT + ENDGAME_MOBILITY_WT + ENDGAME_HEUR_MT_WT; return score; } if(possibleMoves.size() == 0) { score = (HEURISTIC_MAT_WT * heuristic_matrix[move->x][move->y]) + (MOBILITY_WT * getMobilityScore(newBoard, nullptr, other)) + (STONES_WT * getNaiveScore(newBoard, nullptr, other)); delete newBoard; return score; } int minScore = 100000; for (unsigned int i = 0; i < possibleMoves.size(); i++) { score = (HEURISTIC_MAT_WT * heuristic_matrix[possibleMoves[i]->x] [possibleMoves[i]->y]) + (MOBILITY_WT * getMobilityScore(newBoard, nullptr, other)) + (STONES_WT * getNaiveScore(newBoard, nullptr, other)); if (score < minScore) minScore = score; } delete newBoard; return minScore; } // If it's our turn (last move was opponent's) if (side == opponent) { bestScore = -10000000; for (unsigned int i = 0; i < possibleMoves.size(); i++) { score = alphaBetaScore(newBoard, possibleMoves[i], alpha, beta, depth - 1, other); if (score > bestScore) bestScore = score; if (bestScore > alpha) alpha = bestScore; if (beta <= alpha) break; } } // If it's our opponent's turn (last move was ours) else { bestScore = 10000000; for (unsigned int i = 0; i < possibleMoves.size(); i++) { score = alphaBetaScore(newBoard, possibleMoves[i], alpha, beta, depth - 1, other); if (score < bestScore) bestScore = score; if (bestScore < beta) beta = bestScore; if (beta <= alpha) break; } } delete newBoard; return bestScore; } /* * Recursively computes the minimum score with minimax */ int Player::minimaxScore(Board * board, int depth, Side side){ vector <Move *> possibleMoves = getPossibleMoves(board, side); int score = 0; int bestScore = 0; //Side other = side==BLACK? WHITE:BLACK; // Base case - if we are at a terminal node of our tree, or // there are no possible moves, simply return the value of the heuristic if (depth == 0) { if(possibleMoves.size() == 0) return getMobilityScore(board, nullptr, side); int minScore = 100000; for (unsigned int i = 0; i < possibleMoves.size(); i++) { score = (HEURISTIC_MAT_WT * heuristic_matrix[possibleMoves[i]->x] [possibleMoves[i]->y]) + (MOBILITY_WT * getMobilityScore(board, nullptr, side)) + (STONES_WT * getNaiveScore(board, nullptr, side)); if (score < minScore) minScore = score; } return minScore; } // Recursive case else { // If the current player is us, try to maximize our minimum score if (playerSide == side) { bestScore = -100000; for (unsigned int i = 0; i < possibleMoves.size(); i++) { Board * tempBoard = board->copy(); tempBoard->doMove(possibleMoves[i], side); //score = (HEURISTIC_MAT_WT * heuristic_matrix[possibleMoves[i]->x] // [possibleMoves[i]->y]) + minimaxScore(tempBoard, depth - 1, opponent); score = minimaxScore(tempBoard, depth - 1, opponent); delete tempBoard; if (score > bestScore) bestScore = score; } } // Assume that the opponent will try to minimize our score else { bestScore = 100000; for (unsigned int i = 0; i < possibleMoves.size(); i++) { Board * tempBoard = board->copy(); tempBoard->doMove(possibleMoves[i], side); //score = (HEURISTIC_MAT_WT * heuristic_matrix[possibleMoves[i]->x] // [possibleMoves[i]->y]) + minimaxScore(tempBoard, depth - 1, playerSide); score = minimaxScore(tempBoard, depth - 1, opponent); delete tempBoard; if (score < bestScore) bestScore = score; } } } return bestScore; } /* * For a specified side and move, return the value of the * naive heuristic (number of own stones - number of opponent * stones) */ int Player::getNaiveScore(Board * board, Move * m, Side side){ Board * copyBoard = board->copy(); copyBoard->doMove(m, side); Side other = side==BLACK? WHITE:BLACK; int score = copyBoard->count(side) - copyBoard->count(other); delete copyBoard; return score; } int Player::getMobilityScore(Board * board, Move * m, Side side){ Board * copyBoard = board->copy(); copyBoard->doMove(m, side); Side other = side==BLACK? WHITE:BLACK; int score; // if (getNumMoves(copyBoard, side) + getNumMoves(copyBoard, other) != 0) // { // score = int(100 * ((float) (getNumMoves(copyBoard, side) - getNumMoves(copyBoard, other)))/((float) ((getNumMoves(copyBoard, side) + getNumMoves(copyBoard, other))))); // } // else // { // score = 0; // } int playerMoves = getNumMoves(copyBoard, side); int oppMoves = getNumMoves(copyBoard, other); if (playerMoves > oppMoves) { score = int(((float)(100) * playerMoves / ((float) playerMoves + oppMoves))); } else if (playerMoves < oppMoves) { score = -int(((float)(100) * playerMoves / ((float) playerMoves + oppMoves))); } else{ score = 0; } delete copyBoard; return score; } /* * For a specified side, return the number of possible moves in the * current game state */ int Player::getNumMoves(Board * board, Side side) { int moves = 0; if (board->hasMoves(side)) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { Move * move = new Move(i, j); if (board->checkMove(move, side)) moves++; delete move; } } } return moves; } /* * For a specified side, return a vector of all the possible moves * in the current game state */ vector <Move*> Player::getPossibleMoves(Board* board, Side side){ vector <Move*> possibleMoves = vector <Move*>(); if (board->hasMoves(side)) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { Move * move = new Move(i, j); if (board->checkMove(move, side)){ possibleMoves.push_back(move); } else{ delete move; } } } } return possibleMoves; }<file_sep>/README.txt 2017 Caltech CS 2 NP-Compete <NAME>, <NAME> 15 March 2017 ##### CONTRIBUTIONS ##### Over the past two weeks, we proceeded to complete each step of Part 1 of the assignment, in additionwrt to alpha-beta pruning, in concert. We discussed strategies and implementation details together, and worked on the actual code together. For Part 1, Karthik implemented the random and naive heuristic algorithms. We then experimented together with various constant-time heuristics (including the array of scores assigned to each square, and mobility) before implementing minimax. We separately wrote minimax implementations and then took the better one (Karthik's). We then each tested the implementation independently, verifying that the test case was successful and observing that minimax could beat SimplePlayer and ConstantTimePlayer more often than not. For Part 2, Ray wrote the alpha-beta-pruning implementation and devised the essence of the heuristic that we ended up using (weighted # stones + weighted mobility + weighted square value). Karthik then refined these weights from strategies that we discovered online, and implemented an endgame case within the alpha-beta-pruning method. We then tuned our AI separately to empirically find the best heuristics. ##### IMPROVEMENTS ##### To improve our AI for the tournament, we implemented an alpha-beta-pruning search based off of our previous minimax work. For the heuristic, we replaced the naive heuristic with a composite one calculated by adding weighted scores for the number of stones (the old naive heuristic), mobility, and a base heuristic value for each square on the board. Additionally, we added a simple endgame strategy by checking whether we are in the endgame (when the number of remaining squares is less than some cutoff threshold) and utilizing different weight values in such a case, where the number of stones we possess is heavily emphasized over mobility or inherent square heuristics.
c937f98a061a9eaa3e5970e078714380445858b0
[ "Text", "C++" ]
3
C++
ElectronicToast/NP-Compete
629769091d6967eaa5896d35d724f326a074d666
fa74be9f986f442f1083a78123050eb50012d147
refs/heads/master
<repo_name>mabaw/pancakeArt<file_sep>/Pancake/html/pancake/pancake.cpp #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "ext/standard/info.h" #include "php_pancake.h" #include <iostream> #include <string.h> #include <time.h> #include <opencv/cv.h> #include <opencv/highgui.h> //#include <core.h> //#include <contrib.hpp> //#include <highgui.hpp> using namespace cv; static zend_function_entry pancake_functions[] = { PHP_FE(to_pancake, NULL) {NULL, NULL, NULL} }; zend_module_entry pancake_module_entry = { #if ZEND_MODULE_API_NO >= 20010901 STANDARD_MODULE_HEADER, #endif PHP_PANCAKE_EXTNAME, pancake_functions, NULL, NULL, NULL, NULL, PHP_MINFO(pancake), #if ZEND_MODULE_API_NO >= 20010901 PHP_PANCAKE_VERSION, #endif STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_PANCAKE extern "C" { ZEND_GET_MODULE(pancake) } #endif /* {{{ PHP_MINIT_FUNCTION */ PHP_MINFO_FUNCTION(pancake) { php_info_print_table_start(); php_info_print_table_row(2, "pancake support", "enabled"); php_info_print_table_row(2, "pancake version", PHP_PANCAKE_VERSION); php_info_print_table_row(2, "OpenCV version", CV_VERSION); php_info_print_table_end(); } /* }}} */ static void php_pancake(INTERNAL_FUNCTION_PARAMETERS, int return_type) { char *file, *casc; char *outfile; long flen, clen, olen; if(zend_parse_parameters(3 TSRMLS_CC, "sss", &file, &flen, &outfile, &olen, &casc, &clen) == FAILURE) { RETURN_NULL(); } Mat image2 = imread(file); if (!image2.data) RETURN_FALSE; Mat image3; if( image2.cols > image2.rows ) { int dp = image2.cols - image2.rows; Mat(image2, Rect(dp/2, 0, image2.rows, image2.rows)).copyTo(image3); } else { int dp = image2.rows- image2.cols; Mat(image2, Rect(0, dp/2, image2.cols, image2.cols)).copyTo(image3); } Mat image; resize(image3, image, Size(400, 400)); Mat gryImg1; Mat gryImg2; Mat gryImg3; Mat canImg; GaussianBlur(image, image, Size(5, 5), 0, 0); Canny(image, canImg, 1000, 1500, 5); cvtColor(image, gryImg1, CV_BGR2GRAY); cvtColor(image, gryImg2, CV_BGR2GRAY); threshold(gryImg1, gryImg1, 250, 255, CV_THRESH_BINARY); threshold(gryImg2, gryImg2, 64, 255, CV_THRESH_BINARY); Mat resultImg; resultImg.create(400, 400, CV_8UC3); resultImg.setTo(0); for(int i = 0; i < image.rows; i++) { for(int j = 0; j < image.cols; j++) { if( gryImg1.at<uchar>(i, j) > 128 ) circle(resultImg, Point(j, i), 0, CV_RGB(0, 0, 0)); else if( gryImg2.at<uchar>(i, j) > 128 ) circle(resultImg, Point(j, i), 0, CV_RGB(255, 200, 50)); else circle(resultImg, Point(j, i), 2, CV_RGB(100, 63, 15), -1); } } for(int i = 0; i < image.rows; i++) { for(int j = 0; j < image.cols; j++) { if( canImg.at<uchar>(i, j) > 128 ) circle(resultImg, Point(j, i), 3, CV_RGB(63, 31, 15), -1); } } Mat bgImg = imread("bg.jpg"); std::vector<Point2f> p0; std::vector<Point2f> p1; p0.push_back(Point2f(0, 0)); p0.push_back(Point2f(400, 0)); p0.push_back(Point2f(400, 400)); p0.push_back(Point2f(0, 400)); p1.push_back(Point2f(320, 233)); p1.push_back(Point2f(544, 241)); p1.push_back(Point2f(564, 513)); p1.push_back(Point2f(266, 503)); Mat perImg; Mat perMat = getPerspectiveTransform(p0, p1); Mat maskImg = imread("mask.jpg", 0); //std::cout << "perMat : " << perMat << std::endl; warpPerspective(resultImg, perImg, perMat, Size(bgImg.cols, bgImg.rows)); threshold(perImg, gryImg1, 1, 255, CV_THRESH_BINARY); bgImg.copyTo(resultImg); perImg.copyTo(resultImg, gryImg1); threshold(maskImg, gryImg1, 250, 255, CV_THRESH_BINARY_INV); bgImg.copyTo(resultImg, gryImg1); //imshow("resultImg", resultImg); //imshow("gryImg1", gryImg1); imwrite( outfile, resultImg ); //waitKey(); } PHP_FUNCTION(to_pancake) { php_pancake(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } <file_sep>/Pancake/html/pancake/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( pancake ) find_package( OpenCV REQUIRED ) add_executable( pancake pancake.c ) target_link_libraries( pancake ${OpenCV_LIBS} )<file_sep>/Pancake/opencvproject/pancake/main.cpp #include <iostream> #include <string.h> #include <time.h> #include <core.hpp> #include <contrib.hpp> #include <highgui.hpp> void main() { cv::Mat image2 = cv::imread("input.jpg"); cv::Mat image3; if( image2.cols > image2.rows ) { int dp = image2.cols - image2.rows; cv::Mat(image2, cv::Rect(dp/2, 0, image2.rows, image2.rows)).copyTo(image3); } else { int dp = image2.rows- image2.cols; cv::Mat(image2, cv::Rect(0, dp/2, image2.cols, image2.cols)).copyTo(image3); } cv::Mat image; cv::resize(image3, image, cv::Size(400, 400)); cv::Mat gryImg1; cv::Mat gryImg2; cv::Mat gryImg3; cv::Mat canImg; cv::GaussianBlur(image, image, cv::Size(5, 5), 0, 0); cv::Canny(image, canImg, 1000, 1500, 5); cv::cvtColor(image, gryImg1, CV_BGR2GRAY); cv::cvtColor(image, gryImg2, CV_BGR2GRAY); cv::threshold(gryImg1, gryImg1, 250, 255, CV_THRESH_BINARY); cv::threshold(gryImg2, gryImg2, 64, 255, CV_THRESH_BINARY); cv::Mat resultImg; resultImg.create(400, 400, CV_8UC3); resultImg.setTo(0); for(int i = 0; i < image.rows; i++) { for(int j = 0; j < image.cols; j++) { if( gryImg1.at<uchar>(i, j) > 128 ) cv::circle(resultImg, cv::Point(j, i), 0, CV_RGB(0, 0, 0)); else if( gryImg2.at<uchar>(i, j) > 128 ) cv::circle(resultImg, cv::Point(j, i), 0, CV_RGB(255, 200, 50)); else cv::circle(resultImg, cv::Point(j, i), 2, CV_RGB(100, 63, 15), -1); } } for(int i = 0; i < image.rows; i++) { for(int j = 0; j < image.cols; j++) { if( canImg.at<uchar>(i, j) > 128 ) cv::circle(resultImg, cv::Point(j, i), 3, CV_RGB(63, 31, 15), -1); } } cv::Mat bgImg = cv::imread("bg.jpg"); std::vector<cv::Point2f> p0; std::vector<cv::Point2f> p1; p0.push_back(cv::Point2f(0, 0)); p0.push_back(cv::Point2f(400, 0)); p0.push_back(cv::Point2f(400, 400)); p0.push_back(cv::Point2f(0, 400)); p1.push_back(cv::Point2f(320, 233)); p1.push_back(cv::Point2f(544, 241)); p1.push_back(cv::Point2f(564, 513)); p1.push_back(cv::Point2f(266, 503)); cv::Mat perImg; cv::Mat perMat = cv::getPerspectiveTransform(p0, p1); cv::Mat maskImg = cv::imread("mask.jpg", 0); std::cout << "perMat : " << perMat << std::endl; cv::warpPerspective(resultImg, perImg, perMat, cv::Size(bgImg.cols, bgImg.rows)); cv::threshold(perImg, gryImg1, 1, 255, CV_THRESH_BINARY); bgImg.copyTo(resultImg); perImg.copyTo(resultImg, gryImg1); cv::threshold(maskImg, gryImg1, 250, 255, CV_THRESH_BINARY_INV); bgImg.copyTo(resultImg, gryImg1); //cv::imshow("resultImg", resultImg); //cv::imshow("gryImg1", gryImg1); cv::imwrite( "images/resultImg.jpg", resultImg ); cv::imwrite( "images/gryImg1.jpg", gryImg1 ); //cv::waitKey(); return 0; }<file_sep>/README.md # pancakeArt My web template for pancakeArt proj. <file_sep>/Pancake/html/upload.php <?php ini_set('display_errors', 1); error_reporting(~0); function LoadJpeg($imgname) { $im = @imagecreatefromjpeg($imgname); /* Attempt to open */ if (!$im) { /* See if it failed */ $im = imagecreate(150, 30); /* Create a blank image */ $bgc = imagecolorallocate($im, 255, 255, 255); $tc = imagecolorallocate($im, 0, 0, 0); imagefilledrectangle($im, 0, 0, 150, 30, $bgc); /* Output an errmsg */ imagestring($im, 1, 5, 5, "Error loading $imgname", $tc); } return $im; } //echo "hello"; $target_dir = ""; $count_pancakes = ("counter.txt"); $last_count = file($count_pancakes); //$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $target_file = $target_dir . basename("$last_count[0]".".jpg"); //echo "target_file = ".$target_file."<br>"; $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { //echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } //echo "aaaaa"; // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded to".$target_file; //echo " <br>$last_count[0]"."_out.jpg <br>"; $out = "$last_count[0]"."_out.jpg"; to_pancake($target_file,$out,'haarcascade_frontalface_alt.xml'); $im = LoadJpeg($out); header('Content-Type: image/jpeg'); imagejpeg($im); imagedestroy($im); $fp = fopen($count_pancakes , "w"); $last_count[0]++; fputs($fp , "$last_count[0]"); fclose($fp); } else { echo "The file ". basename( $_FILES["fileToUpload"]["name"]); echo $target_file; echo "Sorry, there was an error uploading your file."; } } ?><file_sep>/Pancake/opencvproject/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project( grayImage ) find_package( OpenCV REQUIRED ) add_executable( grayImage grayImage.cpp ) target_link_libraries( grayImage ${OpenCV_LIBS} )
cd454ccad27b8e7624fe4a61a32e59e9fa99a9a2
[ "Markdown", "CMake", "C++", "PHP" ]
6
C++
mabaw/pancakeArt
a6ddfbc88fe18cb73a64a5f3566a0184d63057f2
d502320b889244a57e80f6d6844e4586124df9ad
refs/heads/master
<file_sep>json.text @message.content json.image @message.image_url json.user_name @message.user.name json.date @message.created_at.strftime("%Y/%m/%d %H:%M") json.id @message.id <file_sep>json.array! @new_messages do |new_message| json.text new_message.content json.image new_message.image_url json.date new_message.created_at.strftime("%Y年%m月%d日 %H時%M分") json.user_name new_message.user.name json.id new_message.id end<file_sep>membersテーブル |Column|Type|Options| |------|----|-------| |user_id|references|null: false, foreign_key: true| |group_id|references|null: false, foreign_key: true| ### Association - belongs_to :group - belongs_to :user messagesテーブル |Column|Type|Options| |------|----|-------| |body|text|| |image|string|| |grounp_id|references|null: false, foreign_key: true| |user_id|references|null: false, foreign_key: true| ### Association - belongs_to: user - belongs_to: group usersテーブル |Column|Type|Options| |------|----|-------| |name|text|null: false, foreign_key: true| ### Association - has_many :messages - has_many :groups, through: :members - has_many :members groupsテーブル |Column|Type|Options| |------|----|-------| |name|text|null: false, foreign_key: true| ### Association - has_many :users, through: :members - has_many :messages - has_many :members
bd34a141ab0b9b0fc32355893a9f4915d4e677f2
[ "Markdown", "Ruby" ]
3
Ruby
Takabun/chat-space
f17ab80e0a2ad74dab8b3b1b9a2bfa4e3a5eac35
77f7dc4ff4f43ea6748586558ff642e3843c43a3
refs/heads/master
<repo_name>miakastina/Cryptography-ROT13_HASH_XOR<file_sep>/README.md # Cryptography-ROT13_HASH_XOR Cryptography ROT13_HASH_XOR <file_sep>/ROT13HashXOR.cpp //Created by <NAME> // NIM 2015-81-178 #include <iostream> #include <conio.h> #include <string.h> #include <math.h> using namespace std; void dec(unsigned char y) { cout<<" : "<<y<<"\t: "<<(int)y<<"\t\t"<<": "; } void binary(unsigned char x) { for (int i=7; i>=0; i--) { if(x >= pow(2,i)) { cout<<"1"; x = x - pow(2,i); } else cout<<"0"; } } void garis() { cout <<" ****************************************\n"; } void headerAwal() { cout<<" ........................................ \n"; cout<<" : PROGRAM ENKRIPSI DAN DESKRIPSI : \n"; cout<<" : MENGGUNAKAN METODE : \n"; cout<<" : ROT13, HASHING dan XOR : \n"; cout<<" ........................................ \n\n"; } void headerAscii() { cout<<" Tampilan Kode ASCII\n"; garis(); cout<<" : Char"<<"\t"<<":"<<" Decimal "<<"\t"<<":"<<" Binary "<<"\t"<<":\n"; garis(); } void headerProsesXOR() { cout<<" ============== PROSES XOR ==============\n"; cout<<" ============== ENKRIPSI ==============\n\n"; } void headerStlhEnkripsi() { cout<<" Pesan Setelah di Enkripsi \n"; cout<<" ========================================\n"; cout<<"\n"<<" "; } void headerProsesDeskripsi() { cout<<" ============Proses Deskripsi============\n"; cout<<" ========================================\n"; } void headerPD() { cout<<" Kode ASCII\n"; cout<<" Binary"<<"\t"<<" => "<<"Decimal"<<"\t"<<" => "<<"\t"<<"Char\n"; garis(); } void headerStlhDeskripsi() { cout <<" Pesan Setelah di Deskripsi \n"; cout <<" ========================================\n"; cout <<"\n"<<" "; } void CreatedBy() { char n[20]= {78,97,109,97,32,58,32,77,105,97,32,75,97,115,116,105,110,97}; char m[20]= {78,73,77,32,32,58,32,50,48,49,53,45,56,49,45,49,55,56}; int i; cout <<" ========================================\n\t"<<" "; for(i=0;i<=17;i++) { cout<<n[i]; } cout<<"\n\t"<<" "; for(i=0;i<=17;i++) { cout<<m[i]; } cout<<"\n"<<" ========================================\n"; } template <typename Iter> void rot13(Iter begin, const Iter& end) { while (begin != end) { unsigned char& c = *begin; if (c >= 'a' && c <= 'm') { c += 13; } else if (c >= 'n' && c <= 'z') { c -= 13; } else if (c >= 'A' && c <= 'M') { c += 13; } else if (c >= 'N' && c <= 'Z') { c -= 13; } ++begin; } } int main() { unsigned char pesan [100],kunci[100],enkripsi [100],deskripsi [100]; int panjang_data,panjang_data_kunci,i,j=0; unsigned int ascii[100],ascii_kunci [100],ascii_enkripsi [100],ascii_deskripsi [100]; headerAwal(); cout<<" SILAHKAN MASUKKAN PESAN\n"; cin.sync(); cout <<" Pesan = "; cin.get((char*)pesan,100); panjang_data = strlen ((char*)pesan); cout<<" Panjang Data Pesan = "<<panjang_data<<"\n\n"; headerAscii(); for (i=0; i<=panjang_data-1; i++) { ascii[i] = int (pesan[i]); dec(pesan[i]); binary(pesan[i]); cout<<"\t"<<":\n"; } garis(); cout<<endl; cout <<" SILAHKAN MASUKKAN KUNCI \n"; cin.sync(); cout <<" Kunci : "; cin.get((char*)kunci,100); panjang_data_kunci = strlen ((char*)kunci); cout<<" Panjang Data Kunci = "<<panjang_data_kunci<<"\n\n"; headerAscii(); for (i=0; i<=panjang_data_kunci-1; i++) { ascii_kunci[i] = kunci[i]; dec(kunci[i]); binary(kunci[i]); cout<<"\t"<<":\n"; } garis(); cout<<endl; cout<<" Hasil ROT13 = "; rot13(kunci, kunci + strlen((char*)kunci)); std::cout << kunci << std::endl; int hash = 1; for (int i = 0; i <=panjang_data_kunci-1; i++) { hash = 31 * hash + kunci[i]; } headerAscii(); for (i=0; i<=panjang_data_kunci-1; i++) { ascii_kunci[i] = hash; dec(kunci[i]); binary(kunci[i]); cout<<"\t"<<":\n"; } garis(); cout<<endl; cout<<" Kunci yang telah dihash : "<<hash<<endl<< " karakter \t: "<<char(hash)<<endl; cout<<" Binary \t: "; binary(int(hash)); cout<<"\n\n"; headerProsesXOR(); for (i=0; i<=panjang_data-1; i++) { cout<<" "; binary(pesan[i]); cout<<" "<<" XOR "<<" "; binary(int (hash)); cout<<" = "; ascii_enkripsi[i] = ascii[i] ^ ascii_kunci[j]; j = j + 1; if (j == panjang_data_kunci) { j = 0; } enkripsi [i] = int (ascii_enkripsi[i]); binary(enkripsi[i]); cout<<endl; cout<<"\t\t Decimal "<<" = "<<int(enkripsi[i])<<"\n" <<"\t\t Char "<<"\t = "<<enkripsi[i]<<endl; } cout<<endl; headerStlhEnkripsi(); for (i=0; i<=panjang_data-1; i++) { cout<<enkripsi[i]<<" "; } cout<<"\n\n\n"; headerProsesDeskripsi(); cout<<" *Pesan Enkripsi* \n"; headerPD(); for (i=0; i<=panjang_data-1; i++) { ascii_deskripsi[i] = enkripsi[i] ; cout <<" "; binary(enkripsi[i]); cout<<" => "<<int (enkripsi[i])<<" "<<"\t"<<" => " <<"\t"<<enkripsi [i]<< endl; } cout<<"\n\n"; cout<<" HASIL\n\n"; cout<<" *Pesan Deskripsi* \n"; headerPD(); for (i=0; i<=panjang_data_kunci-1; i++) { ascii_kunci[i] = hash; } garis(); for (i=0; i<=panjang_data-1; i++) { ascii_deskripsi[i] = ascii [i]; ascii_deskripsi[i] = enkripsi[i] ^ ascii_kunci[j]; j = j + 1; if (j == panjang_data_kunci) { j = 0; } deskripsi[i]= int(ascii_deskripsi[i]); cout<<" "; binary(deskripsi[i]); cout<<" => "<<int(deskripsi[i])<<" "<<"\t"<<" =>"<<"\t"<<deskripsi[i]<<endl; } cout <<endl; headerStlhDeskripsi(); for (i=0; i<=panjang_data-1; i++) { cout <<deskripsi[i]<<" " ; } cout<<endl<<endl; CreatedBy(); return 0; }
ac3e44b6fdb1c6ec3915890742581c91c24482a0
[ "Markdown", "C++" ]
2
Markdown
miakastina/Cryptography-ROT13_HASH_XOR
5c9cf5566d76dc0f9a459e797a47820f354b5791
fdaf84eb126f79627d61023ba250b0106b4e97db
refs/heads/master
<file_sep>EDIT-DISTANCE ============= PURPOSE ------- Finding two nearby strings. CONTENTS -------- 1. EditDistanceApp.java : The main hook to our app. We stay in an infinite loop waiting for the user to enter a word and we find the closests string that is available to us and display it on the terminal. 1. FeatureGenerator.java : Reads in the data file containing our dictionary words. Fills a list with all the words contained in the dictionary. If the original data is not clean, then we write all the cleaned words into a new file. 1. EditDistance.java : The algorithm EditDistance. COMPILE AND RUN --------------- ``` # if data is not clean javac EditDistance.java java EditDistance fakepath/<notclean_data_file> 0 # if data is clean javac EditDistance.java java EditDistance fakepath/<clean_data_file> ``` CREDITS ------- data from: Princeton University "About WordNet." WordNet. Princeton University. 2010. <http://wordnet.princeton.edu>. algorithm from: University Of Illinois at Urbana-Champaign, CS473- Fundamental Algorithms. <http://www.cs.illinois.edu/class/fa11/cs473/lec/09_lec.pdf>. <file_sep>mkdir bin # enter the file path for the data javac EditDistanceApp.java -d bin/ java -classpath bin/ EditDistanceApp /Users/efekarakus/Documents/myworkspace/edit-distance/data/index.noun 0
f7a5e6dd28c54aef5f9d1ffdbde2c868ae8350f4
[ "Markdown", "Shell" ]
2
Markdown
efekarakus/Edit-Distance
8a7d1354632cb5f2e0bfbfffc32e1bc76bf07085
dbdee5d33aaa8dff0d4c8ae6665dc8ae8dd65301
refs/heads/master
<repo_name>mohsinalimat/Scratchpad<file_sep>/Creational Patterns.playground/Pages/Prototype.xcplaygroundpage/Contents.swift //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" struct HondaWorkShop { public var city: String? { get { return _city } set { _city = newValue } } private var _city: String? private var compatibleCars: [String] private var owner : String init(city: String? = nil, compatibleCars: [String], owner: String) { self.compatibleCars = compatibleCars self.owner = owner self.city = city } public func clone() -> HondaWorkShop { return HondaWorkShop(city: self.city, compatibleCars: self.compatibleCars, owner: self.owner) } } let harald = "Harald" // Harald has more than 1 Workshop and every workshop has the same comptatible cars let prototype = HondaWorkShop(compatibleCars: ["Civic","Accord","CRX"], owner: harald) var workShopAmsterdam = prototype.clone() workShopAmsterdam.city = "Amsterdam" var workShopNewYork = prototype.clone() workShopNewYork.city = "New York" <file_sep>/Behavioral-Design-Patterns.playground/Pages/Chain of Responsibilty .xcplaygroundpage/Contents.swift //: [Previous](@previous) /// # Chain of Responsibilty import Foundation <file_sep>/Creational Patterns.playground/Pages/Factory Method.xcplaygroundpage/Contents.swift //: [Previous](@previous) import Foundation protocol Currency { func symbol() -> String func code() -> String } class Euro : Currency { func symbol() -> String { return "€" } func code() -> String { return "EUR" } } class Dollar : Currency { func symbol() -> String { return "$" } func code() -> String { return "US" } } enum Country { case US,UK, Greece } enum CurrencyFactory { static func currencyForCountry(country: Country) -> Currency? { switch country { case .Greece,.UK : return Euro() case .US: return Dollar() default return nil } } } let currencyCodeForUK = CurrencyFactory.currencyForCountry(country: .UK)?.code() <file_sep>/Creational Patterns.playground/Pages/Singleton.xcplaygroundpage/Contents.swift //: [Previous](@previous) import Foundation struct TheOnlyOne { public static var sharedInstance = TheOnlyOne() private init() { // Needs to be private so you can ensure that only one Instance is created } } //: [Next](@next) <file_sep>/Creational Patterns.playground/Pages/Builder.xcplaygroundpage/Contents.swift //: [Previous](@previous) import Foundation class Builder { var x: Double? var y: Double? var z: Double? typealias BuilderClosure = (Builder) -> () init(closure:BuilderClosure) { closure(self) } } struct ThingToBuild: CustomStringConvertible { let x : Double let y : Double let z : Double init?(builder: Builder) { if let x = builder.x, y = builder.y, z = builder.z { self.x = x self.y = y self.z = z } else { return nil } } var description:String { return "Death Star at (x:\(x) y:\(y) z:\(z))" } } let testBuilder = Builder { builder in builder.x = 10 builder.y = 20 builder.z = 30 } let instance = ThingToBuild(builder: testBuilder) //: [Next](@next) <file_sep>/Behavioral-Design-Patterns.playground/Pages/Introduction.xcplaygroundpage/Contents.swift //: [Previous](@previous) /* Behavioral design patterns are design patterns that identify common communication patterns increase flexibility by encapsulating this communication. */ //: [Next](@next)
d556cafdef9cd55e75ed9b0a0a873ff64972c9e7
[ "Swift" ]
6
Swift
mohsinalimat/Scratchpad
7b2880832cacb2db289466ace18884da282dc86d
9dadfb5cca292f6b8818b32a1b1bcf494818d36a
refs/heads/main
<repo_name>gediminasurvila/logrocket-vue3<file_sep>/src/routes/index.js export default [ { path: "/", name: "home", component: () => import("@/views/Home.vue"), }, { path: "/jokes", name: "jokes", component: () => import("@/views/Joke.vue"), }, { path: "/counter", name: "counter", component: () => import("@/views/Counter.vue"), }, ]; <file_sep>/src/main.js import { createApp } from "vue"; import { createRouter, createWebHistory} from 'vue-router'; import store from "@/store"; import routes from "@/routes"; import App from "./App.vue"; const router = createRouter({ history: createWebHistory(), routes, }) const app = createApp(App); app.use(router); app.use(store); app.mount("#app");
55350194dc4de09adcafbbc7d04c493f84bc47fa
[ "JavaScript" ]
2
JavaScript
gediminasurvila/logrocket-vue3
28467253fce64588e4b8510b5ee5904fb753cf1b
e28f49f5b9e0c8c3f3451a7b61216bf0f682e939
refs/heads/master
<repo_name>ajohnsonhogan/Mem-SwampHacks-2019<file_sep>/index.js const express = require('express'); const fileUpload = require('express-fileupload'); const mongoose = require('mongoose'); const _request = require('request'); const fs = require('fs'); const person_group_id = 'mem-swamphacks-19'; require('./models'); const bodyParser = require('body-parser'); var mongoDB = 'mongodb://localhost/db'; mongoose.connect(mongoDB); mongoose.Promise = global.Promise; var db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:true})); app.use(fileUpload()); app.get('/', (request, result) => {result.status(200).send('HERRO!')}) app.post('/update', (req,res)=>{mongoose.model('Person').update({name:req.body.name}, {instagramPicUrl:req.body.pictureUrl}).exec((error)=>{if(error){console.log(error)}});res.status(200).send('')}); app.post('/upload', (request, result) => { try{ // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file var sampleFile = Buffer.from(request.body.image, 'base64'); console.log(sampleFile); _request.post({ url: 'https://centralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true', body: sampleFile, headers: { 'Ocp-Apim-Subscription-Key': '<KEY>', 'Content-Type': 'application/octet-stream' } }, (error, response, body) => { console.log(body); let json = JSON.parse(body); _request.post({ url: 'https://centralus.api.cognitive.microsoft.com/face/v1.0/identify', json: { "faceIds": [json[0].faceId], "personGroupId": person_group_id }, headers: { 'Ocp-Apim-Subscription-Key': '<KEY>', 'Content-Type': 'application/json' } }, (error, response, body) => { let canidates = body[0].candidates; console.log(canidates); if (canidates.length){ mongoose.model('Person').find({personId: canidates[0].personId}).exec((error, person) => { result.json(person); }); } else { result.json({}); } }); }); } catch (error) { console.log(error); result.json({}); } }); app.post('/addface', (request, result) => { console.log(request.body) _request.post({ url: `https://centralus.api.cognitive.microsoft.com/face/v1.0/persongroups/${person_group_id}/persons`, json: { "name": request.body.name, }, headers: { 'Ocp-Apim-Subscription-Key': '<KEY>', 'Content-Type': 'application/json' } }, (error, response, body) => { let personId = body.personId; let pictureUrl = request.body.pictureUrl; _request.post({ url: 'https://centralus.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true', json: {url: pictureUrl}, headers: { 'Ocp-Apim-Subscription-Key': '<KEY>' } }, (error, response, body) => { _request.post({ url: `https://centralus.api.cognitive.microsoft.com/face/v1.0/persongroups/${person_group_id}/persons/${personId}/persistedFaces`, json: {url: pictureUrl}, headers: { 'Ocp-Apim-Subscription-Key': '<KEY>', 'Content-Type': 'application/json' } }, (error, response, body) => { mongoose.model('Person')({ personId: personId, instagramLink: request.body.instagram, name: request.body.name, email: request.body.email, hearAbout: request.body.hearAbout, phoneNumber: request.body.phone, race: request.body.race, instagramPicUrl: pictureUrl }).save((error)=>{if(error){result.status(403)}else{result.status(200).send(body);}}); }); }); }); }); app.listen(80); process.on('uncaughtException', function (err) { console.log('Caught exception: ', err); });
3e6e9b64fd16df4036e8c09f26befac0e2a27f16
[ "JavaScript" ]
1
JavaScript
ajohnsonhogan/Mem-SwampHacks-2019
326c65caec65f023f40487e2b983ade7bc624082
e5c2e5b261bda2be5c3eee8bdb98129456e6c6be
refs/heads/master
<repo_name>Teplitsa/vse.to<file_sep>/modules/shop/deliveries/classes/form/backend/delivery/properties.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Delivery_Properties extends Form_Backend { /** * @var Model_Delivery */ protected $_delivery; /** * @var Model_Order */ protected $_order; /** * Create form * * @param Model_Delivery $delivery * @param Model_Order $order * @param string $name */ public function __construct(Model_Delivery $delivery = NULL, Model_Order $order = NULL, $name = NULL) { $this->delivery($delivery); $this->order($order); parent::__construct($delivery, $name); } /** * Get/set delivery * * @param Model_Delivery $delivery * @return Model_Delivery */ public function delivery(Model_Delivery $delivery = NULL) { if ($delivery !== NULL) { $this->_delivery = $delivery; } return $this->_delivery; } /** * Get/set order * * @param Model_Order $order * @return Model_Order */ public function order(Model_Order $order = NULL) { if ($order !== NULL) { $this->_order = $order; } return $this->_order; } } <file_sep>/application/views/pagination_load.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (($pages_count < 2) || ($pages_count<=$page)) { return; } ?> <div class="b-show-more"> <?php $next = (int)$page+1; echo '<a href="' . URL::self(array($page_param => $next), $ignored_params) . '">'.'подгрузить еще'.'</a>'; ?> </div> <file_sep>/modules/system/tasks/classes/task.php <?php defined('SYSPATH') or die('No direct script access.'); abstract class Task { /** * Task name * @var string */ protected $_name; /** * Default values for task parameteres * @var array */ protected $_default_params = array(); /** * @var Log */ protected $_log; /** * Construct task */ public function __construct() { // Determinte task name by class name $name = strtolower(get_class($this)); if (strpos($name, 'task_') === 0) { $name = substr($name, strlen('task_')); } $this->_name = $name; // Create task log $this->_log = TaskManager::log($name); } /** * Get task name * * @return string */ public function get_name() { return $this->_name; } /** * Set task value * * @param string $key * @param mixed $value */ public function set_value($key, $value) { TaskManager::set_value($this->get_name(), $key, $value); } /** * Get task value * * @param string $key * @return mixed */ public function get_value($key) { return TaskManager::get_value($this->get_name(), $key); } /** * Unset task value * * @param string $key */ public function unset_value($key) { TaskManager::unset_value($this->get_name(), $key); } /** * Update task progress * * @param float $progress */ public function set_progress($progress) { $this->set_value('progress', $progress); } /** * Update task status info * * @param string $status_info */ public function set_status_info($status_info) { $this->set_value('status_info', $status_info); } /** * Get / set task default parameters * * @param array $default_params * @return array */ public function default_params(array $default_params = NULL) { if ($default_params !== NULL) { $this->_default_params = $default_params; } else { return $this->_default_params; } } /** * Get the task parameter value * * @param string $name * @param mixed $default * @return mixed */ public function param($name, $default = NULL) { if (isset($_GET[$name])) { return $_GET[$name]; } elseif (isset($this->_default_params[$name])) { return $this->_default_params[$name]; } else { return $default; } } /** * Get the task parameters value * * @param array params * @return mixed */ public function params(array $params) { foreach ($params as $param) { $data[$param] = $this->param($param); } return $data; } /** * Add message to tasg log * * @param integer $level * @param string $message */ public function log($message, $level = Log::INFO) { $this->_log->message($message, $level); } /** * Run the task */ abstract public function run(); }<file_sep>/modules/shop/orders/classes/model/cartproduct.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_CartProduct extends Model { /** * Log model changes * @var boolean */ public $backup = TRUE; /** * Default product price * * @return float */ public function default_price() { return new Money(); } /** * Default product quantity * * @return integer */ public function default_quantity() { return 1; } /** * Set cartproduct price * * @param Money $price */ public function set_price(Money $price) { $this->_properties['price'] = clone $price; } /** * Get cartproduct price * * @return Money */ public function get_price() { if ( ! isset($this->_properties['price'])) { $this->_properties['price'] = $this->default_price(); } return clone $this->_properties['price']; } /** * Create product in cart from actual catalog product * * @param Model_Product $product */ public function from_product(Model_Product $product) { $this->product_id = $product->id; $this->marking = $product->marking; $this->caption = $product->caption; $this->price = clone $product->price; $this->product = $product->properties(); } /** * Return fly instance of the corresponding catalog product * * @return Model_Product */ public function get_product() { $product = Model::fly('Model_Product'); if ( ! empty($this->_properties['product']) && is_array($this->_properties['product'])) { $product->init($this->_properties['product']); } return $product; } /** * Get order this product belongs to * * @return Model_Order */ public function get_order() { if ( ! isset($this->_properties['order'])) { $order = new Model_Order(); $order->find((int) $this->cart_id); $this->_properties['order'] = $order; } return $this->_properties['order']; } // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- /** * Save model and log changes * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); // Recalculate order summaries by saving it $this->order->save(FALSE, FALSE); $this->log_changes($this, $this->previous()); } /** * Delete orderproduct */ public function delete() { $id = $this->id; //@FIXME: It's more correct to log AFTER actual deletion, but after deletion we have all model properties reset $this->log_delete($this); parent::delete(); // Recalculate order summaries Model_Order::recalculate_summaries($id); } /** * Log order product changes * * @param Model_CartProduct $new_orderproduct * @param Model_CartProduct $old_orderproduct */ public function log_changes(Model_CartProduct $new_orderproduct, Model_CartProduct $old_orderproduct) { $fields = array( array('name' => 'caption', 'caption' => 'Статус'), array('name' => 'quantity', 'caption' => 'Количество') ); $text = ''; $created = ! isset($old_orderproduct->id); $has_changes = FALSE; if ($created) { $text .= '<strong>Добавлен товар в заказ № {{id-' . $new_orderproduct->cart_id . "}}</strong>\n"; } else { $text .= '<strong>Изменён товар "' . HTML::chars($new_orderproduct->caption) . '" в заказе № {{id-' . $new_orderproduct->cart_id . "}}</strong>\n"; } // Log field changes foreach ($fields as $field) { $name = $field['name']; $displayed = isset($field['displayed']) ? $field['displayed'] : $name; $caption = $field['caption']; if ($created) { $text .= Model_History::changes_text($caption, $new_orderproduct->$displayed); } elseif ($old_orderproduct->$name != $new_orderproduct->$name) { $text .= Model_History::changes_text($caption, $new_orderproduct->$displayed, $old_orderproduct->$displayed); $has_changes = TRUE; } } // ----- price if ($created) { $text .= Model_History::changes_text('Цена', $new_orderproduct->price); } elseif ($old_orderproduct->price->amount != $new_orderproduct->price->amount) { $text .= Model_History::changes_text('Цена', $new_orderproduct->price, $old_orderproduct->price); $has_changes = TRUE; } if ($created || $has_changes) { // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $new_orderproduct->cart_id; $history->item_type = 'order'; $history->save(); } } /** * Log the deletion of orderproduct * * @param Model_CartProduct $orderproduct */ public function log_delete(Model_CartProduct $orderproduct) { $text = 'Удалён товар ' . $orderproduct->caption . ' из заказа № {{id-' . $orderproduct->cart_id . '}}'; // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $orderproduct->cart_id; $history->item_type = 'order'; $history->save(); } }<file_sep>/modules/shop/acl/views/frontend/forms/register.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div id="regModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Регистрация</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <br> <label for="email"><?php echo $form->get_element('email')->render_input(); ?></label> <label for="pass"><?php echo $form->get_element('password')->render_input(); ?></label> <label for="pass_"><?php echo $form->get_element('password2')->render_input(); ?></label> <?php echo $form->get_element('email')->render_input(); ?> <?php echo $form->get_element('organizer_id')->render_input(); ?> <?php echo $form->get_element('organizer_name')->render_input(); ?> <?php echo $form->get_element('town_id')->render_input(); ?> <?php echo $form->get_element('group_id')->render_input(); ?> <?php $update_url = URL::to('frontend/acl/users/control', array('action'=>'create')); ?> <p class="foget-pass"><a href="<?php echo $update_url ?>">Зарегистрироваться как представитель?</a></p> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_register')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div><file_sep>/modules/backend/views/layouts/backend/default.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><?php echo HTML::chars($view->placeholder('title')); ?></title> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <meta http-equiv="Keywords" content="<?php echo HTML::chars($view->placeholder('keywords')); ?>" /> <meta http-equiv="Description" content="<?php echo HTML::chars($view->placeholder('description')); ?>" /> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/forms.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/tables.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend_ie8.css', NULL, FALSE, 'if lte IE 8'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend_ie6.css', NULL, FALSE, 'if lte IE 6'); ?> <?php echo $view->placeholder('styles'); ?> <?php echo $view->placeholder('scripts'); ?> </head> <body> <!-- bocker --> <div id="blocker"></div> <!-- header --> <div class="header"> <?php echo Widget::render_widget('acl', 'logout'); ?> <!-- sites_menu --> <?php echo Widget::render_widget('sites', 'menu'); ?> <!-- top_menu --> <?php echo Widget::render_widget('menu', 'menu', 'main', 'backend/menu/top_menu'); ?> </div> <!-- main --> <div class="payload"> <!-- top_submenu --> <?php echo Widget::render_widget('menu', 'menu', 'main', 'backend/menu/top_submenu', 1); ?> <?php echo Widget::render_widget('menu', 'menu', 'sidebar', 'backend/menu/top_submenu', 1); ?> <!-- layout --> <table class="layout"><tr> <!-- main --> <td class="main"> <div class="workspace"> <div class="workspace_caption"> <?php echo Widget::render_widget('menu', 'breadcrumbs', 'main'); ?> <?php if (isset($caption)) echo HTML::chars($caption); ?> </div> <?php echo Widget::render_widget('index', 'flashmessages'); ?> <?php echo $content; ?> </div> </td> </tr></table><!-- layout --> </div><!-- main --> <!-- footer --> <div class="footer"></div> <?php if (Kohana::$profiling) { //echo View::factory('profiler/stats')->render(); } ?> </body> </html> <file_sep>/modules/system/history/classes/controller/backend/history.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_History extends Controller_Backend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('history') . '/public/css/backend/history.css'); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->caption = 'Журнал'; $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Index action - renders the history */ public function action_index() { $this->request->response = $this->render_layout($this->widget_history()); } /** * Renders history * * @return string */ public function widget_history() { $per_page = 10; $history = Model::fly('Model_History'); $item_type = $this->request->param('item_type'); if ($item_type != '') { $count = $history->count_by_item_type($item_type); $pagination = new Pagination($count, $per_page); $entries = $history->find_all_by_item_type($item_type, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => 'created_at', 'desc' => TRUE )); } else { $count = $history->count(); $pagination = new Pagination($count, $per_page); $entries = $history->find_all($item_type, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => 'created_at', 'desc' => TRUE )); } // Set up view $view = new View('backend/history'); $view->entries = $entries; $view->pagination = $pagination; return $view->render(); } }<file_sep>/modules/general/tags/classes/model/tag/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Tag_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('name', array('Type' => 'varchar(63)', 'Key' => 'INDEX')); $this->add_column('alias', array('Type' => 'varchar(63)', 'Key' => 'INDEX')); $this->add_column('owner_type', array('Type' => 'varchar(15)', 'Key' => 'INDEX')); $this->add_column('owner_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('weight', array('Type' => 'int unsigned', 'Key' => 'INDEX')); } /** * Move tag one position up * * @param Model $model * @param Database_Expression_Where $condition */ public function up(Model $model, Database_Expression_Where $condition = NULL) { parent::up($model, DB::where('owner_type', '=', $model->owner_type)->and_where('owner_id', '=', $model->owner_id)); } /** * Move tag one position down * * @param Model $model * @param Database_Expression_Where $condition */ public function down(Model $model, Database_Expression_Where $condition = NULL) { parent::down($model, DB::where('owner_type', '=', $model->owner_type)->and_where('owner_id', '=', $model->owner_id)); } /** * Find all tags by part of the name * * @param Model $model * @param string $name * @param array $params * @return Models */ public function find_all_like_name(Model $model, $name, array $params = NULL) { $table = $this->table_name(); $query = DB::select_array(array('name')) ->distinct('whatever') ->from($table) ->where('name', 'LIKE', "$name%"); return $this->find_all_by($model, NULL, $params, $query); } }<file_sep>/application/classes/modules.php <?php defined('SYSPATH') or die('No direct script access.'); /** * CMS modules manager * * @package Eresus * @author <NAME> (<EMAIL>) */ class Modules { /** * Modules uri cache * @var array */ protected static $_uris; /** * Return path to module or FALSE if module was not registered * * @param string $module Module name * @return string */ public static function path($module) { $modules = Kohana::modules(); if ( ! isset($modules[$module])) return FALSE; return $modules[$module]; } /** * Return URI to module * * @param string $module * @return string|boolean */ public static function uri($module) { if ( ! isset(self::$_uris[$module])) { $path = Modules::path($module); if ($path === FALSE) return FALSE; self::$_uris[$module] = File::uri($path); } return self::$_uris[$module]; } /** * Has the specified module been registrered? * * @param string $module * @return boolean */ public static function registered($module) { $modules = Kohana::modules(); return (isset($modules[$module])); } /** * Load module config * Try to load from database config and fall back to file config on failure * * @param string $db_config_group * @param string $file_config_group * @return array | FALSE */ public static function load_config($db_config_group, $file_config_group = NULL) { // First try to read site-specific config from database $reader = new Config_Database(); $config = $reader->load($db_config_group); if ($config !== FALSE) { $config = (array) $config; } elseif ($file_config_group !== NULL) { // Try to read default config from file $reader = new Kohana_Config_File(); $config = $reader->load($file_config_group); if ($config !== FALSE) { $config = (array) $config->as_array(); } else { $config = FALSE; } } else { $config = FALSE; } return $config; } /** * Save module config to database * * @param string $db_config_group * @param array $values */ public static function save_config($db_config_group, $values) { if (empty($values)) { return; } $reader = new Config_Database(); $config = $reader->load($db_config_group); if ($config === FALSE) { $config = $reader->load($db_config_group, array()); } foreach ($values as $k => $v) { // offsetSet is overloaded in Config_Dataabase so that the following // assignment acuatally writes values to database $config[$k] = $v; } } final private function __construct() { // This is a static class } }<file_sep>/modules/general/twig/classes/twig/loader/kohana.php <?php defined('SYSPATH') or die('No direct script access.'); /** * A Twig template loader with support of kohana transparent file system */ class Twig_Loader_Kohana implements Twig_LoaderInterface { /** * Gets the source code of a template, given its name. * * @param string $name string The name of the template to load * @return string The template source code */ public function getSource($name) { return file_get_contents($this->findTemplate($name)); } /** * Gets the cache key to use for the cache for a given template name. * * @param string $name string The name of the template to load * @return string The cache key */ public function getCacheKey($name) { return $this->findTemplate($name); } /** * Returns true if the template is still fresh. * * @param string $name The template name * @param timestamp $time The last modification time of the cached template */ public function isFresh($name, $time) { return filemtime($this->findTemplate($name)) < $time; } /** * Find a template file with given name by using Kohana::find_file. * * @param string $name * @return string */ protected function findTemplate($name) { $path = Kohana::find_file('templates', $name, 'html'); if ($path === FALSE) { throw new RuntimeException(sprintf('Unable to find template "%s".', "$name.html")); } return $path; } }<file_sep>/modules/frontend/classes/controller/frontend.php <?php defined('SYSPATH') OR die('No direct access allowed.'); /** * Frontend controller * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Controller_Frontend extends Controller { /** * @return boolean */ public function before() { // Site is required for frontend application if (Model_Site::current()->id === NULL) { $this->_action_404('Портал не найден'); return FALSE; } $request = Request::current(); if (!method_exists($this, 'action_'.$request->action)) { $this->_action_404('Страница не найдена'); return FALSE; } if (Modules::registered('acl')) { $privilege_name = Model_Privilege::privilege_name($this->request); if ($privilege_name && !Auth::granted($privilege_name)) { $this->_action_404('Доступ запрещен'); return FALSE; } $user = Auth::instance()->get_user(); //$timezone = isset($user->town->timezone)? $user->town->timezone: 'Europe/Moscow'; $timezone = 'Europe/Moscow'; date_default_timezone_set($timezone); } // Breadcrumbs $history = TRUE; $i = 0 ; $controllers = array(); while ($history) { if ($i == 0) { // First - take history from the current url $history = $request->param('history'); } else { // Parse route to retrieve the history param list($name, $request_params) = URL::match($history); if (isset($request_params['history'])) { $history = $request_params['history']; } else { $history = NULL; } } $i++; if ($history !== NULL) { list($name, $request_params) = URL::match($history); if (isset($request_params['controller'])) { $controllers[] = array($request_params['controller'],$request_params); } } } $controllers = array_reverse($controllers); foreach ($controllers as $controller_info) { list($controller,$request_params) = $controller_info; $request->get_controller($controller)->add_breadcrumbs($request_params); } $request->get_controller($request->controller)->add_breadcrumbs(); return TRUE; } /** * Creates and prepares layout to be used for frontend controller * * @return Layout */ public function prepare_layout($layout_script = NULL) { $node = Model_Node::current(); if ($this->request->in_window()) { $layout_script = 'layouts/window'; } if ($layout_script === NULL) { if (isset($node->layout)) { // Selected layout from current node $layout_script = 'layouts/' . $node->layout; } else { $layout_script = 'layouts/default'; } } $layout = parent::prepare_layout($layout_script); // Add meta tags for current node if ($node->id !== NULL) { if ( ! isset($layout->caption)) { $layout->caption = $node->caption; } if ($node->meta_title != '') { $layout->add_title($node->meta_title); } else { $layout->add_title($node->caption); } $layout->add_description($node->meta_description); $layout->add_keywords($node->meta_keywords); } // Add standart javascripts for widgets Widget::add_scripts(); jQuery::add_scripts(); // Add standart js scripts $layout->add_script(Modules::uri('frontend') . '/public/js/bootstrap.min.js'); //$layout->add_script('http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'); $layout->add_script(Modules::uri('frontend') . '/public/js/jquery.preimage.js'); $layout->add_script( '$(document).ready(function() {$('."'.file').preimage(); });" , TRUE); // // Render flash messages // $layout->messages = ''; // foreach (FlashMessages::fetch_all() as $message) // { // $layout->messages .= View_Helper::flash_msg($message['text'], $message['type']); // } return $layout; } /** * Render 404 error * * @param string $message */ protected function _action_404($message = 'Указанный путь не найден') { $ctrl_errors = $this->request->get_controller('Controller_Errors'); $ctrl_errors->action_error($this->request->uri, 404, $message); } public function add_breadcrumbs(array $request_params = array()) { } }<file_sep>/application/views/layouts/errors/404.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require('_header_new.php'); ?> <body> <header> <div class="mainheader"> <div class="container"> <div class="row"> <div class="span2"> <a href="<?php echo URL::site()?>" class="logo pull-left"></a> </div> <div class="span6"> <?php echo Widget::render_widget('menus','menu', 'main'); ?> </div> <div class="span4"> <div class="b-auth-search"> <?php echo Widget::render_widget('products', 'search');?> </div> </div> </div> </div> </div> <div class="subheader"> <div class="container"> <div class="row"> <div class="span2"> </div> <div class="span6"> <ul class="second-menu"> <?php echo Widget::render_widget('towns','select'); ?> <?php echo Widget::render_widget('products','format_select'); ?> <?php echo Widget::render_widget('products','theme_select'); ?> <?php echo Widget::render_widget('products','calendar_select'); ?> </ul> </div> <div class="span4"> <div class="login-form"> <?php echo Widget::render_widget('acl', 'login'); ?> </div> </div> </div> </div> </div> </header> <div id="main"> <div class="container"> <div class="row"> <div class="span12" id="page"> <!-- <div class="wrapper"> --> <div class="row-fluid"> <div class="span3"> <?php echo HTML::image('public/data/img/logo.svg',array('class' =>'big-logo'))?> <!-- <div class="soc-link"> <a href="#" class="button fb">f</a> <a href="#" class="tw button ">t</a> <a href="#" class="button vk">v</a> </div>--> </div> <div class="span1">&nbsp;</div> <div class="span7 content"> <h1>404 - ошибка</h1> <p>Такой страницы не существует. Но у нас есть много других страниц,</p> <p>например, <a href="<?php echo URL::site()?>">список</a> оффлайновых событий и телемостов в разных городах</p> <div class="" style="height: 400px;"></div> </div> <div class="span1">&nbsp;</div> </div> <!-- </div> --> </div> </div> </div> </div> <!-- /#main --> <?php require('_footer.php'); ?> <?php echo $view->placeholder('modal'); ?> <!-- Reformal --> <script type="text/javascript"> var reformalOptions = { project_id: 184340, project_host: "vseto.reformal.ru", tab_orientation: "left", tab_indent: "50%", tab_bg_color: "#a93393", tab_border_color: "#FFFFFF", tab_image_url: "http://tab.reformal.ru/T9GC0LfRi9Cy0Ysg0Lgg0L%252FRgNC10LTQu9C%252B0LbQtdC90LjRjw==/FFFFFF/2a94cfe6511106e7a48d0af3904e3090/left/1/tab.png", tab_border_width: 0 }; (function() { var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'media.reformal.ru/widgets/v3/reformal.js'; document.getElementsByTagName('head')[0].appendChild(script); })(); </script><noscript><a href="http://reformal.ru"><img src="http://media.reformal.ru/reformal.png" /></a><a href="http://vseto.reformal.ru">Oтзывы и предложения для vse.to</a></noscript> </body> <file_sep>/modules/shop/area/classes/model/town/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Town_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('name', array('Type' => 'varchar(63)')); $this->add_column('alias', array('Type' => 'varchar(63)')); $this->add_column('phonecode', array('Type' => 'varchar(31)')); $this->add_column('timezone', array('Type' => 'varchar(31)')); $this->add_column('lat', array('Type' => 'double')); $this->add_column('lon', array('Type' => 'double')); } }<file_sep>/modules/system/database_eresus/classes/dbtable/config.php <?php defined('SYSPATH') or die('No direct script access.'); class DbTable_Config extends DbTable { protected $_columns = array( 'group_name' => array('Type' => 'varchar(63)'), 'config_key' => array('Type' => 'varchar(63)'), 'config_value' => array('Type' => 'text'), ); protected $_indexes = array( 'PRIMARY' => array('Type' => 'PRIMARY', 'Column_names' => array('group_name', 'config_key')) ); }<file_sep>/modules/shop/acl/classes/form/frontend/user.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_User extends Form_Frontend { /** * Initialize form fields */ public function init() { // Set HTML class $this->view_script = 'frontend/forms/user'; // User is being created or updated? $creating = ((int)$this->model()->id == 0) ? TRUE : FALSE; $element = new Form_Element_Hidden('group_id'); $this->add_component($element); if ($creating) $element->value = Model_Group::EDITOR_GROUP_ID; else $element->value = $this->model()->group_id; // ----- E-mail $element = new Form_Element_Input('email', array('label' => 'E-mail'), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Email()); $ajax_uri = URL::uri_self(array('action' => 'validate', 'v_action' => Request::current()->action)); $element ->add_validator(new Form_Validator_Ajax($ajax_uri)); $this->add_component($element); if ($creating) { // ----- Password $element = new Form_Element_Password('password', array('label' => 'Пароль', 'visible' => ! $creating) ); $element ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_StringLength(0, 255)); $this->add_component($element); // ----- Password confirmation $element = new Form_Element_Password('password2', array('label' => 'Подтверждение', 'visible' => ! $creating), array('maxlength' => 255) ); $element ->add_validator(new Form_Validator_NotEmptyString(array( Form_Validator_NotEmptyString::EMPTY_STRING => 'Вы не указали подтверждение пароля!', ))) ->add_validator(new Form_Validator_EqualTo( 'password', array( Form_Validator_EqualTo::NOT_EQUAL => 'Пароль и подтверждение не совпадают!', ) )); $this->add_component($element); } else { // ----- Password $element = new Form_Element_Password('password', array('label' => 'Пароль', 'visible' => ! $creating) ); $element ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_StringLength(0, 255)); $this->add_component($element); } // ----- Last_name $element = new Form_Element_Input('last_name', array('label' => 'Фамилия'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- First_name $element = new Form_Element_Input('first_name', array('label' => 'Имя'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ------------------------------------------------------------------------------------- // organizer // ------------------------------------------------------------------------------------- $control_element = new Form_Element_Hidden('organizer_id',array('id' => 'organizer_id')); $this->add_component($control_element); if ($control_element->value !== FALSE) { $organizer_id = (int) $control_element->value; } else { $organizer_id = (int) $this->model()->organizer_id; } // ----- organizer_name // input field with autocomplete ajax $element = new Form_Element_Input('organizer_name', array('label' => 'Организация', 'layout' => 'wide','id' => 'organizer_name')); $element->autocomplete_url = URL::to('frontend/acl/organizers', array('action' => 'ac_organizer_name')); Layout::instance()->add_style(Modules::uri('acl') . '/public/css/frontend/acl.css'); $this->add_component($element); $organizer = new Model_Organizer(); $organizer->find($organizer_id); $organizer_name = ($organizer->id !== NULL) ? $organizer->name : ''; if ($element->value === FALSE) { $element->value = $organizer_name; } else { if ($element->value !== $organizer_name) $control_element->set_value(NULL); } // ----- tags $element = new Form_Element_Input('tags', array('label' => 'Мои интересы','id' => 'tag'), array('maxlength' => 255)); $element->autocomplete_url = URL::to('frontend/tags', array('action' => 'ac_tag')); $element->autocomplete_chunk = Model_Tag::TAGS_DELIMITER; $element ->add_filter(new Form_Filter_TrimCrop(255)); $this->add_component($element); $element = new Form_Element_Checkbox_Enable('notify', array('label' => 'Информировать о новых интересных событиях')); $this->add_component($element); // ----- town_id $towns = Model_Town::towns(); $element = new Form_Element_Select('town_id', $towns, array('label' => 'Город'), array('class' => 'w300px') ); $element ->add_validator(new Form_Validator_InArray(array_keys($towns))); $this->add_component($element); // ----- User Photo $element = new Form_Element_File('file', array('label' => 'Загрузить фото'),array('placeholder' => 'Загрузить фото')); $this->add_component($element); if ($this->model()->id !== NULL) { $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('images')->widget_image('user', $this->model()->id, 'user'); $this->add_component($element); } foreach ($this->model()->links as $link) { $element = new Form_Element_Input( $link->name, array('label' => $link->caption), array('label_class' => $link->name,'maxlength' => Model_Link::MAXLENGTH) ); $this->add_component($element); } // ----- Personal Webpages if ($this->model()->id) { $options_count = count($this->model()->webpages); } if (!isset($options_count) || $options_count==0) $options_count = 1; $element = new Form_Element_Options("webpages", array('label' => 'Сайты', 'options_count' => $options_count,'options_count_param' => 'options_count','option_caption' => 'добавить ссылку'), array('maxlength' => Model_User::LINKS_LENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_User::LINKS_LENGTH)); $this->add_component($element); // ----- Description $element = new Form_Element_Textarea('info', array('label' => 'О себе')); $element ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Form buttons if ($this->model()->id !== NULL) { $label = 'Изменить'; } else { $label = 'Зарегистрироваться'; } $button = new Form_Element_Button('submit_user', array('label' => $label), array('class' => 'button button-red') ); $this->add_component($button); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/organizer_name.js'); // Url for ajax requests to redraw product properties when main section is changed Layout::instance()->add_script(Modules::uri('tags') . '/public/js/backend/tag.js'); } } <file_sep>/modules/shop/catalog/classes/form/frontend/datesearch.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Datesearch extends Form_Frontend { /** * Initialize form fields */ public function init() { // Set HTML class $this->view_script = 'frontend/forms/datesearch'; // ----- datetime $element = new Form_Element_DateTimeSimple('datetime', array('label' => 'Дата проведения', 'required' => TRUE),array('class' => 'w300px','placeholder' => 'dd-mm-yyyy hh:mm')); $element->value_format = Model_Product::$date_as_timestamp ? 'timestamp' : 'datetime'; $element ->add_validator(new Form_Validator_DateTimeSimple()); $this->add_component($element); $button = new Form_Element_Button('submit_datesearch', array('label' => 'Найти'), array('class' => 'button') ); $this->add_component($button); } }<file_sep>/modules/shop/catalog/classes/controller/backend/plists.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_PLists extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_PList'; $this->_form = 'Form_Backend_PList'; return array( 'create' => array( 'view_caption' => 'Создание списка товаров' ), 'update' => array( 'view' => 'backend/plist', 'view_caption' => 'Редактирование списка товаров ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление списка товаров', 'message' => 'Удалить список товаров ":caption"?' ) ); } /** * Create layout (proxy to catalog controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('catalog') . '/public/css/backend/catalog.css'); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Render all available lists of products */ public function action_index() { $this->request->response = $this->render_layout($this->widget_plists()); } /** * Create new list of products * * @return Model_PList */ protected function _model_create($model, array $params = NULL) { if (Model_Site::current()->id === NULL) { throw new Controller_BackendCRUD_Exception('Выберите магазин для создания списка товаров!'); } // New list of products for the selected site $plist = new Model_PList(); $plist->site_id = (int) Model_Site::current()->id; return $plist; } /** * Generate redirect url * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { if ($action == 'create') { return URL::uri_to( 'backend/catalog/plists', array('action'=>'update', 'id' => $model->id, 'history' => $this->request->param('history')), TRUE ) . '?flash=ok'; } else { return parent::_redirect_uri($action, $model, $form, $params); } } /** * Prepare a view for product list update action * * @param Model $plist * @param Form $form * @param array $params * @return View */ protected function _view_update(Model $plist, Form $form, array $params = NULL) { $view = $this->_view('update', $plist, $form, $params); // Render list of products in list $view->plistproducts = $this->request->get_controller('plistproducts')->widget_plistproducts($plist); return $view; } /** * Render list of product lists */ public function widget_plists() { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите магазин!'); } $order_by = $this->request->param('cat_lorder', 'id'); $desc = (bool) $this->request->param('cat_ldesc', '0'); $plists = Model::fly('Model_PList')->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/plists'); $view->order_by = $order_by; $view->desc = $desc; $view->plists = $plists; return $view->render(); } }<file_sep>/modules/shop/catalog/views/backend/sections/product_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="sections"> <table> <tr> <td> <?php // Highlight current section if ($section_id == 0) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo URL::self(array('cat_section_id' => (string) 0)); ?>" class="section<?php echo $selected; ?>" title="Показать все события" > <strong>Все события</strong> </a> </td> </tr> <?php foreach ($sections as $section) : ?> <tr> <td> <?php // Highlight current section if ($section->id == $section_id) { $selected = 'selected'; } else { $selected = ''; } if ( ! $section->section_active) { $active = 'section_inactive'; } elseif ( ! $section->active) { $active = 'inactive'; } else { $active = ''; } ?> <a href="<?php echo URL::self(array('cat_section_id' => (string) $section->id)); ?>" class="section <?php echo "$selected $active"; ?>" title="Показать все события из раздела '<?php echo HTML::chars($section->caption); ?>'" style="margin-left: <?php echo ($section->level-1)*15; ?>px" > <?php echo HTML::chars($section->caption); ?> </a> </td> </tr> <?php endforeach; //foreach ($sections as $section) ?> </table> </div> <file_sep>/modules/shop/area/classes/controller/backend/towns.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Towns extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Town'; $this->_form = 'Form_Backend_Town'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание города' ), 'update' => array( 'view_caption' => 'Редактирование города' ), 'delete' => array( 'view_caption' => 'Удаление города', 'message' => 'Удалить город ":name" ' ), 'multi_delete' => array( 'view_caption' => 'Удаление городов', 'message' => 'Удалить выбранные города?' ) ); } /** * Create layout (proxy to area controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('area')->prepare_layout($layout_script); } /** * Render layout (proxy to area controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('area')->render_layout($content, $layout_script); } /** * Render all available section properties */ public function action_index() { $this->request->response = $this->render_layout($this->widget_towns('backend/towns/place_select')); } /** * Handles the selection of access towns for event */ public function action_towns_select() { if ( ! empty($_POST['ids']) && is_array($_POST['ids'])) { $town_ids = ''; foreach ($_POST['ids'] as $town_id) { $town_ids .= (int) $town_id . '_'; } $town_ids = trim($town_ids, '_'); $this->request->redirect(URL::uri_back(NULL, 1, array('access_town_ids' => $town_ids))); } else { // No towns were selected $this->request->redirect(URL::uri_back()); } } /** * Import towns */ /*public function action_index() { $form = new Form_Backend_ImportTowns(); if ($form->is_submitted() && $form->validate()) { $model = Model::fly('Model_Town'); $model->import($form->get_component('file')->value); if ( ! $model->has_errors()) { // Upload was successfull $this->request->redirect($this->request->uri . '?flash=ok'); } else { // Add import errors to form $form->errors($model->errors()); } } if (isset($_GET['flash']) && $_GET['flash'] == 'ok') { } $view = new View('backend/form'); $view->caption = 'Импорт списка городов'; $view->form = $form; $this->request->response = $this->render_layout($view); }*/ /** * Display autocomplete options for a city form field */ public function action_ac_city() { $town_str = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $town_str = UTF8::str_ireplace("ё", "е", $town); if ($town == '') { $this->request->response = ''; return; } $limit = 7; $town = Model::fly('Model_Town'); $towns = $town->find_all_like_town($town, array( 'order_by' => 'town', 'desc' => FALSE, 'limit' => $limit )); if ( ! count($towns)) { $this->request->response = ''; return; } $items = array(); foreach ($towns as $town) { $caption = $town->town; // Highlight found part $caption = str_replace($town, '<strong>' . $town .'</strong>', $caption); $items[] = array( 'caption' => $caption, 'value' => UTF8::ucfirst($town->phonecode) ); } $this->request->response = json_encode($items); } /** * Select several towns */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор городов на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_towns(); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_select()); } } /** * Render list of towns to select several towns * @return string */ public function widget_towns($view_script = 'backend/towns/select') { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } // ----- Render section for current section group $order_by = $this->request->param('are_torder', 'name'); $desc = (bool) $this->request->param('are_tdesc', '0'); $town_alias = (int) $this->request->param('are_town_alias'); $per_page = 20; $town = Model::fly('Model_Town'); $count = $town->count(); $pagination = new Paginator($count, $per_page,'tpage'); $towns = Model::fly('Model_Town')->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View($view_script); $view->order_by = $order_by; $view->desc = $desc; $view->towns = $towns; $view->town_alias = $town_alias; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } } <file_sep>/modules/shop/delivery_courier/classes/form/backend/delivery/courier.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Delivery_Courier extends Form_Backend_Delivery { /** * Initialize form fields */ public function init() { parent::init(); // Set HTML class $this->attribute('class', "wide w400px lb120px"); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } } <file_sep>/modules/frontend/classes/controller/frontend/menu.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Menu extends Controller_Backend { /** * Renders backend menu * * @return string */ public function widget_menu($menu, $view, $level = 0) { $menu = Model_Backend_Menu::get_menu($menu); if ($menu === FALSE) return; // There is no menu with such name $path = $menu['path']; $tree = $menu['items']; $caption = isset($menu['caption']) ? $menu['caption'] : NULL; if ($level == 0) { $items = $tree[0]; } elseif (isset($path[$level-1]['id']) && ! empty($tree[$path[$level-1]['id']])) { $items = $tree[$path[$level-1]['id']]; } else { $items = array(); } if (empty($items)) { return; } $view = new View($view); $view->caption = $caption; $view->items = $items; return $view->render(); } /** * Render breadcrumbs for the given menu * * @param string $menu */ public function widget_breadcrumbs($menu) { $menu = Model_Backend_Menu::get_menu($menu); if ($menu === FALSE) return; // There is no menu with such name $path = $menu['path']; $view = new View('backend/breadcrumbs'); $view->path = $path; return $view->render(); } } <file_sep>/modules/shop/acl/views/backend/users/select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // ----- Set up urls // Submit results to previous url $users_select_uri = URL::uri_back(); ?> <?php echo View_Helper_Admin::multi_action_form_open($users_select_uri, array('name' => 'users_select')); ?> <table class="users_select table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'email' => 'E-mail' ); echo View_Helper_Admin::table_header($columns, 'acl_uorder', 'acl_udesc'); ?> </tr> <?php foreach ($users as $user) : ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($user->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'name': echo '<td>' . HTML::chars($user->$field) . '</td>'; break; default: echo '<td>'; if (isset($user->$field) && trim($user->$field) !== '') { echo HTML::chars($user[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> </tr> <?php endforeach; ?> </table> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'users_select', 'label' => 'Выбрать', 'class' => 'button_select') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/acl/classes/model/resource.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Resource extends Model { /** * Save section and link it to selected properties * * @param boolean $force_create * @param boolen $link_properties * @param boolean $update_stats */ // public function save($force_create = FALSE) // { // if (!$this->role_id) { // $this->role_id = Model_User::current()->id; // } // parent::save($force_create); // } public function get_resource(){ if ( ! isset($this->_properties['resource'])) { $resource_class = $this->resource_type; if (class_exists($resource_class)) { $resource = new $resource_class(); $resource = $resource->find($this->resource_id); $this->_properties['resource'] = $resource; } } return $this->_properties['resource']; } // public function get_role(){ // if ( ! isset($this->_properties['role'])) // { // $role_class = $this->role_type; // if (class_exists($role_class)) { // $role = new $role_class(); // $role = $role->find($this->role_id); // $this->_properties['role'] = $role; // } // } // return $this->_properties['role']; // } }<file_sep>/modules/shop/area/views/frontend/towns/select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($type == 'catalog') { $choose_url = URL::to('frontend/area/towns', array('action'=>'choose', 'are_town_alias' => '{{alias}}'), TRUE); $main_town_url = URL::to('frontend/area/towns', array('action'=>'choose', 'are_town_alias' => $town->alias), TRUE); } else { $choose_url = URL::to('frontend/area/towns', array('action'=>'choosemap', 'are_town_alias' => '{{alias}}'), TRUE); $main_town_url = URL::to('frontend/area/towns', array('action'=>'choosemap', 'are_town_alias' => $town->alias), TRUE); } ?> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" href="<?php echo $main_town_url?>"><?php echo mb_strtolower($town->name) ?><b class="caret"></b></a> <ul class="dropdown-menu" role="menu" aria-labelledby="drop10"> <!-- Add all towns --> <?php if($town->alias != Model_Town::ALL_TOWN): ?> <?php $_choose_url = str_replace('{{alias}}', Model_Town::ALL_TOWN, $choose_url); ?> <li><a role="menuitem" tabindex="-1" href="<?php echo $_choose_url ?>">все города</a></li> <?php endif ?> <?php foreach ($towns as $t) { if ($t->id == $town->id) continue; $_choose_url = str_replace('{{alias}}', $t->alias, $choose_url); ?> <li><a role="menuitem" tabindex="-1" href="<?php echo $_choose_url ?>"><?php echo mb_strtolower($t->name) ?></a></li> <?php }?> </ul> </li><file_sep>/application/views/layouts/_footer.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <footer> <div class="container"> <div class="row"> <div class="span2 footer-logo-block"> <a href="<?php echo URL::site();?>" class="logo"></a> <span>первая социальная сеть телемостов и семинаров</span> </div> <div class="span5"> <p> Проект <a href="http://www.newmediacenter.ru/">ЦИИО РЭШ</a>. <br /> Создан при поддержке <a href="http://te-st.ru/">Теплицы социальных технологий</a> </p> <p> Все права на информацию, размещенную на данном ресурсе, принадлежат ЦИИО РЭШ. <br /> При копирование материалов ссылка на сайт обязательна. <br /> &copy; vse.to 2013 </p> </div> <div class="span5"> <div class="address"> <p> Контакты:<br /> Центр изучения интернета и общества <br /> 117418, Москва, Нахимовский пр. 47, оф. 1918<br /> <a href="mailto:<EMAIL>"><EMAIL></a> </p> </div> <div> <a href="<?php echo URL::uri_to('frontend/catalog/products/control', array('action' => 'archive'), TRUE) ?>">Архив событий</a> </div> <div class="soc-link"> <a href="https://www.facebook.com/vsetonetwork" class="button fb">f</a> <a href="https://twitter.com/vse_to" class="tw button ">t</a> <a href="https://vk.com/vseto" class="button vk">v</a> </div> </div> </div> </div> </footer> <?php echo $view->placeholder('scripts'); ?> <file_sep>/modules/shop/catalog/classes/form/backend/event.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Event extends Form_BackendRes { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "lb150px"); $this->layout = 'wide'; // User is being created or updated? $creating = ((int)$this->model()->id == 0) ? TRUE : FALSE; // ----- General tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $tab->add_component($cols); $fieldset = new Form_Fieldset('main_props', array('label' => 'Основные свойства')); $cols->add_component($fieldset); if ($this->model()->id === NULL) { // ----- "Find in catalog" button $product_select_url = URL::to('backend/catalog', array('site_id' => Model_Site::current()->id, 'action' => 'product_select'), TRUE); $element = new Form_Element_Text('product_select'); $element->value = '<div class="buttons">' . ' <a href="' . $product_select_url . '" class="button dim700x500">Подобрать анонс</a>' . '</div>' ; $fieldset->add_component($element); } // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'disabled' => TRUE, 'required' => TRUE), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $fieldset->add_component($element); // ----- Section_id_original $element = new Form_Element_Hidden('section_id_original'); $this->add_component($element); // [!] Set up new section id to product model if ($element->value === FALSE) { $element->value = $this->model()->section_id; } else { $this->model()->section_id = $element->value; } // ----- Section_id $sectiongroups = Model::fly('Model_SectionGroup')->find_all_by_site_id_and_type(Model_Site::current()->id, Model_SectionGroup::TYPE_EVENT, array('columns' => array('id', 'caption'))); $sections = array(); foreach ($sectiongroups as $sectiongroup) { $sections[$sectiongroup->id] = Model::fly('Model_Section')->find_all_by_sectiongroup_id($sectiongroup->id, array( 'order_by' => 'lft', 'desc' => FALSE, 'columns' => array('id', 'rgt', 'lft', 'level', 'caption') )); } $sections_options = array(); foreach ($sections as $sections_in_group) { foreach ($sections_in_group as $section) { $sections_options[$section->id] = str_repeat('&nbsp;', ($section->level - 1) * 3) . Text::limit_chars($section->caption, 30); } } //lecturer $element = new Form_Element_Hidden('lecturer_id'); $this->add_component($element); if ($element->value !== FALSE) { $lecturer_id = (int) $element->value; } else { $lecturer_id = (int) $this->model()->lecturer_id; } // ----- Lecturer name // Lecturer for this order $lecturer = new Model_Lecturer(); $lecturer->find($lecturer_id); $lecturer_name = ($lecturer->id !== NULL) ? $lecturer->name : '--- лектор не указан ---'; $element = new Form_Element_Input('lecturer_name', array('label' => 'Лектор', 'disabled' => TRUE, 'layout' => 'wide'), array('class' => 'w150px') ); $element->value = $lecturer_name; $fieldset->add_component($element); // ----- datetime $element = new Form_Element_DateTimeSimple('datetime', array('label' => 'Дата проведения', 'disabled' => TRUE)); $element->value_format = Model_Product::$date_as_timestamp ? 'timestamp' : 'datetime'; $element ->add_validator(new Form_Validator_DateTimeSimple()); $fieldset->add_component($element); // ----- access $element = new Form_Element_Select('access', Model_Product::$_access_options, array('label' => 'Тип события','disabled' => TRUE) ); $fieldset->add_component($element); // ----- maxAllowedUsers $element = new Form_Element_Input('maxAllowedUsers', array('label' => 'Колличество участников','disabled' => TRUE), array('class' => 'w150px','maxlength' => '4') ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Integer(0, NULL, FALSE)); $fieldset->add_component($element); // ----- Active $fieldset->add_component(new Form_Element_Checkbox('active', array('label' => 'Активный'))); // ----- Visible $fieldset->add_component(new Form_Element_Checkbox('visible', array('label' => 'Видимый'))); // ----- Role properties $fieldset = new Form_Fieldset('role', array('label' => 'Пользователь')); $cols->add_component($fieldset); if (!$creating) { // ----- External Links $options_count = 1; if ($this->model()->id) { $options_count = count($this->model()->links); } $element = new Form_Element_Options("links", array('label' => 'Внешние ссылки', 'options_count' => $options_count,'options_count_param' => 'options_count','option_caption' => 'добавить ссылку'), array('maxlength' => Model_Product::LINKS_LENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Product::LINKS_LENGTH)); $cols->add_component($element); // ----- Additional properties if ($this->model()->id === NULL) { $main_section_id = key($sections_options); $this->model()->section_id = $main_section_id; } $properties = $this->model()->properties; if ($properties->valid()) { $fieldset = new Form_Fieldset('props', array('label' => 'Характеристики')); $cols->add_component($fieldset); foreach ($properties as $property) { switch ($property->type) { case Model_Property::TYPE_TEXT: $element = new Form_Element_Input( $property->name, array('label' => $property->caption), array('maxlength' => Model_Property::MAX_TEXT) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Property::MAX_TEXT)); $fieldset->add_component($element); break; case Model_Property::TYPE_SELECT: $options = array('' => '---'); foreach ($property->options as $option) { $options[$option] = $option; } $element = new Form_Element_Select( $property->name, $options, array('label' => $property->caption) ); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); break; case Model_Property::TYPE_TEXTAREA: $element = new Form_Element_Textarea( $property->name, array('label' => $property->caption), array('maxlength' => Model_Property::MAX_TEXTAREA) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Property::MAX_TEXTAREA)); $fieldset->add_component($element); break; } } } } $fieldset = new Form_Fieldset('product_sections', array('label' => 'Основная категория события')); $cols->add_component($fieldset, 2); // main category $element = new Form_Element_Select('section_id', $sections_options, array('label' => 'Основная категория', 'required' => TRUE)); $element ->add_validator(new Form_Validator_InArray(array_keys($sections_options), array( Form_Validator_InArray::NOT_FOUND => 'Вы не указали основную категорию' ))); $fieldset->add_component($element); if (!$creating) { // ----- Additional sections if (Request::current()->param('cat_section_ids') != '') { // Are section ids explicitly specified in the uri? $section_ids = explode('_', Request::current()->param('cat_section_ids')); } foreach ($sectiongroups as $sectiongroup) { if (count($sections[$sectiongroup->id]) <= 20) { // Use a simple list of checkboxes to select additional sections // when the total number of sections is not very big $options = array(); foreach ($sections[$sectiongroup->id] as $section) { $label = str_repeat('&nbsp;', ($section->level - 1) * 3) . Text::limit_chars($section->caption, 30); if ($this->model()->id !== NULL && $section->id === $this->model()->section_id) { // Render checkbox for the main section as "disabled", to prevent // adding it as additional section when user changes the main section $options[$section->id] = array('label' => $label, 'disabled' => TRUE); } else { $options[$section->id] = $label; } } $element = new Form_Element_CheckSelect('sections[' . $sectiongroup->id . ']', $options, array('label' => 'Дополнительные категории: '.$sectiongroup->caption)); $element->config_entry = 'checkselect_fieldset'; $cols->add_component($element, 2); } else { $fieldset = new Form_Fieldset('sections[' . $sectiongroup->id . ']', array('label' => 'Дополнительные категории: '.$sectiongroup->caption)); $cols->add_component($fieldset, 2); // Button to select additional sections for product $history = URL::uri_to('backend/catalog/products', array('action' => 'sections_select'), TRUE); $sections_select_url = URL::to('backend/catalog/sections', array( 'action' => 'select', 'cat_sectiongroup_id' => $sectiongroup->id, 'history' => $history ), TRUE); $button = new Form_Element_LinkButton('select_sections_button[' . $sectiongroup->id . ']', array('label' => 'Выбрать'), array('class' => 'button_select_sections open_window') ); $button->layout = 'standalone'; $button->url = $sections_select_url; $fieldset->add_component($button); $sections_fieldset = new Form_Fieldset('additional_sections[' . $sectiongroup->id . ']'); $sections_fieldset->config_entry = 'fieldset_inline'; $sections_fieldset->layout = 'standart'; $fieldset->add_component($sections_fieldset); // Obtain a list of selected sections in the following precedence // 1. From $_POST // 2. From cat_section_ids request param // 3. From model if ($this->is_submitted()) { $supplied_sections = $this->get_post_data('sections[' . $sectiongroup->id . ']'); if ( ! is_array($supplied_sections)) { $supplied_sections = array(); } // Filter out invalid sections foreach ($supplied_sections as $section_id => $selected) { if ( ! isset($sections[$sectiongroup->id][$section_id])) { unset($supplied_sections[$section_id]); } } // Add main section if ($this->model()->id !== NULL) { $supplied_sections[$this->model()->section_id] = 1; } } elseif (isset($section_ids)) { // Section ids are explicitly specified in the uri $supplied_sections = array(); foreach ($section_ids as $section_id) { if (isset($sections[$sectiongroup->id][$section_id])) { $supplied_sections[$section_id] = 1; } } // Add main section if ($this->model()->id !== NULL) { $supplied_sections[$this->model()->section_id] = 1; } } else { $supplied_sections = $this->model()->sections; $supplied_sections = (isset($supplied_sections[$sectiongroup->id])) ? $supplied_sections[$sectiongroup->id] : array(); } if ( ! empty($supplied_sections)) { foreach ($supplied_sections as $section_id => $selected) { if (isset($sections[$sectiongroup->id][$section_id])) { $section = $sections[$sectiongroup->id][$section_id]; $element = new Form_Element_Checkbox('sections[' . $sectiongroup->id . '][' . $section_id . ']', array('label' => $section->full_caption)); $element->default_value = $selected; $element->layout = 'default'; if ($this->model()->id !== NULL && $section_id == $this->model()->section_id) { $element->disabled = TRUE; } $sections_fieldset->add_component($element); } } } else { // No additional sectons were selected - add hidden element to emulate an empty array // Without this the previous value of main section_id is stored in additinal sections :-( $element = new Form_Element_Hidden('sections[' . $sectiongroup->id . '][0]'); $element->value = '0'; $this->add_component($element); } } } // foreach ($sectiongroups as $sectiongroup) // ----- Product images if ($this->model()->id !== NULL) { $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('images')->widget_images('product', $this->model()->id, 'product'); $cols->add_component($element, 2); } // ----- Description tab $tab = new Form_Fieldset_Tab('description_tab', array('label' => 'Описание')); $this->add_component($tab); // ----- Description $tab->add_component(new Form_Element_Wysiwyg('description', array('label' => 'Описание события'))); // ----- Address tab $tab = new Form_Fieldset_Tab('address_tab',array('label' => 'Адрес проведения')); $this->add_component($tab); // ----- Town $towns = Model_Town::towns(); $element = new Form_Element_Select('town_show', $towns, array('label' => 'Город') ); $tab->add_component($element); // ----- Address $element = new Form_Element_Textarea('address_show', array('label' => 'Адрес проведения'), array('class' => 'w300px')); $element ->add_filter(new Form_Filter_TrimCrop(1023)); $tab->add_component($element); } // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts // Url for ajax requests to redraw product properties when main section is changed $properties_url = URL::to('backend/catalog/products', array( 'action' => 'ajax_properties', 'type_id' => Model_SectionGroup::TYPE_EVENT, 'id' => $this->model()->id )); // Url for ajax requests to redraw selected additional sections for product $on_sections_select_url = URL::to('backend/catalog/products', array( 'action' => 'ajax_sections_select', 'type_id' => Model_SectionGroup::TYPE_EVENT, 'id' => $this->model()->id, 'cat_section_ids' => '{{section_ids}}', 'cat_sectiongroup_id' => '{{sectiongroup_id}}' )); Layout::instance()->add_script( "var product_form_name='" . $this->name . "';\n\n" . "var properties_url = '" . $properties_url . "';\n" . "var on_sections_select_url = '" . $on_sections_select_url . "';\n" , TRUE); // "props" fieldset id $component = $this->find_component('props'); if ($component !== FALSE) { Layout::instance()->add_script( "var properties_fieldset_id='" . $component->id . "';" , TRUE); } // additional sections fieldset id's to redraw via ajax requests $script = "var sections_fieldset_ids = {};\n"; $sectiongroups = Model::fly('Model_SectionGroup')->find_all_by_site_id_and_type(Model_Site::current()->id, Model_SectionGroup::TYPE_EVENT, array('columns' => array('id', 'caption'))); foreach ($sectiongroups as $sectiongroup) { $component = $this->find_component('additional_sections[' . $sectiongroup->id . ']'); if ($component !== FALSE) { $script .= "sections_fieldset_ids[" . $sectiongroup->id . "]='" . $component->id . "';\n"; } } Layout::instance()->add_script($script, TRUE); // Link product form scripts jQuery::add_scripts(); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/backend/product_form.js'); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/backend/produser.js'); } } <file_sep>/modules/backend/classes/form/backendres.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_BackendRes extends Form_Backend { /** *@todo * * This definition copy the definition in Controller_BackendRES */ protected $_role_class = 'Model_User'; protected $_user_id = 'user_id'; /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts $js = "function on_user_select(user){" . " var f = jforms['$this->name'];" . " if (user['id'])" . "{ f.get_element('$this->_user_id').set_value(user['id']);" . "f.get_element('user_name').set_value(user['user_name']);}" . "else { f.get_element('$this->_user_id').set_value(0);" . "f.get_element('user_name').set_value('');}}"; $layout = Layout::instance(); $layout->add_script($js, TRUE); $script = ''; $component = $this->find_component('access_towns'); if ($component !== FALSE) { $script .= "var towns_fieldset_ids='" . $component->id . "';\n"; } $component = $this->find_component('access_organizers'); if ($component !== FALSE) { $script .= "var organizers_fieldset_ids='" . $component->id . "';\n"; } $component = $this->find_component('access_users'); if ($component !== FALSE) { $script .= "var users_fieldset_ids='" . $component->id . "';\n"; } $layout->add_script($script, TRUE); Layout::instance()->add_script(Modules::uri('area') . '/public/js/backend/towns_form.js'); Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/organizers_form.js'); Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/users_form.js'); //Layout::instance()->add_script(Modules::uri('backend') . '/public/js/roleuser.js'); } }<file_sep>/modules/system/forms/config/form_templates/table/form.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // Standart layout 'standart' => array( 'form' => ' {{form_open}} {{messages}} {{hidden}} <table class="form_table"> <tr class="empty"><td class="label_cell"></td><td class="input_cell"></td></tr> {{elements}} </table> {{form_close}} ' ), // Wide layout 'wide' => array( 'form' => ' {{form_open}} {{messages}} {{hidden}} <table class="form_table"> <tr class="empty"><td class="label_cell"></td><td class="input_cell"></td></tr> {{elements}} </table> {{form_close}} ' ) );<file_sep>/modules/shop/catalog/classes/controller/frontend/telemosts.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Telemosts extends Controller_FrontendRES { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Telemost'; $this->_form = 'Form_Frontend_Telemost'; $this->_view = 'frontend/form'; return array( 'create' => array( 'view_caption' => 'Создание телемоста' ), 'update' => array( 'view_caption' => 'Редактирование телемоста' ), 'delete' => array( 'view_caption' => 'Удаление телемоста', 'message' => 'Удалить телемост?' ) ); } /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { return parent::prepare_layout($layout_script); } protected function _model_create($telemost, array $params = NULL) { $telemost = parent::_model('create', $telemost, $params); $product_id = (int) $this->request->param('product_id'); if ( ! Model::fly('Model_Product')->exists_by_id($product_id)) { throw new Controller_BackendCRUD_Exception('Указанный анонс не существует!'); } $telemost->product_id = $product_id; return $telemost; } /** * Renders list of product telemosts * * @param Model_Product $product * @return string */ public function widget_app_telemosts_by_product($product,$script = 'frontend/app_telemosts_by_product') { $app_telemosts = $product->app_telemosts; // Set up view $view = new View($script); $view->product = $product; $view->app_telemosts = $app_telemosts; $view->telemosts = $telemosts; return $view->render(); } public function widget_app_telemosts_by_owner($owner,$view = 'frontend/small_app_telemosts') { $widget = new Widget($view); $widget->id = 'app_telemosts'; $widget->ajax_uri = NULL; $widget->context_uri = FALSE; // use the url of clicked link as a context url // ----- List of products $telemost = Model::fly('Model_Telemost'); $per_page = 1000; $count = $telemost->count_by_owner($owner->id); $pagination = new Paginator($count, $per_page, 'rpage', 7,NULL,'frontend/catalog/ajax_app_telemosts',NULL,'ajax'); $order_by = $this->request->param('cat_torder', 'created_at'); $desc = (bool) $this->request->param('cat_tdesc', '0'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['owner'] = $owner; $telemosts = $telemost->find_all_by_active_and_visible(FALSE,TRUE,$params); $params['offset'] = $pagination->offset; $widget->order_by = $order_by; $widget->desc = $desc; $widget->telemosts = $telemosts; $widget->pagination = $pagination->render('pagination'); return $widget; } /** * Redraw product images widget via ajax request */ public function action_ajax_app_telemosts() { $request = Widget::switch_context(); $user = Model_User::current(); if ( ! isset($user->id)) { //FlashMessages::add('', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('telemosts') ->widget_app_telemosts_by_owner($user); $widget->to_response($this->request); $this->_action_ajax(); } public function widget_telemosts_by_owner($owner,$view = 'frontend/small_telemosts') { $widget = new Widget($view); $widget->id = 'telemosts'; $widget->ajax_uri = NULL; $widget->context_uri = FALSE; // use the url of clicked link as a context url // ----- List of products $telemost = Model::fly('Model_Telemost'); $per_page = 1000; $count = $telemost->count_by_owner($owner->id); $pagination = new Paginator($count, $per_page, 'tpage', 7,NULL,'frontend/catalog/ajax_telemosts',NULL,'ajax'); $order_by = $this->request->param('cat_torder', 'created_at'); $desc = (bool) $this->request->param('cat_tdesc', '0'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['owner'] = $owner; $telemosts = $telemost->find_all_by_active_and_visible(TRUE,TRUE,$params); // Set up view $params['offset'] = $pagination->offset; $widget->order_by = $order_by; $widget->desc = $desc; $widget->telemosts = $telemosts; $widget->pagination = $pagination->render('pagination'); return $widget; } /** * Redraw product images widget via ajax request */ public function action_ajax_telemosts() { $request = Widget::switch_context(); $user = Model_User::current(); if ( ! isset($user->id)) { //FlashMessages::add('', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('telemosts') ->widget_telemosts_by_owner($user); $widget->to_response($this->request); $this->_action_ajax(); } public function widget_goes_by_owner($owner,$view = 'frontend/small_goes') { $go = Model::fly('Model_Go'); $per_page = 1000; $count = $go->count_by_owner($owner->id); $pagination = new Paginator($count, $per_page, 'mpage', 7,NULL,'frontend/catalog/ajax_goes',NULL,'ajax'); $order_by = $this->request->param('cat_torder', 'created_at'); $desc = (bool) $this->request->param('cat_tdesc', '0'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['owner'] = $owner; $goes = $go->find_all($params); $products = new Models('Model_Product',array()); $i=0; foreach ($goes as $go) { $products[$i] = $go->telemost->product; $i++; } $params['offset'] = $pagination->offset; $view = new View($view); $view->order_by = $order_by; $view->desc = $desc; $view->products = $products; $view->pagination = $pagination->render('pagination'); return $view->render(); } /** * Redraw product images widget via ajax request */ public function action_ajax_goes() { $request = Widget::switch_context(); $user = Model_User::current(); if ( ! isset($user->id)) { //FlashMessages::add('', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('telemosts') ->widget_goes_by_owner($user); $widget->to_response($this->request); $this->_action_ajax(); } /** * Render auth form */ public function widget_request($product) { $user= Model_User::current(); if ( $product->id===NULL || $user->id===NULL) { $this->_action_404(); return; } $telemost = new Model_Telemost(); $view = new View('frontend/telemosts/request'); $form_request = new Form_Frontend_Telemost($product,'telemost_for_product'.$product->alias); if ($form_request->is_submitted()) { // User is trying to log in if ($form_request->validate()) { $vals = $form_request->get_values(); $vals['user_id'] = $user->id; if ($telemost->validate($vals)) { $telemost->values($vals); $telemost->product_id = $product->id; $telemost->save(); // activize telemost if the FIFO algorithm is chosen if($product->choalg == Model_Product::CHOALG_ORDER && $product->price->eq(new Money())) { $telemost->active = TRUE; if ($telemost->validate_choose()) { $telemost->save(); } } //$rc = QIWI::factory()->createBill($vals['telephone'], $vals['price'], $telemost->id, $comment, $alarm); if ($product->price->gt(new Money())) { $url = QIWI::createBill($vals['telephone'],$product->price->amount, $telemost->id,'TRUE',$product->uri_frontend(),$product->uri_frontend(),'iframeName'); $view->url = $url; $view->product = $product; Layout::instance()->set_placeholder('payment',$view->render()); //$this->request->redirect(QIWI::createBill($vals['telephone'],$product->price->amount, $telemost->id,'TRUE',$product->uri_frontend(),$product->uri_frontend(),'iframeName')); } else { $this->request->redirect($product->uri_frontend()); } } } } $modal = Layout::instance()->get_placeholder('modal'); $modal .= ' '.$form_request->render(); Layout::instance()->set_placeholder('modal',$modal); } /** * Redraw product images widget via ajax request */ public function action_ajax_telemost_select() { $telemost_id = (int) $this->request->param('telemost_id'); $request = Widget::switch_context(); $telemost = Model::fly('Model_Telemost')->find($telemost_id); $user = Model_User::current(); if ( ! isset($telemost->id) && ! isset($user->id) && ($telemost->user_id == $user->id)) { $this->_action_404(); return; } $telemost->active = TRUE; if ($telemost->validate_choose()) { $telemost->save(); } $widget = $request->get_controller('products') ->widget_product($telemost->product); $widget->to_response($this->request); $this->_action_ajax(); } public function action_updatebill() { QIWI::factory()->updateBill(); } } <file_sep>/modules/shop/area/classes/controller/backend/places.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Places extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Place'; $this->_form = 'Form_Backend_Place'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание площадки' ), 'update' => array( 'view_caption' => 'Редактирование площадки', ), 'delete' => array( 'view_caption' => 'Удаление площадки', 'message' => 'Удалить площадку ":name" ' ), 'multi_delete' => array( 'view_caption' => 'Удаление площадок', 'message' => 'Удалить выбранные площадки?' ) ); } /** * Create layout (proxy to acl controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Render all available section properties */ public function action_index() { $layout = $this->prepare_layout(); $view = new View('backend/workspace_2col'); $view->column1 = $this->request->get_controller('towns')->widget_towns('backend/towns/place_select'); $view->column2 = $this->widget_places('backend/places/list'); $view->caption = 'Выбор площадки на портале "' . Model_Site::current()->caption . '"'; $layout->content = $view->render(); $this->request->response = $layout->render(); } /** * Render list of places * @return string */ public function widget_places($view_script = 'backend/places/list') { $place = new Model_Place(); // current site $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } $order_by = $this->request->param('are_porder', 'name'); $desc = (bool) $this->request->param('are_pdesc', '0'); $per_page = 20; $town_alias = $this->request->param('are_town_alias'); if ($town_alias !='') { // Show users only from specified group $town = new Model_Town(); $town->find_by_alias($town_alias); if ($town->id === NULL) { // Group was not found - show a form with error message return $this->_widget_error('Указанный город не найдена!'); } $count = $place->count_by_town_id($town->id); $pagination = new Paginator($count, $per_page); $places = $place->find_all_by_town_id($town->id, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc ), TRUE); } else { $town = NULL; // Select all users $count = $place->count(); $pagination = new Paginator($count, $per_page); $places = $place->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); } // Set up view $view = new View($view_script); $view->order_by = $order_by; $view->desc = $desc; $view->places = $places; $view->town = $town; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Select several towns */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор площадки на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_select(); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_select()); } } /** * Render list of towns to select several towns * @param integer $select * @return string */ public function widget_select($select = FALSE) { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } // ----- Render section for current section group $order_by = $this->request->param('acl_oorder', 'name'); $desc = (bool) $this->request->param('acl_odesc', '0'); $organizers = Model::fly('Model_Place')->find_all(array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/organizers/select'); $view->order_by = $order_by; $view->desc = $desc; $view->organizers = $organizers; return $view->render(); } /** * Generate redirect url * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { if ($action == 'create') { return URL::uri_self(array('action'=>'update', 'id' => $model->id, 'history' => $this->request->param('history'))) . '?flash=ok'; } // // if ($action == 'update') // { // return URL::uri_back(); // } if ($action == 'multi_link') { return URL::uri_back(); } return parent::_redirect_uri($action, $model, $form, $params); } /** * Display autocomplete options for a postcode form field */ public function action_ac_organizer_name() { $organizer_name = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $organizer_name = UTF8::str_ireplace("ё", "е", $organizer_name); if ($organizer_name == '') { $this->request->response = ''; return; } $limit = 7; $organizers = Model::fly('Model_Place')->find_all_like_name($organizer_name,array('limit' => $limit)); if ( ! count($organizers)) { $this->request->response = ''; return; } $items = array(); $pattern = new View('backend/organizer_ac'); foreach ($organizers as $organizer) { $name = $organizer->name; $id = $organizer->id; $image_info = $organizer->image(4); $pattern->name = $name; $pattern->image_info = $organizer->image(4); $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name, 'id' => $id) ); } $this->request->response = json_encode($items); } } <file_sep>/modules/frontend/classes/controller/frontendcrud/exception.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Exception that can be thrown during frontend CRUD contoller execution */ class Controller_FrontendCRUD_Exception extends Kohana_Exception {}<file_sep>/modules/backend/views/layouts/backend/window.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Parse window size from ?window=WWWxHHH $_GET paramater $width = 400; $height = 500; if ( ! empty($_GET['window'])) { $dim = explode('x', $_GET['window']); //WWWxHHH if (isset($dim[0]) && (int) $dim[0] > 0) { $width = (int) $dim[0]; } if (isset($dim[1]) && (int) $dim[1] > 0) { $height = (int) $dim[1]; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><?php echo HTML::chars($view->placeholder('title')); ?></title> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <meta http-equiv="Keywords" content="<?php echo HTML::chars($view->placeholder('keywords')); ?>" /> <meta http-equiv="Description" content="<?php echo HTML::chars($view->placeholder('description')); ?>" /> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/forms.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/tables.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend_ie6.css', NULL, FALSE, 'if lte IE 6'); ?> <?php echo $view->placeholder('styles'); ?> <?php echo $view->placeholder('scripts'); ?> </head> <body class="window_body"> <div class="window_caption"> <a href="#" class="close_window"><?php echo View_Helper_Admin::image('controls/close.gif'); ?></a> <?php if (isset($caption)) { echo $caption; } ?> </div> <div class="window_content" style="height: <?php echo $height; ?>px"> <div class="window_workspace"> <?php echo $content; ?> <?php if (Kohana::$profiling) { //echo View::factory('profiler/stats')->render(); } ?> </div> </div> </body> </html> <file_sep>/application/views/layouts/popup.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $id = $view->id; if ( ! Request::$is_ajax) { echo '<div id="' . $id . '_layer">' . '<div id="' . $id . '_blocker" class="popup_blocker"></div>' . '<div id="' . $id . '_wrapper" class="popup_wrapper">' . '<div id="' . $id .'" class="popup_widget">'; } echo $props; if (Request::$is_ajax) { echo '<div class="popup_content">' . '<a href="#" id="' . $id . '_close" class="popup_close">закрыть</a>'; } echo $content; if (Request::$is_ajax) { echo '</div>'; } if ( ! Request::$is_ajax) { echo '</div>' . '</div>' . '</div>'; }<file_sep>/modules/shop/catalog/classes/model/section/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Section_Mapper extends Model_Mapper_NestedSet { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('alias', array('Type' => 'varchar(63)', 'Key' => 'INDEX')); $this->add_column('sectiongroup_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('web_import_id', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('import_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(255)')); $this->add_column('description', array('Type' => 'text')); $this->add_column('meta_title', array('Type' => 'text')); $this->add_column('meta_description', array('Type' => 'text')); $this->add_column('meta_keywords', array('Type' => 'text')); $this->add_column('section_active', array('Type' => 'boolean', 'Key' => 'INDEX')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); $this->add_column('products_count', array('Type' => 'int unsigned')); $this->add_virtual_column('sectiongroup_name', array('Type' => 'varchar(31)')); } /** * Find section by condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Model */ public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } if (is_array($condition) && ! empty($condition['site_id'])) { // Left join section group to get site_id column $sectiongroup_table = Model_Mapper::factory('Model_SectionGroup_Mapper')->table_name(); $query->join($sectiongroup_table, 'INNER') ->on("$sectiongroup_table.id", '=', "$table.sectiongroup_id"); } if (is_array($condition) && ! empty($condition['parent'])) { // Find only descendants of given parent section if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } $query ->where("$table.lft", '>', $condition['parent']->lft) ->and_where("$table.rgt", '<', $condition['parent']->rgt) ->and_where("$table.level", '=', $condition['parent']->level + 1); unset($condition['parent']); } if ( ! empty($params['with_images'])) { // Select logo for section $image_table = Model_Mapper::factory('Model_Image_Mapper')->table_name(); // Select smallest image - the last one $image_sizes = Kohana::config('images.section'); $i = count($image_sizes); // Additinal columns $query->select( array("$image_table.image$i", 'image'), array("$image_table.width$i", 'image_width'), array("$image_table.height$i", 'image_height') ); $query ->join($image_table, 'LEFT') ->on("$image_table.owner_id", '=', "$table.id") ->on("$image_table.owner_type", '=', DB::expr("'section'")) ->join(array($image_table, 'img'), 'LEFT') ->on('"img".owner_id', '=', "$image_table.owner_id") ->on('"img".owner_type', '=', DB::expr("'section'")) ->on('"img".position', '<', "$image_table.position") ->where(DB::expr('ISNULL(img.id)'), NULL, NULL); } return parent::find_by($model, $condition, $params, $query); } /** * Find sections by condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Model */ public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { // ----- cache if ($this->cache_find_all) { $condition = $this->_prepare_condition($condition); $hash = $this->params_hash($params, $condition); if (isset($this->_cache[$hash])) { // Cache hit! return $this->_cache[$hash]; } } $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } if ( (is_array($condition) && ( ! empty($condition['site_id']))) || ( ! empty($params['with_sectiongroup_name'])) ) { // Left join section group to get site_id column $sectiongroup_table = Model_Mapper::factory('Model_SectionGroup_Mapper')->table_name(); $query->join($sectiongroup_table, 'INNER') ->on("$sectiongroup_table.id", '=', "$table.sectiongroup_id"); if ( ! empty($params['with_sectiongroup_name'])) { $query->select(array("$sectiongroup_table.name", 'sectiongroup_name')); } } if ( ! empty($params['with_images'])) { // Select logo for section $image_table = Model_Mapper::factory('Model_Image_Mapper')->table_name(); // Select smallest image - the last one $image_sizes = Kohana::config('images.section'); $i = count($image_sizes); // Additinal columns $query->select( array("$image_table.image$i", 'image'), array("$image_table.width$i", 'image_width'), array("$image_table.height$i", 'image_height') ); $query ->join($image_table, 'LEFT') ->on("$image_table.owner_id", '=', "$table.id") ->on("$image_table.owner_type", '=', DB::expr("'section'")) ->join(array($image_table, 'img'), 'LEFT') ->on('"img".owner_id', '=', "$image_table.owner_id") ->on('"img".owner_type', '=', DB::expr("'section'")) ->on('"img".position', '<', "$image_table.position") ->where(DB::expr('ISNULL(img.id)'), NULL, NULL); } /* if ( ! empty($params['with_active_products_count'])) { // slow, not used ... :-( $prodsec_table = Model_Mapper::factory('ProductSection_Mapper')->table_name(); $product_table = Model_Mapper::factory('Model_Product_Mapper')->table_name(); $query->select(array("COUNT(DISTINCT \"$product_table.id\")", 'products_count')); // Select number of active products in section and it's active subsections $query ->join(array($table, 'subsection'), 'INNER') ->on('"subsection".lft', '>=', "$table.lft") ->on('"subsection".rgt', '<=', "$table.rgt") ->on('"subsection".active', '=', DB::expr('1')) ->join($prodsec_table, 'LEFT') ->on("$prodsec_table.section_id", '=', '"subsection".id') ->join($product_table, 'LEFT') ->on("$product_table.id", '=', "$prodsec_table.product_id") ->on("$product_table.active", '=', DB::expr('1')); $query->group_by("$table.id"); } */ return parent::find_all_by($model, $condition, $params, $query); } /** * Return sections to which the given product belongs * * @param Model $model * @param Model_Product $product * @param array $params * @return Models */ public function find_all_by_product(Model $model, Model_Product $product, array $params = NULL) { $table = $this->table_name(); $prodsec_table = DbTable::instance('ProductSection')->table_name(); $query = DB::select_array($this->_prepare_columns($params)) ->from($table) ->join($prodsec_table, 'INNER') ->on("$table.id", '=', "$prodsec_table.section_id") ->where("$prodsec_table.product_id", '=', (int) $product->id) ->and_where("$prodsec_table.distance", '=', 0); $params['as_list'] = TRUE; return $this->find_all_by($model, NULL, $params, $query); } /** * Find all sections, except the subsection of given one for the specified section group * * @param Model $model * @param integer $sectiongroup_id * @param array $params * @return ModelsTree */ public function find_all_but_subtree_by_sectiongroup_id(Model $model, $sectiongroup_id, array $params = NULL) { return parent::find_all_but_subtree_by($model, DB::where('sectiongroup_id', '=', $sectiongroup_id), $params); } /** * Find all visible (which have their parents unfolded or are top-level) sections for the given site * @FIXME: This also loads unfolded branches that a children of folded ones - i.e. still invisible * Maybe switch to recursive version? * * @param Model $model * @param integer $sectiongroup_id * @param Model $parant * @param array $unfolded * @param array $params * @return ModelsTree|Models|array */ public function find_all_unfolded(Model $model, $sectiongroup_id, Model $parent = NULL, array $unfolded, array $params = NULL) { $table = $this->table_name(); $columns = $this->_prepare_columns($params); // "has_children" column $sub_q = DB::select('id') ->from(array($table, 'child')) ->where('"child".lft', '>', DB::expr($this->get_db()->quote_identifier("$table.lft"))) ->and_where('"child".rgt', '<', DB::expr($this->get_db()->quote_identifier("$table.rgt"))); $columns[] = array(DB::expr("EXISTS($sub_q)"), 'has_children'); $query = DB::select_array($columns) ->from($table) ->join(array($table, 'parent'), 'LEFT') ->on('"parent".lft', '<', "$table.lft") ->on('"parent".rgt', '>', "$table.rgt") ->on('"parent".level', '=', DB::expr($this->get_db()->quote_identifier("$table.level") . " - 1")); // ----- condition $condition = DB::where(); if ($sectiongroup_id !== NULL) { $condition->and_where("$table.sectiongroup_id", '=', $sectiongroup_id); } if ($parent !== NULL) { $condition ->and_where("$table.lft", '>', $parent->lft) ->and_where("$table.rgt", '<', $parent->rgt); } if ( ! empty($unfolded)) { $condition ->and_where_open() ->or_where('"parent".id', 'IN', DB::expr('(' . implode(',', $unfolded) . ')')); if ($parent === NULL) { $condition ->or_where('ISNULL("parent".id)'); } $condition ->and_where_close(); } elseif ($parent === NULL) { $condition->and_where('ISNULL("parent".id)'); } $tree = $this->find_all_by($model, $condition, $params, $query); if ($parent !== NULL && $tree instanceof ModelsTree) { // Set $parent as a root of the tree $tree->root($parent); } return $tree; } /** * Check if there is another section with given condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @return boolean */ public function exists_another_by(Model $model, $condition) { if (is_array($condition)) { if (isset($condition['parent']) && ($condition['parent']->id !== NULL)) { $parent = $condition['parent']; unset($condition['parent']); $condition = $this->_prepare_condition($condition); $table = $this->table_name(); $condition ->and_where("$table.lft", '>', $parent->lft) ->and_where("$table.rgt", '<', $parent->rgt) ->and_where("$table.level", '=', $parent->level + 1); } else { unset($condition['parent']); } } return parent::exists_another_by($model, $condition); } /** * Move section up * * @param Model $section * @param Database_Expression_Where $condition */ public function up(Model $section, Database_Expression_Where $condition = NULL) { parent::up($section, DB::where('sectiongroup_id', '=', $section->sectiongroup_id)); } /** * Move section down * * @param Model $section * @param Database_Expression_Where $condition */ public function down(Model $section, Database_Expression_Where $condition = NULL) { parent::down($section, DB::where('sectiongroup_id', '=', $section->sectiongroup_id)); } /** * Update activity for sections * * @param array $ids */ public function update_activity(array $ids = NULL) { $table = $this->table_name(); $query = DB::select("$table.id")->from($table); // ----- Does inactive parent section exist for the section? $sub_q = DB::select('id') ->from(array($table, 'parent')) ->where('"parent".lft', '<=', DB::expr($this->get_db()->quote_identifier("$table.lft"))) ->and_where('"parent".rgt', '>=', DB::expr($this->get_db()->quote_identifier("$table.rgt"))) ->and_where('"parent".section_active', '=', 0); $exists = DB::expr("NOT EXISTS($sub_q)"); $query->select(array($exists, 'active')); if ( ! empty($ids)) { // Update stats only for specified sections // Select their children - they will be affected too $more_ids = DB::select( "$table.id", array('"child".id', 'child_id') )->from($table) ->join(array($table, 'child'), 'LEFT') ->on('"child".lft', '>', "$table.lft") ->on('"child".rgt', '<', "$table.rgt") ->where("$table.id", 'IN', DB::expr('(' . implode(',', $ids) . ')')) ->execute($this->get_db()); foreach ($more_ids as $id) { if ( ! empty($id['id'])) $ids[] = $id['id']; if ( ! empty($id['child_id'])) $ids[] = $id['child_id']; } $ids = array_unique($ids); $query->where("$table.id", 'IN', DB::expr('(' . implode(',', $ids) . ')')); } $count = $this->count_rows(); $limit = 100; $offset = 0; $loop_prevention = 0; do { $sections = $query ->offset($offset)->limit($limit) ->execute($this->get_db()); foreach ($sections as $section) { $this->update(array( 'active' => $section['active'], ), DB::where('id', '=', $section['id'])); } $offset += count($sections); $loop_prevention++; } while ($offset < $count && count($sections) && $loop_prevention < 1000); if ($loop_prevention >= 1000) { throw new Kohana_Exception('Possible infinite loop in ' . __METHOD__); } } /** * Recalculate active products count for sections */ public function update_products_count(array $ids = NULL) { $table = $this->table_name(); $prodsec_table = DbTable::instance('ProductSection')->table_name(); $product_table = Model_Mapper::factory('Model_Product_Mapper')->table_name(); // Count active products $subq = DB::select(array("COUNT(DISTINCT \"$product_table.id\")", 'products_count')) ->from($product_table) ->join($prodsec_table, 'INNER') ->on("$prodsec_table.product_id", '=', "$product_table.id") ->where("$prodsec_table.section_id", '=', DB::expr($this->get_db()->quote_identifier("$table.id"))) ->and_where("$product_table.active", '=', 1); // Update product count for section $query = DB::update($table) ->set(array('products_count' => $subq)); if (is_array($ids)) { $ids = array_filter($ids); } if ( ! empty($ids)) { // Update stats only for specified sections // Select their parents - they will be affected too $more_ids = DB::select( "$table.id", array('"parent".id', 'parent_id') )->from($table) ->join(array($table, 'parent'), 'LEFT') ->on('"parent".lft', '<', "$table.lft") ->on('"parent".rgt', '>', "$table.rgt") ->where("$table.id", 'IN', DB::expr('(' . implode(',', $ids) . ')')) ->execute($this->get_db()); foreach ($more_ids as $id) { if ( ! empty($id['id'])) $ids[] = $id['id']; if ( ! empty($id['parent_id'])) $ids[] = $id['parent_id']; } $ids = array_unique($ids); $query->where("$table.id", 'IN', DB::expr('(' . implode(',', $ids) . ')')); } // do $query->execute($this->get_db()); } }<file_sep>/modules/shop/catalog/views/frontend/small_telemosts.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (!count($telemosts)) return; $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $today_flag= 0; $tomorrow_flag= 0; $nearest_flag = 0; ?> <div id='telemosts' class='widget'> <div class="wrapper main-list"> <div class="ub-title"> <p>Мои телемосты</p> <!--<a href="#" class="link-add">+ добавить</a>--> </div> <div class="ub-title"> </div> <hr> <?php $i=0; foreach ($telemosts as $telemost): $product = $telemost->product; $url = URL::site($product->uri_frontend()); $image=''; if (isset($product->image)) { $image = '<a href="' . $url . '">' . HTML::image('public/data/' . $product->image, array('alt' => $product->caption)) . '</a>'; } if (($today_flag == 0) && $product->datetime->format('d.m.Y') == $today_datetime->format('d.m.Y')) { $today_flag++; } elseif (($tomorrow_flag == 0) && $product->datetime->format('d.m.Y') == $tomorrow_datetime->format('d.m.Y')){ $tomorrow_flag++; } elseif ($nearest_flag == 0) { $nearest_flag++; } $day = $nearest_flag?$product->weekday:($tomorrow_flag?'Завтра':'Сегодня'); ?> <section class="mini"> <div class="row-fluid"> <div class="span2"><?php echo $image ?></div> <div class="span6"> <p><span class="date"><a class="day" href=""><?php echo $day?></a>, <?php echo $product->get_datetime_front()?> </span></p> <p class="title"><a href="<?php echo $url ?>"><?php echo $product->caption?></a></p> <p class="place"><?php echo $telemost->place->town_name?>: <?php echo $telemost->place->name ?></p> </div> <div class="span4"> <p><span class="type"><?php echo Model_Product::$_interact_options[$product->interact] ?></span></p> <!-- <p class="counter"><span title="я пойду" id="" class="go">999</span><span title="хочу телемост" id-"" class="hand">999</span></p> --> </div> </div> <a href="#" class="link-edit"><i class="icon-pencil icon-white"></i></a> </section> <?php if ($i == count($telemosts)) {?> <hr class='last_hr'> <?php } else { ?> <hr> <?php } ?> <?php endforeach; //foreach ($products as $product) ?> <?php if ($pagination) { echo $pagination; } ?> </div> </div> <file_sep>/modules/general/nodes/views/backend/nodes.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Set up urls $create_url = URL::to('backend/nodes', array('action'=>'create', 'nodes_node_id'=>$node_id), TRUE); $update_url = URL::to('backend/nodes', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/nodes', array('action'=>'delete', 'id' => '${id}'), TRUE); $up_url = URL::to('backend/nodes', array('action'=>'up', 'id' => '${id}'), TRUE); $down_url = URL::to('backend/nodes', array('action'=>'down', 'id' => '${id}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Создать страницу</a> </div> <?php if ( ! count($nodes)) // No users return; ?> <table class="table nodes"> <tr class="header"> <th>&nbsp;&nbsp;&nbsp;</th> <?php $columns = array( 'caption' => 'Название' ); echo View_Helper_Admin::table_header($columns, 'nodes_order', 'nodes_desc'); ?> </tr> <?php foreach ($nodes as $node) : $_update_url = str_replace('${id}', $node->id, $update_url); $_delete_url = str_replace('${id}', $node->id, $delete_url); $_up_url = str_replace('${id}', $node->id, $up_url); $_down_url = str_replace('${id}', $node->id, $down_url); // Highlight current node if ($node->id == $node_id) { $selected = 'selected'; } else { $selected = ''; } // Highlight inactive nodes if ( ! $node->node_active) { $active = 'node_inactive'; } elseif ( ! $node->active) { $active = 'inactive'; } else { $active = ''; } ?> <tr class="<?php echo Text::alternate('odd', 'even'); ?>"> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить раздел', 'controls/delete.gif', 'Удалить'); ?> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать раздел', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_up_url, 'Переместить вверх', 'controls/up.gif', 'Вверх'); ?> <?php echo View_Helper_Admin::image_control($_down_url, 'Переместить вниз', 'controls/down.gif', 'Вниз'); ?> </td> <td class="node <?php echo "$selected $active";?>"> <a class="node_caption" href="<?php echo $node->get_backend_url(TRUE);//$_update_url;?>" style="margin-left: <?php echo ($node->level-1)*15; ?>px"> <?php echo HTML::chars($node->caption); ?> </a> </td> </tr> <?php endforeach; ?> </table> <file_sep>/modules/shop/catalog/classes/model/productcomment/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_ProductComment_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('product_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('created_at', array('Type' => 'int unsigned')); $this->add_column('text', array('Type' => 'text')); $this->add_column('notify_client', array('Type' => 'boolean')); } }<file_sep>/modules/shop/catalog/views/frontend/products/theme_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $theme_url = URL::to('frontend/catalog/products', array('theme' => '{{theme}}'), TRUE); ?> <li class="dropdown"> <?php if ($theme) { $main_theme_url = URL::to('frontend/catalog/products', array('theme' => $theme), TRUE); ?> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="<?php echo $main_theme_url?>"><?php echo Model_Product::$_theme_options[$theme]?><b class="caret"></b></a> <?php } else { ?> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="">тема<b class="caret"></b></a> <?php } ?> <ul class="dropdown-menu" role="menu" aria-labelledby="drop10"> <?php foreach ($themes as $f_id => $f_name) { if ($f_name == $theme) continue; $_theme_url = str_replace('{{theme}}', $f_id, $theme_url); ?> <li><a role="menuitem" tabindex="-1" href="<?php echo $_theme_url ?>"><?php echo $f_name ?></a></li> <?php }?> </ul> </li><file_sep>/modules/general/indexpage/classes/controller/frontend/indexpage.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Indexpage extends Controller_Frontend { /** * Display an index page */ public function action_view() { // Current node $node = Model_Node::current(); if ( ! isset($node->id) || ! $node->active) { $this->_action_404('Страница не найдена'); return; } // Find page for current node $page = new Model_Page(); $page->find_by_node_id($node->id); if ( ! isset($page->id)) { $this->_action_404('Страница не найдена'); return; } // Find all images for this page $owner = 'indexpage_' . $page->id; $images = Model::fly('Model_Image')->find_all_by_owner($owner); $layout = $this->prepare_layout(); $layout->images = $images; $this->request->response = $layout->render(); } } <file_sep>/modules/shop/catalog/views/frontend/small_products.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div id='products' class='widget'> <?php $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $today_flag= 0; $tomorrow_flag= 0; $nearest_flag = 0; // ----- Set up urls $create_url = URL::to('frontend/catalog/products/control', array('action'=>'create')); $update_url = URL::to('frontend/catalog/products/control', array('action'=>'update', 'id' => '${id}'), TRUE); ?> <div class="wrapper main-list"> <div class="ub-title"> <p>Мои оффлайн-события</p> <a href="<?php echo $create_url?>" class="link-add">+ добавить</a> </div><div class="ub-title"></div> <hr> <?php $i=0; foreach ($products as $product): $i++; $url = URL::site($product->uri_frontend()); $telemosts = $product->get_telemosts(); $numTelemosts = count($telemosts); $image=''; if (isset($product->image)) { $image = '<a href="' . $url . '">' . HTML::image('public/data/' . $product->image, array('alt' => $product->caption)) . '</a>'; } if (($today_flag == 0) && $product->datetime->format('d.m.Y') == $today_datetime->format('d.m.Y')) { $today_flag++; } elseif (($tomorrow_flag == 0) && $product->datetime->format('d.m.Y') == $tomorrow_datetime->format('d.m.Y')){ $tomorrow_flag++; } elseif ($nearest_flag == 0) { $nearest_flag++; } $day = $nearest_flag?$product->weekday:($tomorrow_flag?'Завтра':'Сегодня'); ?> <section class="mini"> <div class="row-fluid"> <div class="span2"><?php echo $image ?></div> <div class="span6"> <p><span class="date"><a class="day" href=""><?php echo $day?></a>, <?php echo $product->get_datetime_front()?> </span></p> <p class="title"><a href="<?php echo $url ?>"><?php echo $product->caption?></a></p> <p class="place"><?php echo $product->place->town_name?>: <?php echo $product->place->name ?></p> </div> </div> <?php if ($product->user_id == Model_User::current()->id) { $_update_url = str_replace('${id}', $product->id, $update_url); ?> <a href="<?php echo $_update_url;?>" class="link-edit"><i class="icon-pencil icon-white"></i></a> <span class="link-edit-user-page-req">Заявки: <?php echo $numTelemosts ?></span> <?php } ?> </section> <?php if ($i == count($products)) {?> <hr class='last_hr'> <?php } else { ?> <hr> <?php } ?> <?php endforeach; //foreach ($products as $product) ?> <?php if ($pagination) { echo $pagination; } ?> </div> </div> <file_sep>/modules/general/indexpage/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { Route::add('frontend/indexpage', new Route_Frontend('')) ->defaults(array( 'controller' => 'indexpage', 'action' => 'view' )); } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/indexpage', new Route_Backend( 'indexpage(/<action>(/<node_id>))' . '(/~<history>)', array( 'action' => '\w++', 'node_id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'indexpage', 'action' => 'update', 'node_id' => NULL )); } /****************************************************************************** * Common ******************************************************************************/ // ----- Add node types Model_Node::add_node_type('indexpage', array( 'name' => 'Главная страница', 'backend_route' => 'backend/indexpage', 'frontend_route' => 'frontend/indexpage', 'model' => 'page' ));<file_sep>/modules/shop/catalog/views/backend/sections/list.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'backend/sections/list_branch')); // Set up urls $create_url = URL::to('backend/catalog/sections', array( 'action' => 'create', 'cat_section_id' => $section_id, 'cat_sectiongroup_id' => $sectiongroup_id), TRUE); $update_url = URL::to('backend/catalog/sections', array('action'=>'update', 'id' => '{{id}}'), TRUE); $delete_url = URL::to('backend/catalog/sections', array('action'=>'delete', 'id' => '{{id}}'), TRUE); $up_url = URL::to('backend/catalog/sections', array('action'=>'up', 'id' => '{{id}}'), TRUE); $down_url = URL::to('backend/catalog/sections', array('action'=>'down', 'id' => '{{id}}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } $multi_action_uri = URL::uri_to('backend/catalog/sections', array('action'=>'multi'), TRUE); $toggle_url = URL::to('backend/catalog/sections', array('action' => 'toggle', 'id' => '{{id}}', 'toggle' => '{{toggle}}'), TRUE); ?> <?php // Tabs to select current section group if (isset($sectiongroups)) { $tab_url = URL::to('backend/catalog/sections', array('cat_sectiongroup_id'=>'{{id}}')); echo '<div class="sectiongroup_tabs"><div class="tabs">'; foreach ($sectiongroups as $sectiongroup) { $_tab_url = str_replace('{{id}}', $sectiongroup->id, $tab_url); if ($sectiongroup->id == $sectiongroup_id) { echo '<a href="' . $_tab_url . '" class="selected">' . HTML::chars($sectiongroup->caption) . '</a>'; } else { echo '<a href="' . $_tab_url . '">' . HTML::chars($sectiongroup->caption) . '</a>'; } } echo '</div></div>'; } ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_section_add">Создать раздел</a> </div> <?php if ( ! $sections->has_children()) return; ?> <div class="sections tree" id="sections"> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="very_light_table"> <tr class="table_header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'caption' => 'Название', 'active' => 'Акт.' ); echo View_Helper_Admin::table_header($columns, 'cat_sorder', 'cat_sdesc'); ?> <th></th> </tr> <?php render_sections_branch( $sections, NULL, $unfolded, $update_url, $delete_url, $up_url, $down_url, $toggle_url, $section_id ); ?> </table> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?> </div><file_sep>/modules/shop/payment_check/classes/model/payment/check.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Payment_Check extends Model_Payment { }<file_sep>/modules/shop/orders/classes/model/orderstatus.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_OrderStatus extends Model { // Statuses with ids from 1 to MAX_SYSTEM_ID are considered as system const MAX_SYSTEM_ID = 100; // Predefined order status ids const STATUS_NEW = 1; const STATUS_COMPLETE = 2; const STATUS_CANCELED = 3; /** * Get status caption by id * * @param integer $id * @return string */ public static function caption($id) { // Obtain CACHED[!] collection of all statuses $statuses = Model::fly(__CLASS__)->find_all(array('key' => 'id')); if (isset($statuses[$id])) { return $statuses[$id]->caption; } else { return NULL; } } /** * Prohibit to change the "system" property * * @param boolean $value */ public function set_system($value) { // Intentionally blanks } /** * Validate status deletion * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->system) { $this->error('Свойство является системным. Его удаление запрещено!'); return FALSE; } return parent::validate_delete($newvalues); } }<file_sep>/modules/backend/classes/view/helper/admin.php <?php class View_Helper_Admin { /** * Renders table header row with ability to sort by columns * * @param array $columns List of columns * @param string $order_by_param Name of parameter in request that holds order column name * @param string $desc_param Name of parameter in request that holds the ordering direction * @param Request $request Request * @return html */ public static function table_header(array $columns, $order_by_param = 'order', $desc_param = 'desc', $desc_default = TRUE) { $request = Request::current(); $current_order_by = $request->param($order_by_param); $current_desc = $request->param($desc_param); $html = ''; foreach ($columns as $field => $column) { if (is_array($column)) { $label = isset($column['label']) ? $column['label'] : $field; $sort_field = isset($column['sort_field']) ? $column['sort_field'] : $field; $sortable = isset($column['sortable']) ? (bool) $column['sortable'] : TRUE; } else { $label = $column; $sort_field = $field; $sortable = TRUE; } if ($sortable) { $class = ''; if ($current_order_by == $sort_field) { $class = $current_desc ? 'class="sort_desc"' : 'class="sort_asc"'; $desc = $current_desc ? '0' : '1'; } else { $desc = $desc_default ? '1' : '0'; } $url = URL::self(array($order_by_param => $sort_field, $desc_param => $desc)); $html .= '<th><a href="' . $url . '" ' . $class . '>' . $label .'</a></th>'; } else { $html .= '<th><span>' . $label . '</span></th>'; } } return $html; } /** * Renders tabs * * @param array $tabs * @param string $selected * @return string */ public static function tabs($tabs, $selected) { $html = '<div class="tabs">'; foreach ($tabs as $tab_value => $tab) { $class = ($tab_value == $selected) ? ' class="selected"' : ''; $icon = (isset($tab['icon'])) ? $tab['icon'] : ''; $html .= '<a href="' . $tab['url'] . '"' . $class . '><div class="corner left"><div class="corner right">' . ' <div class="icon' . $icon . '">' . HTML::chars($tab['label']) . '</div>' . '</div></div></a>'; } $html .= '</div>'; return $html; } /** * Renders a control button - a html link with image * * @param string $url * @param string $title * @param string $image * @param string $alt * @param string $module * @return string */ public static function image_control($url, $title, $image, $alt = NULL, $module = 'backend') { if ($alt === NULL) { $alt = $title; } return '<a href="' . $url . '" title="' . HTML::chars($title) . '">' . self::image($image, $alt, $module) . '</a>'; } /** * Renders an image * * @param string $image * @param string $alt * @param string $module * @return string */ public static function image($image, $alt = NULL, $module = 'backend') { return HTML::image(Modules::uri($module) . '/public/css/backend/' . $image, array('alt' => $alt)); } /** * Open multi-action form * * @param string $uri * @return string */ public static function multi_action_form_open($uri, array $attributes = array()) { // Apply "multi_action" class $attributes['class'] = isset($attributes['class']) ? $attributes['class'] . ' multi_action' : 'multi_action'; return Form_Helper::open($uri, $attributes); } /** * Render a checkbox to select an item in multi-action form * * @param mixed $value * @return string */ public static function multi_action_checkbox($value) { return '<input type="checkbox" name="ids[]" value="' . HTML::chars($value) . '" class="checkbox sel" />'; } /** * Render a checkbox to select all items in multi-action form * * @return string */ public static function multi_action_select_all() { return '<input type="checkbox" name="toggle_all" value="1" class="checkbox toggle_all" />'; } /** * Render submit buttons for multi-action form * * @param array $actions * @return string */ public static function multi_actions(array $actions, $text = 'с отмеченными:') { $html = '<div class="table_multi_action">' . ' <div class="buttons">' . $text; foreach ($actions as $action) { $act = $action['action']; $class = isset($action['class']) ? $action['class'] : $act; $label = isset($action['label']) ? $action['label'] : $act; $html .= ' <span class="button ' . $class . '">' . ' <input type="submit" name="action[' . $act .']" value="' . $label . '" />' . '</span>'; } $html .= ' </div>' . '</div>'; return $html; } /** * Close a multi-action form * * @return string */ public static function multi_action_form_close() { return Form_Helper::close(); } protected function __construct() { // This is a static class } }<file_sep>/modules/shop/catalog/public/js/frontend/datesearch.js $("#datesearch").datepicker({ minDate: -1, maxDate: "+2M", }); $('#datesearch_show').click(function(){return false;}); $("#datesearch_show").datepicker({ onSelect: function (dateText) { if ( ! datesearch_url) return; dateText=dateText.split("-"); var newDate=dateText[1]+"/"+dateText[0]+"/"+dateText[2]; var url = datesearch_url.replace('{{d}}', new Date(newDate).getTime()/1000); document.location = url; } }); <file_sep>/modules/system/forms/classes/form/validator/filename.php <?php defined('SYSPATH') or die('No direct script access.'); /** * File name validator. * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_Filename extends Form_Validator_Regexp { const INVALID = 'INVALID'; protected $_messages = array( self::INVALID => 'Invalid value specified: should be string', self::EMPTY_STRING => 'Вы не указали :label!', self::NOT_MATCH => 'Поле ":label" содержит недопустимые символы!' ); /** * Creates File name validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty strings */ public function __construct(array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE) { $regexp = '/^[^\\\\\/]+$/'; //fuck my brain O_o \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ parent::__construct($regexp, $messages, $breaks_chain, $allow_empty); } /** * Validate * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $value = $this->_value; if (!is_string($value)) { $this->_error(self::INVALID); return false; } return parent::_is_valid($context); } }<file_sep>/modules/general/chat/classes/model/dialog.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Dialog extends Model { public function get_opponent() { $current_user = Auth::instance()->get_user(); $opponent_id = ($current_user->id == $this->sender_id) ?$this->receiver_id : $this->sender_id; return Model::fly('Model_User')->find($opponent_id); } /** * Get frontend uri to the product */ public function uri_frontend() { static $uri_template; if ($uri_template === NULL) { $uri_template = URL::uri_to('frontend/messages', array( 'dialog_id' => $this->id )); } return $uri_template; } /** * Default active for dialog * * @return bool */ public function default_sender_active() { return TRUE; } /** * Default active for dialog * * @return bool */ public function default_receiver_active() { return TRUE; } /** * Default site id for dialog * * @return id */ public function default_site_id() { return Model_Site::current()->id; } /** * Default sender id for dialog * * @return id */ public function default_sender_id() { return Auth::instance()->get_user()->id; } /** * Delete dialog and all messages from it */ public function delete() { // Delete all messages from dialog Model::fly('Model_Message')->delete_all_by_dialog_id($this->id); // Delete group itself parent::delete(); } } <file_sep>/modules/backend/views/backend/breadcrumbs.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ( ! count($path)) { return; } ?> <?php $i = count($path); foreach ($path as $item) { $i--; if ($i > 0) { echo '<a href="' . Model_Backend_Menu::url($item) .'"' . (isset($item['title']) ? ' title="' . HTML::chars($item['title']) . '"' : '') . '>' . $item['caption'] . '</a>'; echo '&nbsp;&raquo;&nbsp;'; } else { echo '<span>' . $item['caption'] . '</span>'; } } ?><file_sep>/modules/shop/payments/classes/controller/backend/payment.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Base class for payment module backend controller */ abstract class Controller_Backend_Payment extends Controller_BackendCRUD { /** * Set up default actions for payment module controller */ public function setup_actions() { $module = substr(get_class($this), strlen('Controller_Backend_Payment_')); return array( 'create' => array( 'model' => "Model_Payment_$module", 'form' => "Form_Backend_Payment_$module", 'view' => 'backend/form', 'view_caption' => 'Добавление способа оплаты' ), 'update' => array( 'model' => "Model_Payment_$module", 'form' => "Form_Backend_Payment_$module", 'view' => 'backend/form', 'view_caption' => 'Редактирование способа оплаты ":caption"' ), 'delete' => array( 'model' => "Model_Payment_$module", 'view' => 'backend/form', 'view_caption' => 'Удаление способа оплаты', 'message' => 'Удалить способ оплаты ":caption"?' ) ); } /** * Create layout (proxy to orders controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('orders')->prepare_layout($layout_script); } /** * Render layout (proxy to orders controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('orders')->render_layout($content, $layout_script); } /** * Create action */ public function action_create() { $this->_action('create', array('redirect_uri' => URL::uri_back(NULL, 2))); // Redirect two steps back } }<file_sep>/application/views/pagination_small.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($pages_count < 2) { return; } ?> Страницы: <?php if ($rewind_to_first) { echo '<a href="' . URL::self(array($page_param => 0), $ignored_params) . '" class="rewind">&laquo;</a>'; } for ($i = $l; $i <= $r; $i++) { if ($i == $page) { echo '<span class="active">' . ($i+1) .'</span>'; } else { echo '<a href="' . URL::self(array($page_param => $i), $ignored_params) . '">' . ($i+1) . '</a>'; } } if ($rewind_to_last) { echo '<a href="' . URL::self(array($page_param => $pages_count - 1), $ignored_params) . '" class="rewind">&raquo;</a>'; } ?> <file_sep>/modules/shop/catalog/views/backend/sections/menu_ajax.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'backend/sections/menu_branch')); // Set up urls /* $update_url = URL::to('backend/catalog/sections', array('action'=>'update', 'id' => '{{id}}'), TRUE); $delete_url = URL::to('backend/catalog/sections', array('action'=>'delete', 'id' => '{{id}}'), TRUE); $up_url = URL::to('backend/catalog/sections', array('action'=>'up', 'id' => '{{id}}'), TRUE); $down_url = URL::to('backend/catalog/sections', array('action'=>'down', 'id' => '{{id}}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } * */ $toggle_url = URL::to('backend/catalog/sections', array('action' => 'toggle', 'id' => '{{id}}', 'toggle' => '{{toggle}}'), TRUE); $history = Request::current()->param('history'); if (isset($history)) { //$url = URL::to('backend/catalog/products', array('cat_section_id' => '{{id}}', 'history' => $history), TRUE); } else { //$url = URL::to('backend/catalog/products', array('cat_section_id' => '{{id}}')); } $url = URL::self(array('cat_section_id' => '{{id}}')); ?> <?php render_sections_menu_branch( $sections, $parent, $unfolded, /*$update_url, $delete_url, $up_url, $down_url, */$toggle_url, $url, NULL ); ?><file_sep>/modules/shop/acl/classes/controller/frontend/organizers.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Organizers extends Controller_Frontend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = 'layouts/acl') { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } public function action_index() { //TODO CARD of the USER } /** * Display autocomplete options for a postcode form field */ public function action_ac_organizer_name() { $organizer_name = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $organizer_name = UTF8::str_ireplace("ё", "е", $organizer_name); if ($organizer_name == '') { $this->request->response = ''; return; } $limit = 7; $organizers = Model::fly('Model_Organizer')->find_all_like_name($organizer_name,array('limit' => $limit)); // if ( ! count($organizers)) // { // $this->request->response = ''; // return; // } $items = array(); $pattern = new View('frontend/organizer_ac'); $i=0; foreach ($organizers as $organizer) { $name = $organizer->name; $id = $organizer->id; $image_info = $organizer->image(4); $pattern->name = $name; $pattern->num = $i; $pattern->image_info = $organizer->image(4); $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name, 'id' => $id) ); $i++; } $items[] = array('caption' => '<a data-toggle="modal" href="#OrgModal" class="active">Добавить новую организацию</a>'); $this->request->response = json_encode($items); } } <file_sep>/modules/shop/sites/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/sites', new Route_Backend( 'sites(/<action>(/<id>))' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'sites', 'action' => 'index', 'id' => NULL )); // ----- Add backend menu items if (Kohana::config('sites.multi')) { Model_Backend_Menu::add_item(array( 'id' => 1, 'menu' => 'main', 'caption' => 'Магазины', 'route' => 'backend/sites', 'icon' => 'sites' )); } else { Model_Backend_Menu::add_item(array( 'id' => 1, 'menu' => 'main', 'caption' => 'Настройки', 'route' => 'backend/sites', 'route_params' => array('action' => 'update'), 'icon' => 'settings' )); } } /****************************************************************************** * Module installation ******************************************************************************/ if (Kohana::$environment !== Kohana::PRODUCTION) { if ( ! Kohana::config('sites.multi')) { // Create the default site for single-site environment $site = Model_Site::current(); if ( ! isset($site->id)) { $site->caption = 'Новый сайт'; $site->domain = 'example.com'; $site->save(); } } } <file_sep>/modules/shop/acl/views/privilege_templates/default.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ( ! count($privileges)) { // No menu nodes return; } ?> <ul> <?php foreach ($privileges as $privilege) { if (!$privilege->readable) continue; echo '<li><a href="' . URL::site($privilege->frontend_uri) . '"' . '>' . HTML::chars($privilege->caption) . '</a></li>'; } ?> </ul><file_sep>/modules/shop/acl/classes/form/frontend/register.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Register extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/forms/register'; $element = new Form_Element_Hidden('group_id', array('id' => 'group_id')); $element->value = Model_Group::USER_GROUP_ID; $this->add_component($element); // ----- email $email = new Form_Element_Input('email', array('label' => 'E-Mail', 'required' => TRUE), array('maxlength' => 31, 'placeholder' => 'E-Mail')); $email->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Email()); $this->add_component($email); // ----- Password $element = new Form_Element_Password('password', array('label' => 'Пароль', 'required' => TRUE), array('maxlength' => 255, 'placeholder' => 'Пароль') ); $element ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_StringLength(0, 255)); $this->add_component($element); // ----- Password confirmation $element = new Form_Element_Password('password2', array('label' => 'Подтверждение', 'required' => TRUE), array('maxlength' => 255, 'placeholder' => 'Повтор пароля') ); $element ->add_validator(new Form_Validator_NotEmptyString(array( Form_Validator_NotEmptyString::EMPTY_STRING => 'Вы не указали подтверждение пароля!', ))) ->add_validator(new Form_Validator_EqualTo( 'password', array( Form_Validator_EqualTo::NOT_EQUAL => 'Пароль и подтверждение не совпадают!', ) )); $this->add_component($element); // organizer $element = new Form_Element_Hidden('organizer_id',array('id' => 'organizer_id')); $this->add_component($element); $element->value = Model_Organizer::DEFAULT_ORGANIZER_ID; $element = new Form_Element_Hidden('organizer_name',array('id' => 'organizer_name')); $this->add_component($element); $element->value = Model_Organizer::DEFAULT_ORGANIZER_NAME; $element = new Form_Element_Hidden('town_id',array('id' => 'town_id')); $this->add_component($element); $element->value = Model_Town::DEFAULT_TOWN_ID; // ----- Form buttons $button = new Form_Element_Button('submit_register', array('label' => 'Регистрация'), array('class' => 'button_login button-modal') ); $this->add_component($button); parent::init(); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts Layout::instance()->add_script(Modules::uri('jquery') . '/public/js/jquery.xtsaveform.js'); Layout::instance()->add_script(Modules::uri('acl') . '/public/js/frontend/register.js'); } }<file_sep>/modules/shop/acl/views/backend/logout.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $logout_url = URL::to('backend/acl', array('action' => 'logout')); ?> <div class="logout"> <a href="<?php echo $logout_url; ?>">&raquo; Выход</a> </div> <file_sep>/modules/shop/catalog/classes/model/plistproduct/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PListProduct_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('plist_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('product_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); } /** * Find all products in list joining the product information * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $product_table = Model_Mapper::factory('Model_Product_Mapper')->table_name(); $plistproduct_table = $this->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array( "$plistproduct_table.*", "$product_table.caption", "$product_table.active" ); $query = DB::select_array($columns) ->from($plistproduct_table) ->join($product_table, 'INNER') ->on("$product_table.id", '=', "$plistproduct_table.product_id"); return parent::find_all_by($model, $condition, $params, $query); } }<file_sep>/modules/shop/area/views/frontend/forms/place.php <div id="PlaceModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Добавить площадку</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <label for="name"><?php echo $form->get_element('name')->render_input(); ?></label> <?php echo $form->get_element('name')->render_alone_errors();?> <label for="town_id"><?php echo $form->get_element('town_id')->render_input(); ?></label> <?php echo $form->get_element('town_id')->render_alone_errors();?> <label for="address"><?php echo $form->get_element('address')->render_input(); ?></label> <?php echo $form->get_element('address')->render_alone_errors();?> <label for="description"> <?php echo $form->get_element('description')->render_input(); ?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Какие события тут проходили, какие темы событий интересны площадке.">?</a> </label> <?php echo $form->get_element('description')->render_alone_errors();?> <label for="ispeed">Доступ к интернету: <?php echo $form->get_element('ispeed')->render_input(); ?></label> <?php echo $form->get_element('ispeed')->render_alone_errors();?> <label for="links"><?php echo $form->get_element('links')->render_input(); ?></label> <?php echo $form->get_element('links')->render_alone_errors();?> <?php echo $form->get_element('file')->render_label(); echo $form->get_element('file')->render_input(); ?> <?php echo $form->get_element('file')->render_alone_errors();?> <div id="prev_<?php echo $form->get_element('file')->id?>" class="prev_container"></div><br/> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_place')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div> <file_sep>/modules/shop/catalog/views/frontend/sections/list.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $url_template = URL::to('frontend/catalog/products', array( 'sectiongroup_name' => $sectiongroup->name, 'path' => '{{path}}' )) . '/'; ?> <div class="toptext"> <div> <?php echo Widget::render_widget('blocks', 'block', 'sec_top'); ?> </div> </div> <?php if ( ! count($sections->children())) { echo '<i>Категорий нет</i>'; return; } ?> <table cellpadding="0" cellspacing="0" class="brands"> <?php foreach ($sections->children() as $section) : $path = $section->alias; $url = URL::site($section->uri_frontend()); //$url = str_replace('{{path}}', $path, $url_template); ?> <tr> <td> <a href="<?php echo $url; ?>"> <?php if (isset($section->image)) { echo HTML::image('public/data/' . $section->image, array('alt' => $section->caption)); } else { echo HTML::image('public/css/logos/no-logo.gif', array('alt' => $section->caption)); } ?> </a> <td> <h4> <?php echo '<a href="' . $url . '">' . HTML::chars($section->caption) . ($section->products_count > 0 ? ' [' . $section->products_count . ']' : '') . '</a>' ?> </h4> <div> <?php $subsections = $sections->children($section); $count = count($subsections); $i = 0; foreach ($subsections as $subsection) { $subpath = $path . '/' . $subsection->alias; $url = URL::site($subsection->uri_frontend()); //$url = str_replace('{{path}}', $subpath, $url_template); echo '<a href="' . $url . '">' . HTML::chars($subsection->caption) . ($subsection->products_count > 0 ? ' [' . $subsection->products_count . ']' : '') . '</a>'; if ($i < $count - 1) { echo '&nbsp;|&nbsp; '; } $i++; } ?> </div> </td> </tr> <?php endforeach; ?> </table><file_sep>/modules/shop/catalog/classes/task/import/gulliver.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Import catalog from www.gulliver.ru */ class Task_Import_Gulliver extends Task_Import_Web { /** * Construct task */ public function __construct() { parent::__construct('http://www.gulliver.ru'); } /** * Run the task */ public function run() { $this->set_progress(0); $brands = Kohana::cache('gulliver_brands', NULL, 7200); // 2 hour if ($brands === NULL) { // import brands $brands = $this->import_brands(); Kohana::cache('gulliver_brands', $brands); } // import products $this->import_products($brands); $this->set_status_info('Импорт завершён'); } /** * Import brands * * @return array $brands */ public function import_brands() { $brands = array(); $this->import_brands_branch($brands); // Finally update activity & stats for all sections Model::fly('Model_Section')->mapper()->update_stats(); return $brands; } /** * Import a branch of brands recursively * * @param array $brands * @param Model_Section $parent * @param array $parent_info */ public function import_brands_branch(array & $brands, Model_Section $parent = NULL, array $parent_info = NULL) { $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task // get all properties $properties = Model::fly('Model_Property')->find_all_by_site_id($site_id, array('columns' => array('id'))); $propsections = array(); foreach ($properties as $property) { $propsections[$property['id']] = array( 'active' => 1, 'filter' => 0, 'sort' => 0 ); } $brand = new Model_Section(); $url_path = isset($parent_info['url_path']) ? $parent_info['url_path'] : ''; // Open brand page $page = $this->get('/catalogue/toys' . $url_path); // Find all subbrands $result = preg_match_all( '!' . '<td\s*class="groupFoto">\s*' . '<a\s*href="/catalogue/toys' . $url_path . '/((group_)?\d+)/?">\s*' . '<img\s*src="([^"]*)"[^>]*>.*?' . '<a\s*class="likeText"[^>]*>\s*([^—<]*)' . '!uis', $page, $matches, PREG_SET_ORDER); $count = count($matches); $i = 0; foreach ($matches as $match) { if ($parent === NULL) { // Report progress only for top-level brands $this->set_status_info('Importing brands: ' . $i . ' of ' . $count); $this->set_progress((int) (100 * $i / $count)); $i++; } $id = $match[1]; $caption = $this->decode_trim($match[4], 255); $image_url = trim($match[3]); $parent_id = isset($parent_info['id']) ? $parent_info['id'] : 0; $brand_info = array( 'id' => $id, 'caption' => $caption, 'image_url' => $image_url, 'url_path' => $url_path . '/' . $id ); $brands[$parent_id][$id] = $brand_info; // get brand description $page = $this->get('/catalogue/toys' . $url_path . '/' . $id . '/?mode=info'); if (preg_match('!<div id="Content">\s*<h3[^>]*>.*?</h3>(.*?)</div>!uis', $page, $m)) { // cut out images, links and empty <p> from description $description = trim($m[1]); $description = preg_replace('!<img[^>]*>!', '', $description); $description = preg_replace('!<a[^>]*>.*?</a>!', '', $description); $description = preg_replace('!<p[^>]*>(\s|&nbsp;)*</p>!', '', $description); } else { $description = ''; } if ($parent === NULL) { $brand->find_by_caption_and_sectiongroup_id($caption, $sectiongroup_id); } else { $brand->find_by_caption_and_parent($caption, $parent); } $creating = ( ! isset($brand->id)); $brand->sectiongroup_id = $sectiongroup_id; if ($parent !== NULL) { $brand->parent_id = $parent->id; } $brand->caption = $caption; $brand->description = $description; // Select all additional properties $brand->propsections = $propsections; $brand->save(FALSE, FALSE); // Reload brand to obtain correct id, lft and rgt values $brand->find($brand->id, array('columns' => array('id', 'lft', 'rgt', 'level'))); // Brand logo if ($creating) { $image_file = $this->download_cached($image_url); if ($image_file) { $image = new Model_Image(); /* if ( ! $creating) { // Delete possible existing images for section $image->delete_all_by_owner_type_and_owner_id('section', $brand->id); } */ try { $image->source_file = $image_file; $image->owner_type = 'section'; $image->owner_id = $brand->id; $image->config = 'section'; $image->save(); } catch (Exception $e) {} } } // ----- subbrans $this->import_brands_branch($brands, $brand, $brand_info); } // foreach $brand return $brands; } /** * Import products * * @param array $brands */ public function import_products(array $brands) { $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task $brand = new Model_Section(); $product = new Model_Product(); // Caclulate progress info $count = count($brands, COUNT_RECURSIVE) - count($brands); $i = 0; $this->set_status_info('Importing products'); $_imported = array(/* '225', 'group_46527', '226', 'group_41053', 'group_56132', 'group_46989', '231', 'group_46487', 'group_46581', '241', 'group_51213', 'group_51814', 'group_47677', '222', '232', 'group_54376', 'group_55896', '27292', '243', '239', '240', '239', '240', 'group_57187' , 'group_57469', 'group_58056', 'group_58187', 'group_58326', 'group_45062', 'group_45131', 'group_53175', 'group_41112', 'group_41113', 'group_41114', 'group_46367', 'group_54258', 'group_48693', 'group_57566', 'group_32473', 'group_32474', 'group_32475', 'group_32476', 'group_32478', 'group_32479', 'group_32480', 'group_38544', 'group_49452', 'group_46096', 'group_46211', 'group_35451', 'group_35553', 'group_35806', 'group_35804', 'group_35805', 'group_35802', 'group_35803' * */ ); $status_info = ''; foreach ($brands as $brands_branch) { foreach ($brands_branch as $brand_info) { if (in_array($brand_info['id'], $_imported)) continue; $status_info .= $brand_info['id'] . "\n"; $this->set_status_info($status_info); $this->set_progress((int) (100 * $i / $count)); $i++; $brand->find_by_caption_and_sectiongroup_id($brand_info['caption'], $sectiongroup_id, array('columns' => array('id', 'lft', 'rgt', 'level'))); // Obtain first page of the paginated results $page = $this->get('/catalogue/toys' . $brand_info['url_path']); // Detect number of pages if products display is paginated $offset = 0; $max_offset = 0; $per_page = 24; preg_match_all('!<a.*?href="[^"]*from=(\d+)!', $page, $matches); if ( ! empty($matches[1])) { $per_page = min($matches[1]); $max_offset = max($matches[1]); } // Iterate over pages for ($offset = 0; $offset <= $max_offset; $offset += $per_page) { if ($offset > 0) { // obtain next page $page = $this->get('/catalogue/toys' . $brand_info['url_path'] . '/?from=' . $offset); } // detect maximum page number on every page preg_match_all('!<a.*?href="[^"]*from=(\d+)!', $page, $matches); if ( ! empty($matches[1])) { $new_max_offset = max($matches[1]); if ($new_max_offset > $max_offset) { $max_offset = $new_max_offset; } } $result = preg_match_all( '!' . '<td\s*class="goodFoto">\s*' . '<a\s*href="/catalogue/toys' . $brand_info['url_path'] . '/([^"/]*)' . '!uis', $page, $matches); foreach (array_unique($matches[1]) as $product_id) { $url = '/catalogue/toys' . $brand_info['url_path'] . '/' . $product_id; $page = $this->get($url); // caption if (preg_match('!<div\s*id="Content">\s*<h3[^>]*>\s*([^<]+)!i', $page, $m)) { $caption = $this->decode_trim($m[1], 255); } else { FlashMessages::add('Unable to determine caption for product ' . $url, FlashMessages::ERROR); continue; //throw new Kohana_Exception('Unable to determine caption for product :url ', array(':url' => $url)); } $product->find_by_caption_and_section_id($caption, $brand->id, array('with_properties' => FALSE)); $creating = ( ! isset($product->id)); // Set caption $product->caption = $caption; // Link to brand $product->section_id = $brand->id; // Marking if (preg_match('!Арт.\s*([^<]*)!', $page, $m)) { $product->marking = $this->decode_trim($m[1], 63); } // Description if (preg_match('!<img\s*class="goodFotoBig"[^>]*>(.*?)</div>!is', $page, $m)) { $product->description = trim($m[1]); } $product->save(); // Product images $image = new Model_Image(); if ($creating) { /* if ( ! $creating) { // Delete already existing images for product $image->delete_all_by_owner_type_and_owner_id('product', $product->id); } */ // main image preg_match_all( '!<img\s*class="goodFotoBig"\s*src="([^"]*)"!', $page, $m1); // additional popup images preg_match_all( '!<a\s*href="([^"]*)"\s*onclick="wop\(!', $page, $m2); // additional non-popup images if (preg_match('!<div class="goodGalery">.*?</div>!is', $page, $m)) { preg_match_all('~<img\s*src="([^"]*)"[^>]*>\s*(?!</a>)~i', $m[0], $m3); } else { $m3 = array(1 => array()); } foreach (array_unique(array_merge($m1[1], $m2[1], $m3[1])) as $image_url) { $image_file = $this->download_cached($image_url); if ($image_file) { try { $image = new Model_Image(); $image->source_file = $image_file; $image->owner_type = 'product'; $image->owner_id = $product->id; $image->config = 'product'; $image->save(); unset($image); } catch (Exception $e) {} } } } } // foreach $offset } // foreach $product_id } //foreach $brand }// foreach $brands_branch } } <file_sep>/modules/shop/payments/classes/form/backend/payment.php <?php defined('SYSPATH') or die('No direct script access.'); abstract class Form_Backend_Payment extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "w500px wide lb120px"); // ----- Module $modules = Model_Payment::modules(); $options = array(); foreach ($modules as $module_info) { $caption = isset($module_info['caption'])? $module_info['caption']: $module_info['module']; $options[$module_info['module']] = $caption; } $element = new Form_Element_Select('module', $options, array('label' => 'Модуль', 'required' => TRUE, 'disabled' => TRUE)); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Description $this->add_component(new Form_Element_Textarea('description', array('label' => 'Описание'))); // ----- Supported delivery types $deliveries = Model::fly('Model_Delivery')->find_all(array('order_by' => 'id', 'desc' => FALSE)); $options = array(); foreach ($deliveries as $delivery) { $options[$delivery->id] = $delivery->caption; } $element = new Form_Element_CheckSelect('delivery_ids', $options, array('label' => 'Возможные способы доставки')); $element->config_entry = 'checkselect_fieldset'; $this->add_component($element); } } <file_sep>/modules/shop/orders/public/js/backend/order.js /** * Change user in order form */ function on_user_select(user) { var f = jforms['order1']; // change "user_id" element value var e = f.get_element('user_id'); if (user['id']) { e.set_value(user['id']); // Change personal data for (var name in {'user_name' : '', 'first_name' : '', 'last_name' : '', 'middle_name' : ''}) { e = f.get_element(name); e.set_value(user[name]); } } else { e.set_value(0); f.get_element('user_name').set_value('---'); } } /** * Apply product values in order product form */ function on_product_select(product) { var f = jforms['orderproduct1']; for (var name in f.get_elements()) { if (product[name] !== undefined) { f.get_element(name).set_value(product[name]); } } }<file_sep>/modules/shop/acl/views/frontend/lecturer_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php list($hist_route, $hist_params) = URL::match(URL::uri_back()); $hist_params['lecturer_id'] = '{{lecturer_id}}'; $select_url = URL::to($hist_route, $hist_params, TRUE); $hist_params['lecturer_id'] = 0; $no_lecturer_url = URL::to($hist_route, $hist_params, TRUE); ?> <div id="lecturer_select"> <div class="no_lecturer"> <em><a href="<?php echo $no_lecturer_url; ?>" class="lecturer_select" id="lecturer_0">&raquo; Без лектора</a></em> </div> <table class="very_light_table"> <tr class="table_header"> <?php $columns = array( 'image' => 'Фото', 'name' => 'Имя' ); echo View_Helper_Admin::table_header($columns, 'acl_lorder', 'acl_ldesc'); ?> </tr> <?php foreach ($lecturers as $lecturer) : $image_info = $lecturer->image(4); $_select_url = str_replace('{{lecturer_id}}', $lecturer->id, $select_url); ?> <tr> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if ($field === 'image') { echo '<a href="' . $_select_url . '" class="lecturer_select" id="lecturer_' . $lecturer->id . '">' . HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'])) . '</a></td>'; } if (isset($lecturer->$field) && trim($lecturer->$field) !== '') { echo '<a href="' . $_select_url . '" class="lecturer_select" id="lecturer_' . $lecturer->id . '">' . HTML::chars($lecturer->$field) . '</a>'; } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> </tr> <?php endforeach; //foreach ($lecturers as $lecturer) ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php if (empty($_GET['window'])) : ?> <div class="back"> <div class="buttons"> <a href="<?php echo URL::back(); ?>" class="button_adv button_cancel"><span class="icon">Назад</span></a> </div> </div> <?php endif; ?> </div><file_sep>/modules/shop/catalog/views/frontend/plist.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'frontend/products/_helper')); ?> <h2 class="title"><?php echo HTML::chars($plist->caption); ?></h2> <div class="separator"></div> <?php if ( ! count($products)) { echo '<i>Анонсов нет</i>'; return; } ?> <table class="products" cellpadding="0" cellspacing="0"> <?php $count = count($products); $rows = ceil($count / $cols); $i = 0; $cell_i = 0; $row_i = 0; $products->rewind(); while ($i < $count) { echo '<tr>'; for ($cell_i = 0; $cell_i < $cols; $cell_i++, $i++) { if ($i >= $count) { echo '<td class="last"></td>'; continue; } $product = $products->current(); $products->next(); // build brands, subbrands and categories for product list($brands_html, $series_html, $cat_html) = brands_and_categories($product); $url = URL::site($product->uri_frontend()); echo '<td' . ($cell_i >= $cols - 1 ? ' class="last"' : '') . '>' . '<table class="image"><tr><td>'; if (isset($product->image)) { echo '<a href="' . $url . '">' . HTML::image('public/data/' . $product->image, array( 'width' => $product->image_width, 'height' => $product->image_height, 'alt' => $product->caption)) . '</a>'; } echo '</td></tr></table>' . '<a href="' . $url . '">' . '<strong>' . HTML::chars($product->caption) . '</strong>' . '</a>' . '<div class="lh20">' . 'Бренд: ' . $brands_html . ' <br />' . 'Группа: ' . $series_html . ' <br />' . 'Раздел: ' . $cat_html . ' <br />' . 'Цена: <span class="price">' . $product->price . '</span><br />' //. '<span classs="delivery">Доставка: 1-2 дня*</span>' . '</div>'; //echo Widget::render_widget('products', 'add_to_cart', $product); echo '</td>'; } echo '</tr>'; if ($row_i < $rows - 1) { echo '<tr><td colspan="5" class="last" style="width:100%;"><div class="table-separator"> </div></td></tr>'; } $row_i ++; } ?> </table><file_sep>/modules/shop/catalog/views/frontend/products/_map.php <?php defined('SYSPATH') or die('No direct script access.'); require_once(Kohana::find_file('views', 'frontend/products/_helper')); function product_adv(Model_Product $product,$url,$image,$today_flag,$tomorrow_flag,$nearest_flag) { $lecturer_url = URL::to('frontend/acl/lecturers', array('action' => 'show','lecturer_id' => $product->lecturer_id)); $day = $nearest_flag?$product->weekday:($tomorrow_flag?'Завтра':'Сегодня'); $html = '<section><header>'; $html .= '<div class="row-fluid">'; $html .= '<div class="span6" style="white-space: nowrap;">'; $html .= '<span class="date"><a class="day" href="">'.$day.'</a>, '.$product->get_datetime_front().' </span>'; $html .= '<span class="type">'.Model_Product::$_interact_options[$product->interact].'</span>'; $html .= '</div>'; $html .= '<div class="span6 b-link">'; $html .= '<a data-toggle="modal" href="#requestModal" class="request-link button">Подать заявку</a>'; if (Model_User::current()->id == NULL) { $html .= '<a data-toggle="modal" href="#notifyModal" class="go-link button">Я пойду</a>'; } else { $choose_url = URL::to('frontend/catalog/product/choose', array('alias' => $product->alias)); $html .= '<a href="'.$choose_url.'" class="ajax go-link button">Я пойду</a>'; } $html .= '</div></div></header>'; $html .= '<div class="body-section">'; $html .= '<div class="row-fluid">'; $html .= '<div class="span6 face">'; $html .= $image; $html .= Widget::render_widget('products', 'product_stats', $product); //$html .= '<p class="counter"><span title="хочу телемост" id-"" class="hand">999</span></p>'; $html .= '</div>'; $html .= '<div class="span6">'; $html .= '<a class="dir" href="#">'.Model_Product::$_theme_options[$product->theme].'</a>'; $html .= '<h2><a href="'.$url.'">'.$product->caption.'</a></h2>'; $html .= '<p class="lecturer">Лектор: <a href="'.$lecturer_url.'">'.$product->lecturer_name.'</a></p>'; $html .= '<div class="desc"><p>'.$product->short_desc.'</p></div>'; $html .= '<p class="link-more"><a href="'.$url.'">Подробнее</a></p>'; $html .= '</div></div></div></section><hr>'; return $html; } <file_sep>/modules/shop/acl/classes/model/acl.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Acl extends Model { /** * Current node * @var Model_Node */ protected static $_current_acl; /** * Registered node types * @var array */ protected static $_acl_types = array(); /** * Add new acl type * * @param string $type * @param array $type_info */ public static function add_acl_type($type, array $type_info) { self::$_acl_types[$type] = $type_info; } /** * Returns list of all registered acl types * * @return array */ public static function acl_types() { return self::$_acl_types; } /** * Get acl type information * * @param string $type Type name * @return array */ public static function acl_type($type) { if (isset(self::$_acl_types[$type])) { return self::$_acl_types[$type]; } else { return NULL; } } /** * Acl is active by default * * @return boolean */ public function default_active() { return TRUE; } /** * Default site id for acl * * @return id */ public function default_site_id() { return Model_Site::current()->id; } /** * Save node * * @param boolean $force_create */ public function save($force_create = FALSE) { $new_type = $this->new_type; $old_type = $this->type; if ($new_type !== $old_type && $old_type !== NULL) { // Deal with old type $old_type_info = self::node_type($old_type); if (isset($old_type_info['model'])) { // Delete old node model $class = "Model_" . ucfirst($old_type_info['model']); Model::fly($class)->delete_all_by_node_id($this->id); } } // Save node $this->type = $this->new_type; parent::save($force_create); if ($new_type !== $old_type) { // Deal with new type $new_type_info = self::node_type($new_type); if (isset($new_type_info['model'])) { // Create new node model $class = "Model_" . ucfirst($new_type_info['model']); $model = new $class; $model->node_id = $this->id; $model->save(); } } // Recalculate activity $this->mapper()->update_activity(); return $this; } /** * Delete node with all subnodes and corresponding models */ public function delete() { // Selecting subtree $subnodes = $this->find_all_subtree(array('as_array' => TRUE, 'columns' => array('id','type'))); // Adding node itself $subnodes[]= $this->properties(); foreach ($subnodes as $node) { // Deleting all node models $type_info = self::node_type($node['type']); if (isset($type_info['model'])) { // Delete node model $class = "Model_" . ucfirst($type_info['model']); Model::fly($class)->delete_all_by_node_id($node['id']); } } // Deleting node from db with all subnodes $this->mapper()->delete_with_subtree($this); } /** * Validate create and update actions * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { return $this->validate_alias($newvalues); } /** * Validate node alias (must be unique within the current site) * * @param array $newvalues * @return boolean */ public function validate_alias(array $newvalues) { if ( ! isset($newvalues['alias']) || $newvalues['alias'] == '') { // It's allowed no to specify alias for node at all return TRUE; } if ($this->exists_another_by_alias_and_site_id($newvalues['alias'], $this->site_id)) { $this->error('Страница с таким именем в URL уже существует!', 'alias'); return FALSE; } return TRUE; } }<file_sep>/modules/shop/acl/classes/model/lecturer.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Lecturer extends Model { const LINKS_LENGTH = 64; /** * Return user name * * @return string */ public function get_name() { $name = ''; if ($this->first_name) $name.=$this->first_name; if ($this->last_name) $name.=' '.$this->last_name; return $name; } public function image($size = NULL) { $image_info = array(); $image = Model::fly('Model_Image')->find_by_owner_type_and_owner_id('lecturer', $this->id, array( 'order_by' => 'position', 'desc' => FALSE )); if ($size) { $field_image = 'image'.$size; $field_width = 'width'.$size; $field_height = 'height'.$size; $image_info['image'] = $image->$field_image; $image_info['width'] = $image->$field_width; $image_info['height'] = $image->$field_height; } return $image_info; } public function save($force_create = FALSE) { parent::save($force_create); if (is_array($this->file)) { $file_info = $this->file; if (isset($file_info['name'])) { if ($file_info['name'] != '') { // Delete organizer images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('lecturer', $this->id); $image = new Model_Image(); $image->file = $this->file; $image->owner_type = 'lecturer'; $image->owner_id = $this->id; $image->config = 'user'; $image->save(); } } } } /** * Delete product */ public function delete() { // Delete product images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('lecturer', $this->id); // Delete from DB parent::delete(); } } <file_sep>/modules/shop/catalog/classes/model/property/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Property_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('name', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(31)')); $this->add_column('type', array('Type' => 'tinyint')); $this->add_column('options', array('Type' => 'array')); $this->add_column('system', array('Type' => 'boolean')); } /** * Find all active non-system properties with their values for given product * * @param Model_Property $property * @param Model_Product $product * @param boolean $active * @param boolean $system * @param array $params * @return Models */ /** * Find all properties by given condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { if (is_array($condition) && ! empty($condition['section_id'])) { // Find properties that apply to selected section $columns = $this->_prepare_columns($params); $table = $this->table_name(); $propsec_table = Model_Mapper::factory('Model_PropertySection_Mapper')->table_name(); $query = DB::select_array($columns) ->from($table) ->join($propsec_table, 'INNER') ->on("$propsec_table.property_id", '=', "$table.id") ->on("$propsec_table.section_id", '=', DB::expr((int) ($condition['section_id']))); if (isset($condition['active'])) { $query->and_where("$propsec_table.active", '=', $condition['active']); unset($condition['active']); } unset($condition['product']); } return parent::find_all_by($model, $condition, $params, $query); } /** * Move property up * * @param Model $property * @param Database_Expression_Where $condition */ public function up(Model $property, Database_Expression_Where $condition = NULL) { parent::up($property, DB::where('site_id', '=', $property->site_id)); } /** * Move property down * * @param Model $property * @param Database_Expression_Where $condition */ public function down(Model $property, Database_Expression_Where $condition = NULL) { parent::down($property, DB::where('site_id', '=', $property->site_id)); } }<file_sep>/modules/shop/catalog/classes/task/comdi/status.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Create event through COMDI API */ class Task_Comdi_Status extends Task_Comdi_Base { public static $params = array( 'key', 'event_id', ); /** * Default parameters for this task * @var array */ public static $default_params = array( ); /** * Construct task */ public function __construct() { parent::__construct('http://my.webinar.ru'); $this->default_params(self::$default_params); } /** * Run the task */ public function run() { $xml_response = parent::send('/api0/GetStatus.php',$this->params(self::$params)); $stage = ($xml_response['stage'] == null)? null:strtolower((string)$xml_response['stage']); if ($stage === NULL) { $this->set_status_info('Статус мероприятия не известен'); } else { $this->set_status_info('Статус мероприятия '.$stage); } return $stage; } } <file_sep>/modules/system/forms/views/forms/default/autocomplete.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="autocomplete"> <?php for ($i = 0; $i < count($items); $i++) { $item = $items[$i]; echo '<div class="item">' . ' <div class="item_i">' . $i . '</div>' . ' <div class="item_value">' . HTML::chars($item['value']) . '</div>' . ' <div class="item_caption">' . $item['caption'] . '</div>' . '</div>'; } ?> </div><file_sep>/modules/system/forms/classes/form/validator/ajax.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Ajax validator * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_Ajax extends Form_Validator { protected $_uri; /** * Construct ajax validator * * @param string $uri */ public function __construct($uri) { $this->_uri = $uri; } /** * Validate * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { return TRUE; } /** * Render javascript for this validator * * @return string */ public function render_js() { $js = "v = new jFormValidatorAjax('" . URL::site($this->_uri) . "');\n"; return $js; } }<file_sep>/modules/shop/area/views/backend/towns/place_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php //Set up urls $tab_url = URL::self(array('are_town_alias' => '${alias}')); $create_url = URL::to('backend/area/towns', array('action'=>'create'), TRUE); $update_url = URL::to('backend/area/towns', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/area/towns', array('action'=>'delete', 'id' => '${id}'), TRUE); $multi_action_uri = URL::uri_to('backend/area/towns', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_user_add">Добавить Город</a> </div> <?php if ( ! count($towns)) // No users return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'name' => 'Название' ); echo View_Helper_Admin::table_header($columns, 'are_torder', 'are_tdesc'); ?> <th></th> </tr> <?php foreach ($towns as $town) : $_tab_url = str_replace('${alias}', $town->alias, $tab_url); $_delete_url = str_replace('${id}', $town->id, $delete_url); $_update_url = str_replace('${id}', $town->id, $update_url); ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($town->id); ?> </td> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if ($field == 'name') { echo '<a href="' . $_tab_url . '">' . HTML::chars($town->name) . '</a>'; } elseif (isset($town->$field) && trim($town->$field) !== '') { echo HTML::chars($town->$field); } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать город', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить город', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; //foreach ($towns as $town) ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/catalog/classes/controller/backend/sectiongroups.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_SectionGroups extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_SectionGroup'; $this->_form = 'Form_Backend_SectionGroup'; $this->_view = 'backend/form'; return array( 'create' => array( 'view_caption' => 'Создание группы категорий' ), 'update' => array( 'view_caption' => 'Редактирование группы категорий ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление группы категорий', 'message' => 'Удалить группу категорий ":caption", все категории и события из этой группы?' ) ); } /** * Create layout (proxy to catalog controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = $this->request->get_controller('catalog')->prepare_layout($layout_script); if ($this->request->action == 'select') { // Add sections select js scripts $layout->add_script(Modules::uri('catalog') . '/public/js/backend/sectiongroups_select.js'); } return $layout; } /** * Render layout (proxy to catalog controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('catalog')->render_layout($content, $layout_script); } /** * Render all available section groups for current site */ public function action_index() { $this->request->response = $this->render_layout($this->widget_sectiongroups()); } /** * Select several sections */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор категорий на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_sectiongroups('backend/sectiongroups/select'); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_sectiongroups('backend/sectiongroups/select')); } } /** * Create new section group * * @param string|Model $model * @param array $params * @return Model_SectionGroup */ protected function _model_create($model, array $params = NULL) { if (Model_Site::current()->id === NULL) { throw new Controller_BackendCRUD_Exception('Выберите магазин перед созданием группы категорий!'); } // New section for current site $sectiongroup = new Model_SectionGroup(); $sectiongroup->site_id = (int) Model_Site::current()->id; return $sectiongroup; } /** * Renders list of sectiongroups * * @return string */ public function widget_sectiongroups($view = 'backend/sectiongroups') { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите магазин!'); } $sectiongroup = new Model_SectionGroup(); $order_by = $this->request->param('cat_sgorder', 'id'); $desc = (bool) $this->request->param('cat_sgdesc', '0'); $sectiongroups = $sectiongroup->find_all_by_site_id($site_id, array( 'columns' => array('id', 'caption'), 'order_by' => $order_by, 'desc' => $desc )); $view = new View($view); $view->order_by = $order_by; $view->desc = $desc; $view->sectiongroups = $sectiongroups; return $view->render(); } } <file_sep>/application/classes/view/helper.php <?php /** * View helper * * @package Eresus * @author <NAME> (<EMAIL>) */ class View_Helper { /** * Renders table header row with ability to sort by columns * * @param array $columns List of columns * @param array $params * @param array $ignored_columns * @return string */ //$order_by_param = 'order', $desc_param = 'desc', $desc_default = TRUE, $ignored_columns = array() public static function table_header(array $columns, array $params = NULL, array $ignored_columns = array()) { $request = Request::current(); $order_by_param = isset($params['order_by_param']) ? $params['order_by_param'] : 'order'; $desc_param = isset($params['desc_param']) ? $params['desc_param'] : 'desc'; $desc_default = isset($params['desc_default']) ? $params['desc_default'] : TRUE; $current_order_by = $request->param($order_by_param); $current_desc = $request->param($desc_param); $template = isset($params['template']) ? $params['template'] : '<th><a href="$(url)">$(label)</a></th>'; $template_asc = isset($params['template_asc']) ? $params['template_asc'] : '<th><a href="$(url)" class="asc">$(label)</a></th>'; $template_desc = isset($params['template_desc']) ? $params['template_desc'] : '<th><a href="$(url)" class="desc">$(label)</a></th>'; $template_ignore = isset($params['template_ignore']) ? $params['template_ignore'] : '<th><span>$(label)</span></th>'; $html = ''; foreach ($columns as $field => $label) { if ( ! in_array($field, $ignored_columns)) { $class = ''; if ($current_order_by == $field) { $desc = $current_desc ? '0' : '1'; $tmpl = $desc ? $template_asc : $template_desc; } else { $desc = $desc_default ? '1' : '0'; $tmpl = $template; } $url = URL::self(array($order_by_param => $field, $desc_param => $desc)); Template::replace($tmpl, array('label' => HTML::chars($label), 'url' => $url)); } else { Template::replace($tmpl, array('label' => HTML::chars($label))); } $html .= $tmpl; } return $html; } protected static $_words_regexp; /** * Highlight specific words inside tags with class = $class * * @param array $words * @param string $content * @param string $class * @return string */ public static function highlight_search($words, $content, $class = "searchable") { self::$_words_regexp = '#(' . implode('|', $words) . ')#iu'; $content = preg_replace_callback('#(<[^>]*class="searchable"[^>]*>)([^<]*)#ui', array(__CLASS__, '_highlight_search_cb'), $content); return $content; } protected static function _highlight_search_cb($matches) { $tag = $matches[1]; $text = $matches[2]; $highlighted = preg_replace(self::$_words_regexp, '<span class="highlight">$0</span>', $text); return $tag . $highlighted; } /** * Displays a flash-style message * * @param string $message Message text * @param string $class Message class * @return string */ public static function flash_msg($message, $type = FlashMessages::MESSAGE) { switch ($type) { case FlashMessages::MESSAGE: $class = 'ok'; break; default: $class = 'error'; } return '<div class="flash_msg_' . $class .'">' . HTML::chars($message) . '</div>'; } /** * Highlight a cache block and display some info * * @param string $html * @param string $cache_id * @param array $cache_tags * @return string */ public static function highlight_cache_block($html, $cache_id, array $cache_tags) { return '<div class="cache_block">' . ' <div class="cache_block_info">' . ' id: "' . $cache_id . '", tags: "' . implode(',', $cache_tags) . '"' . ' </div>' . $html . '</div>'; } protected function __construct() { // This is a static class } }<file_sep>/modules/general/flash/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/flashblocks', new Route_Backend( 'flashblocks(/<action>(/<id>))' . '(/opts1-<options_count1>)' . '(/opts2-<options_count2>)' . '(/opts3-<options_count3>)' . '(/$<history>)', array( 'action' => '\w++', 'id' => '\d++', 'options_count1' => '\d++', 'options_count2' => '\d++', 'options_count3' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'flashblocks', 'action' => 'index', 'id' => NULL, 'options_count1' => NULL, 'options_count2' => NULL, 'options_count3' => NULL )); // ----- Add backend menu items Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => 2, 'caption' => 'Flash', 'route' => 'backend/flashblocks', 'icon' => 'flashblocks' )); }<file_sep>/modules/shop/acl/classes/form/frontend/profileedit.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_ProfileEdit extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/users/profedit'; // ----- email $email = new Form_Element_Input('email', array('label' => 'E-Mail', 'required' => TRUE), array('maxlength' => 31, 'placeholder' => 'Электронная почта')); $email->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Email()); $this->add_component($email); // ----- Password $element = new Form_Element_Password('password', array('label' => 'Пароль', 'required' => TRUE), array('maxlength' => 255, 'placeholder' => 'Пароль') ); $element ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_StringLength(0, 255)); $this->add_component($element); // organizer $element = new Form_Element_Input('organizer_name', array('label' => 'Организация', 'id' => 'organizer_name')); $this->add_component($element); $element = new Form_Element_Input('first_name', array('label' => 'Имя', 'id' => 'first_name')); $this->add_component($element); $element = new Form_Element_Input('last_name', array('label' => 'Фамилия', 'id' => 'last_name')); $this->add_component($element); $element = new Form_Element_Input('town_id',array('label' => 'Город', 'id' => 'town_id')); $this->add_component($element); $element = new Form_Element_TextArea('info',array('label' => 'О себе', 'id' => 'info')); $this->add_component($element); // ----- Form buttons $button = new Form_Element_Button('submit_register', array('label' => 'Сохранить') ); $this->add_component($button); parent::init(); } }<file_sep>/application/views/layouts/errors/500.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <title><?php echo HTML::chars($message); ?></title> <?php echo HTML::style('public/css/stylesheet.css'); ?> <?php echo HTML::style('public/css/print_stylesheet.css',array('media'=>'print')); ?> <?php echo HTML::style('public/css/stylesheet_css_buttons.css'); ?> </head> <body> <br> <br> <h1><?php echo HTML::chars($message); ?></h1> <?php if (Kohana::$profiling) { echo View::factory('profiler/stats')->render(); } ?> </body> </html><file_sep>/modules/general/news/classes/model/newsitem/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Newsitem_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('date', array('Type' => 'date', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(255)')); $this->add_column('short_text', array('Type' => 'text')); $this->add_column('text', array('Type' => 'text')); } /** * Find all news in specified year and month * * @param Model_Newsitem $newsitem * @param integer $year * @param integer $month * @param integer $site_id * @param array $params * @return array */ public function find_all_by_year_and_month_and_site_id(Model_Newsitem $newsitem, $year, $month, $site_id, array $params = NULL) { $from = "$year-$month-01"; if ($month < 12) { $to = "$year-" . ($month+1) . '-01'; } else { $to = ($year+1) . "-01-01"; } $condition = DB::where('site_id', '=', (int) $site_id) ->and_where('date', '>=', $from) ->and_where('date', '<', $to); return $this->find_all_by($newsitem, $condition, $params); } /** * Find all years for which there are news * * @param Model_Newsitem $newsitem * @param integer $site_id * @return array */ public function find_all_years_by_site_id(Model_Newsitem $newsitem, $site_id) { $query = DB::select(array(DB::expr("YEAR(date)"), 'year')) ->distinct('year') ->from($this->table_name()); $condition = DB::where('site_id', '=', (int) $site_id); $result = $this->select($condition, array('order_by' => 'date', 'desc' => TRUE), $query); $years = array(); foreach ($result as $values) { $years[] = (int) $values['year']; } return $years; } /** * Find all month for which there are news for given year * * @param Model_Newsitem $newsitem * @param string $year * @param integer $site_id * @return array */ public function find_all_months_by_year_and_site_id(Model_Newsitem $newsitem, $year, $site_id) { $year = (int) $year; $query = DB::select(array(DB::expr("MONTH(date)"), 'month')) ->distinct('month') ->from($this->table_name()); $condition = DB::where('site_id', '=', (int) $site_id) ->and_where('date', '>=', "$year-01-01") ->and_where('date', '<', ($year+1) . "-01-01"); $result = $this->select($condition, array('order_by' => 'date', 'desc' => FALSE), $query); $months = array(); foreach ($result as $values) { $months[] = (int) $values['month']; } return $months; } }<file_sep>/modules/shop/acl/classes/form/backend/user.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_User extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class // User is being created or updated? $creating = ((int)$this->model()->id == 0) ? TRUE : FALSE; $this->attribute('class', "lb130px"); $this->layout = 'wide'; // ----- General tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $tab->add_component($cols); // ----- Group // Obtain a list of groups $groups = Model::fly('Model_Group')->find_all(); $options = array(); foreach ($groups as $group) { $options[$group->id] = $group->name; } $element = new Form_Element_Select('group_id', $options, array('label' => 'Группа', 'required' => TRUE)); $element ->add_validator(new Form_Validator_InArray( array_keys($options), array(Form_Validator_InArray::NOT_FOUND => 'Указана несуществующая группа!') )); $cols->add_component($element); // ----- Active $cols->add_component(new Form_Element_Checkbox('active', array('label' => 'Активность'))); // ----- Login and password $fieldset = new Form_Fieldset('email_and_password', array('label' => 'E-mail и пароль')); $cols->add_component($fieldset); // ----- Login $element = new Form_Element_Input('email', array('label' => 'E-mail', 'required' => TRUE), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $ajax_uri = URL::uri_self(array('action' => 'validate', 'v_action' => Request::current()->action)); $element ->add_validator(new Form_Validator_Ajax($ajax_uri)); $fieldset->add_component($element); // ----- Password $element = new Form_Element_Password('password', array('label' => 'Пароль', 'required' => $creating, 'ignored' => ! $creating), array('maxlength' => 255) ); $element ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_StringLength(0, 255)); $fieldset->add_component($element); // ----- Password confirmation $element = new Form_Element_Password('<PASSWORD>', array('label' => 'Подтверждение', 'required' => $creating, 'ignored' => ! $creating), array('maxlength' => 255) ); $element ->add_validator(new Form_Validator_NotEmptyString(array( Form_Validator_NotEmptyString::EMPTY_STRING => 'Вы не указали подтверждение пароля!', ))) ->add_validator(new Form_Validator_EqualTo( 'password', array( Form_Validator_EqualTo::NOT_EQUAL => 'Пароль и подтверждение не совпадают!', ) )); $fieldset->add_component($element); if ( ! $creating) { $element = new Form_Element_Checkbox_Enable('change_credentials', array('label' => 'Сменить пароль')); $element->dep_elements = array('password', '<PASSWORD>'); $fieldset->add_component($element); } // ----- Personal data $fieldset = new Form_Fieldset('personal_data', array('label' => 'Личные данные')); $cols->add_component($fieldset); $cols1 = new Form_Fieldset_Columns('name'); $fieldset->add_component($cols1); // ----- Last_name $element = new Form_Element_Input('last_name', array('label' => 'Фамилия', 'required' => TRUE), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $cols1->add_component($element, 1); // ----- First_name $element = new Form_Element_Input('first_name', array('label' => 'Имя', 'required' => TRUE), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $cols1->add_component($element, 2); // ----- Middle_name $element = new Form_Element_Input('middle_name', array('label' => 'Отчество'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $fieldset->add_component($element); // organizer // control hidden field $control_element = new Form_Element_Hidden('organizer_id',array('id' => 'organizer_id')); $this->add_component($control_element); if ($control_element->value !== FALSE) { $organizer_id = (int) $control_element->value; } else { $organizer_id = (int) $this->model()->organizer_id; } // ----- organizer_name // input field with autocomplete ajax $element = new Form_Element_Input('organizer_name', array('label' => 'Организация', 'layout' => 'wide','id' => 'organizer_name','required' => true)); $element->autocomplete_url = URL::to('backend/acl/organizers', array('action' => 'ac_organizer_name')); $element ->add_validator(new Form_Validator_NotEmptyString()); Layout::instance()->add_style(Modules::uri('acl') . '/public/css/backend/acl.css'); $fieldset->add_component($element); $organizer = new Model_Organizer(); $organizer->find($organizer_id); $organizer_name = ($organizer->id !== NULL) ? $organizer->name : ''; if ($element->value === FALSE) { $element->value = $organizer_name; } else { if ($element->value !== $organizer_name) $control_element->set_value(NULL); } // ----- Position $element = new Form_Element_Input('position', array('label' => 'Должность'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $fieldset->add_component($element); // ----- phone $element = new Form_Element_Input('phone', array('label' => 'Телефон'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $fieldset->add_component($element); // ----- town_id $towns = Model_Town::towns(); $element = new Form_Element_Select('town_id', $towns, array('label' => 'Город','required' => true), array('class' => 'w300px') ); $element ->add_validator(new Form_Validator_InArray(array_keys($towns))); $fieldset->add_component($element); // ----- tags $element = new Form_Element_Input('tags', array('label' => 'Мои интересы','id' => 'tag'), array('maxlength' => 255)); $element->autocomplete_url = URL::to('backend/tags', array('action' => 'ac_tag')); $element->autocomplete_chunk = Model_Tag::TAGS_DELIMITER; $element ->add_filter(new Form_Filter_TrimCrop(255)); $fieldset->add_component($element); $element = new Form_Element_Checkbox_Enable('notify', array('label' => 'Информировать о новых событиях')); $fieldset->add_component($element); // ----- Userprops if (!$creating && count($this->model()->userprops)) { $fieldset = new Form_Fieldset('userprops', array('label' => 'Параметры учетной записи')); $cols->add_component($fieldset); foreach ($this->model()->userprops as $userprop) { switch ($userprop->type) { case Model_UserProp::TYPE_TEXT: $element = new Form_Element_Input( $userprop->name, array('label' => $userprop->caption), array('maxlength' => Model_UserProp::MAXLENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_UserProp::MAXLENGTH)); $fieldset->add_component($element); break; case Model_UserProp::TYPE_SELECT: $options = array('' => '---'); foreach ($userprop->options as $option) { $options[$option] = $option; } $element = new Form_Element_Select( $userprop->name, $options, array('label' => $userprop->caption) ); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); break; } } } // ----- User Photo if ($this->model()->id !== NULL) { $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('images')->widget_images('user', $this->model()->id, 'user'); $cols->add_component($element, 2); } // ----- links $fieldset = new Form_Fieldset('links', array('label' => 'Внешние ссылки','class' => 'links')); $cols->add_component($fieldset,2); foreach ($this->model()->links as $link) { $element = new Form_Element_Input( $link->name, array('label' => $link->caption), array('label_class' => $link->name,'maxlength' => Model_Link::MAXLENGTH) ); $fieldset->add_component($element); } // ----- Personal Webpages if ($this->model()->id) { $options_count = count($this->model()->webpages); } if (!isset($options_count) || $options_count==0) $options_count = 1; $element = new Form_Element_Options("webpages", array('label' => 'Сайты', 'options_count' => $options_count,'options_count_param' => 'options_count','option_caption' => 'добавить ссылку'), array('maxlength' => Model_User::LINKS_LENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_User::LINKS_LENGTH)); $cols->add_component($element,2); // ----- Description tab $tab = new Form_Fieldset_Tab('info_tab', array('label' => 'О себе')); $this->add_component($tab); // ----- Description $tab->add_component(new Form_Element_Wysiwyg('info', array('label' => 'О себе'))); // ----- Address_data /* $fieldset = new Form_Fieldset('address_data', array('label' => 'Адрес')); $this->add_component($fieldset); $cols = new Form_Fieldset_Columns('city_and_postcode', array('column_classes' => array(2 => 'w40per'))); $fieldset->add_component($cols); // ----- City $element = new Form_Element_Input('city', array('label' => 'Город'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $element->autocomplete_url = URL::to('backend/countries', array('action' => 'ac_city')); $cols->add_component($element, 1); // ----- Postcode $element = new Form_Element_Input('postcode', array('label' => 'Индекс'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $element->autocomplete_url = URL::to('backend/countries', array('action' => 'ac_postcode')); $cols->add_component($element, 2); // ----- Region_id // Obtain a list of regions $regions = Model::fly('Model_Region')->find_all(array('order_by' => 'name', 'desc' => FALSE)); $options = array(); foreach ($regions as $region) { $options[$region->id] = UTF8::ucfirst($region->name); } $element = new Form_Element_Select('region_id', $options, array('label' => 'Регион')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- zone_id // Obtain a list of ALL zones $zones = Model::fly('Model_CourierZone')->find_all(array('order_by' => 'position', 'desc' => FALSE)); $options = array(0 => '---'); foreach ($zones as $zone) { $options[$zone->id] = $zone->name; } $element = new Form_Element_Select('zone_id', $options, array('label' => 'Зона доставки (Москва)')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- Address $element = new Form_Element_Textarea('address', array('label' => 'Адрес'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $fieldset->add_component($element); * */ // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts // Url for ajax requests to redraw product properties when main section is changed Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/organizer_name.js'); // Url for ajax requests to redraw product properties when main section is changed Layout::instance()->add_script(Modules::uri('tags') . '/public/js/backend/tag.js'); } } <file_sep>/application/classes/models.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Traversable models collection * * @package Eresus * @author <NAME> (<EMAIL>) */ class Models implements Iterator, Countable, ArrayAccess { /** * Name of the model which values are stored * @var string */ protected $_model_class; /** * An instance of model which is returned when the collection is iterated * @var Model */ protected $_model; /** * Name of the column that serves as a primary key * @var string */ protected $_pk = FALSE; /** * @var array */ protected $_properties_array = array(); /** * Construct container from array of properties * * @param string $model_class * @param array $properties_array * @param string $key name of the primary key field */ public function __construct($model_class, array $properties_array, $pk = FALSE) { $this->_model_class = $model_class; $this->_pk = $pk; $this->properties($properties_array); } /** * Set/get array of model properties * * @param array $properties_array * @return array */ public function properties(array $properties_array = NULL) { if ($properties_array !== NULL) { $this->_properties_array = $properties_array; } return $this->_properties_array; } /** * Get properties array * * @return array */ public function as_array() { return $this->_properties_array; } /** * Get the instance of model * * @return Model */ public function model() { if ($this->_model === NULL) { $this->_model = new $this->_model_class; } return $this->_model; } // ------------------------------------------------------------------------- // Iterator // ------------------------------------------------------------------------- public function current() { if (current($this->_properties_array) !== FALSE) { $this->model()->init(current($this->_properties_array)); return $this->model(); } else { return FALSE; } } public function key() { return key($this->_properties_array); } public function next() { next($this->_properties_array); } public function rewind() { reset($this->_properties_array); } public function valid() { return (current($this->_properties_array) !== FALSE); } // ------------------------------------------------------------------------- // Countable // ------------------------------------------------------------------------- public function count() { return count($this->_properties_array); } // ------------------------------------------------------------------------- // ArrayAccess // ------------------------------------------------------------------------- function offsetExists($offset) { return array_key_exists($offset, $this->_properties_array); } function offsetGet($offset) { if ( ! array_key_exists($offset, $this->_properties_array) || ! is_array($this->_properties_array[$offset])) { return FALSE; } else { $this->model()->init($this->_properties_array[$offset]); return $this->model(); } } function offsetSet($offset, $value) { if ($value instanceof Model) { $value = $value->properties(); } if ($offset === NULL) { // Appending new model if ($this->_pk !== FALSE && isset($value[$this->_pk])) { $this->_properties_array[$value[$this->_pk]] = $value; } else { $this->_properties_array[] = $value; } } else { // Modifying properties of existing model $this->_properties_array[$offset] = $value; } } function offsetUnset($offset) { unset($this->_properties_array[$offset]); } // ------------------------------------------------------------------------- // Additional // ------------------------------------------------------------------------- /** * Return the model at the specified index * * @param integer $i * @return Model */ public function at($i) { if ($this->_pk === FALSE) { $this->model()->init($this->_properties_array[$i]); return $this->model(); } else { $pks = array_keys($this->_properties_array); if (isset($pks[$i])) { return $this[$pks[$i]]; } else { return FALSE; } } } } <file_sep>/modules/general/chat/classes/form/frontend/smallmsg.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_SmallMsg extends Form_Frontend { /** * Initialize form fields */ public function init() { $this->view_script = 'frontend/forms/smallmsg'; // ----- message $element = new Form_Element_Textarea('message', array('label' => 'Сообщение', 'required' => TRUE),array('rows' => '2')); $element->add_filter(new Form_Filter_TrimCrop(512)); $element->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- notify $this->add_component(new Form_Element_Checkbox('notify', array( 'label' => 'Оповестить клиента о сообщении по e-mail', ))); $element = new Form_Element_Hidden('dialog_id'); $this->add_component($element); parent::init(); } } <file_sep>/application/config/form_templates/frontend/form.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( array( 'form' => ' <div class="form"> {{form_open}} {{messages}} {{hidden}} {{elements}} {{form_close}} </div> ' ) );<file_sep>/modules/shop/acl/classes/controller/frontend/acl.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Acl extends Controller_Frontend { public function before() { if ($this->request->action === 'login' || $this->request->action === 'logout') { // Allow everybody to login & logout return TRUE; } return parent::before(); } /** * Prepare layout * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('acl') . '/public/css/frontend/acl.css'); if ($this->request->action == 'user_select') { // Add user select js scripts $layout->add_script(Modules::uri('acl') . '/public/js/frontend/user_select.js'); $layout->add_script( "var user_selected_url = '" . URL::to('frontend/acl', array('action' => 'user_selected', 'user_id' => '{{id}}')) . "';" , TRUE); } if ($this->request->action == 'lecturer_select') { // Add lecturer select js scripts $layout->add_script(Modules::uri('acl') . '/public/js/frontend/lecturer_select.js'); $layout->add_script( "var lecturer_selected_url = '" . URL::to('frontend/acl', array('action' => 'lecturer_selected', 'lecturer_id' => '{{id}}')) . "';" , TRUE); } return $layout; } /** * Render acl with given name * * @param string $name * @return string */ public function widget_acl() { // Find acl by name $user = Auth::instance()->get_user(); $privileges = $user->privileges_granted; $view = new View('privilege_templates/default'); $view->privileges = $privileges; return $view; } /** * Render auth form */ public function widget_login() { $user = Model_User::current(); $view = new View('frontend/login'); if ($user->id) { $view->user = $user; } else { $form_log = new Form_Frontend_Login($user); if ($form_log->is_submitted()) { // User is trying to log in if ($form_log->validate()) { $result = Auth::instance()->login( $form_log->get_element('email')->value, $form_log->get_element('password')->value, $form_log->get_element('remember')->value ); if ($result) { //$this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Auth::instance()->get_user()->town->alias))); //$this->request->redirect(Request::current()->uri); $this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Model_Town::ALL_TOWN))); } else { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin'))); } } else { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin'))); } } $form_reg = new Form_Frontend_Register(); if ($form_reg->is_submitted()) { // User is trying to log in if ($form_reg->validate()) { $new_user = new Model_User(); if ($new_user->validate($form_reg->get_values())) { $new_user->values($form_reg->get_values()); $new_user->save(); $result = Auth::instance()->login( $form_reg->get_element('email')->value, $form_reg->get_element('password')->value ); if ($result) { //$this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Auth::instance()->get_user()->town->alias))); //$this->request->redirect(Request::current()->uri); $this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Model_Town::ALL_TOWN))); } else { $form_reg->errors(Auth::instance()->errors()); } } else { $form_reg->errors($new_user->errors()); } } } $form_notify = new Form_Frontend_Notify(); $modal = Layout::instance()->get_placeholder('modal'); $modal = $form_log->render().' '.$form_reg->render().' '.$form_notify->render().' '.$modal; Layout::instance()->set_placeholder('modal',$modal); //Layout::instance()->set_placeholder('modal',$form_log->render().' '.$form_reg->render().' '.$form_notify->render()); } return $view; } /** * Render auth form */ public function widget_register() { $view = new View('frontend/register'); $form = new Form_Frontend_Register(); if ($form->is_submitted()) { // User is trying to log in if ($form->validate()) { $new_user = new Model_User($form->get_values()); if ($new_user->validate_save()) { $new_user->save(); $result = Auth::instance()->login( $form->get_element('email')->value, $form->get_element('password')->value ); if ($result) { //$this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Auth::instance()->get_user()->town->alias))); //$this->request->redirect(Request::current()->uri); $this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Model_Town::ALL_TOWN))); } else { $form->errors(Auth::instance()->errors()); } } else { $form->errors($new_user->errors()); } } } Layout::instance()->set_placeholder('modal',$form->render()); return $view; } public function action_logout() { Auth::instance()->logout(); $this->request->redirect(''); } public function action_relogin() { $view = new View('frontend/relogin'); $form_log = new Form_Frontend_Relogin(); if ($form_log->is_submitted()) { // User is trying to log in if ($form_log->validate()) { $result = Auth::instance()->login( $form_log->get_element('email')->value, $form_log->get_element('password')->value, $form_log->get_element('remember')->value ); if ($result) { //$this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Auth::instance()->get_user()->town->alias))); //$this->request->redirect(Request::current()->uri); $this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Model_Town::ALL_TOWN))); } else { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin'))); } } } $view->form = $form_log; $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } public function widget_pasrecovery() { $view = new View('frontend/pasrecovery'); $form_log = new Form_Frontend_Pasrecovery(); if ($form_log->is_submitted()) { // User is trying to log in if ($form_log->validate()) { $user = Model::fly('Model_User')->find_by_email($form_log->get_element('email')->value); $result = FALSE; if ($user->id) { $result=$user->password_recovery(); } if ($result) { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin','stat' => 'ok'))); } else { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin'))); } } } $modal = Layout::instance()->get_placeholder('modal'); Layout::instance()->set_placeholder('modal',$modal.' '.$form_log->render()); return $view; } public function action_newpas() { $user = Model::fly('Model_User')->find_by_recovery_link('http://vse.to'.URL::site().$this->request->uri); if ($user->id) { $form_log = new Form_Frontend_Newpas(); if ($form_log->is_submitted()) { // User is trying to log in if ($form_log->validate()) { $user->password = $form_log->get_element('password')->value; $user->recovery_link = ''; $user->save(); $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin','stat' => 'try'))); } } } else { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin'))); } $view = new View('frontend/newpas'); $view->form = $form_log; $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } public function action_activation() { $user = Model::fly('Model_User')->find_by_activation_link('http://vse.to'.URL::site().$this->request->uri); if ($user->id) { $user->activation_link = ''; $user->active = TRUE; $user->save(); $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin','stat' => 'act'))); } else { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin'))); } } public function action_pasrecovery() { $view = new View('frontend/pasrecovery'); $form_log = new Form_Frontend_Pasrecovery(); if ($form_log->is_submitted()) { // User is trying to log in if ($form_log->validate()) { $result = Auth::instance()->login( $form_log->get_element('email')->value, $form_log->get_element('password')->value, $form_log->get_element('remember')->value ); if ($result) { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin','stat' => 'ok'))); } else { $this->request->redirect(URL::uri_to('frontend/acl',array('action'=>'relogin'))); } } } $view->form = $form_log; $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Renders logout button * * @return string */ public function widget_logout() { $view = new View('backend/logout'); return $view; } /** * Render user-select dialog */ public function action_user_select() { $layout = $this->prepare_layout(); if (empty($_GET['window'])) { $view = new View('frontend/workspace'); $view->caption = 'Выбор пользователя'; // $view->content = $this->request->get_controller('users')->widget_user_select(); $view->content = $this->widget_user_select(); $layout->content = $view; } else { $view = new View('frontend/workspace'); // $view->content = $this->request->get_controller('users')->widget_user_select(); $view->content = $this->widget_user_select(); $layout->caption = 'Выбор пользователя'; $layout->content = $view->render(); } $this->request->response = $layout->render(); } public function widget_user_select() { $view = new View('frontend/workspace_2col'); $view->column1 = $this->widget_groups(); $view->column2 = $this->request->get_controller('users')->widget_user_select(); return $view; } public function widget_groups() { $group = new Model_Group(); $group_id = (int) $this->request->param('group_id'); $group_ids = array(Model_Group::EDITOR_GROUP_ID,Model_Group::USER_GROUP_ID); $groups = new Models('Model_Group',array()); foreach ($group_ids as $group_id) { $groups[] = $group->find($group_id); } $view = new View('frontend/groups'); $view->group_id = $group_id; $view->groups = $groups; return $view->render(); } /** * Generate the response for ajax request after user is selected * to inject new values correctly into the form */ public function action_user_selected() { $user = new Model_User(); $user->find((int) $this->request->param('user_id')); $values = $user->values(); $values['user_name'] = $user->name; $this->request->response = JSON_encode($values); } /** * Render lecturer-select dialog */ public function action_lecturer_select() { $layout = $this->prepare_layout(); if (empty($_GET['window'])) { $view = new View('frontend/workspace'); $view->caption = 'Выбор лектора'; $view->content = $this->request->get_controller('lecturers')->widget_lecturer_select_form(); $layout->content = $view; } else { $view = new View('frontend/workspace'); $view->content = $this->request->get_controller('lecturers')->widget_lecturer_select_form(); $layout->caption = 'Выбор лектора'; $layout->content = $view->render(); } $this->request->response = $layout->render(); } /** * Generate the response for ajax request after lecturer is selected * to inject new values correctly into the form */ public function action_lecturer_selected() { $lecturer = new Model_Lecturer(); $lecturer->find((int) $this->request->param('lecturer_id')); $values = $lecturer->values(); $values['lecturer_name'] = $lecturer->name; $this->request->response = JSON_encode($values); } /** * Login with social network */ public function action_login_social() { $ulogin = Ulogin::factory(); $layout = $this->prepare_layout(); $layout->caption = 'Вход через социальные сети'; if (!$ulogin->mode()) { $layout->content = $ulogin->render(); $this->request->response = $layout->render(); } else { // правильно try { $userPassword = $ulogin->login(); if($userPassword) { $layout->content = 'Вы успешно вошли! Ваш временный пароль: '.$userPassword .'. <br />Вы можете входить на сайта как через комбинацию email-пароль, так и через выбранную социальную сеть' .'. <br /><br />Пожалуйста, проверьте свой город на странице настроек учетной записи.'; $this->request->response = $layout->render(); } else { $this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Model_Town::ALL_TOWN))); } } catch(Kohana_Exception $e) { $layout->content = 'Произошла ошибка: '.$e->getMessage(); $this->request->response = $layout->render(); } } } } <file_sep>/modules/shop/acl/views/backend/groups.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Set up urls $create_url = URL::to('backend/acl/groups', array('action'=>'create'), TRUE); $update_url = URL::to('backend/acl/groups', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/acl/groups', array('action'=>'delete', 'id' => '${id}'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_group_add">Создать группу</a> </div> <div class="groups"> <table> <tr> <td> <?php // Highlight current group if ($group_id == 0) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo URL::self(array('group_id' => (string) 0)); ?>" class="group<?php echo $selected; ?>" title="Показать всех пользователей" > <strong>Все пользователи</strong> </a> </td> <td>&nbsp;</td> <?php foreach ($groups as $group) : $_delete_url = str_replace('${id}', $group->id, $delete_url); $_update_url = str_replace('${id}', $group->id, $update_url); ?> <tr> <td> <?php // Highlight current group if ($group->id == $group_id) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo URL::self(array('group_id' => (string) $group->id)); ?>" class="group<?php echo $selected; ?>" title="Показать пользователей из группы '<?php echo HTML::chars($group->name); ?>'" > <?php echo HTML::chars($group->name); ?> </a> </td> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать группу', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить группу', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; //foreach ($groups as $group) ?> </table> </div> <file_sep>/modules/general/chat/classes/form/frontend/message.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Message extends Form_Frontend { /** * Initialize form fields */ public function init() { $this->layout = 'wide'; //$this->attribute('class', 'lb120px'); $this->attribute('class', "w500px lb120px"); // ----- receiver_id // Store receiver_id in hidden field $element = new Form_Element_Hidden('receiver_id'); $this->add_component($element); if ($element->value !== FALSE) { $user_id = (int) $element->value; } else { $user_id = (int) $this->model()->receiver_id; } // ----- Receiver name // Receiver of this message $user = new Model_User(); $user->find($user_id); $user_name = ($user->id !== NULL) ? $user->name : '--- получатель не указан ---'; $element = new Form_Element_Input('user_name', array('label' => 'Получатель', 'disabled' => TRUE, 'layout' => 'wide'), array('class' => 'w150px') ); $element->value = $user_name; $this->add_component($element); // Button to select user $button = new Form_Element_LinkButton('select_user_button', array('label' => 'Выбрать', 'render' => FALSE), array('class' => 'button_select_user open_window dim500x500') ); $button->url = URL::to('frontend/acl', array('action' => 'user_select','group_id' => Model_Group::EDITOR_GROUP_ID), TRUE); $this->add_component($button); $element->append = '&nbsp;&nbsp;' . $button->render(); // ----- message $element = new Form_Element_Textarea('message', array('label' => 'Сообщение', 'required' => TRUE)); $element->add_filter(new Form_Filter_TrimCrop(512)); $element->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- notify $this->add_component(new Form_Element_Checkbox('notify', array( 'label' => 'Оповестить клиента о сообщении по e-mail', ))); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Frontend_Element_Submit('submit', array('label' => 'Отправить'), array('class' => 'button_accept') )); parent::init(); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts Layout::instance()->add_script(Modules::uri('chat') . '/public/js/frontend/mesuser.js'); } } <file_sep>/modules/shop/delivery_courier/classes/model/courierzone.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_CourierZone extends Model { /** * Default zone delivery price * * @return float */ public function default_price() { return 0.0; } }<file_sep>/modules/shop/area/views/frontend/forms/selecttown.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php echo $form->render_form_open(); ?> <table border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td class="selecttown_input-name-value"> <?php echo $form->get_element('name')->render_input(); ?> </td> <td> <?php echo $form->get_element('submit')->render_input(); ?> </td> </tr> </tbody> </table> <?php echo $form->render_form_close(); ?> <file_sep>/modules/shop/orders/classes/form/frontend/cart.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Cart extends Form { /** * Initialize form fields based on products from cart * * @param array $quantities */ public function init_fields(array $quantities) { foreach ($quantities as $product_id => $quantity) { $element = new Form_Element_Input('quantities[' . $product_id . ']'); $element->default_value = $quantity; $element->add_validator(new Form_Validator_Integer(0, Model_Cart::MAX_QUANTITY)); $this->add_component($element); } $element = new Form_Element_Submit('recalculate'); $element->value = 'Пересчитать'; $this->add_component($element); } } <file_sep>/modules/shop/catalog/classes/task/import/saks_old.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Import catalog from www.saks.ru */ class Task_Import_Saks_Old extends Task_Import_Web { /** * Construct task */ public function __construct() { parent::__construct('http://www.saks.ru'); // Set defaults for task parameters $this->params(array( // brands & series 'create_brands' => FALSE, 'create_series' => FALSE, 'update_brand_captions' => FALSE, 'update_brand_descriptions' => FALSE, 'update_brand_images' => FALSE, // products 'create_products' => TRUE, 'update_product_captions' => FALSE, 'update_product_descriptions' => FALSE, 'update_product_images' => FALSE, 'link_products_by' => 'caption' )); } /** * Run the task */ public function run() { $this->set_progress(0); // tmp //$this->fix_main_sections(); //$this->fix_suppliers(); $this->fix_images(); die; // import brands $brands = $this->import_brands(); // import products //$this->import_products($brands); $this->set_status_info('Импорт завершён'); } /** * Import brands */ public function import_brands() { $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task // get all properties $properties = Model::fly('Model_Property')->find_all_by_site_id($site_id, array('columns' => array('id'))); $propsections = array(); foreach ($properties as $property) { $propsections[$property['id']] = array( 'active' => 1, 'filter' => 0, 'sort' => 0 ); } // ----- brands -------------------------------------------------------- $brands = array(0 => array()); // Retrieve list of all brands with links from catalog page ... $this->set_status_info('Parsing brands'); $page = $this->get('/catalog/'); preg_match_all( '!<li><div><a\s*href="/catalog/about_m/\?brend=(\d+)">([^<]*)!', $page, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $import_id = trim($match[1]); $brand_caption = $this->decode_trim($match[2], 255); $brands[0][$import_id] = array( 'import_id' => $import_id, 'caption' => $brand_caption ); } // Retrieve brand description and image urls & import brands $count = count($brands[0]); $i = 0; $this->set_status_info('Retrieving brands info and importing'); $brand = new Model_Section(); $subbrand = new Model_Section(); foreach ($brands[0] as $brand_info) { $page = $this->get('/catalog/about_m/?brend=' . $brand_info['import_id']); if (preg_match( '!<tr\s*class="noborder">\s*<td>\s*(<img\s*src="([^"]*)"[^>]*>)?(.*?)(?=</td>)!s', $page, $matches)) { $brand_info['image_url'] = $matches[2]; $brand_info['description'] = $matches[3]; } $brand->find_by_web_import_id_and_sectiongroup_id($brand_info['import_id'], $sectiongroup_id); $creating = ( ! isset($brand->id)); $brand->web_import_id = $brand_info['import_id']; $brand->sectiongroup_id = $sectiongroup_id; if ($this->param('update_brands_captions')) { $brand->caption = $brand_info['caption']; } if ($this->param('update_brands_descriptions') && isset($brand_info['description'])) { $brand->description = $brand_info['description']; } // Select all additional properties $brand->propsections = $propsections; if ($creating) { if ($this->param('create_brands')) { $this->log('Creating new brand: "' . $brand->caption . '"'); $brand->save(FALSE, TRUE, FALSE); } else { $this->log('Skipped new brand: "' . $brand->caption . '"'); continue; } } else { $brand->save(FALSE, TRUE, FALSE); } $brand->find($brand->id); //@FIXME: we use it to obtain 'lft' and 'rgt' values if ( isset($brand_info['image_url']) && ($creating || $this->param('update_brands_images'))) { if ( ! $creating) { // Delete existing images $image->delete_all_by_owner_type_and_owner_id('section', $brand->id); } $image_file = $this->download_cached($brand_info['image_url']); if ($image_file) { try { $image = new Model_Image(); $image->source_file = $image_file; $image->owner_type = 'section'; $image->owner_id = $brand->id; $image->config = 'section'; $image->save(); } catch (Exception $e) {} } } // ----- Importing subbrands preg_match_all( '!<li><div><a\s*href="((/catalog)?/(section)?' . $brand_info['id'] . '/(item_)?(\d+)/\?brend=' . $brand_info['id'] . ')">([^<]*)!', $page, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $subbrand_import_id = trim($match[5]); $subbrand_caption = $this->decode_trim($match[6], 255); $brands[$brand_info['id']][$subbrand_import_id] = array( 'id' => $subbrand_import_id, 'caption' => $subbrand_caption, 'url' => $match[1] ); $subbrand->find_by_web_import_id_and_parent($subbrand_import_id, $brand); $subbrand->web_import_id = $subbrand_import_id; $subbrand->sectiongroup_id = $sectiongroup_id; $subbrand->parent_id = $brand->id; //$subbrand->caption = $subbrand_caption; // Select all additional properties $subbrand->propsections = $propsections; // do not recalculate activity for now if ( ! isset($subbrand->id)) { if ($this->param('create_series')) { $this->log('Creating new seria: "' . $subbrand->caption .'" for brand "' . $brand->caption . '"'); $subbrand->save(FALSE, TRUE, FALSE); } else { $this->log('Skipped new seria: "' . $subbrand->caption .'" for brand "' . $brand->caption . '"'); continue; } } else { $subbrand->save(FALSE, TRUE, FALSE); } } $i++; $this->set_status_info('Importing brands : ' . $i . ' of ' . $count . ' done.'); } // Update activity info & stats for sections $brand->mapper()->update_activity(); $brand->mapper()->update_products_count(); return $brands; } /** * Import products * * @param array $brands */ public function import_products(array $brands) { $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task $brand = new Model_Section(); $subbrand = new Model_Section(); $product = new Model_Product(); // Caclulate progress info $count = count($brands, COUNT_RECURSIVE) - count($brands) - count($brands[0]); $i = 0; $this->set_status_info('Importing products'); $status_info = ''; $_imported = array(/* '9846', '16018', '132', '144', '13656', '12133', '134', '12548', '141', '13915', '16234', '16846', '16998', '17035', */ ); foreach ($brands[0] as $brand_info) { /* if (in_array($brand_info['id'], $_imported)) continue; $status_info .= $brand_info['id'] . "\n"; $this->set_status_info($status_info); */ $brand->find_by_caption_and_sectiongroup_id($brand_info['caption'], $sectiongroup_id); foreach ($brands[$brand_info['id']] as $subbrand_info) { $this->set_progress((int) (100 * $i / $count)); $i++; $subbrand->find_by_caption_and_parent($subbrand_info['caption'], $brand); // Obtain first page $subbrand_page = $this->get($subbrand_info['url']); // Detect number of pages if products display is paginated $offset = 0; $max_offset = 0; $per_page = 24; preg_match_all('!<a\s*href="[^"]*from=(\d+)!', $subbrand_page, $matches); if ( ! empty($matches[1])) { $per_page = min($matches[1]); $max_offset = max($matches[1]); } // Iterate over pages for ($offset = 0; $offset <= $max_offset; $offset += $per_page) { if ($offset > 0) { // obtain next page $subbrand_page = $this->get($subbrand_info['url'] . '&from=' . $offset); } preg_match_all( '!<a\s*href="([^"]*)">Перейти\s*на\s*страницу\s*товара!', $subbrand_page, $matches); foreach (array_unique($matches[1]) as $url) { $page = $this->get($url); // caption if (preg_match('!<td>\s*<h6[^>]*>\s*([^<]+)!', $page, $m)) { $caption = $this->decode_trim($m[1], 255); } else { throw new Kohana_Exception('Unable to determine caption for product :ulr', array(':url' => $url)); } $product->find_by_caption_and_section_id($caption, $subbrand->id, array('with_properties' => FALSE)); $creating = ( ! isset($product->id)); // Set caption $product->caption = $caption; // Link to subbrand $product->section_id = $subbrand->id; // marking, age & description if (preg_match( '!' . 'Артикул:([^<]*)(<br>\s*)+' . '(Возраст:([^<]*))?(<br>\s*)' . '(.*?)' . '(<p>\s*(январь|февраль|март|апрель|май|июнь|июль|август|сентябрь|октябрь|ноябрь|декабрь|новинка).*?</p>\s*)?' . '(<p>Рекомендованная\s*розничная.*?</p>\s*)?' . '<ul\s*class="links">' . '!is' , $page, $m)) { $product->marking = $this->decode_trim($m[1], 63); $product->age = $this->decode_trim($m[4]); // cut out images & links from description $description = trim($m[6]); $description = preg_replace('!<img[^>]*>!', '', $description); $description = preg_replace('!<a[^>]*>.*?</a>!', '', $description); $product->description = $description; } // price if (preg_match('!цена:\s*<span[^>]*>([^<]*)!', $page, $m)) { $product->price = new Money(l10n::string_to_float(trim($m[1]))); } // dimensions if (preg_match( '!' . 'Размеры:\s*([\d\.,]+)\s*.\s*([\d\.,]+)\s*.\s*([\d\.,]+)\s*</em>\s*' . '</p>\s*<tr>\s*<td\s*class="link">\s*' . '<a\s*href="' . str_replace(array('?'), array('\?'), $url) . '!is', $subbrand_page, $m)) { $product->width = l10n::string_to_float(trim($m[1])); $product->height = l10n::string_to_float(trim($m[2])); $product->depth = l10n::string_to_float(trim($m[3])); $product->volume = round($product->width * $product->height * $product->depth, 1); } $product->save(); if ($creating) { // Product images $image = new Model_Image(); /* if ( ! $creating) { // Delete already existing images for product $image->delete_all_by_owner_type_and_owner_id('product', $product->id); } * */ preg_match_all( '!<img\s*src="([^"]*_big_[^"]*)"!', $page, $m); foreach (array_unique($m[1]) as $image_url) { $image_url = trim($image_url); $image_file = $this->download_cached($image_url); if ($image_file) { try { $image = new Model_Image(); $image->source_file = $image_file; $image->owner_type = 'product'; $image->owner_id = $product->id; $image->config = 'product'; $image->save(); unset($image); } catch (Exception $e) {} } } } } // foreach $product_id } // foreach $offset }// foreach $subbrand }// foreach $brand } /** * TEMP */ public function update_import_ids() { $rows = DB::select('id', 'web_import_id') ->from('section_tmp') ->where('web_import_id', 'RLIKE', '[[:digit:]]+') ->execute(); foreach ($rows as $row) { DB::update('section') ->set(array('web_import_id' => $row['web_import_id'])) ->where('id', '=', $row['id']) ->execute(); } } /** * TEMP */ public function fix_main_sections() { $sectiongroup_id = 1; $brands = Model::fly('Model_Section')->find_all_by_sectiongroup_id($sectiongroup_id, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption'), 'as_tree' => TRUE )); $loop_protection = 500; do { $products = Model::fly('Model_Product')->find_all(array( 'with_sections' => TRUE, 'columns' => array('id', 'section_id', 'caption', 'web_import_id'), 'batch' => 1000 )); foreach ($products as $product) { if ($product->web_import_id == '' && $product->section_id == 1) { if ( ! isset($product->sections[$sectiongroup_id])) { $this->log('Product "' . $product->caption . '" (' . $product->id . ') is not linked to any brand at all'); $product->delete(FALSE); } else { $this->log('Product "' . $product->caption . '" (' . $product->id . ') has invalid main section value'); $section_ids = array_keys(array_filter($product->sections[$sectiongroup_id])); $product->section_id = $section_ids[0]; $product->save(FALSE, TRUE, FALSE, FALSE, FALSE); } } } } while (count($products) && $loop_protection-- > 0); if ($loop_protection <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); Model::fly('Model_Section')->mapper()->update_products_count(); } /** * */ public function fix_suppliers() { $saks_brands = array( 'LEGO', 'Moxie', 'AURORA', 'Zapf Creation', 'BRATZ', 'WELLY', 'CHAP MEI', 'Little Tikes', 'Peg-Perego', 'Taf Toys', 'Disney', 'NICI', 'Bakugan', 'Cubicfun', 'BEN10', 'Daesung', 'Legend of Nara', 'TRON', 'Hello Kitty' ); $gulliver_brands = array( 'K\'s Kids', 'Sylvanian Families', 'Tiny Love', 'Sonya', 'Tomy', 'Ouaps', 'Gulliver', 'Gulliver (0-3 лет)', 'Gulliver (Collecta)', 'Gulliver коляски', 'Gulliver «Чаепитие»', 'Gulliver рюкзаки', 'Bruder', 'Keenway', 'Silverlit', 'Imaginary Play', 'Wader', 'Hap-P-Kid', 'Fenbo', 'I\'m Toy', 'Hello!', 'Wow', 'Tomica', 'The Colored World', 'Gormiti', 'In my pocket' ); $sectiongroup_id = 1; $brands = Model::fly('Model_Section')->find_all_by_sectiongroup_id($sectiongroup_id, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption'), 'as_tree' => TRUE )); $loop_protection = 500; do { $products = Model::fly('Model_Product')->find_all(array( 'with_sections' => TRUE, 'columns' => array('id', 'section_id', 'supplier', 'caption'), 'batch' => 1000 )); foreach ($products as $product) { if ($product->supplier == 0) { $brand = $brands->ancestor($product->section_id, 1, TRUE); if (in_array($brand['caption'], $saks_brands)) { $this->log('Setting supplier SAKS for product "' . $product->caption . '", brand "' . $brand['caption'] . '"'); $product->supplier = Model_Product::SUPPLIER_SAKS; $product->save(FALSE, FALSE, FALSE, FALSE, FALSE); } elseif (in_array($brand['caption'], $gulliver_brands)) { $this->log('Setting supplier GULLIVER for product "' . $product->caption . '", brand "' . $brand['caption'] . '"'); $product->supplier = Model_Product::SUPPLIER_GULLIVER; $product->save(FALSE, FALSE, FALSE, FALSE, FALSE); } else { $this->log('WARNING: Unable to detect supplier for product "' . $product->caption . '", brand ' . $brand['caption'] . '"'); } } } } while (count($products) && $loop_protection-- > 0); if ($loop_protection <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); } /** * Delete unused images */ public function fix_images() { /* $loop_protection = 1000; do { $images = Model::fly('Model_Image')->find_all(array( 'batch' => '100' )); foreach ($images as $image) { if ($image->owner_type == 'product') { if ( ! Model::fly('Model_Product')->exists_by_id($image->owner_id)) { $this->log('Unused image: ' . $image->image1); } } } } while (count($images) && $loop_protection-- > 0); if ($loop_protection <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); * */ $iterator = new DirectoryIterator(DOCROOT . 'public/data'); $counter = 0; foreach ($iterator as $file) { if (preg_match('/_product(\d+)_/', $file, $matches)) { if ( ! Model::fly('Model_Product')->exists_by_id($matches[1])) { echo 'Deleting ' . $file . '<br />'; unlink(DOCROOT . 'public/data/' . $file); } } $counter++; } echo $counter . ' files processed<br />'; } } <file_sep>/modules/general/gmap/config/gmap.php <?php defined('SYSPATH') or die('No direct access allowed.'); // Don't delete or rename any keys unless you know what you're doing! return array ( // Default map-center. 'default_lat' => 57.397, 'default_lng' => 70.644, // Default zoom-level. 'default_zoom' => 3, // Default "sensor" setting - Used for mobile devices. 'default_sensor' => FALSE, // Default map-type. 'default_maptype' => 'road', // The instance will be set in the render method to a random string (if this value is empty). 'instance' => '', // Default view-options. 'default_view' => 'gmap', 'default_gmap_size_x' => '100%', 'default_gmap_size_y' => '100%', // Default Google Maps controls. 'default_gmap_controls' => array( 'maptype' => array( 'display' => TRUE, 'style' => 'default', 'position' => NULL, ), 'navigation' => array( 'display' => TRUE, 'style' => 'default', 'position' => NULL, ), 'scale' => array( 'display' => TRUE, 'position' => NULL, ), ), // Default options for polylines. 'default_polyline_options' => array( 'strokeColor' => '#000', 'strokeOpacity' => 1, 'strokeWeight' => 3, ), // Default options for polygons. 'default_polygon_options' => array( 'strokeColor' => '#000', 'strokeOpacity' => 1, 'strokeWeight' => 3, 'fillColor' => '#000', 'fillOpacity' => .5, ), );<file_sep>/modules/system/forms/classes/form/element/simpledate.php <?php defined('SYSPATH') or die('No direct script access.'); /** * A date selection input * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_SimpleDate extends Form_Element_Input { /** * Use the same templates as the input element * * @return string */ public function default_config_entry() { return 'input'; } /** * Default date format string * Format is the same as for the strftime() function * * @return string */ public function default_format() { return Kohana::config('datetime.date_format'); } /** * Render date format as default comment * * @return string */ public function default_comment() { return l10n::translate_datetime_format($this->format); } /** * Get element * * @return array */ public function attributes() { $attributes = parent::attributes(); // Add "integer" HTML class if (isset($attributes['class'])) { $attributes['class'] .= ' date'; } else { $attributes['class'] = 'date'; } return $attributes; } /** * Format of the value to be returned by get_value() function * 'date' - string representation in 'Y-m-d' format * 'timestamp' - unix timestamp (default) * * @return string */ public function default_value_format() { return 'timestamp'; } /** * Set value from model * * @param mixed $value * @return Form_Element_SimpleDate */ public function set_value($value) { if ($value instanceof DateTime) { $value = $value->format('Y-m-d'); } if ($this->value_format == 'timestamp') { $this->_value = l10n::date($this->format, $value); } else // == 'date' { if ($value == '') { $this->_value = ''; } else { $this->_value = l10n::datetime_convert($value, 'Y-m-d', $this->format); } } return $this; } /** * Get date value * * @return string|integer */ public function get_value() { $value = parent::get_value(); if ($value === '') { // Allow not to specify dates return $value; } if ($this->value_format == 'timestamp') { return l10n::timestamp($this->format, $value, 0, 0, 0); } else { return l10n::datetime_convert($value, $this->format, 'Y-m-d'); } } /** * @return string */ public function get_value_for_validation() { return parent::get_value(); } /** * @return string */ public function get_value_for_render() { return parent::get_value(); } } <file_sep>/modules/general/flash/classes/controller/frontend/flashblocks.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Flashblocks extends Controller_Frontend { /** * Render all blocks with given name * * @param string $name * @return string */ public function widget_flashblocks() { // Find all visible blocks with given name for current node $node_id = Model_Node::current()->id; $flashblock = new Model_Flashblock(); $flashblocks = $flashblock->find_all_visible_by_node_id($node_id, array('order_by' => 'position', 'desc' => FALSE)); if ( ! count($flashblocks)) { return ''; } $script = ''; foreach ($flashblocks as $flashblock) { $script .= $flashblock->register(); } Layout::instance()->add_script($script,TRUE); } } <file_sep>/modules/general/filemanager/classes/filemanager/exception.php <?php defined('SYSPATH') or die('No direct access'); /** * Filemanager exception * * @package Eresus * @author <NAME> (<EMAIL>) */ class Filemanager_Exception extends Kohana_Exception { } <file_sep>/modules/general/menus/classes/controller/backend/menus.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Menus extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Menu'; $this->_form = 'Form_Backend_Menu'; return array( 'create' => array( 'view_caption' => 'Создание меню' ), 'update' => array( 'view_caption' => 'Редактирование меню ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление меню', 'message' => 'Удалить меню ":caption"?' ) ); } /** * @return boolean */ public function before() { if ( ! parent::before()) { return FALSE; } if ($this->request->is_forwarded()) // Request was forwarded in parent::before() return TRUE; // Check that there is a site selected if (Model_Site::current()->id === NULL) { $this->_action_error('Выберите сайт для работы с меню!'); return FALSE; } return TRUE; } /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Default action */ public function action_index() { $this->request->response = $this->render_layout($this->widget_menus()); } /** * Renders menu list * * @return string */ public function widget_menus() { $site_id = (int) Model_Site::current()->id; $menu = new Model_Menu(); $order_by = $this->request->param('menus_order', 'id'); $desc = (bool) $this->request->param('menus_desc', '0'); // Select all menus for current site $site_id = Model_Site::current()->id; $menus = $menu->find_all_by_site_id($site_id, array('order_by' => $order_by, 'desc' => $desc)); // Set up view $view = new View('backend/menus'); $view->order_by = $order_by; $view->desc = $desc; $view->menus = $menus; return $view; } } <file_sep>/modules/general/comments/views/comments/comments.php <hr /> <div class="row"> <div class="span6"> <div id="vk_comments"></div> <script type="text/javascript" src="//vk.com/js/api/openapi.js?79"></script> <script type="text/javascript"> VK.init({apiId: <?=$cfg['vk_key'];?>, onlyWidgets: true}); </script> <script type="text/javascript"> VK.Widgets.Comments("vk_comments", {limit: <?=$cfg['vk_messages'];?>, width: "<?=$cfg['vk_width'];?>", attach: "*"}); </script> </div> <div class="span6"> <div class="fb-comments" data-href="<?=$_SERVER['HTTP_HOST'];?>/<?=$_SERVER['REQUEST_URI'];?>" data-width="<?=$cfg['fb_width'];?>" data-num-posts="<?=$cfg['fb_messages'];?>"></div> </div> </div><file_sep>/modules/system/forms/classes/form/filter.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Abstract form filter * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Form_Filter { /** * Form element to which this filter is attached * @var Form_Element */ protected $_form_element; /** * Set form element * * @param Form_Element $form_element * @return Validator */ public function set_form_element(Form_Element $form_element) { $this->_form_element = $form_element; return $this; } /** * Get form element * * @return Form_Element */ public function get_form_element() { return $this->_form_element; } /** * Filter given value * * @param mixed $value * @return mixed */ public function filter($value) { return $value; } }<file_sep>/modules/system/database_eresus/classes/database/query/builder/where.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Database query builder for WHERE statements. * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Database_Query_Builder_Where extends Kohana_Database_Query_Builder_Where { /** * Maintained as array to preserve compatibility with _compile_conditions(), * which requires the second parameter, conditions, to be an array * @var Database_Expression_Where */ protected $_where; /** * @return Database_Expression_Where */ public function get_where() { if ($this->_where === NULL) { $this->_where = array(new Database_Expression_Where()); } return $this->_where[0]; } /** * Creates a new "AND WHERE" condition for the query. * * @param mixed column name or array($column, $alias) or Database_Query_Builder_Where object * @param string logic operator * @param mixed column value or object * @return $this */ public function and_where($column, $op, $value) { $this->get_where()->and_where($column, $op, $value); return $this; } /** * Creates a new "OR WHERE" condition for the query. * * @param mixed column name or array($column, $alias) or Database_Query_Builder_Where object * @param string logic operator * @param mixed column value * @return $this */ public function or_where($column, $op, $value) { $this->get_where()->or_where($column, $op, $value); return $this; } /** * Opens a new "AND WHERE (...)" grouping. * * @return $this */ public function and_where_open() { $this->get_where()->and_where_open(); return $this; } /** * Opens a new "OR WHERE (...)" grouping. * * @return $this */ public function or_where_open() { $this->get_where()->or_where_open(); return $this; } /** * Closes an open "AND WHERE (...)" grouping. * * @return $this */ public function and_where_close() { $this->get_where()->and_where_close(); return $this; } /** * Closes an open "OR WHERE (...)" grouping. * * @return $this */ public function or_where_close() { $this->get_where()->or_where_close(); return $this; } } // End Database_Query_Builder_Where<file_sep>/modules/general/tags/views/frontend/image.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Width & height of one image preview $canvas_height = 110; $canvas_width = 110; if (!$image->id) { return; } $delete_url = URL::to('frontend/images', array('action'=>'delete', 'id' => $image->id, 'config' => $image->config), TRUE); ?> <?php $i = count($image->get_thumb_settings()); // Number of the last (the smallest) thumb $width = $image->__get("width$i"); $height = $image->__get("height$i"); if ($width > $canvas_width || $height > $canvas_height) { if ($width > $height) { $scale = ' style="width: ' . $canvas_width . 'px;"'; $height = $height * $canvas_width / $width; $width = $canvas_width; } else { $scale = ' style="height: ' . $canvas_height . 'px;"'; $width = $width * $canvas_height / $height; $height = $canvas_height; } } else { $scale = ''; } if ($canvas_height > $height) { $padding = ($canvas_height - $height) >> 1; // ($canvas_height - $height) / 2 $padding = ' padding-top: ' . $padding . 'px;'; } else { $padding = ''; } ?> <div class="images"style="width: <?php echo $canvas_width+10; ?>px; float: left; margin-left:130px;"> <div class="image"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($delete_url, 'Удалить изображение', 'controls/delete.gif', 'Удалить'); ?> </div> <div class="img" style="width: <?php echo $canvas_width; ?>px; height: <?php echo $canvas_width; ?>px;"> <a href="" style="<?php echo $padding; ?>"> <img src="<?php // Render the last (assumed to be the smallest) thumbnail echo File::url($image->image($i)); ?>" <?php echo $scale; ?> alt="" /> </a> </div> </div> </div> <file_sep>/modules/shop/acl/views/frontend/forms/notify.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div id="notifyModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3>Пожалуйста</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <label for="text"><?php echo $form->get_element('text')->render_input(); ?></label> </div> <div class="modal-footer"> <button type="button" class="button_notify button-modal button" data-dismiss="modal" aria-hidden="true">Вернуться</button> </div> <?php echo $form->render_form_close();?> </div><file_sep>/application/views/layouts/vision.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require('_header_new.php'); ?> <body> <header> <div class="container"> <div class="row"> <div class="span12"> <a href="home.html" class="logo pull-left"></a> <?php echo Widget::render_widget('menus','menu', 'main'); ?> <ul class="second-menu"> <?php echo Widget::render_widget('towns','select'); ?> <?php echo Widget::render_widget('products','format_select'); ?> <?php echo Widget::render_widget('products','theme_select'); ?> <?php echo Widget::render_widget('products','calendar_select'); ?> </ul> <div class="b-auth-search"> <?php echo Widget::render_widget('acl', 'login'); ?> <?php echo Widget::render_widget('products', 'search');?> <div class="b-lang"> <a class="current" href="">RU</a><span class="dash">|</span><a href="">EN</a> </div> </div> </div> </div> </div> </header> <div id="main"> <div class="container"> <div class="row"> <article class="span12" id="event"> <?php echo $content; ?> </article> </div> </div> </div> <?php require('_footer.php'); ?> <?php echo $view->placeholder('modal'); ?> </body> <file_sep>/modules/general/breadcrumbs/classes/breadcrumbs.php <?php defined('SYSPATH') or die('No direct script access.'); class Breadcrumbs { /** * Append a custom breadcrumb * * @param array $breadcrumb * @param Request $request */ public static function append(array $breadcrumb, Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } $append = $request->get_value('breadcrumbs_append'); if ($append === NULL) { $append = array(); } $append[] = $breadcrumb; $request->set_value('breadcrumbs_append', $append); } /** * Get all breadcrumbs * * @param Request $request */ public static function get_all(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } $breadcrumbs = array(); // Generate breadcrumbs from path to current node if (Model_Node::current()->id !== NULL) { foreach (Model_Node::current()->path as $node) { $breadcrumbs[] = array( 'id' => $node->id, 'caption' => $node->caption, 'uri' => $node->frontend_uri ); } } $append = $request->get_value('breadcrumbs_append'); if ( ! empty($append)) { // Add custom breadcrumbs $breadcrumbs = array_merge($breadcrumbs, $append); } return $breadcrumbs; } } <file_sep>/modules/general/faq/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { Route::add('frontend/faq', new Route_Frontend( 'faq(/<action>(/<id>))(/p-<page>)', array( 'action' => '\w++', 'id' => '\d++', 'page' => '(\d++|all)' ))) ->defaults(array( 'controller' => 'faq', 'action' => 'index', 'id' => NULL, 'page' => '0' )); } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/faq', new Route_Backend( 'faq(/<action>(/<id>)(/ids-<ids>))' . '(/p-<page>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[0-9_]++', 'page' => '(\d++|all)', 'history' => '.++' ))) ->defaults(array( 'controller' => 'faq', 'action' => 'index', 'id' => NULL, 'ids' => '', 'page' => '0', )); // ----- Add backend menu items $id = Model_Backend_Menu::add_item(array( 'id' => 6, 'menu' => 'main', 'caption' => 'Вопрос-ответ', 'route' => 'backend/faq', 'icon' => 'faq' )); Model_Backend_Menu::add_item(array( 'parent_id' => $id, 'menu' => 'main', 'caption' => 'Список вопросов', 'route' => 'backend/faq', 'select_conds' => array( array('route' => 'backend/faq', 'route_params' => array('action' => 'index')), array('route' => 'backend/faq', 'route_params' => array('action' => 'create')), array('route' => 'backend/faq', 'route_params' => array('action' => 'update')), array('route' => 'backend/faq', 'route_params' => array('action' => 'delete')) ) )); Model_Backend_Menu::add_item(array( 'parent_id' => $id, 'menu' => 'main', 'caption' => 'Настройки', 'route' => 'backend/faq', 'route_params' => array('action' => 'config') )); } /****************************************************************************** * Common ******************************************************************************/ // ----- Add node types Model_Node::add_node_type('faq', array( 'name' => 'Вопрос-ответ', 'backend_route' => 'backend/faq', 'frontend_route' => 'frontend/faq' )); <file_sep>/modules/general/twig/lib/Twig/Template.php <?php /* * This file is part of Twig. * * (c) 2009 <NAME> * (c) 2009 <NAME> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ abstract class Twig_Template extends Twig_Resource implements Twig_TemplateInterface { protected $blocks; public function __construct(Twig_Environment $env) { parent::__construct($env); $this->blocks = array(); } protected function getBlock($name, array $context) { return call_user_func($this->blocks[$name][0], $context, array_slice($this->blocks[$name], 1)); } protected function getParent($context, $parents) { return call_user_func($parents[0], $context, array_slice($parents, 1)); } public function pushBlocks($blocks) { foreach ($blocks as $name => $call) { if (!isset($this->blocks[$name])) { $this->blocks[$name] = array(); } $this->blocks[$name] = array_merge($call, $this->blocks[$name]); } } /** * Renders the template with the given context and returns it as string. * * @param array $context An array of parameters to pass to the template * * @return string The rendered template */ public function render(array $context) { ob_start(); try { $this->display($context); } catch (Exception $e) { ob_end_clean(); throw $e; } return ob_get_clean(); } abstract protected function getName(); } <file_sep>/modules/shop/acl/views/frontend/login.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (isset($user)) { $logout_url = URL::to('frontend/acl', array('action' => 'logout')); $profile_url = URL::to('frontend/acl/users/control',array('action' => 'control')); ?> <a href="<?php echo $profile_url; ?>">Моя страница</a> <!-- Вы зашли как: <a href="<?php echo $profile_url; ?>"> <?php echo $user->email ?> --></a> <a href="<?php echo $logout_url; ?>">&raquo; Выход</a> <?php } else { $reg_url = URL::to('frontend/acl/users/register',array('action' => 'create')); //echo '<a data-toggle="modal" href="#enterModal">Войти</a><span class="dash">|</span><a data-toggle="modal" href="#regModal">Регистрация</a>'; echo '<a data-toggle="modal" href="#enterModal">Войти</a><span class="dash">|</span><a href="'.$reg_url.'">Стать представителем</a>'; }?> <file_sep>/modules/system/forms/classes/form/fieldset/columns.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Render elements in columns * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Fieldset_Columns extends Form_Fieldset { /** * Add a child component to the desired column * * @param FormComponent $component * @param integer $column * @return FormComponent */ public function add_component(FormComponent $component, $column = 1) { parent::add_component($component); if ( ! isset($component->column)) { $component->column = $column; } return $this; } // ------------------------------------------------------------------------- // Rendering // ------------------------------------------------------------------------- /** * Renders all elements in fieldset in columns * * @return string */ public function render_components() { $html = ''; $columns = array(); // Render each column foreach ($this->get_components() as $component) { $column_i = (int) $component->column; if ( ! isset($columns[$column_i])) { $columns[$column_i] = ''; } $columns[$column_i] .= $component->render(); } // Join columns together $template = $this->get_template('column'); $html = ''; foreach ($columns as $i => $column) { $html .= Template::replace_ret($template, array( 'elements' => $column, 'last' => ($i >= count($columns)) ? 'last' : '', 'class' => isset($this->column_classes[$i]) ? $this->column_classes[$i] : '' )); } return $html; } }<file_sep>/modules/shop/catalog/classes/task/comdi/delete.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Delete event through COMDI API */ class Task_Comdi_Delete extends Task_Comdi_Base { public static $params = array( 'key', 'event_id', ); /** * Construct task */ public function __construct() { parent::__construct('http://my.webinar.ru'); $this->default_params(); } /** * Run the task */ public function run() { $xml_response = parent::send('/api0/Delete.php',$this->params(self::$params)); $id = ($xml_response['event_id'] == null)? null:(string)$xml_response['event_id']; if ($id ===NULL) { $this->set_status_info('Событие не было удалено'); } else { $this->set_status_info('Событие удалено'); } return $id; } } <file_sep>/modules/shop/delivery_courier/classes/controller/backend/courierzones.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_CourierZones extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_CourierZone'; $this->_form = 'Form_Backend_CourierZone'; return array( 'create' => array( 'view_caption' => 'Создание новой зоны доставки курьером' ), 'update' => array( 'view_caption' => 'Редактирование зоны доставки курьером ":name"' ), 'delete' => array( 'view_caption' => 'Удаление товара', 'message' => 'Удалить зону доставки курьером ":name"?' ), 'multi_delete' => array( 'view_caption' => 'Удаление зон доставки курьером', 'message' => 'Удалить выбранные зоны?', 'message_empty' => 'Выберите хотя бы одну зону!' ) ); } /** * Create layout (proxy to delivery_courier controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('delivery_coureir')->prepare_layout($layout_script); } /** * Render layout (proxy to delivery_courier controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('delivery_courier')->render_layout($content, $layout_script); } /** * Create new courier zone model * * @param string|Model $model * @param array $params * @return Model_CourierZone */ protected function _model_create($model, array $params = NULL) { // New zone for current delivery type $delivery = new Model_Delivery_Courier(); $delivery->find((int) $this->request->param('delivery_id')); if ( ! isset($delivery->id)) { throw new Controller_BackendCRUD_Exception('Указанный способ доставки не найден!'); } $zone = new Model_CourierZone(); $zone->delivery_id = $delivery->id; return $zone; } /** * Render list of courier delivery zones * * @param Model_Delivery_Courier $delivery */ public function widget_courierzones(Model_Delivery_Courier $delivery) { $order_by = 'position'; $desc = FALSE; $zones = Model::fly('Model_CourierZone')->find_all_by_delivery_id($delivery->id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/delivery/courierzones'); $view->order_by = $order_by; $view->desc = $desc; $view->delivery_id = $delivery->id; $view->zones = $zones; return $view->render(); } }<file_sep>/modules/general/indexpage/config/images.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // Configure images for slideshow 'indexpage' => array( array('width' => 680, 'height' => 360, 'master' => Image::INVERSE) ) );<file_sep>/modules/general/images/classes/controller/frontend/images.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Images extends Controller_FrontendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Image'; $this->_form = 'Form_Frontend_Image'; return array( 'create' => array( 'view_caption' => 'Создание изображения' ), 'update' => array( 'view_caption' => 'Редактирование изображения' ), 'delete' => array( 'view_caption' => 'Удаление изображения', 'message' => 'Удалить изображение?' ) ); } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('frontend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->caption = 'Изображения'; $layout->content = $view; return $layout->render(); } /** * Prepare image for update & delete actions * * @param string $action * @param string|Model $model * @param array $params * @return Model_image */ protected function _model($action, $model, array $params = NULL) { $image = parent::_model($action, $model, $params); if ($action == 'create') { // Set up onwer for image being created $image->owner_type = $this->request->param('owner_type'); $image->owner_id = $this->request->param('owner_id'); } // Set up config for image in action $image->config = $this->request->param('config'); return $image; } /** * Renders list of images for specified owner * * @param string $owner_type * @param integer $owner_id * @return string */ public function widget_images($owner_type, $owner_id, $config) { // Add styles to layout Layout::instance()->add_style(Modules::uri('images') . '/public/css/frontend/images.css'); $order_by = $this->request->param('img_order_by', 'position'); $desc = (boolean) $this->request->param('img_desc', '0'); $images = Model::fly('Model_Image')->find_all_by_owner_type_and_owner_id( $owner_type, $owner_id, array('order_by' => $order_by, 'desc' => $desc) ); $view = new View('frontend/images'); $view->images = $images; $view->owner_type = $owner_type; $view->owner_id = $owner_id; $view->config = $config; $view->desc = $desc; return $view; } /** * Redraw product images widget via ajax request */ public function action_ajax_create() { $request = Widget::switch_context(); // // $product = Model_Product::current(); // // $user = Model_User::current(); // // if ( ! isset($product->id) && ! isset($user->id)) // { // $this->_action_404(); // return; // } // // $telemost = new Model_Telemost(); // $telemost->find_by_product_id($product->id, array('owner' => $user)); // // if ($telemost->id) { // $telemost->delete(); // } // $owner_type = $this->request->param('owner_type',NULL); $owner_id = $this->request->param('owner_id',NULL); $config = $this->request->param('config'); $widget = $request->get_controller('images') ->widget_small_images($owner_type,$owner_id,$config); $widget->to_response($this->request); $this->_action_ajax(); } /** * Renders list of images for specified owner * * @param string $owner_type * @param integer $owner_id * @return string */ public function widget_small_images($owner_type, $owner_id, $config) { $widget = new Widget('frontend/small_images'); $widget->id = 'image_' . $owner_id; $widget->context_uri = FALSE; // use the url of clicked link as a context url // Add styles to layout Layout::instance()->add_style(Modules::uri('images') . '/public/css/frontend/images.css'); $order_by = $this->request->param('img_order_by', 'position'); $desc = (boolean) $this->request->param('img_desc', '0'); $images = Model::fly('Model_Image')->find_all_by_owner_type_and_owner_id( $owner_type, $owner_id, array('order_by' => $order_by, 'desc' => $desc) ); $widget->images = $images; $widget->owner_type = $owner_type; $widget->owner_id = $owner_id; $widget->config = $config; $widget->desc = $desc; return $widget; } public function widget_create($owner_type, $owner_id, $config) { $view = new View('frontend/create'); $image = new Model_Image(); $form_image_ajax = new Form_Frontend_ImageAJAX(); if ($form_image_ajax->is_submitted()) { // User is trying to log in if ($form_image_ajax->validate()) { $vals = $form_image_ajax->get_values(); $vals['owner_type'] = $owner_type; $vals['owner_id'] = $owner_id; $vals['config'] = $config; if ($image->validate($vals)) { $image->values($vals); $image->save(); } } } $modal = Layout::instance()->get_placeholder('modal'); $modal .= ' '.$form_image_ajax->render(); Layout::instance()->set_placeholder('modal',$modal); return $view; } /** * Render one image for specified owner * * @param string $owner_type * @param integer $owner_id * @return string */ public function widget_image($owner_type, $owner_id, $config) { // Add styles to layout Layout::instance()->add_style(Modules::uri('images') . '/public/css/frontend/images.css'); $image = new Model_Image(); $image->find_by_owner_type_and_owner_id($owner_type, $owner_id); $image->owner_type = $owner_type; $image->owner_id = $owner_id; $image->config = $config; $view = new View('frontend/image'); $view->image = $image; return $view; } }<file_sep>/modules/shop/catalog/public/js/backend/catalog.js /** * Initialize */ $(function(){ // ----- Sections tree // Initialize toggle tree branches controls $('.tree').each(function(i, tree){ // Obtain tree id - this would be used as prefix to control and branch ids var prefix = tree.id; var loaded = {}; /** * Detect all clicks within the tree, determine what was clicked by event.target * If a control was clicked then toggle corresponding branch */ $(tree).click(function(event){ var re = new RegExp(prefix + '_toggle_(\\d+)'); var matches = event.target.id.match(re); if (matches) { // "toggle" bullet was clicked var toggle = $(event.target); var branch_id = matches[1]; var branch = $('#' + prefix + '_branch_' + branch_id); var url = branch_toggle_url.replace('{{id}}', branch_id); if (branch.hasClass('folded')) { // Unfold (show) the branch toggle.removeClass('toggled_off'); branch.removeClass('folded').show(); if ( ! loaded[branch_id]) { // If branch is empty - load its contents via ajax request branch.html('Loading...'); $.get(url.replace('{{toggle}}', 'on'), null, function(response){ loaded[branch_id] = 1; branch.html(response); }); } else { // If not empty - simply peform an ajax request to save branch state in session $.get(url.replace('{{toggle}}', 'on')); } } else { // Fold (hide) the branch toggle.addClass('toggled_off'); branch.addClass('folded').hide(); // Mark as loaded loaded[branch_id] = 1; // Peform an ajax request to save branch state in session $.get(url.replace('{{toggle}}', 'off')); } event.preventDefault(); } }); }); }); <file_sep>/modules/shop/catalog/classes/controller/backend/telemosts.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Telemosts extends Controller_BackendRES { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Telemost'; $this->_form = 'Form_Backend_Telemost'; $this->_view = 'backend/form'; return array( 'create' => array( 'view_caption' => 'Создание телемоста' ), 'update' => array( 'view_caption' => 'Редактирование телемоста' ), 'delete' => array( 'view_caption' => 'Удаление телемоста', 'message' => 'Удалить телемост?' ) ); } /** * Create layout (proxy to products controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('products')->prepare_layout($layout_script); } /** * Render layout (proxy to products controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('products')->render_layout($content, $layout_script); } /** * Prepare telemost model for create action * * @param string|Model_Telemost $telemost * @param array $params * @return Model_Telemost */ protected function _model_create($telemost, array $params = NULL) { $telemost = parent::_model('create', $telemost, $params); $product_id = (int) $this->request->param('product_id'); if ( ! Model::fly('Model_Product')->exists_by_id($product_id)) { throw new Controller_BackendCRUD_Exception('Указанный анонс не существует!'); } $telemost->product_id = $product_id; return $telemost; } /** * Renders list of product telemosts * * @param Model_Product $product * @return string */ public function widget_telemosts($product) { $app_telemosts = $product->app_telemosts; $telemosts = $product->telemosts; // Set up view $view = new View('backend/telemosts'); $view->product = $product; $view->app_telemosts = $app_telemosts; $view->telemosts = $telemosts; return $view->render(); } /** * Choose telemost application */ public function action_choose() { $this->_action_get('choose'); } /** * Choose telemost application * * @param Model $model * @param Form $form * @param array $params */ protected function _execute_choose(Model $model, array $params = NULL) { $model->active = TRUE; if ($model->validate_choose()) { $model->save(); } $this->request->redirect(URL::uri_back()); /*$telemost_id = (int) $this->request->param('id'); $telemost = Model::fly('Model_Telemost')->find($telemost_id); if ( ! $telemost->id) { throw new Controller_BackendCRUD_Exception('Указанная заявка на телемост не существует!'); } $telemost->active = TRUE; $telemost->save(); $this->request->redirect(URL::uri_back()); */ } }<file_sep>/modules/shop/catalog/classes/controller/frontend/sections.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Sections extends Controller_Frontend { public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('catalog') . '/public/css/frontend/catalog.css'); if ($this->request->action == 'select') { // Add sections select js scripts $layout->add_script(Modules::uri('catalog') . '/public/js/frontend/sections_select.js'); } return $layout; } /** * Render a list of sections */ public function action_index() { $sectiongroup = Model_SectionGroup::current(); if ( ! isset($sectiongroup->id)) { $this->_action_404('Указанная группа категорий не найдена'); return; } // Find all active sections for given sectiongroup $sections = Model::fly('Model_Section')->find_all_active_cached($sectiongroup->id); $view = new View('frontend/sections/list'); $view->sectiongroup = $sectiongroup; $view->sections = $sections; // Add breadcrumbs //$this->add_breadcrumbs(); $this->request->response = $this->render_layout($view->render()); } /** * Renders catalog sections menu * * @return string */ public function widget_menu() { $sectiongroup = Model_SectionGroup::current(); $section = Model_Section::current(); // Obtain information about which sections are expanded from session // The returned array is an array of id's of unfolded sections $unfolded = Session::instance()->get('sections', array()); // Select only sections that are visible (i.e. their parents are unfolded) $sections = $section->find_all_unfolded($sectiongroup->id, NULL, $unfolded, array( 'order_by' => 'lft', 'desc' => '0', 'as_tree' => true )); $sectiongroups = $sectiongroup->find_all_cached(); $view = new View('frontend/sections/menu'); $view->section_id = $section->id; $view->sectiongroup = $sectiongroup; $view->unfolded = $unfolded; $view->sections = $sections; $view->sectiongroups = $sectiongroups; $toggle_url = URL::to('frontend/catalog/section', array( 'sectiongroup_name' => $sectiongroup->name, 'path' => '{{path}}', 'toggle' => '{{toggle}}' )) . '?context=' . $this->request->uri . "';"; $layout = $this->prepare_layout(); $layout->add_script(Modules::uri('catalog') . '/public/js/frontend/catalog.js'); $layout->add_script( "var branch_toggle_url = '" . $toggle_url , TRUE); return $view->render(); } /** * Save sections branch visibility (folded or not?) in session * * Executed either via ajax or normally */ public function action_toggle() { $section = Model_Section::current(); $toggle = $this->request->param('toggle', ''); if ($toggle != '' && $section->id !== NULL) { $branch_id = $section->id; $unfolded = Session::instance()->get('sections', array()); if ($toggle == 'on' && ! in_array($branch_id, $unfolded)) { // Unfold the branch - add section id to the list of unfolded sections $unfolded[] = $branch_id; } else { // Fold the branch - remove section id from the list of unfolded sections $k = array_search($branch_id, $unfolded); if ($k !== FALSE) { unset($unfolded[$k]); } } Session::instance()->set('sections', $unfolded); if (Request::$is_ajax && $toggle == 'on') { // Render branch of sections if ( ! empty($_GET['context'])) { // Switch request context (render as if a controller is accessed via url = $context) $context = $_GET['context']; $request = new Request($context); Request::$current = $request; $controller = $request->get_controller('sections'); $this->request->response = $controller->widget_sections_branch($section); } else { // Render in current context $this->request->response = $this->widget_sections_branch($section); } } } if ( ! Request::$is_ajax) { $this->request->redirect(URL::uri_back()); } } /** * Select several sections */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор каталога событий "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_select(); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_select()); } } /** * Render list of section to select several section for current section group * * @param integer $select * @return string */ public function widget_select($select = FALSE) { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } $sectiongroup = Model_SectionGroup::current(); $section = Model_Section::current(); // ----- Render section for current section group $order_by = $this->request->param('cat_sorder', 'lft'); $desc = (bool) $this->request->param('cat_sdesc', '0'); $sections = $section->find_all_by_sectiongroup_id($sectiongroup->id, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'active', 'section_active'), 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('frontend/sections/select'); $view->order_by = $order_by; $view->desc = $desc; $view->sectiongroup_id = $sectiongroup->id; $view->section_id = $section->id; $view->sections = $sections; return $view->render(); } /** * Render a branch of sections (used to redraw tree via ajax requests) * * @param Model_Section $parent */ public function widget_sections_branch(Model_Section $parent) { $sectiongroup = Model_SectionGroup::current(); // Obtain information about which sections are expanded from session // The returned array is an array of id's of unfolded sections $unfolded = Session::instance()->get('sections', array()); // Select only sections that are visible (i.e. their parents are unfolded) $sections = $parent->find_all_unfolded(NULL, $parent, $unfolded, array( 'order_by' => 'lft', 'desc' => '0', 'as_tree' => true )); $view_script = 'frontend/sections/menu_ajax'; $view = new View($view_script); $view->parent = $parent; $view->unfolded = $unfolded; $view->sections = $sections; $view->sectiongroup_name = $sectiongroup->name; return $view->render(); } /** * Renders catalog sections menu * * @return string */ /* public function widget_menu() { $current = Model_Section::current(); if ( ! isset($current->id)) { return 'Указанный раздел не найден'; } $sections = $current->find_all_active_cached($current->sectiongroup_id); // Find the root parent for current section $root = clone $sections->ancestor($current, 1); // Set up view $view = new View('frontend/sections/menu'); $view->current = $current; $view->root = $root; $view->sections = $sections; $view->sectiongroup = Model_SectionGroup::current(); return $view->render(); } */ /** * Add breadcrumbs for current action */ public function add_breadcrumbs(array $request_params = array()) { if (empty($request_params)) { list($name, $request_params) = URL::match(Request::current()->uri); } $sectiongroup = Model_SectionGroup::current(); if ( ! isset($sectiongroup->id)) return; Breadcrumbs::append(array( 'uri' => $sectiongroup->uri_frontend(), 'caption' => $sectiongroup->caption )); $section = Model_Section::current(); if ( ! isset($section->id)) return; // find all parents for current section and append the current section itself $sections = $section->find_all_active_cached($sectiongroup->id); $parents = $sections->parents($section, FALSE); foreach ($parents as $parent) { Breadcrumbs::append(array( 'uri' => $parent->uri_frontend(), 'caption' => $parent->caption )); } Breadcrumbs::append(array( 'uri' => $section->uri_frontend(), 'caption' => $section->caption )); } } <file_sep>/modules/general/twig/lib/Twig/Resource.php <?php /* * This file is part of Twig. * * (c) 2009 <NAME> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ abstract class Twig_Resource { protected $env; protected $cache; public function __construct(Twig_Environment $env) { $this->env = $env; $this->cache = array(); } public function getEnvironment() { return $this->env; } protected function getContext($context, $item) { if (isset($context[$item])) { return $context[$item]; } if (!$this->env->isStrictVariables()) { return null; } throw new InvalidArgumentException(sprintf('Item "%s" from context does not exist.', $item)); } protected function getAttribute($object, $item, array $arguments = array(), $type = Twig_Node_Expression_GetAttr::TYPE_ANY) { // array if (Twig_Node_Expression_GetAttr::TYPE_METHOD !== $type) { if ((is_array($object) || is_object($object) && $object instanceof ArrayAccess) && isset($object[$item])) { return $object[$item]; } if (Twig_Node_Expression_GetAttr::TYPE_ARRAY === $type) { if (!$this->env->isStrictVariables()) { return null; } throw new InvalidArgumentException(sprintf('Key "%s" for array "%s" does not exist.', $item, $object)); } } if (!is_object($object)) { if (!$this->env->isStrictVariables()) { return null; } throw new InvalidArgumentException(sprintf('Item "%s" for "%s" does not exist.', $item, $object)); } // object property if (Twig_Node_Expression_GetAttr::TYPE_METHOD !== $type) { if (isset($object->$item)) { if ($this->env->hasExtension('sandbox')) { $this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item); } return $object->$item; } } // object method $class = get_class($object); if (!isset($this->cache[$class])) { $r = new ReflectionClass($class); $this->cache[$class] = array(); foreach ($r->getMethods(ReflectionMethod::IS_STATIC | ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_FINAL) as $method) { $this->cache[$class][strtolower($method->getName())] = true; } } $item = strtolower($item); if (isset($this->cache[$class][$item])) { $method = $item; } elseif (isset($this->cache[$class]['get'.$item])) { $method = 'get'.$item; } elseif (isset($this->cache[$class]['__call'])) { $method = $item; } else { if (!$this->env->isStrictVariables()) { return null; } throw new InvalidArgumentException(sprintf('Method "%s" for object "%s" does not exist.', $item, get_class($object))); } if ($this->env->hasExtension('sandbox')) { $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method); } return call_user_func_array(array($object, $method), $arguments); } } <file_sep>/modules/shop/catalog/classes/form/frontend/product.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Product extends Form_Frontend { /** * Initialize form fields */ public function init() { // Set HTML class $this->view_script = 'frontend/forms/product'; // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название'), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $element->config_entry = 'input_front'; $this->add_component($element); // ------------------------------------------------------------------------------------- // lecturer // ------------------------------------------------------------------------------------- // control hidden field $control_element = new Form_Element_Hidden('lecturer_id',array('id' => 'lecturer_id')); $this->add_component($control_element); if ($control_element->value !== FALSE) { $lecturer_id = (int) $control_element->value; } else { $lecturer_id = (int) $this->model()->lecturer_id; } // ----- lecturer_name // input field with autocomplete ajax $element = new Form_Element_Input('lecturer_name', array('label' => 'Лектор', 'layout' => 'wide','id' => 'lecturer_name')); $element->autocomplete_url = URL::to('frontend/acl/lecturers', array('action' => 'ac_lecturer_name')); Layout::instance()->add_style(Modules::uri('acl') . '/public/css/frontend/acl.css'); $this->add_component($element); $lecturer = new Model_Lecturer(); $lecturer->find($lecturer_id); $lecturer_name = ($lecturer->id !== NULL) ? $lecturer->name : '--- лектор не указан ---'; if ($element->value === FALSE) { $element->value = $lecturer_name; } else { if ($element->value !== $lecturer_name) $control_element->set_value(NULL); } // ------------------------------------------------------------------------------------- // organizer // ------------------------------------------------------------------------------------- $control_element = new Form_Element_Hidden('organizer_id',array('id' => 'organizer_id')); $this->add_component($control_element); if ($control_element->value !== FALSE) { $organizer_id = (int) $control_element->value; } elseif ($this->model()->organizer_id) { $organizer_id = (int) $this->model()->organizer_id; $control_element->value = $organizer_id; } elseif (Model_User::current()->organizer_id) { $organizer_id = (int) Model_User::current()->organizer_id; $control_element->value = $organizer_id; } // ----- organizer_name // input field with autocomplete ajax $element = new Form_Element_Input('organizer_name', array('label' => 'Организация', 'layout' => 'wide','id' => 'organizer_name')); $element->autocomplete_url = URL::to('frontend/acl/organizers', array('action' => 'ac_organizer_name')); Layout::instance()->add_style(Modules::uri('acl') . '/public/css/frontend/acl.css'); $this->add_component($element); $organizer = new Model_Organizer(); $organizer->find($organizer_id); $organizer_name = ($organizer->id !== NULL) ? $organizer->name : ''; if ($element->value === FALSE) { $element->value = $organizer_name; } else { if ($element->value !== $organizer_name) $control_element->set_value(NULL); } // ----- Form buttons $button = new Form_Element_Button('add_organizer', array('label' => 'Добавить'), array('class' => 'button button-modal') ); $this->add_component($button); // ----- datetime $element = new Form_Element_DateTimeSimple('datetime', array('label' => 'Дата проведения', 'required' => TRUE),array('class' => 'w300px','placeholder' => 'dd-mm-yyyy hh:mm')); $element->value_format = Model_Product::$date_as_timestamp ? 'timestamp' : 'datetime'; $element ->add_validator(new Form_Validator_DateTimeSimple()); $this->add_component($element); // ----- Duration $options = Model_Product::$_duration_options; $element = new Form_Element_Select('duration', $options, array('label' => 'Длительность'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ------------------------------------------------------------------------------------- // place // ------------------------------------------------------------------------------------- // control hidden field $control_element = new Form_Element_Hidden('place_id',array('id' => 'place_id')); $this->add_component($control_element); if ($control_element->value !== FALSE) { $place_id = (int) $control_element->value; } else { $place_id = (int) $this->model()->lecturer_id; } // ----- place_name // input field with autocomplete ajax $element = new Form_Element_Input('place_name', array('label' => 'Площадка', 'layout' => 'wide','id' => 'place_name')); $element->autocomplete_url = URL::to('frontend/area/places', array('action' => 'ac_place_name')); Layout::instance()->add_style(Modules::uri('area') . '/public/css/frontend/area.css'); $this->add_component($element); $place = new Model_Place(); $place->find($place_id); $place_name = ($place->id !== NULL) ? $place->name : ''; if ($element->value === FALSE) { $element->value = $place_name; } else { if ($element->value !== $place_name) $control_element->set_value(NULL); } /* $places = Model::fly('Model_Place')->find_all_by_town_id(Model_User::current()->town->id); $places_arr = array(); foreach ($places as $place) { $places_arr[$place->id] = $place->name; } $element = new Form_Element_Select('place_id', $places_arr, array('label' => 'Площадка','required' => TRUE), array('placeholder' => 'Выберите площадку') ); $this->add_component($element); */ // ----- theme $options = Model_Product::$_theme_options; $element = new Form_Element_Select('theme', $options, array('label' => 'Тема'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- format $options = Model_Product::$_format_options; $element = new Form_Element_Select('format', $options, array('label' => 'Формат'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- tags $element = new Form_Element_Input('tags', array('label' => 'Теги','id' => 'tag'), array('maxlength' => 255)); $element->autocomplete_url = URL::to('frontend/tags', array('action' => 'ac_tag')); $element->autocomplete_chunk = Model_Tag::TAGS_DELIMITER; $element ->add_filter(new Form_Filter_TrimCrop(255)); $this->add_component($element); // ----- Description $element = new Form_Element_Wysiwyg('description', array('label' => 'О событии')); $element ->add_validator(new Form_Validator_NotEmptyString(array(Form_Validator_NotEmptyString::EMPTY_STRING => 'Добавьте информацию о событии'))); $this->add_component($element); // ----- Product images // if ($this->model()->id !== NULL) // { // $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); // $element->value = Request::current()->get_controller('images')->widget_images('product', $this->model()->id, 'product'); // $this->add_component($element, 2); // } // ----- File $element = new Form_Element_File('file', array('label' => 'Загрузить фото'),array('placeholder' => 'Загрузить фото')); $element->add_validator(new Form_Validator_File(NULL,TRUE,TRUE)); $this->add_component($element); if ($this->model()->id !== NULL) { $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('images')->widget_image('product', $this->model()->id, 'product'); $this->add_component($element); } // Hidden element for product images for parser $element = new Form_Element_Hidden('image_url',array('id' => 'image_url')); $this->add_component($element); // ----- interact $options = Model_Product::$_interact_options; $element = new Form_Element_RadioSelect('interact', $options, array('label' => 'Интерактивность','required' => TRUE),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $element->set_disabled(true); $element->config_entry = 'checkselect_spec'; $this->add_component($element); // ----- Price $element = new Form_Element_Money('price', array('label' => 'Стоимость лицензии')); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Float(0, NULL)); $this->add_component($element); // ----- numviews $options = Model_Product::$_numviews_options; $element = new Form_Element_Select('numviews', $options, array('label' => 'Количество телемостов'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- choalg $options = Model_Product::$_choalg_options; $element = new Form_Element_RadioSelect('choalg', $options, array('label' => 'Кто выбирает'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- telemost provider $options = Model_Product::$_telemost_provider_options; $element = new Form_Element_RadioSelect('telemost_provider', $options, array('label' => 'Платформа телемоста'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- Require $this->add_component(new Form_Element_Textarea('require', array('label' => 'Требования к площадке, аудитории и др.'))); // // ----- access // $fieldset = new Form_Fieldset('access', array('label' => 'Кто может подать заявку')); // $cols->add_component($fieldset); // // $element->add_validator(new Form_Validator_InArray(array_keys($places_arr))); // $this->add_component($element); // ----- Form buttons // ----- Form buttons if ($this->model()->id !== NULL) { // Button to select place $button = new Form_Element_LinkButton('cancel_product', array('label' => 'Отменить событие'), array('class' => 'button') ); $button->url = URL::to('frontend/catalog/products/control', array('action' => 'cancel','id' => $this->model()->id), TRUE); $this->add_component($button); $label = 'Сохранить'; } else { $label = 'Добавить'; } $button = new Form_Element_Button('submit_product', array('label' => $label), array('class' => 'button button-red') ); $this->add_component($button); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts Layout::instance()->add_script(Modules::uri('area') . '/public/js/frontend/place_name.js'); Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/lecturer_name.js'); Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/organizer_name.js'); Layout::instance()->add_script(Modules::uri('tags') . '/public/js/backend/tag.js'); Layout::instance()->add_script(Modules::uri('jquery') . '/public/js/jquery.xtsaveform.js'); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/frontend/product-create.js'); } }<file_sep>/modules/shop/acl/classes/form/backend/userprop.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_UserProp extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->layout = 'wide'; // Render using view //$this->view_script = 'backend/forms/property'; $cols = new Form_Fieldset_Columns('userprop'); $this->add_component($cols); // ----- caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()); $cols->add_component($element); // ----- name $element = new Form_Element_Input('name', array('label' => 'Имя', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Alnum()); $element->comment = 'Имя для характеристики, состоящее из цифр и букв латинсокого алфавита для использования в шаблонах. (например: page_numbers, news_creation, ...)'; $cols->add_component($element); // ----- Type $options = $this->model()->get_types(); $element = new Form_Element_RadioSelect('type', $options, array('label' => 'Тип')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- Options $element = new Form_Element_Options("options", array('label' => 'Возможные значения', 'options_count' => 5), array('maxlength' => Model_UserProp::MAXLENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_UserProp::MAXLENGTH)); $cols->add_component($element); // ----- PropSections grid $x_options = array('active' => 'Акт.'); $y_options = array(); $users = Model::fly('Model_User')->find_all_by_active(true); foreach ($users as $user) { $y_options[$user->id] = $user->email; } $element = new Form_Element_CheckGrid('userprops', $x_options, $y_options, array('label' => 'Настройки для пользователей') ); $element->config_entry = 'checkgrid_capt'; $cols->add_component($element, 2); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $cols->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } }<file_sep>/modules/general/comments/classes/kohana/comments.php <?php defined('SYSPATH') or die('No direct script access.'); // как обычно - защита от прямого доступа class Kohana_Comments { // поехали! public static function factory(array $config = array()) // здесь происходит создание объекта { return new Comments($config); // создаем новый объект Comments с нашим конфигом } public function __construct(array $config = array()) // конструктор класса { $this->config = Kohana::$config->load('comments')->as_array(); // заносим в $this->config конфиг из папки с модулем и объединяем его с конфигом пользователя, елси он есть } public function render() // функция рисования комментариев { $view = View::factory('comments/comments')->set('cfg', $this->config); // создаем переменную с нашим видом, в который передаем конфиг return $view->render(); // как результат вызова функции - возвращаем отрендеренный вид } }<file_sep>/modules/shop/catalog/views/backend/goes.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/products/goes', array('action'=>'create', 'telemost_id' => $telemost->id), TRUE); $delete_url = URL::to('backend/products/goes', array('action'=>'delete', 'id' => '${id}'), TRUE); ?> <div class="caption">Пойдут</div> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Добавить участника</a> </div> <div class="images"> <?php foreach ($goes as $go) : $_delete_url = str_replace('${id}', $go->id, $delete_url); ?> <div class="image"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить "Я пойду"', 'controls/delete.gif', 'Удалить'); ?> </div> <div class="img"> Участник: <?php echo $go->user->name?> </div> </div> <?php endforeach; ?> </div> <file_sep>/modules/shop/delivery_courier/classes/model/courierzone/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_CourierZone_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('delivery_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('name', array('Type' => 'varchar(63)')); $this->add_column('price', array('Type' => 'float')); } /** * Move zone up * * @param Model $zone * @param Database_Expression_Where $condition */ public function up(Model $zone, Database_Expression_Where $condition = NULL) { parent::up($zone, DB::where('delivery_id', '=', $zone->delivery_id)); } /** * Move zone down * * @param Model $zone * @param Database_Expression_Where $condition */ public function down(Model $zone, Database_Expression_Where $condition = NULL) { parent::down($zone, DB::where('delivery_id', '=', $zone->delivery_id)); } }<file_sep>/modules/shop/acl/views/frontend/users/links.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (isset($links)) { echo '<div class="soc-link">'; foreach ($links as $link) { $link_name = $link->name; if (!empty($user->$link_name)) { echo '<a href="'.$user->$link_name.'" class="button '.$link->name.'">'.strtolower(substr($link->caption,0,1)).'</a>'; } } echo '</div>'; } ?> <file_sep>/modules/system/tasks/views/backend/task_status.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $log_url = URL::to('backend/tasks', array('action' => 'log', 'task' => $task)); ?> <div class="task_status"> <div class="progress"> <div class="bar" style="width: <?php echo $progress; ?>%"></div> <div class="status"> <?php echo HTML::chars($status); if ($progress > 0) { echo " ($progress %)"; } ?> </div> </div> <?php if (isset($status_info)) { echo '<div class="status_info">' . nl2br(HTML::chars($status_info)) . '</div>'; } ?> <?php if ($log_stats[0] > 0) { $errors_num = $log_stats[Log::ERROR] + $log_stats[Log::FATAL]; $warnings_num = $log_stats[Log::WARNING]; $stats = ''; if ($errors_num || $warnings_num) { $stats .= '( '; } if ($errors_num > 0) { $stats .= '<span class="errors_num">' . $errors_num . ' ' . l10n::plural($errors_num, 'ошибка', 'ошибок', 'ошибки') . '</span>, '; } if ($warnings_num > 0) { $stats .= '<span class="warnings_num">' . $warnings_num . ' ' . l10n::plural($warnings_num, 'предупреждение', 'предупреждений', 'предупреждения') . '</span>, '; } if ($errors_num || $warnings_num) { $stats = trim($stats, ' ,') . ' )'; } echo '<div><a href="' . $log_url . '" target="_blank" class="log_link">' . 'Лог' . ($stats ? ' ' . $stats : '') .' &raquo;' . '</a></div>'; } ?> </div><file_sep>/modules/general/nodes/classes/model/node.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Node extends Model { /** * Current node * @var Model_Node */ protected static $_current_node; /** * Registered node types * @var array */ protected static $_node_types = array(); /** * Add new node type * * @param string $type * @param array $type_info */ public static function add_node_type($type, array $type_info) { self::$_node_types[$type] = $type_info; } /** * Returns list of all registered node types * * @return array */ public static function node_types() { return self::$_node_types; } /** * Get node type information * * @param string $type Type name * @return array */ public static function node_type($type) { if (isset(self::$_node_types[$type])) { return self::$_node_types[$type]; } else { return NULL; } } /** * Load current node using 'node_id' request parameter / sets current node * * @param Model_Node * @return Model_Node */ public static function current(Model_Node $node = NULL) { $site_id = (int) Model_Site::current()->id; if ($node !== NULL) { // Explicitly set current node self::$_current_node = $node; } elseif (self::$_current_node === NULL) { $request = Request::current(); $node_id = $request->param('node_id'); $node = new Model_Node(); if ($node_id != '' && ctype_digit($node_id)) { // Find node by id $node->find_by_id_and_site_id((int) $node_id, $site_id); } elseif ($node_id != '') { // Find node by alias $node->find_by_alias_and_site_id($node_id, $site_id); } else { // Determine node type by current route $route_name = Route::name(Request::current()->route); $route_key = strtolower(APP) . '_route'; $type = NULL; foreach (self::node_types() as $type_name => $type_info) { if ($type_info[$route_key] === $route_name) { $type = $type_name; break; } } if ($type !== NULL) { // Try to find node by node type $node->find_by_type_and_site_id($type, $site_id); } } self::$_current_node = $node; } return self::$_current_node; } /** * Node is active by default * * @return boolean */ public function default_node_active() { return TRUE; } /** * Default site id for node * * @return id */ public function default_site_id() { return Model_Site::current()->id; } /** * Default node layout (basename of file, without ".php") * * @return string */ public function default_layout() { return 'default'; } /** * Finds a parent node id for this node * * @return integer */ public function get_parent_id() { if ( ! isset($this->_properties['parent_id'])) { $parent = $this->mapper()->find_parent($this, array('columns' => array('id'))); $this->_properties['parent_id'] = $parent->id; } return $this->_properties['parent_id']; } /** * Get path to this node * * @return array(id => array(id, caption)) */ public function get_path() { if ( ! isset($this->_properties['path'])) { $path = $this->find_all_parents(array('columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'type'), 'key' => 'id')); $path[$this->id] = $this; $this->_properties['path'] = $path; } return $this->_properties['path']; } /** * Get nodes of the same level * * @return array(id => array(id, caption)) */ public function get_siblings() { if ( ! isset($this->_properties['siblings'])) { $siblings = $this->find_all_siblings(array('columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'type'), 'key' => 'id')); $path[$this->id] = $this; $this->_properties['siblings'] = $siblings; } return $this->_properties['siblings']; } /** * Get frontend URI to this node * * @return string */ public function get_frontend_uri() { $type_info = self::node_type($this->type); if ($type_info === NULL) { throw new Kohana_Exception('Type info for node type ":type" was not found! (May be you have fogotten to register this node type?)', array(':type' => $this->type)); } $url_params = array(); if (isset($type_info['model'])) { if ($this->alias != '') { $url_params['node_id'] = $this->alias; } else { $url_params['node_id'] = $this->id; } } if (isset($type_info['frontend_route_params'])) { $url_params += $type_info['frontend_route_params']; } return URL::uri_to($type_info['frontend_route'], $url_params); } /** * Backend uri to this node contents * * @param boolean $save_history * @return string */ public function get_backend_uri($save_history = FALSE) { $type_info = Model_Node::node_type($this->type); // Generate url params and url to node $url_params = isset($type_info['backend_params']) ? $type_info['backend_params'] : array(); if (isset($type_info['model'])) { $url_params['node_id'] = $this->id; } return URL::uri_to($type_info['backend_route'], $url_params, $save_history); } /** * Full backend url to this node contents * * @param boolean $save_history * @return string */ public function get_backend_url($save_history = FALSE) { return URL::site($this->get_backend_uri($save_history)); } /** * Save node * * @param boolean $force_create */ public function save($force_create = FALSE) { $new_type = $this->new_type; $old_type = $this->type; if ($new_type !== $old_type && $old_type !== NULL) { // Deal with old type $old_type_info = self::node_type($old_type); if (isset($old_type_info['model'])) { // Delete old node model $class = "Model_" . ucfirst($old_type_info['model']); Model::fly($class)->delete_all_by_node_id($this->id); } } // Save node $this->type = $this->new_type; parent::save($force_create); if ($new_type !== $old_type) { // Deal with new type $new_type_info = self::node_type($new_type); if (isset($new_type_info['model'])) { // Create new node model $class = "Model_" . ucfirst($new_type_info['model']); $model = new $class; $model->node_id = $this->id; $model->save(); } } // Recalculate activity $this->mapper()->update_activity(); return $this; } /** * Delete node with all subnodes and corresponding models */ public function delete() { // Selecting subtree $subnodes = $this->find_all_subtree(array('as_array' => TRUE, 'columns' => array('id','type'))); // Adding node itself $subnodes[]= $this->properties(); foreach ($subnodes as $node) { // Deleting all node models $type_info = self::node_type($node['type']); if (isset($type_info['model'])) { // Delete node model $class = "Model_" . ucfirst($type_info['model']); Model::fly($class)->delete_all_by_node_id($node['id']); } } // Deleting node from db with all subnodes $this->mapper()->delete_with_subtree($this); } /** * Validate create and update actions * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { return $this->validate_alias($newvalues); } /** * Validate node alias (must be unique within the current site) * * @param array $newvalues * @return boolean */ public function validate_alias(array $newvalues) { if ( ! isset($newvalues['alias']) || $newvalues['alias'] == '') { // It's allowed no to specify alias for node at all return TRUE; } if ($this->exists_another_by_alias_and_site_id($newvalues['alias'], $this->site_id)) { $this->error('Страница с таким именем в URL уже существует!', 'alias'); return FALSE; } return TRUE; } }<file_sep>/modules/system/forms/classes/form/element/input.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form input element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Input extends Form_Element { /** * Default type of input is "text" * * @return string */ public function default_type() { return 'text'; } /** * Renders input * By default, 'text' type is used * * @return string */ public function render_input() { return Form_Helper::input($this->full_name, $this->value_for_render, $this->attributes()); } public function render_alone_autoload() { return Form_Helper::autoload($this->id); } /** * Get input attributes * * @return array */ public function attributes() { $attributes = parent::attributes(); // Set element type if ( ! isset($attributes['type'])) { $attributes['type'] = $this->type; } // Add HTML class for form element (equal to "type") if (isset($attributes['class'])) { $attributes['class'] .= ' ' . $this->type; } else { $attributes['class'] = $this->type; } return $attributes; } } <file_sep>/modules/shop/orders/classes/model/cartproduct/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_CartProduct_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('cart_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('product_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('marking', array('Type' => 'varchar(127)')); $this->add_column('caption', array('Type' => 'varchar(255)')); $this->add_column('price', array('Type' => 'money')); $this->add_column('quantity', array('Type' => 'int unsigned')); } }<file_sep>/modules/shop/countries/classes/controller/backend/countries.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Countries extends Controller_Backend { /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->caption = 'Страны и регионы'; return $layout; } /** * Import post offices */ public function action_index() { $form = new Form_Backend_ImportPostOffices(); if ($form->is_submitted() && $form->validate()) { $model = Model::fly('Model_PostOffice'); $model->import($form->get_component('file')->value); if ( ! $model->has_errors()) { // Upload was successfull $this->request->redirect($this->request->uri . '?flash=ok'); } else { // Add import errors to form $form->errors($model->errors()); } } if (isset($_GET['flash']) && $_GET['flash'] == 'ok') { } $view = new View('backend/form'); $view->caption = 'Импорт списка объектов почтовой связи'; $view->form = $form; $this->request->response = $this->render_layout($view); } /** * Display autocomplete options for a postcode form field */ public function action_ac_postcode() { $postcode = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $postcode = UTF8::str_ireplace("ё", "е", $postcode); if ($postcode == '') { $this->request->response = ''; return; } $limit = 7; $postoffice = Model::fly('Model_PostOffice'); $postoffices = $postoffice->find_all_like_postcode($postcode, array('limit' => $limit)); if ( ! count($postoffices)) { $this->request->response = ''; return; } $items = array(); foreach ($postoffices as $postoffice) { $caption = $postoffice->postcode; // Add additional info (city, region) $info = UTF8::ucfirst($postoffice->city); if ($postoffice->region_name != '') { $info .= ', ' . UTF8::ucfirst($postoffice->region_name); } $caption .= " ($info)"; $items[] = array( 'caption' => $caption, 'value' => $postoffice->postcode ); } $this->request->response = json_encode($items); } /** * Display autocomplete options for a city form field */ public function action_ac_city() { $city = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $city = UTF8::str_ireplace("ё", "е", $city); if ($city == '') { $this->request->response = ''; return; } $limit = 7; $postoffice = Model::fly('Model_PostOffice'); $postoffices = $postoffice->find_all_like_city($city, array( 'order_by' => 'city', 'desc' => FALSE, 'limit' => $limit )); if ( ! count($postoffices)) { $this->request->response = ''; return; } $items = array(); foreach ($postoffices as $postoffice) { $caption = $postoffice->city; // Highlight found part $caption = str_replace($city, '<strong>' . $city .'</strong>', $caption); // Add additional info (postcode, region) $info = $postoffice->postcode; if ($postoffice->region_name != '') { $info .= ', ' . UTF8::ucfirst($postoffice->region_name); } $caption .= " ($info)"; $items[] = array( 'caption' => $caption, 'value' => UTF8::ucfirst($postoffice->city) ); } $this->request->response = json_encode($items); } } <file_sep>/modules/general/pages/classes/controller/backend/pages.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Pages extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Page'; $this->_form = 'Form_Backend_Page'; return array( 'update' => array( 'view_caption' => 'Редактирование страницы ":caption"' ) ); } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Prepare page model for update action * * @param string|Model $page * @param array $params * @return Model */ protected function _model_update($page, array $params = NULL) { // Find page by given node id $page = new Model_Page(); $page->find_by_node_id((int) $this->request->param('node_id')); if ( ! isset($page->id)) { throw new Controller_BackendCRUD_Exception('Текстовая страница не найдена'); } return $page; } } <file_sep>/modules/general/images/classes/model/image.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Image extends Model { // Maximum allowed number of image size variants const MAX_SIZE_VARIANTS = 4; /** * Return settings for image thumbs * * @return array */ public function get_thumb_settings() { if ($this->config === NULL) { throw new Kohana_Exception('"config" is not defined for image'); } $settings = Kohana::config('images.' . $this->config); if ( ! is_array($settings)) { throw new Kohana_Exception('Config entry ":config" not found for image', array(':config' => $this->config)); } return $settings; } /** * Generate file name for image size variant * * @param integer $i */ public function gen_filename($i, $type = 'jpg') { $rnd = Text::random('numeric', 3); return 'img'.$this->id.'_'.$this->owner_type.$this->owner_id.'_size'.$i.'_'.$rnd.'.'.$type; } /** * Get full path to specified image size variant * * @param integer $i * @return string */ public function image($i = 1) { if (isset($this->_properties["image$i"])) { $folder = DOCROOT . 'public/data'; return $folder . '/' . $this->_properties["image$i"]; } else { return NULL; } } /** * Get uri of the specified image size variant * * @param integer $i * @return string */ public function uri($i = 1) { return 'public/data/' . $this->_properties["image$i"]; } /** * Get uri of the specified image size variant * * @param integer $i * @return string */ public function url($i = 1) { return URL::base(FALSE) . $this->uri($i); } /** * Get the source file to use for creating / updating image * * This property can be specified explicitly: * $image->image_file = '/path/to/some_image.jpg' * * If this property is not specified, than a 'tmp_file' proprtety will be returned */ public function get_source_file() { if (isset($this->_properties['source_file'])) { return $this->_properties['source_file']; } else { return $this->tmp_file; } } /** * Move an uploaded file from PHP temp dir to another temporary directory, were * it can be processed. * * We have to do it because sometimes PHP security settings prohibit operating * on temporary uploaded files directly. */ public function get_tmp_file() { if ( ! isset($this->_properties['tmp_file'])) { if (is_array($this->file)) { $tmp_file = File::upload($this->file); } else { $tmp_file = FALSE; } $this->_properties['tmp_file'] = $tmp_file; } return $this->_properties['tmp_file']; } /** * Save an uploaded image */ public function save($force_create = FALSE) { try { $creating = ( ! isset($this->id) || $force_create); if ( ! isset($this->id)) { // Dummy save for new images to obtain image id parent::save($force_create); } $source_file = $this->source_file; if ( ! empty($source_file)) { // ----- An image was uploaded // Delete previous thumbnails (if any) for ($i = 1; $i <= Model_Image::MAX_SIZE_VARIANTS; $i++) { $path = $this->image($i); if ($path != '') { @unlink($path); } } // Create new thumbnails from uploaded image $img = new Image_GD($source_file); $i = 1; foreach ($this->get_thumb_settings() as $settings) { $thumb = clone $img; $thumb->thumbnail($settings['width'], $settings['height'], (isset($settings['master']) ? $settings['master'] : NULL)); // Generate thumbnail file name $this->__set("image$i", $this->gen_filename($i)); // Save thumbnail to file $thumb->save($this->image($i)); $this->__set("width$i", $thumb->width); $this->__set("height$i", $thumb->height); $i++; } // Save image parent::save(); } } catch (Exception $e) { // Shit happened while saving image if ($creating) { $this->delete(); } if (Kohana::$environment === Kohana::DEVELOPMENT) { throw $e; } else { $this->error($e->getMessage()); } } } /** * Delete all image files for image */ protected function _delete_files(Model_Image $image) { // Delete thumbnails for ($i = 1; $i <= Model_Image::MAX_SIZE_VARIANTS; $i++) { $path = $image->image($i); if ($path != '') { @unlink($path); } } } /** * Delete image */ public function delete() { // Delete image files $this->_delete_files($this); // Delete from DB parent::delete(); } /** * Delete images by owner * * @param string $owner_type * @param integer $owner_id */ public function delete_all_by_owner_type_and_owner_id($owner_type, $owner_id) { // Delete files for all images $images = $this->find_all_by_owner_type_and_owner_id($owner_type, $owner_id); foreach ($images as $image) { $this->_delete_files($image); } // Delete images from DB $this->mapper()->delete_all_by_owner_type_and_owner_id($this, $owner_type, $owner_id); } /** * Model destructor */ public function __destruct() { // Don't forget to delete temporary file, if it exists if ( ! empty($this->_properties['tmp_file'])) { @unlink($this->_properties['tmp_file']); } } }<file_sep>/modules/system/database_eresus/classes/database/expression/where.php <?php defined('SYSPATH') or die('No direct script access.'); /** * "Where" database expression * Can be used as standalone expression (DB::where) * To expressions can be combined together: * $where1 = DB::where('foo', '=', 'bar'); * $where2 = DB::where('la', '=', 'me')->and_where($where1); * * @package Eresus * @author <NAME> (<EMAIL>) */ class Database_Expression_Where { /** * @var array */ protected $_where = array(); /** * Cache compiled statement * @var string */ protected $_compiled_sql; /** * Creates a new "AND WHERE" condition for the query. * * @param mixed column name or array($column, $alias) or object * @param string logic operator * @param mixed column value or object * @return $this */ public function and_where($operand1 = NULL, $operator = NULL, $operand2 = NULL) { if ($operand1 === NULL && $operator === NULL && $operand2 === NULL) { throw new Exception('Empty operands and operators supplied to :function', array(':function' => __FUNCTION__) ); } $this->_where[] = array('AND' => array($operand1, $operator, $operand2)); return $this; } /** * Creates a new "OR WHERE" condition for the query. * * @param mixed column name or array($column, $alias) or object * @param string logic operator * @param mixed column value or object * @return $this */ public function or_where($operand1 = NULL, $operator = NULL, $operand2 = NULL) { if ($operand1 === NULL && $operator === NULL && $operand2 === NULL) { throw new Exception('Empty operands and operators supplied to :function', array(':functioin' => __FUNCTION__) ); } $this->_where[] = array('OR' => array($operand1, $operator, $operand2)); return $this; } /** * Alias of and_where_open() * * @return $this */ public function where_open() { return $this->and_where_open(); } /** * Opens a new "AND WHERE (...)" grouping. * * @return $this */ public function and_where_open() { $this->_where[] = array('AND' => '('); return $this; } /** * Opens a new "OR WHERE (...)" grouping. * * @return $this */ public function or_where_open() { $this->_where[] = array('OR' => '('); return $this; } /** * Closes an open "AND WHERE (...)" grouping. * * @return $this */ public function where_close() { return $this->and_where_close(); } /** * Closes an open "AND WHERE (...)" grouping. * * @return $this */ public function and_where_close() { $this->_where[] = array('AND' => ')'); return $this; } /** * Closes an open "OR WHERE (...)" grouping. * * @return $this */ public function or_where_close() { $this->_where[] = array('OR' => ')'); return $this; } /** * Compiles an array of conditions into an SQL partial. * Used for WHERE and HAVING. * * @param object Database instance * @param array condition statements * @return string */ public function compile(Database $db) { if (isset($this->_compiled_sql)) return $this->_compiled_sql; $last_condition = NULL; $sql = ''; foreach ($this->_where as $group) { // Process groups of conditions foreach ($group as $logic => $condition) { if ($condition === '(') { if ( ! empty($sql) AND $last_condition !== '(') { // Include logic operator $sql .= ' '.$logic.' '; } $sql .= '('; } elseif ($condition === ')') { $sql .= ')'; } else { if ( ! empty($sql) AND $last_condition !== '(') { // Add the logic operator $sql .= ' '.$logic.' '; } // Split the condition list($operand1, $operator, $operand2) = $condition; if ($operand1 !== NULL) { if ($operand1 instanceof Database_Expression_Where) { $sql .= '(' . $operand1->compile($db) . ')'; } else { // operand1 is a column name or Database_Query object or Database_Expression object $sql .= $db->quote_identifier($operand1); } } if ($operator !== NULL) { $sql .= ' ' . strtoupper($operator); } if ($operand2 !== NULL) { if ($operand2 instanceof Database_Expression_Where) { $sql .= ' (' . (string) $operand2 . ')'; } else { // operand2 is a value or Database_Query object or Database_Expression object $sql .= ' ' . $db->quote($operand2); } } } $last_condition = $condition; } } $this->_compiled_sql = $sql; return $sql; } /** * Does this expression actually have any conditions? * * @return boolean */ public function is_empty() { return ! count($this->_where); } public function __toString() { return $this->compile(Database::instance()); } }<file_sep>/modules/shop/delivery_russianpost/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Common ******************************************************************************/ // Register this delivery module Model_Delivery::register(array( 'module' => 'russianpost', 'caption' => 'Доставка почтой России' ));<file_sep>/modules/shop/acl/classes/model/token/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Token_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('type', array('Type' => 'tinyint unsigned', 'Key' => 'INDEX')); $this->add_column('token', array('Type' => 'char(32)')); $this->add_column('expires_at', array('Type' => 'int unsigned', 'Key' => 'INDEX')); // Peform cleanup from time to time if (mt_rand(0, 100) > 80) { $this->cleanup(); } } /** * Delete expired tokens */ public function cleanup() { $this->delete_rows(DB::where('expires_at', '<=', time())); } /** * Finds a NOT EXPIRED token by criteria * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Model */ public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $condition = $this->_prepare_condition($condition); $condition->and_where('expires_at', '>', time()); return parent::find_by($model, $condition, $params, $query); } /** * Save the token and generate unique token string for new tokens * * @return integer */ public function save(Model $token, $force_create = FALSE) { if ( ! isset($token->id)) { // A new token here - generate new unique token string $this->lock(); $loop_prevention = 0; do { $tk = md5(mt_rand() . mt_rand() . mt_rand() . mt_rand()); $loop_prevention++; } while ($this->exists(DB::where('token', '=', $tk)) && $loop_prevention < 100 ); if ($loop_prevention >= 100) { throw new Kohana_Exception('Infinite loop while generate unique token string'); } $token->token = $tk; parent::save($token); $this->unlock(); } else { parent::save($token); } return $token->id; } }<file_sep>/modules/shop/acl/classes/model/link/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Link_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(31)')); $this->add_column('name', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); } /** * Move privilege up * * @param Model $link * @param Database_Expression_Where $condition */ public function up(Model $link, Database_Expression_Where $condition = NULL) { parent::up($link, DB::where('site_id', '=', $link->site_id)); } /** * Move property down * * @param Model $link * @param Database_Expression_Where $condition */ public function down(Model $link, Database_Expression_Where $condition = NULL) { parent::down($link, DB::where('site_id', '=', $link->site_id)); } }<file_sep>/modules/shop/catalog/classes/form/frontend/telemost.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Telemost extends Form_Frontend { /** * Initialize form fields */ public function init() { // Set HTML class $this->view_script = 'frontend/forms/telemost'; $userTownId = Model_User::current()->town->id; $places_arr = array(); if ($userTownId) { $places = Model::fly('Model_Place')->find_all_by_town_id(Model_User::current()->town->id); foreach ($places as $place) { $places_arr[$place->id] = $place->name; } } $element = new Form_Element_Select('place_id', $places_arr, array('label' => 'Площадка','required' => TRUE), array('placeholder' => 'Выберите площадку') ); $element->add_validator(new Form_Validator_InArray(array_keys($places_arr))); $this->add_component($element); // control hidden field $control_element = new Form_Element_Hidden('product_alias'); $control_element->value = $this->model()->alias; $this->add_component($control_element); $button_text = 'Отправить заявку'; if ($this->model()->price->gt(new Money())) { // ----- Сумма $price_elem = new Form_Element_Text('price', array('label' => 'Стоимость лицензии'),array('placeholder' => "Стоимость лицензии")); $price_elem->value = $this->model()->price; $this->add_component($price_elem); // ----- Telephone $phone_elem = new Form_Element_Input('telephone', array('label' => 'Номер телефона пользователя Visa QIWI Wallet'),array('placeholder' => "Номер телефона пользователя Visa QIWI Wallet")); $phone_elem ->add_validator(new Form_Validator_Integer()) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($phone_elem); $button_text = 'Оплатить лицензию'; } // ----- Description $this->add_component(new Form_Element_Textarea('info', array('label' => 'Дополнительная информация'),array('placeholder' => "Дополнтельная информация"))); // ----- Form buttons $button = new Form_Element_Button('submit_request', array('label' => $button_text), array('class' => 'button button-modal') ); $this->add_component($button); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/frontend/telemostplace.js'); } } <file_sep>/modules/shop/acl/classes/model/userprop/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_UserProp_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('name', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(31)')); $this->add_column('type', array('Type' => 'tinyint')); $this->add_column('options', array('Type' => 'array')); $this->add_column('system', array('Type' => 'boolean')); } /** * Find all userprops by given condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { if (is_array($condition) && ! empty($condition['user_id'])) { // Find properties that apply to selected section $columns = $this->_prepare_columns($params); $table = $this->table_name(); $privgr_table = Model_Mapper::factory('Model_UserPropUser_Mapper')->table_name(); $query = DB::select_array($columns) ->from($table) ->join($privgr_table, 'INNER') ->on("$privgr_table.userprop_id", '=', "$table.id") ->on("$privgr_table.user_id", '=', DB::expr((int) ($condition['user_id']))); if (isset($condition['active'])) { $query->and_where("$privgr_table.active", '=', $condition['active']); unset($condition['active']); } unset($condition['user']); } return parent::find_all_by($model, $condition, $params, $query); } /** * Move userprop up * * @param Model $userprop * @param Database_Expression_Where $condition */ public function up(Model $userprop, Database_Expression_Where $condition = NULL) { parent::up($userprop, DB::where('site_id', '=', $userprop->site_id)); } /** * Move property down * * @param Model $userprop * @param Database_Expression_Where $condition */ public function down(Model $userprop, Database_Expression_Where $condition = NULL) { parent::down($userprop, DB::where('site_id', '=', $userprop->site_id)); } }<file_sep>/modules/system/forms/classes/formcomponent.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Basic class for all form components (form itself, elements, fieldsets, ...) * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class FormComponent { /** * Owner of this component(Form, Form_Fieldset, ...) * @var FormComponent */ protected $_owner; /** * Form that this component belongs to * @var Form */ protected $_form; /** * Child components * @var array array(FormComponent) */ protected $_components = array(); /** * Component properties * @var array */ protected $_properties = array(); /** * HTML attributes * @var array */ protected $_attributes = array(); /** * Templates * @var array */ protected $_templates = array(); /** * Proxy errors to this element * @var FormComponent */ protected $_errors_target; /** * Errors, warining & other messages in this component * @var array */ protected $_messages = array(); /** * Component constructor * * @param string $name * @param array $properties Component properties * @param array $attributes Component HTML attributes(such as "class", "maxlength", ...) */ public function __construct($name, array $properties = NULL, array $attributes = NULL) { if ($properties !== NULL) { foreach ($properties as $k => $v) { $this->$k = $v; } } if ($attributes !== NULL) { foreach ($attributes as $k => $v) { $this->attribute($k, $v); } } $this->name = $name; } /** * Initialize the component (originally called from form constructor) */ public function init() { } /** * Initialize child components in post init * (originally called from form constructor) */ public function post_init() { // Initialize child components foreach ($this->_components as $component) { $component->init(); $component->post_init(); } } // ------------------------------------------------------------------------- // Parent-child relations // ------------------------------------------------------------------------- /** * Set/get the owner of this component * * @param FormComponent $owner * @return FormComponent */ public function owner(FormComponent $owner = NULL) { if ($owner !== NULL) { $this->_owner = $owner; } return $this->_owner; } /** * Set/get the form this component belongs to * * @param Form $form * @return Form */ public function form(Form $form = NULL) { if ($this instanceof Form) { // This component is already a form return $this; } if ($form !== NULL) { // Change form for the component itself $this->_form = $form; // and for all child components foreach ($this->get_components() as $component) { $component->form($form); } } return $this->_form; } // ------------------------------------------------------------------------- // Child components // ------------------------------------------------------------------------- /** * Add a child component * * @param FormComponent $component * @return FormComponent */ public function add_component(FormComponent $component) { if (isset($this->_components[$component->name])) { throw new Kohana_Exception('Child component with name ":name" already exists in :component', array(':name' => $component->name, ':component' => get_class($this))); } // Set this as the owner for the new child component $component->owner($this); // Update the form for the new child component and all its sub-components $component->form($this->form()); $this->_components[$component->name] = $component; return $this; } /** * Get child component by name * * @param string $name * @return FormComponent */ public function get_component($name) { if (isset($this->_components[$name])) { return $this->_components[$name]; } else { return NULL; } } /** * Does this component have child component with given name? * * @return boolean */ public function has_component($name) { return isset($this->_components[$name]); } /** * Return array of all direct child components * * @return array array(FormComponent) */ public function get_components() { return $this->_components; } /** * Find a component with given name in this component or any of its children * Returns FALSE if component is not found * * @param string $name * @return FormComponent|FALSE */ public function find_component($name) { if ($this->has_component($name)) { return $this->_components[$name]; } // Search in child components foreach ($this->get_components() as $child) { $component = $child->find_component($name); if ($component !== FALSE) { return $component; } } return FALSE; } // ------------------------------------------------------------------------- // Properties & attributes // ------------------------------------------------------------------------- /** * Component property setter * * @param string $name Name of property to set * @param mixed $value Property value * @return FormComponent */ public function __set($name, $value) { $setter = 'set_' . strtolower($name); if (method_exists($this, $setter)) { $this->$setter($value); } else { $this->_properties[$name] = $value; } return $this; } /** * Component property getter * * @param string $name Name of property to get * @return mixed */ public function __get($name) { $name = strtolower($name); $getter = "get_$name"; $defaulter = "default_$name"; if (method_exists($this, $getter)) { return $this->$getter(); } elseif (isset($this->_properties[$name])) { return $this->_properties[$name]; } elseif (method_exists($this, $defaulter)) { $this->_properties[$name] = $this->$defaulter(); return $this->_properties[$name]; } else { return NULL; } } /** * Check that specified property is set * * @param string $name * @return boolean */ public function __isset($name) { $name = strtolower($name); $getter = "get_$name"; $defaulter = "default_$name"; if (method_exists($this, $getter)) { return ($this->$getter() !== NULL); } elseif (method_exists($this, $defaulter)) { return ($this->$defaulter() !== NULL); } else { return isset($this->_properties[$name]); } } /** * Default value for component id * * @return string */ public function default_id() { // Leave only valid characters for id $name = preg_replace('/[^\w]/i', '_', $this->name); if ($this instanceof Form) { return 'id-' . $name; } else { return 'id-' . $this->form()->name . '-' . $name; } } /** * Get/set HTML attribute value * * @param string $name * @param mixed $value * @return mixed */ public function attribute($name, $value = NULL) { if ($value !== NULL) { $this->_attributes[$name] = $value; } if (isset($this->_attributes[$name])) { return $this->_attributes[$name]; } else { return NULL; } } /** * Get all attributes in array * * @return array */ public function attributes() { $attributes = $this->_attributes; //@FIXME: 'name' is NOT a common HTML attribute for all components $attributes['name'] = $this->name; $attributes['id'] = $this->id; return $attributes; } /** * Components are rendered by default * * @return boolean */ public function default_render() { return TRUE; } // ------------------------------------------------------------------------- // Templates // ------------------------------------------------------------------------- /** * Sets template * * @param string $template * @param string $type * @return Form_Element */ public function set_template($template, $type = 'element') { $this->_templates[$type] = $template; return $this; } /** * Gets template * * @param string $type * @return array */ public function get_template($type = 'element') { if (isset($this->_templates[$type])) { return $this->_templates[$type]; } else { return $this->default_template($type); } } /** * Template set to use for rendering * * @return string */ public function default_template_set() { return $this->form()->template_set; } /** * Get default config entry name for this element * * @return string */ public function default_config_entry() { return strtolower(get_class($this)); } /** * Default value for form element layout * * @return string */ public function default_layout() { return $this->form()->layout; } /** * Default template * * @param string $type * @return array */ public function default_template($type = 'element') { $config_entry = 'form_templates/' . $this->template_set . '/' . $this->config_entry; $template_set = Kohana::config("$config_entry"); if ($template_set === NULL) { throw new Kohana_Exception('Unable to find template set in config ":entry" for element ":name" (:class)', array(':entry' => $config_entry, ':name' => $this->name, ':class' => get_class($this))); } if (empty($template_set)) { throw new Kohana_Exception('Empty template set in config ":entry" for element ":name" (:class)', array(':entry' => $config_entry, ':name' => $this->name, ':class' => get_class($this))); } // Choose appropriate layout $layout = $this->layout; if (isset($template_set[$layout])) { // Specific layout is defined for this element $template_set = $template_set[$layout]; } else { // Use default layout $template_set = $template_set[0]; } if ( ! isset($template_set[$type])) { throw new Kohana_Exception('There is no template ":type" in templates for the element element ":name" (:class)', array(':type' => $type, ':name' => $this->name, ':class' => get_class($this))); } return $template_set[$type]; } // ------------------------------------------------------------------------- // Errors & messages // ------------------------------------------------------------------------- /** * Get/set errors target * * @param object $target * @return FormComponent */ public function errors_target($target = NULL) { if ($target !== NULL) { $this->_errors_target = $target; } return $this->_errors_target; } /** * Add a message (error, warning) to this form component * * @param string $text * @param string $type * @return FormComponent */ public function message($text, $type = FlashMessages::MESSAGE) { $this->_messages[] = array( 'text' => $text, 'type' => $type ); return $this; } /** * Adds an error message to this component (or proxy error to another one) * * @param string $text Error text * @return FormComponent */ public function error($text) { if ($this->_errors_target !== NULL) { $this->_errors_target->error($text); } else { $this->message($text, FlashMessages::ERROR); } return $this; } /** * Get / set all component errors at once * * @param array $errors * @return array */ public function errors(array $errors = NULL) { if ($errors !== NULL) { $this->_messages += $errors; } $errors = array(); foreach ($this->_messages as $message) { if ($message['type'] == FlashMessages::ERROR) { $errors[] = $message; } } return $errors; } /** * Does this component have errors? * * @return boolean */ public function has_errors() { foreach ($this->_messages as $message) { if ($message['type'] == FlashMessages::ERROR) { return TRUE; } } return FALSE; } /** * Does this components or any of its subcomponents have errors? * * @return boolean */ public function contains_errors() { if ($this->has_errors()) { // The component itself has errors return TRUE; } // Check the children for errors foreach ($this->get_components() as $component) { if ($component->contains_errors()) { return TRUE; } } return FALSE; } }<file_sep>/modules/backend/classes/route/backend.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Backend route * * @package Eresus * @author <NAME> (<EMAIL>) */ class Route_Backend extends Route { /** * Does this route match the specified uri? * * @param string $uri * @return array */ public function matches($uri) { // Cut 'admin' prefix from uri if (preg_match('#admin(/(.*))?#', $uri, $matches)) { $uri = isset($matches[2]) ? $matches[2] : ''; } // Cut site id from the beginning of the uri if (Kohana::config('sites.multi') && preg_match('#^site-(\d++)(/(.*))?#', $uri, $matches)) { $site_id = $matches[1]; $uri = isset($matches[3]) ? $matches[3] : ''; $params = parent::matches($uri); // Add site id to params if ($params !== FALSE && ! isset($params['site_id'])) { $params['site_id'] = $site_id; } } else { $params = parent::matches($uri); } // Add 'backend' directory if ($params !== FALSE && ! isset($params['directory'])) { $params['directory'] = 'backend'; } return $params; } /** * Generates a URI for the current route based on the parameters given. * * * @param array URI parameters * @return string * @throws Kohana_Exception * @uses Route::REGEX_Key */ public function uri(array $params = NULL) { // Add 'backend' directory if ($params !== FALSE && ! isset($params['directory'])) { $params['directory'] = 'backend'; } $uri = parent::uri($params); $uri = ltrim($uri, '/'); // Prepend current site id to uri if (Kohana::config('sites.multi')) { if (isset($params['site_id'])) { $site_id = $params['site_id']; } else { $site_id = Model_Site::current()->id; } if ($site_id !== NULL) { $uri = 'site-' . $site_id . '/' . $uri; } } // Prepend "admin" prefix $uri = 'admin/' . $uri; return $uri; } }<file_sep>/modules/shop/acl/classes/form/backend/lecturer.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Lecturer extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class // User is being created or updated? $creating = ((int)$this->model()->id == 0) ? TRUE : FALSE; if ($creating) { $this->attribute('class', 'w400px'); } else { $this->attribute('class', "lb150px"); $this->layout = 'wide'; } // ----- General tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $tab->add_component($cols); // ----- Personal data $fieldset = new Form_Fieldset('personal_data', array('label' => 'Личные данные')); $cols->add_component($fieldset); $cols1 = new Form_Fieldset_Columns('name'); $fieldset->add_component($cols1); // ----- Last_name $element = new Form_Element_Input('last_name', array('label' => 'Фамилия', 'required' => TRUE), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $cols1->add_component($element, 1); // ----- First_name $element = new Form_Element_Input('first_name', array('label' => 'Имя', 'required' => TRUE), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $cols1->add_component($element, 2); // ----- Middle_name $element = new Form_Element_Input('middle_name', array('label' => 'Отчество'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $fieldset->add_component($element); // ----- External Links $options_count = 1; if ($this->model()->id) { $options_count = count($this->model()->links); } $element = new Form_Element_Options("links", array('label' => 'Внешние ссылки', 'options_count' => $options_count,'options_count_param' => 'options_count','option_caption' => 'добавить ссылку'), array('maxlength' => Model_Lecturer::LINKS_LENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Lecturer::LINKS_LENGTH)); $cols->add_component($element); // ----- Userprops if (!$creating) { // ----- User Photo $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('images')->widget_images('lecturer', $this->model()->id, 'user'); $cols->add_component($element, 2); } // ----- Description tab $tab = new Form_Fieldset_Tab('info_tab', array('label' => 'О себе')); $this->add_component($tab); // ----- Description $tab->add_component(new Form_Element_Wysiwyg('info', array('label' => 'О себе'))); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/frontend/classes/controller/frontend/index.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Index extends Controller_Frontend { /** * Render flash messages * * @return string */ public function widget_flashmessages() { $messages = FlashMessages::fetch_all(); $view = new View('frontend/flashmessages'); $view->messages = $messages; return $view->render(); } } <file_sep>/modules/shop/catalog/classes/form/backend/catalog/updatelinks.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Catalog_UpdateLinks extends Form_Backend { /** * Initialize form fields */ public function init() { $this->attribute('class', 'w300px'); // Set HTML class //$this->layout = 'wide'; $element = new Form_Element_Text('text'); $element->value = 'Обновить привязку товаров к разделам' . Widget::render_widget('tasks', 'status', 'updatelinks'); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Обновить'), array('class' => 'button_accept') )); } }<file_sep>/modules/system/forms/config/form_templates/table/fieldset_buttons.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( array( 'fieldset' => '<tr> <td class="input_cell" colspan="2"> <div class="form_buttons">{{elements}}</div> </td> </tr> ', 'element' => '{{element}}' ) );<file_sep>/modules/general/tags/classes/controller/frontend/tags.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Tags extends Controller_Frontend { /** * Display autocomplete options for a postcode form field */ public function action_ac_tag() { $tag = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; if ($tag == '') { $this->request->response = ''; return; } $limit = 7; $tags = Model::fly('Model_Tag')->find_all_like_name($tag,array('limit' => $limit)); if ( ! count($tags)) { $this->request->response = ''; return; } $items = array(); $pattern = new View('backend/tag_ac'); $num = 0; foreach ($tags as $tag) { $name = $tag->name; $pattern->name = $name; $pattern->num = $num; $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name) ); $num++; } $this->request->response = json_encode($items); } }<file_sep>/application/views/layouts/_header_new.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!doctype html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <title><?php echo HTML::chars($view->placeholder('title')); ?></title> <meta http-equiv="keywords" content="<?php echo HTML::chars($view->placeholder('keywords')); ?>" /> <meta http-equiv="description" content="<?php echo HTML::chars($view->placeholder('description')); ?>" /> <?php echo HTML::style(Modules::uri('frontend') . '/public/css/frontend/bootstrap.css'); ?> <?php echo HTML::style(Modules::uri('frontend') . '/public/css/frontend/style.css'); ?> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <?php echo $view->placeholder('styles'); ?> </head> <file_sep>/modules/shop/catalog/classes/form/backend/catimport/pricelist.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_CatImport_Pricelist extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "lb150px w500px"); $this->layout = 'wide'; // ----- supplier $element = new Form_Element_Select('supplier', Model_Product::suppliers(), array('label' => 'Поставщик')); $element->add_validator(new Form_Validator_InArray(array_keys(Model_Product::suppliers()))); $this->add_component($element); // ----- price_factor $element = new Form_Element_Float('price_factor', array('label' => 'Коэффициент для цен')); $element->add_validator(new Form_Validator_Float(0, NULL)); $element->default_value = 1; $this->add_component($element); // ----- file $element = new Form_Element_File('file', array('label' => 'XLS файл прайслиста')); $element->add_validator(new Form_Validator_File()); $this->add_component($element); // ----- task status $element = new Form_Element_Text('task_status'); $element->value = Widget::render_widget('tasks', 'status', 'import_pricelist'); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('start', array('label' => 'Начать'), array('class' => 'button_accept') )); } } <file_sep>/modules/system/tasks/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Common ******************************************************************************/ Route::set('tasks', 'tasks(/<action>(/<task>))', array( 'action' => '\w++', 'task' => '\w++' ) ) ->defaults(array( 'controller' => 'tasks', 'action' => 'execute' )); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/tasks', new Route_Backend( 'tasks(/<action>(/<task>))' . '(/~<history>)' , array( 'action' => '\w++', 'task' => '\w++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'tasks', 'action' => 'ajax_status', 'task' => NULL, )); }<file_sep>/modules/general/calendar/classes/base/calendar.php <?php /** * Класс Calendar предназначен для генерации HTML кода календаря. Умеет * делать календарь для отдельно взятого месяца или для года, создавать * гиперссылки и хинты для заданных дат, имеет многоязыковую поддержку * (на данный момент - русский и английский язык) и возможность в гибкой * настроки стилевого оформления с помощью внешних CSS. * В классе используются только стандартные функции PHP4, никакие внешние * библиотеки для его работы не требуются. * * @author <NAME> <<EMAIL>> * @version 0.0.1 * @link http://paradigm.ru/calendar * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @copyright Copyright &copy; 2005, <NAME> */ /* Внутренняя документация выполнена в соответствии со стандартом phpDocumentor */ /** * Опция отображения календаря. Определяет, отмечать ли воскресенья с помощью * специального CSS класса. */ define("CLD_MARKSUN", 1); /** * Опция отображения календаря. Определяет, отмечать ли субботы и воскресенья с * помощью CSS класса. */ define("CLD_MARKSATSUN", 2); /** * Опция отображения календаря. Определяет, считать ли первым днём недели * понедельник или воскресенье. По-умолчанию первым считается воскресенье. */ define("CLD_MONDAYS", 4); /** * Опция отображения календаря. Определяет, использовать ли переносы строки * в генерируемом HTML коде. Необходимо только для отладки. По-умолчанию * переносы выключены. */ define("CLD_BREAKS", 8); class Base_Calendar { /** * Массив с названиями месяцев на разных языках. Используется классом Calendar. * (я знаю про setlocale(), но она не везде работает) * Индексы массива - сокращённые названия языков, используемые в качестве * параметров для конструктора Calendar и метода Calendar::setLang(). * @name $MONTHES * @global $GLOBALS['MONTHES'] * @see Calendar, Calendar::setLang() */ public static $MONTHES = array( 'en' => array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'), 'ru' => array('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь') ); /** * Массив с сокращёнными названиями дней недели на разных языках. * Индексы массива - сокращённые названия языков, используемые в качестве * параметров для конструктора Calendar и метода Calendar::setLang(). * Последовательность дней недели должна соответствовать значениям date('w') * (0 сообтветствует воскресенью, 1 - понедельнику и т.д.) * @name $DOWS * @global $GLOBALS['DOWS'] * @see Calendar, Calendar::setLang() */ public static $DOWS = array( 'en' => array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'), 'ru' => array('Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб') ); /** * Шаблон генерации ссылок для всех дат. * @var string * @access private */ var $patternLink = NULL; /** * Ключ замены по шаблону * @var string * @access private */ var $patternSearch = NULL; /** * Массив для хранения ссылок, ассоциированных с датами. * @var array * @see addUDateLink(), addDateLink(), removeUDateLink(), * removeDateLink(), removeDateLinks() * @access private */ var $dateLinks = array(); /** * Массив для хранения хинтов, ассоциированных с датами. * @var array * @see addUDateTitle(), addDateTitle(), removeUDateTitle(), * removeDateTitle(), removeDateTitles() * @access private */ var $dateTitles = array(); /** * Язык, на котором будут отображаться названия месяцев и дней недели * в календаре. Значение переменной должно соответствовать одному * из индексов в массивах $MONTHES и $DOWS. * @var string * @see setLang() * @access private */ var $lng = false; /** * Префикс, используемый для имён всех CSS классов * @var string * @see setCssPrefix() * @access private */ var $cssPrefix; /** * Опции отображения календаря. Значение переменной задаётся с помощью * констант CLD_*, перечислямых через двоичное OR. * @var int * @see setOptions() * @access private */ var $options = false; /** * Конструктор * @access public * @param string $_lng Язык, на котором будут выводиться названия дней * недели и месяцев. После создания объекта он может быть переопределён * с помощью метода setLang(). * @param int $_options Параметры календаря, задаваемые через двоичное OR * (см. константы CLD_*). После создания объекта, опции можно * переопределять методом setOptions(). * @param int $_cssPrefix Префикс, используемый для имён всех CSS классов. * После создания объекта он может быть переопределён с помощью метода * setCssPrefix(). * @see setLang(), setOptions(), setCssPrefix() */ function __construct($_lng = 'en', $_options = false, $_cssPrefix = 'cld_') { if(!isset(self::$DOWS[$_lng])) { trigger_error("Undefined language was specified.", E_USER_WARNING); return false; } $this->dows = self::$DOWS[$_lng]; $this->setLang($_lng); $this->setOptions($_options); $this->setCssPrefix($_cssPrefix); } /** * Задаёт язык отображения названий дней недели и месяцев в календаре. * @param string $_lng Код языка. Указанное значение должно соответствовать * индексам в глобальных массивах $DOWS и $MONTHES. По-умолчанию * используется английский. * @return bool В зависимости от того, корректный ли задан код языка, метод * возвращает true или false. */ function setLang($_lng) { if(isset(self::$MONTHES[$_lng]) && isset(self::$DOWS[$_lng])) { $this->lng = $_lng; return true; } else { trigger_error("Calendar language not defined: '".$_lng."'", E_USER_WARNING); return false; } } /** * Задаёт параметры календаря, перечисляемые через двоичное OR * (см. константы CLD_*). * @param string $_options Параметры, заданные через двоичное OR. * @return void * @example $clndr->setOptions(CLD_MONDAYS | CLD_MARKSATSUN) */ function setOptions($_options) { $this->options = $_options; } /** * Задаёт префикс, используемый для имён всех CSS классов. С помощью * этого метода, можно изменять стилевое оформление календаря в рантайме. * @param string $_cssPrefix Строковое значение, с которого начинаются все * CSS классы. * @return void */ function setCssPrefix($_cssPrefix) { $this->cssPrefix = $_cssPrefix; } /** * Добавляет гиперссылку для заданной даты. Если ссылка была уже задана, * она будет переопределена. * @access public * @param int $_date Дата в формате Unix timestamp, к которой будет * привязана ссылка. Можно задавать "неточную" дату - значение часов, минут * и секунд игнорируется. * @param string $_url Ссылка * @return void * @see addDateLink(), removeUDateLink(), removeDateLink(), * removeDateLinks() */ function addUDateLink($_date, $_url) { $d = getdate($_date); $d = mktime(0, 0, 0, $d["mon"], $d["mday"], $d["year"]); $this->dateLinks[$d] = $_url; } /** * Добавляет гиперссылку для заданной даты. Отличается от addUDateLink * только форматом, в котором определяется дата. Если ссылка была уже * задана, она будет переопределена. * @access public * @param int $_day Число * @param int $_month Месяц * @param int $_year Год * @param string $_url Ссылка * @see addUDateLink(), removeUDateLink(), removeDateLink(), * removeDateLinks() */ function addDateLink($_day, $_month, $_year, $_url) { $this->addUDateLink(mktime(0, 0, 0, $_month, $_day, $_year), $_url); return true; } /** * Добавляет гиперссылку для всех дат по стандартному шаблону. * Все предыдущие ссылки переопределяются * @access public * @param string $_url Ссылка * @see addDateLink(), removeUDateLink(), removeDateLink(), * removeDateLinks() */ function addDateLinks($_url,$search) { $this->patternLink = $_url; $this->patternSearch = $search; return true; } /** * Удаляет ссылку для заданной даты (если она определена). * @access public * @param int $_date Дата, для которой необходимо удалить ссылку (имеет * значение год, месяц и день) * @see addUDateLink(), addDateLink(), removeDateLink(), removeDateLinks() * @return void */ function removeUDateLink($_date) { $d = gethate($_date); $d = mktime(0, 0, 0, $d["mon"], $d["mday"], $d["year"]); unset($this->dateLinks[$d]); } /** * Удаляет ссылку для заданной даты (если она определена). Отличается * от removeUDateLink только форматом, в котором определяется дата. * @access public * @param int $_day Число * @param int $_month Месяц * @param int $_year Год * @see addUDateLink(), addDateLink(), removeUDateLink(), removeDateLinks() * @return void */ function removeDateLink($_day, $_month, $_year) { $this->removeUDateLink(mktime(0, 0, 0, $_month, $_day, $_year)); } /** * Удаляет все определённые ссылки. * @access public * @see addUDateLink(), addDateLink(), removeUDateLink(), removeDateLink() * @return void */ function removeDateLinks() { $this->dateLinks = array(); } /** * Добавляет хинт для заданной даты. Если хинт был уже задан, он будет * переопределен. * @access public * @param int $_date Дата в формате Unix timestamp, к которой будет * привязан хинт. Можно задавать "неточную" дату, значение часов, минут * и секунд игнорируется. * @param string $_title Текст хинта * @return void */ function addUDateTitle($_date, $_title) { $d = getdate($_date); $d = mktime(0, 0, 0, $d["mon"], $d["mday"], $d["year"]); $this->dateTitles[$d] = $_title; } /** * Добавляет хинт для заданной даты. Отличается от addUDateTitle только * форматом, в котором определяется дата. * @access public * @param int $_day Число * @param int $_month Месяц * @param int $_year Год * @param string $_title Текст хинта * @return void */ function addDateTitle($_day, $_month, $_year, $_title) { $this->addUDateTitle(mktime(0, 0, 0, $_month, $_day, $_year), $_title); } /** * Удаляет хинт для заданной даты (если он определен). * @access public * @param int $_date Дата, для которой необходимо удалить ссылку * (имеет значение год, месяц и день) * @return void */ function removeUDateTitle($_date) { $d = getdate($_date); $d = mktime(0, 0, 0, $d["mon"], $d["mday"], $d["year"]); unset($this->dateTitles[$d]); } /** * Удаляет хинт для заданной даты (если он определен). Отличается * от removeUDateTitle только форматом, в котором определяется дата. * @access public * @param int $_day Число * @param int $_month Месяц * @param int $_year Год * @return void */ function removeDateTitle($_day, $_month, $_year) { $this->removeUDateTitle(mktime(0, 0, 0, $_month, $_day, $_year)); } /** * Удаляет все определённые хинты. * @access public * @return void */ function removeDateTitles() { $this->dateTitles = array(); } /** * Генерирует HTML код для заданного месяца. Дата задаётся в формате Unix * tiestamp. * @access public * @param int $_date Месяц, для которого необходимо сгенерировать * календарь, задаваемый формате Unix timestamp (значение года, само собой, * тоже имеет значение; часы, минуты и секунды - игнорируются) * @param bool $_mark Флаг, определяющий необходимость выделить текущую * дату. По-умолчанию, текущая дата не выделяется. * @return string Сгенерированный HTML код */ function genUMonth($_date, $_mark = false) { $d = getdate($_date); $month = $d["mon"]; $day = $d["mday"]; $year = $d["year"]; $wDay = date('w', mktime(0, 0, 0, $month, 1, $year)); $res[] = '<table border="0" cellspacing="0" cellpadding="0" class="'. $this->cssPrefix.'month">'; $monthes = (isset(self::$MONTHES[$this->lng]))? self::$MONTHES[$this->lng]:date('F', $_date); $dows = self::$DOWS[$this->lng]; // строка-заголовок с названием месяца $res[] = '<tr><th colspan="7" class="'.$this->cssPrefix.'montitle">'. $monthes[$month - 1].'</th></tr>'; // опции отображения календаря $mondayIsFirst = ($this->options & CLD_MONDAYS); $markSat = ($this->options & CLD_MARKSATSUN); $markSun = ($this->options & CLD_MARKSUN) || ($this->options & CLD_MARKSATSUN); if($mondayIsFirst) { $sunday = array_shift($dows); array_push($dows, $sunday); $wDay = $wDay?($wDay - 1):6; } // строка-заголовок с названиями дней недели $tmp = array(); for($i = 0; $i < 7; $i++) { // опционально выделение суббот и/или воскресенья с помощю // специальных CSS классов $weekEnd = ($mondayIsFirst?(($i == 6) && $markSun) || (($i == 5) && $markSat):(($i == 0) && $markSun) || (($i == 6) && $markSat))?'marked':''; // определяем имя CSS класса для следующей ячейки $cssClass = $this->cssPrefix.(($i % 2)?'light':'dark').$weekEnd; $tmp[] = '<th class="'.$cssClass.'">'.$dows[$i].'</th>'; } // опредляем, нужен ли разделитель для строк HTML кода $s = ($this->options & CLD_BREAKS)?"\n":''; $res[] = '<tr>'.implode($s, $tmp).'</tr>'; // значение понадобиться для вычисления количества пробелов вконце // таблицы $spacesNum = $wDay; // пробелы перед первым числом $tmp = '<tr>'; for($i = 0; $i < $wDay; $i++) { $tmp .= '<td class="'.$this->cssPrefix. (($i % 2)?'light':'dark').'">&nbsp;</td>'; } $res[] = $tmp; // счётчик недель $wcnt = 0; for($i = 1, $striper = $wDay % 2; $i <= date('t', $_date); $i++, $striper = !$striper) { // отмечаем текущий день, если надо $today = $_mark && ($i == $day); // добавляем линки $d = mktime(0, 0, 0, $month, $i, $year); if ($this->patternLink !== NULL) { $this->dateLinks[$d] = str_replace($this->patternSearch, $d, $this->patternLink); } $linkSet = isset($this->dateLinks[$d]); $titleSet = isset($this->dateTitles[$d]); if($linkSet && $titleSet) { $dayCode = '<a href="'.$this->dateLinks[$d]. '" title="'.$this->dateTitles[$d].'" class="'. $this->cssPrefix.'titleddatelink'.'">'.$i.'</a>'; } elseif($linkSet) { $dayCode = '<a href="'.$this->dateLinks[$d]. '" class="'.$this->cssPrefix.'datelink">'.$i.'</a>'; } elseif($titleSet) { $dayCode = '<em title="'.$this->dateTitles[$d]. '" class="'.$this->cssPrefix.'titleddate">'.$i.'</a>'; } else { $dayCode = $i; } // далее $wDay используется в качестве определителя дня недели, // для выделения суббот и воскресений, и переноса строк $wDay = ($wDay + 1) % 7; // определяем, нужно ли отметить субботу и/или воскресенье $weekEnd = (($wDay == 0) && $markSun) || (($wDay == 6) && $markSat)?'marked':''; $cssClass = $this->cssPrefix.($today?'today': (($striper?'light':'dark').$weekEnd)); $res[] = '<td class="'.$cssClass.'">'.$dayCode.'</td>'; if(!$wDay) { $res[] = '</tr><tr>'; $wcnt++; $striper = true; } } // пробелы в конце $spacesNum = (7 - ($spacesNum + $i) % 7) % 7 + 1; $tmp = ''; for($i = 0; $i < $spacesNum; $i++, $striper = !$striper) { $tmp .= '<td class="'.$this->cssPrefix.($striper?'light':'dark'). '">&nbsp;</td>'; } $res[] = $tmp.'</tr>'; // вне зависимости от количества недель в месяце, выравниваем высоту // до 6 строк if($wcnt < 5) { $res[] = '<tr><td class="'.$this->cssPrefix. 'dark">&nbsp;</td><td class="'.$this->cssPrefix. 'light">&nbsp;</td><td class="'.$this->cssPrefix. 'dark">&nbsp;</td><td class="'.$this->cssPrefix. 'light">&nbsp;</td><td class="'.$this->cssPrefix. 'dark">&nbsp;</td><td class="'.$this->cssPrefix. 'light">&nbsp;</td><td class="'.$this->cssPrefix. 'dark">&nbsp;</td></tr>'; } $res[] = '</table>'; return implode($s, $res); } /** * Генерирует HTML код для заданного месяца из заданного года. * @access public * @param mixed $_day Если параметру задать числовое значение, заданная * дата будет выделена. Если задать значение false - выделение выполнено * не будет. * @param int $_month Месяц, для которого необходимо сгенерировать * календарь. * @param int $_year Год, к которому относится заданный в предыдущем * параметре месяц. * @return string Сгенерированный HTML код */ function genMonth($_day, $_month, $_year) { return $this->genUMonth(mktime(0, 0, 0, $_month, is_numeric($_day)?$_day:1, $_year), is_numeric($_day)?true:false); } /** * Генерирует HTML код для заданного года * @access public * @param int $_date Год, для которого необходимо сгенерировать календарь * в формате Unix timestamp (значениа месяца часов, минут и секунд * игнорируются) * @param int $_mark Флаг, определяющий необходимость выделить текущую * дату. По-умолчанию, текущая дата не выделяется. * @param int $_width Количество месяцев, отображемых в один ряд. * По-умолчанию - 3. * @return string Сгенерированный HTML код * @see genYear() */ function genUYear($_date, $_mark = false, $_width = 3) { $year = date('Y', $_date); $mMonth = date('n', $_date); $res[] = '<table border="0" cellspacing="0" cellpadding="10" class="'. $this->cssPrefix.'year">'; $res[] = '<tr><th colspan="'.$_width.'" class="'.$this->cssPrefix. 'yeartitle"><big>'.$year.'</big></th></tr>'; $res[] = '<tr>'; for($i = 1; $i <= 12; $i++) { if($mMonth == $i) { $monthHtml = $this->genUMonth($_date, $_mark); } else { $monthHtml = $this->genUMonth(mktime(0, 0, 0, $i, 1, $year)); } $res[] = '<td valign="top" class="'.$this->cssPrefix. (($i % $_width)?'monthcell':'monthlastcell').'">'.$monthHtml. '</td>'; if(!($i % $_width)) { $res[] = '</tr><tr>'; } } $res[] = $tmp.'</tr>'; $res[] = '</table>'; // опредляем, нужен ли разделитель для строк HTML кода $s = ($this->options & CLD_BREAKS)?"\n":''; return implode($s, $res); } /** * Генерирует HTML код для заданного года. Отличается от genUYear() только * форматом задания даты. * @access public * @param int $_day Число (имеет значение только в том случае, если его * необходимо выделить; в противном случае, можно задать false) * @param int $_month Месяц (имеет значение только в том случае, если * необходимо выделить заданное число; в противном случае, можно задать * false) * @param int $_year Год, для которого необходимо сгенерировать календарь * @param int $_mark Флаг, определяющий необходимость выделить текущую * дату. По-умолчанию, текущая дата не выделяется. * @param int $_width Количество месяцев, отображемых в один ряд. * По-умолчанию - 3. * @return string Сгенерированный HTML код * @see genUYear() */ function genYear($_day, $_month, $_year, $_mark = false, $_width = 3) { return $this->genUYear(mktime(0, 0, 0, is_numeric($_month)?$_month:1, is_numeric($_day)?$_day:1, $_year), $_mark, $_width); } } ?><file_sep>/modules/shop/area/classes/model/place.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Place extends Model { const LINKS_LENGTH = 64; const ISPEED_LOW = 1; const ISPEED_MEDIUM = 2; const ISPEED_HIGH = 3; public static $_ispeed_options = array( self::ISPEED_LOW => '< 400 Kb/s', self::ISPEED_MEDIUM => '400 Kb/s - 800 Kb/s', self::ISPEED_HIGH => '> 800 Kb/s' ); public function image($size = NULL) { $image_info = array(); $image = Model::fly('Model_Image')->find_by_owner_type_and_owner_id('place', $this->id, array( 'order_by' => 'position', 'desc' => FALSE )); if ($size) { $field_image = 'image'.$size; $field_width = 'width'.$size; $field_height = 'height'.$size; $image_info['image'] = $image->$field_image; $image_info['width'] = $image->$field_width; $image_info['height'] = $image->$field_height; } return $image_info; } public function validate_update(array $newvalues = NULL) { return $this->validate_create($newvalues); } public function validate_create(array $newvalues = NULL) { if (Modules::registered('gmaps3')) { if (isset($newvalues['town_id'])) { $town = Model::fly('Model_Town')->find($newvalues['town_id']); $newvalues['address'] = $town->name.' '.$newvalues['address']; } $geoinfo = Gmaps3::instance()->get_from_address($newvalues['address']); $err = 0; if (!$geoinfo) { FlashMessages::add('Площадка не найдена и не будет отображена на карте!',FlashMessages::ERROR); $err = 1; } if (!$err) { if (count($geoinfo->address_components) < 6) { FlashMessages::add('Площадка не найдена и не будет отображена на карте!',FlashMessages::ERROR); $err = 1; } } if (!$err) { if (!isset($geoinfo->geometry->location->lat)) { FlashMessages::add('Площадка не найдена и не будет отображена на карте!',FlashMessages::ERROR); $err = 1; } } if (!$err) { if (!isset($geoinfo->geometry->location->lng)) { FlashMessages::add('Площадка не найдена и не будет отображена на карте!',FlashMessages::ERROR); $err = 1; } } if (!$err) { $this->lat = $geoinfo->geometry->location->lat; $this->lon = $geoinfo->geometry->location->lng; } } if (!$this->validate_email($newvalues)) return FALSE; return TRUE; } /** * Validate place email * * @param array $newvalues * @return boolean */ public function validate_email(array $newvalues) { if (isset($newvalues['email']) && !empty($newvalues['email'])) { if ($this->exists_another_by_email($newvalues['email'])) { $this->error('Организация с таким e-mail уже существует!', 'email'); return FALSE; } } return TRUE; } /** * Make alias for town from it's 'town' field * * @return string */ public function make_alias() { $caption_alias = str_replace(' ', '_', strtolower(l10n::transliterate($this->name))); $caption_alias = preg_replace('/[^a-z0-9_-]/', '', $caption_alias); $i = 0; $loop_prevention = 1000; do { if ($i > 0) { $alias = substr($caption_alias, 0, 30); $alias .= $i; } else { $alias = substr($caption_alias, 0, 31); } $i++; $exists = $this->exists_another_by_alias($alias); } while ($exists && ($loop_prevention-- > 0)); if ($loop_prevention <= 0) throw new Kohana_Exception ('Possible infinite loop in :method', array(':method' => __METHOD__)); return $alias; } public function save($force_create = NULL) { parent::save($force_create); if (is_array($this->file)) { $file_info = $this->file; if (isset($file_info['name'])) { if ($file_info['name'] != '') { // Delete place images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('place', $this->id); $image = new Model_Image(); $image->file = $this->file; $image->owner_type = 'place'; $image->owner_id = $this->id; $image->config = 'place'; $image->save(); } } } } /** * Delete product */ public function delete() { // Delete product images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('place', $this->id); // Delete from DB parent::delete(); } } <file_sep>/modules/shop/catalog/views/backend/productcomments.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/products/comments', array('action'=>'create', 'product_id' => $product->id), TRUE); $update_url = URL::to('backend/products/comments', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/products/comments', array('action'=>'delete', 'id' => '${id}'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Добавить комментарий</a> </div> <table class="productcomments"> <?php foreach ($productcomments as $comment) : $_update_url = str_replace('${id}', $comment->id, $update_url); $_delete_url = str_replace('${id}', $comment->id, $delete_url); ?> <tr> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать заказ', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить заказ', 'controls/delete.gif', 'Удалить'); ?> </td> <td class="productcomment"> <div> <span class="date">[<?php echo date('Y-m-d H:i:s', $comment->created_at); ?>]</span> <?php echo $comment->user_name; ?> <?php if ($comment->notify_client) { echo '<span class="notify_client">с оповещением представителя</span>'; } ?> </div> <div> <?php echo HTML::chars($comment->text); ?> </div> </td> </tr> <?php endforeach; ?> </table><file_sep>/application/config/form_templates/frontend/fieldset_buttons.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( array( 'fieldset' => '<div class="element"> {{elements}} </div> ', 'fieldset_ajax' => '<div class="element"> {{elements}} </div> ', 'element' => '{{element}}' ) );<file_sep>/application/config/datetime.php <?php defined('SYSPATH') or die('No direct script access.'); return array( // Date format used in the application (as accepted by the date() function) 'date_format' => 'd-m-Y', 'db_date_format' => 'Y-m-d', 'date_format_front' => 'j M, D', 'datetime_format' => 'd-m-Y H:i', 'db_datetime_format' => 'Y-m-d H:i:s', 'datetime_format_front' => 'j M Y, H:i', 'time_format' => 'H:i', 'time_format_front' => 'H.i' );<file_sep>/modules/shop/catalog/views/backend/sections/list_ajax.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'backend/sections/list_branch')); // Set up urls $update_url = URL::to('backend/catalog/sections', array('action'=>'update', 'id' => '{{id}}'), TRUE); $delete_url = URL::to('backend/catalog/sections', array('action'=>'delete', 'id' => '{{id}}'), TRUE); $up_url = URL::to('backend/catalog/sections', array('action'=>'up', 'id' => '{{id}}'), TRUE); $down_url = URL::to('backend/catalog/sections', array('action'=>'down', 'id' => '{{id}}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } $toggle_url = URL::to('backend/catalog/sections', array('action' => 'toggle', 'id' => '{{id}}', 'toggle' => '{{toggle}}'), TRUE); ?> <table class="very_light_table"> <?php render_sections_branch( $sections, $parent, $unfolded, $update_url, $delete_url, $up_url, $down_url, $toggle_url, NULL ); ?> </table><file_sep>/modules/shop/acl/config/images.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // Thumbnail sizes for user photo 'user' => array( array('width' => 0, 'height' => 0), array('width' => 303, 'height' => 3030), array('width' => 498, 'height' => 338), array('width' => 50, 'height' => 50) ), // Thumbnail sizes for lecturer photo 'lecturer' => array( array('width' => 0, 'height' => 0), array('width' => 303, 'height' => 303), array('width' => 498, 'height' => 338), array('width' => 50, 'height' => 50) ) );<file_sep>/modules/general/feedback/classes/controller/frontend/feedback.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Feedback extends Controller_Frontend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->caption = 'Обратная связь'; Breadcrumbs::append(array('uri' => $this->request->uri, 'caption' => 'Обратная связь')); return $layout; } /** * Render feedback form */ public function action_index() { $form = new Form_Frontend_Feedback(); if ($form->is_submitted() && $form->validate()) { // Send notifications $this->notify($form); if ( ! Request::$is_ajax) { $this->request->redirect(URL::uri_to('frontend/feedback', array('action' => 'success'))); } else { $this->request->forward('feedback', 'success'); return; } } else { $content = $form->render(); } if ( ! Request::$is_ajax) { $this->request->response = $this->render_layout($content); } else { $request = Widget::switch_context(); $widget = $request->get_controller('feedback') ->widget_popup(); $widget->content = $content; $widget->to_response($this->request); $this->_action_ajax(); } } /** * Display success message after the form is submitted */ public function action_success() { $content = Widget::render_widget('blocks', 'block', 'feed_succ'); if ( ! Request::$is_ajax) { $this->request->response = $this->render_layout($content); } else { $request = Widget::switch_context(); $widget = $request->get_controller('feedback') ->widget_popup(); $widget->content = $content; $widget->to_response($this->request); $this->_action_ajax(); } } /** * Popup widget * * @return Widget */ public function widget_popup() { $widget = new Widget('layouts/popup'); $widget->id = 'popup'; $widget->wrapper = FALSE; // wrapping is done in the view file $widget->context_uri = FALSE; $widget->content = ''; return $widget; } /** * Send e-mail notification about new question * * @param Form $form Feedback form */ public function notify(Form $form) { try { $settings = Model_Site::current()->settings; $email_to = isset($settings['email']['to']) ? $settings['email']['to'] : ''; $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; if ($email_sender != '') { $email_from = array($email_from => $email_sender); } if ($email_to != '') { // Init mailer SwiftMailer::init(); $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); // --- Send message to administrator $message = Swift_Message::newInstance() ->setSubject('Заполнена форма обратной связи на сайте ' . URL::base(FALSE, TRUE)) ->setFrom($email_from) ->setTo($email_to); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate('mail/feedback_admin'); $message->setBody($template->render(array( 'phone' => $form->get_value('phone'), 'name' => $form->get_value('name'), 'comment' => $form->get_value('comment') ))); // Send message $mailer->send($message); } } catch (Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { throw $e; } } } }<file_sep>/modules/system/forms/classes/form/validator/float.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Floating point number validator. * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_Float extends Form_Validator_Regexp { const INVALID = 'INVALID'; const TOO_SMALL = 'TOO_SMALL'; const TOO_BIG = 'TOO_BIG'; protected $_messages = array( self::INVALID => 'Invalid value specified: should be string or integer or float', self::EMPTY_STRING => 'Вы не указали поле ":label!"', self::NOT_MATCH => 'Неверный формат числа', self::TOO_SMALL => 'Некорректное значение!', self::TOO_BIG => 'Некорректное значение!', ); /** * Minimum allowed value * @var integer */ protected $_min; /** * Maximum allowed value * @var integer */ protected $_max; /** * Inclusive or non-inclusive min/max * @var boolean */ protected $_inclusive; /** * Creates float number validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty strings */ public function __construct($min = NULL, $max = NULL, $inclusive = TRUE, array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE) { $this->_min = $min; $this->_max = $max; $this->_inclusive = $inclusive; parent::__construct('/^\s*[+-]?\d+([.,]\d+)?\s*$/', $messages, $breaks_chain, $allow_empty); } /** * Validate * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $value = $this->_value; if (!is_string($value) && !is_int($value) && !is_double($value)) { $this->_error(self::INVALID); return FALSE; } if ( ! parent::_is_valid($context)) { return FALSE; } $value = l10n::string_to_float($value); if ( $this->_min !== NULL && ( $value < $this->_min && $this->_inclusive || $value <= $this->_min && ! $this->_inclusive ) ) { $this->_error(self::TOO_SMALL); return FALSE; } if ( $this->_max !== NULL && ( $value > $this->_max && $this->_inclusive || $value >= $this->_max && ! $this->_inclusive ) ) { $this->_error(self::TOO_BIG); return FALSE; } return TRUE; } /** * Replaces :min and :max * * @param string $error_text * @return string */ protected function _replace_placeholders($error_text) { $error_text = parent::_replace_placeholders($error_text); return str_replace( array(':min', ':max'), array($this->_min, $this->_max), $error_text ); } }<file_sep>/modules/general/faq/classes/controller/frontend/faq.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Faq extends Controller_Frontend { public $per_page = 20; /** * Render the list of questions */ public function action_index() { $site_id = (int) Model_Site::current()->id; $criteria = array( 'site_id' => $site_id, 'answered' => 1, 'active' => 1 ); $count = Model::fly('Model_Question')->count_by($criteria); $pagination = new Pagination($count, $this->per_page); $order_by = $this->request->param('faq_order', 'created_at'); $desc = (bool) $this->request->param('faq_pdesc', '1'); $questions = Model::fly('Model_Question')->find_all_by($criteria, array( 'order_by' => $order_by, 'desc' => $desc, 'limit' => $pagination->limit, 'offset' => $pagination->offset )); // Set up view $view = new View('frontend/faq'); $view->form = $this->widget_form(); $view->questions = $questions; $view->pagination = $pagination->render('pagination'); $this->request->response = $this->render_layout($view->render()); } /** * Render the question */ public function action_question() { $site_id = (int) Model_Site::current()->id; $criteria = array( 'site_id' => $site_id, 'answered' => 1, 'active' => 1 ); $question = new Model_Question(); $crit = $criteria; $crit['id'] = (int) $this->request->param('id'); $question->find_by($crit); if ( ! isset($question->id)) { $this->_action_404('Указанный вопрос не найден'); return; } // Determine the page for the question // and contruct correct url back to the list of questions $order_by = $this->request->param('faq_order', 'created_at'); $desc = (bool) $this->request->param('faq_pdesc', '1'); $offset = $question->offset_by($criteria, array('order_by' => $order_by, 'desc' => $desc)); $page = floor($offset / $this->per_page); $faq_url = URL::to('frontend/faq', array('page' => $page)); // Set up view $view = new View('frontend/question'); $view->form = $this->widget_form(); $view->question = $question; $view->faq_url = $faq_url; $this->request->response = $this->render_layout($view->render()); } /** * Render form to ask a question */ public function widget_form() { // Form to ask question $form = new Form_Frontend_Question(); if ($form->is_submitted() && $form->validate()) { $question = new Model_Question(); $question->values($form->get_values()); $question->save(); $question->notify_admin(); FlashMessages::add('Ваш вопрос успешно отправлен!'); $this->request->redirect($this->request->uri); } $view = new View('frontend/faq_form'); $view->form = $form; return $view->render(); } } <file_sep>/modules/shop/acl/classes/form/backend/login.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Login extends Form_Backend { /** * Initialize form fields */ public function init() { $this->attribute('class', 'wide w300px lb60px'); // ----- Login $element = new Form_Element_Input('email', array('label' => 'E-mail', 'required' => TRUE), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Password $element = new Form_Element_Password('password', array('label' => 'Пароль', 'required' => TRUE), array('maxlength' => 255) ); $element ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_StringLength(0,255)); $this->add_component($element); // ----- Remember $this->add_component(new Form_Element_Checkbox('remember', array('label' => 'Запомнить'))); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Войти'), array('class' => 'button_accept') )); parent::init(); } }<file_sep>/modules/shop/acl/views/frontend/forms/user.php <div class="wrapper main-list"> <?php echo $form->render_form_open();?> <?php if ($form->model()->id) { ?> <p class="title">Редактирование учетной записи</p> <?php }else { ?> <p class="title">Регистрация нового пользователя</p> <?php } ?> <?php echo $form->render_messages(); ?> <h1 class="main-title"><span>Учетная запись</span></h1> <p>Делаете ли вы события от имени организации? Если да, укажите эту организацию, если нет - оставьте это поле пустым.</p> <fieldset class="d-f-org"> <div class="b-input"><label for="">Организация</label><?php echo $form->get_element('organizer_name')->render_input();?></div> <?php echo $form->get_element('organizer_name')->render_alone_autoload();?> <?php echo $form->get_element('organizer_name')->render_alone_errors();?> <?php echo $form->get_element('organizer_id')->render_input();?> </fieldset> <fieldset class="d-f-main"> <div class="b-select"><label for=""><?php echo $form->get_element('first_name')->render_label();?></label><?php echo $form->get_element('first_name')->render_input();?></div> <?php echo $form->get_element('first_name')->render_alone_errors();?> <div class="b-input"><label for=""><?php echo $form->get_element('last_name')->render_label();?></label><?php echo $form->get_element('last_name')->render_input();?></div> <?php echo $form->get_element('last_name')->render_alone_errors();?> <div class="b-input"><label for="i-title"><?php echo $form->get_element('email')->render_label();?></label><?php echo $form->get_element('email')->render_input();?></div> <?php echo $form->get_element('email')->render_alone_errors();?> <?php if ($form->model()->id == NULL) { ?> <div class="b-input"><label for="i-title"><?php echo $form->get_element('password')->render_label();?></label><?php echo $form->get_element('password')->render_input();?></div> <?php echo $form->get_element('password')->render_alone_errors();?> <div class="b-input"><label for="i-title"><?php echo $form->get_element('password2')->render_label();?></label><?php echo $form->get_element('password2')->render_input();?></div> <?php echo $form->get_element('password2')->render_alone_errors();?> <?php } ?> <div class="b-input"><label for="i-title"><?php echo $form->get_element('town_id')->render_label();?></label><?php echo $form->get_element('town_id')->render_input();?></div> <?php echo $form->get_element('town_id')->render_alone_errors();?> <div class="b-input"> <label for="i-title"><?php echo $form->get_element('tags')->render_label();?></label> <?php echo $form->get_element('tags')->render_input();?> <a class="help-pop" href="#" title="" data-placement="right" data-original-title="Интересы нужны для того, чтобы vse.to мог рекомендовать Вам события. Поставьте галочку, если Вы хотите получать анонсы интересных событий на почту.">?</a> </div> <?php echo $form->get_element('tags')->render_alone_autoload();?> <?php echo $form->get_element('tags')->render_alone_errors();?> </fieldset> <fieldset class="d-f-notify"> <div class="b-input"><label for="i-title"><?php echo $form->get_element('notify')->render_label();?></label><?php echo $form->get_element('notify')->render_input();?></div> <?php echo $form->get_element('notify')->render_alone_errors();?> </fieldset> <fieldset class="d-f-about"> <div class="b-txt"><label for=""><?php echo $form->get_element('info')->render_label();?></label><?php echo $form->get_element('info')->render_input();?></div> <?php echo $form->get_element('info')->render_alone_errors();?> </fieldset> <h1 class="main-title"><span>Контакты</span></h1> <fieldset class="d-f-links"> <?php foreach ($form->model()->links as $link) { ?> <div class="b-input <?php echo $link->name;?>" alt="ddd"><?php echo $form->get_element($link->name)->render_input();?></div> <?php echo $form->get_element($link->name)->render_alone_errors();?> <?php } ?> </fieldset> <fieldset class="b-f-image"> <div class="b-input"><?php echo $form->get_element('file')->render_label(); echo $form->get_element('file')->render_input(); ?></div> <?php echo $form->get_element('file')->render_alone_errors();?> <?php if ($form->model()->id) echo $form->get_element('images')->render_input();?> <div id="prev_<?php echo $form->get_element('file')->id?>" class="prev_container"></div> </fieldset> <div class="form-action"> <?php if ($form->model()->id != NULL) { ?> <div class="b-input"><label for="i-title">Введите пароль для подтверждения изменений&nbsp;</label><?php echo $form->get_element('password')->render_input();?></div> <?php echo $form->get_element('password')->render_alone_errors();?> <?php } ?> <?php echo $form->get_element('submit_user')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div><file_sep>/modules/backend/classes/controller/backendres.php <?php defined('SYSPATH') or die('No direct script access.'); abstract class Controller_BackendRES extends Controller_BackendCRUD { protected $_resource_class = 'Model_Resource'; protected $_role_class = 'Model_User'; protected $_resource_id = 'resource_id'; protected $_resource_type = 'resource_type'; protected $_user_id = 'user_id'; protected $_organizer_id = 'organizer_id'; protected $_town_id = 'town_id'; protected $_mode = 'mode'; protected $_access_users = 'access_users'; protected $_access_organizers = 'access_organizers'; protected $_access_towns = 'access_towns'; protected function _prepare_form($action, Model $model, array $params = NULL) { $form = parent::_prepare_form($action, $model, $params); if (in_array($action, array('create','update'))) { // ----- user_id // Store user_id in hidden field $user_id = NULL; $element = new Form_Element_Hidden('user_id'); $form->add_component($element); if ($element->value !== FALSE) { $user_id = (int) $element->value; } // user_id can be changed via url parameter $req_user_id = Request::instance()->param('user_id', NULL); if ($req_user_id !== NULL) { $req_user_id = (int) $req_user_id; if ( ($req_user_id == 0) || ($req_user_id > 0 && Model::fly('Model_User')->exists_by_id($req_user_id)) ) { $user_id = $req_user_id; } } $user_name = ($user_id !== NULL) ? Model::fly('Model_User')->find($user_id)->name : ''; $element = new Form_Element_Input('user_name', array('label' => 'Пользователь', 'disabled' => TRUE, 'layout' => 'wide','required' => TRUE), array('class' => 'w150px') ); $element->value = $user_name; // Button to select user $button = new Form_Element_LinkButton('select_user_button', array('label' => 'Выбрать', 'render' => FALSE), array('class' => 'button_select_user open_window dim600x500') ); $button->url = URL::to('backend/acl', array('action' => 'user_select','group_id' => Model_Group::EDITOR_GROUP_ID), TRUE); $form->add_component($button); $element->append = '&nbsp;&nbsp;' . $button->render(); $fieldset = $form->find_component('user'); if ($fieldset) { $fieldset->add_component($element); } else { $form->add_component($element); } ////////////////////////////////////////////////////////////////// // // Button to select access towns for resource $fieldset = $form->find_component('access'); if (!$fieldset) { return $form; } $element = new Form_Element_Checkbox_Enable('all', array('label' => 'Все редакторы')); $fieldset->add_component($element); $history = URL::uri_to('backend/area/towns', array('action' => 'towns_select'), TRUE); $towns_select_url = URL::to('backend/area/towns', array( 'action' => 'select', 'history' => $history ), TRUE); $button = new Form_Element_LinkButton('select_towns_button', array('label' => 'Выбрать','render' => FALSE), array('class' => 'button_select_towns open_window') ); $button->url = $towns_select_url; $fieldset->add_component($button); $checkbox = new Form_Element_Checkbox_Enable('from_town', array('label' => 'Из городов','layout' => 'wide'),array('visible' => FALSE)); $checkbox->dep_elements = array('select_towns_button'); $fieldset->add_component($checkbox); $checkbox->append = '&nbsp;&nbsp;' . $button->render(); $access_towns_fieldset = new Form_Fieldset('access_towns'); $access_towns_fieldset->config_entry = 'fieldset_inline'; $access_towns_fieldset->layout = 'standart'; $fieldset->add_component($access_towns_fieldset); $towns = Model_Town::towns(); // ----- Access Towns if (Request::current()->param('access_town_ids') != '') { // Are town ids explicitly specified in the uri? $town_ids = explode('_', Request::current()->param('access_town_ids')); } if ($form->is_submitted()) { $access_towns = $form->get_post_data('access_towns'); if ( ! is_array($access_towns)) { $access_towns = array(); } } elseif (isset($town_ids)) { // Section ids are explicitly specified in the uri $access_towns = array(); foreach ($town_ids as $town_id) { if (isset($towns[$town_id])) { $access_towns[$town_id] = 1; } } } else { $access_towns = $model->access_towns; } if ( ! empty($access_towns)) { $checkbox->set_value(1); foreach ($access_towns as $town_id => $selected) { if (isset($towns[$town_id])) { $town = $towns[$town_id]; $element = new Form_Element_Checkbox('access_towns['.$town_id.']', array('label' => $town)); $element->default_value = $selected; $element->layout = 'default'; $access_towns_fieldset->add_component($element); } } } // Button to select access organizers for product $history = URL::uri_to('backend/acl/organizers', array('action' => 'organizers_select'), TRUE); $organizers_select_url = URL::to('backend/acl/organizers', array( 'action' => 'select', 'history' => $history ), TRUE); $button = new Form_Element_LinkButton('select_organizers_button', array('label' => 'Выбрать','render' => FALSE), array('class' => 'button_select_organizers open_window') ); $button->url = $organizers_select_url; $fieldset->add_component($button); $checkbox = new Form_Element_Checkbox_Enable('from_organizer', array('label' => 'Из организаций','layout' => 'wide'),array('visible' => FALSE)); $checkbox->dep_elements = array('select_organizers_button'); $fieldset->add_component($checkbox); $checkbox->append = '&nbsp;&nbsp;' . $button->render(); $access_organizers_fieldset = new Form_Fieldset('access_organizers'); $access_organizers_fieldset->config_entry = 'fieldset_inline'; $access_organizers_fieldset->layout = 'standart'; $fieldset->add_component($access_organizers_fieldset); // Obtain a list of selected sections in the following precedence // 1. From $_POST // 2. From model $organizers = Model_Organizer::organizers(); // ----- Access Organizers if (Request::current()->param('access_organizer_ids') != '') { // Are organizerr ids explicitly specified in the uri? $organizer_ids = explode('_', Request::current()->param('access_organizer_ids')); } if ($form->is_submitted()) { $access_organizers = $form->get_post_data('access_organizers'); if ( ! is_array($access_organizers)) { $access_organizers = array(); } } elseif (isset($organizer_ids)) { // Section ids are explicitly specified in the uri $access_organizers = array(); foreach ($organizer_ids as $organizer_id) { if (isset($organizers[$organizer_id])) { $access_organizers[$organizer_id] = 1; } } } else { $access_organizers = $model->access_organizers; } if ( ! empty($access_organizers)) { $checkbox->set_value(1); foreach ($access_organizers as $organizer_id => $selected) { if (isset($organizers[$organizer_id])) { $organizer = $organizers[$organizer_id]; $element = new Form_Element_Checkbox('access_organizers['.$organizer_id.']', array('label' => $organizer)); $element->default_value = $selected; $element->layout = 'default'; $access_organizers_fieldset->add_component($element); } } } // Button to select access users for product $history = URL::uri_to('backend/acl/users', array('action' => 'users_select'), TRUE); $users_select_url = URL::to('backend/acl/users', array( 'action' => 'select', 'history' => $history ), TRUE); $button = new Form_Element_LinkButton('select_users_button', array('label' => 'Выбрать','render' => FALSE), array('class' => 'button_select_users open_window') ); $button->url = $users_select_url; $fieldset->add_component($button); $checkbox = new Form_Element_Checkbox_Enable('from_user', array('label' => 'Из редакторов','layout' => 'wide'),array('visible' => FALSE)); $checkbox->dep_elements = array('select_users_button'); $fieldset->add_component($checkbox); $checkbox->append = '&nbsp;&nbsp;' . $button->render(); $access_users_fieldset = new Form_Fieldset('access_users'); $access_users_fieldset->config_entry = 'fieldset_inline'; $access_users_fieldset->layout = 'standart'; $fieldset->add_component($access_users_fieldset); // Obtain a list of selected sections in the following precedence // 1. From $_POST // 2. From model // ----- Access Users $users = Model_User::users(Model_Group::EDITOR_GROUP_ID); if (Request::current()->param('access_user_ids') != '') { // Are user ids explicitly specified in the uri? $user_ids = explode('_', Request::current()->param('access_user_ids')); } if ($form->is_submitted()) { $access_users = $form->get_post_data('access_users'); if ( ! is_array($access_users)) { $access_users = array(); } } elseif (isset($user_ids)) { // Section ids are explicitly specified in the uri $access_users = array(); foreach ($user_ids as $user_id) { if (isset($users[$user_id])) { $access_users[$user_id] = 1; } } } else { $access_users = $model->access_users; } if ( ! empty($access_users)) { $checkbox->set_value(1); foreach ($access_users as $user_id => $selected) { if (isset($users[$user_id])) { $user = $users[$user_id]; $element = new Form_Element_Checkbox('access_users['.$user_id.']', array('label' => $user)); $element->default_value = $selected; $element->layout = 'default'; $access_users_fieldset->add_component($element); } } } } return $form; } } <file_sep>/modules/shop/orders/classes/paymentdelivery/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class PaymentDelivery_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('payment_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('delivery_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); } /** * Link payment type to given delivery types * * @param Model_Payment $payment * @param array $delivery_ids */ public function link_payment_to_deliveries(Model_Payment $payment, array $delivery_ids) { $this->delete_rows(DB::where('payment_id', '=', (int) $payment->id)); foreach ($delivery_ids as $delivery_id) { $this->insert(array( 'payment_id' => $payment->id, 'delivery_id' => $delivery_id )); } } /** * Link delivery type to given payment types * * @param Model_Delivery $delivery * @param array $payment_ids */ public function link_delivery_to_payments(Model_Delivery $delivery, array $payment_ids) { $this->delete_rows(DB::where('delivery_id', '=', (int) $delivery->id)); foreach ($payment_ids as $payment_id) { $this->insert(array( 'payment_id' => $payment_id, 'delivery_id' => $delivery->id )); } } }<file_sep>/modules/system/forms/classes/form/validator/alnum.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Alpha-numeric validator. * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_Alnum extends Form_Validator_Regexp { const INVALID = 'INVALID'; protected $_messages = array( self::INVALID => 'Invalid value specified: should be float, string or integer', self::EMPTY_STRING => 'Вы не указали поле ":label!"', self::NOT_MATCH => 'Поле ":label" может содержать только латинские буквы, цифры и символ подчёркивания' ); /** * Creates Alpha-Numeric validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty strings * @param boolean $allow_underscore Allow underscores */ public function __construct(array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE, $allow_underscore = TRUE) { if ($allow_underscore) { $regexp = '/^[a-zA-Z0-9_]+$/'; } else { $regexp = '/^[a-zA-Z0-9]+$/'; $this->_messages[self::NOT_MATCH] = 'Поле ":label" может содержать только латинские буквы и цифры'; } parent::__construct($regexp, $messages, $breaks_chain, $allow_empty); } /** * Validate * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $value = $this->_value; if (!is_string($value) && !is_int($value) && !is_float($value)) { $this->_error(self::INVALID); return false; } return parent::_is_valid($context); } }<file_sep>/modules/shop/catalog/classes/model/property.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Property extends Model { const TYPE_TEXT = 1; // Text property const TYPE_TEXTAREA= 3; // Text area property const TYPE_SELECT = 2; // Property with value from given list of options const MAXLENGTH = 512; const MAX_PROPERTY = 63; // Maximum length for the property value const MAX_TEXTAREA = 512; // Maximum length for the textarea property const MAX_TEXT = 63; // Maximum length for the text property protected static $_types = array( Model_Property::TYPE_TEXT => 'Текст', Model_Property::TYPE_TEXTAREA => 'Параграф', Model_Property::TYPE_SELECT => 'Список опций' ); /** * Get all possible property types * * @return array */ public function get_types() { return self::$_types; } /** * Get text description for the type of the property * * @return string */ public function get_type_text() { return (isset(self::$_types[$this->type]) ? self::$_types[$this->type] : NULL); } /** * Default property type * * @return integer */ public function default_type() { return Model_Property::TYPE_TEXT; } /** * Default property type * * @return integer */ public function default_site_id() { return Model_SIte::current()->id; } /** * Set property variants * * @param array $options */ public function set_options(array $options) { $options = array_values(array_filter($options)); $this->_properties['options'] = $options; } /** * Created properties are non-system * * @return boolean */ public function default_system() { return 0; } /** * Prohibit changing the "system" property * * @param boolean $value */ public function set_system($value) { //Intentionally blank } /** * @param integer $value */ public function set_type($value) { // Do not allow to change type for system properties if ($this->system) return; $this->_properties['type'] = $value; } /** * Get property-section infos * * @return Models */ public function get_propertysections() { if ( ! isset($this->_properties['propertysections'])) { $this->_properties['propertysections'] = Model::fly('Model_PropertySection')->find_all_by_property($this); } return $this->_properties['propertysections']; } /** * Get property-section infos as array for form * * @return array */ public function get_propsections() { if ( ! isset($this->_properties['propsections'])) { $result = array(); foreach ($this->propertysections as $propsection) { $result[$propsection->section_id]['active'] = (int)$propsection->active; $result[$propsection->section_id]['filter'] = (int)$propsection->filter; $result[$propsection->section_id]['sort'] = (int)$propsection->sort; $result[$propsection->section_id]['section_id'] = (int)$propsection->section_id; } $this->_properties['propsections'] = $result; } return $this->_properties['propsections']; } /** * Set property-section link info (usually from form - so we need to add 'section_id' field) * * @param array $propsections */ public function set_propsections(array $propsections) { foreach ($propsections as $section_id => & $propsection) { if ( ! isset($propsection['section_id'])) { $propsection['section_id'] = $section_id; } } $propsections = array_replace($this->propsections, $propsections); $this->_properties['propsections'] = $propsections; } /** * Save property and link it to selected sections * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); // Link property to selected sections Model::fly('Model_PropertySection')->link_property_to_sections($this, $this->propsections); } /** * Delete property */ public function delete() { // Delete all product values for this property Model_Mapper::factory('PropertyValue_Mapper')->delete_all_by_property_id($this, $this->id); // Delete section binding information Model::fly('Model_PropertySection')->delete_all_by_property_id($this->id); // Delete the property $this->mapper()->delete($this); } /** * Validate creation/updation of property * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { // Check that property name is unque if ( ! isset($newvalues['name'])) { $this->error('Вы не указали имя!', 'name'); return FALSE; } if ($this->exists_another_by_name($newvalues['name'])) { $this->error('Свойство с таким именем уже существует!', 'name'); return FALSE; } return TRUE; } /** * Validate property deletion * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->system) { $this->error('Свойство является системным. Его удаление запрещено!'); return FALSE; } return parent::validate_delete($newvalues); } }<file_sep>/application/classes/route.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Routing system. * Differences from Kohana_Route: * 1) Directory is automatically cut out of controller name when uri is constructed * 2) Optional parameters with default values are NOT placed in uri, when uri * is constructed. * 3) add() function to create routes that are instances of custom classes * * @package Eresus * @author <NAME> (<EMAIL>) */ class Route extends Kohana_Route { /** * Adds a named route and returns it. * Just like Route::set(), but allows route to be an instance of class derived from Route * * @param string $name * @param Route $route * @return Route */ public static function add($name, Route $route) { return Route::$_routes[$name] = $route; } /** * Generates a URI for the current route based on the parameters given. * * // Using the "default" route: "users/profile/10" * $route->uri(array( * 'controller' => 'users', * 'action' => 'profile', * 'id' => '10' * )); * * @param array URI parameters * @return string * @throws Kohana_Exception * @uses Route::REGEX_Key */ public function uri(array $params = NULL) { if ($params === NULL) { // Use the default parameters $params = $this->_defaults; } else { // Add the default parameters $params += $this->_defaults; } // Chop the directory prefix off controller if (isset($params['directory']) && $params['directory'] !== '') { $prefix = str_replace(array('\\', '/'), '_', trim($params['directory'], '/')) . '_'; if (stripos($params['controller'], $prefix) === 0) { $params['controller'] = substr($params['controller'], strlen($prefix)); } } // Start with the routed URI $uri = $this->_uri; if (strpos($uri, '<') === FALSE AND strpos($uri, '(') === FALSE) { // This is a static route, no need to replace anything return $uri; } // Process optional parameters and cut out groups with all default values while (preg_match('#\([^()]++\)#', $uri, $match)) { // Search for the matched value $search = $match[0]; // Remove the parenthesis from the match as the replace $replace = substr($match[0], 1, -1); $all_default = TRUE; preg_match_all('#'.Route::REGEX_KEY.'#', $replace, $matches); foreach ($matches[1] as $param) { if ( isset($params[$param]) && ( ! isset($this->_defaults[$param]) || $params[$param] != $this->_defaults[$param]) ) { // There is a parameter with non-default value in group :-( $all_default = FALSE; break; } } if ($all_default) { // If all parameters in optional group are default - cut the group out $uri = str_replace($search, '', $uri); } else { // Leave the group in URI and remove parenthesis $uri = str_replace($search, $replace, $uri); } } // Replace parameters with their values while(preg_match('#'.Route::REGEX_KEY.'#', $uri, $match)) { list($key, $param) = $match; if ( ! isset($params[$param])) { // Ungrouped parameters are required throw new Kohana_Exception('Required route parameter not passed: :param', array(':param' => $param)); } $uri = str_replace($key, $params[$param], $uri); } // Trim all extra slashes from the URI $uri = preg_replace('#//+#', '/', rtrim($uri, '/')); return $uri; } } <file_sep>/modules/shop/payments/classes/model/payment.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Payment extends Model { /** * Registered payment modules * @var array */ protected static $_modules = array(); /** * Register payment module * * @param string $module */ public static function register(array $module_info) { if ( ! isset($module_info['module'])) { throw new Kohana_Exception('Module was not supplied in module_info for :method', array(':method' => __METHOD__)); } self::$_modules[$module_info['module']] = $module_info; } /** * Get module info for the specified module * * @param string $module * @return array */ public static function module_info($module) { if (isset(self::$_modules[$module])) { return self::$_modules[$module]; } else { return NULL; } } /** * Get registered payment modules * * @return array */ public static function modules() { return self::$_modules; } /** * Get payment type caption by id * * @param integer $id */ public static function caption($id) { // Obtain all payments (CACHED!) $payments = Model::fly('Model_Payment')->find_all(array('key' => 'id')); if (isset($payments[$id])) { return $payments[$id]->caption; } else { return NULL; } } /** * All payment models use the same mapper * * @param string $mapper * @return Model_Mapper */ public function mapper($mapper = NULL) { if ($mapper !== NULL || $this->_mapper !== NULL) { return parent::mapper($mapper); } // All payment models uses Model_Payment_Mapper as mapper $this->_mapper = Model_Mapper::factory('Model_Payment_Mapper'); return $this->_mapper; } /** * Determine payment module from model class name * * @return string */ public function default_module() { $class = get_class($this); if (strpos($class, 'Model_Payment_') === 0) { return strtolower(substr($class, strlen('Model_Payment_'))); } else { return NULL; } } /** * Default payment price * * @return Money */ public function default_price() { return new Money(); } /** * Module caption for this payment type * * @return string */ public function get_module_caption() { $module_info = self::module_info($this->module); if (is_array($module_info)) { return (isset($module_info['caption']) ? $module_info['caption'] : $module_info['module']); } else { return NULL; } } /** * Get id of all delivery types that this payment type support */ public function get_delivery_ids() { if ( ! isset($this->_properties['delivery_ids'])) { $delivery_ids = array(); $deliveries = Model::fly('Model_Delivery')->find_all_by_payment($this, array('columns' => array('id'))); foreach ($deliveries as $delivery) { $delivery_ids[$delivery->id] = TRUE; } $this->_properties['delivery_ids'] = $delivery_ids; } return $this->_properties['delivery_ids']; } /** * Save payment type and link it to selected delivery types * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); // Link payment type to the selected delivery types $delivery_ids = array_keys(array_filter($this->delivery_ids)); Model_Mapper::factory('PaymentDelivery_Mapper')->link_payment_to_deliveries($this, $delivery_ids); } /** * Calculate payment price for specified order * * @param Model_Order $order * @return float */ public function calculate_price(Model_Order $order) { return $this->default_price(); } }<file_sep>/modules/general/filemanager/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/filemanager', new Route_Backend( 'filemanager(/<action>)(/path-<fm_path>)' . '(/root-<fm_root>)(/style-<fm_style>)(/tinymce-<fm_tinymce>)' . '(/order-<fm_order>)(/desc-<fm_desc>)' . '(/~<history>)', array( 'action' => '\w++', 'fm_path' => '[0-9a-fA-F]++', //path is encoded by URL::encode() 'fm_root' => '\w++', 'fm_style' => '\w++', 'fm_tinymce' => '[01]', 'fm_order' => '\w++', 'fm_desc' => '\w++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'filemanager', 'action' => 'index', 'fm_path' => '', 'fm_root' => 'files', 'fm_style' => 'list', 'fm_tinymce' => '0', 'fm_order' => 'name', 'fm_desc' => '1' )); // ----- Add backend menu items $parent_id = Model_Backend_Menu::add_item(array( 'menu' => 'sidebar', 'caption' => 'Файловый менеджер', 'route' => 'backend/filemanager', 'icon' => 'filemanager' )); Model_Backend_Menu::add_item(array( 'menu' => 'sidebar', 'parent_id' => $parent_id, 'caption' => 'Файлы пользователя', 'route' => 'backend/filemanager', 'route_params' => array('fm_root' => 'files') )); Model_Backend_Menu::add_item(array( 'menu' => 'sidebar', 'parent_id' => $parent_id, 'caption' => 'Оформление', 'route' => 'backend/filemanager', 'route_params' => array('fm_root' => 'css') )); Model_Backend_Menu::add_item(array( 'menu' => 'sidebar', 'parent_id' => $parent_id, 'caption' => 'Яваскрипты', 'route' => 'backend/filemanager', 'route_params' => array('fm_root' => 'js') )); Model_Backend_Menu::add_item(array( 'menu' => 'sidebar', 'parent_id' => $parent_id, 'caption' => 'Шаблоны', 'route' => 'backend/filemanager', 'route_params' => array('fm_root' => 'templates') )); }<file_sep>/modules/shop/catalog/classes/controller/backend/properties.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Properties extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Property'; $this->_form = 'Form_Backend_Property'; return array( 'create' => array( 'view_caption' => 'Создание характеристики' ), 'update' => array( 'view_caption' => 'Редактирование характеристики ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление характеристики', 'message' => 'Удалить характеристику ":caption"?' ) ); } /** * Create layout (proxy to catalog controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('catalog')->prepare_layout($layout_script); } /** * Render layout (proxy to catalog controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('catalog')->render_layout($content, $layout_script); } /** * Render all available section properties */ public function action_index() { $this->request->response = $this->render_layout($this->widget_properties()); } /** * Handles the selection of additional sections for product */ public function action_sectiongroups_select() { if ( ! empty($_POST['ids']) && is_array($_POST['ids'])) { $sectiongroup_ids = ''; foreach ($_POST['ids'] as $sectiongroup_id) { $sectiongroup_ids .= (int) $sectiongroup_id . '_'; } $sectiongroup_ids = trim($sectiongroup_ids, '_'); $this->request->redirect(URL::uri_back(NULL, 1, array('cat_sectiongroup_ids' => $sectiongroup_ids))); } else { // No sections were selected $this->request->redirect(URL::uri_back()); } } /** * This action is executed via ajax request after additional * sectiongroups for property have been selected. * * It redraws the "additional sectiongroups" form element accordingly */ public function action_ajax_sectiongroups_select() { if ($this->request->param('cat_sectiongroup_ids') != '') { $action = ((int)$this->request->param('id') == 0) ? 'create' : 'update'; $property = $this->_model($action, 'Model_Property'); $form = $this->_form($action, $property); $component = $form->find_component('propsections'); if ($component) { $this->request->response = $component->render(); } } } /** * Create new property * * @return Model_Property */ protected function _model_create($model, array $params = NULL) { if (Model_Site::current()->id === NULL) { throw new Controller_BackendCRUD_Exception('Выберите магазин перед созданием характеристики!'); } // New section for current site $property = new Model_Property(); $property->site_id = (int) Model_Site::current()->id; return $property; } /** * Render list of section properties */ public function widget_properties() { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите магазин!'); } $order_by = $this->request->param('cat_prorder', 'position'); $desc = (bool) $this->request->param('cat_prdesc', '0'); $properties = Model::fly('Model_Property')->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/properties'); $view->order_by = $order_by; $view->desc = $desc; $view->properties = $properties; return $view->render(); } }<file_sep>/modules/shop/catalog/views/frontend/small_app_telemosts.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (!count($telemosts)) return; $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $today_flag= 0; $tomorrow_flag= 0; $nearest_flag = 0; ?> <div class="wrapper main-list"> <div class="ub-title"> <p>Мои заявки</p> </div> <div class="ub-title"> </div> <hr> <?php $i=0; foreach ($telemosts as $telemost): $i++; $product = $telemost->product; $url = URL::site($product->uri_frontend()); if (($today_flag == 0) && $product->datetime->format('d.m.Y') == $today_datetime->format('d.m.Y')) { $today_flag++; } elseif (($tomorrow_flag == 0) && $product->datetime->format('d.m.Y') == $tomorrow_datetime->format('d.m.Y')){ $tomorrow_flag++; } elseif ($nearest_flag == 0) { $nearest_flag++; } $day = $nearest_flag?$product->weekday:($tomorrow_flag?'Завтра':'Сегодня'); ?> <section class="mini"> <div class="row-fluid"> <div class="span5"> <p><span class="date"><a class="day" href=""><?php echo $day?></a>, <?php echo $product->get_datetime_front()?> </span></p> <p class="title"><a href="<?php echo $url ?>"><?php echo $product->caption?></a></p> <p class="place">Плащадка: <?php echo $product->place->town_name?>: <?php echo $product->place->name ?></p> <p class="organizer">Организатор: <?php echo $product->organizer_name?><span></span></p> </div> <div class="span7 desc"> <?php echo $telemost->info; ?> </div> </div> <a href="#" class="link-edit"><i class="icon-pencil icon-white"></i></a> </section> <?php if ($i == count($telemosts)) {?> <hr class='last_hr'> <?php } else { ?> <hr> <?php } ?> <?php endforeach; //foreach ($products as $product) ?> <?php if ($pagination) { echo $pagination; } ?> </div> <file_sep>/modules/general/chat/views/backend/messages.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ( !isset($messages) || ! count($messages)) // No menus return; ?> <?php if (isset($pagination)) { echo $pagination; } ?> <table class="messages table"> <tr class="header"> <?php $columns = array( 'sender_id' => array( 'label' => 'Отправитель', 'sortable' => FALSE ), 'message_preview' => array( 'label' => 'Сообщение', 'sortable' => FALSE ), 'date' => array( 'label' => 'Дата', 'sortable' => FALSE ) ); echo View_Helper_Admin::table_header($columns); ?> </tr> <?php foreach ($messages as $message) : ?> <tr> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'message_preview': echo '<td id="message">'.HTML::chars($message->$field) . '</a></td>'; break; case 'sender_id': $sender = Model::fly('Model_User')->find($message->user_id); echo '<td>'; echo Widget::render_widget('users', 'user_card', $sender); echo '</td>'; break; default: echo '<td>'; if (isset($message->$field) && trim($message->$field) !== '') { echo HTML::chars($message[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> </tr> <?php endforeach; ?> </table> <?php echo $form->render(); ?> <file_sep>/modules/shop/catalog/classes/task/generatealiases.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Regenerate aliases for products and sections */ class Task_GenerateAliases extends Task { /** * Run the task */ public function run() { // ----- Sections $this->set_status_info('Генерация алиасов для разделов'); $section = new Model_Section; $count = $section->count(); $i = 0; $loop_prevention = 1000; do { $sections = $section->find_all(array( 'batch' => 100, 'columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'section_active'), 'as_array' => TRUE )); foreach ($sections as $properties) { // update progress for every 10th section if ($i % 10 == 0) { $this->set_status_info('Генерация алиасов для разделов : ' . $i . ' из ' . $count); $this->set_progress((int) (100 * $i / $count)); } $i++; // alias will be regenerated on save $section->init($properties); // [!!!] @FIXME: save breaks property-section links //$section->save(FALSE, FALSE); } } while (count($sections) && ($loop_prevention-- > 0)); if ($loop_prevention <= 0) throw new Kohana_Exception ('Possible infinite loop in :method', array(':method' => __METHOD__)); // ----- Products $this->set_status_info('Генерация алиасов для товаров'); $product = new Model_Product; $count = $product->count(); $i = 0; $loop_prevention = 1000; do { $products = $product->find_all(array( 'batch' => 100, 'columns' => array('id', 'section_id', 'marking', 'price', 'active'), 'as_array' => TRUE )); foreach ($products as $properties) { // update progress for every 50th product if ($i % 50 == 0) { $this->set_status_info('Генерация алиасов для товаров : ' . $i . ' из ' . $count); $this->set_progress((int) (100 * $i / $count)); } $i++; // alias will be regenerated on save $product->init($properties); $product->save(FALSE, TRUE); } } while (count($products) && ($loop_prevention-- > 0)); if ($loop_prevention <= 0) throw new Kohana_Exception ('Possible infinite loop in :method', array(':method' => __METHOD__)); $this->set_status_info('Генерация завершёна'); } } <file_sep>/modules/shop/sites/classes/controller/backend/sites.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Sites extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Site'; $this->_form = 'Form_Backend_Site'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание сайта' ), 'update' => array( 'view_caption' => 'Редактирование настроек сайта ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление сайта', 'message' => 'Удалить сайт ":caption"?' ) ); } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Index action - renders the list of sites */ public function action_index() { $this->request->response = $this->render_layout($this->widget_sites()); } /** * Prepare site model for updating * * @param Model_Site|string $model * @param array $params * @return Model_Site */ public function _model_update($model, array $params = NULL) { if ( ! Kohana::config('sites.multi')) { return Model_Site::current(); } else { return parent::_model('update', $model, $params); } } /** * Renders list of sites * * @return string */ public function widget_sites() { $site = Model::fly('Model_Site'); $order_by = $this->request->param('sites_order', 'id'); $desc = (bool) $this->request->param('sites_desc', '0'); // Select all products $sites = $site->find_all(); // Set up view $view = new View('backend/sites'); $view->order_by = $order_by; $view->desc = $desc; $view->sites = $sites; return $view->render(); } /** * Site selection menu * * @return string */ public function widget_menu() { $site = Model::fly('Model_Site'); // Select all products $sites = $site->find_all(); // Set up view $view = new View('backend/sites_menu'); $view->sites = $sites; $view->current = Model_Site::current(); return $view->render(); } }<file_sep>/modules/system/forms/config/form_templates/table/submit.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( array( 'element' => '{{input}}' ), 'standalone' => array( 'element' => '<tr> <td class="input_cell" colspan="2"> {{input}} </td> </tr> ' ) );<file_sep>/modules/general/xls_reader/classes/xls.php <?php defined('SYSPATH') or die('No direct script access.'); class XLS { /** * @var Spreadsheet_Excel_Reader */ protected static $_reader; /** * @return Spreadsheet_Excel_Reader */ public static function reader() { if (self::$_reader === NULL) { require_once(Modules::path('xls_reader') . 'lib/excel_reader2.php'); self::$_reader = new Spreadsheet_Excel_Reader(); } return self::$_reader; } }<file_sep>/modules/system/forms/classes/form/element/select.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form select element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Select extends Form_Element { /** * Select options * @var array */ protected $_options = array(); /** * Creates form select element * * @param string $name Element name * @param array $options Select options * @param array $properties Properties * @param array $attributes HTML attrinutes */ public function __construct($name, array $options, array $properties = NULL, array $attributes = NULL) { parent::__construct($name, $properties, $attributes); $this->_options = $options; } /** * Set up options for select * * @param array $options * @return Form_Element_Select */ public function set_options(array $options) { $this->_options = $options; return $this; } /** * Renders select * By default, 'text' type is used * * @return string */ public function render_input() { return Form_Helper::select($this->full_name, $this->_options, $this->value, $this->attributes()); } } <file_sep>/modules/system/database_eresus/classes/db.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Database object creation helper methods. * * Added WHERE expression helper * * @package Eresus * @author <NAME> (<EMAIL>) */ class DB extends Kohana_DB { /** * Create a new WHERE expression * * @return Database_Expression_Where */ public static function where($operand1 = NULL, $operator = NULL, $operand2 = NULL) { $where = new Database_Expression_Where(); if ($operand1 !== NULL || $operator !== NULL || $operand2 !== NULL) { $where->and_where($operand1, $operator, $operand2); } return $where; } } // End DB<file_sep>/modules/shop/delivery_russianpost/classes/model/delivery/russianpost.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Delivery_RussianPost extends Model_Delivery { /** * Get list of all available post types * * @return array */ public static function post_types() { return array( 44 => 'EMS обыкновенный', 45 => 'EMS с объявленной ценностью', 23 => 'Заказная бандероль', 52 => 'Заказная бандероль 1 класса', 12 => 'Заказная карточка', 13 => 'Заказное письмо', 50 => 'Заказное письмо 1 класса', 55 => 'Заказное уведомление', 54 => 'СЕКОГРАММА', 26 => 'Ценная бандероль', 53 => 'Ценная бандероль 1 класса', 36 => 'Ценная посылка', 16 => 'Ценное письмо', 51 => 'Ценное письмо 1 класса' ); } /** * Get list of all available transfer types * * @return array */ public static function post_transfers() { return array( 1 => 'НАЗЕМН.', 2 => 'АВИА', 3 => 'КОМБИН.', 4 => 'УСКОР' ); } /** * Default settings for this delivery type * * @return array */ public function default_settings() { return array( 'viewPost' => 23, 'typePost' => 1 ); } /** * Calculate delivery price * * @param Model_Order $order * @return float */ public function calculate_price(Model_Order $order) { $price = 0.0; if ($order->postcode == '') { $this->error('Не указан индекс!'); return $price; } if ($order->total_weight <= 0) { $this->error('Вес заказа равен 0'); return $price; } //viewPost - вид отправления //typePost - способ пересылки //postOfficeIf - индекс получателя //weight - вес (в граммах) //value1 - Объявленная ценность $url = 'http://www.russianpost.ru/autotarif/Autotarif.aspx' . '?viewPost=' . (int) $this->settings['viewPost'] . '&countryCode=643' // Российская Федерация . '&typePost=' . (int) $this->settings['typePost'] . '&weight=' . (int) $order->total_weight . '&value1=' . round($order->sum->amount) // Объявленная ценость = стоимость заказа (сервис почты России разрешает только круглую сумму, без копеек) . '&postOfficeId=' . urlencode($order->postcode); // Peform an http request to russianpost server $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //timeout in seconds /* curl_setopt($ch, CURLOPT_PROXY, '192.168.20.99'); curl_setopt($ch, CURLOPT_PROXYPORT, '8080'); */ $response = curl_exec($ch); if ( $response === FALSE) { if (Kohana::$environment === Kohana::DEVELOPMENT) { $this->error(curl_error($ch)); } else { $this->error('Произошла ошибка при обращении к серверу почты России'); } return $price; } curl_close($ch); // ------ Parse response // Searh for error text if (preg_match('!<span\s+id="lblErrStr"\s*>([^<>]*)!i', $response, $matches)) { $error = trim($matches[1]); if ($error != '') { $this->error($error); return $price; } } // Parse result if (preg_match('!<span\s+id="TarifValue"\s*>([\d\.,]*)</span>!i', $response, $matches)) { $price = l10n::string_to_float($matches[1]); } else { $this->error('Ошибка при расчёте стоимости доставки'); return $price; } return new Money($price); } }<file_sep>/modules/shop/acl/classes/model/organizer.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Organizer extends Model { const LINKS_LENGTH = 36; const TYPE_BIBLIOTEKA = 1; const TYPE_KNMAGAZIN = 2; const TYPE_СLUB = 3; const TYPE_RESTORAN = 4; const TYPE_INSTITUT = 5; const TYPE_CULCENTER = 6; const TYPE_TVGROUP = 7; const DEFAULT_ORGANIZER_ID = 1; const DEFAULT_ORGANIZER_NAME = 'VSE.TO'; protected static $_types = array( Model_Organizer::TYPE_BIBLIOTEKA => 'библиотека', Model_Organizer::TYPE_KNMAGAZIN => 'книжный магазин', Model_Organizer::TYPE_СLUB => 'клуб', Model_Organizer::TYPE_RESTORAN => 'ресторан', Model_Organizer::TYPE_INSTITUT => 'институт', Model_Organizer::TYPE_CULCENTER => 'культурный центр', Model_Organizer::TYPE_TVGROUP => 'творческая группа' ); static $organizers = NULL; public static function organizers() { if (self::$organizers === NULL) { self::$organizers =array(); $results = Model::fly('Model_Organizer')->find_all(array( 'order_by'=> 'name', 'columns'=>array('id','name'), 'as_array' => TRUE)); foreach ($results as $result) { self::$organizers[$result['id']] = $result['name']; } } return self::$organizers; } public function get_full_name() { return $this->type_name.' '.$this->name; } public function get_full_address() { return $this->town->name.', '.$this->address; } public function get_town() { if ( ! isset($this->_properties['town'])) { $town = new Model_Town(); $town->find((int) $this->town_id); $this->_properties['town'] = $town; } return $this->_properties['town']; } /** * Get all possible types * * @return array */ public function get_types() { return self::$_types; } public function get_type_name() { return self::$_types[$this->type]; } public function image($size = NULL) { $image_info = array(); $image = Model::fly('Model_Image')->find_by_owner_type_and_owner_id('organizer', $this->id, array( 'order_by' => 'position', 'desc' => FALSE )); if ($size) { $field_image = 'image'.$size; $field_width = 'width'.$size; $field_height = 'height'.$size; $image_info['image'] = $image->$field_image; $image_info['width'] = $image->$field_width; $image_info['height'] = $image->$field_height; } return $image_info; } public function save($force_create = FALSE) { parent::save($force_create); if (is_array($this->file)) { $file_info = $this->file; if (isset($file_info['name'])) { if ($file_info['name'] != '') { // Delete organizer images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('organizer', $this->id); $image = new Model_Image(); $image->file = $this->file; $image->owner_type = 'organizer'; $image->owner_id = $this->id; $image->config = 'user'; $image->save(); } } } } public function validate_update(array $newvalues = NULL) { return $this->validate_create($newvalues); } public function validate_create(array $newvalues = NULL) { if (!$this->validate_email($newvalues)) return FALSE; return TRUE; } /** * Validate organizer email * * @param array $newvalues * @return boolean */ public function validate_email(array $newvalues) { if (isset($newvalues['email']) && !empty($newvalues['email'])) { if ($this->exists_another_by_email($newvalues['email'])) { $this->error('Организация с таким e-mail уже существует!', 'email'); return FALSE; } } return TRUE; } /** * Is group valid to be deleted? * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->id == self::DEFAULT_ORGANIZER_ID) { $this->error('Организация является системной. Её удаление запрещено!', 'system'); return FALSE; } return TRUE; } /** * Delete product */ public function delete() { // Delete product images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('organizer', $this->id); // Delete from DB parent::delete(); } } <file_sep>/modules/shop/sites/classes/form/backend/site.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Site extends Form_Backend { /** * Initialize form fields */ public function init() { // HTML class $this->attribute('class', 'w500px'); // ----- General tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); if (Kohana::config('sites.multi')) { // ----- Domain $element = new Form_Element_Input('url', array('label' => 'Адрес', 'required' => TRUE), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $tab->add_component($element); } // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название проекта', 'required' => TRUE), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $tab->add_component($element); // ----- email tab $tab = new Form_Fieldset_Tab('email_tab', array('label' => 'E-Mail оповещения')); $this->add_component($tab); // ----- to $element = new Form_Element_Input('settings[email][to]', array( 'label' => 'E-Mail администратора', 'comment' => 'На этот адрес по умолчанию будут отправляться все административные e-mail оповещения с сайта' ), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)); $tab->add_component($element); // ----- from $element = new Form_Element_Input('settings[email][from]', array( 'label' => 'Адрес отправителя', 'required' => TRUE, 'comment' => 'Этот e-mail адрес будет стоять в поле "От кого" у оповещений, приходящих с сайта клиентам и администратору' ), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $tab->add_component($element); // ----- sender $element = new Form_Element_Input('settings[email][sender]', array( 'label' => 'Имя отправителя', 'comment' => 'Имя отправителя для оповещений, приходящих с сайта клиентам и администратору' ), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)); $tab->add_component($element); // ----- textarea $element = new Form_Element_Textarea('settings[email][signature]', array( 'label' => 'Подпись письма для клиентов', 'comment' => 'Подпись, добавляемая к email оповещениям для клиентов' ) ); $element ->add_filter(new Form_Filter_TrimCrop(511)); $tab->add_component($element); // ----- seo tab $tab = new Form_Fieldset_Tab('seo_tab', array('label' => 'SEO')); $this->add_component($tab); // ----- Title $element = new Form_Element_Textarea('settings[meta_title]', array('label' => 'Метатег title','required' => TRUE), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)) ->add_validator(new Form_Validator_NotEmptyString()); $tab->add_component($element); // ----- Description $element = new Form_Element_Textarea('settings[meta_description]', array('label' => 'Метатег description','required' => TRUE), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)) ->add_validator(new Form_Validator_NotEmptyString()); $tab->add_component($element); // ----- Keywords $element = new Form_Element_Textarea('settings[meta_keywords]', array('label' => 'Метатег keywords','required' => TRUE), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)) ->add_validator(new Form_Validator_NotEmptyString()); $tab->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); if (Kohana::config('sites.multi')) { // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); } // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } } <file_sep>/modules/system/forms/classes/form/element/checkbox.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form input element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Checkbox extends Form_Element_Input { /** * Default type of input is "checkbox" * * @return string */ public function get_type() { return 'checkbox'; } /** * Renders checkbox * * @return string */ public function render_input() { return Form_Helper::hidden($this->full_name, '0') . Form_Helper::checkbox($this->full_name, '1', (bool) $this->value, $this->attributes()); } } <file_sep>/modules/shop/catalog/views/backend/sections/menu.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'backend/sections/menu_branch')); /* // Set up urls $create_url = URL::to('backend/catalog/sections', array( 'action' => 'create', 'cat_section_id' => $section_id, 'cat_sectiongroup_id' => $sectiongroup_id), TRUE); $update_url = URL::to('backend/catalog/sections', array('action'=>'update', 'id' => '{{id}}'), TRUE); $delete_url = URL::to('backend/catalog/sections', array('action'=>'delete', 'id' => '{{id}}'), TRUE); $up_url = URL::to('backend/catalog/sections', array('action'=>'up', 'id' => '{{id}}'), TRUE); $down_url = URL::to('backend/catalog/sections', array('action'=>'down', 'id' => '{{id}}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } * */ $toggle_url = URL::to('backend/catalog/sections', array('action' => 'toggle', 'id' => '{{id}}', 'toggle' => '{{toggle}}'), TRUE); $history = Request::current()->param('history'); if (isset($history)) { $all_url = URL::to('backend/catalog/products', array( 'cat_section_id' => '0', 'cat_sectiongroup_id' => $sectiongroup_id, 'history' => $history), TRUE); //$url = URL::to('backend/catalog/products', array('cat_section_id' => '{{id}}', 'history' => $history), TRUE); } else { $all_url = URL::to('backend/catalog/products', array( 'cat_section_id' => '0', 'cat_sectiongroup_id' => $sectiongroup_id)); //$url = URL::to('backend/catalog/products', array('cat_section_id' => '{{id}}')); } $url = URL::self(array( 'cat_section_id' => '{{id}}', 'search_text' => '', 'active' => '-1' )); ?> <?php // Tabs to select current section group if (isset($sectiongroups)) { //$tab_url = URL::to('backend/catalog/products', array('cat_sectiongroup_id'=>'{{id}}')); $tab_url = URL::self(array('cat_sectiongroup_id' => '{{id}}', 'cat_section_id' => NULL)); echo '<div class="sectiongroup_tabs"><div class="tabs">'; foreach ($sectiongroups as $sectiongroup) { $_tab_url = str_replace('{{id}}', $sectiongroup->id, $tab_url); if ($sectiongroup->id == $sectiongroup_id) { echo '<a href="' . $_tab_url . '" class="selected">' . HTML::chars($sectiongroup->caption) . '</a>'; } else { echo '<a href="' . $_tab_url . '">' . HTML::chars($sectiongroup->caption) . '</a>'; } } echo '</div></div>'; } ?> <!-- <div class="buttons"> <a href="<?php //echo $create_url; ?>" class="button button_section_add">Создать раздел</a> </div> --> <div class="sections_menu tree" id="sections"> <div> <?php // Highlight current section if ($section_id == 0) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo $all_url; ?>" class="<?php echo $selected; ?>" title="Показать все события" > <strong>Все события</strong> </a> </div> <?php render_sections_menu_branch( $sections, NULL, $unfolded, /*$update_url, $delete_url, $up_url, $down_url, */$toggle_url, $url, $section_id ); ?> </div><file_sep>/modules/backend/classes/controller/backendcrud/exception.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Exception that can be thrown during backend CRUD contoller execution */ class Controller_BackendCRUD_Exception extends Kohana_Exception {}<file_sep>/modules/general/flash/classes/model/flashblock.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Flashblock extends Model { const MAXLENGTH = 63; // Maximum length for the property value const FLASH_DIR = 'public/user_data/'; public function get_url() { return URL::site().self::FLASH_DIR.$this->_properties['file']; } /** * Is block visible by default for new nodes? * * @return boolean */ public function default_default_visibility() { return TRUE; } /** * Default site id for block * * @return id */ public function default_site_id() { return Model_Site::current()->id; } /** * Get nodes visibility info for this block * * @return array(node_id => visible) */ public function get_nodes_visibility() { if ( ! isset($this->_properties['nodes_visibility'])) { $result = Model_Mapper::factory('FlashblockNode_Mapper') ->find_all_by_flashblock_id($this, (int) $this->id, array('as_array' => TRUE)); $nodes_visibility = array(); foreach ($result as $visibility) { $nodes_visibility[$visibility['node_id']] = $visibility['visible']; } $this->_properties['nodes_visibility'] = $nodes_visibility; } return $this->_properties['nodes_visibility']; } public function register() { $arr['flashvars'] = $this->flashvars; $arr['params'] = $this->params; $arr['attributes'] = $this->attributes; $arr['name'] = $this->name; $arr['url'] = $this->url; $arr['width'] = $this->width; $arr['height'] = $this->height; $arr['version'] = $this->version; return swfObject::register($arr); } public function validate(array $newvalues) { // Upload file if (isset($newvalues['file'])) { $file_info = $newvalues['file']; } $file_path = Upload::save($file_info,$file_info['name'],self::FLASH_DIR); if (!$file_path) { $this->error('Фаил не может быть загружен!', 'flashblock'); return FALSE; } return true; } /** * Save block properties and block nodes visibility information * * @param boolean $force_create * @return Model_Menu */ public function save($force_create = FALSE) { $this->file = $this->file['name']; parent::save($force_create); // Update nodes visibility info for this menu if ($this->id !== NULL && is_array($this->nodes_visibility)) { Model_Mapper::factory('FlashblockNode_Mapper')->update_nodes_visibility($this, $this->nodes_visibility); } return $this; } } <file_sep>/application/views/layouts/_header.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <title><?php echo HTML::chars($view->placeholder('title')); ?></title> <meta http-equiv="keywords" content="<?php echo HTML::chars($view->placeholder('keywords')); ?>" /> <meta http-equiv="description" content="<?php echo HTML::chars($view->placeholder('description')); ?>" /> <?php echo HTML::style('public/css/default.css'); ?> <?php echo HTML::style('public/css/default_ie6.css', NULL, FALSE, 'if lte IE 6'); ?> <?php echo HTML::style('public/css/int.css'); ?> <?php echo $view->placeholder('styles'); ?> <?php echo $view->placeholder('scripts'); ?> </head> <body> <!-- popup --> <?php echo Widget::render_widget('feedback', 'popup'); ?> <!-- Шапка --> <div id="head"> <div class="out"> <a id="logo" href="<?php echo URL::site(''); ?>" title="Интернет-магазин игрушек Папа Саша"> <?php echo HTML::image('public/css/img/logo.gif', array('alt' => 'Интернет-магазин игрушек Папа Саша', 'border' => '0')); ?> </a> <a id="topban" href="<?php echo URL::site('pages/payment_and_delivery'); ?>" title="Специальные условия доставки"> <?php echo HTML::image('public/css/img/top-banner.gif', array('alt' => 'Специальные условия доставки в Мытищи, Королев, Щелково, Пушкино', 'border' => '0')); ?> </a> <div id="phone"> <?php echo Widget::render_widget('blocks', 'block', 'phones'); ?> Не смогли дозвониться? <strong><a href="<?php echo URL::site('feedback'); ?>" class="orange popup">Оставьте свой телефон</a></strong> </div> <!-- Меню о магазине --> <div id="topmenu"> <ul> <li class="first"><a href="<?php echo URL::site('pages/about'); ?>">О магазине</a></li> <li><a href="<?php echo URL::site('pages/payment_and_delivery'); ?>">Доставка и оплата</a></li> <li><a href="<?php echo URL::site('faq'); ?>">Вопрос-ответ</a></li> <li><a href="<?php echo URL::site('pages/contacts'); ?>">Контакты</a></li> </ul> </div> </div> </div> <!-- Главное меню --> <div id="mainmenu"> <div class="out"> <div class="tl"> <table width="966" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="205"> <a href="<?php echo URL::site('catalog-brand'); ?>"> <?php echo HTML::image('public/css/img/brands.gif', array('class' => 'mm', 'width' => 179, 'height' => 20, 'alt' => 'Игрушки по брендам')); ?> </a> </td> <td width="11"><?php echo HTML::image('public/css/img/mainmenu-sep.gif', array('width' => 11, 'height' => 45)); ?></td> <td width="237"> <a href="<?php echo URL::site('catalog-cat'); ?>"> <?php echo HTML::image('public/css/img/categories.gif', array('class' => 'mm', 'width' => 201, 'height' => 20, 'alt' => 'Игрушки по категориям')); ?> </a> </td> <td width="11"><?php echo HTML::image('public/css/img/mainmenu-sep.gif', array('width' => 11, 'height' => 45)); ?></td> <td width="189"> <a href="#"> <?php echo HTML::image('public/css/img/help.gif', array('class' => 'mm', 'width' => 153, 'height' => 20, 'alt' => 'Помощь в выборе')); ?> </a> </td> <td width="3" style="background-color:#fff;"><div style="width:3px;"></div></td> <td width="299" class="cart"> <?php echo Widget::render_widget('cart', 'summary'); ?> </td> <td width="11" class="cart"><div class="tr"><div class="br"></div></div></td> </tr> </table> </div> </div> </div> <!-- Поиск --> <div id="search"> <div class="out"> <?php echo Widget::render_widget('products', 'search'); ?> <div class="blog"> <a href="#"> <?php echo HTML::image('public/css/img/dot.gif', array('width' => 260, 'height' => 55, 'alt' => 'Игрушечный блог')); ?> </a> </div> </div> </div><file_sep>/application/views/layouts/catalog.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require('_header_new.php'); ?> <body> <header> <div class="mainheader"> <div class="container"> <div class="row"> <div class="span2"> <a href="<?php echo URL::site()?>" class="logo pull-left"></a> </div> <div class="span6"> <?php echo Widget::render_widget('menus','menu', 'main'); ?> </div> <div class="span4"> <div class="b-auth-search"> <?php echo Widget::render_widget('products', 'search');?> </div> </div> </div> </div> </div> <div class="subheader"> <div class="container"> <div class="row"> <div class="span2"> </div> <div class="span6"> </div> <div class="span4"> <div class="login-form"> <?php echo Widget::render_widget('acl', 'login'); ?> </div> </div> </div> </div> </div> </header> <div id="main"> <div class="container"> <div class="row"> <article class="span12" id="event"> <?php echo $view->placeholder('vision'); ?> <div class="wrapper product"> <?php echo $content; ?> </div> </article> </div> </div> </div> <?php require('_footer.php'); ?> <?php echo $view->placeholder('modal'); ?> <script> jQuery(function($){ $('.help-pop').tooltip() }); </script> </body> <file_sep>/modules/frontend/classes/controller/frontendcrud.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Admin controller with basic CRUD functionality * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Controller_FrontendCRUD extends Controller_Frontend { /** * Actions configuration * @var array */ protected $_actions; /** * Default model for actions * @var string */ protected $_model; /** * Default form for actions * @var string */ protected $_form; /** * Default view for actions * @var string */ protected $_view = 'frontend/form'; /** * @param Kohana_Request $request */ public function __construct(Kohana_Request $request) { parent::__construct($request); if ($this->_actions === NULL) { $this->_actions = $this->setup_actions(); } } /** * Setup controller actions * * @return array */ public function setup_actions() { return array(); } // ------------------------------------------------------------------------- // Models // ------------------------------------------------------------------------- /** * Prepare model for action * * @param string $action * @param array $params * @return Model */ protected function _prepare_model($action, array $params = NULL) { $model = isset($params['model']) ? $params['model'] : $this->_model; if ( ! isset($model)) { throw new Kohana_Exception('Model is not defined for action :action in :controller', array(':action' => $action, ':controller' => get_class($this))); } if (method_exists($this, "_$model" . "_$action")) { // Use user-defined method to prepare the model (model-specific) $method = "_$model" . "_$action"; $model = $this->$method($params); } elseif (method_exists($this, "_model_$action")) { // Use user-defined method to prepare the model $method = "_model_$action"; $model = $this->$method($model, $params); } else { $model = $this->_model($action, $model, $params); } return $model; } /** * Default method to prepare the model * Override it to customize model initialization * * @param string $action * @param string|Model $model * @param array $params * @return Model */ protected function _model($action, $model, array $params = NULL) { if ( ! is_object($model)) { // Create model instance $model = new $model; } if ($action != 'create') { // Find model by id for all actions but create // Model id if (isset($params['id'])) { $id = $params['id']; } else { $id_param = isset($params['id_param']) ? $params['id_param'] : 'id'; $id = (int) $this->request->param($id_param); } // Find model by id $model->find($id); if ($model->id === NULL) { // Model was not found $msg = isset($params['msg_not_found']) ? $params['msg_not_found'] : 'Указанный объект не найден'; throw new Controller_FrontendCRUD_Exception($this->_format($msg, $model)); } } return $model; } /** * Prepare models for multi-action * * @param string $action * @param array $params * @return array array(Model) */ protected function _prepare_models($action, array $params = NULL) { $model = isset($params['model']) ? $params['model'] : $this->_model; if ( ! isset($model)) { throw new Kohana_Exception('Model is not defined for action :action in :controller', array(':action' => $action, ':controller' => get_class($this))); } if (method_exists($this, "_$model" . "_$action")) { // Use user-defined method to prepare the model (model-specific) $method = "_$model" . "_$action"; $models = $this->$method($params); } elseif (method_exists($this, "_models_$action")) { // Use user-defined method to prepare the model $method = "_models_$action"; $models = $this->$method($model, $params); } else { $models = $this->_models($action, $model, $params); } return $models; } /** * Default method to prepare the models for multi-action * Override it to customize model initialization * * @param string $action * @param string $model * @param array $params * @return array array(Model) */ protected function _models($action, $model, array $params = NULL) { // Model ids if (isset($params['ids']) && is_array($params['ids'])) { $ids = $params['ids']; } elseif (isset($_POST['ids'])) { if (is_array($_POST['ids'])) { $ids = $_POST['ids']; } else { $ids = explode('_', (string) ($_POST['ids'])); } } else { $ids = $this->request->param('ids', ''); $ids = explode('_', $ids); } $models = array(); foreach ($ids as $id) { $model = new $model; $model->find((int) $id); if (isset($model->id)) { $models[] = $model; } } return $models; } // ------------------------------------------------------------------------- // Forms // ------------------------------------------------------------------------- /** * Prepare form for action. * Override it to customize form initialization * * @param string $action * @param Model $model * @param array $params * @return Form */ protected function _prepare_form($action, Model $model, array $params = NULL) { $method = "_form_$action"; if (method_exists($this, $method)) { // Use user-defined method to prepare the form $form = $this->$method($model, $params); } else { $form = $this->_form($action, $model, $params); } return $form; } /** * Default method to prepare the form * * @param string action * @param Model $model * @param array $params * @return Form */ protected function _form($action, Model $model, array $params = NULL) { $form = isset($params['form']) ? $params['form'] : $this->_form; if ( ! isset($form)) { throw new Kohana_Exception('Form is not defined for action :action in :controller', array(':action' => $action, ':controller' => get_class($this))); } // Create the form and bind the model to it $form = new $form($model); // Display flash message if (isset($_GET['flash'])) { $flash = (string) $_GET['flash']; if (isset($this->_actions[$action]["message_$flash"])) { $msg = $this->_actions[$action]["message_$flash"]; } else { $msg = 'Действие выполнено успешно'; } $form->message($this->_format($msg, $model)); } return $form; } /** * Default form for delete action * * @param Model $model * @param array $params * @return Form */ protected function _form_delete(Model $model, array $params = NULL) { $msg = isset($params['message']) ? $params['message'] : 'Действительно удалить?'; $msg = $this->_format($msg, $model); $form = new Form_Frontend_Confirm($msg); return $form; } /** * Prepare form for multi-action. * Override it to customize form initialization * * @param string $action * @param array $models array(Model) * @param array $params * @return Form */ protected function _prepare_form_multi($action, array $models, array $params = NULL) { if ( ! count($models)) { $msg = isset($params['message_empty']) ? $params['message_empty'] : 'Выберите хотя бы один элемент!'; $form = new Form_Frontend_Error($msg); return $form; } $method = "_form_$action"; if (method_exists($this, $method)) { // Use user-defined method to prepare the form $form = $this->$method($models, $params); } else { $form = $this->_form_multi($action, $models, $params); } // If ids were obtained through $_POST - save them in serialized form in hidden input // change form's target action if (isset($_POST['ids'])) { $form->action = URL::uri_to(NULL, array('action' => $action, 'history' => $this->request->param('history')), TRUE); if (is_array($_POST['ids'])) { $ids = implode('_', $_POST['ids']); } else { $ids = (string) $_POST['ids']; } $element = new Form_Element_Hidden('ids'); // Override full name, so it is not prefixed with forms name $element->full_name = 'ids'; $element->value = $ids; $form->add_component($element); } return $form; } /** * Default method to prepare the form for multi action * * @param string action * @param array $models array(Model) * @param array $params * @return Form */ protected function _form_multi($action, array $models, array $params = NULL) { $form = isset($params['form']) ? $params['form'] : $this->_form; if ( ! isset($form)) { throw new Kohana_Exception('Form is not defined for action :action in :controller', array(':action' => $action, ':controller' => get_class($this))); } // Create the form $form = new $form(); // Display flash message if (isset($_GET['flash'])) { $flash = (string) $_GET['flash']; if (isset($this->_actions[$action]["message_$flash"])) { $msg = $this->_actions[$action]["message_$flash"]; } else { $msg = 'Действие выполнено успешно'; } $form->message($msg); } return $form; } /** * Default form for multi-delete action * * @param array $models array(Model) * @param array $params * @return Form */ protected function _form_multi_delete(array $models, array $params = NULL) { $msg = isset($params['message']) ? $params['message'] : 'Действительно удалить?'; $msg = str_replace(':count', count($models), $msg); $form = new Form_Frontend_Confirm($msg); return $form; } // ------------------------------------------------------------------------- // Validation // ------------------------------------------------------------------------- /** * Validate the specified action * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return boolean */ protected function _validate($action, Model $model, Form $form, array $params = NULL) { // Validate form $form_result = $form->validate(); // Validate model if (isset($params['model_validate_method'])) { $method = $params['model_validate_method']; } else { $method = "validate_$action"; } $data = $form->get_values(); $model_result = $model->$method($data); if ( ! $model_result) { // Add model validation errors to the form $form->errors($model->errors()); } return ($model_result && $form_result); } /** * Validate the specified multi-action * * @param string $action * @param array $models array(Model) * @param Form $form * @param array $params * @return boolean */ protected function _validate_multi($action, array $models, Form $form, array $params = NULL) { // Validate form return $form->validate(); } /** * Validate the multi_delete * * @param array $models array(Model) * @param Form $form * @param array $params * @return boolean */ protected function _validate_multi_delete(array $models, Form $form, array $params = NULL) { // Validate form $form_result = $form->validate(); // Validate models $models_result = TRUE; foreach ($models as $model) { if ( ! $model->validate_delete()) { $form->errors($model->errors()); $models_result = FALSE; } } return ($models_result && $form_result); } // ------------------------------------------------------------------------- // Views // ------------------------------------------------------------------------- /** * Prepare view for action * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return View */ protected function _prepare_view($action, Model $model, Form $form, array $params = NULL) { $method = "_view_$action"; if (method_exists($this, $method)) { // Use user-defined method to prepare the view $view = $this->$method($model, $form, $params); } else { $view = $this->_view($action, $model, $form, $params); } return $view; } /** * Default view for action * Override it to customize view initialization * * @param string action * @param Model $model * @param Form $form * @param array $params * @return View */ protected function _view($action, Model $model, Form $form, array $params = NULL) { $view = isset($params['view']) ? $params['view'] : $this->_view; if ( ! isset($view)) { throw new Kohana_Exception('View script is not defined for action :action in :controller', array(':action' => $action, ':controller' => get_class($this))); } $view = new View($view); // View caption if (isset($params['view_caption'])) { $view->caption = $this->_format($params['view_caption'], $model); } // Set form $view->form = $form; return $view; } /** * Prepare view for multi-action * * @param string $action * @param array $models array(Model) * @param Form $form * @param array $params * @return View */ protected function _prepare_view_multi($action, array $models, Form $form, array $params = NULL) { $method = "_view_$action"; if (method_exists($this, $method)) { // Use user-defined method to prepare the view $view = $this->$method($models, $form, $params); } else { $view = $this->_view_multi($action, $models, $form, $params); } return $view; } /** * Default view for multi-action * Override it to customize view initialization * * @param string action * @param array $models array(Model) * @param Form $form * @param array $params * @return View */ protected function _view_multi($action, array $models, Form $form, array $params = NULL) { $view = isset($params['view']) ? $params['view'] : $this->_view; if ( ! isset($view)) { throw new Kohana_Exception('View script is not defined for action :action in :controller', array(':action' => $action, ':controller' => get_class($this))); } $view = new View($view); // View caption if (isset($params['view_caption'])) { $view->caption = $params['view_caption']; } // Render form $view->form = $form; return $view; } // ------------------------------------------------------------------------- // Action handlers // ------------------------------------------------------------------------- /** * Execute the specified action * * @param string $action * @param Model $model * @param Form $form * @param array $params */ protected function _execute($action, Model $model, Form $form, array $params = NULL) { throw new Kohana_Exception(':action handler is not defined in :controller', array(':action' => $action, ':controller' => get_class($this))); } /** * Method is called before execution of $action * * @param string $action * @param Model $model * @param Form $form * @param array $params */ protected function _before_execute($action, Model $model, Form $form, array $params = NULL) { } /** * Method is called after succesfull execution of $action * * @param string $action * @param Model $model * @param Form $form * @param array $params */ protected function _after_execute($action, Model $model, Form $form, array $params = NULL) { // Invalidate cache tags, if any if ( ! empty($params['cache_tags'])) { $cache = Cache::instance(); foreach ($params['cache_tags'] as $tag) { $cache->delete_tag($tag); } } } /** * Execute the specified multi-action * * @param string $action * @param array $models array(Model) * @param Form $form * @param array $params */ protected function _execute_multi($action, array $models, Form $form, array $params = NULL) { throw new Kohana_Exception(':action handler is not defined in :controller', array(':action' => $action, ':controller' => get_class($this))); } /** * Method is called after succesfull execution of multi $action * * @param string $action * @param array $model array(Model) * @param Form $form * @param array $params */ protected function _after_execute_multi($action, array $models, Form $form, array $params = NULL) { // Invalidate cache tags, if any if ( ! empty($params['cache_tags'])) { $cache = Cache::instance(); foreach ($params['cache_tags'] as $tag) { $cache->delete_tag($tag); } } } /** * Create model * * @param Model $model * @param Form $form * @param array $params */ protected function _execute_create(Model $model, Form $form, array $params = NULL) { $this->_before_execute('create', $model, $form, $params); $model->backup(); $model->values($form->get_values()); $model->save(); // Saving failed if ($model->has_errors()) { $form->errors($model->errors()); return; } $this->_after_execute('create', $model, $form, $params); $this->request->redirect($this->_redirect_uri('create', $model, $form, $params)); } /** * Update model * * @param Model $model * @param Form $form * @param array $params */ protected function _execute_update(Model $model, Form $form, array $params = NULL) { $this->_before_execute('update', $model, $form, $params); $model->backup(); $model->values($form->get_values()); $model->save(); // Saving failed if ($model->has_errors()) { $form->errors($model->errors()); return; } $this->_after_execute('update', $model, $form, $params); $this->request->redirect($this->_redirect_uri('update', $model, $form, $params) . '?flash=ok'); } /** * Delete model * * @param Model $model * @param Form $form * @param array $params */ protected function _execute_delete(Model $model, Form $form, array $params = NULL) { $this->_before_execute('delete', $model, $form, $params); $model->delete(); // Deleting failed if ($model->has_errors()) { $form->errors($model->errors()); return; } $this->_after_execute('delete', $model, $form, $params); $this->request->redirect($this->_redirect_uri('delete', $model, $form, $params)); } /** * Delete multiple models * * @param array $models array(Model) * @param Form $form * @param array $params */ protected function _execute_multi_delete(array $models, Form $form, array $params = NULL) { $result = TRUE; foreach ($models as $model) { $model->delete(); // Deleting failed if ($model->has_errors()) { $form->errors($model->errors()); $result = FALSE; } } if ( ! $result) return; // Deleting of at least one model failed... $this->_after_execute_multi('multi_delete', $models, $form, $params); $this->request->redirect($this->_redirect_uri('multi_delete', $model, $form, $params)); } /** * Move model up * * @param Model $model * @param array $params */ protected function _execute_up(Model $model, array $params = NULL) { $model->up(); $this->request->redirect($this->_redirect_uri('up', $model, NULL, $params)); } /** * Move model down * * @param Model $model * @param array $params */ protected function _execute_down(Model $model, array $params = NULL) { $model->down(); $this->request->redirect($this->_redirect_uri('down', $model, NULL, $params)); } /** * Generate redirect url for action * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { switch ($action) { case 'create': case 'delete': case 'multi_delete': case 'up': case 'down': $redirect_uri = isset($params['redirect_uri']) ? $params['redirect_uri'] : URL::uri_back(); break; case 'update': $redirect_uri = isset($params['redirect_uri']) ? $params['redirect_uri'] : $this->request->uri; break; default: $redirect_uri = ''; } return $redirect_uri; } // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- /** * Do the POST action * * @param string $action * @param array $params */ protected function _action($action, array $params = array()) { try { if (isset($this->_actions[$action])) { $params = array_merge($this->_actions[$action], $params); } if (isset($params['action'])) { // Change action $action = $params['action']; } // Prepare model for action $model = $this->_prepare_model($action, $params); // Prepare form for action $form = $this->_prepare_form($action, $model, $params); // It's a POST action (create, update, delete, ...) if ($form->is_submitted()) { // ----- Execute the action $action_to_do = $action; // Is there a sub-action executed? if ( ! empty($params['subactions'])) { foreach ($params['subactions'] as $subaction) { if ($form->has_component($subaction) && $form->get_value($subaction)) { $action_to_do = $subaction; break; } } } // Validate action $method = "_validate_$action_to_do"; if (method_exists($this, $method)) { // Use user-defined method to validate the action $result = $this->$method($model, $form, $params); } else { $result = $this->_validate($action_to_do, $model, $form, $params); } if ($result) { // Execute $method = "_execute_$action_to_do"; if (method_exists($this, $method)) { // Use user-defined method to execute the action $result = $this->$method($model, $form, $params); } else { $result = $this->_execute($action_to_do, $model, $form, $params); } } } // Prepare view for action $view = $this->_prepare_view($action, $model, $form, $params); // Render view & layout $this->request->response = $this->render_layout($view); } catch (Controller_FrontendCRUD_Exception $e) { // An error happened during action execution $this->_action_error($e->getMessage()); } } /** * Do the POST multi-action: action peformed on the list of models * * @param string $action * @param array $params */ protected function _action_multi($action, array $params = array()) { try { if (isset($this->_actions[$action])) { $params = array_merge($this->_actions[$action], $params); } if (isset($params['action'])) { // Change action $action = $params['action']; } // Prepare models for multi-action $models = $this->_prepare_models($action, $params); // Prepare form for multi-action $form = $this->_prepare_form_multi($action, $models, $params); // It's a POST action (create, update, delete, ...) if ($form->is_submitted()) { // ----- Execute the action // Validate action $method = "_validate_$action"; if (method_exists($this, $method)) { // Use user-defined method to validate the action $result = $this->$method($models, $form, $params); } else { $result = $this->_validate_multi($action, $models, $form, $params); } if ($result) { // Execute $method = "_execute_$action"; if (method_exists($this, $method)) { // Use user-defined method to execute the action $result = $this->$method($models, $form, $params); } else { $result = $this->_execute_multi($action, $models, $form, $params); } } } // Prepare view for multi-action $view = $this->_prepare_view_multi($action, $models, $form, $params); // Render view & layout $this->request->response = $this->render_layout($view); } catch (Controller_FrontendCRUD_Exception $e) { // An error happened during action execution $this->_action_error($e->getMessage()); } } /** * Do the GET action * * @param string $model * @param array $params */ protected function _action_get($action, array $params = array()) { try { if (isset($this->_actions[$action])) { $params = array_merge($this->_actions[$action], $params); } if (isset($params['action'])) { // Change action $action = $params['action']; } // Prepare model for action $model = $this->_prepare_model($action, $params); // Execute (should always redirect) $method = "_execute_$action"; if (method_exists($this, $method)) { // Use user-defined method to execute the action $result = $this->$method($model, $params); } else { $result = $this->_execute($action, $model, $params); } } catch (Controller_FrontendCRUD_Exception $e) { // An error happened during action execution $this->_action_error($e->getMessage()); } } /** * Create new model */ public function action_create() { $this->_action('create'); } /** * Update model */ public function action_update() { $this->_action('update'); } /** * Delete model */ public function action_delete() { $this->_action('delete'); } /** * Move model up */ public function action_up() { $this->_action_get('up'); } /** * Move model down */ public function action_down() { $this->_action_get('down'); } /** * Handle ajax validation */ public function action_validate() { try { // Action to validate $action = $this->request->param('v_action'); $params = array(); if (isset($this->_actions[$action])) { $params = $this->_actions[$action]; } if (isset($params['action'])) { // Change action $action = $params['action']; } // Prepare model for action $model = $this->_prepare_model($action, $params); // Prepare form for action $form = $this->_prepare_form($action, $model, $params); // Validate action $method = "_validate_$action"; if (method_exists($this, $method)) { // Use user-defined method to validate the action $result = $this->$method($model, $form, $params); } else { $result = $this->_validate($action, $model, $form, $params); } // Return errors (if any) in JSON format $this->request->response = json_encode($form->errors()); } catch (Exception $e) { // An error happened during action execution $this->request->response = json_encode(array($e->getMessage())); } } // ------------------------------------------------------------------------- // Multi-actions // ------------------------------------------------------------------------- /** * Multi-action: action with the list of models */ public function action_multi() { // What action to peform? if (empty($_POST['action']) || ! is_array($_POST['action'])) { $this->request->redirect(URL::uri_back ()); } $action = array_keys($_POST['action']); $action = $action[0]; // Model ids if (isset($_POST['ids']) && is_array($_POST['ids'])) { $ids = $_POST['ids']; } else { $ids = array(); } if (count($ids) > 20) { // Too many ids selected - do not redirect, forward as post action $this->request->forward(get_class($this), $action); } else { $ids = implode('_', $ids); // Redirect to action $this->request->redirect(URL::uri_to(NULL, array('action' => $action, 'ids' => $ids, 'history' => $this->request->param('history')), TRUE)); } } /** * Delete multiple models * * @param array $ids */ public function action_multi_delete() { $this->_action_multi('multi_delete'); } // ------------------------------------------------------------------------- // Misc // ------------------------------------------------------------------------- /** * Replace placeholders in string by actual values from model. * * @param string $str * @param Model $model * @return string */ protected function _format($str, Model $model = NULL) { if ($model === NULL) { return $str; } preg_match_all('/:(\w+)/', $str, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $param = $match[1]; $str = str_replace($match[0], HTML::chars($model->$param), $str); } return $str; } } <file_sep>/modules/shop/acl/classes/controller/frontend/users.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Users extends Controller_FrontendRES { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_User'; $this->_form = 'Form_Frontend_User'; $this->_view = 'frontend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание пользователя' ), 'update' => array( 'view_caption' => 'Редактирование пользователя' ) ); } /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = 'layouts/acl') { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = 'layouts/acl') { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Prepare user for update action * * @param string $action * @param string|Model_User $user * @param array $params * @return Model_User */ protected function _model($action, $user, array $params = NULL) { $params['id'] = Model_User::current()->id; return parent::_model($action, $user, $params); } public function _view_create(Model_User $model, Form_Frontend_User $form, array $params = NULL) { $organizer = new Model_Organizer(); $form_organizer = new Form_Frontend_Organizer($organizer); if ($form_organizer->is_submitted()) { $form_organizer->validate(); // User is trying to log in if ($form_organizer->validate()) { $vals = $form_organizer->get_values(); if ($organizer->validate($vals)) { $organizer->values($vals); $organizer->save(); $form->get_element('organizer_name')->set_value($organizer->name); $form->get_element('organizer_id')->set_value($organizer->id); } } } $modal = Layout::instance()->get_placeholder('modal'); $modal = $form_organizer->render().' '.$modal; Layout::instance()->set_placeholder('modal',$modal); $view = new View('frontend/users/control'); $view->user = $model; $view->form = $form; return $view; } protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { if($action == 'create') { return URL::uri_to('frontend/acl/users/control',array('action' => 'confirm')); } if ($action == 'update') { $result = Auth::instance()->login( $model->email, $model->password); if ($result) { //$this->request->redirect(URL::uri_to('frontend/acl/users/control',array('action' => 'control'))); //$this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Auth::instance()->get_user()->town->alias))); $this->request->redirect(URL::uri_to('frontend/area/towns',array('action'=>'choose', 'are_town_alias' => Model_Town::ALL_TOWN))); } else { $this->_action_404(); return; } } return parent::_redirect_uri($action, $model, $form, $params); } public function _view_update(Model_User $model, Form_Frontend_User $form, array $params = NULL) { $organizer = new Model_Organizer(); $form_organizer = new Form_Frontend_Organizer($organizer); if ($form_organizer->is_submitted()) { $form_organizer->validate(); // User is trying to log in if ($form_organizer->validate()) { $vals = $form_organizer->get_values(); if ($organizer->validate($vals)) { $organizer->values($vals); $organizer->save(); $form->get_element('organizer_name')->set_value($organizer->name); $form->get_element('organizer_id')->set_value($organizer->id); } } } $modal = Layout::instance()->get_placeholder('modal'); $modal = $form_organizer->render().' '.$modal; Layout::instance()->set_placeholder('modal',$modal); $view = new View('frontend/users/control'); $view->user = $model; $view->form = $form; return $view; } public function action_index() { //TODO CARD of the USER } public function action_control() { $view = new View('frontend/workspace'); $view->content = $this->widget_user(); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Redraw user images widget via ajax request */ public function action_ajax_user_images() { $request = Widget::switch_context(); $user = Model_User::current(); if ( ! isset($user->id)) { FlashMessages::add('Пользователь не найден', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('users') ->widget_user_images($user); $widget->to_response($this->request); $this->_action_ajax(); } /** * Renders user account settings * * @param boolean $select * @return string */ public function widget_user($view = 'frontend/user') { // ----- Current user $user_id = $this->request->param('user_id',NULL); if (!$user_id) { $user = Model_User::current(); } else { $user = Model::fly('Model_User')->find($user_id); } if ( $user->id === NULL) { $this->_action_404('Указанный пользователь не найден'); return; } // Set up view $view = new View($view); $view->user = $user; return $view->render(); } /** * Render images for user (when in user profile) * * @param Model_User $user * @return Widget */ public function widget_user_images(Model_User $user) { $widget = new Widget('frontend/users/user_images'); $widget->id = 'user_' . $user->id . '_images'; $widget->ajax_uri = URL::uri_to('frontend/acl/user/images'); $widget->context_uri = FALSE; // use the url of clicked link as a context url $images = Model::fly('Model_Image')->find_all_by_owner_type_and_owner_id('user', $user->id, array( 'order_by' => 'position', 'desc' => FALSE )); if ($images->valid()) { $image_id = (int) $this->request->param('image_id'); if ( ! isset($images[$image_id])) { $image_id = $images->at(0)->id; } $widget->image_id = $image_id; // id of current image $widget->images = $images; $widget->user = $user; } return $widget; } /** * Perpare user model for creation * * @param string|Model $model * @param array $params * @return Model */ protected function _model_create($model, array $params = NULL) { $user = parent::_model('create', $model, $params); $user->group_id = $this->request->param('group_id'); return $user; } /** * Renders list of users * * @return string Html */ public function widget_users() { $user = new Model_User(); $order_by = $this->request->param('acl_uorder', 'id'); $desc = (bool) $this->request->param('acl_udesc', '0'); $per_page = 10; $group_id = (int) $this->request->param('group_id'); if ($group_id > 0) { // Show users only from specified group $group = new Model_Group(); $group->find($group_id); if ($group->id === NULL) { // Group was not found - show a form with error message return $this->_widget_error('Группа с идентификатором ' . $group_id . ' не найдена!'); } $count = $user->count_by_group_id($group->id); $pagination = new Paginator($count, $per_page); $users = $user->find_all_by_group_id_and_active($group->id,true, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc ), TRUE); } else { $group = NULL; // Select all users $count = $user->count(); $pagination = new Paginator($count, $per_page); $users = $user->find_all_by_active(true,array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); } $view = new View('backend/users'); $view->order_by = $order_by; $view->desc = $desc; $view->group = $group; $view->users = $users; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Renders list of users for user-select dialog * * @return string Html */ public function widget_user_select($view = 'frontend/user_select') { $user = new Model_User(); $order_by = $this->request->param('acl_uorder', 'id'); $desc = (bool) $this->request->param('acl_udesc', '0'); $per_page = 20; $group_id = (int) $this->request->param('group_id'); if ($group_id > 0) { // Show users only from specified group $group = new Model_Group(); $group->find($group_id); if ($group->id === NULL) { // Group was not found - show a form with error message return $this->_widget_error('Группа с идентификатором ' . $group_id . ' не найдена!'); } $count = $user->count_by_group_id($group->id); $pagination = new Paginator($count, $per_page); $users = $user->find_all_by_group_id_and_active($group->id,true, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc ), TRUE); } else { $group = NULL; // Select all users $count = $user->count(); $pagination = new Paginator($count, $per_page); $users = $user->find_all_by_active(true,array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); } $view = new View($view); $view->order_by = $order_by; $view->desc = $desc; $view->group = $group; $view->users = $users; $view->pagination = $pagination->render('pagination'); return $view->render(); } /** * Renders user account settings * * @param boolean $select * @return string */ public function widget_user_card($user,array $fields = array()) { if (empty($fields)) { $fields = array('image','name'); } $view = 'frontend/user_card'; $widget = new Widget($view); $widget->id = 'user_card' . $user->id; $widget->context_uri = FALSE; // use the url of clicked link as a context url $widget->user = $user; $widget->fields = $fields; return $widget; } /** * Render list of external links for user (when in user profile) * * @param Model_User $user * @return Widget */ public function widget_links(Model_User $user) { $widget = new Widget('frontend/users/links'); $widget->id = 'user_' . $user->id . '_links'; $links = $user->links; if ($links->valid()) { $widget->links = $links; $widget->user = $user; } return $widget; } /** * Add breadcrumbs for current action */ public function add_breadcrumbs(array $request_params = array()) { if (empty($request_params)) { list($name, $request_params) = URL::match(Request::current()->uri); } if ($request_params['action'] == 'control') { Breadcrumbs::append(array( 'uri' => URL::uri_to('frontend/acl/users/control',array('action' => 'control')), 'caption' => 'Профайл')); } } public function action_confirm() { $view = new View('frontend/users/confirm'); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } } <file_sep>/modules/general/cackle/config/cackle.php <?php defined('SYSPATH') OR die('No direct access allowed.'); return array ( // Ключ api вконтакте "cackle_key" => "26520" ); <file_sep>/application/classes/layout.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Layout * * @package Eresus * @author <NAME> (<EMAIL>) */ class Layout extends View { /** * Layout instance * @var Layout */ protected static $_instance; /** * Returns a new Layout object. * * @param string view filename * @param array array of values * @return View */ public static function factory($file = NULL, array $data = NULL) { return new Layout($file, $data); } /** * Get layout instance * * @return Layout */ public static function instance() { if (self::$_instance === NULL) { self::$_instance = new Layout(); } return self::$_instance; } /** * @var array */ protected $_title = array(); /** * @var array */ protected $_description = array(); /** * @var array */ protected $_keywords = array(); /** * Stylesheets for this layout * * @var array */ protected $_styles = array(); /** * Script files for layout * * @var array */ protected $_scripts = array(); /** * Add string to site title * * @param boolean $reverse * @param string $title */ public function add_title($title, $reverse = FALSE) { $title = trim($title); if ($title !== '') { if ($reverse) { array_unshift($this->_title, $title); } else { $this->_title[] = $title; } } } /** * Add string to site description * * @param boolean $reverse * @param string $description */ public function add_description($description, $reverse = FALSE) { $description = trim($description); if ($description !== '') { if ($reverse) { array_unshift($this->_description, $description); } else { $this->_description[] = $description; } } } /** * Add string to site keywords * * @param boolean $reverse * @param string $keywords */ public function add_keywords($keywords, $reverse = FALSE) { $keywords = trim($keywords); if ($keywords !== '') { if ($reverse) { array_unshift($this->_keywords, $keywords); } else { $this->_keywords[] = $keywords; } } } /** * Add stylesheet to layout * * @param string $file Url to stylesheet * @return Layout */ public function add_style($file, $ie_condition = FALSE) { $this->_styles[$file] = array( 'file' => $file, 'ie_condition' => $ie_condition ); return $this; } /** * Add script to layout * * $raw determines whether to link $script points to script file or is a raw script text * * @param string $script Url to script file | raw script text * @param boolean $raw If true - $file is link scripts file, if f * @return Layout */ public function add_script($script, $raw = FALSE) { $this->_scripts[$script] = array( 'script' => $script, 'raw' => $raw ); return $this; } /** * Replace title, description, keywords, styles and scripts * * @param string $name * @return string */ public function render_placeholder($name) { switch ($name) { case 'title': $this->add_title(Model_Site::current()->settings['meta_title']); return implode(' - ', $this->_title); case 'description': $this->add_description(Model_Site::current()->settings['meta_description']); return implode(' ', $this->_description); case 'keywords': $this->add_keywords(Model_Site::current()->settings['meta_keywords']); return implode(' ', $this->_keywords); case 'styles': $styles_html = ''; foreach ($this->_styles as $style) { $styles_html .= HTML::style($style['file'], NULL, FALSE, $style['ie_condition']) . "\n"; } return $styles_html; case 'scripts': $scripts_html = ''; foreach ($this->_scripts as $script) { $scripts_html .= HTML::script($script['script'], NULL, FALSE, $script['raw']) . "\n"; } return $scripts_html; default: return parent::render_placeholder($name); } } }<file_sep>/modules/general/tags/public/js/backend/tag.js /** * Set form element value */ jFormElement.prototype.set_tag = function(value) { $('#' + 'tag').val(value['name']); }<file_sep>/modules/shop/acl/classes/model/privilegegroup.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PrivilegeGroup extends Model { /** * Get "active" privilege * * @return boolean */ public function get_active() { if ($this->system) { // System privileges are always active return 1; } elseif (isset($this->_properties['active'])) { return $this->_properties['active']; } else { return 0; // default value } } /** * Set "active" privilege * * @param <type> $value */ public function set_active($value) { // System privileges are always active if ($this->system) { $value = 1; } $this->_properties['active'] = $value; } /** * Link given privilege to group * * @param Model_Privilege $privilege * @param array $privgroups */ public function link_privilege_to_groups(Model_Privilege $privilege, array $privgroups) { // Delete all info $this->delete_all_by_privilege_id($privilege->id); $privgroup = Model::fly('Model_PrivilegeGroup'); foreach ($privgroups as $values) { $privgroup->values($values); $privgroup->privilege_id = $privilege->id; $privgroup->save(); } } /** * Link given group to privileges * * @param Model_Group $group * @param array $privgroups */ public function link_group_to_privileges(Model_Group $group, array $privgroups) { // Delete all info $this->delete_all_by_group_id($group->id); $privgroup = Model::fly('Model_PrivilgeGroup'); foreach ($privgroups as $values) { $privgroup->values($values); $privgroup->group_id = $group->id; $privgroup->save(); } } }<file_sep>/modules/backend/views/backend/menu/sidebar.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="panel"> <?php if (isset($caption)) { echo '<div class="panel_caption">' . $caption . '</div>'; } ?> <div class="panel_content"> <div class="area"> <div class="area_content"> <div class="content"> <div class="sidebar_menu"> <?php foreach ($items as $item) { // Build menu item class $class = ''; if ( ! empty($item['selected'])) { $class .= ' selected'; } if (isset($item['icon'])) { $class .= ' icon_' . $item['icon']; } $class = trim($class); if ($class != '') { $class = ' class="' . trim($class) . '"'; } echo '<a href="' . Model_Backend_Menu::url($item) .'"' . (isset($item['title']) ? ' title="' . HTML::chars($item['title']) . '"' : '') . $class . '>' . $item['caption'] . '</a>'; } ?> </div> </div> </div> </div> </div> </div> <file_sep>/modules/shop/catalog/views/frontend/products/_helper.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Build brands, subbrands and categories html for given product * * @param Model_Product $product * @return array(brands_html, subbrands_html, cat_html) */ function categories(Model_Product $product) { $sectiongroups = Model::fly('Model_SectionGroup')->find_all_cached(); foreach ($sectiongroups as $sectiongroup) { $sections[$sectiongroup->id] = Model::fly('Model_Section')->find_all_active_cached($sectiongroup->id); } $section_ids = $product->sections; $series_html = array(); $cat_html = array(); foreach ($sectiongroups as $sectiongroup) { if (isset($section_ids[$sectiongroup->id])) { foreach (array_keys($section_ids[$sectiongroup->id]) as $id) { $sec = $sections[$sectiongroup->id][$id]; if ($sec->level <= 2) { $cat_html[$sectiongroup->id][$sec->id] = '<a href="' . URL::site($sec->uri_frontend()) . '">' . $sec->caption . '</a>'; } else { foreach ($sections[$sectiongroup->id]->parents($sec) as $par) { if ($par->level == 2) { $cat_html[$sectiongroup->id][$par->id] = '<a href="' . URL::site($par->uri_frontend()) . '">' . $par->caption . '</a>'; break; } } } } } } foreach ($cat_html as $sectiongroup_id => $cat_html_sectiongroup) { $cat_html_sectiongroup = ( ! empty($cat_html_sectiongroup)) ? implode(' , ', $cat_html_sectiongroup) : '---'; $cat_html[$sectiongroup_id] = $cat_html_sectiongroup; } return $cat_html; } <file_sep>/application/classes/l10n.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Locale info * * @package Eresus * @author <NAME> (<EMAIL>) */ class l10n { /** * Locale information cache * @var array */ protected static $_locale_info; /** * Obtain locale information * * @param string $field * @return string */ protected static function get_locale_info($field) { if (self::$_locale_info === NULL) { self::$_locale_info = localeconv(); } if (isset(self::$_locale_info[$field])) { return self::$_locale_info[$field]; } else { return NULL; } } /** * Return decimal point character for current locale * * @return string */ public static function decimal_point() { return self::get_locale_info('decimal_point'); } /** * Make a correct plural form of word for given number * * @param integer $number * @param string $form1 1 'Товар' 1 'Рубль' * @param string $form2 10 'Товаров' 10 'Рублей' * @param string $form3 2 'Товара' 2 'Рубля' * @return string */ public static function plural($number, $form1, $form2 = NULL, $form3 = NULL) { if ( ! isset($form2)) $form2 = $form1; if ( ! isset($form3)) $form3 = $form1; if ($number >= 11 && $number <= 19) return $form2; $last_digit = (int) $number % 10; if ($last_digit == 1) return $form1; if ($last_digit >= 2 && $last_digit <= 4) return $form3; return $form2; } /** * Convert a string to floating point * @TODO: more carefully handle locale-specific formatting (such as decimal and thousands separators) * * @param string $value * @return float */ public static function string_to_float($value) { if (is_int($value) || is_double($value)) return $value; return (float) str_replace(array('.', ','), '.', (string) $value); } /** * Format a time/date * * @param string $format Formatted like for the strftime() function * @param integer $timestamp * @return string */ public static function date($format, $timestamp) { return strftime($format, $timestamp); } public static function rdate($param, $time=0) { if(intval($time)==0)$time=time(); $MonthNames=array("Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августа", "Сентября", "Октября", "Ноября", "Декабря"); $DayNames=array("Воскресение","Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"); if(strpos($param,'D')) { $param = str_replace('D',$DayNames[date('w',$time)],$param); } if(strpos($param,'M')) { $param = str_replace('M',$MonthNames[date('n',$time)-1],$param); } return date($param, $time); } /** * Parse the given date and return the unix timestamp * The format of the date is specified in $format * Default values for time components, that are not present in format, can be specified * If not specified, the values defaults to the current time ($hour = time('H'), $minute = time('i'), ...) * * @param string $format Formatted like for the strftime() function * @param string $date * @param int $hour * @param int $minute * @param int $second * @param int $month * @param int $day * @param int $year * * @return integer|boolean The desired timestamp or FALSE on failure */ public static function timestamp( $format, $date, $hour = NULL, $minute = NULL, $second = NULL, $month = NULL, $day = NULL, $year = NULL) { $regexp = self::date_format_regexp($format); if ( ! preg_match($regexp, $date, $matches)) return FALSE; extract($matches); return mktime($hour, $minute, $second, $month, $day, $year); } /** * Convert date string from one format to another * @todo: a lot, a lot ... * * @param string $datetime * @param string $format_from * @param string $format_to * @return string */ public static function datetime_convert($datetime, $format_from, $format_to) { $regexp = self::date_format_regexp($format_from); if ( ! preg_match($regexp, $datetime, $matches)) return FALSE; extract($matches); if ( ! isset($hour)) $hour = '00'; if ( ! isset($minute)) $minute = '00'; if ( ! isset($second)) $second = '00'; if ( ! isset($month)) $month = '00'; if ( ! isset($day)) $day = '00'; if ( ! isset($year)) $year = '0000'; return str_replace( array('H', 'i', 's', 'm', 'd', 'Y'), array($hour, $minute, $second, $month, $day, $year), $format_to ); } /** * Return localized version of date format * * @param string $format Formatted like for strftime() function */ public static function translate_datetime_format($format) { return str_replace( array('Y', 'm', 'd', 'H', 'i', 's'), array('гггг', 'мм', 'дд', 'чч', 'мм', 'сс'), $format ); } /** * Build a regexp to parse date format * Format is expected to have special characters just like in strftime() function * @todo: excape more regexp special characters in format * * @param string $format * @return string */ public static function date_format_regexp($format) { $regexp = strtr($format, array( 'H' => '(?<hour>\d{2})', 'i' => '(?<minute>\d{2})', 's' => '(?<second>\d{2})', 'd' => '(?<day>\d{2})', 'm' => '(?<month>\d{2})', 'Y' => '(?<year>\d{4})' )); $regexp = '/^\s*' . $regexp . '\s*$/i'; return $regexp; } /** * @param string $string * @return string */ public static function transliterate($string) { return strtr($string, array( 'а' => 'a', 'А' => 'A', 'б' => 'b', 'Б' => 'B', 'в' => 'v', 'В' => 'V', 'г' => 'g', 'Г' => 'G', 'д' => 'd', 'Д' => 'D', 'е' => 'e', 'Е' => 'E', 'ё' => 'jo', 'Ё' => 'JO', 'ж' => 'zh', 'Ж' => 'ZH', 'з' => 'z', 'З' => 'Z', 'и' => 'i', 'И' => 'I', 'й' => 'j', 'Й' => 'J', 'к' => 'k', 'К' => 'K', 'л' => 'l', 'Л' => 'L', 'м' => 'm', 'М' => 'M', 'н' => 'n', 'Н' => 'N', 'о' => 'o', 'О' => 'O', 'п' => 'p', 'П' => 'P', 'р' => 'r', 'Р' => 'R', 'с' => 's', 'С' => 'S', 'т' => 't', 'Т' => 'T', 'у' => 'u', 'У' => 'U', 'ф' => 'f', 'Ф' => 'F', 'х' => 'h', 'Х' => 'H', 'ц' => 'c', 'Ц' => 'C', 'ч' => 'ch', 'Ч' => 'CH', 'ш' => 'sh', 'Ш' => 'SH', 'щ' => 'w', 'Щ' => 'W', 'ь' => '\'', 'Ь' => '\'', 'ы' => 'y', 'Ы' => 'У', 'ъ' => '#', 'Ъ' => '#', 'э' => 'je', 'Э' => 'JE', 'ю' => 'ju', 'Ю' => 'JU', 'я' => 'ja', 'Я' => 'JA' )); } }<file_sep>/modules/shop/acl/classes/model/group.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Group extends Model { const ADMIN_GROUP_ID = 1; const EDITOR_GROUP_ID = 2; const USER_GROUP_ID = 3; /** * Does this group have the requested privilege? * * @param string $privilege * @return boolean */ public function granted($privilege) { if ($this->id === NULL) { // deny access for all unauthorized users return false; } if (isset($this->privileges_hash[$privilege])) { $privilege_desc = $this->privileges_hash[$privilege]; return ($privilege_desc['value'] == 1); } return false; } /** * Group is not system by default * * @return boolean */ public function default_system() { return FALSE; } /** * Get privileges for this group * * @return array */ /*public function get_privileges() { if ($this->system) { // System groups has all privileges $privileges = array(); foreach (array_keys(Auth::instance()->privileges()) as $privilege) { $privileges[$privilege] = TRUE; } return $privileges; } elseif (isset($this->_properties['privileges'])) { return $this->_properties['privileges']; } else { return $this->default_privileges(); } }*/ /** * Get active[!] privileges for this group */ public function get_privileges() { if ( ! isset($this->_properties['privileges'])) { if ($this->id !== NULL) { $privileges = Model::fly('Model_Privilege')->find_all_by_group_id_and_active_and_system( $this->id, 1, 0, array('order_by' => 'position', 'desc' => FALSE) ); } else { $privileges = new Models('Model_Privilege',array()); } $this->_properties['privileges'] = $privileges; } return $this->_properties['privileges']; } public function get_privileges_hash() { if (!isset($this->_properties['privileges_hash'])) { $privileges_hash = array(); $privileges = $this->privileges; foreach ($privileges as $privilege) { $name = $privilege->name; if (isset($this->$name)) { $privilege_desc['value'] = $this->$name; $privileges_hash[$name] = $privilege_desc; } } $this->_properties['privileges_hash'] = $privileges_hash; } return $this->_properties['privileges_hash']; } public function get_privileges_granted() { if (!isset($this->_properties['privileges_granted'])) { $privileges = $this->privileges; $privileges_granted = clone $privileges; $privileges_granted_arr = array(); foreach ($privileges_granted as $key =>$privilege) { if ($this->granted($privilege->name)) { $privileges_granted_arr[$privilege->id] = $privilege->values(); } } $this->_properties['privileges_granted'] = new Models('Model_Privilege',$privileges_granted_arr); } return $this->_properties['privileges_granted']; } /** * Set group privileges * @param array $privileges */ /*public function set_privileges(array $privileges) { if ( ! $this->system) { // Privileges can be changed only for non-system groups $this->_properties['privileges'] = $privileges; } }*/ /** * Set system flag * * @param boolean $system */ public function set_system($system) { // Prohibit setting system property for group - do nothing } /** * Is group valid to be deleted? * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->system) { $this->error('Группа является системной. Её удаление запрещено!', 'system'); return FALSE; } return TRUE; } /** * Get property-section infos * * @return Models */ public function get_privilegegroups() { if ( ! isset($this->_properties['privilegegroups'])) { $this->_properties['privilegegroups'] = Model::fly('Model_PrivilegeGroup')->find_all_by_group($this, array('order_by' => 'position', 'desc' => FALSE)); } return $this->_properties['privilegegroups']; } /** * Get property-section infos as array for form * * @return array */ public function get_privgroups() { if ( ! isset($this->_properties['privgroups'])) { $result = array(); foreach ($this->privilegegroups as $privgroup) { if ($privgroup->privilege_id !== NULL) $result[$privgroup->privilege_id]['privilege_id'] = $privgroup->privilege_id; $result[$privgroup->privilege_id]['active'] = $privgroup->active; } $this->_properties['privgroups'] = $result; } return $this->_properties['privgroups']; } /** * Set property-section link info (usually from form - so we need to add 'section_id' field) * * @param array $propsections */ public function set_privgroups(array $privgroups) { foreach ($privgroups as $privilege_id => & $privgroup) { if ( ! isset($privgroup['privilege_id'])) { $privgroup['privilege_id'] = $privilege_id; } } $this->_properties['privgroups'] = $privgroups; } public function save($create = FALSE,$update_privileges = TRUE) { parent::save($create); if ($update_privileges) { // Link section to the properties Model::fly('Model_PrivilegeGroup_Mapper')->link_group_to_privileges($this, $this->privgroups); // Update values for additional properties Model_Mapper::factory('Model_PrivilegeValue_Mapper')->update_values_for_group($this); } } /** * Delete group and all users from it */ public function delete() { // Delete all users from group Model::fly('Model_User')->delete_all_by_group_id($this->id); // Delete privilege values for this group Model_Mapper::factory('Model_PrivilegeGroup_Mapper')->delete_all_by_group_id($this, $this->id); // Delete privilege values for this product Model_Mapper::factory('Model_PrivilegeValue_Mapper')->delete_all_by_group_id($this, $this->id); // Delete group itself parent::delete(); } }<file_sep>/modules/general/filemanager/classes/controller/backend/filemanager.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Filemanager extends Controller_Backend { /** * Default action */ public function action_index() { $view = new View('backend/workspace'); if ( ! $this->request->param('fm_tinymce')) { // Filemanager is NOT rendered in TinyMCE popup window $view->caption = 'Файловый менеджер'; } $view->content = $this->widget_files(); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Create new directory */ public function action_mkdir() { try { $this->setup_root_path(); $file = new Model_File(); // Create in current directory $file->relative_dir_name = URL::decode($this->request->param('fm_path')); $form = new Form_Backend_File(TRUE, TRUE); if (Request::$method == 'POST') { // Add values from _POST to form $data = $form->get_values(); // Validate form and file if ($form->validate() && $file->validate_mkdir($data)) { // Make dir $file->values($data); if ($file->do_mkdir($data)) { // Directory was created succesfully $this->request->redirect(URL::uri_back()); } } // Add model errors to form $form->errors($file->errors()); } } catch (Filemanager_Exception $e) { // An error occured $form = new Form_Backend_Error($e->getMessage()); } $view = new View('backend/form'); $view->caption = 'Создание директории'; $view->form = $form; // Display flash message if (isset($_GET['flash']) && (string) $_GET['flash'] == 'ok') { $form->message('Директория создана успешно'); } $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Rename file/dir */ public function action_rename() { try { $this->setup_root_path(); $file = new Model_File(); $file->relative_path = URL::decode($this->request->param('fm_path')); if ( ! $file->file_exists()) { // Specified path doesn't exists or access is denied throw new Filemanager_Exception('Файл "' . $file->path . '" не найден!'); } if ( ! $file->is_relative()) { // $file->path is outside root path throw new Filemanager_Exception('Путь "' . $file->path . '" находится вне корневой директории "' . $file->root_path . '"!'); } $form = new Form_Backend_File($file->is_dir()); // Set default values from model $form->set_defaults(array( 'relative_dir_name' => $file->relative_dir_name, 'base_name' => $file->base_name )); if ($form->is_submitted()) { $data = $form->get_values(); // Validate form and file if ($form->validate() && $file->validate_rename($data)) { // Rename file if ($file->do_rename($data)) { // Renaming succeded $this->request->redirect(URL::uri_back()); } } // Get model errors $form->errors($file->errors()); } } catch (Filemanager_Exception $e) { // An error occured $form = new Form_Backend_Error($e->getMessage()); } $view = new View('backend/form'); $view->caption = 'Изменение имени ' . ($file->is_dir() ? 'директории' : 'файла'); $view->form = $form; // Display flash message if (isset($_GET['flash']) && (string) $_GET['flash'] == 'ok') { $form->message('Имя файла изменено'); } $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Delete file/dir */ public function action_delete() { try { $this->setup_root_path(); $file = new Model_File(); $file->relative_path = URL::decode($this->request->param('fm_path')); if ( ! $file->file_exists()) { // Specified path doesn't exists or access is denied throw new Filemanager_Exception('Файл "' . $file->path . '" не найден!'); } $errors = array(); if (Request::$method == 'POST') { if ($file->validate_delete()) { // Delete file/dir if ($file->do_delete()) { // Deletion succeded, redirect back $this->request->redirect( URL::uri_back()); } } // Add model errors $errors = $file->get_errors(); } // Display form with request for delete confirmation $form = new Form_Backend_Confirm('Удалить ' . ($file->is_dir() ? 'директорию' : 'файл') .' "' . $file->relative_path . '"?'); // Add errors to form if (!empty($errors)) { $form->add_errors(array_values($errors)); } } catch (Filemanager_Exception $e) { // An error occured $form = new Form_Backend_Error($e->getMessage()); } $view = new View('backend/form'); $view->caption = 'Удаление ' . ($file->is_dir() ? 'директории' : 'файла'); $view->form = $form; $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Edit file contents */ public function action_edit() { try { $this->setup_root_path(); $file = new Model_File(); $file->relative_path = URL::decode($this->request->param('fm_path')); if ( ! $file->file_exists()) { // Specified path doesn't exists or access is denied throw new Filemanager_Exception('Файл "' . $file->relative_path . '" не найден!'); } if ($file->is_dir()) { throw new Filemanager_Exception('Путь "' . $file->relative_path . '" является директорией!'); } $form = new Form_Backend_EditFile(); // Set default values from model $form->set_defaults(array( 'content' => $file->content, )); if ($form->is_submitted()) { // Validate form and file if ($form->validate() && $file->validate_save()) { $file->values($form->get_values()); // Save file contents if ($file->save()) { // Renaming succeded $this->request->redirect(Request::current()->uri . '?flash=ok'); } } // Get model errors $form->add_errors($file->get_errors()); } } catch (Filemanager_Exception $e) { // An error occured $form = new Form_Backend_Error($e->getMessage()); } $view = new View('backend/form'); $view->caption = 'Редактирование файла ' . $file->base_name; $view->form = $form; // Display flash message if (isset($_GET['flash']) && (string) $_GET['flash'] == 'ok') { $form->message('Файл сохранён успешно!'); } $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Render list of files * * @return <type> */ /** * * @param string $root_path Root path. NULL means that root path * @return <type> */ public function widget_files() { try { $this->setup_root_path(); $dir = new Model_File(); $dir->relative_path = URL::decode($this->request->param('fm_path')); if ( ! $dir->is_dir()) { throw new Filemanager_Exception('Путь "' . $dir->path . '" не является директорией!'); } if ( ! $dir->is_relative()) { // $dir->path is outside root path throw new Filemanager_Exception('Путь "' . $dir->path . '" находится вне корневой директории "' . $dir->root_path . '"!'); } if ($dir->is_hidden()) { // Don't allow viewing hidden dirs throw new Filemanager_Exception('Директория ' . $dir->relative_path . ' является скрытой!'); } // ----- Obtain sorted list of files in directory $files = $dir->get_files(); if ($files === NULL) { // An error occured while retrieving files in directory throw new Filemanager_Exception($dir->get_last_error()); } // ----- Create thumbnails for images (silently ignore all errors) $dir->create_preview_thumbs($files); // Select appropriate view script to render list of files $list_style = $this->request->param('fm_style'); switch ($list_style) { case 'thumbs': case 'list': break; default: $list_style = 'list'; } $view = new View('backend/files'); $view->file_upload = $this->widget_file_upload(); $view->dir = $dir; $view->files = $files; $view->list_style = $list_style; $view->in_tinymce = $this->request->param('fm_tinymce'); $view->root = $this->request->param('fm_root'); return $view; } catch (Filemanager_Exception $e) { return $this->_widget_error($e->getMessage()); } } /** * Render file upload form, handle uploads * * @return string */ public function widget_file_upload() { try { $file = new Model_File(); // Upload to current directory $file->relative_dir_name = URL::decode($this->request->param('fm_path')); $file->uploaded_file = 'uploaded_file'; //$form = new Form_Backend_ImageUpload(); $form = new Form_Backend_FileUpload(); if ($form->is_submitted()) { $data = $form->get_values(); // Validate form and file if ($form->validate() && $file->validate_upload($data)) { // Upload file if ($file->do_upload($data)) { // Uploading succeeded $this->request->redirect(Request::current()->uri . '?flash=ok'); } } // Add model errors to form $form->errors($file->errors()); } } catch (Filemanager_Exception $e) { return $this->_widget_error($e->getMessage()); } if (isset($_GET['flash']) && $_GET['flash'] == 'ok') { $form->message('Файл загружен успешно!'); } return $form; } /** * Set up layout for actions * * @return View */ public function prepare_layout($layout_script = NULL) { $in_tinymce = $this->request->param('fm_tinymce'); if ($in_tinymce) { // Filebrowser is opened in tinyMCE popup window $layout_script = 'layouts/backend/filemanager_tinymce'; } $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('filemanager') . '/public/css/backend/filemanager.css'); return $layout; } /** * Set up file root path for action */ public function setup_root_path() { switch ($this->request->param('fm_root')) { case 'css': Model_File::set_root_path(File::normalize_path(Kohana::config('filemanager.css_root_path'))); break; case 'js': Model_File::set_root_path(File::normalize_path(Kohana::config('filemanager.js_root_path'))); break; case 'templates': Model_File::set_root_path(File::normalize_path(Kohana::config('filemanager.templates_root_path'))); break; default: Model_File::set_root_path(File::normalize_path(Kohana::config('filemanager.files_root_path'))); } } } <file_sep>/modules/shop/discounts/classes/model/coupon.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Coupon extends Model { public static $date_as_timestamp = FALSE; /** * @return string */ public function default_code() { return Text::random('alnum', 8); } /** * @return Money */ public function default_discount_sum() { return new Money(); } /** * @return float */ public function default_discount_percent() { return 0; } /** * @return integer */ public function default_valid_after() { if (self::$date_as_timestamp) { return mktime(0, 0, 0); } else { return date('Y-m-d'); } } /** * @return integer */ public function default_valid_before() { if (self::$date_as_timestamp) { return mktime(23, 59, 59); } else { return date('Y-m-d'); } } /** * Determine discount type by finding which value (sum or percent) is not zero * * @return string */ public function get_discount_type() { if (isset($this->_properties['discount_type'])) { return $this->_properties['discount_type']; } elseif ($this->discount_sum->amount > 0) { return 'sum'; } else { return 'percent'; } } /** * Get discount value (sum or percent - depends on type) * * @return float */ public function get_discount() { if (isset($this->_properties['discount'])) { return $this->_properties['discount']; } elseif ($this->discount_type == 'sum') { return $this->discount_sum->amount; } else { return $this->discount_percent; } } /** * @return string */ public function get_discount_formatted() { if ($this->discount_type == 'sum') { return $this->discount_sum->format(); } else { return $this->discount_percent . ' %'; } } /** * Return the unix-timestamp of day after which coupon is considered valid * * @return integer */ public function get_date_from() { return $this->valid_after; } /** * @return string */ public function get_date_from_formatted() { if (self::$date_as_timestamp) { return l10n::date(Kohana::config('date.format'), $this->date_from); } else { return l10n::date_convert($this->date_from, '%Y-%m-%d', Kohana::config('date.format')); } } /** * Return the unix-timestamp of day before which coupon is considered valid * * @return integer */ public function get_date_to() { return $this->valid_before; } /** * @return string */ public function get_date_to_formatted() { if (self::$date_as_timestamp) { return l10n::date(Kohana::config('date.format'), $this->date_to); } else { return l10n::date_convert($this->date_to, '%Y-%m-%d', Kohana::config('date.format')); } } /** * Set the day from which coupon is valid * * @param integer $value [!]unix-timestamp */ public function set_date_from($value) { $this->valid_after = $value; } /** * Set the day before which coupon is valid * * @param integer $value [!]unix-timestamp */ public function set_date_to($value) { if (self::$date_as_timestamp) { $this->valid_before = $value + 24*60*60 - 1; } else { $this->valid_before = $value; } } /** * @return string */ public function get_description_short() { return Text::limit_chars($this->description, 63, '...'); } /** * @return string */ public function get_type() { return ($this->multiple ? 'многоразовый' : 'одноразовый'); } /** * Get the coupon user (if this coupon is personal) * * @return Model_User */ public function get_user() { $user = new Model_User(); $user->find((int) $this->user_id); return $user; } /** * Get sites this coupon is valid in * * @return array array(site_id => TRUE/FALSE) */ public function get_sites() { if ( ! isset($this->_properties['sites'])) { $result = array(); if ( ! isset($this->id)) { // For new coupon all sites are selected /* $sites = Model::fly('Model_Site')->find_all(); foreach ($sites as $site) { $result[$site->id] = 1; } */ // Select current site for new coupon if (Model_Site::current()->id !== NULL) { $result[Model_Site::current()->id] = 1; } } else { $sites = Model_Mapper::factory('CouponSite_Mapper')->find_all_by_coupon_id($this, (int) $this->id, array('columns' => array('site_id'), 'as_array' => TRUE) ); foreach ($sites as $site) { $result[$site['site_id']] = 1; } } $this->_properties['sites'] = $result; } return $this->_properties['sites']; } /** * Validate values * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { // date range if ( ! isset($newvalues['date_from']) || ! isset($newvalues['date_to'])) { $this->error('Вы не указали срок действия купона!', 'date_from'); return FALSE; } if ( self::$date_as_timestamp && ($newvalues['date_to'] < $newvalues['date_from']) || ! self::$date_as_timestamp && (l10n::timestamp('%Y-%m-%d', $newvalues['date_to']) < l10n::timestamp('%Y-%m-%d', $newvalues['date_from'])) ) { $this->error('Дата конца срока не может быть меньше даты начала!', 'date_to'); return FALSE; } // discount amount if ( ! isset($newvalues['discount']) || ! isset($newvalues['discount_type'])) { $this->error('Вы не указали скидку!', 'discount'); return FALSE; } if ($newvalues['discount_type'] == 'percent' && $newvalues['discount'] > 100.0) { $this->error('Скидка не может быть больше 100%!', 'discount'); return FALSE; } return TRUE; } /** * Save coupon * * @param boolean $force_create * @return integer */ public function save($force_create = FALSE) { if ($this->discount_type == 'sum') { $this->discount_percent = 0; $this->discount_sum->amount = $this->discount; } else { $this->discount_percent = $this->discount; $this->discount_sum->amount = 0; } parent::save($force_create); // Mark sites selected for this coupon Model_Mapper::factory('CouponSite_Mapper')->link_coupon_to_sites($this, $this->sites); } }<file_sep>/modules/shop/catalog/classes/model/propertysection.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PropertySection extends Model { /** * Get "active" property * * @return boolean */ public function get_active() { if ($this->system) { // System properties are always active return 1; } else { return $this->_properties['active']; } } /** * Set "active" property * * @param <type> $value */ public function set_active($value) { // System properties are always active if ($this->system) { $value = 1; } $this->_properties['active'] = $value; } /** * Link given property to sections * * @param Model_Property $property * @param array $propsections */ public function link_property_to_sections(Model_Property $property, array $propsections) { // Delete all info $this->delete_all_by_property_id($property->id); $propsection = Model::fly('Model_PropertySection'); foreach ($propsections as $values) { $propsection->values($values); $propsection->property_id = $property->id; $propsection->save(); } } /** * Link given section to properties * * @param Model_Section $section * @param array $propsections */ public function link_section_to_properties(Model_Section $section, array $propsections) { // Delete all info $this->delete_all_by_section_id($section->id); $propsection = Model::fly('Model_PropertySection'); foreach ($propsections as $values) { $propsection->values($values); $propsection->section_id = $section->id; $propsection->save(); } } }<file_sep>/modules/shop/catalog/classes/propertyvalue/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class PropertyValue_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('product_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('property_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('value', array('Type' => 'varchar(' . Model_Property::MAXLENGTH . ')')); } /** * Update additional property values for given product * * @param Model_Product $product */ public function update_values_for_product(Model_Product $product) { foreach ($product->properties as $property) { $name = $property->name; $value = $product->__get($name); if ($value === NULL) continue; $where = DB::where('product_id', '=', (int) $product->id) ->and_where('property_id', '=', (int) $property->id); if ($this->exists($where)) { $this->update(array('value' => $value), $where); } else { $this->insert(array( 'product_id' => (int) $product->id, 'property_id' => (int) $property->id, 'value' => $value )); } } } }<file_sep>/modules/shop/catalog/classes/form/backend/productslink.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_ProductsLink extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "lb100px w500px"); $this->layout = 'wide'; $options = array( 'link' => 'Привязать', 'link_main' => 'Привязать как основной', 'unlink' => 'Отвязать' ); $element = new Form_Element_RadioSelect('mode', $options, array('label' => 'Действие')); $element->default_value = 'link'; $this->add_component($element); // ----- Section_id $sectiongroups = Model::fly('Model_SectionGroup')->find_all_by_site_id(Model_Site::current()->id, array('columns' => array('id', 'caption'))); foreach ($sectiongroups as $sectiongroup) { $sections = Model::fly('Model_Section')->find_all_by_sectiongroup_id($sectiongroup->id, array( 'order_by' => 'lft', 'desc' => FALSE, 'columns' => array('id', 'rgt', 'lft', 'level', 'caption') )); $options = array(0 => '---'); foreach ($sections as $section) { $options[$section->id] = str_repeat('&nbsp;', ($section->level - 1) * 3) . Text::limit_chars($section->caption, 30); } $element = new Form_Element_Select('section_ids[' . $sectiongroup->id . ']', $options, array('label' => $sectiongroup->caption, 'required' => TRUE)); $element ->add_validator(new Form_Validator_InArray(array_keys($options), array( Form_Validator_InArray::NOT_FOUND => 'Вы не указали ' . $sectiongroup->caption ))); $this->add_component($element); } // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Выполнить'), array('class' => 'button_accept') )); } } <file_sep>/modules/shop/catalog/classes/form/backend/section.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Section extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "wide lb100px"); // "general" tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $tab->add_component($cols); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Заголовок', 'required' => TRUE), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $cols->add_component($element); // ----- web_import_id $element = new Form_Element_Input('web_import_id', array('label' => 'ID импорта из web'), array('maxlength' => 31)); $element ->add_filter(new Form_Filter_TrimCrop(31)); $cols->add_component($element); // ----- Parent_id $params = array('order_by' => 'lft', 'desc' => FALSE); { $sections = $this->_model->find_all_but_subtree_by_sectiongroup_id($this->model()->sectiongroup_id, $params); } $options = array(0 => '---'); foreach ($sections as $section) { $options[$section->id] = str_repeat('&nbsp;', ((int)$section->level - 1) * 2) . Text::limit_chars($section->caption, 30); } $element = new Form_Element_Select('parent_id', $options, array('label' => 'Родитель', 'required' => TRUE)); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- Active $cols->add_component(new Form_Element_Checkbox('section_active', array('label' => 'Активный'))); // ----- Properties grid $x_options = array('active' => 'Акт.', 'filter' => 'Фильтр', 'sort' => 'Сорт.'); $y_options = array(); $properties = Model::fly('Model_Property')->find_all_by_site_id(Model_Site::current()->id, array( 'order_by' => 'position', 'desc' => FALSE )); foreach ($properties as $property) { $y_options[$property->id] = $property->caption; } $element = new Form_Element_CheckGrid('propsections', $x_options, $y_options, array('label' => 'Характеристики событий в разделе')); $element->config_entry = 'checkgrid_capt'; $cols->add_component($element); // ----- Section logo if ($this->model()->id !== NULL) { $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = '<div class="content_caption">Логотип раздела</div>' . Request::current()->get_controller('images')->widget_image('section', $this->model()->id, 'section'); $cols->add_component($element, 2); } // ----- "description" tab $tab = new Form_Fieldset_Tab('description_tab', array('label' => 'Описание')); $this->add_component($tab); // ----- Description $tab->add_component(new Form_Element_Wysiwyg('description', array('label' => 'Описание раздела'))); // ----- "SEO" tab $tab = new Form_Fieldset_Tab('seo_tab', array('label' => 'SEO')); $this->add_component($tab); // ----- URL alias $element = new Form_Element_Input('alias', array('label' => 'Имя в URL'), array('maxlength' => 31)); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_Regexp('/^\s*[\w-]+\s*$/', array( Form_Validator_Alnum::NOT_MATCH => 'Имя раздела в URL содержит недопустимые символы! Разрешается использовать только английские буквы, цифры и символы "_" и "-".' ), TRUE, TRUE )) ->add_validator(new Form_Validator_Regexp('/^(?!\d+$)/', array( Form_Validator_Regexp::NOT_MATCH => 'Имя раздела в URL не может быть числом' ), TRUE, TRUE )); $element->comment = 'Имя раздела в URL'; $element->disabled = TRUE; $tab->add_component($element); // ----- Title $element = new Form_Element_Textarea('meta_title', array('label' => 'Метатег title'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $tab->add_component($element); // ----- Description $element = new Form_Element_Textarea('meta_description', array('label' => 'Метатег description'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $tab->add_component($element); // ----- Keywords $element = new Form_Element_Textarea('meta_keywords', array('label' => 'Метатег keywords'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $tab->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } }<file_sep>/modules/frontend/views/frontend/form.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="simple_panel"> <?php if (isset($caption)) { echo '<div class="simple_panel_caption">' . $caption . '</div>'; } ?> <?php echo $form->render(); ?> </div><file_sep>/modules/shop/acl/classes/auth.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Authentication & authorization * * @package Eresus * @author <NAME> (<EMAIL>) */ class Auth { /** * @var Auth */ protected static $_instance; /** * @return Auth */ public static function instance() { if (self::$_instance === NULL) { self::$_instance = new Auth(); } return self::$_instance; } /** * Is current user allowed to do $privilege? * * @param string $privilege * @return boolean */ public static function granted($privilege) { return self::instance()->get_user()->granted($privilege); } /** * Current authenticated user * @var Model_User */ protected $_user; /* * Login errors and messages */ protected $_messages; /** * Gets all available privileges * * @return array */ public function privileges() { return self::instance()->get_user()->group->privileges(); } /** * Gets current authenticated user * * @return Model_User */ public function get_user() { if ($this->_user === NULL) { $user = new Model_User(); // Try the login from session $login = Session_Native::instance()->get('login'); if ($login !== NULL) { $user->find_by_email($login); // Invalid login stored in session - destroy session, reset user to anonymous if ($user->id === NULL) { Session_Native::instance()->destroy(); $user->init(); } } if ($user->id === NULL) { // Try autologin via cookie $token_str = Cookie::get('login_token', ''); if ($token_str != '') { $token = Model::fly('Model_Token')->find_by_token_and_type($token_str, Model_Token::TYPE_LOGIN); if (isset($token->id)) { $user->find($token->user_id); if (isset($user->id)) { // User was succesfully found - regenerate token $token->delete(); $token = $user->generate_token(Model_Token::TYPE_LOGIN); Cookie::set('login_token', $token->token, Model_Token::LOGIN_LIFETIME); // and store user login in session Session_Native::instance()->set('login', $user->email); } else { // Invalid token $token->delete(); Cookie::set('login_token', NULL); } } else { // Invalid token string Cookie::set('login_token', NULL); } } } $this->_user = $user; } return $this->_user; } /** * Peforms a login attempt */ public function login($login, $password, $remember = FALSE) { $user = new Model_User(); // Try to find user by login specified $user->find_by_email($login); if ($user->id === NULL) { // Invalid login $this->error('Пользователя с указанным email не существует!', 'email'); return FALSE; } // Check password if ($this->calculate_hash($password, $this->get_salt($user->hash)) !== $user->hash) { // Invalid password $this->error('Пароль указан неверно!', 'password'); return FALSE; } if (!$user->active) { // Not active user $this->error('Доступ пользователя на портал ограничен!'); return FALSE; } // Login succeded! $user->complete_login(); // Save user to session Session_Native::instance()->set('login', $user->email); if ($remember) { // Enable autologin via cookie $token = $user->generate_token(Model_Token::TYPE_LOGIN); Cookie::set('login_token', $token->token, Model_Token::LOGIN_LIFETIME); } $this->_user = $user; return TRUE; } /** * Forces user to be current authenticated * * @param Model_User $user */ public function set_authenticated(Model_User $user) { $this->_user = $user; // Save to session Session_Native::instance()->set('login', $user->email); } /** * Log user out, destroy the session, disable autologin */ public function logout() { // Destroy session Session_Native::instance()->destroy(); // Delete all login tokens Model::fly('Model_Token')->delete_all_by_user_id_and_type((int) $this->get_user()->id, Model_Token::TYPE_LOGIN); Cookie::set('login_token', NULL); // Reset user $this->get_user()->init(); } /** * Calculate hash from password using existing or generated salt. * * @param string $password * @param string $salt FALSE to generate new salt seed * @return string */ public function calculate_hash($password, $salt = FALSE) { if ($salt === FALSE) { // Generate salt $salt = substr($this->hash(uniqid(NULL, TRUE)), 0, 4); } $hash = $this->hash($password . $salt); // Append salt to hash return $hash . ':' . $salt; } /** * Get salt from password hash * * @param string $hash * @return string */ public function get_salt($hash) { return substr(strstr($hash, ':'), 1); } /** * Hash function * * @param string $str * @return string */ public function hash($str) { return hash('sha1', $str); } // ------------------------------------------------------------------------- // Errors & messages // ------------------------------------------------------------------------- /** * Add a message (error, warning) to this model * * @param string $text * @param string $field * @param integer $type * @return Model */ public function message($text, $field = NULL, $type = FlashMessages::MESSAGE) { $this->_messages[] = array( 'text' => $text, 'field' => $field, 'type' => $type ); return $this; } /** * Add an error to this model * * @param string $text * @param string $field * @return Model */ public function error($text, $field = NULL) { return $this->message($text, $field, FlashMessages::ERROR); } /** * Get all model errors at once * * @return array */ public function errors() { $errors = array(); foreach ($this->_messages as $message) { if ($message['type'] == FlashMessages::ERROR) { $errors[] = $message; } } return $errors; } /** * Does this model have errors? * * @return boolean */ public function has_errors() { foreach ($this->_messages as $message) { if ($message['type'] == FlashMessages::ERROR) { return TRUE; } } return FALSE; } private function __construct() { } } <file_sep>/application/classes/view.php <?php defined('SYSPATH') or die('No direct script access.'); /** * View * Extends Kohana_View with filters & placeholders * * @package Eresus * @author <NAME> (<EMAIL>) */ class View extends Kohana_View { /** * View filters * @var array */ protected $_filters = array(); /** * @var array */ protected $_placeholders = array(); /** * Register view filter * * @param View_Filter|string $filter Filter class name or filter instance */ public function add_filter($filter) { $this->_filters[] = $filter; } /** * Register several view filters at once * * @param array $filters */ public function add_filters(array $filters) { $this->_filters += $filters; } /** * Render placeholder (actually renders special string, that will be replaced with placeholder content after view rendering) * * @param string $name * @return string */ public function placeholder($name) { if ( ! isset($this->_placeholders[$name])) { $this->_placeholders[$name] = ''; } return '{{placeholder-' . $name . '}}'; } /** * Replace placeholders in view output * * @param string $output */ public function replace_placeholders(& $output) { foreach (array_keys($this->_placeholders) as $name) { $output = str_replace('{{placeholder-'.$name.'}}', $this->render_placeholder($name), $output); } } /** * Render placeholder * * @param string $name * @return string */ public function render_placeholder($name) { $content = $this->get_placeholder($name); if ($content === NULL) { $content = ''; } return $content; } /** * Set placeholder content * * @param string $name * @param string $content */ public function set_placeholder($name, $content) { $this->_placeholders[$name] = $content; } /** * Get placeholder content * * @param string $name * @return string */ public function get_placeholder($name) { if (isset($this->_placeholders[$name])) { return $this->_placeholders[$name]; } else { return NULL; } } /** * Renders the view object to a string. Global and local data are merged * and extracted to create local variables within the view file. * * Note: Global variables with the same key name as local variables will be * overwritten by the local variable. * * @throws View_Exception * @param view filename * @return string */ public function render($file = NULL) { // Run before_render() for registered filters in reverse order if ( ! empty($this->_filters)) { end($this->_filters); do { $filter = current($this->_filters); if (is_string($filter)) { // filter is a name of the class - create filter instance $filter = new $filter; $k = key($this->_filters); $this->_filters[$k] = $filter; } $filter->before_render(); } while (prev($this->_filters)); } // Render view $this->set('view', $this); $output = parent::render($file); // Replace placeholders $this->replace_placeholders($output); // Render widgets $output = $this->_render_widgets($output); // Replace basic macroses $output = str_replace( array('{{base_url}}', '{{base_uri}}'), array(URL::base(TRUE, TRUE), URL::base()), $output ); // Run after_render() for registered filters foreach ($this->_filters as $filter) { $filter->after_render($output); } return $output; } /** * Render widgets in content. * Macros format for widget is: * $(widget:controller:action:param1:param2:param2) * * @param string $output * @return string */ protected function _render_widgets($output) { if (strpos($output, '$(widget:') !== FALSE) { // Search for widget macroses $output = preg_replace_callback('/\$\(widget:(\w+):(\w+)(:([^\)]+))?\)/i', array($this, '_render_widget'), $output); } return $output; } /** * Callback for widget rendering * * @param array $matches * @return string */ protected function _render_widget($matches) { $controller = $matches[1]; $widget = $matches[2]; if ( ! empty($matches[4])) { $args = explode(':', $matches[4]); } else { $args = NULL; } return Widget::render_widget_with_args($controller, $widget, $args); } }<file_sep>/modules/shop/acl/classes/form/frontend/login.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Login extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/forms/login'; // ----- Login $element = new Form_Element_Input('email', array('label' => 'E-mail', 'required' => TRUE), array('maxlength' => 63,'placeholder' => ' E-mail') ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Email()); $this->add_component($element); // ----- Password $element = new Form_Element_Password('password', array('label' => 'Пароль', 'required' => TRUE), array('maxlength' => 255,'placeholder' => 'Пароль') ); $element ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_StringLength(0,255)); $this->add_component($element); // ----- Remember $this->add_component(new Form_Element_Checkbox('remember', array('label' => 'Запомнить'))); // ----- Form buttons $button = new Form_Element_Button('submit_login', array('label' => 'Вход'), array('class' => 'button_login button-modal') ); $this->add_component($button); parent::init(); } }<file_sep>/modules/system/tasks/classes/controller/tasks.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Tasks extends Controller { /** * Exectute the task */ public function action_execute() { if ( ! Kohana::$is_cli) { throw new Kohana_Exception('Tasks can be executed only from command line'); } $task = $this->request->param('task'); if ( ! preg_match('/^\w+$/', $task)) { throw new Kohana_Exception('Invalid task name :task', array(':task' => $task)); } TaskManager::execute($task); } }<file_sep>/modules/shop/orders/classes/model/ordercomment.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_OrderComment extends Model { /** * Back up properties before changing (for logging) */ public $backup = TRUE; /** * @return integer */ public function default_user_id() { return Auth::instance()->get_user()->id; } /** * @return string */ public function default_user_name() { return Auth::instance()->get_user()->name; } // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- /** * Save model and log changes * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); $this->log_changes($this, $this->previous()); } /** * Delete ordercomment */ public function delete() { $id = $this->id; //@FIXME: It's more correct to log AFTER actual deletion, but after deletion we have all model properties reset $this->log_delete($this); parent::delete(); } /** * Log order comment changes * * @param Model_OrderComment $new_ordercomment * @param Model_OrderComment $old_ordercomment */ public function log_changes(Model_OrderComment $new_ordercomment, Model_OrderComment $old_ordercomment) { $text = ''; $created = ! isset($old_ordercomment->id); $has_changes = FALSE; if ($created) { $text .= '<strong>Добавлен комментарий к заказу № {{id-' . $new_ordercomment->order_id . "}}</strong>\n"; } else { $text .= '<strong>Изменён комментарий к заказу № {{id-' . $new_ordercomment->order_id . "}}</strong>\n"; } // ----- text if ($created) { $text .= Model_History::changes_text('Текст', $new_ordercomment->text); } elseif ($old_ordercomment->text != $new_ordercomment->text) { $text .= Model_History::changes_text('Текст', $new_ordercomment->text, $old_ordercomment->text); $has_changes = TRUE; } // ----- notify_client if ($created) { $text .= Model_History::changes_text('Оповещать клиента', $new_ordercomment->notify_client ? 'да' : 'нет'); } elseif ($old_ordercomment->notify_client != $new_ordercomment->notify_client) { $text .= Model_History::changes_text('Оповещать клиента', $new_ordercomment->notify_client ? 'да' : 'нет', $old_ordercomment->notify_client ? 'да' : 'нет' ); $has_changes = TRUE; } if ($created || $has_changes) { // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $new_ordercomment->order_id; $history->item_type = 'order'; $history->save(); } } /** * Log the deletion of ordercomment * * @param Model_OrderComment $ordercomment */ public function log_delete(Model_OrderComment $ordercomment) { $text = 'Удалён комментарий "' . $ordercomment->text . '" к заказу № {{id-' . $ordercomment->order_id . '}}'; // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $ordercomment->order_id; $history->item_type = 'order'; $history->save(); } }<file_sep>/modules/shop/acl/public/js/backend/organizers_form.js /** * Sections select callback (called from section select iframe) */ function on_organizers_select(organizer_ids) { if ( ! on_organizers_select_url) return; // Peform an ajax request to redraw form "additional sections" elements if (organizer_ids.length) { organizer_ids = organizer_ids.join('_'); } else { // dummy value when no ids are selected organizer_ids = '_'; } var url = on_organizers_select_url .replace('{{organizer_ids}}', organizer_ids); $('#' + organizers_fieldset_ids).html('Loading...'); $.get(url, null, function(response){ // Redraw "additional sections" fieldset if (response) { $('#' + organizers_fieldset_ids).html(response); } }); } <file_sep>/modules/shop/catalog/views/frontend/products/product_images.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($images->valid()) { $image_url = URL::self(array('image_id' => '{{image_id}}')); // First image - big $image = $images[$image_id]; echo '<a href="' . $image->url(1) . '" target="_blank">' . HTML::image($image->uri(2), array( 'alt' => $product->caption, 'width' => $image->width2, 'height' => $image->height2 )) . '</a>' . '<br clear="all">'; if (count($images) > 1) { foreach ($images as $image) { $_url = str_replace('{{image_id}}', $image->id, $image_url); // Small thumbnails echo '<a href="' . $_url . '" class="ajax">' . HTML::image($image->uri(4), array('class' => ($image->id == $image_id ? 'active' : NULL), 'alt' => $product->caption)) . '</a>'; } } } ?> <file_sep>/modules/shop/catalog/classes/task/import/web.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Abstract base class for a task, which is supposed to grap info from web sites */ abstract class Task_Import_Web extends Task { /** * Temporary directory to store downloaded images and other files * @var string */ protected $_tmp_dir; /** * Base url, used by _get method * @var string */ protected $_base_url; /** * Construct task * * @param string $base_url * @param string $tmp_dir */ public function __construct($base_url, $tmp_dir = NULL) { parent::__construct(); $this->_base_url = $base_url; if ($tmp_dir === NULL) { // Build tmp directory from class name $tmp_dir = strtolower(get_class($this)); if (strpos($tmp_dir, 'task_') === 0) $tmp_dir = substr($tmp_dir, strlen('task_')); $tmp_dir = TMPPATH . '/' . $tmp_dir; } if ( ! is_dir($tmp_dir)) { mkdir($tmp_dir, 0777); } $this->_tmp_dir = $tmp_dir; } /** * Set/get base url * * @param string $base_url * @return string */ public function base_url($base_url = NULL) { if ($base_url !== NULL) { $this->_base_url = trim($base_url, ' /\\'); } return $this->_base_url; } /** * Decode html entities and trim whitespaces (including non-breakable) from string * * @param string $encoded * @param integer $maxlength * @return string */ public function decode_trim($encoded, $maxlength = 0) { $encoded = html_entity_decode($encoded); $encoded = trim($encoded, " \t\n\r\0\x0B\xA0"); if ($maxlength) { $encoded = UTF8::substr($encoded, 0, $maxlength); } return $encoded; } /** * GET the contencts of the specified url * * @param string $url * @param boolean iconv Convert the result to UTF-8 */ public function get($url, $iconv = TRUE) { static $ch; if ($ch === NULL) { $ch = curl_init(); } if ($url[0] == '/') { $url = $this->_base_url . $url; } $url = str_replace(' ', '%20', $url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //timeout in seconds /* curl_setopt($ch, CURLOPT_PROXY, '192.168.20.99'); curl_setopt($ch, CURLOPT_PROXYPORT, '8080'); */ $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Check if any error occured if(curl_errno($ch)) { throw new Kohana_Exception('cURL : ' . curl_error($ch)); } //curl_close($ch); if (($code == 200) && ($response !== FALSE)) { if ($iconv) { // Try to detect character set from <meta> header $encoding = ''; if (preg_match('!<meta[^>]*charset=([\w-]+)!i', $response, $matches)) { $encoding = $matches[1]; $response = iconv($encoding, 'UTF-8', $response); } else { throw new Kohana_Exception('Unable to detect response encoding ... '); } } return $response; } else { return FALSE; } } /** * Download the file pointed by url to the specified path * If $local_path is not specified, than it's obtained from * the * * @param string $url * @param string $local_path * @return full path to downloaded file | FALSE on failure */ public function download($url, $local_path = NULL) { $data = $this->get($url, FALSE); if ($data) { if ( ! isset($local_path)) { $local_path = TMPPATH . '/' . basename($url); } file_put_contents($local_path, $data); return $local_path; } else { return FALSE; } } /** * Download file only if local file with the same name doesn't exist or is not readable * * @param string $url * @param string $local_path * @return full path to downloaded file | FALSE on failure */ public function download_cached($url, $local_path = NULL) { if ( ! isset($local_path)) { $local_path = $this->_tmp_dir . '/' . basename($url); } if (is_readable($local_path)) return $local_path; return $this->download($url, $local_path); } }<file_sep>/modules/shop/catalog/views/frontend/products/administrator_nav.php <?php defined('SYSPATH') or die('No direct script access.'); $provider = $product->get_telemost_provider(); $isButton = false; if ($provider == Model_Product::COMDI) { $connectUrl = URL::to('frontend/catalog/product/fullscreen', array('alias' => $product->alias)); $endUrl = URL::site($product->uri_frontend(NULL,Model_Product::STOP_STAGE)); } else if ($provider == Model_Product::HANGOTS) { if (!empty($product->hangouts_url)) { $connectUrl = base64_decode($product->hangouts_url); } else { $isButton = true; $connectUrl = ''; } $endUrl = URL::site($product->uri_frontend(NULL,Model_Product::STOP_STAGE)); // Hangouts test $startTestUrl = 'https://plus.google.com/hangouts/_?gid=1085528649580&gd=zzzzzTESTzzzzz'.$product->hangouts_test_secret_key; $connectTestUrl = base64_decode($product->hangouts_test_url); } ?> <?php switch ($stage) { case Model_Product::ACTIVE_STAGE: ?> <a href="<?php echo $connectUrl; ?>" class="go-link button" target="_blank">Подключиться</a> <?php break; case Model_Product::START_STAGE: // Set hangouts test url if($connectTestUrl) echo '<a href="',$connectTestUrl,'" class="go-link button" target="_blank" style="vertical-align: top">Войти в тест</a>'; else echo '<a href="',$startTestUrl,'" class="request-link button" target="_blank" style="vertical-align: top">Начать тест</a>'; ?> <?php if($isButton): ?> <div id="hangouts-button"></div> <script src="https://apis.google.com/js/platform.js"></script> <script> (function() { gapi.hangout.render('hangouts-button', { 'render': 'createhangout', 'initial_apps': [{'app_id' : '1085528649580', 'start_data' : '<?php echo $product->hangouts_secret_key; ?>', 'app_type' : 'ROOM_APP' }], 'hangout_type': 'onair', 'widget_size': 175 // 136, 72 }); })(); </script> <?php else: ?> <a href="<?php echo $connectUrl; ?>" class="go-link button" target="_blank">Подключиться</a> <?php endif; ?> <a href="<?php echo $endUrl ?>" style="vertical-align: top" class="request-link button">Закончить</a> <?php break; } ?> <file_sep>/modules/general/nodes/classes/form/backend/node.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Node extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "wide w500px lb100px"); // ----- "general" tab $tab = new Form_Fieldset_Tab('general', array('label' => 'Свойства')); $this->add_component($tab); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Заголовок', 'required' => TRUE), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $tab->add_component($element); // ----- Menu_caption $element = new Form_Element_Input('menu_caption', array('label' => 'Заголовок в меню'), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)); $tab->add_component($element); // ----- Parent_id $params = array('order_by' => 'lft', 'desc' => FALSE); { $nodes = $this->model()->find_all_but_subtree_by_site_id(Model_Site::current()->id, $params); } $options = array(0 => '---'); foreach ($nodes as $node) { $options[$node->id] = str_repeat('&nbsp;', ((int)$node->level - 1) * 2) . Text::limit_chars($node->caption, 30); } $element = new Form_Element_Select('parent_id', $options, array('label' => 'Родитель', 'required' => TRUE, 'layout' => 'wide') ); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $tab->add_component($element); // ----- Node type $node_types = Model_Node::node_types(); $options = array(); foreach ($node_types as $type => $info) { $options[$type] = $info['name']; } $element = new Form_Element_Select('new_type', $options, array('label' => 'Модуль', 'required' => TRUE, 'layout' => 'wide') ); $element->default_value = $this->model()->type; $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $tab->add_component($element); // ----- Layout // Select all *.php files from APPPATH/views/layouts directory $options = array(); $templates = glob(APPPATH . '/views/layouts/*.php'); foreach ($templates as $template) { $template = basename($template, '.php'); $options[$template] = $template; } $element = new Form_Element_Select('layout', $options, array('label' => 'Шаблон', 'required' => TRUE, 'layout' => 'wide') ); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $tab->add_component($element); // ----- URL alias $element = new Form_Element_Input('alias', array('label' => 'Имя в URL'), array('maxlength' => 31)); $element ->add_filter(new Form_Filter_TrimCrop(31)); // ->add_validator(new Form_Validator_Regexp('/^\s*[\w-]+\s*$/', // array( // Form_Validator_Alnum::NOT_MATCH => 'Имя раздела в URL содержит недопустимые символы! Разрешается использовать только английские буквы, цифры и символы "_" и "-".' // ), // TRUE, TRUE // )) // ->add_validator(new Form_Validator_Regexp('/^(?!\d+$)/', // array( // Form_Validator_Regexp::NOT_MATCH => 'Имя раздела в URL не может быть числом' // ), // TRUE, TRUE // )); $element->comment = 'Имя страницы в URL'; $tab->add_component($element); // ----- Active $tab->add_component(new Form_Element_Checkbox('node_active', array('label' => 'Активная'))); /* // ----- Info about page url (only for existing pages) if ($this->_model->id !== NULL) { $url = URL::site($this->_model->uri(), TRUE); $this->add_element(new Form_Element_Text('page_address', ' Адрес страницы: <a href="' . $url . '">' . HTML::chars($url) . '</a> ')); } */ // ----- "meta" tab $tab = new Form_Fieldset_Tab('meta', array('label' => 'Мета-теги')); $this->add_component($tab); // ----- Title $element = new Form_Element_Textarea('meta_title', array('label' => 'Метатег title'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $tab->add_component($element); // ----- Description $element = new Form_Element_Textarea('meta_description', array('label' => 'Метатег description'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $tab->add_component($element); // ----- Keywords $element = new Form_Element_Textarea('meta_keywords', array('label' => 'Метатег keywords'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $tab->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } }<file_sep>/modules/shop/catalog/classes/task/comdi/base.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Abstract base class for a task, which is supposed to cooperate with comdi web service */ abstract class Task_Comdi_Base extends Task { public function default_params(array $default_params = NULL) { $default_params['key'] = Kohana::config('comdi.key'); return parent::default_params($default_params); } /** * Mapping keys from Model_Product to COMDI API * @var array */ public static $mapping = array( 'event_id' => 'event_id', 'caption' => 'name', 'datetime' => 'time', 'description' => 'description', 'access' => 'access', 'numviews' => 'maxAllowedUsers', 'role' => 'role', 'username' => 'username', 'email' => 'email', ); public static function mapping(array $values) { foreach (self::$mapping as $key => $value) { if (!isset($values[$key])) continue; switch ($key) { case 'datetime': //$t = new DateTime(); //$t->setTimezone(new DateTimeZone("Europe/Moscow")); //var_dump($t); //die(); $data[$value] = $values[$key]->getTimeStamp()+ $values[$key]->getOffset(); break; case 'description': $filter = new Form_Filter_Crop(100); $data[$value] = $filter->filter($values[$key]); break; case 'event_id': $data[$value] = (int)$values[$key]; break; default: $data[$value] = $values[$key]; break; } } return $data; } /** * Temporary directory to store downloaded images and other files * @var string */ protected $_tmp_dir; /** * Base url, used by _get method * @var string */ protected $_base_url; /** * Construct task * * @param string $base_url * @param string $tmp_dir */ public function __construct($base_url, $tmp_dir = NULL) { parent::__construct(); $this->default_params(); $this->_base_url = $base_url; if ($tmp_dir === NULL) { // Build tmp directory from class name $tmp_dir = strtolower(get_class($this)); if (strpos($tmp_dir, 'task_') === 0) $tmp_dir = substr($tmp_dir, strlen('task_')); $tmp_dir = TMPPATH . '/' . $tmp_dir; } if ( ! is_dir($tmp_dir)) { mkdir($tmp_dir, 0777); } $this->_tmp_dir = $tmp_dir; } /** * Set/get base url * * @param string $base_url * @return string */ public function base_url($base_url = NULL) { if ($base_url !== NULL) { $this->_base_url = trim($base_url, ' /\\'); } return $this->_base_url; } public function send($url,array $data = array()) { //static $ch; //if ($ch === NULL) //{ $ch = curl_init(); //} if ($url[0] == '/') { $url = $this->_base_url . $url; } $url = str_replace(' ', '%20', $url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); //timeout in seconds $response = curl_exec($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Check if any error occured if(curl_errno($ch)) { return FALSE; } if (($code == 200) && ($response !== FALSE)) { $xml_response = simplexml_load_string($response); curl_close($ch); return $xml_response; } else { return FALSE; } } }<file_sep>/modules/general/gmap/classes/gmap.php <?php defined('SYSPATH') or die('No direct script access.'); class Gmap { protected static $_initialized = FALSE; protected static $_gmap = FALSE; public static function instance() { if (!self::$_initialized) { require_once Modules::path('gmap') . '/lib/GoogleMap.php'; require_once Modules::path('gmap') . '/lib/JSMin.php'; self::$_gmap = new GoogleMapAPI(); } return self::$_gmap; } protected function __construct() { // This is a static class } }<file_sep>/modules/general/filemanager/views/layouts/backend/filemanager_tinymce.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Файловый менеджер</title> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/forms.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/tables.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend_ie6.css', NULL, FALSE, 'if lte IE 6'); ?> <?php echo $view->placeholder('styles'); ?> <!-- TinyMCE popup scripts --> <?php echo HTML::script(Modules::uri('tinymce') . '/public/js/tiny_mce/tiny_mce_popup.js'); ?> <!-- File manager dialogue --> <?php echo HTML::script(Modules::uri('filemanager') . '/public/js/tiny_mce/filemanager.js'); ?> </head> <body> <div class="filemanager"> <?php echo $content; ?> </div> </body> </html><file_sep>/modules/system/forms/config/form_templates/table/fieldset.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( array( 'fieldset' => '<tr> <td colspan="2" class="fieldset"> <fieldset> <legend>{{label_text}}</legend> <div id="{{id}}"> <table class="form_table"> <tr class="empty"><td class="label_cell"></td><td class="input_cell"></td></tr> {{elements}} </table> </div> </fieldset> </td> </tr> ', 'fieldset_ajax' => '<table class="form_table"> <tr class="empty"><td class="label_cell"></td><td class="input_cell"></td></tr> {{elements}} </table> ', 'element' => '{{element}}' ), );<file_sep>/modules/shop/delivery_courier/classes/controller/backend/delivery/courier.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Delivery_Courier extends Controller_Backend_Delivery { /** * Prepare a view for update action * * @param Model $model * @param Form $form * @param array $params * @return View */ protected function _view_update(Model $model, Form $form, array $params = NULL) { $params['view'] = 'backend/delivery/courier'; $view = $this->_view('update', $model, $form, $params); // Render list of courier delivery zones $view->zones = $this->request->get_controller('courierzones')->widget_courierzones($model); return $view; } }<file_sep>/modules/shop/area/views/frontend/towns/map.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php echo Gmaps3::instance()->get_apilink();?> <!-- <script> jQuery(function($){ var gmap = document.getElementById('gmap'), list = document.getElementById('main'), shm = document.getElementsByClassName('show-map')[0], shl = document.getElementsByClassName('show-list')[0], ftr = document.getElementsByTagName('footer')[0]; $('.show-list').click(function(){ gmap.hidden = true; list.hidden = false; this.hidden = true; shm.hidden = false; $(ftr).show(); }) $('.show-map').click(function(){ gmap.hidden = false; list.hidden = true; this.hidden = true; shl.hidden = false; $(ftr).hide(); }) }) </script> --> <script type="text/javascript"> window.onload = function() { // Reference to autogenerated code <?php echo Gmaps3::instance()->get_map('gmap',$lat,$lon,$zoom);?> }; </script> <!--<p class="change-view"> <a href="#" class="button show-map" hidden>Показaть карту</a> <a href="#" class="button show-list">Показать список</a> </p>--> <div id="gmap"> </div> <div id="main" class="map" hidden> <div id="listPoint"> <div class="container"> <div class="wrapper"> <h1>Представители</h1> <div class="row-fluid"> <div class="span4"> <h2>ПЕТРОПАВЛОВСК-КАМЧАТСКИЙ</h2> <div class="el"><img src="img/img.png" class="pull-left" alt=""><p class="title">Иванов Иван</span></p> <p class="desc"> Интересы: <a href="#">интерес</a>, <a href="#">другой интерес</a>, <a href="#"> третий интерес</a>, <a href="#"> просто интерес</a> </p> </div> <div class="el"><img src="img/img.png" class="pull-left" alt=""><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> <p class="desc">Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</p></div> <div class="el"><img src="img/img.png" class="pull-left" alt=""><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> <p class="desc">Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</p></div> <div class="el"><img src="img/img.png" class="pull-left" alt=""><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> <p class="desc">Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</p></div> </div> <div class="span4"> <h2>ПЕТРОПАВЛОВСК-КАМЧАТСКИЙ</h2> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> </div> <div class="span4"> <h2>ПЕТРОПАВЛОВСК-КАМЧАТСКИЙ</h2> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> </div> </div> <h1>Площадки</h1> <div class="row-fluid"> <div class="span4"> <h2>ПЕТРОПАВЛОВСК-КАМЧАТСКИЙ</h2> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> </div> <div class="span4"> <h2>ПЕТРОПАВЛОВСК-КАМЧАТСКИЙ</h2> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> <div class="el"><p class="title">Библиотека имени Ленина</span><span class="dash">|</span><a href="#">как добраться</a></p> Петропавловск-Камчатский, ул. Краснопролетарская, д. 999, библиотечный зал.</div> </div> <div class="span4"> </div> </div> </div> </div> </div> </div><file_sep>/modules/shop/discounts/classes/form/backend/coupon.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Coupon extends Form_Backend { /** * Initialize form fields */ public function init() { // HTML class $this->attribute('class', 'w600px'); $this->layout = 'wide'; // ----- code $element = new Form_Element_Input('code', array('label' => 'Код купона', 'required' => TRUE), array('maxlength' => 8) ); $element ->add_filter(new Form_Filter_TrimCrop(8)) ->add_validator(new Form_Validator_StringLength(8, 8)) ->add_validator(new Form_Validator_Alnum(NULL, TRUE, FALSE, FALSE)); $this->add_component($element); // ----- discount $element = new Form_Element_Float('discount', array('label' => 'Скидка', 'required' => TRUE, 'layout' => 'wide') ); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Float(0, NULL, FALSE)); $this->add_component($element); $e = new Form_Element_RadioSelect('discount_type', array('percent' => '%', 'sum' => 'руб'), array('label' => '', 'render' => FALSE, 'layout' => 'inline') ); $this->add_component($e); $element->append = $e->render(); // ----- Valid date range $fieldset = new Form_Fieldset('valid', array('label' => 'Срок действия', 'required' => TRUE, 'layout' => 'wide') ); $fieldset->config_entry = 'fieldset_inline'; $this->add_component($fieldset); // ----- valid_after $element = new Form_Element_SimpleDate('date_from', array('label' => '', 'layout' => 'fieldset_inline')); $element->value_format = Model_Coupon::$date_as_timestamp ? 'timestamp' : 'date'; $element ->add_filter(new Form_Filter_Date()) ->add_validator(new Form_Validator_Date()); $element->append = ' - '; $fieldset->add_component($element); // ----- valid_before $element = new Form_Element_SimpleDate('date_to', array('label' => '', 'layout' => 'fieldset_inline')); $element->value_format = Model_Coupon::$date_as_timestamp ? 'timestamp' : 'date'; $element ->add_filter(new Form_Filter_Date()) ->add_validator(new Form_Validator_Date()); $fieldset->add_component($element); // ----- multiple $options = array(0 => 'один раз', 1 => 'не ограничено'); $element = new Form_Element_RadioSelect('multiple', $options, array('label' => 'Количество использований')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- User_id // Store user id in hidden field $element = new Form_Element_Hidden('user_id'); $this->add_component($element); if ($element->value !== FALSE) { $user_id = (int) $element->value; } else { $user_id = (int) $this->model()->user_id; } // ----- User name // User for this order $user = new Model_User(); $user->find($user_id); $user_name = ($user->id !== NULL) ? $user->name : '--- для всех пользователей ---'; $element = new Form_Element_Input('user_name', array('label' => 'Пользователь', 'disabled' => TRUE, 'layout' => 'wide'), array('class' => 'w250px') ); $element->value = $user_name; $this->add_component($element); // Button to select user $button = new Form_Element_LinkButton('select_user_button', array('label' => 'Выбрать', 'render' => FALSE), array('class' => 'button_select_user open_window') ); $button->url = URL::to('backend/acl', array('action' => 'user_select'), TRUE); $this->add_component($button); $element->append = '&nbsp;&nbsp;' . $button->render(); // ----- sites $sites = Model::fly('Model_Site')->find_all(); $options = array(); foreach ($sites as $site) { $options[$site->id] = $site->caption; } $element = new Form_Element_CheckSelect('sites', $options, array('label' => 'Магазины')); $element ->add_validator(new Form_Validator_CheckSelect(array_keys($options))); $this->add_component($element); // ----- description $element = new Form_Element_Textarea('description', array('label' => 'Описание')); $element->add_filter(new Form_Filter_Crop(1024)); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } } <file_sep>/modules/shop/discounts/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { // ----- coupons Route::add('backend/coupons', new Route_Backend( 'coupons(/<action>(/<id>)(/user-<user_id>))' . '(/order-<coupons_order>)(/desc-<coupons_desc>)(/p-<page>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'user_id' => '\d++', 'coupons_order' => '\w++', 'coupons_desc' => '[01]', 'page' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'coupons', 'action' => 'index', 'id' => NULL, 'user_id' => NULL, 'coupons_order' => 'id', 'coupons_desc' => '1', 'page' => '0', )); // ----- Add backend menu items $parent_id = Model_Backend_Menu::add_item(array( 'menu' => 'main', 'caption' => 'Акции и скидки', 'route' => 'backend/coupons', 'select_conds' => array( array('route' => 'backend/coupons'), array('route' => 'backend/specialoffers'), ), 'icon' => 'discounts' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'caption' => 'Купоны на скидку', 'route' => 'backend/coupons' )); }<file_sep>/modules/shop/catalog/classes/controller/backend/productcomments.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_ProductComments extends Controller_BackendRES { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_ProductComment'; $this->_form = 'Form_Backend_ProductComment'; $this->_view = 'backend/form'; return array( 'create' => array( 'view_caption' => 'Создание комментария к событию № :product_id' ), 'update' => array( 'view_caption' => 'Редактирование комментария к событию' ), 'delete' => array( 'view_caption' => 'Удаление комментария к событию', 'message' => 'Удалить комментарий к событию : caption?' ) ); } /** * Create layout (proxy to products controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('products')->prepare_layout($layout_script); } /** * Render layout (proxy to products controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('products')->render_layout($content, $layout_script); } /** * Prepare productcomment model for create action * * @param string|Model_ProductComment $productcomment * @param array $params * @return Model_ProductComment */ protected function _model_create($productcomment, array $params = NULL) { $productcomment = parent::_model('create', $productcomment, $params); $product_id = (int) $this->request->param('product_id'); if ( ! Model::fly('Model_Product')->exists_by_id($product_id)) { throw new Controller_BackendCRUD_Exception('Указанное событие не существует!'); } $productcomment->product_id = $product_id; return $productcomment; } /** * Renders list of product comments * * @param Model_Product $product * @return string */ public function widget_productcomments($product) { $productcomments = $product->comments; // Set up view $view = new View('backend/productcomments'); $view->product = $product; $view->productcomments = $productcomments; return $view->render(); } }<file_sep>/modules/shop/acl/classes/model/organizer/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Organizer_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('name', array('Type' => 'varchar(63)')); $this->add_column('town_id', array('Type' => 'int unsigned','Key' => 'INDEX')); $this->add_column('type', array('Type' => 'varchar(63)', 'Key' => 'INDEX')); $this->add_column('address', array('Type' => 'text')); $this->add_column('links', array('Type' => 'array')); $this->add_column('info', array('Type' => 'text')); $this->add_column('email', array('Type' => 'varchar(63)')); $this->add_column('phone', array('Type' => 'varchar(63)')); } public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } if ( ! isset($params['with_town']) || ! empty($params['with_town'])) { $table = $this->table_name(); $town_table = Model_Mapper::factory('Model_Town_Mapper')->table_name(); // Add column to query $query->select(array(DB::expr("town.name"), 'town_name')); $query->join(array($town_table, "town"), 'LEFT') ->on(DB::expr("town.id"), '=', "$table.town_id"); } return parent::find_by($model, $condition, $params, $query); } /** * Find all models by criteria and return them in {@link Models} container * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by( Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->distinct('whatever') ->from($table); } // ----- process contition if (is_array($condition) && ! empty($condition['ids'])) { // find product by several ids $query->where("$table.id", 'IN', DB::expr('(' . implode(',', $condition['ids']) . ')')); unset($condition['ids']); } // if ( ! isset($params['with_town']) || ! empty($params['with_town'])) // { // $table = $this->table_name(); // $town_table = Model_Mapper::factory('Model_Town_Mapper')->table_name(); // // // Add column to query // $query->select(array(DB::expr("town.name"), 'town_name')); // // $query->join(array($town_table, "town"), 'LEFT') // ->on(DB::expr("town.id"), '=', "$table.town_id"); // // } return parent::find_all_by($model, $condition, $params, $query); } /** * Find all organizations by part of the name * * @param Model $model * @param string $name * @param array $params * @return Models */ public function find_all_like_name(Model $model, $name, array $params = NULL) { $table = $this->table_name(); $query = DB::select_array($this->_prepare_columns($params)) ->distinct('whatever') ->from($table) ->where('name', 'LIKE', "$name%"); return $this->find_all_by($model, NULL, $params, $query); } }<file_sep>/modules/general/news/views/frontend/recent_news.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $view_url = URL::to('frontend/news', array('action'=>'view', 'id' => '{{id}}'), TRUE); ?> <!-- news list --> <?php if ( ! count($news)) // No news return; ?> <?php foreach ($news as $newsitem) : $_view_url = str_replace('{{id}}', $newsitem->id, $view_url); ?> <div class="item"> <a href="<?php echo $_view_url; ?>"> <?php echo HTML::chars($newsitem->caption); ?> </a> </div> <?php endforeach; ?> <div class="link"><a href="<?php echo URL::to('frontend/news'); ?>">Архив новостей</a></div><file_sep>/modules/shop/catalog/views/frontend/forms/product.php <?php echo $form->render_form_open();?> <a href="#" id="parsing-fill-btn">Заполнить поля автоматически</a> <?php if ($form->model()->id) { ?> <p class="title">Редактирование анонса события</p> <?php }else { ?> <p class="title">Добавление анонса события</p> <?php } ?> <?php echo $form->render_messages(); ?> <h1 class="main-title"><span>О событии</span></h1> <fieldset class="b-f-main"> <div class="b-input"><label for="i-title">Название</label><?php echo $form->get_element('caption')->render_input();?></div> <?php echo $form->get_element('caption')->render_alone_errors();?> <div class="b-input"><label for="">Лектор</label><?php echo $form->get_element('lecturer_name')->render_input();?></div> <?php echo $form->get_element('lecturer_name')->render_alone_autoload();?> <?php echo $form->get_element('lecturer_name')->render_alone_errors();?> <?php echo $form->get_element('lecturer_id')->render_input();?> <div class="b-input"><label for="">Организация</label><?php echo $form->get_element('organizer_name')->render_input();?></div> <?php echo $form->get_element('organizer_name')->render_alone_autoload();?> <?php echo $form->get_element('organizer_name')->render_alone_errors();?> <?php echo $form->get_element('organizer_id')->render_input();?> <div class="b-input"><label for="">Площадка</label><?php echo $form->get_element('place_name')->render_input();?></div> <?php echo $form->get_element('place_name')->render_alone_autoload();?> <?php echo $form->get_element('place_name')->render_alone_errors();?> <?php echo $form->get_element('place_id')->render_input();?> </fieldset> <fieldset class="b-f-date"> <div class="b-input"><label for="">Дата</label><?php echo $form->get_element('datetime')->render_input();?> </div><div class="b-select"><label for="">Длительность</label><?php echo $form->get_element('duration')->render_input();?></div> <?php echo $form->get_element('datetime')->render_alone_errors();?> <?php echo $form->get_element('duration')->render_alone_errors();?> </fieldset> <fieldset class="b-f-theme"> <div class="b-select"><label for="">Тема</label><?php echo $form->get_element('theme')->render_input();?> </div><div class="b-select"><label for="">Формат события</label><?php echo $form->get_element('format')->render_input();?></div> <?php echo $form->get_element('theme')->render_alone_errors();?> <?php echo $form->get_element('format')->render_alone_errors();?> </fieldset> <div class="b-input b-tegs"><label for=""><?php echo $form->get_element('tags')->render_label();?></label><?php echo $form->get_element('tags')->render_input();?></div> <?php echo $form->get_element('tags')->render_alone_autoload();?> <?php echo $form->get_element('tags')->render_alone_errors();?> <div class="b-txt"><label for="">О событии</label><?php echo $form->get_element('description')->render_input();?></div> <?php echo $form->get_element('description')->render_alone_errors();?> <fieldset class="b-f-image"> <div class="b-input"><?php echo $form->get_element('file')->render_label(); echo $form->get_element('file')->render_input(); ?></div> <?php echo $form->get_element('file')->render_alone_errors();?> <?php if ($form->model()->id) echo $form->get_element('images')->render_input();?> <div id="prev_<?php echo $form->get_element('file')->id?>" class="prev_container"></div> <?php echo $form->get_element('image_url')->render_input();?> </fieldset> <h1 class="main-title"><span>О трансляции</span></h1> <fieldset class="b-f-tvbridge"> <span class="title">Интерактивность</span> <div class="pull-left"> <?php echo $form->get_element('interact')->render_input();?> </div> </fieldset> <?php echo $form->get_element('interact')->render_alone_errors();?> <div class="b-txt b-require"> <label for="">Стоимость лицензии</label> <?php echo $form->get_element('price')->render_input();?> руб. &nbsp;<a class="help-pop" href="#" title="" data-placement="top" data-original-title="Если Вы планируете выдавать лицензии на трансляцию Вашего события, укажите стоимость одной лицензии.">?</a> </div> <?php echo $form->get_element('require')->render_alone_errors();?> <fieldset class="b-f-chose"> <span class="title">Количество телемостов</span> <div class="pull-left"> <?php echo $form->get_element('numviews')->render_input();?> &nbsp;<a class="help-pop" href="#" title="" data-placement="right" data-original-title="Это максимальное количество городов, в которых могут быть телемосты Вашего события. Количество телемостов нельзя будет поменять после публикации анонса. Обратите внимание: чем больше телемостов, тем меньше возможности для обратной связи.">?</a> </div> </fieldset> <?php echo $form->get_element('numviews')->render_alone_errors();?> <fieldset class="b-f-chose"> <span class="title">Кто выбирает</span> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Алгоритм (в порядке очередности заявок) - первые поданные заявки будут одобрены автоматически. Алгоритм (случайный выбор) - алгоритм выберет случайные заявки. Автор анонса - Вы сами выберете из заявок. Это нужно сделать в течение 3 дней после публикации анонса. Если вы не выберете заявки к этому сроку, заявки будут отобраны автоматически. ">?</a> <div class="pull-left"> <?php echo $form->get_element('choalg')->render_input();?> </div> </fieldset> <?php echo $form->get_element('choalg')->render_alone_errors();?> <fieldset class="b-f-chose"> <span class="title">Платформа телемоста</span> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="В случае выбора Google Hangouts возможно недокументированное поведение системы">?</a> <div class="pull-left"> <?php echo $form->get_element('telemost_provider')->render_input();?> </div> </fieldset> <?php echo $form->get_element('telemost_provider')->render_alone_errors();?> <div class="b-txt b-require"> <label for="">Требования к площадке</label> <?php echo $form->get_element('require')->render_input();?> &nbsp;<a class="help-pop" href="#" title="" data-placement="top" data-original-title="Если представителю понадобится специфическая техника или особенный зал, если вы хотите видеть определённых зрителей - эти и другие требования укажите тут.">?</a> </div> <?php echo $form->get_element('require')->render_alone_errors();?> <div class="form-action"> <?php if ($form->has_element('cancel_product')) echo $form->get_element('cancel_product')->render_input(); ?> <?php echo $form->get_element('submit_product')->render_input(); ?> </div> <?php echo $form->render_form_close();?> <file_sep>/modules/shop/acl/views/backend/user_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php list($hist_route, $hist_params) = URL::match(URL::uri_back()); $hist_params['user_id'] = '{{user_id}}'; $select_url = URL::to($hist_route, $hist_params, TRUE); $hist_params['user_id'] = 0; $no_user_url = URL::to($hist_route, $hist_params, TRUE); ?> <div id="user_select"> <?php if (isset($group)) { echo '<h3 class="group_name">' . HTML::chars($group->name) . '</h3>'; } ?> <table class="very_light_table"> <tr class="table_header"> <?php $columns = array( 'image' => 'Фото', 'email' => 'E-mail', 'name' => 'Имя', 'town_name' => 'Город' ); echo View_Helper_Admin::table_header($columns, 'acl_uorder', 'acl_udesc'); ?> </tr> <?php foreach ($users as $user) : $image_info = $user->image(4); $_select_url = str_replace('{{user_id}}', $user->id, $select_url); ?> <tr> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if ($field === 'image') { echo '<a href="' . $_select_url . '" class="user_select" id="user_' . $user->id . '">' . HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'])) . '</a></td>'; } if (isset($user->$field) && trim($user->$field) !== '') { echo '<a href="' . $_select_url . '" class="user_select" id="user_' . $user->id . '">' . HTML::chars($user->$field) . '</a>'; } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> </tr> <?php endforeach; //foreach ($users as $user) ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php if (empty($_GET['window'])) : ?> <div class="back"> <div class="buttons"> <a href="<?php echo URL::back(); ?>" class="button_adv button_cancel"><span class="icon">Назад</span></a> </div> </div> <?php endif; ?> </div><file_sep>/modules/general/flash/config/flashblocks.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // Available block names 'names' => array( 'hello' => 'Приветсвие', 'phones' => 'Контактные телефоны', 'flash_header1' => 'Flash банер 1', 'flash_header2' => 'Flash банер 2', 'flash_header3' => 'Flash банер 3', 'flash_header4' => 'Flash банер 4', 'flash_header5' => 'Flash банер 5', 'ban1' => 'Верхнее меню 1', 'ban2' => 'Верхнее меню 2', 'ban3' => 'Верхнее меню 3', 'ban4' => 'Верхнее меню 4', 'sec_top' => 'Информация над списком брендов/категорий', 'order_succ' => 'Сообщение при успешном оформлении заказа', 'copyrights' => 'Копирайты', 'feed_succ' => 'Сообщение при заполнении формы обратной связи' ) );<file_sep>/application/views/pagination.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($pages_count < 2) { return; } ?> <div class="pages"> <span class="stats">Показано <?php echo "$from-$to из $count"; ?></span> <strong>Страницы:</strong> <?php if ($rewind_to_first) { if ($route === NULL) echo '<a href="' . URL::self(array($page_param => 0), $ignored_params) . '" class="rewind '. $class.'">&laquo;</a>'; else { $params[$page_param] = 0; echo '<a href="' . URL::to($route,$params) . '" class="rewind '. $class.'">&laquo;</a>'; } } for ($i = $l; $i <= $r; $i++) { if ($i == $page) { echo '<span class="active">' . ($i+1) .'</span>'; } else { if ($route === NULL) echo '<a href="' . URL::self(array($page_param => $i), $ignored_params) . '" class="'. $class.'">' . ($i+1) . '</a>'; else { $params[$page_param] = $i; echo '<a href="' . URL::to($route,$params) . '" class="'. $class.'">' . ($i+1) . '</a>'; } } } if ($rewind_to_last) { if ($route === NULL) echo '<a href="' . URL::self(array($page_param => $pages_count - 1), $ignored_params) . '" class="rewind '. $class.'">&raquo;</a>'; else { $params[$page_param] = $pages_count - 1; echo '<a href="' . URL::to($route,$params) . '" class="rewind '. $class.'">&raquo;</a>'; } } ?> </div><file_sep>/modules/shop/acl/classes/controller/backend/lecturers.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Lecturers extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Lecturer'; $this->_form = 'Form_Backend_Lecturer'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание лектора' ), 'update' => array( 'view_caption' => 'Редактирование лектора' ), 'delete' => array( 'view_caption' => 'Удаление лектора', 'message' => 'Удалить лектора ":name" ' ), 'multi_delete' => array( 'view_caption' => 'Удаление лекторов', 'message' => 'Удалить выбранных лекторов?' ) ); } /** * Create layout (proxy to acl controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Render all available section properties */ public function action_index() { $this->request->response = $this->render_layout($this->widget_lecturers()); } /** * Renders list of users * * @return string Html */ public function widget_lecturers() { $lecturer = new Model_Lecturer(); $order_by = $this->request->param('acl_lorder', 'id'); $desc = (bool) $this->request->param('acl_ldesc', '0'); $per_page = 20; // Select all users $count = $lecturer->count(); $pagination = new Paginator($count, $per_page); $lecturers = $lecturer->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); $view = new View('backend/lecturers'); $view->order_by = $order_by; $view->desc = $desc; $view->lecturers = $lecturers; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Renders list of lecturers for lecturer-select dialog * * @return string Html */ public function widget_lecturer_select($view_script = 'backend/lecturer_select') { $lecturer = new Model_Lecturer(); $order_by = $this->request->param('acl_lorder', 'id'); $desc = (bool) $this->request->param('acl_ldesc', '0'); $per_page = 20; // Select all lecturers $count = $lecturer->count(); $pagination = new Paginator($count, $per_page); $lecturers = $lecturer->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); $view = new View($view_script); $view->order_by = $order_by; $view->desc = $desc; $view->lecturers = $lecturers; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Display autocomplete options for a postcode form field */ public function action_ac_lecturer_name() { $lecturer_name = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $lecturer_name = UTF8::str_ireplace("ё", "е", $lecturer_name); if ($lecturer_name == '') { $this->request->response = ''; return; } $limit = 7; $lecturers = Model::fly('Model_Lecturer')->find_all_like_name($lecturer_name,array('limit' => $limit)); if ( ! count($lecturers)) { $this->request->response = ''; return; } $items = array(); $pattern = new View('backend/lecturer_ac'); foreach ($lecturers as $lecturer) { $name = $lecturer->name; $id = $lecturer->id; $image_info = $lecturer->image(4); $pattern->name = $name; $pattern->image_info = $lecturer->image(4); $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name, 'id' => $id) ); } $this->request->response = json_encode($items); } } <file_sep>/modules/shop/area/config/images.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // Thumbnail sizes for user photo 'place' => array( array('width' => 0, 'height' => 0), array('width' => 303, 'height' => 3030), array('width' => 498, 'height' => 338), array('width' => 50, 'height' => 50) ) );<file_sep>/modules/system/history/classes/model/history/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_History_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('created_at', array('Type' => 'int unsigned')); // type and id of the item that the history entry describes // (i.e. as "order" "10") $this->add_column('item_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('item_type', array('Type' => 'varchar(15)', 'Key' => 'INDEX')); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('user_name', array('Type' => 'varchar(255)')); $this->add_column('text', array('Type' => 'text')); } }<file_sep>/modules/system/forms/classes/form/element/checkbox/enable.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Checkbox that can enables/disables form fields * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Checkbox_Enable extends Form_Element_Checkbox { /** * Element names that are enabled/disabled by this checkbox * @var array */ protected $_dep_elements = array(); /** * Get template config entry for this element * * @return string */ public function get_config_entry() { // Use the same template as of the ordinary checkbox return 'checkbox'; } /** * Set dependent elements * * @param array $dep_elements * @return Form_Element_Checkbox_Enable */ public function set_dep_elements(array $dep_elements) { $this->_dep_elements = $dep_elements; return $this; } /** * Get dependent elements * * @return array */ public function get_dep_elements() { return $this->_dep_elements; } /** * Initialize this form element */ public function init() { // Enable/disable dependent fields according to the value foreach ($this->dep_elements as $element_name) { $element = $this->form()->get_element($element_name); $element->ignored = ! ((boolean) $this->value); } parent::init(); } /** * Render javascript for checkbox enabler * * @return string */ public function render_js() { $js = "\ne = new jFormElementCheckboxEnable('" . $this->name . "', '" . $this->id . "');\n" . "e.set_dep_elements(['" . implode("','", $this->get_dep_elements()) . "']);\n"; // Add validators foreach ($this->get_validators() as $validator) { $validator_js = $validator->render_js(); if ($validator_js !== NULL) { $js .= $validator_js . "e.add_validator(v);\n"; } } $js .= "f.add_element(e);\n"; return $js; } }<file_sep>/modules/shop/acl/classes/form/backend/link.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Link extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->layout = 'wide'; // Render using view //$this->view_script = 'backend/forms/property'; $cols = new Form_Fieldset_Columns('link'); $this->add_component($cols); // ----- caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()); $cols->add_component($element); // ----- name $element = new Form_Element_Input('name', array('label' => 'Имя', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Alnum()); $element->comment = 'Имя для внешней ссылки, состоящее из цифр и букв латинсокого алфавита для использования в шаблонах. (например: page_numbers, news_creation, ...)'; $cols->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $cols->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } }<file_sep>/modules/general/filemanager/classes/form/backend/fileupload.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_FileUpload extends Form { /** * Initialize form fields */ public function init() { // HTML class $this->attribute('class', 'w500px wide'); // ----- File upload $fieldset = new Form_Fieldset('file_upload', array('label' => 'Загрузка файла')); $this->add_component($fieldset); // ----- File $element = new Form_Element_File('uploaded_file', array('label' => 'Загрузить файл')); $element ->add_validator(new Form_Validator_File()); $element->errors_target($this); $element->set_template('<dt></dt><dd>{{label}}&nbsp;&nbsp;{{input}}&nbsp;&nbsp;'); $fieldset->add_component($element); // ----- Submit button $element = new Form_Backend_Element_Submit('submit', array('label' => 'Загрузить'), array('class' => 'button_accept') ); $element ->set_template('{{input}}</dd>'); $fieldset->add_component($element); } } <file_sep>/modules/shop/acl/classes/form/backend/privilege.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Privilege extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->layout = 'wide'; // Render using view //$this->view_script = 'backend/forms/property'; $cols = new Form_Fieldset_Columns('privilege'); $this->add_component($cols); // ----- caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()); $cols->add_component($element); // ----- Privilege type $privilege_types = Model_Privilege::privilege_types(); $options = array(); foreach ($privilege_types as $type => $info) { $options[$type] = $info['name']; } $element = new Form_Element_Select('name', $options, array('label' => 'Привилегия', 'required' => TRUE, 'layout' => 'wide') ); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- Params $element = new Form_Element_Options("options", array('label' => 'Params', 'options_count' => 1,'options_count_param' => 'options_count'), array('maxlength' => Model_Flashblock::MAXLENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Flashblock::MAXLENGTH)); $cols->add_component($element); // ----- Type /*$options = $this->model()->get_types(); $element = new Form_Element_RadioSelect('type', $options, array('label' => 'Тип')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- Options $element = new Form_Element_Options("options", array('label' => 'Возможные значения', 'options_count' => 5), array('maxlength' => Model_Property::MAXLENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Property::MAXLENGTH)); $cols->add_component($element); */ // ----- PropSections grid $x_options = array('active' => 'Акт.'); $y_options = array(); $groups = Model::fly('Model_Group')->find_all(); foreach ($groups as $group) { $y_options[$group->id] = $group->name; } $element = new Form_Element_CheckGrid('privgroups', $x_options, $y_options, array('label' => 'Настройки для групп') ); $element->config_entry = 'checkgrid_capt'; $cols->add_component($element, 2); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $cols->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } }<file_sep>/modules/shop/catalog/views/frontend/products/user_nav.php <?php defined('SYSPATH') or die('No direct script access.'); $provider = $product->get_telemost_provider(); if ($provider == Model_Product::COMDI) $choose_url = URL::to('frontend/catalog/product/fullscreen', array('alias' => $product->alias)); else if ($provider == Model_Product::HANGOTS) { $choose_url = base64_decode($product->hangouts_url); $hangouts_test_url = base64_decode($product->hangouts_test_url); } switch ($stage) { case Model_Product::ACTIVE_STAGE: break; case Model_Product::START_STAGE: if(!empty($hangouts_test_url)) echo '<a href="',$hangouts_test_url,'" class="request-link button" target="_blank">Присоединиться к тесту</a>'; if (!empty($choose_url)): ?> <a href="<?php echo $choose_url; ?>" class="request-link button" target="_blank">Присоединиться</a> <?php endif; break; } ?><file_sep>/modules/system/forms/classes/form/element/checkselect.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form select element consisting of checkboxes * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_CheckSelect extends Form_Element { /** * Select options * @var array */ protected $_options = array(); /** * Creates form select element * * @param string $name Element name * @param array $options Select options * @param array $properties * @param array $attributes */ public function __construct($name, array $options = NULL, array $properties = NULL, array $attributes = NULL) { parent::__construct($name, $properties, $attributes); $this->_options = $options; } /** * Return input type * @return string */ public function default_type() { return 'checkselect'; } /** * Set up options for select * * @param array $options * @return Form_Element_Select */ public function set_options(array $options) { $this->_options = $options; return $this; } /** * Renders select element, constiting of checkboxes * * @return string */ public function render_input() { $value = $this->value; if ( ! is_array($value)) { $value = array(); } $html = ''; foreach ($this->_options as $option => $label) { $name = "$this->full_name[$option]"; if (isset($value[$option])) { $checked = (bool) $value[$option]; } else { $checked = (bool) $this->default_selected; } if (is_array($label)) { $label = $label['label']; $disabled = ! empty($label['disabled']); } else { $disabled = FALSE; } $option_template = $this->get_template('option'); if ( ! $this->disabled && ! $disabled) { $checkbox = Form_Helper::hidden($name, '0') . Form_Helper::checkbox($name, '1', $checked, array('class' => 'checkbox')); } else { $checkbox = Form_Helper::checkbox($name, '1', $checked, array('class' => 'checkbox', 'disabled' => 'disabled')); } Template::replace($option_template, array( 'checkbox' => $checkbox, 'label' => $label )); $html .= $option_template; } return $html; } /** * No javascript for this element * * @return string */ public function render_js() { return FALSE; } } <file_sep>/modules/general/menus/classes/menunode/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class MenuNode_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('menu_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('node_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('visible', array('Type' => 'boolean')); } /** * Find menu nodes with visibility information for given menu and root node * * @param Model_Menu $menu * @param Model_Node $root_node * @param Database_Expression_Where $condition * @return ModelsTree_NestedSet|Models|array */ public function find_all_menu_nodes(Model_Menu $menu, Model_Node $root_node, Database_Expression_Where $condition = NULL) { $node_mapper = Model_Mapper::factory('Model_Node_Mapper'); $menunode_table = $this->table_name(); $node_table = $node_mapper->table_name(); $table_prefix = $this->get_db()->table_prefix(); $default_visibility = (int) $menu->default_visibility; $query = DB::select("$node_table.*", array(DB::expr("IFNULL(".$table_prefix.$menunode_table.".visible, $default_visibility)"), "visible")) ->from($node_table) ->join($menunode_table, 'LEFT') ->on("$menunode_table.node_id", '=', "$node_table.id") ->on("$menunode_table.menu_id", '=', DB::expr((int) $menu->id)); // Search only nodes from the same site as the menu if ($condition === NULL) { $condition = DB::where("$node_table.site_id", '=', (int) $menu->site_id); } else { $condition->and_where("$node_table.site_id", '=', (int) $menu->site_id); } if (isset($root_node->id)) { $condition->and_where('lft', '>', (int) $root_node->lft); $condition->and_where('rgt', '<', (int) $root_node->rgt); } $params = array('order_by' => 'lft', 'desc' => FALSE); return $node_mapper->find_all_by($root_node, $condition, $params, $query); } /** * Find visible menu nodes for given menu and root node * * @param Model_Menu $menu * @param Model_Node $root_node * @return array */ public function find_all_visible_menu_nodes(Model_Menu $menu, Model_Node $root_node) { if ($menu->default_visibility == 1) { $condition = DB::where() ->and_where_open() ->and_where('visible', '=', '1') ->or_where(DB::expr('ISNULL(`visible`)')) ->and_where_close(); } else { $condition = DB::where('visible', '=', '1'); } if ($menu->max_level > 0) { $condition->and_where('level', '<=', $root_node->level + $menu->max_level); } return $this->find_all_menu_nodes($menu, $root_node, $condition); } /** * Update information about visible nodes for menu * * @param Model_Menu $menu * @param array $nodes_visibility */ public function update_menu_nodes(Model_Menu $menu, array $nodes_visibility) { $this->delete_rows(DB::where('menu_id', '=', (int)$menu->id)); foreach ($nodes_visibility as $node_id => $visible) { if ($visible != $menu->default_visibility) { $this->insert(array( 'node_id' => $node_id, 'menu_id' => (int)$menu->id, 'visible' => $visible )); } } } }<file_sep>/modules/shop/acl/classes/model/userprop.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_UserProp extends Model { const TYPE_TEXT = 1; // Checkbox userprop const TYPE_SELECT = 2; // Userprop with value from given list of options const MAXLENGTH = 63; // Maximum length for the property value protected static $_types = array( Model_UserProp::TYPE_TEXT => 'Текст', Model_UserProp::TYPE_SELECT => 'Список опций' ); /** * Get all possible userprop types * * @return array */ public function get_types() { return self::$_types; } /** * Get text description for the type of the userprop * * @return string */ public function get_type_text() { return (isset(self::$_types[$this->type]) ? self::$_types[$this->type] : NULL); } /** * Default userprop type * * @return integer */ public function default_type() { return Model_UserProp::TYPE_TEXT; } /** * Set userprop variants * * @param array $options */ public function set_options(array $options) { $options = array_values(array_filter($options)); $this->_properties['options'] = $options; } /** * Created userprops are non-system * * @return boolean */ public function default_system() { return 0; } /** * Prohibit changing the "system" userprop * * @param boolean $value */ public function set_system($value) { //Intentionally blank } /** * @param integer $value */ public function set_type($value) { // Do not allow to change type for system userprops if ($this->system) return; $this->_properties['type'] = $value; } /** * Get user-props infos * * @return Models */ public function get_userproperties() { if ( ! isset($this->_properties['userproperties'])) { $this->_properties['userproperties'] = Model::fly('Model_UserPropUser')->find_all_by_userprop($this); } return $this->_properties['userproperties']; } /** * Get user-props infos as array for form * * @return array */ public function get_userprops() { if ( ! isset($this->_properties['userprops'])) { $result = array(); foreach ($this->userproperties as $userprop) { $result[$userprop->user_id]['active'] = $userprop->active; } $this->_properties['userprops'] = $result; } return $this->_properties['userprops']; } /** * Set user-prop link info (usually from form - so we need to add 'user_id' field) * * @param array $privgroups */ public function set_userprops(array $userprops) { foreach ($userprops as $user_id => & $userprop) { if ( ! isset($userprop['user_id'])) { $userprop['user_id'] = $user_id; } } $this->_properties['userprops'] = $userprops; } /** * Save userprop and link it to selected groups * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); // Link property to selected sections Model::fly('Model_UserPropUser')->link_userprop_to_users($this, $this->userprops); } /** * Delete privilege */ public function delete() { // Delete all user values for this privilege Model_Mapper::factory('Model_UserPropValue_Mapper')->delete_all_by_userprop_id($this, $this->id); // Delete userprop binding information Model::fly('Model_UserPropUser')->delete_all_by_userprop_id($this->id); // Delete the userprop $this->mapper()->delete($this); } /** * Validate creation/updation of userprop * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { // Check that privilege name is unque if ( ! isset($newvalues['name'])) { $this->error('Вы не указали имя!', 'name'); return FALSE; } if ($this->exists_another_by_name($newvalues['name'])) { $this->error('Свойство с таким именем уже существует!', 'name'); return FALSE; } return TRUE; } /** * Validate userprop deletion * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->system) { $this->error('Свойство является системным. Его удаление запрещено!'); return FALSE; } return parent::validate_delete($newvalues); } }<file_sep>/modules/shop/delivery_courier/classes/model/delivery/courier.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Delivery_Courier extends Model_Delivery { /** * Calculate delivery price for order * * @param Model_Order $order * @return float */ public function calculate_price(Model_Order $order) { $price = 0.0; $zone = new Model_CourierZone(); $zone->find((int) $order->zone_id); if ( ! isset($zone->id)) { $this->error('Не указана зона доставки'); return $price; } return $zone->price; } }<file_sep>/modules/general/tinymce/classes/form/element/wysiwyg.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Textarea converted to WYSIWYG editor * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Wysiwyg extends Form_Element_Textarea { /** * Use the same config entry as the simple textarea * * @return string */ public function default_config_entry() { return 'textarea'; } /** * Set form element value, replace urls macroses with actual urls * * @param <type> $value * @return Form_Element_Wysiwyg */ public function set_value($value) { parent::set_value($value); $this->_value = str_replace( array('{{base_url}}', '{{base_uri}}'), array(URL::base(TRUE, TRUE), URL::base()), $this->_value ); return $this; } /** * Replace full urls with macroses * * @return string */ public function get_value() { $value = parent::get_value(); $value = str_replace(URL::base(TRUE, TRUE), '{{base_url}}', $value); return $value; } /** * Default number of rows * * @return integer */ public function defaultattr_rows() { return 30; } /** * Renders textarea * * @return string */ public function render_input() { // Add TinyMCE scripts (scripts are added only once, which is controlled by add_scripts function) if (Modules::registered('tinymce')) { TinyMCE::add_scripts(); } $this->attribute('class', 'wysiwyg_content'); return parent::render_input(); } } <file_sep>/modules/shop/delivery_russianpost/classes/controller/backend/delivery/russianpost.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Delivery_RussianPost extends Controller_Backend_Delivery { }<file_sep>/modules/shop/catalog/classes/controller/backend/goes.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Goes extends Controller_BackendRES { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Go'; $this->_form = 'Form_Backend_Go'; $this->_view = 'backend/form'; return array( 'create' => array( 'view_caption' => 'Создание "Я пойду"' ), 'delete' => array( 'view_caption' => 'Удаление "Я пойду"', 'message' => 'Удалить "Я пойду"?' ) ); } /** * Create layout (proxy to products controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('telemosts')->prepare_layout($layout_script); } /** * Render layout (proxy to products controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('telemosts')->render_layout($content, $layout_script); } /** * Prepare telemost model for create action * * @param string|Model_Telemost $telemost * @param array $params * @return Model_Telemost */ protected function _model_create($go, array $params = NULL) { $go = parent::_model('create', $go, $params); $telemost_id = (int) $this->request->param('telemost_id'); if ( ! Model::fly('Model_Telemost')->exists_by_id($telemost_id)) { throw new Controller_BackendCRUD_Exception('Указанный телемост не существует!'); } $go->telemost_id = $telemost_id; return $go; } /** * Renders list of telemost goes * * @param Model_Telemost $telemost * @return string */ public function widget_goes($telemost) { $goes = $telemost->goes; // Set up view $view = new View('backend/goes'); $view->telemost = $telemost; $view->goes = $goes; return $view->render(); } }<file_sep>/modules/backend/classes/form/backend.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend extends Form_Model { /** * Get the form name or generate one. * * @return string */ public function default_name() { return trim(str_replace('backend', '', parent::default_name()), '_'); } }<file_sep>/modules/shop/acl/views/frontend/forms/organizer.php <div id="OrgModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Добавить организацию</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <label for="name"><?php echo $form->get_element('name')->render_input(); ?></label> <?php echo $form->get_element('name')->render_alone_errors();?> <div class="row-fluid"> <div class="span6"> <label for="town"><?php echo $form->get_element('town_id')->render_input();?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Город в котором зарегистрирована организация">?</a></label> </div> </div> <?php echo $form->get_element('town_id')->render_alone_errors();?> <div class="row-fluid"> <div class="span6"> <label for="type"><?php echo $form->get_element('type')->render_input();?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Род дейтельности организации">?</a></label> </div> </div> <?php echo $form->get_element('type')->render_alone_errors();?> <label for="info"> <?php echo $form->get_element('info')->render_input(); ?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Чем занимается организация, какие её основные достижения">?</a> </label> <?php echo $form->get_element('info')->render_alone_errors();?> <label for="links"><?php echo $form->get_element('links')->render_input(); ?></label> <?php echo $form->get_element('links')->render_alone_errors();?> <?php echo $form->get_element('file')->render_label(); echo $form->get_element('file')->render_input(); ?> <?php echo $form->get_element('file')->render_alone_errors();?> <div id="prev_<?php echo $form->get_element('file')->id?>" class="prev_container"></div><br/> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_organizer')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div> <file_sep>/modules/shop/acl/classes/model/privilege/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Privilege_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(31)')); $this->add_column('name', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('options', array('Type' => 'array')); $this->add_column('system', array('Type' => 'boolean')); } /** * Find all privileges by given condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { if (is_array($condition) && ! empty($condition['group_id'])) { // Find properties that apply to selected section $columns = $this->_prepare_columns($params); $table = $this->table_name(); $privgr_table = Model_Mapper::factory('Model_PrivilegeGroup_Mapper')->table_name(); $query = DB::select_array($columns) ->from($table) ->join($privgr_table, 'INNER') ->on("$privgr_table.privilege_id", '=', "$table.id") ->on("$privgr_table.group_id", '=', DB::expr((int) ($condition['group_id']))); if (isset($condition['active'])) { $query->and_where("$privgr_table.active", '=', $condition['active']); unset($condition['active']); } unset($condition['group']); } return parent::find_all_by($model, $condition, $params, $query); } /** * Move privilege up * * @param Model $privilege * @param Database_Expression_Where $condition */ public function up(Model $privilege, Database_Expression_Where $condition = NULL) { parent::up($privilege, DB::where('site_id', '=', $privilege->site_id)); } /** * Move property down * * @param Model $property * @param Database_Expression_Where $condition */ public function down(Model $privilege, Database_Expression_Where $condition = NULL) { parent::down($privilege, DB::where('site_id', '=', $privilege->site_id)); } }<file_sep>/modules/system/forms/config/form_templates/table/fieldset_columns.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( array( 'fieldset' => '<tr> <td colspan="2"> <table class="form_table"><tr> {{elements}} </tr></table> </td> </tr> ', 'column' => '<td class="fieldset_column {{class}} {{last}}"> <table class="form_table"> <tr class="empty"><td class="label_cell"></td><td class="input_cell"></td></tr> {{elements}} </table> </td> ', 'element' => '{{element}}' ) );<file_sep>/modules/shop/catalog/views/frontend/sections/menu_old.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="caption"> <?php echo '<a href="' . URL::site($sectiongroup->uri_frontend()) . '">' . (($sectiongroup->name == 'brand') ? 'вернуться к списку брендов' : 'вернуться к категориям') . '</a> &raquo;<br />'; ?> <div> <a href="<?php echo URL::site($root->uri_frontend()); ?>" class="section"> <?php echo HTML::chars($root->caption); ?> </a>&nbsp;: </div> </div> <?php if ($sections->has_children($root)) : ?> <div class="caption2">Подразделы:</div> <div class="navigation"><ul> <?php foreach ($sections->children($root) as $subsection) { echo '<li>' . '<a href="' . URL::site($subsection->uri_frontend()) . '"' . ($subsection->id == $current->id ? ' class="active"' : '') . '>' . HTML::chars($subsection->caption) . ($subsection->products_count > 0 ? ' (' . $subsection->products_count . ')' : '') . '</a>' . '</li>'; } ?> </ul></div> <?php endif; ?> <!-- <div class="caption2"> Товары LEGO присутствуют в категориях: </div> <div class="navigation"> <ul> <li><a href="#">Конструкторы</a></li> <li><a href="#">Настолные игры</a></li> </ul> </div> --><file_sep>/modules/shop/orders/classes/controller/frontend/orders.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Orders extends Controller_Frontend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); if ($this->request->action == 'checkout_success') { $layout->caption = 'Ваш заказ принят в обработку!'; } else { $layout->caption = 'Оформление заказа'; } Breadcrumbs::append(array('uri' => URL::uri_to('frontend/orders'), 'caption' => 'Оформление заказа')); return $layout; } /** * Checkout */ public function action_checkout() { $cart = Model_Cart::session(); $serialized = $this->request->param('cart'); if ($serialized != '') { $cart->unserialize($serialized); } if ($cart->has_errors()) { FlashMessages::add_many($cart->errors()); $this->request->redirect(URL::uri_to('frontend/cart')); } $form = new Form_Frontend_Checkout(); if ($form->is_submitted() && $form->validate()) { if ( ! count($cart->cartproducts)) { $form->error('В корзине нет товаров'); } else { $order = new Model_Order(); $order->values($form->get_values()); $order->products = $cart->cartproducts; $order->save(); $cart->clean(); // Send email notifications $order->notify(); $this->request->redirect(URL::uri_to('frontend/orders', array('action' => 'checkout_success'))); } } $view = new View('frontend/checkout'); $view->form = $form; $this->request->response = $this->render_layout($view); } /** * New order was created succesfully */ public function action_checkout_success() { $this->request->response = $this->render_layout(Widget::render_widget('blocks', 'block', 'order_succ')); } }<file_sep>/modules/general/news/classes/model/newsitem.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Newsitem extends Model { public static $date_as_timestamp = FALSE; /** * Default site id for news * * @return integer */ public function default_site_id() { return Model_Site::current()->id; } /** * Default date * * @return string */ public function default_date() { return date(Kohana::config('datetime.date_format')); } } <file_sep>/modules/general/breadcrumbs/classes/controller/frontend/breadcrumbs.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Breadcrumbs extends Controller_Frontend { /** * Renders breadcrumbs */ public function widget_breadcrumbs() { // Set up view $view = new View('frontend/breadcrumbs'); $view->breadcrumbs = Breadcrumbs::get_all(); return $view->render(); } } <file_sep>/modules/shop/catalog/public/js/frontend/product/choose.js /** * Initialize */ $(document).ready(function(){ if (current_window) { // ----- Choose product buttons $('#events_show').click(function(event){ if ($(event.target).hasClass('product_choose')) { // "Choose Product" link was pressed // Determine product alias from link "alias" attribute (alias is like 'product_somealias') var product_alias = $(event.target).attr('id').substr(8); // Peform an ajax request to get selected user var ajax_url = product_selected_url.replace('{{alias}}', product_alias); $.post(ajax_url, null, function(response) { if (response) { //@FIXME: Security breach! eval('var user = ' + response + ';'); // Execute custom actions on user selection // (there should be a corresponding function defined in parent window) if (parent.on_user_select) { parent.on_user_select(user) } // Close the window current_window.close(); } }); event.preventDefault(); } }); } });<file_sep>/modules/shop/acl/classes/model/ulogin/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Ulogin_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('network', array('Type' => 'varchar(255)')); $this->add_column('identity', array('Type' => 'varchar(255)')); } }<file_sep>/modules/shop/catalog/public/js/backend/prodplace.js /** * Change place in product form */ function on_place_select(place) { var f = jforms['product1']; if (place['id']) { f.get_element('place_id').set_value(place['id']); f.get_element('place_name').set_value(place['town']+": "+place['name']); } else { f.get_element('place_id').set_value(0); f.get_element('place_name').set_value('--- площадка не указана ---'); } }<file_sep>/modules/general/faq/classes/form/backend/faqconfig.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_FaqConfig extends Form_Backend { /** * Initialize form fields */ public function init() { $this->layout = 'wide'; $this->attribute('class', 'lb120px'); // ----- email_client $fieldset = new Form_Fieldset('email_client', array('label' => 'Оповещение клиента')); $this->add_component($fieldset); // ----- email[client][subject] $element = new Form_Element_Input('email[client][subject]', array('label' => 'Заголовок письма', 'required' => TRUE), array('maxlength' => 255) ); $element->add_filter(new Form_Filter_TrimCrop(255)); $element->add_validator(new Form_Validator_NotEmptyString()); $fieldset->add_component($element); // ----- email[client][body] $element = new Form_Element_Textarea('email[client][body]', array('label' => 'Шаблон письма'), array('rows' => 7) ); $fieldset->add_component($element); // ----- email_admin $fieldset = new Form_Fieldset('email_admin', array('label' => 'Оповещение администратора')); $this->add_component($fieldset); // ----- email[admin][subject] $element = new Form_Element_Input('email[admin][subject]', array('label' => 'Заголовок письма', 'required' => TRUE), array('maxlength' => 255) ); $element->add_filter(new Form_Filter_TrimCrop(255)); $element->add_validator(new Form_Validator_NotEmptyString()); $fieldset->add_component($element); // ----- email[admin][body] $element = new Form_Element_Textarea('email[admin][body]', array('label' => 'Шаблон письма'), array('rows' => 7) ); $fieldset->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/general/calendar/classes/calendar.php <?php defined('SYSPATH') or die('No direct script access.'); class Calendar { /** * @var boolean */ protected static $_scripts_added = FALSE; /** * Calendar instance * @var Layout */ protected static $_instance; /** * Add jQuery scripts to the layout */ public static function add_scripts() { if (self::$_scripts_added) return; $layout = Layout::instance(); $layout->add_style(Modules::uri('calendar') . '/public/css/calendar.css'); self::$_scripts_added = TRUE; } public static function instance() { if (self::$_instance === NULL) { self::add_scripts(); self::$_instance = new Base_Calendar('ru'); } return self::$_instance; } protected function __construct() { // This is a static class } }<file_sep>/modules/shop/acl/views/frontend/groups.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="groups"> <table> <tr> <td> <?php // Highlight current group if ($group_id == 0) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo URL::self(array('group_id' => (string) 0)); ?>" class="group<?php echo $selected; ?>" title="Показать всех пользователей" > <strong>Все пользователи</strong> </a> </td> <td>&nbsp;</td> <?php foreach ($groups as $group) : ?> <tr> <td> <?php // Highlight current group if ($group->id == $group_id) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo URL::self(array('group_id' => (string) $group->id)); ?>" class="group<?php echo $selected; ?>" title="Показать пользователей из группы '<?php echo HTML::chars($group->name); ?>'" > <?php echo HTML::chars($group->name); ?> </a> </td> </tr> <?php endforeach; //foreach ($groups as $group) ?> </table> </div> <file_sep>/modules/shop/catalog/classes/controller/frontend/plists.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_PLists extends Controller_Frontend { /** * Render list of product lists */ public function widget_plist($name) { $plist = new Model_PList(); $plist->find_by_name_and_site_id($name, Model_Site::current()->id); if ( ! isset($plist->id)) return ''; // Specified list not found $products = Model::fly('Model_Product')->find_all_by( array( 'plist' => $plist, 'active' => 1, ), array( 'with_sections' => TRUE, 'with_image' => 3 ) ); // sections tree $brands = Model::fly('Model_Section')->find_all_active_cached(1); $categories = Model::fly('Model_Section')->find_all_active_cached(2); $view = new View('frontend/plist'); $view->cols = 5; $view->brands = $brands; $view->categories = $categories; $view->plist = $plist; $view->products = $products; return $view->render(); } }<file_sep>/application/classes/modelstree/nestedset.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Nested set models tree * * @package Eresus * @author <NAME> (<EMAIL>) */ class ModelsTree_NestedSet extends ModelsTree { /** * Indicates whether properties array have been rebuilt to the tree structure * @var boolean */ public $tree_is_built = FALSE; /** * Return tree as structured list of models * * @return Models */ public function as_list() { // Reorder list of properties $list = array(); $this->_build_list($list); return new Models($this->_model_class, $list, $this->_pk); } /** * Get direct children of the parent node * If $parent == NULL returns top level items * * @param Model $parent * @param boolean as_array * @return Models | array */ public function children(Model $parent = NULL, $as_array = FALSE) { // convert properties to tree (if not already converted) $this->build_tree(); if ($parent === NULL) { // top-level items $parent_pk = 0; } else { $parent_pk = $parent[$this->_pk]; } $children = array(); if ( ! empty($this->_properties_array[$parent_pk]['child_ids'])) { foreach ($this->_properties_array[$parent_pk]['child_ids'] as $child_pk) { $children[$child_pk] = $this->_properties_array[$child_pk]; } } if ($as_array) { return $children; } else { return new Models($this->_model_class, $children, $this->_pk); } } /** * Get parents for the model * * @param Model $child * @param boolean $as_array * @param boolean $sort_asc Sort by level from top to bottom * @return Models | array */ public function parents(Model $child, $as_array = FALSE, $sort_asc = TRUE) { // convert properties to tree (if not already converted) $this->build_tree(); $parents = array(); $child_pk = $child[$this->_pk]; $loop_prevention = 1000; while ( ! empty($this->_properties_array[$child_pk]['parent_id']) && $loop_prevention > 0) { $child_pk = $this->_properties_array[$child_pk]['parent_id']; $parents[$child_pk] = $this->_properties_array[$child_pk]; $loop_prevention--; } if ($loop_prevention == 0) throw new Kohana_Exception ('Possible infinite loop in :method', array(':method' => __METHOD__)); if ($sort_asc) { $parents = array_reverse($parents, TRUE); } if ($as_array) { return $parents; } else { return new Models($this->_model_class, $parents, $this->_pk); } } /** * Get the ancestor for descendant * * @param Model|integer $descendant * @param integer $level * @param boolean $as_array * @return Model */ public function ancestor($descendant, $level = -1, $as_array = FALSE) { $this->build_tree(); $pk = $this->_pk; if ($descendant instanceof Model) { $lev = $descendant->level; $id = $descendant->$pk; } else { $id = $descendant; if ( ! isset($this->_properties_array[$id])) return NULL; $lev = $this->_properties_array[$id]['level']; } if ($level <= 0) { $level = $lev + $level; } if ($level > $lev) return NULL; if ($level < $lev) { // traverse the tree up, starting from $descendant do { if ( ! isset($this->_properties_array[$id])) return NULL; // $descendant not in tree / broken tree structure $id = $this->_properties_array[$id]['parent_id']; } while($this->_properties_array[$id]['level'] > $level); } if ($as_array) { return $this->_properties_array[$id]; } else { return $this[$id]; } } /** * Returns TRUE if the specified parent has children * * @return boolean */ public function has_children(Model $parent = NULL) { // convert properties to tree (if not already converted) $this->build_tree(); if ($parent === NULL) { return ( ! empty($this->_properties_array[0]['child_ids'])); } else { return ( ! empty($this->_properties_array[$parent[$this->_pk]]['child_ids'])); } } /** * Get the branch of the tree with root at $root * * @param Model $root * @return ModelsTree */ public function branch(Model $root = NULL) {} /** * Rebuild list of properties to the tree structure */ public function build_tree() { if ($this->tree_is_built) return; //$token = Profiler::start('models', 'build_tree'); $tree = & $this->_properties_array; foreach ($tree as $child) // <------------------------------| { // | if ( ! isset($child[$this->_pk])) // | continue; //root item // | // | $child_pk = $child[$this->_pk]; // | // | if ($this->root() === NULL && $this->_is_top_level($child)) // | { // | // It's a top-level item // | $tree[0]['child_ids'][] = $child_pk; // | $tree[$child_pk]['parent_id'] = 0; // | } // | elseif ($this->root() !== NULL && $this->_is_child($child, $this->root()->properties())) //| { // | // $child is a child of $root for this tree // | $tree[$this->root()->id]['child_ids'][] = $child_pk; // | $tree[$child_pk]['parent_id'] = $this->root()->id; // | } // | else // | { // | // Find parent for child // | foreach ($tree as $parent) // | { // | if ( ! isset($parent[$this->_pk])) // | continue; //root item // | // | $parent_pk = $parent[$this->_pk]; // | // | if ($this->_is_child($child, $parent)) // | { // | $tree[$parent_pk]['child_ids'][] = $child_pk; // | $tree[$child_pk]['parent_id'] = $parent_pk; // | // | continue 2; // parent found, move to the next item -----------| } } // parent was not found - an orphaned child... } } $this->tree_is_built = TRUE; $this->_properties_array = $tree; //Profiler::stop($token); } /** * Recursively build ordered list of properties for as_list() method * * @param array $list * @param array $parent ' */ protected function _build_list(array & $list, array $parent = NULL) { foreach ($this->_properties_array as $item) { if ( ! isset($item[$this->_pk])) continue; if ( $parent === NULL && $this->_is_top_level($item) || $parent !== NULL && $this->_is_child($item, $parent) ) { $list[$item[$this->_pk]] = $item; $this->_build_list($list, $item); } } } /** * Is $child a direct child of $parent ? * * @param array $child * @param array $parent * @return boolean */ protected function _is_child(array $child, array $parent) { return ( ($child['level'] == $parent['level'] + 1) && ($child['lft'] > $parent['lft']) && ($child['rgt'] < $parent['rgt']) ); } /** * Is item a top-level one? * * @param array $item * @return boolean */ protected function _is_top_level(array $item) { return ($item['level'] <= 1); } /** * If $child a descendant of $parent? * * @param Model $child * @param Model $parent * @return boolean */ public function is_descendant(Model $child, Model $parent) { return ($child->lft > $parent->lft && $child->rgt < $parent->rgt); } } <file_sep>/modules/shop/orders/classes/controller/backend/cartproducts.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_CartProducts extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_CartProduct'; $this->_form = 'Form_Backend_CartProduct'; $this->_view = 'backend/form'; return array( 'create' => array( 'view_caption' => 'Добавление товара в заказ № :order_id' ), 'update' => array( 'view_caption' => 'Редактирование товара в заказе' ), 'delete' => array( 'view_caption' => 'Удаление товара из заказа', 'message' => 'Удалить товар из заказа № :order_id?' ) ); } /** * Create layout (proxy to orders controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('orders')->prepare_layout($layout_script); } /** * Render layout (proxy to orders controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('orders')->render_layout($content, $layout_script); } /** * Prepare cartproduct model for create action * * @param string|Model_CartProduct $cartproduct * @param array $params * @return Model_CartProduct */ protected function _model_create($cartproduct, array $params = NULL) { $cartproduct = parent::_model('create', $cartproduct, $params); $order_id = (int) $this->request->param('order_id'); if ( ! Model::fly('Model_Order')->exists_by_id($order_id)) { throw new Controller_BackendCRUD_Exception('Указанный заказ не существует!'); } $cartproduct->cart_id = $order_id; // Set defaults from actual product in catalog $product = new Model_Product(); $product->find((int) $this->request->param('product_id')); if (isset($product->id)) { $cartproduct->from_product($product); } return $cartproduct; } /** * Renders list of order products * * @param Model_Order $order * @return string */ public function widget_cartproducts($order) { $cartproducts = $order->products; // Set up view $view = new View('backend/cartproducts'); $view->order = $order; $view->cartproducts = $cartproducts; return $view->render(); } }<file_sep>/modules/shop/orders/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { // ----- cart Route::add('frontend/cart', new Route_Frontend( 'cart(/<action>(/product-<product_id>)(/style-<widget_style>))' . '(/~<history>)' , array( 'action' => '\w++', 'product_id' => '\d++', 'widget_style' => '(small|big)', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'cart', 'action' => 'index', 'product_id' => NULL, 'widget_style' => 'small', 'history' => '' )); // ----- order checkout Route::add('frontend/orders', new Route_Frontend( 'orders(/<action>(/cart-<cart>))' , array( 'action' => '\w++', 'cart' => '[0-9_-]++', ) )) ->defaults(array( 'controller' => 'orders', 'action' => 'checkout', 'cart' => '' )); } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { // ----- cartproducts Route::add('backend/orders/products', new Route_Backend( 'orders/products(/<action>(/<id>)(/order-<order_id>)(/product-<product_id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'order_id' => '\d++', 'product_id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'cartproducts', 'action' => 'index', 'id' => NULL, 'order_id' => NULL )); // ----- orderstatuses Route::add('backend/orders/statuses', new Route_Backend( 'orders/statuses(/<action>(/<id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'orderstatuses', 'action' => 'index', 'id' => NULL, )); // ----- ordercomments Route::add('backend/orders/comments', new Route_Backend( 'orders/comments(/<action>(/<id>)(/order-<order_id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'order_id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'ordercomments', 'action' => 'index', 'id' => NULL, 'order_id' => NULL )); // ----- orders Route::add('backend/orders', new Route_Backend( 'orders(/<action>(/<id>)(/ids-<ids>)(/user-<user_id>))' . '(/order-<orders_order>)(/desc-<orders_desc>)(/p-<page>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'user_id' => '\d++', 'orders_order' => '\w++', 'orders_desc' => '[01]', 'page' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'orders', 'action' => 'index', 'id' => NULL, 'ids' => '', 'user_id' => NULL, 'orders_order' => 'id', 'orders_desc' => '1', 'page' => 0 )); // ----- Add backend menu items $parent_id = Model_Backend_Menu::add_item(array( 'id' => 5, 'menu' => 'main', 'caption' => 'Заказы', 'route' => 'backend/orders', 'select_conds' => array( array('route' => 'backend/orders'), array('route' => 'backend/orders/products'), array('route' => 'backend/orders/statuses'), array('route' => 'backend/orders/comments'), array('route' => 'backend/deliveries'), array('route' => 'backend/payments'), array('route' => 'backend/history', 'route_params' => array('item_type' => 'order')) ), 'icon' => 'orders' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'caption' => 'Список заказов', 'route' => 'backend/orders', 'select_conds' => array( array('route' => 'backend/orders'), array('route' => 'backend/orders/products'), array('route' => 'backend/orders/comments') ) )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'caption' => 'Статусы', 'route' => 'backend/orders/statuses', )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'caption' => 'Журнал работы', 'route' => 'backend/history', 'route_params' => array('item_type' => 'order') )); } /****************************************************************************** * Module installation ******************************************************************************/ if (Kohana::$environment !== Kohana::PRODUCTION) { // Register system statuses $status = new Model_OrderStatus(); if ( ! $status->exists_by_id(Model_OrderStatus::STATUS_NEW)) { $status->init(array( 'id' => Model_OrderStatus::STATUS_NEW, 'caption' => 'Новый заказ', 'system' => TRUE )); $status->create(); } if ( ! $status->exists_by_id(Model_OrderStatus::STATUS_COMPLETE)) { $status->init(array( 'id' => Model_OrderStatus::STATUS_COMPLETE, 'caption' => 'Выполнен', 'system' => TRUE )); $status->create(); } if ( ! $status->exists_by_id(Model_OrderStatus::STATUS_CANCELED)) { $status->init(array( 'id' => Model_OrderStatus::STATUS_CANCELED, 'caption' => 'Отменён', 'system' => TRUE )); $status->create(); } }<file_sep>/modules/general/images/classes/form/frontend/imageajax.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_ImageAJAX extends Form_Frontend { /** * Initialize form fields */ public function init() { $this->view_script = 'frontend/forms/image'; // Set HTML class $this->attribute('class', "w500px wide lb120px"); // ----- File $element = new Form_Element_File('file', array('label' => 'Файл с изображением'),array('placeholder' => 'Выберите файл')); $element->add_validator(new Form_Validator_File()); $this->add_component($element); // ----- Form buttons $button = new Form_Element_Button('submit_image', array('label' => 'Загрузить'), array('class' => 'button button-modal') ); $this->add_component($button); } } <file_sep>/modules/system/forms/config/form_templates/dldtdd/checkgrid.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( 'element' => '<dt></dt> <dd> <fieldset class="element-checkselect"> <legend>{{label_text}}</legend> <div class="options">{{input}}</div> <div class="errors" id="{{id}}-errors">{{errors}}</div> <div class="comment">{{comment}}</div> </fieldset> </dd> ' );<file_sep>/modules/shop/catalog/views/frontend/telemosts/request.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (isset($url)) {?> <p>Бронь на сертификат будет действовать в течении 12 часов.</p> <p>Вы можете произвести оплату сейчас же на портале <a href="http://vse.to">VSE.TO</a> либо воспользоваться личным кабинетом <a href="https://visa.qiwi.com/features/list.action">VISA QIWI WALLET</a> в случае если оплата будет произведена позже.</p> <iframe name="iframeName" src="<?php echo $url?>" frameborder="0" width="100%" height="450" scrolling="no"></iframe> <?php } ?> <file_sep>/modules/general/news/views/frontend/news.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $view_url = URL::to('frontend/news', array('action'=>'view', 'id' => '{{id}}'), TRUE); ?> <?php if (empty($years)) { echo '<div class="news"><div class="item">Новостей нет</div></div>'; return; } ?> <!-- Selecting news by year and month --> <div id="pages"> <ul class="year"> <?php foreach ($years as $year) { $url = URL::to('frontend/news', array('year' => $year)); $selected = ($year == $current_year); echo '<li>' . ' <a href="' . $url . '"' . ($selected ? ' class="current"' : '') . '>' . $year . '</a>' . '</li>'; } ?> </ul> <ul class="month"> <?php for ($month = 1; $month <= 12; $month++) { if ( ! in_array($month, $months)) { echo '<li><span>' . $month . '</span></li>'; } else { $url = URL::to('frontend/news', array('year' => $current_year, 'month' => $month)); $selected = ($month == $current_month); echo '<li>' . ' <a href="' . $url . '"' . ($selected ? ' class="current"' : '') . '>' . $month . '</a>' . '</li>'; } } ?> </ul> </div> <!-- news list --> <?php if ( ! count($news)) // No news return; ?> <div class="news"> <?php foreach ($news as $newsitem) : $_view_url = str_replace('{{id}}', $newsitem->id, $view_url); ?> <div class="item"> <div class="date"><?php echo $newsitem->date->format(Kohana::config('datetime.date_format')); ?></div> <div class="title"> <a href="<?php echo $_view_url; ?>"> <?php echo HTML::chars($newsitem->caption); ?> </a> <div class="text"> <?php echo $newsitem->short_text; ?> </div> </div> </div> <?php endforeach; ?> <div class="item last"></div> </div> <?php if (isset($pagination)) { echo $pagination; } ?><file_sep>/modules/frontend/views/frontend/form_adv.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="panel"> <div class="panel_content"> <?php echo $form->render(); ?> </div> </div> <file_sep>/application/config/form_templates/frontend/text.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array( array( 'element' => '<tr> <td class="input_cell element-{{type}}" colspan="2"> {{input}} </td> </tr> ' ) );<file_sep>/modules/system/forms/classes/form/fieldset/buttons.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Logical fieldset of form buttons * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Fieldset_Buttons extends Form_Fieldset { }<file_sep>/modules/general/gmap/tests/gmap.php <?php /** * Tests the Google Maps Module. * * @group Google Maps Module * * @package Unittest * @author <NAME> <<EMAIL>> */ Class GmapTest extends Kohana_Unittest_TestCase { /** * Provides maptype test data() * * @return array */ public function provider_maptype() { return array( array('road'), array('satellite'), array('hybrid'), array('terrain'), ); } /** * Tests the exception, thrown by the validate_latitude method. * * @test * @covers Gmap::set_pos * @covers Gmap::validate_latitude * @expectedException Kohana_Exception */ function test_validate_latitude_exception_if_higher_than_180() { $map = new Gmap(); $map->set_pos(180.1, NULL); } // function /** * Tests the exception, thrown by the validate_latitude method. * * @test * @covers Gmap::set_pos * @covers Gmap::validate_latitude * @expectedException Kohana_Exception */ function test_validate_latitude_exception_if_lower_than_minus180() { $map = new Gmap(); $map->set_pos(-180.1, NULL); } // function /** * Tests the exception, thrown by the validate_longitude method. * * @test * @covers Gmap::set_pos * @covers Gmap::validate_longitude * @expectedException Kohana_Exception */ function test_validate_longitude_exception_if_higher_than_90() { $map = new Gmap(); $map->set_pos(NULL, 90.1); } // function /** * Tests the exception, thrown by the validate_longitude method. * * @test * @covers Gmap::set_pos * @covers Gmap::validate_longitude * @expectedException Kohana_Exception */ function test_validate_longitude_exception_if_lower_than_minus90() { $map = new Gmap(); $map->set_pos(NULL, -90.1); } // function /** * Tests the validate_maptype method. * * @test * @covers Gmap::set_maptype * @covers Gmap::validate_maptype * @dataProvider provider_maptype */ function test_validate_maptype($maptype) { $map = new Gmap(); $this->assertSame($map ,$map->set_maptype($maptype)); } // function /** * Tests the exception, thrown by the validate_maptype method. * * @test * @covers Gmap::set_maptype * @covers Gmap::validate_maptype * @expectedException Kohana_Exception */ function test_validate_maptype_exception() { $map = new Gmap(); $map->set_maptype('NotExisting'); } // function /** * Tests the setting options through the constructor. * * @test * @covers Gmap::__construct * @covers Gmap::get_option */ function test_constructor_options_parameter() { $options = array( 'abc' => 123, 'def' => TRUE, 'ghi' => FALSE, 'jkl' => array(), 'lat' => 12.34, 'lng' => 34.56, 'zoom' => 10, 'sensor' => TRUE, 'maptype' => 'terrain', 'view' => 'gmap_demo', 'gmap_size_x' => 666, 'gmap_size_y' => 333, 'gmap_controls' => array( 'maptype' => array('display' => FALSE), 'navigation' => array('display' => FALSE), 'scale' => array('display' => FALSE), ), ); $map = new Gmap($options); $expected = array( 'lat' => 12.34, 'lng' => 34.56, 'zoom' => 10, 'sensor' => TRUE, 'maptype' => 'terrain', 'view' => 'gmap_demo', 'gmap_size_x' => 666, 'gmap_size_y' => 333, 'gmap_controls' => array( 'maptype' => array('display' => FALSE), 'navigation' => array('display' => FALSE), 'scale' => array('display' => FALSE), ), ); $this->assertEquals($expected, $map->get_option()); } // function /** * Tests the factory method. * * @test * @covers Gmap::__construct * @covers Gmap::factory */ function test_factory_metod() { $this->assertEquals(new Gmap(), Gmap::factory()); } // function } // class<file_sep>/modules/system/forms/views/forms/default/form.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php echo $form->render_messages(); echo Form_Helper::open($form->action, $form->attributes()); echo $form->render_hidden(); echo $form->render_components(); echo Form_Helper::close(); //$form->render_js(); ?><file_sep>/application/views/layouts/_header_map_new.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!doctype html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <title><?php echo HTML::chars($view->placeholder('title')); ?></title> <meta http-equiv="keywords" content="<?php echo HTML::chars($view->placeholder('keywords')); ?>" /> <meta http-equiv="description" content="<?php echo HTML::chars($view->placeholder('description')); ?>" /> <?php echo HTML::style(Modules::uri('frontend') . '/public/css/frontend/bootstrap.css'); ?> <?php echo HTML::style(Modules::uri('frontend') . '/public/css/frontend/style.css'); ?> <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <?php echo Gmaps3::instance()->get_apilink();?> <script type="text/javascript"> window.onload = function() { // Reference to autogenerated code <?php echo Gmaps3::instance()->get_map('gmap');?> }; </script> <?php echo $view->placeholder('styles'); ?> </head> <file_sep>/modules/shop/orders/classes/model/cart.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Cart extends Model { /** * Maximum number of distinct products that can be but into the cart */ const MAX_DISTINCT_COUNT = 500; /** * Maximum allowed quantity for the product in cart */ const MAX_QUANTITY = 10; /** * @var Model_Cart */ protected static $_instance; /** * Get cart instance * * @return Model_Cart */ public static function instance() { if (self::$_instance === NULL) { $cart = new Model_Cart(); self::$_instance = $cart; } return self::$_instance; } /** * Get cart instance with session mapper * * @return Model_Cart */ public static function session() { $cart = self::instance(); $cart->mapper('Model_Cart_Mapper_Session'); return $cart; } /** * @param array $properties */ public function __construct(array $properties = array()) { $this->mapper('Model_Cart_Mapper_Db'); parent::__construct($properties); } /** * Add a product to cart by id * * @param integer $product_id * @param integer $quantity * @return Model_Product */ public function add_product($product_id, $quantity = 1) { if ( ! preg_match('/^\d+$/', $quantity)) { $this->error('Количество товара указано неверно!'); return; } $quantity = (int) $quantity; if ($quantity == 0) { $this->error('Вы не указали количество товара'); return; } if ($this->distinct_count >= self::MAX_DISTINCT_COUNT) { $this->error('Максимальное количество различных товаров в корзине не должно превышать ' . self::MAX_DISTINCT_COUNT); return; } $product = new Model_Product(); $product->find_by(array( 'id' => $product_id, 'active' => 1, 'section_active' => 1, 'site_id' => Model_Site::current()->id )); if ( ! isset($product->id)) { $this->error('Указанный товар не найден'); return; } $cartproducts = $this->cartproducts; if ( ! isset($cartproducts[$product->id])) { // Add new product to cart $cartproduct = new Model_CartProduct(); $cartproduct->from_product($product); $new_quantity = $quantity; } else { // Update quantity for product already in cart $cartproduct = $cartproducts[$product->id]; $new_quantity = $cartproduct->quantity + $quantity; } // Validate quantity if ($new_quantity > self::MAX_QUANTITY) { $new_quantity = self::MAX_QUANTITY; } /* if ($new_quantity > $product->quantity) { $new_quantity = $product->quantity; } */ // Update quantity $cartproduct->quantity = $new_quantity; $cartproducts[$product->id] = $cartproduct; // Update cartproducts info $this->save($this); // Invalidate possibly cached properties unset($this->_properties['cartproducts']); unset($this->_properties['sum']); return $product; } /** * Remove product from cart * * @param integer $product_id */ public function remove_product($product_id) { $cartproducts = $this->cartproducts; unset($cartproducts[$product_id]); $this->mapper()->save($this); } /** * Check if product with this id is in cart * * @param integer $product_id */ public function has_product($product_id) { $cartproducts = $this->cartproducts; return (isset($cartproducts[$product_id])); } /** * Update products in cart with supplied values (FRONTEND) * * @param array $quantities array(product_id=>quantity) * @return boolean */ public function update_products(array $quantities, $save = TRUE) { $cartproducts = array(); $count = 0; $product = new Model_Product(); foreach ($quantities as $product_id => $quantity) { if ($this->distinct_count >= self::MAX_DISTINCT_COUNT) { $this->error('Максимальное количество различных товаров в корзине не должно превышать ' . self::MAX_DISTINCT_COUNT); return; } $product->find_by(array( 'id' => $product_id, 'active' => 1, 'section_active' => 1, 'site_id' => Model_Site::current()->id )); if ( ! isset($product->id)) { $this->error('Товар с идентификатором ' . $product_id . ' не найден в каталоге'); continue; } $quantity = (int) $quantity; if ( ! isset($cartproducts[$product->id])) { // Add the product for the first time $cartproduct = new Model_CartProduct(); $cartproduct->from_product($product); $new_quantity = $quantity; } else { // Product has already been added (duplicate values for product_id) $cartproduct = $cartproducts[$product->id]; $new_quantity = $cartproduct->quantity + $quantity; } // Validate quantity if ($new_quantity > self::MAX_QUANTITY) { $new_quantity = self::MAX_QUANTITY; } /* if ($new_quantity > $product->quantity) { $new_quantity = $product->quantity; } */ $cartproduct->quantity = $new_quantity; $cartproducts[$product->id] = $cartproduct; } if ( ! $this->has_errors()) { $this->cartproducts = $cartproducts; if ($save) { // Save cart products to session $this->save(); } return TRUE; } else { return FALSE; } } /** * Remove all products from cart */ public function clean() { $this->cartproducts = array(); $this->save(); } /** * Find all products in cart * * @param array $params * @return Models (of Model_CartProduct) */ public function get_cartproducts(array $params = NULL) { if ( ! isset($this->_properties['cartproducts'])) { $this->_properties['cartproducts'] = $this->mapper()->get_cartproducts($this, $params); } return $this->_properties['cartproducts']; } /** * Get quantities of products in cart in format array(product_id=>quantity) * * @return array */ public function get_quantities() { $quantities = array(); foreach ($this->cartproducts as $cartproduct) { $quantities[$cartproduct->product_id] = $cartproduct->quantity; } return $quantities; } /** * Serialize cart contents to a string */ public function serialize() { $str = ''; foreach ($this->quantities as $product_id => $quantity) { $str .= $product_id . '_' . $quantity . '-'; } return trim($str, '-'); } /** * Set cart contents form a serialized string * * @param string $str * @return boolean */ public function unserialize($str) { $quantities = array(); foreach (explode('-', $str) as $pair) { $product_id = (int) strtok($pair, '_'); $quantity = (int) strtok('_'); $quantities[$product_id] = $quantity; } return $this->update_products($quantities, FALSE); } /** * Get the total price of all products in cart - without any discounts * * @return Money */ public function calculate_sum() { $sum = new Money(); foreach ($this->cartproducts as $cartproduct) { $sum->add($cartproduct->price->mul($cartproduct->quantity)); } return $sum; } /** * Getter for sum of all products in cart * @return Money */ public function get_sum() { if ( ! isset($this->_properties['sum'])) { $this->_properties['sum'] = $this->calculate_sum(); } return $this->_properties['sum']; } /** * Calculate overall cart price with all discounts appliedt */ public function get_total_sum() { return $this->sum; } /** * Get the total number of all products in cart * * @return integer */ public function get_total_count() { $total_count = 0; foreach ($this->cartproducts as $cartproduct) { $total_count += $cartproduct->quantity; } return $total_count; } /** * Get the number of distinct products in cart * * @return integer */ public function get_distinct_count() { return count($this->cartproducts); } }<file_sep>/modules/system/forms/classes/form/validator.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Abstract form validator * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Form_Validator { /** * Reference to form element * @var Form_Element */ protected $_form_element; /** * Messages for each type of the error * @var array */ protected $_messages = array(); /** * Error messages * @var array */ protected $_errors = array(); /** * Value to be validated * @var mixed */ protected $_value; /** * Break chain after validation failure * @var boolean */ protected $_breaks_chain = TRUE; /** * Creates validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure */ public function __construct(array $messages = NULL, $breaks_chain = TRUE) { if ($messages !== NULL) { foreach ($messages as $type => $message) { $this->_messages[$type] = $message; } } $this->_breaks_chain = $breaks_chain; } /** * Set form element * * @param Form_Element $form_element * @return Validator */ public function set_form_element(Form_Element $form_element) { $this->_form_element = $form_element; return $this; } /** * Get form element * * @return Form_Element */ public function get_form_element() { return $this->_form_element; } /** * Should this validator break chain after failure * * @return boolean */ public function breaks_chain() { return $this->_breaks_chain; } /** * Actual validation is done here. * * @param array $context Entire form data * @return boolean */ protected function _is_valid(array $context = NULL) { return true; } /** * Perform validation of value * * @param mixed $value * @param array $context Entire form data * @return boolean */ public function validate($value, array $context = NULL) { $this->reset(); $this->_value = $value; $result = $this->_is_valid($context); if ( ! is_bool($result)) { throw new Kohana_Exception('Result of _is_valid() function is not boolen in validator :validator', array(':validator' => get_class($this)) ); } if ( ! $result && !$this->has_errors()) { throw new Kohana_Exception('Validator :validator returned false for value ":value", but did not supplied any error messages', array(':validator' => get_class($this), ':value' => $this->_value) ); } return $result; } /** * Resets validator: clears error messages, ... */ public function reset() { $this->_errors = array(); } /** * Adds an error message. * A message template must specified in $this->_messages for given type. * * @param string $type Type of the error. * @param boolean $encode Encode html chars when replacing value */ protected function _error($type) { if (isset($this->_messages[$type])) { $this->_errors[] = array( 'text' => $this->_replace_placeholders($this->_messages[$type]), 'type' => FlashMessages::ERROR ); } else { throw new Kohana_Exception('There is no message for type :type in validator :validator', array(':type' => $type, ':validator' => get_class($this)) ); } } /** * Replaces placeholders in error message * * @param string $error_text * @return string */ protected function _replace_placeholders($error_text) { if (strpos($error_text, ':value') !== FALSE) { $error_text = str_replace(':value', $this->_value, $error_text); } if ($this->_form_element !== NULL) { $error_text = str_replace(':label', UTF8::strtolower($this->_form_element->label), $error_text); } return $error_text; } /** * Are there any validation errors? * * @return boolean */ public function has_errors() { return !empty($this->_errors); } /** * Returns validation errors * * @return array */ public function get_errors() { return $this->_errors; } /** * Render javascript for this validator * * @return string */ public function render_js() { return NULL; } }<file_sep>/modules/general/userpages/classes/model/page/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Page_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('node_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('content', array('Type' => 'text')); } /** * Find page by criteria joining some node information * * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Model */ public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $page_table = $this->table_name(); $node_table = Model_Mapper::factory('Model_Node_Mapper')->table_name(); $columns = isset($params['columnd']) ? $params['columns'] : array("$page_table.*"); // Select node caption as page caption $columns[] = "$node_table.caption"; $columns[] = "$node_table.type"; $columns[] = "$node_table.active"; $query = DB::select_array($columns) ->from($page_table) ->join($node_table, 'INNER') ->on("$node_table.id", '=', "$page_table.node_id"); return parent::find_by($model, $condition, $params, $query); } }<file_sep>/application/classes/flashmessages.php <?php class FlashMessages { const MESSAGE = 1; const ERROR = 2; /** * Add new message * * @param string $text * @param integer $type * @param string $category */ public static function add($text, $type = self::MESSAGE, $category = 'default') { $messages = Session::instance()->get('flash_messages', array()); $messages[] = array( 'text' => $text, 'type' => $type, 'category' => $category ); Session::instance()->set('flash_messages', $messages); } /** * Add several messages at once * * @param array $messages * @param string $category */ public static function add_many(array $messages, $category = 'default') { $msgs = Session::instance()->get('flash_messages', array()); foreach ($messages as $message) { if (is_array($message)) { $text = $message['text']; $type = $message['type']; } else { $text = (string) $message; $type = self::MESSAGE; } $msgs[] = array( 'text' => $text, 'type' => $type, 'category' => $category ); } Session::instance()->set('flash_messages', $msgs); } /** * Return all messages for specified category and delete them from session * * @param string $category * @return array */ public static function fetch_all($category = 'default') { $result = array(); $messages = Session::instance()->get('flash_messages', array()); // Fetch only messages with specified category foreach ($messages as $k => $message) { if ($message['category'] == $category) { $result[] = $message; unset($messages[$k]); } } Session::instance()->set('flash_messages', $messages); return $result; } }<file_sep>/modules/general/menus/views/backend/menus.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/menus', array('action'=>'create'), TRUE); $update_url = URL::to('backend/menus', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/menus', array('action'=>'delete', 'id' => '${id}'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Создать меню</a> </div> <?php if ( ! count($menus)) // No menus return; ?> <table class="table"> <tr class="header"> <th>&nbsp;&nbsp;&nbsp;</th> <?php $columns = array( 'name' => 'Имя', 'caption' => 'Название' ); echo View_Helper_Admin::table_header($columns, 'menus_order', 'menus_desc'); ?> </tr> <?php foreach ($menus as $menu) : $_delete_url = str_replace('${id}', $menu->id, $delete_url); $_update_url = str_replace('${id}', $menu->id, $update_url); ?> <tr> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить меню', 'controls/delete.gif', 'Удалить'); ?> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать меню', 'controls/edit.gif', 'Редактировать'); ?> </td> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if (isset($menu->$field) && trim($menu->$field) !== '') { echo HTML::chars($menu->$field); } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> </tr> <?php endforeach; //foreach ($menus as $menu) ?> </table><file_sep>/modules/shop/orders/classes/controller/backend/orders.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Orders extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Order'; $this->_form = 'Form_Backend_Order'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание заказа', ), 'update' => array( 'view' => 'backend/order', 'view_caption' => 'Редактирование заказа № :id', 'subactions' => array('calc_delivery_price', 'calc_payment_price'), 'redirect_uri' => URL::uri_self(array('user_id' => NULL)) ), 'delete' => array( 'view_caption' => 'Удаление заказа', 'message' => 'Удалить заказ № :id?' ), 'multi_delete' => array( 'view_caption' => 'Удаление заказов', 'message' => 'Удалить выбранные заказы?' ) ); } /** * Prepare layout * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_script(Modules::uri('orders') . '/public/js/backend/order.js'); $layout->add_style(Modules::uri('orders') . '/public/css/backend/orders.css'); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->caption = 'Заказы'; $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Index action - renders the list of orders */ public function action_index() { $this->request->response = $this->render_layout( $this->widget_orders() ); } /** * Calculate dilvery price subaction * * @param Model_Order $order * @param Form $form * @param array $params */ public function _execute_calc_delivery_price(Model_Order $order, Form $form, array $params = NULL) { // Apply values to order (except delivery id and delivery price) $values = $form->get_values(); unset($values['delivery_id']); unset($values['delivery_price']); $order->values($values); // Recalculate price & apply new value to form $delivery_price = $order->calc_delivery_price(); $order->delivery_price = $delivery_price; $form->get_element('delivery_price')->value = $delivery_price; if ($order->has_errors()) { $form->errors($order->errors()); } } /** * Calculate payment price subaction * * @param Model_Order $order * @param Form $form * @param array $params */ public function _execute_calc_payment_price(Model_Order $order, Form $form, array $params = NULL) { // Apply values to order (except delivery id and delivery price) $values = $form->get_values(); unset($values['payment_id']); unset($values['payment_price']); $order->values($values); // Recalculate price & apply new value to form $payment = $order->calc_payment_price(); $order->payment_price = $payment; $form->get_element('payment_price')->value = $payment; if ($order->has_errors()) { $form->errors($order->errors()); } } /** * Renders list of orders * * @return string */ public function widget_orders() { $order = Model::fly('Model_Order'); $order_by = $this->request->param('orders_order', 'id'); $desc = (bool) $this->request->param('orders_desc', '1'); $per_page = 25; $count = $order->count(); $pagination = new Pagination($count, $per_page); // Select all products $orders = $order->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/orders'); $view->order_by = $order_by; $view->desc = $desc; $view->pagination = $pagination; $view->orders = $orders; return $view->render(); } /** * Generate redirect url * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { if ($action == 'create') { return URL::uri_to( 'backend/orders', array('action'=>'update', 'id' => $model->id, 'history' => $this->request->param('history')), TRUE ) . '?flash=ok'; } else { return parent::_redirect_uri($action, $model, $form, $params); } } /** * Prepare a view for order update action * * @param Model $order * @param Form $form * @param array $params * @return View */ protected function _view_update(Model $order, Form $form, array $params = NULL) { $view = $this->_view('update', $order, $form, $params); // Render list of products in order $view->cartproducts = $this->request->get_controller('cartproducts')->widget_cartproducts($order); // Render list of comments for order $view->ordercomments = $this->request->get_controller('ordercomments')->widget_ordercomments($order); return $view; } }<file_sep>/modules/system/forms/classes/form/filter/char.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Cut string to the specified length * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Filter_Char extends Form_Filter { /** * Cut strings longer than this parameter * @var string */ protected $_char = '.'; /** * Creates filter * * @param integer $maxlength Maximum allowed length * @param string $charlist Characters to trim */ public function __construct($char = '.') { $this->_char = $char; } /** * Trims characters from value * * @param string $value */ public function filter($value) { // Crop string value, if necessary return current(explode($this->_char,$value)); } }<file_sep>/modules/shop/catalog/views/frontend/products/search.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="b-search-head"> <p>Результаты поиска:</p> <ul class="b-results"> <li><a href="">события и телемосты <span class="count"><?php echo '('.count($products).')' ?></span></a></li> </ul> </div> <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'frontend/products/_map')); ?> <?php if ( ! count($products)) { echo '<i>Анонсов нет</i>'; } else { $count = count($products); $i = 0; $products->rewind(); $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $today_flag= 0; $tomorrow_flag= 0; $nearest_flag = 0; if (!isset($without_dateheaders)) $without_dateheaders=FALSE; while ($i < $count) { $product = $products->current(); $products->next(); if (($today_flag == 0) && $product->datetime->format('d.m.Y') == $today_datetime->format('d.m.Y')) { if (!$without_dateheaders) echo '<h1 class="main-title"><span>Сегодня, '.$product->datetime->format('d.m.Y').'</span></h1>'; $today_flag++; } elseif (($tomorrow_flag == 0) && $product->datetime->format('d.m.Y') == $tomorrow_datetime->format('d.m.Y')){ if (!$without_dateheaders) echo '<h1 class="main-title"><span>Завтра, '.$product->datetime->format('d.m.Y').'</span></h1>'; $tomorrow_flag++; } elseif ($nearest_flag == 0) { if (!$without_dateheaders) echo '<h1 class="main-title"><span>В ближайшее время </span></h1>'; $nearest_flag++; } $i++; echo Widget::render_widget('products', 'small_product', $product); echo Widget::render_widget('telemosts', 'request', $product); } ?> <?php if ($pagination) { echo $pagination; } }?> <file_sep>/application/views/layouts/_footer_new.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!--bof-navigation display --> <div id="navSuppWrapper"> <div id="navSupp"> <?php echo Widget::render_widget('menus','menu', 'main'); ?> </div> </div> <!--eof-navigation display --> <?php if (Kohana::$profiling) { //echo View::factory('profiler/stats')->render(); } ?> </body> </html><file_sep>/modules/system/forms/config/form_templates/dldtdd/fieldset_tab.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( 'fieldset' => '<dt></dt> <dd id="{{id}}"> <dl> {{elements}} </dl> </dd> ' );<file_sep>/modules/shop/catalog/views/frontend/products/format_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $format_url = URL::to('frontend/catalog/products', array('format' => '{{format}}'), TRUE); ?> <li class="dropdown"> <?php if ($format) { $main_format_url = URL::to('frontend/catalog/products', array('format' => $format), TRUE); ?> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="<?php echo $main_format_url?>"><?php echo Model_Product::$_format_options[$format]?> <b class="caret"></b></a> <?php } else { ?> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="">формат<b class="caret"></b></a> <?php } ?> <ul class="dropdown-menu" role="menu" aria-labelledby="drop10"> <?php foreach ($formats as $f_id => $f_name) { if ($f_name == $format) continue; $_format_url = str_replace('{{format}}', $f_id, $format_url); ?> <li><a role="menuitem" tabindex="-1" href="<?php echo $_format_url ?>"><?php echo $f_name ?></a></li> <?php }?> </ul> </li><file_sep>/modules/general/tags/views/backend/tag_ac.php <div class="tag_ac item i_<?php echo $num;?>"> <div class="item i_<?php echo $num;?>"><?php echo $name ?></div> </div><file_sep>/modules/general/filemanager/views/backend/editfile.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="panel editfile_form"> <div class="caption"><?php echo HTML::chars($caption) ?></div> <div class="content"> <?php if (isset($flash_msg)) { echo View_Helper::flash_msg($flash_msg, $flash_msg_class); } ?> <?php echo $form->render(); ?> </div> </div> <file_sep>/modules/general/nodes/classes/controller/backend/nodes.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Nodes extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Node'; $this->_form = 'Form_Backend_Node'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание страницы' ), 'update' => array( 'view_caption' => 'Редактирование страницы ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление страницы', 'message' => 'Удалить страницу ":caption" и все подстраницы?' ) ); } /** * @return boolean */ public function before() { if ( ! parent::before()) { return FALSE; } // Check that there is a site selected if (Model_Site::current()->id === NULL) { $this->_action_error('Выберите сайт для работы со страницами!'); return FALSE; } return TRUE; } /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('nodes') . '/public/css/backend/nodes.css'); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Render nodes tree */ public function action_index() { $this->request->response = $this->render_layout($this->widget_nodes()); } /** * Create new node * * @param string|Model $model * @param array $params * @return Model_Node */ protected function _model_create($model, array $params = NULL) { // New node (as child of current node) $node = new Model_Node(); $node->parent_id = (int) $this->request->param('node_id'); return $node; } /** * Delete node */ protected function _execute_delete(Model $node, Form $form, array $params = NULL) { list($hist_route, $hist_params) = URL::match(URL::uri_back()); // Id of selected node $node_id = isset($hist_params['node_id']) ? (int) $hist_params['node_id'] : 0; if ($node->id === $node_id || $node->is_parent_of($node_id)) { // If current selected section or its parent is deleted - redirect back to root unset($hist_params['node_id']); $params['redirect_uri'] = URL::uri_to($hist_route, $hist_params); } parent::_execute_delete($node, $form, $params); } /** * Renders tree of nodes * * @return string */ public function widget_nodes() { $site_id = Model_Site::current()->id; $node = new Model_Node(); $order_by = $this->request->param('nodes_order', 'lft'); $desc = (bool) $this->request->param('nodes_desc', '0'); $node_id = (int) $this->request->param('node_id'); $nodes = $node->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/nodes'); $view->order_by = $order_by; $view->desc = $desc; $view->node_id = $node_id; $view->nodes = $nodes; return $view->render(); } /** * Renders nodes menu (site structure) */ public function widget_menu() { $site_id = Model_Site::current()->id; if ($site_id === NULL) // Current site is not selected return; $node = new Model_Node(); $order_by = $this->request->param('nodes_menu_order', 'lft'); $desc = (bool) $this->request->param('nodes_menu_desc', '0'); $node_id = (int) $this->request->param('node_id'); $nodes = $node->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/nodes_menu'); $view->order_by = $order_by; $view->desc = $desc; $view->node_id = $node_id; $view->nodes = $nodes; // Wrap into panel $panel = new View('backend/panel'); $panel->caption = 'Страницы сайта'; $panel->content = $view; return $panel->render(); } } <file_sep>/modules/shop/catalog/views/frontend/products/small_product.php <?php defined('SYSPATH') or die('No direct script access.'); $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $url = URL::site($product->uri_frontend()); $image = ''; if (isset($product->image)) { $image = '<a href="' . $url . '">' . HTML::image('public/data/' . $product->image, array('alt' => $product->caption)) . '</a>'; } $lecturer_url = URL::to('frontend/acl/lecturers', array('action' => 'show','lecturer_id' => $product->lecturer_id)); $day =NULL; if ($product->datetime->format('d.m.Y') == $today_datetime->format('d.m.Y')) $day = 'Сегодня'; if ($product->datetime->format('d.m.Y') == $tomorrow_datetime->format('d.m.Y')) $day = 'Завтра'; if (!$day) $day = $product->weekday; $telemost_flag= FALSE; if (Model_Town::current()->alias != Model_Town::ALL_TOWN) $telemost_flag = ($product->place->town_name != Model_Town::current()->name); $user_id = Model_User::current()->id; $group_id = Model_User::current()->group_id; $telemosts = $product->telemosts; $available_num = (int)$product->numviews; if (count($telemosts)) { $available_num = ((int)$product->numviews > count($telemosts))?true:false; } ?> <section><header> <div class="row-fluid"> <div class="span6" style="white-space: nowrap;"> <span class="date"><a class="day" href=""><?php echo $day ?></a><?php echo " ".$product->get_datetime_front()." "?></span> <?php if (Model_Town::current()->alias == Model_Town::ALL_TOWN) { ?><span class="town"><?php echo $product->place->town_name;?></span><?php } ?> <?php if ($telemost_flag) { ?><span class="type"><?php echo Model_Product::$_interact_options[$product->interact];?></span><?php } ?> </div> <div class="span6 b-link"> <?php $datenow = new DateTime("now"); if($product->datetime > $datenow): ?> <?php if (!$telemost_flag && $group_id != Model_Group::USER_GROUP_ID && $group_id && $product->user_id != $user_id) { if ($available_num && !$user_id) { ?> <a data-toggle="modal" href="#notifyModal" class="request-link button">Провести телемост</a> <?php } elseif ($available_num && !$already_req) { ?> <a data-toggle="modal" href="<?php echo "#requestModal_".$product->alias?>" class="request-link button">Провести телемост</a> <?php } elseif($already_req) { $unrequest_url = URL::to('frontend/catalog/smallproduct/unrequest', array('alias' => $product->alias));?> <a href="<?php echo $unrequest_url?>" class="ajax request-link button">Отменить заявку</a> <?php }} ?> <? endif ?> </div></div></header> <div class="body-section"> <div class="row-fluid"> <div class="span6 face"> <?php echo $image ?> <?php //$html .= '<p class="counter"><span title="хочу телемост" id-"" class="hand">999</span></p>'; ?> </div> <div class="span6"> <a class="dir" href="#">Категория: <?php echo Model_Product::$_theme_options[$product->theme] ?></a> <h2><a href="<?php echo $url ?>"><?php echo $product->caption ?></a></h2> <p class="lecturer">Лектор: <a href="<?php echo $lecturer_url ?>"><?php echo $product->lecturer_name?></a></p> <div class="desc"><p><?php echo $product->short_desc ?></p></div> <p class="link-more"><a href="<?php echo $url ?>">Подробнее</a></p> </div></div></div></section><hr> <file_sep>/modules/shop/orders/classes/model/cart/mapper/db.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Cart_Mapper_DB extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('order_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); // Discounts for this cart (applied coupons) $this->add_column('discount_percent', array('Type' => 'float')); $this->add_column('discount_sum', array('Type' => 'money')); // Bonuses used // Cart summary $this->add_column('sum', array('Type' => 'money')); $this->add_column('total_sum', array('Type' => 'money')); } }<file_sep>/modules/shop/catalog/classes/form/frontend/search.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Search extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/forms/search'; // ----- search_text $element = new Form_Element_Input('search_text', array('label' => 'Поиск'), array('maxlength' => 255,'class' => 'go','placeholder' => 'Поиск')); $element ->add_filter(new Form_Filter_TrimCrop(255)); $this->add_component($element); // ----- Submit button /* $this ->add_component(new Form_Element_Submit('submit', array('label' => 'Выбрать') array('class' => 'submit') )); */ } } <file_sep>/modules/system/forms/classes/form/element/money.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form element for entering prices * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Money extends Form_Element_Input { /** * Sets the value for the element * * @param mixed $value * @return Form_Element */ public function set_value($value) { if ($value instanceof Money) { // Obtain value from Money object $value = $value->amount; } return parent::set_value($value); } /** * Get value as Money object * * @return Money */ public function get_value() { $value = parent::get_value(); $money = new Money(); $money->amount = $value; return $money; } /** * Get raw value for validation * * @return string */ public function get_value_for_validation() { return parent::get_value(); } /** * Use the same templates as input element * * @return string */ public function default_config_entry() { return 'input'; } /** * Get element * * @return array */ public function attributes() { $attributes = parent::attributes(); // Add "integer" HTML class if (isset($attributes['class'])) { $attributes['class'] .= ' integer'; } else { $attributes['class'] = 'integer'; } return $attributes; } /** * Append currency label to input field * * @return string */ public function default_append() { return '&nbsp;&nbsp;руб.'; } /** * Renders input * By default, 'text' type is used * * @return string */ public function render_input() { return Form_Helper::input($this->full_name, sprintf("%.2f", $this->value_for_validation), $this->attributes()); } } <file_sep>/modules/system/forms/classes/form/filter/trimcrop.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Trim whitespace and cut strings to specified length * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Filter_TrimCrop extends Form_Filter { /** * Cut strings longer than this parameter * @var string */ protected $_maxlength = 0; /** * List of characters to trim. (@see trim) * Defaults to tabs and whitespaces * @var string */ protected $_charlist = " \t"; /** * Creates filter * * @param integer $maxlength Maximum allowed length * @param string $charlist Characters to trim */ public function __construct($maxlength = 0, $charlist = NULL) { $this->_maxlength = $maxlength; } /** * Trims characters from value * * @param string $value */ public function filter($value) { // Trim string value $value = trim((string) $value, $this->_charlist); // Crop string value, if necessary if ($this->_maxlength > 0 && strlen($value) > $this->_maxlength) { return UTF8::substr($value, 0, $this->_maxlength); } else { return $value; } } }<file_sep>/modules/shop/acl/classes/controller/backend/userprops.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_UserProps extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_UserProp'; $this->_form = 'Form_Backend_UserProp'; return array( 'create' => array( 'view_caption' => 'Создание характеристики' ), 'update' => array( 'view_caption' => 'Редактирование характеристики ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление характеристики', 'message' => 'Удалить характеристику ":caption"?' ) ); } /** * Create layout (proxy to acl controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Render all available user properties */ public function action_index() { $this->request->response = $this->render_layout($this->widget_userprops()); } /** * Create new user property * * @return Model_UserProp */ protected function _model_create($model, array $params = NULL) { if (Model_Site::current()->id === NULL) { throw new Controller_BackendCRUD_Exception('Выберите портал перед созданием характеристики!'); } // New userprop for current site $userprop = new Model_UserProp(); $userprop->site_id = (int) Model_Site::current()->id; return $userprop; } /** * Render list of user properties */ public function widget_userprops() { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } $order_by = $this->request->param('acl_uprorder', 'position'); $desc = (bool) $this->request->param('acl_uprdesc', '0'); $userprops = Model::fly('Model_UserProp')->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/userprops'); $view->order_by = $order_by; $view->desc = $desc; $view->userprops = $userprops; return $view->render(); } }<file_sep>/modules/general/feedback/classes/form/frontend/feedback.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Feedback extends Form_Frontend { public function init() { $this->attribute('class', 'ajax'); // ----- phone $element = new Form_Element_Input('phone', array( 'label' => 'Телефоны для связи', 'required' => TRUE, 'comment' => '' ), array( 'size' => '80', 'maxlength' => '63', ) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- name $element = new Form_Element_Input('name', array( 'label' => 'Ваше имя', 'required' => TRUE, 'comment' => '' ), array( 'size' => '80', 'maxlength' => '63', ) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- comment $element = new Form_Element_Textarea('comment', array( 'label' => 'Дополнительная информация', 'comment' => '' ), array( 'cols' => '80', 'rows' => '5' ) ); $element ->add_filter(new Form_Filter_TrimCrop(1023)); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Element_Submit('submit', array('label' => 'Отправить'), array('class' => 'submit') )); } } <file_sep>/application/classes/request.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Request and response wrapper. * * Controllers are now bound to the request and can be obtained using get_controller() method. * * @package Eresus * @author <NAME> (<EMAIL>) */ class Request extends Kohana_Request { /** * Controllers loaded for current request * @var array */ protected $_controllers; /** * Forward information * @var array */ protected $_forward; /** * Registry that holds per-request data * @var array */ protected $_registry; /** * This request should be rendered as in window * * @return boolean */ public function in_window() { return ( ! empty($_GET['window'])); } /** * Forward the request to another action * * @param string $controller * @param string $action * @param array $params * @return Request */ public function forward($controller, $action, array $params = NULL) { $this->_forward = array( 'controller' => $controller, 'action' => $action, 'params' => $params ); return $this; } /** * Cancel request forwarding * * @return Request */ public function dont_forward() { $this->_forward = NULL; return $this; } /** * Is this request forwarded? * * @return boolean */ public function is_forwarded() { return ( ! empty($this->_forward)); } /** * Returns an instance of controller with specified class name. * * Instance of controller is created only once and than stored in the request. * That implies that the controller's lifetime is the same as the request's lifetime. * * If $class is NULL, than an instance of current request controller is returned. * * @param string $class * @return Controller */ public function get_controller($class = NULL) { // Downcase class name $class = strtolower($class); if ($class === NULL) { // Construct the class name of current controller // Create the class prefix $class = 'controller_'; if ($this->directory) { // Add the directory name to the class prefix $class .= str_replace(array('\\', '/'), '_', trim($this->directory, '/')).'_'; } $class .= $this->controller; } elseif (strpos($class, 'controller_') === FALSE) { // Short name of the controller if ($this->directory) { // Add the directory name to the controller $class = str_replace(array('\\', '/'), '_', trim($this->directory, '/')) . '_' . $class; } $class = 'controller_' . $class; } if ( ! isset($this->_controllers[$class])) { // Create new controller instance via reflection $reflection_class = new ReflectionClass($class); $this->_controllers[$class] = $reflection_class->newInstance($this); } return $this->_controllers[$class]; } /** * Execute the request * * @return Request */ public function execute() { // Create the class prefix $prefix = 'controller_'; if ($this->directory) { // Add the directory name to the class prefix $prefix .= str_replace(array('\\', '/'), '_', trim($this->directory, '/')).'_'; } if (Kohana::$profiling) { // Set the benchmark name $benchmark = '"'.$this->uri.'"'; if ($this !== Request::$instance AND Request::$current) { // Add the parent request uri $benchmark .= ' « "'.Request::$current->uri.'"'; } // Start benchmarking $benchmark = Profiler::start('Requests', $benchmark); } // Store the currently active request $previous = Request::$current; // Change the current request to this request Request::$current = $this; // Start with the current request's controller and action // Determine the action to use $action = empty($this->action) ? Route::$default_action : $this->action; $this->forward($this->controller, $action); $forward_count = 0; try { while ($this->is_forwarded() && ($forward_count < 100)) { $forward_count++; $this->controller = $this->_forward['controller']; $this->action = $this->_forward['action']; // Substitute params if (isset($this->_forward['params'])) { $this->_params = $this->_forward['params']; } $this->dont_forward(); // Get controller instance $controller = $this->get_controller($this->controller); // Load the controller class using reflection $class = new ReflectionClass($controller); // Execute the "before action" method $do_execute = $class->getMethod('before')->invoke($controller); // Request was forwarded in 'before' method if ($this->is_forwarded()) continue; // Execute the main action with the parameters if ($do_execute) { $class->getMethod('action_'.$this->action)->invokeArgs($controller, $this->_params); } // Request was forwarded during action execution if ($this->is_forwarded()) continue; // Execute the "after action" method $class->getMethod('after')->invoke($controller); } if ($forward_count >= 100) { throw new Kohana_Exception('Too many request forwards.'); } } catch (Exception $e) { // Restore the previous request Request::$current = $previous; if (isset($benchmark)) { // Delete the benchmark, it is invalid Profiler::delete($benchmark); } if ($e instanceof ReflectionException) { // Reflection will throw exceptions for missing classes or actions $this->status = 404; } else { // All other exceptions are PHP/server errors $this->status = 500; } // Re-throw the exception throw $e; } // Restore the previous request Request::$current = $previous; if (isset($benchmark)) { // Stop the benchmark Profiler::stop($benchmark); } return $this; } /** * Set value in request's registry * * @param string $name * @param mixed $value * @return Request */ public function set_value($name, $value) { $this->_registry[$name] = $value; return $this; } /** * Get value from request's registry * * @param string $name * @param mixed $default * @return mixed */ public function get_value($name, $default = NULL) { if (isset($this->_registry[$name])) { return $this->_registry[$name]; } else { return $default; } } /** * Check whether the specified value is set in the request's registry * * @param string $name * @return mixed */ public function has_value($name) { return isset($this->_registry[$name]); } } <file_sep>/modules/shop/orders/classes/controller/backend/orderstatuses.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_OrderStatuses extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_OrderStatus'; $this->_form = 'Form_Backend_OrderStatus'; return array( 'create' => array( 'view_caption' => 'Создание статуса заказа' ), 'update' => array( 'view_caption' => 'Редактирование статуса заказа ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление статуса заказа', 'message' => 'Удалить статус заказа ":caption"?' ) ); } /** * Create layout (proxy to orders controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('orders')->prepare_layout($layout_script); } /** * Render layout (proxy to orders controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('orders')->render_layout($content, $layout_script); } /** * Index action - renders the list of order statuses */ public function action_index() { $this->request->response =$this->render_layout($this->widget_statuses()); } /** * Renders list of order statuses * * @return string */ public function widget_statuses() { $status = Model::fly('Model_OrderStatus'); $order_by = 'id'; $desc = FALSE; // Select all order statuses $statuses = $status->find_all(array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/orderstatuses'); $view->order_by = $order_by; $view->desc = $desc; $view->statuses = $statuses; return $view->render(); } }<file_sep>/modules/shop/acl/views/frontend/forms/lecturer.php <div id="LectorModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Добавить лектора</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <label for="last_name"><?php echo $form->get_element('last_name')->render_input(); ?></label> <?php echo $form->get_element('last_name')->render_alone_errors();?> <label for="first_name"><?php echo $form->get_element('first_name')->render_input(); ?></label> <?php echo $form->get_element('first_name')->render_alone_errors();?> <label for="middle_name"><?php echo $form->get_element('middle_name')->render_input(); ?></label> <?php echo $form->get_element('middle_name')->render_alone_errors();?> <label for="info"> <?php echo $form->get_element('info')->render_input(); ?> &nbsp;<a class="help-pop help-pop-right" href="#" title="" data-placement="bottom" data-original-title="Где учился лектор, где он работает, какие у него научные или практические интересы, какие главные публикации и основные достижения.">?</a> </label> <?php echo $form->get_element('info')->render_alone_errors();?> <label for="links"><?php echo $form->get_element('links')->render_input(); ?></label> <?php echo $form->get_element('links')->render_alone_errors();?> <?php echo $form->get_element('file')->render_label(); echo $form->get_element('file')->render_input(); ?> <?php echo $form->get_element('file')->render_alone_errors();?> <div id="prev_<?php echo $form->get_element('file')->id?>" class="prev_container"></div><br/> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_lecturer')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div> <file_sep>/modules/shop/acl/classes/model/privilegegroup/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PrivilegeGroup_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('privilege_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('group_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); } /** * Link privilege to given groups * * @param Model_Privilege $privilege * @param array $privgroups */ public function link_privilege_to_groups(Model_Privilege $privilege, array $privgroups) { $this->delete_rows(DB::where('privilege_id', '=', (int) $privilege->id)); foreach ($privgroups as $privgroup) { $privgroup['privilege_id'] = $privilege->id; $this->insert($privgroup); } } /** * Link group to given privileges * * @param Model_Group $group * @param array $privgroups */ public function link_group_to_privileges(Model_Group $group, array $privgroups) { $this->delete_rows(DB::where('group_id', '=', (int) $group->id)); foreach ($privgroups as $privgroup) { $privgroup['group_id'] = $group->id; $this->insert($privgroup); } } /** * Find all privilege-group infos by given group * * @param Model_PrivilegeGroup $privgr * @param Model_Group $group * @param array $params * @return Models */ public function find_all_by_group(Model_PrivilegeGroup $privgr, Model_Group $group, array $params = NULL) { $privgr_table = $this->table_name(); $privilege_table = Model_Mapper::factory('Model_Privilege_Mapper')->table_name(); $group_table = Model_Mapper::factory('Model_Group_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array( array("$privilege_table.id", 'privilege_id'), "$privilege_table.caption", "$privilege_table.system", "$privgr_table.active", ); $query = DB::select_array($columns) ->from($privilege_table) ->join($privgr_table, 'LEFT') ->on("$privgr_table.privilege_id", '=', "$privilege_table.id") ->on("$privgr_table.group_id", '=', DB::expr((int) $group->id)); $data = parent::select(NULL, $params, $query); // Add group properties foreach ($data as & $privileges) { $privileges['group_id'] = $group->id; $privileges['group_name'] = $group->name; } return new Models(get_class($privgr), $data); } /** * Find all privilege-group infos by given privilege * * @param Model_PrivilegeGroup $privgr * @param Model_Privilege $privilege * @param array $params * @return Models */ public function find_all_by_privilege(Model_PrivilegeGroup $privgr, Model_Privilege $privilege, array $params = NULL) { $privgr_table = $this->table_name(); $privilege_table = Model_Mapper::factory('Model_Privilege_Mapper')->table_name(); $group_table = Model_Mapper::factory('Model_Group_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array( array("$group_table.id", 'group_id'), array("$group_table.name", 'group_name'), "$privgr_table.active" ); $query = DB::select_array($columns) ->from($group_table) ->join($privgr_table, 'LEFT') ->on("$privgr_table.group_id", '=', "$group_table.id") ->on("$privgr_table.privilege_id", '=', DB::expr((int) $privilege->id)); $data = parent::select(array(), $params, $query); // Add property properties foreach ($data as & $privileges) { $privileges['privilege_id'] = $privilege->id; $privileges['caption'] = $privilege->caption; $privileges['system'] = $privilege->system; } return new Models(get_class($privgr), $data); } }<file_sep>/modules/general/blocks/classes/form/backend/block.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Block extends Form_Backend { /** * Initialize form fields */ public function init() { // Set html class $this->attribute('class', 'w99per'); // ----- "general" tab $tab = new Form_Fieldset_Tab('general', array('label' => 'Основные свойства')); $this->add_component($tab); // ----- Name $options = Kohana::config('blocks.names'); if (empty($options)) { $options = array(); } $element = new Form_Element_Select('name', $options, array('label' => 'Положение', 'required' => TRUE), array('maxlength' => 15)); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $tab->add_component($element); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $tab->add_component($element); // ----- Text $element = new Form_Element_Wysiwyg('text', array('label' => 'Содержимое')); $tab->add_component($element); // ----- "visibility" tab $tab = new Form_Fieldset_Tab('visibility', array('label' => 'Видимость на страницах')); $this->add_component($tab); // ----- Default_visibility $tab ->add_component(new Form_Element_Checkbox('default_visibility', array('label' => 'Блок отображается на новых страницах'))); // ----- Nodes visibility $nodes = Model::fly('Model_Node')->find_all_by_site_id($this->model()->site_id, array('order_by' => 'lft')); $options = array(); foreach ($nodes as $node) { $options[$node->id] = str_repeat('&nbsp;', ((int)$node->level - 1) * 4) . $node->caption; } $element = new Form_Element_CheckSelect('nodes_visibility', $options, array('label' => 'Отображать на страницах', 'default_selected' => $this->model()->default_visibility) ); $element->config_entry = 'checkselect_fieldset'; $tab->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/system/forms/classes/form/element/submit.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form input element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Submit extends Form_Element_Input { /** * Default type of input is "submit" * * @return string */ public function default_type() { return 'submit'; } /** * Renders submit button * * @return string */ public function render_input() { return Form_Helper::input($this->full_name, $this->label, $this->attributes()); } /** * No js for submit buttons * * @return string */ public function render_js() { return FALSE; } } <file_sep>/modules/shop/acl/classes/form/backend/organizer.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Organizer extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class // User is being created or updated? $creating = ((int)$this->model()->id == 0) ? TRUE : FALSE; if ($creating) { $this->attribute('class', 'w400px'); } else { $this->attribute('class', "lb150px"); $this->layout = 'wide'; } // ----- General tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $tab->add_component($cols); // ----- Personal data $fieldset = new Form_Fieldset('personal_data', array('label' => 'Общие данные')); $cols->add_component($fieldset); // ----- Name $element = new Form_Element_Input('name', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $fieldset->add_component($element, 1); // ----- Email $element = new Form_Element_Input('email', array('label' => 'E-mail', 'required' => FALSE), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_Email(NULL,TRUE,TRUE)); ; $fieldset->add_component($element); // ----- Phone $element = new Form_Element_Input('phone', array('label' => 'Телефон', 'required' => FALSE), array('maxlength' => 63) ); $element->add_filter(new Form_Filter_TrimCrop(63)); $fieldset->add_component($element); // ----- Town $towns = Model_Town::towns(); $element = new Form_Element_Select('town_id', $towns, array('label' => 'Город', 'required' => TRUE)); $element ->add_validator(new Form_Validator_InArray(array_keys($towns))); $fieldset->add_component($element); // ----- Type $options = $this->model()->get_types(); $element = new Form_Element_Select('type', $options, array('label' => 'Тип')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- Address $fieldset->add_component(new Form_Element_TextArea('address', array('label' => 'Адрес'))); // ----- External Links $options_count = 1; if ($this->model()->id) { $options_count = count($this->model()->links); } $element = new Form_Element_Options("links", array('label' => 'Ссылки', 'options_count' => $options_count,'options_count_param' => 'options_count','option_caption' => 'добавить ссылку'), array('maxlength' => Model_Organizer::LINKS_LENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Organizer::LINKS_LENGTH)); $cols->add_component($element); // ----- Organizer if (!$creating) { // ----- Organizer Photo $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('images')->widget_images('organizer', $this->model()->id, 'user'); $cols->add_component($element, 2); } // ----- Description tab $tab = new Form_Fieldset_Tab('info_tab', array('label' => 'Об организации')); $this->add_component($tab); // ----- Description $tab->add_component(new Form_Element_Wysiwyg('info', array('label' => 'Об организации'))); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/shop/acl/views/frontend/user.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // ----- Set up urls $update_url = URL::to('frontend/acl/users/control', array('action'=>'update')); ?> <div class="wrapper lecturer"> <h1><?php echo $user->name?></h1> <div class="row-fluid"> <div class="span6 bio"> <?php echo Widget::render_widget('users', 'user_images', $user); ?> <?php if (is_array($user->webpages)) { foreach ($user->webpages as $webpage) { ?> <a class="website" href="<?php echo $webpage?>"><?php echo $webpage?></a> <?php }} ?> <?php echo Widget::render_widget('users', 'links', $user); ?> </div> <div class="span6 content"> <?php echo $user->info ?> <!-- <p class="who meta">Контактное лицо: <span><?php if ($user->name) echo "$user->name,"; ?><?php if ($user->phone) echo "$user->phone,"; ?><?php echo $user->email ?></span></p> --> <p class="typelec meta">Институция: <span><?php echo $user->organizer->full_name ?></span></p> <p class="address meta">Адрес институции: <span><?php echo $user->organizer->full_address ?></span></p> </div> </div> <div class="b-social"></div> <div class="action"> <!--<a href="#messageModal" data-toggle="modal" class="button write-message">Написать сообщение</a> --> <?php if (Auth::granted('user_update') && ($user->id === Model_User::current()->id)) { ?> <a href="<?php echo $update_url ?>" class="link-edit"><i class="icon-pencil icon-white"></i></a> <?php } ?> </div> </div> <?php echo Widget::render_widget('products','products', 'frontend/small_products'); ?> <?php echo Widget::render_widget('telemosts','telemosts_by_owner', Auth::instance()->get_user()); ?> <?php echo Widget::render_widget('telemosts','app_telemosts_by_owner', Auth::instance()->get_user()); ?> <?php echo Widget::render_widget('telemosts','goes_by_owner', Auth::instance()->get_user()); ?> <file_sep>/application/classes/model/mapper/nestedset.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Represents a hierarchical structure in database table using nested sets * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Model_Mapper_NestedSet extends Model_Mapper { public function init() { parent::init(); $this->add_column('lft', array('Type' => 'int unsigned', 'Key' => 'INDEX')) ->add_column('rgt', array('Type' => 'int unsigned', 'Key' => 'INDEX')) ->add_column('level', array('Type' => 'smallint unsigned', 'Key' => 'INDEX')); } /** * Prepare tree item for saving * calculate necessary values, update nested set structure * * @param Model $model * @param boolean $force_create * @param array $values that will be prepared for saving in the database * @return array */ public function before_save(Model $model, $force_create = FALSE, array $values = array()) { $values = parent::before_save($model, $force_create, $values); if ( ! isset($model->id) || $force_create) { // Inserting new row to db $values = $this->before_create($model, $values); } else { // Updating row in db $values = $this->before_update($model, $values); } return $values; } /** * Prepare values & table structure for a new model * * @param Model $model * @param array $values * @return array */ public function before_create(Model $model, array $values) { $this->lock(); if ((int) $model->parent_id > 0) { // Insert node as child of parent_id DB::select(DB::expr('@parentRight:=`rgt`, @parentLevel:=`level`')) ->from($this->table_name()) ->where('id', '=', (int) $model->parent_id) ->execute($this->get_db()); DB::update($this->table_name()) ->set(array('rgt' => DB::expr('rgt + 2'))) ->where('rgt', '>=', DB::expr('@parentRight')) ->execute($this->get_db()); DB::update($this->table_name()) ->set(array('lft' => DB::expr('lft + 2'))) ->where('lft', '>', DB::expr('@parentRight')) ->execute($this->get_db()); } else { // defaults for empty table DB::select(DB::expr('@parentRight:=1, @parentLevel:=0')) ->execute($this->get_db()); // Insert new as child of root DB::select(DB::expr('@parentRight:=IFNULL((`rgt`+1),1), @parentLevel:=0')) ->from($this->table_name()) ->order_by('rgt', 'DESC') ->limit(1) ->execute($this->get_db()); } $values['lft'] = DB::expr('@parentRight'); $values['rgt'] = DB::expr('@parentRight + 1'); $values['level'] = DB::expr('@parentLevel + 1'); $this->unlock(); return $values; } /** * Updates existing row * * @param Model $model * @param array $values * @return array */ public function before_update(Model $model, array $values) { $pk = $this->get_pk(); $this->lock(); // ----- Node is moved from old_parent to new_parent $parent_id = (int) $model->parent_id; if ($parent_id > 0) { // get old_parent (current parent for node) $old_parent = array(); $old_parent = $this->select_row( DB::where('lft', '<', (int) $model->lft)->and_where('rgt', '>', (int) $model->rgt), array( 'order_by' => 'level', 'desc' => TRUE, 'limit' => 1, 'columns' => array($pk, 'lft', 'rgt', 'level') ) ); // get new_parent (where the node will be moved to) $new_parent = array(); if ($parent_id > 0) { $new_parent = $this->select_row( DB::where($pk, '=', $parent_id), array('columns' => array($pk, 'lft', 'rgt', 'level')) ); } $old_parent_id = ! empty($old_parent) ? $old_parent[$pk] : NULL; $new_parent_id = ! empty($new_parent) ? $new_parent[$pk] : NULL; } else { // Don't move $new_parent_id = $old_parent_id = NULL; } // Move node only when new parent differs from old parent if ($new_parent_id !== $old_parent_id) { $lft = (int) $model->lft; $rgt = (int) $model->rgt; $width = $rgt - $lft + 1; $level = (int) $model->level; if ( ! empty($new_parent)) { // ----- Move node to existing parent node $level_diff = $new_parent['level'] - $level + 1; if ($new_parent['rgt'] < $rgt) { // Moving to the "left" $diff = $new_parent['rgt'] + $width - 1 - $rgt; DB::update($this->table_name()) ->set(array( 'level' => DB::expr("IF(`lft` < $lft, `level`, `level` + ($level_diff))"), 'lft' => DB::expr("IF(`lft` < $lft, `lft` + $width, `lft` + ($diff))") )) ->where('lft', '>', $new_parent['rgt']) ->and_where('lft', '<', $rgt) ->execute($this->get_db()); DB::update($this->table_name()) ->set(array('rgt' => DB::expr("IF(`rgt` < $lft, `rgt` + $width, `rgt` + ($diff))"))) ->where('rgt', '>=', $new_parent['rgt']) ->and_where('rgt', '<=', $rgt) ->execute($this->get_db()); } else { // Moving to the "right" $diff = $new_parent['rgt'] - 1 - $rgt; DB::update($this->table_name()) ->set(array( 'level' => DB::expr("IF(`lft` > $rgt, `level`, `level` + ($level_diff))"), 'lft' => DB::expr("IF(`lft` > $rgt, `lft` - $width, `lft` + ($diff))") )) ->where('lft', '<', $new_parent['rgt']) ->and_where('lft', '>=', $lft) ->execute($this->get_db()); DB::update($this->table_name()) ->set(array('rgt' => DB::expr("IF(`rgt` > $rgt, `rgt` - $width, `rgt` + ($diff))"))) ->where('rgt', '<', $new_parent['rgt']) ->and_where('rgt', '>', $lft) ->execute($this->get_db()); } } else // if (empty($new_parent)) { // ----- Move node to root (moving to "right") DB::select(DB::expr("@level_diff:=-" . ($level - 1) . ", @diff:=`rgt`-$rgt")) ->from($this->table_name()) ->order_by('rgt', 'DESC') ->limit(1) ->execute($this->get_db()); DB::update($this->table_name()) ->set(array( 'level' => DB::expr("IF(`lft` > $rgt, `level`, `level` + @level_diff)"), 'lft' => DB::expr("IF(`lft` > $rgt, `lft` - $width, `lft` + @diff)") )) ->where('lft', '>=', $lft) ->execute($this->get_db()); DB::update($this->table_name()) ->set(array('rgt' => DB::expr("IF(`rgt` > $rgt, `rgt` - $width, `rgt` + @diff)"))) ->where('rgt', '>', $lft) ->execute($this->get_db()); } } unset($values['lft']); unset($model->lft); unset($values['rgt']); unset($model->rgt); unset($values['level']); unset($model->level); $this->unlock(); // print structure errors /* $errors = $this->check_structure(); if (!empty($errors)) { foreach ($errors as $error) { echo '<strong>' . $error[0] . '</strong><br />'; if (isset($error[1]) && is_array($error[1])) { foreach ($error[1] as $row) { echo print_r($row, TRUE) . '<br />'; } } echo '<br />'; } } * */ return $values; } /*************************************************************************** * Find **************************************************************************/ /** * Find all models by given condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return ModelsTree_NestedSet|Models|array */ public function find_all_by( Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { // ----- params // This flag indicates whether the result must be reordered when returned as list $reorder_list = TRUE; // Apply correct sorting direction, when sorting by lft or rgt (this equals to "position" sotring) if (isset($params['order_by']) && ($params['order_by'] == 'lft' || $params['order_by'] == 'rgt')) { if (empty($params['desc'])) { $params['order_by'] = 'lft'; } else { $params['order_by'] = 'rgt'; } $reorder_list = FALSE; // We do not need to reoder the result it its order is "ORDER BY lft/rgt" } if ( ! isset($params['key'])) { $params['key'] = $this->get_pk(); } if ( ! empty($params['batch'])) { $params['offset'] = $this->_batch_offset; $params['limit'] = $params['batch']; } // ----- cache if ($this->cache_find_all) { $condition = $this->_prepare_condition($condition); $hash = $this->params_hash($params, $condition); if (isset($this->_cache[$hash])) { // Cache hit! return $this->_cache[$hash]; } } $result = $this->select($condition, $params, $query); if ( ! empty($params['batch'])) { // Batch find if ( ! empty($result)) { $this->_batch_offset += count($result); } else { // Reset $this->_batch_offset = 0; } } // Return the result of the desired type if ( ! empty($params['as_array'])) { // Intentionally blank - result is already an array } elseif ( ! empty($params['as_list'])) { $result = new Models(get_class($model), $result, $params['key']); } elseif (empty($params['as_tree'])) { // Return result as models LIST, but in the natural tree order if ($reorder_list) { // List needs to be reordered $result = new ModelsTree_NestedSet(get_class($model), $result, $params['key']); $result = $result->as_list(); } else { $result = new Models(get_class($model), $result, $params['key']); } } else { // Return as models tree $result = new ModelsTree_NestedSet(get_class($model), $result, $params['key']); } // ----- cache if ($this->cache_find_all) { if (count($this->_cache) < $this->cache_limit) { $this->_cache[$hash] = $result; } } return $result; } /** * Select all subnodes of given node * * @param Model $model * @param array $params * @return ModelsTree_NestedSet|Models|array */ public function find_all_subtree($model, array $params = NULL) { $condition = DB::where('lft', '>', (int)$model->lft) ->and_where('rgt', '<', (int)$model->rgt); return $this->find_all_by($model, $condition, $params); } /** * Select all subnodes of given node with this node * * @param Model $model * @param array $params * @return ModelsTree_NestedSet|Models|array */ public function find_all_with_subtree($model, array $params = NULL) { $condition = DB::where('lft', '>=', (int)$model->lft) ->and_where('rgt', '<=', (int)$model->rgt); return $this->find_all_by($model, $condition, $params); } /** * Select all nodes from tree except those, that are subnodes of the given node * by criteria * * @param Model $model * @param Database_Expression_Where $condition * @param array $params * @return ModelsTree_NestedSet|Models|array */ public function find_all_but_subtree_by(Model $model, Database_Expression_Where $condition = NULL, array $params = NULL) { if ($condition !== NULL) { $condition ->and_where_open() ->and_where('lft', '<', (int) $model->lft) ->or_where('rgt', '>', (int) $model->rgt) ->and_where_close(); } else { $condition = DB::where('lft', '<', (int) $model->lft) ->or_where('rgt', '>', (int) $model->rgt); } return $this->find_all_by($model, $condition, $params); } /** * Select direct children of given node * * @param Model $model * @param array $params * @return Models|array */ public function find_all_children($model, array $params = NULL) { $lft = (int)$model->lft; $rgt = (int)$model->rgt; $level = (int) $model->level; $condition = DB::where('level', '=', $level + 1); if ($lft != 0 && $rgt != 0) { $condition ->and_where('lft', '>', $lft) ->and_where('rgt', '<', $rgt); } return parent::find_all_by($model, $condition, $params); } /** * Find all parents for given node sorted by level * Sorting direction and limit can be specified in $params * * @param Model $model * @param array $params * @param array $columns * @return Models|array */ public function find_all_parents(Model $model, array $params = NULL) { $condition = DB::where('lft', '<', (int)$model->lft) ->and_where('rgt', '>', (int)$model->rgt); $params['order_by'] = 'level'; return parent::find_all_by($model, $condition, $params); } /** * Find all siblings for given node sorted by left * Sorting direction and limit can be specified in $params * * @param Model $model * @param array $params * @param array $columns * @return Models|array */ public function find_all_siblings(Model $model, array $params = NULL) { $condition = DB::where('level', '=', (int)$model->level); $params['order_by'] = 'lft'; return parent::find_all_by($model, $condition, $params); } /** * Find parent for given node * * @param Model $model * @param array $params * @return Model */ public function find_parent(Model $model, array $params = NULL) { $where = DB::where('lft', '<', (int)$model->lft) ->and_where('rgt', '>', (int)$model->rgt); $params['order_by'] = 'level'; $params['desc'] = TRUE; $result = $this->select_row($where, $params); $class = get_class($model); $parent = new $class; $parent->properties($result); return $parent; } /** * Find root parent for given node * * @param Model $model * @param array $params * @return Model */ public function find_root_parent(Model $model, array $params = NULL) { if ($model->level == 1) { // Already root node return $model->get_properties(); } $where = DB::where('lft', '<', $model->lft) ->and_where('rgt', '>', $model->rgt) ->and_where('level', '=', 1); $result = $this->select_row($where, $params); $class = get_class($model); $parent = new $class; $parent->properties($result); return $parent; } /*************************************************************************** * Delete **************************************************************************/ /** * Deletes node with all subnodes * * @param Model $model */ public function delete_with_subtree(Model $model) { $this->lock(); $pk = $this->get_pk(); $values = $this->select_row(DB::where($pk, '=', $model->$pk), array('columns' => array('lft', 'rgt'))); if ( ! empty($values)) { $this->delete_rows(DB::where('lft', '>=', $values['lft'])->and_where('rgt', '<=', $values['rgt'])); $width = $values['rgt'] - $values['lft'] + 1; DB::update($this->table_name()) ->set(array('lft' => DB::expr("`lft` - $width"))) ->where('lft', '>', $values['rgt']) ->execute($this->get_db()); DB::update($this->table_name()) ->set(array('rgt' => DB::expr("`rgt` - $width"))) ->where('rgt', '>', $values['rgt']) ->execute($this->get_db()); } $this->unlock(); } /*************************************************************************** * Position **************************************************************************/ /** * Move model one position up * * @param Model $model * @param Database_Expression_Where $condition */ public function up(Model $model, Database_Expression_Where $condition = NULL) { $pk = $this->get_pk(); $db = $this->get_db(); // Escape everything $id = $db->quote($model->$pk); $pk = $db->quote_identifier($pk); $table = $db->quote_table($this->table_name()); if ($condition !== NULL) { $condition = " AND " . (string) $condition; } else { $condition = ''; } $this->lock(); $db->query(NULL, "SELECT @lft:=NULL, @rgt:=NULL, @next_lft:=null, @next_rgt:=null, @next_id:=null", FALSE); $db->query(NULL, "SELECT @lft:=`lft`, @rgt:=`rgt`, @width:=`rgt`-`lft`+1 FROM $table WHERE ($pk=$id)", FALSE); $db->query(NULL, "SELECT @next_id:=$pk, @next_lft:=`lft`, @next_rgt:=`rgt`, @next_width:=`rgt`-`lft`+1 FROM $table WHERE (`lft`=@rgt+1) $condition LIMIT 1", FALSE); $db->query(NULL, "UPDATE $table " . " SET `lft`=IF(`lft`<@rgt,`lft`+@next_width,`lft`-@width), " . " `rgt`=IF(`rgt`<=@rgt,`rgt`+@next_width,`rgt`-@width) " . " WHERE (@next_id IS NOT NULL) AND (`lft`>=@lft AND `rgt`<=@next_rgt)", FALSE); $this->unlock(); } /** * Move model one position down * * @param Model $model */ public function down(Model $model, Database_Expression_Where $condition = NULL) { $pk = $this->get_pk(); $db = $this->get_db(); // Escape everything $id = $db->quote($model->$pk); $pk = $db->quote_identifier($pk); $table = $db->quote_table($this->table_name()); if ($condition !== NULL) { $condition = " AND " . (string) $condition; } else { $condition = ''; } $this->lock(); $db->query(NULL, "SELECT @lft:=NULL, @rgt:=NULL, @next_lft:=null, @next_rgt:=null, @next_id:=null", FALSE); $db->query(NULL, "SELECT @lft:=`lft`, @rgt:=`rgt`, @width:=`rgt`-`lft`+1 FROM $table WHERE ($pk=$id)", FALSE); $db->query(NULL, "SELECT @next_id:=$pk, @next_lft:=`lft`, @next_rgt:=`rgt`, @next_width:=`rgt`-`lft`+1 FROM $table WHERE (`rgt`=@lft-1) $condition LIMIT 1", FALSE); $db->query(NULL, "UPDATE $table " . " SET `lft`=IF(`lft`>=@lft,`lft`-@next_width,`lft`+@width), " . " `rgt`=IF(`rgt`>@lft,`rgt`-@next_width,`rgt`+@width) " . " WHERE (@next_id IS NOT NULL) AND (`lft`>=@next_lft AND `rgt`<=@rgt)", FALSE); $this->unlock(); } /*************************************************************************** * Misc **************************************************************************/ /** * Returns true if $child is a child of $parent * ($parent can be either a model or an id) * * @param Model $child * @param Model|integer $parent * @return boolean */ public function is_child_of(Model $child, $parent) { if ($parent instanceof Model) { return (isset($parent->id) && $parent->lft < $child->lft && $parent->rgt > $child->rgt); } else { return $this->exists( DB::where('id', '=', (int) $parent) ->and_where('lft', '<', $child->lft) ->and_where('rgt', '>', $child->rgt) ); } } /** * Returns true if $parent is parent of $child * ($child can be either a model or an id) * * @param Model $parent * @param Model|integer $child * @return boolean */ public function is_parent_of(Model $parent, $child) { if ($child instanceof Model) { return (isset($child->id) && $child->lft > $parent->lft && $child->rgt < $parent->rgt); } else { return $this->exists( DB::where('id', '=', (int) $child) ->and_where('lft', '>', $parent->lft) ->and_where('rgt', '<', $parent->rgt) ); } } /** * Checks the structure of tree */ public function check_structure() { $errors = array(); // 1. Check that lft is less than rgt for every row $invalid_rows = $this->select(DB::where('lft', '>=', DB::expr("`rgt`")), array('id', 'lft', 'rgt', 'level')); if ( ! empty($invalid_rows)) { $errors[] = array("There are nodes with 'lft' greater or equeal to 'rgt'!", $invalid_rows); } // 2. Check that all levels are correctly computed $level_query = DB::select(DB::expr("(COUNT(`id`)+1)")) ->from(array($this->table_name(), 't2')) ->where('t2.lft', '<', DB::expr('t1.lft')) ->where('t2.rgt', '>', DB::expr('t1.rgt')); $query = DB::select('id', 'lft', 'rgt', 'level') ->from(array($this->table_name(), 't1')) ->where('level', '<>', $level_query); $invalid_rows = $query->execute($this->get_db())->as_array(); if (count($invalid_rows)) { // Convert to correct types foreach ($invalid_rows as & $values) { $values = $this->_unsqlize($values); } $errors[] = array("There are nodes with incorrectly calculated levels!", $invalid_rows); } // 3. Check that all lft and rgt values are unique $query = DB::select( array('t1.id', 'id1'), array('t1.lft', 'lft1'), array('t1.rgt', 'rgt1'), array('t2.id', 'id2'), array('t2.lft', 'lft2'), array('t2.rgt', 'rgt2') ) ->from(array($this->table_name(), 't1'), array($this->table_name(), 't2')) ->and_where_open() ->where('t2.lft', '=', DB::expr('t1.lft')) ->or_where('t2.lft', '=', DB::expr('t1.rgt')) ->or_where('t2.rgt', '=', DB::expr('t1.rgt')) ->and_where_close() ->and_where('t2.id', '<>', DB::expr('t1.id')); $invalid_rows = $query->execute($this->get_db())->as_array(); if (count($invalid_rows)) { // Convert to correct types foreach ($invalid_rows as & $values) { $values = $this->_unsqlize($values); } $errors[] = array("There are nodes with duplicate lft or rgt values!", $invalid_rows); } // 4. Check that there are no intersections between (lft, rgt) intervals, only nesting $query = DB::select( array('t1.id', 'id1'), array('t1.lft', 'lft1'), array('t1.rgt', 'rgt1'), array('t2.id', 'id2'), array('t2.lft', 'lft2'), array('t2.rgt', 'rgt2') ) ->from(array($this->table_name(), 't1'), array($this->table_name(), 't2')) ->or_where_open() ->where('t2.lft', '>', DB::expr('t1.lft')) ->and_where('t2.lft', '<', DB::expr('t1.rgt')) ->and_where('t2.rgt', '>', DB::expr('t1.rgt')) ->or_where_close() ->or_where_open() ->where('t2.rgt', '>', DB::expr('t1.lft')) ->and_where('t2.rgt', '<', DB::expr('t1.rgt')) ->and_where('t2.lft', '<', DB::expr('t1.lft')) ->or_where_close(); $invalid_rows = $query->execute($this->get_db())->as_array(); if (count($invalid_rows)) { // Convert to correct types foreach ($invalid_rows as & $values) { $values = $this->_unsqlize($values); } $errors[] = array("There are nodes who have intersecting lft and rgt values!", $invalid_rows); } // 5. Difference between max rgt and min lft + 1 must be 2*number of elements $tmp = $this->select_row(array( 'columns' => array( array('MIN("lft")', 'min_lft'), array('MAX("rgt")', 'max_rgt'), array('COUNT("*")', 'count') ) )); if ($tmp['min_lft'] != 1) { $errors[] = array("Minimal lft value must be 1, not " . $tmp['min_lft'] . " !"); } if ($tmp['max_rgt'] - $tmp['min_lft'] + 1 != 2 * $tmp['count']) { $errors[] = array( "Maximum rgt minus minimum lft plus 1 must be equal to 2 x number of elements. " . "But: " . $tmp['max_rgt'] . " - " . $tmp['min_lft'] . " + 1 != 2 * " . $tmp['count'] . "!" ); } return $errors; } }<file_sep>/modules/frontend/classes/route/frontend.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Frontend route * * @package Eresus * @author <NAME> (<EMAIL>) */ class Route_Frontend extends Route { /** * Does this route match the specified uri? * * @param string $uri * @return array */ public function matches($uri) { $params = parent::matches($uri); // Add 'frontend' directory if ($params !== FALSE && ! isset($params['directory'])) { $params['directory'] = 'frontend'; } return $params; } /** * Generates a URI for the current route based on the parameters given. * * * @param array URI parameters * @return string * @throws Kohana_Exception * @uses Route::REGEX_Key */ public function uri(array $params = NULL) { // Add 'frontend' directory if ($params !== FALSE && ! isset($params['directory'])) { $params['directory'] = 'frontend'; } return parent::uri($params); } }<file_sep>/modules/system/forms/classes/form/element/hidden.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form input element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Hidden extends Form_Element { /** * Template for hidden element * * @param string $type */ public function default_template($type = 'element') { switch ($type) { case 'element': return '{{input}}'; default: return parent::default_template($type); } } /** * Default type of input is "hidden" * * @return string */ public function default_type() { return 'hidden'; } /** * Renders hidden element * * @return string */ public function render_input() { return Form_Helper::hidden($this->full_name, $this->value, $this->attributes()); } /** * Get hidden attributes * * @return array */ public function attributes() { $attributes = parent::attributes(); // Set element type if ( ! isset($attributes['type'])) { $attributes['type'] = $this->type; } return $attributes; } } <file_sep>/modules/general/menus/classes/model/menu.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Menu extends Model { /** * Default value for default visibility for nodes in this menu * * @return boolean */ public function default_default_visibility() { return TRUE; } /** * Default site id for menu * * @return id */ public function default_site_id() { return Model_Site::current()->id; } /** * Default value for maximum menu level * * @return integer */ public function default_max_level() { return 0; } /** * Default values for additional settings * * @return array */ public function default_settings() { return array( 'root_level' => 0 ); } /** * Load root node by root node id for this menu * * @return Model_Node */ public function get_root_node() { if ( ! isset($this->_properties['root_node'])) { $root_node = new Model_Node(); if (empty($this->settings['root_selected'])) { // Root node is defined explicitly if ((int)$this->root_node_id > 0) { $root_node->find((int) $this->root_node_id); } } else { // Root node is choosen from currently selected branch $root_level = (int) $this->settings['root_level']; $path = array_values(Model_Node::current()->path->as_array()); if (count($path)) { if ($root_level <= 0) { // Count backwards from the end of the path $root_level = count($path) + $root_level; if ($root_level < 1) { $root_level = 1; } } if (isset($path[$root_level - 1])) { $root_id = (int) $path[$root_level - 1]['id']; $root_node->find($root_id); } } } $this->_properties['root_node'] = $root_node; } return $this->_properties['root_node']; } /** * Select all nodes with visibility information * * @return ModelsTree_NestedSet */ public function get_nodes() { if ( ! isset($this->_properties['nodes'])) { $this->_properties['nodes'] = Model_Mapper::factory('MenuNode_Mapper')->find_all_menu_nodes($this, new Model_Node()); } return $this->_properties['nodes']; } /** * Get nodes visibility info * * @return array(node_id => visible) */ public function get_nodes_visibility() { if ( ! isset($this->_properties['nodes_visibility'])) { $visibility = array(); foreach ($this->nodes as $node) { $visibility[$node->id] = $node->visible; } $this->_properties['nodes_visibility'] = $visibility; } return $this->_properties['nodes_visibility']; } /** * Select nodes for given menu with respect to root id and visibility information * * @return ModelsTree_NestedSet */ public function get_visible_nodes() { if ( ! isset($this->_properties['visible_nodes'])) { $this->_properties['visible_nodes'] = Model_Mapper::factory('MenuNode_Mapper')->find_all_visible_menu_nodes($this, $this->root_node); } return $this->_properties['visible_nodes']; } /** * Save menu properties and menu nodes visibility information * * @param boolean $force_create * @return Model_Menu */ public function save($force_create = FALSE) { parent::save($force_create); // Update nodes visibility info for this menu if ($this->id !== NULL && is_array($this->nodes_visibility)) { Model_Mapper::factory('MenuNode_Mapper')->update_menu_nodes($this, $this->nodes_visibility); } return $this; } /** * Validate create and update actions * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { return $this->validate_name($newvalues); } /** * Validate menu name * * @param array $newvalues * @return boolean */ public function validate_name(array $newvalues) { if ( ! isset($newvalues['name'])) { $this->error('Вы не указали имя меню!', 'name'); return FALSE; } if ($this->exists_another_by_name_and_site_id($newvalues['name'], $this->site_id)) { $this->error('Меню с таким именем уже существует!', 'name'); return FALSE; } return TRUE; } } <file_sep>/modules/system/forms/classes/form/filter/datetimesimple.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Filter datetime values * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Filter_DateTimeSimple extends Form_Filter { /** * @param string $value */ public function filter($value) { $value = trim((string) $value); $format = $this->get_form_element()->format; if ($value != '' && $format !== NULL) { // Extract special characters form format - we are interested in order in which // these characters appear if (preg_match_all('/(Y|m|d|H|i|s)/', $format, $special_chars)) { $special_chars = array_values($special_chars[0]); // Extract numbers from value $values = preg_split('/[^\d]+/i', $value, NULL, PREG_SPLIT_NO_EMPTY); $day = '00'; $month = '00'; $year = '0000'; $second = '00'; $minute = '00'; $hour = '00'; // Ther order of numbers is expected to be the same, as the order of special chars foreach ($special_chars as $i => $special_char) { if ( ! isset($values[$i])) break; switch ($special_char) { case 'd': $day = (int) $values[$i]; $day = str_pad($day, 2, '0', STR_PAD_LEFT); break; case 'm': $month = (int) $values[$i]; $month = str_pad($month, 2, '0', STR_PAD_LEFT); break; case 'Y': $year = (int) $values[$i]; if ($year < 100) { $year = $year + ($year < 70 ? 2000 : 1900); } $year = str_pad($year, 4, '0', STR_PAD_LEFT); break; case 's': $second = (int) $values[$i]; $second = str_pad($second, 2, '0', STR_PAD_LEFT); break; case 'i': $minute = (int) $values[$i]; $minute = str_pad($minute, 2, '0', STR_PAD_LEFT); case 'H': $hour = (int) $values[$i]; $hour = str_pad($hour, 2, '0', STR_PAD_LEFT); } } $value = str_replace( array('d', 'm', 'Y', 's', 'i', 'H'), array($day, $month, $year, $second, $minute, $hour), $format ); } } return $value; } }<file_sep>/modules/shop/catalog/classes/task/comdi/start.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Create event through COMDI API */ class Task_Comdi_Start extends Task_Comdi_Base { public static $params = array( 'key', 'event_id', 'stage' ); /** * Default parameters for this task * @var array */ public static $default_params = array( 'stage' => 'START' ); /** * Construct task */ public function __construct() { parent::__construct('http://my.webinar.ru'); $this->default_params(self::$default_params); } /** * Run the task */ public function run() { $xml_response = parent::send('/api0/Status.php',$this->params(self::$params)); $id = ($xml_response['event_id'] == null)? null:(string)$xml_response['event_id']; if ($id === NULL) { $this->set_status_info('Мероприятие не было запущено'); } else { $this->set_status_info('Мероприятие запущено'); } return $id; } } <file_sep>/modules/shop/discounts/classes/couponsite/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class CouponSite_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('coupon_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); } /** * Link coupon to sites * * @param Model_Payment $coupon * @param array $sites array(site_id => TRUE/FALSE) */ public function link_coupon_to_sites(Model_Coupon $coupon, array $sites) { $this->delete_rows(DB::where('coupon_id', '=', (int) $coupon->id)); foreach ($sites as $site_id => $selected) { if ($selected) { $this->insert(array( 'coupon_id' => $coupon->id, 'site_id' => $site_id )); } } } }<file_sep>/modules/system/forms/classes/form/validator/inarray.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validates that specified value is in array * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_InArray extends Form_Validator { const NOT_FOUND = 'NOT_FOUND'; const EMPTY_OPTIONS = 'EMPTY_OPTIONS'; protected $_messages = array( self::EMPTY_OPTIONS => 'Empty options!', self::NOT_FOUND => 'Поле :label имеет некорректное значение!' ); /** * List of valid options for value * @var array */ protected $_options = array(); /** * It's possible to select from empty options * @var boolean */ protected $_allow_empty_options = TRUE; /** * Creates validator * * @param array $options List of valid options * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty strings * @param boolean $allow_underscore Allow underscores */ public function __construct(array $options, array $messages = NULL, $breaks_chain = TRUE, $allow_empty_options = TRUE) { $this->_options = $options; $this->_allow_empty_options = $allow_empty_options; parent::__construct($messages, $breaks_chain); } /** * Set up options for validator * * @param array $options */ public function set_options(array $options) { $this->_options = $options; } /** * Validate that value is among valid options * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { if (empty($this->_options) && ! $this->_allow_empty_options) { // Empty options not allowed? $this->_error(self::EMPTY_OPTIONS); return FALSE; } if ( ! in_array($this->_value, $this->_options)) { $this->_error(self::NOT_FOUND); return FALSE; } return TRUE; } }<file_sep>/modules/system/database_eresus/classes/config/database.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Database-based configuration loader. * * Schema for configuration table: * * group_name varchar(128) * config_key varchar(128) * config_value text * primary key (group_name, config_key) * * @package Eresus * @author <NAME> (<EMAIL>) */ class Config_Database extends Kohana_Config_Database { public function __construct(array $config = NULL) { // In development environment use dbtable to automatically create/update needed table if (Kohana::$environment !== Kohana::PRODUCTION) { $dbtable = new DbTable_Config(NULL, $this->_database_table); } parent::__construct($config); } } <file_sep>/modules/system/forms/classes/form/validator/regexp.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validate agains a regular expression * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_Regexp extends Form_Validator { const EMPTY_STRING = 'EMPTY_STRING'; const NOT_MATCH = 'NOT_MATCH'; protected $_messages = array( self::EMPTY_STRING => 'Value cannot be an empty string', self::NOT_MATCH => '":value" does not match pattern ":regexp"' ); /** * Regular expression to match against * @var string */ protected $_regexp; /** * Allow empty strings * @var boolean */ protected $_allow_empty = FALSE; /** * Creates Regexp validator * * @param string $regexp Regular expression * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty strings */ public function __construct($regexp, array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE) { parent::__construct($messages, $breaks_chain); $this->_regexp = $regexp; $this->_allow_empty = $allow_empty; } /** * Validate * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $value = (string) $this->_value; if (preg_match('/^\s*$/', $value)) { // An empty string allowed ? if (!$this->_allow_empty) { $this->_error(self::EMPTY_STRING); return FALSE; } else { return TRUE; } } if ( ! preg_match($this->_regexp, $value)) { $this->_error(self::NOT_MATCH); return FALSE; } return TRUE; } /** * Replaces :value and :regexp * * @param string $error_text * @return string */ protected function _replace_placeholders($error_text) { $error_text = parent::_replace_placeholders($error_text); return str_replace(':regexp', $this->_regexp, $error_text); } /** * Render javascript for this validator * * @return string */ public function render_js() { $error = $this->_messages[self::NOT_MATCH]; $error = $this->_replace_placeholders($error); $js = "v = new jFormValidatorRegexp(" . "{$this->_regexp}" . ", '$error'" . ", " . (int)$this->_allow_empty . ", " . (int)$this->_breaks_chain . ");\n"; return $js; } }<file_sep>/modules/shop/acl/config/acl.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( 'email' => array( 'client' => array( 'subject' => 'Восстановление пароля на сайте "{{site}}"', 'body' => 'По вашей учетной записи была подана заявка на восстановление пароля. Для введения нового пароля перейдите по ссылке: {{recovery_link}} Если вы не подавали эту заявку, и это не первое подобное сообщение, советуем обратиться в службу клиентской поддержки портала vse.to. ' ) ) );<file_sep>/modules/shop/acl/classes/model/linkvalue/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_LinkValue_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('link_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('value', array('Type' => 'varchar(63)')); } /** * Update link values for given user * * @param Model_User $user */ public function update_values_for_user(Model_User $user) { foreach ($user->links as $link) { $name = $link->name; $value = $user->__get($name); if ($value === NULL) continue; $where = DB::where('user_id', '=', (int) $user->id) ->and_where('link_id', '=', (int) $link->id); if ($this->exists($where)) { $this->update(array('value' => $value), $where); } else { $this->insert(array( 'user_id' => (int) $user->id, 'link_id' => (int) $link->id, 'value' => $value )); } } } }<file_sep>/modules/general/nodes/views/backend/nodes_menu.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Add style to the layout Layout::instance()->add_style(Modules::uri('nodes') . '/public/css/backend/nodes.css'); // Current route name $current_route = Route::name(Request::current()->route); ?> <?php if ( ! count($nodes)) { // No nodes yet echo '<i>страниц нет</i>'; return; } ?> <div class="nodes_menu"> <?php foreach ($nodes as $node) : $type_info = Model_Node::node_type($node->type); // Is current node selected? $selected = FALSE; if (isset($type_info['model'])) { $selected = ($node->id == $node_id); } else { $selected = ($current_route == $type_info['backend_route']); } $url = $node->backend_url; // Highlight current node if ($selected) { $selected = 'selected'; } else { $selected = ''; } // Highlight inactive nodes if ( ! $node->node_active) { $active = 'node_inactive'; } elseif ( ! $node->active) { $active = 'inactive'; } else { $active = ''; } ?> <div class="node <?php echo "$selected $active";?>" style="padding-left: <?php echo ($node->level-1)*15; ?>px"> <a class="node_caption" href="<?php echo $url;?>"> <?php echo HTML::chars($node->caption); ?> </a> </div> <?php endforeach; ?> </div> <file_sep>/modules/backend/public/js/backend.js $(function(){ // ----- "Toggle all" support $('form').each(function(i, form){ $('.toggle_all', form).each(function(i, toggle){ // Toggle all form checkboxes by pattern, // where pattern is obtained form the "toggle" name // by stripping of 'toggle_all-' from the beginning var pattern = toggle.name.substr(11); // Create regexp from pattern (escape special chars) var re = pattern.replace('*', "\\w+"); re = re.replace(/([\[\]])/g, "\\$1"); re = new RegExp(re); $(toggle).click(function(){ var value = this.checked; // Toggle all checkboxes with names matching the pattern $('input[type=checkbox]', form).each(function(i, chk){ if (re.test(chk.name)) { chk.checked = value; } }); }); }); }); // ----- Custom select design restyle_selects(); }); /****************************************************************************** * Custom selects ******************************************************************************/ function restyle_selects(selects_ids) { // Store all select options popups here (ie6) restyle_selects.select_popups = []; if (!selects_ids) { selects_arr = $('select'); } else { selects_arr = new Array(); for (i = 0; i < selects_ids.length; i++) { selects_arr[i] = document.getElementById(selects_ids[i]); } } $(selects_arr).each(function(j, select){ // Wrap select element with decorators wrap_class = select.parentElement.className; if (wrap_class == "select_disabled" || wrap_class == "select") { $(select).unwrap(); select.parentElement.removeChild(document.getElementById(select.id+'_value')); } if (select.className =="disabled") { $(select).wrap('<div class="select_disabled" />'); } else { $(select).wrap('<div class="select" />'); } var value = $('<div id="'+select.id+'_value" class="value" />'); value.insertBefore(select); // Add value container // Update value on select var i = select.selectedIndex; if (select.options.length && i >= 0) { value.html(select.options[i].innerHTML); } $(select).change(function(){ var i = select.selectedIndex; if (select.options.length && i >= 0) { value.html(select.options[i].innerHTML); } }); // Apply dimensions var wrapper = $(select).parent(); var w = $(select).width(); // Increase select width //$(select).width(w - parseInt(wrapper.css('padding-right'))); // Adjust wrapper width wrapper.width(w-12); // Adjust value width value.width(w - parseInt(value.css('padding-left')) - parseInt(value.css('padding-right'))); if ($.browser.msie && $.browser.version <= 6) { // ----- IE6 only // Hide the select element $(select).hide(); // Create options popup var options = $('<div class="select_options" />'); $(document.body).prepend(options); restyle_selects.select_popups.push(options); // Stretch options to the width of wrapper //options.width(wrapper.width()); // Append options from select for (i = 0; i < select.options.length; i++) { var option = '<a href="#' + i + '">' + select.options[i].text + '</a>'; options.append(option); } // Select the option from list when clicked options.click(function(event){ // Determine the index of option selected if (event.target.href) { var ind = event.target.href.match(/#(\d+)/); if (ind.length) { ind = parseInt(ind[1]); select.selectedIndex = ind; $(select).trigger('change'); } options.hide(); event.preventDefault(); } }); // Show options popup for this select wrapper.click(function(event){ // Close all other popups restyle_selects.hide_popups(); // Show this popup options.show(); // Move to the bottom of wrapper options.offset({ top : wrapper.position().top + wrapper.height(), left : wrapper.position().left }); event.stopPropagation(); }); } }); if ($.browser.msie && $.browser.version <= 6) { // Close all options when document is clicked $(document).click(function(){ restyle_selects.hide_popups(); }) } } /****************************************************************************** * Custom selects ******************************************************************************/ /*function restyle_selects() { // Store all select options popups here (ie6) restyle_selects.select_popups = []; $('select').each(function(j, select){ // Wrap select element with decorators $(select).wrap('<div class="select" />'); // Add value container var value = $('<div class="value" />'); value.insertBefore(select); // Update value on select var i = select.selectedIndex; if (select.options.length && i >= 0) { value.html(select.options[i].innerHTML); } $(select).change(function(){ var i = select.selectedIndex; if (select.options.length && i >= 0) { value.html(select.options[i].innerHTML); } }); // Apply dimensions var wrapper = $(select).parent(); var w = $(select).width(); // Increase select width $(select).width(w + parseInt(wrapper.css('padding-right'))); // Adjust wrapper width wrapper.width(w); // Adjust value width value.width(w - parseInt(value.css('padding-left')) - parseInt(value.css('padding-right'))); if ($.browser.msie && $.browser.version <= 6) { // ----- IE6 only // Hide the select element $(select).hide(); // Create options popup var options = $('<div class="select_options" />'); $(document.body).prepend(options); restyle_selects.select_popups.push(options); // Stretch options to the width of wrapper options.width(wrapper.width()); // Append options from select for (i = 0; i < select.options.length; i++) { var option = '<a href="#' + i + '">' + select.options[i].text + '</a>'; options.append(option); } // Select the option from list when clicked options.click(function(event){ // Determine the index of option selected if (event.target.href) { var ind = event.target.href.match(/#(\d+)/); if (ind.length) { ind = parseInt(ind[1]); select.selectedIndex = ind; $(select).trigger('change'); } options.hide(); event.preventDefault(); } }); // Show options popup for this select wrapper.click(function(event){ // Close all other popups restyle_selects.hide_popups(); // Show this popup options.show(); // Move to the bottom of wrapper options.offset({ top : wrapper.position().top + wrapper.height(), left : wrapper.position().left }); event.stopPropagation(); }); } }); if ($.browser.msie && $.browser.version <= 6) { // Close all options when document is clicked $(document).click(function(){ restyle_selects.hide_popups(); }) } }*/ /** * Hide all select options popups (ie6) */ restyle_selects.hide_popups = function() { for (i = 0; i < restyle_selects.select_popups.length; i++) { restyle_selects.select_popups[i].hide(); } } /****************************************************************************** * Tabs ******************************************************************************/ /** * Initialize tabs */ function Tabs(tabs_id) { var self = this; // Find the container that holds the id of currently selected tab this.current_tab_cont = $("#" + tabs_id + "-current_tab"); this.current_tab_id = null; // Tabs {id : {tab : jQuery, content : jQuery}} this.tabs = {}; // Find all tabs and corresponding contents $("a[href^='#" + tabs_id +"']").each(function(i, tab) { // Extract tab id var matches = tab.href.match(/#(.*)/); if (matches) { // Find content with the same id var tab_id = matches[1]; var content = $('#' + tab_id); if (content.length) { // Corresponding content was found self.tabs[tab_id] = { 'tab' : $(tab), 'content' : content } // Select the tab when it is clicked $(tab).click(function(event) { self.select(tab_id); event.preventDefault(); }); } } }); // Select the current tab and deselect the other tabs var current_tab_id = this.get_current_tab_id(); for (var tab_id in this.tabs) { if ( ! current_tab_id || current_tab_id == tab_id) { // Highlight the current tab this.select(tab_id, true); current_tab_id = tab_id; } else { // Hide all other tabs this.tabs[tab_id].content.hide(); } } } /** * Select tab with specified tab id */ Tabs.prototype.select = function(tab_id, force) { if ( ! this.tabs[tab_id]) { // Invalid tab id was specified return; } var current_tab_id = this.get_current_tab_id(); if (tab_id == current_tab_id && ! force) { // Tab is already selected return; } // Deselect current tab if (current_tab_id && this.tabs[current_tab_id]) { // Hide content this.tabs[current_tab_id].content.hide(); // Unhighlight this.tabs[current_tab_id].tab.removeClass('selected'); } // Show the desired tab this.tabs[tab_id].content.show(); this.tabs[tab_id].tab.addClass('selected'); // Update current tab id this.set_current_tab_id(tab_id); } /** * Get the id of current tab */ Tabs.prototype.get_current_tab_id = function() { if (this.current_tab_cont.length) { // Container is assumed to be an "input" element //@TODO: Can be another element return this.current_tab_cont.val(); } else { return this.current_tab_id; } } /** * Set the id of current tab */ Tabs.prototype.set_current_tab_id = function(tab_id) { if (this.current_tab_cont.length) { // Container is assumed to be an "input" element //@TODO: Can be another element this.current_tab_cont.val(tab_id); } else { this.current_tab_id = tab_id; } } <file_sep>/modules/shop/catalog/views/frontend/forms/filter_price.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php /* @var $form Form */ echo $form->render_form_open(); ?> <div class="label"> <label>от</label> <?php echo $form->get_element('price_from')->render_input(); ?> <label>до</label> <?php echo $form->get_element('price_to')->render_input(); ?> </div> <input type="image" src="<?php echo URL::base(FALSE) . 'public/css/img/choose-button.gif'; ?>" alt="выбрать" class="submit" /> <?php echo $form->render_form_close(); ?><file_sep>/application/classes/log.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Abstract logger * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Log { // log levels const INFO = 1; const WARNING = 2; const ERROR = 3; const FATAL = 4; /** * If message count exceeds this limit - flush them via write() * @var integer */ public $flush_limit = 1024; /** * Messages * @var array */ protected $_messages = array(); /** * Add message to log * * @param integer $level * @param string $msg */ public function message($message, $level = self::INFO) { $this->_messages[] = array('message' => $message, 'level' => $level); if (count($this->_messages) > $this->flush_limit) { $this->flush(); } } /** * Flush current messages to log */ public function flush() { if ( ! empty($this->_messages)) { $this->_write(); $this->_messages = array(); } } /** * Write pending messages to log */ abstract protected function _write(); /** * Read log messages */ abstract public function read(); /** * Flush log on destruction */ public function __destruct() { $this->flush(); } }<file_sep>/modules/shop/catalog/classes/controller/frontend/products.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Products extends Controller_FrontendRES { // ----------------------------------------------------------------------- // MENU WIDGETS // ----------------------------------------------------------------------- /** * Render search bar */ public function widget_search() { $sectiongroup = Model_SectionGroup::current(); $form = new Form_Frontend_Search(); $form->get_element('search_text')->default_value = URL::decode($this->request->param('search_text')); if ($form->is_submitted() && $form->validate()) { $search_text = URL::encode($form->get_value('search_text')); $this->request->redirect(URL::uri_to('frontend/catalog/search', array('search_text' => $search_text))); } return $form->render(); } public function widget_format_select() { $format = $this->request->param('format',NULL); $formats = Model_Product::$_format_options; $view = new View('frontend/products/format_select'); $view->formats = $formats; $view->format = $format; return $view->render(); } public function widget_theme_select() { $theme = $this->request->param('theme',NULL); $themes = Model_Product::$_theme_options; $view = new View('frontend/products/theme_select'); $view->themes = $themes; $view->theme = $theme; return $view->render(); } public function widget_calendar_select() { $calendar = $this->request->param('calendar',NULL); $calendars = Model_Product::$_calendar_options; if (Modules::registered('jquery')) { jQuery::add_scripts(); Layout::instance()->add_script(Modules::uri('jquery') . '/public/js/datetimesimple.js'); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/frontend/datesearch.js'); } $view = new View('frontend/products/calendar_select'); Layout::instance()->add_script( "var datesearch_url='" . URL::to('frontend/catalog/search', array('date'=>'{{d}}'), TRUE) . "';\n\n",TRUE); $view->form = new Form_Frontend_Datesearch(); $view->calendars = $calendars; $view->calendar = $calendar; return $view->render(); } // ----------------------------------------------------------------------- // INDEX PAGE // ----------------------------------------------------------------------- /** * Render list of products in section */ public function action_index() { $view = new View('frontend/workspace'); $view->content = $this->widget_list_products(); $layout = $this->prepare_layout(); $layout->content = $view; // Add breadcrumbs //$this->add_breadcrumbs(); $this->request->response = $layout->render(); } public function action_archive() { $view = new View('frontend/workspace'); $view->content = $this->widget_list_products_archive(); $layout = $this->prepare_layout(); $layout->content = $view; // Add breadcrumbs //$this->add_breadcrumbs(); $this->request->response = $layout->render(); } public function widget_list_products() { $section = Model_Section::current(); if ( ! isset($section->id)) { $this->_action_404('Указанный раздел не найден'); return; } $product = Model::fly('Model_Product'); // build search condition $search_params = array( 'section' => $section, 'active' => -1, 'section_active' => 1, ); $town_alias = Cookie::get(Model_Town::TOWN_TOKEN, Model_Town::ALL_TOWN); if($town_alias == Model_Town::ALL_TOWN) $search_params['all_towns'] = true; $format = $this->request->param('format',NULL); if ($format) $search_params['format'] = $format; $calendar = $this->request->param('calendar',NULL); if ($calendar) $search_params['calendar'] = $calendar; $theme = $this->request->param('theme',NULL); if ($theme) $search_params['theme'] = $theme; list($search_condition, $params) = $product->search_condition($search_params); // count & find products by search condition $pages = (int)$this->request->param('page',1); $per_page = 50*$pages;//4*$pages; $count = $product->count_by($search_condition, $params); $pagination = new Pagination($count, $per_page, 'page', 7); $pagination->offset = 0; $order_by = $this->request->param('cat_porder', 'datetime'); $desc = false;//(bool) $this->request->param('cat_pdesc', '0'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['with_image'] = 3; $params['with_sections'] = TRUE; $products = $product->find_all_by($search_condition, $params); // Set up view $view = new View('frontend/products/list'); $view->order_by = $order_by; $view->desc = $desc; //$view->properties = $properties; $view->products = $products; $view->pagination = $pagination->render('pagination_load'); return $view->render(); } public function widget_list_products_archive() { $section = Model_Section::current(); if ( ! isset($section->id)) { $this->_action_404('Указанный раздел не найден'); return; } $product = Model::fly('Model_Product'); // build search condition $search_params = array( 'section' => $section, 'active' => -1, 'section_active' => 1, ); $town_alias = Cookie::get(Model_Town::TOWN_TOKEN, Model_Town::ALL_TOWN); if($town_alias == Model_Town::ALL_TOWN) $search_params['all_towns'] = true; $format = $this->request->param('format',NULL); if ($format) $search_params['format'] = $format; $theme = $this->request->param('theme',NULL); if ($theme) $search_params['theme'] = $theme; $search_params['calendar'] = Model_Product::CALENDAR_ARCHIVE; list($search_condition, $params) = $product->search_condition($search_params); // var_dump((string)$search_condition);die(); // count & find products by search condition $pages = (int)$this->request->param('page',1); $per_page = 150;//4*$pages; $count = $product->count_by($search_condition, $params); $pagination = new Pagination($count, $per_page, 'page', 7); $pagination->offset = 0; $order_by = 'datetime';//$this->request->param('cat_porder', 'datetime'); $desc = true;//(bool) $this->request->param('cat_pdesc', '0'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['with_image'] = 3; $params['with_sections'] = TRUE; $products = $product->find_all_by($search_condition, $params); // Set up view $view = new View('frontend/products/list'); $view->order_by = $order_by; $view->desc = $desc; //$view->properties = $properties; $view->products = $products; $view->pagination = $pagination->render('pagination_load'); $view->is_archive = TRUE; return $view->render(); } /** * Search products */ public function action_search() { $view = new View('frontend/workspace'); if ($this->request->param('tag',NULL)) $view->content = $this->widget_search_products_by_tags(); else $view->content = $this->widget_search_products(); $layout = $this->prepare_layout(); $layout->content = $view; // Add breadcrumbs //$this->add_breadcrumbs(); $this->request->response = $layout->render(); } public function widget_search_products_by_tags($view_file = 'frontend/products/search') { $tag_alias = $this->request->param('tag',NULL); $products = array(); if (!$tag_alias) { $this->_action_404(); return; } $tag = new Model_Tag(); $search_condition['alias'] = $tag_alias; $search_condition['owner_type'] = 'product'; $town_alias = Cookie::get(Model_Town::TOWN_TOKEN); if($town_alias == Model_Town::ALL_TOWN) $search_params['all_towns'] = true; $pages = (int)$this->request->param('page',1); $per_page = 4*$pages; $count = $tag->count_by($search_condition); $pagination = new Pagination($count, $per_page, 'page', 7); $pagination->offset = 0; $order_by = $this->request->param('cat_porder', 'price'); $desc = (bool) $this->request->param('cat_pdesc', '1'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['with_image'] = 3; $params['with_sections'] = TRUE; $tags = $tag->find_all_by($search_condition); $ids = array(); foreach ($tags as $tag) { $ids[] =$tag->owner_id; } if (count($ids)) { $products = Model::fly('Model_Product')->find_all_by(array('ids' => $ids),$params); } // Set up view $view = new View($view_file); $view->order_by = $order_by; $view->desc = $desc; $view->cols = 3; //$view->properties = $properties; $view->products = $products; $view->pagination = $pagination->render('pagination_load'); // Add breadcrumbs //$this->add_breadcrumbs(); return $view->render(); } public function widget_search_products(array $search_params = NULL,$view_file = 'frontend/products/search') { // --------------------------------------------------------------------- // ------------------------ search params ------------------------------ // --------------------------------------------------------------------- $search_text = URL::decode($this->request->param('search_text')); $search_date = $this->request->param('date',NULL); $product = Model::fly('Model_Product'); // build search condition if (!$search_params) $search_params = array(); $search_params['search_fields'] = array('caption', 'description'); $search_params['search_text'] = $search_text; $search_params['search_date'] = $search_date; $search_params['active'] = 1; $search_params['section_active'] = 1; $search_params['site_id'] = Model_Site::current()->id; $town_alias = Cookie::get(Model_Town::TOWN_TOKEN); if($town_alias == Model_Town::ALL_TOWN) $search_params['all_towns'] = true; list($search_condition, $params) = $product->search_condition($search_params); // count & find products by search condition $pages = (int)$this->request->param('page',1); $per_page = 4*$pages; $count = $product->count_by($search_condition, $params); $pagination = new Pagination($count, $per_page, 'page', 7); $pagination->offset = 0; $order_by = $this->request->param('cat_porder', 'price'); $desc = (bool) $this->request->param('cat_pdesc', '1'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['with_image'] = 3; $params['with_sections'] = TRUE; $products = $product->find_all_by($search_condition, $params); // Set up view $view = new View($view_file); $view->order_by = $order_by; $view->desc = $desc; $view->cols = 3; if ($search_date !== NULL) { $date_str = l10n::rdate(Kohana::config('datetime.date_format_front'),$search_date); $view->date_str = $date_str; } //$view->properties = $properties; $view->products = $products; $view->pagination = $pagination->render('pagination_load'); // Add breadcrumbs //$this->add_breadcrumbs(); return $view->render(); //$this->request->response = $this->render_layout($view->render()); } public function widget_small_product(Model_Product $product) { $widget = new Widget('frontend/products/small_product'); $widget->id = 'product_' . $product->id; $widget->context_uri = FALSE; // use the url of clicked link as a context url $telemosts = $product->get_telemosts(Model_Town::current()); $go = new Model_Go(); $telemost = new Model_Telemost(); $will_go = 0; $already_go = 0; $user= Model_User::current(); foreach ($telemosts as $telemost) { if ($user->id) $go->find_by_telemost_id($telemost->id,array('owner' => $user)); if ($go->id) $already_go = 1; $will_go += $go->count_by(array('telemost_id' => $telemost->id)); } $already_req = 0; if ($user->id) { $telemost->find_by_product_id($product->id,array('owner' => $user)); if ($telemost->id) $already_req = 1; } $widget->already_go = $already_go; $widget->already_req = $already_req; $widget->will_go = $will_go; $widget->product = $product; return $widget; } /** * Redraw product images widget via ajax request */ public function action_ajax_small_product() { $request = Widget::switch_context(); $product = Model_Product::current(); if ( ! isset($product->id)) { FlashMessages::add('Событие не найдено', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('products') ->widget_small_product($product); $widget->to_response($this->request); $this->_action_ajax(); } /** * Redraw product images widget via ajax request */ public function action_ajax_smallproduct_choose() { $request = Widget::switch_context(); $product = Model_Product::current(); $user = Model_User::current(); if ( ! isset($product->id) && ! isset($user->id)) { $this->_action_404(); return; } $go = new Model_Go(); $telemosts = $product->get_telemosts(Model_Town::current()); if (count($telemosts) > 1) { } elseif (count($telemosts) == 1) { $telemost = $telemosts->current(); $go = new Model_Go(); $go->telemost_id = $telemost->id; $go->user_id = $user->id; $go->save(); $widget = $request->get_controller('products') ->widget_small_product($product); $widget->to_response($this->request); $this->_action_ajax(); } else { $this->_action_404(); return; } } /** * Redraw product images widget via ajax request */ public function action_ajax_smallproduct_unchoose() { $request = Widget::switch_context(); $product = Model_Product::current(); $user = Model_User::current(); if ( ! isset($product->id) && ! isset($user->id)) { $this->_action_404(); return; } $go = new Model_Go(); $telemosts = $product->get_telemosts(Model_Town::current()); if (count($telemosts) > 1) { } elseif (count($telemosts) == 1) { $telemost = $telemosts->current(); $go->find_by_telemost_id($telemost->id,array('owner' => $user)); $go->delete(); $widget = $request->get_controller('products') ->widget_small_product($product); $widget->to_response($this->request); $this->_action_ajax(); } else { $this->_action_404(); return; } } /** * Redraw product images widget via ajax request */ public function action_ajax_smallproduct_unrequest() { $request = Widget::switch_context(); $product = Model_Product::current(); $user = Model_User::current(); if ( ! isset($product->id) && ! isset($user->id)) { $this->_action_404(); return; } $telemost = new Model_Telemost(); $telemost->find_by_product_id($product->id, array('owner' => $user)); if ($telemost->id) { $telemost->delete(); } $widget = $request->get_controller('products') ->widget_small_product($product); $widget->to_response($this->request); $this->_action_ajax(); } public function action_ajax_product_unrequest() { $request = Widget::switch_context(); $product = Model_Product::current(); $user = Model_User::current(); if ( ! isset($product->id) && ! isset($user->id)) { $this->_action_404(); return; } $telemost = new Model_Telemost(); $telemost->find_by_product_id($product->id, array('owner' => $user)); if ($telemost->id) { $telemost->delete(); } $widget = $request->get_controller('products') ->widget_product($product); $widget->to_response($this->request); $this->_action_ajax(); } // Parsing public function action_ajax_parsing() { $parseurl = $_GET['parseurl']; $result = array('parseurl' => $parseurl, 'status'=>'notsupported'); if(strpos($parseurl,'theoryandpractice.ru') !== FALSE) { $html = Remote::get($parseurl); $html = str_replace(array('<nobr>','</nobr>','&nbsp;'),array('','',' '),$html); // Title & format $matches = array(); preg_match('|<title>(.+?)</title>|', $html, $matches); $rawData = html_entity_decode($matches[1], ENT_COMPAT, 'UTF-8'); $pos = strpos($rawData, ':'); $title = substr($rawData, $pos + 2); $format = substr($rawData, 0,$pos); // Date preg_match('|<time class="time" datetime="([^"]+?)" itemprop="startDate">|', $html, $matches); $dateTime = new DateTime($matches[1]); $dateTime = $dateTime->format('d-m-Y H:i'); // Description preg_match('|<div class="description" itemprop="description">(.+?)</div>|s', $html, $matches); $rawDesc = $matches[1]; $descWithUrls = preg_replace('|<a href="([^"]+?)">([^<]+?)</a>|i', '$2 - $1', $rawDesc); $desc = strip_tags(html_entity_decode($descWithUrls, ENT_COMPAT, 'UTF-8')); // Image $imageUrl = ''; if(strpos($html,'<figure class="poster">') !== FALSE) { // <figure class="poster"><span class="img"><img alt="Международный стартап" itemprop="image" src="https://tnp-production.s3.amazonaws.com/uploads/image_unit/000/024/198/image/base_8be2e36ea1.jpg"></span><figcaption><span>Автор картинки: <NAME></span></figcaption></figure> preg_match('|<img alt="([^"]+)" itemprop="image" src="([^"]+)"|s', $html, $matches); $imageUrl = html_entity_decode($matches[2], ENT_COMPAT, 'UTF-8'); } $result['status'] = 'success'; $result['event'] = array( 'time'=> $dateTime, 'title' => $title, 'format' => mb_strtolower(trim($format)), 'desc' => $desc, 'image_url' => $imageUrl ); } $this->request->response['data'] = $result; $this->_action_ajax(); } // ----------------------------------------------------------------------- // PRODUCT PAGE // ----------------------------------------------------------------------- public function action_product() { $product = Model_Product::current(); if ( ! isset($product->id)) { $this->_action_404('Указанное событие не найдено'); return; } $view = new View('frontend/product'); $view->product = $product; $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Render product */ public function widget_product(Model_Product $product) { $widget = new Widget('frontend/products/product'); $widget->id = 'product_' . $product->id; $widget->context_uri = FALSE; // use the url of clicked link as a context url $user = Model_User::current(); // was this event already selected for telemost? $telemost = new Model_Telemost(); $already_req = 0; if ($user->id) { $telemost->find_by_product_id($product->id,array('owner' => $user)); if ($telemost->id) $already_req = 1; } // was the corresponding telemost was already choosen to visit? $telemosts = $product->get_telemosts(Model_Town::current()); $go = new Model_Go(); $will_go = 0; $already_go = 0; foreach ($telemosts as $telemost) { if ($user->id) $go->find_by_telemost_id($telemost->id,array('owner' => $user)); if ($go->id) $already_go = 1; $will_go += $go->count_by(array('telemost_id' => $telemost->id)); } // navigation to start the event $stage = $this->request->param('stage',NULL); $today_datetime = new DateTime("now"); $today_datetime->add(new DateInterval('PT30M')); $nav_turn_on = ($today_datetime->getTimestamp() > $product->datetime->getTimestamp())? TRUE:FALSE; if ($nav_turn_on && $product->stage() == Model_Product::ACTIVE_STAGE && $product->get_telemost_provider() == Model_Product::HANGOTS) $product->change_stage(Model_Product::START_STAGE); $result = FALSE; if ($stage) $result = $product->change_stage($stage); $actual_stage = ($result)?$stage:$product->stage(); $widget->already_req = $already_req; $widget->already_go = $already_go; $widget->will_go = $will_go; $widget->stage = $actual_stage; $widget->user_stage = $stage; $widget->nav_turn_on = $nav_turn_on; $widget->section_description = Model_Section::current()->full_description; $widget->product = $product; $widget->telemosts = $product->telemosts; $widget->app_telemosts = $product->app_telemosts; return $widget; } /** * Render images for product (when in product card) * * @param Model_Product $product * @return Widget */ public function widget_product_images(Model_Product $product) { $widget = new Widget('frontend/products/product_images'); $widget->id = 'product_' . $product->id . '_images'; $widget->ajax_uri = URL::uri_to('frontend/catalog/product/images'); $widget->context_uri = FALSE; // use the url of clicked link as a context url $images = Model::fly('Model_Image')->find_all_by_owner_type_and_owner_id('product', $product->id, array( 'order_by' => 'position', 'desc' => FALSE )); if ($images->valid()) { $image_id = (int) $this->request->param('image_id'); if ( ! isset($images[$image_id])) { $image_id = $images->at(0)->id; } $widget->image_id = $image_id; // id of current image $widget->product = $product; } $widget->images = $images; return $widget; } /** * Redraw product images widget via ajax request */ public function action_ajax_product() { $request = Widget::switch_context(); $product = Model_Product::current(); if ( ! isset($product->id)) { FlashMessages::add('Событие не найдено', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('products') ->widget_product($product); $widget->to_response($this->request); $this->_action_ajax(); } /** * Redraw product images widget via ajax request */ public function action_ajax_product_choose() { $request = Widget::switch_context(); $product = Model_Product::current(); $user = Model_User::current(); if ( ! isset($product->id) && ! isset($user->id)) { $this->_action_404(); return; } $go = new Model_Go(); $telemosts = $product->get_telemosts(Model_Town::current()); if (count($telemosts) > 1) { } elseif (count($telemosts) == 1) { $telemost = $telemosts->current(); $go = new Model_Go(); $go->telemost_id = $telemost->id; $go->user_id = $user->id; $go->save(); $widget = $request->get_controller('products') ->widget_product($product); $widget->to_response($this->request); $this->_action_ajax(); } else { $this->_action_404(); return; } } /** * Redraw product images widget via ajax request */ public function action_ajax_product_unchoose() { $request = Widget::switch_context(); $product = Model_Product::current(); $user = Model_User::current(); if ( ! isset($product->id) && ! isset($user->id)) { $this->_action_404(); return; } $go = new Model_Go(); $telemosts = $product->get_telemosts(Model_Town::current()); if (count($telemosts) > 1) { } elseif (count($telemosts) == 1) { $telemost = $telemosts->current(); $go->find_by_telemost_id($telemost->id,array('owner' => $user)); $go->delete(); $widget = $request->get_controller('products') ->widget_product($product); $widget->to_response($this->request); $this->_action_ajax(); } else { $this->_action_404(); return; } } /** * Redraw product images widget via ajax request */ public function action_ajax_product_images() { $request = Widget::switch_context(); $product = Model_Product::current(); if ( ! isset($product->id)) { FlashMessages::add('Событие не найдено', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('products') ->widget_product_images($product); $widget->to_response($this->request); $this->_action_ajax(); } public function action_cancel() { $product_id = $this->request->param('id',NULL); $user = Model_User::current(); if (!$product_id || !$user->id) { $this->_action_404(); return; } $product = Model::fly('Model_Product')->find_by_id($product_id,array('owner' => $user)); if ($product->id) { $product->backup(); $product->visible=0; $product->save(); $this->request->redirect(URL::uri_to('frontend/acl/users/control',array('action' => 'control'))); } else { $this->_action_404(); return; } } public function action_fullscreen() { $product = Model_Product::current(); $user = Model_User::current(); if (!$product->id || !$user->id) { $this->_action_404(); return; } if ($product->user_id == $user->id) { $aim = $product; if ($product->stage() != Model_Product::START_STAGE) { $result = $product->change_stage(Model_Product::START_STAGE); } } else { $aim = Model::fly('Model_Telemost')->find_by_product_id($product->id,array('owner' => $user)); } if (!$aim->id) { $this->_action_404(); return; } $view = new View('frontend/products/fullscreen'); $view->aim = $aim; $view->product = $product; $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } // ----------------------------------------------------------------------- // USER PAGE // ----------------------------------------------------------------------- /** * Renders list of products * * @param boolean $seelct * @return string */ public function widget_products($view = 'frontend/products',$apage = NULL) { $widget = new Widget($view); $widget->id = 'products'; $widget->ajax_uri = NULL; $widget->context_uri = FALSE; // use the url of clicked link as a context url // ----- List of products $product = Model::fly('Model_Product'); $owner = Auth::instance()->get_user(); $per_page = 1000; $count = $product->count_by_owner($owner->id); $pagination = new Paginator($count, $per_page, 'apage', 7,$apage,'frontend/catalog/ajax_products',NULL,'ajax'); $order_by = $this->request->param('cat_porder', 'datetime'); $desc = (bool) $this->request->param('cat_pdesc', '1'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $params['with_image'] = 2; $params['with_sections'] = TRUE; $params['owner'] = $owner; $products = $product->find_all_by_visible(TRUE,$params); $will_goes = array(); foreach ($products as $product) { $telemosts = $product->get_telemosts(Model_Town::current()); $go = new Model_Go(); $will_go = 0; foreach ($telemosts as $telemost) { $will_go += $go->count_by(array('telemost_id' => $telemost->id)); } $will_goes[$product->id] = $will_go; } $params['offset'] = $pagination->offset; $widget->order_by = $order_by; $widget->desc = $desc; $widget->products = $products; $widget->will_goes = $will_goes; $widget->pagination = $pagination->render('pagination'); return $widget; } /** * Redraw product images widget via ajax request */ public function action_ajax_products() { $apage = $this->request->param('apage',NULL); $request = Widget::switch_context(); $user = Model_User::current(); if ( ! isset($user->id)) { //FlashMessages::add('', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('products') ->widget_products('frontend/small_products',$apage); $widget->to_response($this->request); $this->_action_ajax(); } // ----------------------------------------------------------------------- // PRODUCT CONTROL PAGE // ----------------------------------------------------------------------- public function _view_create(Model_Product $model, Form_Frontend_Product $form, array $params = NULL) { $place = new Model_Place(); $form_place = new Form_Frontend_Place($place); if ($form_place->is_submitted()) { $form_place->validate(); // User is trying to log in if ($form_place->validate()) { $vals = $form_place->get_values(); if ($place->validate($vals)) { $place->values($vals); $place->save(); $form->get_element('place_name')->set_value($place->name); $form->get_element('place_id')->set_value($place->id); } } } $modal = Layout::instance()->get_placeholder('modal'); $modal = $form_place->render().' '.$modal; $lecturer = new Model_Lecturer(); $form_lecturer = new Form_Frontend_Lecturer($lecturer); if ($form_lecturer->is_submitted()) { // User is trying to log in if ($form_lecturer->validate()) { $vals = $form_lecturer->get_values(); if ($lecturer->validate($vals)) { $lecturer->values($vals); $lecturer->save(); $form->get_element('lecturer_name')->set_value($lecturer->name); $form->get_element('lecturer_id')->set_value($lecturer->id); } } } $modal .= ' '.$form_lecturer->render(); $organizer = new Model_Organizer(); $form_organizer = new Form_Frontend_Organizer($organizer); if ($form_organizer->is_submitted()) { $form_organizer->validate(); // User is trying to log in if ($form_organizer->validate()) { $vals = $form_organizer->get_values(); if ($organizer->validate($vals)) { $organizer->values($vals); $organizer->save(); $form->get_element('organizer_name')->set_value($organizer->name); $form->get_element('organizer_id')->set_value($organizer->id); } } } $modal = $form_organizer->render().' '.$modal; Layout::instance()->set_placeholder('modal',$modal); $view = new View('frontend/products/control'); $view->product = $model; $view->form = $form; return $view; } public function _view_update(Model_Product $model, Form_Frontend_Product $form, array $params = NULL) { $place = new Model_Place(); $form_place = new Form_Frontend_Place($place); if ($form_place->is_submitted()) { $form_place->validate(); // User is trying to log in if ($form_place->validate()) { $vals = $form_place->get_values(); if ($place->validate($vals)) { $place->values($vals); $place->save(); $form->get_element('place_name')->set_value($place->name); $form->get_element('place_id')->set_value($place->id); } } } $modal = Layout::instance()->get_placeholder('modal'); $modal = $form_place->render().' '.$modal; $lecturer = new Model_Lecturer(); $form_lecturer = new Form_Frontend_Lecturer($lecturer); if ($form_lecturer->is_submitted()) { // User is trying to log in if ($form_lecturer->validate()) { $vals = $form_lecturer->get_values(); if ($lecturer->validate($vals)) { $lecturer->values($vals); $lecturer->save(); $form->get_element('lecturer_name')->set_value($lecturer->name); $form->get_element('lecturer_id')->set_value($lecturer->id); } } } $modal .= ' '.$form_lecturer->render(); $organizer = new Model_Organizer(); $form_organizer = new Form_Frontend_Organizer($organizer); if ($form_organizer->is_submitted()) { $form_organizer->validate(); // User is trying to log in if ($form_organizer->validate()) { $vals = $form_organizer->get_values(); if ($organizer->validate($vals)) { $organizer->values($vals); $organizer->save(); $form->get_element('organizer_name')->set_value($organizer->name); $form->get_element('organizer_id')->set_value($organizer->id); } } } $modal = $form_organizer->render().' '.$modal; Layout::instance()->set_placeholder('modal',$modal); $view = new View('frontend/products/control'); $view->product = $model; $view->form = $form; return $view; } /** * Configure actions * @return array */ public function setup_actions() { $this->_model = 'Model_Product'; $this->_view = 'frontend/form_adv'; $this->_form = 'Form_Frontend_Product'; return array( 'create' => array( 'view_caption' => 'Создание события', ), 'update' => array( 'view_caption' => 'Редактирование события ":caption"', 'message_ok' => 'Укажите дополнительные характеристики события' ), 'delete' => array( 'view_caption' => 'Удаление анонса', 'message' => 'Удалить анонс ":caption"?' ) ); } /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { if ($layout_script === NULL) { if ($this->request->action == 'product') { $layout_script = 'layouts/catalog'; } if ($this->request->action == 'create' || $this->request->action == 'update') { $layout_script = 'layouts/default_without_menu'; } if ($this->request->action == 'fullscreen') { $layout_script = 'layouts/only_vision'; } } return parent::prepare_layout($layout_script); } /** * Prepare product for create/update/delete action * * @param string $action * @param string|Model_Product $product * @param array $params * @return Model_Product */ protected function _model($action, $product, array $params = NULL) { $product = parent::_model($action, $product, $params); if ($action == 'create') { $product->section_id = Model_Section::EVENT_ID; $product->user_id = Model_User::current()->id; $product->active = 1; } return $product; } /** * Delete model * * @param Model $model * @param Form $form * @param array $params */ protected function _execute_delete(Model $model, Form $form, array $params = NULL) { $model->visible = 0; $model->save(); $this->request->redirect($this->_redirect_uri('delete', $model, $form, $params)); } /** * Delete multiple models * * @param array $models array(Model) * @param Form $form * @param array $params */ protected function _execute_multi_delete(array $models, Form $form, array $params = NULL) { foreach ($models as $model) { $model->visible = 0; $model->save(); } $this->request->redirect($this->_redirect_uri('multi_delete', $model, $form, $params)); } public function action_control() { $view = new View('frontend/workspace'); $view->content = $this->widget_products(); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } public function action_eventcontrol() { $view = new View('frontend/workspace'); $view->content = $this->widget_products('frontend/events'); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Handles the selection of additional sections for product */ public function action_sections_select() { if ( ! empty($_POST['ids']) && is_array($_POST['ids'])) { $section_ids = ''; foreach ($_POST['ids'] as $section_id) { $section_ids .= (int) $section_id . '_'; } $section_ids = trim($section_ids, '_'); $this->request->redirect(URL::uri_back(NULL, 1, array('cat_section_ids' => $section_ids))); } else { // No sections were selected $this->request->redirect(URL::uri_back()); } } public function action_set_hangouts_url($key, $url) { $key = $_GET['key']; $url = $_GET['url']; // Hangouts test if(strpos($key,"zzzzzTESTzzzzz") === 0) { $isTest = true; $key = substr($key, 14); } $result = array('status'=>'ok'); if($key != Model_Product::HANGOUTS_STOP_KEY) { if($isTest) $product = Model::fly('Model_Product')->find_by_hangouts_test_secret_key($key); else $product = Model::fly('Model_Product')->find_by_hangouts_secret_key($key); if($product->id) { if($isTest) $product->hangouts_test_url = $url; else $product->hangouts_url = $url; $product->save(); } else { $result['status'] = 'notfound'; } } else { $result['status'] = 'error'; } $this->request->headers["Access-Control-Allow-Origin"] = "*"; $this->request->headers["Access-Control-Allow-Headers"] = "origin, x-requested-with, content-type"; $this->request->headers["Access-Control-Allow-Methods"] = "PUT, GET, POST, DELETE, OPTIONS"; $this->request->response['data'] = $result; $this->_action_ajax(); } /** * This action is executed via ajax request after additional * sections for product have been selected. * * It redraws the "additional sections" form element accordingly */ public function action_ajax_sections_select() { if ($this->request->param('cat_section_ids') != '') { $action = ((int)$this->request->param('id') == 0) ? 'create' : 'update'; $product = $this->_model($action, 'Model_Product'); $form = $this->_form($action, $product); $component = $form->find_component('additional_sections[' . (int) $this->request->param('cat_sectiongroup_id') . ']'); if ($component) { $this->request->response = $component->render(); } } } /** * Redraw product properties via ajax request */ public function action_ajax_properties() { $product = new Model_Product(); $product->find((int) $this->request->param('id')); if (isset($_GET['section_id'])) { $product->section_id = (int) $_GET['section_id']; } // switch form according to the sectiongroup type $type_id = $this->request->param('type_id', NULL); if ($type_id !== NULL) { $type_id = (int) $type_id; if (!isset($this->_forms[$type_id])) { throw new Controller_BackendCRUD_Exception('Неправильные параметры запроса'); } $form_class = $this->_forms[$type_id]; } $form = new $form_class($product); $component = $form->find_component('props'); if ($component) { $this->request->response = $component->render(); } } public function widget_create() { $widget = new Widget('frontend/products/product_create'); $widget->id = 'product_' . $product->id . '_create'; //$widget->ajax_uri = URL::uri_to('frontend/catalog/product/action'); $widget->context_uri = FALSE; // use the url of clicked link as a context url $widget->sectiongroup = Model_SectionGroup::current(); return $widget; } /** * Generate redirect url * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { if ($action == 'create' || $action == "update") { return URL::uri_to('frontend/acl/users/control',array('action' => 'control')); } return parent::_redirect_uri($action, $model, $form, $params); } /** * Add breadcrumbs for current action */ public function add_breadcrumbs(array $request_params = array()) { if (empty($request_params)) { list($name, $request_params) = URL::match(Request::current()->uri); } if ($request_params['action'] == 'search') { Breadcrumbs::append(array( 'uri' => URL::uri_self(array()), 'caption' => 'Результаты поиска')); } if ($request_params['action'] == 'control') { Breadcrumbs::append(array( 'uri' => URL::uri_to('frontend/catalog/products/control',array('action' => 'control')), 'caption' => 'Управление анонсами')); } if ($request_params['action'] == 'eventcontrol') { Breadcrumbs::append(array( 'uri' => URL::uri_to('frontend/catalog/products/control',array('action' => 'eventcontrol')), 'caption' => 'Управление событиями')); } if ($request_params['action'] == 'index') { $sectiongroup = Model_SectionGroup::current(); if ( ! isset($sectiongroup->id)) return; Breadcrumbs::append(array( 'uri' => $sectiongroup->uri_frontend(), 'caption' => $sectiongroup->caption )); $section = Model_Section::current(); if ( ! isset($section->id)) return; // find all parents for current section and append the current section itself $sections = $section->find_all_active_cached($sectiongroup->id); $parents = $sections->parents($section, FALSE); foreach ($parents as $parent) { Breadcrumbs::append(array( 'uri' => $parent->uri_frontend(), 'caption' => $parent->caption )); } Breadcrumbs::append(array( 'uri' => $section->uri_frontend(), 'caption' => $section->caption )); } } public function widget_calendar() { $calendar = Calendar::instance(); $search_date_url = URL::to('frontend/catalog/search', array('date'=>'{{d}}'), TRUE); $calendar->addDateLinks($search_date_url,'{{d}}'); return $calendar->genUMonth(time(), true); } } <file_sep>/modules/shop/catalog/views/frontend/products/product.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $current_user_id= Model_User::current()->id; if ($product->user_id == $current_user_id) { $update_url = URL::to('frontend/catalog/products/control', array('action'=>'update', 'id' => $product->id), TRUE);?> <div class="action"> <a href="<?php echo $update_url ?>" class="link-edit"><i class="icon-pencil icon-white"></i></a> </div> <?php } if (!$nav_turn_on) { } else { if ($product->user_id == $current_user_id) { $nav = new View('frontend/products/administrator_nav'); $nav->product = $product; $nav->stage = $stage; /*if ($stage == Model_Product::START_STAGE) { $admin_vision = new View('frontend/products/administrator_vision'); $admin_vision->product = $product; Layout::instance()->set_placeholder('vision',$admin_vision->render()); }*/ } else { foreach ($telemosts as $tel) { if ($tel->user_id == $current_user_id) { $nav = new View('frontend/products/user_nav'); $nav->product = $product; $nav->stage = $stage; /*if ($stage == Model_Product::START_STAGE && $user_stage == Model_Product::START_STAGE) { $nav = new View('frontend/products/user_nav_after'); $nav->product = $product; $user_vision = new View('frontend/products/user_vision'); $user_vision->tel = $tel; $user_vision->product = $product; Layout::instance()->set_placeholder('vision',$user_vision->render()); }*/ } } }} $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $today_flag= 0; $tomorrow_flag= 0; $nearest_flag = 0; if (($today_flag == 0) && $product->datetime->format('d.m.Y') == $today_datetime->format('d.m.Y')) { $today_flag++; } elseif (($tomorrow_flag == 0) && $product->datetime->format('d.m.Y') == $tomorrow_datetime->format('d.m.Y')){ $tomorrow_flag++; } elseif ($nearest_flag == 0) { $nearest_flag++; } $day = $nearest_flag?$product->weekday:($tomorrow_flag?'Завтра':'Сегодня'); $telemost_flag= FALSE; if (Model_Town::current()->alias != Model_Town::ALL_TOWN) $telemost_flag = ($product->place->town_name != Model_Town::current()->name); $user_id = Model_User::current()->id; $group_id = Model_User::current()->group_id; $available_num = (int)$product->numviews; if (count($telemosts)) { $available_num = ((int)$product->numviews > count($telemosts))?true:false; } ?> <header> <div class="row-fluid"> <div class="span6" style="white-space: nowrap;"> <span class="date"><a class="day" href=""><?php echo $day ?></a>, <?php echo $product->get_datetime_front()?></span> <?php if ($telemost_flag) { ?><span class="type"><?php echo Model_Product::$_interact_options[$product->interact];?></span><?php } ?> </div> <div class="span6 b-link shifted-links"> <?php if (isset($nav)) { echo $nav->render(); } else { ?> <?php $datenow = new DateTime("now"); if($product->datetime > $datenow): ?> <?php if (!$telemost_flag && $group_id != Model_Group::USER_GROUP_ID && $group_id && $product->user_id != $user_id) { if ($available_num && !$user_id) { ?> <a data-toggle="modal" href="#notifyModal" class="request-link button">Провести телемост</a> <?php } elseif ($available_num && !$already_req) { ?> <a data-toggle="modal" href="<?php echo "#requestModal_".$product->alias?>" class="request-link button">Провести телемост</a> <?php } elseif($already_req) { $unrequest_url = URL::to('frontend/catalog/product/unrequest', array('alias' => $product->alias));?> <a href="<?php echo $unrequest_url ?>" class="ajax request-link button">Отменить заявку</a> <?php }} ?> <?php endif ?> <?php } ?> </div> </div> </header> <div class="row-fluid"> <div class="span5"> <?php echo Widget::render_widget('products', 'product_images', $product); ?> <hr> <div class="event-desc"> <?php if (Model_Town::current()->name == $product->place->town_name) {?> <div class="place-event"> <div class="place-tv-new"> <p class="title">Событие:</p> <p class="place"><?php echo $product->place->town_name?>, <?php echo $product->place->name ?><?php if ($product->place->address) { ?>,<a href="#"> <?php echo $product->place->address ?></a><?php } ?></p> </div> <!-- <p class="address"><?php //echo $product->place->town_name?>, <?php //echo $product->place->address?></p> --> <p class="organizer">Организатор события: <span><?php echo $product->organizer->name?></span></p> </div> <hr> <?php if (count($telemosts)) { ?> <p class="title">Телемосты:</p> <?php } ?> <?php foreach ($telemosts as $telemost) { ?> <div class="place-tv-new"> <p><?php echo $telemost->place->town_name?>, <?php echo $telemost->place->name ?><?php if ($telemost->place->address) { ?>,<a href="#"> <?php echo $telemost->place->address ?></a><?php } ?></p> <!--<div class="address"><?php //echo $telemost->place->town_name?>, <?php //echo $telemost->place->address?> --> </div> <p class="organizer">Организатор телемоста: <span><?php echo $telemost->user->organizer->name?></span></p> <!--<p class="coordinator">Координатор: <span><?php //echo $telemost->user->name?></span></p>--> <?php if ($telemost->info) { ?><p class="desc">Дополнительно: <span><?php echo $telemost->info?></span></p><?php } ?> <hr> <?php } ?> <?php } else { $main_telemosts =array(); $other_telemosts = array(); foreach ($telemosts as $telemost) { if ($telemost->place->town_name == Model_Town::current()->name) { $main_telemosts[] = clone $telemost; } else { $other_telemosts[] = clone $telemost; } } ?> <?php if (count($main_telemosts)) { ?> <p class="title">Телемост:</p> <?php } ?> <?php foreach ($main_telemosts as $telemost) {?> <div class="place-tv-new"> <p><?php echo $telemost->place->town_name?>, <?php echo $telemost->place->name ?><?php if ($telemost->place->address) { ?>,<a href="#"> <?php echo $telemost->place->address ?></a><?php } ?></p> <!--<div class="address"><?php //echo $telemost->place->town_name?>, <?php //echo $telemost->place->address?> --> </div> <p class="organizer">Организатор телемоста: <span><?php echo $telemost->user->organizer->name?></span></p> <!--<p class="coordinator">Координатор: <span><?php //echo $telemost->user->name?></span></p>--> <?php if ($telemost->info) { ?><p class="desc">Дополнительно: <span><?php echo $telemost->info?></span></p><?php } ?> <hr> <?php }?> <div class="place-event"> <div class="place-tv-new"> <p class="title">Оффлайновое событие:</p> <p class="place"><?php echo $product->place->town_name?>, <?php echo $product->place->name ?><?php if ($product->place->address) { ?>,<a href="#"> <?php echo $product->place->address ?></a><?php } ?></p> </div> <!-- <p class="address"><?php //echo $product->place->town_name?>, <?php //echo $product->place->address?></p> --> <p class="organizer">Организатор события: <span><?php echo $product->organizer->name?></span></p> </div> <hr> <?php if (count($other_telemosts)) { ?> <p class="title"><?php echo count($main_telemosts) ? 'Другие телемосты:' : 'Телемосты:' ?></p> <?php } ?> <?php foreach ($other_telemosts as $telemost) {?> <div class="place-tv-new"> <p><?php echo $telemost->place->town_name?>, <?php echo $telemost->place->name ?><?php if ($telemost->place->address) { ?>,<a href="#"> <?php echo $telemost->place->address ?></a><?php } ?></p> <!--<div class="address"><?php //echo $telemost->place->town_name?>, <?php //echo $telemost->place->address?> --> </div> <p class="organizer">Организатор телемоста: <span><?php echo $telemost->user->organizer->name?></span></p> <!--<p class="coordinator">Координатор: <span><?php //echo $telemost->user->name?></span></p>--> <?php if ($telemost->info) { ?><p class="desc">Дополнительно: <span><?php echo $telemost->info?></span></p><?php } ?> <hr> <?php } ?> <?php } ?> </div> <div class="b-new-events"> <?php if ($available_num) { ?> <p><strong>Максимальное количество телемостов: <?php echo $product->numviews ?>, осталось: <?php echo ((int)$product->numviews - count($telemosts))?></strong></p> <?php } else { ?> <p><strong>Вы уже выбрали максимально возможное количество телемостов</strong></p> <?php } ?> <?php if (count($app_telemosts)) { ?> <div class="event-desc"> <p class="title">Заявки на телемосты:</p> <?php foreach ($app_telemosts as $app_telemost) { ?> <?php if ($available_num && ($user_id == $product->user_id)) { ?> <br> <?php } ?> <div class="el event-desc"> <p class="from-who">От кого: <span><?php echo $app_telemost->user->name?></span> &nbsp;&nbsp;Организация: <span><?php echo $app_telemost->user->organizer->name?></span></p> <p class="place"><?php echo $app_telemost->place->town_name?>, <?php echo $app_telemost->place->name?><?php if ($app_telemost->place->address) { ?>,<a href="#"> <?php echo $app_telemost->place->address ?></a><?php } ?></p> <?php if ($app_telemost->info) { ?><p class="desc">Дополнительно: <span><?php echo $app_telemost->info?></span></p><?php } ?> <?php if ($available_num && ($user_id == $product->user_id)) { $select_url = URL::to('frontend/catalog/telemost/select', array('telemost_id' => $app_telemost->id)); ?> <div class="action"> <a href="<?php echo $select_url?>" class="ajax button button-red">Принять</a> </div> <?php } ?> </div> <hr> <?php } ?> </div> <?php }?> </div> </div> <div class="span7 content"> <h1><?php echo $product->caption?></h1> <?php $lecturer_url = URL::to('frontend/acl/lecturers', array('action' => 'show','lecturer_id' => $product->lecturer_id));?> <p class="lecturer">Лектор: <a href="<?php echo $lecturer_url ?>"><?php echo $product->lecturer->name; ?></a></p> <div class="content"> <p><?php echo $product->description; ?></p> </div> <br /> <div class="dir righted"> Категория:&nbsp<a href="<?php echo $product->uri_frontend(); ?>"><?php echo Model_Product::$_theme_options[$product->theme] ?></a> <?php if (count($product->tag_items)) { echo "&nbsp&nbsp&nbspТеги:"; } $i=0; foreach ($product->tag_items as $tag) { $search_url = URL::to('frontend/catalog/search', array('tag'=>$tag->alias), TRUE); $glue =($i)?',':'';$i++;?> <a href="<?php echo $search_url ?>"><?php echo $glue.' '.$tag->name ?></a> <?php } ?> </div> <?php echo Cackle::factory()->render();?> </div> </div> <file_sep>/modules/shop/acl/views/frontend/forms/relogin.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="modal-header"> <h3 id="myModalLabel">Вход</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <?php $stat = Request::current()->param('stat',NULL); switch ($stat) { case 'ok': ?> <p class="repeat-pass">На указанный Вами адрес было отправлено письмо с ссылкой для смены пароля.</p> <?php break; case 'try': ?> <p class="repeat-pass">Пароль успешно изменен.<br>Введите логин и пароль, чтобы войти на портал.</p> <?php break; case 'act': ?> <p class="repeat-pass">Учетная запись успешно активирована. Добро пожаловать на Vse.To!<br>Введите логин и пароль, чтобы войти на портал.</p> <?php break; default: ?> <p class="repeat-pass">Ошибка в адресе или пароле. Попробуйте ещё раз.</p> <?php } ?> <!--<p>Вход через социальные сети</p> <div class="soc-link"> <a href="#" class="button fb">f</a> <a href="#" class="tw button ">t</a> <a href="#" class="button vk">v</a> </div>--> <label for="email"><?php echo $form->get_element('email')->render_input(); ?></label> <label for="pass"><?php echo $form->get_element('password')->render_input(); ?></label> <?php echo Widget::render_widget('acl', 'pasrecovery'); ?> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_login')->render_input(); ?> </div> <?php echo $form->render_form_close();?> <file_sep>/modules/general/images/classes/model/image/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Image_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('owner_type', array('Type' => 'varchar(15)', 'Key' => 'INDEX')); $this->add_column('owner_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); for ($i = 1; $i <= Model_Image::MAX_SIZE_VARIANTS; $i++) { $this->add_column("image$i", array('Type' => 'varchar(63)')); $this->add_column("width$i", array('Type' => 'smallint unsigned')); $this->add_column("height$i", array('Type' => 'smallint unsigned')); } } /** * Move image one position up * * @param Model $model * @param Database_Expression_Where $condition */ public function up(Model $model, Database_Expression_Where $condition = NULL) { parent::up($model, DB::where('owner_type', '=', $model->owner_type)->and_where('owner_id', '=', $model->owner_id)); } /** * Move image one position down * * @param Model $model * @param Database_Expression_Where $condition */ public function down(Model $model, Database_Expression_Where $condition = NULL) { parent::down($model, DB::where('owner_type', '=', $model->owner_type)->and_where('owner_id', '=', $model->owner_id)); } }<file_sep>/modules/shop/catalog/classes/task/comdi/register.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Create event through COMDI API */ class Task_Comdi_Register extends Task_Comdi_Base { public static $params = array( 'key', 'event_id', 'username', 'role', 'email' ); /** * Default parameters for this task * @var array */ public static $default_params = array( 'role' => 'user' ); /** * Construct task */ public function __construct() { parent::__construct('http://my.webinar.ru'); $this->default_params(self::$default_params); } /** * Run the task */ public function run() { $xml_response = parent::send('/api0/Register.php',$this->params(self::$params)); $uri = NULL; if (isset($xml_response->guest)) $uri = ($xml_response->guest['uri'] == NULL)?NULL:(string)$xml_response->guest['uri']; if ($uri === NULL) { $this->set_status_info('Пользователь не был добавлен'); } else { $this->set_status_info('Пользователь добавлен'); } return $uri; } } <file_sep>/application/config/form_templates/frontend/input.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( array( 'element' => '<div class="element"> <div class="caption"><strong>{{label}}</strong> {{comment}}</div> <div class="input">{{input}}{{append}}</div> <div class="errors" id="{{id}}-errors">{{errors}}</div> </div> ' ) ); <file_sep>/modules/shop/acl/classes/model/userpropuser/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_UserPropUser_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('userprop_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); } /** * Link userprop to given users * * @param Model_UserProp $userprop * @param array $userpropusers */ public function link_userprop_to_users(Model_UserProp $userprop, array $userpropusers) { $this->delete_rows(DB::where('userprop_id', '=', (int) $userprop->id)); foreach ($userpropusers as $userpropuser) { $userpropuser['userprop_id'] = $userprop->id; $this->insert($userpropuser); } } /** * Link user to given userprops * * @param Model_User $user * @param array $userpropusers */ public function link_user_to_userprops(Model_User $user, array $userpropusers) { $this->delete_rows(DB::where('user_id', '=', (int) $user->id)); foreach ($userpropusers as $userpropuser) { $userpropuser['user_id'] = $user->id; $this->insert($userpropuser); } } /** * Find all userprop-user infos by given user * * @param Model_UserPropUser $userpropus * @param Model_User $user * @param array $params * @return Models */ public function find_all_by_user(Model_UserPropUser $userpropus, Model_User $user, array $params = NULL) { $userpropus_table = $this->table_name(); $userprop_table = Model_Mapper::factory('Model_UserProp_Mapper')->table_name(); $user_table = Model_Mapper::factory('Model_User_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array( array("$userprop_table.id", 'userprop_id'), "$userprop_table.caption", "$userprop_table.system", "$userpropus_table.active", ); $query = DB::select_array($columns) ->from($userprop_table) ->join($userpropus_table, 'LEFT') ->on("$userpropus_table.userprop_id", '=', "$userprop_table.id") ->on("$userpropus_table.user_id", '=', DB::expr((int) $user->id)); $data = parent::select(NULL, $params, $query); // Add user properties foreach ($data as & $userprops) { $userprops['user_id'] = $user->id; $userprops['user_login'] = $user->email; } return new Models(get_class($userpropus), $data); } /** * Find all userprop-user infos by given userprop * * @param Model_UserPropUser $userpropus * @param Model_UserProp $userprop * @param array $params * @return Models */ public function find_all_by_userprop(Model_UserPropUser $userpropus, Model_UserProp $userprop, array $params = NULL) { $userpropus_table = $this->table_name(); $userprop_table = Model_Mapper::factory('Model_UserProp_Mapper')->table_name(); $user_table = Model_Mapper::factory('Model_User_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array( array("$user_table.id", 'user_id'), array("$user_table.login", 'user_login'), "$userpropus_table.active" ); $query = DB::select_array($columns) ->from($user_table) ->join($userpropus_table, 'LEFT') ->on("$userpropus_table.user_id", '=', "$user_table.id") ->on("$userpropus_table.userprop_id", '=', DB::expr((int) $userprop->id)); $data = parent::select(array(), $params, $query); // Add property properties foreach ($data as & $userprops) { $userprops['userprop_id'] = $userprop->id; $userprops['caption'] = $userprop->caption; $userprops['system'] = $userprop->system; } return new Models(get_class($userpropus), $data); } }<file_sep>/modules/shop/acl/views/layouts/backend/login.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><?php echo HTML::chars($view->placeholder('title')); ?></title> <meta http-equiv="content-type" content="text/html; charset=<?php echo Kohana::$charset; ?>" /> <meta http-equiv="Keywords" content="<?php echo HTML::chars($view->placeholder('keywords')); ?>" /> <meta http-equiv="Description" content="<?php echo HTML::chars($view->placeholder('description')); ?>" /> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/forms.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/tables.css'); ?> <?php echo HTML::style(Modules::uri('backend') . '/public/css/backend/backend_ie6.css', NULL, FALSE, 'if lte IE 6'); ?> <?php echo $view->placeholder('styles'); ?> <?php echo $view->placeholder('scripts'); ?> </head> <body> <table class="authorization"><tr><td class="super_centered"> <?php echo $content; ?> </td></tr></table> <?php if (Kohana::$profiling) { //echo View::factory('profiler/stats')->render(); } ?> </body> </html><file_sep>/modules/shop/catalog/classes/controller/backend/catimport.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_CatImport extends Controller_Backend { /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Import catalog */ public function action_index() { if (Model_Site::current()->id === NULL) { $this->_action_error('Выберите магазин, в который требуется импортировать каталог'); return; } $html = ''; // ----- pricelist $form_pricelist = new Form_Backend_CatImport_Pricelist(); if ($form_pricelist->is_submitted() && $form_pricelist->validate()) { // move uploaded pricelist file $tmp_file = File::upload($form_pricelist->get_value('file')); TaskManager::start('import_pricelist', array( 'supplier' => $form_pricelist->get_value('supplier'), 'price_factor' => $form_pricelist->get_value('price_factor'), 'file' => $tmp_file )); $this->request->redirect($this->request->uri); } $view = new View('backend/form'); $view->caption = 'Импорт прайслиста'; $view->form = $form_pricelist; $html .= $view->render(); // ----- structure $form_structure = new Form_Backend_CatImport_Structure(); $form_structure->set_defaults(Task_Import_Structure::$default_params); if ($form_structure->is_submitted() && $form_structure->validate()) { $params = $form_structure->get_values(); unset($params['submit']); // move uploaded structure file $params['file'] = File::upload($form_structure->get_value('file')); TaskManager::start('import_structure',$params); $this->request->redirect($this->request->uri); } $view = new View('backend/form'); $view->caption = 'Импорт структуры каталога'; $view->form = $form_structure; $html .= $view->render(); $this->request->response = $this->render_layout($html); } } <file_sep>/modules/general/chat/classes/controller/frontend/dialogs.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Dialogs extends Controller_FrontendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Dialog'; return array( 'delete' => array( 'view_caption' => 'Удаление диалога', 'message' => 'Удалить диалог?' ), 'multi_delete' => array( 'view_caption' => 'Удаление диалогов', 'message' => 'Удалить выбранные диалоги?' ) ); } /** * Prepare layout * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('chat') . '/public/css/frontend/chat.css'); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('frontend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Render list of dialogs */ public function action_index() { $view = new View('frontend/workspace'); $view->content = $this->widget_dialogs(); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Renders list of dialogs * * @return string Html */ public function widget_dialogs() { $per_page = 5; $dialog = new Model_Dialog(); $count = $dialog->count(); $pagination = new Pagination($count, $per_page); $dialogs = $dialog->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => 'id', 'desc' => '1' )); $view = new View('frontend/dialogs'); $view->dialogs = $dialogs; $view->pagination = $pagination->render('pagination'); return $view->render(); } /** * Add breadcrumbs for current action */ public function add_breadcrumbs(array $request_params = array()) { if (empty($request_params)) { list($name, $request_params) = URL::match(Request::current()->uri); } Breadcrumbs::append(array( 'uri' => URL::uri_to('frontend/dialogs'), 'caption' => 'Сообщения' )); } }<file_sep>/modules/shop/discounts/views/backend/coupons.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/coupons', array('action'=>'create'), TRUE); $update_url = URL::to('backend/coupons', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/coupons', array('action'=>'delete', 'id' => '${id}'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Создать купон</a> </div> <?php if ( ! count($coupons)) return; ?> <table class="table"> <tr class="header"> <?php $columns = array( 'code' => 'Код', 'type' => array('label' => 'Тип', 'sort_field' => 'multiple'), 'discount_formatted' => 'Скидка', 'description_short' => array('label' => 'Описание', 'sortable' => FALSE), 'date_from_formatted' => array('label' => 'Действ. с', 'sort_field' => 'valid_after'), 'date_to_formatted' => array('label' => 'Действ. по', 'sort_field' => 'valid_before'), 'user_name' => 'Пользователь', 'site_captions' => array('label' => 'Магазины', 'sortable' => FALSE), ); echo View_Helper_Admin::table_header($columns, 'coupons_order', 'coupons_desc'); ?> <th></th> </tr> <?php foreach ($coupons as $coupon) : $_update_url = str_replace('${id}', $coupon->id, $update_url); $_delete_url = str_replace('${id}', $coupon->id, $delete_url); ?> <tr> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if (isset($coupon->$field) && trim($coupon->$field) !== '') { echo HTML::chars($coupon->$field); } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать купон', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить купон', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; ?> </table> <file_sep>/application/classes/controller.php <?php defined('SYSPATH') OR die('No direct access allowed.'); /** * Controller * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Controller extends Kohana_Controller { /** * @var Request */ public $request; /** * Now the before() function must return the boolean value. * It is used to controll the execution of the current action: * if TRUE - the action will be executed * if FALSE - the action will NOT be executed (but the after() method will still be called) * * Note, that before() function MUST return FALSE in case it forwards the request * * @return boolean */ public function before() { return TRUE; } /** * Creates and prepares layout to be used for controller * * @return Layout */ public function prepare_layout($layout_script = NULL) { if ($layout_script === NULL) { throw new Kohana_Exception('Layout script name undefined'); } $layout = Layout::instance(); $layout->set_filename($layout_script); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $layout = $this->prepare_layout($layout_script); $layout->content = $content; return $layout->render(); } /** * Generic ajax actions - prepares the response for output */ protected function _action_ajax() { // Put flash messages into response $this->request->response['messages'] = FlashMessages::fetch_all(); // Encode in json $this->request->response = json_encode($this->request->response); } }<file_sep>/modules/general/tags/views/backend/tags.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Width & height of one image preview $canvas_height = 110; $canvas_width = 110; $create_url = URL::to('backend/tags', array( 'action'=>'create', 'owner_type' => $owner_type, 'owner_id' => $owner_id, 'config' => $config ), TRUE); $update_url = URL::to('backend/tags', array('action'=>'update', 'id' => '${id}', 'config' => $config), TRUE); $delete_url = URL::to('backend/tags', array('action'=>'delete', 'id' => '${id}', 'config' => $config), TRUE); $up_url = URL::to('backend/tags', array('action'=>'up', 'id' => '${id}'), TRUE); $down_url = URL::to('backend/tags', array('action'=>'down', 'id' => '${id}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } ?> <div class="caption">Теги</div> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Добавить Теги</a> </div> <div class="tags"> <?php foreach ($tags as $tag) : $tag->config = $config; $_update_url = str_replace('${id}', $tag->id, $update_url); $_delete_url = str_replace('${id}', $tag->id, $delete_url); $_up_url = str_replace('${id}', $tag->id, $up_url); $_down_url = str_replace('${id}', $tag->id, $down_url); ?> <div class="tag"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить тег', 'controls/delete.gif', 'Удалить'); ?> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать тег', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_up_url, 'Переместить вверх', 'controls/left.gif', 'Вверх'); ?> <?php echo View_Helper_Admin::image_control($_down_url, 'Переместить вниз', 'controls/right.gif', 'Вниз'); ?> </div> <div class="img" style="width: <?php echo $canvas_width; ?>px; height: <?php echo $canvas_width; ?>px;"> <a href="<?php echo $_update_url; ?>" style="<?php echo $padding; ?>"> <img src="<?php echo File::url($image->image($i)); ?>" <?php echo $scale; ?> alt="" /> </a> </div> </div> <?php endforeach; ?> </div><file_sep>/modules/system/database_eresus/classes/database/mysql.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Extends Kohana_Database_Mysql functionality: * - create_table, describe_table, update_table, drop_table support * * @package Eresus * @author <NAME> (<EMAIL>) */ class Database_MySQL extends Kohana_Database_MySQL { // Force using SET NAMES protected static $_set_names = TRUE; /** * List of tables in the database * * @var array */ protected $_tables_cache; /** * Table columns info cache * * @var array */ protected $_table_columns_cache; /** * Table indexes cache * * @var array */ protected $_table_indexes_cache; /** * Returns a list of tables in database via 'SHOW TABLES FROM' query. * * @param string $use_cache Allow to use cached results * @return array List of tables */ public function list_tables($use_cache = TRUE) { if ($this->_tables_cache === NULL || !$use_cache) { $this->_tables_cache = parent::list_tables(); } return $this->_tables_cache; } /** * Returns information about database table, * including information about columns and indexes * * Results are obtained via 'SHOW COLUMNS FROM' and 'SHOW INDEXES FROM' sql commands. * * @param string Table name * @return array Array of columns (including indexes) */ public function describe_table($table_name) { // Table columns if (!isset($this->_table_columns_cache[$table_name])) { $result = $this->query(Database::SELECT, 'SHOW COLUMNS FROM ' . $this->quote_table($table_name), FALSE); if (is_object($result)) { if ($result instanceof Database_Result) { $result = $result->as_array(); } else { throw new Exception('Database query returned result of unkonwn type ":type"', array(':type' => get_class($result))); } } $this->_table_columns_cache[$table_name] = array(); foreach ($result as $column) { $this->_table_columns_cache[$table_name][$column['Field']] = $column; } } // Table indexes if (!isset($this->_table_indexes_cache[$table_name])) { $result = $this->query(Database::SELECT, 'SHOW INDEXES FROM ' . $this->quote_table($table_name), FALSE); if (is_object($result)) { if ($result instanceof Database_Result) { $result = $result->as_array(); } else { throw new Exception('Database query returned result of unkonwn type ":type"', array(':type' => get_class($result))); } } $this->_table_indexes_cache[$table_name] = array(); foreach ($result as $index) { // Support multi-column index: mysql returns a row for every column in index with same Key_name if (!isset($this->_table_indexes_cache[$table_name][$index['Key_name']])) { $this->_table_indexes_cache[$table_name][$index['Key_name']] = array( 'Key_name' => $index['Key_name'], 'Column_names' => array($index['Column_name']), 'Non_unique' => $index['Non_unique'] ); } else { // Append column to index $this->_table_indexes_cache[$table_name][$index['Key_name']]['Column_names'][] = $index['Column_name']; } } } return array($this->_table_columns_cache[$table_name], $this->_table_indexes_cache[$table_name]); } /** * Creates table in database (if not already exists) with supplied columns and indexes. * * Columns is an array of column_name => column_properties * For avaliable column_properties keys @see _column_sql * * Indexes is an array of index_name => index_properties * For avaliable index_properties keys @see _index_sql * * @param string $table_name Name of the table * @param array $columns Columns for the table * @param array $indexes Indexes for the table * @param array $options Table options */ public function create_table($table_name, array $columns, array $indexes, array $options, $if_not_exists = TRUE) { if (empty($columns)) { throw new Exception('No columns specified for create_table()!'); } $sql = ''; // Add columns foreach ($columns as $column) { $sql .= ',' . $this->_column_sql($column); } // Add indexes foreach ($indexes as $index) { $sql .= ',' . $this->_index_sql($index); } $sql = trim($sql, ', '); if ( ! isset($options['ENGINE'])) { // Default engine is MYISAM $options['ENGINE'] = 'MYISAM'; } $opts = ''; foreach ($options as $k => $v) { $opts .= " $k=$v"; } $sql = 'CREATE TABLE ' . ($if_not_exists ? 'IF NOT EXISTS ' : '') . $this->quote_table((string) $table_name) . ' (' . $sql . ')' . $opts; $this->query(NULL, $sql, FALSE); } /** * Alter table in database: * adds columns $columns_to_add, * drops columns $columns_to_drop, * adds indexes $indexes_to_add, * drops indexes $indexes_to_drop * * Format of columns and indexes array is the same as in @link create_table * * @param string $table_name * @param array $columns_to_add Columns to add * @param array $columns_to_drop Columns to drop * @param array $indexes_to_add Indexes to add * @param array $indexes_to_drop Indexes to drop */ public function alter_table($table_name, array $columns_to_add, array $columns_to_drop, array $indexes_to_add, array $indexes_to_drop) { if ( empty($columns_to_add) && empty($columns_to_drop) && empty($indexes_to_add) && empty($indexes_to_drop) ) { // Nothing to do return; } $sql = ''; // Add columns and indexes $add_sql = ''; foreach ($columns_to_add as $column) { $add_sql .= ',' . $this->_column_sql($column); } foreach ($indexes_to_add as $index) { $add_sql .= ',' . $this->_index_sql($index); } $add_sql = trim($add_sql, ', '); if ($add_sql !== '') { $sql .= 'ADD COLUMN (' . $add_sql . ')'; } // Drop columns and indexes $drop_sql = ''; foreach ($columns_to_drop as $column) { if (!isset($column['Field'])) { // Column name is required throw new Exception('"Field" not specified for column :column!', array(':column' => print_r($column, TRUE))); } $drop_sql .= ', DROP COLUMN ' . $this->quote_identifier($column['Field']); } foreach ($indexes_to_drop as $index) { if (!isset($index['Key_name'])) { // Column name is required throw new Exception('"Key_name" not specified for index :index!', array(':index' => print_r($index, TRUE))); } $drop_sql .= ', DROP INDEX ' . $this->quote_identifier($index['Key_name']); } $drop_sql = trim($drop_sql, ', '); if ($drop_sql !== '') { if ($sql !== '') { $sql .= ', '; } $sql .= $drop_sql; } $sql = 'ALTER TABLE ' . $this->quote_table((string) $table_name) . ' ' . $sql; $this->query(NULL, $sql, FALSE); } /** * Builds an sql expression to create a column. * * column must have folowing keys: * - 'Field': name of the column * - 'Type': type of the column (any sql type like 'int(11)', 'varchar(255)') * * Also you can specify this keys: * - 'Null': Column can have NULL values ('YES' or 'NO') * - 'Default': Default value for the column * - 'Extra': Additional attributes (like 'auto_increment') * * * @param array $column Column properties * @return string SQL expression for column. (Like: '`login` CHAR(15) NOT NULL DEFAULT 'nobody') */ protected function _column_sql(array $column) { if (!isset($column['Field'])) { // Column name is required throw new Exception('"Field" not specified for column :column!', array(':column' => print_r($column, TRUE))); } $name = $this->quote_identifier($column['Field']); if (!isset($column['Type'])) { // Column type is required throw new Exception('Type not specified for column :name!', array(':name' => $name)); } $type = strtoupper($column['Type']); if (isset($column['Null']) && strtoupper($column['Null']) === 'NO' ) { $null = 'NOT NULL'; } else { $null = 'NULL'; } if (isset($column['Default'])) { $default = 'DEFAULT ' . $this->quote($column['Default']); } else { $default = ''; } if (isset($column['Extra'])) { $extra = $column['Extra']; } else { $extra = ''; } $sql = "$name $type $null $default $extra"; return $sql; } /** * Builds an sql expression to create an index. * * index must have folowing keys: * - 'Key_name': Name of the key (if 'PRIMARY' - it's a PRIMARY KEY) * - 'Column_names': Array of column names that index is created for * * Also you can specify this keys: * - 'Non_unique': 0 for UNIQUE index, 1 for NON UNIQUE index * * @param array $index Index properties * @return string SQL expression for index. (Like: UNIQUE `some_index` (`col1`, `col2`)) */ protected function _index_sql(array $index) { if (!isset($index['Key_name'])) { // Index name is required throw new Exception('"Key_name" not specified for index :index!', array(':index' => print_r($index, TRUE))); } $name = $this->quote_identifier($index['Key_name']); if (empty($index['Column_names'])) { // Column_names are required throw new Exception('Column names not specified for index :name', array(':name' => $index['Key_name'])); } $index_columns = ''; foreach ($index['Column_names'] as $column_name) { $index_columns .= ',' . $this->quote_identifier($column_name); } $index_columns = trim($index_columns, ', '); if ($index['Key_name'] == 'PRIMARY') { // A primary key $sql = 'PRIMARY KEY (' . $index_columns . ')'; } elseif (empty($index['Non_unique'])) { // A unique index $sql = 'UNIQUE ' . $name . ' (' . $index_columns . ')'; } else { // Index $sql = 'INDEX ' . $name . ' (' . $index_columns . ')'; } return $sql; } } <file_sep>/modules/shop/catalog/classes/model/sectiongroup/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_SectionGroup_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('system', array('Type' => 'boolean')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('name', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(31)')); // $this->cache_find_all = TRUE; } }<file_sep>/modules/shop/catalog/classes/model/telemost/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Telemost_Mapper extends Model_Mapper_Resource { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('product_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('place_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('event_uri', array('Type' => 'varchar(127)')); $this->add_column('info', array('Type' => 'text')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); $this->add_column('visible', array('Type' => 'boolean', 'Key' => 'INDEX')); $this->add_column('created_at', array('Type' => 'int unsigned')); // $this->cache_find_all = TRUE; } /** * Find all models by criteria and return them in {@link Models} container * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by( Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->distinct('whatever') ->from($table); } if (is_array($condition) && isset($condition['town'])) { $place_table = Model_Mapper::factory('Model_Place_Mapper')->table_name(); $query ->where("$place_table.town_id", '=', (int) $condition['town']->id); $params['join_place'] = TRUE; unset($condition['town']); } // ----- joins $this->_apply_joins($query, $params); return parent::find_all_by($model, $condition, $params, $query); } /** * Apply joins to the query * * @param Database_Query_Builder_Select $query * @param array $params */ protected function _apply_joins(Database_Query_Builder_Select $query, array $params = NULL) { $table = $this->table_name(); if ( ! empty($params['join_place'])) { $place_table = Model_Mapper::factory('Model_Place_Mapper')->table_name(); $query ->join($place_table, 'LEFT') ->on("$place_table.id", '=', "$table.place_id"); } } }<file_sep>/modules/backend/views/backend/workspace_2col.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <table class="workspace_content_2col"><tr> <td class="column1"> <?php echo $column1; ?> </td> <td class="column2"> <?php echo $column2; ?> </td> </tr></table><file_sep>/modules/shop/catalog/classes/form/backend/property.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Property extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->layout = 'wide'; $cols = new Form_Fieldset_Columns('property'); $this->add_component($cols); // ----- caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()); $cols->add_component($element); // ----- name $element = new Form_Element_Input('name', array('label' => 'Имя', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Alnum()); $element->comment = 'Имя для свойства, состоящее из цифр и букв латинсокого алфавита для использования в шаблонах. (например: price, weight, ...)'; $cols->add_component($element); // ----- Type $options = $this->model()->get_types(); $element = new Form_Element_RadioSelect('type', $options, array('label' => 'Тип')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- Options $options_count = 5; if ($this->model()->options !== NULL) { $options_count = count($this->model()->options); } $element = new Form_Element_Options("options", array('label' => 'Возможные значения', 'options_count' => $options_count), array('maxlength' => Model_Property::MAX_PROPERTY) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Property::MAX_PROPERTY)); $cols->add_component($element); // ----- PropSections grid // ----- Role properties // ----- Role properties // Button to select active sectiongroups for property $history = URL::uri_to('backend/catalog/properties', array('action' => 'sectiongroups_select'), TRUE); $sections_select_url = URL::to('backend/catalog/sectiongroups', array( 'action' => 'select', 'history' => $history ), TRUE); $button = new Form_Element_LinkButton('select_sectiongroups_button', array('label' => 'Выбрать'), array('class' => 'button_select_sectiongroups open_window') ); $button->layout = 'standalone'; $button->url = $sections_select_url; $cols->add_component($button,2); $fieldset = new Form_Fieldset('secgr', array('label' => 'Разделы')); $cols->add_component($fieldset,2); // ----- Additional sectiongroups $sectiongroups = Model::fly('Model_SectionGroup')->find_all_by_site_id(Model_Site::current()->id, array('columns' => array('id', 'caption'))); if (Request::current()->param('cat_sectiongroup_ids') != '') { // Are section ids explicitly specified in the uri? $sectiongroup_ids = explode('_', Request::current()->param('cat_sectiongroup_ids')); } // Obtain a list of selected sectiongroups in the following precedence // 1. From $_POST // 2. From cat_sectiongroup_ids request param // 3. From model if ($this->is_submitted()) { $supplied_sectiongroups = $this->get_post_data('sectiongroups'); if ( ! is_array($supplied_sectiongroups)) { $supplied_sectiongroups = array(); } // Filter out invalid sectiongroups foreach ($supplied_sectiongroups as $sectiongroup_id => $selected) { if ( ! isset($sectiongroups[$sectiongroup_id])) { unset($supplied_sectiongroups[$sectiongroup_id]); } } } elseif (isset($sectiongroup_ids)) { // Section ids are explicitly specified in the uri $supplied_sectiongroups = array(); foreach ($sectiongroup_ids as $sectiongroup_id) { if (isset($sectiongroups[$sectiongroup_id])) { $supplied_sectiongroups[$sectiongroup_id] = 1; } } } else { $supplied_sectiongroups = $sectiongroups; } if ( ! empty($supplied_sectiongroups)) { foreach ($supplied_sectiongroups as $sectiongroup_id => $selected) { if (isset($sectiongroups[$sectiongroup_id])) { $sectiongroup = $sectiongroups[$sectiongroup_id]; $element = new Form_Element_Hidden('sectiongroups[' . $sectiongroup->id . ']', array('label' => $sectiongroup->caption)); $this->add_component($element); } } } $x_options = array('active' => 'Акт.', 'filter' => 'Фильтр', 'sort' => 'Сорт.'); $y_options = array(); $label = ''; foreach ($supplied_sectiongroups as $supplied_sectiongroup_id => $supplied_sectiongroup_selected) { $supplied_sectiongroup = $sectiongroups[$supplied_sectiongroup_id]; $label = $label.' '.$supplied_sectiongroup->caption; $sections = Model::fly('Model_Section')->find_all_by_sectiongroup_id($supplied_sectiongroup->id, array( 'order_by' => 'lft', 'desc' => FALSE, )); foreach ($sections as $section) { $y_options[$section->id] = str_repeat('&nbsp;', max($section->level - 1, 0)*4) . $section->caption; } } if (!empty($y_options)) { $element = new Form_Element_CheckGrid('propsections', $x_options, $y_options, array('label' => 'Настройки для разделов: '.$label) ); $element->config_entry = 'checkgrid_capt'; $fieldset->add_component($element); } // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $cols->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts // Url for ajax requests to redraw additional sections for selected sectiongroups $on_sectiongroups_select_url = URL::to('backend/catalog/properties', array( 'action' => 'ajax_sectiongroups_select', 'id' => $this->model()->id, 'cat_sectiongroup_ids' => '{{sectiongroup_ids}}', )); Layout::instance()->add_script( "var property_form_name='" . $this->name . "';\n\n" . "var on_sectiongroups_select_url = '" . $on_sectiongroups_select_url . "';\n" , TRUE); $script =''; $component = $this->find_component('secgr'); if ($component !== FALSE) { $script .= "var propsections_fieldset ='" . $component->id . "';\n"; } Layout::instance()->add_script($script, TRUE); // Link product form scripts jQuery::add_scripts(); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/backend/property_form.js'); } }<file_sep>/modules/general/pages/classes/controller/frontend/pages.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Pages extends Controller_FrontendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Page'; $this->_form = 'Form_Backend_Page'; return array( 'update' => array( 'view_caption' => 'Редактирование страницы ":caption"' ) ); } /** * Display a text page */ public function action_view() { // Current node $node = Model_Node::current(); if ( ! isset($node->id) || ! $node->active) { $this->_action_404('Страница не найдена'); return; } // Find page for current node $page = new Model_Page(); $page->find_by_node_id($node->id); if ( ! isset($page->id)) { $this->_action_404('Страница не найдена'); return; } $this->request->response = $this->render_layout($page->content); } /** * Prepare page model for update action * * @param string|Model $page * @param array $params * @return Model */ protected function _model_update($page, array $params = NULL) { // Find page by given node id $page = new Model_Page(); $page->find_by_node_id((int) $this->request->param('node_id')); if ( ! isset($page->id)) { throw new Controller_FrontendCRUD_Exception('Текстовая страница не найдена'); } return $page; } } <file_sep>/modules/general/chat/classes/controller/backend/messages.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Messages extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Message'; $this->_form = 'Form_Backend_Message'; return array( 'create' => array( 'view_caption' => 'Создание сообщения' ), 'delete' => array( 'view_caption' => 'Удаление сообщения', 'message' => 'Удалить сообщение ":message_preview"?' ), 'multi_delete' => array( 'view_caption' => 'Удаление сообщений', 'message' => 'Удалить выбранные сообщения?' ) ); } /** * Prepare message for create/delete action * * @param string $action * @param string|Model_Message $message * @param array $params * @return Model_Message */ protected function _model($action, $message, array $params = NULL) { $message = parent::_model($action, $message, $params); if ($action == 'create') { $message->dialog_id = $this->request->param('dialog_id'); $dialog = new Model_Dialog(); $dialog->find((int) $this->request->param('dialog_id')); if (isset($dialog->id)) { $message->dialog_id = $dialog->id; $message->sender_id = $dialog->sender_id; $message->receiver_id = $dialog->receiver_id; } else { // user_id can be changed via url parameter $user_id = $this->request->param('user_id', NULL); if ($user_id !== NULL) { $user_id = (int) $user_id; if ( ($user_id == 0) || ($user_id > 0 && Model::fly('Model_User')->exists_by_id($user_id)) ) { $message->receiver_id = $user_id; } } } } return $message; } /** * Create layout (proxy to dialog controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('dialogs')->prepare_layout($layout_script); } /** * Render layout (proxy to dialog controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('dialogs')->render_layout($content, $layout_script); } /** * Render list of dialogs and corresponding messages using two-column panel */ public function action_index() { $view = new View('backend/workspace'); $view->content = $this->widget_messages(); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Renders list of messages * * @return string Html */ public function widget_messages() { $message = new Model_Message(); $per_page = 5; $view = new View('backend/messages'); $dialog_id = (int) $this->request->param('dialog_id'); if ($dialog_id > 0) { // Show messages only from specified dialog $dialog = new Model_Dialog(); $dialog->find($dialog_id); if ($dialog->id === NULL) { // Dialog was not found - show a form with error message return $this->_widget_error('Диалог с идентификатором ' . $dialog_id . ' не найден!'); } $count = $message->count_by_dialog_id($dialog->id); $pagination = new Pagination($count, $per_page); $messages = $message->find_all_by_dialog_id($dialog->id, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => 'created_at', 'desc' => '1' ), TRUE); // Prepare model for create action $model = $this->_prepare_model('create', array()); // Prepare form for action $form = new Form_Backend_SmallMsg($model); // It's a POST action create if ($form->is_submitted() && $form->validate()) { $message = new Model_Message($form->get_values()); $message->save(); $this->request->redirect($this->request->uri()); } $view->dialog = $dialog; $view->messages = $messages; $view->pagination = $pagination->render('backend/pagination'); $view->form = $form; } return $view->render(); } }<file_sep>/modules/shop/orders/views/backend/order.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="panel"> <div class="panel_header"> <?php if (isset($caption)) { echo '<div class="panel_caption">' . $caption . '</div>'; } ?> <?php echo $form->render_tabs(); ?> </div> <div class="panel_content"> <?php echo $form->render(); ?> </div> </div> <div class="caption">Товары в заказе</div> <?php echo $cartproducts; ?> <div class="caption">Комменатрии к заказу</div> <?php echo $ordercomments; ?><file_sep>/modules/backend/classes/controller/backend.php <?php defined('SYSPATH') or die('No direct script access.'); abstract class Controller_Backend extends Controller { /** * Allow only access to admin controllers onlу for authenticated users */ public function before() { if (Modules::registered('acl') && ! Auth::granted('backend_access')) { $this->request->forward('acl', 'login'); return FALSE; } return TRUE; } /** * Creates and prepares layout to be used for admin controllers * Adds default admin stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { if ($layout_script === NULL) { if ($this->request->in_window()) { $layout_script = 'layouts/backend/window'; } else { $layout_script = 'layouts/backend/default'; } } $layout = parent::prepare_layout($layout_script); // Add standart js scripts jQuery::add_scripts(); $layout->add_script(Modules::uri('backend') . '/public/js/backend.js'); $layout->add_script(Modules::uri('backend') . '/public/js/windows.js'); $layout->add_script(Modules::uri('widgets') . '/public/js/widgets.js'); return $layout; } /** * Displays an error message * * @param string $msg * @param string $view * @param array $params */ protected function _action_error($msg = 'Произошла ошибка!', $view = 'backend/form', $params = array()) { if ( ! ($view instanceof View)) { // Create view $view = new View((string) $view); } $view->caption = 'Ошибка'; $view->form = $this->_widget_error($msg); $this->request->response = $this->render_layout($view); } /** * Renders a form with an error message * * @param string $msg * @return string */ protected function _widget_error($msg = 'Произошла ошибка!') { $form = new Form_Backend_Error($msg); return $form; } } <file_sep>/modules/general/faq/views/frontend/question.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <table class="faq"><tr> <td class="questions_cell"> <div class="questions"> <div class="question"> <div class="q"><strong>Вопрос:</strong> <?php echo HTML::chars($question->question); ?></div> <div class="a"><strong>Ответ:</strong> <?php echo HTML::chars($question->answer); ?></div> <div class="date"><strong><?php echo $question->date; ?></strong></div> </div> </div> <br /> <a href="<?php echo $faq_url; ?>">&laquo; К списку вопросов</a> </td> <td class="faq_form_cell"> <?php echo $form; ?> </td> </tr></table><file_sep>/modules/shop/catalog/public/js/backend/property_form.js /** * Sections select callback (called from section select iframe) */ function on_sectiongroups_select(sectiongroup_ids) { if ( ! propsections_fieldset || ! on_sectiongroups_select_url) return; // Peform an ajax request to redraw form "additional sections" elements if (sectiongroup_ids.length) { sectiongroup_ids = sectiongroup_ids.join('_'); } else { // dummy value when no ids are selected sectiongroup_ids = '_'; } var url = on_sectiongroups_select_url .replace('{{sectiongroup_ids}}', sectiongroup_ids); $('#' + propsections_fieldset).html('Loading...'); $.get(url, null, function(response){ // Redraw "additional sections" fieldset if (response) { $('#' + propsections_fieldset).html(response); } }); } <file_sep>/application/config/ulogin.php <?php defined('SYSPATH') OR die('No direct access allowed.'); return array ( // на какой адрес придёт POST-запрос от uLogin 'redirect_uri' => Url::base(Request::$current, true).'acl/login_social', 'optional' => array('phone'), 'fields' => array('city'), ); <file_sep>/modules/system/forms/classes/form/validator/stringlength.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validates that length of string is in specified boundaries * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_StringLength extends Form_Validator { const TOO_LONG = 'TOO_LONG'; const TOO_SHORT = 'TOO_SHORT'; protected $_messages = array( self::TOO_SHORT => 'Колчиество символов в поле ":label" должно быть не меньше :minlength!', self::TOO_LONG => 'Колчиество символов в поле ":label" не должно превышать :maxlength!' ); /** * Maximum allowed string length * @var int */ protected $_maxlength = 0; /** * Minimum allowed string length * @var int */ protected $_minlength = 0; /** * Creates validator * * @param int $minlength Minimum allowed string length * @param int $maxlength Maximum allowed string length * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure */ public function __construct($minlength, $maxlength, array $messages = NULL, $breaks_chain = TRUE) { parent::__construct($messages, $breaks_chain); $this->_maxlength = $maxlength; $this->_minlength = $minlength; } /** * Validate! * * @param array $context */ protected function _is_valid(array $context = NULL) { $value = (string) $this->_value; $strlen = UTF8::strlen($value); if ($this->_maxlength > 0 && $strlen > $this->_maxlength) { $this->_error(self::TOO_LONG); return false; } if ($strlen < $this->_minlength) { $this->_error(self::TOO_SHORT); return false; } return true; } /** * Replaces :maxlength and :minlength * * @param string $error_text * @return string */ protected function _replace_placeholders($error_text) { $error_text = parent::_replace_placeholders($error_text); return str_replace( array(':maxlength', ':minlength'), array($this->_maxlength, $this->_minlength), $error_text ); } /** * Render javascript for this validator * * @return string */ public function render_js() { $messages = array(); foreach ($this->_messages as $code => $error_text) { $messages[$code] = $this->_replace_placeholders($error_text); } $config = array( 'messages' => $messages ); $js = "v = new jFormValidatorStringLength(" . "{$this->_minlength}, {$this->_maxlength}" . ", " . json_encode($config) . ");\n"; return $js; } }<file_sep>/modules/shop/catalog/views/frontend/products/fullscreen.php <?php defined('SYSPATH') or die('No direct script access.');?> <?php $url = URL::to('frontend/catalog/product/fullscreen', array('alias' => $product->alias)); if (isset($_GET['width']) AND isset($_GET['height'])) { ?> <div class ="look"> <iframe src="<?php echo $aim->event_uri ?>?t=1&export=1&logout=www<?php echo URL::self(array());?>" width="<?php echo $_GET['width'] ?>" height="<?php echo $_GET['height'] ?>" frameborder="0" style="border:none"></iframe> </div> <?php } else { // передаем переменные с размерами // (сохраняем оригинальную строку запроса // -- post переменные нужно будет передавать другим способом) echo "<script language='javascript'>\n"; echo " location.href=\"$url?" . "&width=\" + (screen.width-80) + \"&height=\" + (screen.height-80);\n"; echo "</script>\n"; exit(); } ?> <file_sep>/application/classes/model/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Model data mapper. * Maps model to a table in database * * @package Eresus * @author <NAME> (<EMAIL>) */ class Model_Mapper extends DbTable { /** * Mapper instances * @var array */ protected static $_mappers; /** * Return an instance of mapper * * @param string $class * @return Model_Mapper */ public static function factory($class) { if ( ! isset(self::$_mappers[$class])) { self::$_mappers[$class] = new $class(); } return self::$_mappers[$class]; } /** * Whether to cache or not to cache the result of find_all_by() function * * @var boolean */ public $cache_find_all = FALSE; /** * Limit maximum number of cached items * @var integer */ public $cache_limit = 100; /** * Cache * @var array */ protected $_cache; /** * Offset for batch find * @var integer */ protected $_batch_offset = 0; /** * Sets/gets db table name * * @param string $table_name * @return string */ public function table_name($table_name = NULL) { if ($table_name !== NULL) { $this->_table_name = $table_name; } if ($this->_table_name === NULL) { // Construct table name from class name $table_name = strtolower(get_class($this)); if (substr($table_name, -strlen('_mapper')) === '_mapper') { $table_name = substr($table_name, 0, -strlen('_mapper')); } elseif (substr($table_name, -strlen('_mapper_db')) === '_mapper_db') { $table_name = substr($table_name, 0, -strlen('_mapper_db')); } if (substr($table_name, 0, strlen('model_')) === 'model_') { $table_name = substr($table_name, strlen('model_')); } $this->_table_name = $table_name; } return $this->_table_name; } /** * Prepare model values for saving: * Leave values only for known columns. * Also setup values for special columns: * -position * -created_at * * * @param Model $model * @param boolean $force_create * @param array $values that will be prepared for saving in the database * @return array */ public function before_save(Model $model, $force_create = FALSE, array $values = array()) { foreach ($this->_columns as $name => $column) { if ($name == 'position' && ( ! isset($model->id) || $force_create)) { $values['position'] = (int) $this->max_position($model) + 1; $model->position = $values['position']; } elseif ($name == 'created_at' && ( ! isset($model->id) || $force_create) && $model->created_at === NULL) { $values['created_at'] = time(); $model->created_at = $values['created_at']; } elseif (isset($model->$name)) { $values[$name] = $model->$name; } } return $values; } /** * Save model to database. * Updates existing row or inserts a new one * * @param Model $model * @param boolean $force_create If true, even models with existing pk's will be inserted * @return integer Id of inserted/updated row */ public function save(Model $model, $force_create = FALSE) { $pk = $this->get_pk(FALSE); // Prepare values to be saved $values = $this->before_save($model, $force_create); if ($pk !== NULL) { $id = $model->$pk; } else { $id = NULL; } if ($id === NULL || $force_create) { // Insert new row $id = $this->insert($values); if ($pk !== NULL) { $model->$pk = $id; } } else { // Update existing row $this->update($values, DB::where($pk, '=', $id)); } return $id; } /*************************************************************************** * Find **************************************************************************/ /** * Find model by condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Model|array */ public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $result = $this->select_row($condition, $params, $query); // Return the result of the desired type if (empty($params['as_array'])) { if ( ! empty($result)) { $model->properties($result); } else { $model->init(); } return $model; } return $result; } /** * Find model by primary key * * @param Model $model * @param mixed $pk_value * @param array $params * @return Model */ public function find(Model $model, $pk_value, array $params = NULL) { return $this->find_by($model, array($this->get_pk() => $pk_value), $params); } public function find_another_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $pk = $this->get_pk(); if ($model->$pk !== NULL) { $condition = $this->_prepare_condition($condition); $condition->and_where($pk, '!=', $model->$pk); } return $this->find_by($model, $condition, $params, $query); } /** * Find all models by criteria and return them in {@link Models} container * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { if ($params === NULL) { $params = $model->params_for_find_all(); } if ( ! empty($params['batch'])) { // Batch find $params['offset'] = $this->_batch_offset; $params['limit'] = $params['batch']; } if ( ! isset($params['key'])) { $params['key'] = $this->get_pk(); } // ----- cache if ($this->cache_find_all) { $condition = $this->_prepare_condition($condition); $hash = $this->params_hash($params, $condition); if (isset($this->_cache[$hash])) { // Cache hit! return $this->_cache[$hash]; } } $result = $this->select($condition, $params, $query); if ( ! empty($params['batch'])) { // Batch find if ( ! empty($result)) { $this->_batch_offset += count($result); } else { // Reset $this->_batch_offset = 0; } } // Return the result of the desired type if (empty($params['as_array'])) { $key = isset($params['key']) ? $params['key'] : FALSE; $result = new Models(get_class($model), $result, $key); } // ----- cache if ($this->cache_find_all) { if (count($this->_cache) < $this->cache_limit) { $this->_cache[$hash] = $result; } } return $result; } /** * Find all models * * @param Model $model * @param array $params * @return Models */ public function find_all(Model $model, array $params = NULL) { return $this->find_all_by($model, NULL, $params); } public function find_another_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $pk = $this->get_pk(); if ($model->$pk !== NULL) { $condition = $this->_prepare_condition($condition); $condition->and_where($pk, '!=', $model->$pk); } return $this->find_all_by($model, $condition, $params, $query); } /*************************************************************************** * Count & exists **************************************************************************/ /** * Count all models by given condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @return integer */ public function count_by(Model $model, $condition = NULL) { return $this->count_rows($condition); } /** * Get the offset of model row in DB assuming the sorting, specified by $params * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @return integer */ public function offset_by(Model $model, $condition = NULL, array $params = NULL) { $condition = $this->_prepare_condition($condition); if ( ! isset($params['order_by'])) throw new Kohana_Exception ('Order by must be specified for offset_by method!'); $order_by = $params['order_by']; if (empty($params['desc'])) { $condition->and_where($order_by, '<', $this->_sqlize_value($model->$order_by, $order_by)); } else { $condition->and_where($order_by, '>', $this->_sqlize_value($model->$order_by, $order_by)); } return $this->count_rows($condition, $params); } /** * Count all models * * @param Model $model * @return integer */ public function count(Model $model) { return $this->count_by($model, NULL); } /** * Check if there is a model with specified condition * * @param Model $model * @param sting|array|Database_Expression_Where $condition * @return boolean */ public function exists_by(Model $model, $condition) { return $this->exists($condition); } /** * Check if there is another model with given condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @return boolean */ public function exists_another_by(Model $model, $condition) { $pk = $this->get_pk(); if ($model->$pk !== NULL) { $condition = $this->_prepare_condition($condition); $condition->and_where($pk, '!=', $model->$pk); } return $this->exists($condition); } /*************************************************************************** * Delete **************************************************************************/ /** * Delete all models by criteria * * @param Model $model * @param string|array|Database_Expression_Where $condition * @return Models */ public function delete_all_by(Model $model, $condition = NULL) { $this->delete_rows($condition); } /** * Delete model by primary key * * @param Model $model * @return Model */ public function delete(Model $model) { $pk = $this->get_pk(); $this->delete_all_by($model, DB::where($pk, '=', $model->$pk)); $model->init(); } /** * Magic method - automatically resolves the following methods: * - find_by_* * - find_all_by_* * - exists_another_by_* * - delete_all_by_* * - count_by_* * * @param string $name * @param array $arguments * @return mixed */ public function __call($name, array $arguments) { // Model is always a first argument to mapper method $model = array_shift($arguments); // find_by_* methods if (strpos($name, 'find_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('find_by_')), $arguments, $name); $params = array_shift($arguments); return $this->find_by($model, $condition, $params); } // find_another_by_* methods if (strpos($name, 'find_another_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('find_another_by_')), $arguments, $name); $params = array_shift($arguments); return $this->find_another_by($model, $condition, $params); } // find_all_by_* methods if (strpos($name, 'find_all_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('find_all_by_')), $arguments, $name); $params = array_shift($arguments); return $this->find_all_by($model, $condition, $params); } // find_another_all_by_* methods if (strpos($name, 'find_another_all_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('find_another_all_by_')), $arguments, $name); $params = array_shift($arguments); return $this->find_another_all_by($model, $condition, $params); } // exists_by_* methods if (strpos($name, 'exists_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('exists_by_')), $arguments, $name); return $this->exists_by($model, $condition); } // exists_another_by_* methods if (strpos($name, 'exists_another_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('exists_another_by_')), $arguments, $name); return $this->exists_another_by($model, $condition); } // delete_all_by_* methods if (strpos($name, 'delete_all_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('delete_all_by_')), $arguments, $name); return $this->delete_all_by($model, $condition); } // count_by_* methods if (strpos($name, 'count_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('count_by_')), $arguments, $name); return $this->count_by($model, $condition); } throw new Kohana_Exception('Unknown method :method', array(':method' => get_class($this) . '::' . $name)); } /** * Convert column names string to array criteria, that can be used as a criteria * for find_all_by and find_by methods * [!] arguments array is modified: columns are shifted off * * @param string $columns_string * @param array $arguments <-- Passed by REFERENCE and is modified * @param string $method_name * @return array */ protected function _cols_to_condition_array($columns_string, array & $arguments, $method_name) { $columns = explode('_and_', $columns_string); if (count($columns) > count($arguments)) { throw new Kohana_Exception('Not enough arguments for :method. Number of columns = :cols, while number of arguments = :args', array(':method' => get_class($this) . '::' . $method_name, ':cols' => count($columns), ':args' => count($arguments))); } $condition = array(); foreach ($columns as $column) { $condition[$column] = array_shift($arguments); } return $condition; } /** * Move model one position up * * @param Model $model * @param Database_Expression_Where $condition */ public function up(Model $model, Database_Expression_Where $condition = NULL) { if ( ! isset($this->_columns['position'])) { throw new Kohana_Exception('Unable to move :model up: model has no "position" column!', array(':model' => get_class($this)) ); } $pk = $this->get_pk(); $db = $this->get_db(); // Escape everything $id = $db->quote($model->$pk); $pk = $db->quote_identifier($pk); $pos = $db->quote_identifier('position'); $table = $db->quote_table($this->table_name()); if ($condition !== NULL) { $condition = " AND " . (string) $condition; } else { $condition = ''; } $this->lock(); $db->query(NULL, "SELECT @pos:=NULL, @next_pos:=null, @next_id:=null", FALSE); $db->query(NULL, "SELECT @pos:=$pos FROM $table WHERE ($pk=$id)", FALSE); $db->query(NULL, "SELECT @next_id:=$pk,@next_pos:=$pos FROM $table WHERE ($pos>@pos) $condition ORDER BY $pos ASC LIMIT 1", FALSE); $db->query(NULL, "UPDATE $table SET $pos=@next_pos WHERE (@next_pos IS NOT NULL) AND ($pk=$id)", FALSE); $db->query(NULL, "UPDATE $table SET $pos=@pos WHERE (@next_id IS NOT NULL) AND ($pk=@next_id)", FALSE); $this->unlock(); } /** * Move model one position down * * @param Model $model * @param Database_Expression_Where $condition */ public function down(Model $model, Database_Expression_Where $condition = NULL) { if ( ! isset($this->_columns['position'])) { throw new Kohana_Exception('Unable to move :model up: model has no "position" column!', array(':model' => get_class($this)) ); } $pk = $this->get_pk(); $db = $this->get_db(); // Escape everything $id = $db->quote($model->$pk); $pk = $db->quote_identifier($pk); $pos = $db->quote_identifier('position'); $table = $db->quote_table($this->table_name()); if ($condition !== NULL) { $condition = " AND " . (string) $condition; } else { $condition = ''; } $this->lock(); $db->query(NULL, "SELECT @pos:=NULL, @next_pos:=null, @next_id:=null", FALSE); $db->query(NULL, "SELECT @pos:=$pos FROM $table WHERE ($pk=$id)", FALSE); $db->query(NULL, "SELECT @next_id:=$pk,@next_pos:=$pos FROM $table WHERE ($pos<@pos) $condition ORDER BY $pos DESC LIMIT 1", FALSE); $db->query(NULL, "UPDATE $table SET $pos=@next_pos WHERE (@next_pos IS NOT NULL) AND ($pk=$id)", FALSE); $db->query(NULL, "UPDATE $table SET $pos=@pos WHERE (@next_id IS NOT NULL) AND ($pk=@next_id)", FALSE); $this->unlock(); } /** * Return maximum value of field $field * @param string $field */ public function max($field) { if ( ! isset($this->_columns[$field])) { throw new Exception('Unable to obtain maximum value for column :field - column not found in :model!', array(':field' => $field, ':model' => get_class($this)) ); } return DB::select(array('MAX("' . $field . '")', 'maximum')) ->from($this->table_name()) ->execute($this->get_db()) ->get('maximum'); } /** * Get maximum value of "position" * * @param Model $model Model is passed to be able to select conditional maximum * @return integer */ public function max_position(Model $model = NULL) { return (int) $this->max('position'); } } <file_sep>/application/classes/html.php <?php defined('SYSPATH') OR die('No direct access allowed.'); /** * HTML helper class. * * @package Eresus * @author <NAME> (<EMAIL>) */ class HTML extends Kohana_HTML { /** * Creates a style sheet link. * * It's also possible to link style sheet under conditional expression for IE. * eg. $ie_condition = 'if lte IE 6' * * @param string file name * @param array default attributes * @param boolean include the index page * @param boolean $ie_condition Wrap in conditional comment for IE * @return string */ public static function style($file, array $attributes = NULL, $index = FALSE, $ie_condition = FALSE) { if ($ie_condition === FALSE) { return parent::style($file, $attributes, $index); } else { return "<!--[$ie_condition]>" . parent::style($file, $attributes, $index) . '<![endif]-->'; } } /** * Creates a script link. * * @param string file name * @param boolean Link external script file or use $file as raw script contents * @param array default attributes * @param boolean include the index page * @return string */ public static function script($file, array $attributes = NULL, $index = FALSE, $raw = FALSE) { // Set the script type $attributes['type'] = 'text/javascript'; if ( ! $raw) { if (strpos($file, '://') === FALSE) { // Add the base URL $file = URL::base($index).$file; } // Set the script link $attributes['src'] = $file; return ' <script'.HTML::attributes($attributes).'></script>'; } else { return ' <script'.HTML::attributes($attributes).'> /* <![CDATA[ */ ' . $file . ' /* ]]> */ </script> '; } } } <file_sep>/modules/shop/catalog/views/backend/products.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($section === NULL || $section->id === NULL) { $section_id = '0'; } else { $section_id = (string) $section->id; } // ----- Set up urls $create_url = URL::to('backend/catalog/products', array('action'=>'create', 'cat_section_id' => $section_id), TRUE); $update_url = URL::to('backend/catalog/products', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/catalog/products', array('action'=>'delete', 'id' => '${id}'), TRUE); $multi_action_uri = URL::uri_to('backend/catalog/products', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Создать</a> </div> <?php // Current section caption if (isset($section) && $section->id !== NULL) { echo '<h3 class="section_caption">' . $section->full_caption . '</h3>'; } ?> <?php // Search form echo $search_form->render(); ?> <?php if ( ! count($products)) // No products return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="products table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'caption' => 'Название', 'active' => 'Акт.', ); echo View_Helper_Admin::table_header($columns, 'cat_porder', 'cat_pdesc'); ?> <th></th> </tr> <?php foreach ($products as $product) : $_delete_url = str_replace('${id}', $product->id, $delete_url); $_update_url = str_replace('${id}', $product->id, $update_url); ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($product->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'caption': echo '<td class="capt' .(empty($product->active) ? ' inactive' : '') . '">' . ' <a href="' . $_update_url . '">' . HTML::chars($product->$field) . ' </a>' . '</td>'; break; case 'active': echo '<td class="c">'; if (!$product->visible) { echo View_Helper_Admin::image('controls/invisible.gif', 'Удален пользователем'); } else { if ( ! empty($product->$field)) { echo View_Helper_Admin::image('controls/on.gif', 'Да'); } else { echo View_Helper_Admin::image('controls/off.gif', 'Нет'); } } echo '</td>'; break; default: echo '<td class="nowrap">'; if (isset($product->$field) && trim($product->$field) !== '') { echo HTML::chars($product[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать событие', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить событие', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; //foreach ($products as $product) ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete'), array('action' => 'multi_link', 'label' => 'Привязать', 'class' => 'button_link'), )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/general/filemanager/config/filemanager.php <?php defined('SYSPATH') or die('No direct script access.'); return array( 'files_root_path' => DOCROOT . 'public/user_data', 'css_root_path' => DOCROOT . 'public/css', 'js_root_path' => DOCROOT . 'public/js', 'templates_root_path' => DOCROOT . 'application/views/layouts', // Content of file with this extensions can be edited 'ext_editable' => array('php', 'css', 'js', 'html'), 'thumbs' => array( 'preview' => array( 'enable' => 1, 'dir_base_name' => '.thumbs', 'width' => 80, 'height' => 80 ), 'popups' => array( 'enable' => 1, 'dir_base_name' => '.popups', 'width' => 0, 'height' => 0 ) ), 'image_resize' => array( 'enable' => 1, 'width' => 300, 'height' => 300, ) ); <file_sep>/modules/general/images/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/images', new Route_Backend( 'images(/<action>(/<id>))(/ot-<owner_type>)(/oid-<owner_id>)(/c-<config>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'owner_type' => '\w++', 'owner_id' => '\d++', 'config' => '\w++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'images', 'action' => 'index', 'id' => NULL, 'owner_type' => '', 'owner_id' => NULL )); } if (APP === 'FRONTEND') { Route::add('frontend/images', new Route_Frontend( 'images(/<action>(/<id>))(/ot-<owner_type>)(/oid-<owner_id>)(/c-<config>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'owner_type' => '\w++', 'owner_id' => '\d++', 'config' => '\w++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'images', 'action' => 'index', 'id' => NULL, 'owner_type' => '', 'owner_id' => NULL )); } <file_sep>/modules/system/widgets/classes/widget.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Ajax widget * * @package Eresus * @author <NAME> (<EMAIL>) */ class Widget extends View { /** * Add necessary javascripts for ajax requests */ public static function add_scripts() { // Depends on jQuery jQuery::add_scripts(); Layout::instance()->add_script("var base_url='" . URL::base() . "';", TRUE); Layout::instance()->add_script(Modules::uri('widgets') . '/public/js/widgets.js'); } /** * The same as @see Widget::widget_with_args, but widget parameters are * function arguments instead of array * * @param string $controller * @param string $widget * @return Widget|View|string */ public static function render_widget($controller, $widget) { $args = func_get_args(); array_shift($args); // controller array_shift($args); // widget return Widget::render_widget_with_args($controller, $widget, $args); } /** * Calls widget_$widget function of the given $controller for the current request * and returns the result * @TODO: [!!] Access control! Access control!! * * @param string $controller * @param string $widget * @return Widget|View|string */ public static function render_widget_with_args($controller, $widget, array $args = NULL) { //$token = Profiler::start('render_widget', $widget); try { $controller = Request::current()->get_controller($controller); $method = 'widget_' . $widget; if (empty($args)) { $output = call_user_func(array($controller, $method)); } else { $output = call_user_func_array(array($controller, $method), $args); } } catch (Exception $e) { if (Kohana::$environment === Kohana::DEVELOPMENT) { throw $e; } $output = 'Произошла ошибка при отрисовке виджета'; } //Profiler::stop($token); return $output; } /** * Switch context (substitute the request's uri with uri from $_GET['context'] parameter) * and return the new request * * @return Request */ public static function switch_context() { if ( ! empty($_GET['context'])) { // context can be uri or url - strip base path & index $uri = $_GET['context']; $uri = parse_url($uri, PHP_URL_PATH); $base_url = parse_url(Kohana::$base_url, PHP_URL_PATH); if (strpos($uri, $base_url) === 0) { $uri = substr($uri, strlen($base_url)); } if (Kohana::$index_file AND strpos($uri, Kohana::$index_file) === 0) { $uri = substr($uri, strlen(Kohana::$index_file)); } // Switch context to given uri $request = new Request($uri); Request::$current = $request; return $request; } else { return Request::current(); } } /** * Widget id * @var string */ public $id; /** * Widget wrapper class * @var string */ public $class; /** * Uri to use to redraw the widget using ajax requests * @var string */ public $ajax_uri; /** * Context uri for this widget (defaults to the uri of current request) * FALSE - do not use context uri * @var string */ public $context_uri; /** * Widget wrapper * @var string */ public $wrapper = '<div id="{{id}}" class="widget {{class}}">{{output}}</div>'; /** * Renders widget content, wrapping it and adding special info if necessary * * @param string $file view filename * @return string */ public function render($file = NULL) { // constuct widget properties $props = ''; if ($this->ajax_uri !== NULL) { // Url that should be used to update the widget $props .= '<div id="' . $this->id . '_url" style="display:none;">' . HTML::chars(URL::site($this->ajax_uri)) . '</div>'; } // Context uri $context_uri = $this->context_uri; if ($context_uri === NULL) { $context_uri = Request::current()->uri; } if ($context_uri !== FALSE) { $props .= '<div id="' . $this->id . '_context_uri" style="display:none;">' . HTML::chars($context_uri) . '</div>'; } $this->props = $props; $output = parent::render($file); if ($this->wrapper === FALSE) return $output; // Wrapping is supposed to be done manually (inluding properties) $output = $props . $output; if ($this->id !== NULL && ! Request::$is_ajax) { $output = str_replace( array('{{id}}', '{{class}}', '{{output}}'), array($this->id, $this->class, $output), $this->wrapper ); } return $output; } /** * Add the output of this widget to the response for specified request * * @param Request $request */ public function to_response(Request $request) { $request->response['widgets'][$this->id] = $this->render(); } }<file_sep>/modules/shop/acl/classes/form/backend/group.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Group extends Form_Backend { /** * Initialize form fields */ public function init() { // HTML class $this->attribute('class', 'w500px lb150px'); $this->layout = 'wide'; // ----- Group name $element = new Form_Element_Input('name', array('label' => 'Имя группы', 'required' => TRUE), array('maxlength' => 31) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Privileges /*$privileges = Auth::instance()->privileges(); $element = new Form_Element_CheckSelect('privileges', $privileges, array('label' => 'Привилегии')); if ($this->model()->system) { // It's impossible to change privileges for a system group $element->disabled = TRUE; } $this->add_component($element); */ // ----- Privileges $fieldset = new Form_Fieldset('privs', array('label' => 'Привилегии')); $this->add_component($fieldset); /*$privileges = Model::fly('Model_Privilege')->find_all_by_site_id(Model_Site::current()->id, array( 'order_by' => 'position', 'desc' => FALSE ));*/ foreach ($this->model()->privileges as $privilege) { $element = new Form_Element_Checkbox( $privilege->name, array('label' => $privilege->caption) ); $fieldset->add_component($element); } // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } } <file_sep>/application/classes/log/file.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Simple file logger * * @package Eresus * @author <NAME> (<EMAIL>) */ class Log_File extends Log { const MODE_READ = 'r'; const MODE_WRITE = 'w'; const MODE_APPEND = 'a'; /** * File path * @var string */ protected $_path; /** * File hanlde * @var resource */ protected $_h; /** * Mode in which the log is opened(write, write and append, read) * @var string */ protected $_mode; /** * Construct file logger * * @param string $path */ public function __construct($path, $mode = self::MODE_WRITE, $flush_limit = 1024) { $this->flush_limit = $flush_limit; $this->_path = $path; $this->_mode = $mode; if ($mode == self::MODE_WRITE) { // Delete previous log file @unlink($path); } } /** * Obtain file handle * * @return resource */ protected function _h() { if ($this->_h === NULL) { $this->_h = fopen($this->_path, $this->_mode); } return $this->_h; } /** * Write pending messages to file */ protected function _write() { if ($this->_mode == self::MODE_READ) throw new Kohana_Exception('Unable to write to the log - it has been opened in the READ mode'); if ( ! empty($this->_messages)) { foreach ($this->_messages as $message) { $text = date('Y-m-d H:i:s') . "\t"; switch ($message['level']) { case self::INFO: $text .= "INFO:\t"; break; case self::WARNING: $text .= "WARNING:\t"; break; case self::ERROR: $text .= "ERROR:\t"; break; case self::FATAL: $text .= "FATAL:\t"; break; } $text .= $message['message']; fputs($this->_h(), $text . PHP_EOL); fputs($this->_h(), PHP_EOL); // use blank line as separator } } } /** * Read all the messages from file * * @return array */ public function read() { if ($this->_mode != self::MODE_READ) throw new Kohana_Exception('Unable to read from the log - it has been opened in the WRITE mode'); $messages = array(); if ( !is_readable($this->_path)) return $messages; do { // Read first line of the log message $line = fgets($this->_h()); if ($line === FALSE) break; // EOF $line = trim($line, " \t\r\n"); if ($line == '') continue; // skip empty lines $line = explode("\t", $line, 3); $time = isset($line[0]) ? $line[0] : ''; $level = isset($line[1]) ? $line[1] : ''; $message = isset($line[2]) ? $line[2] : ''; switch ($level) { case 'WARNING:': $level = Log::WARNING; break; case 'ERROR:': $level = Log::ERROR; break; case 'FATAL:': $level = Log::FATAL; break; default: $level = Log::INFO; } // Read other possible lines of the log message while ($line = trim(fgets($this->_h()), " \t\r\n")) { $message .= PHP_EOL . $line; } $messages[] = array( 'message' => $message, 'level' => $level, 'time' => $time ); } while ($line !== FALSE); return $messages; } /** * Return number of messages in log for each log level * * @return array */ public function stats() { if ($this->_mode != self::MODE_READ) throw new Kohana_Exception('Unable to get log stats - it has been opened in the WRITE mode'); $stats = array( 0 => 0, // number of all messages in log Log::INFO => 0, Log::WARNING => 0, Log::ERROR => 0, Log::FATAL => 0 ); if ( ! is_readable($this->_path)) return $stats; do { // Read first line of the log message $line = fgets($this->_h()); if ($line === FALSE) break; // EOF $line = trim($line, " \t\r\n"); if ($line == '') continue; // skip empty lines $stats[0]++; $line = explode("\t", $line, 3); $level = isset($line[1]) ? $line[1] : ''; switch ($level) { case 'INFO:': $stats[Log::INFO]++; break; case 'WARNING:': $stats[Log::WARNING]++; break; case 'ERROR:': $stats[Log::ERROR]++; break; case 'FATAL:': $stats[Log::FATAL]++; break; } // Read other possible lines of the log message while ($line = trim(fgets($this->_h()), " \t\r\n")) { } } while ($line !== FALSE); return $stats; } /** * Close file handle */ public function __destruct() { parent::__destruct(); if ($this->_h) { fclose($this->_h); } } }<file_sep>/modules/system/forms/config/form_templates/dldtdd/fieldset.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( 'fieldset' => '<dt></dt> <dd> <fieldset {{attributes}}> <legend>{{label}}</legend> <dl> {{elements}} </dl> </fieldset> </dd> ' );<file_sep>/modules/shop/catalog/views/frontend/forms/telemost.php <div id="<?php echo "requestModal_".$form->get_element('product_alias')->value?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <?php if ($form->has_element('price')) { ?> <h3 id="myModalLabel">Оплатить лицензию на телемост</h3> <?php } else { ?> <h3 id="myModalLabel">Добавить заявку на телемост</h3> <?php } ?> <!--<small>Cityname, hh:mm, dd.mm.yyy</small>--> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <div class="row-fluid"> <div class="span6"> <label for="place"><?php echo $form->get_element('place_id')->render_input();?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Выберите площадку из предложенных или добавьте новую в список, написав письмо с названием и адресом площадки на адрес <EMAIL>.">?</a> </label> </div> </div> <?php if ($form->has_element('price')) { ?> <div id="qiwiprice"> <label for="price">Стоимость лицензии:&nbsp<?php echo $form->get_element('price')->render_input(); ?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Событие, которое Вы хотите транслировать платное. Вам необходимо оплатить лицензию.">?</a> </label> </div> <?php } ?> <?php if ($form->has_element('telephone')) { ?> <div id="qiwiphone"> <label for="telephone"><?php echo $form->get_element('telephone')->render_input(); ?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Укажите номер телефона пользователя Visa QIWI Wallet, по которому будет выставлен счет. Указывается в международном формате без знака «+».">?</a> </label> </div> <?php } ?> <label for="info"><?php echo $form->get_element('info')->render_input(); ?> &nbsp;<a class="help-pop" href="#" title="" data-placement="bottom" data-original-title="Тут можно написать о локальном событии, которое будет до или после трансляции (например, дискуссия с приглашённым экспертом, дебаты или просмотр фильма), или о чём-то другом.">?</a> </label> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_request')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div> <file_sep>/modules/shop/area/classes/form/backend/town.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Town extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class // User is being created or updated? $creating = ((int)$this->model()->id == 0) ? TRUE : FALSE; $this->attribute('class', "lb150px"); $this->layout = 'wide'; // ----- General tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $tab->add_component($cols); // ----- Personal data $fieldset = new Form_Fieldset('personal_data', array('label' => 'Общие данные')); $cols->add_component($fieldset); // ----- Name $element = new Form_Element_Input('name', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $fieldset->add_component($element, 1); // ----- Phonecode $element = new Form_Element_Input('phonecode', array('label' => 'Телефонный код', 'required' => TRUE), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $fieldset->add_component($element, 1); // ----- Timezone $options = Model_Town::$_timezone_options; $element = new Form_Element_Select('timezone', $options, array('label' => 'Временная зона','required' => TRUE),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element, 1); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/shop/discounts/classes/controller/backend/coupons.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Coupons extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Coupon'; $this->_form = 'Form_Backend_Coupon'; return array( 'create' => array( 'view_caption' => 'Создание купона' ), 'update' => array( 'view_caption' => 'Редактирование купона' ), 'delete' => array( 'view_caption' => 'Удаление купона', 'message' => 'Действительно удалить купон?' ) ); } /** * Prepare layout * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_script(Modules::uri('discounts') . '/public/js/backend/coupon.js'); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Index action - renders the list of sites */ public function action_index() { $this->request->response = $this->render_layout($this->widget_coupons()); } /** * Prepare model for action * * @param string $action * @param string|Model_Coupon $model * @param array $params * @return Model_Coupon */ public function _model($action, $model, array $params = NULL) { $model = parent::_model($action, $model, $params); // User can be changed via url parameter $user_id = $this->request->param('user_id', NULL); if ($user_id !== NULL) { $user_id = (int) $user_id; if ( ($user_id == 0) || ($user_id > 0 && Model::fly('Model_User')->exists_by_id($user_id)) ) { $model->user_id = $user_id; } } return $model; } /** * Renders list of coupons * * @return string */ public function widget_coupons() { $coupon = Model::fly('Model_Coupon'); $order_by = $this->request->param('coupons_order', 'id'); $desc = (bool) $this->request->param('coupons_desc', '1'); // Select all coupons $coupons = $coupon->find_all(array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/coupons'); $view->order_by = $order_by; $view->desc = $desc; $view->coupons = $coupons; return $view->render(); } }<file_sep>/modules/general/tinymce/classes/tinymce.php <?php defined('SYSPATH') or die('No direct script access.'); class TinyMCE { /** * @var boolean */ protected static $_scripts_added = FALSE; /** * Add TinyMCE scripts to the layout */ public static function add_scripts() { if (self::$_scripts_added) return; $layout = Layout::instance(); // TinyMCE configuration script $layout->add_script(Modules::uri('tinymce') . '/public/js/tiny_mce_config.js'); // Set up config options $layout->add_script(" tinyMCE_config.document_base_url = '" . URL::site() . "'; tinyMCE_config.editor_selector = /content/; tinyMCE_config.content_css = '" . URL::base() . 'public/css/' . Kohana::config('tinymce.css') . "'; tinyMCE_config.body_id = 'Content'; tinyMCE_config.body_class = 'content'; ", TRUE); // Set up filemanager for tinyMCE if (Modules::registered('filemanager')) { $layout->add_script(Modules::uri('filemanager') . '/public/js/tiny_mce/filemanager_init.js'); $layout->add_script(" tinyMCE_config.filemanager_url = '" . URL::to('backend/filemanager', array('fm_tinymce' => '1', 'fm_style' => 'thumbs')) . "'; ", TRUE); } // Load TinyMCE $layout->add_script(Modules::uri('tinymce') . '/public/js/tiny_mce/tiny_mce.js'); $layout->add_script(" tinyMCE.init(tinyMCE_config); ", TRUE); self::$_scripts_added = TRUE; } }<file_sep>/modules/system/forms/config/form_templates/dldtdd/fieldset_buttons.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( 'fieldset' => ' <dt></dt> <dd class="buttons"> {{elements}} </dd> ' );<file_sep>/modules/system/forms/classes/form/validator/callback.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Use custom callback for validation * * @package Eresus * @author <NAME> (<EMAIL>) */ class Validator_Callback extends Validator { const INVALID = 'INVALID'; protected $_messages = array( self::INVALID => 'Validation failed', ); /** * Name of function or array(object,method) to use as callback * @var callback */ protected $_callback; /** * Additional arguments for callback * @var array */ protected $_args; /** * Creates validator * * Callback may be specified as string name of function or * as array(object, method) when method is used as callback * @link http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback * * Callback is supposed to have following arguments: * function my_validate_callback($value, $context = NULL, .. additional args go here ..); * * You can supply additional arguments in $args array * * @param callback $callback Callback * @param array $args Additional arguments for callback * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure */ public function __construct($callback, array $args = NULL, array $messages = NULL, $breaks_chain = TRUE) { parent::__construct($messages, $breaks_chain); // Check that specified callback is valid if (is_array($callback)) { if (count($callback) < 2) { throw new Exception('Invalid callback specified - :callback', array(':callback' => print_r($callback, TRUE)) ); } if ( ! is_object($callback[0]) && ! is_string($callback[0])) { throw new Exception('Invalid object or class specified for callback :object', array(':object' => $callback[0]) ); } if (is_string($callback[0]) && ! class_exists($callback[0])) { throw new Exception('Unknown class specified in callback :class', array(':class' => $callback[0]) ); } } else { $callback = (string)$callback; if ( ! function_exists($callback)) { throw new Exception('Unknown function specified as callback :function', array(':function' => $callback) ); } } $this->_callback = $callback; $this->_args = $args; } /** * Validate: call the callback * * WARNING: context is passed by reference * * @param array $context */ protected function _is_valid(array $context = NULL) { $params = array($this->_value, & $context); $params = array_merge($params, $this->_args); $result = call_user_func_array($this->_callback, $params); if ( ! is_bool($result)) { throw new Exception('Callback :callback has not returned a boolean value!', array(':callback' => (is_array($this->_callback) ? '(' . get_class($this->_callback[0]) . ',' . (string)$this->_callback[1] . ')' : (string)$this->_callback ) ) ); } if ( ! $result) { $this->_error(self::INVALID); return FALSE; } return TRUE; } }<file_sep>/application/classes/model.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Model * * @package Eresus * @author <NAME> (<EMAIL>) */ class Model implements ArrayAccess { /** * Array of created model instances * @var array array(model) */ protected static $_instances; /** * Create an instance for model or return the existing instance * If properties are given then model is initialized with this properties * * @param string $model_class * @param array $properties; * @return Model */ public static function fly($model_class, array $properties = NULL) { $model_class = strtolower($model_class); if ( ! isset(Model::$_instances[$model_class])) { Model::$_instances[$model_class] = new $model_class; } if ($properties !== NULL) { Model::$_instances[$model_class]->init($properties); } return Model::$_instances[$model_class]; } /** * Model properties. * Can be accessed via setters and getters * @var array */ protected $_properties; /** * Save the model at every properties() call to [$_previous] * It can be used to detect changes when model is validated or saved * * Also this may be an array with additional properties, which should be * retrieved from the model being backed up * * @var boolean | array */ public $backup = FALSE; /* * @var array|Model */ protected $_previous = array(); /** * Stores the data mapper for model or the name of class, that should be used for data mapper * @var Model_Mapper | string */ protected $_mapper; /** * Validation errors, warnings & other messages * @var array */ protected $_messages = array(); /** * Creates model instance * * @param array $properties */ public function __construct(array $properties = array()) { $this->init($properties); } // ------------------------------------------------------------------------- // Properties & values // ------------------------------------------------------------------------- /** * Resets model and initializes it with the given properties * * @param array $properties */ public function init(array $properties = array()) { $this->properties($properties); } /** * Model properties setter function - can be used to set model properties * * If corresponding method set_$name() exists (not the double underscore), then set_$name($value) is called. * Otherwise key with name $name is simply set to $value in @see _properties * * @param string $name Name of model property to set * @param <type> $value Value for model property * @return Model_Abstract */ public function __set($name, $value) { $method = 'set_' . strtolower($name); if (method_exists($this, $method)) { $this->$method($value); } else { $this->_properties[$name] = $value; } return $this; } /** * Model property getter function - returns value of property $name. * * If corresponding method get_$name() exists (not the underscore), then get_$name() is returned. * Otherwise returns value of key in @see _properties * * @param string $name Name of model property to get * @return <type> */ public function __get($name) { //$name = strtolower($name); $getter = "get_$name"; $defaulter = "default_$name"; if (method_exists($this, $getter)) { return $this->$getter(); } elseif (isset($this->_properties[$name])) { return $this->_properties[$name]; } elseif (empty($this->_properties['id']) && method_exists($this, $defaulter)) { $this->_properties[$name] = $this->$defaulter(); return $this->_properties[$name]; } else { return NULL; } } /** * Check that specified property of model is set * * @param string $name * @return boolean */ public function __isset($name) { return ($this->$name !== NULL); } /** * Set/get model properties using setters/getters * * @param array $values * @return array */ public function values(array $values = NULL) { if ($values !== NULL) { // Set values foreach ($values as $name => $value) { $this->__set($name, $value); } return; } else { // Get values $values = array(); foreach ($this->_properties as $name => $value) { $values[$name] = $this->__get($name); } return $values; } } /** * Sets /gets an array of properties at once, skipping getters and setters. * Used when restoring model from database. * * @param array $properties * @return array */ public function properties(array $properties = NULL) { if ($properties !== NULL) { $this->_properties = $properties; } return $this->_properties; } /** * Back up current model (used when applying new values before creating/updating) */ public function backup() { if ( ! empty($this->backup)) { $this->_previous = $this->properties(); if (is_array($this->backup)) { foreach ($this->backup as $name) { $this->_previous[$name] = $this->$name; } } } } /** * Return the backed up model */ public function previous() { if ( ! ($this->_previous instanceof Model)) { $class = get_class($this); $this->_previous = new $class($this->_previous); } return $this->_previous; } // ------------------------------------------------------------------------- // Validation // ------------------------------------------------------------------------- /** * Is it ok to create new model with the specified values * * @param array $newvalues * @return boolean */ public function validate_create(array $newvalues) { return $this->validate($newvalues); } /** * Is it ok to update model with the specified values * * @param array $newvalues * @return boolean */ public function validate_update(array $newvalues) { return $this->validate($newvalues); } /** * Generic validation (used to validate creation and updating by default) * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { return TRUE; } /** * Is it ok to delete a model? * * @param $newvalues Additional values * @return boolean */ public function validate_delete(array $newvalues = NULL) { return TRUE; } // ------------------------------------------------------------------------- // Errors & messages // ------------------------------------------------------------------------- /** * Add a message (error, warning) to this model * * @param string $text * @param string $field * @param integer $type * @return Model */ public function message($text, $field = NULL, $type = FlashMessages::MESSAGE) { $this->_messages[] = array( 'text' => $text, 'field' => $field, 'type' => $type ); return $this; } /** * Add an error to this model * * @param string $text * @param string $field * @return Model */ public function error($text, $field = NULL) { return $this->message($text, $field, FlashMessages::ERROR); } /** * Get all model errors at once * * @return array */ public function errors() { $errors = array(); foreach ($this->_messages as $message) { if ($message['type'] == FlashMessages::ERROR) { $errors[] = $message; } } return $errors; } /** * Does this model have errors? * * @return boolean */ public function has_errors() { foreach ($this->_messages as $message) { if ($message['type'] == FlashMessages::ERROR) { return TRUE; } } return FALSE; } // ------------------------------------------------------------------------- // Methods // ------------------------------------------------------------------------- /** * Sets/gets data mapper for model * * @param string|Model_Mapper $mapper * @return Model_Mapper */ public function mapper($mapper = NULL) { if ($mapper !== NULL) { // Set mapper $this->_mapper = $mapper; } else { // Get mapper if (is_object($this->_mapper)) { return $this->_mapper; } if ($this->_mapper === NULL) { $mapper_class = get_class($this) . '_Mapper'; } else { $mapper_class = (string) $this->_mapper; } $this->_mapper = Model_Mapper::factory($mapper_class); return $this->_mapper; } } /** * Default params for find_all_by_...() functions * Is called from mapper * * @return array */ public function params_for_find_all() { return NULL; } /** * Proxy method calls to mapper with model instance prepended to the arguments * * @param string $name * @param array $arguments * @return mixed */ public function __call($name, array $arguments) { $mapper = $this->mapper(); // Prepend model to method arguments array_unshift($arguments, $this); // Call the mapper method with the same name return call_user_func_array(array($mapper, $name), $arguments); } /** * Save the model * [!] Do not remove! PHP 5.2 doesn't use __call magic for parent:: methods * * @param boolean $force_create Force creation of model even if model id is specified * @return integer */ public function save($force_create = FALSE) { return $this->mapper()->save($this, $force_create); } /** * Force the creation of model * Usefull if it's necessary to specify id / primary key manually for a new model * * @return integer */ public function create() { return $this->save(TRUE); } /** * Delete the model * [!] Do not remove! PHP 5.2 doesn't use __call magic for parent:: methods */ public function delete() { return $this->mapper()->delete($this); } // ------------------------------------------------------------------------- // ArrayAccess // ------------------------------------------------------------------------- function offsetExists($name) { return ($this->$name !== NULL); } function offsetGet($name) { return $this->$name; } function offsetSet($name, $value) { $this->$name = $value; } function offsetUnset($name) { unset($this->_properties[$name]); } }<file_sep>/application/classes/model/mapper/resource.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Represents a hierarchical structure in database table using nested sets * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Model_Mapper_Resource extends Model_Mapper { /** * Find model by condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Model|array */ public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } $resource_table = Model_Mapper::factory('Model_Resource_Mapper')->table_name(); $pk = $this->get_pk(); $query->select( array(DB::expr("resourceauthor.user_id"),"user_id"), array(DB::expr('CONVERT(GROUP_CONCAT(DISTINCT resourcereader_user_id.user_id),CHAR(8))'), 'access_users'), array(DB::expr('CONVERT(GROUP_CONCAT(DISTINCT resourcereader_organizer_id.organizer_id),CHAR(8))'), 'access_organizers'), array(DB::expr('CONVERT(GROUP_CONCAT(DISTINCT resourcereader_town_id.town_id),CHAR(8))'), 'access_towns') ); $model_class = get_class($model); $query->join(array($resource_table,"resourceauthor"), 'LEFT') ->on(DB::expr("resourceauthor.resource_id"), '=', "$table.id") ->on(DB::expr("resourceauthor.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourceauthor.mode"), '=', DB::expr((int)Model_Res::MODE_AUTHOR)); $query->join(array($resource_table,"resourcereader_user_id"), 'LEFT') ->on(DB::expr("resourcereader_user_id.resource_id"), '=', "$table.id") ->on(DB::expr("resourcereader_user_id.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourcereader_user_id.mode"), '=', DB::expr((int)Model_Res::MODE_READER)); $query->join(array($resource_table,"resourcereader_organizer_id"), 'LEFT') ->on(DB::expr("resourcereader_organizer_id.resource_id"), '=', "$table.id") ->on(DB::expr("resourcereader_organizer_id.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourcereader_organizer_id.mode"), '=', DB::expr((int)Model_Res::MODE_READER)); $query->join(array($resource_table,"resourcereader_town_id"), 'LEFT') ->on(DB::expr("resourcereader_town_id.resource_id"), '=', "$table.id") ->on(DB::expr("resourcereader_town_id.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourcereader_town_id.mode"), '=', DB::expr((int)Model_Res::MODE_READER)); if ( ! empty($params['owner'])) { $user = $params['owner']; $query->where(DB::expr("resourceauthor.user_id"), '=', $user->id); } if ( ! empty($params['for'])) { $user = $params['for']; $query->where(DB::expr("resourceauthor.user_id"), '=', $user->id) ->or_where(DB::expr("resourceauthor.organizer_id"), '=', $user->organizer_id) ->or_where(DB::expr("resourceauthor.town_id"), '=', $user->town_id); } $result = $this->select_row($condition, $params, $query); if (! empty($params['owner']) && $result['user_id'] === NULL) { // FIXME (I don't know) $result = array(); } // Return the result of the desired type if (empty($params['as_array'])) { if ( ! empty($result)) { $model->properties($result); } else { $model->init(); } return $model; } return $result; } /** * Find model by primary key * * @param Model $model * @param mixed $pk_value * @param array $params * @return Model */ public function find(Model $model, $pk_value, array $params = NULL) { return $this->find_by($model, array($this->get_pk() => $pk_value), $params); } public function find_another_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $pk = $this->get_pk(); if ($model->$pk !== NULL) { $condition = $this->_prepare_condition($condition); $condition->and_where($pk, '!=', $model->$pk); } return $this->find_by($model, $condition, $params, $query); } /** * Find all models by criteria and return them in {@link Models} container * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { if ($params === NULL) { $params = $model->params_for_find_all(); } if ( ! empty($params['batch'])) { // Batch find $params['offset'] = $this->_batch_offset; $params['limit'] = $params['batch']; } if ( ! isset($params['key'])) { $params['key'] = $this->get_pk(); } // ----- cache if ($this->cache_find_all) { $condition = $this->_prepare_condition($condition); $hash = $this->params_hash($params, $condition); if (isset($this->_cache[$hash])) { // Cache hit! return $this->_cache[$hash]; } } // ----- role_id, role_type $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } $resource_table = Model_Mapper::factory('Model_Resource_Mapper')->table_name(); $pk = $this->get_pk(); $query->select( array(DB::expr("resourceauthor.user_id"),"user_id"), array(DB::expr('CONVERT(GROUP_CONCAT(DISTINCT resourcereader_user_id.user_id),CHAR(8))'), 'access_users'), array(DB::expr('CONVERT(GROUP_CONCAT(DISTINCT resourcereader_organizer_id.organizer_id),CHAR(8))'), 'access_organizers'), array(DB::expr('CONVERT(GROUP_CONCAT(DISTINCT resourcereader_town_id.town_id),CHAR(8))'), 'access_towns') ); $model_class = get_class($model); $query->join(array($resource_table,"resourceauthor"), 'LEFT') ->on(DB::expr("resourceauthor.resource_id"), '=', "$table.id") ->on(DB::expr("resourceauthor.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourceauthor.mode"), '=', DB::expr((int)Model_Res::MODE_AUTHOR)); $query->join(array($resource_table,"resourcereader_user_id"), 'LEFT') ->on(DB::expr("resourcereader_user_id.resource_id"), '=', "$table.id") ->on(DB::expr("resourcereader_user_id.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourcereader_user_id.mode"), '=', DB::expr((int)Model_Res::MODE_READER)); $query->join(array($resource_table,"resourcereader_organizer_id"), 'LEFT') ->on(DB::expr("resourcereader_organizer_id.resource_id"), '=', "$table.id") ->on(DB::expr("resourcereader_organizer_id.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourcereader_organizer_id.mode"), '=', DB::expr((int)Model_Res::MODE_READER)); $query->join(array($resource_table,"resourcereader_town_id"), 'LEFT') ->on(DB::expr("resourcereader_town_id.resource_id"), '=', "$table.id") ->on(DB::expr("resourcereader_town_id.resource_type"), '=', DB::expr($this->get_db()->quote($model_class))) ->on(DB::expr("resourcereader_town_id.mode"), '=', DB::expr((int)Model_Res::MODE_READER)); if ( ! empty($params['owner'])) { $user = $params['owner']; $query->where(DB::expr("resourceauthor.user_id"), '=', $user->id); } if ( ! empty($params['for'])) { $user = $params['for']; $query->where(DB::expr("resourceauthor.user_id"), '=', $user->id) ->or_where(DB::expr("resourceauthor.organizer_id"), '=', $user->organizer_id) ->or_where(DB::expr("resourceauthor.town_id"), '=', $user->town_id); } $query->group_by("$table.$pk"); $result = $this->select($condition, $params, $query); if ( ! empty($params['batch'])) { // Batch find if ( ! empty($result)) { $this->_batch_offset += count($result); } else { // Reset $this->_batch_offset = 0; } } // Return the result of the desired type if (empty($params['as_array'])) { $key = isset($params['key']) ? $params['key'] : FALSE; $result = new Models(get_class($model), $result, $key); } // ----- cache if ($this->cache_find_all) { if (count($this->_cache) < $this->cache_limit) { $this->_cache[$hash] = $result; } } return $result; } /** * Find all models * * @param Model $model * @param array $params * @return Models */ public function find_all(Model $model, array $params = NULL) { return $this->find_all_by($model, NULL, $params); } public function find_another_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $pk = $this->get_pk(); if ($model->$pk !== NULL) { $condition = $this->_prepare_condition($condition); $condition->and_where($pk, '!=', $model->$pk); } return $this->find_all_by($model, $condition, $params, $query); } public function count_by(Model $model, $condition = NULL) { if (isset($condition['owner'])) { $pk = $this->get_pk(); $cond['user_id'] = $condition['owner']; $cond[Model_Res::RESOURCE_TYPE] = get_class($model); $cond['mode'] = Model_Res::MODE_AUTHOR; if ($model->$pk !==NULL) { $cond[Model_Res::RESOURCE_ID] = $model->$pk; } unset($condition['owner']); $resource_mapper = Model_Mapper::factory('Model_Resource_Mapper'); return $resource_mapper->count_by($model,$cond); } return parent::count_by($model, $condition); } /** * Returns hash for select parameters (useful when caching results of a select) * * @param array $params * @param Database_Expression_Where $condition * @return string */ public function params_hash(array $params = NULL, Database_Expression_Where $condition = NULL) { if (empty($params['desc'])) { $params['desc'] = FALSE; } if (empty($params['offset'])) { $params['offset'] = 0; } if (empty($params['limit'])) { $params['limit'] = 0; } if ($condition !== NULL) { $params['condition'] = (string) $condition; } $str = ''; foreach ($params as $k => $v) { if ($k=='owner') $v = $v->id; if (is_array($v)) { foreach ($v as $vs) { $str .= $k . $vs; } } else { $str .= $k . $v; } } return substr(md5($str), 0, 16); } }<file_sep>/modules/system/forms/classes/form/element.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Abstract form element * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Form_Element extends FormComponent { /** * Value * @var mixed */ protected $_value; /** * Default value * @var mixed */ protected $_default_value; /** * Validators for element * @var array of Validator */ protected $_validators = array(); /** * Filters for element * @var array of Filter */ protected $_filters = array(); // ------------------------------------------------------------------------- // Parent-child relationships // ------------------------------------------------------------------------- /** * Set/get form for this element * * @param Form $form * @return Form */ public function form(Form $form = NULL) { if ($form !== NULL) { $form->add_element($this); } return parent::form($form); } // ------------------------------------------------------------------------- // Properties & attributes // ------------------------------------------------------------------------- /** * Full name of the element - $form_name[$element_name] - to place in html code * * @return string */ public function default_full_name() { $parts = explode('[', $this->name, 2); $full_name = $this->form()->name . '[' . $parts[0] . ']'; if (isset($parts[1])) { $full_name .= '[' . $parts[1]; } return $full_name; } /** * Default label for element * * @return string */ public function default_label() { return $this->name; } /** * Default caption for element * * @return string */ public function default_caption() { return $this->label; } /** * Disable/enable component * * @param boolean $disabled * @return FormComponent */ public function set_disabled($disabled) { $this->_properties['disabled'] = $disabled; if ($disabled) { $this->_attributes['disabled'] = 'disabled'; } else { unset($this->_attributes['disabled']); } return $this; } /** * Set autocomplete url for this element * * @param string $autocomplete_url * @return Form_Element */ public function set_autocomplete_url($autocomplete_url) { if ($autocomplete_url === NULL) { unset($this->_attributes['autocomplete']); } else { // Disable native autocomplete $this->_attributes['autocomplete'] = 'off'; } $this->_properties['autocomplete_url'] = $autocomplete_url; return $this; } /** * Set autocomplete chunk for this element * * @param char $autocomplete_chunk * @return Form_Element */ public function set_autocomplete_chunk($autocomplete_chunk) { $this->_properties['autocomplete_chunk'] = $autocomplete_chunk; return $this; } /** * Get HTML class with element statuses (.disabled, .invalid, .valid, ...) * * @return string */ public function get_status_class() { $status_class = ''; // Highlight input if there are errors if ($this->has_errors()) { $status_class .= ' invalid'; } // Add "disabled" class if element is disabled if ($this->disabled) { $status_class .= ' disabled'; } return trim($status_class); } /** * Get element attributes * * @return array */ public function attributes() { $attributes = parent::attributes(); // Append status class $status_class = $this->status_class; if ($status_class != '') { if (isset($attributes['class'])) { $attributes['class'] .= ' ' . $status_class; } else { $attributes['class'] = $status_class; } } return $attributes; } // ------------------------------------------------------------------------- // Values // ------------------------------------------------------------------------- /** * Sets the value for the element using filters * * @param mixed $value * @return Form_Element */ public function set_value_filtered($value) { if ($value === NULL) { $this->_value = FALSE; } else { // Filter value foreach ($this->_filters as $filter) { $value = $filter->filter($value); } $this->_value = $value; } return $this; } /** * Set value from POST data * * @param string $value * @return Form_Element */ public function set_value_from_post($value) { return $this->set_value_filtered($value); } /** * Set value "as-is", without using element filters * * @param mixed $value * @return Form_Element */ public function set_value($value) { if ($value === NULL) { $this->_value = FALSE; } else { $this->_value = $value; } return $this; } /** * Gets element value * * @return mixed */ public function get_value() { if ($this->_value !== NULL) return $this->_value; // Value was not yet set (lazy getting) // Try to get value from POST if ( ! $this->disabled && ! $this->ignored) { $value = $this->form()->get_post_data($this->name); if ($value !== NULL) { $this->set_value_from_post($value); return $this->_value; } } // Try to get value from the form's default source (such as associated model) $value = $this->form()->get_data($this->name); if ($value !== NULL) { $this->set_value($value); return $this->_value; } // Default value $this->set_value($this->default_value); return $this->_value; } /** * Get value to use in this element's validation * * @return mixed */ public function get_value_for_validation() { return $this->get_value(); } /** * Get value to use when rendering the element * * @return mixed */ public function get_value_for_render() { return $this->get_value(); } /** * Set default value (without filters) * * @param mixed $value */ public function set_default_value($value) { $this->_default_value = $value; } /** * Get default value * * @return mixed */ public function get_default_value() { return $this->_default_value; } // ------------------------------------------------------------------------- // Filters and validators // ------------------------------------------------------------------------- /** * Adds filter to this element * * @param Form_Filter $filter * @return Form_Element */ public function add_filter(Form_Filter $filter) { $filter->set_form_element($this); $this->_filters[] = $filter; return $this; } /** * Get form element filters * * @return array array(Form_Filter) */ public function get_filters() { return $this->_filters; } /** * Adds validator to this element * * @param Form_Validator $validator * @return Form_Element */ public function add_validator(Form_Validator $validator) { $validator->set_form_element($this); $this->_validators[] = $validator; return $this; } /** * Gets validator by class * * @param string $class Validator class * @return Validator on success * @return NULL on failure */ public function get_validator($class) { foreach ($this->_validators as $validator) { if (get_class($validator) === $class) { return $validator; } } return NULL; } /** * Get all validators for this element * * @return array array(Validator) */ public function get_validators() { return $this->_validators; } /** * Validates element value. * Executes the chain of elemnt validators * * @param array $context Form data * @return boolean */ public function validate(array $context = NULL) { $result = TRUE; foreach ($this->_validators as $validator) { if ( ! $validator->validate($this->value_for_validation, $context)) { $result = FALSE; $this->errors($validator->get_errors()); if ($validator->breaks_chain()) { break; } } } return $result; } // ------------------------------------------------------------------------- // Templates // ------------------------------------------------------------------------- /** * Get default config entry name for this element * * @return string */ public function default_config_entry() { return substr(strtolower(get_class($this)), strlen('Form_Element_')); } // ------------------------------------------------------------------------- // Rendering // ------------------------------------------------------------------------- /** * Renders the whole element */ public function render() { $template = $this->get_template('element'); // Input Template::replace($template, 'input', $this->render_input()); if (Template::has_macro($template, 'label')) { // Label Template::replace($template, 'label', $this->render_label()); } if (Template::has_macro($template, 'comment')) { // Comment Template::replace($template, 'comment', $this->render_comment()); } if (Template::has_macro($template, 'errors')) { // Errors Template::replace($template, 'errors', $this->render_errors()); } // Prepend Template::replace($template, 'prepend', '<span class="prepend">' . $this->prepend . '</span>'); // Append Template::replace($template, 'append', '<span class="append">' . $this->append . '</span>'); // Element id Template::replace($template, 'id', $this->id); // Status class Template::replace($template, 'status_class', $this->status_class); // Element name Template::replace($template, 'name', $this->name); // Element type Template::replace($template, 'type', $this->type); // Label text Template::replace($template, 'label_text', $this->label); return $template; } /** * Renders input for this element * * @return string */ abstract public function render_input(); /** * Renders label for element * * @return string */ public function render_label() { $attributes = $this->attributes(); $label_attributes['required'] = $this->required; if ( isset($attributes['label_class'])) { $label_attributes['class'] = $attributes['label_class']; } if ($this->label !== NULL) { return Form_Helper::label($this->id, $this->label, $label_attributes); } else { return ''; } } /** * Renders comment for element * * @return string */ public function render_comment() { if ($this->comment !== NULL) { return $this->comment; } else { return ''; } } /** * Renders element errors * * @return string */ public function render_errors() { $html = ''; foreach ($this->errors() as $error) { $html .= '<div>' . HTML::chars($error['text']) . '</div>'; } return $html; } public function render_alone_errors() { $html = ''; foreach ($this->errors() as $error) { $html .= '<div>' . HTML::chars($error['text']) . '</div>'; } return '<div class="errors" id="'.$this->id.'-errors">'.$html.'</div>'; } /** * Render javascript for this element * * @return string */ public function render_js() { $js = "\ne = new jFormElement('" . $this->name . "', '" . $this->id . "');\n"; if ($this->disabled || $this->ignored) { $js .= "e.disabled = true;"; } // Add validators foreach ($this->get_validators() as $validator) { $validator_js = $validator->render_js(); if ($validator_js !== NULL) { $js .= $validator_js . "e.add_validator(v);\n"; } } // Autocomplete if ($this->autocomplete_url) { $js .= "e.autocomplete_url = '" . $this->autocomplete_url . "';\n"; } if ($this->autocomplete_chunk) { $js .= "e.autocomplete_chunk = '" . $this->autocomplete_chunk . "';\n"; } $js .= "f.add_element(e);\n"; return $js; } } <file_sep>/modules/system/tasks/classes/controller/backend/tasks.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Tasks extends Controller_Backend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('tasks') . '/public/css/backend/tasks.css'); switch ($this->request->action) { case 'log': $layout->caption = 'Лог задачи'; break; default: $layout->caption = 'Задачи'; } return $layout; } /** * Render task status */ public function widget_status($task) { jQuery::add_scripts(); Layout::instance() ->add_style(Modules::uri('tasks') . '/public/css/backend/tasks.css') ->add_script(Modules::uri('tasks') . '/public/js/backend/tasks.js'); if (TaskManager::is_running($task)) { $status = 'Выполняется'; $progress = TaskManager::get_value($task, 'progress'); } else { $status = '---'; $progress = 0; } $status_info = TaskManager::get_value($task, 'status_info'); $log_stats = TaskManager::log_stats($task); $widget = new Widget('backend/task_status'); $widget->id = $task . '_status'; $widget->class = 'widget_task'; $widget->ajax_uri = URL::uri_to('backend/tasks', array('task' => $task)); $widget->task = $task; $widget->status = $status; $widget->progress = $progress; $widget->status_info = $status_info; $widget->log_stats = $log_stats; return $widget; } /** * Redraw task status via ajax request */ public function action_ajax_status() { $task = $this->request->param('task'); if ($task != '') { $widget = $this->widget_status($task); $widget->to_response($this->request); } $this->_action_ajax(); } /** * Display task log */ public function action_log() { $task = $this->request->param('task'); if ($task == '') return $this->_action_error ('Некорректное имя задачи'); $view = new View('backend/task_log'); $view->messages = TaskManager::log_messages($task); $this->request->response = $this->render_layout($view); } }<file_sep>/modules/shop/area/classes/form/frontend/selecttown.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_SelectTown extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/forms/selecttown'; // ----- town $towns = Model_Town::towns(); $element = new Form_Element_Select('name', $towns, array('label' => '','layout'=>'wide') ); $this->add_component($element); $button = new Form_Frontend_Element_Submit('submit', array('label' => 'Выбрать'), array('class' => 'button_select') ); $this->add_component($button); } } <file_sep>/modules/general/news/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { Route::add('frontend/news', new Route_Frontend( 'news' . '(/<year>)(/<month>)' . '(/<action>(/<id>))' . '(/p-<page>)', array( 'action' => '\w++', 'id' => '\d++', 'year' => '\d++', 'month' => '\d++', 'page' => '\d++', 'news_order' => '\w++', 'news_desc' => '[01]', 'history' => '.++' ))) ->defaults(array( 'controller' => 'news', 'action' => 'index', 'id' => NULL, 'year' => 0, 'month' => 0, 'page' => 0, 'news_order' => 'date', 'news_desc' => '1' )); } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/news', new Route_Backend( 'news(/<action>(/<id>))' . '(/p-<page>)(/order-<news_order>)(/desc-<news_desc>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'page' => '\d++', 'news_order' => '\w++', 'news_desc' => '[01]', 'history' => '.++' ))) ->defaults(array( 'controller' => 'news', 'action' => 'index', 'id' => NULL, 'page' => 0, 'news_order' => 'date', 'news_desc' => '1' )); // ----- Add backend menu items Model_Backend_Menu::add_item(array( 'menu' => 'main', 'caption' => 'Новости', 'route' => 'backend/news', 'icon' => 'news' )); } /****************************************************************************** * Common ******************************************************************************/ // ----- Add node types Model_Node::add_node_type('news', array( 'name' => 'Новости', 'backend_route' => 'backend/news', 'frontend_route' => 'frontend/news', ));<file_sep>/modules/shop/catalog/classes/controller/backend/sections.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Sections extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Section'; $this->_form = 'Form_Backend_Section'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание раздела' ), 'update' => array( 'view_caption' => 'Редактирование раздела ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление раздела', 'message' => 'Удалить раздел ":caption" и все события, для которых он является основным?' ), 'multi_delete' => array( 'view_caption' => 'Удаление разделов', 'message' => 'Удалить выбранные разделы и события, для которых они являются основными?', 'message_empty' => 'Выберите хотя бы один раздел!' ) ); } /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('catalog') . '/public/css/backend/catalog.css'); // Add catalog js scripts if ($this->request->action == 'index') { $layout->add_script(Modules::uri('catalog') . '/public/js/backend/catalog.js'); $layout->add_script( "var branch_toggle_url = '" . URL::to('backend/catalog/sections', array( 'action' => 'toggle', 'id' => '{{id}}', 'toggle' => '{{toggle}}') ) . '?context=' . $this->request->uri . "';" , TRUE); } if ($this->request->action == 'select') { // Add sections select js scripts $layout->add_script(Modules::uri('catalog') . '/public/js/backend/sections_select.js'); } return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Render a list of sections */ public function action_index() { $this->request->response = $this->render_layout($this->widget_sections()); } /** * Create new section * * @param string|Model $model * @param array $params * @return Model_Section */ protected function _model_create($model, array $params = NULL) { if (Model_Site::current()->id === NULL) { throw new Controller_BackendCRUD_Exception('Выберите магазин перед созданием раздела!'); } $sectiongroup_id = (int) $this->request->param('cat_sectiongroup_id'); if ( ! Model::fly('Model_SectionGroup')->exists_by_id_and_site_id($sectiongroup_id, Model_Site::current()->id)) { throw new Controller_BackendCRUD_Exception('Указана не существуюущая группа категорий!'); } // New section in current section $section = new Model_Section(); $section->parent_id = (int) $this->request->param('cat_section_id'); // and for current section group $section->sectiongroup_id = $sectiongroup_id; return $section; } /** * Delete section */ protected function _execute_delete(Model $section, Form $form, array $params = NULL) { list($hist_route, $hist_params) = URL::match(URL::uri_back()); // Id of selected section $section_id = isset($hist_params['cat_section_id']) ? (int) $hist_params['cat_section_id'] : 0; if ($section->id === $section_id || $section->is_parent_of($section_id)) { // If current selected section or its parent is deleted - redirect back to root unset($hist_params['cat_section_id']); $params['redirect_uri'] = URL::uri_to($hist_route, $hist_params); } parent::_execute_delete($section, $form, $params); } /** * Delete multiple models * * @param array $models array(Model) * @param Form $form * @param array $params */ protected function _execute_multi_delete(array $models, Form $form, array $params = NULL) { $result = TRUE; foreach ($models as $model) { // We have to double-reload models, because the structure of the whole table is modified // after deletion and we need correct values for 'lft' and 'rgt' fields before calling ->delete() // Also, this model may already be deleted from db because its' parent was deleted earlier $model->find($model->id); if (isset($model->id)) { $model->delete(); } // Deleting failed if ($model->has_errors()) { $form->errors($model->errors()); $result = FALSE; } } if ( ! $result) return; // Deleting of at least one model failed... $this->_after_execute('multi_delete', $model, $form, $params); $this->request->redirect($this->_redirect_uri('multi_delete', $model, $form, $params)); } /** * Select several sections */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор разделов на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_select(); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_select()); } } /** * Renders list of sections * * @param integer $select * @return string */ public function widget_sections() { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите магазин!'); } $sectiongroup = Model_SectionGroup::current(); $section = Model_Section::current(); // ----- Render section for current section group $order_by = $this->request->param('cat_sorder', 'lft'); $desc = (bool) $this->request->param('cat_sdesc', '0'); // Obtain information about which sections are expanded from session // The returned array is an array of id's of unfolded sections $unfolded = Session::instance()->get('sections', array()); // Select only sections that are visible (i.e. their parents are unfolded) $sections = $section->find_all_unfolded($sectiongroup->id, NULL, $unfolded, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'active', 'section_active'), 'order_by' => $order_by, 'desc' => $desc, 'as_tree' => true )); /* // Load the whole sections tree $sections = $section->find_all_by_sectiongroup_id($sectiongroup->id, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'active', 'section_active'), 'order_by' => $order_by, 'desc' => $desc, 'as_tree' => true )); */ $view = new View('backend/sections/list'); $view->order_by = $order_by; $view->desc = $desc; $view->sectiongroup_id = $sectiongroup->id; $view->section_id = $section->id; $view->unfolded = $unfolded; $view->sections = $sections; $view->sectiongroups = $sectiongroup->find_all_by_site_id($site_id); return $view->render(); } /** * Render list of section to select several section for current section group * * @param integer $select * @return string */ public function widget_select($select = FALSE) { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите магазин!'); } $sectiongroup = Model_SectionGroup::current(); $section = Model_Section::current(); // ----- Render section for current section group $order_by = $this->request->param('cat_sorder', 'lft'); $desc = (bool) $this->request->param('cat_sdesc', '0'); $sections = $section->find_all_by_sectiongroup_id($sectiongroup->id, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'active', 'section_active'), 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/sections/select'); $view->order_by = $order_by; $view->desc = $desc; $view->sectiongroup_id = $sectiongroup->id; $view->section_id = $section->id; $view->sections = $sections; return $view->render(); } /** * Renders sections menu * * @return string */ public function widget_sections_menu() { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите магазин!'); } $sectiongroup = Model_SectionGroup::current(); $section = Model_Section::current(); // ----- Render section for current section group $order_by = $this->request->param('cat_sorder', 'lft'); $desc = (bool) $this->request->param('cat_sdesc', '0'); // Obtain information about which sections are expanded from session // The returned array is an array of id's of unfolded sections $unfolded = Session::instance()->get('sections', array()); // Select only sections that are visible (i.e. their parents are unfolded) $sections = $section->find_all_unfolded($sectiongroup->id, NULL, $unfolded, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'active', 'section_active'), 'order_by' => $order_by, 'desc' => $desc, 'as_tree' => true )); $view = new View('backend/sections/menu'); $view->order_by = $order_by; $view->desc = $desc; $view->sectiongroup_id = $sectiongroup->id; $view->section_id = $section->id; $view->unfolded = $unfolded; $view->sectiongroups = $sectiongroup->find_all_by_site_id($site_id); $view->sections = $sections; return $view->render(); } /** * Save sections branch visibility (folded or not?) in session * * Executed either via ajax or normally */ public function action_toggle() { $branch_id = (int) $this->request->param('id'); $toggle = $this->request->param('toggle', ''); $section = new Model_Section; $section->find($branch_id); if ($toggle != '' && $section->id !== NULL) { $unfolded = Session::instance()->get('sections', array()); if ($toggle == 'on' && ! in_array($branch_id, $unfolded)) { // Unfold the branch - add section id to the list of unfolded sections $unfolded[] = $branch_id; } else { // Fold the branch - remove section id from the list of unfolded sections $k = array_search($branch_id, $unfolded); if ($k !== FALSE) { unset($unfolded[$k]); } } Session::instance()->set('sections', $unfolded); if (Request::$is_ajax && $toggle == 'on') { // Render branch of sections if ( ! empty($_GET['context'])) { // Switch request context (render as if a controller is accessed via url = $context) $context = $_GET['context']; $request = new Request($context); Request::$current = $request; $controller = $request->get_controller('sections'); $this->request->response = $controller->widget_sections_branch($section); } else { // Render in current context $this->request->response = $this->widget_sections_branch($section); } } } if ( ! Request::$is_ajax) { $this->request->redirect(URL::uri_back()); } } /** * Render a branch of sections (used to redraw tree via ajax requests) * * @param Model_Section $parent */ public function widget_sections_branch(Model_Section $parent) { $site_id = (int) Model_Site::current()->id; $order_by = $this->request->param('cat_sorder', 'lft'); $desc = (bool) $this->request->param('cat_sdesc', '0'); // @TODO: //$section_id = (int) $this->request->param('cat_section_id'); // Obtain information about which sections are expanded from session // The returned array is an array of id's of unfolded sections $unfolded = Session::instance()->get('sections', array()); // Select only sections that are visible (i.e. their parents are unfolded) $sections = $parent->find_all_unfolded(NULL, $parent, $unfolded, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption', 'active', 'section_active'), 'order_by' => $order_by, 'desc' => $desc, 'as_tree' => TRUE )); // Set up view if ($this->request->controller == 'products') { $view_script = 'backend/sections/menu_ajax'; } else { $view_script = 'backend/sections/list_ajax'; } $view = new View($view_script); $view->order_by = $order_by; $view->desc = $desc; // @TODO: //$view->section_id = $section_id; $view->parent = $parent; $view->unfolded = $unfolded; $view->sections = $sections; return $view->render(); } } <file_sep>/modules/system/forms/classes/form/element/radioselect.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form select element consisting of radios * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_RadioSelect extends Form_Element { /** * Select options * @var array */ protected $_options = array(); /** * Creates form select element * * @param string $name Element name * @param array $options Select options * @param array $properties * @param array $attributes */ public function __construct($name, array $options = NULL, array $properties = NULL, array $attributes = NULL) { parent::__construct($name, $properties, $attributes); $this->_options = $options; } /** * Set up options for select * * @param array $options * @return Form_Element_Select */ public function set_options(array $options) { $this->_options = $options; return $this; } /** * @return string */ public function get_type() { return 'radioselect'; } /** * Use the same templates as checkselect element * * @return string */ public function default_config_entry() { return 'checkselect'; } /** * Renders select element, constiting of checkboxes * * @return string */ public function render_input() { $value = $this->value; $html = ''; foreach ($this->_options as $option => $label) { $name = "$this->full_name"; if ($value == $option) { $checked = TRUE; } else { $checked = FALSE; } $option_template = $this->get_template('option'); if ( ! $this->disabled) { $checkbox = Form_Helper::radio($name, $option, $checked, array('class' => 'checkbox')); } else { $checkbox = Form_Helper::radio($name, $option, $checked, array('class' => 'checkbox', 'disabled' => 'disabled')); } Template::replace($option_template, array( 'checkbox' => $checkbox, 'label' => $label )); $html .= $option_template; } return $html; } /** * No javascript for this element * * @return string */ public function render_js() { return FALSE; } } <file_sep>/modules/shop/orders/public/js/frontend/orders.js $(function(){ /** * Add products to cart via ajax */ $('form.to_cart').submit(function(event){ // Display "loading" $(event.target).addClass('adding'); // Peform an ajax request in current context // Use standart callback to render the result $.get(event.target.action + '?context=' + widgets_context_uri, null, widgets_callback); event.stopPropagation(); event.preventDefault(); }) })<file_sep>/modules/shop/catalog/config/images.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // proportion 7:5 - strictly!!! // Thumbnail sizes for product image 'product' => array( array('width' => 0, 'height' => 0), array('width' => 400, 'height' => 300), array('width' => 498, 'height' => 338), array('width' => 150, 'height' => 100) ), // Thumbnail sizes for section image 'section' => array( array('width' => 100, 'height' => 90) ) );<file_sep>/modules/shop/catalog/classes/model/sectiongroup.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_SectionGroup extends Model { /** * Get selected section group for the specified request using the value of * corresponding parameter ("cat_sectiongroup_id") in the uri * * @param Request $request (if NULL, current request will be used) * @return Model_SectionGroup */ public static function current(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } $site_id = (int) Model_Site::current()->id; // check cache $sectiongroup = $request->get_value('sectiongroup'); if ($sectiongroup !== NULL) return $sectiongroup; $sectiongroup = new Model_SectionGroup(); if (APP == 'BACKEND') { $id = (int) $request->param('cat_sectiongroup_id'); if ($id > 0) { // id of section group is explicitly specified in the uri $sectiongroup->find_by_id_and_site_id($id, $site_id); } else { if (Model_Section::current()->id !== NULL) { // Find sectiongroup by current section $id = Model_Section::current()->sectiongroup_id; $sectiongroup->find_by_id_and_site_id($id, $site_id); } else { // By default, simply select the first sectiongroup available $sectiongroup->find_by_site_id($site_id); } } } ////SROCHNO /*elseif (APP == 'FRONTEND') { $current_group_id = Auth::instance()->get_user()->group_id; switch ($current_group_id) { case Model_Group::SHOWMAN_GROUP_ID: $section_group_type = self::TYPE_ANNOUNCE; break; case Model_Group::EDITOR_GROUP_ID: $section_group_type = self::TYPE_ANNOUNCE; break; default: $section_group_type = self::TYPE_EVENT; break; } $sectiongroup_name = $request->param('sectiongroup_name'); if ($sectiongroup_name != '') { $sectiongroup->find_by_name($sectiongroup_name); } else { $sectiongroup_id = $request->param('sectiongroup_id'); if ($sectiongroup_id != '') { $sectiongroup->find($sectiongroup_id); } else { // By default, simply select the first sectiongroup available $sectiongroup->find_by_type($section_group_type); } } }*/ // save in cache $request->set_value('sectiongroup', $sectiongroup); return $sectiongroup; } /** * Get list of all section groups for current site (cached) * * @return Models */ public function find_all_cached() { static $cache; if ($cache == NULL) { $cache = $this->find_all_by_site_id(Model_Site::current()->id); } return $cache; } /** * Get frontend uri to the section group */ public function uri_frontend() { static $uri_template; if ($uri_template === NULL) { $uri_template = URL::to('frontend/catalog/sections', array( 'sectiongroup_name' => '{{sectiongroup_name}}' )); } return str_replace( '{{sectiongroup_name}}', $this->name, $uri_template ); } /** * Validate creation/updation of sectiongroup * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { // Check that sectiongroup name is unque if ( ! isset($newvalues['name'])) { $this->error('Вы не указали имя!', 'name'); return FALSE; } if ($this->exists_another_by_name($newvalues['name'])) { $this->error('Группа категорий с таким именем уже существует!', 'name'); return FALSE; } return TRUE; } /** * Prohibit deletion of system users * * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->system) { $this->error('Группа категорий "' . HTML::chars($this->caption) . '" является системной. Её удаление запрещено!'); return FALSE; } return TRUE; } /** * User is not system by default * * @return boolean */ public function default_system() { return FALSE; } /** * Set system flag * * @param boolean $system */ public function set_system($system) { // Prohibit setting system property for user } }<file_sep>/modules/shop/catalog/views/backend/plistproducts.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // ----- Set up urls $add_uri = URL::uri_to( 'backend/catalog/plistproducts', array('action' => 'add', 'plist_id' => $plist->id), TRUE ); $products_select_url = URL::to('backend/catalog/products', array('site_id' => $plist->site_id, 'action' => 'products_select', 'history' => $add_uri), TRUE); $update_url = URL::to('backend/catalog/products', array('action' => 'update', 'id' => '{{id}}'), TRUE); $delete_url = URL::to('backend/catalog/plistproducts', array('action'=>'delete', 'id' => '{{id}}'), TRUE); $up_url = URL::to('backend/catalog/plistproducts', array('action'=>'up', 'id' => '{{id}}'), TRUE); $down_url = URL::to('backend/catalog/plistproducts', array('action'=>'down', 'id' => '{{id}}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } $multi_action_uri = URL::uri_to('backend/catalog/plistproducts', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $products_select_url; ?>" class="button button_add">Добавить товары в список</a> </div> <?php if ( ! count($plistproducts)) // No products return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="products table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'caption' => 'Название' ); echo View_Helper_Admin::table_header($columns, 'cat_lporder', 'cat_lpdesc'); ?> <th></th> </tr> <?php foreach ($plistproducts as $plistproduct) : $_delete_url = str_replace('{{id}}', $plistproduct->id, $delete_url); $_update_url = str_replace('{{id}}', $plistproduct->product_id, $update_url); ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($plistproduct->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'caption': echo '<td class="capt' .(empty($plistproduct->active) ? ' inactive' : '') . '">' . ' <a href="' . $_update_url . '">' . HTML::chars($plistproduct->$field) . ' </a>' . '</td>'; break; case 'active': echo '<td class="c">'; if ( ! empty($plistproduct->$field)) { echo View_Helper_Admin::image('controls/on.gif', 'Да'); } else { echo View_Helper_Admin::image('controls/off.gif', 'Нет'); } echo '</td>'; break; default: echo '<td>'; if (isset($plistproduct->$field) && trim($plistproduct->$field) !== '') { echo HTML::chars($plistproduct[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить товар из списка', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить из списка', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/general/cackle/views/cackle/cackle.php <div id="mc-container"></div> <script type="text/javascript"> var mcSite = <?=$cfg['cackle_key'];?>; (function() { var mc = document.createElement('script'); mc.type = 'text/javascript'; mc.async = true; mc.src = '//cackle.me/mc.widget-min.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(mc); })(); </script> <a id="mc-link" href="http://cackle.me">Социальные комментарии <b style="color:#4FA3DA">Cackl</b><b style="color:#F65077">e</b></a><file_sep>/modules/shop/delivery_courier/views/backend/delivery/courier.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="simple_panel"> <?php if (isset($caption)) { echo '<div class="simple_panel_caption">' . $caption . '</div>'; } ?> <table class="content_layout"><tr> <td class="content_layout" style="width: 500px;"> <?php echo $form; ?> </td> <td class="content_layout"> <?php echo $zones; ?> </td> </tr></table> </div><file_sep>/modules/shop/acl/public/js/backend/users_form.js /** * Sections select callback (called from section select iframe) */ function on_users_select(user_ids) { if ( ! on_users_select_url) return; // Peform an ajax request to redraw form "additional sections" elements if (user_ids.length) { user_ids = user_ids.join('_'); } else { // dummy value when no ids are selected user_ids = '_'; } var url = on_users_select_url .replace('{{user_ids}}', user_ids); $('#' + users_fieldset_ids).html('Loading...'); $.get(url, null, function(response){ // Redraw "additional sections" fieldset if (response) { $('#' + users_fieldset_ids).html(response); } }); } <file_sep>/modules/shop/delivery_courier/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/courierzones', new Route_Backend( 'courierzones(/<action>(/<id>)(/ids-<ids>)(/delivery-<delivery_id>))' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'delivery_id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'courierzones', 'action' => 'index', 'id' => NULL, 'ids' => '', 'delivery_id' => NULL )); } /****************************************************************************** * Common ******************************************************************************/ // Register this delivery module Model_Delivery::register(array( 'module' => 'courier', 'caption' => 'Доставка курьером' ));<file_sep>/modules/shop/orders/classes/form/backend/order.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Order extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "w600px"); if ($this->model()->id !== NULL) { // datetime_created $element = new Form_Element_Input('datetime_created', array('label' => 'Время создания', 'disabled' => TRUE, 'layout' => 'wide'), array('class' => 'w200px') ); $this->add_component($element); } // ----- Status_id $statuses = Model::fly('Model_OrderStatus')->find_all(array('order_by' => 'id', 'desc' => FALSE)); $options = array(); foreach ($statuses as $status) { $options[$status->id] = $status->caption; } $element = new Form_Element_Select('status_id', $options, array('label' => 'Статус', 'required' => TRUE, 'layout' => 'wide') ); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- name $element = new Form_Element_Input('name', array('label' => 'Имя пользователя'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $this->add_component($element, 1); // ----- phone $element = new Form_Element_Input('phone', array('label' => 'Телефон'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $this->add_component($element, 2); // ----- email $element = new Form_Element_Input('email', array('label' => 'E-Mail'), array('maxlength' => 31)); $element ->add_filter(new Form_Filter_TrimCrop(31)); $this->add_component($element); // ----- address $element = new Form_Element_Textarea('address', array('label' => 'Адрес доставки')); $element ->add_filter(new Form_Filter_TrimCrop(1023)); $this->add_component($element); // ----- comment $element = new Form_Element_Textarea('comment', array('label' => 'Комментарий к заказу')); $element ->add_filter(new Form_Filter_TrimCrop(1023)); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => ($this->model()->id !== NULL ? 'Сохранить' : 'Далее')), array('class' => 'button_accept') )); } } <file_sep>/modules/system/forms/classes/form/validator/notemptystring.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validates that value is not an empty string * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_NotEmptyString extends Form_Validator { const EMPTY_STRING = 'EMPTY_STRING'; protected $_messages = array( self::EMPTY_STRING => 'Вы не указали :label!', ); /** * Validate * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $value = (string) $this->_value; if (preg_match('/^\s*$/', $value)) { $this->_error(self::EMPTY_STRING); return false; } return true; } /** * Render javascript for this validator * * @return string */ public function render_js() { $error = $this->_messages[self::EMPTY_STRING]; $error = $this->_replace_placeholders($error); $js = "v = new jFormValidatorRegexp(/\S/, '" . $error . "');\n"; return $js; } }<file_sep>/modules/shop/catalog/views/frontend/products/product_vision.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <iframe src="http://my.webinar.ru/event/<?php echo $product->event_id ?>/?t=1&export=1" width="966" height="768" frameborder="0" style="border:none"></iframe> <file_sep>/modules/backend/views/backend/flashmessages.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (empty($messages)) return; ?> <div class="flash_messages"> <?php foreach ($messages as $message) { echo View_Helper::flash_msg($message['text'], $message['type']); } ?> </div><file_sep>/modules/shop/acl/classes/model/user.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_User extends Model { const LINKS_LENGTH = 36; static $users = array(); public static function users($group_id) { if (!isset(self::$users[$group_id])) { self::$users[$group_id] =array(); $results = Model::fly('Model_User')->find_all_by_group_id_and_active($group_id,true,array( 'order_by'=> 'last_name', 'columns'=>array('id','last_name') )); foreach ($results as $result) { self::$users[$group_id][$result->id] = $result->name; } } return self::$users[$group_id]; } /** * Get userlinks for the user */ public function update_props(array $newvals) { $this->email = $newvals['email']; $this->first_name = $newvals['first_name']; $this->last_name = $newvals['last_name']; $this->organizer_name = $newvals['organizer_name']; $this->town_id = $newvals['town_id']; $this->info = $newvals['info']; $this->set_password($newvals['<PASSWORD>']); } /** * Get currently authorized user (FRONTEND) * * @param Request $request (if NULL, current request will be used) * @return Model_User */ public static function current(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } // cache? $user = $request->param('user',NULL); if ($user !== NULL) return $user; $user = Auth::instance()->get_user(); $request->set_value('user', $user); return $user; } /** * Does this user have the requested privilege? * * @param string $privilege * @return boolean */ public function granted($privilege) { return $this->group->granted($privilege); } /** * Proxy privileges from Model_Group * * @return Models */ public function get_privileges() { return $this->get_group()->privileges; } /** * Proxy privileges_granted from Model_Group * * @return Models */ public function get_privileges_granted() { return $this->get_group()->privileges_granted; } /** * User is not system by default * * @return boolean */ public function default_system() { return FALSE; } public function default_active() { return FALSE; } public function default_notify() { return FALSE; } /** * Returns default group id for user * * @return integer */ public function default_group_id() { return 3; } /** * Returns default logins * * @return integer */ public function default_logins() { return 0; } /** * Get active[!] userprops for this user */ public function get_userprops() { if ( ! isset($this->_properties['userprops'])) { if ($this->id !== NULL) { $userprops = Model::fly('Model_UserProp')->find_all_by_user_id_and_active_and_system( $this->id, 1, 0, array('order_by' => 'position', 'desc' => FALSE) ); } else { $userprops = new Models('Model_UserProp',array()); } $this->_properties['userprops'] = $userprops; } return $this->_properties['userprops']; } /** * Get userlinks for the user */ public function get_links() { if ( ! isset($this->_properties['links'])) { $userlinks = Model::fly('Model_Link')->find_all( array('order_by' => 'position', 'desc' => FALSE) ); $this->_properties['links'] = $userlinks; } return $this->_properties['links']; } /** * Set password for user and regenerate hash * * @param string $value */ public function set_password($value) { $this->password = $value; $this->hash = Auth::instance()->calculate_hash($value); } /** * Get group for this user * * @return Model_Group */ public function get_group() { if ( ! isset($this->_properties['group'])) { $group = new Model_Group(); if ($this->group_id != 0) { $group->find($this->group_id); } $this->_properties['group'] = $group; } return $this->_properties['group']; } /** * Set system flag * * @param boolean $system */ public function set_system($system) { // Prohibit setting system property for user } /** * Return user name * * @return string */ public function get_name() { $name = ''; if ($this->first_name) $name.=$this->first_name; if ($this->last_name) $name.=' '.$this->last_name; return $name; } /** * Generates a new token for this user with the type given * * @param integer $type * @return Model_Token */ public function generate_token($type = Model_Token::TYPE_LOGIN) { $token = new Model_Token(); $token->type = Model_Token::TYPE_LOGIN; $token->user_id = $this->id; $token->save(); return $token; } /** * Complete the login for a user by incrementing the logins and saving login timestamp */ public function complete_login() { // Update the number of logins $this->logins += 1; // Set the last login date $this->last_login = new DateTime(); // Save the user $this->save(); } public function get_last_login() { if ( ! isset($this->_properties['last_login'])) { $this->_properties['last_login'] = new DateTime(); } return clone $this->_properties['last_login']; } public function get_last_login_str() { return $this->last_login->format(Kohana::config('datetime.datetime_format')); } // ------------------------------------------------------------------------- // Validation // ------------------------------------------------------------------------- /** * Validate user creation * * @param array $newvalues * @return boolean */ public function validate_create(array $newvalues) { return $this->validate_update($newvalues); } /** * Validates user update * * @param array $newvalues * @return boolean */ public function validate_update(array $newvalues) { // if (!isset($newvalues['organizer_id']) || $newvalues['organizer_id'] == NULL) { // $this->error('Указана несуществующая организация!'); // return FALSE; // } return ( $this->validate_email($newvalues) AND $this->validate_group_id($newvalues) ); } /** * Validate user email * * @param array $newvalues * @return boolean */ public function validate_email(array $newvalues) { if ( ! isset($newvalues['email'])) { $this->error('Вы не указали e-mail!', 'email'); return FALSE; } if ($this->exists_another_by_email($newvalues['email'])) { $this->error('Пользователь с таким e-mail уже существует!', 'email'); return FALSE; } return TRUE; } /** * Prohibit group changes for system users * * @param array $newvalues New values for model * @return boolean */ public function validate_group_id(array $newvalues) { if ( ! isset($newvalues['group_id'])) { if ( ! isset($this->group_id)) { $this->error('Не указана группа!', 'group_id'); return FALSE; } else { return TRUE; } } if ($this->system && (int)$newvalues['group_id'] !== $this->group_id) { $this->error('Для системного пользователя нельзя сменить группу!', 'group_id'); return FALSE; } //@FIXME: check that group exists here, not in form? return TRUE; } /** * Prohibit deletion of system users * * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->system) { $this->error('Пользователь "' . HTML::chars($this->name) . '" является системным. Его удаление запрещено!'); return FALSE; } return TRUE; } /** * Get userprop-user infos * * @return Models */ public function get_userpropusers() { if ( ! isset($this->_properties['userpropusers'])) { $this->_properties['userpropusers'] = Model::fly('Model_UserPropUser')->find_all_by_user($this, array('order_by' => 'position', 'desc' => FALSE)); } return $this->_properties['userpropusers']; } /** * Get userprop-user infos as array for form * * @return array */ public function get_userpropus() { if ( ! isset($this->_properties['userpropus'])) { $result = array(); foreach ($this->userpropusers as $userpropuser) { if ($userpropuser->userprop_id !== NULL) $result[$userpropuser->userprop_id]['userprop_id'] = $userpropuser->userprop_id; $result[$userpropuser->userprop_id]['active'] = $userpropuser->active; } $this->_properties['userpropus'] = $result; } return $this->_properties['userpropus']; } /** * Set userprop-user link info (usually from form - so we need to add 'user_id' field) * * @param array $userpropusers */ public function set_userpropus(array $userpropusers) { foreach ($userpropusers as $userprop_id => & $userpropuser) { if ( ! isset($userpropuser['userprop_id'])) { $userpropuser['userprop_id'] = $userprop_id; } } $this->_properties['userpropus'] = $userpropusers; } public function get_organizer() { if ( ! isset($this->_properties['organizer'])) { $organizer = new Model_Organizer(); $organizer->find((int) $this->organizer_id); if (!$organizer->id) $organizer->name = $this->organizer_name; $this->_properties['organizer'] = $organizer; } return $this->_properties['organizer']; } public function get_town() { if ( ! isset($this->_properties['town'])) { $town = new Model_Town(); $town->find((int) $this->town_id); $this->_properties['town'] = $town; } return $this->_properties['town']; } public function get_tag_items() { if ( ! isset($this->_properties['tag_items'])) { $tags = array(); if ($this->id) { $tags = Model::fly('Model_Tag')->find_all_by(array( 'owner_type' => 'user', 'owner_id' => $this->id ), array('order_by' => 'weight')); } $this->_properties['tag_items'] = $tags; } return $this->_properties['tag_items']; } public function get_tags() { if ( ! isset($this->_properties['tags'])) { $tag_str = ''; $tag_arr = array(); foreach ($this->tag_items as $tag_item) { $tag_arr[] = $tag_item->name; } $this->_properties['tags'] = implode(Model_Tag::TAGS_DELIMITER,$tag_arr); } return $this->_properties['tags']; } public function save($create = FALSE,$update_userprops = TRUE, $update_userlinks = TRUE) { $notify_flag = FALSE; if ($create || $this->id == NULL) { $notify_flag=TRUE; } if (!$this->organizer_id) { $this->organizer_id = Model_Organizer::DEFAULT_ORGANIZER_ID; $this->organizer_name = Model_Organizer::DEFAULT_ORGANIZER_NAME; } parent::save($create); if (is_array($this->file)) { $file_info = $this->file; if (isset($file_info['name'])) { if ($file_info['name'] != '') { // Delete organizer images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('user', $this->id); $image = new Model_Image(); $image->file = $this->file; $image->owner_type = 'user'; $image->owner_id = $this->id; $image->config = 'user'; $image->save(); $this->file=''; } } } Model::fly('Model_Tag')->save_all($this->tags, 'user',$this->id); if ($update_userprops) { // Link user to the userprops Model::fly('Model_UserPropUser_Mapper')->link_user_to_userprops($this, $this->userpropus); // Update values for additional properties Model_Mapper::factory('Model_UserPropValue_Mapper')->update_values_for_user($this); } if ($update_userlinks) { // Update links values Model_Mapper::factory('Model_LinkValue_Mapper')->update_values_for_user($this); } if ($notify_flag) { $this->notify(); } } /** * Send e-mail notification for activation */ public function notify() { try { $this->activation_link = $this->activation_link_gen(); $settings = Model_Site::current()->settings; $email_to = isset($settings['email']['to']) ? $settings['email']['to'] : ''; $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; if ($email_sender != '') { $email_from = array($email_from => $email_sender); } if ($email_to != '' || $this->email != '') { // Init mailer SwiftMailer::init(); $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); if ($email_to != '') { // --- Send message to administrator $message = Swift_Message::newInstance() ->setSubject('Новый представитель на портале ' . URL::base(FALSE, TRUE)) ->setFrom($email_from) ->setTo($email_to); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate('mail/reg_admin'); $message->setBody($template->render(array( 'user' => $this ))); // Send message $mailer->send($message); } if ($this->email != '') { // --- Send message to client $message = Swift_Message::newInstance() ->setSubject('Регистрация на портале ' . URL::base(FALSE, TRUE)) ->setFrom($email_from) ->setTo($this->email); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate('mail/reg_client'); $body = $template->render(array( 'user' => $this )); if ($signature != '') { $body .= "\n\n\n" . $signature; } $message->setBody($body); // Send message $mailer->send($message); } } } catch (Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { throw $e; } } $this->save(FALSE,FALSE,FALSE); return TRUE; } /** * Set notification to client that his question has been answered */ public function password_recovery() { try { $this->recovery_link = $this->recovery_link_gen(); // Site settings $settings = Model_Site::current()->settings; $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; if ($email_sender != '') { $email_from = array($email_from => $email_sender); } // FAQ settings $config = Modules::load_config('acl_' . Model_Site::current()->id, 'acl'); $subject = isset($config['email']['client']['subject']) ? $config['email']['client']['subject'] : ''; $body = isset($config['email']['client']['body']) ? $config['email']['client']['body'] : ''; if ($this->email != '') { $twig = Twig::instance('string'); // Values for the templates $values = $this->values(); $values['site'] = Model_Site::canonize_url(URL::site('', TRUE)); // Subject $subject = $twig->loadTemplate($subject)->render($values); // Body (with optional signature) $body = $twig->loadTemplate($body)->render($values); if ($signature != '') { $body .= "\n\n\n" . $signature; } // Init mailer SwiftMailer::init(); $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance() ->setSubject($subject) ->setFrom($email_from) ->setTo($this->email) ->setBody($body); // Send message $mailer->send($message); } } catch (Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { throw $e; } else { return FALSE; } } $this->save(FALSE,FALSE,FALSE); return TRUE; } private function activation_link_gen() { return 'http://vse.to/'.URL::uri_to('frontend/acl',array('action'=>'activation','hash' => Auth::instance()->hash(time()))); } private function recovery_link_gen() { return 'http://vse.to/'.URL::uri_to('frontend/acl',array('action'=>'newpas','hash' => Auth::instance()->hash(time()))); } public function delete() { // Delete userprop values for this user Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('user', $this->id); // Delete userprop values for this user Model_Mapper::factory('Model_UserPropValue_Mapper')->delete_all_by_user_id($this, $this->id); // Delete links values for this user Model_Mapper::factory('Model_LinkValue_Mapper')->delete_all_by_user_id($this, $this->id); // Delete user itself parent::delete(); } public function image($size = NULL) { $image_info = array(); $image = Model::fly('Model_Image')->find_by_owner_type_and_owner_id('user', $this->id, array( 'order_by' => 'position', 'desc' => FALSE )); if ($size) { $field_image = 'image'.$size; $field_width = 'width'.$size; $field_height = 'height'.$size; $image_info['image'] = $image->$field_image; $image_info['width'] = $image->$field_width; $image_info['height'] = $image->$field_height; } return $image_info; } } <file_sep>/modules/shop/acl/views/frontend/user_card.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($user->id && count($fields)) { // ----- Set up urls $user_url = URL::to('frontend/acl/users/control', array('action' => 'control','user_id' => $user->id), TRUE); ?> <table class="user_card"> <tr> <?php foreach ($fields as $field) { switch ($field) { case 'image': $image_info = $user->image(4); echo '<td class="image"><a href="' . $user_url . '" class="user_select" id="user_' . $user->id. '">' . HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'])) . '</a>'; break; case 'name': echo '<td class="name"><a href="' . $user_url . '" class="user_select" id="user_' . $user->id. '">' . $user->name . '</a></td>'; break; } } ?> </tr> </table> <?php } ?> <file_sep>/modules/system/forms/classes/form/element/custom.php <?php defined('SYSPATH') or die('No direct script access.'); /** * A custom form element. Element value is used as element contnet * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Custom extends Form_Element { /** * Use element value as it's contents * * @return string */ public function render_input() { return $this->value; } } <file_sep>/modules/general/chat/classes/model/dialog/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Dialog_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('sender_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('receiver_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('sender_active', array('Type' => 'boolean')); $this->add_column('receiver_active', array('Type' => 'boolean')); } public function find_all_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->distinct('whatever') ->from($table); } // ----- process contition if (is_array($condition) && ! empty($condition['sender_id'])) { unset($condition['sender_id']); } if (is_array($condition) && ! empty($condition['receiver_id'])) { unset($condition['receiver_id']); } // find only user's dialogs $query->where("$table.sender_id", '=', Auth::instance()->get_user()->id) ->or_where("$table.receiver_id", '=', Auth::instance()->get_user()->id); return parent::find_all_by($model, $condition, $params, $query); } public function count_by(Model $model, $condition = NULL) { $table = $this->table_name(); $query = DB::select(array('COUNT(DISTINCT "' . $table . '.id")', 'total_count')) ->from($table); // ----- process contition if (is_array($condition) && ! empty($condition['sender_id'])) { unset($condition['sender_id']); } if (is_array($condition) && ! empty($condition['receiver_id'])) { unset($condition['receiver_id']); } // find only user's dialogs $query->where("$table.sender_id", '=', Auth::instance()->get_user()->id) ->or_where("$table.receiver_id", '=', Auth::instance()->get_user()->id); if ($condition !== NULL) { $condition = $this->_prepare_condition($condition); $query->where($condition, NULL, NULL); } $count = $query->execute($this->get_db()) ->get('total_count'); return (int) $count; } }<file_sep>/modules/backend/classes/controller/backend/index.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Index extends Controller_Backend { /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->caption = 'Панель управления'; $layout->content = $view; return $layout->render(); } /** * Index action */ public function action_index() { $this->request->response = $this->render_layout(new View('backend/index')); } /** * Render flash messages * * @return string */ public function widget_flashmessages() { $messages = FlashMessages::fetch_all(); $view = new View('backend/flashmessages'); $view->messages = $messages; return $view->render(); } } <file_sep>/modules/shop/area/views/frontend/place_ac.php <div class="place_ac item i_<?php echo $num;?>"> <div class="item i_<?php echo $num;?>"><?php echo HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'], 'class' => 'item i_'.$num)) ?></div> <div class="item i_<?php echo $num;?>"><?php echo $name ?></div> </div> <file_sep>/modules/general/blocks/classes/model/block/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Block_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); // Имя блока (для вставки в шаблон) $this->add_column('name', array('Type' => 'varchar(15)', 'Key' => 'INDEX')); // Название блока $this->add_column('caption', array('Type' => 'varchar(63)')); // Текст блока $this->add_column('text', array('Type' => 'text')); // Видимость на страницах по умолчанию $this->add_column('default_visibility', array('Type' => 'boolean')); } /** * Find all visible blocks for given node * * @param Model_Block $block * @param string $name * @param integer $node_id * @param array $params * @return Models|array */ public function find_all_visible_by_name_and_node_id(Model_Block $block, $name, $node_id, array $params = NULL) { $blocknode_table = Model_Mapper::factory('BlockNode_mapper')->table_name(); $block_table = $this->table_name(); $query = DB::select("$block_table.*") ->from($block_table) ->join($blocknode_table, 'LEFT') ->on("$blocknode_table.node_id", '=', DB::expr((int) $node_id)) ->on("$blocknode_table.block_id", '=', "$block_table.id"); $condition = DB::where('name', '=', $name) ->and_where_open() ->and_where("$blocknode_table.visible", '=', 1) ->or_where_open() ->and_where("ISNULL(\"$blocknode_table.visible\")", NULL, NULL) ->and_where("$block_table.default_visibility", '=', 1) ->or_where_close() ->and_where_close(); return $this->find_all_by($block, $condition, $params, $query); } /** * Move block one position up * * @param Model $model * @param Database_Expression_Where $condition */ public function up(Model $model, Database_Expression_Where $condition = NULL) { parent::up($model, DB::where('site_id', '=', $model->site_id)); } /** * Move block one position down * * @param Model $model * @param Database_Expression_Where $condition */ public function down(Model $model, Database_Expression_Where $condition = NULL) { parent::down($model, DB::where('site_id', '=', $model->site_id)); } }<file_sep>/modules/general/tags/views/frontend/forms/image.php <div id="ImgModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Загузка Фото</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <label for="file"><?php echo $form->get_element('file')->render_input(); ?></label> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_image')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div> <file_sep>/modules/shop/deliveries/classes/model/delivery.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Delivery extends Model { /** * Registered delivery modules * @var array */ protected static $_modules = array(); /** * Register delivery module * * @param string $module */ public static function register(array $module_info) { if ( ! isset($module_info['module'])) { throw new Kohana_Exception('Module was not supplied in module_info for :method', array(':method' => __METHOD__)); } self::$_modules[$module_info['module']] = $module_info; } /** * Get module info for the specified module * * @param string $module * @return array */ public static function module_info($module) { if (isset(self::$_modules[$module])) { return self::$_modules[$module]; } else { return NULL; } } /** * Get registered delivery modules * * @return array */ public static function modules() { return self::$_modules; } /** * Get delivery type caption by id * * @param integer $id */ public static function caption($id) { // Obtain all deliveries (CACHED!) $deliveries = Model::fly('Model_Delivery')->find_all(array('key' => 'id')); if (isset($deliveries[$id])) { return $deliveries[$id]->caption; } else { return NULL; } } /** * All delivery models use the same mapper * * @param string $mapper * @return Model_Delivery_Mapper */ public function mapper($mapper = NULL) { if ($mapper !== NULL || $this->_mapper !== NULL) { return parent::mapper($mapper); } // All payment models uses Model_Delivery_Mapper as mapper $this->_mapper = Model_Mapper::factory('Model_Delivery_Mapper'); return $this->_mapper; } /** * Determine delivery module from model class name * * @return string */ public function default_module() { $class = get_class($this); if (strpos($class, 'Model_Delivery_') === 0) { return strtolower(substr($class, strlen('Model_Delivery_'))); } else { return NULL; } } /** * Default delivery price * * @return Money */ public function default_price() { return new Money(); } /** * Module caption for this delivery type * * @return string */ public function get_module_caption() { $module_info = self::module_info($this->module); if (is_array($module_info)) { return (isset($module_info['caption']) ? $module_info['caption'] : $module_info['module']); } else { return NULL; } } /** * Get id of all payment types that this delivery type support */ public function get_payment_ids() { if ( ! isset($this->_properties['payment_ids'])) { $payment_ids = array(); $payments = Model::fly('Model_Payment')->find_all_by_delivery($this, array('columns' => array('id'))); foreach ($payments as $payment) { $payment_ids[$payment->id] = TRUE; } $this->_properties['payment_ids'] = $payment_ids; } return $this->_properties['payment_ids']; } /** * Save payment type and link it to selected delivery types * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); // Link delivery type to the selected payment types $payment_ids = array_keys(array_filter($this->payment_ids)); Model_Mapper::factory('PaymentDelivery_Mapper')->link_delivery_to_payments($this, $payment_ids); } /** * Calculate delivery price for specified order * * @param Model_Order $order * @return float */ public function calculate_price(Model_Order $order) { return $this->default_price(); } }<file_sep>/modules/shop/acl/views/frontend/forms/login.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div id="enterModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Вход</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <!--<p>Вход через социальные сети</p> <div class="soc-link"> <a href="#" class="button fb">f</a> <a href="#" class="tw button ">t</a> <a href="#" class="button vk">v</a> </div>--> <div id="social-login"> <p>Через социальные сети</p> <?php echo Ulogin::factory()->render() ?> </div> <div> <p>Или логин-пароль</p> <label for="email"><?php echo $form->get_element('email')->render_input(); ?></label> <label for="pass"><?php echo $form->get_element('password')->render_input(); ?></label> </div> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_login')->render_input(); ?> </div> <?php echo $form->render_form_close();?> </div><file_sep>/application/classes/file.php <?php defined('SYSPATH') OR die('No direct access allowed.'); /** * File helper class. * * @package Eresus * @author <NAME> (<EMAIL>) */ class File extends Kohana_File { const SORT_BY_FILENAME = 'SORT_BY_FILENAME'; const SORT_BY_EXT = 'SORT_BY_EXT'; /** * Concat file names * * @return string */ public static function concat() { $result = ''; $paths = func_get_args(); foreach ($paths as $path) { if ($path === '/') { $result .= $path; } elseif ($path != '') { $result .= rtrim($path, '/\\') . '/'; } } return File::normalize_path($result); } public static function normalize_path($path) { // Convert all backslashes to forward slashes $path = str_replace('\\', '/', $path); // Remove duplicate forward slashes $path = str_replace('//', '/', $path); if ($path !== '/') { // Trim right forward slashes $path = rtrim($path, '/'); } return $path; } public static function real_path($path) { $path = realpath($path); if ($path == FALSE) { return NULL; } return File::normalize_path($path); } /** * Return part of $path relative to $base_path or FALSE if $path is outside $base_path * * @param string $path * @param string $base_path * @return string on success * @return boolean FALSE if $path is outside $base_path */ public static function relative_path($path, $base_path) { $path = File::normalize_path($path); $base_path = File::normalize_path($base_path); if ($base_path === '') { // Base path is empty return $path; } if (strpos($path, $base_path) !== 0) { // $path is outside $base_path return NULL; } $relative_path = substr($path, strlen($base_path)); $relative_path = ltrim($relative_path, '/\\'); return $relative_path; } /** * If $path is inside DOCROOT - return uri to file * * @param string $path * @return string */ public static function uri($path) { $relative_path = File::relative_path($path, DOCROOT); if ($relative_path === NULL) { return NULL; } return $relative_path; } /** * If $path is inside DOCROOT - return uri to file * * @param string $path * @return string */ public static function url($path) { $url = File::uri($path); if ($url !== NULL) { $url = URL::base() . $url; } return $url; } /** * Sort files (directories are always above files) * * @param array $files * @param integer $sort_by */ public static function sort(array & $files, $sort_by = File::SORT_BY_FILENAME) { usort($files, array('File', '_sort_by_filename')); } /** * Compare files in a way to make directories be always on top * * @param array $file1 * @param array $file2 * @return integer 1 if $file1 > $file 2, 0 if $file1 = $file2, -1 if $file1 < $file2 */ private static function _sort_by_filename($file1, $file2) { if ($file1['is_dir'] && ! $file2['is_dir']) { return -1; } elseif ( ! $file1['is_dir'] && $file2['is_dir']) { return 1; } else { if ($file1['base_name'] === $file2['base_name']) { return 0; } else { return ($file1['base_name'] > $file2['base_name']) ? 1 : -1; } } } /** * Delete directory recursively * * @param string $dir * @return boolean */ public static function delete($dir) { if ( ! file_exists($dir)) { return TRUE; } if ( ! is_dir($dir) || is_link($dir)) { // $dir is a file or a sym link return unlink($dir); } $files = scandir($dir); if ($files === FALSE) { return FALSE; } // Delete all subfiles and subfolders foreach ($files as $file) { if ($file == '.' || $file == '..') { // Skip pointers continue; } $file = $dir . DIRECTORY_SEPARATOR . $file; if (is_dir($file)) { // Recursively delete subdirectory File::delete($file); } else { unlink($file); } } // Delete the dir itself return rmdir($dir); } /** * Move uploaded file to specified path or to the temporary location in application tmp dir * and return the new path * * @param array $file Information about uploaded file (entry from $_FILES) * @return string */ public static function upload(array $file, $path = NULL) { $path = File::getPath($path); if ( ! @move_uploaded_file($file['tmp_name'], $path)) { throw new Kohana_Exception('Failed to move uploaded file!'); } @chmod($path, 0666); return $path; } /** * Download file from specific URL and move him to specified path or to the temporary location in application tmp dir * and return the new path * * @param $url Url to download * @param $path Path to save file * @param $allowed_extn Allowed file extensions * @return string */ public static function download_file($url, $path = NULL, array $allowed_extn = array('jpg', 'png')) { $extn = substr($url, strrpos($url, '.')+1); if (!in_array($extn, $allowed_extn)) throw new Kohana_Exception('File has not-allowed extension!'); $file = file_get_contents($url); $pathToSave = File::getPath($path); file_put_contents($pathToSave, $file); @chmod($pathToSave, 0666); return $pathToSave; } private static function getPath($path) { if ( ! is_writable(TMPPATH)) { throw new Kohana_Exception('Temporary directory "' . TMPPATH . '" is not writable'); } if ($path === NULL) { // Generate new temporary file name do { $path = TMPPATH . Text::random(); } while (is_file($path)); } return $path; } } <file_sep>/modules/general/jquery/classes/jquery.php <?php defined('SYSPATH') or die('No direct script access.'); class jQuery { /** * @var boolean */ protected static $_scripts_added = FALSE; /** * Add jQuery scripts to the layout */ public static function add_scripts() { if (self::$_scripts_added) return; $layout = Layout::instance(); $layout->add_script(Modules::uri('jquery') . '/public/js/jquery-1.7.2.min.js'); $layout->add_script(Modules::uri('jquery') . '/public/js/jquery-ui.min.js'); $layout->add_script(Modules::uri('jquery') . '/public/js/jquery-ui-sliderAccess.js'); $layout->add_script(Modules::uri('jquery') . '/public/js/jquery-ui-timepicker-addon.js'); $layout->add_style(Modules::uri('jquery') . '/public/css/jquery-ui-timepicker-addon.css'); $layout->add_style(Modules::uri('jquery') . '/public/css/jquery-ui-1.8.22.custom.css'); self::$_scripts_added = TRUE; } }<file_sep>/modules/general/chat/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { // ----- dialogs Route::add('frontend/dialogs', new Route_Frontend( 'dialogs(/<action>(/<id>)(/ids-<ids>))' . '(/p-<page>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[0-9_]++', 'page' => '(\d++|all)', 'history' => '.++' ))) ->defaults(array( 'controller' => 'dialogs', 'action' => 'index', 'id' => NULL, 'ids' => '', 'page' => '0', )); Route::add('frontend/messages', new Route_Frontend( 'messages(/dialog-<dialog_id>)(/<action>(/<id>)(/ids-<ids>))' . '(/user-<user_id>)' . '(/p-<page>)' . '(/~<history>)', array( 'dialog_id' => '\d++', 'action' => '\w++', 'id' => '\d++', 'ids' => '[0-9_]++', 'user_id' => '\d++', 'page' => '(\d++|all)', 'history' => '.++' ))) ->defaults(array( 'controller' => 'messages', 'action' => 'index', 'id' => NULL, 'dialog_id' => NULL, 'ids' => '', 'user_id' => '0', 'page' => '0', )); } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { // ----- dialogs Route::add('backend/dialogs', new Route_Backend( 'dialogs(/<action>(/<id>)(/ids-<ids>))' . '(/p-<page>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[0-9_]++', 'page' => '(\d++|all)', 'history' => '.++' ))) ->defaults(array( 'controller' => 'dialogs', 'action' => 'index', 'id' => NULL, 'ids' => '', 'page' => '0' )); Route::add('backend/messages', new Route_Backend( 'messages(/dialog-<dialog_id>)(/<action>(/<id>)(/ids-<ids>))' . '(/user-<user_id>)' . '(/p-<page>)' . '(/~<history>)', array( 'dialog_id' => '\d++', 'action' => '\w++', 'id' => '\d++', 'ids' => '[0-9_]++', 'user_id' => '\d++', 'page' => '(\d++|all)', 'history' => '.++' ))) ->defaults(array( 'controller' => 'messages', 'action' => 'index', 'id' => NULL, 'dialog_id' => NULL, 'ids' => '', 'user_id' => '0', 'page' => '0', )); // ----- Add backend menu items $id = Model_Backend_Menu::add_item(array( 'id' => 6, 'menu' => 'main', 'caption' => 'Сообщения', 'route' => 'backend/dialogs', 'select_conds' => array( array('route' => 'backend/dialogs'), array('route' => 'backend/messages'), ), 'icon' => 'dialogs' )); Model_Backend_Menu::add_item(array( 'parent_id' => $id, 'menu' => 'main', 'caption' => 'Диалоги', 'route' => 'backend/dialogs' )); } /****************************************************************************** * Common ******************************************************************************/ Model_Privilege::add_privilege_type('dialogs_index', array( 'name' => 'Сообщения', 'readable' => TRUE, 'controller' => 'dialogs', 'action' => 'index', 'frontend_route' => 'frontend/dialogs', 'frontend_route_params' => array('action' => 'index'), ));<file_sep>/modules/general/chat/views/frontend/forms/smallmsg.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php echo $form->render_form_open(); ?> <table class="table smallmsg"> <tbody> <tr> <td> <table class="smallmsg_up"> <tbody> <tr> <td class="smallmsg_sender"> <?php $sender = Auth::instance()->get_user(); echo Widget::render_widget('users', 'user_card', $sender,array('image')); ?> </td> <td class="smallmsg_message"> <?php echo $form->get_element('message')->render_input(); ?> </td> <td class="smallmsg_receiver"> <?php $receiver_id = ($sender->id == $form->model()->sender_id) ? $form->model()->receiver_id : $form->model()->sender_id; $receiver = Model::fly('Model_User')->find($receiver_id); echo Widget::render_widget('users', 'user_card', $receiver,array('image')); ?> </td> </tr> </tbody> </table> </td> </tr> <tr> <td> <table class="smallmsg_down"> <tbody> <tr> <td class="smallmsg_notify"> <?php echo $form->get_element('notify')->render_label(); ?> </td> <td class="smallmsg_notify"> <?php echo $form->get_element('notify')->render_input(); ?> </td> <td class="smallmsg_button"> <input type="submit" value="Отправить" class="submit" /> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <?php echo $form->render_form_close(); ?> <file_sep>/modules/shop/area/views/frontend/places/map_place.php <?php $url = URL::to('frontend/area/places', array('alias' => $place->alias)); ?> <div class="map_info"><h3><?php echo $place->name?></h3><p class="place"><?php echo $place->town_name?>, <?php echo $place->address ?></p></div> <file_sep>/modules/shop/orders/classes/form/backend/cartproduct.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_CartProduct extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "w500px wide lb120px"); if ($this->model()->id === NULL) { // ----- "Find in catalog" button $product_select_url = URL::to('backend/catalog', array('site_id' => $this->model()->order->site_id, 'action' => 'product_select'), TRUE); $element = new Form_Element_Text('product_select'); $element->value = '<div class="buttons">' . ' <a href="' . $product_select_url . '" class="button open_window dim700x500">Найти в каталоге</a>' . '</div>' ; $this->add_component($element); } // ----- Marking $element = new Form_Element_Input('marking', array('label' => 'Артикул', 'required' => TRUE), array('maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Price $element = new Form_Element_Money('price', array('label' => 'Цена', 'required' => TRUE) ); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Float(0, NULL, FALSE)); $this->add_component($element); // ----- Quantity $element = new Form_Element_Integer('quantity', array('label' => 'Количество', 'required' => TRUE)); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Integer(0, NULL, FALSE)); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } } <file_sep>/modules/shop/area/views/backend/towns/town_place_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="towns"> <table> <tr> <td> <?php // Highlight current group if ($town_alias == 0) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo URL::self(array('are_town_alias' => (string) '')); ?>" class="town<?php echo $selected; ?>" title="Показать все площадки" > <strong>Все площадки</strong> </a> </td> <td>&nbsp;</td> <?php foreach ($towns as $town) : ?> <tr> <td> <?php // Highlight current group if ($town->alias == $town_alias) { $selected = ' selected'; } else { $selected = ''; } ?> <a href="<?php echo URL::self(array('are_town_alias' => (string) $town->alias)); ?>" class="town<?php echo $selected; ?>" title="Показать площадки города '<?php echo HTML::chars($town->name); ?>'" > <?php echo HTML::chars($town->name); ?> </a> </td> </tr> <?php endforeach; //foreach ($towns as $town) ?> </table> </div> <file_sep>/modules/system/widgets/public/js/widgets.js /** * Initialize widgets */ $(function(){ // standart widgets $('.widget').each(function(i,container){ var widget = new jWidget(); widget.init(container.id); }); // popup widgets $('.popup_widget').each(function(i, container){ var widget = new jWidgetPopup(); widget.init(container.id); widget.init_popup(container.id); }); }) // ----------------------------------------------------------------------------- // jWidget // ----------------------------------------------------------------------------- /** * Initialize new widget from dom element */ function jWidget() {} /** * Extend the object by copying its prototype * Constructor of the ancestor is available via this.ancestor_class */ jWidget.extend = function(descendant) { // make the jWidget constructor available in descendant via this.jWidget descendant.prototype['jWidget'] = jWidget; for (var m in jWidget.prototype) { descendant.prototype[m] = jWidget.prototype[m]; } } /** * Collection of all registered widgets {widget_id : widget_object} */ jWidget.widgets = {}; /** * Callback function for ajax requests */ jWidget.ajax_callback = function(data) { if ( ! data) return; //@FIXME: security breach eval('var response = ' + data + ';'); // Redraw widgets if (response.widgets) { for (var widget_id in response.widgets) { if (jWidget.widgets[widget_id]) { jWidget.widgets[widget_id].redraw(response.widgets[widget_id]); } } } // Display messages as alerts if (response.messages) { for (var i = 0; i < response.messages.length; i++) { alert(response.messages[i].text); } } } /** * Initialize the specified widget * * @param id widget id (id of the dom element that serves as a container for the widget) */ jWidget.prototype.init = function(id) { var self = this; // ----- save widget id and register widget this.id = id; jWidget.widgets[id] = this; // ----- setup event handlers $('#' + id).click(function(event) { // Listen to the clicks on links with 'ajax' class inside the widget var target; if (event.target.tagName != 'A') { // Check parents of the clicked element - may be this is an element inside the link target = $(event.target).parent('a'); } else { target = $(event.target); } if (target.hasClass('ajax')) { // links, that are supposed to redraw the widget, must have an 'ajax' class // Execute the handler self.click_handler(target); event.stopPropagation(); event.preventDefault(); } }); $('#' + id).submit(function(event){ // Listen to the submits of forms with 'ajax' class inside the widget var target = $(event.target); if (target.hasClass('ajax')) { // forms, that are supposed to be submitted via ajax, must have an 'ajax' class // Execute the handler self.submit_handler(target); event.stopPropagation(); event.preventDefault(); } }); } /** * This function is called when a link with 'ajax' class inside the widget is clicked * * @param link jQuery object, created from the clicked link */ jWidget.prototype.click_handler = function(link) { this.ajax(link.attr('href')); } /** * This function is called when a form with 'ajax' class is submitted inside the widget * * @param form jQuery object, created from the form being submitted */ jWidget.prototype.submit_handler = function(form) { this.ajax(form.attr('action'), form.serializeArray()); } /** * Some action to peform before an ajax request (display "loading...", for example) */ jWidget.prototype.before_ajax = function(url, data) { } /** * Peform an ajax request for the specified widget. * if data is specified, than a POST request will be made, a GET request * wil be made otherwise. * * @param url Url to send the request to * @param data Request data */ jWidget.prototype.ajax = function(url, data) { // url that will be used for ajax request var ajax_url = $('#' + this.id + '_url').html(); if ( ! ajax_url) { // send request to the clicked url/form action itself ajax_url = url; } if ( ! ajax_url) return; // Failed to retrieve url and it was not supplied to function // context uri / url var context_uri = $('#' + this.id + '_context_uri').html(); if (context_uri) { ajax_url += '?context=' + context_uri; } else { // used clicked url/form action as context ajax_url += '?context=' + url; } this.before_ajax(url, data); if (data) { $.post(ajax_url, data, jWidget.ajax_callback); } else { $.get(ajax_url, null, jWidget.ajax_callback); } } /** * Redraw widget contents */ jWidget.prototype.redraw = function(html) { $('#' + this.id).html(html); } // ----------------------------------------------------------------------------- // jWidgetPopup // ----------------------------------------------------------------------------- /** * Initialize new widget from dom element */ function jWidgetPopup() {} jWidget.extend(jWidgetPopup); /** * Initialize popup widget */ jWidgetPopup.prototype.init_popup = function(id) { this.layer = $('#' + id + '_layer'); this.blocker = $('#' + id + '_blocker'); this.wrapper = $('#' + id + '_wrapper'); this.config = { 'alignment' : 'center', 'stretch_blocker' : true } var self = this; // Bind events to links that should open the popup // This class of those links must be equal to the id of the popup widget $('a.' + id).each(function(i, link){ $(link).click(function(event){ self.show(); self.ajax(link.href); event.stopPropagation(); event.preventDefault(); }); }); // Bind event to the close popup button $('#' + id).click(function(event) { if (event.target.id == self.id + '_close') { self.hide(); event.stopPropagation(); event.preventDefault(); } }); } /** * Show popup */ jWidgetPopup.prototype.show = function() { // Show popup layer this.layer.show(); // Stretch blocker this.stretch_blocker(); // Refresh popup position popup this.reposition(); } /** * Stretch blocker vertically to 100% of document */ jWidgetPopup.prototype.stretch_blocker = function() { if (this.config['stretch_blocker']) { this.layer.height($(document).height()); } } /** * Hide popup */ jWidgetPopup.prototype.hide = function() { this.layer.hide(); } /** * Reposition popup depending on the alignment */ jWidgetPopup.prototype.reposition = function() { if (this.config['alignment'] == 'center') { // Center popup in browser window var top = ($(window).height() - this.wrapper.height()) / 2; if (top < 0) { top = 0; } var left = ($(window).width() - this.wrapper.width()) / 2; if (left < 0) { left = 0; } this.wrapper .css('top', $(window).scrollTop() + top) .css('left', $(window).scrollLeft() + left) } } /** * Display "loading..." message while ajax request is peformed */ jWidgetPopup.prototype.before_ajax = function() { this.redraw('<div class="loading">Загрузка...</div>'); } /** * Redraw widget contents */ jWidgetPopup.prototype.redraw = function(html) { $('#' + this.id).html(html); this.reposition(); } /** * Redraw popup content. Content is obtained via ajax request to url */ /* jWidgetPopup.prototype.redraw = function(url, data) { // Reset popup contents this.popup_content.html('<div class="loading">Загрузка</div>'); this.reposition(); // Load content via ajax request and reposition popup on complete var self = this; this.popup_content.load(url, data, function() { // Refresh popup position self.reposition(); // Stretch blocker (new content can increase document height) self.stretch_blocker(); // Re-init forms in popup content for IE 6-7 if ($.browser.msie) { self.init_forms(); } }); } */<file_sep>/modules/general/tinymce/config/tinymce.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // css file from public/css folder to use in wysiwyg editor 'css' => 'content.css' );<file_sep>/modules/system/forms/classes/form/element/textarea.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form textarea element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Textarea extends Form_Element { /** * Default type of input is "textarea" * * @return string */ public function get_type() { return 'textarea'; } /** * Default number of columns in textarea * * @return integer */ public function defaultattr_cols() { return 30; } /** * Default number of rows in textarea * * @return integer */ public function defaultattr_rows() { return 5; } /** * Get HTML attributes for textarea. * Set default values for 'cols' and 'rows' * * @return array */ public function attributes() { $attributes = parent::attributes(); if ( ! isset($attributes['cols'])) { $attributes['cols'] = $this->defaultattr_cols(); } if ( ! isset($attributes['rows'])) { $attributes['rows'] = $this->defaultattr_rows(); } return $attributes; } /** * Renders textarea * * @return string */ public function render_input() { return Form_Helper::textarea($this->full_name, $this->value, $this->attributes()); } } <file_sep>/modules/shop/acl/views/frontend/users/confirm.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="wrapper main-list"> <h3>Добро пожаловать на Vse.To - первую социальную сеть телемостов и вебинаров!</h3> <p> На Вашу электронную почту было отправлено письмо с ссылкой для активации Вашей учетной записи. После активации Вы сможете участвовать в событиях, происходящих во всём мире. Не откладывайте эту возможность! </p> </div> <file_sep>/modules/general/blocks/classes/model/block.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Block extends Model { /** * Is block visible by default for new nodes? * * @return boolean */ public function default_default_visibility() { return TRUE; } /** * Default site id for block * * @return id */ public function default_site_id() { return Model_Site::current()->id; } /** * Get nodes visibility info for this block * * @return array(node_id => visible) */ public function get_nodes_visibility() { if ( ! isset($this->_properties['nodes_visibility'])) { $result = Model_Mapper::factory('BlockNode_Mapper') ->find_all_by_block_id($this, (int) $this->id, array('as_array' => TRUE)); $nodes_visibility = array(); foreach ($result as $visibility) { $nodes_visibility[$visibility['node_id']] = $visibility['visible']; } $this->_properties['nodes_visibility'] = $nodes_visibility; } return $this->_properties['nodes_visibility']; } /** * Save block properties and block nodes visibility information * * @param boolean $force_create * @return Model_Menu */ public function save($force_create = FALSE) { parent::save($force_create); // Update nodes visibility info for this menu if ($this->id !== NULL && is_array($this->nodes_visibility)) { Model_Mapper::factory('BlockNode_Mapper')->update_nodes_visibility($this, $this->nodes_visibility); } return $this; } } <file_sep>/modules/general/faq/classes/form/frontend/question.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Question extends Form_Frontend { /** * Initialize form fields */ public function init() { // ----- user_name $element = new Form_Element_Input('user_name', array('label' => '<NAME>', 'required' => TRUE), array('maxlength' => 255) ); $element->add_filter(new Form_Filter_TrimCrop(255)); $element->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- email $element = new Form_Element_Input('email', array('label' => 'E-Mail'), array('maxlength' => 63)); $element->add_filter(new Form_Filter_TrimCrop(63)); $this->add_component($element); // ----- phone $element = new Form_Element_Input('phone', array('label' => 'Телефон'), array('maxlength' => 63)); $element->add_filter(new Form_Filter_TrimCrop(63)); $this->add_component($element); // ----- question $element = new Form_Element_Textarea('question', array('label' => 'Вопрос', 'required' => TRUE)); $element->add_filter(new Form_Filter_TrimCrop(512)); $element->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Element_Submit('submit', array('label' => 'Отправить вопрос') )); } } <file_sep>/modules/shop/acl/classes/controller/frontend/lecturers.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Lecturers extends Controller_Frontend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = 'layouts/acl') { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } public function action_index() { //TODO CARD of the USER } public function action_show() { $lecturer_id = $this->request->param('lecturer_id',NULL); $lecturer = new Model_Lecturer(); if ($lecturer_id) { $lecturer = Model::fly('Model_Lecturer')->find($lecturer_id); } if ( ! isset($lecturer->id)) { $this->_action_404('Указанный лектор не найден'); return; } $view = new View('frontend/workspace'); $view->content = $this->widget_lecturer($lecturer); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Redraw lecturer images widget via ajax request */ public function action_ajax_lecturer_images() { $request = Widget::switch_context(); $lecturer_id = $request->param('lecturer_id',NULL); $lecturer = Model::fly('Model_Lecturer')->find($lecturer_id); if ( ! isset($lecturer->id)) { FlashMessages::add('Лектор не найден', FlashMessages::ERROR); $this->_action_ajax(); return; } $widget = $request->get_controller('lecturers') ->widget_lecturer_images($lecturer); $widget->to_response($this->request); $this->_action_ajax(); } /** * Renders lecturer settings * * @param boolean $select * @return string */ public function widget_lecturer($lecturer,$view = 'frontend/lecturer') { // Set up view $view = new View($view); $view->lecturer = $lecturer; return $view->render(); } /** * Render images for lecturer (when in lecturer profile) * * @param Model_Lecturer $lecturer * @return Widget */ public function widget_lecturer_images(Model_Lecturer $lecturer) { $widget = new Widget('frontend/lecturers/lecturer_images'); $widget->id = 'lecturer_' . $lecturer->id . '_images'; $widget->ajax_uri = URL::uri_to('frontend/acl/lecturer/images'); $widget->context_uri = FALSE; // use the url of clicked link as a context url $images = Model::fly('Model_Image')->find_all_by_owner_type_and_owner_id('lecturer', $lecturer->id, array( 'order_by' => 'position', 'desc' => FALSE )); if ($images->valid()) { $image_id = (int) $this->request->param('image_id'); if ( ! isset($images[$image_id])) { $image_id = $images->at(0)->id; } $widget->image_id = $image_id; // id of current image $widget->images = $images; $widget->lecturer = $lecturer; } return $widget; } /** * Renders list of lecturers * * @return string Html */ public function widget_lecturers() { $lecturer = new Model_Lecturer(); $order_by = $this->request->param('acl_lorder', 'id'); $desc = (bool) $this->request->param('acl_ldesc', '0'); $per_page = 20; // Select all users $count = $lecturer->count(); $pagination = new Paginator($count, $per_page); $lecturers = $lecturer->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); $view = new View('frontend/lecturers'); $view->order_by = $order_by; $view->desc = $desc; $view->lecturers = $lecturers; $view->pagination = $pagination->render('pagination'); return $view->render(); } /** * Renders list of lecturers for lecturer-select dialog * * @return string Html */ public function widget_lecturer_select($view_script = 'frontend/lecturer_select',array $ids = NULL) { $lecturer = new Model_Lecturer(); $order_by = $this->request->param('acl_lorder', 'id'); $desc = (bool) $this->request->param('acl_ldesc', '0'); $conditions = array(); if (!empty($ids)) { $conditions['ids'] = $ids; } $per_page = 5; // Select all lecturers $count = $lecturer->count(); $pagination = new Paginator($count, $per_page); $lecturers = $lecturer->find_all_by($conditions,array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); $view = new View($view_script); $view->order_by = $order_by; $view->desc = $desc; $view->lecturers = $lecturers; $view->pagination = $pagination->render('pagination_small'); Layout::instance()->add_style(Modules::uri('acl') . '/public/css/frontend/acl.css'); return $view->render(); } /** * Renders list of lecturers for lecturer-select dialog * * @return string Html */ public function widget_lecturer_select_form($view_script = 'frontend/lecturer_select') { $lecturer = new Model_Lecturer(); $order_by = $this->request->param('acl_lorder', 'id'); $desc = (bool) $this->request->param('acl_ldesc', '0'); $per_page = 20; // Select all lecturers $count = $lecturer->count(); $pagination = new Paginator($count, $per_page); $lecturers = $lecturer->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); $view = new View($view_script); $view->order_by = $order_by; $view->desc = $desc; $view->lecturers = $lecturers; $view->pagination = $pagination->render('pagination'); return $view->render(); } /** * Display autocomplete options for a postcode form field */ public function action_ac_lecturer_name() { $lecturer_name = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $lecturer_name = UTF8::str_ireplace("ё", "е", $lecturer_name); if ($lecturer_name == '') { $this->request->response = ''; return; } $limit = 7; $lecturers = Model::fly('Model_Lecturer')->find_all_like_name($lecturer_name,array('limit' => $limit)); // if ( ! count($lecturers)) // { // $this->request->response = ''; // return; // } $items = array(); $pattern = new View('frontend/lecturer_ac'); $i=0; foreach ($lecturers as $lecturer) { $name = $lecturer->name; $id = $lecturer->id; $image_info = $lecturer->image(4); $pattern->name = $name; $pattern->image_info = $lecturer->image(4); $pattern->num = $i; $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name, 'id' => $id) ); $i++; } $items[] = array('caption' => '<a data-toggle="modal" href="#LectorModal" class="active">Добавить нового лектора</a>'); $this->request->response = json_encode($items); } /** * Add breadcrumbs for current action */ public function add_breadcrumbs(array $request_params = array()) { if (empty($request_params)) { list($name, $request_params) = URL::match(Request::current()->uri); } if ($request_params['action'] == 'show') { Breadcrumbs::append(array( 'uri' => URL::uri_to('frontend/acl/lecturers',array('action' => 'show','lecturer_id' => $request_params['lecturer_id'])), 'caption' => 'Лектор')); } } } <file_sep>/modules/shop/catalog/views/backend/sections/select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // ----- Set up urls // Submit results to previous url $sections_select_uri = URL::uri_back(); ?> <?php echo View_Helper_Admin::multi_action_form_open($sections_select_uri, array('name' => 'sections_select')); echo Form_Helper::hidden('sectiongroup_id', $sectiongroup_id); ?> <table class="sections_select table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'caption' => 'Название', 'section_active' => 'Акт.', ); echo View_Helper_Admin::table_header($columns, 'cat_sorder', 'cat_sdesc'); ?> </tr> <?php foreach ($sections as $section) : if ( ! $section->section_active) { $active = 'capt_inactive'; } elseif ( ! $section->active) { $active = 'inactive'; } else { $active = ''; } ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($section->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'caption': echo '<td>' . ' <div style="padding-left: ' . ($section->level-1)*15 . 'px">' . ' <div class="capt ' . $active . '">' . HTML::chars($section->$field) . ' </div>' . ' </div>' . '</td>'; break; case 'section_active': echo '<td class="c">'; if ( ! empty($section->$field)) { echo View_Helper_Admin::image('controls/on.gif', 'Да'); } else { echo View_Helper_Admin::image('controls/off.gif', 'Нет'); } echo '</td>'; break; default: echo '<td>'; if (isset($section->$field) && trim($section->$field) !== '') { echo HTML::chars($section[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> </tr> <?php endforeach; ?> </table> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'sections_select', 'label' => 'Выбрать', 'class' => 'button_select') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/acl/views/frontend/users/profedit.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="wrapper main-list"> Изменение информации: <?php echo $form->render_form_open();?> <table> <tr><td><label for="pass">Имя</label></td><td><?php echo $form->get_element('first_name')->render_input(); ?></td></tr> <tr><td><label for="organizer_name">Фамилия</label></td><td><?php echo $form->get_element('last_name')->render_input(); ?></td></tr> <tr><td><label for="pass">Пароль</label></td><td><?php echo $form->get_element('password')->render_input(); ?></td></tr> <tr><td><label for="email">Емаил</label></td><td><?php echo $form->get_element('email')->render_input(); ?></td></tr> <tr><td><label for="town_id">Город</label></td><td><?php echo $form->get_element('town_id')->render_input(); ?></td></tr> <tr><td><label for="organizer_name">Организация</label></td><td><?php echo $form->get_element('organizer_name')->render_input(); ?></td></tr> <tr><td><label for="email">О себе</label></td><td><?php echo $form->get_element('info')->render_input(); ?></td></tr> <tr><td><?php echo $form->get_element('submit_register')->render_input(); ?></td></tr> </table> <?php echo $form->render_form_close();?> </div> <file_sep>/modules/shop/catalog/classes/model/section.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Section extends Model { const EVENT_ID = 1; /** * Get currently selected section for the specified request using the value of * corresponding parameter in the uri * * @param Request $request (if NULL, current request will be used) * @return Model_Section */ public static function current(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } // cache? $section = $request->get_value('section'); if ($section !== NULL) return $section; $section = new Model_Section(); if (APP == 'BACKEND') { $id = (int) $request->param('cat_section_id'); if ($id > 0) { $section->find_by_id_and_site_id($id, Model_Site::current()->id); } } elseif (APP == 'FRONTEND') { $section = Model::fly('Model_Section')->find(Model_Section::EVENT_ID); } $request->set_value('section', $section); return $section; } /** * Backup model before saving * @var boolean */ public $backup = array('parent_id'); /** * Find all active sections for given sectiongroup * * @param integer $sectiongroup_id * @param boolean $load_if_missed * @return ModelsTree_NestedSet */ public function find_all_active_cached($sectiongroup_id, $load_if_missed = TRUE) { static $cache; if ( ! isset($cache[$sectiongroup_id])) { if ($load_if_missed) { $cache[$sectiongroup_id] = $this->find_all_by_active_and_sectiongroup_id(1, $sectiongroup_id, array( 'order_by' => 'caption', 'desc' => FALSE, 'columns' => array('id', 'sectiongroup_id', 'alias', 'lft', 'rgt', 'level', 'caption', 'products_count'), 'as_tree' => TRUE, 'with_sectiongroup_name' => TRUE, 'with_images' => TRUE, // //'with_active_products_count' => TRUE )); } else { return NULL; } } return $cache[$sectiongroup_id]; } /** * Get frontend uri to the section */ public function uri_frontend($with_base = FALSE) { if ($with_base) { $uri_template = URL::to('frontend/catalog/products', array( 'sectiongroup_name' => '{{sectiongroup_name}}', 'path' => '{{path}}' )); } else { $uri_template = URL::uri_to('frontend/catalog/products', array( 'sectiongroup_name' => '{{sectiongroup_name}}', 'path' => '{{path}}' )); } return str_replace( array('{{sectiongroup_name}}', '{{path}}'), array($this->sectiongroup_name, $this->full_alias), $uri_template ); } /** * Section is active by default * * @return boolean */ public function default_section_active() { return TRUE; } /** * Make alias for section from it's caption * * @return string */ public function make_alias() { $caption_alias = str_replace(' ', '_', strtolower(l10n::transliterate($this->caption))); $caption_alias = preg_replace('/[^a-z0-9_-]/', '', $caption_alias); $i = 0; $loop_prevention = 1000; do { if ($i > 0) { $alias = substr($caption_alias, 0, 30); $alias .= $i; } else { $alias = substr($caption_alias, 0, 31); } $i++; if ($this->level == 1) { $exists = $this->exists_another_by_alias_and_level($alias, 1); } else { $exists = $this->exists_another_by_alias_and_parent($alias, $this->parent); } } while ($exists && ($loop_prevention-- > 0)); if ($loop_prevention <= 0) throw new Kohana_Exception ('Possible infinite loop in :method', array(':method' => __METHOD__)); return $alias; } /** * Get full alias to this section by concatinating aliases of parent sectoins * * @param string $glue * @return string */ public function get_full_alias($glue = '/') { if ( ! isset($this->_properties['full_alias'])) { $sections = $this->find_all_active_cached($this->sectiongroup_id, FALSE); if ($sections !== NULL) { // Obtain parents from cached version of sections tree $parents = $sections->parents($this, TRUE); } else { // Get parents from database $parents = $this->get_parents(array('columns' => array('id', 'alias'), 'as_array' => TRUE)); } $full_alias = ''; foreach ($parents as $parent) { $full_alias .= $parent['alias'] . $glue; } $full_alias .= $this->alias; $this->_properties['full_alias'] = $full_alias; } return $this->_properties['full_alias']; } /** * Returns the first not empty description of section or it parents * * @return string */ public function get_full_description() { // get section description $section_description = ''; foreach ($this->parents as $par) { if ($par->description != '') { $section_description = $par->description; if ($par->image != '') { $section_description = HTML::image('public/data/' . $par->image, array( 'width' => $par->image_width, 'height' => $par->image_height, 'alt' => $par->caption )) . $section_description; } } } if ($section_description == '') { $section_description = $this->description; if ($section_description != '') { if ($this->image != '') { $section_description = HTML::image('public/data/' . $this->image, array( 'width' => $this->image_width, 'height' => $this->image_height, 'alt' => $this->caption )) . $section_description; } } } return $section_description; } /** * Get sectiongroup name for this section * * @return string */ public function get_sectiongroup_name() { if ( ! isset($this->_properties['sectiongroup_name'])) { $sectiongroups = Model::fly('Model_SectionGroup')->find_all_cached(); $this->_properties['sectiongroup_name'] = $sectiongroups[$this->sectiongroup_id]->name; } return $this->_properties['sectiongroup_name']; } /** * Finds a parent section id for this section * * @return Model_Section */ public function get_parent_id() { if ( ! isset($this->_properties['parent_id'])) { $this->_properties['parent_id'] = $this->parent->id; } return $this->_properties['parent_id']; } /** * Find a parent section * * @param array $params * @return Model_Section */ public function get_parent(array $params = NULL) { if ( ! isset($this->_properties['parent'])) { if (isset($this->_properties['parent_id'])) { $this->_properties['parent'] = new Model_Section; $this->_properties['parent']->find($this->_properties['parent_id'], $params); } else { $this->_properties['parent'] = $this->mapper()->find_parent($this, $params); } } return $this->_properties['parent']; } /** * Get all parents for this section * * @return Models */ public function get_parents(array $params = NULL) { if ( ! isset($this->_properties['parents'])) { $this->_properties['parents'] = $this->mapper()->find_all_parents($this, $params); } return $this->_properties['parents']; } /** * Construct full caption of this section - concatenated caption of all parent sections * * @param string $delimeter * @return string */ public function get_full_caption($delimeter = '&nbsp;&raquo;&nbsp;') { //@fixme: This can be accomplished by a single sql request with group_concat $parents = $this->get_parents(array( 'order_by' => 'level', 'desc' => FALSE, 'columns' => array('caption') )); $caption = ''; foreach ($parents as $parent) { $caption .= HTML::chars($parent->caption) . $delimeter; } $caption .= HTML::chars($this->caption); return $caption; } /** * Get property-section infos * * @return Models */ public function get_propertysections() { if ( ! isset($this->_properties['propertysections'])) { $this->_properties['propertysections'] = Model::fly('Model_PropertySection')->find_all_by_section($this, array('order_by' => 'position', 'desc' => FALSE)); } return $this->_properties['propertysections']; } /** * Get property-section infos as array for form * * @return array */ public function get_propsections() { if ( ! isset($this->_properties['propsections'])) { $result = array(); foreach ($this->propertysections as $propsection) { $result[$propsection->property_id]['active'] = $propsection->active; $result[$propsection->property_id]['filter'] = $propsection->filter; $result[$propsection->property_id]['sort'] = $propsection->sort; } $this->_properties['propsections'] = $result; } return $this->_properties['propsections']; } /** * Set property-section link info (usually from form - so we need to add 'section_id' field) * * @param array $propsections */ public function set_propsections(array $propsections) { foreach ($propsections as $property_id => & $propsection) { if ( ! isset($propsection['property_id'])) { $propsection['property_id'] = $property_id; } } $this->_properties['propsections'] = $propsections; } /** * Save section and link it to selected properties * * @param boolean $force_create * @param boolen $link_properties * @param boolean $update_stats */ public function save($force_create = FALSE, $link_properties = TRUE, $update_stats = TRUE) { // Create alias from caption $this->alias = $this->make_alias(); parent::save($force_create); if ($link_properties) { // Link section to the properties Model::fly('Model_PropertySection')->link_section_to_properties($this, $this->propsections); } if ($this->parent_id !== $this->previous()->parent_id) { // Section is moved to the new parent, we need to relink all products in section Model::fly('Model_Product')->relink($this); } if ($update_stats) { $this->mapper()->update_activity(array($this->id)); $this->mapper()->update_products_count(array($this->id, $this->parent_id, $this->previous()->parent_id)); } } /** * Validate product deletion * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { // Create COMDI event if (Model_Product::COMDI === TRUE) { // Delete products from all subsections $subsections = $this->mapper()->find_all_with_subtree($this,array('as_list' => TRUE)); $deleted = array(); $not_deleted = array(); foreach ($subsections as $subsection) { $loop_prevention = 10000; do { $products = Model::fly('Model_Product')->find_all_by_section_id($subsection->id, array( 'batch' => 100 )); foreach ($products as $product) { $bool = $product->validate_delete(); if ($bool === TRUE) { $deleted[] = $product; } else { $not_deleted[] = $product; } } $loop_prevention--; } while (count($products) && $loop_prevention > 0); if ($loop_prevention <= 0) { throw new Kohana_Exception('Possibly an infinte loop while deleting section'); } } foreach ($not_deleted as $nd) { $this->error('Не удается удалить COMDI-event для события '.$nd->caption.' ID = '.$nd->id); } } return parent::validate_delete($newvalues); /* // Create COMDI event if (Model_Product::COMDI === TRUE) { // Delete products from all subsections $subsections = $this->mapper()->find_all_subtree($this,array('as_list' => TRUE)); $deleted = array(); $repair_flag = FALSE; $stopper = FALSE; foreach ($subsections as $subsection) { $loop_prevention = 10000; $bool = true; do { $products = $this->find_all_by_section_id($section_id, array( 'columns' => array('id'), 'batch' => 100 )); foreach ($products as $product) { $bool = $bool & $product->validate_delete(); if ($bool ===TRUE) { $deleted[] = $product; } else { $repair_flag = TRUE; $stopper = $product; break; } } $loop_prevention--; } while (count($products) && $loop_prevention > 0 && !$repair_flag); if ($loop_prevention <= 0) { throw new Kohana_Exception('Possibly an infinte loop while deleting section'); } if ($repair_flag) break; } if ($repair_flag) { foreach ($deleted as $del_product) { $event_id = TaskManager::start('comdi_create', Task_Comdi_Base::mapping($del_product->values())); if ($event_id === NULL) { $this->error('Сервис COMDI временно не работает!'); return FALSE; } $del_product->event_id = $event_id; $del_product->save(); } if (empty($deleted)) { $this->error('Сервис COMDI временно не работает!'); return FALSE; } else { $this->error('Не удается удалить COMDI-event для события '.$stopper->caption); return FALSE; } } } return parent::validate_delete($newvalues);*/ } /** * Delete section with all subsections and products */ public function delete() { // Delete products from all subsections $subsections = $this->mapper()->find_all_subtree($this,array('as_list' => TRUE)); foreach ($subsections as $subsection) { Model::fly('Model_Product')->delete_all_by_section_id($subsection->id); // Delete section logo Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('section', $subsection->id); // Unlink products from section Model::fly('Model_Product')->unlink_all_from_section($subsection); } // Delete products from this section Model::fly('Model_Product')->delete_all_by_section_id($this->id); // Delete section logo Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('section', $this->id); //@TODO: Unlink properties from section and all subsections // Unlink products from section Model::fly('Model_Product')->unlink_all_from_section($this); $parent_id = $this->parent_id; // Delete section and subsections $this->mapper()->delete_with_subtree($this); // Update products count for all parent sections if ( ! empty($parent_id)) { $this->mapper()->update_products_count(array($parent_id)); } } }<file_sep>/modules/shop/countries/classes/model/country.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Country extends Model { /** * Default country id * * @return integer */ public static function default_country_id() { //@TODO return 1; } }<file_sep>/modules/shop/acl/classes/model/token.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Token extends Model { const TYPE_LOGIN = 1; // A token used to login user via cookie const TYPE_PASSWORD = 2; // A token user to recover password const LOGIN_LIFETIME = 604800; // Auto-login token is valid for 7 days const PASSWORD_LIFETIME = 172800; // Password recovery token is valid for two days /** * Default token type * * @return integer */ public function default_type() { return Model_Token::TYPE_LOGIN; } /** * Default expiration time for token * * @return integer */ public function default_expires_at() { switch ($this->type) { case Model_Token::TYPE_LOGIN: return time() + Model_Token::LOGIN_LIFETIME; break; case Model_Token::TYPE_PASSWORD: return time() + Model_Token::PASSWORD_LIFETIME; break; default: throw new Kohana_Exception('Unable to get default expiration time: invalid or not defined token type'); } } }<file_sep>/modules/system/forms/classes/form/validator/datetimesimple.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validate dates and times * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_DateTimeSimple extends Form_Validator { const EMPTY_STRING = 'EMPTY_STRING'; const INVALID_DAY = 'INVALID_DAY'; const INVALID_MONTH = 'INVALID_MONTH'; const INVALID_YEAR = 'INVALID_YEAR'; const INVALID_SECOND = 'INVALID_SECOND'; const INVALID_MINUTE = 'INVALID_MINUTE'; const INVALID_HOUR = 'INVALID_HOUR'; const INVALID = 'INVALID'; protected $_messages = array( self::EMPTY_STRING => 'Вы не указали дату', self::INVALID_DAY => 'День указан некорректно', self::INVALID_MONTH => 'Месяц указан некорректно', self::INVALID_YEAR => 'Год указан некорректно', self::INVALID_SECOND => 'Секунда указана некорректно', self::INVALID_MINUTE => 'Минута указана некорректно', self::INVALID_HOUR => 'Час указан некорректно', self::INVALID => 'Некорректный формат' ); /** * Allow date to be empty * @var boolean */ protected $_allow_empty = FALSE; /** * Creates validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty dates */ public function __construct(array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE) { parent::__construct($messages, $breaks_chain); $this->_allow_empty = $allow_empty; } /** * Validate. * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { // ----- Validate date string agains a format $value = (string)$this->_value; // An empty string allowed ? if (preg_match('/^\s*$/', $value)) { if (!$this->_allow_empty) { $this->_error(self::EMPTY_STRING); return FALSE; } else { return TRUE; } } $regexp = l10n::date_format_regexp($this->get_form_element()->format); if ( ! preg_match($regexp, $value, $matches)) { $this->_error(self::INVALID); return FALSE; } if (isset($matches['day'])) { $v = $matches['day']; if ( ! ctype_digit($v) || (int)$v <= 0 || (int)$v > 31) { $this->_error(self::INVALID_DAY); return FALSE; } } if (isset($matches['month'])) { $v = $matches['month']; if ( ! ctype_digit($v) || (int)$v <= 0 || (int)$v > 12) { $this->_error(self::INVALID_MONTH); return FALSE; } } if (isset($matches['year'])) { $v = $matches['year']; if ( ! ctype_digit($v) || (int)$v <= 0) { $this->_error(self::INVALID_YEAR); return FALSE; } } if (isset($matches['second'])) { $v = $matches['second']; if ( ! ctype_digit($v) || (int)$v < 0 || (int)$v >= 60) { $this->_error(self::INVALID_SECOND); return FALSE; } } if (isset($matches['minute'])) { $v = $matches['minute']; if ( ! ctype_digit($v) || (int)$v < 0 || (int)$v >= 60) { $this->_error(self::INVALID_MINUTE); return FALSE; } } if (isset($matches['hour'])) { $v = $matches['hour']; if ( ! ctype_digit($v) || (int)$v < 0 || (int)$v >= 24) { $this->_error(self::INVALID_HOUR); return FALSE; } } return TRUE; } }<file_sep>/modules/shop/countries/classes/model/postoffice.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PostOffice extends Model { /** * Get region name for the postoffice * If region name is the same as the city name (Москва, ...) than it returns '' * * @return string */ public function get_region_name() { $region_name = isset($this->_properties['region_name']) ? $this->_properties['region_name'] : ''; if ($region_name == $this->city) { return ''; } else { return $region_name; } } /** * Import list of post offices from an uploaded file * * @param array $uploaded_file */ public function import(array $uploaded_file) { // Increase php script time limit. set_time_limit(480); try { // Move uploaded file to temp location $tmp_file = File::upload($uploaded_file); if ($tmp_file === FALSE) { $this->error('Failed to upload a file'); return; } $country_id = Model_Country::default_country_id(); $region = Model::fly('Model_Region'); $postoffice = Model::fly('Model_PostOffice'); // hash region ids to save one db query $region_hash = array(); // Read file (assuming a UTF-8 encoded csv format) $delimiter = ','; $enclosure = '"'; $h = fopen($tmp_file, 'r'); $first_line = true; while ($fields = fgetcsv($h, NULL, $delimiter, $enclosure)) { if ($first_line) { // Skip first header line $first_line = false; continue; } if (count($fields) < 11) { $this->error('Invalid file format. Expected 11 columns in a row, but ' . count($field) . ' found'); return; } // Regions: insert new or find existing $region_name = UTF8::strtolower(trim($fields[4])); if (isset($region_hash[$region_name])) { $region_id = $region_hash[$region_name]; } else { $region->find_by_name($region_name); if ($region->id === NULL) { // Region with given name not found - create a new one $region->country_id = $country_id; $region->name = $region_name; $region->save(); } $region_id = $region->id; $region_hash[$region_name] = $region_id; } // Fields $name = UTF8::strtolower(trim($fields[1])); $city = UTF8::strtolower(trim($fields[7])); if ($city == '') { // City of federal importance $city = $region_name; } $postcode = UTF8::strtolower(trim($fields[0])); // Does the post office with given postcode already exist? $postoffice->find_by_postcode($postcode); if ( ! isset($postoffice->id)) { // Insert new post office $postoffice->init(array( 'country_id' => $country_id, 'region_id' => $region_id, 'name' => $name, 'city' => $city, 'postcode' => $postcode )); $postoffice->save(); } } fclose($h); @unlink($tmp_file); } catch (Exception $e) { // Shit happened if (Kohana::$environment === Kohana::DEVELOPMENT) { throw $e; } else { $this->error($e->getMessage()); } } } }<file_sep>/application/classes/money.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Money * * @package Eresus * @author <NAME> (<EMAIL>) */ class Money { /** * Power of the smallest fraction (i.e рубль = 100 копеек) */ const FRACTION = 100; /** * @var float */ protected $_amount; /** * Construct money * * @param float $amount */ public function __construct($amount = 0.0) { $this->set_amount($amount); } /** * Set amount from floating point number * * @param float|string $amount */ public function set_amount($amount) { if (is_string($amount)) { $amount = l10n::string_to_float($amount); } $this->_amount = round($amount * Money::FRACTION); } /** * Get money amount as floating point number * * @return float */ public function get_amount() { return $this->_amount / Money::FRACTION; } /** * Specify the intrenal amount value explicitly (for example when retrieving value from db) * * @param float $raw_amount */ public function set_raw_amount($raw_amount) { $this->_amount = $raw_amount; } /** * Get internal amount value (for example to store in db) * * @return float */ public function get_raw_amount() { return $this->_amount; } // ------------------------------------------------------------------------- // Arthmetic operations // ------------------------------------------------------------------------- /** * Add money * * @param Money|float $amount * @return Money */ public function add($amount) { if ($amount instanceof Money) { $this->_amount += $amount->get_raw_amount(); } else { $this->_amount = round($this->_amount + $amount * Money::FRACTION); } return $this; } /** * Sub money * * @param Money|float $amount * @return Money */ public function sub($amount) { if ($amount instanceof Money) { $this->_amount -= $amount->get_raw_amount(); } else { $this->_amount = round($this->_amount - $amount * Money::FRACTION); } return $this; } /** * Multiply amount * * @param float $v * @return Money */ public function mul($v) { $this->_amount = round($this->_amount * $v); return $this; } // ------------------------------------------------------------------------- // Comparisions // ------------------------------------------------------------------------- /** * Equal * * @param Money $money * @return boolean */ public function eq(Money $money) { return ($this->get_raw_amount() == $money->get_raw_amount()); } /** * Greater than * * @param Money $money * @return boolean */ public function gt(Money $money) { return ($this->get_raw_amount() > $money->get_raw_amount()); } /** * Greater than or equal to * * @param Money $money * @return boolean */ public function ge(Money $money) { return ($this->get_raw_amount() >= $money->get_raw_amount()); } /** * Less than * * @param Money $money * @return boolean */ public function lt(Money $money) { return ($this->get_raw_amount() < $money->get_raw_amount()); } /** * Less than or equal to * * @param Money $money * @return boolean */ public function le(Money $money) { return ($this->get_raw_amount() <= $money->get_raw_amount()); } /** * Not zero * * @return boolean */ public function nz() { return $this->get_raw_amount() > 0; } // ------------------------------------------------------------------------- // String representation // ------------------------------------------------------------------------- /** * Format money to a string * * @return string */ public function format() { return sprintf("%.2f", $this->amount) . ' руб.'; } // ------------------------------------------------------------------------- // Magic methods // ------------------------------------------------------------------------- public function __toString() { return $this->format(); } public function __set($name, $value) { $setter = 'set_' . strtolower($name); if (method_exists($this, $setter)) { $this->$setter($value); } else { throw new Kohana_Exception('Unknown property :name', array(':name' => $name)); } } public function __get($name) { $getter = 'get_' . strtolower($name); if (method_exists($this, $getter)) { return $this->$getter(); } else { throw new Kohana_Exception('Unknown property :name', array(':name' => $name)); } } }<file_sep>/application/i18n/ru.php <?php defined('SYSPATH') or die('No direct script access.'); return array( 'Not Found' => 'Страница не найдена', 'Internal Server Error' => 'Произошла ошибка' );<file_sep>/modules/general/tags/classes/controller/backend/tags.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Tags extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Tag'; $this->_form = 'Form_Backend_Tag'; return array( 'create' => array( 'view_caption' => 'Создание тега' ), 'update' => array( 'view_caption' => 'Редактирование тега' ), 'delete' => array( 'view_caption' => 'Удаление тега', 'message' => 'Удалить тег?' ) ); } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->caption = 'Теги'; $layout->content = $view; return $layout->render(); } /** * Prepare tag for update & delete actions * * @param string $action * @param string|Model $model * @param array $params * @return Model_Tag */ protected function _model($action, $model, array $params = NULL) { $tag = parent::_model($action, $model, $params); if ($action == 'create') { // Set up onwer for tag being created $tag->owner_type = $this->request->param('owner_type'); $tag->owner_id = $this->request->param('owner_id'); } // Set up config for tag in action $tag->config = $this->request->param('config'); return $tag; } /** * Display autocomplete options for a postcode form field */ public function action_ac_tag() { $tag = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; if ($tag == '') { $this->request->response = ''; return; } $limit = 7; $tags = Model::fly('Model_Tag')->find_all_like_name($tag,array('limit' => $limit)); if ( ! count($tags)) { $this->request->response = ''; return; } $items = array(); $pattern = new View('backend/tag_ac'); $num=0; foreach ($tags as $tag) { $name = $tag->name; $pattern->name = $name; $pattern->num = $num; $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name) ); $num++; } $this->request->response = json_encode($items); } /** * Renders list of tags for specified owner * * @param string $owner_type * @param integer $owner_id * @return string */ public function widget_tags($owner_type, $owner_id, $config) { // Add styles to layout Layout::instance()->add_style(Modules::uri('tags') . '/public/css/backend/tags.css'); $order_by = $this->request->param('tag_order_by', 'position'); $desc = (boolean) $this->request->param('tag_desc', '0'); $tags = Model::fly('Model_Tag')->find_all_by_owner_type_and_owner_id( $owner_type, $owner_id, array('order_by' => $order_by, 'desc' => $desc) ); $view = new View('backend/tags'); $view->tags = $tags; $view->owner_type = $owner_type; $view->owner_id = $owner_id; $view->config = $config; $view->desc = $desc; return $view; } }<file_sep>/modules/shop/orders/classes/controller/backend/ordercomments.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_OrderComments extends Controller_BackendCRUD { /** * Configure actions * * @return array */ public function setup_actions() { $this->_model = 'Model_OrderComment'; $this->_form = 'Form_Backend_OrderComment'; $this->_view = 'backend/form'; return array( 'create' => array( 'view_caption' => 'Создание комментария к заказу № :order_id' ), 'update' => array( 'view_caption' => 'Редактирование комментария к заказу' ), 'delete' => array( 'view_caption' => 'Удаление комментария к заказу', 'message' => 'Удалить комментарий к заказу № :order_id?' ) ); } /** * Create layout (proxy to orders controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('orders')->prepare_layout($layout_script); } /** * Render layout (proxy to orders controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('orders')->render_layout($content, $layout_script); } /** * Prepare ordercomment model for create action * * @param string|Model_OrderComment $ordercomment * @param array $params * @return Model_OrderComment */ protected function _model_create($ordercomment, array $params = NULL) { $ordercomment = parent::_model('create', $ordercomment, $params); $order_id = (int) $this->request->param('order_id'); if ( ! Model::fly('Model_Order')->exists_by_id($order_id)) { throw new Controller_BackendCRUD_Exception('Указанный заказ не существует!'); } $ordercomment->order_id = $order_id; return $ordercomment; } /** * Renders list of order comments * * @param Model_Order $order * @return string */ public function widget_ordercomments($order) { $ordercomments = $order->comments; // Set up view $view = new View('backend/ordercomments'); $view->order = $order; $view->ordercomments = $ordercomments; return $view->render(); } }<file_sep>/modules/system/forms/classes/form/validator/checkselect.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validates that check select values are among allowed options * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_CheckSelect extends Form_Validator { const INVALID_TYPE = 'INVALID_TYPE'; const INVALID = 'INVALID'; protected $_messages = array( self::INVALID_TYPE => 'Invalid value. Array is expected', self::INVALID => 'Поле ":label" имеет некорректное значение!' ); /** * List of valid options for value * @var array */ protected $_options = array(); /** * Creates validator * * @param array $options List of valid options * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure */ public function __construct(array $options, array $messages = NULL, $breaks_chain = TRUE) { $this->_options = $options; parent::__construct($messages, $breaks_chain); } /** * Set up options for validator * * @param array $options */ public function set_options(array $options) { $this->_options = $options; } /** * Validate that value is among valid options * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { if ( ! is_array($this->_value)) { $this->_error(self::INVALID_TYPE); return FALSE; } if (count(array_diff(array_keys($this->_value), $this->_options))) { // There are some options in value that a not among valid $options $this->_error(self::INVALID); return FALSE; } return TRUE; } }<file_sep>/modules/general/twig/classes/twig.php <?php defined('SYSPATH') or die('No direct script access.'); class Twig { /** * @var array Twig_Environment */ protected static $_twigs = array(); protected static $_initialized = FALSE; /** * Setup twig template engine * * @return Twig_Environment */ public static function instance($loader_class = 'kohana') { if ( ! isset(self::$_twigs[$loader_class])) { self::init(); $loader = 'Twig_Loader_' . ucfirst($loader_class); $loader = new $loader(); self::$_twigs[$loader_class] = new Twig_Environment($loader, array( 'debug' => (Kohana::$environment !== Kohana::PRODUCTION), 'cache' => APPPATH.'cache/twig' )); } return self::$_twigs[$loader_class]; } /** * Setup twig autoloaders */ public static function init() { if ( ! self::$_initialized) { require_once Modules::path('twig') . '/lib/Twig/Autoloader.php'; Twig_Autoloader::register(); self::$_initialized = TRUE; } } protected function __construct() { // This is a static class } }<file_sep>/modules/general/flash/classes/controller/backend/flashblocks.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Flashblocks extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Flashblock'; $this->_form = 'Form_Backend_Flashblock'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание flash блока' ), 'update' => array( 'view_caption' => 'Редактирование flash блока ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление flash блока', 'message' => 'Удалить flash блок ":caption"?' ) ); } /** * @return boolean */ public function before() { if ( ! parent::before()) { return FALSE; } // Check that there is a site selected if (Model_Site::current()->id === NULL) { $this->_action_error('Выберите сайт для работы с flash блоками!'); return FALSE; } return TRUE; } /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Default action */ public function action_index() { $this->request->response = $this->render_layout($this->widget_flashblocks()); } /** * Renders blocks list * * @return string */ public function widget_flashblocks() { $site_id = (int) Model_Site::current()->id; $flashblock = new Model_Flashblock(); $order_by = $this->request->param('flashblocks_order', 'position'); $desc = (bool) $this->request->param('flashblocks_desc', '0'); // Select all menus for current site $flashblocks = $flashblock->find_all_by_site_id($site_id, array('order_by' => $order_by, 'desc' => $desc)); // Set up view $view = new View('backend/flashblocks'); $view->order_by = $order_by; $view->desc = $desc; $view->flashblocks = $flashblocks; return $view; } } <file_sep>/modules/shop/catalog/public/js/frontend/product-create.js $(function(){ $('#parsing-fill-btn').click(function(){ var url = prompt('Введите адрес страницы события для автоматического заполенния полей.\n\nВсе поля будут заполнены автоматически, кроме полей "лектор"и "площадка"'); if(url != null) { var data = praseUrl(url); } return false; }); $('#id-product1').xtautosave(); }); function praseUrl(url) { $.ajax({ 'dataType': "json", 'method': 'post', 'url': 'ajax_parsing', 'data': {'parseurl': url}, 'success': function(response, textStatus, jqXHR ){ if(response.data.status == 'notsupported') { alert('Данный сайт не поддерживается!'); } else { var eventData = response.data.event; var fullDesc = eventData.desc + "\n\nАнонс с "+url; $('#id-product1-caption').val(eventData.title); $('#id-product1-datetime').val(eventData.time); $('#image_url').val(eventData.image_url); $("#id-product1-format option").filter(function() { return $(this).text() == eventData.format; }).prop('selected', true); //$('#id-product1-description').val(fullDesc); tinyMCE.activeEditor.setContent(fullDesc); // Set invalid fields $('#lecturer_name').addClass('invalid'); $('#place_name').addClass('invalid'); $('#id-product1-duration').removeClass('valid').addClass('invalid'); $('#id-product1-theme').removeClass('valid').addClass('invalid'); // Set photo var fileElem = $('#prev_id-product1-file'); fileElem.html('&nbsp Новое фото '); $('<img />').css('margin-top', '10px').addClass('prev_thumb').attr('src',eventData.image_url).appendTo(fileElem); } }, 'error': function(jqXHR, textStatus, errorThrown ){ alert('Произошла ошибка!'); } }); }<file_sep>/modules/shop/sites/views/backend/sites_menu.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php Layout::instance()->add_style(Modules::uri('sites') . '/public/css/backend/sites.css'); $site_url = URL::to('backend', array('site_id'=>'{{id}}')); ?> <div class="sites_menu"> <?php foreach ($sites as $site) { $_site_url = str_replace('{{id}}', $site->id, $site_url); if ($site->id == $current->id) { // Highlight current site echo '<a href="' . $_site_url . '" class="selected">' . $site->caption . '</a>'; } else { echo '<a href="' . $_site_url . '">' . $site->caption . '</a>'; } } ?> </div> <file_sep>/modules/shop/catalog/classes/task/import/pricelist.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Import pricelist */ class Task_Import_Pricelist extends Task { /** * Run the task */ public function run() { $this->set_progress(0); $supplier = (int) $this->param('supplier'); if ( ! array_key_exists($supplier, Model_Product::suppliers())) { $this->log('Указан неверный поставщик', Log::ERROR); return; } $file = $this->param('file'); if ( ! is_readable($file)) { $this->log('Не удалось прочитать файл "' . $file . '"', Log::ERROR); return; } $this->set_status_info('Reading xls file...'); $reader = XLS::reader(); $reader->setOutputEncoding('UTF-8'); $reader->read($file); $this->set_status_info( 'Импорт прайслиста' . ' (поставщик: ' . Model_Product::supplier_caption($supplier) . ', коэффициент для цен: ' . $this->param('price_factor') . ')'); // Generate unique import id $loop_prevention = 500; do { $import_id = mt_rand(1, mt_getrandmax()); } while (Model::fly('Model_Product')->exists_by_import_id($import_id) && $loop_prevention-- > 0); if ($loop_prevention <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' =>__METHOD__)); switch ($supplier) { case Model_Product::SUPPLIER_IKS: $this->iks($reader, $import_id); break; case Model_Product::SUPPLIER_ISV: $this->isv($reader, $import_id); break; } $this->process_not_imported_products($supplier, $import_id); // update stats Model::fly('Model_Section')->mapper()->update_products_count(); $this->set_status_info('Import finished. (' . date('Y-m-d H:i:s') . ')'); //@FIXME: Unlink only temporary files //unlink($file); } /** * Import toysfest pricelist */ public function iks(Spreadsheet_Excel_Reader $reader, $import_id) { $site_id = 1; //@TODO: pass via params $rowcount = $reader->rowcount(); for ($row = 1; $row <= $rowcount; $row++) { if ($row % 20 == 0) { $this->set_progress((int) (($row - 1) * 100 / $rowcount)); } if ($reader->val($row, 1) == '' || $reader->val($row, 1) == 'import_id') continue; // Not a product row // ----- caption & brand_caption $caption = $reader->val($row, 5); $brand_caption = $reader->val($row, 2); // ----- marking $marking = $reader->val($row, 4); /* if ($row == 2459) { echo 'caption: ' . $caption . '<br /><br />'; echo 'val: ' . $reader->val($row, 4) . '<br />'; echo 'raw: ' . $reader->raw($row, 4) . '<br />'; echo 'format: ' . $reader->format($row, 4) . '<br />'; echo 'formatIndex: ' . $reader->formatIndex($row, 4) . '<br />'; $raw = $reader->raw($row, 4); $format = $reader->format($row, 4); $formatIndex = $reader->formatIndex($row, 4); $formatted = $reader->_format_value($format, $raw, $formatIndex, TRUE); echo 'formatted via _format_valua(): ' . $formatted['string']; die; } */ if ($marking == '') { $this->log( '[Строка ' . $row . ']: Для товара "' . $caption . '", ' . $brand . ' не удалось определить артикул' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } // ----- price $price = trim($reader->raw($row, 8)); if ($price == '') { $price = $reader->val($row, 8); } if ($price == '' || ! preg_match('/\d+([\.,]\d+)?/', $price)) { $this->log( '[Строка ' . $row . ']: Некорретное значение цены ' . $price . ' для товара "' . $caption . '", ' . $brand //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } $this->process_product($marking, Model_Product::SUPPLIER_IKS, $price, $caption, $brand_caption, $import_id); } } /** * Import saks pricelist */ public function saks($reader, $import_id) { $site_id = 1; //@TODO: pass via params $rowcount = $reader->rowcount(); for ($row = 1; $row <= $rowcount; $row++) { if ($row % 20 == 0) { $this->set_progress((int) (($row - 1) * 100 / $rowcount)); } if ($reader->val($row, 7) == '' || $reader->val($row, 7) == 'Штрих-код') continue; // Not a product row // ----- caption $caption = $reader->val($row, 3); // ----- marking $marking = $reader->val($row, 2); $marking = trim($marking, " '"); if ($marking == '') { $this->log( '[Строка ' . $row . ']: Для товара "' . $caption . '" не удалось определить артикул' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } // ----- price $price = trim($reader->raw($row, 4)); if ($price == '') { $price = $reader->val($row, 4); } if ($price == '' || ! preg_match('/\d+([\.,]\d+)?/', $price)) { $this->log( '[Строка ' . $row . ']: Некорретное значение цены ' . $price . ' для товара "' . $caption . '"' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } $this->process_product($marking, Model_Product::SUPPLIER_SAKS, $price, $caption, NULL, $import_id); } } /** * Import gulliver pricelist */ public function gulliver($reader, $import_id) { $site_id = 1; //@TODO: pass via params $rowcount = $reader->rowcount(); for ($row = 1; $row <= $rowcount; $row++) { if ($row % 20 == 0) { $this->set_progress((int) (($row - 1) * 100 / $rowcount)); } if ($reader->val($row, 5) == '' || $reader->val($row, 5) == 'Цена') continue; // Not a product row // ----- caption $caption = $reader->val($row, 3); // ----- marking $marking = $reader->val($row, 2); if ($marking == '') { $this->log( '[Строка ' . $row . ']: Для товара "' . $caption . '" не удалось определить артикул' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } // ----- price $price = trim($reader->raw($row, 5)); if ($price == '') { $price = $reader->val($row, 5); } if ($price == '' || ! preg_match('/\d+([\.,]\d+)?/', $price)) { $this->log( '[Строка ' . $row . ']: Некорретное значение цены ' . $price . ' для товара "' . $caption . '"' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } $this->process_product($marking, Model_Product::SUPPLIER_GULLIVER, $price, $caption, NULL, $import_id); } } /** * Update price for product with given marking and supplier */ public function process_product($marking, $supplier, $price, $caption, $brand_caption, $import_id, $marking_like = FALSE) { $site_id = 1; //@FIXME: pass via task params static $brands; if ($brands === NULL) { $brands = Model::fly('Model_Section')->find_all_by_sectiongroup_id(1, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption'), 'as_tree' => TRUE )); } $products = Model::fly('Model_Product')->find_all_by_marking_and_supplier_and_site_id( $marking, $supplier, $site_id, array( 'columns' => array('id', 'marking', 'caption') ) ); if (count($products) <= 0) { $this->log('Товар из прайслиста с артикулом ' . $marking . ' ("' . $caption . '", ' . $brand_caption . ') не найден в каталоге сайта', Log::WARNING); return; } if (count($products) >= 2) { // Two or more products with the same marking $brand_products = array(); if ($brand_caption != '') { // Try to guess the product by brand foreach ($products as $product) { $brand_ids = $product->get_section_ids(1); foreach ($brand_ids as $brand_id) { // Find top-level brand $brand = $brands->ancestor($brand_id, 1); // Product belongs to the brand if ($brand_caption == $brand->caption) { $brand_products[] = $product->id; } } } } if (count($brand_products) != 1) { // Failed to distinguish duplicate markings by brand... $msg = ''; foreach ($products as $product) { $msg .= $product->marking . ' ("' . $product->caption . '")' . "\n"; } $this->log( 'Артикул ' . $marking . ' ("' . $caption . '", ' . $brand_caption . ') не является уникальным в каталоге сайта:' . "\n" . trim($msg, ' ",') , Log::ERROR); return; } $product = $products[$brand_products[0]]; } else // count($products) == 1 { $product = $products->at(0); } $product->active = 1; $price_factor = l10n::string_to_float($this->param('price_factor')); $sell_price = ceil($price * $price_factor); $product->price = new Money($sell_price); $product->import_id = $import_id; $product->save(FALSE, FALSE, FALSE, FALSE, FALSE); } /** * Display warnings about products that are present in the catalog but are not present in the pricelist */ public function process_not_imported_products($supplier, $import_id) { $site_id = 1; //@FIXME: pass via task params $loop_prevention = 1000; do { $products = Model::fly('Model_Product')->find_all_by( array( 'supplier' => $supplier, 'site_id' => $site_id, 'import_id' => array('<>', $import_id) ), array( 'columns' => array('id', 'marking', 'caption'), 'batch' => 100 ) ); foreach ($products as $product) { $this->log('Деактивирован товар с артикулом ' . $product->marking . ' ("' . $product->caption . '"). Товар есть в каталоге сайта, но отсутствует в прайс-листе', Log::WARNING); $product->active = 0; $product->save(FALSE, FALSE, FALSE, FALSE, FALSE); } } while (count($products) && $loop_prevention-- > 0); if ($loop_prevention <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); } } <file_sep>/modules/general/faq/classes/controller/backend/faq.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Faq extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Question'; $this->_form = 'Form_Backend_Question'; return array( 'create' => array( 'view_caption' => 'Новый вопрос' ), 'update' => array( 'view_caption' => 'Редактирование вопроса' ), 'delete' => array( 'view_caption' => 'Удаление вопроса', 'message' => 'Удалить вопрос ":question_preview"?' ), 'multi_delete' => array( 'view_caption' => 'Удаление вопросов', 'message' => 'Удалить выбранные вопросы?' ) ); } /** * @return boolean */ public function before() { if ( ! parent::before()) { return FALSE; } // Check that there is a site selected if (Model_Site::current()->id === NULL) { $this->_action_error('Выберите сайт для работы с вопросами!'); return FALSE; } return TRUE; } /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('faq') . '/public/css/backend/faq.css'); return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Default action */ public function action_index() { $this->request->response = $this->render_layout($this->widget_questions()); } /** * Renders questions list * * @return string */ public function widget_questions() { $site_id = (int) Model_Site::current()->id; $order_by = $this->request->param('faq_order', 'created_at'); $desc = (bool) $this->request->param('faq_desc', '1'); $per_page = 20; $count = Model::fly('Model_Question')->count_by_site_id($site_id); $pagination = new Pagination($count, $per_page); $questions = Model::fly('Model_Question')->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc, 'limit' => $pagination->limit, 'offset' => $pagination->offset )); // Set up view $view = new View('backend/questions'); $view->order_by = $order_by; $view->desc = $desc; $view->questions = $questions; $view->pagination = $pagination->render('backend/pagination'); return $view; } /** * FAQ module config */ public function action_config() { $config = Modules::load_config('faq_' . Model_Site::current()->id, 'faq'); if ($config === FALSE) { $config = array(); } $form = new Form_Backend_FaqConfig(); $form->set_defaults($config); if ($form->is_submitted() && $form->validate()) { $config = $form->get_values(); unset($config['submit']); Modules::save_config('faq_' . Model_Site::current()->id, $config); $form->flash_message('Настройки модуля "Вопрос-ответ" сохранены'); $this->request->redirect($this->request->uri); } $view = new View('backend/form_adv'); $view->caption = 'Настройки модуля "Вопрос-ответ"'; $view->form = $form; $this->request->response = $this->render_layout($view->render()); } } <file_sep>/modules/shop/catalog/classes/task/updatelinks.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Relink products to sections */ class Task_UpdateLinks extends Task { /** * Run the task */ public function run() { $site_id = 1; $count = Model::fly('Model_Product')->count_by_site_id($site_id); $percents = 0; $i = 0; $this->set_status_info('Обновление привязки товаров к разделам'); $this->set_progress($percents); $loop_prevention = 1000; do { if ($i * 100.0 / $count >= $percents + 2) { $percents = round($i * 100.0 / $count); $this->set_status_info('Обновление привязки товаров к разделам : ' . $i . ' из ' . $count); $this->set_progress($percents); } $params = array( 'columns' => array('id', 'section_id'), 'with_sections' => TRUE, 'batch' => 100 ); $products = Model::fly('Model_Product')->find_all_by_site_id($site_id, $params); foreach ($products as $product) { $product->update_section_links(); $i++; } } while (count($products) && $loop_prevention-- > 0); if ($loop_prevention <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); // Model::fly('Model_Section')->mapper()->update_products_count(); $this->set_status_info('Обновление привязки товаров к разделам завершено'); } } <file_sep>/modules/shop/catalog/classes/model/product/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Product_Mapper extends Model_Mapper_Resource { public function init() { parent::init(); // for event $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('event_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('event_uri', array('Type' => 'varchar(127)')); $this->add_column('alias', array('Type' => 'varchar(63)', 'Key' => 'INDEX')); $this->add_column('section_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('web_import_id', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('lecturer_id', array('Type' => 'int unsigned')); $this->add_column('lecturer_name', array('Type' => 'varchar(127)')); $this->add_column('organizer_id', array('Type' => 'int unsigned')); $this->add_column('organizer_name', array('Type' => 'varchar(127)')); $this->add_column('place_id', array('Type' => 'int unsigned')); $this->add_column('place_name', array('Type' => 'varchar(127)')); $this->add_column('theme', array('Type' => 'varchar(127)')); $this->add_column('format', array('Type' => 'varchar(127)')); $this->add_column('caption', array('Type' => 'varchar(255)')); $this->add_column('description', array('Type' => 'text')); $this->add_column('datetime', array('Type' => 'datetime')); $this->add_column('duration', array('Type' => 'varchar(7)')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); $this->add_column('visible', array('Type' => 'boolean', 'Key' => 'INDEX')); // for translation $this->add_column('interact', array('Type' => 'varchar(31)')); $this->add_column('access', array('Type' => 'varchar(31)')); $this->add_column('numviews', array('Type' => 'int unsigned')); $this->add_column('choalg', array('Type' => 'int unsigned')); $this->add_column('require', array('Type' => 'text')); $this->add_column('price', array('Type' => 'money')); // $this->cache_find_all = TRUE; // Telemost provider $this->add_column('telemost_provider', array('Type' => 'varchar(128)')); // Hangouts $this->add_column('hangouts_secret_key', array('Type' => 'varchar(128)')); $this->add_column('hangouts_url', array('Type' => 'varchar(256)')); $this->add_column('hangouts_test_secret_key', array('Type' => 'varchar(128)')); $this->add_column('hangouts_test_url', array('Type' => 'varchar(256)')); } /** * Find product by condition * Load additional properties * * @param Model $model * @param string|array|Database_Condition_Where $condition * @param array $params * @param Database_Query_Builder_Select $query */ public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } if (is_array($condition) && isset($condition['section'])) { // Find a product which is bound to the specified section $prodsec_table = DbTable::instance('ProductSection')->table_name(); $query ->and_where("$prodsec_table.section_id", '=', (int) $condition['section']->id); $params['join_productsection'] = TRUE; unset($condition['section']); } if (is_array($condition) && isset($condition['section_active'])) { $section_table = Model_Mapper::factory('Model_Section_Mapper')->table_name(); $query->where("$section_table.active", '=', (int) $condition['section_active']); $params['join_section'] = TRUE; unset($condition['section_active']); } if ( is_array($condition) && isset($condition['site_id']) ) { $params['join_sectiongroup'] = TRUE; } if ( ! empty($params['with_image'])) { // Select images for product via join $image_table = Model_Mapper::factory('Model_Image_Mapper')->table_name(); // Number of the thumbnail to select $i = $params['with_image']; // Additinal columns $query->select( array("$image_table.image$i", 'image'), array("$image_table.width$i", 'image_width'), array("$image_table.height$i", 'image_height') ); $query ->join($image_table, 'LEFT') ->on("$image_table.owner_id", '=', "$table.id") ->on("$image_table.owner_type", '=', DB::expr("'product'")) ->join(array($image_table, 'img'), 'LEFT') ->on(DB::expr("img.owner_id"), '=', "$image_table.owner_id") ->on(DB::expr("img.owner_type"), '=', DB::expr("'product'")) ->on(DB::expr("img.position"), '<', "$image_table.position") ->where(DB::expr('ISNULL(img.id)'), NULL, NULL); } if ( ! isset($params['with_properties']) || ! empty($params['with_properties'])) { // Select product with additional (non-system) property values // @TODO: use only properties for product's section - load the product, and then load the properties?? $properties = Model::fly('Model_Property')->find_all_by_site_id_and_system(Model_Site::current()->id, 0, array( 'columns' => array('id', 'name'), 'order_by' => 'position', 'desc' => FALSE, 'as_array' => TRUE )); $table = $this->table_name(); $propertyvalue_table = Model_Mapper::factory('PropertyValue_Mapper')->table_name(); foreach ($properties as $property) { $id = (int) $property['id']; // Add column to query $query->select(array(DB::expr("propval$id.value"), $property['name'])); $query->join(array($propertyvalue_table, "propval$id"), 'LEFT') ->on(DB::expr("propval$id.property_id"), '=', DB::expr($id)) ->on(DB::expr("propval$id.product_id"), '=', "$table.id"); } } // ----- joins $this->_apply_joins($query, $params); return parent::find_by($model, $condition, $params, $query); } /** * Build database query condition from search params * * @param Model_Product $product * @param array $search_params * @return (Database_Expression_Where|NULL, array) */ public function search_condition(Model_Product $product, array $search_params = NULL) { $condition = DB::where(); $params = array(); $table = $this->table_name(); // Search text if (isset($search_params['search_text']) && isset($search_params['search_fields'])) { $words = preg_split('/\s+/', $search_params['search_text'], NULL, PREG_SPLIT_NO_EMPTY); foreach ($words as $word) { $condition->and_where_open(); foreach ($search_params['search_fields'] as $field) { if (strpos($field, '.') === FALSE) { $field = "$table.$field"; } $condition->or_where($field, 'LIKE', "%$word%"); } $condition->and_where_close(); } } // Search text if (isset($search_params['search_date'])) { $date = date(Kohana::config('datetime.db_date_format'),$search_params['search_date']); $condition->and_where('datetime', 'LIKE', "%$date%"); } // Condition for fields if ( ! empty($search_params)) { foreach ($search_params as $name => $value) { if ($this->has_column($name)) { $column = $this->get_column($name); } elseif ($this->has_virtual_column($name)) { $column = $this->get_virtual_column($name); } else { continue; } $type_info = $this->_parse_column_type($column['Type']); switch ($type_info['type']) { case 'boolean': if ($value != -1) { $condition->and_where("$table.$name", '=', (int) $value); } break; default: $condition->and_where("$table.$name", '=', (int)$value); break; } } } if (isset($search_params['section']) && $search_params['section']->id !== NULL) { // find products from specified section $section = $search_params['section']; $prodsec_table = DbTable::instance('ProductSection')->table_name(); $condition ->and_where("$prodsec_table.section_id", '=', (int) $section->id); $params['join_productsection'] = TRUE; } if (isset($search_params['sectiongroup'])) { $sectiongroup_table = Model_Mapper::factory('Model_SectionGroup_Mapper')->table_name(); $condition->and_where("$sectiongroup_table.id", '=', $search_params['sectiongroup']->id); $params['join_sectiongroup'] = TRUE; } if ( APP =='FRONTEND') { $condition->and_where("$table.visible", '=', TRUE); $condition->and_where("$table.active", '=', TRUE); $today_datetime = new DateTime("now"); $today_datetime->setTimezone(new DateTimeZone("UTC")); $today_datetime->sub(new DateInterval(Model_Product::DURATION_1)); if(!(isset($search_params['calendar']) && $search_params['calendar'] == Model_Product::CALENDAR_ARCHIVE)) $condition->and_where(DB::expr('TIMEDIFF('.$this->_db->table_prefix()."$table.datetime".','.$this->_db->quote($today_datetime->format(Kohana::config('datetime.db_datetime_format'))).')>0')); else { $condition->and_where(DB::expr('TIMEDIFF('.$this->_db->quote($today_datetime->format(Kohana::config('datetime.db_datetime_format'))).','.$this->_db->table_prefix()."$table.datetime".')>0')); $params['join_telemost'] = TRUE; } if (Modules::registered('area') && !isset($search_params['all_towns'])) { $telemost_table = Model_Mapper::factory('Model_Telemost_Mapper')->table_name(); $place_table = Model_Mapper::factory('Model_Place_Mapper')->table_name(); $telemost_place_table = $place_table."_telemost"; $condition->and_where_open() ->or_where("$place_table.town_id", '=', Model_Town::current()->id) ->or_where_open() ->and_where(DB::expr("$telemost_place_table.town_id"), '=', Model_Town::current()->id) ->and_where(DB::expr($this->_db->table_prefix().$telemost_table.'.active'), '=', TRUE) ->or_where_close() ->and_where_close(); $params['join_place'] = TRUE; $params['join_telemostplace'] = TRUE; } } if (isset($search_params['section_active'])) { $section_table = Model_Mapper::factory('Model_Section_Mapper')->table_name(); $condition->and_where("$section_table.active", '=', (int) $search_params['section_active']); $params['join_section'] = TRUE; } if (isset($search_params['calendar'])) { $key = $search_params['calendar']; if($key != Model_Product::CALENDAR_TODAY && array_key_exists($key,Model_Product::$_calendar_options )) { $needTime = new DateTime("now"); $needTime->setTimezone(new DateTimeZone("UTC")); $needTime->add(new DateInterval($key)); $condition->and_where(DB::expr('TIMEDIFF('.$this->_db->table_prefix()."$table.datetime".','.$this->_db->quote($needTime->format(Kohana::config('datetime.db_datetime_format'))).')>0')); } } if ( ! $condition->is_empty()) { return array($condition, $params); } else { return array(NULL, $params); } } /** * Find all models by criteria and return them in {@link Models} container * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by( Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->distinct('whatever') ->from($table); } // ----- process contition if (is_array($condition) && ! empty($condition['ids'])) { // find product by several ids $query->where("$table.id", 'IN', DB::expr('(' . implode(',', $condition['ids']) . ')')); unset($condition['ids']); } if ( is_array($condition) && isset($condition['section_active'])) { $params['join_section'] = TRUE; $section_table = Model_Mapper::factory('Model_Section_Mapper')->table_name(); $query->where("$section_table.active", '=', (int) $condition['section_active']); unset($condition['section_active']); } if ( is_array($condition) && isset($condition['site_id'])) { $params['join_sectiongroup'] = TRUE; } if (is_array($condition) && isset($condition['plist'])) { // Select products from the list $plistproduct_table = Model_Mapper::factory('Model_PlistProduct_Mapper')->table_name(); $query ->join("$plistproduct_table", 'INNER') ->on("$plistproduct_table.product_id", '=', "$table.id") ->on("$plistproduct_table.plist_id", '=', DB::expr((int)$condition['plist']->id)); unset($condition['plist']); } if (is_array($condition) && isset($condition['section'])) { // Find a product which is bound to the specified section $prodsec_table = DbTable::instance('ProductSection')->table_name(); $query ->where("$prodsec_table.section_id", '=', (int) $condition['section']->id); $params['join_productsection'] = TRUE; unset($condition['section']); } if ( ! empty($params['with_image'])) { // Select images for product via join $image_table = Model_Mapper::factory('Model_Image_Mapper')->table_name(); // Number of the thumbnail to select $i = $params['with_image']; // Additinal columns $query->select( array("$image_table.image$i", 'image'), array("$image_table.width$i", 'image_width'), array("$image_table.height$i", 'image_height') ); $query ->join($image_table, 'LEFT') ->on("$image_table.owner_id", '=', "$table.id") ->on("$image_table.owner_type", '=', DB::expr("'product'")) ->join(array($image_table, 'img'), 'LEFT') ->on(DB::expr("img.owner_id"), '=', "$image_table.owner_id") ->on(DB::expr("img.owner_type"), '=', DB::expr("'product'")) ->on(DB::expr("img.position"), '<', "$image_table.position") ->where(DB::expr('ISNULL(img.id)'), NULL, NULL); } if ( ! empty($params['with_properties'])) { // Select product with additional (non-system) property values // @TODO: use only properties for current section $properties = Model::fly('Model_Property')->find_all_by_site_id_and_system(Model_Site::current()->id, 0, array( 'columns' => array('id', 'name'), 'order_by' => 'position', 'desc' => FALSE, 'as_array' => TRUE )); $table = $this->table_name(); $propertyvalue_table = Model_Mapper::factory('PropertyValue_Mapper')->table_name(); foreach ($properties as $property) { $id = (int) $property['id']; // Add column to query $query->select(array(DB::expr("propval$id.value"), $property['name'])); $query->join(array($propertyvalue_table, "propval$id"), 'LEFT') ->on(DB::expr("propval$id.property_id"), '=', DB::expr($id)) ->on(DB::expr("propval$id.product_id"), '=', "$table.id"); } } if ( ! empty($params['with_sections'])) { $section_table = Model_Mapper::factory('Model_Section_Mapper')->table_name(); $prodsec_table = DbTable::instance('ProductSection')->table_name(); $subq = DB::select('GROUP_CONCAT("s".id, \'-\', "s".sectiongroup_id)') ->from(array($section_table, 's')) ->join(array($prodsec_table, 'ps'), 'INNER') ->on('"ps".section_id', '=', '"s".id') ->on('"ps".distance', '=', DB::expr('0')) ->where('"ps".product_id', '=', DB::expr($this->get_db()->quote_identifier("$table.id"))) ->group_by('"ps".product_id'); $query->select(array($subq, 'sections')); } // ----- joins $this->_apply_joins($query, $params); return parent::find_all_by($model, $condition, $params, $query); } /** * Count products by condition * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @return integer */ public function count_by(Model $model, $condition = NULL, array $params = NULL) { if ( is_array($condition) && isset($condition['owner'])) { return parent::count_by($model, $condition); } $table = $this->table_name(); $query = DB::select(array('COUNT(DISTINCT "' . $table . '.id")', 'total_count')) ->from($table); // ----- condition if ( is_array($condition) && isset($condition['site_id'])) { $params['join_sectiongroup'] = TRUE; } // ----- joins $this->_apply_joins($query, $params); if ($condition !== NULL) { $condition = $this->_prepare_condition($condition); $query->where($condition, NULL, NULL); } $count = $query->execute($this->get_db()) ->get('total_count'); return (int) $count; } /** * Apply joins to the query * * @param Database_Query_Builder_Select $query * @param array $params */ protected function _apply_joins(Database_Query_Builder_Select $query, array $params = NULL) { $table = $this->table_name(); if ( ! empty($params['join_sectiongroup'])) { $params['join_productsection'] = TRUE; $params['join_section'] = TRUE; } elseif ( ! empty($params['join_section'])) { $params['join_productsection'] = TRUE; } if ( ! empty($params['join_productsection'])) { $prodsec_table = DbTable::instance('ProductSection')->table_name(); $query ->join($prodsec_table, 'INNER') ->on("$prodsec_table.product_id", '=', "$table.id"); if ( ! empty($params['join_section'])) { $section_table = Model_Mapper::factory('Model_Section_Mapper')->table_name(); $query ->join($section_table, 'INNER') ->on("$section_table.id", '=', "$prodsec_table.section_id"); //@WARN: DO NOT join sectiongroup on $prodsec_table - sectiongroup_id column of $prodsec_table is corrupted // and can contain NULL values if ( ! empty($params['join_sectiongroup'])) { $sectiongroup_table = Model_Mapper::factory('Model_SectionGroup_Mapper')->table_name(); $query ->join($sectiongroup_table, 'INNER') ->on("$sectiongroup_table.id", '=', "$section_table.sectiongroup_id"); } } } if ( ! empty($params['join_telemostplace'])) { $telemost_table = Model_Mapper::factory('Model_Telemost_Mapper')->table_name(); $place_table = Model_Mapper::factory('Model_Place_Mapper')->table_name(); $telemost_place_table = $place_table."_telemost"; $query ->join($telemost_table, 'LEFT') ->on("$telemost_table.product_id", '=', "$table.id") ->join(array($place_table,$telemost_place_table), 'LEFT') ->on(DB::expr("$telemost_place_table.id"), '=', "$telemost_table.place_id"); } if ( ! empty($params['join_place'])) { $place_table = Model_Mapper::factory('Model_Place_Mapper')->table_name(); $query ->join($place_table, 'LEFT') ->on("$place_table.id", '=', "$table.place_id"); } if ( ! empty($params['join_telemost'])) { $telemost_table = Model_Mapper::factory('Model_Telemost_Mapper')->table_name(); $query ->join($telemost_table, 'inner') ->on("$telemost_table.product_id", '=', "$table.id"); } } /** * Tie product to the selected section and it's parents * * @param Model_Product $product * @param Model_Section $section * @param boolean $check_already_linked */ public function link_to_section(Model_Product $product, Model_Section $section, $check_already_linked = TRUE) { // section parents $sections = $section->get_parents(array('columns' => array('id', 'lft', 'rgt', 'level', 'sectiongroup_id'), 'as_array' => TRUE)); // and the section itself $sections[] = $section->properties(); $prodsec_table = DbTable::instance('ProductSection'); foreach ($sections as $sec) { $distance = $section->level - $sec['level']; if ( $check_already_linked && $prodsec_table->exists( DB::where('product_id', '=', $product->id) ->and_where('section_id', '=', $sec['id']) ->and_where('distance', '=', $distance) ) ) continue; // already linked to this section with the same distance $prodsec_table->insert(array( 'product_id' => $product->id, 'section_id' => $sec['id'], 'distance' => $distance, 'sectiongroup_id' => $section->sectiongroup_id )); } } /** * Link product to sections from the specified sectiongroup * * @param Model_Product $product * @param integer $sectiongroup_id * @param array $section_ids */ public function link_to_sections(Model_Product $product, $sectiongroup_id, $section_ids) { DbTable::instance('ProductSection') ->delete_rows(DB::where('product_id', '=', $product->id)->and_where('sectiongroup_id', '=', $sectiongroup_id)); $section = new Model_Section(); foreach ($section_ids as $section_id) { $section->find($section_id, array('columns' => array('id', 'lft', 'rgt', 'level', 'sectiongroup_id'))); if (isset($section->id)) { $this->link_to_section($product, $section); } } } /** * Update links for products, linked to the given section. * If section is not specified, all products in the catalog are relinked * * @param Model_Section $section */ public function relink(Model_Product $product, Model_Section $section = NULL) { $loop_prevention = 1000; do { $params = array( 'columns' => array('id', 'section_id'), 'with_sections' => TRUE, 'batch' => 100 ); if ($section !== NULL) { $products = Model::fly('Model_Product')->find_all_by_section($section, $params); } else { $products = Model::fly('Model_Product')->find_all_by_site_id(Model_Site::current()->id, $params); } foreach ($products as $product) { $product->update_section_links(); } } while (count($products) && $loop_prevention-- > 0); if ($loop_prevention <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); } /** * Unlink all products from the specified section * * @param Model_Section $section */ public function unlink_all_from_section(Model_Product $product, Model_Section $section) { $loop_prevention = 1000; do { $products = Model::fly('Model_Product')->find_all_by_section($section, array( 'columns' => array('id', 'section_id'), 'with_sections' => TRUE, 'batch' => 100 )); foreach ($products as $product) { $sections = $product->sections; unset($sections[$section->sectiongroup_id][$section->id]); $product->sections = $sections; $product->update_section_links(); } } while (count($products) && $loop_prevention-- > 0); if ($loop_prevention <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); } } <file_sep>/modules/shop/catalog/classes/task/import/saks.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Import catalog from www.saks.ru */ class Task_Import_Saks extends Task_Import_Web { /** * Default parameters for this taks * @var array */ public static $default_params = array( // sections 'create_sections' => FALSE, 'update_section_parents' => FALSE, 'update_section_captions' => FALSE, 'update_section_descriptions' => FALSE, 'update_section_images' => FALSE, // products 'create_products' => TRUE, 'update_product_captions' => FALSE, 'update_product_descriptions' => FALSE, 'update_product_properties' => FALSE, 'update_product_images' => FALSE, 'link_products_by' => 'caption' ); /** * Construct task */ public function __construct() { parent::__construct('http://saks.ru'); $this->default_params(self::$default_params); } /** * Run the task */ public function run() { // parse sections $sections = $this->parse_sections(); // import sections $this->import_sections($sections); // import products $this->import_products($sections); $this->set_status_info('Импорт завершён'); } /** * Parse sections * * @return array */ public function parse_sections() { // ----- parse brands and series --------------------------------------- $sections = array(0 => array()); // Retrieve list of all brands with links from catalog page ... $this->set_status_info('Parsing brands and series'); // ----- parse brands $page = $this->get('/section18/'); if ( ! preg_match_all('!<a\s*href="/section18/ctg(\d+)/\?descript">\s*<strong>([^<]*)</strong>(<br[^>]*>)?(.*?)</a>!is', $page, $matches, PREG_SET_ORDER)) { $this->log('No brands found', Log::WARNING); return; } foreach ($matches as $match) { $import_id = trim($match[1]); $caption = $this->decode_trim($match[2], 255); $description = $this->decode_trim($match[4]); $url = '/section18/ctg' . $import_id . '/'; $sections[0][$import_id] = array( 'import_id' => $import_id, 'caption' => $caption, 'description' => $description, 'url' => $url ); } // brand logos preg_match_all('!<a\s*href="/section18/ctg(\d+)/">\s*<img\s*src="([^"]*)!is', $page, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $import_id = trim($match[1]); $image_url = trim($match[2]); if (isset($sections[0][$import_id])) { $sections[0][$import_id]['image_url'] = $image_url; } } // ----- parse series $page = $this->get('/map/'); foreach ($sections[0] as $section_info) { preg_match_all('!<a href="(/section18/ctg' . $section_info['import_id'] . '/ctg(\d+)/)">(.*?)</a>!is', $page, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $import_id = trim($match[2]); $caption = $this->decode_trim($match[3], 255); $url = trim($match[1]); $sections[$section_info['import_id']][$import_id] = array( 'import_id' => $import_id, 'caption' => $caption, 'url' => $url ); } } return $sections; } /** * Import a branch of sections * * @param array $sections * @param Model_Section $parent */ public function import_sections(array $sections, Model_Section $parent = NULL) { if ($parent === NULL) { $count = count($sections[0]); $i = 0; $this->set_status_info('Importing brands and series'); } $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task // get all product properties static $propsections; if ($propsections === NULL) { $properties = Model::fly('Model_Property')->find_all_by_site_id($site_id, array('columns' => array('id'))); $propsections = array(); foreach ($properties as $property) { $propsections[$property['id']] = array( 'active' => 1, 'filter' => 0, 'sort' => 0 ); } } $section = new Model_Section(); $parent_import_id = ($parent !== NULL) ? $parent->web_import_id : 0; if ( ! isset($sections[$parent_import_id])) return; // No sections in branch foreach ($sections[$parent_import_id] as $import_id => $section_info) { $section->find_by_web_import_id_and_sectiongroup_id($section_info['import_id'], $sectiongroup_id); $creating = ( ! isset($section->id)); // web_import_id $section->web_import_id = $section_info['import_id']; // sectiongroup_id $section->sectiongroup_id = $sectiongroup_id; // parent_id if ($parent !== NULL && ($creating || $this->param('update_section_parents'))) { $section->parent_id = $parent->id; } // caption if (isset($section_info['caption']) && ($creating || $this->param('update_section_captions'))) { $section->caption = $section_info['caption']; } // description if (isset($section_info['description']) && ($creating || $this->param('update_section_descriptions'))) { $section->description = $section_info['description']; } // product properties if ($creating) { $section->propsections = $propsections; } if ($creating) { if ($this->param('create_sections')) { $section->save(FALSE, TRUE, FALSE); if ($parent === NULL) { $this->log('Создан новый раздел "' . $section->caption . '"'); } else { $this->log('Создан новый подраздел "' . $section->caption . '" в разделе "' . $parent->caption . '"'); } } else { if ($parent === NULL) { $this->log('Пропущен новый раздел "' . $section->caption . '"'); } else { $this->log('Пропущен новый подраздел "' . $section->caption . '" в разделе "' . $parent->caption . '"'); } continue; } } else { $section->save(FALSE, FALSE, FALSE); } $section->find($section->id); //@FIXME: we use it to obtain 'lft' and 'rgt' values for saved brand // save section id $sections[$parent_import_id][$import_id]['id'] = $section->id; // logo if ( isset($section_info['image_url']) && ($creating || $this->param('update_section_images'))) { $image = new Model_Image(); if ( ! $creating) { // Delete existing images $image->delete_all_by_owner_type_and_owner_id('section', $section->id); } $image_file = $this->download_cached($section_info['image_url']); if ($image_file) { try { $image->source_file = $image_file; $image->owner_type = 'section'; $image->owner_id = $section->id; $image->config = 'section'; $image->save(); } catch (Exception $e) {} } } // ----- Import subsections $this->import_sections($sections, $section); if ($parent === NULL) { $i++; $this->set_status_info('Importing brands : ' . $i . ' of ' . $count . ' done.'); } } if ($parent === NULL) { // Update activity info & stats for sections $section->mapper()->update_activity(); $section->mapper()->update_products_count(); } } /** * Import products * * @param array $sections */ public function import_products(array $sections) { $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task $section = new Model_Section(); $product = new Model_Product(); // Caclulate progress info $count = count($sections, COUNT_RECURSIVE) - count($sections) - count($sections[0]); $i = 0; $this->set_status_info('Importing products'); $status_info = ''; foreach ($sections as $sections_branch) { foreach ($sections_branch as $section_info) { $this->set_progress((int) (100 * $i / $count)); $i++; if (isset($sections[$section_info['import_id']])) continue; // Import products only for the leaf sections if ( ! isset($section_info['id'])) continue; die('Trolololololololololololololololololo!'); $section->find($section_info['id']); if ( ! isset($section->id)) throw new Kohana_Exception('Section was not found by id :id', array(':id' => $section_info['id'])); if ( ! isset($section_info['url'])) throw new Kohana_Exception('Section url is not set for section :id', array(':id' => $section_info['id'])); $offset = 0; $max_offset = 0; $per_page = 10; while ($offset <= $max_offset) { $url = ($offset == 0) ? $section_info['url'] : $section_info['url'] . '?p=' . $offset; $page = $this->get($url); echo $page; die; // Detect maximum offset and number of products per page if the result is paginated preg_match_all('!<a\s*href="[^"]*\?p=(\d+)!', $page, $matches); if ( ! empty($matches[1])) { $max_offset = max($matches[1]); if ($offset == 0) { $per_page = min($matches[1]); } var_dump($max_offset); var_dump($per_page); die; } $offset += $per_page; } } } /* $section->find_by_caption_and_sectiongroup_id($brand_info['caption'], $sectiongroup_id); foreach ($sections[$brand_info['id']] as $subbrand_info) { $this->set_progress((int) (100 * $i / $count)); $i++; $subbrand->find_by_caption_and_parent($subbrand_info['caption'], $section); // Obtain first page $subbrand_page = $this->get($subbrand_info['url']); // Detect number of pages if products display is paginated $offset = 0; $max_offset = 0; $per_page = 24; preg_match_all('!<a\s*href="[^"]*from=(\d+)!', $subbrand_page, $matches); if ( ! empty($matches[1])) { $per_page = min($matches[1]); $max_offset = max($matches[1]); } // Iterate over pages for ($offset = 0; $offset <= $max_offset; $offset += $per_page) { if ($offset > 0) { // obtain next page $subbrand_page = $this->get($subbrand_info['url'] . '&from=' . $offset); } preg_match_all( '!<a\s*href="([^"]*)">Перейти\s*на\s*страницу\s*товара!', $subbrand_page, $matches); foreach (array_unique($matches[1]) as $url) { $page = $this->get($url); // caption if (preg_match('!<td>\s*<h6[^>]*>\s*([^<]+)!', $page, $m)) { $caption = $this->decode_trim($m[1], 255); } else { throw new Kohana_Exception('Unable to determine caption for product :ulr', array(':url' => $url)); } $product->find_by_caption_and_section_id($caption, $subbrand->id, array('with_properties' => FALSE)); $creating = ( ! isset($product->id)); // Set caption $product->caption = $caption; // Link to subbrand $product->section_id = $subbrand->id; // marking, age & description if (preg_match( '!' . 'Артикул:([^<]*)(<br>\s*)+' . '(Возраст:([^<]*))?(<br>\s*)' . '(.*?)' . '(<p>\s*(январь|февраль|март|апрель|май|июнь|июль|август|сентябрь|октябрь|ноябрь|декабрь|новинка).*?</p>\s*)?' . '(<p>Рекомендованная\s*розничная.*?</p>\s*)?' . '<ul\s*class="links">' . '!is' , $page, $m)) { $product->marking = $this->decode_trim($m[1], 63); $product->age = $this->decode_trim($m[4]); // cut out images & links from description $description = trim($m[6]); $description = preg_replace('!<img[^>]*>!', '', $description); $description = preg_replace('!<a[^>]*>.*?</a>!', '', $description); $product->description = $description; } // price if (preg_match('!цена:\s*<span[^>]*>([^<]*)!', $page, $m)) { $product->price = new Money(l10n::string_to_float(trim($m[1]))); } // dimensions if (preg_match( '!' . 'Размеры:\s*([\d\.,]+)\s*.\s*([\d\.,]+)\s*.\s*([\d\.,]+)\s*</em>\s*' . '</p>\s*<tr>\s*<td\s*class="link">\s*' . '<a\s*href="' . str_replace(array('?'), array('\?'), $url) . '!is', $subbrand_page, $m)) { $product->width = l10n::string_to_float(trim($m[1])); $product->height = l10n::string_to_float(trim($m[2])); $product->depth = l10n::string_to_float(trim($m[3])); $product->volume = round($product->width * $product->height * $product->depth, 1); } $product->save(); if ($creating) { // Product images $image = new Model_Image(); if ( ! $creating) { // Delete already existing images for product $image->delete_all_by_owner_type_and_owner_id('product', $product->id); } preg_match_all( '!<img\s*src="([^"]*_big_[^"]*)"!', $page, $m); foreach (array_unique($m[1]) as $image_url) { $image_url = trim($image_url); $image_file = $this->download_cached($image_url); if ($image_file) { try { $image = new Model_Image(); $image->source_file = $image_file; $image->owner_type = 'product'; $image->owner_id = $product->id; $image->config = 'product'; $image->save(); unset($image); } catch (Exception $e) {} } } } } // foreach $product_id } // foreach $offset }// foreach $subbrand }// foreach $brand */ } } <file_sep>/modules/shop/catalog/classes/form/backend/telemost.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Telemost extends Form_BackendRes { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "w600px"); // ----- place_id $fieldset = new Form_Fieldset('place', array('label' => 'Площадка')); $this->add_component($fieldset); // Store place_id in hidden field $element = new Form_Element_Hidden('place_id'); $this->add_component($element); if ($element->value !== FALSE) { $place_id = (int) $element->value; } else { $place_id = (int) $this->model()->place_id; } // ----- Place name $place = new Model_Place(); $place->find($place_id); $place_name = ($place->id !== NULL) ? $place->name : ''; $element = new Form_Element_Input('place_name', array('label' => 'Площадка', 'disabled' => TRUE, 'layout' => 'wide','required' => TRUE), array('class' => 'w190px') ); $element->value = $place_name; $fieldset->add_component($element); // Button to select place $button = new Form_Element_LinkButton('select_place_button', array('label' => 'Выбрать', 'render' => FALSE), array('class' => 'button_select_place open_window dim500x500') ); $button->url = URL::to('backend/area', array('action' => 'place_select'), TRUE); $this->add_component($button); $element->append = '&nbsp;&nbsp;' . $button->render(); // ----- Description $fieldset->add_component(new Form_Element_Textarea('info', array('label' => 'Дополнительная информация'))); // ----- User properties Request::current()->set_value('spec_group', Model_Group::EDITOR_GROUP_ID); $fieldset = new Form_Fieldset('user', array('label' => 'Пользователь')); $this->add_component($fieldset); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/backend/telemostplace.js'); } } <file_sep>/modules/shop/catalog/classes/model/telemost.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Telemost extends Model_Res { /** * Back up properties before changing (for logging) */ public $backup = TRUE; // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- /** * @return boolean */ public function default_active() { return FALSE; } public function default_visible() { return TRUE; } /** * Get announce for this telemost * * @return Model_Product */ public function get_product() { if ( ! isset($this->_properties['product'])) { $product = new Model_Product(); if ($this->product_id != 0) { $product->find($this->product_id,array('with_image' => 2)); } $this->_properties['product'] = $product; } return $this->_properties['product']; } /** * Get comments for this product */ public function get_goes() { return Model::fly('Model_Go')->find_all_by_telemost_id((int) $this->id); } public function validate(array $newvalues) { $valid = parent::validate($newvalues); if (!$valid) return FALSE; if (isset($newvalues['user_id']) && isset($newvalues['place_id'])) { $user = Model::fly('Model_User')->find($newvalues['user_id']); $place = Model::fly('Model_Place')->find($newvalues['place_id']); if ($user->town_id != $place->town_id) { $this->error('Площадка должна располагаться в городе представителя!'); return FALSE; } } return TRUE; } public function validate_choose() { $allvalues = $this->values(); $dummy_telemost = new Model_Telemost($allvalues); if (Model_Product::COMDI === TRUE && $this->active && $this->event_uri == NULL) { $username = isset($dummy_telemost->user->organizer->name)?$dummy_telemost->user->organizer->name:$dummy_telemost->user->email; $event_uri = TaskManager::start('comdi_register', Task_Comdi_Base::mapping(array( 'role' => 'user', 'username' => $username, 'event_id' => $dummy_telemost->product->event_id ))); if ($event_uri === NULL) { $this->error('Сервис COMDI временно не работает!'); return FALSE; } $this->event_uri = $event_uri; } return TRUE; } /** * Delete productcomment */ public function delete() { $goes = Model::fly('Model_Go')->find_all_by_telemost_id($this->id); foreach ($goes as $go) { $go->delete(); } //@FIXME: It's more correct to log AFTER actual deletion, but after deletion we have all model properties reset //$this->log_delete($this); parent::delete(); } /** * Send e-mail notification about created order */ public function notify() { // $notify_reviewer = 'notify_'.Model_Group::SHOWMAN_GROUP_ID; // $notify_editor = 'notify_'.Model_Group::EDITOR_GROUP_ID; // // if ($this->$notify_reviewer == '1') { // $this->notify_reviewer(); // } elseif ($this->$notify_editor == '1') { // $this->notify_editor(); // } } // public function notify_reviewer() // { // try { // $settings = Model_Site::current()->settings; // // $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; // $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; // $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; // // $reviewer = $this->role; // $email_reviewer = $reviewer->email; // // $editor = $this->product->role; // $email_editor = $editor->email; // // if ($email_sender != '') // { // $email_from = array($email_from => $email_sender); // } // // if ($email_editor != '' && $email_reviewer != '') // { // // Init mailer // SwiftMailer::init(); // $transport = Swift_MailTransport::newInstance(); // $mailer = Swift_Mailer::newInstance($transport); // // // --- Send message to editor // // $message = Swift_Message::newInstance() // ->setSubject('Заявка на рецензию на портале ' . URL::base(FALSE, TRUE)) // ->setFrom($email_from) // ->setTo($email_editor); // // // Message body // $twig = Twig::instance(); // // $template = $twig->loadTemplate('mail/order_editor'); // // $message->setBody($template->render(array( // 'productcomment' => $this, // 'editor' => $editor, // 'reviewer' => $reviewer, // 'article' => $this->product // ))); // // Send message // $mailer->send($message); // // // $message = Swift_Message::newInstance() // ->setSubject('Заявка на рецензию на портале ' . URL::base(FALSE, TRUE)) // ->setFrom($email_from) // ->setTo($email_reviewer); // // // Message body // $twig = Twig::instance(); // // $template = $twig->loadTemplate('mail/order_reviewer'); // // $body = $template->render(array( // 'productcomment' => $this, // 'editor' => $editor, // 'reviewer' => $reviewer, // 'article' => $this->product // )); // // if ($signature != '') // { // $body .= "\n\n\n" . $signature; // } // // $message->setBody($body); // // // Send message // $mailer->send($message); // // } // } // catch (Exception $e) // { // if (Kohana::$environment !== Kohana::PRODUCTION) // { // throw $e; // } // } // } // // public function notify_editor() // { // try { // $settings = Model_Site::current()->settings; // // $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; // $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; // $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; // // $reviewer = $this->role; // $email_reviewer = $reviewer->email; // // $editor = $this->product->role; // $email_editor = $editor->email; // // if ($email_sender != '') // { // $email_from = array($email_from => $email_sender); // } // // if ($email_editor != '' && $email_reviewer != '') // { // // Init mailer // SwiftMailer::init(); // $transport = Swift_MailTransport::newInstance(); // $mailer = Swift_Mailer::newInstance($transport); // // // --- Send message to editor // // $message = Swift_Message::newInstance() // ->setSubject('Завершенная рецензия на портале ' . URL::base(FALSE, TRUE)) // ->setFrom($email_from) // ->setTo($email_editor); // // // Message body // $twig = Twig::instance(); // // $template = $twig->loadTemplate('mail/ok_editor'); // // $message->setBody($template->render(array( // 'productcomment' => $this, // 'editor' => $editor, // 'reviewer' => $reviewer, // 'article' => $this->product // ))); // // Send message // $mailer->send($message); // // // $message = Swift_Message::newInstance() // ->setSubject('Завершенная рецензия на портале ' . URL::base(FALSE, TRUE)) // ->setFrom($email_from) // ->setTo($email_reviewer); // // // Message body // $twig = Twig::instance(); // // $template = $twig->loadTemplate('mail/ok_reviewer'); // // $body = $template->render(array( // 'productcomment' => $this, // 'editor' => $editor, // 'reviewer' => $reviewer, // 'article' => $this->product // )); // // if ($signature != '') // { // $body .= "\n\n\n" . $signature; // } // // $message->setBody($body); // // // Send message // $mailer->send($message); // // } // } // catch (Exception $e) // { // if (Kohana::$environment !== Kohana::PRODUCTION) // { // throw $e; // } // } // } // /** // * Log telemost comment changes // * // */ // public function log_changes(Model_Telemost $new_telemost, Model_Telemost $old_telemost) // { // $text = ''; // // $created = ! isset($old_telemost->id); // // $has_changes = FALSE; // // if ($created) // { // $text .= '<strong>Добавлена заявка на телемост для анонса " {{id-' . $new_telemost->product_id . "}}</strong>\n"; // } // else // { // $text .= '<strong>Изменёна заявка на телемост для анонса {{id-' . $new_telemost->product_id . "}}</strong>\n"; // } // // // ----- info // if ($created) // { // $text .= Model_History::changes_text('Дополнительная информация', $new_telemost->info); // } // elseif ($old_telemost->info != $new_telemost->info) // { // $text .= Model_History::changes_text('Дополнительная информация', $new_telemost->info, $old_telemost->info); // $has_changes = TRUE; // } // // if ($created || $has_changes) // { // // Save text in history // $history = new Model_History(); // $history->text = $text; // $history->item_id = $new_telemost->product_id; // $history->item_type = 'product'; // $history->save(); // } // } // // /** // * Log the deletion of telemost // * // * @param Model_Telemost $telemost // */ // public function log_delete(Model_ProductComment $telemost) // { // $text = 'Удалёна заявка на телемост к анонсу {{id-' . $telemost->product_id . '}}'; // // // Save text in history // $history = new Model_History(); // $history->text = $text; // $history->item_id = $telemost->product_id; // $history->item_type = 'product'; // $history->save(); // } public function get_place(array $params = NULL) { if ( ! isset($this->_properties['place'])) { $place = new Model_Place(); $place->find((int) $this->place_id, $params); $this->_properties['place'] = $place; } return $this->_properties['place']; } }<file_sep>/modules/general/filemanager/classes/form/backend/imageupload.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_ImageUpload extends Form { /** * Initialize form fields */ public function init() { // HTML class $this->set_attribute('class', 'fileupload_form wide'); // ----- File upload $fieldset = new Form_Fieldset('file_upload', array('label' => 'Загрузка файла')); $this->add_fieldset($fieldset); // ----- File $element = new Form_Element_File( 'uploaded_file', NULL, array('label' => 'Загрузить файл') ); $element ->add_validator(new Validator_Upload()) ->set_errors_target($this) ->set_template('<dt></dt><dd>$(label) $(input) $(errors)') ->add_to_fieldset($fieldset); // ----- Submit button $element = new Form_Admin_Element_Button( 'submit', NULL, array('label' => 'Загрузить', 'type' => 'submit'), array('class' => 'ok') ); $element ->set_template('$(input)</dd>') ->add_to_fieldset($fieldset); // ----- Image resizing $image_resize = Kohana::config('filemanager.image_resize'); // ----- Resize $element = new Form_Element_Checkbox( 'resize_image', $image_resize['enable'], array('label' => 'Уменьшить изображение') ); $element ->set_template('<dt></dt><dd>$(input)$(label)$(errors)') ->add_to_fieldset($fieldset); // ----- Width $element = new Form_Element_Input("width", $image_resize['width'], array('label' => 'Ширина'), array('maxlength' => 15, 'class'=>'integer')); $element ->add_filter(new Filter_Trim()) ->add_validator(new Validator_Integer(0)) ->set_template(' до размера: $(input) x ') ->add_to_fieldset($fieldset); // ----- Height $element = new Form_Element_Input("height", $image_resize['height'], array('label' => 'Высота'), array('maxlength' => 15, 'class'=>'integer')); $element ->add_filter(new Filter_Trim()) ->add_validator(new Validator_Integer(0)) ->set_template('$(input)</dd>') ->add_to_fieldset($fieldset); // ----- Resize $element = new Form_Element_Checkbox( 'enable_popups', Kohana::config('filemanager.thumbs.popups.enable'), array('label' => 'Создать всплывающее изображение') ); $element ->set_template('<dt></dt><dd>$(input)$(label)$(errors)</dd>') ->add_to_fieldset($fieldset); } } <file_sep>/modules/system/tasks/classes/taskmanager.php <?php defined('SYSPATH') or die('No direct script access.'); class TaskManager{ /** * Start the specified task - check that it's not already running * and spawn new process in the background * * @param class $task * @param array $params */ public static function start($task, array $params = array()) { if (self::is_running($task)) { FlashMessages::add('Задача уже запущена', FlashMessages::MESSAGE); //return; } //if (Kohana::$is_windows) { // Under windows the task is executed not as a background process, // but as an ordinary request // Fake _GET params if ( ! empty($params)) { foreach ($params as $k => $v) { $_GET[$k] = $v; } } return self::execute($task); } $cmd = 'php ' . DOCROOT . '/index.php --uri=tasks/execute/' . $task; // Pass task parameters in a _GET string format if ( ! empty($params)) { $get = ''; foreach ($params as $name => $value) { $name = (string) $name; if ( ! preg_match('/^\w+$/', $name)) throw new Kohana_Exception('Task parameter name :name contains invalid characters', array(':name' => $name)); if (is_object($value) || is_array($value)) throw new Kohana_Exception('Invalid parameter value type :type', array(':type' => gettype($value))); $get .= $name . '=' . urlencode($value) . '&'; } $cmd .= ' --get="' . $get . '"'; } $output = TMPPATH . '/task_output'; $cmd .= ' > ' . $output . ' 2>&1 &'; exec($cmd); } /** * Is task already runnning? * * @param string $task * @return boolen */ public static function is_running($task) { // Does pidfile exist? $pidfile = TMPPATH . "/$task.pid"; if ( ! is_readable($pidfile)) return FALSE; // No pidfile // Is there a process with specified id? $pid = trim(file_get_contents($pidfile)); if ( !ctype_digit($pid)) return FALSE; // Invalid pid $pid = (int) $pid; // Run `ps` to check that process with this pid is running if ( ! Kohana::$is_windows) { $cols = explode( "\n", trim(shell_exec("ps -p $pid | awk '{print $1}'")) ); if (count($cols) < 2) //@FIXME: do not rely on count. There can be simply error messages. Ought to compare that output is actualy a valid pid return FALSE; // No running process with this pid } return TRUE; } /** * Execute the specified task (must be called in CLI mode) * * @param string $name */ public static function execute($name) { // Check that task is not already running once again //if (self::is_running($name)) //return; // Create task $class = 'Task_' . ucfirst($name); $task = new $class; // Reset task status $task->set_status_info(NULL); $task->set_progress(0); // Create the pid file and save the pid of the process in it $pidfile = TMPPATH . "/$name.pid"; file_put_contents($pidfile, getmypid()); // Run task set_time_limit(0); ini_set('memory_limit', '128M'); ignore_user_abort(TRUE); try { $result = $task->run(); } catch (Exception $e) { $task->log($e->getMessage(), Log::FATAL); if ( ! ($e instanceof Database_Exception)) { // Update status in db only if it's not a database exception $task->set_status_info(Kohana::exception_text($e)); } @unlink($pidfile); // Re-throw the exception, so it will be written into the system log throw $e; } // Remove pid file unlink($pidfile); return $result; } /** * Set value for task * * @param string $task * @param string $key * @param mixed $value */ public static function set_value($task, $key, $value) { if ($value !== NULL) { DbTable::instance('DbTable_TaskValues')->set_value($task, $key, $value); } else { self::unset_value($task, $key); } } /** * Get value for task * * @param string $task * @param string $key * @return mixed */ public static function get_value($task, $key) { return DbTable::instance('DbTable_TaskValues')->get_value($task, $key); } /** * Unset value for task * * @param string $task * @param string $key */ public static function unset_value($task, $key) { DbTable::instance('DbTable_TaskValues')->unset_value($task, $key); } /** * Get log object for the task * * @param string $mode * @return Log_File */ public static function log($task, $mode = Log_File::MODE_WRITE) { return new Log_File(APPPATH . '/logs/' . $task . '.log', $mode, 1); } /** * Read log messages for the specified task * * @param string $task * @return array */ public static function log_messages($task) { return self::log($task, Log_File::MODE_READ)->read(); } /** * Get log stats (number of messages for each log level) for the specified task * * @param string $task * @return array */ public static function log_stats($task) { return self::log($task, Log_File::MODE_READ)->stats(); } }<file_sep>/modules/shop/payment_check/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Common ******************************************************************************/ // Register this payment module Model_Payment::register(array( 'module' => 'check', 'caption' => 'Оплата по квитанции' ));<file_sep>/modules/system/forms/classes/form/element/datetimesimple.php <?php defined('SYSPATH') or die('No direct script access.'); /** * A simple datetime selection input * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_DateTimeSimple extends Form_Element_Input { /** * Use the same templates as the input element * * @return string */ public function default_config_entry() { return 'input'; } /** * Default date display format string * (syntax is like for the date() function) * * @return string */ public function default_format() { return Kohana::config('datetime.datetime_format'); } /** * Render date format as default comment * * @return string */ public function default_comment() { return l10n::translate_datetime_format($this->format); } /** * Get element * * @return array */ public function attributes() { $attributes = parent::attributes(); // Add "integer" HTML class if (isset($attributes['class'])) { $attributes['class'] .= ' datetime'; } else { $attributes['class'] = 'datetime'; } return $attributes; } /** * Set value from model * * @param DateTime $value * @return Form_Element_DateSimple */ public function set_value($value) { if ($value instanceof DateTime) { $value = $value->format($this->format); } $this->_value = $value; return $this; } /** * Get date value * * @return string|integer */ public function get_value() { $value = parent::get_value(); if ($value === '') { // empty date return new DateTime('0000-00-00 00:00:00'); } // convert to format that DateTime::__construct() understands $value = l10n::datetime_convert($value, $this->format, 'Y-m-d H:i:s'); if ($value === FALSE) { // Convertion failed - return empty date return new DateTime('0000-00-00 00:00:00'); } return new DateTime($value); } /** * @return string */ public function get_value_for_validation() { return parent::get_value(); } /** * @return string */ public function get_value_for_render() { return parent::get_value(); } public function render_js() { $js = parent::render_js(); // Link datepicker script $this->add_scripts(); $js .='$(\'#'. $this->id . '\').datetimepicker();'; return $js; } /** * Include required javascripts */ public function add_scripts() { static $datetimesimple_scripts_installed = FALSE; if ( ! $datetimesimple_scripts_installed) { if (Modules::registered('jquery')) { jQuery::add_scripts(); Layout::instance()->add_script(Modules::uri('jquery') . '/public/js/datetimesimple.js'); } $datetimesimple_scripts_installed = TRUE; } } } <file_sep>/modules/shop/acl/classes/model/privilege.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Privilege extends Model { /** * Registered node types * @var array */ protected static $_privilege_types = array(); /** * Add new acl type * * @param string $type * @param array $type_info */ public static function add_privilege_type($type, array $type_info) { self::$_privilege_types[$type] = $type_info; } /** * Returns list of all registered privilege types * * @return array */ public static function privilege_types() { return self::$_privilege_types; } /** * Get privilege type information * * @param string $type Type name * @return array */ public static function privilege_type($type) { if (isset(self::$_privilege_types[$type])) { return self::$_privilege_types[$type]; } else { return NULL; } } public static function privilege_name(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } $controller = $request->controller; $action = $request->action; foreach (self::$_privilege_types as $type => $privilege) { if (isset($privilege['controller']) && isset($privilege['action'])) { if ($privilege['controller'] == $controller && $privilege['action'] == $action) { if (isset($privilege['route_params'])) { $valid = TRUE; foreach ($privilege['route_params'] as $param => $value) { $param_value = $request->param($param,NULL); $valid = $valid & ($param_value == $value); } if (!$valid) continue; } return $type; } } } return NULL; } /** * Get frontend URI to this node * * @return string */ public function get_frontend_uri() { $type_info = self::privilege_type($this->name); if ($type_info === NULL) { throw new Kohana_Exception('Type info for privilege type ":type" was not found! (May be you have fogotten to register this privilege type?)', array(':type' => $this->name)); } $url_params = array(); if (isset($type_info['frontend_route_params'])) { $url_params += $type_info['frontend_route_params']; } return URL::uri_to($type_info['frontend_route'], $url_params); } public function get_readable() { $type_info = self::privilege_type($this->name); if ($type_info === NULL) { throw new Kohana_Exception('Type info for privilege type ":type" was not found! (May be you have fogotten to register this privilege type?)', array(':type' => $this->name)); } return $type_info['readable']; } public function valid(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } $type_info = self::privilege_type($this->name); if ($type_info === NULL) { return FALSE; } $valid = TRUE; if (isset($type_info['access_route_params'])) { foreach ($type_info['access_route_params'] as $param => $value) { $param_value = $request->param($param,NULL); $valid = ($param_value ==$value); } } return $valid; } /** * Set privilege variants * * @param array $options */ public function set_options(array $options) { $options = array_values(array_filter($options)); $this->_properties['options'] = $options; } /** * Created privileges are non-system * * @return boolean */ public function default_system() { return 0; } /** * Prohibit changing the "system" privilege * * @param boolean $value */ public function set_system($value) { //Intentionally blank } /** * Get privilege-group infos * * @return Models */ public function get_privilegegroups() { if ( ! isset($this->_properties['privilegegroups'])) { $this->_properties['privilegegroups'] = Model::fly('Model_PrivilegeGroup')->find_all_by_privilege($this); } return $this->_properties['privilegegroups']; } /** * Get privilege-groups infos as array for form * * @return array */ public function get_privgroups() { if ( ! isset($this->_properties['privgroups'])) { $result = array(); foreach ($this->privilegegroups as $privgroup) { $result[$privgroup->group_id]['active'] = $privgroup->active; } $this->_properties['privgroups'] = $result; } return $this->_properties['privgroups']; } /** * Set privilege-group link info (usually from form - so we need to add 'group_id' field) * * @param array $privgroups */ public function set_privgroups(array $privgroups) { foreach ($privgroups as $group_id => & $privgroup) { if ( ! isset($privgroup['group_id'])) { $privgroup['group_id'] = $group_id; } } $this->_properties['privgroups'] = $privgroups; } /** * Save privilege and link it to selected groups * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); // Link property to selected sections Model::fly('Model_PrivilegeGroup')->link_privilege_to_groups($this, $this->privgroups); } /** * Delete privilege */ public function delete() { // Delete all user values for this privilege Model_Mapper::factory('Model_PrivilegeValue_Mapper')->delete_all_by_privilege_id($this, $this->id); // Delete privilege binding information Model::fly('Model_PrivilegeGroup')->delete_all_by_privilege_id($this->id); // Delete the privilege $this->mapper()->delete($this); } /** * Validate creation/updation of privilege * * @param array $newvalues * @return boolean */ /*public function validate(array $newvalues) { // Check that privilege name is unque if ( ! isset($newvalues['name'])) { $this->error('Вы не указали имя!', 'name'); return FALSE; } if ($this->exists_another_by_name($newvalues['name'])) { $new_privgroups = $newvalues['privgroups']; $old_privileges = $this->find_another_all_by_name($newvalues['name']); foreach ($old_privileges as $old_privilege) { $old_privgroups = $old_privilege->get_privgroups(); foreach ($old_privgroups as $old_key => $old_privgroup) { if ($old_privgroup['active']) { if (isset($new_privgroups[$old_key]) && $new_privgroups[$old_key]['active']) { $this->error('Привилегия с таким именем уже существует!', 'name'); return FALSE; } } } } } return TRUE; }*/ /** * Validate privilege deletion * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->system) { $this->error('Привилегия является системной. Её удаление запрещено!'); return FALSE; } return parent::validate_delete($newvalues); } }<file_sep>/modules/shop/acl/classes/model/acl/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Acl_Mapper extends Model_Mapper { // Turn on find_all_by_...() results caching public $cache_find_all = FALSE; public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('type', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(63)')); $this->add_column('menu_caption', array('Type' => 'varchar(63)')); $this->add_column('alias', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); } /** * Move node up * * @param Model $node * @param Database_Expression_Where $condition */ public function up(Model $node, Database_Expression_Where $condition = NULL) { parent::up($node, DB::where('site_id', '=', $node->site_id)); } /** * Move node down * * @param Model $node * @param Database_Expression_Where $condition */ public function down(Model $node, Database_Expression_Where $condition = NULL) { parent::down($node, DB::where('site_id', '=', $node->site_id)); } }<file_sep>/modules/shop/catalog/classes/form/backend/catalog/updatestats.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Catalog_UpdateStats extends Form_Backend { /** * Initialize form fields */ public function init() { $this->attribute('class', 'w300px'); // Set HTML class //$this->layout = 'wide'; $element = new Form_Element_Text('text'); $element->value = 'Пересчитать значения количества товаров для разделов'; $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Пересчитать'), array('class' => 'button_accept') )); } }<file_sep>/modules/general/filemanager/public/js/tiny_mce/filemanager.js var eresusFileManagerDialogue = { init : function () { // Add onclick event to all file links in current document, so dialog is submitted whenever user clicks on file var file_links = tinymce.DOM.select(".file_link", document); for (var i = 0; i < file_links.length; i++) { tinymce.DOM.bind(file_links[i], 'click', this.submit); } } /** * Submit is called when user clicks on selected file */ ,submit : function (e) { e.preventDefault(); // URL to file var URL = e.target.href; // image popup window var win = tinyMCEPopup.getWindowArg("window"); // insert url into input field win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = URL; // are we an image browser? if (typeof(win.ImageDialog) != "undefined") { // Update image dimensions if (win.ImageDialog.getImageData) win.ImageDialog.getImageData(); // Update preview if (win.ImageDialog.showPreviewImage) win.ImageDialog.showPreviewImage(URL); // Update image description if (win.document.forms[0].elements.alt) { var alt = URL.match(/[^\/]+$/); win.document.forms[0].elements.alt.value = alt; } } // close popup window tinyMCEPopup.close(); } } tinyMCEPopup.onInit.add(eresusFileManagerDialogue.init, eresusFileManagerDialogue);<file_sep>/modules/general/faq/classes/form/backend/question.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Question extends Form_Backend { /** * Initialize form fields */ public function init() { $this->layout = 'wide'; $this->attribute('class', 'lb120px'); // ----- user_name $element = new Form_Element_Input('user_name', array('label' => '<NAME>'), array('maxlength' => 255)); $element->add_filter(new Form_Filter_TrimCrop(255)); $this->add_component($element); // ----- email $element = new Form_Element_Input('email', array('label' => 'E-Mail'), array('maxlength' => 63)); $element->add_filter(new Form_Filter_TrimCrop(63)); $this->add_component($element); // ----- phone $element = new Form_Element_Input('phone', array('label' => 'Телефон'), array('maxlength' => 63)); $element->add_filter(new Form_Filter_TrimCrop(63)); $this->add_component($element); // ----- question $element = new Form_Element_Textarea('question', array('label' => 'Вопрос', 'required' => TRUE)); $element->add_filter(new Form_Filter_TrimCrop(512)); $element->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- answer $element = new Form_Element_Textarea('answer', array('label' => 'Ответ')); $element->add_filter(new Form_Filter_TrimCrop(2048)); $this->add_component($element); // ----- created_at $element = new Form_Element_DateTimeSimple('created_at', array('label' => 'Создан')); $element->add_validator(new Form_Validator_DateTimeSimple()); $this->add_component($element); // ----- active $this->add_component(new Form_Element_Checkbox('active', array('label' => 'Активный'))); // ----- notify $this->add_component(new Form_Element_Checkbox('notify', array( 'label' => 'Оповестить клиента об ответе по e-mail', 'default_value' => ! $this->model()->answered ))); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/shop/catalog/views/frontend/sections/menu_ajax.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'frontend/sections/menu_branch')); $toggle_url = URL::to('frontend/catalog/section', array( 'sectiongroup_name' => $sectiongroup_name, 'path' => '{{path}}', 'toggle' => '{{toggle}}' ), TRUE); render_sections_menu_branch( $sections, $parent, $unfolded, $toggle_url, NULL ); ?><file_sep>/modules/shop/catalog/views/frontend/forms/search.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php echo $form->render_form_open(); ?> <?php echo $form->get_element('search_text')->render_input(); ?> <?php echo $form->render_form_close(); ?> <file_sep>/modules/general/faq/views/backend/questions.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/faq', array('action'=>'create'), TRUE); $update_url = URL::to('backend/faq', array('action'=>'update', 'id' => '{{id}}'), TRUE); $delete_url = URL::to('backend/faq', array('action'=>'delete', 'id' => '{{id}}'), TRUE); $up_url = URL::to('backend/faq', array('action'=>'up', 'id' => '{{id}}'), TRUE); $down_url = URL::to('backend/faq', array('action'=>'down', 'id' => '{{id}}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } $multi_action_uri = URL::uri_to('backend/faq', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Новый вопрос</a> </div> <?php if ( ! count($questions)) // No menus return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="questions table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'date' => 'Дата', 'question_preview' => array( 'label' => 'Вопрос', 'sortable' => FALSE ), 'active' => 'Акт' ); echo View_Helper_Admin::table_header($columns, 'questions_order', 'questions_desc'); ?> <th>&nbsp;&nbsp;&nbsp;</th> </tr> <?php foreach ($questions as $question) : $_delete_url = str_replace('{{id}}', $question->id, $delete_url); $_update_url = str_replace('{{id}}', $question->id, $update_url); $_up_url = str_replace('{{id}}', $question->id, $up_url); $_down_url = str_replace('{{id}}', $question->id, $down_url); $class = ($question->active ? 'active' : 'inactive') . ' ' . ($question->answered ? 'answered' : 'unanswered'); ?> <tr class="<?php echo $class; ?>"> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($question->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'question_preview': echo '<td>' . ' <a href="' . $_update_url . '">' . HTML::chars($question->$field) . ' </a>' . '</td>'; break; case 'active': echo '<td class="c">'; if ( ! empty($question->$field)) { echo View_Helper_Admin::image('controls/on.gif', 'Да'); } else { echo View_Helper_Admin::image('controls/off.gif', 'Нет'); } echo '</td>'; break; default: echo '<td>'; if (isset($question->$field) && trim($question->$field) !== '') { echo HTML::chars($question[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать блок', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить блок', 'controls/delete.gif', 'Удалить'); ?> <?php //echo View_Helper_Admin::image_control($_up_url, 'Переместить вверх', 'controls/up.gif', 'Вверх'); ?> <?php //echo View_Helper_Admin::image_control($_down_url, 'Переместить вниз', 'controls/down.gif', 'Вниз'); ?> </td> </tr> <?php endforeach; ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/backend/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend', new Route_Backend('(/<controller>(/<action>(/<id>)))', array( 'controller' => '\w++', 'action' => '\w++', 'id' => '\d++', ))) ->defaults(array( 'controller' => 'index', 'action' => 'index', 'id' => NULL, )); // ----- Configure menu Model_Backend_Menu::configure('sidebar', array( 'caption' => 'Модули' )); // ----- Add backend menu items Model_Backend_Menu::add_item(array( 'menu' => 'main', 'id' => 2, 'site_required' => TRUE, 'caption' => 'Контент', 'route' => 'backend/nodes', 'icon' => 'pages', 'select_conds' => array( array('route' => 'backend/nodes'), array('route' => 'backend/pages'), array('route' => 'backend/blocks'), array('route' => 'backend/menus'), ) )); }<file_sep>/modules/system/forms/classes/form/filter/trim.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Trim whitespace and cut strings to specified length * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Filter_Trim extends Form_Filter { /** * List of characters to trim. (@see trim) * Defaults to tabs and whitespaces * @var string */ protected $_charlist = " \t"; /** * Creates filter * * @param string $charlist Characters to trim */ public function __construct($charlist = NULL) { if ($charlist !== NULL) { $this->_charlist = $charlist; } } /** * Trims characters from value * * @param string $value */ public function filter($value) { // Trim string value $value = trim((string) $value, $this->_charlist); return $value; } }<file_sep>/modules/general/images/classes/controller/backend/images.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Images extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Image'; $this->_form = 'Form_Backend_Image'; return array( 'create' => array( 'view_caption' => 'Создание изображения' ), 'update' => array( 'view_caption' => 'Редактирование изображения' ), 'delete' => array( 'view_caption' => 'Удаление изображения', 'message' => 'Удалить изображение?' ) ); } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->caption = 'Изображения'; $layout->content = $view; return $layout->render(); } /** * Prepare image for update & delete actions * * @param string $action * @param string|Model $model * @param array $params * @return Model_image */ protected function _model($action, $model, array $params = NULL) { $image = parent::_model($action, $model, $params); if ($action == 'create') { // Set up onwer for image being created $image->owner_type = $this->request->param('owner_type'); $image->owner_id = $this->request->param('owner_id'); } // Set up config for image in action $image->config = $this->request->param('config'); return $image; } /** * Renders list of images for specified owner * * @param string $owner_type * @param integer $owner_id * @return string */ public function widget_images($owner_type, $owner_id, $config) { // Add styles to layout Layout::instance()->add_style(Modules::uri('images') . '/public/css/backend/images.css'); $order_by = $this->request->param('img_order_by', 'position'); $desc = (boolean) $this->request->param('img_desc', '0'); $images = Model::fly('Model_Image')->find_all_by_owner_type_and_owner_id( $owner_type, $owner_id, array('order_by' => $order_by, 'desc' => $desc) ); $view = new View('backend/images'); $view->images = $images; $view->owner_type = $owner_type; $view->owner_id = $owner_id; $view->config = $config; $view->desc = $desc; return $view; } /** * Render one image for specified owner * * @param string $owner_type * @param integer $owner_id * @return string */ public function widget_image($owner_type, $owner_id, $config) { // Add styles to layout Layout::instance()->add_style(Modules::uri('images') . '/public/css/backend/images.css'); $image = new Model_Image(); $image->find_by_owner_type_and_owner_id($owner_type, $owner_id); $image->owner_type = $owner_type; $image->owner_id = $owner_id; $image->config = $config; $view = new View('backend/image'); $view->image = $image; return $view; } }<file_sep>/modules/general/nodes/classes/model/node/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Node_Mapper extends Model_Mapper_NestedSet { // Turn on find_all_by_...() results caching public $cache_find_all = FALSE; public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('type', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(63)')); $this->add_column('menu_caption', array('Type' => 'varchar(63)')); $this->add_column('alias', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('meta_title', array('Type' => 'text')); $this->add_column('meta_description', array('Type' => 'text')); $this->add_column('meta_keywords', array('Type' => 'text')); $this->add_column('layout', array('Type' => 'varchar(63)')); $this->add_column('node_active', array('Type' => 'boolean', 'Key' => 'INDEX')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); } /** * Recalculate overall activity for nodes */ public function update_activity() { $node_table = $this->table_name(); // Subquery to check that there is no inactive parents of current node $sub_q = DB::select('id') ->from(array($node_table, 's')) ->where(DB::expr('s.lft'), '<=', DB::expr($this->get_db()->quote_identifier("$node_table.lft"))) ->and_where(DB::expr('s.rgt'), '>=', DB::expr($this->get_db()->quote_identifier("$node_table.rgt"))) ->and_where(DB::expr('s.node_active'), '=', 0); $exists = DB::expr("NOT EXISTS($sub_q)"); $count = $this->count_rows(); $limit = 100; $offset = 0; $loop_prevention = 0; do { $nodes = DB::select('id', array($exists, 'active')) ->from($node_table) ->offset($offset)->limit($limit) ->execute($this->get_db()); foreach ($nodes as $node) { $this->update(array('active' => $node['active']), DB::where('id', '=', $node['id'])); } $offset += count($nodes); $loop_prevention++; } while ($offset < $count && count($nodes) && $loop_prevention < 1000); if ($loop_prevention >= 1000) { throw new Kohana_Exception('Possible infinite loop in ' . __METHOD__); } } /** * Find all nodes, except the subsection of given one for the specified site * * @param Model $model * @param integer $site_id * @param array $params * @return ModelsTree_NestedSet|Models|array */ public function find_all_but_subtree_by_site_id(Model $model, $site_id, array $params = NULL) { return parent::find_all_but_subtree_by($model, DB::where('site_id', '=', $site_id), $params); } /** * Move node up * * @param Model $node * @param Database_Expression_Where $condition */ public function up(Model $node, Database_Expression_Where $condition = NULL) { parent::up($node, DB::where('site_id', '=', $node->site_id)); } /** * Move node down * * @param Model $node * @param Database_Expression_Where $condition */ public function down(Model $node, Database_Expression_Where $condition = NULL) { parent::down($node, DB::where('site_id', '=', $node->site_id)); } }<file_sep>/modules/system/forms/classes/form.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Forms * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form extends FormComponent { /** * Form elements * @var array array(Form_Element) */ protected $_elements; /** * @var string */ public $template_set = 'table'; /** * Construct form, init form fields * * @param string $name */ public function __construct($name = NULL) { parent::__construct($name); // Initialize form (setup form fields, ...) $this->init(); // Post initialization $this->post_init(); } /** * Default, autogenerated form name. * * [!] It's better not to rely on automatic generation, because it depends on * the order in which forms are rendered/created... * * @return string */ public function default_name() { static $uniq = 1; $name = trim(str_replace('form', '', strtolower(get_class($this))), '_'); $name .= $uniq; $uniq++; return $name; } /** * Default action is current request uri * * @return string */ public function default_action() { // Use current uri return Request::current()->uri; } // ------------------------------------------------------------------------- // Initialization // ------------------------------------------------------------------------- /** * Post init */ public function post_init() { parent::post_init(); // Add hidden input to hold the id of current tab if there are tabs in form $tabs = $this->get_tabs(); if ( ! empty($tabs)) { // Current tab $element = new Form_Element_Hidden('current_tab'); $this->add_component($element); } } // ------------------------------------------------------------------------- // Form elements // ------------------------------------------------------------------------- public function add_element(Form_Element $element) { if (isset($this->_elements[$element->name])) { throw new Kohana_Exception('Form element with name ":name" already exists in form ":form"', array(':name' => $element->name, ':form' => get_class($this))); } $this->_elements[$element->name] = $element; } /** * Get all form elements that are children of this component and it's child components * * @return array array(FormElement) */ public function get_elements() { return $this->_elements; } /** * Does this component have the specified element? * * @param string $name Element name * @return boolean */ public function has_element($name) { return isset($this->_elements[$name]); } /** * Gets form element with specified name * * @param string $name Element name * @return Form_Element */ public function get_element($name) { if (isset($this->_elements[$name])) { return $this->_elements[$name]; } else { return NULL; } } // ------------------------------------------------------------------------- // Templates // ------------------------------------------------------------------------- /** * Default config entry name * * @return string */ public function default_config_entry() { return 'form'; } /** * Default value for form elements layout * * @return string */ public function default_layout() { return 'standart'; } // ------------------------------------------------------------------------- // Form data // ------------------------------------------------------------------------- /** * Returns TRUE if this form was submitted in the request * * @return boolean */ public function is_submitted() { return isset($_POST[$this->name]); } /** * Get value from form post data * * @param string $key * @return string */ public function get_post_data($key) { if ( ! isset($_POST[$this->name])) return NULL; $data =& $_POST[$this->name]; if (strpos($key, '[') !== FALSE) { // Form element name is a hash key $path = str_replace(array('[', ']'), array('.', ''), $key); $value = Arr::path($data, $path); } elseif (isset($data[$key])) { $value = $data[$key]; } else { $value = NULL; } return $value; } /** * Get value from other possible data sources * * @param string $key */ public function get_data($key) { return NULL; } /** * Get Form values for all elements except ignored elements and elements with NULL values * * @return array */ public function get_values() { $data = array(); foreach ($this->get_elements() as $element) { // Skip ignored values and elements that can't have values by definition if ($element->ignored || $element->without_value) continue; $value = $element->value; // Skip NULL values if ($value === NULL) continue; if (strpos($element->name, '[') !== FALSE) { // Form element is a hash key $path = preg_split('/[\[\]]/', $element->name, -1, PREG_SPLIT_NO_EMPTY); $count = count($path); $arr =& $data; foreach ($path as $i => $key) { if ($i < $count - 1) { if ( ! isset($arr[$key])) { $arr[$key] = array(); } $arr =& $arr[$key]; } else { $arr[$key] = $value; } } } else { $data[$element->name] = $value; } } return $data; } /** * Get Form value for specified element. * If element is ignored - returns NULL * * @param string $name Form element name * @return mixed */ public function get_value($name) { $element = $this->get_element($name); if ($element === NULL) { throw new Kohana_Exception('Element ":name" was not found in form ":form"', array(':name' => $name, ':form' => get_class($this)) ); } if ($element->ignored) { return NULL; } else { return $element->value; } } /** * Set default values for form elements * * @param array $values */ public function set_defaults(array $values) { foreach ($this->get_elements() as $element) { $name = $element->name; if (strpos($name, '[') !== FALSE) { // Form element name is a hash key $path = str_replace(array('[', ']'), array('.', ''), $name); $value = Arr::path($values, $path); } elseif (isset($values[$name])) { $value = $values[$name]; } else { $value = NULL; } if ($value !== NULL) { // Set default value $element->default_value = $value; } } } /** * Validate all elements in form, except disabled and ignored ones * * @return boolean */ function validate() { $result = TRUE; $context = $this->get_values(); foreach ($this->_elements as $element) { if ($element->disabled || $element->ignored) { // Skip disabled and ignored elements continue; } if ( ! $element->validate($context)) { $result = FALSE; } } // If validation failed - check if there are tabs in form and // make the tab with the error current foreach ($this->get_components() as $component) { if ( ($component instanceof Form_Fieldset_Tab) && ($component->contains_errors())) { $this->get_element('current_tab')->value = $component->id; } } return $result; } // ------------------------------------------------------------------------- // Rendering // ------------------------------------------------------------------------- /** * Renders form * * @return string Form html */ public function render() { if ($this->view_script !== NULL) { // Render form using View $view = new View($this->view_script); $view->form = $this; $html = $view->render(); } else { // Render form from template $html = $this->get_template('form'); if (Template::has_macro($html, 'messages')) { // Form messages & errors Template::replace($html, 'messages', $this->render_messages()); } // Form opening tag Template::replace($html, 'form_open', $this->render_form_open()); // Hidden elements Template::replace($html, 'hidden', $this->render_hidden()); // Form elements Template::replace($html, 'elements', $this->render_components()); // Form closing tag Template::replace($html, 'form_close', $this->render_form_close()); } // Render form javascripts $this->render_js(); return $html; } /** * Render form open tag * * @return string */ public function render_form_open() { return Form_Helper::open($this->action, $this->attributes()); } /** * Render form close tag * * @return string */ public function render_form_close() { return Form_Helper::close(); } /** * Render javascript for this form */ public function render_js() { // Link required scripts $this->add_scripts(); $js = "var f, e, v;\n\n" . "f = new jForm('{$this->name}', '{$this->id}')\n"; foreach ($this->get_elements() as $element) { if ($element->without_value) continue; $element_js = $element->render_js(); if ($element_js !== NULL) { $js .= $element_js; } } $js .= "\nf.init();\n"; $layout = Layout::instance(); $layout->add_script( " $(document).ready(function(){ $js }); ", TRUE); } /** * Include required javascripts */ public function add_scripts() { static $scripts_installed = FALSE; if ( ! $scripts_installed) { jQuery::add_scripts(); Layout::instance()->add_script(Modules::uri('forms') . '/public/js/forms.js'); $scripts_installed = TRUE; } } /** * Render form via magic method * * @return string Form html */ public function __toString() { return $this->render(); } /** * Renders all not-hidden components * * @param array $include Component to render (NULL - render all) * @param array $exclude Components not to render * @return string */ public function render_components(array $include = NULL, array $exclude = NULL) { $html = ''; foreach ($this->get_components() as $component) { if ( ! ($component instanceof Form_Element_Hidden) && ($include === NULL || in_array($component->name, $include)) && ($exclude === NULL || ! in_array($component->name, $exclude)) && $component->render ) { $html .= $component->render(); } } return $html; } /** * Renders hidden elements * * @return string */ public function render_hidden() { $html = ''; foreach ($this->get_elements() as $element) { if ($element->type == 'hidden') { $html .= $element->render(); } } return $html; } /** * Renders form messages and errors * * @return string */ public function render_messages() { $html = ''; $messages = array_merge($this->_messages, FlashMessages::fetch_all($this->name)); foreach ($messages as $message) { $html .= View_Helper::flash_msg($message['text'], $message['type']); } return $html; } // ------------------------------------------------------------------------- // Errors & messages // ------------------------------------------------------------------------- /** * Manually add error to form or a form element * * @param string $name Element name * @param string $text Error text * @return Form */ function error($text, $element_name = NULL) { if ($element_name === NULL || ! isset($this->_elements[$element_name])) { // General error parent::error($text); } else { // Error for specific element $this->get_element($element_name)->error($text); } return $this; } /** * Adds many errors at once / return component errors * * Errors are in format array(field_name => array(error)) * * @param array $errors * @return Form */ function errors(array $errors = NULL) { if ($errors !== NULL) { // ----- Add errors foreach ($errors as $error) { $element_name = isset($error['field']) ? $error['field'] : NULL; $this->error($error['text'], $element_name); } } // ----- Get errors // General errors $errors = array(); foreach ($this->_messages as $message) { if ($message['type'] == FlashMessages::ERROR) { $errors[] = $message; } } // Element errors foreach ($this->_elements as $element) { foreach ($element->errors() as $error) { $error['field'] = $element->name; $errors[] = $error; } } return $errors; } /** * Add a flash message to form * * @param string $text * @param integer $type * @return Form */ function flash_message($text, $type = FlashMessages::MESSAGE) { FlashMessages::add($text, $type, $this->name); // use form name as category return $this; } // ------------------------------------------------------------------------- // Tabs // ------------------------------------------------------------------------- /** * Get form tabs * * @return array */ public function get_tabs() { if ( ! isset($this->_properties['tabs'])) { $tabs = array(); // Generate all tabs from "Form_Fieldset_Tab" elements foreach ($this->get_components() as $component) { if ($component instanceof Form_Fieldset_Tab) { $tabs[] = array( 'id' => $component->id, 'caption' => $component->label ); } } if ( ! empty($tabs)) { $this->_properties['tabs'] = array( 'prefix' => $this->id, 'tabs' => $tabs ); } else { // Form has no tabs $this->_properties['tabs'] = array(); } } return $this->_properties['tabs']; } /** * Render form tabs (if any) */ public function render_tabs() { $html = ''; $tabs = $this->tabs; if ( ! empty($tabs)) { // Add javascripts to initialize tabs Layout::instance()->add_script('$(function() { var tabs = new Tabs("' . $tabs['prefix'] . '"); });', TRUE); $html .= '<div class="tabs panel_tabs">'; foreach ($tabs['tabs'] as $tab) { $html .= '<a href="#' . $tab['id'] . '">' . $tab['caption'] . '</a>'; } $html .= '</div>'; } return $html; } } <file_sep>/modules/general/chat/classes/model/message/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Message_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('dialog_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('created_at', array('Type' => 'datetime')); $this->add_column('message', array('Type' => 'text')); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('active', array('Type' => 'boolean')); } /*public function find_all_dialogs(Model $model, array $params = NULL) { return $this->find_all_dialogs_by($model, NULL, $params); } public function find_all_dialogs_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->distinct('dialog_id') ->from($table); } if (!isset($params['order_by'])) { $params['order_by'] = 'created_at'; $params['desc'] = FALSE; } $params['for'] = Auth::instance()->get_user(); return parent::find_all_by($model, $condition, $params, $query); }*/ /** * Count all models * * @param Model_Message $model * @return integer */ /*public function count_dialogs(Model_Message $model) { return $this->count_dialogs_by($model, NULL); } */ /** * Count all dialogs by given condition * * @param Model_Message $model * @param string|array|Database_Expression_Where $condition * @return integer */ /*public function count_dialogs_by(Model_Message $model, $condition = NULL, array $params = NULL) { $table = $this->table_name(); $query = DB::select(array('COUNT(DISTINCT "' . $table . '.dialog_id")','total_count')) ->from($table); $user = Auth::instance()->get_user(); $resource_table = Model_Mapper::factory('Model_Resource_Mapper')->table_name(); $pk = $this->get_pk(); $query ->join($resource_table, 'LEFT') ->on("$resource_table.resource_id", '=', "$table.$pk") ->where("$resource_table.role_id", '=', $user->id) ->and_where("$resource_table.resource_type", '=', get_class($model)) ->and_where("$resource_table.role_type", '=', get_class($user)); if ($condition !== NULL) { $condition = $this->_prepare_condition($condition); $query->where($condition, NULL, NULL); } $count = $query->execute($this->get_db()) ->get('total_count'); return (int) $count; }*/ /** * Magic method - automatically resolves the following methods: * - find_all_dialogs_by_* * - count_dialogs_by_* * * @param string $name * @param array $arguments * @return mixed */ /*public function __call($name, array $arguments) { // Model is always a first argument to mapper method $model = array_shift($arguments); // find_all_dialogs_by_* methods if (strpos($name, 'find_all_dialogs_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('find_all_dialogs_by_')), $arguments, $name); $params = array_shift($arguments); return $this->find_all_dialogs_by($model, $condition, $params); } // count_dialogs_by_* methods if (strpos($name, 'count_dialogs_by_') === 0) { $condition = $this->_cols_to_condition_array(substr($name, strlen('count_dialogs_by_')), $arguments, $name); $params = array_shift($arguments); return $this->count_dialogs_by($model, $condition, $params); } return parent::__call($name, $arguments); }*/ }<file_sep>/application/views/layouts/index.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require('_header.php'); ?> <div id="container"> <?php echo $content; ?> <div id="tops"><div id="out"> <?php echo Widget::render_widget('plists', 'plist', 'top5_ch_3'); ?> <?php echo Widget::render_widget('plists', 'plist', 'top5_ch_3_6'); ?> <?php echo Widget::render_widget('plists', 'plist', 'top5_boys'); ?> <?php echo Widget::render_widget('plists', 'plist', 'top5_girls'); ?> </div></div> </div> <?php require('_footer.php'); ?><file_sep>/modules/shop/catalog/classes/model/propertysection/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PropertySection_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('property_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('section_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('active', array('Type' => 'boolean', 'Key' => 'INDEX')); $this->add_column('sort', array('Type' => 'boolean')); $this->add_column('filter', array('Type' => 'boolean')); } /** * Link property to given sections * * @param Model_Property $property * @param array $propsections */ public function link_property_to_sections(Model_Property $property, array $propsections) { $this->delete_rows(DB::where('property_id', '=', (int) $property->id)); foreach ($propsections as $propsection) { $propsection['property_id'] = $property->id; $this->insert($propsection); } } /** * Link section to given properties * * @param Model_Section $section * @param array $propsections */ public function link_section_to_properties(Model_Section $section, array $propsections) { $this->delete_rows(DB::where('section_id', '=', (int) $section->id)); foreach ($propsections as $propsection) { $propsection['section_id'] = $section->id; $this->insert($propsection); } } /** * Find all property-section infos by given section * * @param Model_PropertySection $propsec * @param Model_Section $section * @param array $params * @return Models */ public function find_all_by_section(Model_PropertySection $propsec, Model_Section $section, array $params = NULL) { $propsec_table = $this->table_name(); $property_table = Model_Mapper::factory('Model_Property_Mapper')->table_name(); $section_table = Model_Mapper::factory('Model_Section_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array( array("$property_table.id", 'property_id'), "$property_table.caption", "$property_table.system", "$propsec_table.active", "$propsec_table.filter", "$propsec_table.sort" ); $query = DB::select_array($columns) ->from($property_table) ->join($propsec_table, 'LEFT') ->on("$propsec_table.property_id", '=', "$property_table.id") ->on("$propsec_table.section_id", '=', DB::expr((int) $section->id)); $data = parent::select(NULL, $params, $query); // Add section properties foreach ($data as & $properties) { $properties['section_id'] = $section->id; $properties['section_caption'] = $section->caption; } return new Models(get_class($propsec), $data); } /** * Find all property-section infos by given property * * @param Model_PropertySection $propsec * @param Model_Property $property * @param array $params * @return Models */ public function find_all_by_property(Model_PropertySection $propsec, Model_Property $property, array $params = NULL) { $propsec_table = $this->table_name(); $property_table = Model_Mapper::factory('Model_Property_Mapper')->table_name(); $section_table = Model_Mapper::factory('Model_Section_Mapper')->table_name(); $sectiongroup_table = Model_Mapper::factory('Model_SectionGroup_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array( array("$section_table.id", 'section_id'), array("$section_table.caption", 'section_caption'), "$propsec_table.active", "$propsec_table.filter", "$propsec_table.sort" ); $query = DB::select_array($columns) ->from($section_table) ->join($sectiongroup_table, 'INNER') ->on("$sectiongroup_table.id", '=', "$section_table.sectiongroup_id") ->join($propsec_table, 'LEFT') ->on("$propsec_table.section_id", '=', "$section_table.id") ->on("$propsec_table.property_id", '=', DB::expr((int) $property->id)); $data = parent::select(DB::where("$sectiongroup_table.site_id", '=', $property->site_id), $params, $query); // Add property properties foreach ($data as & $properties) { $properties['property_id'] = $property->id; $properties['caption'] = $property->caption; $properties['system'] = $property->system; } return new Models(get_class($propsec), $data); } }<file_sep>/modules/general/menus/views/menu_templates/submenu.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ( ! count($nodes)) { // No menu nodes return; } ?> <ul id="submenu"> <?php foreach ($nodes as $node) { $selected = isset($path[$node->id]); echo '<li><a href="' . URL::site($node->frontend_uri) . '"' . ($selected ? ' class="current"' : '') . '>' . HTML::chars($node->caption) . '</a></li>'; } ?> </ul><file_sep>/modules/general/filemanager/classes/form/backend/file.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_File extends Form { protected $_is_dir; protected $_creating; public function __construct($is_dir = FALSE, $creating = FALSE) { $this->_is_dir = $is_dir; $this->_creating = $creating; parent::__construct(); } /** * Initialize form fields */ public function init() { // HTML class $this->attribute('class', 'wide w500px lb120px'); // ----- Base name $element = new Form_Element_Input('base_name', array('label' => 'Имя ' . ($this->_is_dir ? 'директории' : 'файла'), 'required' => TRUE), array('class' => 'input_file_name', 'maxlength' => 63) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Filename()); $this->add_component($element); // ----- Folder name if ( ! $this->_is_dir || ! $this->_creating) { // Only if not creating a directory $element = new Form_Element_Input('relative_dir_name', array('label' => 'Директория'), array('class' => 'input_file_name', 'maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)); $this->add_component($element); } // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/shop/discounts/classes/model/coupon/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Coupon_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('code', array('Type' => 'char(8)', 'Key' => 'INDEX')); $this->add_column('user_id', array('Type' => 'int unsigned')); $this->add_column('discount_percent', array('Type' => 'float')); $this->add_column('discount_sum', array('Type' => 'money')); $date_type = Model_Coupon::$date_as_timestamp ? 'unix_timestamp' : 'date'; $this->add_column('valid_after', array('Type' => $date_type)); $this->add_column('valid_before', array('Type' => $date_type)); $this->add_column('multiple', array('Type' => 'boolean')); $this->add_column('description', array('Type' => 'text')); $this->add_column('settings', array('Type' => 'array')); } /** * Find all coupons with info about user and sites it's valid in * * @param Model $model * @param Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by( Model $model, Database_Expression_Where $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { $coupon_table = $this->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array("$coupon_table.*"); // user_name $user_table = Model_Mapper::factory('Model_User_Mapper')->table_name(); $user_name_q = DB::select(DB::expr( "CONCAT(" . $this->get_db()->quote_identifier("$user_table.last_name") . ", ' ', " . $this->get_db()->quote_identifier("$user_table.first_name") . ")" )) ->from($user_table) ->where("$user_table.id", '=', DB::expr($this->get_db()->quote_identifier("$coupon_table.user_id"))); $columns[] = array($user_name_q, 'user_name'); // site_captions $site_table = Model_Mapper::factory('Model_Site_Mapper')->table_name(); $couponsite_table = Model_Mapper::factory('CouponSite_Mapper')->table_name(); $site_captions_q = DB::select(DB::expr("GROUP_CONCAT(" . $this->get_db()->quote_identifier("$site_table.caption") . ")")) ->from($site_table) ->join($couponsite_table) ->on("$couponsite_table.site_id", '=', "$site_table.id") ->where("$couponsite_table.coupon_id", '=', DB::expr($this->get_db()->quote_identifier("$coupon_table.id"))) ->group_by(DB::expr("'ALL'")); $columns[] = array($site_captions_q, 'site_captions'); $params['columns'] = $columns; return parent::find_all_by($model, $condition, $params, $query); } }<file_sep>/modules/general/menus/classes/form/backend/menu.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Menu extends Form_Backend { /** * Initialize form fields */ public function init() { // Set html class $this->attribute('class', 'lb150px'); $this->layout = 'wide'; // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $this->add_component($cols); // ----- Name $element = new Form_Element_Input('name', array('label' => 'Имя', 'required' => TRUE), array('maxlength' => 15)); $element ->add_filter(new Form_Filter_TrimCrop(15)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Alnum()); $cols->add_component($element); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $cols->add_component($element); // ----- Root_node_id $node = new Model_Node(); $nodes = $node->find_all(array('order_by' => 'lft', 'desc' => FALSE, 'columns' => array('id', 'lft', 'rgt', 'level', 'caption'))); $options = array(0 => '---'); foreach ($nodes as $node) { $options[$node['id']] = str_repeat('&nbsp;', ((int)$node->level - 1) * 2) . Text::limit_chars($node->caption, 30); } $element = new Form_Element_Select('root_node_id', $options, array('label' => 'Корневая страница', 'required' => TRUE)); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- View // Select all *.php files from views/menu_templates directory $options = array(); $templates = glob(Modules::path('menus') . 'views/menu_templates/*.php'); foreach ($templates as $template) { $template = basename($template, '.php'); $options[$template] = $template; } $element = new Form_Element_Select('view', $options, array('label' => 'Шаблон', 'required' => TRUE)); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- Additional settings $fieldset = new Form_Fieldset('settings', array('label' => 'Дополнительные настройки')); $cols->add_component($fieldset); // ----- Maximum level $element = new Form_Element_Input('max_level', array('label' => 'Макс. уровень вложенности'), array('class' => 'integer')); $element ->add_validator(new Form_Validator_Integer(0, NULL)); $element->comment = 'Относительно корневого раздела. 0 - не ограничивать'; $fieldset->add_component($element); // ----- root_selected $fieldset ->add_component(new Form_Element_Checkbox('settings[root_selected]', array('label' => 'Корневая страница из выбранной ветки'))); // ----- selected_level $element = new Form_Element_Input('settings[root_level]', array('label' => 'Уровень корневой страницы в выбранной ветке'), array('class' => 'integer')); $element ->add_validator(new Form_Validator_Integer()); $element->comment = '0 - использовать текущую страницу, <br />отрицательное значение - отсчитывать от уровня текущей страницы'; $fieldset->add_component($element); // ----- Nodes visibility $options = array(); $value = array(); foreach ($nodes as $node) { $options[$node->id] = str_repeat('&nbsp;', ((int)$node->level - 1) * 4) . $node->caption; } $element = new Form_Element_CheckSelect('nodes_visibility', $options, array('label' => 'Страницы в меню')); $element->config_entry = 'checkselect_fieldset'; $cols->add_component($element,2 ); // ----- Default_visibility $element = new Form_Element_Checkbox('default_visibility', array('label' => 'Новые страницы видимы по умолчанию')); $cols->add_component($element,2); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/system/tasks/views/backend/task_log.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="task_log"> <?php foreach ($messages as $message) { $text = ''; switch ($message['level']) { case Log::WARNING: $text .= '<span class="warning">Предупреждение:</span>'; break; case Log::ERROR: $text .= '<span class="error">Ошибка:</span>'; break; case Log::FATAL: $text .= '<span class="fatal">Критическая ошибка:</span>'; break; } $text .= $message['message']; echo '<div class="log_message">' . nl2br($text). '</div>'; } ?> </div><file_sep>/modules/shop/area/classes/form/frontend/place.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Place extends Form_Frontend { /** * Initialize form fields */ public function init() { // Set HTML class $this->view_script = 'frontend/forms/place'; // ----- Name $element = new Form_Element_Input('name', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 63, 'placeholder' =>'Название' )); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); $element = new Form_Element_Hidden('town_id'); $this->add_component($element); $element->value = Model_User::current()->town->id; // ----- Address $element = new Form_Element_TextArea('address', array('label' => 'Адрес'),array('placeholder' => 'Адрес площадки')); $element ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- Description $element = new Form_Element_TextArea('description', array('label' => 'Описание'),array('placeholder' => 'Описание площадки')); $element ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- ISpeed $options = Model_Place::$_ispeed_options; $element = new Form_Element_Select('ispeed', $options, array('label' => 'Качество сети')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- External Links $options_count = 1; if ($this->model()->id) { $options_count = count($this->model()->links); } $element = new Form_Element_Options("links", array('label' => 'Ссылки', 'options_count' => $options_count,'options_count_param' => 'options_count','option_caption' => 'добавить ссылку'), array('maxlength' => Model_Lecturer::LINKS_LENGTH,'placeholder' => 'Сайт площадки') ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Place::LINKS_LENGTH)); $this->add_component($element); // ----- File $element = new Form_Element_File('file', array('label' => 'Загрузить фото'),array('placeholder' => 'Загрузить фото')); $element->add_validator(new Form_Validator_File(NULL,TRUE,TRUE)); $this->add_component($element); // ----- Form buttons $button = new Form_Element_Button('submit_place', array('label' => 'Добавить'), array('class' => 'button button-modal') ); $this->add_component($button); } } <file_sep>/modules/shop/acl/classes/controller/backend/organizers.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Organizers extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Organizer'; $this->_form = 'Form_Backend_Organizer'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание организации' ), 'update' => array( 'view_caption' => 'Редактирование организации', ), 'delete' => array( 'view_caption' => 'Удаление организации', 'message' => 'Удалить организацию ":name" ' ), 'multi_delete' => array( 'view_caption' => 'Удаление организаций', 'message' => 'Удалить выбранные организации?' ) ); } /** * Create layout (proxy to acl controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Render all available section properties */ public function action_index() { $this->request->response = $this->render_layout($this->widget_organizers()); } /** * Renders list of organizers * * @return string Html */ public function widget_organizers() { $organizer = new Model_Organizer(); $order_by = $this->request->param('acl_oorder', 'id'); $desc = (bool) $this->request->param('acl_odesc', '0'); $per_page = 20; // Select all organizers $count = $organizer->count(); $pagination = new Paginator($count, $per_page); $organizers = $organizer->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); $view = new View('backend/organizers'); $view->order_by = $order_by; $view->desc = $desc; $view->organizers = $organizers; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Select several towns */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор организаций на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_select(); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_select()); } } /** * Render list of towns to select several towns * @param integer $select * @return string */ public function widget_select($select = FALSE) { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } // ----- Render section for current section group $order_by = $this->request->param('acl_oorder', 'name'); $desc = (bool) $this->request->param('acl_odesc', '0'); $organizers = Model::fly('Model_Organizer')->find_all(array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/organizers/select'); $view->order_by = $order_by; $view->desc = $desc; $view->organizers = $organizers; return $view->render(); } /** * Handles the selection of access organizers for event */ public function action_organizers_select() { if ( ! empty($_POST['ids']) && is_array($_POST['ids'])) { $organizer_ids = ''; foreach ($_POST['ids'] as $organizer_id) { $organizer_ids .= (int) $organizer_id . '_'; } $organizer_ids = trim($organizer_ids, '_'); $this->request->redirect(URL::uri_back(NULL, 1, array('access_organizer_ids' => $organizer_ids))); } else { // No towns were selected $this->request->redirect(URL::uri_back()); } } /** * Generate redirect url * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { if ($action == 'create') { return URL::uri_self(array('action'=>'update', 'id' => $model->id, 'history' => $this->request->param('history'))) . '?flash=ok'; } if ($action == 'update') { return URL::uri_to('backend/acl/organizers'); } if ($action == 'multi_link') { return URL::uri_back(); } return parent::_redirect_uri($action, $model, $form, $params); } /** * Display autocomplete options for a postcode form field */ public function action_ac_organizer_name() { $organizer_name = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $organizer_name = UTF8::str_ireplace("ё", "е", $organizer_name); if ($organizer_name == '') { $this->request->response = ''; return; } $limit = 7; $organizers = Model::fly('Model_Organizer')->find_all_like_name($organizer_name,array('limit' => $limit)); if ( ! count($organizers)) { $this->request->response = ''; return; } $items = array(); $pattern = new View('frontend/organizer_ac'); $i=0; foreach ($organizers as $organizer) { $name = $organizer->name; $id = $organizer->id; $image_info = $organizer->image(4); $pattern->name = $name; $pattern->num = $i; $pattern->image_info = $organizer->image(4); $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name, 'id' => $id) ); $i++; } $this->request->response = json_encode($items); } } <file_sep>/modules/system/database_eresus/classes/database.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Database connection wrapper. * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Database extends Kohana_Database { /** * Returns information about database table, * including information about columns and indexes * * Results are obtained via 'SHOW COLUMNS FROM' and 'SHOW INDEXES FROM' sql commands. * * @param string Table name * @return array Array of columns (including indexes) */ public function describe_table($table_name) { //abstract } /** * Creates table in database (if not already exists) with supplied columns and indexes. * * Columns is an array of column_name => column_properties * For avaliable column_properties keys @see _column_sql * * Indexes is an array of index_name => index_properties * For avaliable index_properties keys @see _index_sql * * @param string $table_name Name of the table * @param array $columns Columns for the table * @param array $indexes Indexes for the table * @param array $options Table options */ public function create_table($table_name, array $columns, array $indexes, array $options, $if_not_exists = TRUE) { //abstract } /** * Alter table in database: * adds columns $columns_to_add, * drops columns $columns_to_drop, * adds indexes $indexes_to_add, * drops indexes $indexes_to_drop * * Format of columns and indexes array is the same as in @link create_table * * @param string $table_name * @param array $columns_to_add Columns to add * @param array $columns_to_drop Columns to drop * @param array $indexes_to_add Indexes to add * @param array $indexes_to_drop Indexes to drop */ public function alter_table($table_name, array $columns_to_add, array $columns_to_drop, array $indexes_to_add, array $indexes_to_drop) { //abstract } } // End Database <file_sep>/modules/shop/orders/classes/model/ordercomment/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_OrderComment_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('order_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('created_at', array('Type' => 'int unsigned')); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('user_name', array('Type' => 'varchar(255)')); $this->add_column('text', array('Type' => 'text')); $this->add_column('notify_client', array('Type' => 'boolean')); } }<file_sep>/modules/shop/catalog/classes/task/comdi/create.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Create event through COMDI API */ class Task_Comdi_Create extends Task_Comdi_Base { public static $params = array( 'key', 'name', 'time', 'description', 'access', 'maxAllowedUsers' ); /** * Default parameters for this task * @var array */ public static $default_params = array( 'access' => 'open', 'maxAllowedUsers' => 50, ); /** * Construct task */ public function __construct() { parent::__construct('http://my.webinar.ru'); $this->default_params(self::$default_params); } /** * Run the task */ public function run() { $xml_response = parent::send('/api0/Create.php',$this->params(self::$params)); $id = ($xml_response['event_id'] == null)? null:(string)$xml_response['event_id']; if ($id === NULL) { $this->set_status_info('Событие не было создано'); } else { $this->set_status_info('Событие создано'); } return $id; } } <file_sep>/modules/shop/acl/classes/model/link.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Link extends Model { const MAXLENGTH = 63; // Maximum length for the link value /** * Default property type * * @return integer */ public function default_site_id() { return Model_SIte::current()->id; } /** * Delete link */ public function delete() { // Delete all user values for this link Model_Mapper::factory('Model_LinkValue_Mapper')->delete_all_by_link_id($this, $this->id); // Delete the link $this->mapper()->delete($this); } /** * Validate creation/updation of link * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { // Check that link name is unque if ( ! isset($newvalues['name'])) { $this->error('Вы не указали имя!', 'name'); return FALSE; } if ($this->exists_another_by_name($newvalues['name'])) { $this->error('Внешняя ссылка с таким именем уже существует!', 'name'); return FALSE; } return TRUE; } }<file_sep>/README.md vse.to(VSE.TO) ====== vsё.to – первая социальная сеть телемостов и вебинаров. vsё.to соединяет живые события (лекции, концерты, кино) с живыми аудиториями (в клубах, библиотеках, музеях) и даёт лекторам и зрителям возможность видеть и слышать друг друга в реальном времени. У лекций vsё.to появляются новые аудитории в других городах, а у зрителей, живущих в городах vsё.to, - возможность участвовать в событиях, происходящих во всём мире.<file_sep>/modules/shop/acl/classes/model/group/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Group_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('system', array('Type' => 'boolean')); $this->add_column('name', array('Type' => 'varchar(31)')); } /** * Find group by condition * Load additional properties * * @param Model $model * @param string|array|Database_Condition_Where $condition * @param array $params * @param Database_Query_Builder_Select $query */ public function find_by(Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->from($table); } if ( ! isset($params['with_privileges']) || ! empty($params['with_privileges'])) { $priv_condition = array( 'site_id' => Model_Site::current()->id, 'system' => 0, 'active' => '1' ); if (isset($condition['id'])) { $priv_condition['group_id'] = $condition['id']; } // Select groups with additional (non-system) privilege values $privileges = Model::fly('Model_Privilege')->find_all_by( $priv_condition, array( 'columns' => array('id', 'name'), 'order_by' => 'position', 'desc' => FALSE, 'as_array' => TRUE )); $table = $this->table_name(); $privilegevalue_table = Model_Mapper::factory('Model_PrivilegeValue_Mapper')->table_name(); foreach ($privileges as $privilege) { $id = (int) $privilege['id']; // Add column to query $query->select(array(DB::expr("privval$id.value"), $privilege['name'])); $query->join(array($privilegevalue_table, "privval$id"), 'LEFT') ->on(DB::expr("privval$id.privilege_id"), '=', DB::expr($id)) ->on(DB::expr("privval$id.group_id"), '=', "$table.id"); } } return parent::find_by($model, $condition, $params, $query); } /** * Find all models by criteria and return them in {@link Models} container * * @param Model $model * @param string|array|Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by( Model $model, $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { $table = $this->table_name(); if ($query === NULL) { $query = DB::select_array($this->_prepare_columns($params)) ->distinct('whatever') ->from($table); } // ----- process contition if (is_array($condition) && ! empty($condition['ids'])) { // find product by several ids $query->where("$table.id", 'IN', DB::expr('(' . implode(',', $condition['ids']) . ')')); unset($condition['ids']); } if ( ! empty($params['with_privileges'])) { // Select product with additional (non-system) property values // @TODO: use only properties for current section $privileges = Model::fly('Model_Privilege')->find_all_by_site_id_and_system(Model_Site::current()->id, 0, array( 'columns' => array('id', 'name'), 'order_by' => 'position', 'desc' => FALSE, 'as_array' => TRUE )); $table = $this->table_name(); $privilegevalue_table = Model_Mapper::factory('Model_PrivilegeValue_Mapper')->table_name(); foreach ($privileges as $privilege) { $id = (int) $privilege['id']; // Add column to query $query->select(array(DB::expr("privval$id.value"), $privilege['name'])); $query->join(array($privilegevalue_table, "privval$id"), 'LEFT') ->on(DB::expr("privval$id.privilege_id"), '=', DB::expr($id)) ->on(DB::expr("privval$id.group_id"), '=', "$table.id"); } } return parent::find_all_by($model, $condition, $params, $query); } }<file_sep>/modules/general/faq/config/faq.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( 'email' => array( 'client' => array( 'subject' => 'Ответ на Ваш вопрос на сайте "{{site}}"', 'body' => '{% if user_name %}Здравствуйте, {{ user_name }}!{% else %}Здравствуйте!{% endif %} На заданный Вами вопрос ----------------------- {{question}} был получен ответ: ------------------ {{answer}}' ), 'admin' => array( 'subject' => 'Новый вопрос с сайта "{{site}}"', 'body' => '{% if user_name %}Имя пользователя: {{ user_name }} {% endif %}{% if email %}E-Mail: {{ email }} {% endif %}{% if phone %}Телефон: {{ phone }} {% endif %} Вопрос: ------- {{question}}' ) ) );<file_sep>/modules/system/forms/classes/form/validator/equalto.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validates the equality of value to another value. * (Such as password confirmation) * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_EqualTo extends Form_Validator { const NOT_EQUAL = 'NOT_EQUAL'; protected $_messages = array( self::NOT_EQUAL => 'Value is not equal to target value' ); /** * Name of element to compare value with * @var string */ protected $_target; /** * Creates validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure */ public function __construct($target, array $messages = NULL, $breaks_chain = TRUE) { parent::__construct($messages, $breaks_chain); $this->_target = $target; } /** * Validate! * * @param array $context */ protected function _is_valid(array $context = NULL) { if ( ! is_array($context)) { // Context is required for confirmation throw new Exception('Context was not supplied to _is_valid function of validator ":validator"', array(':validator' => get_class($this)) ); } if ( ! isset($context[$this->_target])) { throw new Exception('Unable to compare with :target - no such key in context data. (":validator")', array(':target' => $this->_target, ':validator' => get_class($this)) ); } $value = (string) $this->_value; $target_value = (string) $context[$this->_target]; if ($value !== $target_value) { $this->_error(self::NOT_EQUAL); return false; } return true; } /** * Render javascript for this validator * * @return string */ public function render_js() { $error = $this->_messages[self::NOT_EQUAL]; $error = $this->_replace_placeholders($error); $js = "v = new jFormValidatorEqualTo('" . $this->_target . "', '" . $error . "');\n"; return $js; } }<file_sep>/modules/general/filemanager/views/backend/filemanager.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <h1>Файловый менеджер</h1> <?php echo View_Helper_Admin::tabs(array( 'files' => 'Файлы', 'css' => 'Оформление', 'templates' => 'Шаблоны' ), $root, NULL, 'root', array('path' => NULL)); ?> <div class="panel"> <div class="content"> <?php echo $files; ?> </div> </div> <file_sep>/modules/shop/orders/classes/form/frontend/checkout.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Checkout extends Form_Frontend { public function init() { // ----- name $element = new Form_Element_Input('name', array( 'label' => 'Ваше имя', 'required' => TRUE, 'comment' => 'Как нам к вам обращаться?' ), array( 'size' => '80', 'maxlength' => '63', ) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- phone $element = new Form_Element_Input('phone', array( 'label' => 'Телефоны для связи', 'required' => TRUE, 'comment' => 'Мы обязательно захотим вам позвонить, но вы не всегда бываете дома или на работе. Поэтому, огромная просьба, - указывайте номер мобильного телефона, который всегда при себе.' ), array( 'size' => '80', 'maxlength' => '63', ) ); $element ->add_filter(new Form_Filter_TrimCrop(63)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- email $element = new Form_Element_Input('email', array( 'label' => 'E-mail', 'required' => TRUE, 'comment' => 'На введенный адрес придет уведомление с номером заказа, который вы в дальнейшем сможете использовать при общении с менеджерами нашего магазина.' ), array( 'size' => '80', 'maxlength' => '31', ) ); $element ->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- address $element = new Form_Element_Textarea('address', array( 'label' => 'Адрес доставки', 'required' => TRUE, 'comment' => 'Пожалуйста, указывайте адрес максимально точно. Если найти адрес на месте тяжело, подскажите, пожалуйста, как вас лучше искать.' ), array( 'cols' => '80', 'rows' => '5' ) ); $element ->add_filter(new Form_Filter_TrimCrop(1023)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- comment $element = new Form_Element_Textarea('comment', array( 'label' => 'Дополнительная информация по заказу', 'comment' => 'Любые пожелания и предложения' ), array( 'cols' => '80', 'rows' => '5' ) ); $element ->add_filter(new Form_Filter_TrimCrop(1023)); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Element_Submit('submit', array('label' => 'Заказать'), array('class' => 'submit') )); } } <file_sep>/modules/system/forms/classes/form/element/date.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form date element. * Rendered as three input elements for day, month and year * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Date extends Form_Element_Input { public function default_format() { return Kohana::config('date.date_format'); } /** * Sets date value either from string or from array * String format should be yyyy-mm-dd * Array should contain three elements: day, month and year * * @param array | string $value * @return Form_Element_Date */ function set_value($value) { if (is_int($value) || ctype_digit($value)) { //Unix timestamp $value = (int) $value; $day = date('d', $value); $month = date('m', $value); $year = date('Y', $value); } elseif (is_array($value)) { // Expecting array (day, month, year) $day = isset($value['day']) ? $value['day'] : '00'; $month = isset($value['month']) ? $value['month'] : '00'; $year = isset($value['year']) ? $value['year'] : '0000'; } else { // Expecting string in yyyy-mm-dd format $value = explode('-', (string)$value); $day = isset($value[2]) ? $value[2] : '00'; $month = isset($value[1]) ? $value[1] : '00'; $year = isset($value[0]) ? $value[0] : '0000'; } $value = array( 'day' => $day, 'month' => $month, 'year' => $year ); parent::set_value($value); } /** * Get date value * * @return string Date in yyyy-mm-dd format */ function get_value() { return "$this->day-$this->month-$this->year"; } /** * Returns day * * @return string */ function get_day() { $value = parent::get_value(); return $value['day']; } /** * Returns month * * @return string */ function get_month() { $value = parent::get_value(); return $value['month']; } /** * Returns year * * @return string */ function get_year() { $value = parent::get_value(); return $value['year']; } /** * @return string */ public function default_comment() { return 'Формат: ДД-ММ-ГГГГ'; } /** * Renders date element as three text inputs for day, month and year * * @return string */ public function render_input() { $attributes = $this->attributes(); $html = ''; // Day $attrs = $attributes; $attrs['id'] .= '-day'; $attrs['class'] .= ' day'; $attrs['maxlength'] = 2; $html .= Form_Helper::input($this->full_name.'[day]', $this->day, $attrs); $html .= '&nbsp;-&nbsp;'; // Month $attrs = $attributes; $attrs['id'] .= '-month'; $attrs['class'] .= ' month'; $attrs['maxlength'] = 2; $html .= Form_Helper::input($this->full_name.'[month]', $this->month, $attrs); $html .= '&nbsp;-&nbsp;'; // Year $attrs = $attributes; $attrs['id'] .= '-year'; $attrs['class'] .= ' year'; $attrs['maxlength'] = 4; $html .= Form_Helper::input($this->full_name.'[year]', $this->year, $attrs); return $html; } } <file_sep>/modules/shop/acl/views/backend/lecturers.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php //Set up urls $create_url = URL::to('backend/acl/lecturers', array('action'=>'create'), TRUE); $update_url = URL::to('backend/acl/lecturers', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/acl/lecturers', array('action'=>'delete', 'id' => '${id}'), TRUE); $multi_action_uri = URL::uri_to('backend/acl/lecturers', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_user_add">Создать лектора</a> </div> <?php if ( ! count($lecturers)) // No users return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'image' => 'Фото', 'last_name' => 'Фамилия', 'first_name' => 'Имя' ); echo View_Helper_Admin::table_header($columns, 'acl_lorder', 'acl_ldesc'); ?> <th></th> </tr> <?php foreach ($lecturers as $lecturer) : $image_info = $lecturer->image(4); $_delete_url = str_replace('${id}', $lecturer->id, $delete_url); $_update_url = str_replace('${id}', $lecturer->id, $update_url); ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($lecturer->id); ?> </td> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if ($field === 'image') { echo HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'])) . '</a></td>'; } if (isset($lecturer->$field) && trim($lecturer->$field) !== '') { echo HTML::chars($lecturer->$field); } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать лектора', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить лектора', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; //foreach ($lecturers as $lecturer) ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/general/filemanager/views/backend/filemanager_tinymce.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="panel"> <div class="content"> <?php echo $files; ?> </div> </div> <file_sep>/modules/general/faq/views/frontend/faq.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $url = URL::to('frontend/faq', array('action' => 'question', 'id' => '{{id}}')); ?> <table class="faq"><tr> <td class="questions_cell"> <?php if ( ! count($questions)): echo '<i>Вопросов пока нет</i>'; else: ?> <?php if (isset($pagination)) echo $pagination; ?> <div class="questions"> <?php foreach ($questions as $question) : $_url = str_replace('{{id}}', $question->id, $url); ?> <div class="question"> <div class="q"><strong>Вопрос:</strong> <?php echo HTML::chars($question->question); ?></div> <div class="a"><strong>Ответ:</strong> <?php echo HTML::chars($question->answer); ?></div> <div class="date"><strong><?php echo $question->date; ?></strong> <a href="<?php echo $_url; ?>">Постоянная ссылка на этот вопрос</a></div> </div> <?php endforeach; ?> </div> <?php if (isset($pagination)) echo $pagination; ?> <?php endif; ?> </td> <td class="faq_form_cell"> <?php echo $form; ?> </td> </tr></table><file_sep>/modules/system/forms/classes/form/element/checkgrid.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form select element displayed as a grid of checkboxes * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_CheckGrid extends Form_Element { /** * Options for horizontal iteration * @var array */ protected $_x_options = array(); /** * Options for veritcal iteration * @var array */ protected $_y_options = array(); /** * Creates form element * * @param string $name Element name * @param array $options Select options * @param array $properties * @param array $attributes */ public function __construct($name, array $x_options = NULL, array $y_options = NULL, array $properties = NULL, array $attributes = NULL) { parent::__construct($name, $properties, $attributes); $this->_x_options = $x_options; $this->_y_options = $y_options; } /** * Renders select element, constiting of checkboxes * * @return string */ public function render_input() { $value = $this->value; if ( ! is_array($value)) { $value = array(); } $html = ''; // Grid header $html = '<table class="light_table"><tr class="table_header"><th></th>'; foreach ($this->_x_options as $i => $label) { // Pattern to match checkboxes in a column (for "toggle_all" checkbox) $pattern = $this->full_name . "[*][$i]"; $html .= '<th><label style="white-space: nowrap;">' . Form_Helper::checkbox('toggle_all-' . $pattern, '1', FALSE, array('class' => 'checkbox toggle_all')) . '&nbsp;' . $label . '</label></th>'; } $html .= '</tr>'; // Grid elements foreach ($this->_y_options as $j => $label_y) { $html .= '<tr><td>' . $label_y . '</td>'; foreach ($this->_x_options as $i => $label_x) { if (isset($value[$j][$i]) && (int) $value[$j][$i] > 0) { $checked = TRUE; } else { $checked = FALSE; } $name = $this->full_name . "[$j][$i]"; $checkbox = Form_Helper::hidden($name, '0') . Form_Helper::checkbox($name, '1', $checked, array('class' => 'checkbox')); $html .= '<td class="c">' . $checkbox . '</td>'; } $html .= '</tr>'; } $html .= '</table>'; return $html; } /** * No javascript for this element * * @return string */ public function render_js() { return FALSE; } } <file_sep>/modules/shop/catalog/classes/controller/backend/catalog.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Catalog extends Controller_Backend { /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('catalog') . '/public/css/backend/catalog.css'); // Add catalog js scripts if ($this->request->action == 'index') { $layout->add_script(Modules::uri('catalog') . '/public/js/backend/catalog.js'); $layout->add_script( "var branch_toggle_url = '" . URL::to('backend/catalog/sections', array( 'action' => 'toggle', 'id' => '{{id}}', 'toggle' => '{{toggle}}') ) . '?context=' . $this->request->uri . "';" , TRUE); } if ($this->request->action == 'product_select') { // Add product select js scripts $layout->add_script(Modules::uri('catalog') . '/public/js/backend/product_select.js'); $layout->add_script( "var product_selected_url = '" . URL::to('backend/catalog', array('action' => 'product_selected', 'product_id' => '{{id}}')) . "';" , TRUE); } if ($this->request->action == 'sections_select') { // Add sections select js scripts $layout->add_script(Modules::uri('catalog') . '/public/js/backend/sections_select.js'); } return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Render additional catalog actions */ public function action_index() { $updatestats_form = new Form_Backend_Catalog_UpdateStats(); if ($updatestats_form->is_submitted()) { Model::fly('Model_Section')->mapper()->update_products_count(); $updatestats_form->flash_message('Показатели пересчитаны'); $this->request->redirect($this->request->uri); } $generatealiases_form = new Form_Backend_Catalog_GenerateAliases(); if ($generatealiases_form->is_submitted()) { TaskManager::start('generatealiases'); $this->request->redirect($this->request->uri); } $updatelinks_form = new Form_Backend_Catalog_UpdateLinks(); if ($updatelinks_form->is_submitted()) { TaskManager::start('updatelinks'); $this->request->redirect($this->request->uri); } $content = $updatestats_form->render() . $generatealiases_form->render() . $updatelinks_form->render(); $this->request->response = $this->render_layout($content); } /** * Select one product */ public function action_product_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор анонса на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_product_select(); } else { $view = $this->widget_product_select(); $view->caption = 'Выбор анонса на портале "' . Model_Site::current()->caption . '"'; $layout->content = $view->render(); } $this->request->response = $layout->render(); } /** * Generate the response for ajax request after product is selected * to inject new values correctly into the form */ /* public function action_product_selected() { $product = new Model_Product(); $product->find((int) $this->request->param('product_id')); if (isset($product->id)) { $values = array( 'caption' => $product->caption, 'price' => $product->price->amount, 'weight' => $product->weight ); $this->request->response = JSON_encode($values); } } */ /** * Render products and sections for the selection of one product */ public function widget_product_select() { $view = new View('backend/workspace_2col'); $view->column1 = $this->request->get_controller('sections')->widget_sections_menu('backend/sections_product_select'); $view->column2 = $this->request->get_controller('products')->widget_products('backend/product_select'); return $view; } } <file_sep>/modules/general/menus/classes/model/menu/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Menu_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); // Имя меню (для вставки в шаблон) $this->add_column('name', array('Type' => 'varchar(15)', 'Key' => 'INDEX')); // Название меню $this->add_column('caption', array('Type' => 'varchar(63)')); // Корневой раздел для меню $this->add_column('root_node_id', array('Type' => 'int unsigned')); // Максимальный уровень вложенности $this->add_column('max_level', array('Type' => 'int unsigned')); // Видимость для страниц по умолчанию $this->add_column('default_visibility', array('Type' => 'boolean')); // Вид (шаблон) для отрисовки меню $this->add_column('view', array('Type' => 'varchar(63)')); // Дополнительные настройки $this->add_column('settings', array('Type' => 'array')); } }<file_sep>/modules/shop/catalog/views/frontend/product_reps.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (count($reps)) {?> <?php $rep_url = URL::to('frontend/acl/users/control', array('action' => 'control','user_id' => '{{user_id}}')); ?> <div id="product-reps"> <h3>Организаторы:</h3> <table> <tr class="table_header"> <?php $columns = array( 'image' => 'Фото', 'name' => 'Имя' ); ?> </tr> <?php foreach ($reps as $rep_product_url => $prod) : $rep = $prod->role; $image_info = $rep->image(4); $_rep_url = str_replace('{{user_id}}', $rep->id, $rep_url); ?> <tr> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if ($field === 'image') { echo '<a href="' . $_rep_url . '" class="product_reps" id="rep_' . $rep->id . '">' . HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'])) . '</a></td>'; } if ($field === 'name') { $name = (!empty($rep->organization))?$rep->organization:$rep->name; echo '<a href="' . $_rep_url . '" class="product_reps" id="rep_' . $rep->id . '">' . $name . '</a>'; continue; } if (isset($rep->$field) && trim($lecturer->$field) !== '') { echo '<a href="' . $_select_url . '" class="lecturer_select" id="lecturer_' . $lecturer->id . '">' . HTML::chars($lecturer->$field) . '</a>'; } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> <td><?php if ($prod->active) { ?> <a href="<?php echo URL::site($rep_product_url); ?>">Просмотр...</a> <?php } ?> </td> </tr> <?php endforeach; //foreach ($reps as $rep) ?> </table> <?php if (isset($pagination)) { echo $pagination; } } ?> </div><file_sep>/modules/system/forms/classes/form/element/integer.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form element for itegers * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Integer extends Form_Element_Input { /** * Use the same templates as input element * * @return string */ public function default_config_entry() { return 'input'; } /** * Get element * * @return array */ public function attributes() { $attributes = parent::attributes(); // Add "integer" HTML class if (isset($attributes['class'])) { $attributes['class'] .= ' integer'; } else { $attributes['class'] = 'integer'; } return $attributes; } } <file_sep>/application/classes/url.php <?php defined('SYSPATH') OR die('No direct access allowed.'); /** * URL helper class. * * @package Eresus * @author <NAME> (<EMAIL>) */ class URL extends Kohana_URL { /** * Generates uri using specified route name and parameters. * If $save_history is specified than current requests uri is appended to uri via '/~' as history parameter. * * @param string|Route $route Route name or Route instance * @param array $params Route parameters * @param boolean $save_history Append current uri to history via /~ * @return string */ public static function uri_to($route = NULL, array $params = NULL, $save_history = FALSE) { $request = Request::current(); if ($route !== NULL && ! $route instanceof Route) { $route = Route::get($route); } else { $route = $request->route; } if ($save_history) { // Append current uri as history if ( ! isset($params['history'])) { $params['history'] = $request->uri; } } else { unset($params['history']); } $uri = $route->uri($params); // Save "in window" parameter if ( ! empty($_GET['window'])) { $uri .= '?window=1'; } return $uri; } /** * Generates url using specified route name and parameters. * * @param string|Route $route Route name or Route instance * @param array $params Route parameters * @param boolean $save_history Append current uri to history via /~ * @return string */ public static function to($route = NULL, array $params = NULL, $save_history = FALSE) { return URL::site(URL::uri_to($route, $params, $save_history)); } /** * Create uri from current uri by replacing parameters from $params. * * @param array $params * @param array $ignored_params * @return string */ public static function uri_self(array $params, array $ignored_params = array('page')) { $request = Request::current(); $request_params = $request->param(); $request_params['directory'] = $request->directory; $request_params['controller'] = $request->controller; $request_params['action'] = $request->action; // Unset ignored params foreach ($ignored_params as $param) { unset($request_params[$param]); } $params = array_merge($request_params , $params); // Preserve current history $history = $request->param('history'); if ($history !== NULL) { $params['history'] = $history; $save_history = TRUE; } else { $save_history = FALSE; } return URL::uri_to(NULL, $params, $save_history); } /** * Create uri from current uri by replacing parameters from $params. * * @param array $params * @param array $ignored_params * @return string */ public static function self(array $params, array $ignored_params = array('page')) { return URL::site(URL::uri_self($params, $ignored_params)); } /** * Generate uri back based on requests uri history part. * If there is no history part in current uri - route with the name $default * and default parameters is used. * If $default is NULL - current route with default parameters is used. * * @param string $default Name of the default route to use if history is empty. NULL - use current request uri * @param integer $levels How many levels to go back * @param array $params * @return string */ public static function uri_back($default = NULL, $levels = 1, array $params = NULL) { $request = Request::current(); for ($i = 0; $i < $levels; $i++) { if ($i == 0) { // First - take history from the current url $history = $request->param('history'); } else { // Parse route to retrieve the history param list($name, $request_params) = URL::match($history); if (isset($request_params['history'])) { $history = $request_params['history']; } else { $history = NULL; } } if ($history === NULL) { if ($default === NULL) { // Use current route return Request::current()->route->uri($params); } else { // Get route by name return Route::get($default)->uri($params); } } if ($history === '') { return '#'; } } if ($params === NULL) { // There is no need to change any params in history uri return $history; } else { list($name, $request_params) = URL::match($history); $params = array_merge($request_params , $params); return URL::uri_to($name, $params, ( ! empty($params['history']))); } } /** * Generate uri back based on requests uri history part * * @param string $default Name of the default route to use if history is empty. NULL - use current request uri * @param integer $levels How many levels to go back * @param array $params * @return string */ public static function back($default = NULL, $levels = 1, array $params = NULL) { return URL::site(URL::uri_back($default, $levels, $params)); } /** * Match given uri against routes and parse it * * @param string $uri * @return array Route name and parsed params */ public static function match($uri) { $routes = Route::all(); foreach ($routes as $name => $route) { if ($params = $route->matches($uri)) return array($name, $params); } return array(NULL, NULL); } public static function encode($value) { return @bin2hex($value); } public static function decode($value) { return @pack('H*', $value); } }<file_sep>/modules/shop/delivery_russianpost/classes/form/backend/delivery/russianpost.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Delivery_RussianPost extends Form_Backend_Delivery { /** * Initialize form fields */ public function init() { parent::init(); // Set HTML class $this->attribute('class', "wide w400px lb120px"); // ----- Settings $fieldset = new Form_Fieldset('settings', array('label' => 'Настройки')); $this->add_component($fieldset); // ----- viewPost (Вид отправления) $options = Model_Delivery_RussianPost::post_types(); $element = new Form_Element_Select('settings[viewPost]', $options, array('label' => 'Вид отправления')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- typePost (Способ пересылки) $options = Model_Delivery_RussianPost::post_transfers(); $element = new Form_Element_Select('settings[typePost]', $options, array('label' => 'Способ пересылки')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } } <file_sep>/modules/shop/payments/classes/model/payment/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Payment_Mapper extends Model_Mapper { /** * Cache find all results * @var boolean */ public $cache_find_all = FALSE; public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('caption', array('Type' => 'varchar(63)')); $this->add_column('description', array('Type' => 'text')); $this->add_column('module', array('Type' => 'varchar(31)')); $this->add_column('properties', array('Type' => 'array')); $this->add_column('active', array('Type' => 'boolean')); } /** * Find all payment types supported by given delivery type * * @param Model_Payment $payment * @param Model_Delivery $delivery * @param array $params * @return Models */ public function find_all_by_delivery(Model_Payment $payment, Model_Delivery $delivery, array $params = NULL) { $payment_table = $this->table_name(); $paydeliv_table = Model_Mapper::factory('PaymentDelivery_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array("$payment_table.*"); $query = DB::select_array($columns) ->from($payment_table) ->join($paydeliv_table, 'INNER') ->on("$paydeliv_table.payment_id", '=', "$payment_table.id") ->where("$paydeliv_table.delivery_id", '=', (int) $delivery->id); // Add limit, offset and order by statements if (isset($params['known_columns'])) { $known_columns = $params['known_columns']; } else { $known_columns = array(); } $this->_std_select_params($query, $params, $known_columns); $result = $query->execute($this->get_db()); $data = array(); if (count($result)) { // Convert to correct types foreach ($result as $values) { $data[] = $this->_unsqlize($values); } } return new Models(get_class($payment), $data); } }<file_sep>/modules/shop/orders/classes/model/order/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Order_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('created_at', array('Type' => 'int unsigned')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('status_id', array('Type' => 'tinyint unsigned', 'Key' => 'INDEX')); $this->add_column('sum', array('Type' => 'money')); $this->add_column('name', array('Type' => 'varchar(63)')); $this->add_column('phone', array('Type' => 'varchar(63)')); $this->add_column('email', array('Type' => 'varchar(31)')); $this->add_column('address', array('Type' => 'text')); $this->add_column('comment', array('Type' => 'text')); } }<file_sep>/modules/frontend/classes/form/frontend/error.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Error extends Form { /** * Message * @var string */ protected $_message; /** * Label for 'cancel' button * @var string */ protected $_cancel = 'Назад'; /** * Url for cancel button * @var string */ protected $_cancel_url; /** * Create a form with error message and 'back' button * * @param string $message */ public function __construct($message = NULL, $cancel = 'Назад', $cancel_url = NULL) { $this->_message = $message; $this->_cancel = $cancel; if ($cancel_url !== NULL) { $this->_cancel_url = $cancel_url; } else { $this->_cancel_url = URL::back(); } parent::__construct(); } /** * Initialize form fields */ public function init() { // Message $element = new Form_Element_Text('text', array('class' => 'error_message')); $element->value = $this->_message; $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => $this->_cancel), array('class' => 'button_cancel') )); } } <file_sep>/modules/shop/catalog/views/frontend/app_telemosts_by_owner.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/products/telemosts', array('action'=>'create', 'product_id' => $product->id), TRUE); $update_url = URL::to('backend/products/telemosts', array('action'=>'update', 'id' => '${id}'), TRUE); $choose_url = URL::to('backend/products/telemosts', array('action'=>'choose', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/products/telemosts', array('action'=>'delete', 'id' => '${id}'), TRUE); ?> <div class="caption">Заявки на телемосты</div> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Добавить заявку</a> </div> <div class="images"> <?php foreach ($app_telemosts as $telemost) : $_choose_url = str_replace('${id}', $telemost->id, $choose_url); $_update_url = str_replace('${id}', $telemost->id, $update_url); $_delete_url = str_replace('${id}', $telemost->id, $delete_url); ?> <div class="image"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($_choose_url, 'Принять заявку на телемост', 'controls/link.gif', 'Принять'); ?> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать заявку на телемост', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить заявку на телемост', 'controls/delete.gif', 'Удалить'); ?> </div> <div class="img"> <table><tr> <td>Площадка:<td><?php echo $product->place->town_name?>: <?php echo $product->place->name ?> <tr><td>Адрес:<td><?php echo $telemost->place->address; ?> <tr><td>Организация<td><?php echo $telemost->user->organizer->name; ?> <tr><td>Координатор<td><?php echo $telemost->user->name; ?> </table> </div> </div> <?php endforeach; ?> </div> <div class="caption">Телемосты</div> <div class="images"> <?php foreach ($telemosts as $telemost) : $_update_url = str_replace('${id}', $telemost->id, $update_url); $_delete_url = str_replace('${id}', $telemost->id, $delete_url); ?> <div class="image"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать телемост', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить телемост', 'controls/delete.gif', 'Удалить'); ?> </div> <div class="img"> <table><tr> <td>Площадка:<td><?php echo $product->place->town_name?>: <?php echo $product->place->name ?> <tr><td>Адрес:<td><?php echo $telemost->place->address; ?> <tr><td>Организация<td><?php echo $telemost->user->organizer->name; ?> <tr><td>Координатор<td><?php echo $telemost->user->name; ?> </table> </div> </div> <?php endforeach; ?> </div><file_sep>/modules/shop/area/classes/controller/frontend/towns.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Towns extends Controller_Frontend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { if ($layout_script === NULL) { if ($this->request->action == 'index') { $layout_script = 'layouts/map'; } } return parent::prepare_layout($layout_script); } /** * Render select_town bar */ public function widget_select($type = 'catalog') { $town = Model_Town::current(); if ( ! isset($town->id)) { $this->_action_404('Указанный город не найден'); return; } $towns = Model::fly('Model_Town')->find_all(array('order_by'=>'name','desc'=>'0')); $view = new View('frontend/towns/select'); $view->towns = $towns; $view->town = $town; $view->type = $type; return $view->render(); } public function action_choose() { $town = Model_Town::current(); if ( ! isset($town->id)) { $this->_action_404('Указанный город не найден'); return; } Cookie::set(Model_Town::TOWN_TOKEN, $town->alias, time() + Model_Town::TOWN_LIFETIME); $this->request->redirect(URL::uri_to('frontend/catalog')); //$this->request->redirect(URL::uri_self(array())); } public function action_choosemap() { $town = Model_Town::current(); if ( ! isset($town->id)) { $this->_action_404('Указанный город не найден'); return; } Cookie::set(Model_Town::TOWN_TOKEN, $town->alias, time() + Model_Town::TOWN_LIFETIME); $this->request->redirect(URL::uri_to('frontend/area/towns')); //$this->request->redirect(URL::uri_self(array())); } public function action_index() { $town = Model_Town::current(); if (!$town->id) { $towns = Model::fly('Model_Town')->find_all(); $pattern = new View('frontend/places/map_place'); $place = new Model_Place(); foreach ($towns as $town) { $options = array(); $places[$town->alias] = $place->find_all_by_town_id($town->id); $content = ''; $glue= ''; foreach ($places[$town->alias] as $place) { $pattern->place =$place; $content .= $glue.$pattern->render(); $glue = '<br>'; } if ($town->lat) { Gmaps3::instance()->add_mark($town->lat,$town->lon,$town->name); Gmaps3::instance()->add_link(URL::to('frontend/area/towns', array('action'=>'choosemap', 'are_town_alias' => $town->alias), TRUE)); } } $view = new View('frontend/towns/map'); $view->places = $places; $view->zoom = NULL; $view->lat = NULL; $view->lon = NULL; } else { $place = new Model_Place(); $places = $place->find_all_by_town_id($town->id); $pattern = new View('frontend/places/map_place'); foreach ($places as $place) { if ($place->lat) { Gmaps3::instance()->add_mark($place->lat,$place->lon,$place->name); $pattern->place =$place; Gmaps3::instance()->add_infowindow($pattern->render()); } } $view = new View('frontend/towns/map'); //$view->towns = $towns; $view->places = $places; if ($town->name != 'Москва') { $view->zoom = 11; } else { $view->zoom = 9; } $view->lat = $town->lat; $view->lon = $town->lon; } $layout = $this->prepare_layout(); $layout->content = $view; // Add breadcrumbs //$this->add_breadcrumbs(); $this->request->response = $layout->render(); return $view->render(); } } <file_sep>/modules/shop/catalog/views/frontend/products/user_nav_after.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <a href="<?php echo URL::site($product->uri_frontend(NULL)); ?>" class="request-link button">Выйти</a> <file_sep>/modules/shop/acl/public/js/frontend/lecturer_select.js /** * Initialize */ $(document).ready(function(){ if (current_window) { // ----- Select lecturer buttons $('#lecturer_select').click(function(event){ if ($(event.target).hasClass('lecturer_select')) { // "Select lecturer" link was pressed // Determine lecturer id from link "id" attribute (id is like 'lecturer_15') var lecturer_id = $(event.target).attr('id').substr(9); // Peform an ajax request to get selected lecturer var ajax_url = lecturer_selected_url.replace('{{id}}', lecturer_id); $.post(ajax_url, null, function(response) { if (response) { //@FIXME: Security breach! eval('var lecturer = ' + response + ';'); // Execute custom actions on lecturer selection // (there should be a corresponding function defined in parent window) if (parent.on_lecturer_select) { parent.on_lecturer_select(lecturer) } // Close the window current_window.close(); } }); event.preventDefault(); } }); } });<file_sep>/modules/general/news/classes/controller/frontend/news.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_News extends Controller_Frontend { /** * Render list of news * * @return View */ public function action_index() { $site_id = Model_Site::current()->id; $newsitem = new Model_Newsitem(); $order_by = $this->request->param('news_order', 'date'); $desc = (bool) $this->request->param('news_desc', '1'); // ----- Selected years for which there are news $years = $newsitem->find_all_years_by_site_id($site_id); $current_year = (int) $this->request->param('year', 0); if ($current_year == 0 && count($years)) { // Select the latest available year if not explicitly specified in url params $current_year = $years[0]; } if (count($years) && ! in_array($current_year, $years)) { // Invalid year was specified $this->_action_404(); return; } // ----- Selected months for which there are news in selected year $months = $newsitem->find_all_months_by_year_and_site_id($current_year, $site_id); $current_month = (int) $this->request->param('month', 0); if ($current_month == 0 && count($months)) { // Select the latest available month if not explicitly specified in url params $current_month = $months[count($months) - 1]; } if (count($months) && ! in_array($current_month, $months)) { // Invalid month was specified $this->_action_404(); return; } // ----- List of news // Select all news for selected year and month $per_page = 1000; $count = $newsitem->count_by_site_id($site_id); $pagination = new Pagination($count, $per_page); $news = $newsitem->find_all_by_year_and_month_and_site_id($current_year, $current_month, $site_id, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc, 'columns' => array('id', 'date', 'caption', 'short_text') )); // Set up view $view = new View('frontend/news'); $view->years = $years; $view->months = $months; $view->current_year = $current_year; $view->current_month = $current_month; $view->news = $news; $view->pagination = $pagination; // 3-step view //$view2 = new View('content/news'); //$view2->caption = Model_Node::current()->caption; //$view2->content = $view; $this->request->response = $this->render_layout($view); } /** * View the full text of the selected news item */ public function action_view() { $newsitem = new Model_Newsitem(); $newsitem->find_by_id_and_site_id((int) $this->request->param('id'), (int) Model_Site::current()->id); if ( ! isset($newsitem->id)) { $this->_action_404(); return; } $this->request->get_controller('breadcrumbs')->append_breadcrumb(array( 'caption' => $newsitem->caption )); // 3-step view $view = new View('content/text'); $view->content = $newsitem->text; // Layout $layout = $this->prepare_layout(); // Append title $layout->add_title($newsitem->caption); $layout->content = $view; $layout->date = $newsitem->date; $this->request->response = $layout->render(); } /** * Render list of recent news * * @return View */ public function widget_recent() { $site_id = Model_Site::current()->id; $newsitem = new Model_Newsitem(); $order_by = $this->request->param('news_order', 'date'); $desc = (bool) $this->request->param('news_desc', '1'); // ----- List of recent news $limit = 3; $news = $newsitem->find_all_by_site_id($site_id, array( 'limit' => $limit, 'order_by' => $order_by, 'desc' => $desc, 'columns' => array('id', 'date', 'caption', 'short_text') )); // Set up view $view = new View('frontend/recent_news'); $view->news = $news; return $view; } } <file_sep>/modules/system/forms/classes/form/element/password.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form password element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Password extends Form_Element_Input { /** * @return string */ public function get_type() { return 'password'; } /** * Use the same templates as input element * * @return string */ public function default_config_entry() { return 'input'; } } <file_sep>/modules/shop/orders/views/backend/orders.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/orders', array('action'=>'create'), TRUE); $update_url = URL::to('backend/orders', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/orders', array('action'=>'delete', 'id' => '${id}'), TRUE); $multi_action_uri = URL::uri_to('backend/orders', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Новый заказ</a> </div> <?php if ( ! count($orders)) // No orders return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'id' => 'Номер', 'date_created' => array('label' => 'Дата', 'sort_field' => 'created_at'), //'site_caption' => 'Магазин', 'name' => 'Покупатель', //'delivery_caption' => 'Доставка', //'payment_caption' => 'Оплата', 'status_caption' => 'Статус', 'sum' => 'Сумма заказа' ); echo View_Helper_Admin::table_header($columns, 'orders_order', 'orders_desc'); ?> <th></th> </tr> <?php foreach ($orders as $order) : $_update_url = str_replace('${id}', $order->id, $update_url); $_delete_url = str_replace('${id}', $order->id, $delete_url); ?> <tr class="<?php echo Text::alternate('odd', 'even'); ?>"> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($order->id); ?> </td> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if (isset($order->$field) && trim((string) $order->$field) !== '') { echo HTML::chars($order->$field); } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать заказ', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить заказ', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; //foreach ($orders as $order) ?> </table> <?php if (isset($pagination)) { echo $pagination->render('backend/pagination'); } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete'), array('action' => 'merge', 'label' => 'Объединить', 'class' => 'button_merge') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/catalog/views/frontend/products/apply_big.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $url = URL::to('frontend/catalog/products/control', array('action' => 'create', 'product_id' => $product->id,'type_id' => Model_SectionGroup::TYPE_EVENT,), TRUE); // Button to select user /*$button = new Form_Element_LinkButton('apply_button', array('label' => 'Подать заявку', 'render' => FALSE), array('class' => 'apply_button open_window') ); $button->url = $url; echo $button->render(); */ ?> <form action="<?php echo $url; ?>" method="POST"> <input type="image" src="<?php echo URL::base(FALSE); ?>public/css/img/2cart-bigd.gif" class="buy" alt="Регистрация" /> </form> <file_sep>/modules/shop/acl/classes/controller/backend/acl.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Acl extends Controller_Backend { public function before() { if ($this->request->action === 'login' || $this->request->action === 'logout') { // Allow everybody to login & logout return TRUE; } return parent::before(); } /** * Prepare layout * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('acl') . '/public/css/backend/acl.css'); if ($this->request->action == 'user_select') { // Add user select js scripts $layout->add_script(Modules::uri('acl') . '/public/js/backend/user_select.js'); $layout->add_script( "var user_selected_url = '" . URL::to('backend/acl', array('action' => 'user_selected', 'user_id' => '{{id}}')) . "';" , TRUE); } if ($this->request->action == 'lecturer_select') { // Add lecturer select js scripts $layout->add_script(Modules::uri('acl') . '/public/js/backend/lecturer_select.js'); $layout->add_script( "var lecturer_selected_url = '" . URL::to('backend/acl', array('action' => 'lecturer_selected', 'lecturer_id' => '{{id}}')) . "';" , TRUE); } // if ($this->request->action == 'ac_lecturer_name') // { // // Add lecturer select js scripts // $layout->add_script(Modules::uri('acl') . '/public/js/backend/lecturer_name.js'); // } // if ($this->request->action == 'ac_organizer_name') // { // // Add lecturer select js scripts // $layout->add_script(Modules::uri('acl') . '/public/js/backend/organizer_name.js'); // } if ($this->request->action == 'select' && $this->request->controller == 'organizers') { // Add organizers select js scripts $layout->add_script(Modules::uri('acl') . '/public/js/backend/organizers_select.js'); } if ($this->request->action == 'select' && $this->request->controller == 'users') { // Add organizers select js scripts $layout->add_script(Modules::uri('acl') . '/public/js/backend/users_select.js'); } return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Render list of users and groups using two-column panel */ public function action_index() { $view = new View('backend/workspace_2col'); $view->column1 = $this->request->get_controller('groups')->widget_groups(); $view->column2 = $this->request->get_controller('users')->widget_users(); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Render user-select dialog */ public function action_user_select() { $layout = $this->prepare_layout(); if (empty($_GET['window'])) { $view = new View('backend/workspace'); $view->caption = 'Выбор пользователя'; //$view->content = $this->request->get_controller('users')->widget_user_select(); $view->content = $this->widget_user_select(); $layout->content = $view; } else { $view = new View('backend/workspace'); $view->content = $this->widget_user_select(); $layout->caption = 'Выбор пользователя'; $layout->content = $view->render(); } $this->request->response = $layout->render(); } public function widget_user_select() { $view = new View('backend/workspace_2col'); $view->column1 = $this->request->get_controller('groups')->widget_groups('backend/group_user_select'); $view->column2 = $this->request->get_controller('users')->widget_user_select(); return $view; } /** * Generate the response for ajax request after user is selected * to inject new values correctly into the form */ public function action_user_selected() { $user = new Model_User(); $user->find((int) $this->request->param('user_id')); $values = $user->values(); $values['user_name'] = $user->name; $this->request->response = JSON_encode($values); } /** * Render lecturer-select dialog */ public function action_lecturer_select() { $layout = $this->prepare_layout(); if (empty($_GET['window'])) { $view = new View('backend/workspace'); $view->caption = 'Выбор лектора'; $view->content = $this->request->get_controller('lecturers')->widget_lecturer_select(); $layout->content = $view; } else { $view = new View('backend/workspace'); $view->content = $this->request->get_controller('lecturers')->widget_lecturer_select(); $layout->caption = 'Выбор лектора'; $layout->content = $view->render(); } $this->request->response = $layout->render(); } /** * Generate the response for ajax request after lecturer is selected * to inject new values correctly into the form */ public function action_lecturer_selected() { $lecturer = new Model_Lecturer(); $lecturer->find((int) $this->request->param('lecturer_id')); $values = $lecturer->values(); $values['lecturer_name'] = $lecturer->name; $this->request->response = JSON_encode($values); } /** * Login page && authorization */ public function action_login() { $user = Model_User::current(); $form = new Form_Backend_Login($user); if ($form->is_submitted()) { // User is trying to log in if ($form->validate()) { $result = Auth::instance()->login( $form->get_element('email')->value, $form->get_element('password')->value, $form->get_element('remember')->value ); if ($result) { // User was succesfully authenticated // Is he authorized to access backend? if (Auth::granted('backend_access')) { $this->request->redirect(Request::current()->uri); } else { $form->error('Доступ к панели управления запрещён!'); } } else { $form->errors(Auth::instance()->errors()); } } } $view = new View('backend/form'); $view->caption = 'Аутентификация'; $view->form = $form; $this->request->response = $this->render_layout($view, 'layouts/backend/login'); } public function action_logout() { Auth::instance()->logout(); $this->request->redirect(''); } /** * Renders logout button * * @return string */ public function widget_logout() { $view = new View('backend/logout'); return $view; } } <file_sep>/modules/general/flash/classes/flashblocknode/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class FlashblockNode_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('flashblock_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('node_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('visible', array('Type' => 'boolean')); } /** * Update information about visible nodes for block * * @param Model_Block $block * @param array $nodes_visibility */ public function update_nodes_visibility(Model_Flashblock $flashblock, array $nodes_visibility) { $this->delete_rows(DB::where('flashblock_id', '=', (int)$flashblock->id)); foreach ($nodes_visibility as $node_id => $visible) { if ($visible != $flashblock->default_visibility) { $this->insert(array( 'node_id' => $node_id, 'flashblock_id' => (int)$flashblock->id, 'visible' => $visible )); } } } }<file_sep>/modules/shop/catalog/classes/form/backend/product.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Product extends Form_BackendRes { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "lb150px"); $this->layout = 'wide'; // User is being created or updated? $creating = ((int)$this->model()->id == 0) ? TRUE : FALSE; // ----- General tab $tab = new Form_Fieldset_Tab('general_tab', array('label' => 'Основные свойства')); $this->add_component($tab); // 2-column layout $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); $tab->add_component($cols); $fieldset = new Form_Fieldset('main_props', array('label' => 'Основные свойства')); $cols->add_component($fieldset); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название', 'required' => TRUE), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $fieldset->add_component($element); // ----- Section_id_original $element = new Form_Element_Hidden('section_id_original'); $cols->add_component($element, 2); // [!] Set up new section id to product model if ($element->value === FALSE) { $element->value = $this->model()->section_id; } else { $this->model()->section_id = $element->value; } // ----- Section_id $sectiongroups = Model::fly('Model_SectionGroup')->find_all_by_site_id(Model_Site::current()->id, array('columns' => array('id', 'caption'))); $sections = array(); foreach ($sectiongroups as $sectiongroup) { $sections[$sectiongroup->id] = Model::fly('Model_Section')->find_all_by_sectiongroup_id($sectiongroup->id, array( 'order_by' => 'lft', 'desc' => FALSE, 'columns' => array('id', 'rgt', 'lft', 'level', 'caption') )); } $sections_options = array(); foreach ($sections as $sections_in_group) { foreach ($sections_in_group as $section) { $sections_options[$section->id] = str_repeat('&nbsp;', ($section->level - 1) * 3) . Text::limit_chars($section->caption, 30); } } // ------ lecturer_id // control hidden field $control_element = new Form_Element_Hidden('lecturer_id',array('id' => 'lecturer_id')); $this->add_component($control_element); /*$req_lecturer_id = Request::instance()->param('lecturer_id', FALSE); if ($req_lecturer_id) { $control_element->set_value($req_lecturer_id); $lecturer_id = $req_lecturer_id; }*/ if ($control_element->value !== FALSE) { $lecturer_id = (int) $control_element->value; } else { $lecturer_id = (int) $this->model()->lecturer_id; } // ----- lecturer_name // input field with autocomplete ajax $element = new Form_Element_Input('lecturer_name', array('label' => 'Лектор', 'layout' => 'wide','id' => 'lecturer_name','required' => TRUE)); $element->autocomplete_url = URL::to('backend/acl/lecturers', array('action' => 'ac_lecturer_name')); Layout::instance()->add_style(Modules::uri('acl') . '/public/css/frontend/acl.css'); $fieldset->add_component($element); $lecturer = new Model_Lecturer(); $lecturer->find($lecturer_id); $lecturer_name = ($lecturer->id !== NULL) ? $lecturer->name : '--- лектор не указан ---'; /*if ($req_lecturer_id) { $element->set_value($lecturer_name); }*/ if ($element->value === FALSE) { $element->value = $lecturer_name; } else { if ($element->value !== $lecturer_name) $control_element->set_value(NULL); } // ----- select_lecturer_button // Button to select lecturer /*$button = new Form_Element_LinkButton('select_lecturer_button', array('label' => 'Выбрать', 'render' => FALSE), array('class' => 'button_select_lecturer open_window') ); $button->url = URL::to('backend/acl', array('action' => 'lecturer_select'), TRUE); $fieldset->add_component($button); if ($creating) $element->append = '&nbsp;&nbsp;' . $button->render(); */ // organizer // control hidden field $control_element = new Form_Element_Hidden('organizer_id',array('id' => 'organizer_id')); $this->add_component($control_element); if ($control_element->value !== FALSE) { $organizer_id = (int) $control_element->value; } else { $organizer_id = (int) $this->model()->organizer_id; } // ----- organizer_name // input field with autocomplete ajax $element = new Form_Element_Input('organizer_name', array('label' => 'Организация', 'layout' => 'wide','id' => 'organizer_name','required' => TRUE)); $element->autocomplete_url = URL::to('backend/acl/organizers', array('action' => 'ac_organizer_name')); Layout::instance()->add_style(Modules::uri('acl') . '/public/css/backend/acl.css'); $fieldset->add_component($element); $organizer = new Model_Organizer(); $organizer->find($organizer_id); $organizer_name = ($organizer->id !== NULL) ? $organizer->name : ''; if ($element->value === FALSE) { $element->value = $organizer_name; } else { if ($element->value !== $organizer_name) $control_element->set_value(NULL); } // ----- datetime $element = new Form_Element_DateTimeSimple('datetime', array('label' => 'Дата проведения', 'required' => TRUE),array('class' => 'w300px')); $element->value_format = Model_Product::$date_as_timestamp ? 'timestamp' : 'datetime'; $element ->add_validator(new Form_Validator_DateTimeSimple()); $fieldset->add_component($element); // ----- Duration $options = Model_Product::$_duration_options; $element = new Form_Element_Select('duration', $options, array('label' => 'Длительность'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- place_id // Store place_id in hidden field $element = new Form_Element_Hidden('place_id'); $this->add_component($element); if ($element->value !== FALSE) { $place_id = (int) $element->value; } else { $place_id = (int) $this->model()->place_id; } // ----- Place name $place = new Model_Place(); $place->find($place_id); $place_name = ($place->id !== NULL) ? $place->name : '--- площадка не указана ---'; $element = new Form_Element_Input('place_name', array('label' => 'Площадка', 'disabled' => TRUE, 'layout' => 'wide','required' => TRUE), array('class' => 'w190px') ); $element->value = $place_name; $fieldset->add_component($element); // Button to select place $button = new Form_Element_LinkButton('select_place_button', array('label' => 'Выбрать', 'render' => FALSE), array('class' => 'button_select_place open_window dim500x500') ); $button->url = URL::to('backend/area', array('action' => 'place_select'), TRUE); $this->add_component($button); $element->append = '&nbsp;&nbsp;' . $button->render(); /*$towns = Model_Town::towns(); $element = new Form_Element_Select('town', $towns, array('label' => 'Город проведения','required' => TRUE), array('class' => 'w300px') ); $fieldset->add_component($element); */ // ----- theme $options = Model_Product::$_theme_options; $element = new Form_Element_Select('theme', $options, array('label' => 'Тема'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- format $options = Model_Product::$_format_options; $element = new Form_Element_Select('format', $options, array('label' => 'Формат'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); $element = new Form_Element_Input('tags', array('label' => 'Теги','id' => 'tag'), array('maxlength' => 255)); $element->autocomplete_url = URL::to('backend/tags', array('action' => 'ac_tag')); $element->autocomplete_chunk = Model_Tag::TAGS_DELIMITER; $element ->add_filter(new Form_Filter_TrimCrop(255)); $fieldset->add_component($element); // ----- Description $fieldset->add_component(new Form_Element_Wysiwyg('description', array('label' => 'О событии'))); // ----- Product images if ($this->model()->id !== NULL) { $element = new Form_Element_Custom('images', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('images')->widget_images('product', $this->model()->id, 'product'); $cols->add_component($element, 2); $element = new Form_Element_Custom('telemosts', array('label' => '', 'layout' => 'standart')); $element->value = Request::current()->get_controller('telemosts')->widget_telemosts($this->model()); $cols->add_component($element, 2); } // ----- interact $options = Model_Product::$_interact_options; $element = new Form_Element_RadioSelect('interact', $options, array('label' => 'Интерактивность','required' => TRUE),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- Price $element = new Form_Element_Money('price', array('label' => 'Стоимость лицензии')); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Float(0, NULL)); $fieldset->add_component($element); // ----- numviews $options = Model_Product::$_numviews_options; $element = new Form_Element_Select('numviews', $options, array('label' => 'Количество телемостов'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); /*$cols1 = new Form_Fieldset_Columns('price',array('column_classes' => array(2 => 'w60per'))); $fieldset->add_component($cols1); $element = new Form_Element_Checkbox_Enable('change_payable', array('label' => 'Платное событие')); $element->dep_elements = array('price'); $cols1->add_component($element,1); // ----- Price $element = new Form_Element_Money('price', array('label' => 'Стоимость лицензии',)); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Float(0, NULL)); $cols1->add_component($element,2); */ // ----- choalg $options = Model_Product::$_choalg_options; $element = new Form_Element_Select('choalg', $options, array('label' => 'Кто выбирает'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- telemost provider $options = Model_Product::$_telemost_provider_options; $element = new Form_Element_RadioSelect('telemost_provider', $options, array('label' => 'Платформа телемоста'),array('class' => 'w300px')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); // ----- Require $fieldset->add_component(new Form_Element_Textarea('require', array('label' => 'Требования к площадке, аудитории и др.'))); // ----- access $fieldset = new Form_Fieldset('access', array('label' => 'Кто может подать заявку')); $cols->add_component($fieldset); // ----- Role properties $fieldset = new Form_Fieldset('user', array('label' => 'Управление')); $cols->add_component($fieldset); // ----- Active $fieldset->add_component(new Form_Element_Checkbox('active', array('label' => 'Активность'))); // ----- Visible $fieldset->add_component(new Form_Element_Checkbox('visible', array('label' => 'Видимость'))); if (!$creating) { // ----- Additional properties if ($this->model()->id === NULL) { $main_section_id = key($sections_options); $this->model()->section_id = $main_section_id; } $properties = $this->model()->properties; if ($properties->valid()) { $fieldset = new Form_Fieldset('props', array('label' => 'Характеристики')); $cols->add_component($fieldset); foreach ($properties as $property) { switch ($property->type) { case Model_Property::TYPE_TEXT: $element = new Form_Element_Input( $property->name, array('label' => $property->caption), array('maxlength' => Model_Property::MAX_TEXT) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Property::MAX_TEXT)); $fieldset->add_component($element); break; case Model_Property::TYPE_SELECT: $options = array('' => '---'); foreach ($property->options as $option) { $options[$option] = $option; } $element = new Form_Element_Select( $property->name, $options, array('label' => $property->caption) ); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $fieldset->add_component($element); break; case Model_Property::TYPE_TEXTAREA: $element = new Form_Element_Textarea( $property->name, array('label' => $property->caption), array('maxlength' => Model_Property::MAX_TEXTAREA) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Property::MAX_TEXTAREA)); $fieldset->add_component($element); break; } } } } // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Назад'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); } /** * Add javascripts */ public function render_js() { parent::render_js(); // ----- Install javascripts // Url for ajax requests to redraw product properties when main section is changed $properties_url = URL::to('backend/catalog/products', array( 'action' => 'ajax_properties', 'id' => $this->model()->id )); // Url for ajax requests to redraw selected additional sections for product $on_sections_select_url = URL::to('backend/catalog/products', array( 'action' => 'ajax_sections_select', 'id' => $this->model()->id, 'cat_section_ids' => '{{section_ids}}', 'cat_sectiongroup_id' => '{{sectiongroup_id}}' )); // Url for ajax requests to redraw selected additional sections for product $on_towns_select_url = URL::to('backend/catalog/products', array( 'action' => 'ajax_towns_select', 'id' => $this->model()->id, 'access_town_ids' => '{{town_ids}}', )); // Url for ajax requests to redraw selected additional sections for product $on_organizers_select_url = URL::to('backend/catalog/products', array( 'action' => 'ajax_organizers_select', 'id' => $this->model()->id, 'access_organizer_ids' => '{{organizer_ids}}', )); // Url for ajax requests to redraw selected additional sections for product $on_users_select_url = URL::to('backend/catalog/products', array( 'action' => 'ajax_users_select', 'id' => $this->model()->id, 'access_user_ids' => '{{user_ids}}', )); Layout::instance()->add_script( "var product_form_name='" . $this->name . "';\n\n" . "var properties_url = '" . $properties_url . "';\n" . "var on_sections_select_url = '" . $on_sections_select_url . "';\n" . "var on_towns_select_url = '" . $on_towns_select_url . "';\n" . "var on_organizers_select_url = '" . $on_organizers_select_url . "';\n" . "var on_users_select_url = '" . $on_users_select_url . "';\n" , TRUE); // "props" fieldset id $component = $this->find_component('props'); if ($component !== FALSE) { Layout::instance()->add_script( "var properties_fieldset_id='" . $component->id . "';" , TRUE); } // additional sections fieldset id's to redraw via ajax requests $script = "var sections_fieldset_ids = {};\n"; $sectiongroups = Model::fly('Model_SectionGroup')->find_all_by_site_id(Model_Site::current()->id, array('columns' => array('id', 'caption'))); foreach ($sectiongroups as $sectiongroup) { $component = $this->find_component('additional_sections[' . $sectiongroup->id . ']'); if ($component !== FALSE) { $script .= "sections_fieldset_ids[" . $sectiongroup->id . "]='" . $component->id . "';\n"; } } Layout::instance()->add_script($script, TRUE); // Link product form scripts jQuery::add_scripts(); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/backend/product_form.js'); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/backend/prodlecturer.js'); Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/lecturer_name.js'); Layout::instance()->add_script(Modules::uri('acl') . '/public/js/backend/organizer_name.js'); Layout::instance()->add_script(Modules::uri('catalog') . '/public/js/backend/prodplace.js'); Layout::instance()->add_script(Modules::uri('tags') . '/public/js/backend/tag.js'); } } <file_sep>/modules/system/forms/classes/form/element/float.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form element for floating point numbers * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Float extends Form_Element_Input { /** * Return correct floating-point value * regardless of whether point or comma is used for decimal separation * * @return float */ public function get_value() { $value = parent::get_value(); if ($value !== NULL && $value !== FALSE) { $value = l10n::string_to_float($value); } return $value; } public function get_value_for_render() { return parent::get_value(); } public function get_value_for_validation() { return parent::get_value(); } /** * Use the same templates as input element * * @return string */ public function default_config_entry() { return 'input'; } /** * Get element * * @return array */ public function attributes() { $attributes = parent::attributes(); // Add "integer" HTML class if (isset($attributes['class'])) { $attributes['class'] .= ' float'; } else { $attributes['class'] = 'float'; } return $attributes; } } <file_sep>/modules/system/forms/config/form_templates/table/checkselect_spec.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array( // Standart layout 'standart' => array( 'element' => '<tr> <td class="input_cell element-{{type}}" colspan="2"> {{label}} <div class="options">{{input}}</div> <div class="errors" id="{{id}}-errors">{{errors}}</div> <div class="comment">{{comment}}</div> </td> </tr> ', 'option' => ' <div class="b-radio"> <span></span> {{checkbox}} {{label}} </div> ' ), // Wide layout 'wide' => array( 'element' => '<tr> <td class="label_cell">{{label}}</td> <td class="input_cell element-{{type}}"> <div class="options">{{input}}</div> <div class="errors" id="{{id}}-errors">{{errors}}</div> <div class="comment">{{comment}}</div> </td> </tr> ', 'option' => ' <div class="option"> {{checkbox}} {{label}} </div> ' ), // Inline layout 'inline' => array( 'element' => '<span class="element-{{type}}"> {{label}} {{input}} </span> ', 'option' => ' <span class="option"> {{checkbox}} {{label}} </span> ' ) );<file_sep>/modules/shop/catalog/views/frontend/sections/breadcrumbs.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ( ! count($sections)) { return ''; } ?> <div class="sections_breadcrumbs"> <a href="<?php echo URL::site(''); ?>">Главная</a> <?php foreach ($sections as $section) : $_url = URL::site($section->uri_frontend()); ?> &raquo; <a href="<?php echo $_url; ?>"> <?php echo HTML::chars($section->caption); ?> </a> <?php endforeach; ?> </div><file_sep>/modules/shop/catalog/views/backend/sectiongroups/tabs.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $url = URL::to('backend/catalog', array('cat_sectiongroup_id'=>'{{id}}')); ?> <div class="sectiongroup_tabs"> <div class="tabs"> <?php foreach ($sectiongroups as $sectiongroup) { $_url = str_replace('{{id}}', $sectiongroup->id, $url); if ($sectiongroup->id == $current->id) { echo '<a href="' . $_url . '" class="selected">' . HTML::chars($sectiongroup->caption) . '</a>'; } else { echo '<a href="' . $_url . '">' . HTML::chars($sectiongroup->caption) . '</a>'; } } ?> </div> </div><file_sep>/modules/system/forms/classes/form/element/dateselect.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form date element. * Rendered as three input elements for day, month and year * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_DateSelect extends Form_Element_Date { /** * Standart template to render element as table row * * @param string $type */ public function default_template($type = 'element') { switch ($type) { case 'element': return '<tr>' . ' <td class="label">$(label)</td>' . ' <td class="date">$(input)$(comment)</td>' . ' <td class="errors">$(errors)</td>' . '</tr>'; default: return parent::default_template($type); } } /** * Renders date element as three selects for day, month and year * * @return string */ public function render_input() { // Highlight inputs if there are errors if ($this->has_errors()) { $class = ' error'; } else { $class = ''; } $days = array(); $months = array(); $years = array(); $year_max = (int)date('Y'); for ($i = 1; $i < 32; $days[$i] = $i, $i++); for ($i = 1; $i < 13; $months[$i] = $i, $i++); for ($i = $year_max; $i > $year_max - 100; $years[$i] = $i, $i--); return Form_Helper::select( $this->name.'[]', $days, $this->get_day(), array( 'type' => 'text', 'class'=>'text day' . $class, 'maxlength' => 2 ) ) . Form_Helper::select( $this->name.'[]', $months, $this->get_month(), array( 'type' => 'text', 'class'=>'text month' . $class, 'maxlength' => 2 ) ) . Form_Helper::select( $this->name.'[]', $years, $this->get_year(), array( 'type' => 'text', 'class'=>'text year' . $class, 'maxlength' => 4 ) ); } } <file_sep>/modules/general/images/views/backend/image.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Width & height of one image preview $canvas_height = 110; $canvas_width = 110; if ( ! isset($image->id)) { $create_url = URL::to('backend/images', array( 'action'=>'create', 'owner_type' => $image->owner_type, 'owner_id' => $image->owner_id, 'config' => $image->config ), TRUE); } else { $update_url = URL::to('backend/images', array('action'=>'update', 'id' => $image->id, 'config' => $image->config), TRUE); $delete_url = URL::to('backend/images', array('action'=>'delete', 'id' => $image->id, 'config' => $image->config), TRUE); } ?> <?php if ( ! isset($image->id)) : ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Создать изображение</a> </div> <?php else : $i = count($image->get_thumb_settings()); // Number of the last (the smallest) thumb $width = $image->__get("width$i"); $height = $image->__get("height$i"); if ($width > $canvas_width || $height > $canvas_height) { if ($width > $height) { $scale = ' style="width: ' . $canvas_width . 'px;"'; $height = $height * $canvas_width / $width; $width = $canvas_width; } else { $scale = ' style="height: ' . $canvas_height . 'px;"'; $width = $width * $canvas_height / $height; $height = $canvas_height; } } else { $scale = ''; } if ($canvas_height > $height) { $padding = ($canvas_height - $height) >> 1; // ($canvas_height - $height) / 2 $padding = ' padding-top: ' . $padding . 'px;'; } else { $padding = ''; } ?> <div class="images"> <div class="image"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($delete_url, 'Удалить изображение', 'controls/delete.gif', 'Удалить'); ?> <?php echo View_Helper_Admin::image_control($update_url, 'Редактировать изображение', 'controls/edit.gif', 'Редактировать'); ?> </div> <div class="img" style="width: <?php echo $canvas_width; ?>px; height: <?php echo $canvas_width; ?>px;"> <a href="<?php echo $update_url; ?>" style="<?php echo $padding; ?>"> <img src="<?php // Render the last (assumed to be the smallest) thumbnail echo File::url($image->image($i)); ?>" <?php echo $scale; ?> alt="" /> </a> </div> </div> </div> <?php endif; ?><file_sep>/modules/system/forms/public/js/forms.js function copyPrototype(descendant, parent) { var sConstructor = parent.toString(); var aMatch = sConstructor.match( /\s*function (.*)\(/ ); if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } for (var m in parent.prototype) { descendant.prototype[m] = parent.prototype[m]; } } // Global forms contatiner var jforms = {}; /******************************************************************************* * jForm ******************************************************************************/ function jForm(name, id) { // Form name this.name = name; // Form id this.id = id; // Form elements {name => element} this.elements = {}; // Attach to container jforms[name] = this; } /** * Initialize form and elements */ jForm.prototype.init = function() { // Init elements for (var name in this.elements) { if (this.elements[name].init) { this.elements[name].init(); } } } /** * Add a new element to the form */ jForm.prototype.add_element = function(e) { e.form = this; this.elements[e.name] = e; } /** * Get form element by name */ jForm.prototype.get_element = function(name) { return this.elements[name]; } /** * Return all form elements */ jForm.prototype.get_elements = function() { return this.elements; } /** * Get all values from form */ jForm.prototype.get_values = function() { var values = {}; for (var name in this.elements) { e = this.elements[name]; values[name] = e.get_value(); } return values; } /** * Validate the form */ jForm.prototype.validate = function() { // No errors so far var result = true; // Validate all elements in form for (var name in this.elements) { e = this.elements[name]; if ( ! e.validate()) { result = false; // Display element errors e.display_errors(); } } return result; } /******************************************************************************* * jFormElement ******************************************************************************/ function jFormElement(name, id) { // Element name this.name = name; // Element id this.id = id; this.disabled = false; // Element value has been changed by user? this.tampered = false; // Form to which this element relates this.form = null; // Element validators this.validators = []; // Names of the elements to validate together with this one (i.e. password & confirmation) this.validate_also = []; // Validation errors this.errors = []; } /** * Initialize form element. * * Set up all necessary event handlers */ jFormElement.prototype.init = function() { var self = this; // Init validators for (var i = 0; i < this.validators.length; i++) { if (this.validators[i].init) { this.validators[i].init(); } } // Validate element when it looses focus // and highlight as active when it gets focus $('#' + this.id) .blur(function(){ // Mark element as changed self.tampered = true; // Validate it (and display/hide errors accordingly) self.validate(); }) .focus(function(){ self.set_active(); }); // Disable element if (this.disabled) { this.disable(); } if (this.autocomplete_url) { // Enable autocomplete for this field this.autocomplete(); } } /** * Add validator to element */ jFormElement.prototype.add_validator = function(v) { v.element = this; this.validators.push(v); } /** * Add the name of the dependent form element * * It will be validated together with this element */ jFormElement.prototype.add_validate_also = function(name) { this.validate_also.push(name); } /** * Get form element value */ jFormElement.prototype.get_value = function() { return $('#' + this.id).val(); } /** * Set form element value */ jFormElement.prototype.set_value = function(value) { $('#' + this.id).val(value); } /** * Validate this element */ jFormElement.prototype.validate = function() { if ( ! this.tampered) { // Element has not been touched by user yet - don't validate return; } // Start validation chain this.start_validation(); // Validate other elements that depend on this one for (i = 0; i < this.validate_also.length; i++) { var name = this.validate_also[i]; var e = this.form.get_element(name); e.validate(); } } /** * Start validation chain */ jFormElement.prototype.start_validation = function() { // No errors so far this.errors = []; this.v_result = true; this.v_i = -1; // Index of the current validator this.v_value = this.get_value(); // Value to validate this.v_context = this.form.get_values(); // "Context" if (this.validators.length > 0) { this.next_validator(true); } else { this.set_valid(); } } /** * Process result of the current validator and move to the next one */ jFormElement.prototype.next_validator = function(result) { if (result == false && this.v_i >= 0) { var current_v = this.validators[this.v_i]; // This validator failed and so does the whole element validation this.v_result = false if (current_v.error_msg) { this.errors.push(current_v.error_msg); } else if (current_v.get_error_msg) { this.errors.push(current_v.get_error_msg()); } if (current_v.breaks_chain) { this.finish_validation(); return; } } // Move to the next validator this.v_i++; if (this.v_i < this.validators.length) { this.validators[this.v_i].validate(this.v_value, this.v_context); } else { this.finish_validation(); } } /** * Finish element validation, update the status */ jFormElement.prototype.finish_validation = function() { // Lets see what we've got here... if (this.v_result == true) { // Validation succeded this.set_valid(); } else { // Validation failed. this.set_invalid(); } } /** * Highlight element as invalid and * display errors for this element */ jFormElement.prototype.set_invalid = function() { // Highlight input as invalid $('#' + this.id + ',#' + this.id +'-status') .removeClass('valid active') .addClass('invalid'); // Display error messages $('#' + this.id + '-errors') .html('<div>' + this.errors.join('</div><div>') + '</div>') .show(); } /** * Highlight element as valid and * hide possible errors for this element */ jFormElement.prototype.set_valid = function() { // Highlight input as valid $('#' + this.id + ',#' + this.id +'-status') .removeClass('invalid active') .addClass('valid'); // Remove error messages $('#' + this.id + '-errors').empty().hide(); } /** * Set active */ jFormElement.prototype.set_active = function() { // Highlight input as active $('#' + this.id + ',#' + this.id +'-status') .removeClass('valid invalid') .addClass('active'); // Remove error messages $('#' + this.id + '-errors').empty().hide(); } /** * Reset element status */ jFormElement.prototype.reset_status = function() { // Remove all status classes $('#' + this.id + ',#' + this.id +'-status') .removeClass('valid invalid active'); // Remove error messages $('#' + this.id + '-errors').empty().hide(); } /** * Enable element */ jFormElement.prototype.enable = function() { this.enabled = true; $('#' + this.id) .attr('disabled', false); $('#' + this.id + ',#' + this.id +'-status') .removeClass('disabled'); if ($('#' + this.id).is('select')) { restyle_selects(new Array(this.id)); } } /** * Disable element */ jFormElement.prototype.disable = function() { this.enabled = false; this.reset_status(); $('#' + this.id) .attr('disabled', true); $('#' + this.id + ',#' + this.id +'-status') .addClass('disabled'); if ($('#' + this.id).is('select')) { restyle_selects(new Array(this.id)); } } /** * Init autocomplete for this element */ jFormElement.prototype.autocomplete = function() { // Initialize autocomplete this.ac_popup = new Autocomplete(this); } /******************************************************************************* * Autocomplete popup ******************************************************************************/ /** * Initialize autocomplete popup for the specified form element */ function Autocomplete(form_element) { var self = this; this.form_element = form_element; // Find popup DOM element by id (constructed from form element id)ы this.popup = $('#' + form_element.id + '-autocomplete'); // Popup is not visible this.visible = false; // Form element event handlers $('#' + form_element.id).keydown(function(event){ if (event.keyCode == '38') { // An "up" key was pressed self.up(form_element); } else if (event.keyCode == '40') { // A "down" key was pressed self.down(form_element) } }).keypress(function(event){ if (event.keyCode == '13' && self.visible) { // An "enter" key was pressed event.preventDefault(); self.hide(); } else if (event.keyCode != '9' && event.keyCode != '38' && event.keyCode != '40') { // Peform an ajax request when key is pressed in the input (except up, down, enter and tab) // with some delay, because we need the value in form input to be updated after the keypress var text_val; text_val = form_element.get_value(); if (form_element.autocomplete_chunk) { var text_vals; text_vals = text_val.split(form_element.autocomplete_chunk); text_val = text_vals[text_vals.length -1]; } setTimeout(function(){ $.post(form_element.autocomplete_url, 'value=' + encodeURIComponent(text_val), function(response) { if (response) { //@FIXME: Security breach! eval('var items = ' + response + ';'); self.show(items); } else { self.hide(); } }) }, 30); } }).blur(function(){ // Hide autocomplete popup when element looses focus self.hide(); }); // Selecting items with mouse this.popup.mouseover(function(event){ var i = self.get_i_by_target(event.target); if (i > -1) { self.highlight(i); } }).mousedown(function(event){ var i = self.get_i_by_target(event.target); if (i > -1) { self.highlight(i, true,form_element); } else { target = $(event.target); if (target.hasClass('active')) { target.click(); } } }); } /** * Highlight currently selected item */ Autocomplete.prototype.highlight = function(i, set_value,form_element) { this.i = i; // Unhighlight all items $('.item', this.popup).removeClass('highlighted'); // Highlight the current one $('.i_' + i, this.popup).addClass('highlighted'); if (set_value) { var text_val = ''; if (form_element.autocomplete_chunk) { var text_vals; text_vals = form_element.get_value().split(form_element.autocomplete_chunk); for (var j = 0; j < text_vals.length-1; j++) { text_val =text_val + text_vals[j] + form_element.autocomplete_chunk; } } this.items[i].value.name = text_val + this.items[i].value.name; var method = 'set_' + this.form_element.id; // Copy selected item value to form input if (method_exists(this.form_element,method)) { eval('this.form_element.'+ method)(this.items[i].value); } else { this.form_element.set_value(this.items[i].value); } } } /** * Move to the previous item (when user presses "up" key) */ Autocomplete.prototype.up = function(form_element) { if (this.i > 0) { this.highlight(this.i - 1, true,form_element); } } /** * Move to the next item (when user presses "down" key) */ Autocomplete.prototype.down = function(form_element) { if (this.i < this.items.length - 1) { this.highlight(this.i + 1, true,form_element); } } /** * Show autocomplete popup and fill it with the specified items */ Autocomplete.prototype.show = function(items) { this.items = items; // Reset index of currently selected item this.i = -1; // Clean-up popup contents this.popup.empty(); // Create a div wrapper var items_wrapper = $('<div class="autocomplete"></div>').appendTo(this.popup); // Add items for (var i = 0; i < items.length; i++) { $('<div class="item i_' + i + '">' + items[i].caption + '</div>') .appendTo(items_wrapper) } this.popup.show(); this.visible = true; } /** * Hide autocomplete popup */ Autocomplete.prototype.hide = function() { this.popup.hide(); this.visible = false; } /** * Determine index of selected item by target of the event */ Autocomplete.prototype.get_i_by_target = function(target) { target = $(target); if (target.hasClass('item')) { // Determine the index of the clicked item by class name (like i_2) var matches = target.attr('class').match(/i_(\d+)/); if (matches[1]) { return parseInt(matches[1]); } } return -1; } /******************************************************************************* * jFormElementCheckboxEnable ******************************************************************************/ function jFormElementCheckboxEnable(name, id) { // Call parent constructor this.jFormElement(name, id); this.dep_elements = []; } // Inherit from jFormElement copyPrototype(jFormElementCheckboxEnable, jFormElement); /** * Set dependent elements */ jFormElementCheckboxEnable.prototype.set_dep_elements = function(elements) { this.dep_elements = elements; } /** * Init element */ jFormElementCheckboxEnable.prototype.init = function() { var self = this; // Toggle dependent elements on value change $('#' + this.id) .click(function(){ self.toggle_dependent(); }); } /** * Get checkbox value */ jFormElementCheckboxEnable.prototype.get_value = function() { //@TODO: not 'true', 'false', but actual values.... return $('#' + this.id).attr('checked') ? true : false; } /** * Enable/disable dependent elements */ jFormElementCheckboxEnable.prototype.toggle_dependent = function() { var value = this.get_value(); var i=0; var name; var e; for (i = 0; i < this.dep_elements.length; i++) { name = this.dep_elements[i]; e = this.form.get_element(name); if ( ! e) continue; if (value) e.enable(); else e.disable(); } for (i = 0; i < this.depvis_elements.length; i++) { name = this.depvis_elements[i]; e = this.form.get_element(name); if ( ! e) continue; if (value) e.visible = true; else e.visible = false; } } /******************************************************************************* * jFormValidatorRegexp ******************************************************************************/ function jFormValidatorRegexp(regexp, error_msg, allow_empty, breaks_chain) { this.regexp = regexp; this.error_msg = error_msg; this.allow_empty = allow_empty || false; this.breaks_chain = breaks_chain || true; } /** * Validate a value via validator */ jFormValidatorRegexp.prototype.validate = function(value, context) { var result = false; if ( value != null && ( value.match(this.regexp) || // value matches regexp (this.allow_empty && value.match(/^\s*$/)) // or value is empty and empty values are allowed ) ) { result = true; } this.element.next_validator(result); } /******************************************************************************* * jFormValidatorStringLength ******************************************************************************/ function jFormValidatorStringLength(min_length, max_length, config) { this.min_length = min_length; this.max_length = max_length; this.config = config; this.breaks_chain = true; } /** * Validate a value via validator */ jFormValidatorStringLength.prototype.validate = function(value, context) { var result = true; if (value.length < this.min_length) { this.error_msg = this.config.messages['TOO_SHORT']; result = false; } else if (value.length > this.max_length) { this.error_msg = this.config.messages['TOO_LONG']; result = false; } this.element.next_validator(result); } /******************************************************************************* * jFormValidatorEqualTo ******************************************************************************/ function jFormValidatorEqualTo(target, error_msg, breaks_chain) { this.target = target; this.error_msg = error_msg; this.breaks_chain = breaks_chain || true; } /** * Init validator */ jFormValidatorEqualTo.prototype.init = function() { // Target element should be validated together with this element var e = this.element.form.get_element(this.target); e.add_validate_also(this.element.name); } /** * Validate a value via validator */ jFormValidatorEqualTo.prototype.validate = function(value, context) { var result = false; if (context[this.target] && value == context[this.target]) { result = true; } this.element.next_validator(result); } /******************************************************************************* * jFormValidatorAjax ******************************************************************************/ function jFormValidatorAjax(url) { this.url = url; } /** * Validate a value via validator */ jFormValidatorAjax.prototype.validate = function(value, context) { // Serialize all form values var values = $('#' + this.element.form.id).serialize(); var self = this; $.post(this.url + '?name=' + this.element.name, values, function(data) { //@FIXME: Security breach! eval('var data = ' + data + ';'); // Find an error for this element var valid = true; for (var i = 0; i < data.length; i++) { //@FIXME: display all messages, not just the last one if (data[i]['field'] && data[i]['field'] == self.element.name) { // There is an error message for this element - validation failed self.error_msg = data[i]['text']; valid = false; } } // Next validator in chain self.element.next_validator(valid); }); return 0; } function method_exists (obj, method) { // http://kevin.vanzonneveld.net // + original by: <NAME> (http://brett-zamir.me) // * example 1: function class_a() {this.meth1 = function () {return true;}}; // * example 1: var instance_a = new class_a(); // * example 1: method_exists(instance_a, 'meth1'); // * returns 1: true // * example 2: function class_a() {this.meth1 = function () {return true;}}; // * example 2: var instance_a = new class_a(); // * example 2: method_exists(instance_a, 'meth2'); // * returns 2: false if (typeof obj === 'string') { return this.window[obj] && typeof this.window[obj][method] === 'function'; } return typeof obj[method] === 'function'; }<file_sep>/modules/shop/deliveries/classes/model/delivery/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Delivery_Mapper extends Model_Mapper { /** * Cache find_all queries * @var boolean */ public $cache_find_all = FALSE; public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('caption', array('Type' => 'varchar(63)')); $this->add_column('description', array('Type' => 'text')); $this->add_column('module', array('Type' => 'varchar(31)')); $this->add_column('settings', array('Type' => 'array')); $this->add_column('active', array('Type' => 'boolean')); } /** * Find model by criteria and return the model of correct class * * @param Model $model * @param Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Model */ public function find_by( Model $model, Database_Expression_Where $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { $result = $this->select_row($condition, $params); if (empty($result)) { $model->init(); return $model; } $class = 'Model_Delivery_' . ucfirst($result['module']); if (strtolower(get_class($model)) != strtolower($class)) { $model->init(); // Create new model of desired class $model = new $class; } $model->properties($result); return $model; } /** * Find all delivery types supported by given payment type * * @param Model_Delivery $delivery * @param Model_Payment $payment * @param array $params * @return Models */ public function find_all_by_payment(Model_Delivery $delivery, Model_Payment $payment, array $params = NULL) { $delivery_table = $this->table_name(); $paydeliv_table = Model_Mapper::factory('PaymentDelivery_Mapper')->table_name(); $columns = isset($params['columns']) ? $params['columns'] : array("$delivery_table.*"); $query = DB::select_array($columns) ->from($delivery_table) ->join($paydeliv_table, 'INNER') ->on("$paydeliv_table.delivery_id", '=', "$delivery_table.id") ->where("$paydeliv_table.payment_id", '=', (int) $payment->id); // Add limit, offset and order by statements if (isset($params['known_columns'])) { $known_columns = $params['known_columns']; } else { $known_columns = array(); } $this->_std_select_params($query, $params, $known_columns); $result = $query->execute($this->get_db()); $data = array(); if (count($result)) { // Convert to correct types foreach ($result as $values) { $data[] = $this->_unsqlize($values); } } return new Models(get_class($delivery), $data); } }<file_sep>/modules/shop/countries/classes/model/postoffice/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PostOffice_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('country_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('region_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('name', array('Type' => 'varchar(255)')); $this->add_column('city', array('Type' => 'varchar(255)')); $this->add_column('postcode', array('Type' => 'varchar(31)', 'KEY' => 'INDEX')); } /** * Find all postoffices by part of the postcode * * @param Model $model * @param string $postcode * @param array $params * @return Models */ public function find_all_like_postcode(Model $model, $postcode, array $params = NULL) { return $this->find_all_by($model, DB::where('postcode', 'LIKE', "$postcode%"), $params); } /** * Find all postoffices by part of the city name * * @param Model $model * @param string $city * @param array $params * @return Models */ public function find_all_like_city(Model $model, $city, array $params = NULL) { return $this->find_all_by($model, DB::where('city', 'LIKE', "%$city%"), $params); } /** * Find all postoffices by condition * * @param Model $model * @param Database_Expression_Where $condition * @param array $params * @param Database_Query_Builder_Select $query * @return Models|array */ public function find_all_by( Model $model, Database_Expression_Where $condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL ) { $postoffice_table = $this->table_name(); $region_table = $region_mapper = Model_Mapper::factory('Model_Region_Mapper')->table_name(); $query = DB::select('*', array("$region_table.name", 'region_name')) ->from($this->table_name()) ->join($region_table, 'LEFT') ->on("$region_table.id", '=', "$postoffice_table.region_id"); return parent::find_all_by($model, $condition, $params, $query); } }<file_sep>/modules/system/forms/classes/form/element/options.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Select from a list of options * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Options extends Form_Element { /** * Select options * @var array */ protected $_options = array(); /** * Creates form select element * * @param string $name Element name * @param array $options Select options * @param array $properties * @param array $attributes */ public function __construct($name, array $properties = NULL, array $attributes = NULL) { parent::__construct($name, $properties, $attributes); for ($i = 0; $i < $this->options_count; $i++) { $element = new Form_Element_Input($this->name . "[$i]", array('label' => '', 'layout' => 'standart'), $attributes); $this->add_component($element); } } /** * Add filter to the every option * * @param Form_Filter $validator * @return Form_Element_Options */ public function add_filter(Form_Filter $filter) { foreach ($this->get_components() as $component) { if ($component instanceof Form_Element) { $component->add_filter($filter); } } return $this; } /** * Add validator to the every option * * @param Form_Validator $validator * @return Form_Element_Options */ public function add_validator(Form_Validator $validator) { foreach ($this->get_components() as $component) { if ($component instanceof Form_Element) { $component->add_validator($validator); } } return $this; } /** * Return input type * @return string */ public function default_type() { return 'options'; } /** * Default name for parameter in url that holds the number of options * @return string */ public function default_options_count_param() { return 'options_count'; } /** * Default caption of the incremental link * @return string */ public function default_option_caption() { return 'добавить опцию'; } /** * Get number of options for input * * @return integer */ public function get_options_count() { $options_count = Request::current()->param($this->options_count_param); if ($options_count !== NULL) return $options_count; if (isset($this->_properties['options_count'])) return $this->_properties['options_count']; return 0; } /** * Render form element * * @return string */ public function render() { $html = parent::render(); // Url to increase options count $url_params = array(); $url_params[$this->options_count_param] = $this->options_count + 1; Template::replace($html, 'inc_options_count_url', URL::self($url_params)); Template::replace($html, 'option_caption',$this->option_caption); return $html; } /** * Renders select element, constiting of checkboxes * * @return string */ public function render_input() { $html = ''; foreach ($this->get_components() as $component) { $html .= $component->render(); } return $html; } /** * No javascript for this element * * @return string */ public function render_js() { return FALSE; } } <file_sep>/modules/shop/catalog/views/frontend/products/list.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'frontend/products/_map')); ?> <?php if ( ! count($products)) { echo '<i>Анонсов нет</i>'; } else { $count = count($products); $i = 0; $products->rewind(); if (!isset($without_dateheaders)) $without_dateheaders=FALSE; $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $today_time = $today_datetime->format('d.m.Y'); $tomorrow_time = $tomorrow_datetime->format('d.m.Y'); $today_events = array(); $tomorrow_events = array(); $near_events = array(); $today_str = ""; $tomorrow_str = ""; $near_str = ""; while ($i < $count) { $product = $products->current(); $products->next(); $prod_time = $product->datetime->format('d.m.Y'); if($prod_time == $today_time) { array_push($today_events, $product); $today_str .= Widget::render_widget('products', 'small_product', $product); $today_str .= Widget::render_widget('telemosts', 'request', $product); } else if($prod_time == $tomorrow_time) { array_push($tomorrow_events, $product); $tomorrow_str .= Widget::render_widget('products', 'small_product', $product); $tomorrow_str .= Widget::render_widget('telemosts', 'request', $product); } else { array_push($near_events, $product); $near_str .= Widget::render_widget('products', 'small_product', $product); $near_str .= Widget::render_widget('telemosts', 'request', $product); } $i++; } if(count($today_events)) { echo '<h1 class="main-title"><span>Сегодня, '.$today_time.'</span></h1>'; // foreach ($today_events as $product) { // echo Widget::render_widget('products', 'small_product', $product); // Widget::render_widget('telemosts', 'request', $product); // } echo $today_str; } if(count($tomorrow_events)) { echo '<h1 class="main-title"><span>Завтра, '.$tomorrow_time.'</span></h1>'; // foreach ($tomorrow_events as $product) { // echo Widget::render_widget('products', 'small_product', $product); // Widget::render_widget('telemosts', 'request', $product); // } echo $tomorrow_str; } if (count($near_events)) { if (isset($is_archive) && $is_archive) { $title = 'Архивные события'; } else { $title = 'В ближайшее время'; } echo "<h1 class='main-title'><span>$title</span></h1>"; // foreach ($near_events as $product) { // echo Widget::render_widget('products', 'small_product', $product); // Widget::render_widget('telemosts', 'request', $product); // } echo $near_str; } ?> <?php if ($pagination) { echo $pagination; } }?> <file_sep>/modules/shop/orders/classes/model/cart/mapper/session.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Cart_Mapper_Session { /** * Get cart data from session */ protected function _get_data() { return Session::instance()->get('cart', array()); } /** * Write cart data to session */ protected function _set_data($cart_data) { Session::instance()->set('cart', $cart_data); } /** * Save cart data * * @param Model_Cart $cart */ public function save(Model_Cart $cart) { $cart_data = array(); foreach ($cart->cartproducts as $cartproduct) { $cart_data[$cartproduct->product_id] = $cartproduct->quantity; } $this->_set_data($cart_data); } /** * Get all products in cart with product info joined * * @param Model_Cart $cart * @param array $params * @return Models */ public function get_cartproducts(Model_Cart $cart, array $params = NULL) { $cartproducts = new Models('Model_CartProduct', array(), 'product_id'); $cart_data = $this->_get_data(); if (empty($cart_data)) { // No products in cart yet return $cartproducts; } $product = new Model_Product(); $cartproduct = new Model_CartProduct(); $product_ids = array_keys($cart_data); //$params['with_images'] = TRUE; $products = Model::fly('Model_Product')->find_all_by(array( 'ids' => $product_ids, 'active' => 1, 'section_active' => 1, 'site_id' => Model_Site::current()->id ), $params); foreach ($products as $product) { if (isset($cart_data[$product->id])) { $quantity = $cart_data[$product->id]; $cartproduct->from_product($product); $cartproduct->quantity = $quantity; $cartproducts[$product->id] = $cartproduct; } } return $cartproducts; } }<file_sep>/modules/shop/acl/public/js/backend/organizer_name.js /** * Set form element value */ jFormElement.prototype.set_organizer_name = function(value) { if (value['name'] && value['id']) { $('#' + 'organizer_name').val(value['name']); $('#' + 'organizer_id').val(value['id']); } else { $('#' + 'organizer_name').val(value); } }<file_sep>/modules/shop/catalog/classes/task/import/structure.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Import structure */ class Task_Import_Structure extends Task { /** * Default parameters for this taks * @var array */ public static $default_params = array( // sections 'create_sections' => FALSE, 'update_section_parents' => FALSE, 'update_section_captions' => FALSE, 'update_section_descriptions' => FALSE, 'update_section_images' => FALSE, // products 'create_products' => TRUE, 'update_product_marking' => FALSE, 'update_product_captions' => FALSE, 'update_product_descriptions' => FALSE, 'update_product_properties' => FALSE, 'update_product_images' => FALSE, 'link_products_by' => 'caption' ); /** * Construct task */ public function __construct() { parent::__construct(); $this->default_params(self::$default_params); } /** * Run the task */ public function run() { $this->set_progress(0); $supplier = (int) $this->param('supplier'); if ( ! array_key_exists($supplier, Model_Product::suppliers())) { $this->log('Указан неверный поставщик', Log::ERROR); return; } $file = $this->param('file'); if ( ! is_readable($file)) { $this->log('Не удалось прочитать файл "' . $file . '"', Log::ERROR); return; } $this->set_status_info('Reading xls file...'); $reader = XLS::reader(); $reader->setOutputEncoding('UTF-8'); $reader->read($file); $this->set_status_info( 'Импорт струтуры' . ' (поставщик: ' . Model_Product::supplier_caption($supplier)); // Generate unique import id $loop_prevention = 500; do { $import_id = mt_rand(1, mt_getrandmax()); } while (Model::fly('Model_Section')->exists_by_import_id($import_id) && Model::fly('Model_Product')->exists_by_import_id($import_id) && $loop_prevention-- > 0); if ($loop_prevention <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' =>__METHOD__)); switch ($supplier) { case Model_Product::SUPPLIER_IKS: $this->iks($reader, $import_id); break; case Model_Product::SUPPLIER_ISV: $this->isv($reader, $import_id); break; } $this->process_not_imported_products($supplier, $import_id); // update stats Model::fly('Model_Section')->mapper()->update_products_count(); $this->set_status_info('Import finished. (' . date('Y-m-d H:i:s') . ')'); //@FIXME: Unlink only temporary files //unlink($file); } /** * Import Iks catalog structure */ public function iks(Spreadsheet_Excel_Reader $reader, $import_id) { foreach ($reader->boundsheets as $sheet_num => $sheet_desc) { $sheets[$sheet_desc['name']] = $sheet_num; } // import sections if (!isset($sheets['sections'])) { $this->set_status_info('Каталогов не обнаружено'); return FALSE; } $sections = $this->iks_import_sections($reader,$sheets['sections'],$import_id); // import products if (!isset($sheets['products'])) { $this->set_status_info('Товаров не обнаружено'); return FALSE; } $this->iks_import_products($reader,$sheets['products'],$import_id,$sections); $this->set_status_info('Импорт завершён'); } public function iks_import_sections(Spreadsheet_Excel_Reader $reader,$sheet, $import_id) { $sections = array(0 => array()); $this->set_status_info('Fetching sections'); $rowcount = $reader->rowcount($sheet); for ($row = 1; $row <= $rowcount; $row++) { if ($row % 20 == 0) { $this->set_progress((int) (($row - 1) * 100 / $rowcount)); } if ($reader->val($row, 1,$sheet) == '' || $reader->val($row, 1,$sheet) == 'import_id') continue; // Not a section row $section = array(); $parent_import_id = $reader->val($row, 2, $sheet); if ($parent_import_id == '') $parent_import_id = 0; $section['import_id'] = $import_id; $section['web_import_id'] = $reader->val($row, 1, $sheet); $section['caption'] = $reader->val($row, 3, $sheet); $section['description'] = $reader->val($row, 4, $sheet); $section['meta_title'] = $reader->val($row, 5, $sheet); $section['meta_description'] = $reader->val($row, 6, $sheet); $section['meta_keywords'] = $reader->val($row, 7, $sheet); $section['image_file'] = $reader->val($row, 8, $sheet); $sections[$parent_import_id][] = $section; } $sections = $this->import_sections($sections); $flat_sections = array(); foreach ($sections as $parent_import_id => $child_sections) { foreach($child_sections as $section) { $flat_sections[$section['web_import_id']] = $section; } } return $flat_sections; } /** * Import a branch of sections * * @param array $sections * @param Model_Section $parent */ public function import_sections(array $sections, Model_Section $parent = NULL) { if ($parent === NULL) { $count = count($sections[0]); $i = 0; $this->set_status_info('Importing sections'); } $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task $folder = DOCROOT . 'public/user_data/'; // get all product properties static $propsections; if ($propsections === NULL) { $properties = Model::fly('Model_Property')->find_all_by_site_id($site_id, array('columns' => array('id'))); $propsections = array(); foreach ($properties as $property) { $propsections[$property['id']] = array( 'active' => 1, 'filter' => 0, 'sort' => 0 ); } } $section = new Model_Section(); $parent_import_id = ($parent !== NULL) ? $parent->web_import_id : 0; if ( ! isset($sections[$parent_import_id])) return $sections; // No sections in branch foreach ($sections[$parent_import_id] as $import_id => $section_info) { $section->find_by_web_import_id_and_sectiongroup_id($section_info['web_import_id'], $sectiongroup_id); $creating = ( ! isset($section->id)); // import_id $section->import_id = $section_info['import_id']; // web_import_id $section->web_import_id = $section_info['web_import_id']; // sectiongroup_id $section->sectiongroup_id = $sectiongroup_id; // parent_id if ($parent !== NULL && ($creating || $this->param('update_section_parents'))) { $section->parent_id = $parent->id; } // caption if (isset($section_info['caption']) && ($creating || $this->param('update_section_captions'))) { $section->caption = $section_info['caption']; } // description if (isset($section_info['description']) && ($creating || $this->param('update_section_descriptions'))) { $section->description = $section_info['description']; $section->meta_title = $section_info['meta_title']; $section->meta_description = $section_info['meta_description']; $section->meta_keywords = $section_info['meta_keywords']; } // product properties if ($creating) { $section->propsections = $propsections; } if ($creating) { if ($this->param('create_sections')) { $section->save(FALSE, TRUE, FALSE); if ($parent === NULL) { $this->log('Создан новый раздел "' . $section->caption . '"'); } else { $this->log('Создан новый подраздел "' . $section->caption . '" в разделе "' . $parent->caption . '"'); } } else { if ($parent === NULL) { $this->log('Пропущен новый раздел "' . $section->caption . '"'); } else { $this->log('Пропущен новый подраздел "' . $section->caption . '" в разделе "' . $parent->caption . '"'); } continue; } } else { $section->save(FALSE, FALSE, FALSE); } $section->find($section->id); //@FIXME: we use it to obtain 'lft' and 'rgt' values for saved brand // save section id $sections[$parent_import_id][$import_id]['id'] = $section->id; // logo if (!empty($section_info['image_file']) && $this->param('update_section_images')) { $image = new Model_Image(); if ( ! $creating) { // Delete existing images $image->delete_all_by_owner_type_and_owner_id('section', $section->id); } $image_file = $folder.$section_info['image_file']; if (file_exists($image_file)) { try { $image->source_file = $image_file; $image->owner_type = 'section'; $image->owner_id = $section->id; $image->config = 'section'; $image->save(); } catch (Exception $e) {} } } // ----- Import subsections $sections = $this->import_sections($sections, $section); if ($parent === NULL) { $i++; $this->set_status_info('Importing brands : ' . $i . ' of ' . $count . ' done.'); } } if ($parent === NULL) { // Update activity info & stats for sections $section->mapper()->update_activity(); $section->mapper()->update_products_count(); } return $sections; } /** * Import products * * @param array $sections */ public function iks_import_products(Spreadsheet_Excel_Reader $reader,$sheet, $import_id,$sections) { $products = array(); $this->set_status_info('Fetching products'); $rowcount = $reader->rowcount($sheet); for ($row = 1; $row <= $rowcount; $row++) { if ($row % 20 == 0) { $this->set_progress((int) (($row - 1) * 100 / $rowcount)); } if ($reader->val($row, 1,$sheet) == '' || $reader->val($row, 1,$sheet) == 'section_import_id') continue; // Not a product row $product = array(); $product['import_id'] = $import_id; $product['web_import_id'] = $reader->val($row, 2, $sheet); $product['caption'] = $reader->val($row, 4, $sheet); // section $section_import_id = $reader->val($row, 1, $sheet); if ($section_import_id == '') $section_import_id = 0; if (!isset($sections[$section_import_id]['id'])) { $this->log( '[Строка ' . $row . ']: Для товара "' . $product['caption'] . ' не был создан необходимый каталог' , Log::ERROR); continue; } $section_id = $sections[$section_import_id]['id']; // marking $product['marking'] = $reader->val($row, 3, $sheet); if ($product['marking'] == '') { $this->log( '[Строка ' . $row . ']: Для товара "' . $product['caption'] . ' не удалось определить артикул' , Log::ERROR); continue; } $product['description'] = $reader->val($row, 5, $sheet); // price $product['price'] = trim($reader->raw($row, 6, $sheet)); if ($product['price'] == '') { $product['price'] = $reader->val($row, 6, $sheet); } if ($product['price'] == '' || ! preg_match('/\d+([\.,]\d+)?/', $product['price'])) { $this->log( '[Строка ' . $row . ']: Некорретное значение цены ' . $product['price'] . ' для товара "' . $product['caption'] , Log::ERROR); continue; } // available $product['available'] = $reader->val($row, 7, $sheet); // stone $product['stone'] = $reader->val($row, 8, $sheet); // weight $product['weight'] = trim($reader->raw($row, 9, $sheet)); if ($product['weight'] == '') { $product['weight'] = $reader->val($row, 9, $sheet); } if ($product['weight'] == '' || ! preg_match('/\d+([\.,]\d+)?/', $product['weight'])) { $this->log( '[Строка ' . $row . ']: Некорретное значение веса ' . $product['weight'] . ' для товара "' . $product['caption'] , Log::ERROR); continue; } $product['metal'] = $reader->val($row, 10, $sheet); $product['stone_char'] = $reader->val($row, 11, $sheet); $product['other_char'] = $reader->val($row, 12, $sheet); $product['image_file'] = $reader->val($row, 13, $sheet); $products[$section_id][] = $product; } return $this->import_products($products, Model_Product::SUPPLIER_IKS); } public function import_products(array $products,$supplier) { $section = new Model_Section(); $product = new Model_Product(); $folder = DOCROOT . 'public/user_data/'; $this->set_status_info('Importing products'); foreach ($products as $section_id => $section_products) { $section->find($section_id); foreach ($section_products as $product_info) { $product->find_by_web_import_id_and_section_id($product_info['web_import_id'],$section_id); $creating = (!isset($product->id)); // import_id $product->import_id = $product_info['import_id']; unset($product_info['import_id']); // web_import_id $product->web_import_id = $product_info['web_import_id']; unset($product_info['web_import_id']); // section_id $product->section_id = $section_id; // suppliers $product->supplier = $supplier; // marking if (isset($product_info['marking']) && ($creating || $this->param('update_product_markings'))) { $product->marking = $product_info['marking']; unset($product_info['marking']); } // caption if (isset($product_info['caption']) && ($creating || $this->param('update_product_captions'))) { $product->caption = $product_info['caption']; unset($product_info['caption']); } // description if (isset($product_info['description']) && ($creating || $this->param('update_product_descriptions'))) { $product->description = $product_info['description']; unset($product_info['description']); } // properties if ($creating || $this->param('update_product_properties')) { // price $product->price =new Money($product_info['price']); unset($product_info['price']); // available $product->available = $product_info['available']; unset($product_info['available']); // additional foreach ($product_info as $property => $value) { $product->$property = $value; } } if ($creating) { if ($this->param('create_products')) { $product->save(); $this->log('Создан новый товар "' . $product->caption . '"'); } else { $this->log('Пропущен новый товар "' . $product->caption . '"'); continue; } } else { $product->save(FALSE, FALSE, FALSE, FALSE, FALSE); } // image if (!empty($product_info['image_file']) && $this->param('update_product_images')) { $image = new Model_Image(); if ( ! $creating) { // Delete existing images $image->delete_all_by_owner_type_and_owner_id('product', $product->id); } $image_file = $folder.$product_info['image_file']; if (file_exists($image_file)) { try { $image->source_file = $image_file; $image->owner_type = 'product'; $image->owner_id = $product->id; $image->config = 'product'; $image->save(); } catch (Exception $e) {} } } } } } /** * Import saks pricelist */ public function saks($reader, $import_id) { $site_id = 1; //@TODO: pass via params $rowcount = $reader->rowcount(); for ($row = 1; $row <= $rowcount; $row++) { if ($row % 20 == 0) { $this->set_progress((int) (($row - 1) * 100 / $rowcount)); } if ($reader->val($row, 7) == '' || $reader->val($row, 7) == 'Штрих-код') continue; // Not a product row // ----- caption $caption = $reader->val($row, 3); // ----- marking $marking = $reader->val($row, 2); $marking = trim($marking, " '"); if ($marking == '') { $this->log( '[Строка ' . $row . ']: Для товара "' . $caption . '" не удалось определить артикул' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } // ----- price $price = trim($reader->raw($row, 4)); if ($price == '') { $price = $reader->val($row, 4); } if ($price == '' || ! preg_match('/\d+([\.,]\d+)?/', $price)) { $this->log( '[Строка ' . $row . ']: Некорретное значение цены ' . $price . ' для товара "' . $caption . '"' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } $this->process_product($marking, Model_Product::SUPPLIER_SAKS, $price, $caption, NULL, $import_id); } } /** * Import gulliver pricelist */ public function gulliver($reader, $import_id) { $site_id = 1; //@TODO: pass via params $rowcount = $reader->rowcount(); for ($row = 1; $row <= $rowcount; $row++) { if ($row % 20 == 0) { $this->set_progress((int) (($row - 1) * 100 / $rowcount)); } if ($reader->val($row, 5) == '' || $reader->val($row, 5) == 'Цена') continue; // Not a product row // ----- caption $caption = $reader->val($row, 3); // ----- marking $marking = $reader->val($row, 2); if ($marking == '') { $this->log( '[Строка ' . $row . ']: Для товара "' . $caption . '" не удалось определить артикул' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } // ----- price $price = trim($reader->raw($row, 5)); if ($price == '') { $price = $reader->val($row, 5); } if ($price == '' || ! preg_match('/\d+([\.,]\d+)?/', $price)) { $this->log( '[Строка ' . $row . ']: Некорретное значение цены ' . $price . ' для товара "' . $caption . '"' //. "\n" //. 'val: ' . $reader->val($row, 4) . "\n" //. 'raw: ' . $reader->raw($row, 4) . "\n" , Log::ERROR); continue; } $this->process_product($marking, Model_Product::SUPPLIER_GULLIVER, $price, $caption, NULL, $import_id); } } /** * Update price for product with given marking and supplier */ public function process_product($marking, $supplier, $price, $caption, $brand_caption, $import_id, $marking_like = FALSE) { $site_id = 1; //@FIXME: pass via task params static $brands; if ($brands === NULL) { $brands = Model::fly('Model_Section')->find_all_by_sectiongroup_id(1, array( 'columns' => array('id', 'lft', 'rgt', 'level', 'caption'), 'as_tree' => TRUE )); } $products = Model::fly('Model_Product')->find_all_by_marking_and_supplier_and_site_id( $marking, $supplier, $site_id, array( 'columns' => array('id', 'marking', 'caption') ) ); if (count($products) <= 0) { $this->log('Товар из прайслиста с артикулом ' . $marking . ' ("' . $caption . '", ' . $brand_caption . ') не найден в каталоге сайта', Log::WARNING); return; } if (count($products) >= 2) { // Two or more products with the same marking $brand_products = array(); if ($brand_caption != '') { // Try to guess the product by brand foreach ($products as $product) { $brand_ids = $product->get_section_ids(1); foreach ($brand_ids as $brand_id) { // Find top-level brand $brand = $brands->ancestor($brand_id, 1); // Product belongs to the brand if ($brand_caption == $brand->caption) { $brand_products[] = $product->id; } } } } if (count($brand_products) != 1) { // Failed to distinguish duplicate markings by brand... $msg = ''; foreach ($products as $product) { $msg .= $product->marking . ' ("' . $product->caption . '")' . "\n"; } $this->log( 'Артикул ' . $marking . ' ("' . $caption . '", ' . $brand_caption . ') не является уникальным в каталоге сайта:' . "\n" . trim($msg, ' ",') , Log::ERROR); return; } $product = $products[$brand_products[0]]; } else // count($products) == 1 { $product = $products->at(0); } $product->active = 1; /*$price_factor = l10n::string_to_float($this->param('price_factor')); $sell_price = ceil($price * $price_factor); $product->price = new Money($sell_price);*/ $product->price = new Money($price); $product->import_id = $import_id; $product->save(FALSE, FALSE, FALSE, FALSE, FALSE); } /** * Display warnings about products that are present in the catalog but are not present in the pricelist */ public function process_not_imported_products($supplier, $import_id) { $site_id = 1; //@FIXME: pass via task params $loop_prevention = 1000; do { $products = Model::fly('Model_Product')->find_all_by( array( 'supplier' => $supplier, 'site_id' => $site_id, 'import_id' => array('<>', $import_id) ), array( 'columns' => array('id', 'marking', 'caption'), 'batch' => 100 ) ); foreach ($products as $product) { $this->log('Деактивирован товар с артикулом ' . $product->marking . ' ("' . $product->caption . '"). Товар есть в каталоге сайта, но отсутствует в прайс-листе', Log::WARNING); $product->active = 0; $product->save(FALSE, FALSE, FALSE, FALSE, FALSE); } } while (count($products) && $loop_prevention-- > 0); if ($loop_prevention <= 0) throw new Kohana_Exception('Possible infinite loop in :method', array(':method' => __METHOD__)); } } <file_sep>/modules/shop/catalog/views/backend/products/select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($section === NULL || $section->id === NULL) { $section_id = '0'; } else { $section_id = (string) $section->id; } // ----- Set up urls // Presume that the results should be submitted to the previous url $products_select_uri = URL::uri_back(); ?> <?php // Current section caption if (isset($section) && $section->id !== NULL) { echo '<h3 class="section_caption">' . HTML::chars($section->caption) . '</h3>'; } ?> <?php // Search form echo $search_form->render(); ?> <?php echo View_Helper_Admin::multi_action_form_open($products_select_uri); ?> <table class="products table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'caption' => 'Название', 'active' => 'Акт.', ); echo View_Helper_Admin::table_header($columns, 'cat_porder', 'cat_pdesc'); ?> </tr> <?php foreach ($products as $product) : ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($product->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'caption': echo '<td class="capt' .(empty($product->active) ? ' inactive' : '') . '">' . HTML::chars($product->$field) . '</td>'; break; case 'active': echo '<td class="c">'; if ( ! empty($product->$field)) { echo View_Helper_Admin::image('controls/on.gif', 'Да'); } else { echo View_Helper_Admin::image('controls/off.gif', 'Нет'); } echo '</td>'; break; default: echo '<td>'; if (isset($product->$field) && trim($product->$field) !== '') { echo HTML::chars($product[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> </tr> <?php endforeach; ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_select', 'label' => 'Выбрать', 'class' => 'button_select') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/catalog/classes/form/backend/catalog/generatealiases.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Catalog_GenerateAliases extends Form_Backend { /** * Initialize form fields */ public function init() { $this->attribute('class', 'w300px'); // Set HTML class //$this->layout = 'wide'; $element = new Form_Element_Text('text'); $element->value = 'Пересоздать алиасы (имена в URL) для товаров и разделов' . Widget::render_widget('tasks', 'status', 'generatealiases'); $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Пересоздать'), array('class' => 'button_accept') )); } }<file_sep>/application/classes/template.php <?php defined('SYSPATH') OR die('No direct access allowed.'); /** * Simple template helper * * @package Eresus * @author <NAME> (<EMAIL>) */ class Template { /** * Check if the template contains the specified macros (or any macros at all, if $macro is NULL) * * @param string $template * @param string $macro * @return boolean */ public static function has_macro($template, $macro = NULL) { if ($macro !== NULL) { self::_make_macro_cb($macro); } else { $macro = '{{'; } return (strpos($template, $macro) !== FALSE); } /** * Replace macroses in template (recursively) * * @param string $template * @param array|string $values * @param array|string $values2 */ public static function replace(& $template, $values, $values2 = NULL) { if (is_array($values)) { $values = array_filter($values, array('Template', '_prepare_value_cb')); $macroses = array_keys($values); $values = array_values($values); $macroses = array_map(array('Template', '_make_macro_cb'), $macroses); } else { $macroses = $values; $values = $values2; $macroses = self::_make_macro_cb($macroses); } $count = 0; $loop_prevention = 0; do { $count = 0; if (self::has_macro($template)) { $template = str_replace($macroses, $values, $template, $count); } $loop_prevention++; } while ($count > 0 && $loop_prevention < 100); if ($loop_prevention >= 100) { throw new Exception('Endless loop in ' . __FUNCTION__ . '!'); } } /** * Replace macroses in template and return the result * * @param string $template * @param array|string $values * @param array|string $values2 * @return string */ public static function replace_ret($template, $values, $values2 = NULL) { $result = $template; self::replace($result, $values, $values2); return $result; } protected static function _prepare_value_cb($value) { return ( ! is_array($value)); } protected static function _make_macro_cb($value) { return '{{'.$value.'}}'; } } <file_sep>/modules/shop/orders/views/frontend/cart/summary.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $total_count = $cart->total_count; echo '<a href="' . URL::to('frontend/cart') . '">' . HTML::image('public/css/img/cart.gif', array('style' => 'display:inline-block; vertical-align:middle; margin:0 10px 0 10px;', 'alt' => 'Ваша корзина')) . '</a>' . '<span class="big">'; if ($total_count == 0) { echo 'пуста'; } else { echo '<a href="' . URL::to('frontend/cart') . '">' .'<strong>'.$total_count . ' ' . l10n::plural($total_count, 'товар', 'товаров', 'товара').'</strong>' . '</a>'; } echo '</span>'; ?><file_sep>/modules/shop/acl/classes/model/userpropvalue/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_UserPropValue_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('userprop_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('value', array('Type' => 'varchar(31)')); } /** * Update userprop values for given user * * @param Model_User $user */ public function update_values_for_user(Model_User $user) { foreach ($user->userprops as $userprop) { $name = $userprop->name; $value = $user->__get($name); if ($value === NULL) continue; $where = DB::where('user_id', '=', (int) $user->id) ->and_where('userprop_id', '=', (int) $userprop->id); if ($this->exists($where)) { $this->update(array('value' => $value), $where); } else { $this->insert(array( 'user_id' => (int) $user->id, 'userprop_id' => (int) $userprop->id, 'value' => $value )); } } } }<file_sep>/modules/shop/catalog/views/backend/catalog.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (isset($caption)) { echo '<h1>' . HTML::chars($caption) . '</h1>'; } if (isset($tabs)) { echo $tabs; } ?> <div class="panel"> <div class="content"> <table class="layout"><tr> <td class="layout"> <?php echo $products; ?> </td> <td class="layout sections_cell"> <?php echo $sections; ?> </td> </tr></table> </div> </div><file_sep>/modules/general/menus/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/menus', new Route_Backend( 'menus(/<action>(/<id>))' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'menus', 'action' => 'index', 'id' => NULL )); // ----- Add backend menu items Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => 2, 'caption' => 'Меню', 'route' => 'backend/menus', 'icon' => 'menus' )); }<file_sep>/modules/backend/public/js/windows.js /** * Global variable holding instances of all opened windows */ var windows = {}; /** * Global uid used to generate unqiue window names */ var window_uid = 0; /** * Stores the reference to the current window (for document inside the window) */ var current_window; /** * Initialize */ $(document).ready(function(){ // Open window when a link with '.open_window' class is clicked $('.open_window').each(function(i, link){ $(link).click(function(event){ // Try to determine window dimensions from class n var w, h; var dimensions = $(this).attr('class').match(/dim(\d+)x(\d+)/); if (dimensions) { w = parseInt(dimensions[1]); h = parseInt(dimensions[2]); } var wnd = new jWindow(this.href, w, h); wnd.show(); event.preventDefault(); }); }); if (parent != window) { // ----- This is a window (we are inside iframe) // Obtain the reference to the jWindow object, representing // this window in parent document current_window = parent.windows[window.frameElement.id]; // Init "close window" buttons $('.close_window').each(function(i, link){ $(link).click(function(event){ current_window.close(); event.preventDefault(); }); }); } else { // ----- We are inside parent window // Resize blocker together with window $(window).resize(function(event){ jWindow.stretchBlocker(); }); } }); /** * jWindow */ function jWindow(url, width, height) { window_uid++; this.id = 'wnd_' + window_uid; this.url = url; this.width = width || 400; this.height = height || 500; this.header_height = 34; this.o = $('<iframe class="window" id="' + this.id + '" frameborder="0" framespacing="0"></iframe>'); this.o.appendTo(document.body); // Store this window in global array windows[this.id] = this; } /** * Show and center the window */ jWindow.prototype.show = function() { // Show blocker jWindow.showBlocker(); // Show window this.o .width(this.width) .height(this.height + this.header_height) // [!] Add window header size .show() .attr('src', this.url + '?window=' + this.width + 'x' + this.height); this.center(); } /** * Center window in the viewport */ jWindow.prototype.center = function() { var top = (($(window).height() - this.height) >> 1) + $(document).scrollTop(); var left = (($(window).width() - this.width) >> 1) + $(document).scrollLeft(); this.o .css('top', top + 'px') .css('left', left + 'px') } /** * Hide the window */ jWindow.prototype.hide = function() { // Hide blocker jWindow.hideBlocker(); // Hide window this.o.hide(); } /** * Close (hide and destroy) the window */ jWindow.prototype.close = function() { // Hide window this.hide(); // Destroy DOM object this.o.remove(); // Unset window object windows[this.id] = null; } /** * Stretch blocker to the document size */ jWindow.stretchBlocker = function() { $('#blocker') .width($(document).width()) .height($(document).height()) } /** * Show blocker */ jWindow.showBlocker = function() { jWindow.stretchBlocker(); $('#blocker').show(); } /** * Hide blocker */ jWindow.hideBlocker = function() { $('#blocker').hide(); }<file_sep>/modules/shop/catalog/views/frontend/products/calendar_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $calendar_url = URL::to('frontend/catalog/products', array('calendar' => '{{calendar}}'), TRUE); ?> <li class="dropdown"> <?php if ($calendar) { $main_calendar_url = URL::to('frontend/catalog/products', array('calendar' => $calendar), TRUE); ?> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="<?php echo $main_calendar_url?>"><?php echo Model_Product::$_calendar_options[$calendar]?> <b class="caret"></b></a> <?php } else { ?> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="">дата<b class="caret"></b></a> <?php } ?> <ul class="dropdown-menu" role="menu" aria-labelledby="drop10"> <?php foreach ($calendars as $c_id => $c_name) { if ($c_name == $calendar) continue; $_calendar_url = str_replace('{{calendar}}', $c_id, $calendar_url); ?> <li><a role="menuitem" tabindex="-1" href="<?php echo $_calendar_url ?>"><?php echo $c_name ?></a></li> <?php }?> <li><div id ="datesearch_show"></div></li> </ul> </li> <file_sep>/modules/shop/catalog/classes/task/import/toysfest.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Import catalog from www.toysfest.ru */ class Task_Import_Toysfest extends Task_Import_Web { /** * Construct task */ public function __construct() { parent::__construct('http://www.toysfest.ru'); // Set defaults for task parameters $this->default_params(array( 'create_brands' => FALSE, 'create_series' => FALSE, 'create_products' => TRUE, 'update_brands_captions' => FALSE, 'update_brands_descriptions' => FALSE, 'update_brands_images' => FALSE, 'update_products_images' => FALSE, 'link_brands_by' => 'import_id', 'link_products_by' => 'id' )); } /** * Run the task */ public function run() { $this->set_progress(0); // import brands //$this->import_brands(); // import products //$this->import_products(); // update stats Model::fly('Model_Section')->mapper()->update_activity(); Model::fly('Model_Section')->mapper()->update_products_count(); $this->set_status_info('Импорт завершён'); } /** * Import brands */ public function import_brands() { $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; // must be brands section group id @TODO: pass as parameter to task // ----- brands -------------------------------------------------------- $brands = array(); // Retrieve list of all brands with links from catalog page ... $this->set_status_info('Parsing brands'); $page = $this->get('/catalog/'); preg_match_all( '!<li><a\s+href="(/catalog/\?filter\[manuf\]=([^"]+))">([^<]+)!', $page, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $import_id = strtolower(substr(trim($match[2]), 0, 31)); $caption = $this->decode_trim($match[3], 255); $url = trim($match[1]); $brands[$import_id] = array( 'import_id' => $import_id, 'caption' => $caption, 'url' => $url ); } // ... and, additionally, from brands page with image urls $this->set_status_info('Retrieving more brands and image urls for brands'); $page = $this->get('/?tab=4'); preg_match_all( '|<div><a\s+href="(/catalog/\?filter\[manuf\]=([^"]+))"><img\s+src="([^"]+)"\s+/></a></div>([^<]+)|', $page, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $import_id = strtolower(substr(trim($match[2]), 0, 31)); $caption = $this->decode_trim($match[4], 255); $image_url = trim($match[3]); $url = trim($match[1]); if (isset($brands[$import_id])) { // This brands was already imported in catalog page $brands[$import_id]['image_url'] = $image_url; } else { // Brand, that for some reason was not present at catalog page (i.e. Rubie's) $brands[$import_id] = array( 'import_id' => $import_id, 'caption' => $caption, 'url' => $url, 'image_url' => $image_url ); } } // Import brands $properties = Model::fly('Model_Property')->find_all_by_site_id($site_id, array('columns' => array('id'))); $propsections = array(); foreach ($properties as $property) { $propsections[$property['id']] = array( 'active' => 1, 'filter' => 0, 'sort' => 0 ); } $count = count($brands); $i = 0; $this->set_status_info('Importing ' . $count . ' brands'); $brand = new Model_Section(); foreach ($brands as $brand_info) { if ($this->param('link_brands_by') == 'caption') { $brand->find_by_caption_and_level_and_sectiongroup_id($brand_info['caption'], 1, $sectiongroup_id); } else { $brand->find_by_web_import_id_and_level_and_sectiongroup_id($brand_info['import_id'], 1, $sectiongroup_id); } $creating = ( ! isset($brand->id)); $brand->web_import_id = $brand_info['import_id']; $brand->sectiongroup_id = $sectiongroup_id; if ($creating || $this->param('update_brands_captions')) { $brand->caption = $brand_info['caption']; } // Select all additional properties $brand->propsections = $propsections; if ($creating) { if ($this->param('create_brands')) { $this->log('Creating new brand: "' . $brand->caption . '"'); $brand->save(FALSE, TRUE, FALSE); } else { $this->log('Skipped new brand: "' . $brand->caption . '"'); continue; } } else { $brand->save(FALSE, TRUE, FALSE); } if ( isset($brand_info['image_url']) && ($creating || $this->param('update_brands_images'))) { if ( ! $creating) { // Delete existing images $image->delete_all_by_owner_type_and_owner_id('section', $brand->id); } $image_file = $this->download_cached($brand_info['image_url']); if ($image_file) { try { $image = new Model_Image(); $image->source_file = $image_file; $image->owner_type = 'section'; $image->owner_id = $brand->id; $image->config = 'section'; $image->save(); } catch (Exception $e) {} } } $i++; $this->set_status_info('Importing brands : ' . $i . ' of ' . $count . ' done.'); } } /** * Import products * * @param array $brands */ public function import_products() { $site_id = 1; // @TODO: pass as parameter to task $sectiongroup_id = 1; //@FIXME: pass as parameter to task // // ----- Import products $properties = Model::fly('Model_Property')->find_all_by_site_id($site_id, array('columns' => array('id'))); $propsections = array(); foreach ($properties as $property) { $propsections[$property['id']] = array( 'active' => 1, 'filter' => 0, 'sort' => 0 ); } $brand = new Model_Section(); $seria = new Model_Section(); $product = new Model_Product(); // Detect the total number of pages $page = $this->get('/catalog/'); preg_match_all( '!<a\s*href="/catalog/(index.php)?\?PAGEN_1=(\d+)!i', $page, $matches); if ( ! empty($matches[2])) { $total_pages = (int) max($matches[2]); } else { $total_pages = 1; } // Iterate over paginated results for ($page_n = 1; $page_n <= $total_pages; $page_n++) { $this->set_status_info('Importing products: page ' . $page_n . ' of ' . $total_pages); $this->set_progress((int) (100 * ($page_n - 1) / $total_pages)); $page = $this->get('/catalog/?PAGEN_1=' . $page_n); preg_match_all( '!href="/product/(\d+)/!', $page, $import_ids_matches); foreach (array_unique($import_ids_matches[1]) as $import_id) { switch ($this->param('link_products_by')) { case 'web_import_id': $product->find_by_web_import_id($import_id, array('with_properties' => FALSE)); break; case 'web_import_id_and_supplier': $product->find_by_web_import_id_and_supplier($import_id, Model_Product::SUPPLIER_TOYSFEST, array('with_properties' => FALSE)); break; default: // link by id $product->find($import_id, array('with_properties' => FALSE)); } $creating = ! isset($product->id); $product->web_import_id = $import_id; $product->supplier = Model_Product::SUPPLIER_TOYSFEST; $page = $this->get('/product/' . $import_id . '/'); // ----- brand for product $brand->init(); if (preg_match('!<div\s+class="gttl">\s*<div>\s*<a\s+href="/catalog/\?filter\[manuf\]=([^"]+)"!is', $page, $matches)) { $brand_import_id = strtolower(substr(trim($matches[1]), 0, 31)); $brand->find_by_web_import_id_and_level_and_sectiongroup_id($brand_import_id, 1, $sectiongroup_id); } if ( ! isset($brand->id)) { $this->log('ERROR: Unable to determine brand for product "' . $import_id . '"'); continue; // to the next product } // ----- parse subbrands for product $sections = array($sectiongroup_id => array()); $series = array(); $section_id = 0; // from series if (preg_match('!Серия:<span[^>]*>(.*?)</span>!', $page, $matches)) { $strs = explode(',', $matches[1]); foreach ($strs as $str) { if (preg_match('!<a\s*href="/catalog/\?filter\[seria\]=([^"]*)">([^<]*)!', $str, $m)) { $seria_import_id = strtolower(substr(trim($m[1]), 0, 31)); $seria_caption = trim($m[2]); $series[] = array( 'import_id' => $seria_import_id, 'caption' => $seria_caption ); } } } // from licenses if (preg_match('!Лицензии:<span[^>]*>(.*?)</span>!', $page, $matches)) { $strs = explode(',', $matches[1]); foreach ($strs as $str) { if (preg_match('!<a\s*href="/catalog/\?filter\[license\]=([^"]*)">([^<]*)!', $str, $m)) { $license_import_id = strtolower(substr(trim($m[1]), 0, 31)); $license_caption = trim($m[2]); $series[] = array( 'import_id' => $license_import_id, 'caption' => $license_caption ); } } } foreach ($series as $seria_info) { // Create/update subbrands if ($this->param('link_brands_by') == 'caption') { $seria->find_by_caption_and_parent($seria_info['caption'], $brand); } else { $seria->find_by_web_import_id_and_parent($seria_info['import_id'], $brand); } $seria->web_import_id = $seria_info['import_id']; $seria->sectiongroup_id = $sectiongroup_id; $seria->parent_id = $brand->id; if ( ! isset($seria->id) || $this->param('update_brands_captions')) { $seria->caption = $seria_info['caption']; } // Select all additional properties $seria->propsections = $propsections; if ( ! isset($seria->id)) { if ($this->param('create_series')) { $this->log('Creating seria "' . $seria->caption . '" for brand "' . $brand->caption . '"'); $seria->save(FALSE, TRUE, FALSE); } else { $this->log('Skipped new seria "' . $seria->caption . '" for brand "' . $brand->caption . '"'); continue; // to the next seria } } else { $seria->save(FALSE, TRUE, FALSE); } if ($section_id == 0) { // If it is a first seria - select it as a main section $section_id = $seria->id; } else { // Additional brands $sections[$sectiongroup_id][$seria->id] = 1; } } if ($section_id == 0) { // no series for product - link product to brand $section_id = $brand->id; } $product->section_id = $section_id; $product->sections = $sections; // caption if (preg_match('!<h1>([^<]+)</h1>\s*<div\s+class="brend">!', $page, $matches)) { $product->caption = $this->decode_trim($matches[1], 255); } // description if (preg_match('!<div\s*class="tocartl\s*cb">.*?(?<=</div>)\s*(<p>.*?)(?<=</p>)!s', $page, $matches)) { $product->description = $matches[1]; } // price if (preg_match('!<div\s+class="gprc">\s*Цена:\s*<span>\s*(\d*)!i', $page, $matches)) { $product->price = new Money((int) trim($matches[1])); } // marking if (preg_match('!Артикул:<span[^>]*>\s*([^<]*)!i', $page, $matches)) { $marking = trim($matches[1]); if (strlen($marking) > 127) { $this->log('WARNING: Marking for product "' . $product->caption .'" : "' . $marking . '" is too long and will be truncated!'); } $product->marking = substr(trim($matches[1]), 0, 127); } // age if (preg_match('!Возраст:\s*<a[^>]*>([^<]*)!i', $page, $matches)) { $product->age = trim($matches[1]); } // volume if (preg_match('!Объем\s*товара\s*:<span[^>]*>\s*([^<]*)!i', $page, $matches)) { $product->volume = l10n::string_to_float(trim($matches[1])); } // weight if (preg_match('!Вес\s*товара\s*:<span[^>]*>\s*([^<]*)!i', $page, $matches)) { // convert kilogramms to gramms $product->weight = l10n::string_to_float(trim($matches[1])) * 1000; } if ( ! isset($product->id)) { if ($this->param('create_products')) { $this->log('Creating product "' . $product->caption . '" for brand "' . $brand->caption . '"'); $product->save(FALSE, TRUE, TRUE, FALSE, FALSE); } else { $this->log('Skipped new product "' . $product->caption . '" for brand "' . $brand->caption . '"'); continue; // to the next product } } else { $product->save(FALSE, TRUE, TRUE, FALSE, FALSE); } // images for new products if ($creating || $this->param('update_products_images')) { preg_match_all( '!<a\s+href="([^"]*)"\s+rel="lightbox!', $page, $m); foreach (array_unique($m[1]) as $image_url) { $image_file = $this->download_cached($image_url); if ($image_file) { try { $image = new Model_Image(); $image->source_file = $image_file; $image->owner_type = 'product'; $image->owner_id = $product->id; $image->config = 'product'; $image->save(); unset($image); } catch (Exception $e) {} } } } } } // for ($page_n = 1; ...) } } <file_sep>/modules/shop/acl/init.php <?php defined('SYSPATH') or die('No direct script access.'); if (APP === 'FRONTEND') { // ----- registration Route::add('frontend/acl/users/register', new Route_Frontend( 'register' , array( ) )) ->defaults(array( 'controller' => 'users', 'action' => 'create' )); // ----- users Route::add('frontend/acl/users/control', new Route_Frontend( 'acl/users(/<action>)(/user-<user_id>)(/image-<image_id>)' . '(/ap-<apage>)(/tp-<tpage>)(/rp-<rpage>)(/mp-<mpage>)' . '(/opts-<options_count>)' . '(/~<history>)' , array( 'action' => '\w++', 'user_id' => '\d++', 'apage' => '\d++', 'tpage' => '\d++', 'rpage' => '\d++', 'mpage' => '\d++', 'history' => '.++', 'image_id' => '\d++', 'options_count' => '\d++', ) )) ->defaults(array( 'controller' => 'users', 'action' => 'index', 'user_id' => NULL, 'image_id' => NULL, 'options_count' => NULL, 'apage' => '0', 'tpage' => '0', 'rpage' => '0', 'mpage' => '0', )); // ----- user_images Route::add('frontend/acl/user/images', new Route_Frontend( 'acl/user/images' , array( ) )) ->defaults(array( 'controller' => 'users', 'action' => 'ajax_user_images' )); // ----- lecturers Route::add('frontend/acl/lecturers', new Route_Frontend( '(/<town>)acl/lecturers(/<action>)(/lecturer-<lecturer_id>)(/image-<image_id>)' . '(/~<history>)', array( 'action' => '\w++', 'lecturer_id' => '\d++', 'image_id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'lecturers', 'action' => 'index', 'image_id' => NULL, 'lecturer_id' => '0', )); // ----- organizers Route::add('frontend/acl/organizers', new Route_Frontend( 'acl/organizers(/<action>)(/organizer-<organizer_id>)(/image-<image_id>)' . '(/~<history>)', array( 'action' => '\w++', 'organizer_id' => '\d++', 'image_id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'organizers', 'action' => 'index', 'image_id' => NULL, 'organizer_id' => '0', )); // ----- lecturer_images Route::add('frontend/acl/lecturer/images', new Route_Frontend( 'acl/lecturer/images' , array( ) )) ->defaults(array( 'controller' => 'lecturers', 'action' => 'ajax_lecturer_images' )); // ----- acl Route::add('frontend/acl', new Route_Frontend( 'acl(/<action>)(/user-<user_id>)(/group-<group_id>)(/lecturer-<lecturer_id>)(/stat-<stat>)(/code-<hash>)', array( 'action' => '\w++', 'user_id' => '\d++', 'group_id' => '\d++', 'lecturer_id' => '\d++', 'stat' => '\w++', 'hash' => '.++' ))) ->defaults(array( 'controller' => 'acl', 'action' => 'index', 'user_id' => NULL, 'group_id' => NULL, 'lecturer_id' => '0', 'stat' => NULL, )); } if (APP === 'BACKEND') { // ----- users Route::add('backend/acl/users', new Route_Backend( 'acl/users(/<action>(/<id>)(/ids-<ids>)(/v-<v_action>))' . '(/group-<group_id>)' . '(/opts-<options_count>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'v_action' => '\w++', 'group_id' => '\d++', 'options_count' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'users', 'action' => 'index', 'id' => NULL, 'ids' => '', 'v_action' => NULL, 'options_count' => NULL, 'group_id' => NULL, )); // ----- groups Route::add('backend/acl/groups', new Route_Backend( 'acl/groups(/<action>(/<id>))' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'groups', 'action' => 'index', 'id' => NULL )); // ----- privileges Route::add('backend/acl/privileges', new Route_Backend( 'acl/privileges(/<action>(/<id>))' . '(/opts-<options_count>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'options_count' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'privileges', 'action' => 'index', 'id' => NULL, 'options_count' => NULL )); // ----- lecturers Route::add('backend/acl/lecturers', new Route_Backend( 'acl/lecturers(/<action>(/<id>)(/ids-<ids>))(/p-<page>)' . '(/opts-<options_count>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'page' => '(\d++|all)', 'options_count' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'lecturers', 'action' => 'index', 'id' => NULL, 'ids' => '', 'page' => '0', 'options_count' => NULL )); // ----- lecturers Route::add('backend/acl/organizers', new Route_Backend( 'acl/organizers(/<action>(/<id>)(/ids-<ids>))(/p-<page>)' . '(/opts-<options_count>)' . '(/oorder-<acl_oorder>)(/odesc-<acl_odesc>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'page' => '(\d++|all)', 'options_count' => '\d++', 'acl_oorder' => '\w++', 'acl_odesc' => '[01]', 'history' => '.++' ))) ->defaults(array( 'controller' => 'organizers', 'action' => 'index', 'id' => NULL, 'ids' => '', 'page' => '0', 'acl_oorder' => 'name', 'acl_odesc' => '0', 'options_count' => NULL )); // ----- userprops Route::add('backend/acl/userprops', new Route_Backend( 'acl/userprops(/<action>(/<id>))' . '(/opts-<options_count>)' . '(/uprorder-<acl_uprorder>)(/uprdesc-<acl_uprdesc>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'options_count' => '\d++', 'acl_uprorder' => '\w++', 'acl_uprdesc' => '\w++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'userprops', 'action' => 'index', 'id' => NULL, 'acl_uprorder' => 'position', 'acl_uprdesc' => '0', 'options_count' => NULL )); // ----- links Route::add('backend/acl/links', new Route_Backend( 'acl/links(/<action>(/<id>))' . '(/opts-<options_count>)' . '(/uliorder-<acl_uliorder>)(/ulidesc-<acl_ulidesc>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'options_count' => '\d++', 'acl_uliorder' => '\w++', 'acl_ulidesc' => '\w++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'links', 'action' => 'index', 'id' => NULL, 'acl_uliorder' => 'position', 'acl_ulidesc' => '0', 'options_count' => NULL )); // ----- acl Route::add('backend/acl', new Route_Backend( 'acl(/<action>(/<id>)(/v-<v_action>))' . '(/user-<user_id>)(/group-<group_id>)(/lecturer-<lecturer_id>)(/p-<page>)(/tab-<tab>)' . '(/uorder-<acl_uorder>)(/udesc-<acl_udesc>)(/gorder-<acl_gorder>)(/gdesc-<acl_gdesc>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'v_action' => '\w++', 'user_id' => '\d++', 'group_id' => '\d++', 'lecturer_id' => '\d++', 'page' => '(\d++|all)', 'tab' => '\w++', 'acl_uorder' => '\w++', 'acl_udesc' => '\w++', 'acl_gorder' => '\w++', 'acl_gdesc' => '\w++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'acl', 'action' => 'index', 'id' => NULL, 'v_action' => NULL, 'user_id' => '0', 'group_id' => '0', 'lecturer_id' => '0', 'page' => '0', 'tab' => 'users', 'acl_uorder' => 'id', 'acl_udesc' => '0', 'acl_gorder' => 'id', 'acl_gdesc' => '0' )); // ----- Add backend menu items $parent_id = Model_Backend_Menu::add_item(array( 'id' => 4, 'menu' => 'main', 'caption' => 'Пользователи', 'route' => 'backend/acl', 'select_conds' => array( array('route' => 'backend/acl'), array('route' => 'backend/acl/users'), array('route' => 'backend/acl/groups'), array('route' => 'backend/acl/privileges'), array('route' => 'backend/acl/lecturers'), array('route' => 'backend/acl/organizers'), array('route' => 'backend/acl/userprops'), array('route' => 'backend/acl/links') ), 'icon' => 'acl' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Пользователи', 'route' => 'backend/acl' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Привилегии', 'route' => 'backend/acl/privileges' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Лекторы', 'route' => 'backend/acl/lecturers' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Организации', 'route' => 'backend/acl/organizers' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Доп.характеристики', 'route' => 'backend/acl/userprops' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Внешние ссылки', 'route' => 'backend/acl/links' )); } /****************************************************************************** * Module installation ******************************************************************************/ if (Kohana::$environment !== Kohana::PRODUCTION) { // Create superusers group and superuser $group = new Model_Group(); if ( ! $group->count()) { $group->properties(array('system' => 1)); $group->id = Model_Group::ADMIN_GROUP_ID; $group->name = 'Суперпользователи'; $group->save(TRUE); $organizer = new Model_Organizer(); $organizer->id = Model_Organizer::DEFAULT_ORGANIZER_ID; $organizer->name = Model_Organizer::DEFAULT_ORGANIZER_NAME; $organizer->type = Model_Organizer::TYPE_TVGROUP; $organizer->town_id = Model_Town::DEFAULT_TOWN_ID; $organizer->address = "Москва, Нахимовский пр. 47"; $organizer->save(TRUE); $user = new Model_User(array('system' => 1, 'group_id' => $group->id)); $user->email = '<EMAIL>'; $user->password = '<PASSWORD>'; $user->first_name = 'Администратор'; $user->organizer_id = Model_Organizer::DEFAULT_ORGANIZER_ID; $user->organizer_name = Model_Organizer::DEFAULT_ORGANIZER_NAME; $user->town_id = Model_Town::DEFAULT_TOWN_ID; $user->save(); $group->properties(array('system' => 1)); $group->id = Model_Group::EDITOR_GROUP_ID; $group->name = 'Редакторы'; $group->save(TRUE); $group->properties(array('system' => 1)); $group->id = Model_Group::USER_GROUP_ID; $group->name = 'Пользователи'; $group->save(TRUE); // Create system privileges $privilege = new Model_Privilege(); if ( ! $privilege->count()) { $privilege->properties(array( 'site_id' => Model_Site::current()->id, 'system' => 1)); $privilege->name = 'backend_access'; $privilege->caption = 'Доступ в панель управления'; $privilege->save(); $privilege_group = new Model_PrivilegeGroup(); $privilege_group->privilege_id = $privilege->id; $privilege_group->group_id = $group->id; $privilege_group->save(); } } } // ----- Add privilege types Model_Privilege::add_privilege_type('backend_access', array( 'name' => 'Панель управления', 'readable' => FALSE, 'system' => TRUE )); Model_Privilege::add_privilege_type('users_control', array( 'name' => 'Просмотр профайла', 'readable' => FALSE, 'controller' => 'users', 'action' => 'control', 'frontend_route' => 'frontend/acl/users/control', 'frontend_route_params' => array('action' => 'control'), )); Model_Privilege::add_privilege_type('user_update', array( 'name' => 'Редактировать Профайл', 'readable' => FALSE, 'controller' => 'users', 'action' => 'update' )); /* // ----- Add privilege types Model_Privilege::add_privilege_type('product_create', array( 'name' => 'Создание мероприятия', 'readable' => FALSE, 'controller' => 'products', 'action' => 'create' )); Model_Privilege::add_privilege_type('product_update', array( 'name' => 'Редактирование мероприятия', 'readable' => FALSE, 'controller' => 'products', 'action' => 'update' )); Model_Privilege::add_privilege_type('product_delete', array( 'name' => 'Удаление мероприятия', 'readable' => FALSE, 'controller' => 'products', 'action' => 'delete' )); */ <file_sep>/application/classes/controller/errors.php <?php defined('SYSPATH') OR die('No direct access allowed.'); /** * Error handling controller * * @package Eresus * @author <NAME> (<EMAIL>) */ class Controller_Errors extends Controller { /** * Renders an error * * @param string $uri * @param integer $status * @param string $message */ public function action_error($uri, $status, $message = NULL) { if ($status !== NULL) { $status = (int) $status; $this->request->status = $status; } else { $status = $this->request->status; } if ($message === NULL) { $message = Request::$messages[$status]; } if ( ! Request::$is_ajax) { if ($status == 404) { $layout_script = 'layouts/errors/404'; } else { $layout_script = 'layouts/errors/500'; } $layout = $this->prepare_layout($layout_script); $layout->message = __($message); $this->request->response = $layout; } } }<file_sep>/modules/shop/acl/classes/controller/backend/users.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Users extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_User'; $this->_form = 'Form_Backend_User'; $this->_view = 'backend/form_adv'; return array( 'create' => array( 'view_caption' => 'Создание пользователя' ), 'update' => array( 'view_caption' => 'Редактирование пользователя' ), 'delete' => array( 'view_caption' => 'Удаление пользователя', 'message' => 'Удалить пользователя ":name" (:email)?' ), 'multi_delete' => array( 'view_caption' => 'Удаление пользователей', 'message' => 'Удалить выбранных пользователей?' ) ); } /** * Create layout (proxy to acl controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Perpare user model for creation * * @param string|Model $model * @param array $params * @return Model */ protected function _model_create($model, array $params = NULL) { $user = parent::_model('create', $model, $params); $user->group_id = $this->request->param('group_id'); return $user; } /** * Select several towns */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор редакторов на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_user_select('backend/users/select'); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_user_select('backend/users/select')); } } /** * Renders list of users * * @return string Html */ public function widget_users() { $user = new Model_User(); $order_by = $this->request->param('acl_uorder', 'id'); $desc = (bool) $this->request->param('acl_udesc', '0'); $per_page = 20; $group_id = (int) $this->request->param('group_id',Model_Group::EDITOR_GROUP_ID); if ($group_id > 0) { // Show users only from specified group $group = new Model_Group(); $group->find($group_id); if ($group->id === NULL) { // Group was not found - show a form with error message return $this->_widget_error('Группа с идентификатором ' . $group_id . ' не найдена!'); } $count = $user->count_by_group_id($group->id); $pagination = new Paginator($count, $per_page); $users = $user->find_all_by_group_id($group->id,true, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc ), TRUE); } else { $group = NULL; // Select all users $count = $user->count(); $pagination = new Paginator($count, $per_page); $users = $user->find_all(array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); } $view = new View('backend/users'); $view->order_by = $order_by; $view->desc = $desc; $view->group = $group; $view->users = $users; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Handles the selection of access organizers for event */ public function action_users_select() { if ( ! empty($_POST['ids']) && is_array($_POST['ids'])) { $user_ids = ''; foreach ($_POST['ids'] as $user_id) { $user_ids .= (int) $user_id . '_'; } $user_ids = trim($user_ids, '_'); $this->request->redirect(URL::uri_back(NULL, 1, array('access_user_ids' => $user_ids))); } else { // No towns were selected $this->request->redirect(URL::uri_back()); } } /** * Renders list of users for user-select dialog * * @return string Html */ public function widget_user_select($view_script = 'backend/user_select') { $user = new Model_User(); $order_by = $this->request->param('acl_uorder', 'id'); $desc = (bool) $this->request->param('acl_udesc', '0'); $per_page = 20; $group_id = (int) $this->request->param('group_id',Model_Group::EDITOR_GROUP_ID); if ($group_id > 0) { // Show users only from specified group $group = new Model_Group(); $group->find($group_id); if ($group->id === NULL) { // Group was not found - show a form with error message return $this->_widget_error('Группа с идентификатором ' . $group_id . ' не найдена!'); } $count = $user->count_by_group_id($group->id); $pagination = new Paginator($count, $per_page); $users = $user->find_all_by_group_id_and_active($group->id,true, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc ), TRUE); } else { $group = NULL; // Select all users $count = $user->count(); $pagination = new Paginator($count, $per_page); $users = $user->find_all_by_active(true,array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc )); } $view = new View($view_script); $view->order_by = $order_by; $view->desc = $desc; $view->group = $group; $view->users = $users; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Renders user account settings * * @param boolean $select * @return string */ public function widget_user_card($user,array $fields = array()) { if (empty($fields)) { $fields = array('image','name'); } $view = 'backend/user_card'; $widget = new Widget($view); $widget->id = 'user_card' . $user->id; $widget->context_uri = FALSE; // use the url of clicked link as a context url $widget->user = $user; $widget->fields = $fields; return $widget; } } <file_sep>/modules/frontend/views/frontend/menu/menu-main.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <ul class="main-menu"> <?php foreach ($items as $item) { // Build menu item class $class = ''; if ( ! empty($item['selected'])) { $class .= ' current'; } echo '<li class= '.$class.' ><a href="' . Model_Backend_Menu::url($item) .'"' . (isset($item['title']) ? ' title="' . HTML::chars($item['title']) . '"' : '') . '>' . $item['caption'] . '</a></li>'; } ?> </ul><file_sep>/modules/general/filemanager/views/backend/files.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Set up urls $mkdir_url = URL::to('backend/filemanager', array('action' => 'mkdir', 'fm_path' => URL::encode($dir->relative_path), 'fm_tinymce' => $in_tinymce, 'fm_root' => $root), TRUE ); $dir_url = URL::self(array('fm_path' => '${path}')); $edit_url = URL::to('backend/filemanager', array('action' => 'rename', 'fm_path' => '${path}', 'fm_tinymce' => $in_tinymce, 'fm_root' => $root), TRUE); $delete_url = URL::to('backend/filemanager', array('action' => 'delete', 'fm_path' => '${path}', 'fm_tinymce' => $in_tinymce, 'fm_root' => $root), TRUE); $editfile_url = URL::to('backend/filemanager', array('action' => 'edit', 'fm_path' => '${path}', 'fm_tinymce' => $in_tinymce, 'fm_root' => $root), TRUE); // ----- Split current path into elements $path_elements = array(); // First - root path (relative to docroot) to make it more clear where you are now $parts = explode('/', File::relative_path($dir->root_path, DOCROOT)); foreach ($parts as $i => $path_element) { if ($i < count($parts) - 1) { $path_elements[] = '<strong>' . $path_element . '</strong>'; } else { // Last path element is navigatable $path_elements[] = '<a href="' . URL::self(array('fm_path' => '')) . '">' . $path_element . '</a>'; } } // Relative path - make it navigatable $tmp_path = ''; $parent_path = ''; foreach (explode('/', $dir->relative_path) as $path_element) { $parent_path = $tmp_path; if ($tmp_path != '') { $tmp_path .= '/' . $path_element; } else { $tmp_path = $path_element; } $path_elements[] = '<a href="' . str_replace('${path}', URL::encode($tmp_path), $dir_url) .'">' . $path_element . '</a>'; } //array_unshift($path_elements, '<a href="' . URL::self(array('fm_path' => '')) . '">&raquo;</a>'); ?> <div class="buttons"> <a href="<?php echo $mkdir_url; ?>" class="button button_add">Создать директорию</a> </div> <?php // ----- File upload form echo $file_upload; ?> <!-- File list display styles --> <div class="list_styles_select"> Отображение: <?php foreach (array( 'list' => 'список', 'thumbs' => 'миниатюры' ) as $style => $label) { $selected = ($style == $list_style) ? ' selected' : ''; echo '<a href="' . URL::self(array('fm_style' => $style)) . '" class="as_' . $style . $selected . '">' . $label . '</a>'; } ?> </div> <!-- Current address --> <div class="current_path"> Адрес: <?php echo implode('&nbsp;/&nbsp;', $path_elements); ?> <?php if ($parent_path == '') { $parent_url = URL::self(array('fm_path' => '')); } else { $parent_url = str_replace('${path}', URL::encode($parent_path), $dir_url); } //echo View_Helper_Admin::image_control($parent_url, 'Вверх', 'images/up_folder.gif', 'Вверх', 'filemanager'); ?> </div> <!-- Files list --> <?php require('list_style/' . $list_style . '.php'); ?><file_sep>/modules/shop/area/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frotnend ******************************************************************************/ if (APP === 'FRONTEND') { // ----- sections Route::add('frontend/area/towns', new Route_Frontend( 'area/towns(/<action>(/<are_town_alias>))' , array( 'action' => '\w++', 'are_town_alias' => '[^/]++', ) )) ->defaults(array( 'controller' => 'towns', 'action' => 'index', 'are_town_alias' => '', )); Route::add('frontend/area/places', new Route_Frontend( 'area/places(/<action>(/<are_place_alias>))' , array( 'action' => '\w++', 'are_place_alias' => '[^/]++', ) )) ->defaults(array( 'controller' => 'places', 'action' => 'index', 'are_place_alias' => '', )); Route::add('frontend/area/place/select', new Route_Frontend( 'area/place/select', array( ))) ->defaults(array( 'controller' => 'places', 'action' => 'select' )); } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { if (Cookie::get(Model_Town::TOWN_TOKEN,FALSE)) Cookie::delete(Model_Town::TOWN_TOKEN); Route::add('backend/area/places', new Route_Backend( 'area/places(/<action>(/<id>))(/ids-<ids>)' . '(/town-<are_town_alias>)(/p-<page>)(/tp-<tpage>)' . '(/torder-<are_torder>)(/tdesc-<are_tdesc>)' . '(/porder-<are_porder>)(/pdesc-<are_pdesc>)' . '(/opts-<options_count>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'page' => '(\d++|all)', 'tpage' => '(\d++|all)', 'are_torder' => '\w++', 'are_tdesc' => '[01]', 'are_porder' => '\w++', 'are_pdesc' => '[01]', 'are_town_alias' => '[^/]++', 'options_count' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'places', 'action' => 'index', 'id' => NULL, 'ids' => '', 'page' => '0', 'tpage' => '0', 'are_torder' => 'name', 'are_tdesc' => '0', 'are_porder' => 'name', 'are_pdesc' => '0', 'are_town_alias' => '', 'options_count' => NULL, )); // ----- sections Route::add('backend/area/towns', new Route_Backend( 'area/towns(/<action>(/<id>)(/ids-<ids>))(/tp-<tpage>)' . '(/town-<are_town_alias>)' . '(/torder-<are_torder>)(/tdesc-<are_tdesc>)' . '(/opts-<options_count>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'tpage' => '(\d++|all)', 'are_town_alias' => '[^/]++', 'are_torder' => '\w++', 'are_tdesc' => '[01]', 'options_count' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'towns', 'action' => 'index', 'id' => NULL, 'ids' => '', 'tpage' => '0', 'are_torder' => 'lft', 'are_tdesc' => '0', 'are_town_alias' => '', 'options_count' => NULL, )); Route::add('backend/area', new Route_Backend( 'area(/<action>(/<id>))(/ids-<ids>)' . '(/town-<are_town_alias>)(/place-<place_id>)(/p-<page>)' . '(/torder-<are_torder>)(/tdesc-<are_tdesc>)' . '(/porder-<are_porder>)(/pdesc-<are_pdesc>)' . '(/opts-<options_count>)' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'are_town_alias' => '[^/]++', 'place_id' => '\d++', 'are_torder' => '\w++', 'are_tdesc' => '[01]', 'are_porder' => '\w++', 'are_pdesc' => '[01]', 'options_count' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'area', 'action' => 'index', 'id' => NULL, 'ids' => '', 'are_town_alias' => '', 'place_id' => '0', 'are_torder' => 'name', 'are_tdesc' => '0', 'are_porder' => 'name', 'are_pdesc' => '0', 'options_count' => NULL, )); // ----- Add backend menu items $parent_id = Model_Backend_Menu::add_item(array( 'menu' => 'main', 'site_required' => TRUE, 'caption' => 'Места', 'route' => 'backend/area/places', 'controller' => 'area', 'select_conds' => array( array('route' => 'backend/area'), array('route' => 'backend/area/towns'), array('route' => 'backend/area/places') ), 'icon' => 'sites' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Площадки', 'route' => 'backend/area/places', )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Города', 'route' => 'backend/area/towns', )); } /****************************************************************************** * Module installation ******************************************************************************/ if (Kohana::$environment !== Kohana::PRODUCTION) { // Create superusers group and superuser $town = new Model_Town(); if ( ! $town->count()) { $town->id = Model_Town::DEFAULT_TOWN_ID; $town->name = 'Москва'; $town->phonecode = '495'; $town->timezone = Model_Town::$_timezone_options['Europe/Moscow']; $town->save(TRUE); } } // ----- Add node types Model_Node::add_node_type('map', array( 'name' => 'Карта', 'frontend_route' => 'frontend/area/towns', 'backend_route' => 'backend/area' ));<file_sep>/modules/system/forms/classes/form/validator/file.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validate uploaded file * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_File extends Form_Validator { const NO_FILE = 'NO_FILE'; const TOO_BIG = 'TOO_BIG'; const ERROR = 'ERROR'; protected $_messages = array( self::NO_FILE => 'Не указан файл', self::TOO_BIG => 'Размер файла на может превышать :upload_max_filesize', self::ERROR => 'Произошла ошибка при загрузке файла' ); /** * It's possible not to specify a file * @var boolean */ protected $_allow_empty; /** * Creates uploaded file validator * * @param string $name Name of file in $_FILES array * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty strings */ public function __construct(array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE) { parent::__construct($messages, $breaks_chain); $this->_allow_empty = $allow_empty; } /** * Validate * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $file = $this->_value; if (empty($file)) { if ( ! $this->_allow_empty) { $this->_error(self::NO_FILE); return FALSE; } else { return TRUE; } } if ($file['error'] !== UPLOAD_ERR_OK) { switch ($file['error']) { case UPLOAD_ERR_NO_FILE: if ( ! $this->_allow_empty) { $this->_error(self::NO_FILE); return FALSE; } else { return TRUE; } case UPLOAD_ERR_INI_SIZE: $this->_error(self::TOO_BIG); return FALSE; default: $this->_error(self::ERROR); return FALSE; } } if ( ! isset($file['tmp_name']) || ! is_uploaded_file($file['tmp_name'])) { $this->_error(self::ERROR); return FALSE; } return TRUE; } /** * Replaces placeholders in error message * * @param string $error_text * @return string */ protected function _replace_placeholders($error_text) { $error_text = parent::_replace_placeholders($error_text); $upload_max_filesize = ini_get('upload_max_filesize'); $upload_max_filesize = str_replace(array('G', 'M', 'K'), array(' Gb', ' Mb', ' Kb'), $upload_max_filesize); $error_text = str_replace(':upload_max_filesize', $upload_max_filesize, $error_text); return $error_text; } }<file_sep>/modules/general/blocks/classes/controller/frontend/blocks.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Blocks extends Controller_Frontend { /** * Render all blocks with given name * * @param string $name * @return string */ public function widget_block($name) { // Find all visible blocks with given name for current node $node_id = Model_Node::current()->id; $block = new Model_Block(); $blocks = $block->find_all_visible_by_name_and_node_id($name, $node_id, array('order_by' => 'position', 'desc' => FALSE)); if ( ! count($blocks)) { return ''; } $html = ''; foreach ($blocks as $block) { $html .= $block->text; } return $html; } } <file_sep>/modules/shop/area/classes/model/town.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Town extends Model { const DEFAULT_TOWN_ID = 1; const TOWN_TOKEN = 'town_token'; // A token used to town via cookie const TOWN_LIFETIME = 604800; // Town token is valid for 7 days const ALL_TOWN = 'all'; static $towns = NULL; public static $_timezone_options = array( 'Pacific/Midway' => "(GMT-11:00) Midway Island", 'US/Samoa' => "(GMT-11:00) Samoa", 'US/Hawaii' => "(GMT-10:00) Hawaii", 'US/Alaska' => "(GMT-09:00) Alaska", 'US/Pacific' => "(GMT-08:00) Pacific Time (US &amp; Canada)", 'America/Tijuana' => "(GMT-08:00) Tijuana", 'US/Arizona' => "(GMT-07:00) Arizona", 'US/Mountain' => "(GMT-07:00) Mountain Time (US &amp; Canada)", 'America/Chihuahua' => "(GMT-07:00) Chihuahua", 'America/Mazatlan' => "(GMT-07:00) Mazatlan", 'America/Mexico_City' => "(GMT-06:00) Mexico City", 'America/Monterrey' => "(GMT-06:00) Monterrey", 'Canada/Saskatchewan' => "(GMT-06:00) Saskatchewan", 'US/Central' => "(GMT-06:00) Central Time (US &amp; Canada)", 'US/Eastern' => "(GMT-05:00) Eastern Time (US &amp; Canada)", 'US/East-Indiana' => "(GMT-05:00) Indiana (East)", 'America/Bogota' => "(GMT-05:00) Bogota", 'America/Lima' => "(GMT-05:00) Lima", 'America/Caracas' => "(GMT-04:30) Caracas", 'Canada/Atlantic' => "(GMT-04:00) Atlantic Time (Canada)", 'America/La_Paz' => "(GMT-04:00) La Paz", 'America/Santiago' => "(GMT-04:00) Santiago", 'Canada/Newfoundland' => "(GMT-03:30) Newfoundland", 'America/Buenos_Aires' => "(GMT-03:00) Buenos Aires", 'Greenland' => "(GMT-03:00) Greenland", 'Atlantic/Stanley' => "(GMT-02:00) Stanley", 'Atlantic/Azores' => "(GMT-01:00) Azores", 'Atlantic/Cape_Verde' => "(GMT-01:00) Cape Verde Is.", 'Africa/Casablanca' => "(GMT) Casablanca", 'Europe/Dublin' => "(GMT) Dublin", 'Europe/Lisbon' => "(GMT) Lisbon", 'Europe/London' => "(GMT) London", 'Africa/Monrovia' => "(GMT) Monrovia", 'Europe/Amsterdam' => "(GMT+01:00) Amsterdam", 'Europe/Belgrade' => "(GMT+01:00) Belgrade", 'Europe/Berlin' => "(GMT+01:00) Berlin", 'Europe/Bratislava' => "(GMT+01:00) Bratislava", 'Europe/Brussels' => "(GMT+01:00) Brussels", 'Europe/Budapest' => "(GMT+01:00) Budapest", 'Europe/Copenhagen' => "(GMT+01:00) Copenhagen", 'Europe/Ljubljana' => "(GMT+01:00) Ljubljana", 'Europe/Madrid' => "(GMT+01:00) Madrid", 'Europe/Paris' => "(GMT+01:00) Paris", 'Europe/Prague' => "(GMT+01:00) Prague", 'Europe/Rome' => "(GMT+01:00) Rome", 'Europe/Sarajevo' => "(GMT+01:00) Sarajevo", 'Europe/Skopje' => "(GMT+01:00) Skopje", 'Europe/Stockholm' => "(GMT+01:00) Stockholm", 'Europe/Vienna' => "(GMT+01:00) Vienna", 'Europe/Warsaw' => "(GMT+01:00) Warsaw", 'Europe/Zagreb' => "(GMT+01:00) Zagreb", 'Europe/Athens' => "(GMT+02:00) Athens", 'Europe/Bucharest' => "(GMT+02:00) Bucharest", 'Africa/Cairo' => "(GMT+02:00) Cairo", 'Africa/Harare' => "(GMT+02:00) Harare", 'Europe/Helsinki' => "(GMT+02:00) Helsinki", 'Europe/Istanbul' => "(GMT+02:00) Istanbul", 'Asia/Jerusalem' => "(GMT+02:00) Jerusalem", 'Europe/Kiev' => "(GMT+02:00) Kyiv", 'Europe/Minsk' => "(GMT+02:00) Minsk", 'Europe/Riga' => "(GMT+02:00) Riga", 'Europe/Sofia' => "(GMT+02:00) Sofia", 'Europe/Tallinn' => "(GMT+02:00) Tallinn", 'Europe/Vilnius' => "(GMT+02:00) Vilnius", 'Asia/Baghdad' => "(GMT+03:00) Baghdad", 'Asia/Kuwait' => "(GMT+03:00) Kuwait", 'Africa/Nairobi' => "(GMT+03:00) Nairobi", 'Asia/Riyadh' => "(GMT+03:00) Riyadh", 'Asia/Tehran' => "(GMT+03:30) Tehran", 'Europe/Moscow' => "(GMT+04:00) Moscow", 'Asia/Baku' => "(GMT+04:00) Baku", 'Europe/Volgograd' => "(GMT+04:00) Volgograd", 'Asia/Muscat' => "(GMT+04:00) Muscat", 'Asia/Tbilisi' => "(GMT+04:00) Tbilisi", 'Asia/Yerevan' => "(GMT+04:00) Yerevan", 'Asia/Kabul' => "(GMT+04:30) Kabul", 'Asia/Karachi' => "(GMT+05:00) Karachi", 'Asia/Tashkent' => "(GMT+05:00) Tashkent", 'Asia/Kolkata' => "(GMT+05:30) Kolkata", 'Asia/Kathmandu' => "(GMT+05:45) Kathmandu", 'Asia/Yekaterinburg' => "(GMT+06:00) Ekaterinburg", 'Asia/Almaty' => "(GMT+06:00) Almaty", 'Asia/Dhaka' => "(GMT+06:00) Dhaka", 'Asia/Novosibirsk' => "(GMT+07:00) Novosibirsk", 'Asia/Bangkok' => "(GMT+07:00) Bangkok", 'Asia/Jakarta' => "(GMT+07:00) Jakarta", 'Asia/Krasnoyarsk' => "(GMT+08:00) Krasnoyarsk", 'Asia/Chongqing' => "(GMT+08:00) Chongqing", 'Asia/Hong_Kong' => "(GMT+08:00) Hong Kong", 'Asia/Kuala_Lumpur' => "(GMT+08:00) Kuala Lumpur", 'Australia/Perth' => "(GMT+08:00) Perth", 'Asia/Singapore' => "(GMT+08:00) Singapore", 'Asia/Taipei' => "(GMT+08:00) Taipei", 'Asia/Ulaanbaatar' => "(GMT+08:00) Ulaan Bataar", 'Asia/Urumqi' => "(GMT+08:00) Urumqi", 'Asia/Irkutsk' => "(GMT+09:00) Irkutsk", 'Asia/Seoul' => "(GMT+09:00) Seoul", 'Asia/Tokyo' => "(GMT+09:00) Tokyo", 'Australia/Adelaide' => "(GMT+09:30) Adelaide", 'Australia/Darwin' => "(GMT+09:30) Darwin", 'Asia/Yakutsk' => "(GMT+10:00) Yakutsk", 'Australia/Brisbane' => "(GMT+10:00) Brisbane", 'Australia/Canberra' => "(GMT+10:00) Canberra", 'Pacific/Guam' => "(GMT+10:00) Guam", 'Australia/Hobart' => "(GMT+10:00) Hobart", 'Australia/Melbourne' => "(GMT+10:00) Melbourne", 'Pacific/Port_Moresby' => "(GMT+10:00) Port Moresby", 'Australia/Sydney' => "(GMT+10:00) Sydney", 'Asia/Vladivostok' => "(GMT+11:00) Vladivostok", 'Asia/Magadan' => "(GMT+12:00) Magadan", 'Pacific/Auckland' => "(GMT+12:00) Auckland", 'Pacific/Fiji' => "(GMT+12:00) Fiji", ); public static function towns() { if (self::$towns === NULL) { self::$towns =array(); $results = Model::fly('Model_Town')->find_all(array( 'order_by'=> 'name', 'columns'=>array('id','name'), 'as_array' => TRUE)); foreach ($results as $result) { self::$towns[$result['id']] = $result['name']; } } return self::$towns; } /** * Get currently selected town for the specified request using the value of * corresponding parameter in the uri * * @param Request $request (if NULL, current request will be used) * @return Model_Town */ public static function current(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } // cache? $town_model = $request->get_value('town_model'); if ($town_model !== NULL) { return $town_model; } $alias = $request->param('are_town_alias',NULL); if (!$alias) { $alias = Cookie::get(Model_Town::TOWN_TOKEN); if ($alias == null) { $alias = Model_Town::ALL_TOWN; } } $town_model = new Model_Town(); if ($alias !== NULL) { if ($alias == Model_Town::ALL_TOWN) { $town_model = new Model_Town(array('id'=>0, 'alias'=>'all', 'name'=>'все города')); } else { $town_model = Model::fly('Model_Town')->find_by_alias($alias); } } if ($town_model->id === NULL) { $town_model = Model::fly('Model_Town')->find_by(array(),array('order_by' => 'id')); } $request->set_value('town_model', $town_model); return $town_model; } /** * Make alias for town from it's 'town' field * * @return string */ public function make_alias() { $caption_alias = str_replace(' ', '_', strtolower(l10n::transliterate($this->name))); $caption_alias = preg_replace('/[^a-z0-9_-]/', '', $caption_alias); $i = 0; $loop_prevention = 1000; do { if ($i > 0) { $alias = substr($caption_alias, 0, 30); $alias .= $i; } else { $alias = substr($caption_alias, 0, 31); } $i++; $exists = $this->exists_another_by_alias($alias); } while ($exists && ($loop_prevention-- > 0)); if ($loop_prevention <= 0) throw new Kohana_Exception ('Possible infinite loop in :method', array(':method' => __METHOD__)); return $alias; } /** * Import list of towns from an uploaded file * * @param array $uploaded_file */ public function import(array $uploaded_file) { // Increase php script time limit. set_time_limit(480); try { // Move uploaded file to temp location $tmp_file = File::upload($uploaded_file); if ($tmp_file === FALSE) { $this->error('Failed to upload a file'); return; } $town = Model::fly('Model_Town'); // hash region ids to save one db query $region_hash = array(); // Read file (assuming a UTF-8 encoded csv format) $delimiter = ';'; $enclosure = '"'; $h = fopen($tmp_file, 'r'); $first_line = true; while ($fields = fgetcsv($h, NULL, $delimiter, $enclosure)) { if ($first_line) { // Skip first header line $first_line = false; continue; } if (count($fields) < 3) { $this->error('Invalid file format. Expected 3 columns in a row, but ' . count($fields) . ' found'); return; } // Regions: insert new or find existing $name = UTF8::strtolower(trim($fields[0])); $name = UTF8::ucfirst($name); $phonecode = UTF8::strtolower(trim($fields[1])); $timezone = UTF8::strtolower(trim($fields[2])); $town->find_by_phonecode($phonecode); $town->name = $name; $town->phonecode = $phonecode; $town->timezone = $timezone; $town->save(); } fclose($h); @unlink($tmp_file); } catch (Exception $e) { // Shit happened if (Kohana::$environment === Kohana::DEVELOPMENT) { throw $e; } else { $this->error($e->getMessage()); } } } public function validate_update(array $newvalues = NULL) { return $this->validate_create($newvalues); } public function validate_create(array $newvalues = NULL) { if (Modules::registered('gmaps3')) { $geoinfo = Gmaps3::instance()->get_from_address($newvalues['name']); $err = 0; if (!$geoinfo) { FlashMessages::add('Город не найден и не будет отображен на карте!',FlashMessages::ERROR); $err = 1; } if (!$err) { if (!isset($geoinfo->geometry->location->lat)) { FlashMessages::add('Город не найден и не будет отображен на карте!',FlashMessages::ERROR); $err = 1; } } if (!$err) { if (!isset($geoinfo->geometry->location->lng)) { FlashMessages::add('Город не найден и не будет отображен на карте!',FlashMessages::ERROR); $err = 1; } } if (!$err) { $this->lat = $geoinfo->geometry->location->lat; $this->lon = $geoinfo->geometry->location->lng; } } return TRUE; } public function save($force_create = NULL) { // Create alias from name if (!$this->id) $this->alias = $this->make_alias(); return parent::save($force_create); } /** * Is group valid to be deleted? * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ($this->id == self::DEFAULT_TOWN_ID) { $this->error('Город является системным. Его удаление запрещено!', 'system'); return FALSE; } return TRUE; } /** * Delete town */ public function delete() { // Delete town places foreach (Model::fly('Model_Place')->find_all_by_town_id($this->id) as $place) { $place->delete(); } // Delete from DB parent::delete(); } }<file_sep>/modules/shop/area/views/backend/places/list.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($town === NULL || $town->id === NULL) { $town_alias = ''; } else { $town_alias = (string) $town->alias; } // ----- Set up urls $create_url = URL::to('backend/area/places', array('action'=>'create', 'are_town_alias' => $town_alias), TRUE); $update_url = URL::to('backend/area/places', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/area/places', array('action'=>'delete', 'id' => '${id}'), TRUE); $multi_action_uri = URL::uri_to('backend/area/places', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Создать</a> </div> <?php // Current section caption if (isset($town) && $town->id !== NULL) { echo '<h3 class="town_caption">' . $town->name . '</h3>'; } ?> <?php if ( ! count($places)) // No places return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="places table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'name' => 'Название', 'town_name' => 'Город', 'ispeed' => 'Интернет', ); echo View_Helper_Admin::table_header($columns, 'are_porder', 'are_pdesc'); ?> <th></th> </tr> <?php foreach ($places as $place) : $_delete_url = str_replace('${id}', $place->id, $delete_url); $_update_url = str_replace('${id}', $place->id, $update_url); ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($place->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'ispeed': echo '<td class="nowrap">'; echo HTML::chars(Model_Place::$_ispeed_options[$place->ispeed]); echo '</td>'; break; default: echo '<td class="nowrap">'; if (isset($place->$field) && trim($place->$field) !== '') { echo HTML::chars($place[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать площадку', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить площадку', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; //foreach ($places as $place) ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete'), )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?> <file_sep>/modules/system/forms/classes/form/fieldset.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Fieldset of form elements * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Fieldset extends FormComponent { // ------------------------------------------------------------------------- // Properties and attributes // ------------------------------------------------------------------------- /** * Type is "fieldset" * * @return string */ public function default_type() { return 'fieldset'; } /** * Fieldset html attribuges * @return array */ public function attributes() { $attributes = parent::attributes(); // Fieldset has no name unset($attributes['name']); // Add HTML class for form element (equal to "type") if (isset($attributes['class'])) { $attributes['class'] .= ' ' . $this->type; } else { $attributes['class'] = $this->type; } return $attributes; return $attributes; } // ------------------------------------------------------------------------- // Templates // ------------------------------------------------------------------------- /** * Get default config entry name for this fieldset * * @return string */ public function default_config_entry() { return substr(strtolower(get_class($this)), strlen('Form_')); } /** * Sets fieldset template * * @param string $template * @param string $type * @return Form_Fieldset */ public function set_template($template, $type = 'fieldset') { $this->_templates[$type] = $template; return $this; } // ------------------------------------------------------------------------- // Rendering // ------------------------------------------------------------------------- /** * Renders all elements in fieldset * * @return string */ public function render_components() { $html = ''; $template = $this->get_template('element'); foreach ($this->_components as $component) { if ($component->render) { $html .= Template::replace_ret($template, 'element', $component->render()); } } return $html; } /** * Renders all elements in fieldset * * @return string */ public function render() { if ( ! Request::$is_ajax) { $template = $this->get_template('fieldset'); } else { $template = $this->get_template('fieldset_ajax'); } // Fieldset elements Template::replace($template, 'elements', $this->render_components()); if (Template::has_macro($template, 'label')) { // Fieldset label Template::replace($template, 'label', $this->render_label()); } // label text Template::replace($template, 'label_text', $this->label); // Fieldset id Template::replace($template, 'id', $this->id); return $template; } /** * Renders label for fieldset * * @return string */ public function render_label() { if ($this->label !== NULL) { return Form_Helper::label(NULL, $this->label, array('required' => $this->required)); } else { return ''; } } }<file_sep>/modules/backend/classes/model/backend/menu.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Backend_Menu extends Model { /** * Cache of all menus * @var array */ protected static $_menus; /** * Used to generate unique id for menu items (emulate autoincrement) * Leave first 100 ids for manually specifing item position * @var integer */ protected static $_id = 100; /** * Configure the specified menu * * @param string $menu * @param array $properties */ public static function configure($menu, array $properties) { if ( ! isset(self::$_menus[$menu])) { self::$_menus[$menu] = array('items' => array()); } self::$_menus[$menu] = array_merge(self::$_menus[$menu], $properties); } /** * Add new menu item * * @param array $properties * @return integer id of inserted item */ public static function add_item(array $properties) { if ( ! isset($properties['menu'])) { throw new Kohana_Exception('Menu is not specified for menu item ":caption"', array(':caption' => isset($properties['caption']) ? $properties['caption'] : '')); } $menu = $properties['menu']; // Emulate autoincrement if ( ! isset($properties['id'])) { $id = ++self::$_id; } else { $id = $properties['id']; self::$_id = max(self::$_id, $id) + 1; } $parent_id = isset($properties['parent_id']) ? $properties['parent_id'] : 0; if (isset(self::$_menus[$menu]['items'][$parent_id][$id])) { throw new Kohana_Exception('You are trying to create item ":new_caption" with it ":id", but there is already an item ":old_caption" with such id!', array( ':id' => $id, ':new_caption' => isset($properties['caption']) ? $properties['caption'] : '', ':old_caption' => isset(self::$_menus[$menu]['items'][$parent_id][$id]['caption']) ? self::$_menus[$menu]['items'][$parent_id][$id]['caption'] : '' )); } // Automatically generate select condition based on route for new items // that don't have "select_conds" explicitly specified if ( ! isset($properties['select_conds'])) { $cond = array(); if (isset($properties['route'])) { $cond['route'] = $properties['route']; } if (isset($properties['route_params'])) { $cond['route_params'] = $properties['route_params']; } $properties['select_conds'][] = $cond; } $properties['id'] = $id; self::$_menus[$menu]['items'][$parent_id][$id] = $properties; return $id; } /** * Get the specified menu * * @param string $menu * @return array|false */ public static function get_menu($menu) { if ( ! isset(self::$_menus[$menu])) { return FALSE; } // Generate menu path and mark selected items if called for the first time if ( ! isset(self::$_menus[$menu]['path'])) { self::_generate_path($menu); } return self::$_menus[$menu]; } /** * Url to the menu item * * @return string */ public static function url(array $item) { return URL::to($item['route'], isset($item['route_params']) ? $item['route_params'] : NULL); } /** * Generate path and mark selected items for the specified menu * * @param string $menu */ protected static function _generate_path($menu) { $path = array(); $items = self::$_menus[$menu]['items']; // Current route name $route_name = Route::name(Request::current()->route); // Current controller $controller = Request::current()->controller; $directory = Request::current()->directory; if ( ! empty($directory)) { // Prepend the directory name to the controller name $controller = str_replace(array('\\', '/'), '_', trim($directory, '/')) . '_' . $controller; } // Current action $action = Request::current()->action; // Traverse the menu tree and mark current selected items // Also, add these selected items to path foreach ($items as $parent_id => & $branch) { // Sort branch by id ksort($branch, SORT_ASC); foreach ($branch as $id => $item) { // Remove item if there is no current site and item require the site if (Model_Site::current()->id === NULL && ! empty($item['site_required'])) { unset($branch[$id]); continue; } // Check conditions to determine whether this item is selected if ( ! empty($item['select_conds'])) { foreach ($item['select_conds'] as $cond) { $is_selected = TRUE; if ( (isset($cond['route']) && $route_name != $cond['route']) || (isset($cond['route_params']) && ! self::_params_equal($cond['route_params'])) ) { $is_selected = FALSE; } if ($is_selected) { $items[$parent_id][$id]['selected'] = TRUE; // Add item to path $path[$parent_id] = $item; $path[$parent_id]['id'] = $id; break; } } } } } // It's assumed that menu items are NOT MOVED after they are added // Than the id of any item is less than that of its parent and we can simply // use ksort() to sort path items by parent_id and, thereby, by depth level ksort($path, SORT_ASC); $path = array_values($path); self::$_menus[$menu]['path'] = $path; self::$_menus[$menu]['items'] = $items; } /** * Check that specified route params equals to the params from the current uri * This is used to determine whether current menu item is selected * * @param array $route_params * @return boolean */ protected static function _params_equal($route_params) { foreach ($route_params as $k => $v) { switch ($k) { case 'controller': $current_v = Request::current()->controller; break; case 'action': $current_v = Request::current()->action; break; default: $current_v = Request::current()->param($k); } if ($current_v != $v) { return FALSE; } } return TRUE; } }<file_sep>/application/classes/paginator.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Helper for rendering pages * * @package Eresus * @author <NAME> */ class Paginator { protected $_count; protected $_per_page; protected $_page_param; protected $_at_once = 7; public $offset; public $limit; public $route; public $params; public $class; protected $_page; protected $_pages_count; protected $_r; protected $_l; protected $_ignored_params = array(); public function __construct($count = 0, $per_page = 10, $page_param = 'page', $at_once = 7, $page = NULL, $route = NULL, $params = NULL, $class = '') { $this->_count = (int) $count; $this->_per_page = (int) $per_page; $this->_page_param = (string) $page_param; $this->_at_once = (int) $at_once; $this->_page = $page; $this->route = $route; $this->params = $params; $this->class = $class; $this->calculate(); } /** * Set/get ignored params for pagination * * @param array $ignored_params * @return array */ public function ignored_params(array $ignored_params = NULL) { if ($ignored_params !== NULL) { $this->_ignored_params = $ignored_params; } return $this->_ignored_params; } public function calculate() { if ($this->_page === NULL) { $page = Request::instance()->param($this->_page_param); } else { $page = $this->_page; } if ($page === 'all') { $this->_per_page = 0; $page = 0; } else { $page = (int) $page; } if ($this->_count > 0 && $this->_per_page > 0) { $pages_count = ceil($this->_count / $this->_per_page); if ($page >= $pages_count) { $page = $pages_count - 1; } } else { $pages_count = 0; } $this->_page = $page; $this->_pages_count = $pages_count; $this->offset = $this->_page * $this->_per_page; $this->limit = $this->_per_page; if ($this->_pages_count < 2) { return; } if ($this->_pages_count <= $this->_at_once) { $l= 0; $r= $this->_pages_count - 1; } else { $l= $this->_page - floor($this->_at_once/2); $r= $l + $this->_at_once-1; if ($l <= 0) { $l= 0; $r= $this->_at_once - 1; } if ($r >= $this->_pages_count - 1) { $r= $this->_pages_count - 1; $l= $this->_pages_count - $this->_at_once; } } $this->_l = $l; $this->_r = $r; } public function render($file = 'pagination') { $view = new View($file); $view->page_param = $this->_page_param; $view->page = $this->_page; $view->pages_count = $this->_pages_count; $view->l = $this->_l; $view->r = $this->_r; $view->rewind_to_first = ($this->_l > 0); $view->rewind_to_last = ($this->_r < $this->_pages_count - 1); $view->route = $this->route; if (!is_array($this->params)) $view->params = array(); else $view->params = $this->params; $view->ignored_params = $this->_ignored_params; $view->class = $this->class; $from = $this->_page * $this->_per_page + 1; $to = $from + $this->_per_page - 1; if ($to > $this->_count) { $to = $this->_count; } $view->count = $this->_count; $view->from = $from; $view->to = $to; return $view->render(); } public function __toString() { return $this->render(); } }<file_sep>/modules/general/faq/views/frontend/faq_form.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="faq_form"> <div class="faq_form_caption">Задайте свой вопрос</div> <?php echo $form; ?> </div> <file_sep>/modules/shop/catalog/views/frontend/sections/menu.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'frontend/sections/menu_branch')); $toggle_url = URL::to('frontend/catalog/section', array( 'sectiongroup_name' => $sectiongroup->name, 'path' => '{{path}}', 'toggle' => '{{toggle}}' ), TRUE); ?> <?php if (isset($sectiongroups)) { echo '<div id="sectiongroups">'; $tab_url = URL::to('frontend/catalog/search',array('sectiongroup_name'=>'{{name}}')); foreach ($sectiongroups as $secgroup) { $_tab_url = str_replace('{{name}}', $secgroup->name, $tab_url); if ($secgroup->id == $sectiongroup->id) { echo '<a class="button selected" href="' . $_tab_url . '">' . HTML::chars($secgroup->caption) . '</a>'; } else { echo '<a class="button" href="' . $_tab_url . '">' . HTML::chars($secgroup->caption) . '</a>'; } } echo '</div>'; } ?> <div class="sections_menu tree" id="sections"> <?php render_sections_menu_branch( $sections, NULL, $unfolded, $toggle_url, $section_id ); ?> </div><file_sep>/application/classes/modelstree.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Tree of models * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class ModelsTree extends Models { /** * @var Model */ protected $_root; /** * Construct container from array of properties * * @param string $model_class * @param array $properties_array * @param string $key name of the primary key field * @param Model $root */ public function __construct($model_class, array $properties_array, $pk = FALSE, $root = NULL) { parent::__construct($model_class, $properties_array, $pk); $this->root($root); } /** * Get/set tree root * * @param Model $root * @return Model */ public function root(Model $root = NULL) { if ($root !== NULL) { $this->_root = $root; } return $this->_root; } /** * Return tree as a structured list of models * * @return Models */ abstract public function as_list(); /** * Get direct children of the parent node * If $parent == NULL returns top level items * * @param Model $parent * @return Models */ abstract public function children(Model $parent = NULL); /** * Returns TRUE if the specified parent has children * * @return boolean */ abstract public function has_children(Model $parent = NULL); /** * Get the branch of the tree with root at $root * * @param Model $root * @return ModelsTree */ abstract public function branch(Model $root = NULL); } <file_sep>/modules/general/pages/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { Route::add('frontend/pages', new Route_Frontend( 'pages(/<node_id>)', array( 'town' => '\w++', 'action' => '\w++', 'node_id' => '\w++', ))) ->defaults(array( 'controller' => 'pages', 'action' => 'view', 'node_id' => NULL )); // if ( ! Modules::registered('indexpage')) // { // Route::add('frontend/indexpage', new Route_Frontend('')) // ->defaults(array( // 'controller' => 'pages', // 'action' => 'view' // )); // } } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/pages', new Route_Backend( 'pages(/<action>(/<node_id>))' . '(/~<history>)', array( 'action' => '\w++', 'node_id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'pages', 'action' => 'update', 'node_id' => NULL )); // ----- Add backend menu items Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => 10, 'site_required' => TRUE, 'caption' => 'Текстовые страницы', 'route' => 'backend/pages' )); } /****************************************************************************** * Common ******************************************************************************/ // ----- Add node types Model_Node::add_node_type('page', array( 'name' => 'Текстовая страница', 'backend_route' => 'backend/pages', 'frontend_route' => 'frontend/pages', 'model' => 'page' )); //if ( ! Modules::registered('indexpage')) //{ // // Use text page as index page for site // Model_Node::add_node_type('indexpage', array( // 'name' => 'Главная страница', // 'backend_route' => 'backend/pages', // 'frontend_route' => 'frontend/indexpage', // 'model' => 'page' // )); //} Model_Privilege::add_privilege_type('pages_control', array( 'name' => 'Управление Страницами', 'readable' => TRUE, 'frontend_route' => 'frontend/pages', 'frontend_route_params' => array('action' => 'index'), )); <file_sep>/modules/system/forms/classes/form/element/button.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form button element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Button extends Form_Element { /** * Use the same entry as the submit button * * @return string */ public function default_config_entry() { return 'submit'; } /** * This component cannot have value * * @return boolean */ public function get_without_value() { return TRUE; } /** * Render button * * @return string */ public function render_input() { return Form_Helper::button($this->full_name, $this->label, $this->attributes()); } /** * Get button attributes * * @return array */ public function attributes() { $attributes = parent::attributes(); // Set element type if ( ! isset($attributes['type'])) { $attributes['type'] = $this->type; } // Add HTML class for form button if (isset($attributes['class'])) { $attributes['class'] .= ' button ' . $this->type; } else { $attributes['class'] = 'button ' . $this->type; } return $attributes; } } <file_sep>/application/views/layouts/catalog_personal.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require('_header_new.php'); ?> <body> <header> <div class="container"> <div class="row"> <div class="span12"> <a href="home.html" class="logo pull-left"></a> <?php echo Widget::render_widget('menus','menu', 'main'); ?> <ul class="second-menu"> <li><a href="">Петропавловск-Камчатский</a></li> <li><a href="">формат события</a></li> <li><a href="">следующая неделя</a></li> <li><a href="">архитектура</a></li> <li><a href="">лайки</a></li> </ul> <div class="b-auth-search"> <a data-toggle="modal" href="#enterModal">Войти</a><span class="dash">|</span><a data-toggle="modal" href="#regModal">Регистрация</a> <?php echo Widget::render_widget('products', 'search');?> <div class="b-lang"> <a class="current" href="">RU</a><span class="dash">|</span><a href="">EN</a> </div> </div> </div> </div> </div> </header> <div id="main"> <div class="container"> <div class="row"> <div class="span8"> <div class="wrapper main-list"> <?php echo $content; ?> </div> </div> <aside class="span4"> <div class="near-tv"> </div> </aside> </div> </div> </div> <?php require('_footer.php'); ?> </body> <file_sep>/modules/shop/catalog/views/frontend/small_goes.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if (!count($products)) return; $today_datetime = new DateTime("now"); $tomorrow_datetime = new DateTime("tomorrow"); $today_flag= 0; $tomorrow_flag= 0; $nearest_flag = 0; ?> <div class="wrapper main-list"> <div class="ub-title"> <p>Я пойду</p> </div> <hr> <?php $view = new View('frontend/products/list'); $view->order_by = $order_by; $view->desc = $desc; $view->products = $products; $view->pagination = ''; $view->without_dateheaders = true; echo $view->render(); ?> <?php if ($pagination) { echo $pagination; } ?> </div> <file_sep>/modules/shop/acl/classes/model/resource/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Resource_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('resource_type', array('Type' => 'varchar(15)', 'Key' => 'INDEX')); $this->add_column('resource_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('user_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('organizer_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('town_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('mode', array('Type' => 'int unsigned', 'Key' => 'INDEX')); } /** * * @param Model $model * @param Model $resource * @param array $params * @return Model */ // public function find_all_by_role(Model $model, Model $role, array $params = NULL) // { // $res_pk = $role->get_pk(); // $condition['role_type'] = get_class($role); // $condition['role_id'] = $role->$res_pk; // // return parent::find_by($model, $condition, $params); // } }<file_sep>/modules/system/forms/classes/form/element/array.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form input element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Array extends Form_Element_Input { public function default_config_entry() { return 'input'; } /** * Cut strings longer than this parameter * @var string */ protected $_glue = ','; public function __construct($name, array $properties = NULL, array $attributes = NULL) { parent::__construct($name, $properties, $attributes); if (isset($attributes['glue'])) $this->_glue = $attributes['glue']; } /** * Gets element value * * @return mixed */ public function get_value() { $return_vals =array(); if ($this->_value !== NULL) { $vals = explode($this->_glue,$this->_value); foreach ($vals as $val) { $return_vals[] = trim($val); } return $return_vals; } // Value was not yet set (lazy getting) // Try to get value from POST if ( ! $this->disabled && ! $this->ignored) { $value = $this->form()->get_post_data($this->name); if ($value !== NULL) { $this->set_value_from_post($value); $vals = explode($this->_glue,$this->_value); foreach ($vals as $val) { $return_vals[] = trim($val); } return $return_vals; } } // Try to get value from the form's default source (such as associated model) $vals = $this->form()->get_data($this->name); if ($vals !== NULL) { $this->set_value($vals); foreach ($vals as $val) { $return_vals[] = trim($val); } return $return_vals; } // Default value $this->set_value($this->default_value); $vals = explode($this->_glue,$this->_value); foreach ($vals as $val) { $return_vals[] = trim($val); } return $return_vals; } /** * Get value to use in this element's validation * * @return mixed */ public function get_value_for_validation() { return $this->get_value(); } /** * Get value to use when rendering the element * * @return mixed */ public function get_value_for_render() { $value = $this->get_value(); return implode($this->_glue,$value); } } <file_sep>/modules/general/tags/views/frontend/small_images.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Width & height of one image preview $canvas_height = 110; $canvas_width = 110; $create_url = URL::to('frontend/images',array('action' => 'ajax_create','owner_type' => $owner_type,'owner_id' => $owner_id,'config' => $config)); ?> <div class="buttons"> <a data-toggle="modal" href="#ImgModal" class="request-link button">Загрузить фото</a> </div> <div class="images"> <?php foreach ($images as $image) : $image->config = $config; // Number the thumb to render $i = count($image->get_thumb_settings()); if ($i > 3) { $i = 3; } $width = $image->__get("width$i"); $height = $image->__get("height$i"); if ($width > $canvas_width || $height > $canvas_height) { if ($width > $height) { $scale = ' style="width: ' . $canvas_width . 'px;"'; $height = $height * $canvas_width / $width; $width = $canvas_width; } else { $scale = ' style="height: ' . $canvas_height . 'px;"'; $width = $width * $canvas_height / $height; $height = $canvas_height; } } else { $scale = ''; } if ($canvas_height > $height) { $padding = ($canvas_height - $height) >> 1; // ($canvas_height - $height) / 2 $padding = ' padding-top: ' . $padding . 'px;'; } else { $padding = ''; } ?> <div class="image"> <div class="img" style="width: <?php echo $canvas_width; ?>px; height: <?php echo $canvas_width; ?>px;"> <img src="<?php echo File::url($image->image($i)); ?>" <?php echo $scale; ?> alt="" /> </div> </div> <?php endforeach; ?> </div><file_sep>/modules/shop/catalog/classes/form/backend/searchproducts.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_SearchProducts extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "w500px"); $this->layout = 'wide'; // ----- search_text $element = new Form_Element_Input('search_text', array('label' => 'Поиск'), array('maxlength' => 255, 'class' => 'w200px') ); $element ->add_filter(new Form_Filter_TrimCrop(255)); $this->add_component($element); // ----- Submit button $button = new Form_Backend_Element_Submit('submit', array('label' => 'Найти', 'render' => FALSE), array('class' => 'button_accept') ); $this->add_component($button); $element->append = '&nbsp;' . $button->render(); // ----- advanced search options $fieldset = new Form_Fieldset('advanced', array('label' => 'Расширенный поиск')); $this->add_component($fieldset); // ----- active $options = array(-1 => 'не важно', 1 => 'да', 0 => 'нет'); $element = new Form_Element_RadioSelect('active', $options, array('label' => 'Активный:') ); $element->default_value = -1; $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $element->config_entry = 'checkselect_inline'; $fieldset->add_component($element); // ----- presence in product lists /* $fieldset2 = new Form_Fieldset('plists_fieldset', array('label' => 'Наличие в списках товаров'), array('class' => 'lb200px')); $fieldset->add_component($fieldset2); $options = array(-1 => 'не важно', 1 => 'да', 0 => 'нет'); $plists = Model::fly('Model_PList')->find_all_by_site_id(Model_Site::current()->id, array('columns' => array('id', 'caption'), 'order_by' => 'id', 'desc' => FALSE) ); foreach ($plists as $plist) { $element = new Form_Element_RadioSelect('plists[' . $plist->id . ']', $options, array('label' => $plist->caption) ); $element->default_value = -1; $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $element->config_entry = 'checkselect_inline'; $fieldset2->add_component($element); } * */ } } <file_sep>/modules/system/forms/config/form_templates/table/fieldset_inline.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // Standart layout 'standart' => array( 'fieldset' => '<tr> <td class="fieldset_inline_cell" colspan="2"> <div>{{label}}</div> <div id="{{id}}"> <table><tr> {{elements}} </tr></table> </div> </td> </tr> ', 'fieldset_ajax' => '<table><tr> {{elements}} </tr></table> ', 'element' => '<td class="fieldset_inline_element_cell">{{element}}</td>' ), // Wide layout 'wide' => array( 'fieldset' => '<tr> <td class="label_cell">{{label}}</td> <td class="fieldset_inline_cell"> <div id="{{id}}"> <table class="fieldset_inline_elements"><tr> {{elements}} </tr></table> </div> </td> </tr> ', 'fieldset_ajax' => '<table><tr> {{elements}} </tr></table> ', 'element' => '<td class="fieldset_inline_element_cell">{{element}}</td>' ) ); <file_sep>/modules/shop/sites/classes/model/site/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Site_Mapper extends Model_Mapper { /** * Cache find all results * @var boolean */ public $cache_find_all = FALSE; public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('url', array('Type' => 'varchar(255)', 'Key' => 'INDEX')); $this->add_column('caption', array('Type' => 'varchar(255)')); $this->add_column('settings', array('Type' => 'array')); } }<file_sep>/modules/system/forms/classes/form/element/text.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Display text message in form * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_Text extends Form_Element { /** * Creates form element * * @param string $name Element name * @param string $value Default value * @param array $attributes Attributes */ public function __construct($name, array $properties = NULL, array $attributes = NULL) { parent::__construct($name, $properties, $attributes); // This element cannot have a value $this->without_value = 1; } /** * Renders text message in form * * @return string */ public function render_input() { return $this->value; } } <file_sep>/modules/general/tags/classes/model/tag.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Tag extends Model { const TAGS_DELIMITER = ','; public function save_all($tags_string,$owner_type,$owner_id) { $tag_names = explode(self::TAGS_DELIMITER,$tags_string); $tag_names = array_unique($tag_names); $tags = Model::fly('Model_Tag')->delete_all_by(array( 'owner_type' => $owner_type, 'owner_id' => $owner_id)); $i = 0; foreach ($tag_names as $tag_name) { $tag_name = trim($tag_name); if ($tag_name != '') { $tag = new Model_Tag(); $tag->weight = ++$i; $tag->name = trim($tag_name); $tag->owner_type = $owner_type; $tag->owner_id = $owner_id; $tag->save(); } } } /** * Make alias for tag from it's 'name' field * * @return string */ public function make_alias() { $alias = str_replace(' ', '_', strtolower(l10n::transliterate($this->name))); $alias = preg_replace('/[^a-z0-9_-]/', '', $alias); return $alias; } public function save($force_create = FALSE) { if (!$this->id) $this->alias = $this->make_alias(); parent::save($force_create); } }<file_sep>/modules/shop/acl/views/frontend/forms/newpas.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="modal-header"> <h3 id="myModalLabel">Новый пароль</h3> </div> <?php echo $form->render_form_open();?> <div class="modal-body"> <p>Введите новый пароль</p> <label for="pass"><?php echo $form->get_element('password')->render_input(); ?></label> </div> <div class="modal-footer"> <?php echo $form->get_element('submit_newpas')->render_input(); ?> </div> <?php echo $form->render_form_close();?><file_sep>/modules/shop/catalog/classes/dbtable/productsection.php <?php defined('SYSPATH') or die('No direct script access.'); class DbTable_ProductSection extends DbTable { public function init() { parent::init(); $this->add_column('product_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('section_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('distance', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('sectiongroup_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); } }<file_sep>/modules/shop/catalog/views/frontend/products/product_create.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('frontend/catalog/products', array('action'=>'create', 'sectiongroup_name' => $sectiongroup->name), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Создать событие</a> </div> <file_sep>/modules/system/image_eresus/classes/image.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Image manipulation support. Allows images to be thumbnailed, resized, cropped, etc. * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Image extends Kohana_Image { /** * Create a thumbnail from image. * Difference from resize: * 1) Doesn't scale image if it is already smaller, than needed * * @param integer $width * @param integer $height * @param integer $master * @return Image */ public function thumbnail($width = NULL, $height = NULL, $master = NULL) { // No resizing is needed if ($width == 0 && $height == 0) return $this; // Image is already smaller, than required if ($width >= $this->width && $height >= $this->height) return $this; $this->resize($width, $height, $master); if ($master === Image::INVERSE) { // Crop the image to the desired size $this->crop($width, $height); } return $this; } }<file_sep>/modules/shop/catalog/views/backend/sections/menu_branch.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php function render_sections_menu_branch( ModelsTree $sections, Model $parent = NULL, array $unfolded, /*$update_url, $delete_url, $up_url, $down_url, */$toggle_url, $url, $section_id ) { foreach ($sections->children($parent) as $section) { /* $_update_url = str_replace('{{id}}', $section->id, $update_url); $_delete_url = str_replace('{{id}}', $section->id, $delete_url); $_up_url = str_replace('{{id}}', $section->id, $up_url); $_down_url = str_replace('{{id}}', $section->id, $down_url); */ $_url = str_replace('{{id}}', $section->id, $url); // Highlight current section if ($section->id == $section_id) { $selected = ' selected'; } else { $selected = ''; } if ( ! $section->section_active) { $active = ' capt_inactive'; } elseif ( ! $section->active) { $active = ' inactive'; } else { $active = ''; } echo '<div class="section">'; /* echo ' <div class="ctl">' . View_Helper_Admin::image_control($_delete_url, 'Удалить раздел', 'controls/delete.gif', 'Удалить') . View_Helper_Admin::image_control($_update_url, 'Редактировать раздел', 'controls/edit.gif', 'Редактировать') . View_Helper_Admin::image_control($_up_url, 'Переместить вверх', 'controls/up.gif', 'Вверх') . View_Helper_Admin::image_control($_down_url, 'Переместить вниз', 'controls/down.gif', 'Вниз') . ' </div>'; */ echo ' <div class="caption_wrapper">' . ' <div class="level_pad" style="padding-left: ' . ($section->level-1)*15 . 'px">'; if ($section->has_children) { // Render toggle on/off bullet $toggled_on = in_array($section->id, $unfolded); $_toggle_url = str_replace( array('{{id}}', '{{toggle}}'), array($section->id, ($toggled_on ? 'off' : 'on')), $toggle_url ); echo ' <a href="' . $_toggle_url . '"' . ' class="toggle ' . ( $toggled_on ? '' : ' toggled_off') . '"' . ' id="sections_toggle_' . $section->id . '"' . '></a>'; } else { $toggled_on = FALSE; } echo ' <a' . ' href="' . $_url . '"' . ' class="capt' . $selected . $active . '"' . ' title="Показать все события из раздела \'' . HTML::chars($section->caption) . '\'"' . ' >' . HTML::chars($section->caption) . ' </a>' . ' </div>' . ' </div>'; echo '</div>'; if ($section->has_children) { // Render wrapper for branch (used to redraw branch via ajax if it is folded & to toggle branch on/off) echo '<div id="sections_branch_' . $section->id . '" class="' . ($toggled_on ? '' : 'folded') . '">'; if ($toggled_on) { render_sections_menu_branch( $sections, $section, $unfolded, /*$update_url, $delete_url, $up_url, $down_url, */$toggle_url, $url, $section_id ); } echo '</div>'; } } } <file_sep>/modules/shop/acl/views/backend/organizers/select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // ----- Set up urls // Submit results to previous url $organizers_select_uri = URL::uri_back(); ?> <?php echo View_Helper_Admin::multi_action_form_open($organizers_select_uri, array('name' => 'organizers_select')); ?> <table class="organizers_select table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'name' => 'Название' ); echo View_Helper_Admin::table_header($columns, 'are_torder', 'are_tdesc'); ?> </tr> <?php foreach ($organizers as $organizer) : ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($organizer->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'name': echo '<td>' . HTML::chars($organizer->$field) . '</td>'; break; default: echo '<td>'; if (isset($organizer->$field) && trim($organizer->$field) !== '') { echo HTML::chars($organizer[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> </tr> <?php endforeach; ?> </table> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'organizers_select', 'label' => 'Выбрать', 'class' => 'button_select') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/acl/classes/controller/backend/privileges.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Privileges extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Privilege'; $this->_form = 'Form_Backend_Privilege'; return array( 'create' => array( 'view_caption' => 'Создание привилегии' ), 'update' => array( 'view_caption' => 'Редактирование привилегии ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление привилегии', 'message' => 'Удалить привилегию ":caption"?' ) ); } /** * Create layout (proxy to catalog controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('catalog')->prepare_layout($layout_script); } /** * Render layout (proxy to catalog controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('catalog')->render_layout($content, $layout_script); } /** * Render all available section properties */ public function action_index() { $this->request->response = $this->render_layout($this->widget_privileges()); } /** * Create new property * * @return Model_Property */ protected function _model_create($model, array $params = NULL) { if (Model_Site::current()->id === NULL) { throw new Controller_BackendCRUD_Exception('Выберите портал перед созданием привилегии!'); } // New section for current site $privilege = new Model_Privilege(); $privilege->site_id = (int) Model_Site::current()->id; return $privilege; } /** * Render list of section properties */ public function widget_privileges() { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } $order_by = $this->request->param('acl_prorder', 'position'); $desc = (bool) $this->request->param('acl_prdesc', '0'); $privileges = Model::fly('Model_Privilege')->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/privileges'); $view->order_by = $order_by; $view->desc = $desc; $view->privileges = $privileges; return $view->render(); } }<file_sep>/modules/general/news/classes/controller/backend/news.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_News extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Newsitem'; $this->_form = 'Form_Backend_Newsitem'; return array( 'create' => array( 'view_caption' => 'Создание новости' ), 'update' => array( 'view_caption' => 'Редактирование новости ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление новость', 'message' => 'Удалить новость ":caption"?' ) ); } /** * @return boolean */ public function before() { if ( ! parent::before()) { return FALSE; } if ($this->request->is_forwarded()) // Request was forwarded in parent::before() return TRUE; // Check that there is a site selected if (Model_Site::current()->id === NULL) { $this->_action_error('Выберите сайт для работы с новостями!'); return FALSE; } return TRUE; } /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); return $layout; } /** * Default action */ public function action_index() { $view = new View('backend/workspace'); $view->caption = 'Список новостей'; $view->content = $this->widget_news(); $this->request->response = $this->render_layout($view); } /** * Renders news list * * @return string */ public function widget_news() { $newsitem = new Model_Newsitem(); $order_by = $this->request->param('news_order', 'date'); $desc = (bool) $this->request->param('news_desc', '1'); // Select all news for current site $site_id = Model_Site::current()->id; $per_page = 20; $count = $newsitem->count_by_site_id($site_id); $pagination = new Pagination($count, $per_page); $news = $newsitem->find_all_by_site_id($site_id, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc, 'columns' => array('id', 'date', 'caption') )); // Set up view $view = new View('backend/news'); $view->order_by = $order_by; $view->desc = $desc; $view->news = $news; $view->pagination = $pagination; return $view; } } <file_sep>/modules/system/history/classes/model/history.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_History extends Model { /** * Generate value change text * * @param string $label * @param mixed $new_value * @param mixed $old_value * @return string */ public static function changes_text($label, $new_value, $old_value = NULL) { return $label . ': <em>' . HTML::chars($old_value) . '</em> &raquo; <em>' . HTML::chars($new_value) . '</em>' . "\n"; } /** * @return integer */ public function default_site_id() { return Model_Site::current()->id; } /** * @return integer */ public function default_user_id() { return Auth::instance()->get_user()->id; } /** * @return string */ public function default_user_name() { return Auth::instance()->get_user()->name; } /** * Get history entry text ready for output */ public function get_html() { $text = $this->text; // Replace the numbers of existing orders with links to this orders if (preg_match_all('/{{id-(\d+)}}/i', $text, $matches, PREG_SET_ORDER)) { $order = Model::fly('Model_Order'); foreach ($matches as $match) { $order_id = (int) $match[1]; if ($order->exists_by_id($order_id)) { $url = URL::to('backend/orders', array('action' => 'update', 'id' => $order_id), TRUE); $text = str_replace($match[0], '<a href="' . $url . '">' . $order_id . '</a>', $text); } else { $text = str_replace($match[0], $order_id, $text); } } } return nl2br($text); } }<file_sep>/modules/shop/acl/classes/model/userpropuser.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_UserPropUser extends Model { /** * Get "active" userprop * * @return boolean */ public function get_active() { if ($this->system) { // System userprops are always active return 1; } elseif (isset($this->_properties['active'])) { return $this->_properties['active']; } else { return 0; // default value } } /** * Set "active" userprop * * @param <type> $value */ public function set_active($value) { // System userprops are always active if ($this->system) { $value = 1; } $this->_properties['active'] = $value; } /** * Link given userprop to user * * @param Model_Userprop $userprop * @param array $userpropusers */ public function link_userprop_to_users(Model_UserProp $userprop, array $userpropusers) { // Delete all info $this->delete_all_by_userprop_id($userprop->id); $userpropuser = Model::fly('Model_UserPropUser'); foreach ($userpropusers as $values) { $userpropuser->values($values); $userpropuser->userprop_id = $userprop->id; $userpropuser->save(); } } /** * Link given user to userprops * * @param Model_User $user * @param array $userpropusers */ public function link_user_to_userprops(Model_Group $user, array $userpropusers) { // Delete all info $this->delete_all_by_user_id($user->id); $userpropuser = Model::fly('Model_UserPropUser'); foreach ($userpropusers as $values) { $userpropuser->values($values); $userpropuser->user_id = $user->id; $userpropuser->save(); } } }<file_sep>/application/classes/kohana.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Framework core * * @package Eresus * @author <NAME> (<EMAIL>) */ class Kohana extends Kohana_Core { /** * Set up the Kohana::$is_cli when being run using the php-cgi binary from command line * * @param array $settings */ public static function init(array $settings = NULL) { if (Kohana::$_init) { // Do not allow execution twice return; } parent::init($settings); if (PHP_SAPI == 'cgi' && ! isset($_SERVER['HTTP_HOST'])) { // Looks like we've been launched with php-cgi from command line Kohana::$is_cli = TRUE; } } /** * Inline exception handler, displays the error message, source of the * exception, and the stack trace of the error. * * @uses Kohana::exception_text * @param object exception object * @return boolean */ public static function exception_handler(Exception $e) { if (Kohana::$environment === Kohana::DEVELOPMENT) { parent::exception_handler($e); } else { // We are in production mode try { if (Request::$instance !== NULL) { $request = Request::$instance; } else { $request = new Request(''); } if ($request->status !== 404) { // Set status to error $request->status = 500; } // Log all errors, except 404 if ($request->status !== 404 && is_object(Kohana::$log)) { // Get the exception information $type = get_class($e); $code = $e->getCode(); $message = $e->getMessage(); $file = $e->getFile(); $line = $e->getLine(); // Create a text version of the exception $error = Kohana::exception_text($e); // Add this exception to the log Kohana::$log->add(Kohana::ERROR, $error); // Make sure the logs are written Kohana::$log->write(); } // Clean the output buffer if one exists ob_get_level() and ob_clean(); $ctrl_error = $request->get_controller('Controller_Errors'); $ctrl_error->action_error($request->uri, $request->status); echo $request ->send_headers() ->response; } catch (Exception $e) { // An exception happend during production exception handling... // Something has gone definitly wrong. parent::exception_handler($e); } } } } <file_sep>/modules/general/chat/classes/model/message.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Message extends Model { /** * Default active for message * * @return bool */ public function default_user_id() { return Auth::instance()->get_user()->id; } /** * Default active for message * * @return bool */ public function default_active() { return TRUE; } /** * Get short preview of the message text * * @return string */ public function get_message_preview() { return Text::limit_chars($this->message, 128, '...', TRUE); } /** * Set message creation time * * @param DateTime|string $value */ public function set_created_at($value) { if ($value instanceof DateTime) { $this->_properties['created_at'] = clone $value; } else { $this->_properties['created_at'] = new DateTime($value); } } /** * Get message creation time * * @return DateTime */ public function get_created_at() { if ( ! isset($this->_properties['created_at'])) { if (empty($this->_properties['id'])) { // Default value for a new question $this->_properties['created_at'] = new DateTime(); } else { return NULL; } } return clone $this->_properties['created_at']; } /** * Get message creation date as string * * @return string */ public function get_date() { return $this->created_at->format(Kohana::config('datetime.datetime_format')); } /** * @param array $newvalues */ public function validate(array $newvalues) { if ( ! isset($newvalues['message']) || $newvalues['message'] == '') { $this->error('Укажите текст сообщения'); return FALSE; } return TRUE; } /** * Get dialog for this message * * @return Model_Dialog */ public function get_dialog() { if ( ! isset($this->_properties['dialog'])) { $dialog = new Model_Dialog(); if ($this->dialog_id != 0) { $dialog->find($this->dialog_id); } $this->_properties['dialog'] = $dialog; } return $this->_properties['dialog']; } // ------------------------------------------------------------------------- // Validation // ------------------------------------------------------------------------- /** * Validate message creation * * @param array $newvalues * @return boolean */ public function validate_create(array $newvalues) { return ( $this->validate_dialog_id($newvalues) && $this->validate_receiver_id($newvalues) ); } /** * Prohibit invalid dialog_id values * * @param array $newvalues New values for model * @return boolean */ public function validate_dialog_id(array $newvalues) { if ( isset($newvalues['dialog_id'])) { if (!Model::fly('Model_Dialog')->exists_by_id($this->dialog_id)) { $this->error('Указанный диалог не найден!'); return FALSE; } } return TRUE; } public function validate_receiver_id(array $newvalues) { if ( !isset($newvalues['receiver_id']) || ! Model::fly('Model_User')->exists_by_id($newvalues['receiver_id'])) { $this->error('Указан неверный получатель!'); return FALSE; } return TRUE; } /** * Save message * * @param boolean $force_create */ public function save($force_create = FALSE) { if (!isset($this->dialog_id)) { $dialog = new Model_Dialog($this->values()); $dialog->save(); $this->dialog_id = $dialog->id; } parent::save($force_create); //$this->notify_client(); } /** * Set notification to client that his message has been answered */ public function notify_client() { try { // Site settings $settings = Model_Site::current()->settings; $email_to = isset($settings['email']['to']) ? $settings['email']['to'] : ''; $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; if ($email_sender != '') { $email_from = array($email_from => $email_sender); } // FAQ settings $config = Modules::load_config('faq_' . Model_Site::current()->id, 'faq'); $subject = isset($config['email']['client']['subject']) ? $config['email']['client']['subject'] : ''; $body = isset($config['email']['client']['body']) ? $config['email']['client']['body'] : ''; if ($this->email != '') { $twig = Twig::instance('string'); // Values for the templates $values = $this->values(); $values['site'] = Model_Site::canonize_url(URL::site('', TRUE)); // Subject $subject = $twig->loadTemplate($subject)->render($values); // Body (with optional signature) $body = $twig->loadTemplate($body)->render($values); if ($signature != '') { $body .= "\n\n\n" . $signature; } // Init mailer SwiftMailer::init(); $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance() ->setSubject($subject) ->setFrom($email_from) ->setTo($this->email) ->setBody($body); // Send message $mailer->send($message); } } catch (Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { throw $e; } } } /** * Set notification to administrator about the new question */ public function notify_admin() { try { // Site settings $settings = Model_Site::current()->settings; $email_to = isset($settings['email']['to']) ? $settings['email']['to'] : ''; $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; if ($email_sender != '') { $email_from = array($email_from => $email_sender); } // FAQ settings $config = Modules::load_config('faq_' . Model_Site::current()->id, 'faq'); $subject = isset($config['email']['admin']['subject']) ? $config['email']['admin']['subject'] : ''; $body = isset($config['email']['admin']['body']) ? $config['email']['admin']['body'] : ''; if ($email_to != '') { $twig = Twig::instance('string'); // Values for the templates $values = $this->values(); $values['site'] = Model_Site::canonize_url(URL::site('', TRUE)); // Subject $subject = $twig->loadTemplate($subject)->render($values); // Body $body = $twig->loadTemplate($body)->render($values); // Init mailer SwiftMailer::init(); $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); $message = Swift_Message::newInstance() ->setSubject($subject) ->setFrom($email_from) ->setTo($email_to) ->setBody($body); // Send message $mailer->send($message); } } catch (Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { throw $e; } } } } <file_sep>/modules/frontend/classes/form/frontend/confirm.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Confirm extends Form { /** * Message * @var string */ protected $_message; /** * Label for 'submit' button * @var string */ protected $_yes = 'Да'; /** * Label for 'cancel' button * @var string */ protected $_no = 'Нет'; /** * Creates "Yes/No" confirmation form with specified message * * @param string $message */ public function __construct($message, $yes = 'Да', $no = 'Нет') { $this->_message = $message; $this->_yes = $yes; $this->_no = $no; parent::__construct(); } /** * Initialize form fields */ public function init() { // Message $element = new Form_Element_Text('text', array('class' => 'confirm_message')); $element->value = $this->_message; $this->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => $this->_no), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Frontend_Element_Submit('submit', array('label' => $this->_yes), array('class' => 'button_accept') )); } } <file_sep>/modules/shop/catalog/views/frontend/product.php <?php defined('SYSPATH') or die('No direct script access.'); echo Widget::render_widget('products', 'product', $product); echo Widget::render_widget('telemosts', 'request', $product); ?> <file_sep>/modules/system/forms/classes/form/model.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form with associated model */ class Form_Model extends Form { /** * Reference to model * @var Model */ protected $_model; /** * Create form * * @param Model $model Reference to model * @param string $name */ public function __construct(Model $model = NULL, $name = NULL) { $this->model($model); parent::__construct($name); } /** * Set/get associated model * * @param Model $model * @return Model */ public function model(Model $model = NULL) { if ($model !== NULL) { $this->_model = $model; } return $this->_model; } /** * Get data from associated model * * @param string $key * @return mixed */ public function get_data($key) { $data = $this->model(); if (strpos($key, '[') !== FALSE) { // Form element name is a hash key $path = str_replace(array('[', ']'), array('.', ''), $key); $value = Arr::path($data, $path); } elseif (isset($data[$key])) { $value = $data[$key]; } else { $value = NULL; } return $value; } }<file_sep>/modules/system/forms/classes/form/validator/email.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validates value to be a valid e-mail address. * Utilizes Kohana native Validate::email. * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_Email extends Form_Validator { const EMPTY_STRING = 'EMPTY_STRING'; const INVALID = 'INVALID'; protected $_messages = array( self::EMPTY_STRING => 'Вы не указали :label!', self::INVALID => 'Некорректный формат e-mail адреса!' ); /** * Allow empty strings * @var boolean */ protected $_allow_empty = FALSE; /** * Creates validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty strings */ public function __construct(array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE) { parent::__construct($messages, $breaks_chain); $this->_allow_empty = $allow_empty; } /** * Validate using Kohanas native Validate::email * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $value = (string) $this->_value; if (preg_match('/^\s*$/', $value)) { // An empty string allowed ? if (!$this->_allow_empty) { $this->_error(self::EMPTY_STRING); return false; } else { return true; } } if ( ! Validate::email($value)) { $this->_error(self::INVALID); return false; } return true; } }<file_sep>/modules/shop/acl/classes/form/frontend/pasrecovery.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Pasrecovery extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/forms/pasrecovery'; // ----- email $email = new Form_Element_Input('email', array('label' => 'E-Mail', 'required' => TRUE), array('maxlength' => 31, 'placeholder' => 'Электронная почта')); $email->add_filter(new Form_Filter_TrimCrop(31)) ->add_validator(new Form_Validator_NotEmptyString()) ->add_validator(new Form_Validator_Email()); $this->add_component($email); // ----- Form buttons $button = new Form_Element_Button('submit_pasrecovery', array('label' => 'Отправить'), array('class' => 'button_pasrecovery button-modal') ); $this->add_component($button); parent::init(); } }<file_sep>/modules/shop/catalog/classes/form/frontend/filterprice.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_FilterPrice extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/forms/filter_price'; // ----- price_from $element = new Form_Element_Float('price_from', array('label' => 'от')); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Float(0, NULL, TRUE, NULL, TRUE, TRUE)); $this->add_component($element); // ----- price_to $element = new Form_Element_Float('price_to', array('label' => 'до')); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Float(0, NULL, TRUE, NULL, TRUE, TRUE)); $this->add_component($element); // ----- Submit button /* $this ->add_component(new Form_Element_Submit('submit', array('label' => 'Выбрать') array('class' => 'submit') )); */ } } <file_sep>/modules/shop/catalog/views/backend/product_select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php if ($section === NULL || $section->id === NULL) { $section_id = '0'; } else { $section_id = (string) $section->id; } // ----- Set up url list($hist_route, $hist_params) = URL::match(URL::uri_back()); $hist_params['product_id'] = '{{product_id}}'; $select_url = URL::to($hist_route, $hist_params, TRUE); ?> <?php // Current section caption if (isset($section) && $section->id !== NULL) { echo '<h3 class="section_caption">' . HTML::chars($section->caption) . '</h3>'; } ?> <?php // Search form echo $search_form->render(); ?> <table class="products table" id="product_select"> <tr class="table_header"> <?php $columns = array( 'caption' => 'Название', 'active' => 'Акт.', ); echo View_Helper_Admin::table_header($columns, 'cat_porder', 'cat_pdesc'); ?> </tr> <?php foreach ($products as $product) : $_select_url = str_replace('{{product_id}}', $product->id, $select_url); ?> <tr> <?php foreach (array_keys($columns) as $field) { if ($field == 'caption') { echo '<td class="capt' .(empty($product->active) ? ' inactive' : '') . '">' . ' <a href="' . $_select_url . '" class="product_select" id="product_' . $product->id . '">' . HTML::chars($product->$field) . ' </a>' . '</td>'; } elseif ($field == 'active') { echo '<td class="c">'; if ( ! empty($product->$field)) { echo View_Helper_Admin::image('controls/on.gif', 'Да'); } else { echo View_Helper_Admin::image('controls/off.gif', 'Нет'); } echo '</td>'; } else { echo '<td>'; if (isset($product->$field) && trim($product->$field) !== '') { echo HTML::chars($product[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> </tr> <?php endforeach; ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php if ( !Request::current()->in_window()) : ?> <div style="padding-top: 20px;"> <div class="buttons"> <a href="<?php echo URL::back(); ?>" class="button_adv button_cancel"><span class="icon">Назад</span></a> </div> </div> <?php endif; ?> <file_sep>/modules/shop/acl/views/backend/lecturer_ac.php <div class="lecturer_ac"> <div class="item"><?php echo HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'])) ?></div> <div class="item"><?php echo $name ?></div> </div> <file_sep>/modules/general/faq/classes/model/question/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Question_Mapper extends Model_Mapper { public function init() { $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('site_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('position', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('created_at', array('Type' => 'datetime')); $this->add_column('user_name', array('Type' => 'varchar(255)')); $this->add_column('email', array('Type' => 'varchar(63)')); $this->add_column('phone', array('Type' => 'varchar(63)')); $this->add_column('question', array('Type' => 'text')); $this->add_column('answer', array('Type' => 'text')); $this->add_column('answered', array('Type' => 'boolean')); $this->add_column('active', array('Type' => 'boolean')); } /** * Move question one position up * * @param Model $model * @param Database_Expression_Where $condition */ public function up(Model $model, Database_Expression_Where $condition = NULL) { parent::up($model, DB::where('site_id', '=', $model->site_id)); } /** * Move question one position down * * @param Model $model * @param Database_Expression_Where $condition */ public function down(Model $model, Database_Expression_Where $condition = NULL) { parent::down($model, DB::where('site_id', '=', $model->site_id)); } }<file_sep>/modules/shop/deliveries/classes/controller/backend/delivery.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Base class for delivery module backend controller */ abstract class Controller_Backend_Delivery extends Controller_BackendCRUD { /** * Set up default actions for payment module controller */ public function setup_actions() { $module = substr(get_class($this), strlen('Controller_Backend_Delivery_')); $this->_model = "Model_Delivery_$module"; $this->_form = "Form_Backend_Delivery_$module"; return array( 'create' => array( 'view_caption' => 'Добавление способа доставки' ), 'update' => array( 'view_caption' => 'Редактирование способа доставки ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление способа доставки', 'message' => 'Удалить способ доставки ":caption"?' ) ); } /** * Create layout (proxy to orders controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('orders')->prepare_layout($layout_script); } /** * Render layout (proxy to orders controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('orders')->render_layout($content, $layout_script); } /** * Create action */ public function action_create() { // Redirect two steps back $this->_action('create', array('redirect_uri' => URL::uri_back(NULL, 2))); } }<file_sep>/modules/backend/views/backend/workspace.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="workspace_content"> <?php echo $content; ?> </div> <file_sep>/modules/system/database_eresus/classes/dbtable.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Represents a table in database * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class DbTable { /** * Cache for parsed column types * @var array */ protected static $_types_info_cache = array(); /** * Configuration * @var array */ protected $_config; /** * Database instance * @var Database */ protected $_db = 'default'; /** * Name of database table * @var string */ protected $_table_name; /** * Columns * @var array */ protected $_columns = array(); /** * Virtual columns (custom columns, that are not the columns of the table in db, but can appear when using joins or expression) * @var array */ protected $_virtual_columns = array(); /** * Manually specified indexes * @var array */ protected $_indexes = array(); /** * Table options * @var array */ protected $_options = array(); /** * Columns metadata (generated from _columns) * @var array */ protected $_columns_metadata; /** * Indexes metadata (generated from _columns and _indexes) * @var array */ protected $_indexes_metadata; /** * Flag is used to prevent duplicate table creation tries when * mapper is instantinated more than onse * @var array */ protected static $_tables_created = array(); /** * Flag is used to prevent duplicate table updating tries when * mapper is instantinated more than onse * @var array */ protected static $_tables_updated = array(); /** * Name of primary key * @var string */ protected $_pk; /** * DbTable instances * @var array */ protected static $_dbtables; /** * Return an instance of dbtable * * @param string $class * @return DbTable */ public static function instance($class) { $class = strtolower($class); if (strpos($class, 'dbtable_') !== 0) { $class = 'dbtable_' . $class; } if ( ! isset(self::$_dbtables[$class])) { self::$_dbtables[$class] = new $class(); } return self::$_dbtables[$class]; } /** * Loads the database. Sets table name. * * @param mixed Database instance object or string * @return void */ public function __construct($db = NULL, $table_name = NULL, array $config = NULL) { // Load configuration if ($config === NULL) { $this->_config = Kohana::config('dbtable'); } else { $this->_config = $config; } if ($db !== NULL) { // Set the database instance name $this->set_db($db); } if ($table_name !== NULL) { // Set up database table name $this->table_name($table_name); } // Initialize DbTable, add neccessary columns $this->init(); // Auto create/update table columns $this->sync_with_db(); } /** * Sets database to use by mapper * * @param Database | string $db Database object or database instance name * @return Model_Mapper */ public function set_db($db) { $this->_db = $db; return $this; } /** * Gets database instance * * @return Database */ public function get_db() { if (is_object($this->_db)) { return $this->_db; } elseif (is_string($this->_db)) { // Load the database by instance name $this->_db = Database::instance($this->_db); return $this->_db; } elseif ($this->_db === NULL) { throw new Exception('Database instance not specified!'); } else { throw new Exception('Invalid database instance type ":type"', array(':type' => gettype($this->_db))); } } /** * Sets/gets db table name * * @param string $table_name * @return string */ public function table_name($table_name = NULL) { if ($table_name !== NULL) { $this->_table_name = $table_name; } if ($this->_table_name === NULL) { // Try to construct table name from class name $table_name = strtolower(get_class($this)); if (substr($table_name, 0, strlen('dbtable_')) === 'dbtable_') { $table_name = substr($table_name, strlen('dbtable_')); } $this->_table_name = $table_name; } return $this->_table_name; } /** * Initialize dbtable */ public function init() {} /** * Add column to DbTable * * @param string $name Column name * @param array $column Column properties * @return DbTable */ public function add_column($name, array $column) { $this->_columns[$name] = $column; return $this; } /** * Add virtual column to DbTable * * @param string $name Column name * @param array $column Column properties * @return DbTable */ public function add_virtual_column($name, array $column) { $this->_virtual_columns[$name] = $column; return $this; } /** * @param string $name * @return boolean */ public function has_column($name) { return isset($this->_columns[$name]); } /** * @param string $name * @return boolean */ public function has_virtual_column($name) { return isset($this->_virtual_columns[$name]); } /** * Get column info * * @param string $name * @return array */ public function get_column($name) { if (isset($this->_columns[$name])) { return $this->_columns[$name]; } else { return NULL; } } /** * Get virtual column info * * @param string $name * @return array */ public function get_virtual_column($name) { if (isset($this->_virtual_columns[$name])) { return $this->_virtual_columns[$name]; } else { return NULL; } } /** * Add table option (such as ENGINE, AUTO_INCREMENT, ...) * * @param string $name * @param string $value * @return DbTable */ public function add_option($name, $value) { $this->_options[$name] = $value; return $this; } /** * Automatically create table, add or remove columns */ public function sync_with_db() { $table_name = $this->table_name(); if (!empty($this->_config['auto_create']) && ! in_array($table_name, self::$_tables_created)) { if ( ! in_array($this->get_db()->table_prefix() . $table_name, $this->get_db()->list_tables())) { // Create database table automatically, if not already exists $this->create_table(); self::$_tables_created[] = $table_name; } } if (!empty($this->_config['auto_update']) && ! in_array($table_name, self::$_tables_updated)) { // Automatically update table columns when mapper columns change $this->update_table(); self::$_tables_updated[] = $table_name; } } /** * Create table schema in database */ public function create_table() { list($columns, $indexes, $options) = $this->get_metadata(); $this->get_db()->create_table($this->table_name(), $columns, $indexes, $options); } /** * Update table schema in database */ public function update_table() { list($db_columns, $db_indexes) = $this->get_db()->describe_table($this->table_name()); list($columns, $indexes, $options) = $this->get_metadata(); $columns_to_drop = array_diff_key($db_columns, $columns); $columns_to_add = array_diff_key($columns, $db_columns); $indexes_to_drop = array_diff_key($db_indexes, $indexes); $indexes_to_add = array_diff_key($indexes, $db_indexes); $this->get_db()->alter_table( $this->table_name(), $columns_to_add, $columns_to_drop, $indexes_to_add, $indexes_to_drop ); } /** * Truncate table */ public function truncate_table() { $table = $this->get_db()->quote_table($this->table_name()); $this->get_db()->query(Database::DELETE, "TRUNCATE $table", FALSE); } /** * Parses _columns and _indexes into mysql-compatible format * * @return array Columns metadata, Indexes metadata */ public function get_metadata() { if ($this->_columns_metadata === NULL || $this->_indexes_metadata === NULL) { $this->_columns_metadata = array(); $this->_indexes_metadata = array(); // Parsing columns foreach ($this->_columns as $name => $column) { $key = isset($column['Key']) ? $column['Key'] : NULL; $column['Field'] = $name; unset($column['key']); $column['Type'] = $this->_sqlize_column_type($column['Type']); // Add column to columns metadata $this->_columns_metadata[$name] = $column; // Add corresponding index if (isset($key)) { switch (strtolower($key)) { case 'pri': case 'primary': // Add primary key $this->_indexes_metadata['PRIMARY'] = array( 'Key_name' => 'PRIMARY', 'Column_names' => array($name), 'Non_unique' => 0 ); $this->_pk = $name; break; case 'uni': case 'unique': // Add unique index $this->_indexes_metadata[$name] = array( 'Key_name' => $name, 'Column_names' => array($name), 'Non_unique' => 0 ); break; case 'key': case 'ind': case 'mul': case 'index': // Add index $this->_indexes_metadata[$name] = array( 'Key_name' => $name, 'Column_names' => array($name), 'Non_unique' => 1 ); break; default: throw new Exception('Unknown index type ":key" for column ":name"', array(':key' => $key, ':name' => $name) ); } } } // end of parsing columns // Parsing indexes foreach ($this->_indexes as $name => $index) { $index['Key_name'] = $name; if (!isset($index['Non_unique'])) { // Make index non unique by default $index['Non_unique'] = 1; } $this->_indexes_metadata[$name] = $index; } } return array($this->_columns_metadata, $this->_indexes_metadata, $this->_options); } /** * Gets name of primary key. * If $required and there is no pimary key then an exception is thrown. * * @param boolean $required * @return string */ public function get_pk($required = TRUE) { if ($this->_pk === NULL) { foreach ($this->_columns as $name => $column) { if (isset($column['Key']) && in_array(strtolower($column['Key']), array('pri', 'primary'))) { $this->_pk = $name; } } } if ($this->_pk === NULL && $required) { throw new Kohana_Exception('Unable to find primary key column for table :table', array(':table' => $this->table_name()) ); } return $this->_pk; } /** * Insert new row in database table * * @param array $values Values to insert * @return integer Id of inserted row */ public function insert(array $values) { // Leave values only for known columns foreach ($values as $name => $value) { if ( ! isset($this->_columns[$name])) { unset($values[$name]); } } // Make values ready to be stored in database $values = $this->_sqlize($values); $query = DB::insert($this->table_name()) ->columns(array_keys($values)) ->values(array_values($values)); list($id) = $query->execute($this->get_db()); return $id; } /** * Updates existing row * * @param array $values * @param string|array|Database_Expression_Where $condition */ public function update(array $values, $condition = NULL) { $condition = $this->_prepare_condition($condition); // Leave values only for known columns foreach ($values as $name => $value) { if ( ! isset($this->_columns[$name])) { unset($values[$name]); } } // Make values ready to be stored in database $values = $this->_sqlize($values); $query = DB::update($this->table_name()) ->set($values); if ($condition !== NULL) { $query->where($condition, NULL, NULL); } $query ->execute($this->get_db()); } /** * Fetchs multiple rows from db * * @param string|array|Database_Expression_Where $condition * @param array $params Additional params * @param Database_Query_Builder_Select $query Custom query to execute * @return array */ public function select($condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { if ($query === NULL) { $columns = $this->_prepare_columns($params); $query = new Database_Query_Builder_Select($columns); $query->from($this->table_name()); } $condition = $this->_prepare_condition($condition); if ($condition !== NULL) { $query->where($condition, NULL, NULL); } // Add limit, offset and order by statements if (isset($params['known_columns'])) { $known_columns = $params['known_columns']; } else { $known_columns = array(); } $this->_std_select_params($query, $params, $known_columns); // Execute the query $result = $query->execute($this->get_db()); $data = array(); if (count($result)) { $key = isset($params['key']) ? $params['key'] : FALSE; // Convert to correct types foreach ($result as $values) { $values = $this->_unsqlize($values); if ($key && isset($values[$key])) { $data[$values[$key]] = $values; } else { $data[] = $values; } } } return $data; } /** * Fetch only one row from database * * @param string|array|Database_Expression_Where $condition * @param array $params Additional params * @param Database_Query_Builder_Select $query Custom query to execute * @return array */ public function select_row($condition = NULL, array $params = NULL, Database_Query_Builder_Select $query = NULL) { // Limit to one row $params['limit'] = 1; $result = $this->select($condition, $params, $query); if (count($result)) { $result = $result[0]; } return $result; } /** * Delete rows from table by condition * * @param string|array|Database_Expression_Where $condition */ public function delete_rows($condition = NULL) { $query = DB::delete($this->table_name()); if ($condition !== NULL) { $condition = $this->_prepare_condition($condition); $query->where($condition, NULL, NULL); } $query->execute($this->get_db()); } /** * Counts rows in table that satisfy given condition * * @param string|array|Database_Expression_Where $condition * @param array $params * @return integer */ public function count_rows($condition = NULL, array $params = NULL) { $query = DB::select(array('COUNT("*")', 'total_count')) ->from($this->table_name()); if ($condition !== NULL) { $condition = $this->_prepare_condition($condition); $query->where($condition, NULL, NULL); } $this->_std_select_params($query, $params); $count = $query->execute($this->get_db()) ->get('total_count'); return (int) $count; } /** * Check that rows with given conditions exists in table * * @param string|array|Database_Expression_Where $condition * @return boolean */ public function exists($condition = NULL) { $query = DB::select() ->from($this->table_name()); if ($condition !== NULL) { $condition = $this->_prepare_condition($condition); $query->where($condition, NULL, NULL); } $result = DB::select(array(DB::expr('EXISTS (' . $query->compile($this->get_db()) . ')'), 'row_exists')) ->execute($this->get_db()) ->get('row_exists'); return (bool) $result; } /** * Lock table for writing */ public function lock() { $this->get_db()->query(NULL, "LOCK TABLE " . $this->get_db()->quote_table($this->table_name()) . " WRITE", FALSE); } /** * Unlock tables */ public function unlock() { $this->get_db()->query(NULL, "UNLOCK TABLES", FALSE); } /** * Return database column type that will be used for specified mapper column type * * @param string $type Mapper column type * @return string */ protected function _sqlize_column_type($type) { $info = $this->_parse_column_type($type); switch ($info['type']) { case 'boolean': return 'tinyint(1)'; case 'array': return 'text'; case 'money': return 'bigint'; case 'unix_timestamp': return 'int unsigned'; default: return $type; } } /** * Parses given mapper column type and returns information in array * * @param string $type * @return array */ protected function _parse_column_type($type) { if ( ! isset(self::$_types_info_cache[$type])) { if ( ! preg_match('/^(?P<type>\w+)(\((?P<size>\d+)\))?(?P<attributes>(\s+(\w+))*)$/', $type, $matches)) { throw new Exception('Unable to parse column type ":type"', array(':type' => $type) ); } $info = array(); foreach ($matches as $key => $value) { if (is_int($key)) { // Skip all numeric keys continue; } $info[$key] = $value; } $info['type'] = strtolower($info['type']); if (isset($info['attributes'])) { $info['attributes'] = preg_split('/\s+/', $info['attributes'], NULL, PREG_SPLIT_NO_EMPTY); } self::$_types_info_cache[$type] = $info; } return self::$_types_info_cache[$type]; } /** * Prepare values for storing in database * * @param array $values * @return array */ protected function _sqlize($values) { foreach (array_keys($this->_columns) as $name) { if (isset($values[$name])) { $values[$name] = $this->_sqlize_value($values[$name], $name); } } return $values; } /** * Convert model values to the actual types, specified in _columns. * * @param array $values * @return array */ protected function _unsqlize($values) { foreach ((array_merge(array_keys($this->_columns), array_keys($this->_virtual_columns))) as $name) { if (isset($values[$name])) { $values[$name] = $this->_unsqlize_value($values[$name], $name); } } return $values; } /** * Converts value to type of the specified column. * * @param mixed $value * @param string $column_name Column name * @return mixed */ protected function _unsqlize_value($value, $column_name) { if ( ! isset($this->_columns[$column_name]) && ! isset($this->_virtual_columns[$column_name])) { throw new Exception('Unknown column specified :column_name', array(':column_name' => $column_name) ); } if (isset($this->_columns[$column_name])) { $column = $this->_columns[$column_name]; } else { $column = $this->_virtual_columns[$column_name]; } $type_info = $this->_parse_column_type($column['Type']); switch ($type_info['type']) { case 'boolean': return (bool) $value; case 'bigint': case 'int': case 'smallint': case 'tinyint': return (int) $value; case 'float': return (float) $value; case 'array': if ($value === NULL || $value === '') { return array(); } else { return unserialize($value); } case 'money': $money = new Money(); $money->set_raw_amount($value); return $money; case 'datetime': case 'date': // Datetime values are stored in UTC+0 timezone in database $value = new DateTime($value, new DateTimeZone('UTC')); // Convert to application timezone $value->setTimezone(new DateTimeZone(date_default_timezone_get())); default: return $value; } } /** * Prepare value of specific column to be stored in database * * @param mixed $value * @param string $column_name Column name * @return string */ protected function _sqlize_value($value, $column_name) { if ( ! isset($this->_columns[$column_name]) && ! isset($this->_virtual_columns[$column_name])) { throw new Kohana_Exception('Unknown column specified :column_name', array(':column_name' => $column_name) ); } if ($value instanceof Database_Expression) { // Do not touch database expressions return $value; } if (isset($this->_columns[$column_name])) { $column = $this->_columns[$column_name]; } else { $column = $this->_virtual_columns[$column_name]; } $type_info = $this->_parse_column_type($column['Type']); switch ($type_info['type']) { case 'boolean': case 'bigint': case 'int': case 'smallint': case 'tinyint': $value = (int) $value; break; case 'float': case 'double': // Force '.' to be a decimal separator $value = str_replace(',', '.', (string) $value); break; case 'array': if (is_array($value)) { foreach ($value as $value_key => $value_val) { if ($value_val == '') unset($value[$value_key]); } } $value = serialize($value); break; case 'money': if ($value instanceof Money) { $value = $value->raw_amount; } break; case 'unix_timestamp': if ($value === '') { // Allow not-specified dates $value = NULL; } else { $value = (int) $value; } break; case 'datetime': if ($value instanceof DateTime || $value instanceof Date) { // Convert to UTC+0 timezone $value->setTimezone(new DateTimeZone('UTC')); $value = $value->format(Kohana::config('datetime.db_datetime_format')); } else { $value = (string) $value; } break; case 'date': if ($value instanceof DateTime || $value instanceof Date) { // Convert to UTC+0 timezone $value->setTimezone(new DateTimeZone('UTC')); $value = $value->format(Kohana::config('datetime.db_date_format')); } else { $value = (string) $value; } break; default: $value = (string) $value; } return $value; } /** * Apply standart select parameters (such offset, limit, order_by, etc..) to query * * @param $query * @param array $params */ protected function _std_select_params(Database_Query_Builder_Select $query, array $params = NULL, $known_columns = array()) { if (isset($params['order_by'])) { if ( ! is_array($params['order_by'])) { $order_by = array($params['order_by'] => ! empty($params['desc'])); } else { // Several order by expressions $order_by = $params['order_by']; } //@TODO: allow order by on unknown columns foreach ($order_by as $column => $desc) { if (isset($this->_columns[$column]) || isset($this->_virtual_columns[$column]) || in_array($column, $known_columns)) { $query->order_by($column, $desc ? 'DESC' : 'ASC'); } } } if ( ! empty($params['offset'])) { $query->offset((int) $params['offset']); if (empty($params['limit'])) { $query->limit(65535); } } if ( ! empty($params['limit'])) { $query->limit((int) $params['limit']); } return $query; } /** * Prepare columns for SELECT query from params * * @param array $params * @return array */ protected function _prepare_columns(array $params = NULL) { $table = $this->table_name(); if (isset($params['columns'])) { // Explicitly specify table name for columns // to avoid "column is ambiguous" issue $columns = array(); foreach ($params['columns'] as $column) { if (strpos($column, '.') === FALSE) { $columns[] = "$table.$column"; } else { $columns[] = $column; } } } else { $columns = array("$table.*"); } return $columns; } /** * Convert specified condition (string, array, Database_Expression_Where) * to the Database_Expression_Where object * * @param string|array|Database_Expression_Where $condition * @return Database_Expression_Where */ protected function _prepare_condition($condition) { if (is_string($condition)) { throw new Kohana_Exception('String conditions are not yet implemented'); } elseif (is_array($condition)) { $condition = $this->_array_to_condition($condition); } return $condition; } /** * Convert an array of column names and values (array(column=>value)) to criteria * using AND logic * * @param array $condition * @return Database_Expression_Where */ protected function _array_to_condition(array $condition) { if (empty($condition)) return NULL; $table = $this->table_name(); $where = DB::where(); foreach ($condition as $column => $value) { if (is_array($value)) { $op = $value[0]; $value = $value[1]; } else { $op = '='; } if (strpos($column, '.') === FALSE && $this->has_column($column)) { $column = "$table.$column"; } $where->and_where($column, $op, $value); } return $where; } /** * Returns hash for select parameters (useful when caching results of a select) * * @param array $params * @param Database_Expression_Where $condition * @return string */ public function params_hash(array $params = NULL, Database_Expression_Where $condition = NULL) { if (empty($params['desc'])) { $params['desc'] = FALSE; } if (empty($params['offset'])) { $params['offset'] = 0; } if (empty($params['limit'])) { $params['limit'] = 0; } if ($condition !== NULL) { $params['condition'] = (string) $condition; } $str = ''; foreach ($params as $k => $v) { if (is_array($v)) { foreach ($v as $vs) { $str .= $k . $vs; } } else { $str .= $k . $v; } } return substr(md5($str), 0, 16); } }<file_sep>/modules/shop/catalog/classes/controller/backend/products.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Products extends Controller_BackendRES { /** * Configure actions * @return array */ public function setup_actions() { $this->_model = 'Model_Product'; $this->_view = 'backend/form_adv'; $this->_form = 'Form_Backend_Product'; return array( 'create' => array( 'view_caption' => 'Создание анонса', ), 'update' => array( 'view_caption' => 'Редактирование анонса ":caption"', 'message_ok' => 'Укажите дополнительные характеристики анонса' ), 'delete' => array( 'view_caption' => 'Удаление анонса', 'message' => 'Удалить анонс ":caption"?' ), 'multi_delete' => array( 'view_caption' => 'Удаление анонсов', 'message' => 'Удалить выбранные анонсы?', 'message_empty' => 'Выберите хотя бы один анонс!' ), ); } /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('catalog') . '/public/css/backend/catalog.css'); // Add catalog js scripts if ($this->request->action == 'index' || $this->request->action == 'products_select') { $layout->add_script(Modules::uri('catalog') . '/public/js/backend/catalog.js'); $layout->add_script( "var branch_toggle_url = '" . URL::to('backend/catalog/sections', array( 'action' => 'toggle', 'id' => '{{id}}', 'toggle' => '{{toggle}}') ) . '?context=' . $this->request->uri . "';" , TRUE); } if ($this->request->action == 'product_select') { // Add product select js scripts $layout->add_script(Modules::uri('catalog') . '/public/js/backend/product_select.js'); $layout->add_script( "var product_selected_url = '" . URL::to('backend/catalog', array('action' => 'product_selected', 'product_id' => '{{id}}')) . "';" , TRUE); } return $layout; } /** * Prepare product for create/update/delete action * * @param string $action * @param string|Model_Product $product * @param array $params * @return Model_Product */ protected function _model($action, $product, array $params = NULL) { $product = parent::_model($action, $product, $params); if ($action == 'create') { $product->section_id = Model_Section::EVENT_ID; } return $product; } /** * Generate redirect url * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ /** * Generate redirect url * * @param string $action * @param Model $model * @param Form $form * @param array $params * @return string */ protected function _redirect_uri($action, Model $model = NULL, Form $form = NULL, array $params = NULL) { if ($action == 'create') { return URL::uri_self(array('action'=>'update', 'id' => $model->id, 'history' => $this->request->param('history'))) . '?flash=ok'; } if ($action == 'update') { return URL::uri_to('backend/catalog/products'); } if ($action == 'multi_link') { return URL::uri_back(); } return parent::_redirect_uri($action, $model, $form, $params); } /** * Link several products to sections */ public function action_multi_link() { $this->_action_multi('multi_link'); } /** * Link several products to sections * * @param array $models * @param Form $form * @param array $params */ protected function _execute_multi_link(array $models, Form $form, array $params = NULL) { $values = $form->get_values(); // Find sections to which products will be linked $sections = array(); $captions = ''; foreach ($values['section_ids'] as $sectiongroup_id => $section_id) { if ( ! empty($section_id)) { $section = new Model_Section(); $section->find((int) $section_id, array('columns' => array('id', 'lft', 'rgt', 'level', 'sectiongroup_id', 'caption'))); if (isset($section->id)) { $sections[$section->id] = $section; $captions .= '"' . $section->caption . '" , '; } } } if ($values['mode'] == 'link_main' && count($sections) > 1) { $form->error('Пожалуйста выберите только одну группу категорий!'); return; } $result = TRUE; foreach ($models as $model) { foreach ($sections as $section) { $model->link($values['mode'], $section); } if ($model->has_errors()) { $form->errors($model->errors()); $result = FALSE; } } Model::fly('Model_Section')->mapper()->update_products_count(); if ( ! $result) return; $captions = trim($captions, ' ,'); switch ($values['mode']) { case 'link': FlashMessages::add('События были привязаны к разделам ' . $captions); break; case 'link_main': FlashMessages::add('Раздел ' . $captions . ' был сделан основным для выбранных событий'); break; case 'unlink': FlashMessages::add('События были успешно отвязаны от разделов ' . $captions); break; } $this->request->redirect($this->_redirect_uri('multi_link', $model, $form, $params)); } protected function _form($action,Model $model,array $params = NULL) { $form = parent::_form($action,$model,$params); if ($action == 'create' || $action == 'update') { $lecturer_id = $this->request->param('lecturer_id', NULL); if ($lecturer_id !== NULL) { $form->get_element('lecturer_id')->set_value($lecturer_id); $form->get_element('lecturer_name')->set_value(Model::fly('Model_Lecturer')->find($lecturer_id)->name); } } return $form; } /** * Render list of products and sections menu */ public function action_index() { if (Model_SectionGroup::current()->id === NULL) { $this->_action_error('Создайте хотя бы одну группу категорий!'); return; } $view = new View('backend/workspace_2col'); $view->column1 = $this->request->get_controller('sections')->widget_sections_menu(); $view->column2 = $this->widget_products(); $layout = $this->prepare_layout(); $layout->content = $view; $this->request->response = $layout->render(); } /** * Renders list of products * * @param boolean $seelct * @return string */ public function widget_products($view = 'backend/products') { // current site $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } $sectiongroup = Model_SectionGroup::current(); $section = Model_Section::current(); // products search form $search_form = $this->widget_search(); // ----- List of products $product = Model::fly('Model_Product'); // build search condition $search_params = $search_form->get_values(); $search_params['search_fields'] = array( 'caption', 'description'); //$search_params['site_id'] = $site_id; $search_params['sectiongroup'] = $sectiongroup; $search_params['section'] = $section; list($search_condition, $params) = $product->search_condition($search_params); // count & find products by search condition $per_page = 20; $count = $product->count_by($search_condition, $params); $pagination = new Paginator($count, $per_page); $order_by = $this->request->param('cat_porder', 'caption'); $desc = (bool) $this->request->param('cat_pdesc', '0'); $params['offset'] = $pagination->offset; $params['limit'] = $pagination->limit; $params['order_by'] = $order_by; $params['desc'] = $desc; $products = $product->find_all_by($search_condition, $params); // Set up view $view = new View($view); $view->search_form = $search_form; $view->order_by = $order_by; $view->desc = $desc; $view->section = $section; $view->sectiongroup = $sectiongroup; $view->products = $products; $view->pagination = $pagination->render('backend/pagination'); return $view->render(); } /** * Render product search form * * @return Form_Backend_SearchProducts */ public function widget_search() { $search_form = new Form_Backend_SearchProducts(); $search_form->set_defaults(array( 'search_text' => URL::decode($this->request->param('search_text')), 'active' => $this->request->param('active') )); if ($search_form->is_submitted()) { $params = $search_form->get_values(); $params['search_text'] = URL::encode($params['search_text']); $this->request->redirect(URL::uri_self($params)); } return $search_form; } /** * Redraw product properties via ajax request */ public function action_ajax_properties() { $product = new Model_Product(); $product->find((int) $this->request->param('id')); if (isset($_GET['section_id'])) { $product->section_id = (int) $_GET['section_id']; } $form_class = $this->_form; $form = new $form_class($product); $component = $form->find_component('props'); if ($component) { $this->request->response = $component->render(); } } /** * Handles the selection of additional sections for product */ public function action_sections_select() { if ( ! empty($_POST['ids']) && is_array($_POST['ids'])) { $section_ids = ''; foreach ($_POST['ids'] as $section_id) { $section_ids .= (int) $section_id . '_'; } $section_ids = trim($section_ids, '_'); $this->request->redirect(URL::uri_back(NULL, 1, array('cat_section_ids' => $section_ids))); } else { // No sections were selected $this->request->redirect(URL::uri_back()); } } /** * This action is executed via ajax request after additional * sections for product have been selected. * * It redraws the "additional sections" form element accordingly */ public function action_ajax_sections_select() { if ($this->request->param('cat_section_ids') != '') { $action = ((int)$this->request->param('id') == 0) ? 'create' : 'update'; $product = $this->_model($action, 'Model_Product'); $form = $this->_form($action, $product); $component = $form->find_component('additional_sections[' . (int) $this->request->param('cat_sectiongroup_id') . ']'); if ($component) { $this->request->response = $component->render(); } } } /** * This action is executed via ajax request after access * towns for event have been selected. * * It redraws the "access towns" form element accordingly */ public function action_ajax_towns_select() { if ($this->request->param('access_town_ids') != '') { $action = ((int)$this->request->param('id') == 0) ? 'create' : 'update'; $product = $this->_prepare_model($action); $form = $this->_prepare_form($action, $product); $component = $form->find_component('access_towns'); if ($component) { $this->request->response = $component->render(); } } } /** * This action is executed via ajax request after access * organizers for event have been selected. * * It redraws the "access organizers" form element accordingly */ public function action_ajax_organizers_select() { if ($this->request->param('access_organizer_ids') != '') { $action = ((int)$this->request->param('id') == 0) ? 'create' : 'update'; $product = $this->_prepare_model($action); $form = $this->_prepare_form($action, $product); $component = $form->find_component('access_organizers'); if ($component) { $this->request->response = $component->render(); } } } /** * This action is executed via ajax request after access * organizers for event have been selected. * * It redraws the "access organizers" form element accordingly */ public function action_ajax_users_select() { if ($this->request->param('access_user_ids') != '') { $action = ((int)$this->request->param('id') == 0) ? 'create' : 'update'; $product = $this->_prepare_model($action); $form = $this->_prepare_form($action, $product); $component = $form->find_component('access_users'); if ($component) { $this->request->response = $component->render(); } } } /** * Select several products */ public function action_products_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор событий на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_products_select(); } else { $view = $this->widget_products_select(); $view->caption = 'Выбор событий на портале "' . Model_Site::current()->caption . '"'; $layout->content = $view->render(); } $this->request->response = $layout->render(); } /** * Render products and sections for the selection of one product */ public function widget_products_select() { $view = new View('backend/workspace_2col'); $view->column1 = $this->request->get_controller('sections')->widget_sections_menu(); $view->column2 = $this->widget_products('backend/products/select'); return $view; } }<file_sep>/modules/shop/orders/classes/model/order.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Order extends Model { /** * Back up properties before changing (for logging) */ public $backup = TRUE; /** * Default site id for order * * @return integer */ public function default_site_id() { return Model_Site::current()->id; } /** * Default status id for new orders * * @return integer */ public function default_status_id() { return Model_OrderStatus::STATUS_NEW; } /** * Get status caption * * @return string */ public function get_status_caption() { return Model_OrderStatus::caption($this->status_id); } /** * Site caption * * @return string */ public function get_site_caption() { return Model_Site::caption($this->site_id); } /** * Return the date when the order was created * @return string */ public function get_date_created() { return date('Y-m-d', $this->created_at); } /** * Return the date and time when the order was created * @return string */ public function get_datetime_created() { return date('Y-m-d H:i:s', $this->created_at); } /** * Get products for this order */ public function get_products() { if ( ! isset($this->_properties['products'])) { $this->_properties['products'] = Model::fly('Model_CartProduct')->find_all_by_cart_id((int) $this->id); } return $this->_properties['products']; } /** * Get comments for this order */ public function get_comments() { return Model::fly('Model_OrderComment')->find_all_by_order_id((int) $this->id); } // ------------------------------------------------------------------------- // Summaries // ------------------------------------------------------------------------- /** * Calculate total price of all products in order * * @return Money */ public function calculate_sum() { $sum = new Money(); foreach ($this->products as $product) { $sum->add($product->price->mul($product->quantity)); } return $sum; } /** * Get "bare" total price of all products in order (without any additional fees) * * @return Money */ public function get_sum() { if ( ! isset($this->_properties['sum'])) { $sum = $this->calculate_sum(); $this->_properties['sum'] = $sum; } return $this->_properties['sum']; } /** * Get final total sum for the order * * @return Money */ public function get_total_sum() { return $this->sum; } /** * Get total quantity of all products in order * * @return integer */ public function get_total_quantity() { $total_quantity = 0; foreach ($this->products as $cartproduct) { $total_quantity += $cartproduct->quantity; } return $total_quantity; } // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- /** * Save model and log changes * * @param boolean $force_create * @param boolean $log_changes */ public function save($force_create = FALSE, $log_changes = TRUE) { // Recalculate summaries, so they are stored in model properties and will be stored in db $this->sum = $this->calculate_sum(); parent::save($force_create); // Save new products (used when order is submitted in frontend) foreach ($this->products as $cartproduct) { if ( ! isset($cartproduct->id)) { $cartproduct->cart_id = $this->id; $cartproduct->save(); } } if ($log_changes) { $this->log_changes($this, $this->previous()); } } /** * Delete order */ public function delete() { $id = $this->id; // Delete products from order Model::fly('Model_CartProduct')->delete_all_by_cart_id($this->id); //@TODO: delete comments for this order parent::delete(); $this->log_delete($id); } /** * Send e-mail notification about created order */ public function notify() { try { $settings = Model_Site::current()->settings; $email_to = isset($settings['email']['to']) ? $settings['email']['to'] : ''; $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; if ($email_sender != '') { $email_from = array($email_from => $email_sender); } if ($email_to != '' || $this->email != '') { // Init mailer SwiftMailer::init(); $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); if ($email_to != '') { // --- Send message to administrator $message = Swift_Message::newInstance() ->setSubject('Новый заказ с сайта ' . URL::base(FALSE, TRUE)) ->setFrom($email_from) ->setTo($email_to); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate('mail/order_admin'); $message->setBody($template->render(array( 'order' => $this, 'products' => $this->products ))); // Send message $mailer->send($message); } if ($this->email != '') { // --- Send message to client var_dump($email_from); die(); $message = Swift_Message::newInstance() ->setSubject('Ваш заказ в интернет магазине ' . URL::base(FALSE, TRUE)) ->setFrom($email_from) ->setTo($this->email); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate('mail/order_client'); $body = $template->render(array( 'order' => $this, 'products' => $this->products )); if ($signature != '') { $body .= "\n\n\n" . $signature; } $message->setBody($body); // Send message $mailer->send($message); } } } catch (Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { throw $e; } } } //-------------------------------------------------------------------------- // Log //-------------------------------------------------------------------------- /** * Log order changes * * @param Model_Order $new_order * @param Model_Order $old_order */ public function log_changes(Model_Order $new_order, Model_Order $old_order) { $fields = array( array('name' => 'status_id', 'displayed' => 'status_caption', 'caption' => 'Статус'), array('name' => 'name', 'caption' => 'Имя пользователя'), array('name' => 'phone', 'caption' => 'Телефон'), array('name' => 'email', 'caption' => 'E-Mail'), array('name' => 'address', 'caption' => 'Адрес доставки'), array('name' => 'comment', 'caption' => 'Комментарий к заказу'), ); $text = ''; $created = ! isset($old_order->id); $has_changes = FALSE; if ($created) { $text .= '<strong>Создан новый заказ № {{id-' . $new_order->id . "}}</strong>\n"; } else { $text .= '<strong>Изменён заказ № {{id-' . $new_order->id . "}}</strong>\n"; } // Log field changes foreach ($fields as $field) { $name = $field['name']; $displayed = isset($field['displayed']) ? $field['displayed'] : $name; $caption = $field['caption']; if ($created) { $text .= Model_History::changes_text($caption, $new_order->$displayed); } elseif ($old_order->$name != $new_order->$name) { $text .= Model_History::changes_text($caption, $new_order->$displayed, $old_order->$displayed); $has_changes = TRUE; } } if ($created || $has_changes) { // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $new_order->id; $history->item_type = 'order'; $history->save(); } } /** * Log the deletion of order * * @param integer $order_id */ public function log_delete($order_id) { $text = 'Удалён заказ № {{id-' . $order_id . '}}'; // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $order_id; $history->item_type = 'order'; $history->save(); } }<file_sep>/modules/general/flash/classes/form/backend/flashblock.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Flashblock extends Form_Backend { /** * Initialize form fields */ public function init() { // Set html class $this->attribute('class', 'w99per'); $cols = new Form_Fieldset_Columns('cols', array('column_classes' => array(1 => 'w55per'))); // ----- "general" tab $this->add_component($cols); // ----- Name $options = Kohana::config('flashblocks.names'); if (empty($options)) { $options = array(); } $element = new Form_Element_Select('name', $options, array('label' => 'Положение', 'required' => TRUE), array('maxlength' => 15)); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $cols->add_component($element); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Название'), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $cols->add_component($element); // ----- File $element = new Form_Element_File( 'file', array('label' => 'SWF Flash File') ); $element->add_validator(new Form_Validator_File()); $cols->add_component($element); // ----- Width $element = new Form_Element_Integer('width', array('label' => 'Ширина', 'required' => TRUE)); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Integer(1, NULL, FALSE)); $cols->add_component($element); // ----- Height $element = new Form_Element_Integer('height', array('label' => 'Высота', 'required' => TRUE)); $element ->add_filter(new Form_Filter_Trim()) ->add_validator(new Form_Validator_Integer(1, NULL, FALSE)); $cols->add_component($element); // ----- Version $element = new Form_Element_Input('version', array('label' => 'Поддерживаемая версия', 'required' => TRUE), array('maxlength' => 16) ); $element ->add_validator(new Form_Validator_Regexp('/^\d+\.\d+\.\d+$/', array( Form_Validator_Regexp::NOT_MATCH => 'Данной версии Flash плеера не существует' ), TRUE, TRUE )); $element->comment = 'формат: "major.minor.release"'; $cols->add_component($element); // ----- Flashvars $element = new Form_Element_Options("flashvars", array('label' => 'Flashvars', 'options_count' => 1,'options_count_param' => 'options_count1'), array('maxlength' => Model_Flashblock::MAXLENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Flashblock::MAXLENGTH)); $cols->add_component($element); // ----- Params $element = new Form_Element_Options("params", array('label' => 'Params', 'options_count' => 1,'options_count_param' => 'options_count2'), array('maxlength' => Model_Flashblock::MAXLENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Flashblock::MAXLENGTH)); $cols->add_component($element); // ----- Attributes $element = new Form_Element_Options("attributes", array('label' => 'Attributes', 'options_count' => 1,'options_count_param' => 'options_count3'), array('maxlength' => Model_Flashblock::MAXLENGTH) ); $element ->add_filter(new Form_Filter_TrimCrop(Model_Flashblock::MAXLENGTH)); $cols->add_component($element); // ----- "visibility" column // ----- Default_visibility $element = new Form_Element_Checkbox('default_visibility', array('label' => 'Блок отображается на новых страницах')); $cols->add_component($element,2); // ----- Nodes visibility $nodes = Model::fly('Model_Node')->find_all_by_site_id($this->model()->site_id, array('order_by' => 'lft')); $options = array(); foreach ($nodes as $node) { $options[$node->id] = str_repeat('&nbsp;', ((int)$node->level - 1) * 4) . $node->caption; } $element = new Form_Element_CheckSelect('nodes_visibility', $options, array('label' => 'Отображать на страницах', 'default_selected' => $this->model()->default_visibility) ); $element->config_entry = 'checkselect_fieldset'; $cols->add_component($element,2); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/application/views/layouts/default.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require('_header_new.php'); ?> <body> <header> <div class="mainheader"> <div class="container"> <div class="row"> <div class="span2"> <a href="<?php echo URL::site()?>" class="logo pull-left"></a> </div> <div class="span6"> <?php echo Widget::render_widget('menus','menu', 'main'); ?> </div> <div class="span4"> <div class="b-auth-search"> <?php echo Widget::render_widget('products', 'search');?> </div> </div> </div> </div> </div> <div class="subheader"> <div class="container"> <div class="row"> <div class="span2"> </div> <div class="span6"> <ul class="second-menu"> <?php echo Widget::render_widget('towns','select'); ?> <?php echo Widget::render_widget('products','format_select'); ?> <?php echo Widget::render_widget('products','theme_select'); ?> <?php echo Widget::render_widget('products','calendar_select'); ?> </ul> </div> <div class="span4"> <div class="login-form"> <?php echo Widget::render_widget('acl', 'login'); ?> </div> </div> </div> </div> </div> </header> <div id="main"> <div class="container"> <div class="row"> <div class="span8"> <div class="wrapper main-list" id="events_show"> <?php echo $view->placeholder('payment'); ?> <?php echo $content; ?> </div> </div> <aside class="span4"> <div class="right-block wrapper"> <h1 class="main-title"><span>Что такое vsё.to</span></h1> <div class="right-block-content"> <?php echo Widget::render_widget('blocks', 'block', 'short_about'); ?> </div> </div> <!-- <div class="right-block wrapper"> <h1 class="main-title"><span>Что такое vsё.to</span></h1> <div class="right-block-content"> <?php /*echo Widget::render_widget('blocks', 'block', 'main_page_adv');*/ ?> </div> </div> --> </aside> </div> </div> </div> </div> </div> <?php require('_footer.php'); ?> <?php echo $view->placeholder('modal'); ?> <script> jQuery(function($){ $('.help-pop').tooltip() }); </script> <!-- Reformal --> <script type="text/javascript"> var reformalOptions = { project_id: 184340, project_host: "vseto.reformal.ru", tab_orientation: "left", tab_indent: "50%", tab_bg_color: "#a93393", tab_border_color: "#FFFFFF", tab_image_url: "http://tab.reformal.ru/T9GC0LfRi9Cy0Ysg0Lgg0L%252FRgNC10LTQu9C%252B0LbQtdC90LjRjw==/FFFFFF/2a94cfe6511106e7a48d0af3904e3090/left/1/tab.png", tab_border_width: 0 }; (function() { var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'media.reformal.ru/widgets/v3/reformal.js'; document.getElementsByTagName('head')[0].appendChild(script); })(); </script><noscript><a href="http://reformal.ru"><img src="http://media.reformal.ru/reformal.png" /></a><a href="http://vseto.reformal.ru">Oтзывы и предложения для vse.to</a></noscript> </body> <file_sep>/modules/general/indexpage/classes/controller/backend/indexpage.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_IndexPage extends Controller_Backend { /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->caption = 'Главная страница'; return $layout; } /** * Edit index page */ public function action_update() { // Find page by given node id $page = new Model_Page(); $page->find_by_node_id((int) $this->request->param('node_id')); if ( ! isset($page->id)) { $this->_action_error('Указанная страница не найдена'); return; } $view = new View('backend/panel'); $view->caption = 'Главная страница'; $view->content = $this->request->get_controller('images')->widget_images('indexpage_' . $page->id, 'indexpage'); $this->request->response = $this->render_layout($view); } } <file_sep>/modules/shop/delivery_russianpost/classes/form/backend/delivery/russianpost/properties.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Delivery_RussianPost_Properties extends Form_Backend_Delivery_Properties { /** * Initialize form fields */ public function init() { $cols = new Form_Fieldset_Columns('city_and_postcode', array('column_classes' => array(NULL, 'w40per'))); $this->add_component($cols); // ----- City $element = new Form_Element_Input('city', array('label' => 'Город', 'column' => 0), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $element->autocomplete_url = URL::to('backend/countries', array('action' => 'ac_city')); $cols->add_component($element); // ----- Postcode $element = new Form_Element_Input('postcode', array('label' => 'Индекс', 'column' => 1), array('maxlength' => 63)); $element ->add_filter(new Form_Filter_TrimCrop(63)); $element->autocomplete_url = URL::to('backend/countries', array('action' => 'ac_postcode')); $cols->add_component($element); // ----- Region_id // Obtain a list of regions $regions = Model::fly('Model_Region')->find_all(array('order_by' => 'name', 'desc' => FALSE)); $options = array(); foreach ($regions as $region) { $options[$region->id] = UTF8::ucfirst($region->name); } $element = new Form_Element_Select('region_id', $options, array('label' => 'Регион')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- Address $element = new Form_Element_Textarea('address', array('label' => 'Адрес'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $this->add_component($element); } } <file_sep>/modules/general/nodes/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/nodes', new Route_Backend( 'nodes(/<action>(/<id>))' . '(/parent-<node_id>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'node_id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'nodes', 'action' => 'index', 'id' => NULL, 'node_id' => NULL, )); // ----- Add backend menu items Model_Backend_Menu::add_item(array( 'menu' => 'main', 'id' => 10, 'parent_id' => 2, 'site_required' => TRUE, 'caption' => 'Страницы', 'route' => 'backend/nodes', 'select_conds' => array( array('route' => 'backend/nodes'), array('route' => 'backend/pages'), ) )); }<file_sep>/modules/general/breadcrumbs/views/frontend/breadcrumbs.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <!-- Хлебные крошки --> <div id="navBreadCrumb"> <a href="<?php echo URL::site(''); ?>">Главная</a> <?php for ($i = 0; $i < count($breadcrumbs); $i++) { $breadcrumb = $breadcrumbs[$i]; if ($i < count($breadcrumbs) - 1) { echo '&nbsp; » <a href="' . URL::site($breadcrumb['uri']) . '">' . HTML::chars($breadcrumb['caption']) . '</a>'; } else { // Highlight last breadcrumb echo '&nbsp; » <a href="' . URL::site($breadcrumb['uri']) . '">' . '<strong>' . HTML::chars($breadcrumb['caption']) . '</strong>' . '</a>'; } } ?> </div><file_sep>/modules/shop/orders/classes/model/orderstatus/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_OrderStatus_Mapper extends Model_Mapper { /** * Cache find_all() results * @var boolean */ public $cache_find_all = FALSE; public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('caption', array('Type' => 'varchar(63)')); $this->add_column('system', array('Type' => 'boolean')); // Reserve first MAX_SYSTEM_ID ids for system statuses $this->add_option('AUTO_INCREMENT', Model_OrderStatus::MAX_SYSTEM_ID + 1); } }<file_sep>/modules/shop/acl/views/frontend/pasrecovery.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php echo '<a data-toggle="modal" href="#pasrecoveryModal">Забыли пароль?</a>'; ?><file_sep>/modules/general/chat/views/backend/dialogs.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $create_url = URL::to('backend/messages', array('action'=>'create'), TRUE); $messages_url = URL::to('backend/messages', array('action'=>'index','dialog_id' => '${id}'), TRUE); $delete_url = URL::to('backend/dialogs', array('action'=>'delete', 'id' => '{{id}}'), TRUE); $multi_action_uri = URL::uri_to('backend/dialogs', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Новое сообщение</a> </div> <?php if ($dialogs->valid()) { ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="dialogs table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'user_id' => array( 'label' => 'Собеседник', 'sortable' => FALSE ), 'message_preview' => array( 'label' => 'Сообщение', 'sortable' => FALSE ), 'date' => array( 'label' => 'Дата', 'sortable' => FALSE ) ); echo View_Helper_Admin::table_header($columns); ?> <th>&nbsp;&nbsp;&nbsp;</th> </tr> <?php foreach ($dialogs as $dialog) : $_delete_url = str_replace('{{id}}', $dialog->id, $delete_url); $_messages_url = str_replace('${id}', $dialog->id, $messages_url); ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($dialog->id); ?> </td> <?php $message = Model::fly('Model_Message')->find_by_dialog_id($dialog->id,array( 'order_by' => 'created_at', 'desc' => '0')); foreach (array_keys($columns) as $field) { switch ($field) { case 'message_preview': echo '<td id="message"><a href="' . $_messages_url . '" class="messages_select" id="dialog_' . $dialog->id. '">' . HTML::chars($message->$field) . '</a></td>'; break; case 'user_id': $user = $dialog->opponent; echo '<td>'; echo Widget::render_widget('users', 'user_card', $user); echo '</td>'; break; default: echo '<td>'; if (isset($message->$field) && trim($message->$field) !== '') { echo HTML::chars($message[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить диалог', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?> <?php } ?> <file_sep>/modules/shop/deliveries/classes/controller/backend/deliveries.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Deliveries extends Controller_Backend { /** * Create layout (proxy to orders controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('orders')->prepare_layout($layout_script); } /** * Render layout (proxy to orders controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('orders')->render_layout($content, $layout_script); } /** * Index action - renders the list of delivery types */ public function action_index() { $this->request->response = $this->render_layout($this->widget_deliveries()); } /** * Display form for selecting the desired delivery module * and redirect to the selected delivery module create action upon form submit */ public function action_create() { $form = new Form_Backend_CreateDelivery(); if ($form->is_submitted() && $form->validate()) { // Redirect to the controller of the selected delivery module $this->request->redirect(URL::uri_to('backend/deliveries', array( 'controller' => 'delivery_' . $form->get_value('module'), 'action' => 'create' ), TRUE)); } $view = new View('backend/form'); $view->caption = 'Добавление способа доставки'; $view->form = $form; $this->request->response = $this->render_layout($view); } /** * Renders list of available delivery types * * @return string */ public function widget_deliveries() { $delivery = Model::fly('Model_Delivery'); $order_by = $this->request->param('pay_order', 'id'); $desc = (bool) $this->request->param('pay_desc', '0'); // Select all payment types $deliveries = $delivery->find_all(array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/deliveries'); $view->order_by = $order_by; $view->desc = $desc; $view->deliveries = $deliveries; return $view->render(); } }<file_sep>/application/classes/model/res.php <?php defined('SYSPATH') or die('No direct script access.'); /** * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Model_Res extends Model { const ROLE_CLASS = 'Model_User'; const RESOURCE_ID = 'resource_id'; const RESOURCE_TYPE = 'resource_type'; const USER_ID = 'user_id'; const ORGANIZER_ID = 'organizer_id'; const TOWN_ID = 'town_id'; const MODE = 'mode'; const MODE_AUTHOR = 1; const MODE_READER = 2; public static $_mode_options = array( self::MODE_AUTHOR => 'Автор', self::MODE_READER => 'Читатель' ); public function get_access_users() { if (isset($this->_properties['access_users'])) { if (is_string($this->_properties['access_users'])) { // section ids were concatenated with GROUP_CONCAT $access_users = array(); $ids = explode(',', $this->_properties['access_users']); foreach ($ids as $id) { $access_users[$id] = TRUE; } $this->_properties['access_users'] = $access_users; } return $this->_properties['access_users']; } return NULL; } public function get_access_organizers() { if (isset($this->_properties['access_organizers'])) { if (is_string($this->_properties['access_organizers'])) { // section ids were concatenated with GROUP_CONCAT $access_organizers = array(); $ids = explode(',', $this->_properties['access_organizers']); foreach ($ids as $id) { $access_organizers[$id] = TRUE; } $this->_properties['access_organizers'] = $access_organizers; } return $this->_properties['access_organizers']; } return NULL; } public function get_access_towns() { if (isset($this->_properties['access_towns'])) { if (is_string($this->_properties['access_towns'])) { // section ids were concatenated with GROUP_CONCAT $access_towns = array(); $ids = explode(',', $this->_properties['access_towns']); foreach ($ids as $id) { $access_towns[$id] = TRUE; } $this->_properties['access_towns'] = $access_towns; } return $this->_properties['access_towns']; } return NULL; } public function get_user() { if (! isset($this->_properties['user'])) { $user = new Model_User(); if (isset($this->user_id)) { $user->find($this->user_id); } $this->_properties['user'] = $user; } return $this->_properties['user']; } public function validate(array $newvalues) { if (!isset($newvalues[self::USER_ID])) { if ( ! isset($this->{self::USER_ID})) { $this->error('Не указан пользователь!'); return FALSE; } else { return TRUE; } } else { if ($newvalues[self::USER_ID]=='') { $this->error('Не указан пользователь!'); return FALSE; } } return parent::validate($newvalues); } public function save($force_create = FALSE) { parent::save($force_create); $pk = $this->get_pk(); $resources = Model::fly('Model_Resource')->delete_all_by(array( 'resource_id' => $this->$pk, 'resource_type'=> get_class($this))); // author $params = array(); $params[self::RESOURCE_ID] = $this->$pk; $params[self::RESOURCE_TYPE] = get_class($this); $params[self::USER_ID] = $this->user_id; $params[self::MODE] = Model_Res::MODE_AUTHOR; $resource = new Model_Resource(); $resource->values($params); $resource->save(); // reader // access_users if (isset($this->access_users)) { $params = array(); $params[self::RESOURCE_ID] = $this->$pk; $params[self::RESOURCE_TYPE] = get_class($this); $params[self::MODE] = Model_Res::MODE_READER; foreach ($this->access_users as $access_user => $allow) { if (!(int)$allow) continue; $params[self::USER_ID] = $access_user; $resource = new Model_Resource(); $resource->values($params); $resource->save(); } } // access_organizers if (isset($this->access_organizers)) { $params = array(); $params[self::RESOURCE_ID] = $this->$pk; $params[self::RESOURCE_TYPE] = get_class($this); $params[self::MODE] = Model_Res::MODE_READER; foreach ($this->access_organizers as $access_organizer => $allow) { if (!(int)$allow) continue; $params[self::ORGANIZER_ID] = $access_organizer; $resource = new Model_Resource(); $resource->values($params); $resource->save(); } } // access_towns if (isset($this->access_towns)) { $params = array(); $params[self::RESOURCE_ID] = $this->$pk; $params[self::RESOURCE_TYPE] = get_class($this); $params[self::MODE] = Model_Res::MODE_READER; foreach ($this->access_towns as $access_town => $allow) { if (!(int)$allow) continue; $params[self::TOWN_ID] = $access_town; $resource = new Model_Resource(); $resource->values($params); $resource->save(); } } } public function delete(){ $pk = $this->get_pk(); $this->backup(); parent::delete(); $resources = Model::fly('Model_Resource')->delete_all_by(array( 'resource_id' => $this->previous()->$pk, 'resource_type'=> get_class($this))); } }<file_sep>/modules/shop/area/classes/controller/backend/area.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Area extends Controller_Backend { /** * Create layout and link module stylesheets * * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); $layout->add_style(Modules::uri('area') . '/public/css/backend/area.css'); if ($this->request->action == 'place_select') { // Add place select js scripts $layout->add_script(Modules::uri('area') . '/public/js/backend/place_select.js'); $layout->add_script( "var place_selected_url = '" . URL::to('backend/area', array('action' => 'place_selected', 'place_id' => '{{id}}')) . "';" , TRUE); } // Add area js scripts if ($this->request->action == 'select') { // Add towns select js scripts $layout->add_script(Modules::uri('area') . '/public/js/backend/towns_select.js'); } return $layout; } /** * Render layout * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { $view = new View('backend/workspace'); $view->content = $content; $layout = $this->prepare_layout($layout_script); $layout->content = $view; return $layout->render(); } /** * Select one product */ public function action_place_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор площадки на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_place_select(); } else { $view = $this->widget_place_select(); $view->caption = 'Выбор площадки на портале "' . Model_Site::current()->caption . '"'; $layout->content = $view->render(); } $this->request->response = $layout->render(); } /** * Render products and sections for the selection of one product */ public function widget_place_select() { $view = new View('backend/workspace_2col'); $view->column1 = $this->request->get_controller('towns')->widget_towns('backend/towns/town_place_select'); $view->column2 = $this->request->get_controller('places')->widget_places('backend/places/select'); return $view; } /** * Generate the response for ajax request after place is selected * to inject new values correctly into the form */ public function action_place_selected() { $place = new Model_Place(); $place->find((int) $this->request->param('place_id')); $values = $place->values(); $values['town'] = Model::fly('Model_Town')->find($place->town_id)->name; $this->request->response = JSON_encode($values); } } <file_sep>/modules/backend/classes/form/backend/element/submit.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form submit element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Backend_Element_Submit extends Form_Element_Submit { /** * Use the same templates as the standart submit element * * @return string */ public function default_config_entry() { return 'submit'; } /** * Renders submit element * * @return string */ public function render_input() { $attributes = $this->attributes(); if (isset($attributes['class'])) { $class = 'button_adv ' . $attributes['class']; } else { $class = 'button_adv'; } // $attributes['class'] = 'icon'; return '<span class="' . $class . '">' . Form_Helper::input($this->full_name, $this->label, $attributes) . '</span>'; } } <file_sep>/modules/system/database_eresus/classes/database/query/builder.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Database query builder. * Added support to specify pure * * @package Eresus * @author <NAME> (<EMAIL>) */ abstract class Database_Query_Builder extends Kohana_Database_Query_Builder { /** * Compiles an array of conditions into an SQL partial. Used for WHERE * and HAVING. * * Allow to specify WHERE conditions as Database_Query objects * * @param object Database instance * @param array condition statements * @return string */ protected function _compile_conditions(Database $db, array $conditions) { if ( ! count($conditions)) { return ''; } if ($conditions[0] instanceof Database_Expression_Where) { return $conditions[0]->compile($db); } else { return parent::compile_conditions($db, $conditions); } } }<file_sep>/modules/shop/catalog/classes/form/backend/catimport/structure.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_CatImport_Structure extends Form_Backend { /** * Initialize form fields */ public function init() { // Set HTML class $this->attribute('class', "lb150px w500px"); $this->layout = 'wide'; // ----- supplier $element = new Form_Element_Select('supplier', Model_Product::suppliers(), array('label' => 'Поставщик')); $element->add_validator(new Form_Validator_InArray(array_keys(Model_Product::suppliers()))); $this->add_component($element); // ----- file $element = new Form_Element_File('file', array('label' => 'XLS файл прайслиста')); $element->add_validator(new Form_Validator_File()); $this->add_component($element); // ----- task status $element = new Form_Element_Text('task_status'); $element->value = Widget::render_widget('tasks', 'status', 'import_structure'); $this->add_component($element); // ----- sections $fieldset = new Form_Fieldset('sections', array('label' => 'Разделы')); $this->add_component($fieldset); $fieldset->add_component(new Form_Element_Checkbox('create_sections', array('label' => 'Создавать новые разделы'))); $fieldset->add_component(new Form_Element_Checkbox('update_section_parents', array('label' => 'Перемешать разделы'))); $fieldset->add_component(new Form_Element_Checkbox('update_section_captions', array('label' => 'Обновлять названия'))); $fieldset->add_component(new Form_Element_Checkbox('update_section_descriptions', array('label' => 'Обновлять описания'))); $fieldset->add_component(new Form_Element_Checkbox('update_section_images', array('label' => 'Обновлять логотипы'))); // ----- products $fieldset = new Form_Fieldset('products', array('label' => 'Товары')); $this->add_component($fieldset); $fieldset->add_component(new Form_Element_Checkbox('create_products', array('label' => 'Создавать новые товары'))); $fieldset->add_component(new Form_Element_Checkbox('update_product_markings', array('label' => 'Обновлять артикулы'))); $fieldset->add_component(new Form_Element_Checkbox('update_product_captions', array('label' => 'Обновлять названия'))); $fieldset->add_component(new Form_Element_Checkbox('update_product_descriptions', array('label' => 'Обновлять описания'))); $fieldset->add_component(new Form_Element_Checkbox('update_product_properties', array('label' => 'Обновлять свойства товаров'))); $fieldset->add_component(new Form_Element_Checkbox('update_product_images', array('label' => 'Обновлять изображения'))); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('start', array('label' => 'Начать'), array('class' => 'button_accept') )); } } <file_sep>/modules/shop/orders/classes/controller/frontend/cart.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Cart extends Controller_Frontend { /** * Prepare layout * * @param string $layout_script * @return Layout */ public function prepare_layout($layout_script = NULL) { $layout = parent::prepare_layout($layout_script); //$layout->add_script(Modules::uri('orders') . '/public/js/frontend/cart.js'); return $layout; } /** * Add product to cart */ public function action_add_product() { $product_id = (int) $this->request->param('product_id'); $quantity = isset($_POST['quantity']) ? $_POST['quantity'] : 1; $cart = Model_Cart::session(); $product = $cart->add_product($product_id, $quantity); if ($cart->has_errors()) { FlashMessages::add_many($cart->errors()); } else { FlashMessages::add('Товар "' . $product->caption . '" добавлен в корзину'); } if ( ! Request::$is_ajax) { $this->request->redirect(URL::uri_back()); } else { $request = Widget::switch_context(); if ( ! $cart->has_errors()) { // "add to cart" button $request->get_controller('products') ->widget_add_to_cart($product, $this->request->param('widget_style')) ->to_response($this->request); // cart summary $request->get_controller('cart') ->widget_summary() ->to_response($this->request); } // encode response for an ajax request $this->_action_ajax(); } } /** * Remove product from cart */ public function action_remove_product() { $product_id = (int) $this->request->param('product_id'); $cart = Model_Cart::session(); $cart->remove_product($product_id); if ( ! Request::$is_ajax) { $this->request->redirect(URL::uri_back()); } else { // Redraw corresponding widgets $request = Widget::switch_context(); // cart contents $request->get_controller('cart') ->widget_cart() ->to_response($this->request); // cart summary $request->get_controller('cart') ->widget_summary() ->to_response($this->request); // encode response for an ajax request $this->_action_ajax(); } } /** * Render cart contents */ public function action_index() { Breadcrumbs::append(array('uri' => $this->request->uri, 'caption' => 'Корзина')); $this->request->response = $this->render_layout($this->widget_cart()); } /** * Render cart summary * * @return Widget */ public function widget_summary() { $widget = new Widget('frontend/cart/summary'); $widget->id = 'cart_summary'; $widget->cart = Model_Cart::session(); return $widget; } /** * Render full cart contents * * @return Widget */ public function widget_cart() { $cart = Model_Cart::session(); $form = new Form_Frontend_Cart(); // Get cart (from session or from post data) // & initialize cart form using products from cart if ($form->is_submitted()) { $quantities = $form->get_post_data('quantities'); $form->init_fields($quantities); } else { $form->init_fields($cart->quantities); } /* if ($form->is_submitted() && $form->get_value('recalculate')) { if ($form->validate()) { // Update cart contents $cart->update_products_from_post(); } } */ if ($form->is_submitted() && $form->validate()) { // Proceed to checkout $values = $form->get_values(); $cart->update_products($values['quantities']); if ( ! $cart->has_errors()) { $serialized = $cart->serialize(); $uri = URL::uri_to('frontend/orders', array('action' => 'checkout', 'cart' => $serialized)); $this->request->redirect($uri); } else { // An error occured while updating cart contents $form->errors($cart->errors()); } } $widget = new Widget('frontend/cart/contents'); $widget->id = 'cart'; $widget->cart = $cart; $widget->form = $form; $widget->cartproducts = $cart->cartproducts; return $widget; } }<file_sep>/modules/shop/acl/public/js/frontend/lecturer_name.js /** * Set form element value */ jFormElement.prototype.set_value = function(value) { if (value['name'] && value['id']) { $('#' + this.id).val(value['name']); $('#' + 'lecturer_id').val(value['id']); } else { $('#' + this.id).val(value); } }<file_sep>/modules/shop/countries/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { Route::add('backend/countries', new Route_Backend( 'countries(/<action>(/<id>))' . '(/~<history>)', array( 'action' => '\w++', 'id' => '\d++', 'history' => '.++' ))) ->defaults(array( 'controller' => 'countries', 'action' => 'index', 'id' => NULL )); // ----- Add backend menu items Model_Backend_Menu::add_item(array( 'menu' => 'main', 'caption' => 'Страны и регионы', 'route' => 'backend/countries' )); }<file_sep>/modules/shop/acl/classes/model/privilegevalue/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_PrivilegeValue_Mapper extends Model_Mapper { public function init() { parent::init(); $this->add_column('group_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('privilege_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); $this->add_column('value', array('Type' => 'varchar(31)')); } /** * Update privilege values for given group * * @param Model_Group $group */ public function update_values_for_group(Model_Group $group) { foreach ($group->privileges as $privilege) { $name = $privilege->name; $value = $group->__get($name); if ($value === NULL) continue; $where = DB::where('group_id', '=', (int) $group->id) ->and_where('privilege_id', '=', (int) $privilege->id); if ($this->exists($where)) { $this->update(array('value' => $value), $where); } else { $this->insert(array( 'group_id' => (int) $group->id, 'privilege_id' => (int) $privilege->id, 'value' => $value )); } } } }<file_sep>/modules/shop/catalog/classes/controller/backend/plistproducts.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_PListProducts extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_PListProduct'; //$this->_form = 'Form_Backend_PList'; return array( 'create' => array( 'view_caption' => 'Добавление товара в список' ), 'delete' => array( 'view_caption' => 'Удаление товара из списка', 'message' => 'Удалить товар из списка?' ), 'multi_delete' => array( 'view_caption' => 'Удаление товаров из списка', 'message' => 'Удалить выбранные товары из списка?' ) ); } /** * Create layout (proxy to catalog controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('catalog')->prepare_layout($layout_script); } /** * Render layout (proxy to catalog controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('catalog')->render_layout($content, $layout_script); } /** * Add product to list by product id */ public function action_add() { $plist_id = (int) $this->request->param('plist_id'); if (Request::$method != 'POST' || empty($_POST['ids']) || ! is_array($_POST['ids'])) { // No products were selected - silently redirect back $this->request->redirect(URL::uri_back()); } $plist = new Model_PList(); $plist->find($plist_id); if ($plist->id === NULL) { $this->_action_error('Указанный список товаров не найден!'); return; } $plistproduct = new Model_PListProduct(); foreach ($_POST['ids'] as $product_id) { $product_id = (int) $product_id; if (Model::fly('Model_Product')->exists_by_id($product_id)) { // Add product only if it's not already in list if ( ! $plistproduct->exists_by_plist_id_and_product_id($plist_id, $product_id)) { $plistproduct->init(); $plistproduct->plist_id = $plist_id; $plistproduct->product_id = $product_id; $plistproduct->save(); } } } FlashMessages::add('Товары добавлены успешно'); $this->request->redirect(URL::uri_back()); } /** * Render list of products in list * * @param Model_PList $plist */ public function widget_plistproducts(Model_PList $plist) { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите магазин!'); } $plistproduct = new Model_PlistProduct(); $per_page = 20; $count = $plistproduct->count_by_plist_id((int) $plist->id); $pagination = new Paginator($count, $per_page); $order_by = $this->request->param('cat_lporder', 'position'); $desc = (bool) $this->request->param('cat_lpdesc', '0'); $plistproducts = $plistproduct->find_all_by_plist_id((int) $plist->id, array( 'offset' => $pagination->offset, 'limit' => $pagination->limit, 'order_by' => $order_by, 'desc' => $desc ) ); // Set up view $view = new View('backend/plistproducts'); $view->order_by = $order_by; $view->desc = $desc; $view->plist = $plist; $view->plistproducts = $plistproducts; $view->pagination = $pagination; return $view->render(); } }<file_sep>/modules/shop/acl/classes/controller/backend/groups.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Groups extends Controller_BackendCRUD { /** * Setup actions * * @return array */ public function setup_actions() { $this->_model = 'Model_Group'; $this->_form = 'Form_Backend_Group'; return array( 'create' => array( 'view_caption' => 'Создание группы' ), 'update' => array( 'view_caption' => 'Редактирование группы ":name"' ), 'delete' => array( 'view_caption' => 'Удаление группы', 'message' => 'Удалить группу ":name" и всех пользователей из неё?' ) ); } /** * Create layout (proxy to acl controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Renders list of groups * * @return string Html */ public function widget_groups($view = 'backend/groups') { $group = new Model_Group(); $order_by = $this->request->param('acl_gorder', 'id'); $desc = (bool) $this->request->param('acl_gdesc', '0'); $group_id = (int) $this->request->param('group_id'); $groups = $group->find_all(array('order_by' => $order_by, 'desc' => $desc)); $view = new View($view); $view->order_by = $order_by; $view->desc = $desc; $view->group_id = $group_id; $view->groups = $groups; return $view->render(); } } <file_sep>/modules/general/filemanager/classes/model/file.php <?php class Model_File extends Model { protected static $_root_path = SYSPATH; /** * Set root path for all file operations * * @param string $root_path */ public static function set_root_path($root_path) { self::$_root_path = $root_path; } /************************************************************************** * File path **************************************************************************/ /** * Full file path is constructed of two parts: * * path = dirname . basename * * Base name consists of file name and file extension: * basename = filename . "." .ext */ /** * Clear cached variables if path has changed */ protected function _clear_path_cache() { $this->_properties['real_path'] = NULL; $this->_properties['directory'] = NULL; } /** * @param string $path */ public function set_path($path) { $pathinfo = pathinfo($path); $this->_properties['dir_name'] = $pathinfo['dirname']; $this->_properties['file_name'] = $pathinfo['filename']; $this->_properties['ext'] = isset($pathinfo['extension']) ? $pathinfo['extension'] : NULL; $this->_clear_path_cache(); } /** * @return string */ public function get_path() { return File::concat($this->dir_name, $this->base_name); } /** * @param string $base_name */ public function set_base_name($base_name) { $pathinfo = pathinfo($base_name); $this->_properties['file_name'] = $pathinfo['filename']; $this->_properties['ext'] = isset($pathinfo['extension']) ? $pathinfo['extension'] : NULL; $this->_clear_path_cache(); } /** * @return string */ public function get_base_name() { if ($this->ext !== NULL) { return $this->file_name . "." . $this->ext; } else { return $this->file_name; } } /** * @param string $relative_path */ public function set_relative_path($relative_path) { $this->path = File::concat($this->root_path, $relative_path); } /** * @return string */ public function get_relative_path() { return File::relative_path($this->path, $this->root_path); } /** * @return string */ public function set_relative_dir_name($relative_dir_name) { $this->_properties['dir_name'] = File::concat($this->root_path, $relative_dir_name); $this->_clear_path_cache(); } /** * @return string */ public function get_relative_dir_name() { return File::relative_path($this->dir_name, $this->root_path); } /** * @return string */ public function get_real_path() { //if ( ! isset($this->_properties['real_path'])) { $this->_properties['real_path'] = realpath($this->path); } return $this->_properties['real_path']; } /** * @return string */ public function get_root_path() { return self::$_root_path; } /** * Is file relative to root path? * * @return boolean */ public function is_relative() { return (File::relative_path($this->real_path, $this->root_path) !== NULL); } /** * String representation - full file path * * @return string */ public function __toString() { return $this->path; } /************************************************************************** * Basic file functions **************************************************************************/ /** * @return boolean */ public function file_exists() { return file_exists($this->path); } /** * @return boolean */ public function is_dir() { return is_dir($this->path); } /** * @return boolean */ public function is_file() { return is_file($this->path); } /** * @return boolean */ public function is_readable() { return is_readable($this->path); } /** * @return boolean */ public function is_writeable() { return is_writable($this->path); } /** * File is . or .. * * @return boolean */ public function is_dot() { return ($this->base_name == '.' || $this->base_name == '..'); } /** * Hide image thumbs directory and . with .. * * @return boolean */ public function is_hidden() { return ( ! $this->is_dot() && strpos($this->base_name, '.') === 0); } /** * Get file contents * * @return string */ public function get_content() { if ( ! isset($this->_properties['content'])) { if ($this->is_dir()) { $this->_properties['content'] = NULL; } else { $this->_properties['content'] = file_get_contents($this->real_path); } } return $this->_properties['content']; } /** * Copy current file to new path * * @param string $new_path * @return boolean */ public function copy($new_path) { try { copy($this->path, (string) $new_path); } catch (Exception $e) { $this->error($e->getMessage()); return FALSE; } return TRUE; } /** * Move current file to new path * * @param string $new_path * @return boolean */ public function move($new_path) { try { rename($this->path, (string) $new_path); } catch (Exception $e) { $this->error($e->getMessage()); return FALSE; } return TRUE; } /** * Delete file or directory. * Directories are deleted recursively. * * @return boolean */ public function delete() { try { File::delete($this->real_path); } catch (Exception $e) { $this->error($e->getMessage()); return FALSE; } return TRUE; } /** * Create directory from this model * * @return boolean */ public function mkdir() { try { mkdir($this->path); } catch (Exception $e) { $this->error($e->getMessage()); return FALSE; } return TRUE; } /** * Upload file to current path from $_FILES[$file_key] * * @param string $file_key Index to the $_FILES array * @return boolean */ public function upload($file_key) { // Use "@" to suppress stupid open_basedir aware warnings about temporary source if ( ! @move_uploaded_file($_FILES[$file_key]['tmp_name'], $this->path)) { $this->error('Не удалось переместить временный файл!'); return FALSE; } return TRUE; } /*************************************************************************** * Advanced file functions **************************************************************************/ /** * Return the parent directory as object * * @return Model_File */ public function get_directory() { if ( ! isset($this->_properties['directory'])) { $this->_properties['directory'] = new Model_File(); $this->_properties['directory']->path = $this->dir_name; } return $this->_properties['directory']; } /** * Get list of files in a directory * * @return array on success * @return null on failure */ public function get_files() { if ( ! $this->is_dir()) { $this->error('Файл "' . $this->relative_path . '" не является директорией!'); return NULL; } // Try readinig files in directory try { $h = opendir($this->real_path); if ( ! $h) { // Failed to open directory $this->error('Не удалось прочитать директорию "' . $this->relative_path . '"'); return NULL; } $files = array(); while (($base_name = readdir($h)) !== FALSE) { $file_info = array(); $file_info['base_name'] = $base_name; $file_info['path'] = File::concat($this->path, $base_name); $file_info['is_dir'] = is_dir($file_info['path']); // Necessary for sorting files $files[] = $file_info; } closedir($h); } catch (Exception $e) { $this->error($e->getMessage()); return NULL; } // Sort files File::sort($files); return $files; } /************************************************************************** * Actions **************************************************************************/ /** * Validate new directory creation * * @return boolean */ public function validate_mkdir($newvalues) { if ($this->dir_name === NULL) { $this->error('Не указана родительская директория!', 'base_name'); return FALSE; } if ( ! isset($newvalues['base_name'])) { $this->error('Не указано имя директории!', 'base_name'); return FALSE; } $new_base_name = $newvalues['base_name']; $tst_dir = clone $this; $tst_dir->base_name = $new_base_name; if ( ! $tst_dir->directory->is_dir()) { $this->error('Путь "' . $tst_dir->relative_dir_name . '" не существует или не является директорией!', 'base_name'); return FALSE; } if ( ! $tst_dir->directory->is_relative()) { // Directory part of new name is outside root path $this->error('Имя директории "' . $tst_dir->path .'" находится вне корневой директории "' . $this->root_path . '"!', 'base_name'); return FALSE; } if ($tst_dir->file_exists()) { // Such file/dir already exists $this->error('Файл с именем "' . $tst_dir->relative_path . '" уже существует!', 'base_name'); return FALSE; } return TRUE; } /** * Create new directory * * @return boolean */ public function do_mkdir($newvalues) { $this->base_name = $newvalues['base_name']; return $this->mkdir(); } /** * Validate renaming of file to new base name * * @param array $newvalues * @return boolean */ public function validate_rename($newvalues) { if ( ! isset($newvalues['base_name'])) { $this->error('Вы не указали имя файла!'); return FALSE; } if ( ! isset($newvalues['relative_dir_name'])) { $this->error('Вы не указали имя директории для файла!'); return FALSE; } $tst_file = clone $this; $tst_file->relative_dir_name = $newvalues['relative_dir_name']; $tst_file->base_name = $newvalues['base_name']; if ( ! $tst_file->directory->is_dir()) { $this->error('Папка "' . $tst_file->relative_dir_name . ' не существует!'); return FALSE; } if ($tst_file->directory->is_hidden()) { $this->error('Папка "' . $tst_file->relative_dir_name . ' является скрытой!'); return FALSE; } if ( ! $tst_file->directory->is_relative()) { // Directory part of new name is outside root path $this->error('Новое имя файла "' . $tst_file->path . '" находится вне корневой директории!'); return FALSE; } if ($tst_file->real_path === $this->real_path) { // New path is the same as old one return TRUE; } if ($tst_file->file_exists()) { // Such file/dir already exists $this->error('Файл с именем "' . $tst_file->relative_path . '" уже существует!'); return FALSE; } return TRUE; } /** * Rename file * * @param srray $nevalues * @return boolean */ public function do_rename($newvalues) { $new_file = clone $this; $new_file->relative_dir_name = $newvalues['relative_dir_name']; $new_file->base_name = $newvalues['base_name']; try { if ($this->is_image()) { if ($new_file->is_image()) { // Move thumbs together with the image $this->rename_thumbs($new_file); } else { // Delete thumbs $this->delete_thumbs(); } } } catch (Exception $e) {} return $this->move($new_file); } /** * Is it ok to delete a file? * * @param $newvalues Additional values * @return boolean */ public function validate_delete(array $newvalues = NULL) { if ( ! $this->is_relative()) { // File is outside root path $this->error('Файл "' . $this->path . '" находится вне корневой директории "' . $this->root_path . '"!'); return FALSE; } return TRUE; } /** * Delete file or directory. * Directory is deleted recursively. * * @return Model_File */ public function do_delete() { try { if ($this->is_image()) { // Delete thumbs $this->delete_thumbs(); } } catch (Exception $e) {} return $this->delete(); } /** * Validate file upload * $this->uploaded_file property must be set to key in $_FILES array * * @return boolean */ public function validate_upload(array $newvalues = NULL) { if ( ! isset($newvalues['uploaded_file'])) { $this->error('Файл не был загружен', 'uploaded_file'); return FALSE; } if ($newvalues['uploaded_file']['error'] != UPLOAD_ERR_OK) { $this->error('Произошла ошибка при загрузке файла!', 'uploaded_file'); return FALSE; } if ($this->dir_name === NULL) { $this->error('Не указана директория для файла!', 'uploaded_file'); return FALSE; } $tst_file = clone $this; $tst_file->base_name = $newvalues['uploaded_file']['name']; if ( ! $tst_file->directory->is_dir()) { $this->error('Директория "' . $tst_file->relative_dir_name . '" не существует', 'uploaded_file'); } if ( ! $tst_file->directory->is_relative()) { // Directory part of new name is outside root path $this->error('Новое имя файла "' . $tst_file->path . '" находится вне корневой директории "' . $this->root_path . '"!', 'uploaded_file'); return FALSE; } return TRUE; } /** * @param array $newvalues * @return boolean */ public function do_upload($newvalues) { $this->base_name = $newvalues['uploaded_file']['name']; // Upload try { File::upload($newvalues['uploaded_file'], $this->path); } catch (Exception $e) { $this->error($e->getMessage(), 'uploaded_file'); return FALSE; } // Create thumbs & resize image if necessary try { if ($this->is_image()) { if ( ! empty($newvalues['enable_popups'])) { // Create image for popup $popups_config = Kohana::config('filemanager.thumbs.popups'); $this->create_thumb($popups_config['width'], $popups_config['height'], $popups_config['dir_base_name']); } if ( ! empty($newvalues['resize_image'])) { $this->resize_image($newvalues['width'], $newvalues['height']); } } } catch (Exception $e) { $this->error($e->getMessage()); return FALSE; } return TRUE; } /** * Validate saving file contents * * @return boolean */ public function validate_save() { if ($this->is_dir()) { $this->error('Указанный путь "' . $this->relative_path . '" является директорией!'); return FALSE; } if ($this->file_exists() && ! $this->is_writeable()) { $this->error('Доступ к файлу "' . $this->relative_path . '" на запись запрещён!'); return FALSE; } return TRUE; } /** * Save file contents */ public function save($force_create = FALSE) { file_put_contents($this->path, $this->content); return TRUE; } /************************************************************************** * Image & thumbs functions **************************************************************************/ /** * @return boolean */ public function is_image() { switch (strtolower($this->ext)) { case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp': return TRUE; default: return FALSE; } } /** * Create all thumbs for current image */ public function create_thumbs() { foreach (Kohana::config('filemanager.thumbs') as $config) { if ($config['enable']) { $this->create_thumb($config['width'], $config['height'], $config['dir_base_name']); } } } /** * Rename all thumbs for current image being renamed * * @param Model_File $new_file New name of the image */ public function rename_thumbs(Model_File $new_file) { foreach (Kohana::config('filemanager.thumbs') as $config) { if ($config['enable']) { $this->rename_thumb($new_file, $config['dir_base_name']); } } } /** * Delete all thumbs for current image */ public function delete_thumbs() { foreach (Kohana::config('filemanager.thumbs') as $config) { if ($config['enable']) { $this->delete_thumb($config['dir_base_name']); } } } /** * Create a thumbnail for current image. * Thumbnail will be placed in $dir_base_name directory (relative to current directory) * * @param string $width * @param string $height * @param string|Model_File $dir_base_name * @param boolean $force Create thumb even if it already exists * @return boolean */ public function create_thumb($width, $height, $dir_base_name, $force = TRUE) { if ( ! ($dir_base_name instanceof Model_File)) { $thumb_dir = new Model_File(); $thumb_dir->dir_name = $this->dir_name; $thumb_dir->base_name = $dir_base_name; if ( ! $thumb_dir->is_dir()) { $thumb_dir->mkdir(); } } else { $thumb_dir = $dir_base_name; } $thumb_file = new Model_File(); $thumb_file->dir_name = $thumb_dir->path; // Thumb image has the same file name $thumb_file->base_name = $this->base_name; // Thumb already exists if (! $force && $thumb_file->is_file()) return FALSE; $thumb = new Image_GD($this->path); $thumb->thumbnail($width, $height); $thumb->save($thumb_file->path); return TRUE; } /** * Rename thumb together with the current image * * @param Model_File $new_file New file for the current image * @param string $dir_base_name * @return boolean */ public function rename_thumb(Model_File $new_file, $dir_base_name) { $thumb_dir = new Model_File(); $thumb_dir->dir_name = $this->dir_name; $thumb_dir->base_name = $dir_base_name; // Thums directory doesn't exist if ( ! $thumb_dir->is_dir()) return FALSE; $thumb_file = new Model_File(); $thumb_file->dir_name = $thumb_dir->path; // Thumb image has the same file name $thumb_file->base_name = $this->base_name; // No such thumb if ( ! $thumb_file->is_file()) return FALSE; // ----- Move thumb to new location // Create new thumb directory $new_thumb_dir = new Model_File(); $new_thumb_dir->dir_name = $new_file->dir_name; $new_thumb_dir->base_name = $dir_base_name; if ( ! $new_thumb_dir->is_dir()) { $new_thumb_dir->mkdir(); } $new_thumb_file = new Model_File(); $new_thumb_file->dir_name = $new_thumb_dir->path; $new_thumb_file->base_name = $new_file->base_name; // Move thumb $thumb_file->move($new_thumb_file->path); } /** * Delete thumb for current image * * @param string $dir_base_name * @return boolean */ public function delete_thumb($dir_base_name) { $thumb_dir = new Model_File(); $thumb_dir->dir_name = $this->dir_name; $thumb_dir->base_name = $dir_base_name; // Thums directory doesn't exist if ( ! $thumb_dir->is_dir()) return FALSE; $thumb_file = new Model_File(); $thumb_file->dir_name = $thumb_dir->path; // Thumb image has the same file name $thumb_file->base_name = $this->base_name; // No such thumb if ( ! $thumb_file->is_file()) return FALSE; return $thumb_file->delete(); } public function get_thumb_path($config_name) { $config = Kohana::config('filemanager.thumbs.' . $config_name); $thumb_file_name = File::concat($this->dir_name, $config['dir_base_name'], $this->base_name); if (is_file($thumb_file_name)) { return $thumb_file_name; } else { return NULL; } } /** * Resize current image * * @param integer $width * @param integer $height */ public function resize_image($width, $height) { $image = new Image_GD($this->path); $image->thumbnail($width, $height); $image->save($this->path); } /** * Create preview thumbs for images among specified files * Silently... * * @param array $files */ public function create_preview_thumbs($files) { try { $thumbs_config = Kohana::config('filemanager.thumbs.preview'); $preview_dir_created = FALSE; $count = 0; $thumbs_dir = new Model_File(); $file = new Model_File(); foreach ($files as $properties) { $file->init(); $file->path = $properties['path']; if ($file->is_image()) { // Create directory for thumbs, if not already created if ( ! $preview_dir_created) { $thumbs_dir->dir_name = $file->dir_name; $thumbs_dir->base_name = $thumbs_config['dir_base_name']; if ( ! $thumbs_dir->is_dir()) { $thumbs_dir->mkdir(); } // Creation of thumbs directory was succesfull $preview_dir_created = TRUE; } //@TODO: Limit number of created thumbs per request! // Create thumb (ignore failures) if ($file->create_thumb($thumbs_config['width'], $thumbs_config['height'], $thumbs_dir, FALSE)) { $count++; } } // Limit the number of created thumbs per one request to 100 if ($count >= 100) break; } } catch (Exception $e) { return FALSE; } return TRUE; } }<file_sep>/modules/shop/acl/views/backend/users.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php //Set up urls if (isset($group) && $group->id > 0) { $create_url = URL::to('backend/acl/users', array('action'=>'create', 'group_id' => $group->id), TRUE); } else { $create_url = URL::to('backend/acl/users', array('action'=>'create'), TRUE); } $update_url = URL::to('backend/acl/users', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/acl/users', array('action'=>'delete', 'id' => '${id}'), TRUE); $multi_action_uri = URL::uri_to('backend/acl/users', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_user_add">Создать пользователя</a> </div> <?php if (isset($group)) { echo '<div class="group_name">' . HTML::chars($group->name) . '</div>'; } ?> <?php if ( ! count($users)) // No users return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'email' => 'E-mail', //'name' => 'Имя', 'logins' => 'Посещения', 'active' => 'Акт.' ); echo View_Helper_Admin::table_header($columns, 'acl_uorder', 'acl_udesc'); ?> <th></th> </tr> <?php foreach ($users as $user) : $_delete_url = str_replace('${id}', $user->id, $delete_url); $_update_url = str_replace('${id}', $user->id, $update_url); ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($user->id); ?> </td> <?php foreach (array_keys($columns) as $field) { switch ($field) { case 'active': echo '<td class="c">'; if ( ! empty($user->$field)) { echo View_Helper_Admin::image('controls/on.gif', 'Да'); } else { echo View_Helper_Admin::image('controls/off.gif', 'Нет'); } echo '</td>'; break; case 'logins': echo '<td class="nowrap">'; if ($user->logins) { echo $user->logins.' '.l10n::plural($user->logins, 'вход', 'входов', 'входа').', последний '.$user->last_login_str; } echo '</td>'; break; default: echo '<td class="nowrap">'; if (isset($user->$field) && trim($user->$field) !== '') { echo HTML::chars($user[$field]); } else { echo '&nbsp'; } echo '</td>'; } } ?> <td class="ctl"> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать пользователя', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить пользователя', 'controls/delete.gif', 'Удалить'); ?> </td> </tr> <?php endforeach; //foreach ($users as $user) ?> </table> <?php if (isset($pagination)) { echo $pagination; } ?> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/catalog/views/frontend/products/administrator_vision.php <?php defined('SYSPATH') or die('No direct script access.');?> <iframe src="<?php echo $product->event_uri ?>?t=1&export=1&logout=www<?php echo URL::self(array());?>" width="940" height="768" frameborder="0" style="border:none"></iframe> <file_sep>/modules/shop/area/classes/controller/frontend/places.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Places extends Controller_Frontend { /** * Select several towns */ public function action_select() { $layout = $this->prepare_layout(); if ($this->request->in_window()) { $layout->caption = 'Выбор площадки на портале "' . Model_Site::current()->caption . '"'; $layout->content = $this->widget_select(); $this->request->response = $layout->render(); } else { $this->request->response = $this->render_layout($this->widget_select()); } } /** * Render list of towns to select several towns * @param integer $select * @return string */ public function widget_select($select = FALSE) { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } // ----- Render section for current section group $order_by = $this->request->param('acl_oorder', 'name'); $desc = (bool) $this->request->param('acl_odesc', '0'); $organizers = Model::fly('Model_Place')->find_all(array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/organizers/select'); $view->order_by = $order_by; $view->desc = $desc; $view->organizers = $organizers; return $view->render(); } /** * Display autocomplete options for a postcode form field */ public function action_ac_place_name() { $place_name = isset($_POST['value']) ? trim(UTF8::strtolower($_POST['value'])) : NULL; $place_name = UTF8::str_ireplace("ё", "е", $place_name); if ($place_name == '') { $this->request->response = ''; return; } $limit = 7; $places = Model::fly('Model_Place')->find_all_like_name($place_name,array('limit' => $limit)); $items = array(); $pattern = new View('frontend/place_ac'); $i=0; foreach ($places as $place) { $name = $place->name; $id = $place->id; $image_info = $place->image(4); $pattern->name = $name; $pattern->num = $i; $pattern->image_info = $place->image(4); $items[] = array( 'caption' => $pattern->render(), 'value' => array('name' => $name, 'id' => $id) ); $i++; } $items[] = array('caption' => '<a data-toggle="modal" href="#PlaceModal" class="active">Добавить новую площадку</a>'); $this->request->response = json_encode($items); } } <file_sep>/modules/shop/area/public/js/backend/place_select.js /** * Initialize */ $(document).ready(function(){ if (current_window) { // ----- Select user buttons $('#place_select').click(function(event){ if ($(event.target).hasClass('place_select')) { // "Select place" link was pressed // Determine place id from link "id" attribute (id is like 'place_15') var place_id = $(event.target).attr('id').substr(6); // Peform an ajax request to get selected user var ajax_url = place_selected_url.replace('{{id}}', place_id); $.post(ajax_url, null, function(response) { if (response) { //@FIXME: Security breach! eval('var place = ' + response + ';'); // Execute custom actions on place selection // (there should be a corresponding function defined in parent window) if (parent.on_place_select) { parent.on_place_select(place) } // Close the window current_window.close(); } }); event.preventDefault(); } }); } });<file_sep>/modules/shop/acl/classes/controller/backend/links.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Backend_Links extends Controller_BackendCRUD { /** * Configure actions * @var array */ public function setup_actions() { $this->_model = 'Model_Link'; $this->_form = 'Form_Backend_Link'; return array( 'create' => array( 'view_caption' => 'Создание внешней ссылки' ), 'update' => array( 'view_caption' => 'Редактирование внешней ссылки ":caption"' ), 'delete' => array( 'view_caption' => 'Удаление внешней ссылки', 'message' => 'Удалить ссылки ":caption"?' ) ); } /** * Create layout (proxy to acl controller) * * @return Layout */ public function prepare_layout($layout_script = NULL) { return $this->request->get_controller('acl')->prepare_layout($layout_script); } /** * Render layout (proxy to acl controller) * * @param View|string $content * @param string $layout_script * @return string */ public function render_layout($content, $layout_script = NULL) { return $this->request->get_controller('acl')->render_layout($content, $layout_script); } /** * Render all available user properties */ public function action_index() { $this->request->response = $this->render_layout($this->widget_links()); } /** * Create new user link * * @return Model_Link */ protected function _model_create($model, array $params = NULL) { if (Model_Site::current()->id === NULL) { throw new Controller_BackendCRUD_Exception('Выберите портал перед созданием внешней ссылки!'); } // New link for current site $link = new Model_Link(); $link->site_id = (int) Model_Site::current()->id; return $link; } /** * Render list of user links */ public function widget_links() { $site_id = Model_Site::current()->id; if ($site_id === NULL) { return $this->_widget_error('Выберите портал!'); } $order_by = $this->request->param('acl_uliorder', 'position'); $desc = (bool) $this->request->param('acl_ulidesc', '0'); $links = Model::fly('Model_Link')->find_all_by_site_id($site_id, array( 'order_by' => $order_by, 'desc' => $desc )); // Set up view $view = new View('backend/links'); $view->order_by = $order_by; $view->desc = $desc; $view->links = $links; return $view->render(); } }<file_sep>/modules/shop/acl/public/js/frontend/register.js $(function(){ $('#id-user1').xtautosave(); });<file_sep>/modules/system/history/views/backend/history.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="history"> <?php foreach ($entries as $entry) : ?> <div class="entry"> <div> <span class="date">[<?php echo date('Y-m-d H:i:s', $entry->created_at); ?>]</span> <?php echo $entry->user_name; ?> </div> <div> <?php echo $entry->html; ?> </div> </div> <?php endforeach; ?> </div> <?php if (isset($pagination)) { echo $pagination->render(); } ?><file_sep>/modules/general/tags/views/frontend/images.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Width & height of one image preview $canvas_height = 110; $canvas_width = 110; $create_url = URL::to('frontend/images', array( 'action'=>'create', 'owner_type' => $owner_type, 'owner_id' => $owner_id, 'config' => $config ), TRUE); $update_url = URL::to('frontend/images', array('action'=>'update', 'id' => '${id}', 'config' => $config), TRUE); $delete_url = URL::to('frontend/images', array('action'=>'delete', 'id' => '${id}', 'config' => $config), TRUE); $up_url = URL::to('frontend/images', array('action'=>'up', 'id' => '${id}'), TRUE); $down_url = URL::to('frontend/images', array('action'=>'down', 'id' => '${id}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Добавить изображение</a> </div> <div class="images"> <?php foreach ($images as $image) : $image->config = $config; $_update_url = str_replace('${id}', $image->id, $update_url); $_delete_url = str_replace('${id}', $image->id, $delete_url); $_up_url = str_replace('${id}', $image->id, $up_url); $_down_url = str_replace('${id}', $image->id, $down_url); // Number the thumb to render $i = count($image->get_thumb_settings()); if ($i > 3) { $i = 3; } $width = $image->__get("width$i"); $height = $image->__get("height$i"); if ($width > $canvas_width || $height > $canvas_height) { if ($width > $height) { $scale = ' style="width: ' . $canvas_width . 'px;"'; $height = $height * $canvas_width / $width; $width = $canvas_width; } else { $scale = ' style="height: ' . $canvas_height . 'px;"'; $width = $width * $canvas_height / $height; $height = $canvas_height; } } else { $scale = ''; } if ($canvas_height > $height) { $padding = ($canvas_height - $height) >> 1; // ($canvas_height - $height) / 2 $padding = ' padding-top: ' . $padding . 'px;'; } else { $padding = ''; } ?> <div class="image"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить изображение', 'controls/delete.gif', 'Удалить'); ?> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать изображение', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_up_url, 'Переместить вверх', 'controls/left.gif', 'Вверх'); ?> <?php echo View_Helper_Admin::image_control($_down_url, 'Переместить вниз', 'controls/right.gif', 'Вниз'); ?> </div> <div class="img" style="width: <?php echo $canvas_width; ?>px; height: <?php echo $canvas_width; ?>px;"> <a href="<?php echo $_update_url; ?>" style="<?php echo $padding; ?>"> <img src="<?php echo File::url($image->image($i)); ?>" <?php echo $scale; ?> alt="" /> </a> </div> </div> <?php endforeach; ?> </div><file_sep>/application/views/layouts/about.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require('_header_new.php'); ?> <body> <header> <div class="mainheader"> <div class="container"> <div class="row"> <div class="span2"> <a href="<?php echo URL::site()?>" class="logo pull-left"></a> </div> <div class="span6"> <?php echo Widget::render_widget('menus','menu', 'main'); ?> </div> <div class="span4"> <div class="b-auth-search"> <?php echo Widget::render_widget('products', 'search');?> </div> </div> </div> </div> </div> <div class="subheader"> <div class="container"> <div class="row"> <div class="span2"> </div> <div class="span6"> </div> <div class="span4"> <div class="login-form"> <?php echo Widget::render_widget('acl', 'login'); ?> </div> </div> </div> </div> </div> </header> <div id="main"> <div class="container"> <div class="row"> <div class="span12" id="page"> <div class="wrapper"> <div class="row-fluid"> <div class="span3"> </div> <div class="span7 content"> <?php echo Widget::render_widget('blocks', 'block', 'about'); ?> <h2 id="faq">FAQ</h2> <div class="accordion" id="accordion2"> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse1"> Что такое vse.to? </a> </div> <div id="collapse1" class="accordion-body collapse"> <div class="accordion-inner"> Первая в мире сеть обмена культурными событиями. В отличие от обычной социальной сети, vse.to соединяет не только людей, но и пространства: площадки, оборудованные для проведения телемостов и вебинаров и стриминговых трансляций. </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse2"> Если у вас есть событие, и вы хотите транслировать его в регионы </a> </div> <div id="collapse2" class="accordion-body collapse"> <div class="accordion-inner"> <ul> <li><a href="http://vse.to/register">Станьте представителем vse.to</a> </li> <li>Разместите анонс Вашего события </li> <li>Региональные представители vse.to подадут заявки на трансляцию Вашего события </li> <li>Выберите заявки из тех городов, в которых Вы хотите провести трансляцию (города могут быть также отобраны автоматически) </li> <li>Проведите телемост</li> </ul> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse3"> Если вам нравится удалённое событие, и вы хотите показать его в своём городе </a> </div> <div id="collapse3" class="accordion-body collapse"> <div class="accordion-inner"> <ul> <li><a href="http://vse.to/register">Станьте представителем vse.to</a> </li> <li>Добавьте заявку на трансляцию, нажав на кнопку &ldquo;Провести телемост&rdquo; на странице события </li> <li>Если Ваша заявка будет одобрена, создайте ивент в социальных сетях и пригласите всех на телемост </li> <li>Проверьте, что у площадки, которую Вы выбрали, есть всё необходимое оборудование </li> <li>Проведите телемост</li> </ul> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse5"> Кто такие представители vse.to? </a> </div> <div id="collapse5" class="accordion-body collapse"> <div class="accordion-inner"> <p>Люди или организации участвующие в обмене культурными событиями</p> <p>Представитель vse.to может:</p> <ul> <li>Организовать событие, которое увидят в других городах</li> <li>Организовать телемост - то есть трансляцию удалённого события в своём городе.</li> </ul> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse6"> Как стать представителем? </a> </div> <div id="collapse6" class="accordion-body collapse"> <div class="accordion-inner"> <p>Представителями могут стать человек или организация, у которых есть возможность и желание провести телемост, то есть</p> <ul> <li>помещение</li> <li>доступ к Интернету</li> <li>оборудование</li> <li>умение собирать зрителей.</li> </ul> <a href="http://vse.to/register">Станьте представителем vse.to</a> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse7"> Какое потребуется оборудование для телемоста? </a> </div> <div id="collapse7" class="accordion-body collapse"> <div class="accordion-inner"> <p>Для участия в телемосте Вам нужно иметь</p> <ul> <li>ПК: Intel Core 2 Duo 2.13 ГГц или AMD Athlon II 215 и выше, Оперативная память: от 2 Гб и выше для всех ОС</li> <li>Интернет со скоростью доступа не меньше, чем 3 Мбит/с. Вы можете проверить скорость интернета <a href="http://www.speedtest.net/">тут</a>.</li> <li>веб-камеру</li> <li>микрофон</li> <li>колонки</li> <li>проектор и экран или плазменную панель</li> <li>установленный плагин для Google Hangouts. Плагин можно скачать <a href="http://www.google.com/tools/dlpage/hangoutplugin">тут</a>.</li> </ul> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse9"> Какие виды трансляций есть на vse.to? </a> </div> <div id="collapse9" class="accordion-body collapse"> <div class="accordion-inner"> <ul> <li>Телемост (вебинар, видеоконференция) - это прямая трансляция события c возможностью обратной видеосвязи.</li> <li>Стриминг - прямая трансляция без обратной связи или с ограниченной обратной связью через чат.</li> </ul> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse10"> Какие события может транслировать vse.to? </a> </div> <div id="collapse10" class="accordion-body collapse"> <div class="accordion-inner"> <p>Любые, например: лекции, семинары, дискуссии, встречи с писателями, журналистами или режиссерами, фильмы, концерты, спектакли, перформансы.</p> </div> </div> </div> <div class="accordion-group"> <div class="accordion-heading"> <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapse12"> Какие бывают типы организаций? </a> </div> <div id="collapse12" class="accordion-body collapse"> <div class="accordion-inner"> <p>Библиотека, книжный магазин, клуб, ресторан, институт, культурный центр, творческая группа.</p> </div> </div> </div> </div> </div> <div class="span1">&nbsp;</div> </div> </div> </div> </div> </div> </div> <?php require('_footer.php'); ?> <?php echo $view->placeholder('modal'); ?> <script> jQuery(function($){ $('.help-pop').tooltip() }); </script> </body> <file_sep>/modules/shop/catalog/views/frontend/products/apply.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php $url = URL::to('frontend/catalog/products/control', array('action' => 'create', 'product_id' => $product->id,'type_id' => Model_SectionGroup::TYPE_EVENT,), TRUE); ?> <form action="<?php echo $url; ?>" method="POST" class="ajax"> <input type="image" src="<?php echo URL::base(FALSE); ?>public/css/img/3cart.gif" class="buy" alt="В корзину" /> </form><file_sep>/modules/shop/catalog/classes/model/productcomment.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_ProductComment extends Model { /** * Back up properties before changing (for logging) */ public $backup = TRUE; // ------------------------------------------------------------------------- // Actions // ------------------------------------------------------------------------- /** * Save model and log changes * * @param boolean $force_create */ public function save($force_create = FALSE) { parent::save($force_create); $this->log_changes($this, $this->previous()); } /** * Delete productcomment */ public function delete() { $id = $this->id; //@FIXME: It's more correct to log AFTER actual deletion, but after deletion we have all model properties reset $this->log_delete($this); parent::delete(); } /** * Log product comment changes * * @param Model_ProductComment $new_productcomment * @param Model_ProductComment $old_productcomment */ public function log_changes(Model_ProductComment $new_productcomment, Model_ProductComment $old_productcomment) { $text = ''; $created = ! isset($old_productcomment->id); $has_changes = FALSE; if ($created) { $text .= '<strong>Добавлен комментарий к событию № {{id-' . $new_productcomment->product_id . "}}</strong>\n"; } else { $text .= '<strong>Изменён комментарий к событию № {{id-' . $new_productcomment->product_id . "}}</strong>\n"; } // ----- text if ($created) { $text .= Model_History::changes_text('Текст', $new_productcomment->text); } elseif ($old_productcomment->text != $new_productcomment->text) { $text .= Model_History::changes_text('Текст', $new_productcomment->text, $old_productcomment->text); $has_changes = TRUE; } // ----- notify_client if ($created) { $text .= Model_History::changes_text('Оповещать представителя', $new_productcomment->notify_client ? 'да' : 'нет'); } elseif ($old_productcomment->notify_client != $new_productcomment->notify_client) { $text .= Model_History::changes_text('Оповещать представителя', $new_productcomment->notify_client ? 'да' : 'нет', $old_productcomment->notify_client ? 'да' : 'нет' ); $has_changes = TRUE; } if ($created || $has_changes) { // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $new_productcomment->product_id; $history->item_type = 'product'; $history->save(); } } /** * Log the deletion of productcomment * * @param Model_ProductComment $productcomment */ public function log_delete(Model_ProductComment $productcomment) { $text = 'Удалён комментарий "' . $productcomment->text . '" к событию № {{id-' . $productcomment->product_id . '}}'; // Save text in history $history = new Model_History(); $history->text = $text; $history->item_id = $productcomment->product_id; $history->item_type = 'product'; $history->save(); } }<file_sep>/modules/shop/acl/views/frontend/lecturer.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="wrapper lecturer"> <h1><?php echo "Лектор: ".$lecturer->name?></h1> <div class="row-fluid"> <div class="span6 bio"> <?php echo Widget::render_widget('lecturers', 'lecturer_images', $lecturer); ?> </div> <div class="span6 content"> <?php echo $lecturer->info ?> <div> <?php if (is_array($lecturer->links)) { foreach ($lecturer->links as $link) { ?> <a class="website" href="<?php echo $link?>"><?php echo $link?></a> <?php }} ?> </div> </div> </div> <div class="b-social"></div> </div> <?php echo Widget::render_widget('products','search_products',array('lecturer_id' => $lecturer->id), 'frontend/small_products_lecturer'); ?> <file_sep>/modules/general/tinymce/public/js/tiny_mce_config.js var tinyMCE_config = { mode : "specific_textareas" ,language : "ru" ,convert_urls : false ,relative_urls : false ,remove_script_host : false ,theme : "advanced" ,theme_advanced_toolbar_location : "top" ,theme_advanced_toolbar_align : "left" ,theme_advanced_buttons1 : "formatselect,fontselect,fontsizeselect,separator,"+ "forecolor,backcolor,bold,italic,separator," + "numlist,bullistlink,unlink,image,separator," + "pasteword,removeformat,cleanup,code" ,theme_advanced_buttons2 : "" ,theme_advanced_buttons3 : "" ,extended_valid_elements : "iframe[src|width|height|name|align]" ,plugins : "inlinepopups,advimage,advlink,table,paste" //,document_base_url : --- Is set in layout //,editor_selector : --- Is set in layout //,content_css : --- Is set in layout ,height: 600 ,paste_preprocess : function(pl, o) { function strip_tags( str ){ // Strip HTML and PHP tags from a string // // + original by: <NAME> (http://kevin.vanzonneveld.net) return str.replace(/<\/?[^>]+>/gi, ''); } o.content = strip_tags( o.content ); } }; <file_sep>/modules/system/tasks/classes/dbtable/taskvalues.php <?php defined('SYSPATH') or die('No direct script access.'); class DbTable_TaskValues extends DbTable { public function init() { parent::init(); $this->add_column('task', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('key', array('Type' => 'varchar(31)', 'Key' => 'INDEX')); $this->add_column('value', array('Type' => 'text')); } /** * Set a value for task * * @param string $task * @param string $key * @param mixed $value */ public function set_value($task, $key, $value) { $value = serialize($value); if ($this->exists(DB::where('task', '=', $task)->and_where('key', '=', $key))) { // Update existing value $this->update(array('value' => $value), DB::where('task', '=', $task)->and_where('key', '=', $key)); } else { // Insert new value $this->insert(array( 'task' => $task, 'key' => $key, 'value' => $value )); } } /** * Get value for task * * @param string $task * @param string $key */ public function get_value($task, $key) { $result = $this->select_row(DB::where('task', '=', $task)->and_where('key', '=', $key)); if (count($result)) { $value = @unserialize($result['value']); } else { $value = NULL; } return $value; } /** * Unset the value for task * * @param string $task * @param string $key */ public function unset_value($task, $key) { $this->delete_rows(DB::where('task', '=', $task)->and_where('key', '=', $key)); } }<file_sep>/modules/shop/catalog/views/backend/forms/property.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php echo $form->render_messages() . Form_Helper::open($form->action, $form->attributes()) . $form->render_hidden(); ?> <table class="content_layout"><tr> <td class="content_layout" style="width: 320px; padding: 0px 20px 0px 0px;"> <dl> <?php echo $form->render_components(NULL, array('propsections')); ?> </dl> </td> <td class="content_layout" style="width: 380px; padding: 0px 0px 0px 20px;"> <dl> <?php echo $form->render_components(array('propsections')); ?> </dl> </td> </tr></table> <?php echo Form_Helper::close(); ?><file_sep>/modules/shop/catalog/views/frontend/forms/datesearch.php <?php echo $form->render_form_open();?> <fieldset class="b-f-date"> <div class="b-input"><label for=""></label><?php echo $form->get_element('datesearch')->render_input();?> <?php echo $form->get_element('datetime')->render_alone_errors();?> </fieldset> <div class="form-action"> <?php echo $form->get_element('submit_datesearch')->render_input(); ?> </div> <?php echo $form->render_form_close();?> <file_sep>/modules/shop/delivery_courier/views/backend/delivery/courierzones.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // Set up urls $create_url = URL::to('backend/courierzones', array('action'=>'create', 'delivery_id' => $delivery_id), TRUE); $update_url = URL::to('backend/courierzones', array('action'=>'update', 'id' => '${id}'), TRUE); $delete_url = URL::to('backend/courierzones', array('action'=>'delete', 'id' => '${id}'), TRUE); $up_url = URL::to('backend/courierzones', array('action'=>'up', 'id' => '${id}'), TRUE); $down_url = URL::to('backend/courierzones', array('action'=>'down', 'id' => '${id}'), TRUE); if ( ! $desc) { list($up_url, $down_url) = array($down_url, $up_url); } $multi_action_uri = URL::uri_to('backend/courierzones', array('action'=>'multi'), TRUE); ?> <div class="buttons"> <a href="<?php echo $create_url; ?>" class="button button_add">Добавить зону доставки</a> </div> <?php if ( ! count($zones)) // No zones return; ?> <?php echo View_Helper_Admin::multi_action_form_open($multi_action_uri); ?> <table class="table"> <tr class="header"> <th>&nbsp;&nbsp;&nbsp;</th> <?php $columns = array( 'name' => 'Название', 'price' => 'Стоимость', ); echo View_Helper_Admin::table_header($columns); ?> </tr> <?php foreach ($zones as $zone) : $_update_url = str_replace('${id}', $zone->id, $update_url); $_delete_url = str_replace('${id}', $zone->id, $delete_url); $_up_url = str_replace('${id}', $zone->id, $up_url); $_down_url = str_replace('${id}', $zone->id, $down_url); ?> <tr> <td class="ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($zone->id); ?> <?php echo View_Helper_Admin::image_control($_delete_url, 'Удалить зону', 'controls/delete.gif', 'Удалить'); ?> <?php echo View_Helper_Admin::image_control($_update_url, 'Редактировать зону', 'controls/edit.gif', 'Редактировать'); ?> <?php echo View_Helper_Admin::image_control($_up_url, 'Переместить вверх', 'controls/up.gif', 'Вверх'); ?> <?php echo View_Helper_Admin::image_control($_down_url, 'Переместить вниз', 'controls/down.gif', 'Вниз'); ?> </td> <?php foreach (array_keys($columns) as $field) { echo '<td>'; if (isset($zone->$field) && trim($zone->$field) !== '') { echo HTML::chars($zone->$field); } else { echo '&nbsp'; } echo '</td>'; } ?> </tr> <?php endforeach; //foreach ($zones as $zone) ?> </table> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'multi_delete', 'label' => 'Удалить', 'class' => 'button_delete') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/catalog/classes/model/go/mapper.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Go_Mapper extends Model_Mapper_Resource { public function init() { parent::init(); $this->add_column('id', array('Type' => 'int unsigned', 'Key' => 'PRIMARY', 'Extra' => 'auto_increment')); $this->add_column('telemost_id', array('Type' => 'int unsigned', 'Key' => 'INDEX')); // $this->cache_find_all = TRUE; } }<file_sep>/modules/general/news/classes/form/backend/newsitem.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Newsitem extends Form_Backend { /** * Initialize form fields */ public function init() { // Set html class $this->attribute('class', 'w99per'); // ----- date $element = new Form_Element_SimpleDate('date', array('label' => 'Дата', 'required' => TRUE)); $element->value_format = Model_Newsitem::$date_as_timestamp ? 'timestamp' : 'date'; $element ->add_validator(new Form_Validator_Date()); $this->add_component($element); // ----- Caption $element = new Form_Element_Input('caption', array('label' => 'Заголовок', 'required' => TRUE), array('maxlength' => 255) ); $element ->add_filter(new Form_Filter_TrimCrop(255)) ->add_validator(new Form_Validator_NotEmptyString()); $this->add_component($element); // ----- text $tab = new Form_Fieldset_Tab('text_tab', array('label' => 'Полный текст')); $this->add_component($tab); $element = new Form_Element_Wysiwyg('text', array('label' => 'Полный текст'), array('rows' => 15)); $tab->add_component($element); // ----- short_text $tab = new Form_Fieldset_Tab('short_text_tab', array('label' => 'Краткий текст')); $this->add_component($tab); $element = new Form_Element_Textarea('short_text', array('label' => 'Краткий текст')); $tab->add_component($element); // ----- Form buttons $fieldset = new Form_Fieldset_Buttons('buttons'); $this->add_component($fieldset); // ----- Cancel button $fieldset ->add_component(new Form_Element_LinkButton('cancel', array('url' => URL::back(), 'label' => 'Отменить'), array('class' => 'button_cancel') )); // ----- Submit button $fieldset ->add_component(new Form_Backend_Element_Submit('submit', array('label' => 'Сохранить'), array('class' => 'button_accept') )); parent::init(); } } <file_sep>/modules/general/jquery/public/js/jquery.xtsaveform.js /** * jquery.xtsaveform.js 1.1.0 - https://github.com/anibalsanchez/jquery.saveform.js * Saves automatically all entered form fields, to restore them in the next visit. * * Copyright (c) 2013 <NAME> (http://www.extly.com) Licensed under the MIT * license (http://www.opensource.org/licenses/mit-license.php). 2013/05/04 * * Based on the original work of <NAME> (http://yckart.com) * jquery.saveform.js 0.0.1 - https://github.com/yckart/jquery.saveform.js */ ;(function($, window) { "use strict"; // this.prefix - inorder to seperate the fields of different forms $.fn.xtautosave = function(prefix_param) { var storage = window.localStorage, $this = this, prefix; if (typeof $this.prefix_param === 'undefined') { prefix = $this.attr('id') || $this.attr('name') || 'no-Id-Or-Name-Given'; } else { prefix = $this.prefix_param; } // _ $this will give unique names and will not clash with // other fields prefix += "_"; $this.attr('prefix', prefix); function restoreInput(elem, index) { var key = $.fn.xtautosave.getKey($this, index), value = storage.getItem(key); if (!value) { return; } if ((elem.attr('type') === 'checkbox') || (elem.attr('type') === 'radio')) { elem.prop('checked', value); } else { var currentVal = elem.val(); if(!currentVal) elem.val(value); } } function restoreSelect(elem, index) { var key = $.fn.xtautosave.getSelectKey($this, index), value = storage.getItem(key); if (!value) { return; } // Just in case it's an array value = value.split(','); elem.val(value); } function restore() { var elems; elems = $this.find('input:not([type=password],[type=submit])'); elems.each( function(index, elem) { restoreInput($(elem), index); }); elems = $this.find('select'); elems.each( function(index, elem) { restoreSelect($(elem), index); }); } // $this.on({ // submit : $.fn.xtautosave.save // }); $this.on({ change: $.fn.xtautosave.save, submit: $.fn.xtautosave.reset }); restore(); }; $.fn.xtautosave.getKey = function(elem, index) { return elem.attr('prefix') + index; }; $.fn.xtautosave.getSelectKey = function(elem, index) { return 'S' + elem.attr('prefix') + index; }; $.fn.xtautosave.saveInput = function($this, elem, index) { var value, key = $.fn.xtautosave.getKey($this, index), storage = window.localStorage; if ((elem.attr('type') === 'checkbox') || (elem.attr('type') === 'radio')) { value = elem.prop('checked'); } else { value = elem.val(); } if ((value) && (value !== '')) { storage.setItem(key, value); } else { storage.removeItem(key); } }; $.fn.xtautosave.saveSelect = function($this, elem, index) { var value = elem.val(), key = $.fn.xtautosave.getSelectKey($this, index), storage = window.localStorage; if ((value) && (value !== '')) { storage.setItem(key, value); } else { storage.removeItem(key); } }; $.fn.xtautosave.save = function () { var $this = $(this), elems; elems = $this.find('input:not([type=password],[type=submit])'); elems.each( function(index, elem) { $.fn.xtautosave.saveInput($this, $(elem), index); }); elems = $this.find('select'); elems.each( function(index, elem) { $.fn.xtautosave.saveSelect($this, $(elem), index); }); }; $.fn.xtautosave.reset = function () { var storage = window.localStorage, $this = $(this), elems; elems = $this.find('input:not([type=password],[type=submit])'); elems.each( function(index, elem) { var key = $.fn.xtautosave.getKey($this, index); storage.removeItem(key); }); elems = $this.find('select'); elems.each( function(index, elem) { var key = $.fn.xtautosave.getSelectKey($this, index); storage.removeItem(key); }); }; }(jQuery, window));<file_sep>/modules/shop/orders/views/frontend/cart/contents.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php require_once(Kohana::find_file('views', 'frontend/products/_helper')); ?> <h1>Корзина</h1> <?php if ( ! count($cartproducts)) { echo '<i>В корзине нет товаров</i>'; return; } ?> <?php $remove_url = URL::to('frontend/cart', array('action' => 'remove_product', 'product_id' => '{{id}}'), TRUE); ?> <?php echo $form->render_form_open(); ?> <?php echo $form->render_messages(); ?> <table cellspacing="0" cellpadding="0" class="cart"> <tr> <th></th> <th>Артикул</th> <th>Название</th> <th>Категория</th> <th>Цена, руб.</th> <th>Количество</th> <th>&nbsp;</th> </tr> <?php foreach ($cartproducts as $cartproduct) { // Corresponding product in catalog $product = $cartproduct->product; $image_info = $product->image(4); list($brands_html,,) = brands_and_categories($product); $_product_url = URL::site($product->uri_frontend()); $_remove_url = str_replace('{{id}}', $cartproduct->product_id, $remove_url); echo '<tr>' . '<td><a href="' . $_product_url . '">' . HTML::image('public/data/' . $image_info['image'], array('width' => $image_info['width'],'height' => $image_info['height'])) . '</a></td>' . '<td>' . $product->marking . '</td>' . '<td><a href="' . $_product_url . '">' . $product->caption . '</a></td>' . '<td>' . $brands_html . '</td>' . '<td>' . $cartproduct->price . '</td>' . '<td>' . $form->get_component('quantities[' . $cartproduct->product_id . ']')->render_input() . '<div class="errors">' . $form->get_component('quantities[' . $cartproduct->product_id . ']')->render_errors() . '</div>' . '</td>' . '<td><a href="' . $_remove_url . '" class="delete ajax">Удалить&nbsp;этот&nbsp;товар</a></td>' . '</tr>'; } ?> <tr class="bottom"> <td colspan="5"><strong></strong></td> <td colspan="2"> <strong>ИТОГО: <?php echo $cart->total_sum ?></strong><br clear="all" /> <input type="image" name="submit" src="<?php echo URL::base(FALSE) . 'public/css/img/order.gif'; ?>" alt="оформить заказ" class="OrderFinal" /> </td> </tr> </table> <?php echo $form->render_form_close(); ?> <file_sep>/modules/shop/sites/classes/model/site.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Site extends Model { /** * Current site * * @var Model_Site */ protected static $_current; /** * Get currently active site * * @return Model_Site */ public static function current() { if ( ! isset(Model_Site::$_current)) { $site = new Model_Site(); if (Kohana::config('sites.multi')) { // Determine current site for multi-site environment // by "site_id" param or by host name $site_id = Request::current()->param('site_id', NULL); if (APP == 'BACKEND' && ! empty($site_id)) { // Detect site by explicitly specified id $site->find($site_id); } elseif (APP == 'FRONTEND') { // Detect site by url for frontend application $url = self::canonize_url(URL::base(FALSE, TRUE)); $site->find_by_url($url); } } else { // Don't use multisite feature - there is always a single site // Select the first one from db $site->find_by(); } Model_Site::$_current = $site; } return Model_Site::$_current; } /** * Get site caption by site id * * @param integer $id * @return string */ public static function caption($id) { // Obtain all sites (CACHED!) $sites = Model::fly('Model_Site')->find_all(); if (isset($sites[$id])) { return $sites[$id]->caption; } else { return NULL; } } /** * Canonize site url * - strip out protocols * - strip out "www." * - strip out port * - trim slashes * * @param string $url */ public static function canonize_url($url) { $info = @parse_url($url); if ($info === FALSE) { // url is really seriously malformed return $url; } $host = isset($info['host']) ? $info['host'] : ''; $path = isset($info['path']) ? $info['path'] : ''; // Strip out 'www.' if (strpos($host, 'www.') === 0) { $host = substr($host, strlen('www.')); } $path = rtrim($path, '/\\'); return $host . $path; } /** * Set site url * * @param string $url */ public function set_url($url) { $this->_properties['url'] = self::canonize_url($url); } /** * Validate new values * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { if (Kohana::config('sites.multi')) { // ----- url if ( ! isset($newvalues['url'])) { $this->error('Вы не указали адрес', 'url'); return FALSE; } if (@parse_url($newvalues['url']) === FALSE) { $this->error('Некорректный адрес сайта', 'url'); return FALSE; } } return TRUE; } /** * Save the site * * @param boolean $force_create */ public function save($force_create = FALSE) { if ( ! isset($this->id)) { // Creating a new site parent::save($force_create); // ----- Create the default structure // 1) System product properties /* $property = new Model_Property(); $property->init(array( 'site_id' => $this->id, 'name' => 'price', 'caption' => 'Цена', 'type' => Model_Property::TYPE_TEXT, 'system' => TRUE )); $property->save(); * */ } else { return parent::save($force_create); } } /** * Default parameters for find_all_by_...() methods * * @return array */ public function params_for_find_all() { return array( 'key' => 'id', 'order_by' => 'id', 'desc' => FALSE ); } }<file_sep>/modules/system/forms/classes/form/element/file.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Form file upload element * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_File extends Form_Element_Input { /** * Add the 'multipart/form-data' attribute for form this element belongs to * * @param Form $form */ public function form(Form $form = NULL) { if ($form !== NULL) { $form->attribute('enctype', 'multipart/form-data'); } return parent::form($form); } /** * @return string */ public function get_type() { return 'file'; } /** * Full name of file element - to use in form HTML. * * Unlike ordinary element ($form_name[$element_name]) it's impossible to * pass file name in array, so we have to construct it in another way. * * @return string */ public function get_full_name() { return $this->form()->name . '_' . $this->name; } /** * Get element value - an array with information about uploaded file (if any) * from $_FILES * * @return array */ public function get_value() { if (isset($_FILES[$this->full_name])) { return $_FILES[$this->full_name]; } else { return NULL; } } /** * Renders file input * * @return string */ public function render_input() { return Form_Helper::input($this->full_name, NULL, $this->attributes()); } } <file_sep>/modules/general/filemanager/views/backend/list_style/thumbs.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <div class="files thumbs"> <?php $file = new Model_File(); foreach ($files as $properties) : $file->path = $properties['path']; if ($file->is_dot() || $file->is_hidden()) { // Skip hidden continue; } $relative_path_encoded = URL::encode($file->relative_path); if ($file->is_dir()) { $class = 'folder'; $target = ''; $url = str_replace('${path}', $relative_path_encoded, $dir_url); } else { // Strip unknown symbols $class = preg_replace('[^\w-]', '', $file->ext); if (strlen($class) && ctype_digit($class[0])) { // If extentsion starts with digit - prepend css class with "_" $class = '_' . $class; } // Add "file_link" class $class= "file_link $class"; $target = ''; // Url to file if (in_array(strtolower($file->ext), Kohana::config('filemanager.ext_editable'))) { // File can be edited in backend $url = str_replace('${path}', $relative_path_encoded, $editfile_url); } else { // Url to view file file $url = File::url($file->path); // Open/download files in new window $target = 'target="_blank"'; } } $_edit_url = str_replace('${path}', $relative_path_encoded, $edit_url); $_del_url = str_replace('${path}', $relative_path_encoded, $delete_url); ?> <div class="file_thumb"> <div class="ctl"> <?php echo View_Helper_Admin::image_control($_edit_url, 'Изменить имя файла', 'controls/edit.gif', 'Переименовать'); ?> <?php echo View_Helper_Admin::image_control($_del_url, 'Удалить файл', 'controls/delete.gif', 'Удалить'); ?> </div> <div class="file"> <?php // Render thumbnails for images $thumb_path = $file->get_thumb_path('preview'); if ($thumb_path !== NULL) { $thumb_url = File::url($thumb_path); if ($thumb_url !== NULL) { $img = ' style="background-image: url(' . FILE::url($thumb_path) . ');"'; } } else { $img = ''; } if ($url !== NULL) { echo '<a href="' . $url . '" class="' . $class . '" ' . $target . $img . '></a>'; } else { echo '<span class="' . $class . '"' . $img . '>' . $img . '</span>'; } ?> </div> <div class="file_caption"> <?php if ($url !== FALSE) { echo '<a href="' . $url . '" class="file_link" ' . $target . '>' . HTML::chars($file->base_name) . '</a>'; } else { echo '<span>' . HTML::chars($file->base_name) . '</span>'; } ?> </div> </div> <?php endforeach; ?> </div><file_sep>/modules/shop/acl/classes/form/frontend/notify.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Frontend_Notify extends Form_Frontend { /** * Initialize form fields */ public function init() { // Render using view $this->view_script = 'frontend/forms/notify'; $element = new Form_Element_Text('text', array('class' => 'confirm_message')); $element->value = "Зарегистрируйтесь или войдите в свою учетную запись"; $this->add_component($element); // ----- Form buttons $button = new Form_Element_Button('submit_notify', array('label' => 'Вернуться'), array('class' => 'button_notify button-modal') ); $this->add_component($button); parent::init(); } }<file_sep>/modules/general/blocks/config/blocks.php <?php defined('SYSPATH') or die('No direct access allowed.'); return array ( // Available block names 'names' => array( 'about' => 'О проекте', 'short_about' => 'Коротко о проекте', 'events' => 'События', 'faq' => 'FAQ', 'main_page_adv' => 'Реклама', ) );<file_sep>/modules/shop/catalog/views/backend/sectiongroups/select.php <?php defined('SYSPATH') or die('No direct script access.'); ?> <?php // ----- Set up urls // Submit results to previous url $sectiongroups_select_uri = URL::uri_back(); ?> <?php echo View_Helper_Admin::multi_action_form_open($sectiongroups_select_uri, array('name' => 'sectiongroups_select')); ?> <table class="sectiongroups_select table"> <tr class="header"> <th><?php echo View_Helper_Admin::multi_action_select_all(); ?></th> <?php $columns = array( 'caption' => 'Название', ); echo View_Helper_Admin::table_header($columns, 'cat_sorder', 'cat_sdesc'); ?> </tr> <?php foreach ($sectiongroups as $sectiongroup) : ?> <tr> <td class="multi_ctl"> <?php echo View_Helper_Admin::multi_action_checkbox($sectiongroup->id); ?> </td> <?php foreach (array_keys($columns) as $field): ?> <td> <?php if (isset($sectiongroup->$field) && trim($sectiongroup->$field) !== '') { echo HTML::chars($sectiongroup->$field); } else { echo '&nbsp'; } ?> </td> <?php endforeach; ?> </tr> <?php endforeach; ?> </table> <?php echo View_Helper_Admin::multi_actions(array( array('action' => 'sectiongroups_select', 'label' => 'Выбрать', 'class' => 'button_select') )); ?> <?php echo View_Helper_Admin::multi_action_form_close(); ?><file_sep>/modules/shop/catalog/init.php <?php defined('SYSPATH') or die('No direct script access.'); /****************************************************************************** * Frontend ******************************************************************************/ if (APP === 'FRONTEND') { // ----- products Route::add('frontend/catalog/products/control', new Route_Frontend( 'catalog/products(/<action>(/<id>)(/type-<type_id>)(/product-<product_id>)(/user-<user_id>)(/lecturer-<lecturer_id>)(/opts-<options_count>)(/ids-<ids>))' . '(/group-<cat_sectiongroup_id>)(/section-<cat_section_id>)(/sections-<cat_section_ids>)' . '(/porder-<cat_porder>)(/pdesc-<cat_pdesc>)' . '(/page-<page>)' // search params . '(/search-<search_text>)' . '(/active-<active>)' , array( 'action' => '\w++', 'type_id' => '\d++', 'id' => '\d++', 'product_id' => '\d++', 'user_id' => '\d++', 'lecturer_id' => '\d++', 'options_count' => '\d++', 'ids' => '[\d_]++', 'cat_sectiongroup_id' => '\d++', 'cat_section_id' => '\d++', 'cat_section_ids' => '[\d_]++', 'cat_porder' => '\w++', 'cat_pdesc' => '[01]', 'page' => '(\d++|all)', 'search_text' => '\w++', 'active' => '[01]' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'index', 'type_id' => NULL, 'id' => NULL, 'product_id' => NULL, 'user_id' => NULL, 'lecturer_id' => NULL, 'options_count' => NULL, 'ids' => '', 'cat_sectiongroup_id' => NULL, 'cat_section_id' => '0', 'cat_section_ids' => '', 'cat_porder' => 'id', 'cat_pdesc' => '1', 'page' => '0', 'search_text' => '', 'active' => '-1' )); // ----- List of products in section Route::add('frontend/catalog/products', new Route_Frontend( 'events(/p-<page>)(/format-<format>)(/theme-<theme>)(/calendar-<calendar>)' , array( 'page' => '(\d++|all)', 'format' => '\d++', 'theme' => '\d++', 'calendar' => '[P0-9MWD]+', ) )) ->defaults(array( 'controller' => 'products', 'action' => 'index', 'page' => '0', 'format' => NULL, 'theme' => NULL , 'calendar' => NULL )); // // ----- productcomments // Route::add('frontend/products/telemosts', new Route_Frontend( // 'products/telemosts(/<action>(/<id>)(/product-<product_id>))' // . '(/~<history>)' // , // array( // 'action' => '\w++', // 'id' => '\d++', // 'product_id' => '\d++', // // 'history' => '.++' // ) // )) // ->defaults(array( // 'controller' => 'telemosts', // 'action' => 'index', // 'id' => NULL, // 'product_id' => NULL // )); // // ----- Search Route::add('frontend/catalog/search', new Route_Frontend( 'catalog/search(/catalog-<sectiongroup_name>)(/text-<search_text>)' . '(/p-<page>)' . '(/date-<date>)' . '(/tag-<tag>)' , array( 'sectiongroup_name' => '\w++', 'path' => '[/a-z0-9_-]+?', 'page' => '(\d++|all)', 'date' => '[0-9\.]++', 'tag' => '[a-z0-9_-]++', 'search_text' => '[a-z0-9]++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'search', 'search_text' => '', 'page' => '1', 'tag' => NULL, 'price_from' => '', 'price_to' => '' )); // ----- Product Route::add('frontend/catalog/product', new Route_Frontend( 'catalog-<sectiongroup_name>(/stage-<stage>)/<path>/<alias>.html(/image-<image_id>)' , array( 'sectiongroup_name' => '\w++', 'stage' => '\w++', 'path' => '[/a-z0-9_-]+?', 'alias' => '[a-z0-9_-]++', 'image_id' => '\d++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'product', 'stage' => NULL, 'image_id' => NULL )); // ----- fullscreen comdi Route::add('frontend/catalog/product/fullscreen', new Route_Frontend( 'catalog/product/fullscreen(/width-<width>)(/height-<height>)/<alias>.html' , array( 'sectiongroup_name' => '\w++', 'path' => '[/a-z0-9_-]+?', 'alias' => '[a-z0-9_-]++', 'width' => '\d++', 'height' => '\d++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'fullscreen', 'width' => NULL, 'height' => NULL )); // ----- Ajax Product /*Route::add('frontend/catalog/product/choose', new Route_Frontend( 'choose-<alias>.html' , array( 'alias' => '[a-z0-9_-]++', ) )) ->defaults(array( 'controller' => 'products', 'action' => 'choose', )); */ // ----- Product Route::add('frontend/catalog', new Route_Frontend('(p-<page>)' ,array( 'page' => '(\d++|all)', ))) ->defaults(array( 'controller' => 'products', 'action' => 'index', 'page' => '1' )); // ----- product_choose Route::add('frontend/catalog/product/choose', new Route_Frontend( 'catalog/product/choose-<alias>.html' , array( 'alias' => '[a-z0-9_-]++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_product_choose' )); // ----- product_choose Route::add('frontend/catalog/telemost/select', new Route_Frontend( 'catalog/telemost/select-<telemost_id>' , array( 'telemost_id' => '\d++' ) )) ->defaults(array( 'controller' => 'telemosts', 'action' => 'ajax_telemost_select', 'telemost_id'=> NULL )); // ----- product_buy Route::add('frontend/catalog/telemost/updatebill', new Route_Frontend( 'catalog/telemost/updatebill' , array( ) )) ->defaults(array( 'controller' => 'telemosts', 'action' => 'updatebill' )); // ----- product_choose Route::add('frontend/catalog/smallproduct/choose', new Route_Frontend( 'catalog/smallproduct/choose-<alias>.html' , array( 'alias' => '[a-z0-9_-]++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_smallproduct_choose' )); // ----- product_choose Route::add('frontend/catalog/product/unchoose', new Route_Frontend( 'catalog/product/unchoose-<alias>.html' , array( 'alias' => '[a-z0-9_-]++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_product_unchoose' )); // ----- product_choose Route::add('frontend/catalog/smallproduct/unchoose', new Route_Frontend( 'catalog/smallproduct/unchoose-<alias>.html' , array( 'alias' => '[a-z0-9_-]++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_smallproduct_unchoose' )); // ----- product_choose Route::add('frontend/catalog/ajax_products', new Route_Frontend( 'ajax_events' . '(/ap-<apage>)' , array( 'apage' => '\d++', ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_products', 'apage' => '0', )); // ----- product_choose Route::add('frontend/catalog/ajax_telemosts', new Route_Frontend( 'ajax_telemosts' . '(/tp-<tpage>)' , array( 'tpage' => '\d++', ) )) ->defaults(array( 'controller' => 'telemosts', 'action' => 'ajax_telemosts', 'tpage' => '0', )); // ----- product_choose Route::add('frontend/catalog/ajax_app_telemosts', new Route_Frontend( 'ajax_app_telemosts' . '(/rp-<rpage>)' , array( 'rpage' => '\d++', ) )) ->defaults(array( 'controller' => 'telemosts', 'action' => 'ajax_app_telemosts', 'rpage' => '0', )); // ----- product_choose Route::add('frontend/catalog/ajax_goes', new Route_Frontend( 'ajax_goes' . '(/mp-<mpage>)' , array( 'mpage' => '\d++', ) )) ->defaults(array( 'controller' => 'telemosts', 'action' => 'ajax_goes', 'mpage' => '0', )); // ----- product_choose Route::add('frontend/catalog/smallproduct/unrequest', new Route_Frontend( 'catalog/smallproduct/unrequest-<alias>.html' , array( 'alias' => '[a-z0-9_-]++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_smallproduct_unrequest' )); // Unrequest product on product page Route::add('frontend/catalog/product/unrequest', new Route_Frontend( 'catalog/product/unrequest-<alias>.html' , array( 'alias' => '[a-z0-9_-]++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_product_unrequest' )); // ----- product_images Route::add('frontend/catalog/product/images', new Route_Frontend( 'catalog/product/images' , array( ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_product_images' )); // ----- product_images Route::add('frontend/catalog/small_product', new Route_Frontend( 'catalog/product/small' , array( ) )) ->defaults(array( 'controller' => 'products', 'action' => 'ajax_small_product' )); // ----- Product Route::add('frontend/catalog', new Route_Frontend('(p-<page>)' ,array( 'page' => '(\d++|all)', ))) ->defaults(array( 'controller' => 'products', 'action' => 'index', 'page' => '1' )); } /****************************************************************************** * Backend ******************************************************************************/ if (APP === 'BACKEND') { // ----- products Route::add('backend/catalog/products', new Route_Backend( 'catalog/products(/<action>(/<id>)(/type-<type_id>)(/product-<product_id>)(/user-<user_id>)(/lecturer-<lecturer_id>)(/place-<place_id>)(/opts-<options_count>)(/ids-<ids>))' . '(/group-<cat_sectiongroup_id>)(/section-<cat_section_id>)(/sections-<cat_section_ids>)(/towns-<access_town_ids>)(/organizers-<access_organizer_ids>)(/users-<access_user_ids>)' . '(/porder-<cat_porder>)(/pdesc-<cat_pdesc>)' . '(/page-<page>)' // search params . '(/search-<search_text>)' . '(/active-<active>)' . '(/~<history>)' , array( 'action' => '\w++', 'type_id' => '\d++', 'id' => '\d++', 'product_id' => '\d++', 'user_id' => '\d++', 'lecturer_id' => '\d++', 'place_id' => '\d++', 'options_count' => '\d++', 'ids' => '[\d_]++', 'cat_sectiongroup_id' => '\d++', 'cat_section_id' => '\d++', 'cat_section_ids' => '[\d_]++', 'access_user_ids' => '[\d_]++', 'access_organizer_ids' => '[\d_]++', 'access_town_ids' => '[\d_]++', 'cat_porder' => '\w++', 'cat_pdesc' => '[01]', 'page' => '(\d++|all)', 'search_text' => '\w++', 'active' => '[01]', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'products', 'action' => 'index', 'type_id' => NULL, 'id' => NULL, 'product_id' => NULL, 'user_id' => NULL, 'lecturer_id' => NULL, 'place_id' => NULL, 'options_count' => NULL, 'ids' => '', 'cat_sectiongroup_id' => NULL, 'cat_section_id' => '0', 'cat_section_ids' => '', 'access_user_ids' => '', 'access_organizer_ids' => '', 'access_town_ids' => '', 'cat_porder' => 'id', 'cat_pdesc' => '1', 'page' => '0', 'search_text' => '', 'active' => '-1' )); // ----- sectiongroups Route::add('backend/catalog/sectiongroups', new Route_Backend( 'catalog/sectiongroups(/<action>(/<id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'sectiongroups', 'action' => 'index', 'id' => NULL )); // ----- sections Route::add('backend/catalog/sections', new Route_Backend( 'catalog/sections(/<action>(/<id>)(/ids-<ids>)(/<toggle>))' . '(/group-<cat_sectiongroup_id>)' . '(/section-<cat_section_id>)' . '(/sorder-<cat_sorder>)(/sdesc-<cat_sdesc>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'toggle' => '(on|off)', 'cat_sectiongroup_id'=> '\d++', 'cat_section_id' => '\d++', 'cat_sorder' => '\w++', 'cat_sdesc' => '[01]', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'sections', 'action' => 'index', 'id' => NULL, 'ids' => '', 'cat_sorder' => 'lft', 'cat_sdesc' => '0', 'toggle' => '', 'cat_section_id' => '0', )); // ----- properties Route::add('backend/catalog/properties', new Route_Backend( 'catalog/properties(/<action>(/<id>))' . '(/sectiongroups-<cat_sectiongroup_ids>)' . '(/opts-<options_count>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'cat_sectiongroup_ids' => '[\d_]++', 'options_count' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'properties', 'action' => 'index', 'id' => NULL, 'cat_sectiongroup_ids' => '', 'options_count' => NULL )); // ----- plists Route::add('backend/catalog/plists', new Route_Backend( 'catalog/plists(/<action>(/<id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'plists', 'action' => 'index', 'id' => NULL )); // ----- plistproducts Route::add('backend/catalog/plistproducts', new Route_Backend( 'catalog/plistproducts(/<action>(/<id>)(/ids-<ids>)(/product-<product_id>)(/plist-<plist_id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'ids' => '[\d_]++', 'product_id' => '\d++', 'plist_id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'plistproducts', 'action' => 'index', 'id' => NULL, 'ids' => '', 'product_id' => NULL, 'plist_id' => NULL )); // ----- import Route::add('backend/catalog/import', new Route_Backend('catalog/import(/<action>)') , array( 'action' => '\w++' ) ) ->defaults(array( 'controller' => 'catimport', 'action' => 'index', )); // ----- catalog Route::add('backend/catalog', new Route_Backend( 'catalog(/<action>(/<id>))' . '(/group-<cat_sectiongroup_id>)' . '(/section-<cat_section_id>)(/p-<page>)(/tab-<tab>)' . '(/product-<product_id>)' . '(/sorder-<cat_sorder>)(/sdesc-<cat_sdesc>)' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'cat_sectiongroup_id' => '\d++', 'cat_section_id' => '\d++', 'page' => '\d++', 'tab' => '\w++', 'product_id' => '\d++', 'cat_porder' => '\w++', 'cat_pdesc' => '[01]', 'cat_sorder' => '\w++', 'cat_sdesc' => '[01]', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'catalog', 'action' => 'index', 'id' => NULL, 'cat_sectiongroup_id' => '0', 'cat_section_id' => '0', 'page' => '0', 'tab' => 'catalog', 'product_id' => NULL, 'cat_sorder' => 'lft', 'cat_sdesc' => '0', 'cat_prorder' => 'position', 'cat_prdesc' => '0', )); // ----- productcomments Route::add('backend/products/telemosts', new Route_Backend( 'products/telemosts(/<action>(/<id>)(/product-<product_id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'product_id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'telemosts', 'action' => 'index', 'id' => NULL, 'product_id' => NULL )); // ----- productcomments Route::add('backend/products/goes', new Route_Backend( 'products/goes(/<action>(/<id>)(/telemost-<telemost_id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'telemost_id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'goes', 'action' => 'index', 'id' => NULL, 'telemost_id' => NULL )); // ----- productcomments Route::add('backend/products/comments', new Route_Backend( 'products/comments(/<action>(/<id>)(/product-<product_id>))' . '(/~<history>)' , array( 'action' => '\w++', 'id' => '\d++', 'product_id' => '\d++', 'history' => '.++' ) )) ->defaults(array( 'controller' => 'productcomments', 'action' => 'index', 'id' => NULL, 'product_id' => NULL )); // ----- Add backend menu items $parent_id = Model_Backend_Menu::add_item(array( 'menu' => 'main', 'site_required' => TRUE, 'id' => 3, 'caption' => 'Каталог', 'route' => 'backend/catalog/products', 'select_conds' => array( array('route' => 'backend/catalog/sectiongroups'), array('route' => 'backend/catalog/sections'), array('route' => 'backend/catalog/products'), array('route' => 'backend/catalog/properties'), array('route' => 'backend/catalog/plists'), array('route' => 'backend/catalog/plistproducts'), array('route' => 'backend/catalog/import'), array('route' => 'backend/catalog') ), 'icon' => 'catalog' )); $parent_id2 = Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'События', 'route' => 'backend/catalog/products', )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id2, 'site_required' => TRUE, 'caption' => 'Выбор событий', 'route' => 'backend/catalog/products', 'select_conds' => array( array('route' => 'backend/catalog/products', 'route_params' => array('action' => 'products_select')), ) )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Разделы', 'route' => 'backend/catalog/sections' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Характеристики', 'route' => 'backend/catalog/properties' )); Model_Backend_Menu::add_item(array( 'menu' => 'main', 'parent_id' => $parent_id, 'site_required' => TRUE, 'caption' => 'Группы категорий', 'route' => 'backend/catalog/sectiongroups' )); } /****************************************************************************** * Common ******************************************************************************/ Model_Privilege::add_privilege_type('products_control', array( 'name' => 'Управление анонсами событий', 'readable' => TRUE, 'controller' => 'products', 'action' => 'control', 'frontend_route' => 'frontend/catalog/products/control', 'frontend_route_params' => array('action' => 'control'), )); // ----- Add privilege types Model_Privilege::add_privilege_type('announce_create', array( 'name' => 'Создание анонса', 'readable' => FALSE, 'controller' => 'products', 'action' => 'create' )); Model_Privilege::add_privilege_type('announce_update', array( 'name' => 'Редактирование анонса', 'readable' => FALSE, 'controller' => 'products', 'action' => 'update' )); Model_Privilege::add_privilege_type('announce_delete', array( 'name' => 'Удаление анонса', 'readable' => FALSE, 'controller' => 'products', 'action' => 'delete' )); Model_Privilege::add_privilege_type('announce_users', array( 'name' => 'Организаторы События', 'readable' => FALSE, 'system' => TRUE )); Model_Privilege::add_privilege_type('start_event', array( 'name' => 'Начать Мероприятие', 'readable' => FALSE, 'controller' => 'products', 'action' => 'product', 'route_params' => array('stage' => Model_Product::START_STAGE) )); Model_Privilege::add_privilege_type('stop_event', array( 'name' => 'Завершить Мероприятие', 'readable' => FALSE, 'controller' => 'products', 'action' => 'product', 'route_params' => array('stage' => Model_Product::STOP_STAGE) )); //Model_Privilege::add_privilege_type('events_control', array( // 'name' => 'Управление Событиями', // 'readable' => TRUE, // 'controller' => 'products', // 'action' => 'eventcontrol', // 'frontend_route' => 'frontend/catalog/products/control', // 'frontend_route_params' => array('action' => 'eventcontrol'), //)); //// ----- Add privilege types //Model_Privilege::add_privilege_type('event_create', array( // 'name' => 'Создание event-a', // 'readable' => FALSE, // 'controller' => 'products', // 'action' => 'create', // 'route_params' => array('type_id' => Model_SectionGroup::TYPE_EVENT) //)); //Model_Privilege::add_privilege_type('event_update', array( // 'name' => 'Редактирование event-a', // 'readable' => FALSE, // 'controller' => 'products', // 'action' => 'update', // 'route_params' => array('type_id' => Model_SectionGroup::TYPE_EVENT) //)); //Model_Privilege::add_privilege_type('event_delete', array( // 'name' => 'Удаление event-a', // 'readable' => FALSE, // 'controller' => 'products', // 'action' => 'delete', // 'route_params' => array('type_id' => Model_SectionGroup::TYPE_EVENT) //)); // Add node types // Use text page as index page for site Model_Node::add_node_type('indexpage', array( 'name' => 'Главная страница', 'backend_route' => 'backend/catalog/products', 'frontend_route' => 'frontend/catalog' )); /****************************************************************************** * Module installation ******************************************************************************/ if (Kohana::$environment !== Kohana::PRODUCTION) { // Create main sectiongroup and section $sectiongroup = new Model_SectionGroup(); if ( ! $sectiongroup->count()) { $sectiongroup->properties(array( 'system' => 1, 'site_id' => (int)Model_Site::current()->id, 'name' => 'event', 'caption' => 'События')); $sectiongroup->save(); $section = new Model_Section(); if ( $section->count()) $section->delete_all_by(); $section = new Model_Section(array( 'system' => 1, 'id' => Model_Section::EVENT_ID, 'caption' => 'События', 'sectiongroup_id' => $sectiongroup->id)); $section->save(true); } }<file_sep>/modules/shop/area/public/js/frontend/place_name.js /** * Set form element value */ jFormElement.prototype.set_place_name = function(value) { if (value['name'] && value['id']) { $('#' + 'place_name').val(value['name']); $('#' + 'place_id').val(value['id']); } else { $('#' + 'place_name').val(value); } }<file_sep>/modules/general/menus/classes/controller/frontend/menus.php <?php defined('SYSPATH') or die('No direct script access.'); class Controller_Frontend_Menus extends Controller_Frontend { /** * Render menu with given name * * @param string $name * @return string */ public function widget_menu($name) { // Find menu by name $menu = new Model_Menu(); $menu->find_by_name($name); if ( ! isset($menu->id)) { throw new Kohana_Exception('Меню с именем ":name" не найдено!', array(':name' => $name)); } // Load all visible nodes for the menu $nodes = $menu->visible_nodes; // Path to the currently selected node $path = Model_Node::current()->path; $view = new View('menu_templates/' . $menu->view); $view->menu = $menu; $view->root_node = $menu->root_node; $view->current_node = Model_Node::current(); $view->nodes = $nodes; $view->path = $path; return $view; } } <file_sep>/modules/shop/delivery_courier/classes/form/backend/delivery/courier/properties.php <?php defined('SYSPATH') or die('No direct script access.'); class Form_Backend_Delivery_Courier_Properties extends Form_Backend_Delivery_Properties { /** * Initialize form fields */ public function init() { // ----- City $element = new Form_Element_Input('city', array('label' => 'Город', 'disabled' => TRUE)); $element->value = 'Москва'; $this->add_component($element); // ----- zone_id // Obtain a list of zones $zones = Model::fly('Model_CourierZone')->find_all_by_delivery_id($this->delivery()->id, array('order_by' => 'position', 'desc' => FALSE)); $options = array(); foreach ($zones as $zone) { $options[$zone->id] = $zone->name; } $element = new Form_Element_Select('zone_id', $options, array('label' => 'Зона доставки')); $element ->add_validator(new Form_Validator_InArray(array_keys($options))); $this->add_component($element); // ----- Address $element = new Form_Element_Textarea('address', array('label' => 'Адрес'), array('rows' => 3)); $element ->add_filter(new Form_Filter_TrimCrop(511)); $this->add_component($element); } } <file_sep>/modules/shop/catalog/classes/model/product.php <?php defined('SYSPATH') or die('No direct script access.'); class Model_Product extends Model_Res { const SHORT_DESC_WORDS = 25; const LINKS_LENGTH = 36; //Time before starting the event when Video Platform becomes available (in minutes) const SHOW_TIME = 10; // Telemosts's providers const COMDI = 'COMDI'; const HANGOTS = 'HANGOUTS'; // available phases of COMDI events const DEF_STAGE = 'wait'; const ACTIVE_STAGE = 'active'; const START_STAGE = 'start'; const STOP_STAGE = 'stop'; const HANGOUTS_STOP_KEY = 'stop'; // duration options const DURATION_1 = 'PT30M'; const DURATION_2 = 'PT1H'; const DURATION_3 = 'PT1H30M'; const DURATION_4 = 'PT2H'; const DURATION_5 = 'PT2H30M'; const DURATION_6 = 'PT3H'; const DURATION_7 = 'PT3H30M'; const DURATION_8 = 'PT4H'; const DURATION_9 = 'PT4H30M'; const DURATION_10 = 'PT5H'; // theme options const THEME_1 = 1; const THEME_2 = 2; const THEME_3 = 3; const THEME_4 = 4; const THEME_5 = 5; const THEME_6 = 6; const THEME_7 = 7; const THEME_8 = 8; const THEME_9 = 9; const THEME_10 = 10; const THEME_11 = 11; const THEME_12 = 12; const THEME_13 = 13; // FORMAT options const FORMAT_1 = 1; const FORMAT_2 = 2; const FORMAT_3 = 3; const FORMAT_4 = 4; const FORMAT_5 = 5; const FORMAT_6 = 6; const FORMAT_7 = 7; const FORMAT_8 = 8; const FORMAT_9 = 9; const FORMAT_10 = 10; // CALENDAR options const CALENDAR_TODAY = 'P0D'; const CALENDAR_ONEWEEK = 'P1W'; const CALENDAR_TWOWEEK = 'P2W'; const CALENDAR_ONEMONTH = 'P1M'; const CALENDAR_ARCHIVE = 'CLNDARCH'; const INTERACT_LIVE = 1; const INTERACT_STREAM = 2; const CHOALG_RANDOM = 1; const CHOALG_MANUAL = 2; const CHOALG_ORDER = 3; public static $date_as_timestamp = FALSE; public static $_duration_options = array( self::DURATION_1 => '0.30 ч.', self::DURATION_2 => '1.00 ч.', self::DURATION_3 => '1.30 ч.', self::DURATION_4 => '2.00 ч.', self::DURATION_5 => '2.30 ч.', self::DURATION_6 => '3.00 ч.', self::DURATION_7 => '3.30 ч.', self::DURATION_8 => '4.00 ч.', self::DURATION_9 => '4.30 ч.', self::DURATION_10 => '5.00 ч.' ); public static $_theme_options = array( self::THEME_1 => 'дизайн', self::THEME_2 => 'архитектура', self::THEME_3 => 'медиа', self::THEME_4 => 'общество', self::THEME_5 => 'искусство', self::THEME_6 => 'бизнес', self::THEME_7 => 'город', self::THEME_8 => 'технологии', self::THEME_9 => 'наука', self::THEME_10 => 'языки', self::THEME_11 => 'культура', self::THEME_12 => 'фотография', self::THEME_13 => 'кино' ); public static $_format_options = array( self::FORMAT_1 => 'лекция', self::FORMAT_2 => 'мастер-класс', self::FORMAT_3 => 'экскурсия', self::FORMAT_4 => 'показ', self::FORMAT_5 => 'круглый стол', self::FORMAT_6 => 'обсуждение', self::FORMAT_7 => 'конференция', self::FORMAT_8 => 'семинар', self::FORMAT_9 => 'встреча', self::FORMAT_10 => 'дебаты' ); public static $_calendar_options = array( self::CALENDAR_TODAY => 'сегодня', self::CALENDAR_ONEWEEK => 'через неделю', self::CALENDAR_TWOWEEK => 'через две недели', self::CALENDAR_ONEMONTH => 'через месяц', ); public static $_interact_options = array( self::INTERACT_LIVE => 'Телемост', self::INTERACT_STREAM => 'Стриминг' ); public static $_numviews_options = array( 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9', 10 => '10', 11 => '11', 12 => '12', 13 => '13', 14 => '14', 15 => '15', ); public static $_choalg_options = array( self::CHOALG_ORDER => 'алгоритм (в порядке очередности заявок)', self::CHOALG_RANDOM => 'алгоритм (случайный выбор)', self::CHOALG_MANUAL => 'автор анонса' ); public static $_telemost_provider_options = array( self::COMDI => 'webinar.ru (COMDI)', self::HANGOTS => 'Google Hangouts', ); public $backup = array('sections'); /** * Get currently selected product (FRONTEND) * * @param Request $request (if NULL, current request will be used) * @return Model_Product */ public static function current(Request $request = NULL) { if ($request === NULL) { $request = Request::current(); } // cache? $product = $request->get_value('product'); if ($product !== NULL) return $product; $product = new Model_Product(); if ($request->param('alias') != '' && Model_Section::current()->id !== NULL) { $product->find_by_alias_and_section_and_active( $request->param('alias'), Model_Section::current(), 1, array('with_image' => '3') ); } $request->set_value('product', $product); return $product; } public function get_uri_frontend() { return $this->uri_frontend(); } /** * Get frontend uri to the product */ public function uri_frontend(Model_Section $parent_section = NULL, $stage = NULL) { $uri_params['sectiongroup_name'] = '{{sectiongroup_name}}'; $uri_params['path'] = '{{path}}'; $uri_params['alias'] = '{{alias}}'; if ($stage) $uri_params['stage'] = $stage; $uri_template = URL::uri_to('frontend/catalog/product', $uri_params); if ($parent_section !== NULL) { $sections = Model::fly('Model_Section')->find_all_active_cached($parent_section->sectiongroup_id, FALSE); // Select the section that will be used to build an uri to product // (there can be several sections to which this product is linked, so we have to select only one) if (isset($this->sections[$parent_section->sectiongroup_id]) && isset($sections)) { // Choose the first section to which this product is linked and which is also a descendant of $parent_section $section_ids = array_keys(array_filter($this->sections[$parent_section->sectiongroup_id])); foreach ($section_ids as $section_id) { $sec = $sections[$section_id]; if ($sec->id == $parent_section->id || $sections->is_descendant($sec, $parent_section)) { $section = $sec; break; } } } } if ( ! isset($section)) { // Igonre parent_section and simply choose the main section for product // try cache // foreach (Model::fly('Model_SectionGroup')->find_all_by_site_id(Model_Site::current()->id) as $sectiongroup) foreach (Model::fly('Model_SectionGroup')->find_all_cached() as $sectiongroup) { $sections = Model::fly('Model_Section')->find_all_active_cached($sectiongroup->id, FALSE); if (isset($sections[$this->section_id])) { $section = $sections[$this->section_id]; break; } } if ( ! isset($section)) { // finally, load from db $section = new Model_Section(); $section->find($this->section_id); } } return str_replace( array('{{sectiongroup_name}}', '{{path}}', '{{alias}}'), array($section->sectiongroup_name, $section->full_alias, $this->alias), $uri_template ); } /** * Make alias for product from it's marking or id * * @return string */ public function make_alias() { $marking_alias = str_replace(' ', '_', strtolower(l10n::transliterate($this->marking))); $marking_alias = preg_replace('/[^a-z0-9_-]/', '', $marking_alias); if ($marking_alias == '') { // If there is no marking - use product's id $marking_alias = 'event_' . rand(1,9999);//$this->id; } $i = 0; $loop_prevention = 1000; do { if ($i > 0) { $alias = substr($marking_alias, 0, 30); $alias .= $i; } else { $alias = substr($marking_alias, 0, 31); } $i++; } while ($this->exists_another_by_alias($alias) && ($loop_prevention-- > 0)); if ($loop_prevention <= 0) throw new Kohana_Exception ('Possible infinite loop in :method', array(':method' => __METHOD__)); return $alias; } /** * @return boolean */ public function default_active() { if (APP === 'BACKEND') { return TRUE; } return FALSE; } public function default_numviews() { return 4; } public function default_interact() { return self::INTERACT_LIVE; } public function default_choalg() { return self::CHOALG_ORDER; } /** * @return boolean */ public function default_visible() { return TRUE; } /** * @return integer */ public function default_import_id() { return 0; } /** * @return Money */ public function default_price() { return new Money(); } public function default_telemost_provider() { return self::COMDI; } public function get_telemost_provider() { if (!isset($this->_properties['telemost_provider'])) $this->_properties['telemost_provider'] = $this->default_telemost_provider(); if (empty($this->_properties['telemost_provider'])) $this->_properties['telemost_provider'] = $this->default_telemost_provider(); return $this->_properties['telemost_provider']; } /** * Get additional sections this product belongs to for each sectiongroup * * @return array array(sectiongroup_id=>section_id=>1/0) */ public function get_sections() { if ( ! isset($this->_properties['sections'])) { $result = array(); if (isset($this->id)) { $sections = Model::fly('Model_Section')->find_all_by_product($this, array( 'order_by' => 'lft', 'desc' => FALSE, 'columns' => array('id', 'sectiongroup_id')) ); foreach($sections as $section) { $result[$section->sectiongroup_id][$section->id] = 1; } } $this->_properties['sections'] = $result; } elseif (is_string($this->_properties['sections'])) { // section ids were concatenated with GROUP_CONCAT $sections = array(); $ids = explode(',', $this->_properties['sections']); foreach ($ids as $id_gid) { $section_id = strtok($id_gid, '-'); $sectiongroup_id = strtok('-'); $sections[$sectiongroup_id][$section_id] = TRUE; } $this->_properties['sections'] = $sections; } // Add main section, if neccessary if (is_array($this->_properties['sections'])) { $add_main_section = TRUE; foreach ($this->_properties['sections'] as $sectiongroup_id => $sections) { if ( ! empty($sections[$this->section_id])) { // Main section is already present in the linked sections $add_main_section = FALSE; } } if ($add_main_section) { $this->_properties['sections'][$this->section->sectiongroup_id][$this->section_id] = 1; } } return $this->_properties['sections']; } /** * Get product section ids * * @param integer $sectiongroup_id If specified then section ids only for this section group are returned * @return array */ public function get_section_ids($sectiongroup_id = NULL) { if (isset($sectiongroup_id)) { if (!isset($this->sections[$sectiongroup_id])) return array(); return array_keys(array_filter($this->sections[$sectiongroup_id])); } else { $section_ids = array(); if (isset($this->sections)) { foreach ($this->sections as $sectiongroup_id => $sections) { $section_ids[$sectiongroup_id] = array_keys(array_filter($sections)); } } return $section_ids; } } /** * Get active[!] additional properties for this product */ public function get_properties() { if ( ! isset($this->_properties['properties'])) { if ( ! empty($this->_properties['section_id'])) { $properties = Model::fly('Model_Property')->find_all_by_section_id_and_active_and_system( $this->_properties['section_id'], 1, 0, array('order_by' => 'position', 'desc' => FALSE) ); $this->_properties['properties'] = $properties; } else { return array(); } } return $this->_properties['properties']; } /** * Get main section for product * * @param array $params * @return Model_Section */ public function get_section(array $params = NULL) { if ( ! isset($this->_properties['section'])) { $section = new Model_Section(); $section->find((int) $this->section_id, $params); $this->_properties['section'] = $section; } return $this->_properties['section']; } public function get_place(array $params = NULL) { if ( ! isset($this->_properties['place'])) { $place = new Model_Place(); $place->find((int) $this->place_id, $params); $this->_properties['place'] = $place; } return $this->_properties['place']; } public function get_short_desc() { return TEXT::limit_words($this->description, self::SHORT_DESC_WORDS); } /** * Get product list ids to which this product belongs * * @return array array(plist_id=>1/0) */ public function get_plist_ids() { if ( ! isset($this->_properties['plist_ids'])) { $plist_ids = array(); if (isset($this->id)) { $plistproducts = Model::fly('Model_PListProduct')->find_all_by_product_id( (int) $this->id, array('columns' => array('plist_id'), 'as_array' => TRUE) ); foreach ($plistproducts as $plistproduct) { $plist_ids[$plistproduct['plist_id']] = 1; } } $this->_properties['plist_ids'] = $plist_ids; } return $this->_properties['plist_ids']; } /** * Set event datetime * * @param DateTime|string $value */ public function set_datetime($value) { if ($value instanceof DateTime) { $this->_properties['datetime'] = clone $value; } else { $this->_properties['datetime'] = new DateTime($value); } } /** * Get event datetime * * @return DateTime */ public function get_datetime() { if ( ! isset($this->_properties['datetime'])) { return NULL; } return clone $this->_properties['datetime']; } /** * Get event date as string * * @return string */ public function get_date() { return $this->datetime->format(Kohana::config('datetime.datetime_format')); } /** * Get event time as string * * @return string */ public function get_time() { return $this->datetime->format(Kohana::config('datetime.time_format')); } public function get_date_front() { return l10n::rdate(Kohana::config('datetime.date_format_front'),$this->datetime->format('U')); } public function get_datetime_front() { return l10n::rdate(Kohana::config('datetime.datetime_format_front'),$this->datetime->format('U')).' (МСК)'; } public function get_weekday() { return l10n::rdate(' D',$this->datetime->format('U')); } public function get_time_front() { return l10n::rdate(Kohana::config('datetime.time_format_front'),$this->datetime->format('U')); } /** * Get the event lecturer (if this event is personal) * * @return Model_Lecturer */ public function get_lecturer() { $lecturer = new Model_Lecturer(); $lecturer->find((int) $this->lecturer_id); return $lecturer; } /** * Get the event lecturer name (if this event is personal) * * @return Model_Lecturer */ public function get_lecturer_name() { if ( ! isset($this->_properties['lecturer_name'])) { $this->_properties['lecturer_name'] = $this->get_lecturer()->name; } return $this->_properties['lecturer_name']; } /** * Get the event lecturer (if this event is personal) * * @return Model_Organizer */ public function get_organizer() { $organizer = new Model_Organizer(); $organizer->find((int) $this->organizer_id); return $organizer; } /** * Get the organizator of the event * * @return Model_Lecturer */ public function get_organizer_name() { if ( ! isset($this->_properties['organizer_name'])) { $this->_properties['organizer_name'] = $this->get_organizer()->name; } return $this->_properties['organizer_name']; } public function get_tag_items() { if ( ! isset($this->_properties['tag_items'])) { if ($this->id) { $tags = Model::fly('Model_Tag')->find_all_by(array( 'owner_type' => 'product', 'owner_id' => $this->id ), array('order_by' => 'weight')); } else { $tags = array(); } $this->_properties['tag_items'] = $tags; } return $this->_properties['tag_items']; } public function get_tags() { if ( ! isset($this->_properties['tags'])) { $tag_str = ''; $tag_arr = array(); foreach ($this->tag_items as $tag_item) { $tag_arr[] = $tag_item->name; } $this->_properties['tags'] = implode(Model_Tag::TAGS_DELIMITER,$tag_arr); } return $this->_properties['tags']; } public function stage() { $stage = self::START_STAGE; if ($this->get_telemost_provider() == self::COMDI) { $actual_stage = TaskManager::start('comdi_status', Task_Comdi_Base::mapping(array('event_id' => $this->event_id))); if ($actual_stage !== NULL) { $stage = $actual_stage; } } else if ($this->get_telemost_provider() == self::HANGOTS) { $key = $this->hangouts_secret_key; if($key == NULL) $stage = self::ACTIVE_STAGE; else if ($key == self::HANGOUTS_STOP_KEY) $stage = self::STOP_STAGE; else $stage = self::START_STAGE; return $stage; } } public function change_stage($stage) { if ($this->user_id != Model_User::current()->id) { return FALSE; } $event_id = FALSE; if($this->get_telemost_provider() == self::COMDI) { switch ($stage) { case Model_Product::START_STAGE: if ($this->stage() == Model_Product::ACTIVE_STAGE) { $event_id = TaskManager::start('comdi_start', Task_Comdi_Base::mapping(array('event_id' => $this->event_id))); } break; case Model_Product::STOP_STAGE: if ($this->stage() == Model_Product::START_STAGE) { $event_id = TaskManager::start('comdi_stop', Task_Comdi_Base::mapping(array('event_id' => $this->event_id))); } if ($event_id == $this->event_id) { $this->active = 0; $this->save(FALSE,FALSE,FALSE,TRUE); } break; default: return FALSE; } } else if ($this->get_telemost_provider() == self::HANGOTS) { switch ($stage) { case Model_Product::START_STAGE: $this->hangouts_secret_key = Text::random('alnum', 128); $this->hangouts_test_secret_key = Text::random('alnum', 128); $this->save(FALSE,FALSE,FALSE,TRUE); break; case Model_Product::STOP_STAGE: $this->hangouts_secret_key = self::HANGOUTS_STOP_KEY; $this->hangouts_test_secret_key = self::HANGOUTS_STOP_KEY; $this->save(FALSE,FALSE,FALSE,TRUE); break; default: return FALSE; } } return $event_id; } /** * Link/unlink product to/from given section WITHOUT updating stats * * @param string $mode * @param Model_Section $section */ public function link($mode, Model_Section $section) { $sections = $this->sections; switch ($mode) { case 'link': // link product to section $sections[$section->sectiongroup_id][$section->id] = 1; break; case 'link_main': // unlink from the old main section unset($sections[$this->section->sectiongroup_id][$this->section->id]); // link to the new main section $sections[$section->sectiongroup_id][$section->id] = 1; $this->section_id = $section->id; break; case 'unlink': // unlink product from section, if it is not its main section if ($section->id != $this->section_id) { unset($sections[$section->sectiongroup_id][$section->id]); } break; default: throw new Kohana_Exception('Unknown mode ":mode" passed to :method', array(':mode' => $mode, ':method' => __METHOD__)); } $this->sections = $sections; $this->save(FALSE, TRUE, FALSE, FALSE, FALSE); } public function image($size = NULL) { $image_info = array(); $image = Model::fly('Model_Image')->find_by_owner_type_and_owner_id('product', $this->id, array( 'order_by' => 'position', 'as_array' => true, 'desc' => FALSE )); if ($size) { $field_image = 'image'.$size; $field_width = 'width'.$size; $field_height = 'height'.$size; $image_info['image'] = $image->$field_image; $image_info['width'] = $image->$field_width; $image_info['height'] = $image->$field_height; } return $image_info; } /** * Validate creation/updation of product * * @param array $newvalues * @return boolean */ public function validate(array $newvalues) { // save previous state to check what was changed $this->backup(); $valid = parent::validate($newvalues); if (!$valid) return FALSE; if (!isset($newvalues['organizer_id']) || $newvalues['organizer_id'] == NULL) { $this->error('Указана несуществующая организация!'); return FALSE; } if (!isset($newvalues['place_id']) || $newvalues['place_id'] == NULL) { $this->error('Указана несуществующая площадка!'); return FALSE; } if (isset($newvalues['user_id']) && isset($newvalues['place_id'])) { $user = Model::fly('Model_User')->find($newvalues['user_id']); $place = Model::fly('Model_Place')->find($newvalues['place_id']); if ($user->town_id != $place->town_id) { $this->error('Площадка должна располагаться в городе представителя!'); return FALSE; } } $allvalues = array_merge($this->values(),$newvalues); $event_id = NULL; $comdi_uri = NULL; $dummy_product = new Model_Product($allvalues); // Create COMDI FOR ANNOUNCE if ($this->get_telemost_provider() == self::COMDI) { if ($dummy_product->event_id == NULL) { $event_id = TaskManager::start('comdi_create', Task_Comdi_Base::mapping($allvalues)); $username = isset($dummy_product->user->organization_name)?$dummy_product->user->organization_name:$dummy_product->user->email; $event_uri = TaskManager::start('comdi_register', Task_Comdi_Base::mapping(array( 'event_id' => $event_id, 'role' => 'administrator', 'username' => $username, ))); if ($event_id === TRUE) { return FALSE; } if ($event_id === NULL || $event_uri === NULL) { $this->error('Сервис COMDI временно не работает!'); return FALSE; } $this->event_id = $event_id; $this->event_uri = $event_uri; } else { $event_id = TaskManager::start('comdi_update', Task_Comdi_Base::mapping($allvalues)); if ($event_id === TRUE) { return FALSE; } if ($event_id === NULL) { $this->error('Сервис COMDI временно не работает!'); return FALSE; } } // change datetime_locale according to the town of representative /** * @todo * * Uncomment When Problem in COMDI API will be Fixed */ //$this->event_id = $event_id; } // Create COMDI for EVENT ////SROCHNO /*if (Model_Product::COMDI === TRUE && $dummy_product->id ==NULL && $dummy_product->type == Model_SectionGroup::TYPE_EVENT && $dummy_product->parent()->event_id != NULL) { $username = isset($dummy_product->role->organization)?$dummy_product->role->organization:$dummy_product->role->login; $event_uri = TaskManager::start('comdi_register', Task_Comdi_Base::mapping(array( 'role' => 'guest', 'username' => $username, 'event_id' => $dummy_product->parent()->event_id ))); if ($event_uri === NULL) { $this->error('Сервис COMDI временно не работает!'); return FALSE; } $this->event_uri = $event_uri; $this->event_id = $dummy_product->parent()->event_id; }*/ // if ((!$dummy_product->id) || (isset($newvalues['change_main_properties']) && // $newvalues['change_main_properties'] == 1 )) { // $this->active = 0; // if (APP == 'FRONTEND') { // FlashMessages::add('Анонс события "'.$dummy_product->caption .'" отправлен на модерацию', FlashMessages::MESSAGE); // } // if (APP == 'BACKEND') { // FlashMessages::add('Анонс события"'.$dummy_product->caption .'" сохранен', FlashMessages::MESSAGE); // } // } elseif ($dummy_product->id) { // FlashMessages::add('Анонс события"'.$dummy_product->caption .'" изменен', FlashMessages::MESSAGE); // } return TRUE; } /** * Save product and link it to selected sections */ public function save( $create = FALSE, $update_section_links = TRUE, $update_additional_properties = TRUE, $save_parent_photos = TRUE, $update_stats = TRUE ) { $create_flag = ($this->id === NULL) || $create; if ($create_flag) { // Generate alias from product's marking $this->alias = $this->make_alias(); } parent::save($create); if (is_array($this->file) && !empty($this->file['name'])) { $file_info = $this->file; if (isset($file_info['name'])) { if ($file_info['name'] != '') { // Delete product images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('product', $this->id); $image = new Model_Image(); $image->file = $this->file; $image->owner_type = 'product'; $image->owner_id = $this->id; $image->config = 'product'; $image->save(); } } } else { if($this->image_url) { $file = File::download_file($this->image_url); // Delete product images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('product', $this->id); $image = new Model_Image(); $image->tmp_file = $file; $image->owner_type = 'product'; $image->owner_id = $this->id; $image->config = 'product'; $image->save(); } } Model::fly('Model_Tag')->save_all($this->tags, 'product',$this->id); if ($update_section_links) { // Link product to the selected sections $this->update_section_links(); } if ($update_additional_properties) { // Update values for additional properties Model_Mapper::factory('PropertyValue_Mapper')->update_values_for_product($this); } if ($update_stats) { // Update product count for affected sections $section_ids = array(); foreach ($this->previous()->sections as $sections) { $section_ids = array_merge($section_ids, array_keys(array_filter($sections))); } foreach ($this->sections as $sections) { $section_ids = array_merge($section_ids, array_keys(array_filter($sections))); } $section_ids = array_unique($section_ids); Model::fly('Model_Section')->mapper()->update_products_count($section_ids); } if ($create_flag) { $this->notify('create'); } else { $flag_caption = FALSE; $flag_lecturer = FALSE; $flag_place = FALSE; $flag_time = FALSE; $previous_model = $this->previous(); if ($previous_model->visible == 1 && $this->visible == 0) { $this->notify('cancel'); } else { if ($previous_model->caption != $this->caption) { $flag_caption = TRUE; } if ($previous_model->lecturer_name != $this->lecturer_name) { $flag_lecturer = TRUE; } if ($previous_model->place_name != $this->place_name) { $flag_place = TRUE; } if ($previous_model->datetime != $this->datetime) { $flag_time = TRUE; } if ($flag_caption || $flag_lecturer || $flag_place || $flag_time) { $this->notify('change',$flag_caption,$flag_lecturer,$flag_place,$flag_time); } } } } /** * Send e-mail notification for anounce creation */ public function notify($type,$flag_caption = FALSE,$flag_lecturer = FALSE,$flag_place = FALSE,$flag_time = FALSE) { return true; switch ($type) { case 'create': $admin_subject = 'Новый анонс на портале ' . URL::base(FALSE, TRUE); $client_subject = 'Ваш новый анонс на портале ' . URL::base(FALSE, TRUE); $subclient_subject = 'Новый анонс на портале ' . URL::base(FALSE, TRUE); $admin_template = 'mail/product_create_admin'; $client_template = 'mail/product_create_client'; $client_template = 'mail/product_create_subclient'; break; case 'cancel': $admin_subject = 'Отмена события на портале ' . URL::base(FALSE, TRUE); $client_subject = 'Отмена Вашего события на портале ' . URL::base(FALSE, TRUE); $subclient_subject = 'Отмена события на портале ' . URL::base(FALSE, TRUE); $admin_template = 'mail/product_cancel_admin'; $client_template = 'mail/product_cancel_client'; $subclient_template = 'mail/product_cancel_subclient'; break; case 'change': $admin_subject = 'Изменение события на портале ' . URL::base(FALSE, TRUE); $client_subject = 'Изменение Вашего события на портале ' . URL::base(FALSE, TRUE); $subclient_subject = 'Изменение события на портале ' . URL::base(FALSE, TRUE); $admin_template = 'mail/product_change_admin'; $client_template = 'mail/product_change_client'; $subclient_template = 'mail/product_change_subclient'; break; } try { $settings = Model_Site::current()->settings; $email_to = isset($settings['email']['to']) ? $settings['email']['to'] : ''; $email_from = isset($settings['email']['from']) ? $settings['email']['from'] : ''; $email_sender = isset($settings['email']['sender']) ? $settings['email']['sender'] : ''; $signature = isset($settings['email']['signature']) ? $settings['email']['signature'] : ''; if ($email_sender != '') { $email_from = array($email_from => $email_sender); } if ($email_to != '' || $this->user->email != '') { // Init mailer SwiftMailer::init(); $transport = Swift_MailTransport::newInstance(); $mailer = Swift_Mailer::newInstance($transport); if ($email_to != '') { // --- Send message to administrator $message = Swift_Message::newInstance() ->setSubject($admin_subject) ->setFrom($email_from) ->setTo($email_to); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate($admin_template); $message->setBody($template->render(array( 'product' => $this, 'user' => $this->user, 'flag_caption' => $flag_caption, 'flag_lecturer' => $flag_lecturer, 'flag_place' => $flag_place, 'flag_time' => $flag_time ))); // Send message $mailer->send($message); } if ($this->user->email != '') { // --- Send message to client $message = Swift_Message::newInstance() ->setSubject($client_subject) ->setFrom($email_from) ->setTo($this->user->email); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate($client_template); $body = $template->render(array( 'product' => $this, 'user' => $this->user, 'flag_caption' => $flag_caption, 'flag_lecturer' => $flag_lecturer, 'flag_place' => $flag_place, 'flag_time' => $flag_time )); if ($signature != '') { $body .= "\n\n\n" . $signature; } $message->setBody($body); // Send message $mailer->send($message); } foreach ($this->telemosts as $telemost) { if ($telemost->user->email != '') { // --- Send message to client $message = Swift_Message::newInstance() ->setSubject($subclient_subject) ->setFrom($email_from) ->setTo($telemost->user->email); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate($subclient_template); $body = $template->render(array( 'product' => $this, 'user' => $telemost->user, 'flag_caption' => $flag_caption, 'flag_lecturer' => $flag_lecturer, 'flag_place' => $flag_place, 'flag_time' => $flag_time )); if ($signature != '') { $body .= "\n\n\n" . $signature; } $message->setBody($body); // Send message $mailer->send($message); } } foreach ($this->app_telemosts as $telemost) { if ($telemost->user->email != '') { // --- Send message to client $message = Swift_Message::newInstance() ->setSubject($subclient_subject) ->setFrom($email_from) ->setTo($telemost->user->email); // Message body $twig = Twig::instance(); $template = $twig->loadTemplate($subclient_template); $body = $template->render(array( 'product' => $this, 'user' => $telemost->user, 'flag_caption' => $flag_caption, 'flag_lecturer' => $flag_lecturer, 'flag_place' => $flag_place, 'flag_time' => $flag_time )); if ($signature != '') { $body .= "\n\n\n" . $signature; } $message->setBody($body); // Send message $mailer->send($message); } } } } catch (Exception $e) { if (Kohana::$environment !== Kohana::PRODUCTION) { throw $e; } } return TRUE; } /** * Validate product deletion * * @param array $newvalues * @return boolean */ public function validate_delete(array $newvalues = NULL) { // Delete COMDI event if ($this->get_telemost_provider() == self::COMDI && $this->event_id != NULL) { $arr['event_id'] = $this->event_id; $event_id = TaskManager::start('comdi_delete', Task_Comdi_Base::mapping($arr)); if ($event_id === TRUE) { return FALSE; } if ($event_id === NULL) { $this->error('Сервис COMDI временно не работает!'); return FALSE; } } return parent::validate_delete($newvalues); } /** * Delete product */ public function delete($update_stats = TRUE) { // Delete product telemosts $telemosts = Model::fly('Model_Telemost')->find_all_by_product_id($this->id); foreach ($telemosts as $telemost) { $telemost->delete(); } // Delete product images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('product', $this->id); // Delete property values for this product Model_Mapper::factory('PropertyValue_Mapper')->delete_all_by_product_id($this, $this->id); if ($update_stats) { // Update product count for affected sections $section_ids = array(); foreach ($this->sections as $sections) { $section_ids = array_merge($section_ids, array_keys(array_filter($sections))); } $section_ids = array_unique($section_ids); } // Delete from DB parent::delete(); if ($update_stats) { // Update product count for affected sections Model::fly('Model_Section')->mapper()->update_products_count($section_ids); } } /** * Update links to the sections for the product */ public function update_section_links() { if ( ! isset($this->sections)) return; // Link property to the selected sections foreach (array_keys($this->sections) as $sectiongroup_id) { $this->link_to_sections($sectiongroup_id, $this->get_section_ids($sectiongroup_id)); } } /** * Delete products by section id * * @param integer $section_id */ public function delete_all_by_section_id($section_id) { $loop_prevention = 10000; do { $products = $this->find_all_by_section_id($section_id, array( 'columns' => array('id'), 'batch' => 100 )); foreach ($products as $product) { // Delete product images Model::fly('Model_Image')->delete_all_by_owner_type_and_owner_id('product', $product->id); // Delete property values for this product Model_Mapper::factory('PropertyValue_Mapper')->delete_all_by_product_id($product, $product->id); } $loop_prevention--; } while (count($products) && $loop_prevention > 0); if ($loop_prevention <= 0) { throw new Kohana_Exception('Possibly an infinte loop while deleting section'); } // Delete products from DB in one query $this->mapper()->delete_all_by_section_id($this, $section_id); } /** * Get telemost applications for this product */ public function get_app_telemosts() { return Model::fly('Model_Telemost')->find_all_by_product_id_and_active((int) $this->id,FALSE); } /** * Get telemosts for this product */ public function get_telemosts($town = NULL) { $conditions['product_id'] = (int)$this->id; $conditions['active'] = TRUE; if ($town ) $conditions['town'] = $town; return Model::fly('Model_Telemost')->find_all_by($conditions); } /** * Get comments for this product */ public function get_comments() { return Model::fly('Model_ProductComment')->find_all_by_product_id((int) $this->id); } }<file_sep>/modules/system/forms/classes/form/element/linkbutton.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Link, rendered as button * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Element_LinkButton extends Form_Element { /** * Use the same entry as the submit button * * @return string */ public function default_config_entry() { return 'submit'; } /** * This element cannot have value * * @return boolean */ public function get_without_value() { return TRUE; } /** * Renders link like button * $this->_value is used as url * * @return string */ public function render_input() { $attributes = $this->attributes(); // Add "button" class if (isset($attributes['class'])) { $attributes['class'] .= ' button_adv'; } else { $attributes['class'] = 'button_adv'; } return '<a href="' . $this->url . '" class="' . $attributes['class'] . '"><span class="icon">' . $this->label . '</span></a>'; } } <file_sep>/modules/system/forms/classes/form/validator/date.php <?php defined('SYSPATH') or die('No direct script access.'); /** * Validate dates * Date is expected to be specified as an array(day, month, year) * or a string in format 'yyyy-mm-dd' * * @package Eresus * @author <NAME> (<EMAIL>) */ class Form_Validator_Date extends Form_Validator { const EMPTY_STRING = 'EMPTY_STRING'; const INVALID_DAY = 'INVALID_DAY'; const INVALID_MONTH = 'INVALID_MONTH'; const INVALID_YEAR = 'INVALID_YEAR'; const INVALID = 'INVALID'; protected $_messages = array( self::EMPTY_STRING => 'Вы не указали дату', self::INVALID_DAY => 'День указан некорректно', self::INVALID_MONTH => 'Месяц указан некорректно', self::INVALID_YEAR => 'Год указан некорректно', self::INVALID => 'Invalid format for date' ); /** * Day, month and year for current value */ protected $_day; protected $_month; protected $_year; /** * Allow date to be empty * @var boolean */ protected $_allow_empty = FALSE; /** * Creates validator * * @param array $messages Error messages templates * @param boolean $breaks_chain Break chain after validation failure * @param boolean $allow_empty Allow empty dates */ public function __construct(array $messages = NULL, $breaks_chain = TRUE, $allow_empty = FALSE) { parent::__construct($messages, $breaks_chain); $this->_allow_empty = $allow_empty; } /** * Validate. * Date should be an array of (day, month, year) * or a string in 'yyyy-mm-dd' format. * * @param array $context Form data * @return boolean */ protected function _is_valid(array $context = NULL) { $this->_day = NULL; $this->_month = NULL; $this->_year = NULL; if (is_array($this->_value)) { if ( ! isset($value['day']) || ! isset($value['month']) || ! isset($value['year'])) { $this->_error(self::INVALID); return FALSE; } // Value is supposed to be an array(day, month, year) $this->_day = $value['day']; $this->_month = $value['month']; $this->_year = $value['year']; // An empty string allowed ? if ( preg_match('/^\s*$/', $this->_day) && preg_match('/^\s*$/', $this->_month) && preg_match('/^\s*$/', $this->_year) ) { if (!$this->_allow_empty) { $this->_error(self::EMPTY_STRING); return false; } else { return true; } } } else { // ----- Validate date string agains a format $value = (string)$this->_value; // An empty string allowed ? if (preg_match('/^\s*$/', $value)) { if (!$this->_allow_empty) { $this->_error(self::EMPTY_STRING); return FALSE; } else { return TRUE; } } $regexp = l10n::date_format_regexp($this->get_form_element()->format); if ( ! preg_match($regexp, $value, $matches)) { $this->_error(self::INVALID); return FALSE; } if (isset($matches['day'])) { $this->_day = $matches['day']; } if (isset($matches['month'])) { $this->_month = $matches['month']; } if (isset($matches['year'])) { $this->_year = $matches['year']; } } // day if (isset($this->_day) && (! ctype_digit($this->_day) || (int)$this->_day <= 0 || (int)$this->_day > 31)) { $this->_error(self::INVALID_DAY); return false; } // month if (isset($this->_month) && (! ctype_digit($this->_month) || (int)$this->_month <= 0 || (int)$this->_month > 12)) { $this->_error(self::INVALID_MONTH); return false; } // year if (isset($this->_year) && (! ctype_digit($this->_year) || (int)$this->_year <= 0)) { $this->_error(self::INVALID_YEAR); return false; } return true; } /** * Replaces :day, :month and :year * * @param string $error_text * @return string */ protected function _replace_placeholders($error_text) { $error_text = parent::_replace_placeholders($error_text); return str_replace( array(':day', ':month', ':year'), array($this->_day, $this->_month, $this->_year), $error_text ); } }
0e5c4f0aeabf2f5458018cab20187169d1829313
[ "JavaScript", "Markdown", "PHP" ]
615
PHP
Teplitsa/vse.to
4aa6b1898e0875e3e13d8ac437639ccf6ff96410
8ea96ddd73a460e63800686c75f2e84434d13ba1
refs/heads/master
<repo_name>mpcen/stockthing<file_sep>/src/components/app.js import React, { Component } from 'react'; import { connect } from 'react-redux' import HighStock from 'react-highcharts/ReactHighstock.src'; import SearchBar from '../containers/SearchBar'; class App extends Component { renderChart() { if(!this.props.config) { return <p>No Data To Show</p> } else if (this.props.config) { return ( <HighStock config={this.props.config} /> ); } else { return <p>something is going on </p> } } render() { return ( <div> <SearchBar /> <p>Searching for: {this.props.symbol}</p> {this.renderChart()} </div> ); } } const mapStateToProps = (state) => { console.log('config object:', state.stockChart.config); return { symbol: state.searchBar.symbol, config: state.stockChart.config } } export default connect(mapStateToProps)(App);<file_sep>/src/containers/SearchBar.js import React, { Component } from 'react'; import { connect } from 'react-redux'; import { updateInput, fetchStock } from '../actions'; class SearchBar extends Component { constructor(props) { super(props); this.handleInputChange = this.handleInputChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleInputChange(event) { this.props.updateInput(event.target.value); } handleSubmit(event) { event.preventDefault(); this.props.fetchStock(this.props.symbol); } render() { return ( <form className="input-group" onSubmit={this.handleSubmit}> <input type="text" className="form-control" placeholder="Enter stock symbol (EX: AAPL)" onChange={this.handleInputChange} value={this.props.symbol} /> <span className="input-group-btn"> <button className="btn btn-secondary" type="submit"> Search! </button> </span> </form> ); } } const mapStateToProps = (state) => { return { symbol: state.searchBar.symbol } } export default connect(mapStateToProps, { updateInput, fetchStock })(SearchBar);<file_sep>/README.md # Random Stock thing using HighStock<file_sep>/src/actions/types.js export const UPDATE_INPUT = 'UPDATE_INPUT'; export const FETCH_STOCK = 'FETCH_STOCK'; export const FETCH_STOCK_SUCCESS = 'FETCH_STOCK_SUCCESS'; export const FETCH_STOCK_FAIL = 'FETCH_STOCK_FAIL';
ea724c5700f2c02fa4323d787aaf9cff7914669d
[ "JavaScript", "Markdown" ]
4
JavaScript
mpcen/stockthing
6287bb24353280d41859e4f93c1f80d9102d1c31
a342c5f3a6d125038fc2e910f2eea05efedc1250
refs/heads/master
<file_sep>#!/bin/bash mkdir -p .vim cp vimconfig/_vimrc .vimrc cp -r vimconfig/tags .vim/ cp vimconfig/neocomplcache.vimrc .vim/ <file_sep>###PreInstall [Vundle](https://github.com/gmarik/vundle) ###Install * windows * cd %userprofile% * git clone https://github.com/zixiaojindao/vimconfig.git vimconfig * vimconfig\install.cmd * #add .vim/tools to your path * gvim \_vimrc * :BundleInstall * linux * cd ~ * git clone https://github.com/zixiaojindao/vimconfig.git vimconfig * chmod a+x ./vimconfig/install.sh * ./vimconfig/install.sh * gvim vimrc * :BundleInstall ###plugin * NERDTree: * shortcut: normal mode: nt * minibuffer: quick switch buffer * ctrl-j,k,h,l for quick switch window * supertab: * tab complete * neocomplcache: * super auto complete * taglist: * shortcut: normal mode: tl * ctags & cscope: * &lt;F12&gt; generate tags and cscope.out * already added c++ std tags in .vim/tags * NERD\_comment: * head is "," * FuzzyFinder: * shortcut: normal mode: ff, ft, ftf * Calendar: * shortcut: normal mode: ca * &lt;Up&gt; &lt;Down&gt; switch by year * &lt;Left&gt; &lt;Right&gt; switch by month * xml.vim * pydiciton * A.vim * c.vim * \rc: save and compile single source file * \rr: compile and run single source file * windows users should download [mingw](http://www.mingw.org/), install gcc and add bin to $PATH * Align * solarized color scheme * highlight current line * shortcut: normal mode: cul * matrix.vim * type ':Matrix', take fun! ###Caution The color scheme used is [solarized](http://ethanschoonover.com/solarized). It works fine when gui is running. However, you have to do a little more if you prefer terminal. Please get rid of the [official web site](http://ethanschoonover.com/solarized) and refer to [gist1](https://gist.github.com/gmodarelli/5942850) or [gist2](https://gist.github.com/codeforkjeff/1397104#file-solarize-sh). ###ScreenShot ![scrrenshot](http://thumbsnap.com/i/9I2PtKPF.png)
0f56114f0eff36153baa7446062bfc750007bab3
[ "Markdown", "Shell" ]
2
Shell
zixiaojindao/vimconfig
591c08c4ccf9b400caba6355de261b62f179f093
5684452d68c2fb56b6f97b9c9ee8f8b448b02409
refs/heads/master
<repo_name>about-future/Best-Movies<file_sep>/app/src/main/java/com/future/bestmovies/cast/CastResponse.java package com.future.bestmovies.cast; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class CastResponse { @SerializedName("cast") private final ArrayList<Cast> results = new ArrayList<>(); public ArrayList<Cast> getCast() { return results; } } <file_sep>/app/src/main/java/com/future/bestmovies/videos/VideoAdapter.java package com.future.bestmovies.videos; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.future.bestmovies.R; import com.future.bestmovies.utils.ImageUtils; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> { private final Context mContext; private ArrayList<Video> mVideos = new ArrayList<Video>() { }; private final ListItemClickListener mOnclickListener; public interface ListItemClickListener { void onListItemClick(Video videoClicked); } public VideoAdapter(Context context, ListItemClickListener listener) { mContext = context; mOnclickListener = listener; } @Override @NonNull public VideoAdapter.VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.video_list_item, parent, false); view.setFocusable(true); return new VideoViewHolder(view); } @Override public void onBindViewHolder(@NonNull final VideoAdapter.VideoViewHolder holder, int position) { String videoImagePath = mVideos.get(position).getVideoKey(); final String videoImageUrl; // If we have a valid image path, try loading it from cache or from web with Picasso if (!TextUtils.isEmpty(videoImagePath)) { videoImageUrl = ImageUtils.buildVideoThumbnailUrl(mContext, videoImagePath); // Try loading image from device memory or cache Picasso.get() .load(videoImageUrl) .networkPolicy(NetworkPolicy.OFFLINE) .into(holder.videoThumbnailImageView, new Callback() { @Override public void onSuccess() { // Yay again! } @Override public void onError(Exception e) { // Try again online, if cache loading failed Picasso.get() .load(videoImageUrl) .error(R.drawable.ic_image) .into(holder.videoThumbnailImageView); } }); } else { // Otherwise, don't bother using Picasso and set no_poster for videoThumbnailImageView holder.videoThumbnailImageView.setImageResource(R.drawable.ic_image); } holder.videoNameTextView.setText(mVideos.get(position).getVideoName()); holder.videoTypeTextView.setText(mVideos.get(position).getVideoType()); } @Override public int getItemCount() { if (mVideos != null) return mVideos.size(); else return 0; } // This method swaps the old movie result with the newly loaded ones and notify the change public void swapVideos(ArrayList<Video> newVideos) { mVideos = newVideos; notifyDataSetChanged(); } class VideoViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.video_thumbnail_iv) ImageView videoThumbnailImageView; @BindView(R.id.video_name_tv) TextView videoNameTextView; @BindView(R.id.video_type_tv) TextView videoTypeTextView; VideoViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(this); } @Override public void onClick(View view) { // Find the position of the video that was clicked and pass the video object from that // position to the listener int clickedPosition = getAdapterPosition(); mOnclickListener.onListItemClick(mVideos.get(clickedPosition)); } } } <file_sep>/app/src/main/java/com/future/bestmovies/movie/CategoryAdapter.java package com.future.bestmovies.movie; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.future.bestmovies.R; import com.future.bestmovies.utils.ImageUtils; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MovieViewHolder> { private final Context mContext; private ArrayList<Movie> mMovies = new ArrayList<Movie>(){}; private final GridItemClickListener mOnClickListener; public interface GridItemClickListener { void onGridItemClick(Movie movieClicked); } public CategoryAdapter(Context context, GridItemClickListener listener) { mContext = context; mOnClickListener = listener; } @Override @NonNull public MovieViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.movie_list_item, parent, false); view.setFocusable(true); return new MovieViewHolder(view); } @Override public void onBindViewHolder(@NonNull final MovieViewHolder holder, int position) { String posterPath = mMovies.get(position).getPosterPath(); final String posterUrl; // If we have a valid poster path, try loading it from cache or from web with Picasso if (!TextUtils.isEmpty(posterPath)) { posterUrl = ImageUtils.buildImageUrlForRecyclerView(mContext, posterPath); // Try loading image from device memory or cache Picasso.get() .load(posterUrl) .networkPolicy(NetworkPolicy.OFFLINE) .into(holder.moviePosterImageView, new Callback() { @Override public void onSuccess() { // Celebrate: Yay!!! } @Override public void onError(Exception e) { // Try again online, if loading from device memory or cache failed Picasso.get() .load(posterUrl) .error(R.drawable.no_poster) .into(holder.moviePosterImageView); } }); } else { // Otherwise, don't bother using Picasso and set no_poster for moviePosterImageView holder.moviePosterImageView.setImageResource(R.drawable.no_poster); } } @Override public int getItemCount() { if (mMovies != null) return mMovies.size(); else return 0; } // This method swaps the old movie result with the newly loaded ones and notify the change public void swapMovies(ArrayList<Movie> newMovies) { mMovies = newMovies; notifyDataSetChanged(); } // Add to the existing movie list the new movies and notify the change public void addMovies(ArrayList<Movie> newMovies) { mMovies.addAll(newMovies); notifyDataSetChanged(); } class MovieViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.movie_poster_iv) ImageView moviePosterImageView; MovieViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(this); } @Override public void onClick(View view) { // Find the position of the movie that was clicked and pass the movie object from that // position to the listener or the movieId int adapterPosition = getAdapterPosition(); mOnClickListener.onGridItemClick(mMovies.get(adapterPosition)); } } }<file_sep>/app/src/main/java/com/future/bestmovies/credits/CreditsResponse.java package com.future.bestmovies.credits; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class CreditsResponse { @SerializedName("cast") private final ArrayList<Credits> results = new ArrayList<>(); public ArrayList<Credits> getCredits() { return results; } } <file_sep>/app/src/main/java/com/future/bestmovies/ReviewsActivity.java package com.future.bestmovies; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.MenuItem; import android.widget.ImageView; import android.widget.Toast; import com.future.bestmovies.reviews.Review; import com.future.bestmovies.reviews.ReviewAdapter; import com.future.bestmovies.utils.ImageUtils; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import static com.future.bestmovies.DetailsActivity.MOVIE_BACKDROP_KEY; import static com.future.bestmovies.DetailsActivity.MOVIE_REVIEWS_KEY; import static com.future.bestmovies.DetailsActivity.MOVIE_TITLE_KEY; public class ReviewsActivity extends AppCompatActivity { private static final String REVIEWS_POSITION_KEY = "reviews_position"; private int mReviewPosition = RecyclerView.NO_POSITION; @BindView(R.id.reviews_rv) RecyclerView mReviewsRecyclerView; @BindView(R.id.reviews_backdrop_iv) ImageView movieBackdropImageView; @BindView(R.id.reviews_toolbar) Toolbar toolbar; private ArrayList<Review> mReviews; private ReviewAdapter mReviewAdapter; private LinearLayoutManager mReviewLayoutManager; private String mMovieTitle; private String mMovieBackdrop; private Bundle mBundleState; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reviews); ButterKnife.bind(this); // We initialize and set the toolbar setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } mReviewLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); mReviewsRecyclerView.setLayoutManager(mReviewLayoutManager); mReviewsRecyclerView.setHasFixedSize(false); mReviewAdapter = new ReviewAdapter(this); mReviewsRecyclerView.setAdapter(mReviewAdapter); if (savedInstanceState == null) { // Check our intent and see if there is an ArrayList of Review objects passed from // DetailsActivity, so we can populate our reviews UI. If there isn't, we close this // activity and display a toast message. Intent intent = getIntent(); if (intent != null && intent.hasExtra(MOVIE_REVIEWS_KEY)) { mReviews = intent.getParcelableArrayListExtra(MOVIE_REVIEWS_KEY); mReviewAdapter.swapReviews(mReviews); if (intent.hasExtra(MOVIE_TITLE_KEY)) { mMovieTitle = intent.getStringExtra(MOVIE_TITLE_KEY); // Set activity title as the movie name setTitle(mMovieTitle); } if (intent.hasExtra(MOVIE_BACKDROP_KEY)) { mMovieBackdrop = intent.getStringExtra(MOVIE_BACKDROP_KEY); if (!TextUtils.isEmpty(mMovieBackdrop)) { final String backdropUrl = ImageUtils.buildImageUrl(this, mMovieBackdrop, ImageUtils.BACKDROP); // Try loading backdrop image from memory Picasso.get() .load(backdropUrl) .networkPolicy(NetworkPolicy.OFFLINE) .into(movieBackdropImageView, new Callback() { @Override public void onSuccess() { // Yay! We have it! } @Override public void onError(Exception e) { // Try again online, if cache loading failed Picasso.get() .load(backdropUrl) .error(R.drawable.ic_landscape) .into(movieBackdropImageView); } }); } else { // Otherwise, don't bother using Picasso and set no_poster for movieBackdropImageView movieBackdropImageView.setImageResource(R.drawable.ic_landscape); } } } else { closeOnError(); } } if (mReviewPosition == RecyclerView.NO_POSITION) { mReviewPosition = 0; } mReviewsRecyclerView.scrollToPosition(mReviewPosition); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelableArrayList(MOVIE_REVIEWS_KEY, mReviews); if (mReviewLayoutManager.findFirstCompletelyVisibleItemPosition() != RecyclerView.NO_POSITION) { outState.putInt(REVIEWS_POSITION_KEY, mReviewLayoutManager.findFirstCompletelyVisibleItemPosition()); } else { outState.putInt(REVIEWS_POSITION_KEY, mReviewLayoutManager.findFirstVisibleItemPosition()); } outState.putString(MOVIE_TITLE_KEY, mMovieTitle); outState.putString(MOVIE_BACKDROP_KEY, mMovieBackdrop); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState.containsKey(MOVIE_REVIEWS_KEY)) { mReviews = savedInstanceState.getParcelableArrayList(MOVIE_REVIEWS_KEY); mReviewAdapter.swapReviews(mReviews); } // Restore previous position if (savedInstanceState.containsKey(REVIEWS_POSITION_KEY)) { mReviewPosition = savedInstanceState.getInt(REVIEWS_POSITION_KEY); } // Restore activity title as the movie name if (savedInstanceState.containsKey(MOVIE_TITLE_KEY)) { mMovieTitle = savedInstanceState.getString(MOVIE_TITLE_KEY); setTitle(mMovieTitle); } // Restore the backdrop for the movie reviews if (savedInstanceState.containsKey(MOVIE_BACKDROP_KEY)) { mMovieBackdrop = savedInstanceState.getString(MOVIE_BACKDROP_KEY); if (!TextUtils.isEmpty(mMovieBackdrop)) { final String backdropUrl = ImageUtils.buildImageUrl(this, mMovieBackdrop, ImageUtils.BACKDROP); // Try loading backdrop image from memory Picasso.get() .load(backdropUrl) .networkPolicy(NetworkPolicy.OFFLINE) .into(movieBackdropImageView, new Callback() { @Override public void onSuccess() { // Yay! We have it! } @Override public void onError(Exception e) { // Try again online, if cache loading failed Picasso.get() .load(backdropUrl) .error(R.drawable.ic_landscape) .into(movieBackdropImageView); } }); } else { // Otherwise, don't bother using Picasso and set no_poster for movieBackdropImageView movieBackdropImageView.setImageResource(R.drawable.ic_landscape); } } super.onRestoreInstanceState(savedInstanceState); } @Override protected void onPause() { super.onPause(); mBundleState = new Bundle(); // Save Reviews position if (mReviewLayoutManager.findFirstCompletelyVisibleItemPosition() != RecyclerView.NO_POSITION) { mBundleState.putInt(REVIEWS_POSITION_KEY, mReviewLayoutManager.findFirstCompletelyVisibleItemPosition()); } else { mBundleState.putInt(REVIEWS_POSITION_KEY, mReviewLayoutManager.findFirstVisibleItemPosition()); } } @Override protected void onResume() { super.onResume(); // Restore RecyclerView position if (mBundleState != null) { mReviewPosition = mBundleState.getInt(REVIEWS_POSITION_KEY); if (mReviewPosition == RecyclerView.NO_POSITION) { mReviewPosition = 0; } mReviewsRecyclerView.scrollToPosition(mReviewPosition); } } private void closeOnError() { finish(); Toast.makeText(this, R.string.no_reviews, Toast.LENGTH_SHORT).show(); } } <file_sep>/app/src/main/java/com/future/bestmovies/search/SearchLoader.java package com.future.bestmovies.search; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; import android.util.Log; import com.future.bestmovies.movie.MoviePreferences; import com.future.bestmovies.retrofit.ApiClient; import com.future.bestmovies.retrofit.ApiInterface; import com.future.bestmovies.utils.NetworkUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Objects; import retrofit2.Call; public class SearchLoader extends AsyncTaskLoader<ArrayList<SearchResult>> { private ArrayList<SearchResult> cachedSearchResults; private final String searchQuery; //private Context context; public SearchLoader(Context context, String searchQuery) { super(context); //this.context = context; this.searchQuery = searchQuery; } @Override protected void onStartLoading() { if (cachedSearchResults == null) forceLoad(); } @Override public ArrayList<SearchResult> loadInBackground() { ApiInterface movieApiInterface = ApiClient.getClient().create(ApiInterface.class); Call<SearchResponse> call = movieApiInterface.searchResults( searchQuery, NetworkUtils.API_ID, MoviePreferences.getLastSearchPageNumber(getContext()), false); ArrayList<SearchResult> result = new ArrayList<>(); try { result = Objects.requireNonNull(call.execute().body()).getResults(); } catch (IOException e) { Log.v("Review Loader", "Error: " + e.toString()); } return result; } @Override public void deliverResult(ArrayList<SearchResult> data) { cachedSearchResults = data; super.deliverResult(data); } } <file_sep>/app/src/main/java/com/future/bestmovies/search/SearchResponse.java package com.future.bestmovies.search; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class SearchResponse { @SerializedName("results") private final ArrayList<SearchResult> results = new ArrayList<>(); public ArrayList<SearchResult> getResults() { return results; } } <file_sep>/app/src/main/java/com/future/bestmovies/search/SearchResult.java package com.future.bestmovies.search; import android.os.Parcel; import android.os.Parcelable; import com.google.gson.annotations.SerializedName; public class SearchResult { @SerializedName("id") private int id; @SerializedName("media_type") private String type; @SerializedName("poster_path") private String posterPath; @SerializedName("profile_path") private String profilePath; @SerializedName("original_title") private String movieTitle; @SerializedName("original_name") private String showTitle; @SerializedName("name") private String personName; public SearchResult() { } public int getId() { return id; } public String getPosterPath() { return posterPath; } public String getProfilePath() { return profilePath; } public String getPersonName() { return personName; } public String getMovieTitle() { return movieTitle; } public String getShowTitle() { return showTitle; } public String getType() { return type; } } <file_sep>/app/src/main/java/com/future/bestmovies/utils/ScreenUtils.java package com.future.bestmovies.utils; import android.content.Context; import android.util.DisplayMetrics; import android.view.WindowManager; public class ScreenUtils { /* Return the width, height of the screen in pixels and the screen density (i.e. {720.0, 1280.0, 2.0}) * @param context is used to create a windowManager, so we can get the screen metrics */ private static float[] getScreenSize(Context context) { DisplayMetrics displayMetrics = new DisplayMetrics(); WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); if (windowManager != null) windowManager.getDefaultDisplay().getMetrics(displayMetrics); return new float[]{ (float) displayMetrics.widthPixels, (float) displayMetrics.heightPixels, displayMetrics.density}; } /* Return the current width of the screen in DPs. * @param context is used to call getScreenSize method * * For a phone the width in portrait mode can be 360dp and in landscape mode 640dp. * For a tablet the width in portrait mode can be 800dp and in landscape mode 1280dp */ public static int getScreenWidthInDps (Context context) { // Get the screen sizes and density float[] screenSize = getScreenSize(context); // Divide the first item of the array(screen width) by the last one(screen density), // round the resulting number and return it return Math.round(screenSize[0] / screenSize[2]); } /* Return the number of columns that will be used for our RecyclerViews that use a GridLayoutManager. * The return value is based on the screen width in dps. * @param context is used to call getScreenSize method * @param withDivider is used to divide the screen size. It's size depends on each use case * (i.e. in MainActivity the min is 200dps and in ProfileActivity the min is 120dps) * @param minNumberOfColumns is used to set the minimum number of columns on each use case * (i.e. in MainActivity the min is 2 and in ProfileActivity the min is 3) */ public static int getNumberOfColumns (Context context, int widthDivider, int minNumberOfColumns) { // Get screen width in dps int width = getScreenWidthInDps(context); int numberOfColumns = width / widthDivider; if (numberOfColumns < minNumberOfColumns) return minNumberOfColumns; return numberOfColumns; } } <file_sep>/README.md # Best Movies ### Description Most of us can relate to kicking back on the couch and enjoying a movie with friends and family. In this project, I built an app that allows users to discover the most popular movies, using themoviedb.org API. ### Features - Upon launch, present the user with an grid arrangement of movie posters. - Allow your user to change sort order via a setting. The sort order can be: - Most Popular - Top Rated - Upcoming - Now Playing - Allow the user to create a list of favourite movies - Allow the user to create a list of favourite actors - Allow the user to tap on a movie poster and transition to a details screen with additional information such as: - original title - movie poster image thumbnail - a plot synopsis - user rating - release date and more - Allow users to read reviews of a selected movie - Allow users to view and play trailers ( either in the youtube app or a web browser) ### Libraries Used - Picasso v2.71828 to handle loading and caching images. - ButterKnife v8.8.1 for binding views easily. - Retrofit v2.4.0 to easily retrieve and serialize JSON files. ### What did I learn after this project? - How to incorporate libraries to simplify the amount of code I need to write - How to use Picasso library to retrieve images - How to use ButterKnife library to bind views more easily - How to implement and use Retrofit library to retrieve and serialize JSON files - How to fetch data from the Internet with theMovieDB API - How to work with parcelable data ### Screen Shots Favourite Movies and Movie Details | --- | ![](/screenshots/best_movies_1.jpg) | Actor Details and Credits | --- | ![](/screenshots/best_movies_2.jpg) | ![](/screenshots/best_movies_3.jpg) | ### Video [Best Movies](https://youtu.be/NSrq0ulqdYg) <file_sep>/app/src/main/java/com/future/bestmovies/ProfileActivity.java package com.future.bestmovies; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.future.bestmovies.credits.Actor; import com.future.bestmovies.credits.ActorLoader; import com.future.bestmovies.credits.Credits; import com.future.bestmovies.credits.CreditsAdapter; import com.future.bestmovies.credits.CreditsLoader; import com.future.bestmovies.data.FavouritesContract; import com.future.bestmovies.utils.ImageUtils; import com.future.bestmovies.utils.NetworkUtils; import com.future.bestmovies.utils.ScreenUtils; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Calendar; import butterknife.BindString; import butterknife.BindView; import butterknife.ButterKnife; import static com.future.bestmovies.DetailsActivity.*; import static com.future.bestmovies.data.FavouritesContract.*; public class ProfileActivity extends AppCompatActivity implements CreditsAdapter.ListItemClickListener { private static final int ACTOR_LOADER_ID = 136; private static final int CREDITS_LOADER_ID = 435; /* private static final int FAVOURITE_ACTOR_LOADER_ID = 516136; private static final int FAVOURITE_CREDITS_LOADER_ID = 516435; */ private static final int CHECK_IF_FAVOURITE_ACTOR_LOADER_ID = 473136; private static final String IS_FAVOURITE_ACTOR_KEY = "is_favourite_actor"; private static final String PROFILE_PATH_KEY = "profile_path_key"; private static final String ACTOR_DETAILS_KEY = "actor"; private static final String MOVIE_CREDITS_KEY = "movie_credits"; private static final String CREDITS_POSITION_KEY = "credits_position"; private static final String APPBAR_HEIGHT_KEY = "bar_height"; // Query projection used to check if the actor is a favourite or not private static final String[] ACTOR_CHECK_PROJECTION = { ActorsEntry.COLUMN_ACTOR_ID, ActorsEntry.COLUMN_PROFILE_PATH }; /* // Query projection used to retrieve actor details private static final String[] ACTOR_DETAILED_PROJECTION = { ActorsEntry.COLUMN_ACTOR_ID, ActorsEntry.COLUMN_BIRTHDAY, ActorsEntry.COLUMN_BIOGRAPHY, ActorsEntry.COLUMN_DEATH_DAY, ActorsEntry.COLUMN_GENDER, ActorsEntry.COLUMN_NAME, ActorsEntry.COLUMN_PROFILE_PATH, ActorsEntry.COLUMN_PLACE_OF_BIRTH }; // Query projection used to retrieve movie credits private static final String[] CREDITS_DETAILED_PROJECTION = { CreditsEntry.COLUMN_ACTOR_ID, CreditsEntry.COLUMN_CHARACTER, CreditsEntry.COLUMN_MOVIE_ID, CreditsEntry.COLUMN_POSTER_PATH, CreditsEntry.COLUMN_RELEASE_DATE, CreditsEntry.COLUMN_TITLE }; */ @BindView(R.id.profile_toolbar) Toolbar toolbar; @BindView(R.id.profile_app_bar) AppBarLayout appBarLayout; @BindView(R.id.profile_toolbar_layout) CollapsingToolbarLayout collapsingToolbarLayout; // Profile detail variables @BindView(R.id.profile_backdrop_iv) ImageView profileBackdropImageView; @BindView(R.id.actor_age_tv) TextView ageTextView; @BindView(R.id.credit_actor_iv) ImageView profilePictureImageView; @BindView(R.id.credit_gender_tv) TextView genderTextView; @BindView(R.id.credit_birthday_tv) TextView birthdayTextView; @BindView(R.id.credit_place_of_birth_tv) TextView birthPlaceTextView; @BindView(R.id.credit_biography_tv) TextView biographyTextView; @BindView(R.id.credits_rv) RecyclerView mCreditsRecyclerView; private Actor mActor; private ArrayList<Credits> mCredits; private int mActorId; private String mActorName; private String mBackdropPath; private String mProfilePath; private Toast mToast; private CreditsAdapter mCreditsAdapter; private GridLayoutManager mCreditsLayoutManager; private int mCreditsPosition = RecyclerView.NO_POSITION; // Movie credits variables @BindView(R.id.credits_messages_tv) TextView mCreditsMessagesTextView; @BindView(R.id.loading_credits_pb) ProgressBar mCreditsProgressBar; @BindView(R.id.no_credits_iv) ImageView mNoCreditsImageView; @BindView(R.id.no_credits_connection_iv) ImageView mNoCreditsConnectionImageView; @BindString(R.string.no_connection) String noConnection; private boolean mIsFavouriteActor; private MenuItem mFavouriteActorMenuItem; private Bundle mBundleState; // Resources @BindString(R.string.credit_date_unknown) String dateUnknown; @BindString(R.string.credit_age) String age; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); ButterKnife.bind(this); setSupportActionBar(toolbar); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } mCreditsLayoutManager = new GridLayoutManager( this, ScreenUtils.getNumberOfColumns(this, 120, 3)); mCreditsRecyclerView.setLayoutManager(mCreditsLayoutManager); mCreditsRecyclerView.setHasFixedSize(false); mCreditsAdapter = new CreditsAdapter(this, this); mCreditsRecyclerView.setAdapter(mCreditsAdapter); mCreditsRecyclerView.setNestedScrollingEnabled(false); mCreditsMessagesTextView.setText(R.string.loading); if (savedInstanceState == null) { // Check our intent and see if there is an actor ID passed from DetailsActivity, so we // can populate our UI. If there isn't we close this activity and display a toast message. Intent intent = getIntent(); if (intent != null && intent.hasExtra(ACTOR_ID_KEY)) { // If DetailsActivity passed an actor id mActorId = intent.getIntExtra(ACTOR_ID_KEY, 10297); mActorName = intent.getStringExtra(ACTOR_NAME_KEY); setTitle(mActorName); mBackdropPath = intent.getStringExtra(MOVIE_BACKDROP_KEY); if (mBackdropPath != null) { final String backdropUrl = ImageUtils.buildImageUrl(this, mBackdropPath, ImageUtils.BACKDROP); // Try loading backdrop image from memory Picasso.get() .load(backdropUrl) .networkPolicy(NetworkPolicy.OFFLINE) .into(profileBackdropImageView, new Callback() { @Override public void onSuccess() { // Yay! We have it! } @Override public void onError(Exception e) { // Try again online, if cache loading failed Picasso.get() .load(backdropUrl) .error(R.drawable.ic_landscape) .into(profileBackdropImageView); } }); } // Check if this actor is a favourite or not getSupportLoaderManager().restartLoader(CHECK_IF_FAVOURITE_ACTOR_LOADER_ID, null, favouriteActorResultLoaderListener); } else { closeOnError(getString(R.string.details_error_message)); } } } @Override public void onSaveInstanceState(Bundle outState) { outState.putString(MOVIE_BACKDROP_KEY, mBackdropPath); outState.putInt(ACTOR_ID_KEY, mActorId); outState.putString(ACTOR_NAME_KEY, mActorName); outState.putParcelable(ACTOR_DETAILS_KEY, mActor); outState.putParcelableArrayList(MOVIE_CREDITS_KEY, mCredits); outState.putInt(CREDITS_POSITION_KEY, mCreditsPosition); outState.putBoolean(IS_FAVOURITE_ACTOR_KEY, mIsFavouriteActor); outState.putString(PROFILE_PATH_KEY, mProfilePath); outState.putInt(APPBAR_HEIGHT_KEY, appBarLayout.getHeight()); super.onSaveInstanceState(outState); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState != null) { if (savedInstanceState.containsKey(MOVIE_BACKDROP_KEY)) { mBackdropPath = savedInstanceState.getString(MOVIE_BACKDROP_KEY); if (mBackdropPath != null) { final String backdropUrl = ImageUtils.buildImageUrl(this, mBackdropPath, ImageUtils.BACKDROP); // Try loading backdrop image from memory Picasso.get() .load(backdropUrl) .networkPolicy(NetworkPolicy.OFFLINE) .into(profileBackdropImageView, new Callback() { @Override public void onSuccess() { // Yay! We have it! } @Override public void onError(Exception e) { // Try again online, if cache loading failed Picasso.get() .load(backdropUrl) .error(R.drawable.ic_landscape) .into(profileBackdropImageView); } }); } } if (savedInstanceState.containsKey(ACTOR_ID_KEY)) mActorId = savedInstanceState.getInt(ACTOR_ID_KEY); if (savedInstanceState.containsKey(ACTOR_NAME_KEY)) mActorName = savedInstanceState.getString(ACTOR_NAME_KEY); if (savedInstanceState.containsKey(ACTOR_DETAILS_KEY)) { mActor = savedInstanceState.getParcelable(ACTOR_DETAILS_KEY); if (mActor != null) populateActorDetails(mActor); } if (savedInstanceState.containsKey(MOVIE_CREDITS_KEY)) { mCredits = savedInstanceState.getParcelableArrayList(MOVIE_CREDITS_KEY); if (mCredits != null) { populateCredits(mCredits); } } // Favourite Actor if (savedInstanceState.containsKey(IS_FAVOURITE_ACTOR_KEY)) { mIsFavouriteActor = savedInstanceState.getBoolean(IS_FAVOURITE_ACTOR_KEY); } // Image profile path if (savedInstanceState.containsKey(PROFILE_PATH_KEY)) mProfilePath = savedInstanceState.getString(PROFILE_PATH_KEY); } } @Override protected void onPause() { super.onPause(); mBundleState = new Bundle(); // Actor details mBundleState.putParcelable(ACTOR_DETAILS_KEY, mActor); // Movie credits and position mBundleState.putParcelableArrayList(MOVIE_CREDITS_KEY, mCredits); mCreditsPosition = mCreditsLayoutManager.findFirstCompletelyVisibleItemPosition(); mBundleState.putInt(CREDITS_POSITION_KEY, mCreditsPosition); mBundleState.putBoolean(IS_FAVOURITE_ACTOR_KEY, mIsFavouriteActor); // Image profile path mBundleState.putString(PROFILE_PATH_KEY, mProfilePath); } @Override protected void onResume() { super.onResume(); if (mBundleState != null) { // Restore Actor details if (mBundleState.containsKey(ACTOR_DETAILS_KEY)) mActor = mBundleState.getParcelable(ACTOR_DETAILS_KEY); // Restore Credits position if (mBundleState.containsKey(MOVIE_CREDITS_KEY)) { mCredits = mBundleState.getParcelableArrayList(MOVIE_CREDITS_KEY); if (mCredits != null) { populateCredits(mCredits); } } mCreditsPosition = mBundleState.getInt(CREDITS_POSITION_KEY); if (mCreditsPosition == RecyclerView.NO_POSITION) mCreditsPosition = 0; mCreditsRecyclerView.smoothScrollToPosition(mCreditsPosition); mIsFavouriteActor = mBundleState.getBoolean(IS_FAVOURITE_ACTOR_KEY); // Image profile path mProfilePath = mBundleState.getString(PROFILE_PATH_KEY); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.profile_menu, menu); MenuItem favouriteActorMenuItem = menu.findItem(R.id.action_favourite_actor); mFavouriteActorMenuItem = favouriteActorMenuItem; if (mIsFavouriteActor) { DrawableCompat.setTint(favouriteActorMenuItem.getIcon(), ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)); } else { DrawableCompat.setTint(favouriteActorMenuItem.getIcon(), ContextCompat.getColor(getApplicationContext(), R.color.colorWhite)); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { onBackPressed(); return true; } if (id == R.id.action_favourite_actor) { if (mIsFavouriteActor) deleteFavouriteActor(mActor, item); else { insertFavouriteActor(mActor, item); } return true; } return super.onOptionsItemSelected(item); } private void closeOnError(String message) { finish(); toastThis(message); } // Hide the progress bar and show credits private void showCredits() { mCreditsRecyclerView.setVisibility(View.VISIBLE); mCreditsProgressBar.setVisibility(View.INVISIBLE); mCreditsMessagesTextView.setVisibility(View.INVISIBLE); mNoCreditsImageView.setVisibility(View.INVISIBLE); mNoCreditsConnectionImageView.setVisibility(View.INVISIBLE); } // Show progress bar and hide credits private void hideCredits() { mCreditsRecyclerView.setVisibility(View.GONE); mCreditsProgressBar.setVisibility(View.VISIBLE); mCreditsMessagesTextView.setVisibility(View.VISIBLE); mNoCreditsImageView.setVisibility(View.INVISIBLE); mNoCreditsConnectionImageView.setVisibility(View.INVISIBLE); } private void toastThis(String toastMessage) { if (mToast != null) mToast.cancel(); mToast = Toast.makeText(this, toastMessage, Toast.LENGTH_LONG); mToast.show(); } private final LoaderManager.LoaderCallbacks<Actor> actorDetailsResultLoaderListener = new LoaderManager.LoaderCallbacks<Actor>() { @NonNull @Override public Loader<Actor> onCreateLoader(int loaderId, @Nullable Bundle bundle) { switch (loaderId) { case ACTOR_LOADER_ID: // If the loaded id matches ours, return a new cast movie loader return new ActorLoader(getApplicationContext(), mActorId); default: throw new RuntimeException("Loader Not Implemented: " + loaderId); } } @Override public void onLoadFinished(@NonNull Loader<Actor> loader, Actor actorDetails) { mActor = null; mActor = actorDetails; populateActorDetails(mActor); } @Override public void onLoaderReset(@NonNull Loader<Actor> loader) { } }; private final LoaderManager.LoaderCallbacks<ArrayList<Credits>> actorCreditsResultLoaderListener = new LoaderManager.LoaderCallbacks<ArrayList<Credits>>() { @NonNull @Override public Loader<ArrayList<Credits>> onCreateLoader(int loaderId, @Nullable Bundle args) { switch (loaderId) { case CREDITS_LOADER_ID: // If the loaded id matches ours, return a new cast movie loader return new CreditsLoader(getApplicationContext(), mActorId); default: throw new RuntimeException("Loader Not Implemented: " + loaderId); } } @Override public void onLoadFinished(@NonNull Loader<ArrayList<Credits>> loader, ArrayList<Credits> movieCredits) { mCredits = movieCredits; populateCredits(mCredits); } @Override public void onLoaderReset(@NonNull Loader<ArrayList<Credits>> loader) { mCreditsAdapter.swapCredits(null); } }; private final LoaderManager.LoaderCallbacks<Cursor> favouriteActorResultLoaderListener = new LoaderManager.LoaderCallbacks<Cursor>() { @NonNull @Override public Loader<Cursor> onCreateLoader(int loaderId, @Nullable Bundle args) { switch (loaderId) { case CHECK_IF_FAVOURITE_ACTOR_LOADER_ID: return new CursorLoader(getApplicationContext(), FavouritesContract.buildUriWithId(ActorsEntry.CONTENT_URI, mActorId), ACTOR_CHECK_PROJECTION, null, null, null); default: throw new RuntimeException("Loader Not Implemented: " + loaderId); } } @Override public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor cursor) { if (cursor != null && !cursor.isClosed() && cursor.moveToFirst()) { mIsFavouriteActor = true; // As soon as we know the movie is a favourite, color the star, // so the user will know it too and close the cursor if (mFavouriteActorMenuItem != null) DrawableCompat.setTint(mFavouriteActorMenuItem.getIcon(), ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)); // Save the current image profile from the database int profilePathColumnIndex = cursor.getColumnIndex(ActorsEntry.COLUMN_PROFILE_PATH); mProfilePath = cursor.getString(profilePathColumnIndex); cursor.close(); } if (NetworkUtils.isConnected(getApplicationContext())) { // Otherwise, use am actor details loader and download the actor details and credits getSupportLoaderManager().restartLoader(ACTOR_LOADER_ID, null, actorDetailsResultLoaderListener); hideCredits(); getSupportLoaderManager().restartLoader(CREDITS_LOADER_ID, null, actorCreditsResultLoaderListener); } else { closeOnError(noConnection); } } @Override public void onLoaderReset(@NonNull Loader<Cursor> loader) { } }; private void populateActorDetails(final Actor actorDetails) { // Try loading profile picture from memory String profilePath = actorDetails.getProfilePath(); if (profilePath != null) { final String profileImageUrl = ImageUtils.buildImageUrl(getApplicationContext(), profilePath, ImageUtils.POSTER); Picasso.get() .load(profileImageUrl) .placeholder(R.drawable.no_picture) .networkPolicy(NetworkPolicy.OFFLINE) .into(profilePictureImageView, new Callback() { @Override public void onSuccess() { // Yay! We got the picture already! } @Override public void onError(Exception e) { // Try again online, if cache loading failed Picasso.get() .load(profileImageUrl) .placeholder(R.drawable.no_picture) .error(R.drawable.no_picture) .into(profilePictureImageView); } }); } else { profilePictureImageView.setImageResource(R.drawable.no_picture); } if (mIsFavouriteActor && !TextUtils.equals(actorDetails.getProfilePath(), mProfilePath)) { updateFavouriteActor(actorDetails.getProfilePath()); } // Gender switch (actorDetails.getGender()) { case 1: genderTextView.setText(getText(R.string.gender_female)); break; case 2: genderTextView.setText(getString(R.string.gender_male)); break; default: genderTextView.setText(getString(R.string.gender_unknown)); } // Birthday if (actorDetails.getBirthday() != null) birthdayTextView.setText(actorDetails.getBirthday()); else birthdayTextView.setText(getString(R.string.credit_date_unknown)); // Age int birthYear; int endYear; if (actorDetails.getBirthday() != null) { birthYear = Integer.valueOf(actorDetails.getBirthday().substring(0, 4)); if (actorDetails.getDeathDay() != null) { endYear = Integer.valueOf(actorDetails.getDeathDay().substring(0, 4)); } else { endYear = Calendar.getInstance().get(Calendar.YEAR); } ageTextView.setText(age.concat(Integer.toString(endYear - birthYear))); } else { ageTextView.setText(age.concat("unknown")); } // Birthplace if (actorDetails.getPlaceOfBirth() != null) birthPlaceTextView.setText(actorDetails.getPlaceOfBirth()); else birthPlaceTextView.setText(getString(R.string.credit_date_unknown)); // Biography if (actorDetails.getBiography() != null && actorDetails.getBiography().length() > 0) { biographyTextView.setText(actorDetails.getBiography()); } else { biographyTextView.setVisibility(View.GONE); } // Set title as the name of the actor setTitle(actorDetails.getActorName()); } private void populateCredits(ArrayList<Credits> movieCredits) { mCreditsAdapter.swapCredits(mCredits); // If movieCredits has data if (movieCredits.size() != 0) { // If there is no backdrop set yet for our layout, we take the first available movie // poster and set it as a backdrop for the actor profile, so the UI will look good. if (mBackdropPath == null) { int i = 0; while (mBackdropPath == null && i < mCredits.size()) { mBackdropPath = movieCredits.get(i).getPosterPath(); i++; } // Loading backdrop image Picasso.get() .load(ImageUtils.buildImageUrl( getApplicationContext(), mBackdropPath, ImageUtils.BACKDROP)) .error(R.drawable.ic_landscape) .into(profileBackdropImageView); } // Show movie credits showCredits(); } } private void insertFavouriteActor(Actor selectedActor, MenuItem item) { // Actor details insertion ContentValues actorValues = new ContentValues(); actorValues.put(ActorsEntry.COLUMN_ACTOR_ID, selectedActor.getId()); actorValues.put(ActorsEntry.COLUMN_BIRTHDAY, selectedActor.getBirthday()); actorValues.put(ActorsEntry.COLUMN_GENDER, selectedActor.getGender()); actorValues.put(ActorsEntry.COLUMN_NAME, selectedActor.getActorName()); actorValues.put(ActorsEntry.COLUMN_PLACE_OF_BIRTH, selectedActor.getPlaceOfBirth()); actorValues.put(ActorsEntry.COLUMN_BIOGRAPHY, selectedActor.getBiography()); actorValues.put(ActorsEntry.COLUMN_DEATH_DAY, selectedActor.getDeathDay()); actorValues.put(ActorsEntry.COLUMN_PROFILE_PATH, selectedActor.getProfilePath()); Uri actorResponseUri = getContentResolver().insert(ActorsEntry.CONTENT_URI, actorValues); // Show a toast message depending on whether or not the insertion was successful if (actorResponseUri != null) { // The insertion was successful and we can display a toast. DrawableCompat.setTint(item.getIcon(), ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)); toastThis(getString(R.string.favourite_actor_insert_successful)); mIsFavouriteActor = true; } else { // Otherwise, if the new content URI is null, then there was an error with insertion. mIsFavouriteActor = false; DrawableCompat.setTint(item.getIcon(), ContextCompat.getColor(getApplicationContext(), R.color.colorWhite)); toastThis(getString(R.string.favourite_actor_insert_failed)); } } private void deleteFavouriteActor(Actor selectedActor, MenuItem item) { int rowsDeleted = getContentResolver().delete(ActorsEntry.CONTENT_URI, ActorsEntry.COLUMN_ACTOR_ID + " =?", new String[]{String.valueOf(selectedActor.getId())}); // Show a toast message depending on whether or not the delete was successful. if (rowsDeleted != 0) { // Otherwise, the delete was successful and we can display a toast. DrawableCompat.setTint(item.getIcon(), ContextCompat.getColor(getApplicationContext(), R.color.colorWhite)); toastThis(getString(R.string.favourite_actor_delete_successful)); mIsFavouriteActor = false; } else { // Otherwise, if no rows were affected, then there was an error with the delete. mIsFavouriteActor = true; DrawableCompat.setTint(item.getIcon(), ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)); toastThis(getString(R.string.favourite_actor_delete_failed)); } } private void updateFavouriteActor(String newPicture) { // Update the new section title in database ContentValues newValues = new ContentValues(); newValues.put(ActorsEntry.COLUMN_PROFILE_PATH, newPicture); //Uri currentUri = ContentUris.withAppendedId(ActorsEntry.CONTENT_URI, mActorId); int rowsUpdated = getContentResolver().update( FavouritesContract.buildUriWithId(ActorsEntry.CONTENT_URI, mActorId), newValues, null, null); // Show a toast message depending on whether or not the update was successful. if (rowsUpdated == 0) { // If no rows were affected, then there was an error with the update. toastThis(getString(R.string.favourite_actor_update_failed)); } else { // Otherwise, the update was successful and we can display a toast. toastThis(getString(R.string.favourite_actor_update_successful)); } } @Override public void onListItemClick(Credits creditsClicked) { Intent movieDetailsIntent = new Intent(ProfileActivity.this, DetailsActivity.class); movieDetailsIntent.putExtra(DetailsActivity.MOVIE_ID_KEY, creditsClicked.getMovieId()); movieDetailsIntent.putExtra(DetailsActivity.MOVIE_TITLE_KEY, creditsClicked.getTitle()); startActivity(movieDetailsIntent); } } <file_sep>/app/src/main/java/com/future/bestmovies/utils/NetworkUtils.java package com.future.bestmovies.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; public class NetworkUtils { public static final String API_ID = "xxx"; private static final String YOUTUBE_VIDEO_BASE_URL = "https://www.youtube.com/watch"; private static final String YOUTUBE_PARAMETER = "v"; /* Perform a state of network connectivity test and return true or false. * @param context is used to create a reference to the ConnectivityManager */ public static boolean isConnected(Context context) { // Get a reference to the ConnectivityManager to check state of network connectivity ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // Get details on the currently active default data network NetworkInfo activeNetwork = null; if(cm != null){ activeNetwork = cm.getActiveNetworkInfo(); } // Return true if there is an active network and if the device is connected or connecting // to the active network, otherwise return false return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } /* Build and return the YOUTUBE Uri for movie trailers and teasers * @param movieKey is used to build the Uri */ public static Uri buildVideoUri (String movieKey) { return Uri.parse(YOUTUBE_VIDEO_BASE_URL).buildUpon() .appendQueryParameter(YOUTUBE_PARAMETER, movieKey) .build(); } } <file_sep>/app/src/main/java/com/future/bestmovies/data/FavouritesContract.java package com.future.bestmovies.data; import android.content.ContentResolver; import android.net.Uri; import android.provider.BaseColumns; public class FavouritesContract { private FavouritesContract() { } public static final String CONTENT_AUTHORITY = "com.future.bestmovies"; // Use CONTENT_AUTHORITY to create the base of all URI's which apps will use to contact the content provider. private static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); /* Possible path (appended to base content URI for possible URI's) * For instance, content://com.future.bestmovies/movie/ is a valid path for * looking at movie data. content://com.future.bestmovies/ratings/ will fail, * as the ContentProvider hasn't been given any information on what to do with "ratings". */ public static final String PATH_MOVIES = "movies"; // Inner class that defines constant values for the movie details database table. // Each entry in the table represents a single movie. public static abstract class MovieDetailsEntry implements BaseColumns { // The content URI to access the movie data in the provider public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_MOVIES); // The MIME type of the {@link #CONTENT_URI} for a list of movies. public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_MOVIES; // The MIME type of the {@link #CONTENT_URI} for a single movie. public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_MOVIES; public final static String TABLE_NAME = "movie_details"; public final static String _ID = BaseColumns._ID; // Type: INTEGER (Unique ID) public final static String COLUMN_MOVIE_ID = "movie_id"; // Type: INTEGER public final static String COLUMN_TITLE = "title"; // Type: TEXT public final static String COLUMN_POSTER_PATH = "poster_path"; // Type: TEXT public final static String COLUMN_BACKDROP_PATH = "backdrop_path"; // Type: TEXT public final static String COLUMN_PLOT = "overview"; // Type: TEXT public final static String COLUMN_RATINGS = "ratings"; // Type: DOUBLE public final static String COLUMN_RELEASE_DATE = "release_date"; // Type: TEXT public final static String COLUMN_GENRES = "genres"; // Type: TEXT public final static String COLUMN_LANGUAGE = "language"; // Type: TEXT public final static String COLUMN_RUNTIME = "runtime"; // Type: INTEGER } // Inner class that defines constant values for the movie cast database table. // Each entry in the table represents a cast member. public static final String PATH_CAST = "cast"; public static abstract class CastEntry implements BaseColumns { // The content URI to access the section data in the provider public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_CAST); // The MIME type of the {@link #CONTENT_URI} for a cast list. public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CAST; // The MIME type of the {@link #CONTENT_URI} for a single cast member. public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CAST; public final static String TABLE_NAME = "movie_cast"; public final static String _ID = BaseColumns._ID; // Type: INTEGER (Unique ID) public final static String COLUMN_MOVIE_ID = "movie_id"; // Type: INTEGER public final static String COLUMN_ACTOR_NAME = "actor_name"; // Type: TEXT public final static String COLUMN_CHARACTER_NAME = "character_name"; // Type: TEXT public final static String COLUMN_ACTOR_ID = "actor_id"; // Type: INTEGER public final static String COLUMN_IMAGE_PROFILE_PATH = "profile_path"; // Type: TEXT } // Inner class that defines constant values for the movie reviews database table. // Each entry in the table represents a single review. public static final String PATH_REVIEWS = "reviews"; public static abstract class ReviewsEntry implements BaseColumns { // The content URI to access the section data in the provider public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_REVIEWS); // The MIME type of the {@link #CONTENT_URI} for a list of reviews. public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_REVIEWS; // The MIME type of the {@link #CONTENT_URI} for a single review. public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_REVIEWS; public final static String TABLE_NAME = "movie_reviews"; public final static String _ID = BaseColumns._ID; // Type: INTEGER (Unique ID) public final static String COLUMN_MOVIE_ID = "movie_id"; // Type: INTEGER public final static String COLUMN_AUTHOR = "author"; // Type: TEXT public final static String COLUMN_CONTENT = "content"; // Type: TEXT } // Inner class that defines constant values for the movie video database table. // Each entry in the table represents a single video. public static final String PATH_VIDEOS = "videos"; public static abstract class VideosEntry implements BaseColumns { // The content URI to access the section data in the provider public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_VIDEOS); // The MIME type of the {@link #CONTENT_URI} for a list of videos. public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_VIDEOS; // The MIME type of the {@link #CONTENT_URI} for a single video. public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_VIDEOS; public final static String TABLE_NAME = "movie_videos"; public final static String _ID = BaseColumns._ID; // Type: INTEGER (Unique ID) public final static String COLUMN_MOVIE_ID = "movie_id"; // Type: INTEGER public final static String COLUMN_VIDEO_KEY = "video_key"; // Type: TEXT public final static String COLUMN_VIDEO_NAME = "video_name"; // Type: TEXT public final static String COLUMN_VIDEO_TYPE = "video_type"; // Type: TEXT } // Inner class that defines constant values for the actors database table. // Each entry in the table represents a single actor. public static final String PATH_ACTORS = "actors"; public static abstract class ActorsEntry implements BaseColumns { // The content URI to access the section data in the provider public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_ACTORS); // The MIME type of the {@link #CONTENT_URI} for a list of actors. public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_ACTORS; // The MIME type of the {@link #CONTENT_URI} for a single actor. public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_ACTORS; public final static String TABLE_NAME = "actor_details"; public final static String _ID = BaseColumns._ID; // Type: INTEGER (Unique ID) public final static String COLUMN_ACTOR_ID = "actor_id"; // Type: INTEGER public final static String COLUMN_BIRTHDAY = "birthday"; // Type: TEXT public final static String COLUMN_DEATH_DAY = "deathday"; // Type: TEXT public final static String COLUMN_GENDER = "gender"; // Type: INTEGER public final static String COLUMN_NAME = "name"; // Type: TEXT public final static String COLUMN_BIOGRAPHY = "biography"; // Type: TEXT public final static String COLUMN_PLACE_OF_BIRTH = "place_of_birth"; // Type: TEXT public final static String COLUMN_PROFILE_PATH = "profile_path"; // Type: TEXT } // Inner class that defines constant values for the actors credits database table. // Each entry in the table represents a single credit. public static final String PATH_CREDITS = "credits"; public static abstract class CreditsEntry implements BaseColumns { // The content URI to access the section data in the provider public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_CREDITS); // The MIME type of the {@link #CONTENT_URI} for a list of credits. public static final String CONTENT_LIST_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CREDITS; // The MIME type of the {@link #CONTENT_URI} for a single credit. public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/" + CONTENT_AUTHORITY + "/" + PATH_CREDITS; public final static String TABLE_NAME = "movie_credits"; public final static String _ID = BaseColumns._ID; // Type: INTEGER (Unique ID) public final static String COLUMN_ACTOR_ID = "actor_id"; // Type: INTEGER public final static String COLUMN_CHARACTER = "character"; // Type: TEXT public final static String COLUMN_MOVIE_ID = "movie_id"; // Type: INTEGER public final static String COLUMN_POSTER_PATH = "poster_path"; // Type: TEXT public final static String COLUMN_RELEASE_DATE = "release_date"; // Type: TEXT public final static String COLUMN_TITLE = "title"; // Type: TEXT } // Build a specific Uri for accessing table contents, using the content uri for // the selected table and a movieId. public static Uri buildUriWithId(Uri contentUri, int movieId) { return contentUri.buildUpon() .appendPath(Integer.toString(movieId)) .build(); } } <file_sep>/app/src/main/java/com/future/bestmovies/reviews/ReviewAdapter.java package com.future.bestmovies.reviews; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.future.bestmovies.R; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class ReviewAdapter extends RecyclerView.Adapter<ReviewAdapter.ReviewViewHolder> { private final Context mContext; private ArrayList<Review> mReviews = new ArrayList<>(); public ReviewAdapter(Context context) { mContext = context; } @NonNull @Override public ReviewAdapter.ReviewViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.review_list_item, parent, false); view.setFocusable(false); return new ReviewViewHolder(view); } @Override public void onBindViewHolder(@NonNull ReviewAdapter.ReviewViewHolder holder, int position) { holder.reviewAuthorTextView.setText(mReviews.get(position).getReviewAuthor()); holder.reviewContentTextView.setText(mReviews.get(position).getReviewContent()); } @Override public int getItemCount() { if (mReviews != null) return mReviews.size(); else return 0; } public void swapReviews(ArrayList<Review> newReviews) { mReviews = newReviews; notifyDataSetChanged(); } class ReviewViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.review_author_tv) TextView reviewAuthorTextView; @BindView(R.id.review_content_tv) TextView reviewContentTextView; ReviewViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } } <file_sep>/app/src/main/java/com/future/bestmovies/cast/CastLoader.java package com.future.bestmovies.cast; import android.content.AsyncTaskLoader; import android.content.Context; import android.util.Log; import com.future.bestmovies.retrofit.ApiClient; import com.future.bestmovies.retrofit.ApiInterface; import com.future.bestmovies.utils.NetworkUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Objects; import retrofit2.Call; public class CastLoader extends AsyncTaskLoader<ArrayList<Cast>> { private ArrayList<Cast> cachedCast; private final int movieId; public CastLoader(Context context, int movieId) { super(context); this.movieId = movieId; } @Override protected void onStartLoading() { if (cachedCast == null) forceLoad(); } @Override public ArrayList<Cast> loadInBackground() { ApiInterface movieApiInterface = ApiClient.getClient().create(ApiInterface.class); Call<CastResponse> call = movieApiInterface.getMovieCast(movieId, NetworkUtils.API_ID); ArrayList<Cast> result = new ArrayList<>(); try { result = Objects.requireNonNull(call.execute().body()).getCast(); } catch (IOException e) { Log.v("Cast Loader", "Error: " + e.toString()); } return result; } @Override public void deliverResult(ArrayList<Cast> data) { cachedCast = data; super.deliverResult(data); } } <file_sep>/app/src/main/java/com/future/bestmovies/reviews/ReviewResponse.java package com.future.bestmovies.reviews; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class ReviewResponse { @SerializedName("results") private final ArrayList<Review> results = new ArrayList<>(); public ArrayList<Review> getResults() { return results; } } <file_sep>/app/src/main/java/com/future/bestmovies/credits/ActorLoader.java package com.future.bestmovies.credits; import android.content.Context; import android.support.v4.content.AsyncTaskLoader; import android.util.Log; import com.future.bestmovies.retrofit.ApiClient; import com.future.bestmovies.retrofit.ApiInterface; import com.future.bestmovies.utils.NetworkUtils; import java.io.IOException; import retrofit2.Call; public class ActorLoader extends AsyncTaskLoader<Actor> { private Actor cachedActorProfile; private final int actorId; public ActorLoader(Context context, int actorId) { super(context); this.actorId = actorId; } @Override protected void onStartLoading() { if (cachedActorProfile == null) forceLoad(); } @Override public Actor loadInBackground() { ApiInterface movieApiInterface = ApiClient.getClient().create(ApiInterface.class); Call<Actor> call = movieApiInterface.getActorProfile(actorId, NetworkUtils.API_ID); Actor result = new Actor(); try { result = call.execute().body(); } catch (IOException e) { Log.v("Actor Loader", "Error: " + e.toString()); } return result; } @Override public void deliverResult(Actor data) { cachedActorProfile = data; super.deliverResult(data); } } <file_sep>/app/src/main/java/com/future/bestmovies/videos/VideoResponse.java package com.future.bestmovies.videos; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class VideoResponse { @SerializedName("results") private final ArrayList<Video> results = new ArrayList<>(); public ArrayList<Video> getResults() { return results; } }
53280bf1c9f89d8ff9a7eed7c17fbb118eb62535
[ "Markdown", "Java" ]
18
Java
about-future/Best-Movies
ff6fcf3c2562b53a7e7306b276376e1d13493e0b
7d524bd68112620972611dfb1a0050a25d1eaaa0
refs/heads/main
<repo_name>KirubelEnyew/PhpSampleProject<file_sep>/view/edit.php <?php include_once('../controller/control.php'); if(isset($_POST['submit'])){ echo $_POST['pizzaName']; ECHO $_POST['ingredients']; if(!isset($_GET['id'])){ echo "i didnt get an id"; } else{ $updateId = $_GET['id']; } $editPizza = new Controller(); $editPizza->updatePizzaById($_POST['pizzaName'],$_POST['ingredients'],$updateId); } ?> <!DOCTYPE html> <html> <?php include('header.php'); ?> <section class="container"> <h4 class="center">Update Pizza Info</h4> <form class="white" action = "edit.php" method="POST"> <input type="text" name = "pizzaName" placeholder="New Pizza Name"> <input type="text" name = "ingredients" placeholder="New Pizza Ingredients"> <input type = "submit" name = "submit" value = "submit" class="btn"> </form> </section> <?php include('footer.php'); ?> </html><file_sep>/view/add.php <?php include_once('../controller/control.php'); if(isset($_POST['submit'])){ $newPizza = new Controller(); $newPizza->addNewPizza($_POST['pizzaName'],$_POST['ingredients']); } ?> <!DOCTYPE html> <html> <?php include('header.php'); ?> <section class="container"> <h4 class="center">Add New Pizza</h4> <form class="white" action = "add.php" method="POST"> <input type="text" name = "pizzaName" placeholder="Add Pizza Name"> <input type="text" name = "ingredients" placeholder="Add Pizza Ingredients"> <input type = "submit" name = "submit" value = "submit" class="btn"> </form> </section> <?php include('footer.php'); ?> </html><file_sep>/model/model.php <?php class Model { public $conn; public $result; function __construct(){ $this->conn = mysqli_connect('localhost', 'pizzasUser', '', 'pizzas'); if(!$this->conn){ echo 'Failed to Connect to Database :' . mysqli_connect_error(); } } //gets what to query from the controller function queryFunction($queryTerm){ return mysqli_query($this->conn,$queryTerm); } function executeQuery ($queryTerm){ mysqli_query($this->conn,$queryTerm); } function fetchData($queryTerm){ $query = $this->queryFunction($queryTerm); return mysqli_fetch_all($query,MYSQLI_ASSOC); } } ?><file_sep>/view/index.php <?php include_once('../controller/control.php'); $pizzaView = new Controller(); $allPizzas = $pizzaView->getPizza(); if(isset($_POST['submit'])){ $id = htmlspecialchars($_POST['id']); $pizzaView->removePizzaById($id); echo $id; } ?> <!DOCTYPE html> <html> <?php include('header.php'); ?> <h4 class = "center">Pizzas</h4> <div class="container"> <div class="row"> <?php foreach($allPizzas as $pizza){ ?> <div class = "col s6 m3"> <div class = "card"> <div class = "card-content center"> <h5><?= htmlspecialchars($pizza['pizzaName']) ?></h5> <h6><?= htmlspecialchars($pizza['ingredients'])?></h6> </div> <div class = "card-action"> <div class = "left-align"> <a href="edit.php?id=<?php echo $pizza['id']; ?>">Edit</a> </div> <div class = "right-align"> <form action= "index.php" method="POST"> <input type="hidden" name="id" value=<?= $pizza['id']?>> <input type="submit" name="submit" value="delete" class="btn"> </form> </div> </div> </div> </div> <?php } ?> </div> </div> <?php include('footer.php'); ?> </html><file_sep>/controller/control.php <?php include_once('../model/model.php'); class Controller extends Model{ function getPizza() { $queryTerm = "SELECT id, pizzaName, ingredients FROM pizzas_table ORDER BY time_created"; // $this->queryFunction($queryTerm); return $this->fetchData($queryTerm); // print_r($this->fetchData()); } function addNewPizza($name,$ingredients){ $queryTerm = "INSERT INTO pizzas_table (pizzaName,ingredients) VALUES ('$name','$ingredients')"; echo $queryTerm; $this->executeQuery($queryTerm); } function removePizzaById($id){ if($id){ $queryTerm = "DELETE FROM pizzas_table WHERE id=$id"; $this->executeQuery($queryTerm); }else{ echo "Query failed"; } } function updatePizzaById($pizzaName,$ingredients,$id){ if($id){ $queryTerm = "UPDATE pizza_table pizzaName = $pizzaName, ingredients = $ingredients WHERE id=$id"; $this->executeQuery($queryTerm); } } } ?>
ae4160a62becf526540d6f2965b05e5a8c49e0b9
[ "PHP" ]
5
PHP
KirubelEnyew/PhpSampleProject
2c0c9870847c7bd7f9e18b364b19e3101503ca66
1cdb6a60cf14bd84e1789980e341a7abd13a3f62
refs/heads/master
<file_sep>import NavigationBar from 'react-native-navbar' import CheckBox from 'react-native-checkbox' import React, { Component } from 'react' import { StyleSheet, View, Text, } from 'react-native' class CheckItemView extends Component { constructor(props) { super(props) this.state = { checked: this.props.checked || false } } render() { return( <View style={ this.props.containerStyle }> <CheckBox label={ this.props.label } labelStyle={ this.props.labelStyle } underlayColor={ this.props.underlayColor } checkboxStyle={ this.props.isCurrentStep ? null : styles.inActiveCheckbox } checked={ this.state.checked } onChange={ this.props.isCurrentStep ? this.onChange.bind(this) : null } /> </View> ) } onChange(checked) { this.props.onChangeChecked(checked) this.setState({ checked: checked }) } } const styles = StyleSheet.create({ inActiveCheckbox: { backgroundColor: '#bdbdbd', } }) export default CheckItemView <file_sep>import React, { Component } from 'react' import { AppRegistry, StyleSheet, NavigatorIOS, } from 'react-native' import RoadMap from './components/RoadMap' class myHome extends Component { render() { return ( <NavigatorIOS style={ styles.container } barTintColor='#B3E5FC' tintColor='#263238' titleTextColor='#263238' initialRoute={{ title: '不動産購入アプリ', backButtonTitle: '一覧へ戻る', component: RoadMap, }} /> ) } } const styles = StyleSheet.create({ container: { flex: 1, }, }) AppRegistry.registerComponent('myHome', () => myHome) <file_sep>import NavigationBar from 'react-native-navbar' import React, { Component } from 'react' import { StyleSheet, View, TouchableHighlight, Text, Image, } from 'react-native' import WorkView from './WorkView' class StepName extends Component { focusStepNameArea(rowData) { return( <TouchableHighlight onPress={ () => this.rowPressed(rowData) } underlayColor='#dddddd'> <View style={ [styles.focusArea, this.backgroundColor(rowData.step)] }> <Text style={ styles.focusStepName }>{ rowData.step }.{ rowData.title }</Text> <Text style={ styles.shortDesc }>{ rowData.shortDesc }</Text> </View> </TouchableHighlight> ) } notFocusStepNameArea(rowData) { return ( <View style={ [styles.notFocusArea, this.backgroundColor(rowData.step)] }> <Text style={ styles.notFocusStepName }>{ rowData.step }.{ rowData.title }</Text> </View> ) } render() { const rowData = this.props.rowData return rowData.active ? this.focusStepNameArea(rowData) : this.notFocusStepNameArea(rowData) } backgroundColor(step) { return step < this.props.currentStep ? styles.complete : step == this.props.currentStep ? styles.doing : step > this.props.currentStep ? styles.incomplete : '' } rowPressed(rowData) { this.props.navigator.push({ title: `${rowData.step}.${rowData.title}`, component: WorkView, passProps: { rowData: rowData, currentStep: this.props.currentStep, onCompleteStep: this.props.onCompleteStep, isLastStep: this.props.isLastStep, } }) } isFocus(step) { return this.props.currentPosition <= step && step <= this.props.currentPosition + 2 } } const styles = StyleSheet.create({ focusArea: { width: 335, padding: 15, borderRadius: 8, marginTop: 6, marginBottom: 6, }, notFocusArea: { width: 260, padding: 5, borderRadius: 8, marginTop: 6, marginBottom: 6, }, focusStepName: { fontSize: 24, fontWeight: 'bold', color: '#263238', }, shortDesc: { margin: 5, fontSize: 18, }, notFocusStepName: { fontSize: 17, }, incomplete: { backgroundColor: '#FAFAFA', }, doing: { backgroundColor: '#FFD54F', }, complete: { backgroundColor: '#9E9E9E', }, }) export default StepName <file_sep>module.exports = [ { msg: ['少しお金に余裕ができたら', '⇒ 繰り上げ返済'] }, { msg: ['収入がなくなるのが不安', '⇒ 保険のご案内'] }, { msg: ['税金が戻ってくる?', '⇒ 確定申告の方法'] }, { msg: ['家に不満が出てきたら', '⇒ リフォームするには?'] }, { msg: ['振込手数料を得する', '⇒ BTMUなら無料です'] }, ] <file_sep>rootProject.name = 'sugoroku' include ':app' <file_sep>import NavigationBar from 'react-native-navbar' import React, { Component } from 'react' import { StyleSheet, View, TouchableHighlight, Text, Image, } from 'react-native' import AdsView from './AdsView' const skyImage = require('../resources/sky.png') const congratsImage = require('../resources/congratulations.png') class CompletedView extends Component { render() { return ( <Image source={ skyImage } style={ styles.backgroundImage }> <View style={ styles.container }> <Image source={ congratsImage } style={ styles.image } /> <View style={ styles.panelContainer }> <Text style={ styles.description }>おめでとうございます。</Text> <Text style={ styles.description }>全てのステップが完了しました。</Text> <TouchableHighlight underlayColor='#dddddd' onPress={ () => this.btnPressed() }> <View style={ styles.bannerContainer }> <Text style={ styles.bannerText }>住宅ローンとのお付き合いのしかた</Text> </View> </TouchableHighlight> </View> </View> </Image> ) } btnPressed() { this.props.navigator.push({ title: '住宅ローンとのお付き合いのしかた', component: AdsView, }) } } const styles = StyleSheet.create({ backgroundImage: { flex: 1, width: null, height: null, }, container: { alignItems: 'center', marginTop: 70, margin: 15, backgroundColor: '#fafafa', borderRadius: 8, }, image: { width: 330, borderRadius: 4, }, panelContainer: { margin: 10, borderColor: '#E0E0E0', borderRadius: 8, }, bannerContainer: { marginTop: 10, paddingVertical: 15, paddingHorizontal: 10, borderWidth: 1, borderRadius: 8, backgroundColor: '#FFF59D', borderColor: '#FFF9C4', }, bannerText: { fontSize: 20, color: '#263238', fontWeight: 'bold', }, description: { fontSize: 17, marginTop: 3, marginHorizontal: 5, }, }) export default CompletedView <file_sep>module.exports = [ { step: 1, title: '仮審査申込み', todoList: ['収入等確認できる書類を用意する', 'webサイトで申込みをする'], shortDesc: 'web上から仮審査の申込みをします。審査期間は2〜6日です。', longDesc: [ 'お手元にご収入、物件の情報などが確認できる資料をご用意のうえ、サービスサイトからお申し込み下さい。', 'お申込内容の確認のため、ご勤務先やご自宅にお電話させて頂く場合があります。ご本人さまと直接お話しできない場合、審査は保留となりますのでご注意下さい。',, ] }, { step: 2, title: '仮審査結果のご確認', todoList: ['仮審査完了のメールを受信する', 'webサイト上で結果を確認する'], shortDesc: '仮審査の結果はwebサイト上で確認することができます。', longDesc: [ '電子メールにて仮審査完了をご連絡致します。サービスサイトのお取引画面で仮審査結果をご確認下さい。', '可決の場合、住宅ローン申込書を郵送致します。', ] }, { step: 3, title: 'お申込書類のお受取り/ご返送', todoList: ['申込書が届く', '申請書に記入・捺印する', '申請書を送付する'], shortDesc: '申込書が届いたら記入・捺印し返送して下さい。', longDesc: [ '仮審査の可決から一週間以内にお申込書を郵送致します。', '必要事項をご記入・ご捺印しご返送下さい。', ], }, { step: 4, title: 'お申込書類の受付完了', todoList: ['受付完了の連絡を受取る'], shortDesc: 'お申し込み書が届くと受付け完了のメールが届きます。', longDesc: [ 'お申込書が届きましたら電子メールおよびサービスサイト上でご連絡いたします。', ], }, { step: 5, title: '本審査結果のご確認', todoList: ['webサイト上で審査結果を確認する', '契約書の郵送依頼をする'], shortDesc: 'webサイト上で本審査結果を確認し、契約書の郵送依頼をして下さい。', longDesc: [ '電子メールにて本審査完了をご連絡いたします。サービスサイトのお取引画面で本審査結果をご確認下さい。', '同画面にて金利タイプ、ボーナス時のご返済、ご返済日を決定し、契約書の郵送依頼をして下さい。' ], }, { step: 6, title: 'ご契約書類のお受取り・ご返送', todoList: ['契約書が届く', '契約書に記入・捺印する', '契約書を送付する'], shortDesc: '契約書が届いたら記入・捺印し返送して下さい。', longDesc: [ '郵送依頼から一週間以内にご契約書を郵送致します。', '必要事項をご記入・ご捺印しご返送下さい。', ], }, { step: 7, title: 'ご契約書類の受付完了', todoList: ['受付完了の連絡を受取る'], shortDesc: 'お申し込み書が届くと受付け完了のメールが届きます。', longDesc: [ 'ご契約書が届きましたら電子メールおよびサービスサイト上でご連絡いたします。', ], }, { step: 8, title: 'お借入れ日/お振込み先のご設定', todoList: ['借入れ日を決定する', '振込み先を決定する', '金利タイプを決定する'], shortDesc: 'webサイト上でお借入日・お振込み先を決定して下さい。', longDesc: [ 'サービスサイトのお取引画面で、お借入日・お振込み先をご確認下さい.。', '同画面にて、金利タイプを最終決定して下さい。', ], }, { step: 9, title: 'お借入れ', todoList: ['入金の確認をする'], shortDesc: 'お借入日に指定した口座に入金されます。', longDesc: [ 'お借入日にお客さまの口座に入金され、そのままお振り込みされます。', 'この段階でご契約が成立となります。', '翌月よりご返済開始となります。', ], }, { step: 10, title: 'ご契約後の手続き', todoList: ['書類を受領する'], shortDesc: 'ご契約書類の返送等を行います。', longDesc: [ 'ご契約手続き完了後、書類を郵送致します。', ], }, ] <file_sep>import React, { Component } from 'react' import { StyleSheet, View, Text, TouchableHighlight, } from 'react-native' class Footer extends Component { render() { return ( <TouchableHighlight underlayColor='#dddddd' onPress={ () => this.props.onPress() }> <View style={ styles.container }> <Text style={ styles.footerText }>{ this.footerText() }</Text> </View> </TouchableHighlight> ) } footerText() { return this.props.data ? `現在のステップ: ${ this.props.data.step }.${ this.props.data.title }` : '全てのステップが完了しました' } } const styles = StyleSheet.create({ container: { height: 35, bottom: 0, backgroundColor: '#B3E5FC', padding: 5, }, footerText: { color: '#263238', fontSize: 17, fontWeight: 'bold', }, }) export default Footer
bbb21b9bd90f35979211868c966686f71fd53374
[ "JavaScript", "Gradle" ]
8
JavaScript
ozaki25/react_native
1c6965a000d2affaa25301644795155da7821dff
f4eb1b6757af9592dda7c2dbea872d0a501849ce
refs/heads/master
<repo_name>SF-Felling7/pet_hotel<file_sep>/public/index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="jquery-3.2.1.min.js" charset="utf-8"></script> <script src="client.js" charset="utf-8"></script> <link rel="stylesheet" href="style.css"> <title>Pet Hotel</title> </head> <body> <h1>Pet Hotel - Owners and Pets</h1><br /> <h2>Owner Registration</h2> First Name:<input id="firstName" type="text" placeholder="first" /> Last Name:<input id="lastName" type="text" placeholder="last" /> <button id="register">Register</button> <h2>Pets</h2> Owner Name:<select id="ownerName"> </select> Pet name:<input id="petName" type="text" placeholder="name" /> Color:<input id="color" type="text" placeholder="color" /> Breed:<input id="breed" type="text" placeholder="breed"/> <button id="addPet">add pet</button> <div> <table id="table"> <th>Owner</th> <th>Pet</th> <th>Breed</th> <th>Color</th> <th>Update</th> <th>Delete</th> <th>Check In/Out</th> </table> </div> </body> </html> <file_sep>/pet_hotel.sql --ORIGINAL PET HOTEL CREATE CREATE TABLE pets ( id SERIAL PRIMARY KEY NOT NULL, ownerfirstname VARCHAR(20), ownerlastname VARCHAR(20), petname VARCHAR(20), breed VARCHAR(20), color VARCHAR(15), check_indate TIMESTAMP DEFAULT CURRENT_TIMESTAMP, check_outdate TIMESTAMP ) --PET HOTEL 2 SQL COMMANDS -- Create tables CREATE TABLE pets ( id SERIAL PRIMARY KEY, name VARCHAR(40), breed VARCHAR(40), color VARCHAR(40) ); CREATE TABLE visits ( id SERIAL PRIMARY KEY, check_in TIMESTAMP, check_out TIMESTAMP, pet_id INT REFERENCES pets(id) ); CREATE TABLE owners ( id SERIAL PRIMARY KEY, first_name VARCHAR(50), last_name VARCHAR(50), phone_number VARCHAR(20) ); CREATE TABLE pet_owner ( pet_id INT REFERENCES pets(id) ON DELETE CASCADE, owner_id INT REFERENCES owners(id) ON DELETE CASCADE );
65059c8e2f3357ea137bab6fadc4fa5e065d5d9c
[ "SQL", "HTML" ]
2
HTML
SF-Felling7/pet_hotel
0a290e7aaae8b3b88e9752f4ba31f4a3bb1c32dd
9b4972a5b401f7ce6cfa3ec7149bee3ca21b3f57
refs/heads/master
<repo_name>oleckin/for-units<file_sep>/README.md # for-units <file_sep>/ConsoleApp_for_unit/ConsoleApp_for_unit/Program.cs using System; namespace ConsoleApp_for_unit { class Program { static void Main(string[] args) { //Console.WriteLine("Коля, как дела? Нажми любую кнопку, чтобы закончить меня."); //Console.ReadLine(); Console.WriteLine("Введи два числа, чтобы продолжить игру."); string a = Console.ReadLine(); string b = Console.ReadLine(); int num1 = Int32.Parse(a); int num2 = Int32.Parse(b); int result = num1 + num2; Console.WriteLine(result); result = Int32.MaxValue; Console.WriteLine(result); result = num1 * num2; Console.WriteLine(result); result = (num1 * num2 / 2); Console.WriteLine(result); double average = (double) (num1 + num2) / 2; Console.WriteLine(average); } } }<file_sep>/what_watch_today/what_watch_today/Program.cs using System; using System.Diagnostics; namespace what_watch_today { class Program { static void Main(string[] args) { Console.WriteLine("Как тебя зовут?"); String name = Console.ReadLine(); Console.WriteLine("\nПривет, " + name + "! Я помогу выбрать тебе мультик на вечер!"); Console.WriteLine("\nКакой мультик ты хочешь посмотреть весёлый, добрый, музыкальный, поучительный или сказку?"); String genre = Console.ReadLine(); genre = genre.ToLower(); if (genre == "весёлый") { Console.WriteLine("Тогда посоветую вот такие:"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Ну, погоди!"); Console.WriteLine("Простоквашино."); Console.WriteLine("Бобик в гостях у Барбоса."); //searchFilm = "Простоквашино"; //переделать на выбранный фильм } else if (genre == "добрый") { Console.WriteLine("Тогда посоветую вот такие:"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Девочка и спички."); Console.WriteLine("Дюймовочка."); } else if (genre == "музыкальный") { Console.WriteLine("Тогда посоветую вот такие:"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Бременские музыканты."); Console.WriteLine("Летучий корабль."); } else if (genre == "поучительный") { Console.WriteLine("Тогда посоветую вот такие:"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Тётушка Сова."); Console.WriteLine("Фиксики."); Console.WriteLine("Смешарики. Пин-код."); } else { //Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Тогда посоветую вот такие:"); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("Аленький цветочек."); Console.WriteLine("Гора самоцветов."); Console.WriteLine("Конёк-горбунок."); } Console.ResetColor(); Console.WriteLine("\nКакой из этих мультфильмов тебе найти?"); var searchFilm = Console.ReadLine(); searchFilm = searchFilm.ToLower(); Process.Start("open", $"https://www.google.com/search?q=\"{searchFilm}\""); //интерполяция строк Console.ReadLine(); } } }
5591529e7d72c0ee67cbea5ba625706aa3e62437
[ "Markdown", "C#" ]
3
Markdown
oleckin/for-units
bcea8b6db1abd0ecec2b477fc56900c5e7257941
ab0d9c95cbacf72148b0e76fec4b9f0702ee33c0
refs/heads/master
<repo_name>braytac/finger_mdb2MySQL<file_sep>/config.py SSH_USER = '' SSH_PWD = '' URL = '' DB = '' MYSQL_USER = '' MYSQL_PASS = '' MDB_FILE = '' DIFF_IDS = 916594 PORCION = 40000 # INSTALAR AccessDatabaseEngine.exe: # https://www.microsoft.com/es-es/download/confirmation.aspx?id=13255 # python -m py_compile File1.py File2.py File3.py <file_sep>/sincronizar_registro_asistencia.py #!/usr/bin/env python # coding: utf-8 # In[18]: import pyodbc import pymysql #import pandas as pd from paramiko import SSHClient from sshtunnel import SSHTunnelForwarder import datetime from pathlib import Path from config import * DIFF_IDS = 0 """ with SSHTunnelForwarder( ('', 22), ssh_username = '', ssh_password = '', remote_bind_address = ('127.0.0.1', 3306)) as tunnel: conn = pymysql.connect(host='127.0.0.1', user ='', passwd = '', db='', port = tunnel.local_bind_port) query = 'SELECT * FROM USERINFO WHERE USERID<11' data = pd.read_sql_query(query, conn) print(data.head()) conn.close() """; # In[19]: def consulta(query): server = SSHTunnelForwarder( (URL, 22), ssh_username = SSH_USER, ssh_password = <PASSWORD>, remote_bind_address = ('127.0.0.1', 3306) ) #data = pd.read_sql_query('SELECT * FROM USERINFO', conn) server.start() cnx = pymysql.connect(host='127.0.0.1', user = MYSQL_USER, use_unicode=True, charset='utf8', passwd = <PASSWORD>, db = DB, port = server.local_bind_port) cursor = cnx.cursor() cursor.execute(query) #print(cursor.fetchall()) """ for row in cursor: return row print(row) """ """ now = datetime.datetime(2009,5,5) str_now = now.date().isoformat() cursor.execute('INSERT INTO table (name, id, datecolumn) VALUES (%s,%s,%s)', ('name',4,str_now)) """ cnx.commit() cnx.close() #df = pd.read_sql_query(sql , conn) server.stop() return cursor #return df # # IMPORTANDO USUARIOS NUEVOS # In[126]: max_userid = consulta('SELECT MAX(id) FROM USERINFO') max_userid = max_userid.fetchall()[0][0] if max_userid == None: max_userid = 0 conn_str = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ='+MDB_FILE+';' ) conn = pyodbc.connect(conn_str) query = "SELECT USERID,Badgenumber,Name FROM USERINFO WHERE USERID > ? " cursor = conn.cursor() cursor.execute(query,str(max_userid)) # build list of column names to use as dictionary keys from sql results #columns = [column[0] for column in cursor.description] insert = """INSERT INTO USERINFO (id,dni,nombre_apellido) VALUES """ i = 0 for row in cursor.fetchall(): if i == PORCION: break insert += "('"+str(row[0])+"','"+str(row[1])+"','"+str(row[2])+"')," i = i + 1 insert = insert[:-1] #print(insert) #results.append(dict(zip(columns, row))) #output = {"MetaData": {}, "SRData": results} #print(json.dumps(output, sort_keys=True, indent=4)) #query = "SELECT USERID,Badgenumber,Name FROM USERINFO WHERE USERID<10" #dataf = pd.read_sql_query(query, cnxn) conn.close() if i > 0: print("Agregando usuarios nuevos") result = consulta(insert) print("Anterior MAX USER ID: "+str(max_userid)) print("Nuevo MAX USER ID: "+str(max_userid+i)) #dataf # # IMPORTANDO MARCAS NUEVAS # In[123]: #import json max_chkidfecha = consulta("SELECT fecha FROM CHECKINOUT WHERE id_inc=(SELECT MAX(ch1.id_inc) FROM CHECKINOUT ch1 WHERE YEAR(fecha)<'2100' )") if max_chkidfecha.rowcount == 0: max_chkidfecha = '2000-01-01 00:00:00' else: max_chkidfecha = max_chkidfecha.fetchall()[0][0] #if max_chkidfecha == None: conn_str = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ='+MDB_FILE+';' ) conn = pyodbc.connect(conn_str) query = "SELECT TOP "+str(PORCION)+" id, USERID,CHECKTIME,SENSORID FROM CHECKINOUT WHERE CHECKTIME>? ORDER BY CHECKTIME ASC" print("Seleccionando fechas superiores a: "+str(max_chkidfecha)) cursor = conn.cursor() cursor.execute(query,str(max_chkidfecha)) # build list of column names to use as dictionary keys from sql results #columns = [column[0] for column in cursor.description] insert = """INSERT IGNORE INTO CHECKINOUT (id,fecha,sensor_id) VALUES """ i = 0 for row in cursor.fetchall(): if i == PORCION: break insert += "('"+str(row[1])+"','"+str(row[2])+"','"+str(row[3])+"')," max_fecha = row[2] i = i + 1 insert = insert[:-1] #print(insert) #results.append(dict(zip(columns, row))) #output = {"MetaData": {}, "SRData": results} #print(json.dumps(output, sort_keys=True, indent=4)) #query = "SELECT USERID,Badgenumber,Name FROM USERINFO WHERE USERID<10" #dataf = pd.read_sql_query(query, cnxn) conn.close() if i > 0: result = consulta(insert) print("Anterior Max. Fecha: " + str(max_chkidfecha)) print("Nueva Max. Fecha importada: " + str(max_fecha)) #print("Anterior MAX ID: "+str(max_chkid)) #print("Nuevo MAX ID: "+str(max_chkid+i)) #dataf # In[105]: #print(len(insert)) #print(i) consulta('UPDATE config SET last_update=NOW()') #last_update = consulta('SELECT last_update FROM config') #last_update.strftime("%d/%m/%y %H:%m") # In[128]: """ #DATOS PARA SIMULAR chks = consulta("SELECT id_inc,id,fecha FROM CHECKINOUT WHERE id_inc<100000") insert = "INSERT IGNORE INTO CHECKINOUT (id_inc,id,fecha) VALUES " for row in chks.fetchall(): insert += "('"+str(row[0])+"','"+str(row[1])+"','"+str(row[2])+"')," insert = insert[:-1] """;
acd588120e8c08a279cf429e640130e66ec67309
[ "Python" ]
2
Python
braytac/finger_mdb2MySQL
23113e76cd7208ff30e2c98ceaa832939fe7f388
b8c0fa7942571f6bfa80230b8fa3a33d3e54d6ed
refs/heads/master
<repo_name>Lisandro79/JetsonCaffe<file_sep>/classify_caffe_test.py # set up Python environment: numpy for numerical routines, and matplotlib for plotting import numpy as np import matplotlib.pyplot as plt import sys import os import cv2 # The caffe module needs to be on the Python path; # we'll add it here explicitly. caffe_root = '../' # this file should be run from {caffe_root}/examples (otherwise change this line) sys.path.insert(0, caffe_root + 'python') import caffe # If you get "No module named _caffe", either you have not built pycaffe or you have the wrong path if os.path.isfile(caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'): print 'CaffeNet found.' else: print 'Downloading pre-trained CaffeNet model...' !../scripts/download_model_binary.py ../models/bvlc_reference_caffenet caffe.set_device(0) # if we have multiple GPUs, pick the first one caffe.set_mode_gpu() run_model = 2 # 1: the bundled CaffeNet model ; otherwise ResNet # ResNet-50-deploy.prototxt & ResNet-50-model.caffemodel were dowloaded from: https://onedrive.live.com/?authkey=%2<KEY>&id=4006CBB8476FF777%2117887&cid=4006CBB8476FF777 if run_model == 1: model_def = caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt' model_weights = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel' im_size = 227 else: model_def = caffe_root + 'models/ResNet/ResNet-50-deploy.prototxt' model_weights = caffe_root + 'models/ResNet/ResNet-50-model.caffemodel' im_size = 224 net = caffe.Net(model_def, # defines the structure of the model model_weights, # contains the trained weights caffe.TEST) # use test mode (e.g., don't perform dropout) # load the mean ImageNet image (as distributed with Caffe) for subtraction mu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy') mu = mu.mean(1).mean(1) # average over pixels to obtain the mean (BGR) pixel values print 'mean-subtracted values:', zip('BGR', mu) # create transformer for the input called 'data' transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) transformer.set_transpose('data', (2,0,1)) # move image channels to outermost dimension transformer.set_mean('data', mu) # subtract the dataset-mean value in each channel transformer.set_raw_scale('data', 255) # rescale from [0, 1] to [0, 255] transformer.set_channel_swap('data', (2,1,0)) # swap channels from RGB to BGR # set the size of the input (we can skip this if we're happy # with the default; we can also change it later, e.g., for different batch sizes) net.blobs['data'].reshape(50, # batch size 3, # 3-channel (BGR) images im_size, im_size) # image size is 227x227 image = caffe.io.load_image(caffe_root + 'examples/images/cat.jpg') transformed_image = transformer.preprocess('data', image) plt.imshow(image) # copy the image data into the memory allocated for the net net.blobs['data'].data[...] = transformed_image ### perform classification output = net.forward() output_prob = output['prob'][0] # the output probability vector for the first image in the batch print 'predicted class is:', output_prob.argmax() #### <file_sep>/README.md # JetsonCaffe I have successfully installed Caffe on my Jetson TK1 (L4T 21.4, CUDA 6.5, cuDNNv2). The tests for caffee are working fine (make -j 4 all; make -j 4 test; make -j 4 runtest), and I was able to use caffe to classify images from the ImageNet database follwing this example: http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb
7c9e7f10a086106f344470f4ce0b0c26e51e1a3a
[ "Markdown", "Python" ]
2
Python
Lisandro79/JetsonCaffe
9ec0789ebc8e2bb17a0725ad22115ed7eec56788
6dca5d9123fe916e62d929254644cbaf44b6dd1b
refs/heads/main
<repo_name>digitizdat/cdk-elastic-beanstalk<file_sep>/requirements.txt -e . aws_cdk.aws_s3_assets aws_cdk.aws_elasticbeanstalk aws_cdk.aws_iam <file_sep>/cdk_elastic_beanstalk/cdk_elastic_beanstalk_stack.py from glob import glob from os.path import abspath, exists import cdk_elastic_beanstalk_config as config from aws_cdk import aws_elasticbeanstalk as eb from aws_cdk import aws_iam as iam from aws_cdk import aws_s3_assets as assets from aws_cdk import core as cdk class CdkElasticBeanstalkStack(cdk.Stack): def __init__( self, scope: cdk.Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # Get the path to the JAR file from context jarpath = self.node.try_get_context("jarpath") if not jarpath or not exists(abspath(jarpath)): raise RuntimeError( "Set value for jarpath with 'cdk synth --context jarpath=PATH'" ) # Construct an S3 asset from the highest-versioned JAR available in the # ../target dir. jarfile = assets.Asset(self, "app.jar", path=jarpath) # Get the ARN for the TLS certificate from context tls_cert_arn = self.node.try_get_context("tls_cert_arn") if not tls_cert_arn: raise RuntimeError( "Set value for tls_cert_arn with 'cdk synth --context tls_cert_arn=ARN'" ) # Get the app name from context and construct the env name from that. appname = self.node.try_get_context("appname") if not appname: raise RuntimeError( "Set value for appname with 'cdk synth --context appname=NAME'" ) envname = f"{appname}-env" app = eb.CfnApplication(self, "Application", application_name=appname) self.eb_service_role = iam.CfnServiceLinkedRole( self, "ServiceLinkedRole", aws_service_name="elasticbeanstalk.amazonaws.com", ) instance_profile = eb.CfnEnvironment.OptionSettingProperty( namespace="aws:autoscaling:launchconfiguration", option_name="IamInstanceProfile", value=self.eb_service_role.get_att("arn").to_string(), ) certificate = eb.CfnEnvironment.OptionSettingProperty( namespace="aws:elbv2:listener:443", option_name="SSLCertificateArns", value=tls_cert_arn, ) settings = config.create_eb_config() settings += [instance_profile, certificate] # Create an app version from the S3 asset defined above # The S3 "putObject" will occur first before CF generates the template appversion = eb.CfnApplicationVersion( self, "AppVersion", application_name=appname, source_bundle=eb.CfnApplicationVersion.SourceBundleProperty( s3_bucket=jarfile.s3_bucket_name, s3_key=jarfile.s3_object_key ), ) ebenv = eb.CfnEnvironment( self, "Environment", application_name=appname, environment_name=envname, solution_stack_name=config.config["SolutionStackName"], platform_arn=config.config["PlatformArn"], option_settings=settings, # This line is critical - reference the label created in this same stack version_label=appversion.ref, ) # Also very important - make sure that `app` exists before creating an app version appversion.add_depends_on(app) <file_sep>/README.md # AWS CDK / Python / Elastic Beanstalk hosting Java app Start by sourcing the virtual env ``` source .venv/bin/activate ``` Once the virtualenv is activated, you can update the required dependencies. ``` pip install -r requirements.txt ``` Export the CDK_DEFAULT_ACCOUNT and CDK_DEFAULT_REGION variables to your shell environment, unless you'd prefer to hard code them into the Python code. ``` export CDK_DEFAULT_ACCOUNT=ACCOUNT export CDK_DEFAULT_REGION=REGION ``` At this point you can now synthesize the CloudFormation template for this code. ``` cdk synth --context jarpath=PATH_TO_JAR \ --context tls_cert_arn=ACM_CERTIFICATE_ARN \ --context appname=APPNAME ``` If this is the first time you've deployed CDK assets to this account, the toolkit stack must be deployed to the environment. ``` cdk bootstrap --context jarpath=PATH_TO_JAR \ --context tls_cert_arn=ACM_CERTIFICATE_ARN \ --context appname=APPNAME ``` Finally, you are ready to deploy. ``` cdk deploy --context jarpath=PATH_TO_JAR \ --context tls_cert_arn=ACM_CERTIFICATE_ARN \ --context appname=APPNAME ``` ## Useful commands * `cdk ls` list all stacks in the app * `cdk synth` emits the synthesized CloudFormation template * `cdk deploy` deploy this stack to your default AWS account/region * `cdk diff` compare deployed stack with current state * `cdk docs` open CDK documentation Enjoy!
5f4f8af20bda0c5bc2886781ec9fbb13d5a29fc4
[ "Markdown", "Python", "Text" ]
3
Text
digitizdat/cdk-elastic-beanstalk
f7230f2daeee4af3283e636dc1b9982d1407143e
91e314a7a914a8119b3ecc2d873a568f3171d408
refs/heads/master
<file_sep>const red = document.getElementById("red"); const green = document.getElementById("green"); const blue = document.getElementById("blue"); const redTextDisplay = document.getElementById("red-value"); const greenTextDisplay = document.getElementById("green-value"); const blueTextDisplay = document.getElementById("blue-value"); const colorDisplay = document.querySelector(".color-display"); const mainContainer = document.querySelector(".main-container"); const rgb = { red: 0, green: 0, blue: 0 } function renderColor(rgb) { colorDisplay.style.backgroundColor = `rgb(${rgb.red}, ${rgb.green}, ${rgb.blue})`; mainContainer.style.borderTop = `5px solid rgb(${rgb.red}, ${rgb.green}, ${rgb.blue})`; } function setColors() { rgb.red = parseInt(red.value); rgb.green = parseInt(green.value); rgb.blue = parseInt(blue.value); redTextDisplay.value = rgb.red; greenTextDisplay.value = rgb.green; blueTextDisplay.value = rgb.blue; renderColor(rgb); } red.addEventListener("input", setColors); green.addEventListener("input", setColors); blue.addEventListener("input", setColors); window.addEventListener("load", setColors);
3b18b2a926f5bba4cb87627058ecffcf04112db1
[ "JavaScript" ]
1
JavaScript
GuilhermeAmado/rgb-color-visualizer
dd9f78a3b6aca59080629a84557880e4ea1bf9a9
bbd8038bcacac5d2b798cd406fd97047620a7b88
refs/heads/main
<file_sep># Misti Village (Client Side) ## E-commerce site for ordering sweets online. ### Live site link is https://misti-village.web.app/ ### Client site code link is https://github.com/Porgramming-Hero-web-course/full-stack-client-hasanrakibgit ### Server site code link is https://github.com/Porgramming-Hero-web-course/full-stack-server-hasanrakibgit <h3> 👨🏻‍💻 &nbsp;Features </h3> - 🤔 &nbsp; It has login/logout system. - 🎓 &nbsp; Admin of this site can easily add new products and delete products. - 💼 &nbsp; This site is totally based on database. Data are being uploaded and directly send to database and fetch back for showing on UI. - 💼 &nbsp; You can see your order summary. <h3> 🛠 &nbsp;Technologies Used</h3> - 🌐 &nbsp; ![HTML5](https://img.shields.io/badge/-HTML5-333333?style=flat&logo=HTML5) ![CSS](https://img.shields.io/badge/-CSS-333333?style=flat&logo=CSS3&logoColor=1572B6) ![JavaScript](https://img.shields.io/badge/-JavaScript-333333?style=flat&logo=javascript) ![Bootstrap](https://img.shields.io/badge/-Bootstrap-333333?style=flat&logo=bootstrap&logoColor=563D7C) ![Node.js](https://img.shields.io/badge/-Node.js-333333?style=flat&logo=node.js) ![React](https://img.shields.io/badge/-React-333333?style=flat&logo=react) - 🛢 &nbsp; ![MongoDB](https://img.shields.io/badge/-MongoDB-333333?style=flat&logo=mongodb) - ⚙️ &nbsp; ![Git](https://img.shields.io/badge/-Git-333333?style=flat&logo=git) ![GitHub](https://img.shields.io/badge/-GitHub-333333?style=flat&logo=github) - 🔧 &nbsp; ![Visual Studio Code](https://img.shields.io/badge/-Visual%20Studio%20Code-333333?style=flat&logo=visual-studio-code&logoColor=007ACC) <br/> <h3> 🤝🏻 &nbsp;Connect with Me </h3> <p align="center"> <a href="https://www.linkedin.com/in/rakibul-hasan-70667b90/"><img alt="LinkedIn" src="https://img.shields.io/badge/LinkedIn-<NAME>-blue?style=flat-square&logo=linkedin"></a> <a href="<EMAIL>"><img alt="Email" src="https://img.shields.io/badge/Email-<EMAIL>-blue?style=flat-square&logo=gmail"></a> </p> <file_sep>import React from 'react'; import { Link } from 'react-router-dom'; import './Product.css' const Product = ({ product }) => { return ( <div className="card"> <img style={{ height: '300px' }} src={product.imageURl} alt="" /> <div className="card-details"> <h2>{product.name}</h2> <h4>{product.price}</h4> <h5>{product.weight}</h5> <h3><Link to={`/checkOut/${product._id}`}>Buy Now</Link></h3> </div> </div> ); }; export default Product;<file_sep> import React, { useContext } from 'react'; import { Link } from 'react-router-dom'; import { UserContext } from '../../App'; import logo from '../../images/Misti Village.png'; import './Header.css'; const Header = () => { const [loggedInUser, setLoggedInUser] = useContext(UserContext); return ( <div> <nav className= "nav"> <ul> <li> <img className ="logo"src={logo} alt=""/> </li> <li> <Link to="/home">Home</Link> </li> <li> <Link to="/order">Order</Link> </li> <li> <Link to="/admin">Admin</Link> </li> <li> <Link to="/deals">Deals</Link> </li> <li> <Link to="/login">Login </Link> </li> <button onClick = {() => setLoggedInUser ({})}>Log Out</button> </ul> </nav> </div> ); }; export default Header;<file_sep>const firebaseConfig = { apiKey: "<KEY>", authDomain: "misti-village.firebaseapp.com", projectId: "misti-village", storageBucket: "misti-village.appspot.com", messagingSenderId: "375639933104", appId: "1:375639933104:web:214241ed029151d639bb75" }; export default firebaseConfig;<file_sep>import React from 'react'; import { Link, Route, Router, Switch, } from 'react-router-dom'; const Admin = () => { return ( <div style={{ textAlign: 'center' }}> <h1>You can add and manage Products here</h1> <h1><Link to="/addProducts">Add Products</Link> </h1> <h1><Link to="/manageProducts">Manage Products</Link> </h1> </div> ); }; export default Admin;
ae872039eb1ad78b5838719f35f311ad05229647
[ "Markdown", "JavaScript" ]
5
Markdown
hasanrakibgit/full-stack-client
33a4c2c2254a7626c6575756340fb7db33da721f
8d02c259d83451e614a5b65f7c4eb05a790663bb
refs/heads/main
<repo_name>AHMADMUHMMED/Lab16_Segue<file_sep>/Lab16_Segue. AHMAD/Lab16_Segue. AHMAD/ViewControllerTwo.swift // // ViewControllerTwo.swift // Lab16_Segue. AHMAD // // Created by <NAME> on 26/03/1443 AH. // import Foundation class ViewControllerTwo:ViewController{ } <file_sep>/Lab16_Segue. AHMAD/Lab16_Segue. AHMAD/ViewControllerOne.swift // // ViewControllerOne.swift // Lab16_Segue. AHMAD // // Created by <NAME> on 26/03/1443 AH. // import Foundation import UIKit class ViewControlleOne:UIViewController{ } <file_sep>/Lab16_Segue. AHMAD/Lab16_Segue. AHMAD/ViewControllerThree.swift // // ViewControllerThree.swift // Lab16_Segue. AHMAD // // Created by <NAME> on 26/03/1443 AH. // import Foundation class ViweControllerThree:ViewController{ }
af7271f148edf782e3a3f4a14e90a4c8a849b784
[ "Swift" ]
3
Swift
AHMADMUHMMED/Lab16_Segue
6dfaa69c5f1b90bf162a4abbe823e9b210662296
df93394d6c55b132d6a583d1340dc0db8b872c95
refs/heads/master
<file_sep>package com.ykmimi.jdk13test; public class JDK13Test2 { public static void main(String[] args) { howMany(1); } //switch private static void howMany(int k) { System.out.println( switch (k) { case 1 -> "one"; case 2 -> "two"; default -> "many"; } ); } // var 变量类型声明不可用于switch判定 // private static void howType(var param) { // // } } <file_sep>使用idea 2019.2 之后的版本可以支持jdk13 <br> JDK13Test 测试了 text block <br> JDK13Test2 测试了 switch <br> 如果有报错的地方,如text block是报错的,那么调整: <br> Settings > Build,... > Compiler > Java Compiler > Module > Target bytecode version > change to 13 <br> jdk13 API : https://docs.oracle.com/en/java/javase/13/docs/api/ <br>
00702d63e56e60aef61c882d14d9db3f6fc4fed4
[ "Markdown", "Java" ]
2
Java
deadzq/jdk13-test
46eb9fae5201cd5f373788e921590082c35f1307
6afa4aaf033a38834790494c835ddb210969ee11
refs/heads/master
<file_sep>package Evaluvation1.ArrayCompare; import java.util.Arrays; public class ArrayComaparision { public static void main(String []args) { int arr1[]= {1,2,3}; int arr2[]= {1,2,3}; if (Arrays.equals(arr1, arr2)) System.out.println("The Array 1 and 2 are Same"); else System.out.println("The Array 1 and 2 are different"); } } <file_sep>package Evaluvation1.EnumEg; import java.util.Scanner; public class EumAndSwitch { public static void main(String []args) { EnumDays[] day=EnumDays.values(); System.out.println("Enter the day order number to print the day "); Scanner sc = new Scanner(System.in); int ch=sc.nextInt(); switchMethod(ch); } private static void switchMethod(int ch) { switch(ch) { case 1: System.out.println(EnumDays.SUNDAY);break; case 2: System.out.println(EnumDays.MONDAY);break; case 3: System.out.println(EnumDays.TUESDAY);break; case 4: System.out.println(EnumDays.WEDNESDAY);break; case 5: System.out.println(EnumDays.THURSDAY);break; case 6: System.out.println(EnumDays.FRIDAY);break; case 7: System.out.println(EnumDays.SATURDAY);break; default : System.out.println("No Such Data Exist "); break; } } } <file_sep>package Evaluvation1.Interface; public class InterfaceEg { public static void main(String[] args) { drawable d= new circle(); d.draw(); d=new rect(); d.draw(); } } interface drawable{ void draw(); } class rect implements drawable{ public void draw() { int lent=10,breath=12; int area=lent*breath; System.out.println("draw rectangle with arrea "+area ); } } class circle implements drawable{ public void draw() { int radius=2; double PI=3.14; double area=PI*radius*radius; System.out.println("circle on the way with area "+area); } } <file_sep>package Evaluvation1.EnumEg; public enum EnumDays { SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY } <file_sep>package Evaluvation1.Java8; public class LambdaExpression { public static void main(String [] args) { Sayable s=()->{ return "I have nothing to say"; }; System.out.println(s.say()); } } <file_sep>package Evaluvation1.LargeandSmall; public class LargestAndSmallest { public static void main(String[] args) { int arr[]= {2,34,45,156,94,209}; int min=arr[0]; int max=arr.length ; for(int i=1;i<arr.length;i++){ if(min>arr[i]) min=arr[i]; } for(int i=0;i<arr.length;i++) { if(max<arr[i]) max=arr[i]; } System.out.println("smallest in array is "+min); System.out.println("Largest in array is "+max); } } <file_sep>package Evaluvation1.StringToSubString; public class StringToSubString { public static void main(String args[]) { String str = "jan-feb-march"; String[] temp; String atpoint = "-"; temp = str.split(atpoint); for(int i = 0; i < temp.length; i++) { System.out.println(temp[i]); } } } <file_sep>package Evaluvation1.NumberReverse; import java.util.Scanner; public class ReverseNumber { public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.println("Enetr a number:"); int num=sc.nextInt(); int sum=0,rem=0,temp; temp=num; while(num>0) { rem=num%10; sum=(sum*10)+rem; num=num/10; } System.out.println("Reverse of the "+temp+" is "+sum); } } <file_sep># Basic Basic Java Codes You wiil get basic interview question on java <file_sep>package Evaluvation1.CollectionConcepts; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class MapEg { public static void main(String []args) { Map <String,String>map1 = new HashMap<>(); map1.put("1", "One"); map1.put("2", "Two"); map1.put("3", "Three"); map1.put("4", "Four"); SortedMap<String,String> map2 = new TreeMap<>(); map2.put("1", "One"); map2.put("2", "Two"); map2.put("3", "Three"); map2.put("4", "Four"); LinkedHashMap<String,String> map3 = new LinkedHashMap<>(); map3.put("1", "One"); map3.put("2", "Two"); map3.put("3", "Three"); map3.put("4", "Four"); System.out.println("Hash Map"); System.out.println(map1); System.out.println("Tree Map "); System.out.println(map2); System.out.println("LinkedHash Map"); System.out.println(map3); } }
3633bf45a08fc1624bae756f9beed0da23b402f2
[ "Markdown", "Java" ]
10
Java
manojraj013/Basic
ea3cbcab06cdbeb11b5e90fab10714023117b2bc
b6c9fd9eaef90a701a7baeed42e12e288840c236
refs/heads/master
<repo_name>jacoboliveira/corretor-ato-cotepe-web<file_sep>/test/testes/TestStrings.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package testes; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author jacoboliveira */ public class TestStrings { public TestStrings() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // @Test public void hello() throws Exception { // String fileName = "atocotepe.txt"; // // if(StringHelper.endsWith(fileName, ".txt")){ // System.out.println("foi encontrado"); // }else{ // System.out.println("nao foi encontrado"); // } // ICaminhosArquivosDao caminhosArquivosDao = CaminhosArquivosDao.instance(); // // List<CaminhosArquivos> list = caminhosArquivosDao.findAll(); // for (CaminhosArquivos object : list) { // System.out.println(object.getCaminho()); // } // } } <file_sep>/src/java/br/com/ato/cotepe/hibernate/GenericDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.ato.cotepe.hibernate; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.Query; /** * * @author jacoboliveira */ public class GenericDao<E , ID extends Serializable> implements IGenericDao<E,ID> { private Class<E> persistentClass; private EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("corretor-ato-cotepe-pu"); private EntityManager entityManager; public GenericDao() { entityManager = entityManagerFactory.createEntityManager(); this.persistentClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } // public void init(EntityManager entityManager) { // this.entityManager = entityManager; // this.persistentClass = (Class<E>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; // } @Override public E findById(ID id, boolean lock) throws Exception { E object; if (lock) { object = (E) entityManager.find(persistentClass, id); } else { object = (E) entityManager.getReference(persistentClass, id); } return object; } @Override public E findById(ID id) throws Exception { if (entityManager.isOpen()) { E e = (E) entityManager.find(persistentClass, id); return e; } return null; } @Override public List<E> findAll() throws Exception { List<E> lista = createQuery("select entity from " + persistentClass.getSimpleName() + " entity").getResultList(); return lista; } @Override public E save(E entity) throws Exception { entityManager.persist(entity); return entity; } @Override public E update(E entity) throws Exception { entityManager.merge(entity); return entity; } @Override public List<E> updateAll(E... entitys) throws Exception { for (E entity : entitys) { entity = entityManager.merge(entity); } return Arrays.asList(entitys); } @Override public List<E> updateAll(List<E> entitys) throws Exception { for (E entity : entitys) { entity = entityManager.merge(entity); } return entitys; } @Override public List<E> saveAll(E... entitys) throws Exception { for (E entity : entitys) { entityManager.persist(entity); } return Arrays.asList(entitys); } @Override public List<E> saveAll(List<E> entitys) throws Exception { for (E entity : entitys) { entityManager.persist(entity); } return entitys; } @Override public void delete(E entity) throws Exception { entityManager.remove(entity); } @Override public void delete(ID id) throws Exception { entityManager.remove(entityManager.find(persistentClass, id)); } @Override public List<E> deleteAll(E... entitys) throws Exception { for (E entity : entitys) { entityManager.remove(entity); } return Arrays.asList(entitys); } @Override public List<ID> deleteAll(ID... ids) throws Exception { for (ID id : ids) { entityManager.remove(entityManager.find(persistentClass, id)); } return Arrays.asList(ids); } @Override public Query createNamedQuery(String namedQuery) { return entityManager.createNamedQuery(namedQuery); } @Override public Query createQuery(String hql) throws Exception { return entityManager.createQuery(hql); } @Override public EntityManager getEntittyManager() { return entityManager; } } <file_sep>/src/java/br/com/ato/cotepe/dao/ICaminhosArquivosDao.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.ato.cotepe.dao; import br.com.ato.cotepe.entities.CaminhosArquivos; import br.com.ato.cotepe.hibernate.IGenericDao; /** * * @author jacoboliveira */ public interface ICaminhosArquivosDao extends IGenericDao<CaminhosArquivos, Long> { } <file_sep>/README.md corretor-ato-cotepe-web ======================= Sistema de correção ato cotepe
fcf0e3edf744a16d3af847c53a8d50fd57fc6846
[ "Markdown", "Java" ]
4
Java
jacoboliveira/corretor-ato-cotepe-web
fb289b08f4145cc93694496af883dfb0bfcd5428
711245d5384657e3f73c00768988dd1ab5be8714
refs/heads/master
<repo_name>vitorperesss/measure_image<file_sep>/js/main.js $(document).ready(function(){ var clicks = 0; var lastClick = [0, 0]; var valor_final_X = 0; var valor_final_Y = 0; document.getElementById('canvas').addEventListener('click', drawLine, false); function getCursorPosition(e) { var x; var y; if (e.pageX != undefined && e.pageY != undefined) { x = e.pageX; y = e.pageY; } else { x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } return [x, y]; } function drawLine(e) { var canvas = document.getElementById("canvas"); var context = this.getContext('2d'); var key = 'false'; var x = getCursorPosition(e)[0] - this.offsetLeft; var y = getCursorPosition(e)[1] - this.offsetTop; if(clicks == 1){ key = true; } var eixoX = x; var eixoY = y; calculateAxes(eixoX,eixoY,key); if (clicks != 1 && key != true) { context.lineWidth = '4'; context.beginPath(); context.arc(x+0.9, y, 6, 20, Math.PI*2, true); context.closePath(); context.fillStyle = 'green'; context.fill(); context.strokeStyle = '#ADFF2F'; context.stroke(); context.save(); clicks++; } else { context.beginPath(); context.arc(x, y, 6, 20, Math.PI*2, true); context.closePath(); context.fill(); context.fillStyle = 'green'; context.moveTo(lastClick[0], lastClick[1]); context.lineTo(x, y, 6); context.strokeStyle = '#ADFF2F'; context.lineWidth = '4'; context.stroke(); context.font = "16px Comic Sans MS"; context.fillStyle = 'green'; context.textAlign = "center"; context.fillText((valor_final_X+valor_final_Y).toFixed(2)+" Cm", x, y-12); context.save(); clicks = 0; $("#undo").click(function() { context.clearRect(0, 0, canvas.width, canvas.height); }); } lastClick = [x, y]; } var array = ['X','Y','key']; array['X'] = []; array['Y'] = []; array['key'] = []; function calculateAxes(eixoX,eixoY,key){ var tamX = ""; var tamY = ""; var chave = ""; if (tamX == '' && tamY == ''){ var i = 0; tamX = eixoX; tamY = eixoY; chave = key; if(chave == true){ i = i+1; } array['X'][i] = tamX; array['Y'][i] = tamY; array['key'][i] = chave; var result_x = array['X'][0] - array['X'][1]; var result_y = array['Y'][0] - array['Y'][1]; var valor_de_x = Math.abs(result_x); var valor_de_y = Math.abs(result_y); if(chave == true){ getImgSize(valor_de_x,valor_de_y); } } } var X; var Y; function getImgSize(valor_de_x,valor_de_y,X,Y) { var tamanho_x = valor_de_x * 2.54 / 96; var tamanho_y = valor_de_y * 2.54 / 96; if(tamanho_x > tamanho_y){ X = tamanho_x; if(X > 0){ valor_final_X = X; valor_final_Y = 0; } }else{ Y = tamanho_y; if(Y > 0){ valor_final_Y = Y; valor_final_X = 0; } } } var x = (x!==undefined) ? x : 0; var y = (y!==undefined) ? x : 0; document.getElementById('imageLoader').addEventListener('change', function(event) { var h = $("#canvas").height(); var w = $("#canvas").width(); var x = $("#imagem").width(); var newx = w; var y = $("#imagem").height(); var prop = (100 * newx/x) / 100; var newy = x * prop; var myCanvas = document.getElementById('canvas'); var ctx = myCanvas.getContext('2d'); var img = new Image(); img.onload = function(){ myCanvas.width = img.width; myCanvas.height = img.height; $("#canvas").attr('width',newx); $("#canvas").attr('height',newy); $("#imagem").attr('src', img); ctx.drawImage(img, 0,0,newx,newy); ctx.save(); }; img.src = URL.createObjectURL(event.target.files[0]); }); }); <file_sep>/README.md ### Medidor de Imagem Medidor de imagem usando **JavaScript** e **Canvas**. Interação e Manipulação de eixos(x,y), calculando tamanho e largura da imagem em pixel e transformando em centímetros com DPI constante e proporção relativa a área setada no tamanho do canvas.
b57bcf882ebd6c0196144d7ab720c1d90faa19c6
[ "JavaScript", "Markdown" ]
2
JavaScript
vitorperesss/measure_image
8dbc93b108c78bdfada42b46823ccc81debf83bb
9a54a9788e8978883f9e12e6717d7346106887c7
refs/heads/main
<file_sep>import React, { Component } from "react"; class TodoList extends Component { state = { list: [], }; HandleAdd = (e) => { e.preventDefault(); if (e.target.task.value === "") { window.alert("empty input"); } else { const NewList = [...this.state.list]; NewList.push({ id: Math.random(), phrase: e.target.task.value, }); this.setState({ list: NewList }); } e.target.task.value = ""; }; HandleDelete = (id) => { const ListNew = [...this.state.list]; const list = ListNew.filter((f) => f.id !== id); this.setState({ list }); }; render() { const length = this.state.list.length; const task = length ? ( this.state.list.map((l) => { return ( <li key={l.id}> {l.phrase}{" "} <i class="fas fa-trash-alt" onClick={() => this.HandleDelete(l.id)} ></i> </li> ); }) ) : ( <p>No todos</p> ); return ( <section> <form onSubmit={this.HandleAdd}> <label htmlFor="">Put your todo</label> <input type="text" name="task"></input> <button>Add</button> </form> {task} </section> ); } } export default TodoList; <file_sep># Simple-React-TodoApp
de8c53280b00cfe6d61e68492fbd679d1e981b91
[ "JavaScript", "Markdown" ]
2
JavaScript
medhatnasra/Simple-React-TodoApp
86d3b95916791a9c7ca6335c32c0504a9fbcdab1
ec54faf1e15d1f77c9725fd05afa087bb5749448
refs/heads/main
<file_sep>const { Router } = require("express"); const router = Router(); const FacturacionCtrl = require("../controllers/Facturacion.controllers"); router.post("/crear", FacturacionCtrl.createFacturacion); router.get("/listarfacturacion", FacturacionCtrl.listar); router.get("/listar/:id", FacturacionCtrl.listarid); router.delete("/eliminar/:id", FacturacionCtrl.eliminar); router.put("/actualizar/:id", FacturacionCtrl.actualizar); router.get("/buscar/:factura", FacturacionCtrl.buscarfactura); module.exports = router; <file_sep># <NAME> # Descripcion El desarrollo consiste una api NODE / Express - MongoDB encargada de servir datos de facutracion electrica # Instalacion Para la instalacion de dependencias ejecutar tanto en el front como en el back ``` npm install ``` # Backend La aplicacion correra en el puerto 4001. Para inciarla, ejecutar: ``` npm run start ``` Creará la BBDD y levantará la API Adicionalmente, se permite la subida de datos de prueba desde un csv (El Csv se llama bbddPruebas.csv) incluido en el directorio, ya validado en origen con las siguientes instrucciones: ``` npm run install-db ``` Para eliminar la BBDD ejecutamos: ``` npm run delete-db ``` ## Schema de mongoose ``` const FacturacionSchema = new Schema({ factura: { type: String, required: true, unique: true }, /* Obligatorio y unico */ nombreCliente: String, fecha: String, idFiscal: String, consumo: String, importe: String, }); ``` ## Metodos La V1 de la API permite hacer operaciones CRUD sobre los datos ## Post Para añadir datos a la api, realizar una operacion post a la url: ``` url/facturacion/crear ``` ## Get - La API muestra los anuncios en la ruta: ``` url/facturacion/listarfacturacion ``` devuelve consultas tipo: ``` {"_id": "5fc4ae9e4635b6802c39ecd2", "factura": "F00001", "nombreCliente": "Empresa1", "fecha": "2020-11-01", "idFiscal": "A00000001", "consumo": "524", "importe": "250" }, { "_id": "5fc4ae9e4635b6802c39ecd3", "factura": "F00002", "nombreCliente": "Empresa2", "fecha": "2020-11-01", "idFiscal": "A00000002", "consumo": "524", "importe": "250" }, ``` Adicionalmente, se ha incluido una busqueda individual por numero de factura ``` url/facturacion/buscar/:factura { "_id": "5fc4ae9e4635b6802c39ecd2", "factura": "F00001", "nombreCliente": "Empresa1", "fecha": "2020-11-01", "idFiscal": "A00000001", "consumo": "524", "importe": "250" } ``` ## Put Para realizar actualizaciones acceder a: ``` url/facturacion/buscar/:factura ``` ## Delete Para eliminar registros acceder a: ``` url/facturacion/eliminar/:id ``` ## Test Se han creados varios test para la API, una vez que la aplicación esté iniciada pueden ejecutarse con : ``` npm run test ``` # FrontEnd Dessarrolo Front en React para el consumo de la API. Se pueden buscar registros por factura, añadirlos, eliminarlos y actualizarlos. Una vez iniciada la API node del back: ``` npm start ``` <file_sep>const request = require("supertest"); const app = require("../src/index"); // Test sobre la API it("Consulta correcta", (done) => { request(app) .get("/facturacion/listarfacturacion") .set("Accept", "application/json") .expect(200, done); }); it("Consulta por numero de factura que existe", (done) => { request(app) .get("/facturacion/buscar/F00003") .set("Accept", "application/json") .expect(200, done); }); it("Crear nuevo registro", (done) => { const data = { factura: "PRUEBA0X", nombreCliente: "<NAME>", fecha: "2020-05-11", idFiscal: "Fprueba", consumo: 547, importe: 541, }; request(app) .post("/facturacion/crear") .send(data) .type("json") .set("Accept", "application/json") .expect(200, done); }); /* CAMBIAR ID POR ALGUNO EXISTENTE it('Eliminar correcto', done => { request(app) .delete('/facturacion/eliminar/5fc4df6024aa3899731360ea') .set('Accept', 'application/json') .expect(200,done); }); */ <file_sep>import { BrowserRouter as Router, Route } from "react-router-dom"; import React from "react"; import Index from "./components/Index"; import Actualizar from "./components/Actualizar"; function App() { return ( <Router> <Route path="/" exact component={Index} /> <Route path="/editar/:id" component={Actualizar} /> </Router> ); } export default App; <file_sep>import React, { useEffect, useState } from "react"; import Axios from "axios"; import Swal from "sweetalert2"; export default function Actualizar(props) { const [factura, setFactura] = useState(""); const [nombreCliente, setNombreCliente] = useState(""); const [fecha, setFecha] = useState(""); const [idFiscal, setIdFiscal] = useState(""); const [consumo, setConsumo] = useState(""); const [importe, setImporte] = useState(""); const URL = "http://localhost:4001/facturacion/"; useEffect(() => { //Ejecutamos en la carga obtenerFacturacion(); }, []); const obtenerFacturacion = async () => { const id = props.match.params.id; const respuesta = await Axios.get(URL + "listar/" + id); setFactura(respuesta.data.factura); setNombreCliente(respuesta.data.nombreCliente); setFecha(respuesta.data.fecha); setIdFiscal(respuesta.data.idFiscal); setConsumo(respuesta.data.consumo); setImporte(respuesta.data.importe); }; const actualizar = async (e) => { e.preventDefault(); const id = props.match.params.id; const facturacion = { factura, nombreCliente, fecha, idFiscal, consumo, importe, }; const respuesta = await Axios.put(URL + "actualizar/" + id, facturacion); const { mensaje, retorno } = respuesta.data; if (retorno === "200") { Swal.fire({ icon: "success", title: mensaje, showConfirmButton: false, }); setTimeout(() => { window.location.href = "/"; }, 2500); } else { Swal.fire({ icon: "error", title: mensaje, showConfirmButton: true, }); } }; return ( <div className="container col-md-6 mt-4"> <div className="card"> <div className="card-header"> <h3>Editar</h3> <div className="card-body"> <form onSubmit={actualizar}> <div className="form-group"> <label> Factura </label> <input type="text" className="form-control" required onChange={(e) => setFactura(e.target.value)} value={factura} /> </div> <div className="form-group"> <label> Nombre Cliente </label> <input type="text" className="form-control" required onChange={(e) => setNombreCliente(e.target.value)} value={nombreCliente} /> </div> <div className="form-group"> <label> Fecha </label> <input type="text" className="form-control" required onChange={(e) => setFecha(e.target.value)} value={fecha} /> </div> <div className="form-group"> <label> Id Fiscal </label> <input type="text" className="form-control" required onChange={(e) => setIdFiscal(e.target.value)} value={idFiscal} /> </div> <div className="form-group"> <label> Consumo </label> <input type="text" className="form-control" required onChange={(e) => setConsumo(e.target.value)} value={consumo} /> </div> <div className="form-group"> <label> Importe </label> <input type="text" className="form-control" required onChange={(e) => setImporte(e.target.value)} value={importe} /> </div> <div className="form-group"> <button className="btn btn-warning" type="submit"> Actualizar </button> </div> </form> </div> </div> </div> </div> ); } <file_sep>import React, { useState, useEffect } from "react"; import Axios from "axios"; import { Link } from "react-router-dom"; import Swal from "sweetalert2"; export default function Index() { const [facturacion, setFacturacion] = useState([]); const [factura, setFactura] = useState(""); const [nombreCliente, setNombreCliente] = useState(""); const [fecha, setFecha] = useState(""); const [idFiscal, setIdFiscal] = useState(""); const [consumo, setConsumo] = useState(""); const [importe, setImporte] = useState(""); const URL = "http://localhost:4001/facturacion/"; useEffect(() => { obtenerFacturacion(); }, []); const obtenerFacturacion = async () => { const respuesta = await Axios.get(URL + "listarfacturacion/"); setFacturacion(respuesta.data); }; const eliminar = async (id) => { const respuesta = await Axios.delete(URL + "eliminar/" + id); const mensaje = respuesta.data.mensaje; if (respuesta.data.retorno === "200") { Swal.fire({ icon: "success", title: mensaje, showConfirmationButton: false, timer: 2500, }); obtenerFacturacion(); } else { Swal.fire({ icon: "error", title: mensaje, showConfirmationButton: false, timer: 2500, }); obtenerFacturacion(); } }; const guardar = async (e) => { e.preventDefault(); const nuevoRegFacturacion = { factura, nombreCliente, fecha, idFiscal, consumo, importe, }; const respuesta = await Axios.post(URL + "crear", nuevoRegFacturacion); const mensaje = respuesta.data.mensaje; if (respuesta.data.retorno === "201") { Swal.fire({ icon: "success", title: mensaje, showConfirmationButton: false, }); setTimeout(() => { window.location.href = "/"; }, 2500); } else { Swal.fire({ icon: "error", title: mensaje, showConfirmationButton: false, }); } }; const buscar = async (e) => { if (e.target.value === "") { return obtenerFacturacion(); } const buscar = e.target.value; const respuesta = await Axios.get(URL + "buscar/" + buscar); setFacturacion(respuesta.data); }; return ( <div> <header className="py-2 bg-primary text-white"> <div className="container"> <div className="row"> <div className="col-md-6"> <h1> <i className="fas fa-pencil-alt"></i> Datos de facturación </h1> </div> </div> </div> </header> {/* Busqueda */} <nav className="navbar py-4"> <div className="container"> <div className="col-md-3"> <Link to="/" className="btn btn-primary btn-block" data-toggle="modal" data-target="#addRegistro" > <i className="fas fa-plus"> Add Registro</i> </Link> </div> <div className="col-md-6 ml-auto"> <div className="input-group"> <input className="form-control mr-sm-2" type="search" placeholder="Buscar por factura" aria-label="Search" onChange={(e) => buscar(e)} ></input> </div> </div> </div> </nav> {/*MOSTRAR REGISTROS*/} <section> <div className="container"> <div className="row"> <div className="col-md-12"> <div className="card"> <div className="card-header"> <h4> Facturacion</h4> </div> <table className="table table-responsive-lg table-striped"> <thead className="thead-dark"> <tr> <th>#</th> <th>Factura</th> <th>Nombre Cliente</th> <th>Fecha</th> <th>Id Fiscal</th> <th>Consumo</th> <th>Importe</th> <th>Opciones</th> </tr> </thead> <tbody> {facturacion.map((facturacion, i) => ( <tr key={facturacion._id}> <td>{i + 1}</td> <td>{facturacion.factura}</td> <td>{facturacion.nombreCliente}</td> <td>{facturacion.fecha}</td> <td>{facturacion.idFiscal}</td> <td>{facturacion.consumo}</td> <td>{facturacion.importe}</td> <td> <button className="btn btn-danger mr-1" onClick={() => eliminar(facturacion._id)} > Eliminar </button> <Link className="btn btn-warning mr-1" to={"/editar/" + facturacion._id} > Actualizar </Link> </td> </tr> ))} </tbody> </table> </div> </div> </div> </div> </section> {/*Agregar registro */} <div className="modal fade" id="addRegistro"> <div className="modal-dialog modal-lg"> <div className="modal-content"> <div className="modal-header bg-primary text-white"> <h5 className="modal-tittle">Add registro </h5> <button className="close" data-dismiss="modal"> <span>&times;</span> </button> </div> <div className="modal-body"> <form onSubmit={guardar}> <div className="form-group"> <label> Factura </label> <input type="text" className="form-control" required onChange={(e) => setFactura(e.target.value)} /> </div> <div className="form-group"> <label> Nombre Cliente </label> <input type="text" className="form-control" required onChange={(e) => setNombreCliente(e.target.value)} /> </div> <div className="form-group"> <label> Fecha </label> <input type="date" className="form-control" required onChange={(e) => setFecha(e.target.value)} /> </div> <div className="form-group"> <label> Id Fiscal </label> <input type="text" className="form-control" required onChange={(e) => setIdFiscal(e.target.value)} /> </div> <div className="form-group"> <label> Consumo </label> <input type="number" step="any" className="form-control" required onChange={(e) => setConsumo(e.target.value)} /> </div> <div className="form-group"> <label> Importe </label> <input type="number" step="any" className="form-control" required onChange={(e) => setImporte(e.target.value)} /> </div> <div className="form-group"> <button className="btn btn-primary" type="submit"> {" "} Guardar </button> </div> </form> </div> </div> </div> </div> </div> ); } <file_sep>const mongoose = require("mongoose"); URI = "mongodb://localhost/pruebaw"; mongoose .connect(URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false, }) .then((db) => console.log("la base de datos esta conectada")) .catch((error) => console.log(error)); module.exports = mongoose; <file_sep>const FacturacionCtrl = {}; const Facturacion = require("../models/Facturacion.model"); // Crear registro FacturacionCtrl.createFacturacion = async (req, res) => { const { factura, nombreCliente, fecha, idFiscal, consumo, importe, } = req.body; const NuevoFacturacion = new Facturacion({ factura, nombreCliente, fecha, idFiscal, consumo, importe, }); if (!factura) { res.json({ mensaje: "Campo Factura obligatorio", retorno: "400", }); res.render("error", { error: err }); } else { const idFactura = await Facturacion.findOne({ factura: factura }); if (idFactura) { res.json({ mensaje: "El numero de factura ya existe", retorno: "402", }); } else { await NuevoFacturacion.save(); res.json({ mensaje: "Registro agregado OK", retorno: "201", factura: NuevoFacturacion.factura, }); } } }; // Listar todos los registros FacturacionCtrl.listar = async (req, res) => { const respuesta = await Facturacion.find(); res.json(respuesta); }; // Listar por ID FacturacionCtrl.listarid = async (req, res) => { const id = req.params.id; const respuesta = await Facturacion.findById({ _id: id }); res.json(respuesta); }; //Eliminar Registro FacturacionCtrl.eliminar = async (req, res, next) => { try { const id = req.params.id; const facturacion = await Facturacion.findByIdAndRemove({ _id: id }); if (facturacion) { res.json({ mensaje: "Registro Eliminado", retorno: "200", }); } else { res.json({ mensaje: "Registro Inexistente", retorno: "402", }); } } catch (err) { res.json({ mensaje: "Error", retorno: "500", }); } }; // Actualizar registro FacturacionCtrl.actualizar = async (req, res, next) => { try { const id = req.params.id; const facturacion = await Facturacion.findByIdAndUpdate( { _id: id }, req.body ); if (facturacion) { res.json({ mensaje: "Registro Actualizado", retorno: "200", }); } else { res.json({ mensaje: "Registro Inexistente", retorno: "402", }); } } catch (err) { if (err.code == 11000) { res.json({ mensaje: "El numero de factura ya existe", retorno: "402", }); } else { res.json({ mensaje: "Error al actualizar", retorno: "500", }); } } }; // Busqueda por factura FacturacionCtrl.buscarfactura = async (req, res) => { const factura = req.params.factura; const respuesta = await Facturacion.find({ factura: factura }); if (respuesta) { res.json(respuesta); } else { res.json({ mensaje: "Registro Inexistente", retorno: "304", }); } }; module.exports = FacturacionCtrl;
d7842fc65226159322adeedb33e9f35ab81e451e
[ "JavaScript", "Markdown" ]
8
JavaScript
gradosj/pruebaW
30c211b634009acabc5e40ac4e9dd55c92a8ef84
ea9da0a73bdf5bc6e7a48b2f22f67450afaf607c
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # Argumentos def suma(otro, *args): print(type(args)) suma(1, 2, 3, 5, 5, 6, 7, 6, 7, 7) def crear_persona(nombre, *args,**kwargs): print(kwargs) crear_persona(9, nombre="hector", edad=28, pelo="negro") <file_sep># -*- # Bucles # Repeticiones grupo = ['Héctor', 'Foco', 'Carlos', 'Luis', 'Miguel'] # print(grupo[0]) # print(grupo[1]) # print(grupo[2]) # print(grupo[3]) # print(grupo[4]) # print(grupo[5]) # mi_tupla = (1,2) i = 1 # Acumulador for nombre in grupo: print("El alumno en posición %s, se llama: %s" % (i, nombre)) i += 1 # Factorial # n! = n * (n - 1) ... * 1 # 4! = 4 * 3 * 2 * 1 # coleccion_4 = range(1, 5) #. 4! = ( (4 * 3) * 2) * 1 x = 10 acumulador = 1 for n in range(1, x + 1): # [4, 5, 6, 7, 8, 9, 10] acumulador = acumulador * n # 1 * 2 * 3 * 4 * 5 print(acumulador) # Calcular el promedio de una lista edades = [21, 34, 25, 34, 28, 23] # Peromedio = suma de los datos / numero de datos n = 0 for edad in edades: n += edad longitudes = len(edades) print(n/longitudes) <file_sep># -*- coding: utf-8 -*- import time # Fibonacci # f(n) = f(n-1) + f (n-2) # f(0) = 1 # f(1) = 1 # 1, 1, 2, 3, 5, 8, 13, 21 # 0, 1, 2, 3, 4, 5, 6, 7 def fibonacci(n): if n <= 1: return 1 fn_1 = 1 fn_2 = 1 for i in range(2, n + 1): resultado = fn_1 + fn_2 fn_2 = fn_1 fn_1 = resultado # print(resultado) return resultado start_time = time.time() fibonacci(1000000) end_time = time.time() print("Tardó: %s" % (end_time - start_time))<file_sep># -*- coding: utf-8 -*- # Funciones # Conjunto de código que corre bajo demanda def calcular_promedio(datos): suma = 0 for dato in datos: suma += dato promedio = suma / len(datos) return promedio # calcular_promedio([1, 2, 3]) # calcular_promedio([lista_edades) # calcular_promedio([1, 2, 3, 334]) # calcular_promedio([1, 2, 3, 232]) def calcular_iva(precio, tasa_iva=1.16, imprimir=False): subtotal = precio / tasa_iva iva = precio - subtotal if imprimir: print(iva) return iva # print(calcular_iva(100)) # print(calcular_iva(100, 1.25)) calcular_iva(200, 1.20) # calcular_iva(116, True, 1.16) calcular_iva(116, imprimir=True) # *args # **kwargs <file_sep># -*- coding: utf-8 -*- # Números # Enteros (Integer) edad = 28 # eDaD = 28 edad_de_hector = 28 # snake case edadDeHector = 28 # camel case # Flotantes (float) peso = 90.5 pi = 3.141592 # Complejos (Complex) z = 8 + 9j # Operaciones 6 + 7 5 - 7 5 / 7 5 * 8 # módulo 5 % 8 # residuo <file_sep># -*- coding: utf-8 -*- # # # Esto es un comentario # ESto es un Here-doc """ Esto es el heredoc """ mensaje = ''' ESto también es un comentario o heredoc Esto es otra línea ''' # Cadenas de carácteres (strings) nombre = "Héctor" apellido = 'Patricio' # Esta es la preferida nombre_completo = nombre + ' ' + apellido print(nombre_completo) print(len(nombre)) # length # Función print(nombre.upper()) print(nombre.lower()) print(nombre.replace('o', 'X')) # Formateo de cadenas mensaje_de_saludo = 'Hola soy %s, mucho gusto' % nombre print(mensaje_de_saludo) nombre_dado = input("Dime tu nombre: ") # print("tu nombre tiene" + ' ' + len(nombre_dado) + ' ' + 'letras') longitud_nombre = len(nombre_dado) print("Tu nombre tiene: %s letras" % longitud_nombre) print("Tu nombre tiene: %s letras" % len(nombre_dado + apellido)) <file_sep> # -*- coding: utf-8 -*- # Colecciones # Lista grupo_back = ['Cesar', 'Miguel', 'Luis', 'Toño'] len(grupo_back) grupo_back[0] # diccionarios persona = { 'nombre': 'Héctor', 'apellido': 'Patricio', 'edad': 28, 'hobbies': ['leer', 'programar', 'dormir'], 'tiene_mascotas': True } persona['nombre'] print(persona.get('estatura', 1.65)) <file_sep># -*- coding: utf-8 -*- # Condicionales # # condicion = "" otra_condicion = "" mi_varible = 0 if condicion: mi_varible = 1 print("La condición evalúa a verdadero") elif otra_condicion: print("La otra condición se cumple") else: mi_varible = 2 print("La condicion es falsa") # if EXPRESSION: # SENTENCES mi_varible = 1 if condicion else 2 condicion = 1 while condicion < 10: print("Esto esta corriendo") # condicion += 1 <file_sep># PythonBasics Practicas de Python
2d00574e7a7b8fe1d443ef7f0a2c4dd42987c9d4
[ "Markdown", "Python" ]
9
Python
hectorip/PythonBasics
8370c32805c4fa46a3ff620fece81e7bb0bf6757
0e970ef3fe89f23bfdc7fbdf9467082144328f6e
refs/heads/master
<file_sep>package main import ( "encoding/json" "flag" "fmt" "net/http" "strconv" "sync" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/log" ) const ( namespace = "nightscout" // For Prometheus metrics. ) var ( listenAddress = flag.String("telemetry.address", ":9552", "Address on which to expose metrics.") metricsPath = flag.String("telemetry.endpoint", "/metrics", "Path under which to expose metrics.") nightscoutUrl = flag.String("nightscout_endpoint", "https://foo.azurewebsites.net/pebble?count=2&units=mmol", "Nightscout url to jsondata, only mmol is supported") ) // Exporter collects nightscout stats from machine of a specified user and exports them using // the prometheus metrics package. type Exporter struct { mutex sync.RWMutex statusNightscout *prometheus.GaugeVec } type NightscoutPebble struct { Status []struct { Now int64 `json:"now"` } `json:"status"` Bgs []struct { Sgv string `json:"sgv"` Trend int `json:"trend"` Direction string `json:"direction"` Datetime int64 `json:"datetime"` Bgdelta string `json:"bgdelta"` } `json:"bgs"` Cals []interface{} `json:"cals"` } func getJson(url string) NightscoutPebble { //fmt.Println("fetching body from url", url) r, err := http.Get(url) if err != nil { fmt.Println("got error1", err.Error()) } defer r.Body.Close() bar := NightscoutPebble{} err2 := json.NewDecoder(r.Body).Decode(&bar) if err2 != nil { fmt.Println("error:", err2.Error()) } return bar } // NewNightscoutCheckerExporter returns an initialized Exporter. func NewNightscoutCheckerExporter() *Exporter { return &Exporter{ statusNightscout: prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: "nightscout", Name: "nightscout_pebble", Help: "checks current blood sugar from url", }, []string{"glucosetype", "url"}), } } // Describe describes all the metrics ever exported by the nightscout exporter. It // implements prometheus.Collector. func (e *Exporter) Describe(ch chan<- *prometheus.Desc) { e.statusNightscout.Describe(ch) } func (e *Exporter) scrape(ch chan<- prometheus.Metric) error { e.statusNightscout.Reset() data := getJson(*nightscoutUrl) fmt.Println("trying to convert to float:", data.Bgs[0].Sgv) glucose, _ := strconv.ParseFloat(data.Bgs[0].Sgv, 64) e.statusNightscout.With(prometheus.Labels{"glucosetype": "mmol", "url": *nightscoutUrl}).Set(float64(glucose)) return nil } // Collect fetches the stats of a user and delivers them // as Prometheus metrics. It implements prometheus.Collector. func (e *Exporter) Collect(ch chan<- prometheus.Metric) { e.mutex.Lock() // To protect metrics from concurrent collects. defer e.mutex.Unlock() if err := e.scrape(ch); err != nil { log.Printf("Error scraping nightscout url: %s", err) } e.statusNightscout.Collect(ch) return } func main() { flag.Parse() exporter := NewNightscoutCheckerExporter() prometheus.MustRegister(exporter) http.Handle(*metricsPath, prometheus.Handler()) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<html> <head><title>Nightscout exporter</title></head> <body> <h1>nightscout exporter</h1> <p><a href='` + *metricsPath + `'>Metrics</a></p> </body> </html> `)) }) log.Infof("Starting Server: %s", *listenAddress) log.Fatal(http.ListenAndServe(*listenAddress, nil)) }
8cb5464b9f5e2fc8f791695409cb0a26b653a52f
[ "Go" ]
1
Go
dabear/nightscout_exporter
00cd8e7a04fd29ae9e8125a3f35d735c44f701e5
df2f83da9a58a1a3402ddd8121b41879cdbc9b55
refs/heads/master
<repo_name>ldmcdona/Mastermind<file_sep>/mastermind.py import random def unique_string(string): a = len(string) for x in range(a): for i in range(a - x - 1): if string[x] == string[x + i + 1]: return False return True def main(): print("Welcome to Mastermind.") print("Do you know how to play (y/n)?") tutorial = input(">") if tutorial == "n": print("In this game you are trying to find the hidden number combination.\nEvery number in the combination is only used once.\nIf you guess a correct number in the wrong space the 'close' count will go up by one.\nIf you guess a correct number in the correct space the 'match' count will go up one.") clear = True while clear: print("How many digits do you want the combination to be? (Between 2 and 9)") digits = input(">") print("How many guesses do you want to have? (Enter 0 for unlimited)") guesses = input(">") try: digits = int(digits) guesses = int(guesses) if digits >= 2 and digits <= 9: clear = False else: print("The game can only be played with between 2 and 9 digits.") pass except: print("Please answer both questions with a number.") pass if guesses == 0: guesses -= 1 combo = [] for _ in range(digits): while True: x = random.randint(0, 9) if x not in combo: combo.append(x) break win = False print("Hidden combination generated. Good luck!") while guesses != 0: if guesses > 0: print("You have", guesses, "guesses left.") temp = [] match = 0 close = 0 guess = input("Guess >") try: int(guess) valid = True except: valid = False if unique_string(guess) and len(guess) == digits and valid: for x in range(len(guess)): if int(guess[x]) == combo[x]: match += 1 else: temp.append(guess[x]) for x in temp: if int(x) in combo: close += 1 if match == digits: win = True break print("Close:", close, ", Match: ", match) guesses -= 1 else: print("You guess has to be a", digits, "digit number combination using each number only once.") if win: print("Congragulations! You guessed the secret number combination!") else: print("Sorry, you ran out of guesses. Better luck next time!") main()<file_sep>/README.md Just a small project I wanted to do after I discovered this game existed. I learned it's name as 'Mastermind' but I have no idea if that is accurate. In this game you are trying to find the hidden number combination. Every number in the combination is only used once. If you guess a correct number in the wrong space the 'close' count will go up by one. If you guess a correct number in the correct space the 'match' count will go up one. That's basically it. Tried to bug-proof the inputs. Literally just did it in an hour or so. C++ version : https://github.com/ldmcdona/Mastermind-Cplusplus
d2c9c154bc9001d28a5de6d72ba8e71189367a77
[ "Markdown", "Python" ]
2
Python
ldmcdona/Mastermind
2aca28e87c88f49d970a748af7d73cc4a36d127c
eec04c95f9df600ad75d7577b6229fbc997c449f
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 import os import sys import json import random #import GUI features import tkinter import tkinter.messagebox from tkinter import Tk from tkinter.filedialog import * import pandas as pd # Define Constants grades = [ 'A', 'B', 'C', 'D', 'E' ] cutOffs = [ 80, 65, 50, 20, 0 ] teacher = 'foxwell' #Used to find the tasks in the Markbook export assessments = [ 'AT2', 'Exam', 'Overall Mark' ] # Names of the tasks for comment display taskNames = [ 'Maya Modeling', 'Theory Examination' ] # Course Name courseName = "Information & Software Technology" # Define Variables student = [ ['', assessments[0], 0], ['', assessments[1], 0] ] ################## # Setup functions ################## def tkSetup(): """ Setup main python window and screen elements """ ''' BUG TK crashes macintosh mojave causes logout DONOT implement this method unless issue is resolved ''' window = Tk() ################# # Screen elements ################# #screenButton = Button(master = window) window.mainloop() def errorCheck(fileName): ''' Checks the input file for non entered values then either prompts the user select new file or quit program ''' if (fileName == ""): answer = tkinter.messagebox.askyesno('No file selected', 'Do you want to try again?') if answer == True: locateSheet() else: exit() return fileName def locateSheet(title): # Tkinter GUI setup Tk().withdraw() return errorCheck(askopenfilename(title = title)) def setupPandas(inputDir): # Read the csv file into pandas object excelFile = pd.read_excel(inputDir) return excelFile ################## # Student setup ################## def getItemList(dataframe): array = [] for frame in dataframe.iteritems(): if ('Teacher' in frame[0]): array.append(frame[0]) elif ('Family' in frame[0]): array.append(frame[0]) elif ('Given' in frame[0]): array.append(frame[0]) elif (assessments[0] in frame[0]): array.append(frame[0]) elif (assessments[1] in frame[0]): array.append(frame[0]) elif (assessments[2] in frame[0]): array.append(frame[0]) return array def genStudentArray(dataFrame): # Student array [[name],[AT2],[AT3]] student = [] # Iterate through dataframe for row in dataFrame.iterrows(): student.append([row[1][2], row[1][3], row[1][6], row[1][8]]) return student def filterCols(dataframe, itemList, flag): # Remove rows from the excel document if flag: dataframe = dataframe.drop(0) dataframe = dataframe.drop(['Teacher Family', 'Teacher Given'], axis=1) #filter dataframe using list dataframe = dataframe.filter(itemList, axis=1) return dataframe ################## # Generate comments ################## def generateCommentFile(): # Comment sheet file #commentSheet = locateSheet("Select comments Excel sheet") # Desired columns #itemList = ['assessment comment', 'Exam Comment', 'Reccomendations'] #Get Comment file #commentFile = setupPandas(commentSheet) # Filter comment file #commentFile = filterCols(commentFile, itemList, False) # Comment file Json fileName = "Comments.json" # Parse Json File with open(fileName, 'r') as f: commentFile = json.load(f) return commentFile def map(value, low, high, tolow, toHigh): """ Maps input values from specified low - high range to a specified low - high range Parameters: Value (float): input value to be mapped Low (float): low end input range of function high (float): end input range of function toLow (float): low end output range of function toHigh (float): High end output range of function Returns: Map (int): single value mapped between toLow & toHigh """ return int((value - low) * (toHigh - tolow) / (high - low) + tolow) def commentArray(dataFrame, column): array = [] for row in dataFrame.iterrows(): array.append(row[1][column]) return array def createComment(studentList, commentDataFrame): # Variable for storing comment array comment = [] openComment = commentDataFrame['LeadingComment'] assessmentComment = commentDataFrame['Assessment_1'] examComment = commentDataFrame['Assessment_2'] closingComment = commentDataFrame['Closing'] recomend = commentDataFrame['Reccomendation'] #iterate through students and develop for x in range(len(studentList)): # Break down studentList studentName = studentList[x][0] opening = str(random.randint(0, len(openComment) - 1)) ATX = str(map(studentList[x][1], 0, 100, 0, len(assessmentComment) - 1)) ATY = str(map(studentList[x][2], 0, 100, 0, len(examComment) - 1)) closing = str(map(studentList[x][3], 0, 100, 0, len(closingComment) - 1)) finalMark = str(map(studentList[x][3], 0, 100, 0, len(recomend) - 1)) comment.append((openComment[opening].format(studentName, taskNames[0], courseName).strip() + " " + assessmentComment[ATX].format(studentName, taskNames[0], courseName)).strip() + " " + (examComment[ATY].format(studentName, taskNames[1], courseName)).strip() + " " + closingComment[closing].format(studentName, taskNames[0], courseName).strip() + "\n" + (recomend[finalMark].format(studentName, taskNames[0], courseName)).strip() + "\n") return comment ################### # Main function of script ################### def main(): # TODO known issue: TK() crashes macintosh mojave backend # Setup the GUI interface #tkSetup() # Get sheet location sheet = locateSheet("Select Markbook export") # Get data from sheet excelFile = setupPandas(sheet) # Get list of items that are desired from the excel doc itemList = getItemList(excelFile) # Remove unwanted columns excelFile = filterCols(excelFile, itemList, True) # Generate array of student information # Student = [name, exam mark 1, exam mark 2] students = genStudentArray(excelFile) # Generate comment list from Excel file commentFile = generateCommentFile() #print(students) #display(students) comment = createComment(students,commentFile) # Print out to text file fileOut = open("output.txt",'w') fileOut.writelines(comment) fileOut.close() # Print out to console for i in range(len(comment)): print(comment[i]) main () <file_sep># Reports-Generator Python script for generating report comments # Simple report writing system This project is designed to import a marks export from Marksbook Online. It then maps a contained JSON file of comments from which it then generates a simple report comment. These comments only contain the students name and are tailored based on marks. They have recenly been made to include a random leading comment and a performance based tailing comment. Currently the script works only with an export from Marks book online which is set up the TKS, however, with some modificaiton the script could feasably run using any excel export. The CSV file which is exported by the Marks Book online is unsutable to be used by the script. There is a leading cell which pandas cannot rectify, therefore, the sheet has to be saved as an excel export so that it can be used by the script. however, this function needs to be built into the script. # Future - Add GUI support - Further modulularise the system so it can be used to comment on other subjects - Variable word limit support - System to convert CSV -> Excel files or to json to remove dependance on pandas dataframes # Current Features - Integrate the comments system so that external files are not relied upon for simplicity - Modularise the assessment task and marks intake system so they arn't hard coded - MAP assessment marks so they more smoothy align with comment numbers
49bc9358db685b977f8b8006a22b54a43dc1d54a
[ "Markdown", "Python" ]
2
Python
FoxClock/Reports-Generator
2971e640b30d499d8c9c7a0030ea83f45a264531
69862db0718f5467603abed9e08db193302f7f33
refs/heads/main
<file_sep>import { StaggedValue } from './staggedValue' export interface Machine { id: string, name: string, fees: StaggedValue[] } <file_sep>import machines from "../data/machines.json"; import { Machine } from "../model/machine"; export async function getMachines(): Promise<Machine[]> { return new Promise((resolve) => { setTimeout(() => { resolve(machines); }, 2000); }); } <file_sep># MetalHeaven frontend challenge are you an awesome front end developer? **we're looking for you!** ### complete our challenge and became part of our team! ## what is MetalHeaven/Rhodium24? MetalHeaven is a young Dutch startup aiming at the sheet metal market. We're building a full sales platform (Rhodium24) for that market, including a top-grade feature recognition engine and a customizable portal for those factories' clients to follow their orders. Rhodium24 is fully customizable for each factory's needs, so each quotation will be calculated with a set of parameters like the cost price and the fees applied to the factory's machines. And this is the background for our challenge. ## the problem</h4> We need to define a fee for each machine. The fee is based on the amount of usage of that resource - from 0min to 10min: 20% - from 10min to 40min: 30% - above 40min: 10% ## the requirements - should be fun to use! (be creative) - should show the list of machines returned by ```javascript import { getMachines } from "./services/machine-services"; await getMachines(); ``` - user should be able to add a new "level" and assign a "value" to it - user should be able to change the "level" value - user should be able to change the "level" unit of measure with one of the "abbrs" in level.abbrs - user should be able to change the "value" value - user should be able to save the changes (for this sample, just `console.log`) ## codesandbox you can use this [codesandbox](https://codesandbox.io/s/reverent-chatelet-8wc5f?file=/src/app.tsx) as start point ## bonus points - how easy is to use the control or update the form? (do I hear auto save?) - automated tests - a reusable NPM Package with that control ## the prize - your code will be reviewed by the MetalHeaven team (continuous feedback about our coding is always good, right?) - be part of a fresh company and be involved directly with the product creation/evolution - full remote work (English is not a hard requirement, be bold Portuguese speaker fellows!) - **competitive salary offer** (we're looking for a full time team member, no freelas!) <file_sep>export interface Quantity { value: number, unit: string, abbrs?: string[] }<file_sep>import { Quantity } from './quantity'; export interface StaggedValue { level: Quantity value: Quantity }
c7018fd520e2ac01a698587dde4ab093a4208b13
[ "Markdown", "TypeScript" ]
5
TypeScript
GersonDias/rh24-front-end-challenge
8568b32a5756a11a8a06f6a699b8200000b1c423
5f268d20299608f40cc648c87d833762aca5f57b
refs/heads/master
<repo_name>hsaleem2/log-parser<file_sep>/Dockerfile FROM openjdk:14-jdk-alpine COPY build/libs/log.parser-all-1.0-SNAPSHOT.jar /app.jar COPY resources /resources CMD ["java", "-jar", "-Dspring.profiles.active=default", "/app.jar"]<file_sep>/src/test/java/LogParserTest.java import org.junit.Test; public class LogParserTest { @Test public void readLogsTest() { LogParser lpTester = new LogParser(); } @Test public void parseLogsTest() { LogParser lpTester = new LogParser(); } @Test public void countLogsTest() { LogParser lpTester = new LogParser(); } @Test public void writeLogsTest() { LogParser lpTester = new LogParser(); } } <file_sep>/README.md # log-parser Source code files are located under ```src/main/java```. Instructions, sample log file, and output file is located under ```src/main/resources```. To run the program, you can clone this project and build the docker image: ``` docker build -t log-parser:latest . ``` And then run the docker image: ``` docker run --name log-parser -v resources:/resources log-parser:latest ``` The program works by taking a command line argument (which is the name of the log file) and writing the parsed output to "output_logs.txt". If no command line argument is passed, the log file name defaults to "localhost_access_log.2016-08-04", which is the name of the sample log file provided. The output format is displayed as ```ip request uri count```, so an example for one of the logs would be: ``` 127.0.0.1 GET /myapi/endpoint1/{guid}/quiz-status 4 ```
8f313e527053d2258ebf935340b10cba6a6574a0
[ "Markdown", "Java", "Dockerfile" ]
3
Dockerfile
hsaleem2/log-parser
a9583f350cf0ccb16270641813a46465b111e72f
84d58bdf2773eb95e867a06898402b5e1d6bf6c0
refs/heads/master
<repo_name>jb-tester/feign-rest-api-test1<file_sep>/src/main/java/com/mytests/spring/api/restapitest1/controllers/MyController1.java package com.mytests.spring.api.restapitest1.controllers; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/simple") public class MyController1 { @GetMapping("/") public String getHome(){ return "this is the simple test"; } @GetMapping("/{g_name}") public String getHello(@PathVariable String g_name){ return "hello "+ g_name; } } <file_sep>/src/main/resources/application.properties spring.mvc.servlet.path=/rest-api-test1 server.port=8081 spring.datasource.url=jdbc:mysql://localhost:3306/jbtests?serverTimezone=UTC spring.datasource.username=irina spring.datasource.password=<PASSWORD> spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
66b5755e214aad52c833bc6ae082fb42fb008a72
[ "Java", "INI" ]
2
Java
jb-tester/feign-rest-api-test1
878739f3b5c7746bbb2f411a4f8de54edf1558b8
86f6a8b5b2377643d7b3b92e9aacb11ae3614865
refs/heads/master
<repo_name>Vinaysai/Spring-Login-Boot-Service<file_sep>/README.md # Spring-Login-Boot-Service This a micro Service for https://github.com/Vinaysai/Spring-Boot-Login. ![screenshot 15](https://user-images.githubusercontent.com/15280792/43722449-ea173a1a-99b2-11e8-96f0-306f30413677.png) ![screenshot 17](https://user-images.githubusercontent.com/15280792/43723526-7cc6fc86-99b5-11e8-95dc-9c513ac82c0a.png) <file_sep>/src/main/java/com/spring/boot/all/bean/Answers.java package com.spring.boot.all.bean; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "answers") public class Answers { @Id @Column(name = "aid") private int aid; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "qid") private User qid; @Column(name = "answers") private String answers; public int getAid() { return aid; } public void setAid(int aid) { this.aid = aid; } public User getQid() { return qid; } public void setQid(User qid) { this.qid = qid; } @Override public String toString() { return "Answers [aid=" + aid + ", qid=" + qid + ", answers=" + answers + "]"; } public String getAnswers() { return answers; } public void setAnswers(String answers) { this.answers = answers; } } <file_sep>/src/main/java/com/spring/boot/all/bean/Questions.java package com.spring.boot.all.bean; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "questions") public class Questions { @Id @Column(name = "id") private int id; @Column(name = "questions") private String questions; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "qid") private User qid; public int getId() { return id; } public User getQid() { return qid; } public String getQuestions() { return questions; } public void setId(int id) { this.id = id; } public void setQid(User qid) { this.qid = qid; } public void setQuestions(String questions) { this.questions = questions; } @Override public String toString() { return "Questions [id=" + id + ", questions=" + questions + ", qid=" + qid + "]"; } }<file_sep>/src/main/java/com/spring/boot/all/bean/AnsQue.java package com.spring.boot.all.bean; public class AnsQue { private int id; private String username; private String passwod; private String questions; private String answers; public String getAnswers() { return answers; } public int getId() { return id; } public String getPasswod() { return passwod; } public String getQuestions() { return questions; } public String getUsername() { return username; } public void setAnswers(String answers) { this.answers = answers; } public void setId(int id) { this.id = id; } public void setPasswod(String passwod) { this.passwod = passwod; } public void setQuestions(String questions) { this.questions = questions; } public void setUsername(String username) { this.username = username; } @Override public String toString() { return "AnsQue [id=" + id + ", username=" + username + ", passwod=" + passwod + ", questions=" + questions + ", answers=" + answers + "]"; } } <file_sep>/src/main/java/com/spring/boot/all/repository/Repositoryclass.java package com.spring.boot.all.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.spring.boot.all.bean.User; @Repository public interface Repositoryclass extends JpaRepository<User, String> { //JPA Query DSL(or) JPQL.... @Query("SELECT t FROM User t where t.username = ?1 AND t.password = ?2") List<User> findByUsernameAndPassword(String username, String password); }
c89881b64c2544247052bcc29edfd0d5cc401d2e
[ "Markdown", "Java" ]
5
Markdown
Vinaysai/Spring-Login-Boot-Service
a65fcf5ecb8a859c0c0831e4c0d2a6262a450585
7f55f59f54afbb3bf5098ea48563bd22a6019c9b
refs/heads/main
<file_sep>var database var gameState = 0; var playerCount = 0; var form, player, game; var allPlayers; var distance = 0; function setup(){ createCanvas(400,400); database = firebase.database(); console.log(database); game = new Game(); game.getState(); game.start(); // ref() : location for read and write eg: car position // set() : write to the database - update to dB // on() : read from the database - get data from dB } function draw(){ background("white"); if(playerCount === 4){ game.update(1); } if(gameState === 1){ clear(); game.play(); } }
97bea518edbd9c339cd693c57d16a3853822daec
[ "JavaScript" ]
1
JavaScript
anikethgr/c-37
d1dde1b7e4449849d5a471dbb4decec8e5094ff4
b6cbb1abde68ebe3808aa7e6832e9f277ba9fe79
refs/heads/master
<repo_name>woss/react-native-audio-4expo<file_sep>/index.js // import 'expo'; import AudioRecorder from './AudioRecorder'; import AudioPlayer from './AudioPlayer'; module.exports = { AudioPlayer, AudioRecorder };<file_sep>/AudioPlayer.js import React, { Component } from 'react'; import { TouchableOpacity, View, ActivityIndicator, Alert, Slider } from 'react-native'; import { Text } from 'native-base'; import { Audio } from 'expo'; import PropTypes from 'prop-types'; import * as styles from './styles'; // the amount of time fast forward or rewind moves within the audio clip const SOUND_JUMP_MILLIS = 5000; const formattedSeconds = (millis) => { const totalSeconds = millis / 1000; const seconds = Math.floor(totalSeconds % 60); const minutes = Math.floor(totalSeconds / 60); const padWithZero = (number) => { const string = number.toString(); if (number < 10) { return '0' + string; } return string; }; return padWithZero(minutes) + ':' + padWithZero(seconds); }; export default class AudioPlayer extends Component { constructor(props) { super(props); this.recording = null; this.state = { error: null, secondsElapsed: 0, audioInfo: {}, debugStatements: 'debug info will appear here', isAudioReady: false }; this.sound = null; } componentDidMount = async () => { console.log('mounting player'); console.log({ 'this.props: ': this.props }); if (this.props.source.uri) { this.loadSound(); } }; componentDidUpdate = (prevProps, prevState) => { if (this.props.source !== prevProps.source) { this.loadSound(); } }; componentWillUnmount = () => { if (this.sound) { this.sound.setOnPlaybackStatusUpdate(null); } }; loadSound = async () => { this.sound = new Audio.Sound(); try { this.sound.setOnPlaybackStatusUpdate( this.onPlaybackStatusUpdate.bind(this) ); let playbackSoundInfo = await this.sound.loadAsync({ uri: this.props.source.uri }); console.log({ playbackSoundInfo }); this.setState({ isAudioReady: true, playbackSoundInfo }); } catch (error) { this.props.onError && this.props.onError({ 'onPlayPress loadAsync error': error }); } }; /* Function used to update the UI during playback */ onPlaybackStatusUpdate = (playbackStatus) => { let that = this; this.props.debug && console.log({ playbackStatus }); this.setState({ prevPlaybackStatus: that.state.playbackStatus, playbackStatus: playbackStatus }); if (playbackStatus.error) { this.setState({ playBackStatus: 'ERROR' }); this.props.onError && this.props.onError( `Encountered a fatal error during playback: ${playbackStatus.error} Please report this error as an issue. Thank you!` ); } if (playbackStatus.isLoaded) { // don't care about buffering if state.playStatus is equal to one of the other states // state.playStatus can only be equal to one of the other states after buffer // has completed, at which point state.playStatus is set to 'STOPPED' if ( this.state.playStatus !== 'PLAYING' && this.state.playStatus !== 'PAUSED' && this.state.playStatus !== 'STOPPED' && this.state.playStatus !== 'ERROR' ) { if (playbackStatus.isLoaded && !this.state.isLoaded) { this.setState({ isLoaded: true }); } if (this.state.isLoaded && playbackStatus.isBuffering) { this.setState({ isBuffering: true }); } if ( this.state.isLoaded && !playbackStatus.isBuffering && playbackStatus.hasOwnProperty('durationMillis') ) { this.setState({ isPlaying: false, isStopped: true, isPaused: false }); } } // Update the UI for the loaded state if (playbackStatus.isPlaying) { // Update UI for the playing state this.setState({ isPlaying: true, isStopped: false, isPaused: false, positionMillis: playbackStatus.positionMillis, currentSliderValue: playbackStatus.positionMillis }); } if (playbackStatus.didJustFinish && !playbackStatus.isLooping) { this.setState({ playStatus: 'STOPPED', isPlaying: false, isStopped: true, isPaused: false, positionMillis: playbackStatus.durationMillis, currentSliderValue: playbackStatus.durationMillis }); } } }; // perform this action when the user presses the "done" key onComplete = async () => { // need to check if sound has been set to null in case the user // has recorded something, then did a reset, and then clicks the finish button if (this.sound !== null) { try { await this.sound.unloadAsync().then(() => { this.props.onComplete(this.state.soundFileInfo); }); } catch (error) { this.props.onError && this.props.onError({ 'Error: unloadAsync': error }); } // clear the status update object if the sound hasn't already been set to null if (this.sound.hasOwnProperty('setOnPlaybackStatusUpdate')) { this.sound.setOnPlaybackStatusUpdate(null); } this.sound = null; } else { // only get here if the user has never tried to click record or // did a reset this.props.onComplete(this.state.soundFileInfo); } }; onPlaybackSliderValueChange = (value) => { // set the postion of the actual sound object this.sound.setPositionAsync(value); }; onPlayPress = async () => { this.playAudio(); }; playAudio = async () => { try { if (this.state.isPaused) { let playFromPositionAsyncRes = await this.sound.playFromPositionAsync( this.state.pausedPosition ); this.props.debug && console.log({ playFromPositionAsyncRes }); } else { let playAsyncRes = await this.sound.playAsync(); this.props.debug && console.log(playAsyncRes); ({ playAsyncRes }); } this.setState({ isPlaying: true, isPaused: false }); } catch (error) { this.props.onError && this.props.onError({ 'onPlayPress playAsync error': error }); } }; onPausePress = async () => { try { let pauseAsyncRes = await this.sound.pauseAsync(); this.setState({ isPlaying: false, isPaused: true, pausedPosition: pauseAsyncRes.positionMillis }); console.log({ pauseAsyncRes }); } catch (error) { console.warn(`pauseAsync error : ${error}`); } }; onResetPlaybackPress = async () => { let replayAsyncRes = await this.sound.replayAsync(); this.props.onError && this.props.onError({ replayAsyncRes }); }; onFastForwardPressed = async () => { try { this.props.debug && console.log('in onFastForwardPressed'); let status = await this.sound.getStatusAsync(); this.props.debug && console.log({ status }); let res = await this.sound.setPositionAsync( Math.min( status.positionMillis + SOUND_JUMP_MILLIS, status.playableDurationMillis ) ); this.props.debug && console.log(res); } catch (error) { this.props.debug && console.log({ error }); } }; onRewindPressed = async () => { this.props.debug && console.log('in onRewindPressed'); try { let status = await this.sound.getStatusAsync(); this.props.debug && console.log({ status }); let res = await this.sound.setPositionAsync( Math.max(status.positionMillis - SOUND_JUMP_MILLIS, 0) ); this.props.debug && console.log(res); } catch (error) { this.props.debug && console.log({ error }); } }; renderPlaybackTimer = () => { return this.props.playbackTimer({ currentValue: formattedSeconds( this.state.playbackStatus.positionMillis || 0 ), duration: formattedSeconds(this.state.playbackStatus.durationMillis || 0), isPlaying: this.state.isPlaying, isPaused: this.state.isPaused }); }; renderTopControls = () => { return ( <View style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: 15, display: 'flex', justifyContent: 'center', alignItems: 'center' }} > {this.props.resetButton({ onPress: this.onResetPlaybackPress, isPlaying: this.state.isPlaying })} </View> ); }; haltPlaybackForSliderValueChange = async () => { try { if (!this.state.tempDurationMillis) { this.setState({ tempDurationMillis: this.state.playbackStatus.durationMillis }); } let pauseAsyncRes = await this.videoRef.pauseAsync(); this.props.onError && this.props.onError({ pauseAsyncRes }); } catch (error) { this.props.onError && this.props.onError({ error }); } }; changePlaybackLocation = async (value) => { this.props.onError && this.props.onError({ value }); this.props.onError && console.log({ tempDurationMillis: this.state.tempDurationMillis }); try { let setStatusAsyncRes = await this.videoRef.setStatusAsync({ positionMillis: value, durationMillis: this.state.tempDurationMillis }); this.props.onError && this.props.onError({ setStatusAsyncRes }); this.props.onError && this.props.onError(this.state); let playAsyncRes = await this.videoRef.playAsync(); this.props.onError && this.props.onError({ playAsyncRes }); this.setState({ tempDurationMillis: null }); } catch (error) { this.props.onError && this.props.onError({ error }); } }; renderPlaybackSlider = () => { return ( <View style={{ width: '100%' }}> {this.props.playbackSlider({ minimumValue: 0, maximumValue: this.state.playbackStatus.durationMillis, value: this.state.playbackStatus.positionMillis, onSlidingComplete: this.changePlaybackLocation, onValueChange: this.haltPlaybackForSliderValueChange })} </View> ); }; renderMiddleControls = () => { if (this.state.playbackStatus) { return ( <View style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center' }} > {this.props.showPlaybackTimer ? this.renderPlaybackTimer() : null} {this.props.showPlaybackSlider ? this.renderPlaybackSlider() : null} </View> ); } else { return null; } }; renderBottomControls = () => { return ( <View style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: 5 }} > <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-evenly' }} > {this.props.rewindButton({ onPress: this.onRewindPressed, isAudioReady: this.state.isAudioReady })} {this.state.isAudioReady && !this.state.isPlaying ? this.props.playButton({ onPress: this.onPlayPress, isAudioReady: this.state.isAudioReady }) : null} {this.state.isPlaying ? this.props.pauseButton({ onPress: this.onPausePress }) : null} {this.props.fastForwardButton({ onPress: this.onFastForwardPressed, isAudioReady: this.state.isAudioReady })} </View> {this.props.showCloseButton ? this.props.closeAudioPlayerButton({ onPress: () => {}, audioInfo: this.state.audioInfo }) : null} </View> ); }; render() { return ( <View style={{ flex: 1 }}> {this.state.isAudioReady ? ( <> {this.renderTopControls()} {this.renderMiddleControls()} {this.renderBottomControls()} </> ) : ( <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} > {this.props.activityIndicator()} </View> )} </View> ); } } AudioPlayer.propTypes = { // spinner shown until the the camera is available activityIndicator: PropTypes.func, // onError: callback that is passed an error object onError: PropTypes.func, // UI elements playButton: PropTypes.func, pauseButton: PropTypes.func, resetButton: PropTypes.func, closeAudioPlayerButton: PropTypes.func.isRequired, // showTimer: show a timer while playing showPlaybackTimer: PropTypes.bool, // showPlaybackSlider: show a slider while playing showPlaybackSlider: PropTypes.bool, // timer: function returning component to render as timeStamp playbackTimer: PropTypes.func, // slider: function returning component to render as playback slider playbackSlider: PropTypes.func, debug: PropTypes.bool }; AudioPlayer.defaultProps = { source: { uri: 'https://s3.amazonaws.com/exp-us-standard/audio/playlist-example/Comfort_Fit_-_03_-_Sorry.mp3' }, activityIndicator: () => { return <ActivityIndicator size="large" color="#0000ff" />; }, onError: (error) => { console.log({ error }); }, playButton: ({ onPress }) => { return ( <TouchableOpacity style={styles.defaultTouchableHighlight} onPress={onPress} underlayColor="#E0E0E0" > <Text style={styles.defaultText}>Play</Text> </TouchableOpacity> ); }, pauseButton: ({ onPress }) => { return ( <TouchableOpacity style={styles.defaultTouchableHighlight} onPress={onPress} underlayColor="#E0E0E0" > <Text style={styles.defaultText}>Pause</Text> </TouchableOpacity> ); }, fastForwardButton: (renderProps) => { return ( <TouchableOpacity style={styles.defaultTouchableHighlight} onPress={renderProps.onPress} underlayColor="#E0E0E0" > <Text style={{ fontSize: 24, fontWeight: 'bold' }}>{'>>'}</Text> </TouchableOpacity> ); }, rewindButton: (renderProps) => { return ( <TouchableOpacity style={styles.defaultTouchableHighlight} onPress={renderProps.onPress} underlayColor="#E0E0E0" > <Text style={{ fontSize: 24, fontWeight: 'bold' }}>{'<<'}</Text> </TouchableOpacity> ); }, resetButton: ({ onPress, isPlaying, isRecording }) => { return ( <TouchableOpacity style={styles.defaultTouchableHighlight} onPress={onPress} underlayColor="#E0E0E0" > <Text style={{ ...styles.defaultText, color: isPlaying || isRecording ? 'gray' : 'black' }} > Reset </Text> </TouchableOpacity> ); }, showCloseButton: true, closeAudioPlayerButton: ({ onPress }) => { return ( <TouchableOpacity style={styles.defaultTouchableHighlight} onPress={onPress} underlayColor="#E0E0E0" > <Text style={styles.defaultText}>Go Back</Text> </TouchableOpacity> ); }, showPlaybackTimer: true, playbackTimer: ({ currentValue, duration }) => { return ( <View style={{ background: 'rgba(0,0,0,.5' }}> <Text style={{ fontSize: 42, color: 'white' }}> {`${currentValue} / ${duration}`} </Text> </View> ); }, showPlaybackSlider: true, playbackSlider: (renderProps) => { return ( <Slider minimumValue={renderProps.minimumValue} maximumValue={renderProps.maximumValue} value={renderProps.value} onSlidingComplete={renderProps.onSlidingComplete} onValueChange={renderProps.onValueChange} disabled={renderProps.disabled} /> ); }, debug: false }; <file_sep>/RecordAudioScreen.js import React from 'react'; import { Text, Button, Container } from 'native-base'; import { withNavigation } from 'react-navigation'; import { AudioRecorder } from './index'; import { Audio } from 'expo'; const random_rgba = () => { var o = Math.round, r = Math.random, s = 255; return ( 'rgba(' + o(r() * s) + ',' + o(r() * s) + ',' + o(r() * s) + ',' + r().toFixed(1) + ')' ); }; const BACKGROUND_COLOR = random_rgba(); class RecordAudioScreen extends React.Component { constructor(props) { super(props); this.state = {}; } permissionsRetrievedCallback = (permissionsRetrievedCallbackRes) => { console.log({ permissionsRetrievedCallbackRes }); }; doNotTryAgainCallback = () => { console.log('Permissions denied'); }; onAudioRecorderError = (error) => { console.log({ error }); }; onRecordingCompleteCallback = () => { console.log('onRecordingCompleteCallback called'); }; onStartRecording = () => { console.log('onStartRecording'); }; onStopRecording = () => { console.log('onStopRecording'); }; onCloseAudioRecorder = (audioInfo) => { console.log({audioInfo}); this.props.navigation.navigate('HomeScreen', { audioInfo }); }; render() { return ( <Container style={{ backgroundColor: `${BACKGROUND_COLOR}` }} > <AudioRecorder permissionsRetrievedCallback={this.permissionsRetrievedCallback} doNotTryAgainCallback={this.doNotTryAgainCallback} onError={this.onAudioRecorderError} getAudioCallback={this.getAudioCallback} recordingOptions={{ quality: Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY }} denyPermissionRequestCallback={() => { console.log('request for permissions denied'); this.props.navigation.goBack(); }} showRecorderTimer={true} showPlaybackTimer={true} debug={false} /* permissionsAlert={{ display: true, title: 'Permissions Required', message: 'Camera permissions are required to add images to location.', tryAgainText: 'Try Again', doNotTryAgainText: 'OK' }} */ /* activityIndicator={() => { return <ActivityIndicator size="large" color="#00ff00" />; }} */ /* startRecordingButton={(renderProps) => { return ( <Button onPress={() => { renderProps.onPress(); this.onStartRecording(); }} danger style={{ ...styles.bigButtonStyle, backgroundColor: 'red', borderWidth: 6, borderColor: 'lightgray' }} /> ); }} */ /* stopRecordingButton={(renderProps) => { return ( <Button onPress={() => { renderProps.onPress(); this.onStopRecording(); }} style={{ ...styles.bigButtonStyle, border: 3, backgroundColor: 'lightgray', borderColor: 'white' }} /> ); }} */ closeAudioRecorderButton={(renderProps) => { return ( <Button onPress={() => { renderProps.onPress(); this.onCloseAudioRecorder(renderProps.audioInfo); }} disabled={renderProps.isRecording} block info={ !renderProps.isRecording && !renderProps.isRecordingAvailable } success={ !renderProps.isRecording && renderProps.isRecordingAvailable } style={{ margin: 5 }} > <Text > {renderProps.isRecordingAvailable ? 'Save Recording' : 'Go Back'} </Text> </Button> ); }}/* playButton={(renderProps) => { return ( <Button onPress={renderProps.onPress} success style={styles.bigButtonStyle} > <Icon type="FontAwesome" name="play" color="white" style={{ fontSize: ICON_SIZE }} /> </Button> ); }} timerComponent={(renderProps) => { return ( <View style={{ background: 'rgba(0,0,0,.5' }}> <Text style={{ color: 'white', fontSize: 20 }}> {renderProps.value} </Text> </View> ); }}*/ /> </Container> ); } } export default withNavigation(RecordAudioScreen); <file_sep>/jest.config.js module.exports = { preset: 'jest-expo', transform: { '\\.js$': '<rootDir>/node_modules/react-native/jest/preprocessor.js' }, transformIgnorePatterns: [ 'node_modules/(?!native-base-shoutem-theme|native-base|react-native-easy-grid|react-native|react-navigation|expo|@expo/vector-icons)' ] };
4e56e2e6210048e44e3f971bf72a4f3ef02db546
[ "JavaScript" ]
4
JavaScript
woss/react-native-audio-4expo
0416f57a576d98abe59ae4da1275cd771ff99fb7
760b4e4c54948ef842776916d95e4518e77acfb8
refs/heads/master
<repo_name>UddeshJain/Quick-Notes<file_sep>/src/pages/updateNote.js import React from 'react'; import UpdateNote from '../containers/notes/updateNote'; const UpdateANote = () => { return <UpdateNote />; }; export default UpdateANote; <file_sep>/src/components/home/search.js import React, { useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import MicIcon from '@material-ui/icons/Mic'; import SearchIcon from '@material-ui/icons/Search'; import ClearIcon from '@material-ui/icons/Clear'; import useAutocomplete from '@material-ui/lab/useAutocomplete'; import Button from '@material-ui/core/Button'; import CloseIcon from '@material-ui/icons/Close'; import './search.css'; const useStyles = makeStyles((theme) => ({ label: { display: 'block', }, listbox: { width: 200, margin: 0, padding: 0, zIndex: 1, position: 'absolute', listStyle: 'none', marginTop: '50px', backgroundColor: theme.palette.background.paper, overflow: 'auto', maxHeight: 200, border: '1px solid rgba(0,0,0,.25)', borderRadius: '5px', '& li[data-focus="true"]': { backgroundColor: 'rgba(0, 0, 0, 0.04)', color: 'rgba(0, 0, 0, 0.87)', cursor: 'pointer', }, '& li': { padding: '10px', }, '& li:active': { backgroundColor: 'rgba(0, 0, 0, 0.04)', color: 'rgba(0, 0, 0, 0.87)', }, '& div': { display: 'flex', justifyContent: 'flex-end', }, '& svg': { cursor: 'pointer', }, }, margin: { margin: theme.spacing(1), minWidth: 0, }, })); const SearchBar = ({ notes, searchText, handleSearch, handleOptionClick, titles, isListening, handleSpeech, isSpeechSupported, closeRecognitionError, }) => { const { getRootProps, getInputProps, getListboxProps, getOptionProps, groupedOptions, focused, } = useAutocomplete({ id: 'use-autocomplete-demo', options: notes, getOptionLabel: (option) => option.data.title, }); const classes = useStyles(); const [inputRef, setRef] = useState(null); const [showSuggestions, setShowSuggestions] = useState(true); React.useEffect(() => { if (focused) { let list = document.querySelector('.searchBox'); setRef(list); } }, [focused]); return ( <> <div className="searchContainer" {...getRootProps()}> <SearchIcon className="searchIcon" /> <input className="searchBox" type="search" name="search" placeholder="Search..." {...getInputProps()} value={searchText} onChange={handleSearch} /> <div id="speech"> <MicIcon className="MicIcon" onClick={handleSpeech} /> <div className={isListening ? 'pulse-ring' : null}></div> </div> {showSuggestions && groupedOptions.length && titles.length ? ( <ul className={classes.listbox} {...getListboxProps()} id="listContainer" > <div onClick={() => setShowSuggestions(false)}> <ClearIcon /> </div> {titles.map((option, index) => ( <li {...getOptionProps({ option, index })} onClick={() => { handleOptionClick(option.data.title); inputRef.blur(); }} > {option.data.title} </li> ))} </ul> ) : null} </div> {!isSpeechSupported ? ( <div className="errContainer"> <p className="msg"> Sorry, speech recognition is not supported in your browser :( </p> <Button variant="outlined" size="small" color="primary" className={classes.margin} onClick={closeRecognitionError} > <CloseIcon /> </Button> </div> ) : null} </> ); }; export default SearchBar; <file_sep>/src/containers/home/index.js import React, { useState, useEffect } from 'react'; import HomeComponent from '../../components/home'; import firebase, { firestore, auth } from '../../firebase'; import Spinner from '../../reusable-components/spinner'; import SearchBar from '../../components/home/search'; const HomeContainer = () => { let SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; const [data, setData] = useState({}); const [combinedData, setCombinedData] = useState([]); const [loading, setLoading] = useState(false); const [searchText, setSearchText] = useState(''); const [searchResults, setSearchResults] = useState([]); const [titles, setTitles] = useState([]); const [isListening, setIsListening] = useState(false); const [isSpeechSupported, setIsSpeechSupported] = useState(true); let recognition = SpeechRecognition ? new SpeechRecognition() : null; if (recognition) { recognition.continuous = true; recognition.interimResults = true; recognition.onspeechend = function () { recognition.stop(); setIsListening(false); }; recognition.onresult = function (event) { var text = event.results[0][0].transcript; setSearchText(text.toLowerCase()); }; } useEffect(() => { setLoading(true); let user = auth.currentUser; if (user) { let normalItems = []; let pinnedItems = []; firestore .collection('notes') .where('userId', '==', user.uid) .get() .then((snapshot) => { snapshot.forEach((doc) => { if (doc.data().pinned) { pinnedItems.push({ id: doc.id, data: doc.data() }); } else { normalItems.push({ id: doc.id, data: doc.data() }); } }); normalItems.sort((a, b) => b.data.timestamp - a.data.timestamp); pinnedItems.sort((a, b) => b.data.timestamp - a.data.timestamp); let fullData = [...normalItems, ...pinnedItems]; setTitles(fullData); setCombinedData(fullData); setData({ pinnedItems, normalItems }); setLoading(false); }); } }, []); const onDelete = (id, pinned) => { setLoading(true); firestore .collection('notes') .doc(id) .delete() .then(() => setLoading(false)) .catch((err) => console.log(err)); if (pinned) { setData({ ...data, pinnedItems: data.pinnedItems.filter((obj) => obj.id !== id), }); } else { setData({ ...data, normalItems: data.normalItems.filter((obj) => obj.id !== id), }); } setLoading(false); }; const handlePin = async (id, bool) => { setLoading(true); try { await firestore .collection('notes') .doc(id) .update({ pinned: bool ? firebase.firestore.FieldValue.delete() : true, timestamp: Date.now(), }); if (bool) { let item = data.pinnedItems.find((ele) => ele.id === id); item.pinned = !bool; let arr = data.pinnedItems.filter((ele) => ele.id !== id); setData({ normalItems: [item, ...data.normalItems], pinnedItems: arr, }); } else { let item = data.normalItems.find((ele) => ele.id === id); item.pinned = !bool; let arr = data.normalItems.filter((ele) => ele.id !== id); setData({ normalItems: arr, pinnedItems: [item, ...data.pinnedItems], }); } setLoading(false); } catch (error) { console.log(error); } }; const handleSearch = (e) => { setSearchText(e.target.value); let objs = combinedData.filter((obj) => obj.data.title.toLowerCase().includes(e.target.value.toLowerCase()) ); setTitles(objs); }; const handleOptionClick = (text) => { setSearchText(text); }; const handleSpeech = () => { if (!recognition) { setIsSpeechSupported(false); return; } recognition.start(); setIsListening(true); }; const closeRecognitionError = () => { setIsSpeechSupported(true); }; useEffect(() => { if (searchText) { const res = combinedData.filter((obj) => { var currentNode, ni = document.createNodeIterator( new DOMParser().parseFromString(obj.data.description, 'text/html') .documentElement, NodeFilter.SHOW_ELEMENT ); let text = ''; while ((currentNode = ni.nextNode())) { text += currentNode.textContent; } return ( text .toLowerCase() .replace(/\s/g, '') .includes(searchText.toLowerCase().replace(/\s/g, '')) || obj.data.title .toLowerCase() .replace(/\s/g, '') .includes(searchText.toLowerCase().replace(/\s/g, '')) ); }); setSearchResults(res); } }, [combinedData, searchText]); return ( <> {loading ? ( <Spinner /> ) : ( <HomeComponent show={!searchText ? true : false} onDelete={onDelete} data={data} handlePin={handlePin} searchResults={searchResults} > <SearchBar handleSearch={handleSearch} searchText={searchText} handleOptionClick={handleOptionClick} notes={combinedData} titles={titles} isSpeechSupported={isSpeechSupported} isListening={isListening} handleSpeech={handleSpeech} closeRecognitionError={closeRecognitionError} /> </HomeComponent> )} </> ); }; export default HomeContainer; <file_sep>/src/containers/notes/updateNote.js import React, { useState } from 'react'; import UpdateNoteComponent from '../../components/notes/updateNote'; import { firestore } from '../../firebase'; import { useLocation, useParams, useHistory } from 'react-router-dom'; const UpdateNote = () => { const { id } = useParams(); const history = useHistory(); const location = useLocation(); const [text, setText] = useState(location.state.content); const [headingText, setHeadingText] = useState(location.state.title); const handleQuillChange = (value) => { setText(value); }; const handleHeadingChange = (e) => { setHeadingText(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); firestore .collection('notes') .doc(id) .update({ title: headingText, description: text, timestamp: Date.now(), }) .then(() => { history.push('/'); }) .catch((err) => console.log(err)); }; return ( <UpdateNoteComponent text={text} handleQuillChange={handleQuillChange} headingText={headingText} handleHeadingChange={handleHeadingChange} handleSubmit={handleSubmit} /> ); }; export default UpdateNote; <file_sep>/src/pages/signin.js import React from 'react'; import SignInContainer from '../containers/signin'; const SignIn = () => { return <SignInContainer />; }; export default SignIn; <file_sep>/src/containers/signin/index.js import React, { useState, useCallback } from 'react'; import SignInComponent from '../../components/signin'; import { withRouter } from 'react-router-dom'; import firebase, { auth } from '../../firebase'; const SignInContainer = ({ history }) => { const [values, setValues] = useState({ email: '', password: '', }); const handleChange = (name) => (e) => { setValues({ ...values, [name]: e.target.value }); }; const handleSignIn = (e) => { e.preventDefault(); auth.signInWithEmailAndPassword(values.email, values.password).then(() => { history.push('/'); }); }; const handleGoogleSignIn = useCallback(() => { var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithRedirect(provider); history.push('/'); }, [history]); return ( <SignInComponent handleChange={handleChange} handleSignIn={handleSignIn} handleGoogleSignIn={handleGoogleSignIn} /> ); }; export default withRouter(SignInContainer); <file_sep>/src/components/navbar/index.js import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import Button from '@material-ui/core/Button'; import { Link } from 'react-router-dom'; import SvgIcon from '@material-ui/core/SvgIcon'; const useStyles = makeStyles((theme) => ({ link: { color: 'inherit', }, flexToolbar: { display: 'flex', justifyContent: 'space-between', }, })); const NavBarComponent = ({ isLoggedIn, handleSignOut }) => { const classes = useStyles(); return ( <div className={classes.root}> <AppBar position="static"> <Toolbar className={classes.flexToolbar}> <Typography variant="h6"> <Link className={classes.link} color="inherit" to="/"> QuickNotes </Link> </Typography> {isLoggedIn && ( <> <Link to="/new-note"> <Button style={{ backgroundColor: 'white' }}> <SvgIcon color="secondary" height="448pt" viewBox="0 0 448 448" width="448pt" xmlns="http://www.w3.org/2000/svg" > <path d="m408 184h-136c-4.417969 0-8-3.582031-8-8v-136c0-22.089844-17.910156-40-40-40s-40 17.910156-40 40v136c0 4.417969-3.582031 8-8 8h-136c-22.089844 0-40 17.910156-40 40s17.910156 40 40 40h136c4.417969 0 8 3.582031 8 8v136c0 22.089844 17.910156 40 40 40s40-17.910156 40-40v-136c0-4.417969 3.582031-8 8-8h136c22.089844 0 40-17.910156 40-40s-17.910156-40-40-40zm0 0" /> </SvgIcon> </Button> </Link> <div> <Button color="inherit" onClick={handleSignOut}> Sign Out </Button> </div> </> )} {!isLoggedIn && ( <div> <Link className={classes.link} color="inherit" to="/signin"> <Button color="inherit">Login</Button> </Link> <Link className={classes.link} color="inherit" to="/signup"> <Button color="inherit">Signup</Button> </Link> </div> )} </Toolbar> </AppBar> </div> ); }; export default NavBarComponent; <file_sep>/README.md Hey there 👋, visit [Quick-Notes](https://quick-notes-1748a.web.app/) for live demo. ## How to run locally 1. Clone this repo 2. Setup `.env` file like this (You can find these credentials in your firebase project setup guide). ``` REACT_APP_API_KEY="" REACT_APP_AUTH_DOMAIN="" REACT_APP_DATABASE_URL="" REACT_APP_PROJECT_ID="" REACT_APP_STORAGE_BUCKET="" REACT_APP_MESSAGE_SENDER_ID="" REACT_APP_APP_ID="" REACT_APP_MEASUREMENT_ID="" ``` 3. To install dependencies run, ``` $ npm install ``` 4. To start on `localhost` ``` $ npm start ``` This app is using firebase, Material-UI. I've used firestore as database and firebase auth for authenticating users. **Note:**- This app uses Web Speech API which is provided by browser. Current Voice search works in `chrome` browser only. <file_sep>/src/components/home/card.js import React, { useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import Typography from '@material-ui/core/Typography'; import MoreVertIcon from '@material-ui/icons/MoreVert'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import IconButton from '@material-ui/core/IconButton'; import ReactQuill from 'react-quill'; import 'react-quill/dist/quill.snow.css'; import { Link } from 'react-router-dom'; const useStyles = makeStyles({ root: { minWidth: 100, borderRadius: '10px', }, title: { padding: '10px 0 0 0', }, pos: { opacity: 0.8, }, operations: { width: '100%', display: 'flex', justifyContent: 'space-between', }, link: { color: 'inherit', }, verticalIcon: { '&:focus': { backgroundColor: 'transparent', }, }, }); export default function SimpleCard({ title, content, onDelete, id, handlePin, pinned, }) { const [anchorEl, setAnchorEl] = useState(null); const open = Boolean(anchorEl); const handleClick = (event) => { setAnchorEl(event.currentTarget); }; const handleClose = () => { setAnchorEl(null); }; const classes = useStyles(); return ( <Card className={classes.root} variant="outlined"> <CardContent> <div className={classes.operations}> <Typography variant="h4" className={classes.title} gutterBottom> {title} </Typography> <IconButton style={{ height: '50%' }} aria-label="more" aria-controls="long-menu" aria-haspopup="true" onClick={handleClick} className={classes.verticalIcon} > <MoreVertIcon /> </IconButton> </div> <div className={classes.pos}> <ReactQuill value={content} readOnly={true} modules={{ toolbar: false }} id="quill" /> </div> <Menu id="long-menu" anchorEl={anchorEl} keepMounted open={open} onClose={handleClose} PaperProps={{ style: { maxHeight: 48 * 4.5, width: '15ch', }, }} > <Link className={classes.link} to={{ pathname: `/updateNote/${id}`, state: { title: title, content: content, }, }} > <MenuItem onClick={handleClose}> <div>Edit</div> </MenuItem> </Link> <div onClick={() => onDelete(id, pinned ? true : false)}> <MenuItem onClick={handleClose}>Delete</MenuItem> </div> {pinned ? ( <div onClick={() => handlePin(id, true)}> <MenuItem onClick={handleClose}>Unpin</MenuItem> </div> ) : ( <div onClick={() => handlePin(id, false)}> <MenuItem onClick={handleClose}>Pin</MenuItem> </div> )} </Menu> </CardContent> </Card> ); } <file_sep>/src/containers/signup/index.js import React, { useState, useCallback } from 'react'; import { auth } from '../../firebase'; import { withRouter } from 'react-router-dom'; import SignUpComponent from '../../components/signup'; import firebase from '../../firebase'; const SignupContainer = ({ history }) => { const [values, setValues] = useState({ name: '', email: '', password: '', }); const { name, email, password } = values; const handleChange = (name) => (e) => { setValues({ ...values, [name]: e.target.value }); }; const handleSubmit = async (e) => { e.preventDefault(); await auth .createUserWithEmailAndPassword(email, password) .then((userData) => { userData.user .updateProfile({ displayName: name, }) .then(() => { history.push('/'); }); }); }; const handleGoogleSignIn = useCallback(() => { var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithRedirect(provider); history.push('/'); }, [history]); return ( <SignUpComponent handleChange={handleChange} handleSubmit={handleSubmit} handleGoogleSignIn={handleGoogleSignIn} /> ); }; export default withRouter(SignupContainer); <file_sep>/src/containers/navbar/index.js import React, { useState, useEffect } from 'react'; import NavBarComponent from '../../components/navbar'; import { auth } from '../../firebase'; import { useHistory } from 'react-router-dom'; const NavBarContainer = () => { const history = useHistory(); const [isLoggedIn, setIsLoggedIn] = useState(false); const [username, setUsername] = useState(''); useEffect(() => { let user = auth.currentUser; if (user) { setIsLoggedIn(true); setUsername(user.displayName); } }, []); const handleSignOut = () => { auth.signOut().then(() => { setIsLoggedIn(false); history.push('/signin'); }); }; return ( <NavBarComponent isLoggedIn={isLoggedIn} handleSignOut={handleSignOut} username={username} /> ); }; export default NavBarContainer; <file_sep>/src/containers/notes/index.js import React, { useState } from 'react'; import TakeNoteComponent from '../../components/notes'; import { auth, firestore } from '../../firebase'; import { withRouter } from 'react-router-dom'; const TakeNote = ({ history }) => { const [text, setText] = useState(''); const [headingText, setHeadingText] = useState(''); const [errorMessage, setErrorMessage] = useState(''); const handleQuillChange = (value) => { setText(value); }; const handleHeadingChange = (e) => { setHeadingText(e.target.value); }; const handleSnackBarClose = () => { setErrorMessage(''); }; const handleSubmit = (e) => { e.preventDefault(); if (!headingText || !text) { setErrorMessage('Please, fill out all the fields'); return; } firestore .collection('notes') .doc() .set({ title: headingText, description: text, userId: auth.currentUser.uid, timestamp: Date.now(), }) .then(() => { history.push('/'); }) .catch((err) => console.log('ERROR: ', err)); }; return ( <TakeNoteComponent text={text} headingText={headingText} handleQuillChange={handleQuillChange} handleHeadingChange={handleHeadingChange} handleSubmit={handleSubmit} errorMessage={errorMessage} handleSnackBarClose={handleSnackBarClose} /> ); }; export default withRouter(TakeNote); <file_sep>/src/pages/notes.js import React from 'react'; import NavBarContainer from '../containers/notes'; const Notes = () => { return <NavBarContainer />; }; export default Notes; <file_sep>/src/reusable-components/separator.js import React from 'react'; import styled from '@emotion/styled'; const Separator = () => { return ( <Container> <FlexDiv> <Hr /> <Text>or</Text> <Hr /> </FlexDiv> </Container> ); }; const Container = styled.div` width: 100%; margin: 20px 0; `; const FlexDiv = styled.div` display: flex; align-items: center; justify-content: center; `; const Hr = styled.hr` width: 80%; `; const Text = styled.div` margin: 0 10px; transform: translateY(-3px); `; export default Separator; <file_sep>/src/App.js import React, { useEffect, useState } from 'react'; import { Redirect, Route, Switch, withRouter } from 'react-router-dom'; import Home from './pages/home'; import Signup from './pages/signup'; import SignIn from './pages/signin'; import Notes from './pages/notes'; import { firestore, auth } from './firebase'; import UpdateANote from './pages/updateNote'; import Spinner from './reusable-components/spinner'; import NotFound from './pages/not-found'; import NavBar from './containers/navbar'; function App({ history }) { const [loading, setLoading] = useState(false); useEffect(() => { setLoading(true); auth.onAuthStateChanged((user) => { firestore.enablePersistence().catch((err) => console.log(err)); if (!user) { history.push('/signin'); setLoading(false); return; } setLoading(false); }); }, [history]); if (loading) { return <Spinner />; } return ( <div className="App"> <NavBar /> <Switch> <Route exact path="/new-note"> <Notes /> </Route> <Route exact path="/updateNote/:id"> <UpdateANote /> </Route> <Route exact path="/signin"> <SignIn /> </Route> <Route exact path="/signup"> <Signup /> </Route> <Route exact path="/"> <Home /> </Route> <Route path="/not-found"> <NotFound /> </Route> <Redirect to="/not-found" /> </Switch> </div> ); } export default withRouter(App);
1450014852c55c339baf70a008d5d1851f42ac18
[ "JavaScript", "Markdown" ]
15
JavaScript
UddeshJain/Quick-Notes
f4102f127a8f8b60db979c4bbddb9336a495aff2
f39c5edbe91aff91fd851bd15dc4f1a2e4ee70b6
refs/heads/main
<file_sep>import { NullableBoolean } from '../types' export type NullableTrieNode = TrieNode | null export class TrieNode { character!: string isWord!: NullableBoolean parent!: NullableTrieNode children!: Record<string, TrieNode> constructor(character = '', isWord: NullableBoolean = null, parent: NullableTrieNode = null) { this.character = character this.isWord = isWord this.parent = parent this.children = {} } isHead(): boolean { return this.character === '' && this.isWord === null && this.parent === null } addChild(char: string, isWord: boolean): TrieNode { if (this.children[char]) { if (!this.children[char].isWord && isWord) { this.children[char].isWord = true } } else { this.children[char] = new TrieNode(char, isWord, this) } return this.children[char] } walkBack(): string { let ret = '' let curNode: TrieNode = this while (!curNode.isHead()) { ret = curNode.character + ret curNode = curNode.parent as TrieNode } return ret } getAllChildNodes(): TrieNode[] { return Object.values(this.children) } } <file_sep>// import React from 'react'; // import { render, screen } from '@testing-library/react'; // import App from './App'; import { TrieNode } from './TrieNode' test('Can construct a node', () => { const node = new TrieNode('a', true, null) expect(node.character).toBe('a') expect(node.isWord).toBe(true) expect(node.parent).toBe(null) }) test('A null node is a head node', () => { const node = new TrieNode() expect(node.character).toBe('') expect(node.isWord).toBe(null) expect(node.parent).toBe(null) expect(node.isHead()).toBe(true) }) test('A non-null node is NOT a head node', () => { const node = new TrieNode('a', true, null) expect(node.isHead()).toBe(false) }) test('This trie is unicode tolerant', () => { const node = new TrieNode('🍕', true, null) expect(node.isHead()).toBe(false) }) test('A node can have a child node added', () => { const head = new TrieNode() const baby = head.addChild('a', true) expect(baby.character).toBe('a') expect(baby.isWord).toBe(true) expect(head.children.a).toBe(baby) }) test('If you try to add a child that exists, but it is now a word terminator where before it wasnt, we just flip that bit and leave the node alone otherwise', () => { const head = new TrieNode() const firstLetterOfAt = head.addChild('a', false) const secondLetterOfAt = firstLetterOfAt.addChild('t', true) // we loaded 'at' into the trie. expect(firstLetterOfAt.character).toBe('a') expect(firstLetterOfAt.isWord).toBe(false) expect(firstLetterOfAt.children.t.character).toBe('t') expect(firstLetterOfAt.children.t.isWord).toBe(true) expect(firstLetterOfAt.children.t).toBe(secondLetterOfAt) const newA = head.addChild('a', true) // now let's add the word 'a' into the trie... expect(newA).toBe(firstLetterOfAt) // same ref expect(newA.isWord).toBe(true) // now true }) test('walkback() returns the whole string from the given node.', () => { const head = new TrieNode() const nodeA = head.addChild('a', false) const nodeB = nodeA.addChild('b', false) const nodeC = nodeB.addChild('c', false) const nodeD = nodeC.addChild('d', false) const nodeE = nodeD.addChild('e', false) const nodeF = nodeE.addChild('f', false) expect(nodeC.walkBack()).toBe('abc') expect(nodeF.walkBack()).toBe('abcdef') }) test('Everything is fine if there are branches...', () => { const head = new TrieNode() const nodeA = head.addChild('a', false) const nodeB = nodeA.addChild('t', false) const nodeC = nodeB.addChild('e', false) const nodeSpace = nodeA.addChild(' ', false) const nodePizza = nodeSpace.addChild('🍕', true) expect(nodeC.walkBack()).toBe('ate') expect(nodePizza.walkBack()).toBe('a 🍕') }) test('getChildNodes() returns a TrieNode[] of the children.', () => { const head = new TrieNode() const n1 = head.addChild('a', false) const n2 = head.addChild('1', false) const n3 = head.addChild('🍕', false) const n4 = head.addChild('~', false) const res = head.getAllChildNodes() expect(res).toContain(n1) expect(res).toContain(n2) expect(res).toContain(n3) expect(res).toContain(n4) }) <file_sep>// import React from 'react'; // import { render, screen } from '@testing-library/react'; // import App from './App'; import { Corpus } from './Corpus' test('Can construct a Corpus', () => { const corpus = new Corpus(false) expect(corpus.head.isHead()).toBe(true) expect(corpus.isCaseSensitive).toBe(false) }) test('Can add a word', () => { const corpus = new Corpus(false) const wordNode = corpus.addWord('butt') expect(wordNode.walkBack()).toBe('butt') }) test('Can add two words and the endpoints are valid', () => { const corpus = new Corpus(false) const butteNode = corpus.addWord('butte') expect(butteNode.isWord).toBe(true) expect(butteNode.parent!.isWord).toBe(false) // 'butt' isnt a word yet corpus.addWord('butt') expect(butteNode.parent!.isWord).toBe(true) // now it is! }) test('Can walk to a non-word node given a string input', () => { const corpus = new Corpus(false) corpus.addWord('butte') const node = corpus.fetchNode('but')! expect(node.isWord).toBe(false) expect(node.children.t!.character).toBe('t') expect(node.children.t!.children.e!.character).toBe('e') expect(node.children.t!.children.e!.isWord).toBe(true) }) describe('case tests - ', () => { const inputWords = [ 'mercury', 'VENUS', '🌍', 'MARS', 'Jupiter', 'Saturn', '🍑', 'Neptune', // 'Pluto' ] describe('case insensitive tests', () => { let corpus: Corpus beforeEach(() => { corpus = new Corpus(false) inputWords.forEach((w) => { corpus.addWord(w) }) }) test('Words get lowercased in case-insens land!', () => { expect(corpus.isWord('VENUS')).toBe(true) expect(corpus.isWord('venus')).toBe(true) expect(corpus.isWord('🌍')).toBe(true) }) }) describe('CaSe SENSITIVE TeStS', () => { let corpus: Corpus beforeEach(() => { corpus = new Corpus(true) inputWords.forEach((w) => { corpus.addWord(w) }) }) test('Words get lowercased in case-insens land!', () => { expect(corpus.isWord('VENUS')).toBe(true) expect(corpus.isWord('venus')).toBe(false) expect(corpus.isWord('🌍')).toBe(true) }) }) }) describe('search tests ', () => { const inputWords = [ 'but', 'bunny', 'zaa', 'bent', 'bend', 'butte', 'hoobes', 'bunnies', 'bUTt', 'brett', 'zebra', 'bundt', 'hoobalicious', 'zest', 'bun', 'butts', 'hoobo', 'bender', 'bunt', 'hobba', 'hoober', 'zedzedzed', ] let corpus: Corpus beforeEach(() => { corpus = new Corpus(true) inputWords.forEach((w) => { corpus.addWord(w) }) }) test('fetch autocomplete words', () => { const results = corpus.getBroadWords('bu', 3) expect(results[0]).toBe('but') expect(results[1]).toBe('bun') expect(results[2]).toBe('bunt') const results2 = corpus.getBroadWords('bu', 1) expect(results2[0]).toBe('but') }) test('get all words', () => { expect(corpus.getAllWords()).toStrictEqual(inputWords) }) }) <file_sep>import { TrieNode, NullableTrieNode } from './TrieNode' interface TrieWalkFunction { (nodesToVisit: TrieNode[], curNode: TrieNode): TrieNode[] } export class Corpus { readonly head: TrieNode readonly isCaseSensitive: boolean private dictionaryMap: Record<string, TrieNode> private wordSet: Set<string> constructor(isCaseSensitive: boolean) { this.head = new TrieNode() this.isCaseSensitive = isCaseSensitive this.dictionaryMap = {} this.wordSet = new Set() } getAllWords(): string[] { return Array.from(this.wordSet.values()) } addWord(word: string): TrieNode { if (!this.isCaseSensitive) { word = word.toLowerCase() } if (this.dictionaryMap[word]) { return this.dictionaryMap[word] } let curNode = this.head for (let i = 0; i < word.length; i++) { curNode = curNode.addChild(word.charAt(i), false) } curNode.isWord = true this.dictionaryMap[word] = curNode this.wordSet.add(word) return curNode } isWord(word: string): boolean { if (!this.isCaseSensitive) { word = word.toLowerCase() } return !!this.dictionaryMap[word] } fetchNode(fragment: string): NullableTrieNode { if (!this.isCaseSensitive) { fragment = fragment.toLowerCase() } const cachedMaybe = this.dictionaryMap[fragment] if (cachedMaybe) { return cachedMaybe } let curNode = this.head for (let i = 0; i < fragment.length; i++) { curNode = curNode.children[fragment.charAt(i)] if (!curNode) { return null } } return curNode } private childrenwalkCommon(word: string, limit: number, fn: TrieWalkFunction): string[] { const ret: string[] = [] // const tmp = word; if (limit <= 0) { throw new Error('limit must be a positive non-zero number') } const root = this.fetchNode(word) if (!root) { return ret } // let curNode!: TrieNode let nodesToVisit: TrieNode[] = [] nodesToVisit = nodesToVisit.concat(root.getAllChildNodes()) while (nodesToVisit.length > 0 && ret.length < limit) { const curNode = nodesToVisit.shift() as TrieNode // pop is bottom nodesToVisit = fn(nodesToVisit, curNode) if (curNode.isWord) { ret.push(curNode.walkBack()) } } return ret } getBroadWords(word: string, limit: number): string[] { const fn = (nodesToVisit: TrieNode[], curNode: TrieNode): TrieNode[] => nodesToVisit.concat(Object.values(curNode.children) as TrieNode[]) return this.childrenwalkCommon(word, limit, fn) } /* def fn(nodes_to_visit, currentnode): childs = sorted(currentnode.children.values(), key=lambda x: x.char) nodes_to_visit.extend(childs) return self._childrenwalkCommon( word, limit, fn ) */ }
5c56fbe1643cc57038ed1565d40ad1b93620f65e
[ "TypeScript" ]
4
TypeScript
mcgrue/corpus-flower
52d1d79bb40cbb0b2df564de0e365d4535271c10
db7fde8e3d41ee479bb4b9abe4e8f63f0b7a650c
refs/heads/master
<repo_name>tilky/SQLiteUsersOnline<file_sep>/setup.php <?php try { //open the database $db = new PDO('sqlite:UsersOnline.db'); //create the database $db->exec("CREATE TABLE UsersOnline (IP TEXT PRIMARY KEY, Time TEXT)"); echo "Database and Table created sucessfully."; // close the database connection $db = NULL; } catch(PDOException $e) { print 'Exception : '.$e->getMessage(); } ?><file_sep>/usersonline.php <?php $IPaddress = $_SERVER["REMOTE_ADDR"]; $UsersOnlinetime=time(); $time_check=$UsersOnlinetime-900; // Time = 60 * Minutes, Example: 10 minutes = 60 * 10 = 600. //open the database $db = new PDO('sqlite:UsersOnline.db'); // add new visitor $db->exec("INSERT INTO UsersOnline(IP, Time) VALUES('$IPaddress', '$UsersOnlinetime')"); // update the time of a visitor $db->exec("UPDATE UsersOnline SET Time='$UsersOnlinetime' WHERE IP = '$IPaddress'"); // delete if visitor left $db->exec("DELETE FROM UsersOnline WHERE Time<$time_check"); // display number of users online $result = $db->query("SELECT * FROM UsersOnline"); $rows = $result->fetchAll(); $count = count($rows); // close the database connection $db = NULL; if($count>1) { echo "$count users online!"; } else { echo "$count user online!"; } ?>
350b6ae9c31a6ee73427957f2a75d4746663aa7e
[ "PHP" ]
2
PHP
tilky/SQLiteUsersOnline
6240dc4ed9ca4e0159ee77fad3cb91c62e3c45aa
0dbb27dee1b42e8b1a672cd48f312554eff6f8ce
refs/heads/master
<file_sep>const fs = require('fs'); const mysql = require('mysql'); const moment = require('moment'); const config = require('./../config.private.json'); const Twitter = require('twitter'); const client = new Twitter({ consumer_key: config.CONSUMER_KEY, consumer_secret: config.CONSUMER_SECRET, access_token_key: config.TOKEN_KEY, access_token_secret: config.TOKEN_SECRET }); const db = mysql.createPool({ connectionLimit : 3, host : config.DB_HOST, user : config.DB_USER, password : <PASSWORD>, database : config.DB_NAME }); // process runs once a day so we use a fixed timestamp const today = moment().add(-1, 'days').format('YY-MM-DD 00:00:00'); const yesterday = moment(today,'YY-MM-DD 00:00:00').add(-1, 'days').format('YY-MM-DD 00:00:00'); // import functions const { coolDown, kill, log, emailReport } = require('./utils.js'); const { createTableUsers, createTableConnections, saveUsers, saveFollowerConnections, saveFriendConnections } = require('./db.js'); const { fetchFollowers, fetchFriends } = require('./twitter-client.js'); /* //####################################### // uncommend to run report only return generateDailyReport(db, today, moment(today, 'YY-MM-DD 00:00:00').add(-1, 'days').format('YY-MM-DD 00:00:00') ).catch(error => kill('[UNCAUGHT ERROR] -> ', error) ) .then(report => kill(report) ); //####################################### */ // Setup DB tables `Users` and `Connections` Promise.all([ createTableUsers(db), createTableConnections(db) ]).catch(error => kill('[DB ERROR] -> ', error) ) // Fetch Twitter Followers and Friends .then(res => { log('Connecting to Twitter API'); return Promise.all([ fetchFollowers(client, config.TWITTER_HANDLE), fetchFriends(client, config.TWITTER_HANDLE), ]); }).catch(error => kill('[API ERROR] -> ', error) ) // Save new users and daily connections .then( values => { log('Updating `users` and `connections` table'); let followers = values[0]; let friends = values[1]; log('followers', followers.length); log('friends', friends.length); return Promise.all([ saveUsers(db, today, followers, friends), saveFollowerConnections(db, today, followers), saveFriendConnections(db, today, friends) ]); }).catch(error => kill('[DB ERROR] -> ', error) ) // Generate daily report .then( (values) => { return generateDailyReport(db, today, yesterday ) }).catch(error => kill('[DB REPORT ERROR] -> ', error) ) // print daily report in a log file .then( (report) => { log( report ) log('Saving report'); fs.appendFileSync('./report.txt', report) if ( config.SEND_EMAIL ) { log('Sending report'); return emailReport(report); } }).catch( error => kill('[EMAIL REPORT ERROR] -> ', error) ) // We're done here .then( () => { log('Closing connection'); return db.end(); }).catch(error => kill('[UNCAUGHT ERROR] -> ', error) ); <file_sep># twitter-bot Mine twitter followers/friends and generate/email a report daily ## install install *sendmail* `sudo apt-get install sendmail` download repo and install dependencies `cd twitter-bot/` `yarn` ## configuration `cp config.example.json config.private.json` gather your twitter API keys, create a mysql db, and edit the config file: ``` { "CONSUMER_KEY": "<KEY>", "CONSUMER_SECRET": "<KEY>", "TOKEN_KEY": "<KEY>", "TOKEN_SECRET": "<KEY>", "TWITTER_HANDLE": "michael_iriarte", "DB_HOST": "localhost", "DB_USER": "root", "DB_PASSWORD": "<PASSWORD>", "DB_NAME": "twitter_bot", "SEND_EMAIL": true, "EMAIL_SENDER": "<EMAIL>", "EMAIL_RECIPIENT": "XXXXXXXXXXXXXXXXXXXXXXXXXX", "EMAIL_SUBJECT": "Twitter Bot Stats" } ``` ## run `node ./js/bot.js` ## setup cron job `sudo vim /etc/crontab` `sudo service cron reload` #### Run once a day `0 10 * * * root /projects/twitter-bot/ && node ./js/bot.js >> /projects/twitter-bot/logs.txt ` <file_sep>const moment = require('moment'); // Initialize and create Users tabe if not exist createTableUsers = (db) => { return new Promise( (resolve, reject) => { let q = "CREATE TABLE IF NOT EXISTS `users` ( " + " `id` bigint(20) NOT NULL DEFAULT 0, " // -> id + " `profile_image` varchar(140) NOT NULL DEFAULT '', " // -> profile_image_url_https + " `followers_count` int(11) NULL, " // -> followers_count + " `friends_count` int(11) NULL, " // -> friends_count + " `screen_name` varchar(40) NOT NULL DEFAULT '', " // -> screen_name + " `name` varchar(40) NOT NULL default '', " // -> name + " `time_zone` varchar(40) NOT NULL DEFAULT '', " // -> time_zone + " `lang` varchar(4) NOT NULL DEFAULT '', " // -> lang + " `timestamp` TIMESTAMP NULL, " // NOT NULL DEFAULT CURRENT_TIMESTAMP," + " PRIMARY KEY (`id`) ); " db.query( q, (error, results, fields) => { if ( error ) return reject(error); if ( results.warningCount == 0 ) log('Created `users` table'); resolve(); }); }); } // Initialize and create Connections table if not exist createTableConnections = (db) => { return new Promise( (resolve, reject) => { let q = " CREATE TABLE IF NOT EXISTS `connections` ( " + " `id` bigint(20) NOT NULL DEFAULT 0, " + " `is_follower` BOOLEAN NOT NULL DEFAULT 0, " + " `is_friend` BOOLEAN NOT NULL DEFAULT 0, " + " `timestamp` TIMESTAMP NULL, " // NOT NULL DEFAULT CURRENT_TIMESTAMP, " + " PRIMARY KEY (`id`, `timestamp`) ); " db.query( q, (error, results, fields) => { if ( error ) return reject(error); if ( results.warningCount == 0 ) log('Created `connections` table'); resolve(); }); }); } // Save/Update users saveUsers = (db, timestamp, followers, friends) => { let users = followers.concat(friends); return new Promise( (resolve, reject) => { let q = "INSERT INTO `users` ( " + " `id`, `profile_image`, `followers_count`, `friends_count`, " + " `screen_name`, `name`, `time_zone`, `lang`, `timestamp` ) " + " VALUES "; for ( let user of users ) { let data = { id: user.id, profile_image: db.escape(user.profile_image_url_https), followers_count: user.followers_count, friends_count: user.friends_count, screen_name: db.escape(user.screen_name), name: db.escape(user.name), time_zone: user.time_zone, lang: user.lang, timestamp: timestamp }; q += ' ( ' + data.id +', "' + db.escape(data.profile_image) +'", ' + data.followers_count +', ' + data.friends_count +', "' + db.escape(data.screen_name) +'", "' + db.escape(data.name) +'", "' + data.time_zone +'", "' + data.lang +'", "' + timestamp + '" ),' } q = q.slice(0, -1); // remove last coma q += " ON DUPLICATE KEY UPDATE profile_image=VALUES(profile_image)," q += " followers_count=VALUES(followers_count), friends_count=VALUES(friends_count)," q += " screen_name=VALUES(screen_name), name=VALUES(name), time_zone=VALUES(time_zone)," q += " lang=VALUES(lang), timestamp=VALUES(timestamp);" db.query( q, (error, results, fields) => { if ( error ) return reject(error); resolve([followers, friends]); }); }); } // Save/Update follower connections saveFollowerConnections = (db, timestamp, users) => { return new Promise( (resolve, reject) => { let q = "INSERT INTO `connections` ( " + " `id`, `is_follower`, `timestamp` ) " + " VALUES "; for ( let user of users ) q += ' ( ' + user.id + ', 1, "' + timestamp + '" ),'; q = q.slice(0, -1); // remove last coma q += " ON DUPLICATE KEY UPDATE is_follower=1;" db.query( q, (error, results, fields) => { if ( error ) return reject(error); resolve(results); }); }); } // Save/Update friend connection saveFriendConnections = (db, timestamp, users) => { return new Promise( (resolve, reject) => { let q = "INSERT INTO `connections` ( " + " `id`, `is_friend`, `timestamp` ) " + " VALUES "; for ( let user of users ) q += ' ( ' + user.id + ', 1, "' + timestamp + '" ),'; q = q.slice(0, -1); // remove last coma q += " ON DUPLICATE KEY UPDATE is_friend=1;" db.query( q, (error, results, fields) => { if ( error ) return reject(error); resolve(results); }); }); } // get daily saved connections getDailySavedConnection = (db, timestamp) => { return new Promise( (resolve, reject) => { let q = 'SELECT * FROM `connections` WHERE timestamp="'+timestamp+'";'; db.query( q, (error, results, fields) => { if ( error ) return reject(error); resolve(results); }); }); } // Generate report between 2 dates generateDailyReport = (db, today, yesterday) => { return new Promise( (resolve, reject) => { // collect both days of data return Promise.all([ getDailySavedConnection(db, today), // select connections from today getDailySavedConnection(db, yesterday), // select connections from yesterday ]).catch(error => kill('[DB ERROR] -> ', error) ) .then( values => { let merged = {}; let friends = []; let followers = []; let newFriends = []; let lostFriends = []; let newFollowers = []; let lostFollowers = []; // parse today's connections for ( let user of values[0] ) { if ( user.is_friend ) friends.push(user.id); if ( user.is_follower ) followers.push(user.id); merged[user.id] = { id: user.id, is_friend: user.is_friend, is_follower: user.is_follower }; } // parse yesterday's connections for ( let user of values[1] ) { if ( merged[user.id] ) { merged[user.id].was_friend = user.is_friend merged[user.id].was_follower = user.is_follower } else { merged[user.id] = { id: user.id, was_friend: user.is_friend, was_follower: user.is_follower }; } } for ( let key in merged ) { let user = merged[key]; if ( user.was_friend && !user.is_friend ) lostFriends.push(user); if ( !user.was_friend && user.is_friend ) newFriends.push(user); if ( user.was_follower && !user.is_follower ) lostFollowers.push(user); if ( !user.was_follower && user.is_follower ) newFollowers.push(user); } let followerUpdate = ''; if ( newFollowers.length + lostFollowers.length ) { followerUpdate = ' ('+ (newFollowers.length > lostFollowers.length ? '+' : '-' ) followerUpdate += (newFollowers.length + lostFollowers.length) + ')' } let friendUpdate = ''; if ( newFriends.length + lostFriends.length ) { friendUpdate = ' ('+ (newFriends.length > lostFriends.length ? '+' : '-' ) friendUpdate += (newFriends.length + lostFriends.length) + ')' } let report = '\n' + '# timestamp: ' + today.slice(0,8) + '\n' + '# friends: ' + friends.length + friendUpdate + '\n' + '# followers: ' + followers.length + followerUpdate + '\n'; if ( newFollowers.length + lostFollowers.length > 0 ) report += '# diff followers:' + '\n' for ( let user of newFollowers ) report += ' + ' + user.id + '\n' for ( let user of lostFollowers ) report += ' - ' + user.id + '\n' if ( newFriends.length + lostFriends.length > 0 ) report += '# diff friends: ' + '\n' for ( let user of newFriends ) report += ' + ' + user.id + '\n' for ( let user of lostFriends ) report += ' - ' + user.id + '\n' report += '------------------------' resolve(report); }) }); } module.exports = { createTableUsers: createTableUsers, createTableConnections: createTableConnections, saveUsers: saveUsers, saveFollowerConnections: saveFollowerConnections, saveFriendConnections: saveFriendConnections, generateDailyReport: generateDailyReport }
4b3ecf68ac8791892a39377999c2e237dc25f9a5
[ "JavaScript", "Markdown" ]
3
JavaScript
mikatalk/twitter-bot
73f6af5bf3f34cbbde60577cbd901c9eff7ccf58
952e345ecd35de4277b756968700971fc0b40076
refs/heads/master
<file_sep>cmake_minimum_required(VERSION 3.13.4) project(TrackAssociator) # Set C++ standard set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Add sources set(SOURCES_FILTERS src/track_associator.cpp ) include_directories( include ../include ) add_library(${PROJECT_NAME} STATIC ${SOURCES_FILTERS}) # Testing enable_testing() find_package(GTest REQUIRED) include_directories(${GTEST_INCLUDE_DIR}) target_link_libraries(${PROJECT_NAME} GTest::GTest GTest::Main) add_subdirectory(tests) <file_sep>#include <gtest/gtest.h> #include <iostream> #include "track_associator.h" using namespace mht::track_association; TEST(TrackAssociatorTest, ConstructorTest) { AssociatorConfiguration config; TrackAssociator ta; ta.Initialize(config); } TEST(TrackAssociatorTest, AssociationSimpleTest) { TrackList tracks; TrackList observations; AssociatorConfiguration config; TrackAssociator ta; ta.Initialize(config); ta.AssociateTracks(tracks, observations); } <file_sep>add_executable(motion_models_tests constant_velocity_model_test.cpp constant_acceleration_model_test.cpp ) target_link_libraries(motion_models_tests gtest_main MotionModels ) add_test( NAME unit COMMAND ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}/motion_models_tests )<file_sep>#ifndef MHT_MHT_FILTERS_INCLUDE_FILTER_ALIASES_H_ #define MHT_MHT_FILTERS_INCLUDE_FILTER_ALIASES_H_ #include <eigen3/Eigen/Dense> namespace mht::filters { using StateVector = Eigen::Matrix<float, 6, 1>; using TransitionMatrix = Eigen::Matrix<float, 6, 6>; using ObservationMatrix = Eigen::Matrix<float, 3, 6>; using ObservationVector = Eigen::Matrix<float, 3, 1>; using StateCovariancematrix = Eigen::Matrix<float, 6, 6>; using InnovationCovarianceMatrix = Eigen::Matrix<float, 3, 3>; using ProcessNoiseCovariance = Eigen::Matrix<float, 6, 6>; using MeasurementNoiseCovariance = Eigen::Matrix<float, 3, 3>; using ModelType = mht::motion_model::MotionModelType; using ModelState = mht::motion_model::MotionModelBase<6>::ModelState; } #endif <file_sep>#ifndef MHT_MHT_MOTION_MODEL_MOION_MODEL_FACTORY_H_ #define MHT_MHT_MOTION_MODEL_MOION_MODEL_FACTORY_H_ #include <memory> #include "motion_model_base.h" #include "motion_model_type.h" namespace mht::motion_model { class MotionModelFactory { public: MotionModelFactory() = default; ~MotionModelFactory() = default; std::unique_ptr<MotionModelBase<6>> CreateModel(MotionModelType model_type, const MotionModelBase<6>::ModelState & initial_state, float initial_time_stamp); private: }; } #endif<file_sep>#ifndef MHT_MHT_MOTION_MODEL_INCLUDE_MOTION_MODEL_BASE_H_ #define MHT_MHT_MOTION_MODEL_INCLUDE_MOTION_MODEL_BASE_H_ #include <stdint.h> #include <eigen3/Eigen/Dense> namespace mht::motion_model { template <uint8_t state_size> class MotionModelBase { public: using ModelState = Eigen::Matrix<float, state_size, 1>; using TransitionMatrix = Eigen::Matrix<float, state_size, state_size>; MotionModelBase(const ModelState & initial_state, float initial_time_stamp) : time_stamp_(initial_time_stamp) , state_(initial_state) { } virtual ~MotionModelBase(void) {}; virtual void PredictState(const float time_stamp) = 0; virtual TransitionMatrix GetTransitionMatrix(void) = 0; virtual ModelState GetPredictedState(void) = 0; protected: ModelState state_; float time_stamp_; }; } #endif <file_sep>#ifndef MHT_INCLUDE_TRACK_STATUS_H_ #define MHT_INCLUDE_TRACK_STATUS_H_ namespace mht::interface { enum class TrackStatus { INVALID = 0, NEW = 1, UPDATED = 2, COASTING = 3 }; } #endif <file_sep># mht Multi hypothesis tracking <file_sep>#ifndef MHT_MHT_ASSOCIATION_INCLUDE_ASSOCIATON_TYPE_H_ #define MHT_MHT_ASSOCIATION_INCLUDE_ASSOCIATON_TYPE_H_ namespace mht::track_association { enum class AssociatonType { NEAREST_NEIGHBOUR = 0, JPDA = 1 }; } #endif <file_sep>#ifndef MHT_MHT_FILTERS_INCLUDE_KALMAN_FILTER_H_ #define MHT_MHT_FILTERS_INCLUDE_KALMAN_FILTER_H_ #include "bayesian_filter.h" #include <memory> #include <tuple> namespace mht::filters { using FusionResult = std::tuple<StateVector, StateCovariancematrix>; class KalmanFilter : public BayesianFilter { public: KalmanFilter(const FilterCalibrations & calibrations); ~KalmanFilter(void); void FuseNewObservation(const ObservationVector & observation, float timestamp); FusionResult GetFusionResult(void) const; private: void PredictState(float timestamp); void UpdateMeasurement(const ObservationVector & observation); TransitionMatrix a_; ObservationMatrix c_; StateVector x_; StateCovariancematrix P_; }; } #endif <file_sep>#include <gtest/gtest.h> #include <iostream> #include "constant_velocity_model.h" #include "motion_models_factory.h" using namespace mht::motion_model; TEST(ConstantVelocityTests, Constructor) { ConstantVelocityModel::ModelState x0; x0.setZero(); float t0 = 0.0f; ConstantVelocityModel model(x0, t0); EXPECT_TRUE(true); } TEST(ConstantVelocityTests, FactoryCreate) { auto mmf = MotionModelFactory(); auto cvm = std::move(mmf.CreateModel(MotionModelType::CV, MotionModelBase<6>::ModelState(), 0.0F)); } TEST(ConstantVelocityTests, PredictStateSimpleTest) { ConstantVelocityModel::ModelState x0; x0.setZero(); float t0 = 0.0f; ConstantVelocityModel model(x0, t0); model.PredictState(t0); const auto predicted_state = model.GetPredictedState(); EXPECT_FLOAT_EQ(predicted_state(0), 0.0f); EXPECT_FLOAT_EQ(predicted_state(1), 0.0f); EXPECT_FLOAT_EQ(predicted_state(2), 0.0f); EXPECT_FLOAT_EQ(predicted_state(3), 0.0f); EXPECT_FLOAT_EQ(predicted_state(4), 0.0f); EXPECT_FLOAT_EQ(predicted_state(5), 0.0f); } <file_sep>#include <track_associator.h> #include <vector> #include <cmath> namespace mht::track_association { TrackAssociator::TrackAssociator(void) {} TrackAssociator::~TrackAssociator(void) {} void TrackAssociator::Initialize(const AssociatorConfiguration & config) { config_ = config; } void TrackAssociator::InitializeDistances(size_t tracks_number, size_t observations_number) { for (auto & track_row : distances_) track_row.clear(); distances_.clear(); for (int track_idx = 0; track_idx < tracks_number; track_idx++) { std::vector<float> tmp(observations_number); distances_.push_back(tmp); } } void TrackAssociator::CalculateDistances(const TrackList & tracks, const TrackList & observations) { for (int track_idx = 0; track_idx < tracks.size(); track_idx++) { for (int obs_idx = 0; obs_idx < observations.size(); obs_idx++) distances_[track_idx][obs_idx] = CalculateDistance(tracks.at(track_idx), observations.at(obs_idx)); } } float TrackAssociator::CalculateDistance(const TrackerObject & track, const TrackerObject & observaion) { /* Dummy difference */ float difference = std::pow(track.x - observaion.x, 2) + std::pow(track.y - observaion.y, 2) + std::pow(track.v_x - observaion.v_x, 2) + std::pow(track.v_y - observaion.v_y, 2) + std::pow(track.yaw - observaion.yaw, 2) + std::pow(track.yaw_rate - observaion.yaw_rate, 2); return difference; } void TrackAssociator::AssociateTracks(const TrackList & tracks, const TrackList & observations) { InitializeDistances(tracks.size(), observations.size()); CalculateDistances(tracks, observations); Associate(); } void TrackAssociator::Associate(void) { switch (config_.association_type) { case AssociatonType::NEAREST_NEIGHBOUR: NearestNeighbourAssociation(); break; case AssociatonType::JPDA: JPDAAssociation(); break; default: return; } } void TrackAssociator::NearestNeighbourAssociation(void) {} void TrackAssociator::JPDAAssociation(void) {} } <file_sep>cmake_minimum_required(VERSION 3.13.4) project(MHT VERSION 1.0) # specify the C++ standard set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/mht/motion_model) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/mht/filters) add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/mht/track_associator) include_directories( mht/motion_model/include mht/filters/include mht/track_associator/include mht/include ) add_executable(${PROJECT_NAME} mht/main.cpp) target_link_libraries(${PROJECT_NAME} PUBLIC MotionModels Filters TrackAssociator ) <file_sep>#ifndef MHT_MHT_FILTERS_INCLUDE_FILTER_CALIBRATIONS_H_ #define MHT_MHT_FILTERS_INCLUDE_FILTER_CALIBRATIONS_H_ #include "motion_model_type.h" #include "filters_aliases.h" namespace mht::filters { struct FilterCalibrations { mht::motion_model::MotionModelType model_type = mht::motion_model::MotionModelType::CV; ModelState initial_state = ModelState(); float initial_time_stamp = 0.0F; ProcessNoiseCovariance process_noise = ProcessNoiseCovariance(); MeasurementNoiseCovariance measurement_noise = MeasurementNoiseCovariance(); }; } #endif <file_sep>#ifndef MHT_MHT_FILTERS_INCLUDE_BAYESIAN_FILTER_H_ #define MHT_MHT_FILTERS_INCLUDE_BAYESIAN_FILTER_H_ #include <memory> #include <motion_models_factory.h> #include <filter_calibrations.h> namespace mht::filters { class BayesianFilter { public: BayesianFilter(const FilterCalibrations & calibrations) : model_(std::move(mmf_.CreateModel(calibrations.model_type, calibrations.initial_state, calibrations.initial_time_stamp))) , calibrations_(calibrations) {}; virtual ~BayesianFilter(void){}; virtual void FuseNewObservation(const ObservationVector & observation, float timestamp) = 0; ModelType GetMotionModelType(void) const { return calibrations_.model_type; } protected: virtual void PredictState(float timestamp) = 0; virtual void UpdateMeasurement(const ObservationVector & observation) = 0; StateVector state_; mht::motion_model::MotionModelFactory mmf_ = mht::motion_model::MotionModelFactory(); std::unique_ptr<mht::motion_model::MotionModelBase<6>> model_; FilterCalibrations calibrations_; }; } #endif <file_sep>#ifndef MHT_MHT_MOTION_MODEL_INCLUDE_CONSTANT_VELOCITY_MODEL_BASE_H_ #define MHT_MHT_MOTION_MODEL_INCLUDE_CONSTANT_VELOCITY_MODEL_BASE_H_ #include "motion_model_base.h" namespace mht::motion_model { class ConstantVelocityModel : public MotionModelBase<6> { public: ConstantVelocityModel(const ModelState & initial_state, float initial_time_stamp); virtual ~ConstantVelocityModel(void); void PredictState(const float time_stamp); TransitionMatrix GetTransitionMatrix(void); ModelState GetPredictedState(void); private: void FindTransitionMatrix(const float time_stamp); TransitionMatrix transition_matrix_; }; } #endif<file_sep>#include <constant_velocity_model.h> namespace mht::motion_model { ConstantVelocityModel::ConstantVelocityModel(const ModelState & initial_state, float initial_time_stamp) : MotionModelBase<6>(initial_state, initial_time_stamp) { } ConstantVelocityModel::~ConstantVelocityModel(void) { } void ConstantVelocityModel::PredictState(const float time_stamp) { FindTransitionMatrix(time_stamp); state_ = transition_matrix_ * state_; } void ConstantVelocityModel::FindTransitionMatrix(const float time_stamp) { const auto tme_delta = time_stamp - time_stamp_; transition_matrix_.setIdentity(); transition_matrix_(0, 1) = tme_delta; transition_matrix_(2, 3) = tme_delta; transition_matrix_(4, 5) = tme_delta; } ConstantVelocityModel::TransitionMatrix ConstantVelocityModel::GetTransitionMatrix(void) { return transition_matrix_; } ConstantVelocityModel::ModelState ConstantVelocityModel::GetPredictedState(void) { return state_; } } <file_sep>#ifndef MHT_INCLUDE_MOTION_STATUS_H_ #define MHT_INCLUDE_MOTION_STATUS_H_ namespace mht::interface { enum class MotionStatus { INVALID = 0, MOVING = 1, STATIC = 2, UNAMBIGIOUS = 3 }; } #endif <file_sep>cmake_minimum_required(VERSION 3.13.4) project(MotionModels) # Set C++ standards set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Add source set(SOURCES_MOTION_MODELS src/constant_velocity_model.cpp src/motion_models_factory.cpp src/constant_acceleration_model.cpp ) include_directories(include) add_library(${PROJECT_NAME} STATIC ${SOURCES_MOTION_MODELS}) # Testing enable_testing() find_package(GTest REQUIRED) include_directories(${GTEST_INCLUDE_DIR}) target_link_libraries(${PROJECT_NAME} GTest::GTest GTest::Main) add_subdirectory(tests) <file_sep>#ifndef MHT_MHT_ASSOCIATION_INCLUDE_TRACK_ASSOCIATOR_H_ #define MHT_MHT_ASSOCIATION_INCLUDE_TRACK_ASSOCIATOR_H_ #include <vector> #include <tracker_object.h> #include "associator_configuration.h" using namespace mht::interface; namespace mht::track_association { using TrackList = std::vector<TrackerObject>; class TrackAssociator { public: TrackAssociator(void); ~TrackAssociator(void); void Initialize(const AssociatorConfiguration & config); void AssociateTracks(const TrackList & tracks, const TrackList & observations); private: void InitializeDistances(size_t tracks_number, size_t observations_number); void CalculateDistances(const TrackList & tracks, const TrackList & observations); float CalculateDistance(const TrackerObject & track, const TrackerObject & observaion); void Associate(void); void NearestNeighbourAssociation(void); void JPDAAssociation(void); std::vector<std::vector<float>> distances_; AssociatorConfiguration config_; }; } #endif <file_sep>#ifndef MHT_MHT_INCLUDE_TRACKER_OBJECT_H_ #define MHT_MHT_INCLUDE_TRACKER_OBJECT_H_ #include <track_status.h> #include <moving_status.h> namespace mht::interface { struct TrackerObject { float x = 0.0f; float y = 0.0; float yaw = 0.0f; float v_x = 0.0f; float v_y = .0f; float yaw_rate = 0.0f; float x_std = 0.0f; float y_std = 0.0f; float yaw_std = 0.0f; float v_x_std = 0.0f; float v_y_std = .0f; float yaw_rate_std = 0.0f; float age = 0.0f; TrackStatus status = TrackStatus::INVALID; MovingStatus moving_status = MovingStatus::INVALID; }; } #endif <file_sep>#include <gtest/gtest.h> #include <iostream> #include "constant_acceleration_model.h" #include "motion_models_factory.h" using namespace mht::motion_model; TEST(ConstantAccelerationTests, Constructor) { ConstantAccelerationModel::ModelState x0; x0.setZero(); float t0 = 0.0f; ConstantAccelerationModel model(x0, t0); EXPECT_TRUE(true); } TEST(ConstantAccelerationTests, FactoryCreate) { auto mmf = MotionModelFactory(); auto cvm = std::move(mmf.CreateModel(MotionModelType::CV, MotionModelBase<6>::ModelState(), 0.0F)); } TEST(ConstantAccelerationTests, PredictStateSimpleTest) { ConstantAccelerationModel::ModelState x0; x0.setZero(); float t0 = 0.0f; ConstantAccelerationModel model(x0, t0); model.PredictState(t0); const auto predicted_state = model.GetPredictedState(); EXPECT_FLOAT_EQ(predicted_state(0), 0.0f); EXPECT_FLOAT_EQ(predicted_state(1), 0.0f); EXPECT_FLOAT_EQ(predicted_state(2), 0.0f); EXPECT_FLOAT_EQ(predicted_state(3), 0.0f); EXPECT_FLOAT_EQ(predicted_state(4), 0.0f); EXPECT_FLOAT_EQ(predicted_state(5), 0.0f); EXPECT_FLOAT_EQ(predicted_state(6), 0.0f); EXPECT_FLOAT_EQ(predicted_state(7), 0.0f); EXPECT_FLOAT_EQ(predicted_state(8), 0.0f); } <file_sep>#ifndef MHT_MHT_MOTION_MODEL_INCLUDE_CONSTANT_ACCELERATION_MODEL_BASE_H_ #define MHT_MHT_MOTION_MODEL_INCLUDE_CONSTANT_ACCELERATION_MODEL_BASE_H_ #include "motion_model_base.h" namespace mht::motion_model { class ConstantAccelerationModel : public MotionModelBase<9> { public: ConstantAccelerationModel(const ModelState & initial_state, float initial_time_stamp); virtual ~ConstantAccelerationModel(void); void PredictState(const float time_stamp); TransitionMatrix GetTransitionMatrix(void); ModelState GetPredictedState(void); private: void FindTransitionMatrix(const float time_stamp); TransitionMatrix transition_matrix_; }; } #endif <file_sep>#include "kalman_filter.h" namespace mht::filters { KalmanFilter::KalmanFilter(const FilterCalibrations & calibrations) : BayesianFilter(calibrations) , a_(TransitionMatrix()) , c_(ObservationMatrix()) , x_(StateVector()) , P_(StateCovariancematrix()) { a_.setZero(); c_.setZero(); x_.setZero(); P_.setZero(); for (int i = 0; i < 6; i++) P_(i, i) = 100.0F; } KalmanFilter::~KalmanFilter() {} void KalmanFilter::FuseNewObservation(const ObservationVector & observation, float timestamp) { PredictState(timestamp); UpdateMeasurement(observation); } FusionResult KalmanFilter::GetFusionResult(void) const { return FusionResult{x_, P_}; } void KalmanFilter::PredictState(float timestamp) { model_->PredictState(timestamp); const auto a = model_->GetTransitionMatrix(); P_ = a * P_ * a.transpose() + calibrations_.process_noise; } void KalmanFilter::UpdateMeasurement(const ObservationVector & observation) { const auto z = observation - c_ * model_->GetPredictedState(); const auto S = c_ * P_ * c_.transpose() + calibrations_.measurement_noise; const auto K = P_ * c_.transpose() * S.inverse(); x_ = model_->GetPredictedState() + K * z; P_ = P_ - K * S * K.transpose(); } } <file_sep>#include <iostream> #include <kalman_filter.h> #include <motion_models_factory.h> int main(void) { auto mf = mht::motion_model::MotionModelFactory(); auto cvm = std::move(mf.CreateModel(mht::motion_model::MotionModelType::CV, mht::motion_model::MotionModelBase<6>::ModelState(), 0.0F)); cvm->PredictState(0.0F); cvm->GetPredictedState(); mht::filters::FilterCalibrations fc; fc.model_type = mht::motion_model::MotionModelType::CV; fc.initial_state = mht::motion_model::MotionModelBase<6>::ModelState(); fc.initial_time_stamp = 0.0F; mht::filters::KalmanFilter kf{fc}; const auto obs = mht::filters::ObservationVector(); kf.FuseNewObservation(obs, 0.0); auto [x, P] = kf.GetFusionResult(); return EXIT_SUCCESS; }<file_sep># Set C++ standard set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_executable(track_associator_tests track_associator_test.cpp ) target_link_libraries(track_associator_tests gtest_main TrackAssociator ) add_test( NAME unit COMMAND ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}/track_associator_tests ) <file_sep>#ifndef MHT_INCLUDE_RADAR_DETECTION_H_ #define MHT_INCLUDE_RADAR_DETECTION_H_ #include "radar_detection_status.h" namespace mht::interface { struct RadarDetection { float azimuth = 0.0f; float range = 0.0f; float elevation = 0.0f; float range_rate = 0.0f; float rcs = 0.0f; float dcs = 0.0f; RadarDetectionStatus detection_status = RadarDetectionStatus::INVALID; }; }; #endif <file_sep>#include <constant_acceleration_model.h> namespace mht::motion_model { ConstantAccelerationModel::ConstantAccelerationModel(const ModelState & initial_state, float initial_time_stamp) : MotionModelBase<9>(initial_state, initial_time_stamp) { } ConstantAccelerationModel::~ConstantAccelerationModel(void) { } void ConstantAccelerationModel::PredictState(const float time_stamp) { FindTransitionMatrix(time_stamp); state_ = transition_matrix_ * state_; } void ConstantAccelerationModel::FindTransitionMatrix(const float time_stamp) { const auto tme_delta = time_stamp - time_stamp_; transition_matrix_.setIdentity(); transition_matrix_(0, 2) = tme_delta; transition_matrix_(3, 5) = tme_delta; transition_matrix_(7, 8) = tme_delta; } ConstantAccelerationModel::TransitionMatrix ConstantAccelerationModel::GetTransitionMatrix(void) { return transition_matrix_; } ConstantAccelerationModel::ModelState ConstantAccelerationModel::GetPredictedState(void) { return state_; } } <file_sep>#ifndef MHT_MHT_MOTION_MODEL_MOTION_MODEL_TYPE_H_ #define MHT_MHT_MOTION_MODEL_MOTION_MODEL_TYPE_H_ namespace mht::motion_model { enum class MotionModelType { CV = 0 }; } #endif <file_sep># Set C++ standard set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) add_executable(filters_tests kalman_filter_test.cpp ) target_link_libraries(filters_tests gtest_main Filters MotionModels ) add_test( NAME unit COMMAND ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR}/filters_tests ) <file_sep>#ifndef MHT_MHT_ASSOCIATION_INCLUDE_ASSOCIATOR_CONFIGURATION_H_ #define MHT_MHT_ASSOCIATION_INCLUDE_ASSOCIATOR_CONFIGURATION_H_ #include "association_type.h" namespace mht::track_association { struct AssociatorConfiguration { AssociatonType association_type = AssociatonType::NEAREST_NEIGHBOUR; }; } #endif <file_sep>#include <gtest/gtest.h> #include <iostream> #include "kalman_filter.h" using namespace mht::filters; using namespace mht::motion_model; TEST(KalmanFilterTests, ConstructorTest) { FilterCalibrations fc{MotionModelType::CV, ModelState(), 0.0F}; KalmanFilter kf{fc}; } TEST(KalmanFilterTests, GetTypeTest) { FilterCalibrations fc{MotionModelType::CV, ModelState(), 0.0F}; KalmanFilter kf{fc}; const auto type = kf.GetMotionModelType(); EXPECT_EQ(MotionModelType::CV, type); } TEST(KalmanFilterTests, SimplePredictionTest) { FilterCalibrations fc{MotionModelType::CV, ModelState(), 0.0F, ProcessNoiseCovariance(), MeasurementNoiseCovariance()}; for (auto i = 0; i < 6; i++) fc.process_noise(i, i) = 1.0F; for (auto i = 0; i < 3; i++) fc.measurement_noise(i, i) = 1.0F; KalmanFilter kf{fc}; auto y = ObservationVector(); y.setZero(); kf.FuseNewObservation(y, 0.0F); auto [x, P] = kf.GetFusionResult(); EXPECT_EQ(x(0), 0.0F); EXPECT_EQ(x(1), 0.0F); EXPECT_EQ(x(2), 0.0F); EXPECT_EQ(x(3), 0.0F); EXPECT_EQ(x(4), 0.0F); EXPECT_EQ(x(5), 0.0F); } <file_sep>#include "motion_models_factory.h" #include <exception> #include "constant_velocity_model.h" namespace mht::motion_model { std::unique_ptr<MotionModelBase<6>> MotionModelFactory::CreateModel(MotionModelType model_type, const MotionModelBase<6>::ModelState & initial_state, float initial_time_stamp) { switch (model_type) { case MotionModelType::CV: return std::make_unique<ConstantVelocityModel>(initial_state, initial_time_stamp); default: throw std::invalid_argument("Invalid Motion Model Type"); } } } <file_sep>#ifndef MHT_INCLUDE_RADAR_DETECTION_STATUS_H_ #define MHT_INCLUDE_RADAR_DETECTION_STATUS_H_ namespace mht::interface { enum class RadarDetectionStatus { INVALID = 0, MOVING = 1, STATIONARY = 2, STOPPED = 3 }; } #endif
1efd0e4b7c4e6069179f3b3a8660af32317d9055
[ "Markdown", "CMake", "C++" ]
34
CMake
borodziejciesla/mht
d66edeb2b0d01261ce96655b130debbdb031bc0a
353821e538998a28b99186433a4901aee04faa92
refs/heads/master
<repo_name>zycoJamie/ziz-cli<file_sep>/src/create-action.js const inquirer = require("inquirer"); const fse = require("fs-extra"); const chalk = require("chalk"); const getTemplate = require("./download"); const constants = require("./constants"); module.exports = (projectName) => { let prompts = []; if (!fse.existsSync(constants.getConfigPath())) { console.log( `${chalk.red( constants.getConfigPath() )} 路径下不存在配置文件 ${chalk.greenBright(".zizrc")}` ); console.log( `${chalk.cyanBright( "本脚手架通过配置文件动态拉取模版,请创建配置文件哦" )}` ); return; } try { const buf = fse.readFileSync(constants.getConfigPath()); const config = JSON.parse(buf.toString()); const { templateList } = config; if (!projectName || fse.existsSync(projectName)) { if (!projectName) console.log(`${chalk.red("项目名不能为空")}`); else console.log(`${chalk.red(projectName)} 已经存在,请重新输入项目名`); prompts.push({ type: "input", name: "projectName", message: "项目名:", validate(input) { if (!input) { return `${chalk.red("项目名不能为空")}`; } if (fse.existsSync(input)) { return `${chalk.red(input)} 已经存在,请重新输入项目名`; } return true; }, }); } // 项目描述 prompts.push({ type: "input", name: "description", message: "项目描述:", }); // 选择模板 prompts.push({ type: "list", message: "选择模版:", name: "template", choices: Object.keys(templateList).map((templateName) => { return { name: templateName, value: templateList[templateName] }; }), }); inquirer.prompt(prompts).then((answer) => { // 进入下载模版逻辑 getTemplate(projectName, answer, config); }); } catch (err) { console.log(err); } }; <file_sep>/src/download.js const path = require("path"); const process = require("process"); const ora = require("ora"); const download = require("download-git-repo"); const chalk = require("chalk"); const fse = require("fs-extra"); const constants = require("./constants"); const initTemplate = require("./initialize"); const { readdirSync, injectTemplate, commitEdit, logFileInfo, } = require("./util"); /** * 下载模版 * @param {string} projectName 项目名 * @param {object} option 选项 * @param {object} config 配置 */ const getTemplate = (projectName, option, config) => { projectName = projectName || option.projectName; const projectPath = path.join(process.cwd(), projectName); const downloadPath = path.join(projectPath, "cli_download"); const { gitUrl } = config; const { template } = option; const spinner = ora("正在从远程git仓库下载template"); spinner.start(); const sourcePath = `direct:${gitUrl}${template}`; // 开始下载模版 download(sourcePath, downloadPath, { clone: true }, (err) => { if (err) { spinner.color = "red"; spinner.fail(`${chalk.red("请检查git地址是否正确?😅")}`); return; } spinner.color = "green"; spinner.succeed("下载成功"); const { INJECT_FILES } = constants; const copyFiles = readdirSync(downloadPath, INJECT_FILES); // 读取要复制的文件 // 将从仓库下载的模版文件复制到项目目录,并输出文件列表、文件大小等信息 copyFiles.map((file) => { fse.copySync(path.join(downloadPath, file), path.join(projectPath, file)); logFileInfo("创建", file, projectPath); }); INJECT_FILES.map((file) => { injectTemplate( path.join(downloadPath, file), path.join(projectName, file), { ...option } ); }); // 提交注入 commitEdit(() => { INJECT_FILES.map((file) => { logFileInfo("创建", file, projectPath); // 删除下载文件cli_download fse.remove(downloadPath); // 初始化模版项目 initTemplate(projectName); }); }); }); }; module.exports = getTemplate; <file_sep>/src/main.js #! /usr/bin/env node const program = require("commander"); const createAction = require("./create-action"); const configAction = require("./config-action"); // 创建命令 // ziz create program .usage("<command> [options]") .command("create [name]") .action(createAction); // ziz config -r program .command("config") .option("-r, --register", "register your config file, typing your file path") .action(configAction); program.parse(process.argv); <file_sep>/README.md ##### 前端脚手架 当前版本 v1.0.0 通过读取配置文件设置模版列表,交互式输入项目信息,下载所选项目模版,自动化初始git仓库和安装项目依赖<file_sep>/src/util.js const fse = require("fs-extra"); const memFs = require("mem-fs"); const editor = require("mem-fs-editor"); const chalk = require("chalk"); const path = require("path"); // memFs 修改文件,并按照ejs进行解析 const store = memFs.create(); let memFsEditor = editor.create(store); /** * 同步读取目录 * @param {string} dir 目录 * @param {array} exclude 排除指定文件列表 */ function readdirSync(dir, exclude) { try { const files = fse.readdirSync(dir); const res = []; files.map((file) => { let isExclude = false; exclude.map((item) => file.indexOf(item) !== -1 ? (isExclude = true) : null ); !isExclude && res.push(file); }); return res; } catch (err) { console.log(err); return []; } } /** * 解析模版 并注入上下文 * @param {string} source 源目录 * @param {string} dest 目标目录 * @param {object} ctx ejs模版上下文 */ function injectTemplate(source, dest, ctx) { memFsEditor.copyTpl(source, dest, ctx); } /** * 提交对模版的修改 * @param {function} callback */ function commitEdit(callback) { memFsEditor.commit(() => { callback(); }); } /** * 格式化输出文件信息 * @param {string} action 操作 e.g 创建 * @param {string} file 文件名 * @param {string} filePath 文件路径 */ function logFileInfo(action, file, filePath) { const state = fse.statSync(path.join(filePath, file)); let output = `${action}${filePath}/${file}`.padEnd(100, "\040\040\040\040"); console.log( `${chalk.green("✔ ")}${chalk.green(`${output}`)}${( state.size / 1024 ).toFixed(2)} KiB` ); } module.exports = { readdirSync, injectTemplate, commitEdit, logFileInfo, }; <file_sep>/src/constants.js const os = require("os"); _CONFIG_PATH = `${os.homedir}/Desktop/.zizrc`; INJECT_FILES = ["package.json"]; // 需要ejs解析,并注入上下文的文件列表 module.exports = { // 获取配置路径 getConfigPath() { return _CONFIG_PATH; }, // 设置配置路径 setConfigPath(path) { _CONFIG_PATH = path; }, INJECT_FILES, }; <file_sep>/src/config-action.js module.exports = (projectName, option) => {}; <file_sep>/src/initialize.js const process = require("process"); const { exec } = require("child_process"); const ora = require("ora"); const chalk = require("chalk"); const path = require("path"); let projectName = ""; /** * 初始化模版项目 * @param {string} name 项目名 */ const initTemplate = (name) => { const projectPath = path.join(process.cwd(), name); projectName = name; process.chdir(projectPath); gitInit(); npmInstall(); }; // 初始化git仓库 const gitInit = () => { const gitInitSpinner = ora( `cd ${chalk.green.bold(projectName)} 目录, 执行 ${chalk.green.bold( "git init" )}` ); gitInitSpinner.start(); const subProcess = exec("git init"); subProcess.on("close", (code) => { if (+code === 0) { gitInitSpinner.color = "green"; gitInitSpinner.succeed(subProcess.stdout.read()); } else { gitInitSpinner.color = "red"; gitInitSpinner.fail(subProcess.stderr.read()); } }); }; // 安装依赖 const npmInstall = () => { const installSpinner = ora( `正在执行${chalk.green.bold("npm install")} 安装项目依赖中, 请稍后...` ); installSpinner.start(); exec("npm install", (error, stdout, stderr) => { if (error) { installSpinner.color = "red"; installSpinner.fail( chalk.red("安装项目依赖失败,请手动执行 npm install 重新安装😭") ); console.log(error); } else { installSpinner.color = "green"; installSpinner.succeed("安装成功"); console.log(chalk.green("创建项目成功!")); console.log(chalk.green("输入npm run serve启动项目")); } }); }; module.exports = initTemplate;
48ba7d3c8e6e4ede2af61ecba9606c28c90fbff1
[ "JavaScript", "Markdown" ]
8
JavaScript
zycoJamie/ziz-cli
931d1903f9045247f9628faf8664ca36662a752b
2be439939b6f2a4dd849dc2fe0e0e5d1b7377bad
refs/heads/master
<file_sep>import { Meteor } from 'meteor/meteor'; import { Songs, Versions } from '../lib/collections.js'; /* permissions (thanks to ongoworks:security) */ Security.permit(['insert', 'update','remove']) .collections([Songs]).allowInClientCode();<file_sep>![Quasar Framework logo](https://cdn.rawgit.com/quasarframework/quasar-art/863c14bd/dist/svg/quasar-logo-full-inline.svg) # quasar-template-meteor Quasar Starter Kit for Meteor (Updated 1st January 2019). Quasar 0.17.18 #### Meteor 1.8.0.2 This is a resource which will show how to install Quasar inside the Meteor framework, with Vue2 also installed. First of all, this was forked from **https://github.com/Akryum/meteor-vue2-example-routing** and then we added Quasar to that. So thankyou to Akryum for making Meteor work with Vue. Unfortunately, there is a small problem with the meteor package called akryum:vue-router2. Meteor 1.8 does not play nice with versions above akryum:vue-router2@0.2.0. So do not update to 0.2.2 for the moment. #### We no longer have to transpile Quasar ! With the arrival of **Meteor 1.7**, we just have to put a link to /node-modules/quasar-framework in the /imports folder and then add some code on the server-side to indicate that we want to ignore legacy browsers - please see setMinimumBrowserVersions() in /imports/startup/server/index.js In this way Quasar compiles normally and we no longer get 'unexpected token: export' messages.... See this link for explanations of the changes that enabled this in Meteor 1.7: https://github.com/meteor/meteor/blob/devel/History.md#v1421 Quasar have split the es6 .js file into two: - one for 'ios' - and one for 'mat' (material design - Android) This means that if you want to compile for 'ios' instead of 'mat' you will need to change your **import** from: '/node_modules/quasar-framework/dist/quasar.mat.common.js' to '/node_modules/quasar-framework/dist/quasar.ios.common.js' #### Installation **clone this repository:** ``` git clone https://github.com/quasarframework/quasar-template-meteor.git ``` **cd into the 'template' folder:** ``` cd quasar-template-meteor/template ``` **Install from npm** ``` meteor npm install ``` **Create a link to quasar-framework in the /imports directory** ``` ln -s ../node_modules/quasar-framework imports ``` (If you are doing this on *Windows* the link command is: ``` mklink /D "imports\quasar-framework" "..\node_modules\quasar-framework\" ``` - thanks to Noboxulus for working this out) **Create a link to the quasar-extras .woff files in the /public directory** This makes the material-icons stuff appear ``` ln -s ../node_modules/quasar-extras/material-icons/web-font public ``` (If you are doing this on *Windows* the link command is: ``` mklink /D "public\web-font" "..\node_modules\quasar-extras\material-icons\web-font" ``` - thanks to Noboxulus) **run meteor (still inside the template folder)** ``` meteor ``` It should eventually say: App running at: http://localhost:3000/ Point your desktop browser to that address. Then if you open Chrome or Firefox dev tools and click on the mobile phone icon you should see this: ![you should see this](mobile.png) Please refer to guide.meteor.com/mobile.html for how to launch mobile apps on IOS and Android. This project uses the Akryum projects to get Meteor working with vuejs and quasar-framework. The most useful page to consult is: https://github.com/meteor-vue/vue-meteor-tracker This is the main page for all the Meteor/Vuejs projects: https://github.com/meteor-vue/vue-meteor #### Note: The 'template' folder is necessary for the *quasar cli* command to function. All meteor commands however should only be run once you are inside the 'template' folder. This extra 'template' folder is there because quasar-framework requires it. Quasar-framework uses Webpack for its builds, but Meteor does not. This means that it is unlikely that you will be able to use *quasar cli*, for example, because it all leads up to a quasar build using webpack. To use Meteor, just cd into the 'template' folder and run all your usual meteor commands from there. **Problems:** Quasar es6 code from v0.15 was split into two: one for ios and one for material design. There may be a way to switch automatically to the correct .js file according to the platform ... <file_sep> import { Meteor } from 'meteor/meteor'; //quasar framework is based on vuejs import Vue from 'vue'; // Import the router factory import { RouterFactory, nativeScrollBehavior } from 'meteor/akryum:vue-router2' // Create router instance // See https://github.com/meteor-vue/vue-meteor/tree/master/packages/vue-router2 // - actual routes are configured in routes.js const routerFactory = new RouterFactory({ mode: 'history', scrollBehavior: nativeScrollBehavior, }) // App layout import AppLayout from '/imports/ui/AppLayout.vue'; //import Quasar globally //swap the comment on these lines if you want to compile for ios import Quasar from '/node_modules/quasar-framework/dist/quasar.mat.esm.js'; //import Quasar from '/node_modules/quasar-framework/dist/quasar.ios.esm.js'; Vue.use(Quasar, {}); //App start Meteor.startup(() => { const router = routerFactory.create(); new Vue({ router: router, render: h => h(AppLayout), }).$mount('app'); }); <file_sep>// Import the router import { RouterFactory } from 'meteor/akryum:vue-router2' // Components import Home from '/imports/ui/Home.vue' import Songbook from '/imports/ui/Songbook.vue' import Lyrics from '/imports/ui/Lyrics.vue' import Versions from '/imports/ui/Versions.vue' import Help from '/imports/ui/Help.vue' RouterFactory.configure(factory => { // Simple routes factory.addRoutes([ { path: '/', name: 'home', component: Home, }, { path: '/songbook', name: 'songbook', component: Songbook, }, { path: '/song/:id', name: 'song', component: Lyrics, meta: {layout: 'song'} }, { path: '/song/:id/versions', name: 'song-versions', component: Versions, meta: {layout: 'song'} }, { path: '/help', name: 'help', component: Help, }, ]) }) <file_sep>import { Meteor } from 'meteor/meteor'; import { Songs, Versions } from '../lib/collections.js'; Meteor.publish('songs', function(){ return Songs.find({}); }); /* Meteor.publish('versions', function(){ return Versions.find({}); });*/ Meteor.publish('files.versions.all', function () { return Versions.find().cursor; }); if (Meteor.isClient) { Meteor.subscribe('files.versions.all'); }
41833ef1fb81a1bf5781c969b4cc3cdfaa8940b4
[ "JavaScript", "Markdown" ]
5
JavaScript
fredericlb/repet2000
c71ee24926957ede1f82d993faa8b7148bdaafee
93c346f200c271f609f6c2db94d0506a40672db5
refs/heads/main
<repo_name>scottymccormick/onmyshelf<file_sep>/client/App.js import React, { Component } from "react"; class App extends Component { constructor(props) { super(props); this.state = { books: [] }; } componentDidMount() { console.log('component did the mount'); fetch('/books') .then(res => res.json()) .then(result => { console.log('successful /books call'); this.setState({ books: result.books }) }, (error) => { console.log('there was an error from the /books call'); console.log(error); }); } render() { const { name } = this.props; return ( <> <header> <h1 className="site-title"> {name} </h1> </header> <section className="shelf-container"> <ul className="shelf"> { this.state.books.map(book => { return ( <li key={book.id} className="book"> <span className="book-title"> {book.title} </span> <span className="book-author"> {`by ${book.author}`} </span> </li> ) }) } </ul> </section> </> ); } } export default App;<file_sep>/server/index.js import express from 'express'; import session from 'express-session'; import bodyParser from 'body-parser'; import path from 'path'; import './config.js'; const app = express(); const PORT = process.env.PORT || 9001; import mysqlConnection from './connection.js'; import testShelf from '../test/shelf.js'; app.use(express.static('dist')); app.use(session({ secret: process.env.SESSION_SECRET, resave: true, saveUninitialized: true })); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.get('/books', (req, res) => { const books = testShelf; res.send(books); }); app.get('/users', (req, res) => { const user = mysqlConnection.query(`SELECT username FROM user`, function(error, results, fields) { if (error) { console.log('error on users request', error.message); res.status(500).send('mysql error'); return; } res.send(results); }); }); app.listen(PORT, () => { console.log('Listening on the port', PORT); });<file_sep>/test/shelf.js const testShelf = { shelf: 'MyShelf', books: [ { id: 1, title: 'Dune', author: '<NAME>' }, { id: 2, title: 'Beloved', author: '<NAME>' }, { id: 3, title: 'How to Be an Antiracist', author: '<NAME>' }, { id: 4, title: 'Red Storm Rising', author: '<NAME>' } ] }; export default testShelf;
4861b5fc373ea36a061cf6b8314e5fdb5bdd6d23
[ "JavaScript" ]
3
JavaScript
scottymccormick/onmyshelf
f0d7e0d1c213b12e3c4bdd9acb6c71768f6f7bcb
ccc5a3952fb66a23601e40450c490c844ad1febb
refs/heads/master
<repo_name>pbinkley/bookmap<file_sep>/README.md Bookmap ======= Generate an OpenLayers-based zoomable image of all the pages of an Internet Archive book, layed out as a grid. This is a pair of bash scripts that download the JPEG2000 files from a given Internet Archive scanned book, generate a single large image containing all the pages in a grid, and produce an HTML file that gives an OpenLayers-based zoomable view of the whole book. See an example here: http://www.wallandbinkley.com/bookmap/storyofdoghisuse00ceci/openlayers.html These packages must be available on the path: - ImageMagick - [jq][1] - [gdal][2] - python To generate a view for a given IA item "abxxxx", there are two steps - run "./fetch.sh abxxxx" - this will download and unzip the JPEG2000s - run "./process.sh abxxxx" Process.sh will generate a uniform JPEG image of each page, using the most common dimensions found among the JPEG2000s. Pages that do not have these dimensions will be cropped or padded to fit. It will then use ImageMagick's montage to stitch the page images into a single image. This can take a very long time (three hours for a 244-page book on a MacBook Pro), and will initially tie up the CPU to a great extent; after a few minutes it will relax its grip and make the machine more responsive. Finally, process.sh will run GDAL to generate the tiles and the html file. They will be created in a directory named with the Internet Archive ID. The example took about three hours to process, and the generated tiles allowed nine levels of zoom and came to 2.2gb. For the example linked above, I have removed the lowest two levels, leaving 200mb of tiles, in order to save server space. The process of building the large uniform JPEG can use a lot of temporary disk space. Set a TMPDIR environment variable to point to somewhere that has room if you need to (see the [ImageMagick FAQ][3]) I have developed this under OS/X but the tools should all run on Linux, and perhaps on Windows. Note: I installed jq and gdal with Homebrew. I had trouble with gdal because of conflicts with an earlier attempt to install it from source. I also had trouble adding JPEG2000 support to ImageMagick from Homebrew, and ended up installing this package instead: http://cactuslab.com/imagemagick/ > Written with [StackEdit](https://stackedit.io/). [1]: http://stedolan.github.io/jq/ [2]: http://www.gdal.org/ [3]: http://imagemagick.sourceforge.net/http/www/FAQ.html#C1 <file_sep>/fetch.sh #!/bin/bash # assume we have an IA id as first param if [ "$1" = "" ] then echo "Usage: $0 <Internet Archvie id>" exit fi IAID=$1 echo Fetching $IAID mkdir source wget -O source/$IAID.json https://archive.org/details/$IAID?output=json DIR=`jq -r '.dir' source/$IAID.json` SERVER=`jq -r '.server' source/$IAID.json` JP2='_jp2.zip' ZIP=$IAID$JP2 if [ -e "source/$ZIP" ] then echo "source/$ZIP exists, not downloading again" else echo Fetching https://$SERVER$DIR/$ZIP wget -O source/$ZIP https://$SERVER$DIR/$ZIP fi echo Unzipping $ZIP cd source unzip $ZIP <file_sep>/process.sh #!/bin/bash # assume we have an IA id as first param if [ "$1" = "" ] then echo "Usage: $0 <Internet Archvie id>" exit fi IAID=$1 # find most common page size: #DIMS=`identify source/$IAID\_jp2/*.jp2 | awk '{ print $3; }' | sort | uniq -c | sort -n | tail -1 | awk '{ print $2; }'` DIMS=1866x2914 WIDTH=`echo $DIMS | awk -Fx '{ print $1; }'` HEIGHT=`echo $DIMS | awk -Fx '{ print $2; }'` PIXELS=$(($WIDTH * $HEIGHT)) echo Most common dimensions: $WIDTH x $HEIGHT = $PIXELS # choose dimensions, calculate todal pixels: e.g. 1866x2884 = 5381544 # use those values to generate uniform page images: echo Generating jpg images ls source/$IAID\_jp2/*.jp2 | xargs -n 1 -I {} convert {} -thumbnail $PIXELS@ -gravity center -background white -extent $DIMS `echo {} | sed 's/\//_/g'`.jpg # merge page images into master # montage tied the machine up completely: should run with increased niceness echo Generating master jpg: source/$IAID.jpg time nice montage -geometry +0+0 source/$IAID\_jp2/*.jpg source/$IAID.jpg identify source/$IAID.jpg # generate tiles # this creates a directory named after the image, containing all the tile # directories, and a file "openlayers.html" which gives a basic zoomable view gdal2tiles.py -p raster -w openlayers source/$IAID.jpg
bbe365f08ac14626b6167efbcc2a34e8c93ad777
[ "Markdown", "Shell" ]
3
Markdown
pbinkley/bookmap
1e3e0926864b86cfd89730a697ef8e94f5e77573
a667d7a5248524ccba71577970368ac819b98278
refs/heads/gh-pages
<file_sep># Academic Visual Data You can see outcome from [Academic Visual Data](https://shinsukeimai.github.io/acvis-mds/). This project is going on with [C-PIER](http://www.cpier.kyoto-u.ac.jp/).We visualize [this data](https://survey2015.symposium-hp.jp/). ## Motivation ||| |---:|:---| |対象ユーザー|学際融合のハブとなる人| |課題|どこをつなげると新しい学際融合が生まれるかわからない| |解決手法|アンケートデータから新たな繋がりが生まれそうな分野を探索できる可視化を行う| |関連データ|[学際融合教育研究推進センター](http://www.cpier.kyoto-u.ac.jp/guide/#mission)| ||| |---:|:---| |対象ユーザー|新たな研究テーマを探す研究者| |課題|自分の研究と相乗効果を生み出せそうな研究分野がわからない| |解決方法|アンケートデータから新たな繋がりが生まれそうな分野を探索できる可視化を行う| |関連データ|| ||| |---:|:---| |対象ユーザー|科研費区分を策定する人| |課題|審査区分の設け方に根拠がない| |解決方法|アンケートデータから新たな新たな区分を設定できる見識を得られる可視化を行う| |関連データ|[科学研究費助成事業(科研費)審査システム改革2018](http://www.mext.go.jp/component/a_menu/science/detail/__icsFiles/afieldfile/2016/04/22/1367694_02_1.pdf)| ## Methods - [Multi Dimensional Scaling](https://en.wikipedia.org/wiki/Multidimensional_scaling) - [Principal component analysis](https://en.wikipedia.org/wiki/Principal_component_analysis) - [Chord Diagram]() - [Word cloud]() - [t-Test]() - [k-means]() - [modularity](https://en.wikipedia.org/wiki/Modularity_(networks)) - [modularity slide](http://www.slideshare.net/komiyaatsushi/newman-6670300) ## Progress - [進捗メモ](https://shinsukeimai.github.io/acvis-mds/protress) ## Refer - [Community detection in graphs](http://digitalinterface.blogspot.jp/2013/05/community-detection-in-graphs.html) - [Quantifying social group evolution](http://www.nature.com/nature/journal/v446/n7136/pdf/nature05670.pdf) - [コミュニティ分類アルゴリズムの高速化とソーシャルグラフへの応用](http://www.slideshare.net/mosa_siru/ss-16539108) - [Finding communities in large networks](https://sites.google.com/site/findcommunities/) ## Memo ### コミュニティ分類アルゴリズム #### オーバーラップ | オーバーラップを許さない | オーバーラップを許す | |:---|:---| | - グラフ分割 | - clique percolation method | | - 階層的クラスタリング | - 線グラフ化 | | - Givan-Newman Algorithm | - Givan-Newman Algorithm の拡張 | | - モデュラリティ最適化 | - Modularityの拡張 | | - Surprise最適化 | | #### CMP(Clique Percolation Method) ### [京都大学 学際融合教育研究推進センター](http://www.cpier.kyoto-u.ac.jp/guide/) > 近年、大学の教育研究を取り巻く環境は大きく変化しており、萌芽的分野や潜在的に連携が可能な分野におけるボトムアップ型の研究および様々な教育・人材育成プログラム等、部局を超えた連携・融合の必要性はますます高まっています。これに対応するため,本学では教育や研究を目的とした時限付のグループ”ユニット”を設置し、複数の部局による分野横断型の教育研究プロジェクトを実施してきました。しかし、全学的な教育・研究組織を設置し運営する体制は、かえって連携・融合が必要とする柔軟性、機動性に欠ける場合もあり、必ずしも十分なものとは言えなくなってきていました。このような状況を踏まえ、上記のような連携・融合プロジェクトを個々に現行の部局相当組織として位置づけるのではなく、より柔軟で機動的な教育研究活動ができるよう、全学的な新センターを設置し、異分野融合を促進することになりました。そして、部局を超えた学際分野の教育研究をより促進し、本学における教育研究の活性化を図ることとなりました。 > 本学の基本理念の一つに「京都大学は、総合大学として、基礎研究と応用研究、文科系と理科系の研究の多様な発展と統合をはかる」とありますが、本センターは、この「統合をはかる」活動を中心的に行って、「多元的な課題の解決に挑戦し、地球社会の調和ある共存に貢献する」ことを目指します。総長は「大学土壌論」において、大学は、新しい学術と科学技術を生み出し、同時にそれを使う人を生み出す唯一の場であると述べられていますが、本センターは、異分野連携・融合により学際領域を開拓する場、学問を繋げて新たな学問をつくる場となることを目指します。人文・社会科学や基礎科学も共に、幅広くシーズ優先型の教育研究を推進し、学術創成と人材育成を図ることは、出口を見据えたニーズ優先型の研究を推進することであると共に、今日の大学に課せられた大きな役割であると考えます。本学の新たな土壌で知的贅沢感を醸成し、知的探検の面白さを提示することで、京都ならではのメッセージを発信していければと思います。 ### [昨今の「異分野融合の物神化」を問い、政策論かつ学問論的な理論モデルの構築とそれを踏まえた分野融合実践場の創成に挑む](http://www.natureasia.com/ja-jp/jobs/tokushu/detail/322) > 「結局、学術領域の細分化は、個々の研究者ががんばればがんばるほど進んでいくのです」。つまり、学術研究の使命であるオリジナリティーの追究はそのまま新規分野創出につながり、さらに学問的に厳密を求めるためにより狭い境界(環境)条件を設定せざるを得なくなり、結果として量産された諸分野は結局のところ細分化され過ぎて大勢があまり注目しない。特に検証や淘汰はされないままに乱立していく。」 > 「こうした学問的営為に内在する細分化特性が進行し過ぎたため、真理を追究するために単独分野では不十分であるという本質と、今日的な課題の重層化への懸念とが相まって、今“異分野融合”に期待がかかっているのです。ところが、現状ではその異分野融合そのものの理解が不足したままなので、まるで異分野を同じテーブルにつかせたら、そこで分野融合が完結するような幻想を抱いてしまっています。理論も手法もガタガタです。これらを打破するために、政策論的かつ学問論的に異分野融合の今日的な新しい理論モデルが必要であり、同時に、それを踏まえた分野越境の実践が求められています。そうしてある意味その実験場として、挑戦的に“融合・越境”を仕掛け、学内外と対話することの専門組織である学際融合教育研究推進センターが存在するのです。」 > 「異分野融合とは、異分野“衝突”の結果として生じるもので、手段ではありません。さらに言うと、最終的に異分野の知識や体験が帰着するのは個々人の内面であり、“融合”とは個々人の実践知(主に暗黙知、身体知として未言語領域に存在するもの)の言語化を通じて自身の内面で生じる啓発(気付き)」 > 「今日的な異分野融合が評価や肩書きにこだわることなく、信頼関係で成り立つ対話の“場”となれば、研究から新しい成果が生まれるはず。そういう気風を学内に醸成していきたい」 ### 学際融合と学際連携の違い ### 学際融合のニーズはどこにあるのか 例えば、科学の領域での成果を社会へ適応したいとする。社会では科学技術を受け入れられないことがある。 > 科学者が追究する真理は、社会を構成する一般の生活者には専門特化しすぎていて理解が難しいく、細分化が進めば進むほど社会の理解は得られない。 - [「社会と科学技術を結び付けるために」](https://www.jst.go.jp/crds/pdf/about/FR201405.pdf) この問題を解決する[科学技術社会論](https://ja.wikipedia.org/wiki/%E7%A7%91%E5%AD%A6%E6%8A%80%E8%A1%93%E7%A4%BE%E4%BC%9A%E8%AB%96)という研究分野がある。 ### 学際研究(プロセスと理論) #### 統合主義的学際研究 > 統合が学際活動の目標である #### 学術的専門分野 > 学術的専門分野は学者のコミュニティである。コミュニティは、どのような現象が研究されるべきかを定義し、幾つかの中心的概念・構成理論を進歩させ、一定の研究方法を持ち、研究や知見を共有するためのフォーラムを開催し、学者にキャリアパスを提供する。各専門分野は特徴的要素、つまり現象、家庭、認識論、概念、理論、方法を持つ。これらの要素によって専門分野は他分野から区別される。 memo: 「現象、家庭、認識論、概念、理論、方法」が異なれば別分野となる。研究対象とする「現象」が同じであれば連携することが多い? #### 伝統的専門分野 > - 自然科学 > - 社会科学 > - 人文学 #### 専門分野と学際性の境界線 > 専門分野と学際性の境界線は、近年の学際分野の出現とともに不鮮明になり始めている。学際分野は起源、特徴、状態、発展のレベルという点で専門分野と異なっている。 #### 構成体 > 専門分野、応用分野、学際分野は固定した不変のものではない苦、発展する社会的及び知的構成体であり、それ自体として時間に依存するものである。 memo: 「学術的専門分野は学者のコミュニティ」ということからもコミュニティの移り変わりに依存するものかな? > ジュリー・クライン(Klein 1996)は「学際性の隠れた実体」について語っている。その実体とは、例えば、医学、農学、海洋学に置いては学際性がもてはやされているが、それ自体としては名付けられていないといったものである。 > 学際性が効果的に作用するパタン > - 研究者は現存する専門分野の枠組みから主題または対象を分離する。 > - 研究者は専門分野の注意力不足により発生する知識の隙間を埋める。 > - 研究が必要量に達したら、研究者は「新しい知識空間と職業的役割を作り出すことで境界線を定義し直す」 #### 学際研究の「研究」の部分 > なぜ伝統的専門分野は「○○研究」と呼ばれないのか: 専門分野が歴史「研究」や生物「研究」と呼ばれない理由は、研究の核(つまり専門分野のカリキュラム)が十分に確立されており、研究と教育の分野として認知されているということである。 #### なぜ「研究」は学際研究の必要不可欠な部分なのか editing… <file_sep>import {FIELDS} from "./constant"; import {Field} from "./field"; export class Fields { private list: {[key: string]: Field}; constructor() { Object.keys(FIELDS).forEach((fieldNum: string) => { this.list[fieldNum] = new Field(fieldNum); }); } appendField() { } } <file_sep>export class FileLoader { constructor(d3) { this.d3 = d3; this.cacheMap = new Map(); this.loadStatus = []; } next(cb) { let promise = new Promise((resolve, reject) => { if (this.loadStatus.length === 0) { cb(); resolve(); } else { this.loadStatus[0].then(() => { cb(); resolve(); }); this.loadStatus.shift(); } }); return promise; } loadFile(path) { if (this.cacheMap.has(path)) return this.cacheMap.get(path); let promise = new Promise((resolve, reject) => { if (this.loadStatus.length === 0) { d3.json(path, (d) => { this.cacheMap.set(path, d); resolve(d); }); } else { this.loadStatus[0].then(() => { d3.json(path, (d) => { this.cacheMap.set(path, d); resolve(d); }); }); this.loadStatus.shift(); } }); this.loadStatus.push(promise); return promise; } loadFiles(paths) { return new Promise.all(paths.map(path => this.loadFile(path))); } _startLoading(promise) { this.loadStatus.push(promise); } } <file_sep>export class View { constructor(utils) { this.d3 = utils.d3; this.svg = this.d3 .select("#svg"); this.scale = 1; } setSize(height, width) { this.height = height; this.width = width; this.leftPadding = 200; this.container = this.svg .attr("width", width) .attr("height", height) .call(this.d3.behavior.zoom().scaleExtent([1, 10]).on("zoom", () => { this.container.attr("transform", `translate(${this.d3.event.translate})scale(${this.d3.event.scale})`); this.scale = this.d3.event.scale; this.d3.selectAll("circle").attr("r", d => d.r / this.scale); this.d3.selectAll("text").attr("font-size", d => 10 / this.scale + "px"); })) .append("g"); this._setScale(); } resize(height, width) { this.height = height; this.width = width; this.svg .attr("width", width) .attr("height", height); this._setScale(); } setPoints(points) { this.points = points; this._setScale(); this.texts = this.container.selectAll("text.field") .data(this.points); this.texts.exit().remove(); this.texts.enter() .append("text") .attr("class", "field"); this.circles = this.container.selectAll("circle") .data(this.points); this.circles.exit().remove(); this.circles.enter() .append("circle"); return this; } listener(targets, action, cb) { if (Array.isArray(targets)) { targets.forEach(target => { this.d3.selectAll(target).on(action, d => cb(d.index)); }); return; } this.d3.selectAll(targets).on(action, d => cb(d.index)); } renderBiplot(vecs) { let line = this.d3.svg.line() .x(d => d[0]) .y(d => d[1]); let center = [(this.width - this.leftPadding)/2 + this.leftPadding, this.height/2]; this.container.selectAll("path").data(vecs).enter().append("path"); this.container.selectAll("path").attr("d", d => { return line([ [center[0] + d.vec[0] * (this.width - this.leftPadding)/2, center[1] + d.vec[1] * this.height/2], center ]); }) .attr("stroke", "red") .attr("stroke-width", 3); this.container.selectAll("text.biplot") .data(vecs) .enter() .append("text") .attr("class", "biplot"); this.container.selectAll("text.biplot") .text(d => d.question) .attr("x", d => center[0] + d.vec[0] * (this.width - this.leftPadding)/2) .attr("y", d => center[1] + d.vec[1] * this.height/2) .attr("fill", "red") .attr("font-size", "20px"); } render(delay = 0, duration = 0) { this.container.selectAll("circle") .transition().delay(delay).duration(duration) .attr("cx", d => this.xScale(d.coord.x)) .attr("cy", d => this.yScale(d.coord.y)) .attr("r", d => d.r / this.scale) .attr("fill", d => d.fill); this.container.selectAll("text.field").text(d => d.label) .transition().delay(delay).duration(duration) .attr("x", d => this.xScale(d.coord.x)) .attr("y", d => this.yScale(d.coord.y)) .attr("fill", "gray") .attr("font-size", 10 / this.scale + "px"); } _setScale() { if (!this.points) return; this.xScale = this.d3.scale.linear() .domain([this.d3.min(this.points, p => p.coord.x), this.d3.max(this.points, p => p.coord.x)]) .range([this.leftPadding, this.width]); this.yScale = this.d3.scale.linear() .domain([this.d3.min(this.points, p => p.coord.y), this.d3.max(this.points, p => p.coord.y)]) .range([0, this.height]); } } <file_sep>import {Question} from "./question"; export class Questions { constructor(private list: Question[]) { } } <file_sep>"use strict"; class MDSViewer { constructor() { this.barWidth = 220; this.width = window.innerWidth; this.height = window.innerHeight; this.padding = 10; this.svg = d3.select("#svg") .attr("width", this.width) .attr("height", this.height) .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", () => { this.svg.attr("transform", `translate(${d3.event.translate})scale(${d3.event.scale})`); })) .append("g"); } init() { return new Promise((resolve) => { d3.json("./field.json", (error, fields) => { this.map = this.getFieldMap(fields); resolve(); }); }); } load(method) { this.method = method; this.updateTitle(); return new Promise((resolve) => { d3.json(`./output_${this.method}.json`, (error, output) => { this.points = output.result.map((point) => { let label = Object.keys(point)[0]; let coord = point[label]; return [coord[0], coord[1], label]; }); resolve(); }); }).then(() => { this.render(this.points); }); } getFieldMap(fields) { let map = new Map(); fields.forEach((fieldClass) => { fieldClass.subclasses.forEach((flds) => { Object.keys(flds.fields).forEach((fld) => { map.set(fld, { fieldClass: fieldClass.class, subfieldClass: flds.subclass, field: flds.fields[fld], fieldNum: fld }); }); }); }); return map; } render(points) { let xScale = d3.scale.linear() .domain([d3.min(points, p => p[0]), d3.max(points, (p) => p[0])]) .range([this.padding + this.barWidth, this.width - this.padding]); let yScale = d3.scale.linear() .domain([d3.min(points, p => p[1]), d3.max(points, (p) => p[1])]) .range([this.padding, this.height - this.padding]); let circles = this.svg.selectAll("circle") .data(points); circles.enter() .append("circle"); circles.exit().remove(); circles.on("mouseover", (d) => this.onMouseover(d[2])) .on("mouseout", () => this.onMouseover()) .on("click", (d) => { this.selectedLabel = d[2]; }); let texts = this.svg.selectAll("text") .data(points); texts.enter() .append("text"); texts.exit().remove(); texts.on("mouseover", d => this.onMouseover(d[2])) .on("mouseout", () => this.onMouseover()) .on("click", (d) => { this.selectedLabel = d[2]; }); circles.transition().delay(500).duration(1000) .attr("cx", d => xScale(d[0])) .attr("cy", d => yScale(d[1])) .attr("r", 3) .call(() => this.onMouseover(this.selectedLabel)); texts.text(d => d[2]) .transition().delay(500).duration(1000) .attr("x", d => xScale(d[0])) .attr("y", d => yScale(d[1])) .attr("fill", "gray") .attr("font-size", "10px") .call(() => this.onMouseover(this.selectedLabel)); } onMouseover(label) { this.selectedField = this.map.get(label); if (!this.selectedField) { return; } this.updateTitle(); d3.selectAll("circle") .attr("r", (d) => { if (label === d[2]) { return 10; } if (!this.map.get(d[2]) || !this.selectedField) return 0; if (this.map.get(d[2]).subfieldClass === this.selectedField.subfieldClass) return 5; if (this.map.get(d[2]).fieldClass === this.selectedField.fieldClass) return 3; return 0; }); } updateTitle() { if (!this.selectedField) { d3.select("#fieldNum").text("no"); d3.select("#field").text("no"); d3.select("#subfieldClass").text("no"); d3.select("#fieldClass").text("no"); return; } d3.select("#fieldNum").text(this.selectedField.fieldNum); d3.select("#field").text(this.selectedField.field); d3.select("#subfieldClass").text(this.selectedField.subfieldClass); d3.select("#fieldClass").text(this.selectedField.fieldClass); }; } const methods = [ "braycurtis_nonmetric", "chebyshev_nonmetric", "cityblock_nonmetric", "correlation_nonmetric", "dice_nonmetric", "euclidean_nonmetric", "hamming_nonmetric", "jaccard_nonmetric", "kulsinski_nonmetric", "matching_nonmetric", "rogerstanimoto_nonmetric", "russellrao_nonmetric", "sokalmichener_nonmetric", "sokalsneath_nonmetric", "sqeuclidean_nonmetric", "braycurtis", "chebyshev", "cityblock", "correlation", "dice", "euclidean", "hamming", "jaccard", "kulsinski", "matching", "rogerstanimoto", "russellrao", "sokalmichener", "sokalsneath", "sqeuclidean" ]; let initMethod = "euclidean_nonmetric"; let selector = document.getElementById("methodSelection"); selector.addEventListener("change", () => viewer.load(selector.value), false); methods.forEach((method) => { let option = document.createElement("option"); option.value = method; option.text = method; selector.appendChild(option); }); selector.value = initMethod; let viewer = new MDSViewer(); viewer.init().then(viewer.load(initMethod)); <file_sep>export class Model { constructor() {} setMetaData(d) { this.metaData = d; } getMetaData() { return this.metaData; } setCurrentView(d) { this.currentView = d; } getCurrentView() { return this.currentView; } setBiplotData(d) { this.biplot = d; } getBiplotData() { return this.biplot; } } <file_sep>export class Transformer { constructor() {} fieldMap(fields) { let map = new Map(); fields.forEach((fieldClass) => { fieldClass.subclasses.forEach((flds) => { Object.keys(flds.fields).forEach((fld) => { map.set(fld, { fieldClass: fieldClass.class, subfieldClass: flds.subclass, field: flds.fields[fld], fieldNum: fld }); }); }); }); return map; } pca(output, fields) { let X1 = output.components[0], X2 = output.components[1]; let coords = [...output.labels] .map((label, idx) => { return { label, coord: this.transformCoords(output.dataset[idx], X1, X2) }; }); return coords.map((d, idx) => { let target = fields.get(d.label); return Object.assign(d, target, {index: idx}) }); } transformCoords(values, X1, X2) { let x = 0, y = 0; values.forEach((value, idx) => { x += values[idx] * X1[idx]; y += values[idx] * X2[idx]; }); return {x, y}; } } <file_sep>import * as d3 from "d3"; import {Researcher} from "./researcher"; import {Field} from "./field"; import {Questions} from "./questions"; import {Question} from "./question"; import {Efforts} from "./efforts"; import {Effort} from "./effort"; import {Researchers} from "./researchers"; export let loader = (cb: Function) => { d3.json("./20160318_v3.json", (d: any) => { let researcherList = d.rawdata.map((researcherData: any, index: number) => { // field let field: Field = new Field(researcherData.field_n); // questions let questionList: Question[] = Object.keys(researcherData.question) .map((key :string) => { return new Question(key, researcherData.question[key]); }); let questions: Questions = new Questions(questionList); // efforts let effortList: Effort[] = Object.keys(researcherData.effort) .map((key: string) => { return new Effort(key, researcherData.effort[key]); }); let efforts = new Efforts(effortList); // keywords let keywords: string[] = researcherData.keywords; let researcher = new Researcher(index, field, questions, efforts, keywords); return researcher; }); console.log(researcherList); let researchers = new Researchers(researcherList); cb(researchers); }); }; <file_sep>import {QUESTIONS} from "./constant"; export class Question { private text: string; constructor(private key: string, private amount: number) { this.text = QUESTIONS[key]; } } <file_sep>/** * */ class Fields{ constructor(rawData){ this.rawData = rawData; let fields = new Map(); let _fields = new Map(); // let classes = new Map(); // let subclasses = new Map(); rawData.forEach((classField) => { let className = classField.class; // classes.set(className); let classFields = new Map(); classField.subclasses.forEach((subclassObj) => { // subclasses.set(subclassObj.subclass); // let subclassName = subclassObj.subclass; let subclassFields = new Map(); for (let key in subclassObj.fields){ classFields.set(key); subclassFields.set(key); fields.set(key, new Map([ ["name", subclassObj.fields[key]], ["id", key], ["className", className], ["subclassName", subclassName], ["class", classFields], ["subclass", subclassFields] ])); } }); }); for (let field of fields.values()){ let classMap = new Map(); for (let key of field.get("class").keys()) { classMap.set(key, fields.get(key)); } field.set("class", classMap); } this.fields = fields; } getField(id) { return this.fields.get(id); } getFields() { return this.fields; } getSubClasses() { } getClasses() { // class let classes = new Map(); let swap = new Map(); let prev = new Map(); for(let [key, field] of this.fields) { if (prev.get("className") !== field.get("className") && swap.size !== 0) { classes.set(prev.get("className"), new Map([ ["fields", new Map(swap)], ["subclasses", new Map()] ])); swap = new Map(); } prev = field; swap.set(key, field); } classes.set(prev.get("className"), new Map([ ["fields", new Map(swap)], ["subclasses", new Map()] ])); // subclass swap = new Map(); prev = new Map(); for(let [key, field] of this.fields) { if (prev.get("subclassName") !== field.get("subclassName") && swap.size !== 0) { classes.get(prev.get("className")) .get("subclasses") .set(prev.get("subclassName"), new Map(swap)); swap = new Map(); } prev = field; swap.set(key, field); } classes.get(prev.get("className")) .get("subclasses") .set(prev.get("subclassName"), new Map(swap)); return classes; } } /** * * @returns {Promise} */ let getFieldData = () => { d3.json("field.json", (res) => { let treeObj = { "name": "科研費細目", "children": [] }; let fieldMap = new Fields(res).getClasses(); let nodes = treeObj["children"]; for( let [key, value] of fieldMap) { let subclasses = value.get("subclasses"); let child = { "name": key, "children": [] }; for( let [key, value] of subclasses){ child.children.push({ "name": key, "children": (() => { let result = []; for( let v of value.values()){ result.push({ "name": v.get("id") + v.get("name") }); } return result; })() }); } nodes.push(child); } generateSVG(treeObj); }); }; let generateSVG = (treeObj) => { console.log(treeObj); let width = 1500, height = 10000; let padding = 500; let svg = d3.select("#svg").attr({ width: width, height: height }); let tree = d3.layout.tree().size([height-padding, width-padding]); let nodes = tree.nodes(treeObj); let links = tree.links(nodes); let diagonal = d3.svg.diagonal() .projection((d) => [d.y, d.x]); svg.selectAll(".link") .data(links) .enter() .append("path") .attr("class", "link") .attr("fill", "none") .attr("stroke", "gray") .attr("d", diagonal); let node = svg.selectAll(".node") .data(nodes) .enter() .append("g") .attr("class", "node") .attr("transform", (d) => `translate(${d.y},${d.x})`); node.append("circle") .attr("r", 4) .attr("fill", "steelblue"); node.append("text") .text((d) => d.name) .attr("y", 0); }; getFieldData();<file_sep>export class Controller { constructor(model, viewer, utils) { this.model = model; this.viewer = viewer; this.transformer = utils.transformer; this.fileLoader = utils.fileLoader; this.window = utils.window; this.d3 = utils.d3; this.viewer.setSize(this.window.innerHeight, this.window.innerWidth); this._loadFields(utils.fieldFilePaths); } loadFile_v2(path) { this.fileLoader .loadFile(path) .then(output => { let viewData = this.transformer.pca(output, this.model.getMetaData()); this._setRadial(viewData, 5); this.model.setCurrentView(viewData); let biplot = this._calcBiplotVec(output.components); this.model.setBiplotData(biplot); this.viewer.setPoints(this.model.currentView); this.viewer.render(); this.viewer.renderBiplot(this.model.getBiplotData()); this._listener(); }); return this; } loadKmeans(path) { let color = this.d3.scale.category20b(); this.fileLoader .loadFile(path) .then(output => { let nextView = this.model.getCurrentView() .map((point, index) => { return Object.assign(point, {fill: color(output.pred[index])}); }); this.model.setCurrentView(nextView); this.viewer.render(); }); } resizeWindow() { this.viewer.resize(this.window.innerHeight, this.window.innerWidth); this.viewer.render(0, 1000); this.viewer.renderBiplot(this.model.getBiplotData()); } registerSelected(func) { this.emitSelected = func; } _loadFields(path) { this.fileLoader .loadFile(path) .then(fieldMetaData => { let map = this.transformer.fieldMap(fieldMetaData); this.model.setMetaData(map); }); return this; } _calcBiplotVec(componetnts) { let vecs = componetnts[0].map((d, idx) => { return { vec: [d, componetnts[1][idx]], index: idx, question: (() => { if (0 <= idx && idx <= 61) return `A${idx}`; if (62 <= idx && idx <= 70) return `B${idx-61}`; if (71 <= idx && idx <= 78) return `C${idx-70}`; if (79 <= idx && idx <= 91) return `D${idx-78}`; })() }; }); let biplot = vecs.sort((a, b) => { if (Math.pow(a.vec[0], 2) + Math.pow(a.vec[1], 2) > Math.pow(b.vec[0], 2) + Math.pow(b.vec[1], 2)) return -1; if (Math.pow(a.vec[0], 2) + Math.pow(a.vec[1], 2) < Math.pow(b.vec[0], 2) + Math.pow(b.vec[1], 2)) return 1; return 0; }).splice(0, 20); return biplot; } _setRadial(data, r = 5) { data.forEach(datum => datum.r = r); } _listener() { this.viewer.listener(["circle"], "mouseover", index => { this.selectField(index); }); this.viewer.listener(["circle"], "mouseout", () => { this.unselect(); }); } selectField(index) { let currentView = this.model.getCurrentView(); let target = currentView[index]; if (!target) { this.unselect(); return; } this.emitSelected(target); let showText = { field: false, subfieldClass: false, fieldClass: false }; let nextView = this.model .getCurrentView() .map(d => { if (target.index === d.index) return Object.assign(d, {r: 10, label: d.field}); if (target.field === d.field) { return Object.assign(d, {r: 10, label: ""}); } if (target.subfieldClass === d.subfieldClass) { if (!showText.subfieldClass) { showText.subfieldClass = true; return Object.assign(d, {r: 6, label: d.subfieldClass}); } return Object.assign(d, {r: 6, label: ""}); } if (target.fieldClass === d.fieldClass) { if (!showText.fieldClass) { showText.fieldClass = true; return Object.assign(d, {r: 3, label: d.fieldClass}); } return Object.assign(d, {r: 3, label: ""}); } return Object.assign(d, {r: .5, label: ""}); }); this.model.setCurrentView(nextView); this.viewer.render(100, 1000); } unselect() { this.emitSelected(); let nextView = this.model .getCurrentView() .map(d => { return Object.assign(d, {r: 5, label: d.fieldNum}); }); this.model.setCurrentView(nextView); this.viewer.render(); } } <file_sep>import {Field} from "./field"; import {Questions} from "./questions"; import {Efforts} from "./efforts"; export class Researcher { constructor(private index: number, private field: Field, private questions: Questions, private efforts: Efforts, private keywords: string[]) { } } <file_sep>import {FIELDS, FIELD_CLASS, FIELD_SUBCLASS} from "./constant"; export class Field { private fieldName: string; private className: string; private subClassName: string; constructor(private num: string) { this.fieldName = FIELDS[num]; this.className = FIELD_CLASS[num]; this.subClassName = FIELD_SUBCLASS[num]; } // accessor getFieldName() {return this.fieldName; } getClassName() {return this.className; } getSubClassName() {return this.subClassName; } getNum() {return this.num; } } <file_sep>import {loader} from "./loader"; import {Researchers} from "./researchers"; loader((researchers: Researchers) => { console.log(researchers); }); <file_sep>export const QUESTION_GROUP: {[key: string]: string} = { "_A1_A2_A3_A4_A5": "研究の価値", "_A6_A7_A8": "研究とは", "_A9_A10_A11_A12_A13": "研究成果の意味", "_A14_A15_A16_A17_A18": "研究の姿勢", "_A19_A20": "知の獲得", "_A21_A22": "研究と対象", "_A23": "研究とお金", "_A24_A25_A26": "研究者コミュニティ", "_A27_A28_A29_A30_A31": "世界観", "_A32_A33_A34_A35_A36_A37": "人間の存在", "_A38": "人間の中核", "_A39_A40_A41_A42_A43_A44_A45_A46_A47_A48_A49_A50": "研究成果の評価基準", "_A51_A52": "結果とプロセス", "_A53": "一体感", "_A54_A55_A56_A57": "研究室に望まれる姿", "_A58_A59_A60_A61": "リーダーシップ", "_B1_B2_B3_B4_B5_B6": "研究に関して行っていること", "_B7_B8_B9": "主義と立ち位置の関係", "_C1_C2_C3_C4_C5_C6_C7_C8": "行動特性8つの知能(H.ガードナー)", "_D1_D2_D3_D4": "研究者コミュニティの関係性", "_D5_D6_D7": "研究者コミュニティの帰属意識", "_D8_D9_D10_D11": "研究室の特性", "_D12_D13": "論文著者" }; export const QUESTIONS: {[key: string]: string} = { "A1": "新しいもの・概念を生み出すこと", "A2": "深い理解に到達すること", "A3": "成果を活用してインパクトを与えること", "A4": "社会課題の解決", "A5": "価値中立的な科学的研究は分野を問わず可能", "A6": "生活をするための職業", "A7": "人生をかけるべきもの", "A8": "ツール", "A9": "キャリアアップのための道具", "A10": "知の探究の結果", "A11": "研究課題を達成するための1ステップ", "A12": "研究者でいることの単なる証明", "A13": "「本数稼ぎの論文」と「本気の論文」が存在する", "A14": "個人でコツコツ取り組むよりも、他者と活発に議論すること", "A15": "様々な分野とつながること", "A16": "多方面で活発に活動すること", "A17": "専門分野一筋で取り組むこと", "A18": "自らの研究において異分野融合が必要", "A19": "体系的な推論(理論、論理)である」", "A20": "知覚的経験(観察や実験)である」", "A21": "対象を完全に切り離すこと", "A22": "対象の一部であるととらえること", "A23": "私は、論文を書くためには、「お金の確保がなによりも大事」だと思う", "A24": "他分野に対する影響力が、将来的にさらに拡大してほしい", "A25": "他分野に関心を払う必要などなく、分野独自にとにかく真理を追究すること", "A26": "これからさらに社会に求められ、伸びる分野である", "A27": "全ての事象を説明できる絶対的な法則がある", "A28": "完全に要素機能(部品)から構成されたものである", "A29": "完全に有機的な生命体である", "A30": "完全に概念的なものであり自分が知覚した現象はそのまま本当に「在る」かどうかはわからない", "A31": "完全に実在しており自分が知覚した現象は実際にそれが在ることに他ならない", "A32": "個人は、「集団(社会)を構成する一単位にすぎない存在である」", "A33": "集団(社会)は、「個人のために存在する」", "A34": "人間は、「自然の一部としての存在である」", "A35": "人間は、「他の動物とは全く異なる存在である」", "A36": "人間は、「機械的に理解できる存在である」", "A37": "人間は、「社会においてはじめて人間になる存在である」", "A38": "感情や衝動、欲望よりも、理性である", "A39": "論文が著書より評価", "A40": "論文と著書が同等に評価", "A41": "翻訳がかなり評価", "A42": "社会貢献や企業・NPO等の兼業がかなり評価", "A43": "招待講演や基調講演がかなり評価", "A44": "文科省や行政等の公的な委員を務めることがかなり評価", "A45": "テキストや啓蒙書の執筆がかなり評価", "A46": "メディアの露出(テレビ、新聞等)がかなり評価", "A47": "複数分野で業績があることがかなり評価", "A48": "研究集会を自ら主催することがかなり評価", "A49": "海外で行われている新たな研究手法を国内に紹介することがなにより評価", "A50": "既存の理論の新たな解釈がなにより評価", "A51": "研究では、「結果がなにより重視される", "A52": "研究では、「プロセスがなにより重視される", "A53": "研究室(ゼミ)には一体感が絶対に必要である", "A54": "人材育成、チームワーク、メンバーの研究室への献身が重視される場", "A55": "独創的または革新的な考え方を持っていることが重視される場", "A56": "研究分野内でトップを走ること、ライバル研究室をしのぐことが重視される場", "A57": "効率性が高いことが重視される場", "A58": "後輩を育て、人々を助けることが第1だ", "A59": "革新的であり、リスクを進んでとることが第1だ", "A60": "現実的で、活動的で、結果至上主義であることが第1だ", "A61": "調整を行い、組織化し、効率的なことが第1だ", "B1": "国の政策動向に敏感であることが必須であると思い、常に注目している", "B2": "外部資金を積極的にとりに行っている", "B3": "様々な他の分野とつながりたいと思い、そのための行動をしている", "B4": "研究室(ゼミ)で仲良くしたいと思い、そのための行動をしている", "B5": "基本的に研究者2人以上のチームで行う", "B6": "1人ではなく研究を手伝ってくれる技術補佐員的な人的資源が必須である", "B7": "自らの主義を常に意識している", "B8": "自らの立ち位置を常に意識している", "B9": "所属する研究室の歴史や系譜を重視している", "C1": "私は、「音楽・リズム知能」が高いと思う", "C2": "私は、「対人的知能」が高いと思う", "C3": "私は、「論理・数学的知能」が高いと思う", "C4": "私は、「博物学的知能」が高いと思う", "C5": "私は、「視覚・空間的知能が高いと思う", "C6": "私は、「内省的知能」が高いと思う", "C7": "私は、「言語・語学知能」が高いと思う", "C8": "私は、「身体・運動感覚知能」が高いと思う", "D1": "学生(院生)の時に所属していた研究室(ゼミ)では、研究テーマを決める際には、自らの意見がなによりも重視された", "D2": "学生(院生)の時に所属していた研究室(ゼミ)では、教員と学生の関係は完全に対等であった", "D3": "所属する研究室(ゼミ)には、かなりの一体感がある", "D4": "所属する研究室(ゼミ)では、飲み会やイベントが頻繁に実施されている", "D5": "大学や所属部局への帰属意識が非常に高い", "D6": "自分の主たる学会(研究者コミュニティー)への帰属意識が非常に高い", "D7": "所属する学会は、一枚岩の団結を誇っている", "D8": "「人間的な場所であり、家族の延長のような存在である」研究室(ゼミ)では皆、価値観・考えを共有している。", "D9": "「変化が激しく、イノベーション精神に溢れた場所である」皆あえて危険を冒し、進んでリスクをとる傾向にある。", "D10": "「結果至上主義であり、計画の達成が最も大事なことだとされている」皆は各領域での目的の達成を重視する。", "D11": "「管理され、構造化されている」基本的に、形式的な手続きが人々の仕事を規定している。", "D12": "私は、基本的に論文を執筆する際に、実際に執筆していなくても、実験や調査に関わった人すべてを「著者」として載せる", "D13": "私は、基本的に論文を執筆する際に、執筆にも実験や調査にも直接関わっていない人であっても、関係者であれば「著者」として載せる" }; export const FIELDS: {[key: string]: string} = { "1001": "情報学基礎理論", "1002": "数理情報学", "1003": "統計科学", "1101": "計算機システム", "1102": "ソフトウェア", "1103": "情報ネットワーク", "1104": "マルチメディア・データベース", "1105": "高性能計算", "1106": "情報セキュリティ", "1201": "認知科学", "1202": "知覚情報処理", "1203": "ヒューマンインタフェース・インタラクション", "1204": "知能情報学", "1205": "ソフトコンピューティング", "1206": "知能ロボティクス", "1207": "感性情報学", "1301": "生命・健康・医療情報学", "1302": "ウェブ情報学・サービス情報学", "1303": "図書館情報学・人文社会情報学", "1304": "学習支援システム", "1305": "エンタテインメント・ゲーム情報学", "1401": "環境動態解析", "1402": "放射線・化学物質影響科学", "1403": "環境影響評価", "1501": "環境技術・環境負荷低減", "1502": "環境モデリング・保全修復技術", "1503": "環境材料・リサイクル", "1504": "環境リスク制御・評価", "1601": "自然共生システム", "1602": "持続可能システム", "1603": "環境政策・環境社会システム", "1651": "デザイン学", "1701": "家政・生活学一般", "1702": "衣・住生活学", "1703": "食生活学", "1801": "科学教育", "1802": "教育工学", "1901": "科学社会学・科学技術史", "2001": "文化財科学・博物館学", "2101": "地理学", "2201": "社会システム工学・安全システム", "2202": "自然災害科学・防災学", "2301": "生体医工学・生体材料学", "2302": "医用システム", "2303": "医療技術評価学", "2304": "リハビリテーション科学・福祉工学", "2401": "身体教育学", "2451": "子ども学(子ども環境学)", "2501": "生物分子化学", "2502": "ケミカルバイオロジー", "2601": "基盤・社会脳科学", "2602": "脳計測科学", "2701": "地域研究", "2801": "ジェンダー", "2851": "観光学", "2901": "哲学・倫理学", "2902": "中国哲学・印度哲学・仏教学", "2903": "宗教学", "2904": "思想史", "3001": "美学・芸術諸学", "3002": "美術史", "3003": "芸術一般", "3101": "日本文学", "3102": "英米・英語圏文学", "3103": "ヨーロッパ文学", "3104": "中国文学", "3105": "文学一般", "3201": "言語学", "3202": "日本語学", "3203": "英語学", "3204": "日本語教育", "3205": "外国語教育", "3301": "史学一般", "3302": "日本史", "3303": "アジア史・アフリカ史", "3304": "ヨーロッパ史・アメリカ史", "3305": "考古学", "3401": "人文地理学", "3501": "文化人類学・民俗学", "3601": "基礎法学", "3602": "公法学", "3603": "国際法学", "3604": "社会法学", "3605": "刑事法学", "3606": "民事法学", "3607": "新領域法学", "3701": "政治学", "3702": "国際関係論", "3801": "理論経済学", "3802": "経済学説・経済思想", "3803": "経済統計", "3804": "経済政策", "3805": "財政・公共経済", "3806": "金融・ファイナンス", "3807": "経済史", "3901": "経営学", "3902": "商学", "3903": "会計学", "4001": "社会学", "4002": "社会福祉学", "4101": "社会心理学", "4102": "教育心理学", "4103": "臨床心理学", "4104": "実験心理学", "4201": "教育学", "4202": "教育社会学", "4203": "教科教育学", "4204": "特別支援教育", "4301": "ナノ構造化学", "4302": "ナノ構造物理", "4303": "ナノ材料化学", "4304": "ナノ材料工学", "4305": "ナノバイオサイエンス", "4306": "ナノマイクロシステム", "4401": "応用物性", "4402": "結晶工学", "4403": "薄膜・表面界面物性", "4404": "光工学・光量子科学", "4405": "プラズマエレクトロニクス", "4406": "応用物理学一般", "4501": "量子ビーム科学", "4601": "計算科学", "4701": "代数学", "4702": "幾何学", "4703": "解析学基礎", "4704": "数学解析", "4705": "数学基礎・応用数学", "4801": "天文学", "4901": "素粒子・原子核・宇宙線・宇宙物理", "4902": "物性Ⅰ", "4903": "物性Ⅱ", "4904": "数理物理・物性基礎", "4905": "原子・分子・量子エレクトロニクス", "4906": "生物物理・化学物理・ソフトマターの物理", "5001": "固体地球惑星物理学", "5002": "気象・海洋物理・陸水学", "5003": "超高層物理学", "5004": "地質学", "5005": "層位・古生物学", "5006": "岩石・鉱物・鉱床学", "5007": "地球宇宙化学", "5101": "プラズマ科学", "5201": "物理化学", "5202": "有機化学", "5203": "無機化学", "5301": "機能物性化学", "5302": "合成化学", "5303": "高分子化学", "5304": "分析化学", "5305": "生体関連化学", "5306": "グリーン・環境化学", "5307": "エネルギー関連化学", "5401": "有機・ハイブリッド材料", "5402": "高分子・繊維材料", "5403": "無機工業材料", "5404": "デバイス関連化学", "5501": "機械材料・材料力学", "5502": "生産工学・加工学", "5503": "設計工学・機械機能要素・トライボロジー", "5504": "流体工学", "5505": "熱工学", "5506": "機械力学・制御", "5507": "知能機械学・機械システム", "5601": "電力工学・電力変換・電気機器", "5602": "電子・電気材料工学", "5603": "電子デバイス・電子機器", "5604": "通信・ネットワーク工学", "5605": "計測工学", "5606": "制御・システム工学", "5701": "土木材料・施工・建設マネジメント", "5702": "構造工学・地震工学・維持管理工学", "5703": "地盤工学", "5704": "水工学", "5705": "土木計画学・交通工学", "5706": "土木環境システム", "5801": "建築構造・材料", "5802": "建築環境・設備", "5803": "都市計画・建築計画", "5804": "建築史・意匠", "5901": "金属物性・材料", "5902": "無機材料・物性", "5903": "複合材料・表界面工学", "5904": "構造・機能材料", "5905": "材料加工・組織制御工学", "5906": "金属・資源生産工学", "6001": "化工物性・移動操作・単位操作", "6002": "反応工学・プロセスシステム", "6003": "触媒・資源化学プロセス", "6004": "生物機能・バイオプロセス", "6101": "航空宇宙工学", "6102": "船舶海洋工学", "6103": "地球・資源システム工学", "6104": "核融合学", "6105": "原子力学", "6106": "エネルギー学", "6201": "神経生理学・神経科学一般", "6202": "神経解剖学・神経病理学", "6203": "神経化学・神経薬理学", "6301": "実験動物学", "6401": "腫瘍生物学", "6402": "腫瘍診断学", "6403": "腫瘍治療学", "6501": "ゲノム生物学", "6502": "ゲノム医科学", "6503": "システムゲノム科学", "6601": "生物資源保全学", "6701": "分子生物学", "6702": "構造生物化学", "6703": "機能生物化学", "6704": "生物物理学", "6705": "細胞生物学", "6706": "発生生物学", "6801": "植物分子・生理科学", "6802": "形態・構造", "6803": "動物生理・行動", "6804": "遺伝・染色体動態", "6805": "進化生物学", "6806": "生物多様性・分類", "6807": "生態・環境", "6901": "自然人類学", "6902": "応用人類学", "7001": "遺伝育種科学", "7002": "作物生産科学", "7003": "園芸科学", "7004": "植物保護科学", "7101": "植物栄養学・土壌学", "7102": "応用微生物学", "7103": "応用生物化学", "7104": "生物有機化学", "7105": "食品科学", "7201": "森林科学", "7202": "木質科学", "7301": "水圏生産科学", "7302": "水圏生命科学", "7401": "経営・経済農学", "7402": "社会・開発農学", "7501": "農業工学地域環境工学・計画学", "7502": "農業環境・情報工学", "7601": "動物生産科学", "7602": "獣医学", "7603": "統合動物科学", "7701": "昆虫科学", "7702": "環境農学(含ランドスケープ科学)", "7703": "応用分子細胞生物学", "7801": "化学系薬学", "7802": "物理系薬学", "7803": "生物系薬学", "7804": "薬理系薬学", "7805": "天然資源系薬学", "7806": "創薬化学", "7807": "環境・衛生系薬学", "7808": "医療系薬学", "7901": "解剖学一般(含組織学・発生学)", "7902": "生理学一般", "7903": "環境生理学(含体力医学・栄養生理学)", "7904": "薬理学一般", "7905": "医化学一般", "7906": "病態医化学", "7907": "人類遺伝学", "7908": "人体病理学", "7909": "実験病理学", "7910": "寄生虫学(含衛生動物学)", "7911": "細菌学(含真菌学)", "7912": "ウイルス学", "7913": "免疫学", "8001": "医療社会学", "8002": "応用薬理学", "8003": "病態検査学", "8004": "疼痛学", "8005": "医学物理学・放射線技術学", "8101": "疫学・予防医学", "8102": "衛生学・公衆衛生学", "8103": "病院・医療管理学", "8104": "法医学", "8201": "内科学一般(含心身医学)", "8202": "消化器内科学", "8203": "循環器内科学", "8204": "呼吸器内科学", "8205": "腎臓内科学", "8206": "神経内科学", "8207": "代謝学", "8208": "内分泌学", "8209": "血液内科学", "8210": "膠原病・アレルギー内科学", "8211": "感染症内科学", "8212": "小児科学", "8213": "胎児・新生児医学", "8214": "皮膚科学", "8215": "精神神経科学", "8216": "放射線科学", "8301": "外科学一般", "8302": "消化器外科学", "8303": "心臓血管外科学", "8304": "呼吸器外科学", "8305": "脳神経外科学", "8306": "整形外科学", "8307": "麻酔科学", "8308": "泌尿器科学", "8309": "産婦人科学", "8310": "耳鼻咽喉科学", "8311": "眼科学", "8312": "小児外科学", "8313": "形成外科学", "8314": "救急医学", "8401": "形態系基礎歯科学", "8402": "機能系基礎歯科学", "8403": "病態科学系歯学・歯科放射線学", "8404": "保存治療系歯学", "8405": "補綴・理工系歯学", "8406": "歯科医用工学・再生歯学", "8407": "外科系歯学", "8408": "矯正・小児系歯学", "8409": "歯周治療系歯学", "8410": "社会系歯学", "8501": "基礎看護学", "8502": "臨床看護学", "8503": "生涯発達看護学", "8504": "高齢看護学", "8505": "地域看護学", "9055": "震災問題と人文学・社会科学" }; export const FIELD_CLASS: {[key: string]: string} = { "1001": "情報学", "1002": "情報学", "1003": "情報学", "1101": "情報学", "1102": "情報学", "1103": "情報学", "1104": "情報学", "1105": "情報学", "1106": "情報学", "1201": "情報学", "1202": "情報学", "1203": "情報学", "1204": "情報学", "1205": "情報学", "1206": "情報学", "1207": "情報学", "1301": "情報学", "1302": "情報学", "1303": "情報学", "1304": "情報学", "1305": "情報学", "1401": "環境学", "1402": "環境学", "1403": "環境学", "1501": "環境学", "1502": "環境学", "1503": "環境学", "1504": "環境学", "1601": "環境学", "1602": "環境学", "1603": "環境学", "1651": "複合領域", "1701": "複合領域", "1702": "複合領域", "1703": "複合領域", "1801": "複合領域", "1802": "複合領域", "1901": "複合領域", "2001": "複合領域", "2101": "複合領域", "2201": "複合領域", "2202": "複合領域", "2301": "複合領域", "2302": "複合領域", "2303": "複合領域", "2304": "複合領域", "2401": "複合領域", "2451": "複合領域", "2501": "複合領域", "2502": "複合領域", "2601": "複合領域", "2602": "複合領域", "2701": "総合人文社会", "2801": "総合人文社会", "2851": "総合人文社会", "2901": "人文学", "2902": "人文学", "2903": "人文学", "2904": "人文学", "3001": "人文学", "3002": "人文学", "3003": "人文学", "3101": "人文学", "3102": "人文学", "3103": "人文学", "3104": "人文学", "3105": "人文学", "3201": "人文学", "3202": "人文学", "3203": "人文学", "3204": "人文学", "3205": "人文学", "3301": "人文学", "3302": "人文学", "3303": "人文学", "3304": "人文学", "3305": "人文学", "3401": "人文学", "3501": "人文学", "3601": "社会科学", "3602": "社会科学", "3603": "社会科学", "3604": "社会科学", "3605": "社会科学", "3606": "社会科学", "3607": "社会科学", "3701": "社会科学", "3702": "社会科学", "3801": "社会科学", "3802": "社会科学", "3803": "社会科学", "3804": "社会科学", "3805": "社会科学", "3806": "社会科学", "3807": "社会科学", "3901": "社会科学", "3902": "社会科学", "3903": "社会科学", "4001": "社会科学", "4002": "社会科学", "4101": "社会科学", "4102": "社会科学", "4103": "社会科学", "4104": "社会科学", "4201": "社会科学", "4202": "社会科学", "4203": "社会科学", "4204": "社会科学", "4301": "総合理工", "4302": "総合理工", "4303": "総合理工", "4304": "総合理工", "4305": "総合理工", "4306": "総合理工", "4401": "総合理工", "4402": "総合理工", "4403": "総合理工", "4404": "総合理工", "4405": "総合理工", "4406": "総合理工", "4501": "総合理工", "4601": "総合理工", "4701": "数物系科学", "4702": "数物系科学", "4703": "数物系科学", "4704": "数物系科学", "4705": "数物系科学", "4801": "数物系科学", "4901": "数物系科学", "4902": "数物系科学", "4903": "数物系科学", "4904": "数物系科学", "4905": "数物系科学", "4906": "数物系科学", "5001": "数物系科学", "5002": "数物系科学", "5003": "数物系科学", "5004": "数物系科学", "5005": "数物系科学", "5006": "数物系科学", "5007": "数物系科学", "5101": "数物系科学", "5201": "化学", "5202": "化学", "5203": "化学", "5301": "化学", "5302": "化学", "5303": "化学", "5304": "化学", "5305": "化学", "5306": "化学", "5307": "化学", "5401": "化学", "5402": "化学", "5403": "化学", "5404": "化学", "5501": "工学", "5502": "工学", "5503": "工学", "5504": "工学", "5505": "工学", "5506": "工学", "5507": "工学", "5601": "工学", "5602": "工学", "5603": "工学", "5604": "工学", "5605": "工学", "5606": "工学", "5701": "工学", "5702": "工学", "5703": "工学", "5704": "工学", "5705": "工学", "5706": "工学", "5801": "工学", "5802": "工学", "5803": "工学", "5804": "工学", "5901": "工学", "5902": "工学", "5903": "工学", "5904": "工学", "5905": "工学", "5906": "工学", "6001": "工学", "6002": "工学", "6003": "工学", "6004": "工学", "6101": "工学", "6102": "工学", "6103": "工学", "6104": "工学", "6105": "工学", "6106": "工学", "6201": "総合生物", "6202": "総合生物", "6203": "総合生物", "6301": "総合生物", "6401": "総合生物", "6402": "総合生物", "6403": "総合生物", "6501": "総合生物", "6502": "総合生物", "6503": "総合生物", "6601": "総合生物", "6701": "生物学", "6702": "生物学", "6703": "生物学", "6704": "生物学", "6705": "生物学", "6706": "生物学", "6801": "生物学", "6802": "生物学", "6803": "生物学", "6804": "生物学", "6805": "生物学", "6806": "生物学", "6807": "生物学", "6901": "生物学", "6902": "生物学", "7001": "農学", "7002": "農学", "7003": "農学", "7004": "農学", "7101": "農学", "7102": "農学", "7103": "農学", "7104": "農学", "7105": "農学", "7201": "農学", "7202": "農学", "7301": "農学", "7302": "農学", "7401": "農学", "7402": "農学", "7501": "農学", "7502": "農学", "7601": "農学", "7602": "農学", "7603": "農学", "7701": "農学", "7702": "農学", "7703": "農学", "7801": "医歯薬学", "7802": "医歯薬学", "7803": "医歯薬学", "7804": "医歯薬学", "7805": "医歯薬学", "7806": "医歯薬学", "7807": "医歯薬学", "7808": "医歯薬学", "7901": "医歯薬学", "7902": "医歯薬学", "7903": "医歯薬学", "7904": "医歯薬学", "7905": "医歯薬学", "7906": "医歯薬学", "7907": "医歯薬学", "7908": "医歯薬学", "7909": "医歯薬学", "7910": "医歯薬学", "7911": "医歯薬学", "7912": "医歯薬学", "7913": "医歯薬学", "8001": "医歯薬学", "8002": "医歯薬学", "8003": "医歯薬学", "8004": "医歯薬学", "8005": "医歯薬学", "8101": "医歯薬学", "8102": "医歯薬学", "8103": "医歯薬学", "8104": "医歯薬学", "8201": "医歯薬学", "8202": "医歯薬学", "8203": "医歯薬学", "8204": "医歯薬学", "8205": "医歯薬学", "8206": "医歯薬学", "8207": "医歯薬学", "8208": "医歯薬学", "8209": "医歯薬学", "8210": "医歯薬学", "8211": "医歯薬学", "8212": "医歯薬学", "8213": "医歯薬学", "8214": "医歯薬学", "8215": "医歯薬学", "8216": "医歯薬学", "8301": "医歯薬学", "8302": "医歯薬学", "8303": "医歯薬学", "8304": "医歯薬学", "8305": "医歯薬学", "8306": "医歯薬学", "8307": "医歯薬学", "8308": "医歯薬学", "8309": "医歯薬学", "8310": "医歯薬学", "8311": "医歯薬学", "8312": "医歯薬学", "8313": "医歯薬学", "8314": "医歯薬学", "8401": "医歯薬学", "8402": "医歯薬学", "8403": "医歯薬学", "8404": "医歯薬学", "8405": "医歯薬学", "8406": "医歯薬学", "8407": "医歯薬学", "8408": "医歯薬学", "8409": "医歯薬学", "8410": "医歯薬学", "8501": "医歯薬学", "8502": "医歯薬学", "8503": "医歯薬学", "8504": "医歯薬学", "8505": "医歯薬学", "9055": "時限" }; export const FIELD_SUBCLASS: {[key: string]: string} = { "1001": "情報学基礎", "1002": "情報学基礎", "1003": "情報学基礎", "1101": "計算基盤", "1102": "計算基盤", "1103": "計算基盤", "1104": "計算基盤", "1105": "計算基盤", "1106": "計算基盤", "1201": "人間情報学", "1202": "人間情報学", "1203": "人間情報学", "1204": "人間情報学", "1205": "人間情報学", "1206": "人間情報学", "1207": "人間情報学", "1301": "情報学フロンティア", "1302": "情報学フロンティア", "1303": "情報学フロンティア", "1304": "情報学フロンティア", "1305": "情報学フロンティア", "1401": "環境解析学", "1402": "環境解析学", "1403": "環境解析学", "1501": "環境保全学", "1502": "環境保全学", "1503": "環境保全学", "1504": "環境保全学", "1601": "環境創成学", "1602": "環境創成学", "1603": "環境創成学", "1651": "デザイン学", "1701": "生活科学", "1702": "生活科学", "1703": "生活科学", "1801": "科学教育・教育工学", "1802": "科学教育・教育工学", "1901": "科学社会学・科学技術史", "2001": "文化財科学・博物館学", "2101": "地理学", "2201": "社会・安全システム科学", "2202": "社会・安全システム科学", "2301": "人間医工学", "2302": "人間医工学", "2303": "人間医工学", "2304": "人間医工学", "2401": "健康・スポーツ科学", "2451": "子ども学", "2501": "生体分子科学", "2502": "生体分子科学", "2601": "脳科学", "2602": "脳科学", "2701": "地域研究", "2801": "ジェンダー", "2851": "観光学", "2901": "哲学", "2902": "哲学", "2903": "哲学", "2904": "哲学", "3001": "芸術学", "3002": "芸術学", "3003": "芸術学", "3101": "文学", "3102": "文学", "3103": "文学", "3104": "文学", "3105": "文学", "3201": "言語学", "3202": "言語学", "3203": "言語学", "3204": "言語学", "3205": "言語学", "3301": "史学", "3302": "史学", "3303": "史学", "3304": "史学", "3305": "史学", "3401": "人文地理学", "3501": "文化人類学", "3601": "法学", "3602": "法学", "3603": "法学", "3604": "法学", "3605": "法学", "3606": "法学", "3607": "法学", "3701": "政治学", "3702": "政治学", "3801": "経済学", "3802": "経済学", "3803": "経済学", "3804": "経済学", "3805": "経済学", "3806": "経済学", "3807": "経済学", "3901": "経営学", "3902": "経営学", "3903": "経営学", "4001": "社会学", "4002": "社会学", "4101": "心理学", "4102": "心理学", "4103": "心理学", "4104": "心理学", "4201": "教育学", "4202": "教育学", "4203": "教育学", "4204": "教育学", "4301": "ナノ・マイクロ科学", "4302": "ナノ・マイクロ科学", "4303": "ナノ・マイクロ科学", "4304": "ナノ・マイクロ科学", "4305": "ナノ・マイクロ科学", "4306": "ナノ・マイクロ科学", "4401": "応用物理学", "4402": "応用物理学", "4403": "応用物理学", "4404": "応用物理学", "4405": "応用物理学", "4406": "応用物理学", "4501": "量子ビーム科学", "4601": "計算科学", "4701": "数学", "4702": "数学", "4703": "数学", "4704": "数学", "4705": "数学", "4801": "天文学", "4901": "物理学", "4902": "物理学", "4903": "物理学", "4904": "物理学", "4905": "物理学", "4906": "物理学", "5001": "地球惑星科学", "5002": "地球惑星科学", "5003": "地球惑星科学", "5004": "地球惑星科学", "5005": "地球惑星科学", "5006": "地球惑星科学", "5007": "地球惑星科学", "5101": "プラズマ科学", "5201": "基礎化学", "5202": "基礎化学", "5203": "基礎化学", "5301": "複合化学", "5302": "複合化学", "5303": "複合化学", "5304": "複合化学", "5305": "複合化学", "5306": "複合化学", "5307": "複合化学", "5401": "材料化学", "5402": "材料化学", "5403": "材料化学", "5404": "材料化学", "5501": "機械工学", "5502": "機械工学", "5503": "機械工学", "5504": "機械工学", "5505": "機械工学", "5506": "機械工学", "5507": "機械工学", "5601": "電気電子工学", "5602": "電気電子工学", "5603": "電気電子工学", "5604": "電気電子工学", "5605": "電気電子工学", "5606": "電気電子工学", "5701": "土木工学", "5702": "土木工学", "5703": "土木工学", "5704": "土木工学", "5705": "土木工学", "5706": "土木工学", "5801": "建築学", "5802": "建築学", "5803": "建築学", "5804": "建築学", "5901": "材料工学", "5902": "材料工学", "5903": "材料工学", "5904": "材料工学", "5905": "材料工学", "5906": "材料工学", "6001": "プロセス・化学工学", "6002": "プロセス・化学工学", "6003": "プロセス・化学工学", "6004": "プロセス・化学工学", "6101": "総合工学", "6102": "総合工学", "6103": "総合工学", "6104": "総合工学", "6105": "総合工学", "6106": "総合工学", "6201": "神経科学", "6202": "神経科学", "6203": "神経科学", "6301": "実験動物学", "6401": "腫瘍学", "6402": "腫瘍学", "6403": "腫瘍学", "6501": "ゲノム科学", "6502": "ゲノム科学", "6503": "ゲノム科学", "6601": "生物資源保全学", "6701": "生物科学", "6702": "生物科学", "6703": "生物科学", "6704": "生物科学", "6705": "生物科学", "6706": "生物科学", "6801": "基礎生物学", "6802": "基礎生物学", "6803": "基礎生物学", "6804": "基礎生物学", "6805": "基礎生物学", "6806": "基礎生物学", "6807": "基礎生物学", "6901": "人類学", "6902": "人類学", "7001": "生産環境農学", "7002": "生産環境農学", "7003": "生産環境農学", "7004": "生産環境農学", "7101": "農芸化学", "7102": "農芸化学", "7103": "農芸化学", "7104": "農芸化学", "7105": "農芸化学", "7201": "森林圏科学", "7202": "森林圏科学", "7301": "水圏応用科学", "7302": "水圏応用科学", "7401": "社会経済農学", "7402": "社会経済農学", "7501": "社会経済農学", "7502": "社会経済農学", "7601": "動物生命科学", "7602": "動物生命科学", "7603": "動物生命科学", "7701": "境界農学", "7702": "境界農学", "7703": "境界農学", "7801": "薬学", "7802": "薬学", "7803": "薬学", "7804": "薬学", "7805": "薬学", "7806": "薬学", "7807": "薬学", "7808": "薬学", "7901": "基礎医学", "7902": "基礎医学", "7903": "基礎医学", "7904": "基礎医学", "7905": "基礎医学", "7906": "基礎医学", "7907": "基礎医学", "7908": "基礎医学", "7909": "基礎医学", "7910": "基礎医学", "7911": "基礎医学", "7912": "基礎医学", "7913": "基礎医学", "8001": "境界医学", "8002": "境界医学", "8003": "境界医学", "8004": "境界医学", "8005": "境界医学", "8101": "社会医学", "8102": "社会医学", "8103": "社会医学", "8104": "社会医学", "8201": "内科系臨床医学", "8202": "内科系臨床医学", "8203": "内科系臨床医学", "8204": "内科系臨床医学", "8205": "内科系臨床医学", "8206": "内科系臨床医学", "8207": "内科系臨床医学", "8208": "内科系臨床医学", "8209": "内科系臨床医学", "8210": "内科系臨床医学", "8211": "内科系臨床医学", "8212": "内科系臨床医学", "8213": "内科系臨床医学", "8214": "内科系臨床医学", "8215": "内科系臨床医学", "8216": "内科系臨床医学", "8301": "外科系臨床医学", "8302": "外科系臨床医学", "8303": "外科系臨床医学", "8304": "外科系臨床医学", "8305": "外科系臨床医学", "8306": "外科系臨床医学", "8307": "外科系臨床医学", "8308": "外科系臨床医学", "8309": "外科系臨床医学", "8310": "外科系臨床医学", "8311": "外科系臨床医学", "8312": "外科系臨床医学", "8313": "外科系臨床医学", "8314": "外科系臨床医学", "8401": "歯学", "8402": "歯学", "8403": "歯学", "8404": "歯学", "8405": "歯学", "8406": "歯学", "8407": "歯学", "8408": "歯学", "8409": "歯学", "8410": "歯学", "8501": "看護学", "8502": "看護学", "8503": "看護学", "8504": "看護学", "8505": "看護学", "9055": "" }; export const FIELD: any = [ { "class": "情報学", "subclasses":[ { "subclass": "情報学基礎", "fields": { "1001": "情報学基礎理論", "1002": "数理情報学", "1003": "統計科学" } }, { "subclass": "計算基盤", "fields": { "1101": "計算機システム", "1102": "ソフトウェア", "1103": "情報ネットワーク", "1104": "マルチメディア・データベース", "1105": "高性能計算", "1106": "情報セキュリティ" } }, { "subclass": "人間情報学", "fields": { "1201": "認知科学", "1202": "知覚情報処理", "1203": "ヒューマンインタフェース・インタラクション", "1204": "知能情報学", "1205": "ソフトコンピューティング", "1206": "知能ロボティクス", "1207": "感性情報学" } }, { "subclass": "情報学フロンティア", "fields": { "1301": "生命・健康・医療情報学", "1302": "ウェブ情報学・サービス情報学", "1303": "図書館情報学・人文社会情報学", "1304": "学習支援システム", "1305": "エンタテインメント・ゲーム情報学" } } ] }, { "class": "環境学", "subclasses":[ { "subclass": "環境解析学", "fields": { "1401": "環境動態解析", "1402": "放射線・化学物質影響科学", "1403": "環境影響評価" } }, { "subclass": "環境保全学", "fields": { "1501": "環境技術・環境負荷低減", "1502": "環境モデリング・保全修復技術", "1503": "環境材料・リサイクル", "1504": "環境リスク制御・評価" } }, { "subclass": "環境創成学", "fields": { "1601": "自然共生システム", "1602": "持続可能システム", "1603": "環境政策・環境社会システム" } } ] }, { "class": "複合領域", "subclasses":[ { "subclass": "デザイン学", "fields": { "1651": "デザイン学" } }, { "subclass": "生活科学", "fields": { "1701": "家政・生活学一般", "1702": "衣・住生活学", "1703": "食生活学" } }, { "subclass": "科学教育・教育工学", "fields": { "1801": "科学教育", "1802": "教育工学" } }, { "subclass": "科学社会学・科学技術史", "fields": { "1901": "科学社会学・科学技術史" } }, { "subclass": "文化財科学・博物館学", "fields": { "2001": "文化財科学・博物館学" } }, { "subclass": "地理学", "fields": { "2101": "地理学" } }, { "subclass": "社会・安全システム科学", "fields": { "2201": "社会システム工学・安全システム", "2202": "自然災害科学・防災学" } }, { "subclass": "人間医工学", "fields": { "2301": "生体医工学・生体材料学", "2302": "医用システム", "2303": "医療技術評価学", "2304": "リハビリテーション科学・福祉工学" } }, { "subclass": "健康・スポーツ科学", "fields": { "2401": "身体教育学" } }, { "subclass": "子ども学", "fields": { "2451": "子ども学(子ども環境学)" } }, { "subclass": "生体分子科学", "fields": { "2501": "生物分子化学", "2502": "ケミカルバイオロジー" } }, { "subclass": "脳科学", "fields": { "2601": "基盤・社会脳科学", "2602": "脳計測科学" } } ] }, { "class": "総合人文社会", "subclasses": [ { "subclass": "地域研究", "fields": { "2701": "地域研究" } }, { "subclass": "ジェンダー", "fields": { "2801": "ジェンダー" } }, { "subclass": "観光学", "fields": { "2851": "観光学" } } ] }, { "class": "人文学", "subclasses":[ { "subclass": "哲学", "fields": { "2901": "哲学・倫理学", "2902": "中国哲学・印度哲学・仏教学", "2903": "宗教学", "2904": "思想史" } }, { "subclass": "芸術学", "fields": { "3001": "美学・芸術諸学", "3002": "美術史", "3003": "芸術一般" } }, { "subclass": "文学", "fields": { "3101": "日本文学", "3102": "英米・英語圏文学", "3103": "ヨーロッパ文学", "3104": "中国文学", "3105": "文学一般" } }, { "subclass": "言語学", "fields": { "3201": "言語学", "3202": "日本語学", "3203": "英語学", "3204": "日本語教育", "3205": "外国語教育" } }, { "subclass": "史学", "fields": { "3301": "史学一般", "3302": "日本史", "3303": "アジア史・アフリカ史", "3304": "ヨーロッパ史・アメリカ史", "3305": "考古学" } }, { "subclass": "人文地理学", "fields": { "3401": "人文地理学" } }, { "subclass": "文化人類学", "fields": { "3501": "文化人類学・民俗学" } } ] }, { "class": "社会科学", "subclasses":[ { "subclass": "法学", "fields": { "3601": "基礎法学", "3602": "公法学", "3603": "国際法学", "3604": "社会法学", "3605": "刑事法学", "3606": "民事法学", "3607": "新領域法学" } }, { "subclass": "政治学", "fields": { "3701": "政治学", "3702": "国際関係論" } }, { "subclass": "経済学", "fields": { "3801": "理論経済学", "3802": "経済学説・経済思想", "3803": "経済統計", "3804": "経済政策", "3805": "財政・公共経済", "3806": "金融・ファイナンス", "3807": "経済史" } }, { "subclass": "経営学", "fields": { "3901": "経営学", "3902": "商学", "3903": "会計学" } }, { "subclass": "社会学", "fields": { "4001": "社会学", "4002": "社会福祉学" } }, { "subclass": "心理学", "fields": { "4101": "社会心理学", "4102": "教育心理学", "4103": "臨床心理学", "4104": "実験心理学" } }, { "subclass": "教育学", "fields": { "4201": "教育学", "4202": "教育社会学", "4203": "教科教育学", "4204": "特別支援教育" } } ] }, { "class": "総合理工", "subclasses":[ { "subclass": "ナノ・マイクロ科学", "fields": { "4301": "ナノ構造化学", "4302": "ナノ構造物理", "4303": "ナノ材料化学", "4304": "ナノ材料工学", "4305": "ナノバイオサイエンス", "4306": "ナノマイクロシステム" } }, { "subclass": "応用物理学", "fields": { "4401": "応用物性", "4402": "結晶工学", "4403": "薄膜・表面界面物性", "4404": "光工学・光量子科学", "4405": "プラズマエレクトロニクス", "4406": "応用物理学一般" } }, { "subclass": "量子ビーム科学", "fields": { "4501": "量子ビーム科学" } }, { "subclass": "計算科学", "fields": { "4601": "計算科学" } } ] }, { "class": "数物系科学", "subclasses":[ { "subclass": "数学", "fields": { "4701": "代数学", "4702": "幾何学", "4703": "解析学基礎", "4704": "数学解析", "4705": "数学基礎・応用数学" } }, { "subclass": "天文学", "fields": { "4801": "天文学" } }, { "subclass": "物理学", "fields": { "4901": "素粒子・原子核・宇宙線・宇宙物理", "4902": "物性Ⅰ", "4903": "物性Ⅱ", "4904": "数理物理・物性基礎", "4905": "原子・分子・量子エレクトロニクス", "4906": "生物物理・化学物理・ソフトマターの物理" } }, { "subclass": "地球惑星科学", "fields": { "5001": "固体地球惑星物理学", "5002": "気象・海洋物理・陸水学", "5003": "超高層物理学", "5004": "地質学", "5005": "層位・古生物学", "5006": "岩石・鉱物・鉱床学", "5007": "地球宇宙化学" } }, { "subclass": "プラズマ科学", "fields": { "5101": "プラズマ科学" } } ] }, { "class": "化学", "subclasses":[ { "subclass": "基礎化学", "fields": { "5201": "物理化学", "5202": "有機化学", "5203": "無機化学" } }, { "subclass": "複合化学", "fields": { "5301": "機能物性化学", "5302": "合成化学", "5303": "高分子化学", "5304": "分析化学", "5305": "生体関連化学", "5306": "グリーン・環境化学", "5307": "エネルギー関連化学" } }, { "subclass": "材料化学", "fields": { "5401": "有機・ハイブリッド材料", "5402": "高分子・繊維材料", "5403": "無機工業材料", "5404": "デバイス関連化学" } } ] }, { "class": "工学", "subclasses":[ { "subclass": "機械工学", "fields": { "5501": "機械材料・材料力学", "5502": "生産工学・加工学", "5503": "設計工学・機械機能要素・トライボロジー", "5504": "流体工学", "5505": "熱工学", "5506": "機械力学・制御", "5507": "知能機械学・機械システム" } }, { "subclass": "電気電子工学", "fields": { "5601": "電力工学・電力変換・電気機器", "5602": "電子・電気材料工学", "5603": "電子デバイス・電子機器", "5604": "通信・ネットワーク工学", "5605": "計測工学", "5606": "制御・システム工学" } }, { "subclass": "土木工学", "fields": { "5701": "土木材料・施工・建設マネジメント", "5702": "構造工学・地震工学・維持管理工学", "5703": "地盤工学", "5704": "水工学", "5705": "土木計画学・交通工学", "5706": "土木環境システム" } }, { "subclass": "建築学", "fields": { "5801": "建築構造・材料", "5802": "建築環境・設備", "5803": "都市計画・建築計画", "5804": "建築史・意匠" } }, { "subclass": "材料工学", "fields": { "5901": "金属物性・材料", "5902": "無機材料・物性", "5903": "複合材料・表界面工学", "5904": "構造・機能材料", "5905": "材料加工・組織制御工学", "5906": "金属・資源生産工学" } }, { "subclass": "プロセス・化学工学", "fields": { "6001": "化工物性・移動操作・単位操作", "6002": "反応工学・プロセスシステム", "6003": "触媒・資源化学プロセス", "6004": "生物機能・バイオプロセス" } }, { "subclass": "総合工学", "fields": { "6101": "航空宇宙工学", "6102": "船舶海洋工学", "6103": "地球・資源システム工学", "6104": "核融合学", "6105": "原子力学", "6106": "エネルギー学" } } ] }, { "class": "総合生物", "subclasses":[ { "subclass": "神経科学", "fields": { "6201": "神経生理学・神経科学一般", "6202": "神経解剖学・神経病理学", "6203": "神経化学・神経薬理学" } }, { "subclass": "実験動物学", "fields": { "6301": "実験動物学" } }, { "subclass": "腫瘍学", "fields": { "6401": "腫瘍生物学", "6402": "腫瘍診断学", "6403": "腫瘍治療学" } }, { "subclass": "ゲノム科学", "fields": { "6501": "ゲノム生物学", "6502": "ゲノム医科学", "6503": "システムゲノム科学" } }, { "subclass": "生物資源保全学", "fields": { "6601": "生物資源保全学" } } ] }, { "class": "生物学", "subclasses":[ { "subclass": "生物科学", "fields": { "6701": "分子生物学", "6702": "構造生物化学", "6703": "機能生物化学", "6704": "生物物理学", "6705": "細胞生物学", "6706": "発生生物学" } }, { "subclass": "基礎生物学", "fields": { "6801": "植物分子・生理科学", "6802": "形態・構造", "6803": "動物生理・行動", "6804": "遺伝・染色体動態", "6805": "進化生物学", "6806": "生物多様性・分類", "6807": "生態・環境" } }, { "subclass": "人類学", "fields": { "6901": "自然人類学", "6902": "応用人類学" } } ] }, { "class": "農学", "subclasses":[ { "subclass": "生産環境農学", "fields": { "7001": "遺伝育種科学", "7002": "作物生産科学", "7003": "園芸科学", "7004": "植物保護科学" } }, { "subclass": "農芸化学", "fields": { "7101": "植物栄養学・土壌学", "7102": "応用微生物学", "7103": "応用生物化学", "7104": "生物有機化学", "7105": "食品科学" } }, { "subclass": "森林圏科学", "fields": { "7201": "森林科学", "7202": "木質科学" } }, { "subclass": "水圏応用科学", "fields": { "7301": "水圏生産科学", "7302": "水圏生命科学" } }, { "subclass": "社会経済農学", "fields": { "7401": "経営・経済農学", "7402": "社会・開発農学", "7501": "農業工学地域環境工学・計画学", "7502": "農業環境・情報工学" } }, { "subclass": "動物生命科学", "fields": { "7601": "動物生産科学", "7602": "獣医学", "7603": "統合動物科学" } }, { "subclass": "境界農学", "fields": { "7701": "昆虫科学", "7702": "環境農学(含ランドスケープ科学)", "7703": "応用分子細胞生物学" } } ] }, { "class": "医歯薬学", "subclasses": [ { "subclass": "薬学", "fields": { "7801": "化学系薬学", "7802": "物理系薬学", "7803": "生物系薬学", "7804": "薬理系薬学", "7805": "天然資源系薬学", "7806": "創薬化学", "7807": "環境・衛生系薬学", "7808": "医療系薬学" } }, { "subclass": "基礎医学", "fields": { "7901": "解剖学一般(含組織学・発生学)", "7902": "生理学一般", "7903": "環境生理学(含体力医学・栄養生理学)", "7904": "薬理学一般", "7905": "医化学一般", "7906": "病態医化学", "7907": "人類遺伝学", "7908": "人体病理学", "7909": "実験病理学", "7910": "寄生虫学(含衛生動物学)", "7911": "細菌学(含真菌学)", "7912": "ウイルス学", "7913": "免疫学" } }, { "subclass": "境界医学", "fields": { "8001": "医療社会学", "8002": "応用薬理学", "8003": "病態検査学", "8004": "疼痛学", "8005": "医学物理学・放射線技術学" } }, { "subclass": "社会医学", "fields": { "8101": "疫学・予防医学", "8102": "衛生学・公衆衛生学", "8103": "病院・医療管理学", "8104": "法医学" } }, { "subclass": "内科系臨床医学", "fields": { "8201": "内科学一般(含心身医学)", "8202": "消化器内科学", "8203": "循環器内科学", "8204": "呼吸器内科学", "8205": "腎臓内科学", "8206": "神経内科学", "8207": "代謝学", "8208": "内分泌学", "8209": "血液内科学", "8210": "膠原病・アレルギー内科学", "8211": "感染症内科学", "8212": "小児科学", "8213": "胎児・新生児医学", "8214": "皮膚科学", "8215": "精神神経科学", "8216": "放射線科学" } }, { "subclass": "外科系臨床医学", "fields": { "8301": "外科学一般", "8302": "消化器外科学", "8303": "心臓血管外科学", "8304": "呼吸器外科学", "8305": "脳神経外科学", "8306": "整形外科学", "8307": "麻酔科学", "8308": "泌尿器科学", "8309": "産婦人科学", "8310": "耳鼻咽喉科学", "8311": "眼科学", "8312": "小児外科学", "8313": "形成外科学", "8314": "救急医学" } }, { "subclass": "歯学", "fields": { "8401": "形態系基礎歯科学", "8402": "機能系基礎歯科学", "8403": "病態科学系歯学・歯科放射線学", "8404": "保存治療系歯学", "8405": "補綴・理工系歯学", "8406": "歯科医用工学・再生歯学", "8407": "外科系歯学", "8408": "矯正・小児系歯学", "8409": "歯周治療系歯学", "8410": "社会系歯学" } }, { "subclass": "看護学", "fields": { "8501": "基礎看護学", "8502": "臨床看護学", "8503": "生涯発達看護学", "8504": "高齢看護学", "8505": "地域看護学" } } ] }, { "class": "時限", "subclasses": [ { "subclass": "", "fields": { "9055": "震災問題と人文学・社会科学" } } ] } ]; <file_sep><!doctype html> <html> <head> <title>Academic Visual Data</title> <meta charset="UTF-8"> <link rel="stylesheet" href="./assets/style/bootstrap.css"> </head> <body> <div class="jumbotron"> <div class="container"> <h1>Academic Visual Data</h1> <p class="lead"> 学術分野の文化を可視化する </p> <p> This project is going on with <a href="http://www.cpier.kyoto-u.ac.jp/" target="_blank">C-PIER</a>. The creator of this visualization is <a href="http://shinsukeimai.github.io/" target="_blank">Shinsuke IMAI</a>. </p> </div> </div> <div class="container"> <h2>Academic Field Visualization App</h2> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <img src="./assets/img/academic_field_visualization.png" style="width: 100%; padding: 10px" > </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <h4>どういったアプリケーションか</h4> <p> 研究者から集められた研究領域に関するアンケートを可視化し、研究分野間で比較できるアプリケーション。 共同プロジェクトを進める時、メンバー同士の慣習を知ることで円滑に共同作業を行える。 本アプリケーションは、二つの分野に属する研究者がお互いの差異を知るために用いることを想定している。 </p> <h4>手法</h4> <p> ワードクラウド、ドーナツグラフ、レーダーチャート </p> <!--<h4>参考</h4>--> <hr> <a href="https://acvis.herokuapp.com/" class="btn btn-lg btn-default" target="_blank" > Launch App </a> <span>* ユーザー名とパスワードが必要です。</span> </div> </div> <div style="padding-bottom: 50px"></div> <h2>Academic Field Relation</h2> <div class="row"> <div class="col-md-12"> <div class="col-md-6"> <img src="./assets/img/keywords_v1.png" style="width: 80%" > </div> <div class="col-md-6"> <h4>どういったアプリケーションか</h4> <p>研究者があげた研究キーワードを元に可視化。このグラフから本来あるべき学術分野の分類が見えてくるかもしれない。</p> <h4>手法</h4> <p>Word Cloud</p> <h4>利用データ</h4> <p>アンケードデータ(研究キーワード)</p> <hr> <a href="./keyword-relation" class="btn btn-lg btn-default" target="_blank" > Launch App </a> </div> </div> <div class="col-md-12" style="padding-bottom: 25px"></div> <div class="col-md-12"> <div class="col-md-6"> <img src="./assets/img/chord_diagram_visualization_v4.png" style="width: 80%" > </div> <div class="col-md-6"> <h4>どういったアプリケーションか</h4> <p>どの学術分野との関係が強いですかという問いを可視化したグラフ。このグラフから本来あるべき学術分野の分類が見えてくるかもしれない。</p> <h4>手法</h4> <p>Chord Diagram</p> <h4>利用データ</h4> <p>アンケードデータ(自分が近いと思う分野)</p> <hr> <a href="./chord-diagram-bundle" class="btn btn-lg btn-default" target="_blank" > Launch App v4 </a> <a href="./force-layout" class="btn btn-lg btn-default" target="_blank" > Launch App force-layout </a> </div> </div> <div class="col-md-12" style="padding-bottom: 25px"></div> <div class="col-md-12"> <div class="col-md-6"> <img src="./assets/img/chord_diagram_visualization_v3.png" style="width: 80%" > </div> <div class="col-md-6"> <h4>どういったアプリケーションか</h4> <p>どの学術分野の質問回答が似ているを探り出すことができる。任意を複数の質問項目を選択し、学術分野間の近いものがChord Diagram上で線が結ばれる。</p> <h4>手法</h4> <p>重心距離、Chord Diagram</p> <h4>利用データ</h4> <p>アンケードデータ(4段階評価項目)</p> <hr> <a href="./chord-diagram-bundle/v3" class="btn btn-lg btn-default" target="_blank" > Launch App v3 </a> </div> </div> <div class="col-md-12" style="padding-bottom: 25px"></div> <div class="col-md-12"> <div class="col-md-6"> <img src="./assets/img/chord_diagram_visualization_v2.png" style="width: 80%" > </div> <div class="col-md-6"> <h4>どういったアプリケーションか</h4> <p>どの学術分野の質問回答が似ているを探り出すことができる。任意の質問項目を選択し、学術分野間の近いものがChord Diagram上で線が結ばれる。</p> <h4>手法</h4> <p>t検定、Chord Diagram</p> <h4>利用データ</h4> <p>アンケードデータ(4段階評価項目)</p> <hr> <a href="./chord-diagram-bundle/v2" class="btn btn-lg btn-default" target="_blank" > Launch App v2 </a> </div> </div> <div class="col-md-12" style="padding-bottom: 25px"></div> <div class="col-md-12"> <div class="col-md-6"> <img src="./assets/img/chord_diagram_visualization_v1.png" style="width: 80%" > </div> <div class="col-md-6"> <h4>どういったアプリケーションか</h4> <p>どの学術分野の質問回答が似ているを探り出すことができる。学術分野間の近いものがChord Diagram上で線が結ばれる。</p> <h4>手法</h4> <p>t検定、Chord Diagram</p> <h4>利用データ</h4> <p>アンケードデータ(4段階評価項目)</p> <hr> <a href="./chord-diagram-bundle/v1" class="btn btn-lg btn-default" target="_blank" > Launch App v1 </a> </div> </div> </div> <div style="padding-bottom: 50px"></div> <h2>2D Mapping Visualization</h2> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" > <img src="./assets/img/pca.png" style="width: 80%" > </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" > <h4>どういったアプリケーションか</h4> <p>主成分分析を用い、質問回答の類似距離を2次元上にプロットしている。インタラクティブに学術分野のフィルタリングができる。</p> <h4>手法</h4> <p>PCA、Scatter plot、k-means、Biplot</p> <h4>利用データ</h4> <p>アンケードデータ(4段階評価項目)</p> <hr> <a href="./pca" class="btn btn-lg btn-default" target="_blank" > Launch PCA App </a> </div> </div> <div style="padding-bottom: 25px"></div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" > <img src="./assets/img/mds.png" style="width: 80%" > </div> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12" > <h4>どういったアプリケーションか</h4> <p>多次元尺度構成法を用い、質問回答の類似距離を2次元上にプロットしている。インタラクティブに学術分野のフィルタリングができる。</p> <h4>手法</h4> <p>MDS、Scatter plot</p> <h4>利用データ</h4> <p>アンケードデータ(4段階評価項目)</p> <hr> <a href="./mds" class="btn btn-lg btn-default" target="_blank" > Launch MDS App </a> <a href="./mds-selectable" class="btn btn-lg btn-default" target="_blank" > Launch MDS Selectable App </a> </div> </div> <div style="padding-bottom: 50px"></div> <h2>Progress</h2> <p> <a href="./progress">progress</a> </p> </div> <footer style="background-color: #eee; padding-top: 20px; padding-bottom: 20px; margin-top: 20px;" > <div class="container"> <p>view on <a href="https://www.google.co.jp/intl/ja/chrome/browser/desktop/index.html" target="_blank">chrome</a></p> </div> </footer> </body> </html> <file_sep>export class Effort { constructor(private key: string, private amount: number) { // this.text = EFFORT[key]; } } <file_sep>import {Researcher} from "./researcher"; export class Researchers { constructor(private list: Researcher[]) { } }<file_sep>import {Effort} from "./effort"; export class Efforts { constructor(private list: Effort[]) { } getEfforts() { return this.list; } } <file_sep>"use strict"; class MDSViewer { constructor() { this.barWidth = 220; this.width = window.innerWidth; this.height = window.innerHeight; this.padding = 10; this.svg = d3.select("#svg") .attr("width", this.width) .attr("height", this.height) .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", () => { this.svg.attr("transform", `translate(${d3.event.translate})scale(${d3.event.scale})`); })) .append("g"); } init() { return new Promise((resolve) => { d3.json("./field.json", (error, fields) => { this.map = this.getFieldMap(fields); resolve(); }); }); } load(method) { this.method = method; this.updateTitle(); return new Promise((resolve) => { d3.json(`./${this.method}.json`, (error, output) => { console.log(output); this.points = output.result.map((point) => { return [point.coord[0], point.coord[1], point.field_num]; }); resolve(); }); }).then(() => { this.render(this.points); }); } getFieldMap(fields) { let map = new Map(); fields.forEach((fieldClass) => { fieldClass.subclasses.forEach((flds) => { Object.keys(flds.fields).forEach((fld) => { map.set(fld, { fieldClass: fieldClass.class, subfieldClass: flds.subclass, field: flds.fields[fld], fieldNum: fld }); }); }); }); return map; } render(points) { let xScale = d3.scale.linear() .domain([d3.min(points, p => p[0]), d3.max(points, (p) => p[0])]) .range([this.padding + this.barWidth, this.width - this.padding]); let yScale = d3.scale.linear() .domain([d3.min(points, p => p[1]), d3.max(points, (p) => p[1])]) .range([this.padding, this.height - this.padding]); let circles = this.svg.selectAll("circle") .data(points); circles.enter() .append("circle"); circles.exit().remove(); circles.on("mouseover", (d) => this.onMouseover(d[2])) .on("mouseout", () => this.onMouseover()) .on("click", (d) => { this.selectedLabel = d[2]; }); let texts = this.svg.selectAll("text") .data(points); texts.enter() .append("text"); texts.exit().remove(); texts.on("mouseover", d => this.onMouseover(d[2])) .on("mouseout", () => this.onMouseover()) .on("click", (d) => { this.selectedLabel = d[2]; }); circles.transition().delay(500).duration(1000) .attr("cx", d => xScale(d[0])) .attr("cy", d => yScale(d[1])) .attr("r", 3) .call(() => this.onMouseover(this.selectedLabel)); texts.text(d => d[2]) .transition().delay(500).duration(1000) .attr("x", d => xScale(d[0])) .attr("y", d => yScale(d[1])) .attr("fill", "gray") .attr("font-size", "10px") .call(() => this.onMouseover(this.selectedLabel)); } onMouseover(label) { this.selectedField = this.map.get(label); if (!this.selectedField) { return; } this.updateTitle(); d3.selectAll("circle") .attr("r", (d) => { if (label === d[2]) { return 10; } if (!this.map.get(d[2]) || !this.selectedField) return 0; if (this.map.get(d[2]).subfieldClass === this.selectedField.subfieldClass) return 5; if (this.map.get(d[2]).fieldClass === this.selectedField.fieldClass) return 3; return 0; }); } updateTitle() { if (!this.selectedField) { d3.select("#fieldNum").text("no"); d3.select("#field").text("no"); d3.select("#subfieldClass").text("no"); d3.select("#fieldClass").text("no"); return; } d3.select("#fieldNum").text(this.selectedField.fieldNum); d3.select("#field").text(this.selectedField.field); d3.select("#subfieldClass").text(this.selectedField.subfieldClass); d3.select("#fieldClass").text(this.selectedField.fieldClass); }; } const methods = [ "A1-A2-A3-A4-A5-euclidean", "A1-A2-euclidean", "A10-A11-A12-A13-A9-euclidean", "A14-A15-A16-A17-A18-euclidean", "A19-A20-euclidean", "A21-A22-euclidean", "A23-euclidean", "A24-A25-A26-euclidean", "A27-A28-A29-A30-A31-euclidean", "A32-A33-A34-A35-A36-A37-euclidean", "A38-euclidean", "A39-A40-A41-A42-A43-A44-A45-A46-A47-A48-A49-A50-euclidean", "A51-A52-euclidean", "A53-euclidean", "A54-A55-A56-A57-euclidean", "A58-A59-A60-A61-euclidean", "A6-A7-A8-euclidean", "B1-B2-B3-B4-B5-B6-euclidean", "B7-B8-B9-euclidean", "C1-C2-C3-C4-C5-C6-C7-C8-euclidean", "D1-D2-D3-D4-euclidean", "D10-D11-D8-D9-euclidean", "D12-D13-euclidean", "D5-D6-D7-euclidean" ]; let initMethod = methods[0]; let selector = document.getElementById("methodSelection"); selector.addEventListener("change", () => viewer.load(selector.value), false); methods.forEach((method) => { let option = document.createElement("option"); option.value = method; option.text = method; selector.appendChild(option); }); selector.value = initMethod; let viewer = new MDSViewer(); viewer.init().then(viewer.load(initMethod)); <file_sep>import {FileLoader} from "./file-loader"; import {Transformer} from "./transformer"; import {Model} from "./model"; import {Controller} from "./controller"; import {View} from "./view"; const model = new Model(); const viewer = new View({d3}); const utils = { transformer: new Transformer(), fileLoader: new FileLoader(d3), fieldFilePaths: "./field.json", window: window, d3: d3 }; const controller = new Controller(model, viewer, utils); controller .loadFile_v2("./output_pca.json"); controller.registerSelected((target) => { if (target) { document.getElementById("fieldNum").textContent = target.fieldNum; document.getElementById("field").textContent = target.field; document.getElementById("fieldClass").textContent = target.fieldClass; document.getElementById("subfieldClass").textContent = target.subfieldClass; return; } document.getElementById("fieldNum").textContent = "non"; document.getElementById("field").textContent = "non"; document.getElementById("fieldClass").textContent = "non"; document.getElementById("subfieldClass").textContent = "non"; }); controller.fileLoader.next(() => { let fieldSelector = document.getElementById("fieldSelection"); let option = document.createElement("option"); option.text = "---"; fieldSelector.appendChild(option); let fields = controller.model.getMetaData(); fields.forEach((fieldObj) => { let option = document.createElement("option"); option.value = fieldObj.fieldNum; option.text = `[${fieldObj.fieldNum}] ${fieldObj.field} - ${fieldObj.fieldClass}`; fieldSelector.appendChild(option); }); fieldSelector.addEventListener( "change", () => { let currentView = model.getCurrentView(); let targets = currentView.filter(d => d.fieldNum === fieldSelector.value); if (targets.length === 0) { controller.unselect(); return; } controller.selectField(targets[0].index); }, false ); }); // cluster let clusterSelector = document.getElementById("clusterSelection"); let option = document.createElement("option"); option.text = "---"; clusterSelector.appendChild(option); [2,3,4,5,6,7,8,9, 10,11,12,13,14,15,16,17,18,19, 20,21,22,23,24,25,26,27,28,29, 30,31,32,33,34,35,36,37,38,39, 40,41,42,43,44,45,46,47,48,49, 50,51,52,53,54,55,56,57,58,59, 60,61,62,63,64,65,66,67,68,69] .forEach(i => { let option = document.createElement("option"); option.value = `./assets/output_kmeans_cluster_${i}.json`; option.text = `cluster=${i}`; clusterSelector.appendChild(option); }); clusterSelector.addEventListener( "change", () => { controller.loadKmeans(clusterSelector.value); }, false ); // Resize event let queue; let wait = 100; window.addEventListener("resize", () => { clearTimeout(queue); queue = setTimeout(() => { controller.resizeWindow(); }, wait) });
221ce0781f8317840e0234a8bac192b86f1eebb9
[ "Markdown", "TypeScript", "JavaScript", "HTML" ]
22
Markdown
shinsukeimai/acvis-mds
46a4da1b29109b751ba44367d5ca1bea5c63a670
3257371132dd8f2063fb901f7e234b516a995fd0
refs/heads/master
<repo_name>Niall47/React<file_sep>/05-state-and-lifecycle/src/components/DeepState.js import React from 'react'; export default class DeepState extends React.Component { constructor() { super(); // This is different from the counter component is that person is an object not a primative data type this.state = { person: {name: 'Niall', age: 28} } this.handleButtonClick = this.handleButtonClick.bind(this); } handleButtonClick() { // Mutations are shallow // React will update the person reference but does not look at the object // The new person state now references an object that only contains name, age has been lost // Mutations are merged at the top level only, so quote will be unaffected // this.setState({person: {name: 'Thomas'}}); // How to mutate the person object's name so that age is unaffected // This will work in a class component (but not when using hooks) // if we want to guarantee the the comp. will be re-rendered // We must mutate the reference and not the object referenced // Dont do this // this.state.person.name = "Thomas"; // this.setState({person: this.state.person}); // You could do this // but it is unneccesarily verbose // this.setState({person: {name: 'Thomas', age: this.state.person.age}}) // Here we are copying the object, changing a value and passing it to the setState method // We should be using the version of setState that accepts a handler function! // We are accessing the person object directly, but we can't be sure it is still current this.setState({person: {...this.state.person, name: 'Dave'}}) // The golden rule of state // Treat your state as if it immutable // We alwasy should be using spread to copy the array and change the state with the new copy } render() { const {name, age} = this.state.person; return ( <div> <p> My name is {name} and I am {age} years old </p> <button onClick={this.handleButtonClick} className="btn btn-primary">Change the person's name</button> </div> ) } }<file_sep>/03 -jsx/src/App.js import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import LeagueTable from './LeagueTable.js' const myArray = ['word1', 'word2']; // const jsx = null; // if (myArray) { // jsx = myArray.map(el => <p>{el}</p>) // } export default function App() { return ( <div className='container'> <LeagueTable /> {/* We need to ensure the array has a value so we use the inline if statement to decide */} {/* Boolenas or null will render nothing */} {/* {myArray.map(el => <p>{el}</p>)} */} {/* render myArray if it exists or render nothing */} {myArray ? myArray.map(el => <p>{el}</p>) : null} {/* if the thing on the left is true the thing on the right is returned */} {myArray && myArray.map(el => <p>{el}</p>)} {/* if the thing on the left is false the thing on the right it returned */} {myArray || <p>myArrayisEmpty</p>} </div> ); } <file_sep>/my-beer-app/src/components/NewBeer.js import React, {Component} from 'react'; export default class NewBeer extends Component { constructor(props) { super(props); console.log(props); } handleSubmit(event) { alert(this.state.value); } render() { return ( <div className="container"> <h1 className="display-4 mt-4 mb-4">Beers and stuff</h1> <hr /> <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> <NewBeer beer={'dsfs'}/> </div> // return <p>I tried a new beer: {this.props.beer}</p> ); } }<file_sep>/closures.js // Closures are behind React Hooks // a closure is a function that captures a ref to a lexically scoped variable let global = 'global'; function f() { let local = 'local'; } function getClosure () { let lexical = 0; // The returned function is a closure // it captures a ref to a variable declared in the parent scope return function() { return lexical++; } } const closure = getClosure(); // The function maintains a reference to the object between invocations // The function has state console.log(closure()); console.log(closure()); // A hacky version of useState function useState(initValue) { let state = {value: initValue}; function setState(newValue){ state.value = newValue; } return [state, setState]; } const [counter, setCounter] = useState(0) console.log(counter) setCounter(counter.value + 1) console.log(counter)<file_sep>/my-beer-app/src/components/BeerConsumed.js import React, {Component} from 'react'; export default class BeerConsumed extends Component { constructor(props) { super(props); console.log(props); } render() { return <p>I tried a new beer: {this.props.beer}</p> } }<file_sep>/05-state-and-lifecycle/src/components/QuoteGenerator.js import React from 'react'; const quotes = [ "You've got to capture as much of the room sound as possible. That's the very essence of it. - <NAME>", "Life is a pigsty. - Morrissey", "I used to think anyone doing anything weird was weird. Now I know that it is the people that call others weird that are weird. - McCartney", "The rock and roll business is pretty absurd, but the world of serious music is much worse. - Zappa", "America: It's like Britain, only with buttons. - Ringo" ]; export default class QuoteGenerator extends React.Component { constructor(){ super(); this.state = { quote: "Songwriting is a bitch. And then it has puppies - <NAME>" } this.newQuote = this.newQuote.bind(this); } newQuote() { // Ripped from SO, this.setState({quote: quotes[Math.floor(Math.random() * quotes.length)]}); } render() { return( <div> <h1>{this.state.quote}</h1> <button onClick={this.newQuote} className="btn btn-primary">Feed Me Quotes</button> </div> ) } }<file_sep>/09-hooks/src/App.js import React from 'react'; import Counter from './components/Counter'; import DeepState from './components/DeepState'; import 'bootstrap/dist/css/bootstrap.min.css'; import Lifecycyle from './components/lifecycle'; import ReducerFunctionV2 from './components/ReducerFunctionV2'; export default function App() { return ( <div className="container"> <h1 className="display-4 mt-4 mb-4">Hooks</h1> <hr /> <ReducerFunctionV2 /> </div> ); } <file_sep>/09-hooks/src/components/lifecycle.js import React, {useEffect, useState} from 'react'; export default function Lifecycyle(props){ const [time, setTime] = useState(new Date().toLocaleTimeString()) // side effects shoudl NOt be performed in the main body of the function // they will be executed everytime the component is re-rendered // setInterval(() => setTime(new Date().toLocaleTimeString()), 1000) // the solution is to use useEffect // The callback passed to useEffect will be executed after EVERY re-render (by default) // It is effectivley equivilent to a componentDidUpdate in a class component (by default) // the optional second argument is a list of dependencies // dependencies are items of state or props, changes to which should result in the effect being re-executed // In this case the effect is not dependant on anything and so should not re-execuste after the first time round useEffect(() => { const intervalId = setInterval(() => setTime(new Date().toLocaleTimeString())) // You can return a function that will be executed before the effect is applied next time return () =>{clearInterval(intervalId);} }, []); // note the second arg is an empty array return (<p>The current time is: {time}</p>); }<file_sep>/05-state-and-lifecycle/src/components/lifting-state-up/child.js import React from 'react' export default class Child extends React.Component { constructor() { super(); this.state = {command: ''}; } handleFeedMe() { this.props.onFeedMe('Hello') } render() { // Typically an event is handled by a handler in this class // But we can lift state/data from child to parent by calling on the parent const {onFeedMe} = this.props; const {onCleanMe} = this.props; const {onPayMe} = this.props; return ( <div> <button onClick={this.handleFeedMe} className="btn btn-primary">Feed Me</button> <button onClick={onCleanMe} className="btn btn-primary">Clean Me</button> <button onClick={onPayMe} className="btn btn-primary">Pay Me</button> </div> ); } }<file_sep>/03 -jsx/src/LeagueTable.js import React from 'react'; const table = [ {name: 'Geoff', wins: '2', losses: '1'}, {name: 'Jeff', wins: '5', losses: '1'}, {name: 'Jeffery', wins: '4', losses: '1'} ]; export default function LeagueTable(){ return ( <div> <h3>League Table</h3> <table className="table table-striped"> <thead> <tr> <th>Team Name</th> <th>Wins</th> <th>Losses</th> </tr> </thead> <tbody> {table.map(tableRow => { return ( <tr> <td>{tableRow.name}</td> <td>{tableRow.wins}</td> <td>{tableRow.losses}</td> </tr> ); })} </tbody> </table> </div> ); }<file_sep>/05-state-and-lifecycle/src/components/AsyncStateMutation.js import React from 'react'; export default class AsyncStateMutation extends React.Component { constructor() { super(); this.state = {counter: 0}; this.handleButtonClick = this.handleButtonClick.bind(this); } handleButtonClick(){ // Each subsequent call to setState does not wait for the previous one to complete // If the mutation is dependent on the previous value // you should not mutate the state like this // this.setState({counter: this.state.counter +1}); // this.setState({counter: this.state.counter +1}); // this.setState({counter: this.state.counter +1}); // The solution is to use the version of setState that accepts a function // to return an object from an arrow function it must be wrapped in round brackets this.setState((previousState, currentProps) => ({counter: previousState.counter + 1})); this.setState((previousState, currentProps) => ({counter: previousState.counter + 1})); this.setState((previousState, currentProps) => ({counter: previousState.counter + 1})); } render() { const {counter} = this.state; return( <div> <p> Counter: {counter} </p> <button onClick={this.handleButtonClick} className="btn btn-primary"> Increment</button> </div> ) } }<file_sep>/04-components-and-props/src/components/composition.js import React from 'react' export class Book extends React.Component { render () { const {title, auther} = this.props; return ( <span>{title} by {auther}</span> ); } } // Composition describes a HAS-A relationship // i.e. a LibraryBook HAS-A Book export class LibraryBook extends React.Component { render () { const {title, auther} = this.props; return ( <div> {/* Calling the super class render method */} <Book title={title} author={author}/> <button>Loan</button> </div> ) } }<file_sep>/my-beer-appv2/src/App.js import React from 'react'; import {BrowserRouter, Link, Route, Switch} from 'react-router-dom'; import 'bootstrap/dist/css/bootstrap.min.css' import BeerContainer from './components/BeerContainer'; import NewBeerForm from './components/NewBeerForm'; import BeerList from './components/BeerList' const style = { ul: { listStyleType: 'none', paddingLeft: 0 } , li: { display: 'inline-block', padding: '1em', border: '1px solid grey' } } function HomePage() { return <p>Home Page</p>; } export default function App() { const {ul, li} = style; return ( <BrowserRouter> <div className="container"> <h1 className="display-4 mt-4 mb-4">React Router</h1> <hr /> <ul style={ul}> <li style={li}><Link to="/">Home</Link></li> <li style={li}><Link to="/list">Beer List</Link></li> <li style={li}><Link to="/new">Add New Beer</Link></li> <li style={li}><Link to="/container">Beer Container</Link></li> </ul> <Switch> <Route exact path="/"><HomePage /></Route> <Route path="/list"><BeerList /></Route> <Route path="/new"><NewBeerForm /></Route> <Route path="/container"><BeerContainer /></Route> </Switch> </div> </BrowserRouter> // <div className='container' > // <h1 className='display-4 mt-4 mb-4'> My Beers</h1> // <hr/ > // <BeerContainer /> // {/* <NewBeerForm /> // <BeerList beers={['fosters', 'stella', 'bud']}/> */} // </div> ); } <file_sep>/09-hooks/src/components/ReducerFunctionV2.js import React, { useReducer } from 'react'; export default function ReducerFunctionV2(props) { const reducer = (previousState, action) => { switch (action.type) { case 'increment': return {...previousState, counter: previousState.counter + previousState.step}; case 'decrement': return {...previousState, counter: previousState.counter - previousState.step}; case 'changeStep': return {...previousState, step: action.payload}; default: return previousState; } } const initState = {counter: 0, step: 1} const [state, dispatch] = useReducer(reducer, initState); const {counter, step} = state; return ( <> <p>Counter: {counter}</p> <IncrementForm step={step} dispatch={dispatch}/> </> ) } const IncrementForm = (props) => { const {step, dispatch} = props; return ( <> <input type="number" value={step} onChange={e => dispatch({type: 'changeStep', payload: e.target.value})} placeholder='Increment By' /> <button onClick={() => dispatch({type: 'increment'})} className='btn btn-primary'>Increment</button> </> ) }<file_sep>/my-beer-appv2/src/components/NewBeerForm.js import React from 'react'; export default class NewBeerForm extends React.Component { constructor() { super(); this.state = {newBeer: ''} this.handleNewBeerChange = this.handleNewBeerChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleNewBeerChange(event) { this.setState({newBeer: event.target.value}) } handleSubmit(event) { event.preventDefault(); // We are calling the handler in the parent component // it will add the new beer to its array of beers // and in doing so trigger a re-render of the BeerList component this.props.onNewBeer(this.state.newBeer); } render() { const {newBeer} = this.state; return( <form onSubmit={this.handleSubmit} className='mb-3'> <div className='form-group'> <label>New Beer</label> <input type="text" value={newBeer} onChange={this.handleNewBeerChange} className="form-control"/> </div> <button className="btn btn-primary">Add</button> </form> ); } }<file_sep>/array-methods.js // the map method is used alot in react // it transforms an array and creates a new array from existing one // each value in a given array is mapped onto a new value which is added to a new array const nums = [1,2,3,4,5]; // the .map method accepts a function, the function will be called for each element in the array // the return value is added to the new array // function square(num){ // return num * num // } // const squares = nums.map(square); // console.log(squares) const squares2 = nums.map(num => num * num); console.log(squares2) // the orignal array should be unchanged // the filter method accepts a function // it will be called for each value in the array // the return value (boolean) determines if that value is added to the array const oddNums = nums.filter(n => n % 2 != 0) console.log(oddNums)<file_sep>/data-fetcher/src/components/Books.js import React, { useEffect, useState } from 'react'; export default function Books(props) { const [books, setBooks] = useState([]); useEffect(() => { fetch('http://localhost:4000/books') .then(response => response.json()) .then(books => setBooks(books)) }, []); return ( <> <BookList books={books}/> </> ); } const BookList = props => { const {books} = props; return ( <ul> {books && books.map(book => <li key={book.id}>{book.title}</li>)} </ul> ) }<file_sep>/04-components-and-props/src/App.js import React from 'react'; import ReactDOM from 'react-dom' import MyFunctionCompnent from './components/myFunctionComponent'; import MyClassComponent from './components/myClassComponent'; import ChangingPropFunctionComponent from './components/ChangingPropFunctionComponent'; // This is a react component (custom html element) // It is the apps root component // all other components will be rendered within it // a component is a class or a function that renders/returns JSX // it must be named using TitleCase // a component may be passed props (custom HTML attributes) // A prop is data that is input into a component by its parent component // props are the mechanisem by which data is passed down the tree (DOM) // Props cannot be modified by the component they are passed to // Props can be modified by the parent // A changing prop triggers a rerender of the component recieving the prop export default function App() { return ( <div className="container"> <h1 className="display-4 mt-4 mb-4">React App Template</h1> <hr /> <MyFunctionCompnent number="42"/> <MyClassComponent words={['dsfs', 'dsfsfs']}/> <div id="changingPropsDiv"> </div> {/* <ChangingPropFunctionComponent /> */} </div> ); } const p1 = 'Descartes' const q1 = "I am" const p2 = 'Danton' const q2 = "Eat shit" setTimeout(() => { ReactDOM.render(<ChangingPropFunctionComponent person={p1} quote={q1}/>, document.querySelector('#changingPropsDiv')); }, 3000); setTimeout(() => { ReactDOM.render(<ChangingPropFunctionComponent person={p2} quote={q2}/>, document.querySelector('#changingPropsDiv')); }, 9000);<file_sep>/my-beer-app/src/App.js import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import NewBeer from './components/NewBeer'; export default function App() { <NewBeer /> } <file_sep>/09-hooks/src/components/ReducerFunctionV1.js import React, { useReducer } from 'react'; // state management on a large scale is hard // your app is likely to have a lot of state; // -UI state, e.g. themes, language, sort & filter options // - user state, e.g. current user. authorisation // - server data. e.g. data that you've fetched from an API // Much of this state will be managed by container/stateful/fat components // changes to state are often affected by various components not only container components // app state tends to be distributed widely across the app and that creates a maintenence challenge // it is particularly difficult when many disparate components are interested in the same data // the purpose of tools like useReducer and Redux is to centralise state managment // and to enable many components to effect changes on the app state export default function ReducerFunctionV1(props) { // the reducer is responsible for transforming the state // it must return a new version of the state // the reducer accepts two arguments // 1. the previous state // 2. an action object // action objects typically have two props: type and a payload const reducer = (previousState, action) => { console.log('reducer called') console.log(previousState) console.log(action) switch (action.type) { case 'increment': // We are returning a copy of the state with a changed counter // typically the stae will be composed of multiple branches return {...previousState, counter: previousState.counter + 1} case 'decrement': return {...previousState, counter: previousState.counter - 1} default: return previousState; } } const initState = {counter: 0} // useReducer accepts two args: // 1. a reducer function; it is responsible for transforming the state // 2. The initial state; an object compose of one of more props // useReducer returns an array comprising of two elements // 1. the state; an object // 2. a dispatch function; it is repsonsible for iniiating state transformations const [state, dispatch] = useReducer(reducer, initState); const {counter} = state; return ( <> <p>Counter: {counter}</p> {/* don't call the reducer directly instead call the dispatch function and pass it an action object it will then call the reducer which will transform state your handlers should no longer perform state transformations that work is now centralised */} <button onClick={() => dispatch({type: 'increment'})} className='btn btn-primary'>Increment Counter</button> <button onClick={() => dispatch({type: 'decrement'})} className='btn btn-primary'>Decrement Counter</button> </> ) }<file_sep>/truthy-falsey.js // everything in js can be converted to a boolean // meaning everything is either truthy / falsey console.log(Boolean(null)); //null = false console.log(Boolean('')); //empty string = false console.log(Boolean(NaN)); //not a number = false console.log(Boolean([])); //empty array = true console.log(Boolean({})); //empty object = true console.log(Boolean(() => {})); //empty function = true<file_sep>/09-hooks/src/components/Counter.js import React, {useState} from 'react'; // we can write this function as a fat arrow function like this // but cant default export it // const Counter = props => { // } export default function Counter(props) { // the useStatefunction is a hook // All hooks (including custom) are prefixed 'use' // useState accepts a value representing the initial state // useState returns an array comprising two elements: // We are assigning values in the array // counter is the items state (in this case a number called counter) // setCounter is a setter function for updating the state // just like setState the setter has two implementations // 1: accpets a new value, used where the new value IS NOTdependent on the old // 2: accepts a function, used where the new value IS dependent on the old const [counter, setCounter] = useState(0); // const [] let newNum = 0; // We could declare the function here and call it from the jsx // But its easier to write it inline with a fat arrow // const handleButtonClick = event => setCounter(counter + 1); return ( // the empty tags are a REACT fragmnet // saves us from litering the HTML with unnecessary divs <> <p>Counter: {counter}</p> <label> Number: <br/> <input type='number' onChange={newNum + 1} /> </label> <button onClick={() => setCounter(newNum)} className='btn btn-primary'>Increment Counter</button> </> ); }<file_sep>/08-react-router/src/App.js import React from 'react'; import {BrowserRouter, Link, Route, Switch} from 'react-router-dom'; import 'bootstrap/dist/css/bootstrap.min.css'; // This is a react component (custom html element) // It is the apps root component // all other components eill be rendered within it const style = { ul: { listStyleType: 'none', paddingLeft: 0 } , li: { display: 'inline-block', padding: '1em', border: '1px solid grey' } } function HomePage() { return <p>Home Page</p>; } function AboutPage() { return <p> About Page</p> } function ContactPage() { return <p> Contact Page</p> } export default function App() { const {ul, li} = style; return ( // Your links and linked components must be wrapped in a browser router <BrowserRouter> <div className="container"> <h1 className="display-4 mt-4 mb-4">React Router</h1> <hr /> <ul style={ul}> <li style={li}><Link to="/">Home</Link></li> <li style={li}><Link to="/about">About</Link></li> <li style={li}><Link to="/contact">Contact</Link></li> </ul> <Switch> {/* Your linked componets will be redered here only one component will be rendered depending on which one has a path matching current address Be Aware that react does partial matching by default which means that '/about' matches '/'*/} <Route exact path="/"><HomePage /></Route> <Route path="/about"><AboutPage /></Route> <Route path="/contact"><ContactPage /></Route> </Switch> </div> </BrowserRouter> ); } <file_sep>/state.js //Every JS object may have state and/or behavior // state: sn object's data attributes // this object has a name and age state // It also has talk as a behviour p1 = { name: 'Niall', age: 47, // The 'this' keyword is not bound correctly when using an arrow function talk: function(){ console.log(`hello, My name is ${this.name}`) } }; class Person { constructor(name, age) { this.name = name; this.age = age; } talk() { console.log(`hello, My name is ${this.name}`); } } const p2 = new Person('Niall', 47); p2.talk();<file_sep>/shallow-vs-deep-copy.js // Values vs references const num = 42; let numCopy = num; numCopy += 1; console.log(num) console.log(numCopy) let obj = {num: 42}; let shallowObjCopy = obj // Since ES6 we can use the spread operator to create a deep(ish) copy // You get a copy of the object but if the object contains references to other object they will not be updated let deepObjcopy = {...obj}; let deepObjcopy = {num: obj.num}; person = {name: 'struate', age: 20} let deepPersonCopy = {...person, name: 'sadasf'} console.log(deepPersoncopy) // This is how we force react to update the object and re-render person = {...person, name: 'Dave'};<file_sep>/my-beer-appv2/src/components/BeerContainer.js import React from 'react'; import BeerList from './BeerList'; import NewBeerForm from './NewBeerForm'; // This is a container/stateful/fat component // It has state and doesnt; do any rendering of its own // rather it delegates the rendering to presentational components // this is the parent of the presentational components export default class BeerContainer extends React.Component { constructor() { super(); this.state = {beers: []}; this.handleNewBeer = this.handleNewBeer.bind(this); } componentDidMount() { // Called after first render // Its returns a json string from storage so we need to parse throught the string to return it back to an array const beersFromStorage = JSON.parse(localStorage.getItem('beers')); console.log(beersFromStorage) if (beersFromStorage) { this.setState({beers: beersFromStorage}) } } componentDidUpdate() { // everytime a new beer is added the component will be re-renderd and this method will be called // this is the safest place to update local storage localStorage.setItem('beers', JSON.stringify(this.state.beers)) } // setting state will trigger a re-render of this component // That will set new props on the BeerList which will trigger a re-render of that component also handleNewBeer(newBeer) { this.setState((prevState, props) => ({beers: [...prevState.beers, newBeer]})); } render() { return ( <div> <NewBeerForm onNewBeer={this.handleNewBeer}/> <BeerList beers={this.state.beers}/> </div> ) } }<file_sep>/05-state-and-lifecycle/src/components/lifting-state-up/parent.js import React from 'react' import Child from './Child' export default class Parent extends React.Component { constructor(){ super(); } handleFeedMe(){ console.log('Feed Me') } handleCleanMe(){ console.log('Clean Me') } handlePayMe(){ console.log('Pay Me') } render() { // We are passing handler functions to the child as props // In the child, onFeedMe is a ref to the handleFeedMe function return <Child onFeedMe={this.handleFeedMe} onCleanMe={this.handleCleanMe} onPayMe={this.handlePayMe}/>; } }<file_sep>/react-app-template/src/App.js import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; // This is a react component (custom html element) // It is the apps root component // all other components eill be rendered within it export default function App() { return ( <div className="container"> <h1 className="display-4 mt-4 mb-4">React App Template</h1> <hr /> </div> ); }
ce534c7ea386a64448410b015ca799769ae919cc
[ "JavaScript" ]
28
JavaScript
Niall47/React
3f0c614be58ca98d127a7143f68035fb6254a5bc
dfd8bfe13d8cbfbd7b361495cd600721b4a0c7de
refs/heads/master
<file_sep>from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^taller2$', views.index, name='index'), url(r'^$', views.inicio), url(r'^grafo$', views.grafo, name='mygraph'), url(r'^Taller3$', views.taller3, name='taller3'), ] <file_sep># Create your views here. from django.shortcuts import render from django.http import HttpResponseRedirect,HttpResponse from django.http import JsonResponse import os import sys import json import glob reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') def inicio(request): return render(request, 'inicio.html') def index(request): return render(request, "index.html", {}) def grafo(request): return render(request, "grafo.html") def taller3(request): return render(request, "taller3.html")
86d35597b86e79f131bd3a6a8113deacb5d6d0af
[ "Python" ]
2
Python
FrancyPinedaB77/PlantillaDjango
d438f37021625401fb84e48514352fd295872533
d6aa5c65643a08a54896d9d03a73d808c61554c6
refs/heads/master
<repo_name>pennennolde/numerical_analysis<file_sep>/src/math2/Hilbert.java package math2; public class Hilbert { public static void main(String[] args) { // Hilbert行列 A=(a_ij), a_ij=1/(i+j-1) を作成 int n = 5; // 行列サイズ double A[][] = new double[n][n]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { A[i][j] = 1.0/((i+1)+(j+1)-1.0); } } Calc.printMat(A); } } <file_sep>/src/math2/Condition_Number.java package math2; public class Condition_Number { public static void main(String[] args) { // 条件数 κ_∞(A) = (||A||_∞)*(||A^(-1)||_∞) double A[][] = {{6, 1, 1, 1, 0}, {1, 7, 1, 1, 1}, {0, 1, 8, 1, 1}, {0, 0, 1, 9, 1}, {0, 0, 0, 1, 10}}; double κ = Calc.Condition_Number(A); System.out.println("Condition_Number = " + κ); /* int n = A.length; double E[][] = new double[n][n]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(i==j) { E[i][j] = 1.0; } else { E[i][j] = 0.0; } } } double originA[][] = new double[n][n]; // 後であってるか確認するための for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { originA[i][j] = A[i][j]; } } // LU分解 double α = 0.0; for(int k=0; k<n; k++) { for(int i=k+1; i<n; i++) { α = A[i][k]/A[k][k]; A[i][k] = α; for(int j=k+1; j<n; j++) { A[i][j] = A[i][j]-α*A[k][j]; } // b[i] = b[i]-α*b[k]; } } Calc.printMat(A); System.out.println(); // XとYを用いず、AとEだけで行う方法 for(int i=0; i<n; i++) { // (1)前進代入 Ly=b → Ly_i=e_i for(int k=0; k<n; k++) { for(int j=0; j<k; j++) { E[k][i] = E[k][i]-A[k][j]*E[j][i]; } } // (2)後退代入 Ux=y → Ux_i=y_i for(int k=n-1; k>=0; k--) { for(int j=k+1; j<n; j++) { E[k][i] = E[k][i]-A[k][j]*E[j][i]; } E[k][i] = E[k][i]/A[k][k]; } } System.out.println(Calc.matNormInf(E)*Calc.matNormInf(originA)); */ } } <file_sep>/src/math2/WinterReport2015_Z.java package math2; public class WinterReport2015_Z { public static void main(String[] args) { // Z = ωT + (1-ω)I をパラメータω毎に求める double D[][] = {{6.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 7.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 8.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 9.0, 0.0}, {0.0, 0.0, 0.0, 0.0, 10.0}}; double E[][] = {{0.0, 0.0, 0.0, 0.0, 0.0}, {1.0, 0.0, 0.0, 0.0, 0.0}, {0.0, 1.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0, 0.0}, {0.0, 0.0, 0.0, 1.0, 0.0}}; double F[][] = {{0.0, 1.0, 1.0, 1.0, 0.0}, {0.0, 0.0, 1.0, 1.0, 1.0}, {0.0, 0.0, 0.0, 1.0, 1.0}, {0.0, 0.0, 0.0, 0.0, 1.0}, {0.0, 0.0, 0.0, 0.0, 0.0}}; // (D+E)^(-1) double Inv[][] = Calc.LU_Inverse(Calc.addMat(D, E)); double T[][] = Calc.multipleMat(Inv, F); for(int i=0; i<T.length; i++) { for(int j=0; j<T.length; j++) { T[i][j] = -1*T[i][j]; } } for(double ω=0.0; ω<2.1; ω+=0.1) { System.out.println("ω= " + ω); double Z1[][] = new double[T.length][T.length]; for(int i=0; i<T.length; i++) { for(int j=0; j<T.length; j++) { Z1[i][j] = ω*T[i][j]; } } double Z2[][] = new double[T.length][T.length]; for(int i=0; i<T.length; i++) { for(int j=0; j<T.length; j++) { if( i==j ) { Z2[i][j] = 1.0-ω; }else if( i!=j ) { Z2[i][j] = 0.0; } } } double Z[][] = Calc.addMat(Z1, Z2); //System.out.print(/*"matNorm1= " + */Calc.matNorm1(Z)); //System.out.print(/*"matNormInf= " + */Calc.matNormInf(Z)); //System.out.print(","); // Zの共役転置行列 double Zt[][] = new double[Z.length][Z.length]; for(int i=0; i<T.length; i++) { for(int j=0; j<T.length; j++) { Zt[i][j] = Z[j][i]; } } double W[][] = new double[Z.length][Z.length]; W = Calc.multipleMat(Zt, Z); // べき乗法 → 絶対値最大の固有値を求める // たぶんできてる int N = 10000000; double ε = 1.0e-10; double x_old[] = new double[W.length]; double x_new[] = new double[W.length]; int iter = 0; int ell = 0; double norm = 0.0; double λ_old = 0.0; double λ_new = 0.0; for(int i=0; i<W.length; i++) { x_old[i] = Math.random(); } while( iter<N) { double x_norm2 = Calc.vecNorm2(x_old); for(int i=0; i<W.length; i++) { x_old[i] /= x_norm2; } for(int i=0; i<W.length; i++) { x_new[i] = Calc.matVec(W, x_old)[i]; } for(int i=0; i<W.length; i++) { if( Math.abs(x_old[0]) < Math.abs(x_old[i]) ) { ell = i; x_old[0] = x_old[i]; } } λ_new = x_new[ell]/x_old[ell]; norm = Math.abs(λ_new - λ_old)/Math.abs(λ_new); if( norm<ε ) { //System.out.println("breakします。"); break; } for(int i=0; i<W.length; i++) { x_old[i] = x_new[i]; } λ_old = λ_new; iter++; } if( iter==N ) { System.out.println("収束しませんでした。"); } double x_norm2 = Calc.vecNorm2(x_new); for(int i=0; i<T.length; i++) { x_new[i] /= x_norm2; } System.out.println("反復回数: iter= " + iter); //System.out.println("絶対値最大固有値: λ_new=" + Math.abs(λ_new)); //System.out.print("固有ベクトル: x[]_new= "); //Calc.printVec(x_new); //System.out.println(); System.out.print(Math.pow(Math.abs(λ_new), 0.50) + ","); System.out.println(); } } } <file_sep>/src/math/Secant.java package math; public class Secant { public static void main(String[] args) { double x0 = 5.0; double x1 = 6.0; double ε = 1.0e-10; int Nmax = 50; double xk = x0; double xk1 = x1; System.out.println("初期値x_0= " + xk); System.out.println("初期値x_1= " + xk1); for(int k=0; k<=Nmax; k++) { if(k==Nmax) { System.out.println("収束しませんでした."); break; } //double xk2 = xk-func(xk)*(xk-xk1)/(func(xk)-func(xk1)); double xk2 = xk1-func(xk1)*(xk-xk1)/(func(xk)-func(xk1)); System.out.println("x_" + (k+2) + "= " + xk2); if( //Math.abs(func(xk2))<ε // 残差 Math.abs((xk1-xk2)/xk2)<ε // 相対誤差 ) { System.out.print("許容誤差内に収まりました. "); System.out.print("近似解はx_" + (k+2) + "になります. "); System.out.println((k+1) + "回反復しました."); break; } xk = xk1; xk1 = xk2; } System.out.println("終了します."); } static double func(double x) { //double y = x*x*x -4.0*x*x +13.0*x/4.0 -3.0/4.0; double y = Math.sin(x)/(x-1.0); return y; } } <file_sep>/src/math/BisectionalMethod.java package math; public class BisectionalMethod { public static void main(String[] args) { /* * 計算が終了したときの区間は、 * |b-a|/2^(n+1) <ε * 与えられたεに対し、この式を満たす最小のnが2分法で必要な計算回数 */ double a0 = -3.0; double b0 = 0.0; double ε = 1.0e-12; int iter = 0; double a = a0; double b = b0; double c = 0.0; System.out.println("初期値 a= " + a + ", b= " + b); while(Math.abs(b-a)/2 >= ε) { iter++; System.out.print(iter + "回目 "); c = (a+b)/2; System.out.println("c= " + c); double P = func(a)*func(c); if(P>0) { a=c; } else if(P<0) { b=c; } else if(P==0.0) { break; } } System.out.println("許容誤差内に収まりました."); System.out.print("近似解は " + c + " です. "); System.out.println(iter + "回反復しました."); System.out.println("|f(x)|= " + Math.abs(c*c*c -2.0*c*c -c +2.0)); System.out.println("終了します."); System.out.println(Math.log10(2.0)); } static double func(double x) { double y = x*x*x -2.0*x*x -x +2.0; return y; } } <file_sep>/src/math2/ShusokuHantei12.java package math2; public class ShusokuHantei12 { public static void main(String[] args) { /* 収束判定 全12通り */ /*// 誤差1-ノルム double AbsoluteError1 = Calc.vecNorm1(Calc.subVec(x_new, x_old)); */ /*// 誤差2-ノルム double AbsoluteError2 = Calc.vecNorm2(Calc.subVec(x_new, x_old)); */ /*// 誤差∞-ノルム double AbsoluteErrorInf = Calc.vecNormInf(Calc.subVec(x_new, x_old)); */ /*// 残差1-ノルム double AbsoluteResidual1 = Calc.vecNorm1(Calc.residual(A, x_new, b)); */ /*// 残差2-ノルム double AbsoluteResidual2 = Calc.vecNorm2(Calc.residual(A, x_new, b)); */ /*// 残差∞-ノルム double AbsoluteResidualInf = Calc.vecNormInf(Calc.residual(A, x_new, b)); */ /*// 相対誤差1-ノルム double RelativeError1 = Calc.vecNorm1(Calc.subVec(x_new, x_old))/Calc.vecNorm1(x_new); */ /*// 相対誤差2-ノルム double RelativeError2 = Calc.vecNorm2(Calc.subVec(x_new, x_old))/Calc.vecNorm2(x_new); */ /* // 相対誤差∞-ノルム double RelativeErrorInf = Calc.vecNormInf(Calc.subVec(x_new, x_old))/Calc.vecNormInf(x_new); */ /*// 相対残差1-ノルム double RelativeResidual1 = Calc.vecNorm1(Calc.residual(A, x_new, b))/Calc.vecNorm1(b); */ /*// 相対残差2-ノルム double RelativeResidual2 = Calc.vecNorm2(Calc.residual(A, x_new, b))/Calc.vecNorm2(b); */ /*// 相対残差∞-ノルム double RelativeResidualInf = Calc.vecNormInf(Calc.residual(A, x_new, b))/Calc.vecNormInf(b); */ } } <file_sep>/src/math/SummerReport2015.java package math; public class SummerReport2015 { public static void main(String[] args) { // 複素ニュートン法 // f(x)= x^2+1 Complex x0 = new Complex(18.0, -66.0); double ε = 1.0e-24; int Nmax = 100; Complex xk = x0; System.out.println("初期値x_0= " + xk); for(int k=0; k<=Nmax; k++) { if(k==Nmax) { System.out.println("収束しませんでした."); break; } Complex xk1 = Complex.sub(xk, Complex.div(func1(xk), func2(xk))); System.out.println("x_" + (k+1) +"= " + xk1); if( //Complex.abs(func1(xk1))<ε // 残差 Complex.abs(Complex.div(Complex.sub(xk, xk1), xk1))<ε // 相対誤差 ) { System.out.print("許容誤差内に収まりました. "); System.out.println("近似解は x_" +(k+1) + " になります."); break; } xk = xk1; } System.out.println("終了します."); } static Complex func1(Complex x) { Complex y = Complex.mul(x, x); y.re += 1.0; return y; } static Complex func2(Complex x) { Complex y = x; Complex z = new Complex(2.0, 0.0); y = Complex.mul(y, z); /* * Complex y = x; * y.re *= 2.0; * y.im *= 2.0; * return y; * ではダメ。xにもyと同様の操作がかかってしまう → 参照とかの問題? */ return y; } } <file_sep>/src/math2/GaussZenshin.java package math2; public class GaussZenshin { public static void main(String[] args) { // Gaussの消去法(前進消去過程)のアルゴリズム // 連立一次方程式 Ax=b を解く double A[][] = {{1.0, 2.0, 1.0, 2.0, 1.0}, {2.0, 3.0, 2.0, 3.0, 2.0}, {1.0, 2.0, 3.0, 4.0, 5.0}, {4.0, 3.0, 8.0, 1.0, 2.0}, {8.0, 2.0, 4.0, 1.0, 9.0}}; double b[] = {7.0, 7.0, 7.0, 7.0, 7.0}; int n = 0; // 四則演算の回数を記録する double α = 0.0; // α= (a_ik)/(a_kk) for(int k=0; k<A.length; k++) { // a_kk をピボット?とする for(int i=k+1; i<A.length; i++) { // a_kk についての計算を i 行で α = A[i][k]/A[k][k]; n++; for(int j=k+1; j<A.length; j++) { // a_kk についての計算を i 行 j 列で A[i][j] = A[i][j]-α*A[k][j]; n += 2; } b[i] = b[i]-α*b[k]; n += 2; } } System.out.println("A= "); Calc.printMat(A); System.out.println(); System.out.print("b= "); Calc.printVec(b); System.out.println(); System.out.println("四則演算を " + n + " 回しました。"); } } <file_sep>/src/math/Factorial.java package math; public class Factorial { public static void main(String[] args) { // nの階乗を計算する int n = 7; int y = 1; // 結果 for(int i=0; i<n; i++) { y *= n-i; } System.out.println(n + "!= " + y ); } } <file_sep>/src/math2/Kakomon2014.java package math2; public class Kakomon2014 { public static void main(String[] args) { /* * 指数表記で出力 * System.out.println(String.format("%1$3e", x)); */ // 問題1(1) double x[] = new double[49]; for(int i=0; i<x.length; i++) { x[i] = Math.sqrt(i+1.0); } System.out.println("[1](1) ||x||_2= " + Calc.vecNorm2(x)); System.out.println(String.format("%1$3e", Calc.vecNorm2(x))); System.out.println(); // 問題1(2) double A[][] = new double[100][100]; double sum = 0.0; for(int i=0; i<A.length; i++) { for(int j=0; j<A.length; j++) { A[i][j] = (i+1.0)+(j+1.0); sum += Math.pow(A[i][j], 2.0); } } System.out.println("[1](2) ||A||_F= " + Math.sqrt(sum)); System.out.println(String.format("%1$3e", Math.sqrt(sum))); System.out.println(); /* * ユークリッドノルム ⇔ フロベニウスノルム * は、「自然なノルム」ではない。 * 自然なノルム⇔||A||=sup(x!=0)[(||Ax||/||x||)] * 単位行列Iに対しては、||I||=1 となるもの */ /* // 問題2 int n = 6; // 行列サイズ // Hilbert行列A double A[][] = new double[n][n]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { A[i][j] = 1.0/((i+1)+(j+1)-1.0); } } double x_star[] = new double[n]; // 真の解=要素がすべて1 for(int i=0; i<n; i++) { x_star[i] = 1.0; } double b[] = new double[n]; b = Calc.matVec(A, x_star); // (1) double κ = Calc.Condition_Number(A); System.out.print("[2](1) "); System.out.println("Condition_Number = " + κ); // (2) double x_tilde[] = new double[n]; x_tilde = Calc.PivotGauss(A, b); // 相対誤差∞-ノルム double RelativeErrorInf = Calc.vecNormInf(Calc.subVec(x_star, x_tilde))/Calc.vecNormInf(x_star); System.out.println("[2](2) = " + RelativeErrorInf); // (3) double Δb[] = new double[n]; Δb[0] = 0.001*b[0]; double x2[] = new double[n]; x2 = Calc.PivotGauss(A, Calc.addVec(b, Δb)); // 相対誤差∞-ノルム double RelativeErrorInf2 = Calc.vecNormInf(Calc.subVec(x_star, x2))/Calc.vecNormInf(x_star); System.out.println("[2](3) = " + RelativeErrorInf2); */ /* // 問題3 double A[][] = {{1.0, -2.0, 2,0}, {-1.0, 1.0, -1.0}, {-2.0, -2.0, 1.0}}; double b[] = {1.0, 1.0, 1.0}; // Step: 1 double x_0[] = new double[A.length]; for(int i=0; i<A.length; i++) { x_0[i] = 0.0; } double ε = 1.0e-12; int N = 50; */ /* System.out.println("[3](1)"); // Step: 2 int m = 0; double x_old[] = x_0.clone(); double x_new[] = new double[A.length]; double sum; while(true) { for(int i=0; i<A.length; i++) { sum = 0.0; for(int j=0; j<A.length; j++) { if( i!=j ) { sum += A[i][j]*x_old[j]; } } x_new[i] = (b[i]-sum)/A[i][i]; } m++; // 相対誤差∞-ノルム double RelativeErrorInf = Calc.vecNormInf(Calc.subVec(x_new, x_old))/Calc.vecNormInf(x_new); if( RelativeErrorInf<ε) { System.out.println("breakしました。"); break; } if( m==N ) { System.out.println("収束しません。"); break; } for(int k=0; k<A.length; k++) { x_old[k] = x_new[k]; } } // Step: 3 System.out.println("反復回数 m= " + m); System.out.print("近似解x= "); Calc.printVec(x_new); System.out.println(); */ /* System.out.println("[3](2)"); // Step: 2 int m = 0; double x_new[] = x_0.clone(); // こちらが主役。i1回ずつ書き換えられてく double x_old[] = x_0.clone(); // 収束判定のみに使う double sum; while(true) { for(int i=0; i<A.length; i++) { sum = 0.0; for(int j=0; j<A.length; j++) { if( i!=j ) { sum += A[i][j]*x_new[j]; } } x_new[i] = (b[i]-sum)/A[i][i]; } m++; // 相対誤差∞-ノルム double RelativeErrorInf = Calc.vecNormInf(Calc.subVec(x_new, x_old))/Calc.vecNormInf(x_new); if( RelativeErrorInf<ε) { System.out.println("breakしました。"); break; } if( m==N ) { System.out.println("収束しません。"); break; } for(int k=0; k<A.length; k++) { x_old[k] = x_new[k]; } } // Step: 3 System.out.println("反復回数 m= " + m); System.out.print("近似解x= "); Calc.printVec(x_new); */ /* // 問題4 System.out.println("[4]"); double A[][] = {{0.0, -1.0, 2.0}, {-4.0, 5.0, 6.0}, {8.0, 9.0,10.0}}; double b[] = {3.0, 7.0, 11.0}; // Step: 1 double x_0[] = new double[A.length]; for(int i=0; i<A.length; i++) { x_0[i] = 0.0; } double ε = 1.0e-8; int N = 50; // Step: 2 int m = 0; double x_old[] = x_0.clone(); double x_new[] = new double[A.length]; double sum; while(true) { for(int i=0; i<A.length; i++) { sum = 0.0; for(int j=0; j<A.length; j++) { if( i!=j ) { sum += A[i][j]*x_old[j]; } } x_new[i] = (b[i]-sum)/A[i][i]; System.out.println("A[i][i]= " + A[i][i]); System.out.print("x_new = "); Calc.printVec(x_new); } m++; // 相対誤差2-ノルム double RelativeError2 = Calc.vecNorm2(Calc.subVec(x_new, x_old))/Calc.vecNorm2(x_new); System.out.println("vecNorm2(Calc.subVec(x_new, x_old)) = " + Calc.vecNorm2(Calc.subVec(x_new, x_old))); System.out.println("vecNorm2(x_new) = "+ Calc.vecNorm2(x_new)); System.out.println("RelativeError2 = " + RelativeError2); if( RelativeError2<ε) { System.out.println("breakしました。"); break; } if( m==N ) { System.out.println("収束しません。"); break; } for(int k=0; k<A.length; k++) { x_old[k] = x_new[k]; } } // Step: 3 System.out.println("反復回数 m= " + m); System.out.print("近似解x= "); Calc.printVec(x_new); */ /* // 問題5 double A[][] = new double[100][100]; double b[] = new double[100]; for(int i=0; i<b.length; i++) { b[i] = 1.0; } for(int l=1; l<10; l++) { double a = (l+1.0); for(int i=0; i<A.length; i++) { for(int j=0; j<A.length; j++) { if( i==j ) { A[i][j] = a; } else if( Math.abs(i-j)==1 ) { A[i][j] = 4.0; } } } for(double ω=0.0; ω<2.1; ω+=0.1) { // ω0.1ごとの反復 System.out.println("a= " + a); // Step: 1 double x_0[] = new double[A.length]; for(int i=0; i<A.length; i++) { x_0[i] = 0.0; } double ε = 1.0e-8; int N = 500; // Step: 2 int m = 0; double x_new[] = x_0.clone(); // こちらが主役。i1回ずつ書き換えられてく double x_old[] = x_0.clone(); // SOR法では、収束判定だけでなく反復式にも使う double sum; //double ω = 0.0; // SOR法のパラメータ while(true) { for(int i=0; i<A.length; i++) { sum = 0.0; for(int j=0; j<A.length; j++) { if( i!=j ) { sum += A[i][j]*x_new[j]; } } x_new[i] = (b[i]-sum)/A[i][i]; x_new[i] = (1.0-ω)*x_old[i] + ω*x_new[i]; } m++; // 相対誤差∞-ノルム double RelativeErrorInf = Calc.vecNormInf(Calc.subVec(x_new, x_old))/Calc.vecNormInf(x_new); if( RelativeErrorInf<ε) { System.out.println("breakしました。"); break; } if( m==N ) { System.out.println("収束しません。"); break; } for(int k=0; k<A.length; k++) { x_old[k] = x_new[k]; } } // Step: 3 System.out.println("ω= " + ω); System.out.println("反復回数 m= " + m); System.out.print("近似解x= "); Calc.printVec(x_new); System.out.println(); } } */ // 問題6 /* double A[][] = new double[100][100]; for(int i=0; i<A.length; i++) { for(int j=0; j<A.length; j++) { if( i==j ) { A[i][j] = 4.0; } else if( Math.abs(i-j)==1 ) { A[i][j] = 2.0; } else if( Math.abs(i-j)==2 ) { A[i][j] = 1.0; } } } double AInv[][] = new double[100][100]; AInv = Calc.LU_Inverse(A); double trA = 0.0; for(int i=0; i<A.length; i++) { for(int j=0; j<A.length; j++) { if( i==j ) { trA += AInv[i][j]; } } } System.out.print("[6]= "); System.out.println(String.format("%1$3e", trA)); */ } } <file_sep>/src/math2/Kadai_Hilbert.java package math2; public class Kadai_Hilbert { public static void main(String[] args) { // 演習課題4 : 連立一次方程式の解きにくさ int n = 10; // 行列サイズ System.out.println("n= " + n); System.out.println(); // Hilbert行列A double A[][] = new double[n][n]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { A[i][j] = 1.0/((i+1.0)+(j+1.0)-1.0); } } /* (1) */ System.out.println("(1)"); double κ = Calc.Condition_Number(A); System.out.println("Condition_Number = " + κ); System.out.println(); /* (2) */ System.out.println("(2)"); double x_star[] = new double[n]; // 真の解=要素がすべて1 for(int i=0; i<n; i++) { x_star[i] = 1.0; } double b[] = new double[n]; b = Calc.matVec(A, x_star); System.out.print("残差ノルム : ||b-Ax_1||_∞ = "); System.out.println(Calc.vecNormInf(Calc.residual(A, Calc.PivotGauss(A, b), b))); System.out.print("誤差ノルム : ||x_star-x_1||_∞ = "); System.out.println(Calc.vecNormInf(Calc.subVec(x_star, Calc.PivotGauss(A, b)))); System.out.println(); /* (3) */ System.out.println("(3)"); double Δb[] =new double[n]; Δb[0] = 0.001*b[0]; System.out.print("解に含まれる誤差の上限 : κ_∞(A)*(||Δb||_∞)/(||b||_∞) = "); System.out.println(κ*((Calc.vecNormInf(Δb))/(Calc.vecNormInf(b)))); System.out.println(); /* (4) */ System.out.println("(4)"); // Ax=b+Δb を部分Pivot選択付きGaussの消去法で System.out.print("誤差ノルム : ||x_star-x_2||_∞ = "); System.out.println(Calc.vecNormInf(Calc.subVec(x_star, Calc.PivotGauss(A, Calc.addVec(b, Δb))))); } } <file_sep>/src/math2/SOR.java package math2; public class SOR { public static void main(String[] args) { /* SOR法 */ // Gauss-Seidel法にパラメータωを足した /* * A = D + E + F * =(対角)+(下三角)+(上三角) * * x_(m+1) = (D+ωE)^(-1)*{(1-ω)*D -ω*F}*x_(m) + ω*(D+ω*E)^(-1)*b */ System.out.println("SOR法"); System.out.println(); double A[][] = {{6.0, 1.0, 1.0, 1.0, 0.0}, {1.0, 7.0, 1.0, 1.0, 1.0}, {0.0, 1.0, 8.0, 1.0, 1.0}, {0.0, 0.0, 1.0, 9.0, 1.0}, {0.0, 0.0, 0.0, 1.0, 10.0}}; double b[] = {9.0, 11.0, 11.0, 11.0, 11.0}; for(double ω=0.0; ω<2.1; ω+=0.1) { // ω0.1ごとの反復 System.out.println("ω= " + ω); // Step: 1 double x_0[] = new double[A.length]; for(int i=0; i<A.length; i++) { x_0[i] = 0.0; } double ε = 1.0e-10; int N = 100; // Step: 2 int m = 0; double x_new[] = x_0.clone(); // こちらが主役。i1回ずつ書き換えられてく double x_old[] = x_0.clone(); // SOR法では、収束判定だけでなく反復式にも使う double sum; //double ω = 0.0; // SOR法のパラメータ while(true) { for(int i=0; i<A.length; i++) { sum = 0.0; for(int j=0; j<A.length; j++) { if( i!=j ) { sum += A[i][j]*x_new[j]; } } x_new[i] = (b[i]-sum)/A[i][i]; x_new[i] = (1.0-ω)*x_old[i] + ω*x_new[i]; } m++; /* 収束判定 全12通り */ /*// 誤差1-ノルム double AbsoluteError1 = Calc.vecNorm1(Calc.subVec(x_new, x_old)); if( AbsoluteError1<ε) { System.out.println("breakしました。"); break; } */ /*// 誤差2-ノルム double AbsoluteError2 = Calc.vecNorm2(Calc.subVec(x_new, x_old)); if( AbsoluteError2<ε) { System.out.println("breakしました。"); break; } */ /*// 誤差∞-ノルム double AbsoluteErrorInf = Calc.vecNormInf(Calc.subVec(x_new, x_old)); if( AbsoluteErrorInf<ε) { System.out.println("breakしました。"); break; } */ /*// 残差1-ノルム double AbsoluteResidual1 = Calc.vecNorm1(Calc.residual(A, x_new, b)); if( AbsoluteResidual1<ε ) { System.out.println("breakしました。"); break; } */ /*// 残差2-ノルム double AbsoluteResidual2 = Calc.vecNorm2(Calc.residual(A, x_new, b)); if( AbsoluteResidual2<ε ) { System.out.println("breakしました。"); break; } */ /*// 残差∞-ノルム double AbsoluteResidualInf = Calc.vecNormInf(Calc.residual(A, x_new, b)); if( AbsoluteResidualInf<ε ) { System.out.println("breakしました。"); break; } */ /*// 相対誤差1-ノルム double RelativeError1 = Calc.vecNorm1(Calc.subVec(x_new, x_old))/Calc.vecNorm1(x_new); if( RelativeError1<ε) { System.out.println("breakしました。"); break; } */ /*// 相対誤差2-ノルム double RelativeError2 = Calc.vecNorm2(Calc.subVec(x_new, x_old))/Calc.vecNorm2(x_new); if( RelativeError2<ε) { System.out.println("breakしました。"); break; } */ ///* // 相対誤差∞-ノルム double RelativeErrorInf = Calc.vecNormInf(Calc.subVec(x_new, x_old))/Calc.vecNormInf(x_new); if( RelativeErrorInf<ε) { System.out.println("breakしました。"); break; } //*/ /*// 相対残差1-ノルム double RelativeResidual1 = Calc.vecNorm1(Calc.residual(A, x_new, b))/Calc.vecNorm1(b); if( RelativeResidual1<ε) { System.out.println("breakしました。"); break; } */ /*// 相対残差2-ノルム double RelativeResidual2 = Calc.vecNorm2(Calc.residual(A, x_new, b))/Calc.vecNorm2(b); if( RelativeResidual2<ε) { System.out.println("breakしました。"); break; } */ /*// 相対残差∞-ノルム double RelativeResidualInf = Calc.vecNormInf(Calc.residual(A, x_new, b))/Calc.vecNormInf(b); if( RelativeResidualInf<ε) { System.out.println("breakしました。"); break; } */ if( m==N ) { System.out.println("収束しません。"); break; } for(int k=0; k<A.length; k++) { x_old[k] = x_new[k]; } } // Step: 3 System.out.println("反復回数 m= " + m); System.out.print("近似解x= "); Calc.printVec(x_new); System.out.println(); } } } <file_sep>/src/math/ZenkiTest.java package math; public class ZenkiTest { public static void main(String[] args) { /* double d = 1.0; double k; for(int i=0; i<20; i++) { k = i+1; for(int j=i+1; j>1; j--) { k *= j-1; } System.out.println(k); d += 1.0/k; } System.out.println(); System.out.println(d); */ /* float d = 1.0f; float k; for(int i=0; i<20; i++) { k = i+1; for(int j=i+1; j>1; j--) { k *= j-1; } System.out.println(k); d += 1.0/k; } System.out.println(); System.out.println(d); */ //ここから /* // step 1 double z = 100.65625; int x = (int) z; double y = z - x; // step 2 int[] a = new int[20]; int n =0; for( int i = 0; i <a.length; i++) { a[i] = x%4; x = x/4; if( x<4) { a[i+1] = x; n = i+1; break; } } // step 3 int[] b = new int[20]; for( int i = 0; i < b.length; i++) { b[i] = (int)(y*4); y = y*4 - b[i]; } // step 4 while( n >= 0 ) { System.out.print(a[n]); n--; } System.out.print("."); for( int i = 0; i < b.length; i++) { System.out.print(b[i]); } */ /* int[] a = new int[7]; //2進数の整数部分 int[] b = new int[5]; //2進数の小数部分 a[0] = 1; // 0の位 a[1] = 1; // 2の位 a[2] = 1; a[3] = 1; a[4] = 1; a[5] = 1; a[6] = 1; b[0] = 0; // 0の位 b[1] = 0; // (1/2)の位 b[2] = 1; b[3] = 0; b[4] = 1; //整数部分 double[] y = new double[7]; y[6] = a[6]; for( int k = 5; k >= 0; k--) { y[k] = y[k+1]*2+a[k]; } System.out.println( y[0] ); //少数部分 double[] z = new double[5]; z[4] = b[4]; for( int k =3; k >= 0; k--) { z[k] = z[k+1]/2+b[k]; } System.out.println( z[0] ); // 解 double A = y[0] + z[0]; System.out.println( "A="+A ); */ /* double z = 120; System.out.println( Integer.toHexString( (int)z )); int x = (int)z; double y = z-x; // 整数部分 int a[] = new int[20]; int i1 = 0; while( x>0 ) { int w = x%16; if( w<10 ) { a[i1] = w; }else{ a[i1] = HexaDecimal(w); } x = x/16; i1++; } i1--; // 少数部分 int b[] = new int[20]; int i2 = 0; while( y>0 ) { int w = (int)(y*16); if( w<10 ) { b[i2] = w; } else { b[i2] = HexaDecimal(w); } y = y*16-w; i2++; } i2--; // 出力 while( i1>=0 ) { if( a[i1]<10 ) { System.out.print(a[i1]); } else { System.out.print((char)a[i1]); } i1--; } System.out.print("."); for( int k=0; k<=i2; k++) { if( b[k]<10 ) { System.out.print(b[k]); } else { System.out.print((char)b[k]); } } } static char HexaDecimal(int x) { char y = 'X'; if( x==10) y = 'A'; else if( x==11) y = 'B'; else if( x==12) y = 'C'; else if( x==13) y = 'D'; else if( x==14) y = 'E'; else if( x==15) y = 'F'; else System.out.println("例外が発生しました。"); return y; */ /* double[] F = new double[71]; F[0] = 0.0; F[1] = 1.0; for(int n=0; n<=68; n++) { F[n+2] = F[n+1]+F[n]; } System.out.println("F[70]= " + F[70]); System.out.println(); */ /* double a = 1.0e-9; double b = 9.999e-10; System.out.println("絶対誤差:" + Math.abs(a-b)); System.out.println("相対誤差:" + Math.abs((a-b)/a)); */ /* double en = 1.0; double en1=1.0; double val = 1.0; int iter = 0; while(en>0) { iter++; System.out.print(iter + " "); val = val*iter; en1 = en + Math.pow(1.5, iter)/val; if(en==en1) { System.out.println("終り"); System.out.println("en= " + en); System.out.println("en1= " + en1); break; } en = en1; } */ /* double x0 = -2.0; double ε = 1.0e-12; int Nmax = 200; double xk = x0; System.out.println("初期値x_0= " + xk); for(int k=0; k<=Nmax; k++) { if(k==Nmax) { System.out.println("収束しませんでした."); break; } double xk1 = xk-func1(xk)/func2(xk); System.out.println("x_" + (k+1) +"= " + xk1); if( Math.abs(func1(xk1))<ε // 残差 //Math.abs((xk-xk1)/xk1)<ε // 相対誤差 ) { System.out.print("許容誤差内に収まりました. "); System.out.println("近似解は x_" +(k+1) + " になります."); break; } xk = xk1; } System.out.println("終了します."); } static double func1(double x) { //double y = x*x*x -4.0*x*x +13.0*x/4.0 -3.0/4.0; //double y = Math.sin(x)/(x-1.0); double y = x*x*x*x -13.0*x*x*x/2.0 +15.0*x*x -14.0*x +4; return y; } static double func2(double x) { //double y = 3.0*x*x -8.0*x +13.0/4.0; //double y = (Math.cos(x)*(x-1.0)-Math.sin(x))/Math.pow(x-1.0, 2.0); double y = 4.0*x*x*x -39.0*x*x/2.0 +30.0*x -14.0; return y; } */ double x0 = 1.0; double x1 = 1.5; double ε = 1.0e-12; int Nmax = 200; double xk = x0; double xk1 = x1; System.out.println("初期値x_0= " + xk); System.out.println("初期値x_1= " + xk1); for(int k=0; k<=Nmax; k++) { if(k==Nmax) { System.out.println("収束しませんでした."); break; } //double xk2 = xk-func(xk)*(xk-xk1)/(func(xk)-func(xk1)); double xk2 = xk1-func(xk1)*(xk-xk1)/(func(xk)-func(xk1)); System.out.println("x_" + (k+2) + "= " + xk2); if( //Math.abs(func(xk2))<ε // 残差 Math.abs((xk1-xk2)/xk2)<ε // 相対誤差 ) { System.out.print("許容誤差内に収まりました. "); System.out.print("近似解はx_" + (k+2) + "になります. "); System.out.println((k+1) + "回反復しました."); break; } xk = xk1; xk1 = xk2; } System.out.println("終了します."); } static double func(double x) { //double y = x*x*x -4.0*x*x +13.0*x/4.0 -3.0/4.0; double y = 4.0*x*x*x -39.0*x*x/2.0 +30.0*x -14.0; return y; } } <file_sep>/src/math2/Kadai_Gauss.java package math2; public class Kadai_Gauss { public static void main(String[] args) { /* A, b の作成、保管用のoriginA, originb の作成 */ int n = 500; // 行列サイズ double A[][] = new double[n][n]; double b[] = new double[n]; double originA[][] = new double[n][n]; double originb[] = new double[n]; for(int r=0; r<100; r++) { //A_r*x=b_r r個の方程式を解く for(int i=0; i<A.length; i++) { for(int j=0; j<A.length; j++) { A[i][j] = Math.random(); originA[i][j] = A[i][j]; } b[i] = Math.random(); originb[i] = b[i]; } /* Gaussの消去法(Pivot選択なし) */ // 前進消去過程 double α = 0.0; // α= (a_ik)/(a_kk) for(int k=0; k<A.length-1; k++) { // a_kk をピボット?とする for(int i=k+1; i<A.length; i++) { // a_kk についての計算を i 行で α = A[i][k]/A[k][k]; for(int j=k+1; j<A.length; j++) { // a_kk についての計算を i 行 j 列で A[i][j] = A[i][j]-α*A[k][j]; } b[i] = b[i]-α*b[k]; } } // 後退代入過程 for(int k=A.length-1; k>=0; k--) { for(int j=A.length-1; j>k; j--) { b[k] = b[k] -A[k][j]*b[j]; } b[k] = b[k]/A[k][k]; } /* 残差2ノルム ||b-Ax||_2 を算出 */ System.out.print("x_" +(r+1) + "= "); System.out.println(Calc.vecNorm2(Calc.residual(originA, b, originb))); /* A, b を初期値に戻す */ for(int i=0; i<A.length; i++) { for(int j=0; j<A.length; j++) { A[i][j] = originA[i][j]; } b[i] = originb[i]; } /* 部分Pivot選択付きGaussの消去法 */ int l = 0; // Pivotの行番号 double temp = 0.0; // Pivot選択、入れ替え時の一時保管用 // 前進消去過程 α = 0.0; // α= (a_ik)/(a_kk) for(int k=0; k<A.length-1; k++) { // a_kk をピボット?とする // Pivot選択用に追加 temp = Math.abs(A[k][k]); l = k; for(int i=k+1; i<A.length; i++) { // Pivotの選択 if(temp < Math.abs(A[i][k])) { // 選択したものをtempに入れるだけで、行列の中身は変えていない temp = Math.abs(A[i][k]); l = i; } } if(Math.abs(A[k][k]) < 1.0e-10) { // Pivotの例外処理 System.out.println("Pivot= " + A[k][k]); System.out.println("絶対値最大成分が0または非常に小さいので、解けないと判断します。"); break; } for(int j=k; j<A.length; j++) { // k行目とl行目を入れ替える temp = A[l][j]; A[l][j] = A[k][j]; A[k][j] = temp; } temp = b[l]; // bの入れ替えも忘れずに b[l] = b[k]; b[k] = temp; // 通常の消去 for(int i=k+1; i<A.length; i++) { // a_kk についての計算を i 行で α = A[i][k]/A[k][k]; for(int j=k+1; j<A.length; j++) { // a_kk についての計算を i 行 j 列で A[i][j] = A[i][j]-α*A[k][j]; } b[i] = b[i]-α*b[k]; } } // 後退代入過程 for(int k=A.length-1; k>=0; k--) { for(int j=A.length-1; j>k; j--) { b[k] = b[k] -A[k][j]*b[j]; } b[k] = b[k]/A[k][k]; } /* 残差2ノルム ||b-Ax||_2 を算出 */ System.out.print("x_" + (r+1) + "= "); System.out.println(Calc.vecNorm2(Calc.residual(originA, b, originb))); System.out.println(); } } } <file_sep>/src/math2/Cholesky.java package math2; public class Cholesky { public static void main(String[] args) { /* Cholesky分解 */ double A[][] = new double[3][3]; A[0][0] = 1.0; A[1][0] = 2.0; A[0][1] = A[1][0]; A[1][1] = 13.0; A[2][0] = 4.0; A[0][2] = A[2][0]; A[2][1] = 23.0; A[1][2] = A[2][1]; A[2][2] = 77.0; double L[][] = new double[A.length][A.length]; for(int j=0; j<A.length; j++) { for(int i=j; i<A.length; i++) { double sum = 0.0; for(int k=0; k<j; k++) { sum += L[i][k]*L[j][k]; // Ltの表現に注意 } if( i==j ) { L[i][i] = Math.pow((A[i][i]-sum), 0.50); } else { L[i][j] = (A[i][j]-sum)/L[j][j]; } // System.out.println("L[" + i + "][" + j +"]= " + L[i][j]); } } System.out.println(); System.out.println("L="); Calc.printMat(L); System.out.println(); double Lt[][] = new double[L.length][L.length]; for(int i=0; i<L.length; i++) { for(int j=0; j<L.length; j++) { Lt[i][j] = L[j][i]; } } System.out.println("A= L*Lt ="); Calc.printMat(Calc.multipleMat(L, Lt)); } } <file_sep>/src/math2/EnshuKadai_1.java package math2; public class EnshuKadai_1 { // import math.Complex ? public static void main(String[] args) { /* 後期演習課題1 */ // 問題1 System.out.println("問題1: "); double x1[] = {1.0, -2.0, 3.0, -4.0}; System.out.println("||x1||_1 = " + Calc.vecNorm1(x1)); System.out.println("||x1||_2 = " + Calc.vecNorm2(x1)); System.out.println("||x1||_∞ = " + Calc.vecNormInf(x1)); System.out.println(); // 問題2 System.out.println("問題2: "); double A1[][] = {{1.0, -1.0}, {2.0, 0.0}, {0.0, -2.0}}; System.out.println("||x1||_1 = " + Calc.matNorm1(A1)); //System.out.println("||x1||_2 = " + Calc.matNorm2(A1)); System.out.println("||x1||_∞ = " + Calc.matNormInf(A1)); System.out.println(); // 問題3 System.out.println("問題3: "); // ベクトルx2を配列x2に定義 Complex x2[] = new Complex[3]; x2[0] = new Complex(1.0, 1.0); x2[1] = new Complex(2.0, -2.0); x2[2] = new Complex(0.0, -1.0); // ベクトルx2の各値の絶対値を配列x2absに定義 double x2abs[] = new double[3]; x2abs[0] = Complex.abs(x2[0]); x2abs[1] = Complex.abs(x2[1]); x2abs[2] = Complex.abs(x2[2]); /* * Norm計算に使われるのは複素数の絶対値のみなので * 絶対値を入れた配列をCalcメソッドに渡せばいける */ System.out.println("vecNorm1 = " + Calc.vecNorm1(x2abs)); System.out.println("vecNorm2 = " + Calc.vecNorm2(x2abs)); System.out.println("vecNormInf = " + Calc.vecNormInf(x2abs)); //System.out.println(Calc.vecNorm1(x2)); ←これはできない。Calcが複素数に対応していないから // import math.Complex ? // 問題3 Ver.2 System.out.println(); // Norm1は絶対値の列和 double sum = x2abs[0] + x2abs[1] + x2abs[2]; System.out.println("vecNorm1 = " + sum); // 2NormはEuclidNorm double vecNorm2 = Math.sqrt(Math.pow(x2abs[0], 2.0)+Math.pow(x2abs[1], 2.0)+Math.pow(x2abs[2], 2.0)); System.out.println("vecNorm2 = " + vecNorm2); // ∞Normは絶対値の最大行 double vecNormInf = 0.0; for(int i=0; i<x2abs.length; i++) { if(vecNormInf<x2abs[i]) { vecNormInf = x2abs[i]; } } System.out.println("vecNormInf = " + vecNormInf); System.out.println(); // 問題4 System.out.println("問題4"); Complex A2[][] = new Complex[2][2]; A2[0][0] = new Complex(2.0, 0.0); A2[0][1] = new Complex(1.0, -1.0); A2[1][0] = new Complex(1.0, 1.0); A2[1][1] = new Complex(0.0, -2.0); double A2abs[][] = new double[2][2]; A2abs[0][0] = Complex.abs(A2[0][0]); A2abs[0][1] = Complex.abs(A2[0][1]); A2abs[1][0] = Complex.abs(A2[1][0]); A2abs[1][1] = Complex.abs(A2[1][1]); System.out.println("||A2||_1 = " + Calc.matNorm1(A2abs)); // matNorm2だけ複雑 System.out.println("||A2||_2 = " + "ルートmax{|λ|} : λは(A*A)の固有値(A*はAの共役転置行列)"); System.out.println("||A2||_∞ = " + Calc.matNormInf(A2abs)); System.out.println(); // 問題5 System.out.println("問題5"); double x3[] = new double[100]; for(int i=0; i<x3.length; i++) { x3[i] = Math.pow((i+1.0), 0.50); } System.out.println("||x3||_1 = " + Calc.vecNorm1(x3)); System.out.println("||x3||_2 = " + Calc.vecNorm2(x3)); System.out.println("||x3||_∞ = " + Calc.vecNormInf(x3)); System.out.println(); // System.out.println(1/2); ←注意:(1/2)=0 ※intのわり算だから // 問題6 System.out.println("問題6"); double A3[][] = new double[100][100]; for(int i=0; i<A3.length; i++) { for(int j=0; j<A3.length; j++) { A3[i][j] = Math.pow((2.0*(i+1.0)+(j+1.0)), 0.50); } } System.out.println("||A3||_1 = " + Calc.matNorm1(A3)); System.out.println("||A3||_∞ = " + Calc.matNormInf(A3)); } }
6b0ac80541f8a043c827693eec7ca5290a3aa6a2
[ "Java" ]
16
Java
pennennolde/numerical_analysis
0be2ed95c519b24f33da6a8b055bdbfb47b3183d
0b89ca37bdd06a2f71925742b0fba8ecd7a57cfc
refs/heads/master
<repo_name>Polpetta/minibashlib<file_sep>/modules/logging.sh #!/bin/bash function msg () { # 3 type of messages: # - info # - warn # - err local color="" local readonly default="\033[m" #reset if [ "$1" = "info" ] then color="\033[0;32m" #green elif [ "$1" = "warn" ] then color="\033[1;33m" #yellow elif [ "$1" = "err" ] then color="\033[0;31m" #red fi echo -e "$color==> $2$default" } <file_sep>/modules/systemop.sh #!/bin/bash MB_DISTRO="" CMD="" function _die () { echo "$1" exit 1 } function _check_if_sudo_needed () { if [ "$EUID" -ne 0 ] then # I need to place sudo in front of the administrative commands [[ -f $(which sudo) ]] || _die "You're not root and you don't have sudo installed: I won't be \ able to run admin commands" CMD=$(which sudo) fi } function detect_distro () { if [ -f /etc/os-release ] then local res="$(cat /etc/os-release | grep ID= | cut -d'=' -f2 | head -n1)" # It removes extra double quotes echo $(echo $res | sed "s/^\(\"\)\(.*\)\1\$/\2/g") fi } function set_distro () { MB_DISTRO="$1" } function get_distro () { echo $MB_DISTRO } function install_centos () { $CMD yum install -y $@ } function install_ubuntu () { $CMD apt-get install -y $@ } function update_ubuntu () { $CMD apt-get update $CMD apt-get upgrade -y $CMD apt-get autoclean $CMD apt-get autoremove -y } function update_centos () { $CMD yum upgrade -y } function update () { if [ -z "$MB_DISTRO" ] then set_distro "$(detect_distro)" fi case "$MB_DISTRO" in "ubuntu") update_ubuntu ;; "centos") update_centos ;; *) _die "Package installation on this distro is not supported yet" esac } function install () { local package_list=( "$@" ) if [ -z "$MB_DISTRO" ] then set_distro "$(detect_distro)" fi case "$MB_DISTRO" in "ubuntu") install_ubuntu "${package_list[@]}" ;; "centos") install_centos "${package_list[@]}" ;; *) _die "Package installation on this distro is not supported yet" esac } function exec_root_func () { # I use underscores to remember it's been passed local _funcname_="$1" local params=( "$@" ) ## array containing all params passed here local tmpfile="/dev/shm/$RANDOM" ## temporary file local content ## content of the temporary file local regex ## regular expression local func ## function source # Shift the first param (which is the name of the function) unset params[0] ## remove first element # params=( "${params[@]}" ) ## repack array content="#!/bin/bash\n\n" # Write the params array content="${content}params=(\n" regex="\s+" for param in "${params[@]}" do if [[ "$param" =~ $regex ]] then content="${content}\t\"${param}\"\n" else content="${content}\t${param}\n" fi done content="$content)\n" echo -e "$content" > "$tmpfile" # Append the function source echo "#$( type "$_funcname_" )" >> "$tmpfile" # Append the call to the function echo -e "\n$_funcname_ \"\${params[@]}\"\n" >> "$tmpfile" sudo bash "$tmpfile" local sudo_exit_code=$? rm "$tmpfile" echo $sudo_exit_code } # The following code was taken from https://www.maketecheasier.com/ssh-pipes-linux/ # Exec a script remotely # - $1: remote username # - $2: machine ip # - $3: path to the script # - $4: optional ssh arguments function exec_script_remotely () { local readonly remote_user="$1" local readonly remote_ip="$2" local readonly script_path="$3" local readonly opt_args="$4" ssh $remote_user@$remote_ip "$opt_args" 'bash -s' < $script_path } # Send a file to the remote machine # - $1: remote username # - $2: machine ip # - $3: path to the file # - $4: remote filename # - $5: optional ssh arguments function send_file_to_remote () { local readonly remote_user="$1" local readonly remote_ip="$2" local readonly file_path="$3" local readonly opt_args="$5" local remote_filename="$4" if [ -z "$remote_filename" ] then remote_filename="remote" fi cat $file_path | ssh $remote_user@$remote_ip "$opt_args" "cat > $remote_filename" } # Download a file from a remote host # - $1: remote username # - $2: machine ip # - $3: path to the file # - $4: remote filename # - $5: optional ssh arguments function download_file_from_remote () { local readonly remote_user="$1" local readonly remote_ip="$2" local readonly file_path="$3" local readonly opt_args="$5" local remote_filename="$4" if [ -z "$remote_filename" ] then remote_filename="remote" fi ssh $remote_user@$remote_ip "$opt_args" "cat > $remote_filename" < $file_path } _check_if_sudo_needed <file_sep>/minibashlib.sh #!/bin/bash readonly MB_RELEASE_REPO_URL=https://github.com/Polpetta/minibashlib readonly MB_RAW_REPO_URL=https://raw.githubusercontent.com/Polpetta/minibashlib # args: # - $1: module name - if blank all modules are fetched # - $2: module version - if blank modules are downloaded from master, otherwise # a corrispective tag is downloaded, if possible function mb_load () { local version local module_name=$1 local module_version=$2 if [ -z "$module_name" ] then local mb_modules=() mb_modules+=("logging") mb_modules+=("assertions") mb_modules+=("systemop") # load all the modules local mb_modules_size=$((${#mb_modules[@]} - 1)) for i in $(seq 0 $mb_modules_size) do module_name=${mb_modules[$i]} mb_load "$module_name" "$2" done else local file_to_load if [ -z "$2" ] then version="master" file_to_load=$(_mb_download_module "$MB_RAW_REPO_URL/$version/modules/$1.sh") else version="$2" file_to_load=$(_mb_download_module "$MB_BASE_REPO_URL/releases/$2/$1.sh") fi . $file_to_load fi } function _mb_download_module () { local module_path=$(mktemp) curl -s "$1" > $module_path echo "$module_path" } <file_sep>/modules/assertions.sh #!/bin/bash function check () { if [ "$1" -ne 0 ] then msg err "$2" exit 1 fi } function set_dbg () { if [ "$1" = "true" ] then set -x else set +x fi } function exec_if_not_null () { [[ -z "$1" ]] && "$2" } function exec_if_null () { [[ -z "$1" ]] || "$2" } <file_sep>/README.md # minibashlib Minimal set of bash libraries to ease the writing of bash scripts
b737074266dce7db167c4495a2a86a6982abe0a8
[ "Markdown", "Shell" ]
5
Shell
Polpetta/minibashlib
6fbb5526be41bcc44229c19f3304700b7e2dffa4
c4665c9580c986926663352130cb988d9a5b00b2
refs/heads/master
<file_sep>using System.Collections.Generic; using TeamCitySharp.DomainEntities; namespace TeamCitySharp.ActionTypes { public interface IChanges { List<Change> All(int aHttpTimeOut = -1); Change ByChangeId(string id, int aHttpTimeOut = -1); Change LastChangeDetailByBuildConfigId(string buildConfigId, int aHttpTimeOut = -1); List<Change> ByBuildConfigId(string buildConfigId, int aHttpTimeOut = -1); List<Change> ByBuild(Build aBuild, int aHttpTimeOut = -1); List<Change> ByBuildId(int aBuildId, int aHttpTimeOut = -1); } }
2a70cb95837878cc75416078ac894881a89dbd0b
[ "C#" ]
1
C#
tikicoder/TeamCitySharp
ed54792dcb95bd17eab5ef41075e38bc99572dba
cf9899d48e2d81731d01dc1c8ab312a46dd4e0bf
refs/heads/main
<file_sep>import * as PIXI from 'pixi.js'; import * as box from 'box2d.ts'; import { BodyTypes, Transform, Vector, LineStyle, Color } from './properties'; const BODY_SCALE = 10.5; export class GameObject { private _transform: Transform; private _box: PIXI.Rectangle; private _sprite!: PIXI.Sprite; private _boxColliderShape!: PIXI.Graphics; private _body!: box.b2Body; public get sprite(): PIXI.Sprite { if (!this._sprite) throw new Error(`GameObject does not contain a sprite.`); return this._sprite; } public get boxColliderShape(): PIXI.Graphics { if (!this._boxColliderShape) throw new Error(`GameObject does not contain a visual collider shape.`); return this._boxColliderShape; } public get body(): box.b2Body { if (!this._body) throw new Error(`GameObject does not contain a b2Body.`); return this._body; } private get bodyTransform(): Transform { const position = this.toVector(this.body.GetPosition()); position.x *= BODY_SCALE; position.y *= BODY_SCALE; return { position: position, rotation: box.b2RadToDeg(this.body.GetAngle()), scale: this._transform.scale }; } constructor( container: PIXI.Container, world: box.b2World, { transform: { position = { x: 0, y: 0 } as Vector, rotation = 0, scale = { x: 1, y: 1 } as Vector }, sprite: { src = PIXI.Texture.WHITE, pivot = { x: 0.5, y: 0.5 } as Vector }, box: { width = 0, height = 0, color = Color.red(), lineStyle = { width: 3, alignment: 0, native: undefined } as LineStyle }, body: { bodyType = BodyTypes.STATIC, density = 0.0 } } ) { this._transform = { position: position, rotation: rotation, scale: scale }; this._box = this.initBox(width, height, pivot); this._sprite = this.initSprite(src, pivot); this._boxColliderShape = this.initBoxColliderShape(color, lineStyle); this._body = this.initBody(world, bodyType, density); container.addChild(this.sprite); container.addChild(this.boxColliderShape); } public onUpdate(): void { this.setTransform(this.bodyTransform); } private initBox( width: number, height: number, pivot: Vector ): PIXI.Rectangle { return new PIXI.Rectangle( -width * pivot.x, -height * pivot.y, width, height ); } private initSprite( src: PIXI.Texture, pivot: Vector ): PIXI.Sprite { const sprite = new PIXI.Sprite(src); sprite.anchor.set(pivot.x, pivot.y); return sprite; } private initBoxColliderShape( color: Color, lineStyle: LineStyle ): PIXI.Graphics { const shape = new PIXI.Graphics(); shape.lineStyle( lineStyle.width, color.hexCode, color.a, lineStyle.alignment, lineStyle.native ); shape.drawShape(this._box); return shape; } private initBody( world: box.b2World, bodyType: BodyTypes, density: number ): box.b2Body { const vertices = this.toXYArray(this._box, this._transform.scale); const position = this._transform.position; const shape = new box.b2PolygonShape(); shape.SetAsArray(vertices); const bodyDef = new box.b2BodyDef(); bodyDef.type = bodyType.valueOf(); const body = world.CreateBody(bodyDef); body.CreateFixture(shape, density); body.SetTransformVec({ x: position.x, y: position.y }, this._transform.rotation ); return body; } private toXYArray( colliderShape: PIXI.Rectangle, scale: Vector = { x: 1, y: 1 } ): Array<box.XY> { const vectorList = new Array<box.XY>(); const objectScale = 1 / BODY_SCALE; vectorList.push({ x: colliderShape.x * objectScale * scale.x, y: colliderShape.y * objectScale * scale.y }); vectorList.push({ x: colliderShape.width * objectScale * scale.x * 0.5, y: colliderShape.y * objectScale * scale.y }); vectorList.push({ x: colliderShape.width * objectScale * scale.x * 0.5, y: colliderShape.height * objectScale * scale.y * 0.5 }); vectorList.push({ x: colliderShape.x * objectScale * scale.x, y: colliderShape.height * objectScale * scale.y * 0.5 }); return vectorList; } private toVector(vector: box.XY | box.b2Vec2): Vector { return { x: vector.x, y: vector.y }; } private setTransform(transform: Transform): void { this._transform = transform; this.sprite.position.set(transform.position.x, transform.position.y); this.sprite.angle = transform.rotation; this.sprite.scale.set(transform.scale.x, transform.scale.y); this.boxColliderShape.position.set(transform.position.x, transform.position.y); this.boxColliderShape.angle = transform.rotation; this.boxColliderShape.scale.set(transform.scale.x, transform.scale.y); } }<file_sep>export enum BodyTypes { STATIC = 0, KINEMATIC = 1, DYNAMIC = 2, } export interface Transform { position: Vector; rotation: number; scale: Vector; } export interface Vector { x: number; y: number; } export interface LineStyle { width: number; alignment?: number | undefined; native?: boolean | undefined; } export class Color { private _red: number; private _green: number; private _blue: number; private _alpha: number; public get r(): number { return this._red; } public get g(): number { return this._green; } public get b(): number { return this._blue; } public get a(): number { return this._alpha; } public get hex(): string { const red = this.rgbToHex(this._red); const green = this.rgbToHex(this._green); const blue = this.rgbToHex(this._blue); return red + green + blue; } public get hexCode(): number { return Number.parseInt("0x" + this.hex); } constructor( r: number = 0, g: number = 0, b: number = 0, a: number = 1 ) { this._red = r; this._green = g; this._blue = b; this._alpha = a; } public static black(): Color { return new Color(0, 0, 0, 1); } public static white(): Color { return new Color(255, 255, 255, 1); } public static red(): Color { return new Color(255, 0, 0, 1); } public static green(): Color { return new Color(0, 255, 0, 1); } public static blue(): Color { return new Color(0, 0, 255, 1); } public static yellow(): Color { return new Color(255, 255, 0, 1); } public static magenta(): Color { return new Color(255, 0, 255, 1); } public static cyan(): Color { return new Color(0, 255, 255, 1); } private rgbToHex(rgb: number): string { let hex = Number(rgb).toString(16); return hex.length == 1 ? "0" + hex : hex; } }<file_sep>## Project setup 1. Download Node.js 1. ```git clone```, fork or download a .zip of this repository 1. Perform a ```npm install``` inside the project 1. Run the project with ```npm run build``` <file_sep>import { Application } from './app'; const app = new Application({}); function animate() { requestAnimationFrame(animate); app.onUpdate(); } animate();<file_sep>import * as PIXI from 'pixi.js'; import * as box from 'box2d.ts'; import { GameObject } from './game_object'; import { BodyTypes } from './properties'; export class Application { private _pixiApp: PIXI.Application; private _b2world: box.b2World; private _loader: PIXI.Loader; private _objects!: Map<string, GameObject>; private _isLoaded: boolean; private get loader(): PIXI.Loader { if (!this._loader) throw new Error(`Application does not contain a loader.`); return this._loader; } constructor({ gravity = { x: 0, y: 50 } }) { this._isLoaded = false; this._pixiApp = new PIXI.Application({ width: window.screen.width, height: window.screen.height }); document.body.appendChild(this._pixiApp.view); this._b2world = new box.b2World( new box.b2Vec2(gravity.x, gravity.y) ); this._loader = this.setLoader(); this.onLoadItems(); } public onUpdate(): void { this.step(); this._objects?.forEach((obj) => { obj.onUpdate(); }); } private setLoader(): PIXI.Loader { let loader: PIXI.Loader; if (!this._isLoaded) { loader = PIXI.Loader.shared; this._isLoaded = true; } else { loader = this.loader; } return loader; } private onLoadItems(){ this.loader.add("player", "assets/images/player.png"); this.loader.add("button", "assets/images/start-button.png"); this.loader.load(); this.loader.onComplete.add(() => {this._objects = this.setObjects()}); } private getResource(index: string): PIXI.Texture<PIXI.CanvasResource> { const texture = this.loader.resources[index].texture; if (texture) {return texture as PIXI.Texture<PIXI.CanvasResource>;} return PIXI.Texture.WHITE; } private setObjects(): Map<string, GameObject> { const objArray = new Map(); objArray.set("DynamicObject", new GameObject(this._pixiApp.stage, this._b2world, { transform: { position: { x: 50, y: 20 }, scale: { x: 0.4, y: 0.4 } }, sprite: { src: this.getResource("player") }, box: { width: 362, height: 166 }, body: { bodyType: BodyTypes.DYNAMIC, density: 5.0 } })); objArray.set("Platform", new GameObject(this._pixiApp.stage, this._b2world, { transform: { position: { x: 40, y: 50 }, scale: { x: 0.4, y: 0.2 } }, sprite: { src: this.getResource("button") }, box: { width: 436, height: 149 }, body: { bodyType: BodyTypes.STATIC, density: 0.0 } })); return objArray; } private step(): void { this._b2world.ClearForces(); this._b2world.Step(1/60, 2, 6); } }
fe60cde8fca0d54008a713297c446be8767cb966
[ "Markdown", "TypeScript" ]
5
TypeScript
WHofstra/box2dPhysicsTest01
ca3e07c94c2623c1709a0bcec7797987d08682ff
02e81d07f395c6c4fcf464be4ef414d61b888645
refs/heads/main
<file_sep>import car.Car; import car.CarUtils; import org.junit.Assert; import org.junit.Test; public class CarDetailsTest { // naming for unit tests __ method name_what are the inputs_ what do // you expect to happen @Test public void getCarDetails_givenValidCar_returnsExpectedString(){ //arrange Car car= new Car(); car.setMake("Ford"); car.setModel("Mustang"); car.setYear("2019"); //act String details = CarUtils.getCarDetails(car); // assert Assert.assertEquals("2019 Ford Mustang", details); } @Test public void getCarDetails_GivenNullValues_ReturnErrorString(){ //arrange Car car= new Car(); //act String details = CarUtils.getCarDetails(car); //assert Assert.assertEquals("not able to provide details", details); } @Test public void getCarDetails_GivenOneNullValue_ReturnErrorString(){ //arrange Car car= new Car(); car.setMake("Ford"); car.setModel("Mustang"); // we did not set the year //act String details = CarUtils.getCarDetails(car); //assert Assert.assertEquals("not able to provide details", details); } @Test public void getCarDetails_GivenTwoValues_ReturnErrorString(){ //arrange Car car= new Car(); car.setMake("Ford"); //we did not set the model nor year //act String details = CarUtils.getCarDetails(car); //assert Assert.assertEquals("not able to provide details", details); } } <file_sep># Maven-UnitTesting-Lesson
6f3cc212e0146a81ff7e9e5b7a15b519d46bd287
[ "Markdown", "Java" ]
2
Java
SuitcaseCoder/Maven-UnitTesting-Lesson
e2b754d14d8e56bffe9ee5ea378492651f00b741
98e8104d048df38e2caaa9df985cb165634217c4
refs/heads/master
<repo_name>matticoli/Golden-Ratio<file_sep>/Assets/CubeController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class CubeController : MonoBehaviour { private const float phi = 1.62f; private bool varyWidth; public float deltaScale; private Vector2 screenBounds, screenOrigin; private float score = 0f; private int lives = 5; bool stop = true; void Start() { varyWidth = false; deltaScale = 0.01f; screenBounds = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width * 5 / 6, Screen.height * 5 / 6)); screenOrigin = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width / 6, Screen.height / 6)); gameObject.transform.localScale= new Vector3(1f, 1f, 1f); lives = 5; score = 0f; updateScoreText(); updateLives(); setRatio(1f); } void Update() { if(stop) { if (Input.anyKeyDown || Input.touchCount > 0) { Start(); stop = false; } return; } this.IncrementScale(); if (Input.anyKeyDown || Input.touchCount > 0) // TODO: Scoring { varyWidth = !varyWidth; if (deltaScale < phi / 10) { deltaScale *= 1.1f; } if (isGolden()) { score += phi; updateScoreText(); lives++; } else if(!stop) { lives--; } updateLives(); if (lives <= 0) { stop = true; } } if (isOffScreen()) // If cube goes off-screen { gameObject.transform.localScale /= 1.6f; } } bool isGolden() { float width = gameObject.transform.localScale.x, height = gameObject.transform.localScale.y; setRatio(varyWidth ? Mathf.Abs((height / width)) : Mathf.Abs((width / height))); return (varyWidth ? Mathf.Abs((height / width) - phi) <= 0.1 : Mathf.Abs((width / height) - phi) <= 0.1); } bool isOffScreen() { return (gameObject.transform.position.y + (gameObject.transform.localScale.y / 2) > screenBounds.y) || (gameObject.transform.position.y - (gameObject.transform.localScale.y / 2) < screenOrigin.y) || (gameObject.transform.position.x + (gameObject.transform.localScale.x / 2) > screenBounds.x) || (gameObject.transform.position.x - (gameObject.transform.localScale.x / 2) < screenOrigin.x); } void IncrementScale() { Vector3 currentScale = gameObject.transform.localScale; gameObject.transform.localScale = new Vector3(currentScale.x + (varyWidth ? deltaScale : 0), currentScale.y + (varyWidth ? 0 : deltaScale), 1f); } void setRatio(float f) { GameObject.Find("Num").GetComponent<Text>().text = (f.ToString()); } void updateScoreText() { GameObject.Find("Score").GetComponent<Text>().text = "Score: " + (score.ToString()); } void updateLives() { GameObject.Find("Lives").GetComponent<Text>().text = new string('φ', lives); } }
d14467e23e95c5e33f27d5e7a4ad7ed6a683d515
[ "C#" ]
1
C#
matticoli/Golden-Ratio
e2e4e35002997ef2d4b8b96636d468ecd62c0cb6
69973c18e8c5559bfd67a6bf8fb8e4f4124d4c84
refs/heads/master
<file_sep>package org.afyahmis.streamz.core.model; import java.time.LocalDateTime; public class Result { int id; String clientId; String name; String test; String result; LocalDateTime resultDate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getClientId() { return clientId; } public void setClientId(String clientId) { this.clientId = clientId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public LocalDateTime getResultDate() { return resultDate; } public void setResultDate(LocalDateTime resultDate) { this.resultDate = resultDate; } public String getTest() { return test; } public void setTest(String test) { this.test = test; } public Result() { } public Result(int id, String clientId, String name,String test, String result, LocalDateTime resultDate) { this.id = id; this.clientId = clientId; this.name = name; this.test=test; this.result = result; this.resultDate = resultDate; } public static Result Create(String printOut) { String[] cols = printOut.split("\\s+"); return new Result( Integer.parseInt(cols[0]), cols[1], cols[2], cols[3], cols[4], LocalDateTime.parse(cols[5])); } @Override public String toString() { return String.format("%s %s %s",name,result,resultDate); } public String getPrintOut(){ return String.format("%s|%s|%s|%s",name,result,resultDate,LocalDateTime.now()); } }<file_sep>package org.afyahmis.streamz.core.service; import org.afyahmis.streamz.core.interfaces.ResultLoader; import org.afyahmis.streamz.core.interfaces.ResultReader; import org.afyahmis.streamz.core.interfaces.ResultWriter; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; public class FileResultWriterTest { private ResultWriter resultWriter; private final String src = "/Users/koskedk/Documents/labz"; private final String stage = "/Users/koskedk/Projects/labz/stage"; private final String trash = "/Users/koskedk/Projects/labz/trash"; private final String store = "/Users/koskedk/Projects/labz/store"; @Before public void setUp() throws Exception { ResultLoader loader = new FileResultLoader(); loader.load(new String[]{src}); ResultReader resultReader = new FileResultReader(); resultWriter = new FileResultWriter(resultReader); } @After public void tearDown() throws Exception { List<String> files = Files.list(Paths.get(store)) .map(f -> f.toString()) .collect(Collectors.toList()); for (String file : files) Files.delete(Paths.get(file)); } @Test public void write() throws IOException { resultWriter.write(); List<String> contents = Files.readAllLines(Paths.get(String.format("%s/labs.txt",store))); Assert.assertTrue(contents.size() > 0); contents.forEach(c-> System.out.println(c)); } }<file_sep>package org.afyahmis.streamz; import org.afyahmis.streamz.core.interfaces.ResultLoader; import org.afyahmis.streamz.core.interfaces.ResultReader; import org.afyahmis.streamz.core.model.Result; import org.afyahmis.streamz.core.service.FileResultLoader; import org.afyahmis.streamz.core.service.FileResultReader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.IOException; import java.util.List; public class App { private static final Logger LOGGER = LogManager.getLogger(App.class); public static void main(String[] args) { LOGGER.debug("starting App"); ResultLoader loader = new FileResultLoader(); ResultReader reader=new FileResultReader(); try { loader.load( new String[]{"/Users/koskedk/Documents/labz"} ); }catch (IOException e){ LOGGER.error(e.getMessage()); } try { List<Result> results= reader.read(); results.forEach(System.out::println); }catch (Exception e){ LOGGER.error(e.getMessage()); } LOGGER.debug("App completed !"); } } <file_sep>package org.afyahmis.streamz.core.interfaces; public interface ResultWriter { void write(); } <file_sep>package org.afyahmis.streamz.core.service; import org.afyahmis.streamz.core.interfaces.ResultLoader; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; public class FileResultLoader implements ResultLoader { private static final Logger LOGGER = LogManager.getLogger(FileResultLoader.class); private final String stage = "/Users/koskedk/Projects/labz/stage"; private final String trash = "/Users/koskedk/Projects/labz/trash"; public void load(String[] locations) throws IOException { for (String location : locations) { LOGGER.trace(String.format("reading from %s", location)); //valid files List<String> files = Files .list(Paths.get(location)) .map(f -> f.toString()) .collect(Collectors.toList()); files.forEach(f->{ String fileName=Paths.get(f).getFileName().toString(); String dest=String.format("%s/%s",stage,fileName); try { Files.copy(Paths.get(f),Paths.get(dest), StandardCopyOption.REPLACE_EXISTING); }catch (Exception e) { LOGGER.error(e.getMessage()); } }); } } } <file_sep>package org.afyahmis.streamz.core.service; import org.afyahmis.streamz.core.interfaces.ResultLoader; import org.afyahmis.streamz.core.model.Result; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.sql.SQLOutput; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.*; public class FileResultLoaderTest { private ResultLoader loader; private final String src = "/Users/koskedk/Documents/labz"; private final String stg = "/Users/koskedk/Projects/labz/stage"; private final String trs = "/Users/koskedk/Projects/labz/trash"; @Before public void setUp() throws Exception { loader = new FileResultLoader(); } @After public void tearDown() throws Exception { List<String> files= Files.list(Paths.get(stg)) .map(f->f.toString()) .collect(Collectors.toList()); for(String file: files) Files.delete(Paths.get(file)); } @Test public void load() throws IOException { loader.load(new String[]{src}); List<String> files= Files.list(Paths.get(stg)) .map(f->f.toString()) .collect(Collectors.toList()); Assert.assertTrue(files.size()>0); files.forEach(System.out::println); } }
95702b0bb5d28fe5d8b4f9e7c276f9351bb783d0
[ "Java" ]
6
Java
koskedk/streamz
2950b38d3bc711c0fcde8793666b68e3efc43375
d7105bcb079442efb4d18ea65c1db217473e2e50
refs/heads/master
<repo_name>BrightBridgeWeb/django-mako-plus<file_sep>/docs/static_links.rst Including Static Files ================================ In the `tutorial <tutorial_css_js.html>`_, you learned how to automatically include CSS and JS based on your page name . If your page is named ``mypage.html``, DMP will automatically include ``mypage.css`` and ``mypage.js`` in the page content. Skip back to the `tutorial <tutorial_css_js.html>`_ if you need a refresher. Open ``base.htm`` and look at the following code: :: ## render the static file links for this template ${ django_mako_plus.links(self) } The calls to ``links(self)`` include the ``<link>`` and ``<script>`` tags for the template name and all of its supertemplates. These links are placed at the end of your ``<head>`` section. (Just a few years ago, common practice was to place script tags at the end of the body, but modern browsers with asyncronous and deferred scripts have put them back in the body.) This all works because the ``index.html`` template extends from the ``base.htm`` template. If you fail to inherit from ``base.htm`` or ``base_ajax.htm``, DMP won't be able to include the support files. Javascript Matters ---------------------------------- Your ``base.htm`` file contains the following script link: :: <script src="/django_mako_plus/dmp-common.min.js"></script> This file contains a few functions that DMP uses to run scripts and send context variables to your javascript. It is important that this link be loaded **before** any DMP calls are done in your templates. When running in production mode, your web server (IIS, Nginx, etc.) should serve this file rather than Django. Or you may want to include the file in a bundler like webpack. In any case, the file just needs to be included on every page of your site, so do it in an efficient way for your setup. The following is an example setting for Nginx: :: location /django_mako_plus/dmp-common.min.js { alias /to/django_mako_plus/scripts/dmp-common.min.js; } If you don't know the location of DMP on your server, try this command: :: python3 -c 'import django_mako_plus; print(django_mako_plus.__file__)' Preprocessors (Scss and Less) ----------------------------------- If you are using preprocessors for your CSS or JS, DMP can automatically compile files. While this could alternatively be done with an editor plugin or with a 'watcher' process, letting DMP compile for you keeps the responsibility within your project settings (rather than per-programmer-dependent setups). When this feature is enabled, DMP looks for ``app_folder/styles/index.scss``. If it exists, DMP checks the timestamp of the compiled version, ``app_folder/styles/index.css``, to see if if recompilation is needed. If needed, it runs ``scss`` before generating ``<link type="text/css" />`` for the file. During development, this check is done every time the template is rendered. During production, this check is done only once -- the first time the template is rendered. To enable automatic compiling, uncomment the appropriate provider to your settings.py. The following setting adds Scss compiling to the normal JS Context, JS, and CSS providers: .. code-block:: python TEMPLATES = [ { 'NAME': 'django_mako_plus', 'BACKEND': 'django_mako_plus.MakoTemplates', 'OPTIONS': { 'CONTENT_PROVIDERS': [ { 'provider': 'django_mako_plus.JsContextProvider' }, # adds JS context - this should normally be listed first { 'provider': 'django_mako_plus.CompileScssProvider' }, # autocompiles Scss files # { 'provider': 'django_mako_plus.CompileLessProvider' }, # autocompiles Less files { 'provider': 'django_mako_plus.CssLinkProvider' }, # generates links for app/styles/template.css { 'provider': 'django_mako_plus.JsLinkProvider' }, # generates links for app/scripts/template.js ], }, }, ] Rendering Other Pages ------------------------------ But suppose you need to autorender the JS or CSS from a page *other than the one currently rendering*? For example, you need to include the CSS and JS for ``otherpage.html`` while ``mypage.html`` is rendering. This is a bit of a special case, but it has been useful at times. To include CSS and JS by name, use the following within any template on your site (``mypage.html`` in this example): .. code-block:: html+mako ## instead of using the normal: ## ${ django_mako_plus.links(self) } ## ## specify the app and page name: ${ django_mako_plus.template_links(request, 'homepage', 'otherpage.html', context) Rendering Nonexistent Pages ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This special case is for times when you need the CSS and JS autorendered, but don't need a template for HTML. The ``force`` parameter allows you to force the rendering of CSS and JS files, even if DMP can't find the HTML file. Since ``force`` defaults True, the calls just above will render even if the template isn't found. In other words, this behavior already happens; just use the calls above. Even if ``otherpage.html`` doesn't exist, you'll get ``otherpage.css`` and ``otherpage.js`` in the current page content. <file_sep>/docs/basics.rst Basic Concepts ========================== After the tutorial, start through these topics to learn how to use DMP. .. toctree:: :maxdepth: 1 basics_settings basics_escaping basics_variables basics_paths basics_convenience basics_redirecting basics_converters basics_csrf basics_django The following are further destinations to learn Mako and Django: - Go through the `Mako Templates <http://www.makotemplates.org/>`__ documentation. It will explain all the constructs you can use in your html templates. - Read or reread the `Django Tutorial <http://www.djangoproject.com/>`__. Just remember as you see the tutorial's Django template code (usually surrounded by ``{{ }}``) that you'll be using Mako syntax instead (``${ }``). - Link to this project in your blog or online comments. I'd love to see the Django people come around to the idea that Python isn't evil inside templates. Complex Python might be evil, but Python itself is just a tool within templates. <file_sep>/django_mako_plus/webroot/dmp-common.js // note that I'm intentionally using older JS syntax to meet // the widest possible browser base (function() { // if dmp-common.js already ran (duplicate <script> or inclusion in two bundles), // short circuit because it may already have data in it. if (window.DMP_CONTEXT) { return; } // connect the dmp object window.DMP_CONTEXT = { __version__: '5.7.9', // DMP version to check for mismatches contexts: {}, // contextid -> context1 contextsByName: {}, // app/template -> [ context1, context2, ... ] lastContext: null, // last inserted context (see getAll() below) bundleFunctions: {}, // functions that wraps template JS/CSS (see DMP's webpack docs) /* Adds data to the DMP context under the given key */ set: function(version, contextid, data, templates) { if (DMP_CONTEXT.__version__ != version) { console.warn('DMP framework version is ' + version + ', while dmp-common.js is ' + DMP_CONTEXT.__version__ + '. Unexpected behavior may occur.'); } // link this contextid to the data and templates DMP_CONTEXT.contexts[contextid] = { id: contextid, data: data, templates: templates, triggerCount: 0 }; DMP_CONTEXT.lastContext = DMP_CONTEXT.contexts[contextid]; // reverse lookups by name to contextid for (var i = 0; i < templates.length; i++) { if (typeof DMP_CONTEXT.contextsByName[templates[i]] === "undefined") { DMP_CONTEXT.contextsByName[templates[i]] = []; } DMP_CONTEXT.contextsByName[templates[i]].push(contextid); } }, /* Retrieves context data. If multiple script contexts are found, such as when ajax retrieves the same template snippet multiple times, the last one is returned. DMP_CONTEXT.get() // for the currently-executing script DMP_CONTEXT.get('myapp/mytemplate') // for the app/template DMP_CONTEXT.get(document.querySelector('some selector')) // for the specified <script> tag */ get: function(option) { var ret = DMP_CONTEXT.getAll(option); if (ret.length == 0) { return undefined; } return ret[ret.length - 1]; }, /* Retrieves the context data for all scripts on the page matching the option. The returned array usually has one context item. But when ajax retrieves the same template snippet multiple times, it will have multiple contexts in the array. DMP_CONTEXT.getAll() // an array of one item: currently-executing script // (this is the preferred way when on script's first execution) DMP_CONTEXT.getAll(elem) // an array of one item: context for the given <script> element // (elem retrieved with querySelector, getElementById, etc.) DMP_CONTEXT.getAll('myapp/mytemplate') // an array of all scripts matching this template name */ getAll: function(option) { var ret = []; // if empty option and we have currentScript[data-context="something"], use that for the option if (!option && document.currentScript && document.currentScript.getAttribute('data-context')) { option = document.currentScript; } // if still empty option, get the last-added context if (!option && DMP_CONTEXT.lastContext) { ret.push(DMP_CONTEXT.lastContext.data); } // if a string, assume it is a context name in format "app/template" else if (typeof option === 'string' || option instanceof String) { var contextids = DMP_CONTEXT.contextsByName[option]; if (typeof contextids !== "undefined") { for (var i = 0; i < contextids.length; i++) { var c = DMP_CONTEXT.contexts[contextids[i]]; if (typeof c !== "undefined") { ret.push(c.data); } } } } // if script[current-context="something"] else if (option && option.nodeType === 1 && option.nodeName.toLowerCase() == 'script' && option.getAttribute('data-context')) { var c = DMP_CONTEXT.contexts[option.getAttribute('data-context')]; if (typeof c !== "undefined") { ret.push(c.data); } }//if return ret; }, //////////////////////////////////////////////////////////////////// /// Webpack bundling functions /* Links a bundle-defined template function so it can be called from DMP_CONTEXT (i.e. outside the bundle). We only allow functions to link once so state isn't overwritten by duplicate script tags. */ linkBundleFunction(template, func) { if (typeof DMP_CONTEXT.bundleFunctions[template] === "undefined") { DMP_CONTEXT.bundleFunctions[template] = func; } }, /* Checks if bundle-defined template functions need to run for a function. We check with every script's onLoad as well as an explicit call. This ensures the functions are run when async and/or out of order. */ checkBundleLoaded(contextid) { // get the context var context = DMP_CONTEXT.contexts[contextid]; if (typeof context === "undefined") { return; } // are all the bundles we need loaded? for (var i = 0; i < context.templates.length; i++) { var template = context.templates[i]; if (typeof DMP_CONTEXT.bundleFunctions[template] === "undefined") { return; } } // everything is here, so run the bundle functions // for each time the triggerBundleContext() was called while (context.triggerCount > 0) { context.triggerCount = Math.max(0, context.triggerCount - 1); for (var i = 0; i < context.templates.length; i++) { var template = context.templates[i]; if (DMP_CONTEXT.bundleFunctions[template]) { // might be null (if no scripts for the template) DMP_CONTEXT.bundleFunctions[template](); } } } }, /* Triggers a template context to run a given bundle. */ triggerBundleContext(contextid) { // get the context var context = DMP_CONTEXT.contexts[contextid]; if (typeof context === "undefined") { return; } // increase the trigger count and check the bundle context.triggerCount++; DMP_CONTEXT.checkBundleLoaded(contextid); }, };//DMP_CONTEXT })() <file_sep>/django_mako_plus/provider/link.py from django.core.exceptions import ImproperlyConfigured from django.conf import settings from django.forms.utils import flatatt import logging import os import os.path import posixpath from ..util import crc32, getdefaultattr from ..util import log from .base import BaseProvider ##################################################### ### LinkProvider abstract base class class LinkProvider(BaseProvider): ''' Renders links like <link> and <script> based on the name of the template and supertemplates. ''' DEFAULT_OPTIONS = { # explicitly sets the path to search for - if this filepath exists, DMP # includes a link to it in the template. globs are not supported because this # should resolve to one exact file. possible values: # 1. None: a default path is used, such as "{app}/{subdir}/{filename.ext}", prefixed # with the static root at production; see subclasses for their default filenames. # 2. function, lambda, or other callable: called as func(provider) and # should return a string # 3. str: used directly 'filepath': None, # explicitly sets the link to be inserted into the template (when filepath exists). # possible values: # 1. None: a default path is used, such as "<script src="..."></script>, prefixed # with the static url at production; see subclasses for the default link format. # 2. function, lambda, or other callable: called as func(provider) and # should return a string # 3. str: inserted directly into the template 'link': None, # if a template is rendered more than once in a request, should we link more than once? # defaults are: css=False, js=True, bundled_js=False 'skip_duplicates': False, } def __init__(self, template, options): super().__init__(template, options) self.filepath = os.path.join( settings.BASE_DIR if settings.DEBUG else settings.STATIC_ROOT, self.build_source_filepath() ) # file time and version hash try: self.mtime = int(os.stat(self.filepath).st_mtime) # version_id combines current time and the CRC32 checksum of file bytes self.version_id = (self.mtime << 32) | crc32(self.filepath) except FileNotFoundError: self.mtime = 0 self.version_id = 0 if log.isEnabledFor(logging.DEBUG): log.debug('%s created for %s: [%s]', repr(self), self.filepath, 'will link' if self.mtime > 0 else 'will skip nonexistent file') ### Source Filepath Building Methods ### def build_source_filepath(self): # if defined in settings, run the function or return the string if self.options['filepath'] is not None: return self.options['filepath'](self) if callable(self.options['filepath']) else self.options['filepath'] # build the default if self.app_config is None: log.warn('{} skipped: template %s not in project subdir and `targetpath` not in settings', (self.__class__.__qualname__, self.template_relpath)) return self.build_default_filepath() def build_default_filepath(self): raise ImproperlyConfigured('{} must set `filepath` in options (or a subclass can override build_default_filepath).'.format(self.__class__.__qualname__)) ### Target Link Building Methods ### def build_target_link(self, provider_run, data): # if defined in settings, run the function or return the string if self.options['link'] is not None: return self.options['link'](self) if callable(self.options['link']) else self.options['link'] # build the default if self.app_config is None: log.warn('{} skipped: template %s not in project subdir and `targetpath` not in settings', (self.__class__.__qualname__, self.template_relpath)) return self.build_default_link(provider_run, data) def build_default_link(self, provider_run, data): raise ImproperlyConfigured('{} must set `link` in options (or a subclass can override build_default_link).'.format(self.__class__.__qualname__)) ### Provider Run Methods ### def start(self, provider_run, data): # add a set to the request (fallback to provider_run if request is None) for skipping duplicates if self.options['skip_duplicates']: data['seen'] = getdefaultattr( provider_run.request.dmp if provider_run.request is not None else provider_run, '_LinkProvider_Filename_Cache_', factory=set, ) # enabled providers in the chain go here data['enabled'] = [] def provide(self, provider_run, data): filepath = self.filepath # delaying printing of tag to finish() because the JsContextProvider delays and this must go after it # short circuit if the file for this provider doesn't exist if self.mtime == 0: return # short circut if we're skipping duplicates and we've already seen this one if self.options['skip_duplicates']: if filepath in data['seen']: if log.isEnabledFor(logging.DEBUG): log.debug('%s skipped duplicate %s', repr(self), self.filepath) return data['seen'].add(filepath) # if we get here, this provider is enabled, so add it to the list if log.isEnabledFor(logging.DEBUG): log.debug('%s linking %s', repr(self), self.filepath) data['enabled'].append(self) def finish(self, provider_run, data): for provider in data['enabled']: provider_run.write(provider.build_target_link(provider_run, data)) ##################################### ### CssLinkProvider class CssLinkProvider(LinkProvider): '''Generates a CSS <link>''' DEFAULT_OPTIONS = { 'group': 'styles', # if a template is rendered more than once in a request, we usually don't # need to include the css again. 'skip_duplicates': True, } def build_default_filepath(self): return os.path.join( self.app_config.name, 'styles', self.template_relpath + '.css', ) def build_default_link(self, provider_run, data): attrs = {} attrs['rel'] = 'stylesheet' attrs["data-context"] = provider_run.uid attrs["href"] ="{}?{:x}".format( # posixpath because URLs use forward slash posixpath.join( settings.STATIC_URL, self.app_config.name, 'styles', self.template_relpath.replace(os.path.sep, '/') + '.css', ), self.version_id, ) return '<link{} />'.format(flatatt(attrs)) ############################################## ### JsLinkProvider class JsLinkProvider(LinkProvider): '''Generates a JS <script>.''' DEFAULT_OPTIONS = { 'group': 'scripts', # if a template is rendered more than once in a request, we should link each one # so the script runs again each time the template runs 'skip_duplicates': False, # whether to create an async script tag 'async': False, } def build_default_filepath(self): return os.path.join( self.app_config.name, 'scripts', self.template_relpath + '.js', ) def build_default_link(self, provider_run, data): attrs = {} attrs["data-context"] = provider_run.uid attrs["src"] ="{}?{:x}".format( # posixpath because URLs use forward slash posixpath.join( settings.STATIC_URL, self.app_config.name, 'scripts', self.template_relpath.replace(os.path.sep, '/') + '.js', ), self.version_id, ) if self.options['async']: attrs['async'] = "async" return '<script{}></script>'.format(flatatt(attrs)) <file_sep>/django_mako_plus/provider/base.py from django.apps import apps from django.conf import settings import os, inspect import logging from ..util import log TEMPLATE_ATTR_NAME = '_dmp_provider_cache_' ############################################################## ### Abstract Provider Base class BaseProvider(object): ''' Abstract base provider class. An instance is tied to a template at runtime. Note that the app can only be inferred for templates in project apps (below settings.BASE_DIR). The app has to be inferred because mako creates templates internally during the render runtime, and I don't want to hack into Mako internals. Always set: self.template Mako template object self.options The combined options from the provider, its supers, and settings.py self.template_ext Template extension. If app can be inferred (None if not): self.app_config AppConfig the template resides in, if possible to infer. self.template_relpath Template path, relative to app/templates/, without extension. Usually this is just the template name, but could contain a subdirectory: homepage/templates/index.html => "index" homepage/templates/forms/login.html => "forms/login" ''' DEFAULT_OPTIONS = { # the group this provider is part of. this only matters when # the html page limits the providers that will be called with # ${ django_mako_plus.links(group="...") } 'group': 'styles', # whether enabled (see "Dev vs. Prod" in the DMP docs) 'enabled': True, } @classmethod def instance_for_template(cls, template, options): '''Returns an instance for the given template''' # Mako already caches template objects, so I'm attaching provider instances to templates provider_cache = getattr(template, TEMPLATE_ATTR_NAME, None) if provider_cache is None: provider_cache = {} setattr(template, TEMPLATE_ATTR_NAME, provider_cache) try: return provider_cache[options['_template_cache_key']] except KeyError: pass # not cached yet, so create the object instance = cls(template, options) if not settings.DEBUG: provider_cache[options['_template_cache_key']] = instance return instance def __init__(self, template, options): self.template = template self.options = options self.app_config = None self.template_ext = None self.template_relpath = None self.template_name = None if self.template.filename is not None: # try to infer the app fn_no_ext, self.template_ext = os.path.splitext(template.filename) relpath = os.path.relpath(fn_no_ext, settings.BASE_DIR) if not relpath.startswith('..'): # can't infer reliably outside of project dir try: path_parts = os.path.normpath(relpath).split(os.path.sep) self.app_config = apps.get_app_config(path_parts[0]) self.template_relpath = '/'.join(path_parts[2:]) self.template_name = path_parts[-1] except LookupError: # template isn't under an app pass def __repr__(self): return '<{}{}: {}/{}>'.format( self.__class__.__qualname__, '' if self.options['enabled'] else ' (disabled)', self.app_config.name if self.app_config is not None else 'unknown', self.template_relpath if self.template_relpath is not None else self.template, ) @property def group(self): return self.options['group'] def start(self, provider_run, data): ''' Called on the *main* template's provider list as the run starts. Initialize values in the data dictionary here. ''' def provide(self, provider_run, data): '''Called on *each* template's provider list in the chain - use provider_run.write() for content''' def finish(self, provider_run, data): ''' Called on the *main* template's provider list as the run finishes Finalize values in the data dictionary here. ''' <file_sep>/docs/topics.rst Special Topics ========================== The following are special topics / advanced features of DMP: .. toctree:: :maxdepth: 1 topics_converters topics_view_function topics_partial_templates topics_class_views topics_signals topics_translation <file_sep>/tests_project/homepage/tests/test_uid.py from django_mako_plus import uid class Tester(uid.Tester): # extending it here allows the Django test suite to find # the tests already in the uid module pass <file_sep>/docs/install_as_renderer.rst Using DMP to Render Mako Templates ======================================= The following shows how to use DMP to render Mako templates only -- without any of DMP's other features. It uses DMP as a normal template engine within a vanilla Django project. Install Django, Mako, and DMP ---------------------------------- DMP works with Django 1.9+, including the 2.0 releases. The following will install all three dependencies: :: pip3 install --upgrade django-mako-plus (note that on Windows machines, ``pip3`` may need to be replaced with ``pip``) Create a Vanilla Django Project ------------------------------------- 1. Create a vanilla Django project. You may want to follow the `standard Django Tutorial <https://docs.djangoproject.com/en/dev/intro/tutorial01/>`_ to create a ``mysite`` project. Follow the tutorial through the section creating templates. 2. Create a basic view function in ``polls/views.py``: .. code-block:: python from django.shortcuts import render from datetime import datetime def index(request): context = { 'now': datetime.now(), } return render(request, 'polls/index.html', context) 3. Create a template in ``polls/templates/polls/index.html``: :: <html> <body> The current time is {{ now|date:'c' }} </body> </html> 4. Add a path in ``mysite/urls.py``: .. code-block:: python from django.urls import url from polls import views urlpatterns = [ url('', views.index, name='index'), ] Run the project and go to `http://localhost:8000/ <http://localhost:8000/>`_. Note that everything above is a normal Django project -- DMP isn't in play yet. Enable the DMP Template Engine ---------------------------------- 1. Add DMP to your installed apps in ``settings.py``. .. code-block:: python INSTALLED_APPS = [ ... 'django_mako_plus', 'polls', ] 2. Add the DMP template engine in ``settings.py``. .. code-block:: python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, { 'NAME': 'django_mako_plus', 'BACKEND': 'django_mako_plus.MakoTemplates', }, ] Note that we won't be using DMP to render templates. But as a Django template engine, DMP initializes by being listed in ``TEMPLATES``. We've listed DMP *after* the Django template renderer so Django can match and render templates first. 3. Enable a logger in ``settings.py`` to see DMP routing information and other messages: .. code-block:: python LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'loggers': { 'django_mako_plus': { 'handlers': ['console_handler'], 'level': DEBUG and 'DEBUG' or 'WARNING', 'propagate': False, }, 'django': { 'handlers': ['console_handler'], 'level': 'INFO', 'propagate': False, }, }, 'handlers': { 'console_handler': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', }, }, } Create a View with Mako Syntax ------------------------------------- Let's create a new endpoint that uses the Mako engine. We'll leave the ``index`` endpoint as a Django template. 1. Add another endpoint to ``polls/views.py``: .. code-block:: python from django.shortcuts import render from datetime import datetime def index(request): context = { 'now': datetime.now(), } return render(request, 'polls/index.html', context) def another(request): context = { 'now': datetime.now(), } return render(request, 'polls/another.html', context) 2. Create a Mako-syntax template in ``polls/templates/another.html``: :: <html> <body> The current time is ${ now.strftime('c') } </body> </html> Note that your two templates are in **different folders**: * ``mysite/polls/templates/polls/index.html`` * ``mysite/polls/templates/another.html`` See how the extra ``polls`` is missing in the DMP template? That's because DMP template discovery algorithm is "app-aware". When the view function specifies ``polls/another.html``, DMP interprets it using the pattern ``appname/templatename``. The following code instructs DMP to go to the ``polls`` app and look for the ``another.html`` template. Where Django would enumerate all your apps in search of the file, DMP looks for exactly one file path. .. code-block:: python # goes directly to `polls/templates/another.html` render(request, 'polls/another.html', context) We could adjust the DMP algorithm to match Django's locations, but the difference gives a nice separation when both Mako and Django templates exist in the same project. 3. Add a path in ``mysite/mysite/urls.py``: .. code-block:: python from django.urls import path from polls import views # note this is Django 2.x syntax urlpatterns = [ path('', views.index, name='index'), path('another', views.another, name='another'), ] Run the project and go to `http://localhost:8000/another <http://localhost:8000/another>`_. Congratulations. You've got a standard Django project that can render Mako syntax. <file_sep>/docs/topics_converters.rst Parameter Conversion ========================== .. contents:: :depth: 2 DMP automatically converts URL parameters for you. To enable this, simply put standard Python type hints in your ``process_request`` functions: .. code-block:: python def process_request(request, name:str, age:int=40, happy:bool=True): ... These were already discussed in other areas of our documentation: * `Built-in Converters </tutorial_urlparams.html#automatic-type-converters>`_ for a list of supported types. * `Converting URL Parameters </basics_converters.html>`_ for the primer. This page contains more advanced conversion topics. Raw Parameter Values ------------------------- During URL resolution, DMP populates the ``request.dmp.urlparams[ ]`` list with all URL parts *after* the first two parts (``/homepage/index/``), up to the ``?`` (query string). For example, the URL ``/homepage/index/144/A58UX/`` has two urlparams: ``144`` and ``A58UX``. These can be accessed as ``request.dmp.urlparams[0]`` and ``request.dmp.urlparams[1]`` throughout your view function. Empty parameters and trailing slashes are handled in a specific way. The following table gives examples: +--------------------------------------------------+-----------------------------------------------------------+ | ``/homepage/index/first/second/`` | ``request.urlparam = [ 'first', 'second' ]`` | +--------------------------------------------------+-----------------------------------------------------------+ | ``/homepage/index/first/second`` | ``request.urlparam = [ 'first', 'second' ]`` | +--------------------------------------------------+-----------------------------------------------------------+ | ``/homepage/index/first//`` | ``request.urlparam = [ 'first', '' ]`` | +--------------------------------------------------+-----------------------------------------------------------+ | ``/homepage/index`` | ``request.urlparam = [ ]`` | +--------------------------------------------------+-----------------------------------------------------------+ In the examples above, the first and second URL result in the *same* list, even though the first URL has an ending slash. The ending slash is optional and can be used to make the URL prettier. The ending slash is optional because DMP's default ``urls.py`` patterns ignore it. If you define custom URL patterns instead of including the default ones, be sure to add the ending ``/?`` (unless you explicitly want the slash to be explicitly counted). In the Python language, the empty string and None have a special relationship. The two are separate concepts with different meanings, but both evaluate to False, acting the same in the truthy statement: ``if not mystr:``. Denoting "empty" parameters in the url is uncertain because: 1. Unless told otherwise, many web servers compact double slashes into single slashes. ``http://localhost:8000/storefront/receipt//second/`` becomes ``http://localhost:8000/storefront/receipt/second/``, preventing you from ever seeing the empty first paramter. 2. There is no real concept of "None" in a URL, only an empty string or some character *denoting* the absence of value. Because of these difficulties, the urlparams list is programmed to never return None and never raise IndexError. Even in a short URL with only a few parameters, accessing ``request.dmp.urlparams[50]`` returns an empty string. For this reason, the default converters for booleans and Models objects equate the empty string *and* dash '-' as the token for False and None, respectively. The single dash is especially useful because it provides a character in the URL (so your web server doesn't compact that position) and explicitly states the value. Your custom converters can override this behavior, but be sure to check for the empty string in ``request.dmp.urlparams`` instead of ``None``. Conversion Errors -------------------------------- Suppose we use a url of ``/homepage/index/Homer/a/t/`` to the example above. The integer converter will fail because ``a`` is not a valid integer. A ValueError is raised. When this occurs, the default behavior of DMP is to raise an Http404 exception, indicating to the browser that the given url does not exist. If you want a different resolution to conversion errors, such as a redirect, the sections below explain how to customize the conversion process. Adding a Custom Converter -------------------------------- Suppose we want to use geographic locations in the format "20.4,-162.0". The URL might looks something like this: ``http://localhost:8000/homepage/index/20.4,-162.0/`` Let's place our new class and converter function in ``homepage/__init__.py`` (you can actually place these in any file that loads with Django). Decorate the function with ``@parameter_converter``, with the type(s) as arguments. .. code-block:: python from django_mako_plus import parameter_converter class GeoLocation(object): def __init__(self, latitude, longitude): self.latitude = latitude self.longitude = longitude @parameter_converter(GeoLocation) def convert_geo_location(value, parameter): parts = value.split(',') if len(parts) < 2: raise ValueError('Both latitude and longitude are required') # the float constructor will raise ValueError if invalid return GeoLocation(float(parts[0]), float(parts[1])) When called, your function must do one of the following: 1. Return the converted type. 2. Raise an exception, such as: * a ValueError, which causes DMP to return not found (Http404) to the browser. * Raise DMP's RedirectException, which redirects the browser url. * Raise DMP's InternalRedirectException, which immediately calls a different view function (without changing the browser url). * Raise Django's Http404 with a custom message. Now in ``homepage/views/index.py``, use our custom ``GeoLocation`` class as the type hint in the index file. .. code-block:: python @view_function def process_request(request, loc:GeoLocation): print(loc.latitude) print(loc.longitude) return request.dmp.render('index.html', {}) When a request occurs, DMP will read the signature on ``process_request``, look up the ``GeoLocation`` type, and use your function to convert the string to a GeoLocation object. Special Considerations for Models -------------------------------------- Since Python usually parses converter functions **before** your models are ready, you can't reference them by type. This issue is `described in the Django documentation <https://docs.djangoproject.com/en/dev/ref/models/fields/#module-django.db.models.fields.related>`_. In other words, the following doesn't work: .. code-block:: python from django_mako_plus import parameter_converter from homepage.models import Question @parameter_converter(Question) def convert_question(value, parameter): ... DMP uses the same solution as Django when referencing models: use "app.Model" syntax. In the following function, we specify the type as a string. After Django starts up, DMP replaces the string with the actual type. .. code-block:: python from django_mako_plus import parameter_converter @parameter_converter("homepage.Question") def convert_question(value, parameter): ... Using string-based types only works with models (not with other types). Replacing the Converter -------------------------------- There may be situations where you need to specialize the converter. This is done by subclassing the ``ParameterConverter`` class and referencing your subclass in ``settings.py``. As an example, suppose you need to convert the first url parameter in a standard way, regardless of its type. The following code looks for this parameter by position: .. code-block:: python from django_mako_plus.converter.base import ParameterConverter class SiteConverter(BaseConverter): '''Customized converter that always converts the first parameter in a standard way, regardless of type''' def convert_value(self, value, parameter, request): # in the view function signature, request is position 0 # and the first url parameter is position 1 if parameter.position == 1: return some_custom_converter(value, parameter) # any other url params convert the normal way return super().convert_value(value, parameter, request) We'll assume you placed the class in ``myproject/lib/converters.py``. Activate your new converter in DMP's section of ``settings.py``: .. code-block:: python DEFAULT_OPTIONS = { 'PARAMETER_CONVERTER': 'lib.converters.SiteConverter', } All parameters in the system will now use your customization rather than the standard DMP converter. Non-Wrapping Decorators -------------------------------- Automatic conversion is done using ``inspect.signature``, which comes standard with Python. This function reads your ``process_request`` source code signature and gives DMP the parameter hints. As we saw in the `tutorial <tutorial_urlparams.html#adding-type-hints>`_, your code specifies these hints with something like the following: .. code-block:: python @view_function def process_request(request, hrs:int, mins:int, forward:bool=True): ... The trigger for DMP to read parameter hints is the ``@view_function`` decorator, which signals a callable endpoint to DMP. When it sees this decorator, DMP goes to the wrapped function, ``process_request``, and inspects the hints. Normally, this process works without issues. But it can fail when certain decorators are chained together. Consider the following code: .. code-block:: python @view_function @other_decorator # this might mess up the type hints! def process_request(request, hrs:int, mins:int, forward:bool=True): ... If the developer of ``@other_decorator`` didn't "wrap" it correctly, DMP will **read the signature from the wrong function**: ``def other_decorator(...)`` instead of ``def process_request(...)``! This issue is well known in the Python community -- Google "fix your python decorators" to read many blog posts about it. Debugging when this occurs can be fubar and hazardous to your health. Unwrapped decorators are essentially just function calls, and there is no way for DMP to differentiate them from your endpoints (without using hacks like reading your source code). You'll know something is wrong because DMP will ignore your parameters, sent them the wrong values, or throw unexpected exceptions during conversion. If you are using multiple decorators on your endpoints, check the wrapping before you debug too much (next paragraph). You can avoid/fix this issue by ensuring each decorator you are using is wrapped correctly, per the Python decorator pattern. When coding ``other_decorator``, be sure to include the ``@wraps(func)`` line. You can read more about this in the `Standard Python Documentation <https://docs.python.org/3/library/functools.html#functools.wraps>`_. The pattern looks something like the following: .. code-block:: python from functools import wraps def other_decorator(func): @wraps(func) def wrapper(request, *args, **kwargs): # decorator work here goes here # ... # call the endpoint return func(request, *args, **kwargs) # outer function return return wrapper When your inner function is decorated with ``@wraps``, DMP is able to "unwrap" the decorator chain to the real endpoint function. If your decorator comes from third-party code that you can't control, one solution is to create a new decorator (following the pattern above) that calls the third-party function as its "work". Then decorate functions with your own decorator rather than the third-party decorator. Disabling the Converter ------------------------------ If you want to entirely disable the parameter converter, set DMP's converter setting to None. This will result in a slight speedup. .. code-block:: python DEFAULT_OPTIONS = { 'PARAMETER_CONVERTER': None, } <file_sep>/django_mako_plus/uid.py #!/usr/bin/env python3 ''' Created by <NAME> <<EMAIL>> Apache open source license. November, 2017 ''' ################################################## ### Unique id generator. Similar to uuid1() but ### also includes the process id. ### ### Note that upping the counter requires a global lock. ### ### The bit assignment: ### ### 52 bits for nanoseconds since epoch (really it can use unlimited bits because on left side of the number, but 52 bits gets us to ~2100) ### 16 bits for counter ### 48 bits for machine id ### 24 bits for process id ### ======== ### 140 bits total, or 35 hex characters ### ### Maximum number is 1.39e42 ### import uuid import time as time import os import random import threading import math import collections # initial values/constants lastnow = 0 counterstart = random.getrandbits(16) - 1 countermax = math.pow(2, 16) - 1 counter = counterstart # returns a 48 bit number machineid = uuid.getnode() # linux is usually 16 bits processid = os.getpid() # the main data structure UID = collections.namedtuple('UID', ( 'time', 'counter', 'machine', 'process' )) # binary size of each number # and binary positions for shifting # and for splitting hex and binary (from right side) size = UID(52, 16, 48, 24) _shift = [] for i in reversed(range(len(size))): _shift.append(sum(size[i:])) shift = UID(*reversed(_shift)) hsplit = UID(*(int(s/-4) for s in shift)) bsplit = UID(*(s*-1 for s in shift)) ###################################### ### Main API def ruid(): ''' Creates a "raw" unique id. The result is a UID namedtuple with four parts: time counter machine process All other functions in this module just format the id created in this function. ''' global lastnow, counter_start, counter # update the nanoseconds and counter with threading.RLock(): now = int(time.time())#int(time.time() * 1e6) counter += 1 if counter >= countermax: counter = 0 while now == lastnow and counter == counterstart: time.sleep(.001) # wait a millisecond and try again now = int(time.time())#int(time.time() * 1e6) lastnow = now # return the named tuple return UID(now, counter, machineid, processid) def iuid(raw=None): ''' Creates a unique id as an int. If provided, raw should be a UID named tuple (usually from a call to ruid). ''' if raw is None: raw = ruid() return (raw.time << shift.counter) + \ (raw.counter << shift.machine) + \ (raw.machine << shift.process) + \ (raw.process) def uid(raw=None, sep=None): ''' Creates a unique id as a hex string. If provided, raw should be a UID named tuple (usually from a call to ruid). Use sep='-' to separate the parts by dashes. ''' if raw is None: raw = ruid() # hex version if sep is None: return '{:0x}'.format(iuid(raw)) # pretty version n = uid(raw) return sep.join(( n[:hsplit.counter], n[hsplit.counter: hsplit.machine], n[hsplit.machine: hsplit.process], n[hsplit.process:], )) def buid(raw=None, sep=None): ''' Creates a unique id as a binary string. If provided, raw should be a UID named tuple (usually from a call to ruid). Use sep='-' to separate the parts by dashes. ''' if raw is None: raw = ruid() # hex version if sep is None: return '{:0b}'.format(iuid(raw)) # pretty version n = buid(raw) return sep.join(( n[:bsplit.counter], n[bsplit.counter: bsplit.machine], n[bsplit.machine: bsplit.process], n[bsplit.process:], )) def wuid(raw=None, leading='u'): ''' Creates a unique id as a web-compliant id for use in HTML ids. This is the same as a hex id, but it has a leading `u` to ensure an alphabetical character comes first, per the standard. If provided, raw should be a UID named tuple (usually from a call to ruid). Use sep='-' to separate the parts by dashes. ''' if raw is None: raw = ruid() return '{}{}'.format(leading, uid(raw)) def iunpack(n): ''' Unpacks the given integer number into a UID namedtuple. ''' # format of these is (mask & n) >> shifted return UID( n >> shift.counter, ((((1 << size.counter) - 1) << shift.machine) & n) >> shift.machine, ((((1 << size.machine) - 1) << shift.process) & n) >> shift.process, ((1 << shift.process) - 1) & n, ) def unpack(hex_n): ''' Unpacks the given hex number string into a UID namedtuple. To unpack a web id, use unpack(myid[1:]) to remove the leading character. ''' return iunpack(int(hex_n, 16)) ################################################### ### Unit tests for this module: ### ### python3 uid.py ### import unittest class Tester(unittest.TestCase): def test_ruid(self): u = ruid() u2 = ruid() self.assertEqual(u.machine, u2.machine) self.assertEqual(u.process, u2.process) def test_int_hex_binary(self): u = ruid() n = iuid(u) h = uid(u) b = buid(u) self.assertEqual(n, int(h, 16)) self.assertEqual(n, int(b, 2)) def test_int_hex_binary(self): u = ruid() n = iuid(u) h = uid(u) b = buid(u) self.assertEqual(n, int(h, 16)) self.assertEqual(n, int(b, 2)) def test_pretty(self): u = ruid() # hex h = uid(u) p = uid(u, '-') self.assertEqual(h, p.replace('-', '')) # binary b = buid(u) p = buid(u, '-') self.assertEqual(b, p.replace('-', '')) def test_unpack(self): # one test u = ruid() self.assertEqual(u, unpack(uid(u))) self.assertEqual(u, iunpack(iuid(u))) # other direction with int n = iuid() self.assertEqual(n, iuid(iunpack(n))) # other direction with hex h = uid() self.assertEqual(h, uid(unpack(h))) if __name__ == '__main__': unittest.main() <file_sep>/livereload-docs.py #!/usr/bin/env python # This starts a web server on http://localhost:5500/ where doc files are automatically recompiled. # # If you need to create the docs from scratch, run: # cd docs # make html # from livereload import Server, shell server = Server() server.watch('docs/*.rst', shell('make html --always-make', cwd='docs')) server.watch('docs/_static/*.css', shell('make html --always-make', cwd='docs')) print('PORT IS 5500') server.serve(root='docs/_build/html')<file_sep>/django_mako_plus/tags.py from mako.runtime import supports_caller ### ### Mako-style tags that DMP provides ### ######################################################### ### Autoescaping toggling # attaching to `caller_stack` because it's the same object # throughout rendering of a template inheritance AUTOESCAPE_KEY = '__dmp_autoescape' def is_autoescape(context): return bool(getattr(context.caller_stack, AUTOESCAPE_KEY, True)) def toggle_autoescape(context, escape_on=True): previous = is_autoescape(context) setattr(context.caller_stack, AUTOESCAPE_KEY, escape_on) try: context['caller'].body() finally: setattr(context.caller_stack, AUTOESCAPE_KEY, previous) @supports_caller def autoescape_on(context): ''' Explicitly turns autoescaping on for a given block within a template, (individual filters can still override with ${ somevar | n }). Example use in template: <%namespace name="dmp" module="django_mako_plus.tags"/> <%dmp:autoescape_on> ${ somevar } will be autoescaped. </%dmp:autoescape_on> ''' toggle_autoescape(context, True) return '' @supports_caller def autoescape_off(context): ''' Explicitly turns autoescaping off for a given block within a template, (individual filters can still override with ${ somevar | h }). Example use in template: <%namespace name="dmp" module="django_mako_plus.tags"/> <%dmp:autoescape> ${ somevar } will not be autoescaped. </%dmp:autoescape> ''' toggle_autoescape(context, False) return '' <file_sep>/docs/static_context.rst The JS Context ================================ In the `tutorial <tutorial_css_js.html>`_, you learned to send context variables to ``*.js`` files using ``jscontext``: .. code-block:: python from django.conf import settings from django_mako_plus import view_function, jscontext from datetime import datetime @view_function def process_request(request): context = { jscontext('now'): datetime.now(), } return request.dmp.render('index.html', context) Two providers in DMP go to work. First, the ``JsContextProvider`` adds the values to its variable in context (initially created by ``dmp-common.js``). This script goes right into the generated html, which means the values can change per request. Your script file uses these context variables, essentially allowing your Python view to influence Javascript files in the browser, even cached ones! :: <script>DMP_CONTEXT.set('u1234567890abcdef', { "now": "2020-02-11 09:32:35.41233"}, ...)</script> Second, the ``JsLinkProvider`` adds a script tag for your script--immediately after the context. The ``data-context`` attribute on this tag links it to your data in ``DMP_CONTEXT``. :: <script src="/static/homepage/scripts/index.js?1509480811" data-context="u1234567890abcdef"></script> TypeError: ``context.now`` is undefined ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If things are working, open your browser console/inspector and see if JS is giving you any messages. The following are a few reasons that the context might be undefined: * Your JS code is running too late. If you reverse the closure functions, the code doesn't run in time to catch the context. Compare your code with the examples below. * You might be missing script lines ``<script src="/django_mako_plus/dmp-common.min.js"></script>`` and ``${ django_mako_plus.links(self) }``, or these might be reversed. * ``/django_mako_plus/dmp-common.min.js`` might not be available. Check for a 404 error in the Network tab of your browser's inspector. Serialization ------------------------------ The context dictionary is sent to Javascript using JSON, which places limits on the types of objects you can mark with ``jscontext``. This normally means only strings, booleans, numbers, lists, and dictionaries are available. However, there may be times when you need to send "full" objects. When preparing the JS object, DMP looks for a class method named ``__jscontext__`` in the context values. If the method exists on a value, DMP calls it and includes the return as the reduced, "JSON-compatible" version of the object. The following is an example: .. code-block:: python class NonJsonObject(object): def __init__(self): # this is a complex, C-based structure self.root = etree.fromString('...') def __jscontext__(self): # this return string is what DMP will place in the context return etree.tostring(self.root) When you add a ``NonJsonObject`` instance to the render context, you'll still get the full ``NonJsonObject`` in your template code (since it's running on the server side). But it's reduced with ``instance.__jscontext__()`` to transit to the browser JS runtime: .. code-block:: python def process_request(request): obj = NonJsonObject() context = { # DMP will call obj.__jscontext__() and send the result to JS jscontext('myobj'): obj, } return request.dmp.render('template.html', context) Referencing the Context ----------------------------- *Your script should immediately get a reference to the context data object*. The Javascript global variable ``document.currentScript`` points at the correct ``<script>`` tag *on initial script run only*. If you delay through ``async`` or a ready function, DMP will still most likely get the right context, but in certain cases (see below) you might get another script's context! The following is a template for getting context data. It retrieves the context immediately and creates a closure for scope: :: // arrow style (context => { // main code here console.log(context) })(DMP_CONTEXT.get()) // function style (function(context) { // main code here console.log(context) })(DMP_CONTEXT.get()) Alternatively, the following is a template for getting context data **and** using a ``ready`` (onload) handler. It retrieves the context reference immediately, but delays the main processing until document load is finished. Delaying with jQuery ``ready()``: :: // arrow style $((context => () => { // main code here console.log(context) })(DMP_CONTEXT.get())) // function style $(function(context) { return function() { // main code here console.log(context) } }(DMP_CONTEXT.get())) Delaying with pure Javascript: :: // arrow style document.addEventListener("DOMContentLoaded", (context => () => { // main code here console.log(context) })(DMP_CONTEXT.get())) // function style document.addEventListener("DOMContentLoaded", function(context) { return function() { // main code here console.log(context) } }(DMP_CONTEXT.get())) Handling the "Certain Cases" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Above, we said that DMP could get the wrong context in "certain cases". These are fringe issues, but you should handle them when developing libraries or widgets that might get ajax'd in many places. Here's an example of when this might occur: 1. Your code uses jQuery.ajax() to retrieve ``snippet.html``, which has accompanying ``snippet.js`` and ``another.js`` files. 2. When jQuery receives the response, it strips the ``<script>`` element from the html. The html is inserted in the DOM **without** the tag (this behavior is how jQuery is written -- it avoids a security issue by doing this). 3. jQuery executes the script code as a string, disconnected from the DOM. 4. Since DMP can't use the predictable ``document.currentScript`` variable, it defaults to the last-inserted context. This is normally a good assumption. 5. However, suppose the two ``.js`` files were inserted during two different render() calls on the server. Two context dictionaries will be included in the html, and only one of them will be the "last" one. 6. Both scripts run with the same, incorrect context. Do not pass Go. Do not collect $200. No context for you. The solution is to help DMP by specifying the context by its ``app/template`` key: :: // look away Ma -- being explicit here! (function(context) { // your code here, such as console.log(context); })(DMP_CONTEXT.get('homepage/index')); In the above code, DMP retrieves correct context by template name. Even if the given template has been loaded twice, the latest one will be active (thus giving the right context). Problem solved. A third alternative is to get the context by using a ``<script>`` DOM object as the argument to ``.get``. This approach always returns the correct context. <file_sep>/django_mako_plus/provider/static_links.py from django.conf import settings from django.forms.utils import flatatt from django.utils.module_loading import import_string from ..util import crc32, getdefaultattr, log, merge_dicts from ..version import __version__ from .base import BaseProvider import logging import os import os.path import json ##################################################### ### Abstract Link Provider class LinkProvider(BaseProvider): ''' Renders links like <link> and <script> based on the name of the template and supertemplates. ''' # the default options are for CSS files default_options = merge_dicts(BaseProvider.default_options, { # the filename to search for (resolves to a single file, if it exists) # if it does not start with a slash, it is relative to the app directory. # if it starts with a slash, it is an absolute path. # codes: {basedir}, {app}, {template}, {template_name}, {template_file}, {template_subdir} 'filepath': os.path.join('scripts', '{template}.js'), # if a template is rendered more than once in a request, should we link more than once? 'skip_duplicates': False, }) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) path = self.filepath if log.isEnabledFor(logging.DEBUG): log.debug('[%s] %s searching for %s', self.template_file, self.__class__.__qualname__, path) # file time and version hash try: self.mtime = int(os.stat(path).st_mtime) if log.isEnabledFor(logging.DEBUG): log.debug('[%s] found %s', self.template_file, path) # version_id combines current time and the CRC32 checksum of file bytes self.version_id = (self.mtime << 32) | crc32(path) except FileNotFoundError: self.mtime = 0 self.version_id = 0 @property def filepath(self): ''' The absolute path to the file on disk. This default implementation uses: development: /app path/ production: settings.STATIC_ROOT/app name/ during production. ''' if settings.DEBUG: return os.path.normpath(os.path.join( self.app_config.path, self.options['filepath'].format( basedir=settings.BASE_DIR, app=self.app_config.name, template=self.template, template_name=self.template_name, template_file=self.template_file, template_subdir=self.template_subdir, ), )) else: return os.path.normpath(os.path.join( settings.STATIC_ROOT, self.app_config.name, self.options['filepath'].format( basedir=settings.BASE_DIR, app=self.app_config.name, template=self.template, template_name=self.template_name, template_file=self.template_file, template_subdir=self.template_subdir, ), )) def create_link(self, provider_run, data): ''' If the file referenced in filepath() exists, this method is called to create the link to be included in the html. Subclasses should provide an implementation for their type of file, such as <script> or <link>. ''' return '<link rel="stylesheet" type="text/css" href="/web/path/to/file" />' def start(self, provider_run, data): # add a set to the request (fallback to provider_run if request is None) for skipping duplicates if self.options['skip_duplicates']: data['seen'] = getdefaultattr( provider_run.request.dmp if provider_run.request is not None else provider_run, '_LinkProvider_Filename_Cache_', factory=set, ) # enabled providers in the chain go here data['enabled'] = [] def provide(self, provider_run, data): filepath = self.filepath # delaying printing of tag to finish() because the JsContextProvider delays and this must go after it # short circuit if the file for this provider doesn't exist if self.mtime == 0: return # short circut if we're skipping duplicates and we've already seen this one if self.options['skip_duplicates']: if filepath in data['seen']: return data['seen'].add(filepath) # if we get here, this provider is enabled, so add it to the list data['enabled'].append(self) def finish(self, provider_run, data): for provider in data['enabled']: provider_run.write(provider.create_link(provider_run, data)) ############################################# ### Css and Js Link Providers class CssLinkProvider(LinkProvider): '''Generates a CSS <link>''' default_options = merge_dicts(LinkProvider.default_options, { 'group': 'styles', # the filename to search for (resolves to a single file, if it exists) # if it does not start with a slash, it is relative to the app directory. # if it starts with a slash, it is an absolute path. 'filepath': os.path.join('styles', '{template}.css'), # if a template is rendered more than once in a request, we usually don't # need to include the css again. 'skip_duplicates': True, }) def create_attrs(self, provider_run, data): '''Creates the attributes for the link (allows subclasses to add)''' if settings.DEBUG: relpath = os.path.relpath(self.filepath, settings.BASE_DIR) else: relpath = os.path.relpath(self.filepath, settings.STATIC_ROOT) attrs = {} attrs["data-context"] = provider_run.uid attrs["rel"] = "stylesheet" attrs["href"] ="{}{}?{:x}".format(settings.STATIC_URL, relpath.replace('\\', '/'), self.version_id) return attrs def create_link(self, provider_run, data): '''Creates a link to the given URL''' attrs = self.create_attrs(provider_run, data) return '<link{} />'.format(flatatt(attrs)) class JsLinkProvider(LinkProvider): '''Generates a JS <script>.''' default_options = merge_dicts(LinkProvider.default_options, { 'group': 'scripts', # the filename to search for (resolves to a single file, if it exists) # if it does not start with a slash, it is relative to the app directory. # if it starts with a slash, it is an absolute path. 'filepath': os.path.join('scripts', '{template}.js'), # if a template is rendered more than once in a request, we should link each one # so the script runs again each time the template runs 'skip_duplicates': False, # whether to create an async script tag 'async': False, }) def create_attrs(self, provider_run, data): '''Creates the attributes for the link (allows subclasses to add)''' if settings.DEBUG: relpath = os.path.relpath(self.filepath, settings.BASE_DIR) else: relpath = os.path.relpath(self.filepath, settings.STATIC_ROOT) attrs = {} attrs["data-context"] = provider_run.uid attrs["src"] ="{}{}?{:x}".format(settings.STATIC_URL, relpath.replace('\\', '/'), self.version_id) if self.options['async']: attrs['async'] = "async" return attrs def create_link(self, provider_run, data): '''Creates a link to the given URL''' attrs = self.create_attrs(provider_run, data) return '<script{}></script>'.format(flatatt(attrs)) ################################### ### JS Context Provider class JsContextProvider(BaseProvider): ''' Adds all js_context() variables to DMP_CONTEXT. This should be listed before JsLinkProvider so the context variables are available during <script> runs. ''' default_options = merge_dicts(BaseProvider.default_options, { # the group this provider is part of. this only matters when # the html page limits the providers that will be called with # ${ django_mako_plus.links(group="...") } 'group': 'scripts', # the encoder to use for the JSON structure 'encoder': 'django.core.serializers.json.DjangoJSONEncoder', }) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.encoder = import_string(self.options['encoder']) self.template = "{}/{}".format(self.app_config.name, self.template_name) def start(self, provider_run, data): data['templates'] = [] def provide(self, provider_run, data): data['templates'].append(self.template) def finish(self, provider_run, data): if len(data['templates']) == 0: return context_data = { jscontext('__router__'): { 'template': self.template, 'app': provider_run.request.dmp.app if provider_run.request is not None else None, 'page': provider_run.request.dmp.page if provider_run.request is not None else None, }, } for k in provider_run.context.kwargs: if isinstance(k, jscontext): value = provider_run.context[k] context_data[k] = value.__jscontext__() if hasattr(value, '__jscontext__') else value # add to the JS DMP_CONTEXT provider_run.write('<script>') provider_run.write('DMP_CONTEXT.set("{version}", "{contextid}", {data}, {templates});'.format( version=__version__, contextid=provider_run.uid, data=json.dumps(context_data, cls=self.encoder, separators=(',', ':')) if context_data else '{}', templates=json.dumps(data['templates']), )) provider_run.write('</script>') class jscontext(str): ''' Marks a key in the context dictionary as a JS context item. JS context items are sent to the template like normal, but they are also added to the runtime JS namespace. See the tutorial for more information on this function. ''' # no code needed, just using the class for identity <file_sep>/django_mako_plus/defaults.py # this dict of options is merged with the current project's TEMPLATES entry for DMP DEFAULT_OPTIONS = { # the default app and page to render in Mako when the url is too short # if None (no default app), DMP will not capture short URLs 'DEFAULT_APP': 'homepage', 'DEFAULT_PAGE': 'index', # functions to automatically add variables to the params/context before templates are rendered 'CONTEXT_PROCESSORS': [ 'django.template.context_processors.static', # adds "STATIC_URL" from settings.py 'django.template.context_processors.debug', # adds debug and sql_queries 'django.template.context_processors.request', # adds "request" object 'django.contrib.auth.context_processors.auth', # adds "user" and "perms" objects 'django.contrib.messages.context_processors.messages', # adds messages from the messages framework 'django_mako_plus.context_processors.settings', # adds "settings" dictionary ], # identifies where the Mako template cache will be stored, relative to each template directory 'TEMPLATES_CACHE_DIR': '__dmpcache__', # the default encoding of template files 'DEFAULT_TEMPLATE_ENCODING': 'utf-8', # imports for every template 'DEFAULT_TEMPLATE_IMPORTS': [ # alternative syntax blocks within your Mako templates # 'from django_mako_plus import django_syntax, jinja2_syntax, alternate_syntax', # the next two lines are just examples of including common imports in templates # 'from datetime import datetime', # 'import os, os.path, re, json', ], # whether autoescaping of expressions is on or off 'AUTOESCAPE': True, # the converter class to use for parameter conversion # this should be ParameterConverter or a subclass of it 'PARAMETER_CONVERTER': 'django_mako_plus.converter.ParameterConverter', # whether to send the custom DMP signals -- set to False for a slight speed-up in router processing # determines whether DMP will send its custom signals during the process 'SIGNALS': False, # static file providers (see "static file" docs for full options here) 'CONTENT_PROVIDERS': [ { 'provider': 'django_mako_plus.JsContextProvider' }, # adds JS context - this should normally be listed FIRST # { 'provider': 'django_mako_plus.CompileProvider' }, # generic auto-compiler # { 'provider': 'django_mako_plus.CompileScssProvider' }, # autocompiles Scss files # { 'provider': 'django_mako_plus.CompileLessProvider' }, # autocompiles Less files # { 'provider': 'django_mako_plus.LinkProvider' }, # generic link generator { 'provider': 'django_mako_plus.CssLinkProvider' }, # generates links for app/styles/template.css { 'provider': 'django_mako_plus.JsLinkProvider' }, # generates links for app/scripts/template.js # { 'provider': 'django_mako_plus.WebpackJsLinkProvider' }, # generates links to app/scripts/__bundle__.js (see DMP docs on webpack) ], # webpack file discovery (used by `manage.py dmp_webpack`) 'WEBPACK_PROVIDERS': [ { 'provider': 'django_mako_plus.CssLinkProvider' }, # generates links for app/styles/template.css { 'provider': 'django_mako_plus.JsLinkProvider' }, # generates links for app/scripts/template.js ], # additional template dirs to search 'TEMPLATES_DIRS': [ # '/var/somewhere/templates/', ], } <file_sep>/docs/topics_view_function.rst Customizing @view_function -------------------------------------- .. contents:: :depth: 2 The ``@view_function`` decorator annotates functions in your project that are web-accessible. Without it, clients could use DMP's conventions to call nearly any function in your system. The decorator implementation itself is fairly straightforward. However, as a decorator for all endpoints in your system, it is a great place to do pre-endpoint work. ``@view_function`` was intentionally programmed as a class-based decorator so you can extend it. Using Keyword Arguments ============================= Although we normally specify ``@view_function`` without any arguments, it can take an arbitrary number of keyword arguments. Any extra arguments are placed in ``self.decorator_args`` and ``self.decorator_kwargs``. For this example, lets check user groups in the view function decorator. We really should use permission-based security rather than group-based security. And Django already comes with the ``@require_permission`` decorator. And Django has ``process_view`` middleware you could plug into. So even if this example is a little contrived, let's go with it. We've found places where, despite the other options, this is the right place to do pre-view work. We'll override both the constructor and the __call__ methods in this example so you can see both: .. code-block:: python from django_mako_plus import view_parameter class site_endpoint(view_function): '''Customized view function decorator''' def __init__(self, f, require_role=None, *args, **kwargs): ''' This runs as Python loads the module containing your view function. You can specify new parameters (like require_role here) or just use **kwargs. Don't forget to include the function as the first argument. ''' super().__init__(self, f, *args, **kwargs) self.require_role = require_role def __call__(self, request, *args, **kwargs): ''' This runs every time the view function is accessed by a client. Be sure to return the result of super().__call__ as it is your view function's response. ''' # check roles if self.require_role: if request.user.is_anonymous or request.user.groups.filter(name=self.require_role).count() == 0: return HttpResponseRedirect('/login/') # call the view function return super().__call__(request, *args, **kwargs) In ``homepage/views/index.py``, use your custom decorator. .. code-block:: python from .some.where import site_endpoint @site_endpoint(require_role='mentors') def process_request(request): ... In the above example, overriding ``__init__`` isn't technically necessary. Any extra ``*args`` and ``**kwargs`` in the constructor call are placed in ``self.decorator_args`` and ``self.decorator_kwargs``. So instead of explictily listing ``require_role`` in the argument list, we could have used ``self.decorator_kwargs.get('require_role')``. I listed the parameter explicitly for code clarity. <file_sep>/docs/install_other_syntax.rst Using Django/Jinja2 within Mako Templates ======================================================= Django officially supports multiple template engines, even within the same project/app. Simply list the engines you want to use, such as Django, Jinja2, and DMP, in your settings.py file. With multiple engines, Django's ``render`` function tries each engine and uses the first one that takes a given template. Django templates are rendered by the Django engine. Mako templates are rendered by the DMP engine. Jinja2 templates are rendered by the Jinja2 engine. Becoming Bilingual --------------------------- There may be times when you need or want to call real, Django tags or include Django template syntax in your DMP templates. In other words, you need to combine both Mako, Django, and/or Jinja2 syntaxes in the *same* template. This situation can occur when you include a third-party app in your project, and the new library provides Django tags. You need to reference these tags within your DMP templates. For example, although `Crispy Forms' <http://django-crispy-forms.readthedocs.io/>`__ functions can be called directly, you may want to use its custom tags. To enable alternative syntaxes, enable the DMP tags with the following settings. Also ensure you have the Django template engine included. .. code-block:: python TEMPLATES = [ { 'NAME': 'django_mako_plus', 'OPTIONS': { 'DEFAULT_TEMPLATE_IMPORTS': [ 'from django_mako_plus import django_syntax, jinja2_syntax, alternate_syntax', ], } }, { 'NAME': 'django', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Then clear out the compiled templates caches: :: python3 manage.py dmp_cleanup In your Mako template, include a Django expression or embed an entire block by using a Mako filter: :: ## Expression containing Django template syntax (assuming name was created in the view.py) ${ '{{ name }}' | django_syntax(local) } ## Full Django code block, with Mako creating the variable first <% titles = [ 'First', 'Second', 'Third' ] %> <%block filter="django_syntax(local, titles=titles)"> {% for title in titles %} <h2> {{ title|upper }} </h2> {% endfor %} </%block> ## Third-party, crispy form tags (assume my_formset was created in the view.py) <%block filter="django_syntax(local)"> {% load crispy_forms_tags %} <form method="post" class="uniForm"> {{ my_formset|crispy }} </form> </%block> The ``local`` parameter passes your context variables to the Django render call. It is a global Mako variable (available in any template), and it is always included in the filter. In other words, include ``local`` every time as shown in the examples above. The Mako Templates web site provides more information on filters. Jinja2 or ((insert template engine)) ------------------------------------------------------------------------------ If Jinja2 is needed, replace the filters with ``jinja2_syntax(context)`` in the above examples. If another engine is needed, replace the filter with ``template_syntax(context, 'engine name')`` as specified in ``settings.TEMPLATES``. DMP will render with the appriate engine and put the result in your HTML page. Don't forget to include the ``TEMPLATES`` declaration for Jinja2 in your ``settings.py`` file. Local Variables --------------------------------------- Embedded template code has access to any variable passed to your temple (i.e. any variable in the context). Although not an encouraged practice, variables are sometimes created right in your template, and faithful to the Mako way, are not accessible in embedded blocks. You can pass locally-created variables as kwargs in the filter call. This is done with ``titles=titles`` in the Django code block example above. Reverse That: DMP in Django Templates ------------------------------------------- Thus far, we've shown how to embed other tags and template languages within DMP templates. The opposite is supported as well: embedding DMP snippets within Django templates. Suppose a third party contains a "normal" Django template -- one that uses the standard Django syntax instead of Mako syntax. In customizing these templates, you may want to include DMP templates. Django has an ``include`` template tag, but that's for Django templates. That's where DMP's ``dmp_include`` tag comes in. Inside a standard Django template, use the following: :: {% load django_mako_plus %} {% dmp_include "app" "template name" %} For example, suppose your Django template, ``my_standard_template.html`` needs to include the Mako-syntax ``navigation_snippet.htm`` in app ``homepage``. Put the follwoing inside ``my_standard_template.html``: :: <!-- this file is my_standard_template.html --> {% load django_mako_plus %} {% dmp_include "homepage" "navigation_snippet.htm" %} You can also specify a ``def`` or ``block`` within the navigation snippet: :: <!-- this file is my_standard_template.html --> {% load django_mako_plus %} {% dmp_include "homepage" "navigation_snippet.htm" "someblock" %} <file_sep>/release_version.py #!/usr/bin/env python3 from django_mako_plus.version import __version__ from django_mako_plus.command import run_command import sys, os, os.path, re, shutil from rjsmin import jsmin # set the version number in dmp-common.js print('Updating the version in .js files...') VERSION_PATTERN = re.compile("__version__\: '\w+\.\w+\.\w+'") DMP_COMMON = 'django_mako_plus/webroot/dmp-common' with open(DMP_COMMON + '.js') as f: content = f.read() match = VERSION_PATTERN.search(content) if not match: raise RuntimeError('Version pattern did not match. Aborting because the version number cannot be updated in dmp-common.js.') content = VERSION_PATTERN.sub("__version__: '{}'".format(__version__), content) with open(DMP_COMMON + '.js', 'w') as f: f.write(content) with open(DMP_COMMON + '.min.js', 'w') as f: f.write(jsmin(content)) # update the archives print('Creating the archives...') shutil.make_archive('app_template', 'zip', root_dir='./django_mako_plus/app_template') shutil.make_archive('project_template', 'zip', root_dir='./django_mako_plus/project_template') # run the setup and upload print() if input('Ready to upload to PyPi. Continue? ')[:1].lower() == 'y': ret = run_command('python3', 'setup.py', 'sdist') print(ret.stdout) ret = run_command('twine', 'upload', 'dist/*') print(ret.stdout) run_command('rm', '-rf', 'dist/', 'django_mako_plus.egg-info/') <file_sep>/django_mako_plus/util.py from django.apps import apps import os, os.path import collections import zlib from importlib import import_module # set up the logger import logging log = logging.getLogger('django_mako_plus') ################################################################ ### Special type of list used for url params class URLParamList(list): ''' A simple extension to Python's list that returns '' for indices that don't exist. For example, if the object is ['a', 'b'] and you call obj[5], it will return '' rather than throwing an IndexError. This makes dealing with url parameters simpler since you don't have to check the length of the list. ''' def __getitem__(self, idx): '''Returns the element at idx, or '' if idx is beyond the length of the list''' return self.get(idx, '') def get(self, idx, default=''): '''Returns the element at idx, or default if idx is beyond the length of the list''' # if the index is beyond the length of the list, return '' if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)): return default # else do the regular list function (for int, slice types, etc.) return super().__getitem__(idx) ########################################## ### Utilities def import_qualified(name): ''' Imports a fully-qualified name from a module: cls = import_qualified('homepage.views.index.MyForm') Raises an ImportError if it can't be ipmorted. ''' parts = name.rsplit('.', 1) if len(parts) != 2: raise ImportError('Invalid fully-qualified name: {}'.format(name)) try: return getattr(import_module(parts[0]), parts[1]) except AttributeError: raise ImportError('{} not found in module {}'.format(parts[1], parts[0])) def merge_dicts(*dicts): ''' Shallow merges an arbitrary number of dicts, starting with the first argument and updating through the last argument (last dict wins on conflicting keys). ''' merged = {} for d in dicts: if d: merged.update(d) return merged def flatten(*args): '''Generator that recursively flattens embedded lists, tuples, etc.''' for arg in args: if isinstance(arg, collections.Iterable) and not isinstance(arg, (str, bytes)): yield from flatten(*arg) else: yield arg def split_app(path): ''' Splits a file path on the app, returning (app config, relative path within app). ''' parts = os.path.abspath(path).split(os.path.sep) for i in reversed(range(0, len(parts) - 1)): appdir, appname, filepath = os.path.sep.join(parts[:i]), parts[i], os.path.sep.join(parts[i + 1:]) config = apps.app_configs.get(appname) if config is not None and os.path.samefile(config.path, appdir + os.path.sep + appname): # got it! return config, filepath # not found return None, path def crc32(filename): ''' Calculates the CRC checksum for a file. Using CRC32 because security isn't the issue and don't need perfect noncollisions. We just need to know if a file has changed. On my machine, crc32 was 20 times faster than any hashlib algorithm, including blake and md5 algorithms. ''' result = 0 with open(filename, 'rb') as fin: while True: chunk = fin.read(48) if len(chunk) == 0: break result = zlib.crc32(chunk, result) return result EMPTY = object() def getdefaultattr(obj, name, default=None, factory=EMPTY): ''' Gets the given attribute from the object, creating it with a default or by calling a factory if needed. ''' try: return getattr(obj, name) except AttributeError: pass val = factory() if factory is not EMPTY else None setattr(obj, name, val) return val def qualified_name(obj): '''Returns the fully-qualified name of the given object''' if not hasattr(obj, '__module__'): obj = obj.__class__ module = obj.__module__ if module is None or module == str.__class__.__module__: return obj.__qualname__ return '{}.{}'.format(module, obj.__qualname__) <file_sep>/readme.txt Routing Django to Mako since 2013. **Please visit http://django-mako-plus.readthedocs.io/ for tutorials, examples, and other documentation topics.** <file_sep>/docs/install_new.rst New Project ====================== Ensure you have Python 3.4+ installed (``python3 --version``), and check that you can run ``python3`` (or ``python``) at the command prompt. If you are using virtual environments, be sure to activate that first. Install Django, Mako, and DMP ---------------------------------- DMP works with Django 1.9+, including the 2.0 releases. The following will install all three dependencies: :: pip3 install --upgrade django-mako-plus (note that on Windows machines, ``pip3`` may need to be replaced with ``pip``) Create a Django project ---------------------------------- Create a Django project, and specify that you want a DMP-style project layout: :: python3 -m django_mako_plus dmp_startproject mysite You can, of course, name your project anything you want, but in the sections below, I'll assume you called your project ``mysite``. Don't forget to migrate to synchronize your database and create a superuser: :: cd mysite python3 manage.py migrate python3 manage.py createsuperuser Create a DMP-Style App ---------------------------------- Change to your project directory in the terminal/console, then create a new Django-Mako-Plus app with the following: :: python3 manage.py dmp_startapp homepage **After** the new ``homepage`` app is created, add your new app to the ``INSTALLED_APPS`` list in ``settings.py``: .. code-block:: python INSTALLED_APPS = [ ... 'homepage', ] Congratulations. You're ready to go! Load it Up! ---------------------------------- Start your web server with the following: :: python3 manage.py runserver If you get a message about unapplied migrations, ignore it for now and continue. Open your web browser to http://localhost:8000/. You should see a message welcoming you to the homepage app. If everything is working, `skip ahead to the tutorial <tutorial.html>`_. <file_sep>/docs/static_providers.rst Under the Hood: Providers ================================ The framework is built to be extended for custom file types. When you call ``links(self)`` within a template, DMP iterates through a list of providers (``django_mako_plus.BaseProvider`` subclasses). You can customize the behavior of these providers in your ``settings.py`` file. Here's a basic version: .. code-block:: python TEMPLATES = [ { 'NAME': 'django_mako_plus', 'BACKEND': 'django_mako_plus.MakoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'CONTENT_PROVIDERS': [ { 'provider': 'django_mako_plus.JsContextProvider' }, # adds JS context - this should normally be listed first { 'provider': 'django_mako_plus.CompileScssProvider' }, # autocompiles Scss files { 'provider': 'django_mako_plus.CompileLessProvider' }, # autocompiles Less files { 'provider': 'django_mako_plus.CssLinkProvider' }, # generates links for app/styles/template.css { 'provider': 'django_mako_plus.JsLinkProvider' }, # generates links for app/scripts/template.js ], } } ] Setting Options ------------------------------- Each provider has an options dictionary that allows you to adjust its behavior. For example, link providers like ``JsLinkProvider`` allow custom search paths: .. code-block:: python { 'provider': 'django_mako_plus.JsContextProvider', 'filepath': lambda provider: os.path.join(provider.app_config.name, 'scripts', provider.template_name + '.js'), }, While the options for each provider are different, most allow either a string or a function/lambda (e.g. ``filepath`` above). This allows path names to be created as simple strings or using full logic and method calls. If a function is specified, it should take one parameter: the provider. Every provider contains the following: * ``provider.template_name`` - the name of the template, without extension * ``provider.template_relpath`` - the path of the template, relative to the ``app/templates`` directory. This is usually the same as ``template_name``, but it can be different if in a subdir of templates (e.g. ``homepage/templates/forms/login.html`` -> ``forms/login``. * ``provider.template_ext`` - the extension of the template filename * ``provider.app_config`` - the AppConfig the template resides in * ``provider.app_config.name`` - the name of the app * ``provider.template`` - the Mako template object * ``provider.template.filename`` - full path to template file * ``provider.options`` - the options for this provider (defaults + settings.py) When running in production mode, provider objects are created once and then cached, so any lambda functions are run at system startup (not every request). Order Matters -------------------- Just like Django middleware, the providers are run in order. If one provider depends on the work of another, be sure to list them in the right order. For example, the ``JsContextProvider`` provides context variables for scripts, so it must be placed before ``JsLinkProvider``. That way, the variables are loaded when the scripts run. ``JsContextProvider`` should usually be listed first because several other providers depend on it. Another example is the need to list ``ScssCompileProvider`` before ``CssLinkProvider``, which allows the first to create the .css file for the second to find. Dev vs. Prod ------------------------------- Providers are triggered by a call to ``${ django_mako_plus.links(self) }``. By default, they run in both development and production mode. The process might be a little different from dev to prod. For example, certain providers may only be needed when ``DEBUG=True``. Or in production mode, you may have options values that are slightly different. Every provider has an ``enabled`` boolean option that sets whether it should be active or not. Clever use of this variable can make providers activate under different circumstances. The following setting uses ``settings.DEBUG`` to run the ``CompileScssProvider`` only during development: :: { 'provider': 'django_mako_plus.CompileScssProvider', 'enabled': DEBUG, # this is in settings.py, so no need for the usual `settings.` } Example: Sass Filenames ---------------------------------------- Sass normally compiles ``[name].scss`` to ``[name].css``. The output file is placed in the same directory as the source file. This can make it hard to differentiate the generated `*.css` files from normal non-sass css files. It also makes it difficult to add a pattern for the generated files in ``.gitignore``. Assuming you aren't bundling with something like webpack, there are at least two possibilities. **Option 1: Place generated files in a top-level ``dist/`` folder in your project.** .. code-block:: python { 'provider': 'django_mako_plus.CompileScssProvider', 'sourcepath': lambda provider: os.path.join(provider.app_config.name, 'styles', provider.template_name + '.scss'), 'targetpath': lambda provider: os.path.join('dist', provider.app_config.name, 'styles', provider.template_name + '.css'), }, { 'provider': 'django_mako_plus.CssLinkProvider', 'filepath': lambda provider: os.path.join('dist', provider.app_config.name, 'styles', provider.template_name + '.css'), }, **Option 2: Use a custom extension for generated files, such as `[name].scss.css``.** .. code-block:: python { 'provider': 'django_mako_plus.CompileScssProvider', 'sourcepath': lambda provider: os.path.join(provider.app_config.name, 'styles', provider.template_name + '.scss'), 'targetpath': lambda provider: os.path.join('dist', provider.app_config.name, 'styles', provider.template_name + '.scss.css'), }, { 'provider': 'django_mako_plus.CssLinkProvider', 'filepath': lambda provider: os.path.join('dist', provider.app_config.name, 'styles', provider.template_name + '.scss.css'), }, Example: Running a Transpiler ------------------------------- Transpiling is usually done with a bundler like ``webpack``. However, there may be situations when you want DMP to trigger the transpiler. Since the process is essentially the same as compiling Sass or Less, we just need to adjust the options to match our transpiler. `Transcrypt <https://www.transcrypt.org/>`_ is a library that transpiles Python code into Javascript. It lets you write browser scripts in our favorite language rather than that other one. The setup requires two providers: 1. A ``CompileProvider`` to run the transpiler when the source file changes. 2. A ``JsLinkProvider`` to link the generated javascript (transcrypt places the generated files in a subdirectory). .. code-block:: python { 'provider': 'django_mako_plus.CompileProvider', 'group': 'scripts', 'sourcepath': lambda provider: os.path.join(provider.app_config.name, 'scripts', provider.template_name + '.py'), 'targetpath': lambda provider: os.path.join(provider.app_config.name, 'scripts', '__javascript__', provider.template_name + '.js'), 'command': lambda provider: [ shutil.which('transcrypt'), '--map', '--build', '--nomin', os.path.join(provider.app_config.name, 'scripts', provider.template_name + '.py'), ], }, { 'provider': 'django_mako_plus.JsLinkProvider', 'filepath': lambda provider: os.path.join(provider.app_config.name, 'scripts', '__javascript__', provider.template_name + '.js') }, Creating a Provider ------------------------ If you need something beyond the standard providers, you can `create a custom provider </static_custom.html>`_. <file_sep>/django_mako_plus/provider/runner.py from django.apps import apps from django.conf import settings from django.utils.module_loading import import_string from collections import namedtuple import io import logging import inspect from ..template import template_inheritance from ..util import log, qualified_name from ..uid import wuid # I can't keep the options inside the provider class itself because a given class # can be listed more than once in settings.py (with different options). # So instead I keep a list of the classes and their options here. ProviderClassInfo = namedtuple("ProviderClassInfo", [ 'cls', 'options' ]) #################################################### ### Main runner for providers class ProviderRun(object): '''A run through the providers for tself and its ancestors''' SETTINGS_KEY = 'CONTENT_PROVIDERS' CONTENT_PROVIDERS = [] @classmethod def initialize_providers(cls): '''Initializes the providers (called from dmp app ready())''' dmp = apps.get_app_config('django_mako_plus') # regular content providers cls.CONTENT_PROVIDERS = [] for provider_settings in dmp.options[cls.SETTINGS_KEY]: # import the class for this provider assert 'provider' in provider_settings, "Invalid entry in settings.py: CONTENT_PROVIDERS item must have 'provider' key" provider_cls = import_string(provider_settings['provider']) # combine options from all of its bases, then from settings.py options = {} for base in reversed(inspect.getmro(provider_cls)): options.update(getattr(base, 'DEFAULT_OPTIONS', {})) options.update(provider_settings) # add to the list if options['enabled']: # the index in the provider list is needed because a given class # can be listed more than once in settings.py (with different options) options['_template_cache_key'] = '_{}_{}_'.format(qualified_name(provider_cls), len(cls.CONTENT_PROVIDERS)) cls.CONTENT_PROVIDERS.append(ProviderClassInfo(provider_cls, options)) def __init__(self, tself, group=None): ''' tself: `self` object from a Mako template (available during rendering). group: provider group to include (defaults to all groups if None) ''' dmp = apps.get_app_config('django_mako_plus') self.uid = wuid() # a unique id for this run self.request = tself.context.get('request') self.context = tself.context self.buffer = io.StringIO() # Create a table of providers for each template in the ancestry: # # base.htm, [ JsLinkProvider1, CssLinkProvider1, ... ] # | # app_base.htm, [ JsLinkProvider2, CssLinkProvider2, ... ] # | # index.html, [ JsLinkProvider3, CssLinkProvider3, ... ] self.template_providers = [] for template in self.get_template_inheritance(tself): providers = [] for pci in self.CONTENT_PROVIDERS: provider = pci.cls.instance_for_template(template, pci.options) if group is None or provider.group == group: providers.append(provider) self.template_providers.append(providers) # Column-specific data dictionaries are maintained as the template providers run # (one per provider column). These allow the provider instances of a given # column to share data if needed. # # column_data = [ { col 1 } , { col 2 } , ... ] self.column_data = [ {} for pf in self.CONTENT_PROVIDERS ] def get_template_inheritance(self, tself): '''Returns a list of the template inheritance of tself, starting with the oldest ancestor''' return reversed(list(template_inheritance(tself))) def run(self): '''Performs the run through the templates and their providers''' # start() on tself (the last template in the list) for providers in self.template_providers[-1:]: for provider, data in zip(providers, self.column_data): provider.start(self, data) # provide() on the all provider lists in the chain for providers in self.template_providers: for provider, data in zip(providers, self.column_data): provider.provide(self, data) # finish() on tself (the last template in the list) for providers in self.template_providers[-1:]: for provider, data in zip(providers, self.column_data): provider.finish(self, data) def write(self, content): '''Provider instances use this to write to the buffer''' self.buffer.write(content) if settings.DEBUG: self.buffer.write('\n') def getvalue(self): '''Returns the buffer string''' return self.buffer.getvalue() <file_sep>/docs/static_webpack_faq.rst Webpack - FAQ ==================================== How do I clear the generated bundle files? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a terminal (Mac, Linux, or Windows+GitBash), issue these commands: :: # careful, this is recursive! rm **/__entry__.js rm **/__bundle__.js How do I use Sass (Less, TypeScript, etc.) with DMP Webpack? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ One benefit to bundling is the output files from compiles like ``sass`` are piped right into bundles instead of as extra files in your project. Here's the steps: 1. Clear out existing entry and bundle files (see above). 2. Install the Sass dependencies :: npm install --save-dev node-sass sass-loader 3. Modify ``webpack.config.js`` to find Sass files: .. code-block:: js module.exports = { ... module: { rules: [ ... { test: /\.scss$/, use: [ { loader: 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader' }, ] } ] }, }; 4. Configure ``settings.py`` to include ``app/styles/*.scss`` files wherever they match template names. .. code-block:: python TEMPLATES = [ { 'NAME': 'django_mako_plus', ... 'OPTIONS': { ... 'WEBPACK_PROVIDERS': [ { 'provider': 'django_mako_plus.CssLinkProvider' }, { 'provider': 'django_mako_plus.CssLinkProvider', 'filepath': lambda p: os.path.join(p.app_config.name, 'styles', p.template_relpath + '.scss'), }, { 'provider': 'django_mako_plus.JsLinkProvider' }, ], }, }, ] Note in the above options, we're including ``.scss`` and ``.css`` (whenever they exist), so be sure to erase any generated ``.css`` files from previous runs of Sass. We only need the source ``.scss`` files in the ``styles`` subdir. 3. Recreate the entry files and compile the bundles: :: python3 manage.py dmp_webpack --overwrite npm run watch How do I create a vendor bundle? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the `tutorial </static_webpack.html>`_, we created one bundle per app. These bundles can grow large as you enjoy the convenience of ``npm init`` and link to more and more things in ``node_modules/``. Since each bundle is self-contained, there will be a lot of duplication between bundles. For example, the webpack bootstrapping JS will be in every one of your bundles--even if you don't specifically import any extra modules. At some point, and usually sooner than later, you should probably make a vendor bundle. A vendor bundle combines the common code into a shared bundle, allowing the per-app bundles to lose quite a bit of weight. To enable a vendor bundle, do the following: 1. Clear out existing entry and bundle files (see above). 2. Adjust your ``webpack.config.js`` file with a ``chunkFilename`` output and ``optimization`` section. .. code-block:: js module.exports = { output: { ... chunkFilename: 'homepage/scripts/__bundle__.[name].js' }, ... optimization: { splitChunks: { cacheGroups: { vendor: { chunks: 'all', name: 'vendor', test: /[\\/]node_modules[\\/]/, enforce: true, }, } } } }; The above config creates a single bundle file in ``homepage/scripts/__bundle__.vendor.js``. Any import coming from ``node_modules`` goes into this common bundle. The web is filled with exotic recipes for code splitting and even more SO questions regarding splitting bundles into chunks. This configuration is a basic one, and you may want to split the vendor file into more than one chunk. Enter at your own risk...there be dragons here but also some rewards. 3. Recreate the entry files and compile the bundles: :: python3 manage.py dmp_webpack --overwrite npm run watch 4. Reference your vendor bundle in ``base.htm`` *before* the ``links(self)`` call. .. code-block:: html+mako <script src="/django_mako_plus/dmp-common.js"></script> <script src="${STATIC_URL}homepage/scripts/__bundle__.vendor.js"></script> ${ django_mako_plus.links(self) } How do I create a single, sitewide bundle? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In some situations, it might make sense to create a single monstrosity that includes the scripts for every DMP app on your site. Let's create a single ``__entry__.js`` file for your entire site 1. Clear out existing entry and bundle files (see above). 2. Modify ``webpack.config.js`` for this single entry. .. code-block:: js module.exports = { entry: 'homepage/scripts/__bundle__.js', ... } 3. Create a single entry file and compile the bundle: :: python3 manage.py dmp_webpack --overwrite --single homepage/scripts/__entry__.js npm run watch The above command will place the sitewide entry file in the homepage app, but it could be located anywhere. 4. Specify the bundle as the JS link for all pages: .. code-block:: python 'CONTENT_PROVIDERS': [ { 'provider': 'django_mako_plus.JsContextProvider' }, { 'provider': 'django_mako_plus.WebpackJsLinkProvider', 'filepath': 'homepage/scripts/__bundle__.js', 'duplicates': False, }, ], The above settings hard code the bundle location for all apps. Since 'duplicates' is False, the bundle will be included once per request, even if your base template (the ``links(self)`` call) is run multiple times by subtemplates. See also the question (below) regarding creating links manually. How do I specify the <script> link myself? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is easy to do as long as you call the bundle functions properly. Let's review the provider process: 1. Your template calls ``links(self)``, which triggers a "provider run". DMP generates a unique ``contextid`` and then iterates through the providers and template inheritance. For this example, suppose the context id is ``12345``. 2. ``[JsContextProvider]`` maps a "context" object to key ``12345`` to include the variables from the python ``render`` call. 3. ``[WebpackJsLinkProvider]`` creates the script link, ``<script data-context="12345" onLoad="DMP_CONTEXT.checkBundleLoaded('12345')">...</script>``, which makes the bundle functions accessible to the page. 4. ``[WebpackJsLinkProvider]`` creates a second script link, ``<script data-context="12345">DMP_CONTEXT.triggerBundleContext("12345")</script>``, which triggers the bundle functions for the template (and ancestors). #1 and #2 should remain as they are because DMP has the information for the context. However, #3 and #4 can be replaced by custom links in your base template: * Remove the ``WebpackJsLinkProvider`` in settings.py. You only need to leave the ``JsContextProvider`` in place. * *After ``dmp-common.js`` and ``links()`` run*, add a custom call to your bundle(s) in your base template. This replaces #3 above. You only need the "onLoad" event if your script tag is async. * After the bundle script tag, trigger the context with a custom script: ``<script>DMP_CONTEXT.triggerBundleContext(DMP_CONTEXT.lastContext.id)</script>``. This works because the last context added by ``links()`` should be the current page. This replaces #4 above, and it runs the correct functions in the bundle. If your script tag was async, dmp-common.js waits if needed for the bundle to load. How do I create multi-app bundles? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Somewhere in between a sitewide bundle and app-specific bundles lives the multi-app bundle. Suppose you want app1 and app2 in one bundle and app3, app4, and app5 in another. The following commands create the two needed entry files: :: python3 manage.py dmp_webpack --overwrite --single homepage/scripts/__entry_1__.js app1 app2 python3 manage.py dmp_webpack --overwrite --single homepage/scripts/__entry_2__.js app3 app4 app5 Then follow the same logic as the previous question (sitewide bundle) to include them in webpack's config and in the provider run. <file_sep>/docs/topics_signals.rst Signals =================== DMP sends several custom signals through the Django signal dispatcher. The purpose is to allow you to hook into the router's processing. Perhaps you need to run code at various points in the process, or perhaps you need to change the request.dmp\_\* variables to modify the router processing. Before going further with this section's examples, be sure to read the standard Django signal documentation. DMP signals are simply additional signals in the same dispatching system, so the following examples should be easy to understand once you know how Django dispatches signals. Step 1: Enable DMP Signals --------------------------------- Be sure your settings.py file has the following in it: :: 'SIGNALS': True, Step 2: Create a Signal Receiver ------------------------------------- The following creates two receivers. The first is called just before the view's process\_request function is called. The second is called just before DMP renders .html templates. .. code-block:: python from django.dispatch import receiver from django_mako_plus import signals, get_template_loader @receiver(signals.dmp_signal_pre_process_request) def pre_process_request(sender, request, view_args, view_kwargs, **kwargs): print('>>> process_request signal received!') @receiver(signals.dmp_signal_pre_render_template) def pre_render_template(sender, request, context, template, **kwargs): print('>>> render_template signal received!') # let's return a different template to be used - DMP will use this instead of kwargs['template'] tlookup = get_template_loader('myapp') template = tlookup.get_template('different.html') The above code should be in a code file that is called during Django initialization. Good locations might be in a ``models.py`` file or your app's ``__init__.py`` file. See `signals.py <https://github.com/doconix/django-mako-plus/blob/master/django_mako_plus/signals.py>`_ for all the full list of DMP signals and their keyword arguments. <file_sep>/docs/install_third_party.rst Integrating DMP with Third-Party Apps ======================================================= Since most third-party apps use standard Django routing and template syntax, new users to DMP often worry about conflicts between the two engines. Have no fear, they work together just like Windows and Linux! (just kidding, they work great together) Third-party apps often come with custom Django tags that you include in templates. Since those tags are likely in Django format (and not Mako), you'll have to slightly translate the documentation for each library. In most cases, third-party functions can be called directly from Mako. For example, the custom form tag in the `Django Paypal library <http://django-paypal.readthedocs.io/>`_ converts easily to Mako syntax: - The docs show: ``{{ form.render }}`` - You use: ``${ form.render() }`` In the above example, we're simply using regular Python in DMP to call the tags and functions within the third party library. If the tag can't be called using regular Python, you can usually inspect the third-party tag code. In most libraries, tags just call Python functions because since Django doesn't allow direct Python in templates. In the `Crispy Form library <http://django-crispy-forms.readthedocs.io/>`_, you can simply import and call its ``render_crispy_form`` function directly. This skips over the Django tag entirely: :: <%! from crispy_forms.utils import render_crispy_form %> <html> <body> <form method="POST"> ${ csrf_input } ${ render_crispy_form(form) } </form> </body> </html> If you call the ``render_crispy_form`` method in many templates, you may want to add the import to ``DEFAULT_TEMPLATE_IMPORTS`` in your ``settings.py`` file. Once this import exists in your settings, the function will be globally available in every template on your site. Whenever you modify the DMP settings, be sure to clean out your cached templates with ``python3 manage.py dmp_cleanup``. This ensures your compiled templates are rebuilt with the new settings. Using Third-Party Tags ------------------------------ There may be times when you can't call a third-party function. Or perhaps you just want to use the Django tags as the third-party library intended, dammit! Venture over to `Django Syntax and Tags </topics_other_syntax.html>`_ to see how to include Django-style tags in your Mako templates. <file_sep>/docs/static_custom.rst Creating a Provider ========================== Suppose you need custom preprocessing of static files or custom template content. Your future may include creating a new provider class. Fortunately, these are pretty simple classes. Once you create the class, simply reference it in your settings.py file. .. code-block:: python from django_mako_plus import BaseProvider class YourCustomProvider(BaseProvider): # these default options will be combined with BaseProvider.DEFAULT_OPTIONS and any in settings.py DEFAULT_OPTIONS = { 'any': 'additional', 'options': 'should', 'be': 'specified', 'here': '.', } def start(self, provider_run, data): ''' Called on the *main* template's provider list as the run starts. Initialize values in the data dictionary here. ''' pass def provide(self, provider_run, data): '''Called on *each* template's provider list in the chain - use provider_run.write() for content''' pass def finish(self, provider_run, data): ''' Called on the *main* template's provider list as the run finishes Finalize values in the data dictionary here. ''' pass Your provider will be instantitated once for each template in the system. When a template is first rendered at production time, your provider will be instantiated and cached with the template for future use. This single instance for a template will be used regardless of when the template is rendered -- as an ancestor of another template or as a final template. Wherever possible, move code to the constructor so the calls to ``start``, ``provide``, and ``finish`` can be as fast as possible. In particular, ``provide`` is called for the template **and** every supertemplate. During development (``DEBUG = True``), providers are instantiated **every** time the template is rendered. In effect, each render of a template is treated as if it were the "first time". This allows template/script/css changes to be seen without a server restart. For More Information -------------------------- See the ``provider/`` directory of the `DMP source code <https://github.com/doconix/django-mako-plus>`_. <file_sep>/django_mako_plus/template/util.py from django.apps import apps from django.utils.html import mark_safe from mako.exceptions import RichTraceback from mako.template import Template import mako.runtime import io import os, os.path def template_inheritance(obj): ''' Generator that iterates the template and its ancestors. The order is from most specialized (furthest descendant) to most general (furthest ancestor). obj can be either: 1. Mako Template object 2. Mako `self` object (available within a rendering template) ''' if isinstance(obj, Template): obj = create_mako_context(obj)['self'] elif isinstance(obj, mako.runtime.Context): obj = obj['self'] while obj is not None: yield obj.template obj = obj.inherits def create_mako_context(template_obj, **kwargs): # I'm hacking into private Mako methods here, but I can't see another # way to do this. Hopefully this can be rectified at some point. kwargs.pop('self', None) # some contexts have self in them, and it messes up render_unicode below because we get two selfs runtime_context = mako.runtime.Context(io.StringIO(), **kwargs) runtime_context._set_with_template(template_obj) _, mako_context = mako.runtime._populate_self_namespace(runtime_context, template_obj) return mako_context def get_template_debug_info(error): ''' Retrieves mako template information for Django's debug stack trace template. This allows Django to print Mako syntax/runtime template errors the same way it prints all other errors. ''' from ..convenience import get_template_loader_for_path dmp = apps.get_app_config('django_mako_plus') loader = get_template_loader_for_path(os.path.join(dmp.path, 'templates')) # going straight to the mako template in case the error bubbles into our # adapter (which calls this function and would cause infinite loops) template = loader.get_mako_template('stack_trace.html') tback = RichTraceback(error, error.__traceback__) return { 'message': '', 'source_lines': [ ( '', mark_safe(template.render_unicode(tback=tback)) ), ], 'before': '', 'during': '', 'after': '', 'top': 0, 'bottom': 0, 'total': 0, 'line': tback.lineno or 0, 'name': '', 'start': 0, 'end': 0, } <file_sep>/django_mako_plus/management/commands/dmp_webpack.py from django.apps import apps from django.utils.module_loading import import_string from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django_mako_plus.template import create_mako_context from django_mako_plus.provider.runner import ProviderRun from django_mako_plus.management.mixins import DMPCommandMixIn from mako.template import Template as MakoTemplate import os import os.path from collections import OrderedDict class Command(DMPCommandMixIn, BaseCommand): help = 'Removes compiled template cache folders in your DMP-enabled app directories.' can_import_settings = True def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( '--overwrite', action='store_true', dest='overwrite', default=False, help='Overwrite existing __entry__.js if necessary' ) parser.add_argument( '--single', type=str, metavar='FILENAME', help='Instead of per-app entry files, create a single file that includes the JS for all listed apps' ) parser.add_argument( 'appname', type=str, nargs='*', help='The name of one or more DMP apps. If omitted, all DMP apps are processed' ) def handle(self, *args, **options): dmp = apps.get_app_config('django_mako_plus') self.options = options WebpackProviderRun.initialize_providers() # ensure we have a base directory try: if not os.path.isdir(os.path.abspath(settings.BASE_DIR)): raise CommandError('Your settings.py BASE_DIR setting is not a valid directory. Please check your settings.py file for the BASE_DIR variable.') except AttributeError: raise CommandError('Your settings.py file is missing the BASE_DIR setting.') # the apps to process enapps = [] for appname in options.get('appname'): enapps.append(apps.get_app_config(appname)) if len(enapps) == 0: enapps = dmp.get_registered_apps() # main runner for per-app files if options.get('single') is None: for app in enapps: self.message('Searching `{}` app...'.format(app.name)) filename = os.path.join(app.path, 'scripts', '__entry__.js') self.create_entry_file(filename, self.generate_script_map(app), [ app ]) # main runner for one sitewide file else: script_map = {} for app in enapps: self.message('Searching `{}` app...'.format(app.name)) script_map.update(self.generate_script_map(app)) self.create_entry_file(options.get('single'), script_map, enapps) def create_entry_file(self, filename, script_map, enapps): '''Creates an entry file for the given script map''' if len(script_map) == 0: return # delete previous file if it exists, and ensure the target directory is there if os.path.exists(filename): if self.options.get('overwrite'): os.remove(filename) else: raise CommandError('Refusing to destroy existing file: {} (use --overwrite option or remove the file)'.format(filename)) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) # write the entry file self.message('Creating {}'.format(os.path.relpath(filename, settings.BASE_DIR))) template = MakoTemplate(''' <%! from datetime import datetime %> <%! import sys %> <%! import os %> // Generated on ${ datetime.now().strftime('%Y-%m-%d %H:%M') } by `${ ' '.join(sys.argv) }` // Contains links for ${ 'app' if len(enapps) == 1 else 'apps' }: ${ ', '.join(sorted([ a.name for a in enapps ])) } (context => { %for (app, template), script_paths in script_map.items(): %if len(script_paths) == 0: DMP_CONTEXT.linkBundleFunction("${ app }/${ template }", null); %else: DMP_CONTEXT.linkBundleFunction("${ app }/${ template }", () => { %for path in script_paths: require("./${ os.path.relpath(path, os.path.dirname(filename)) }"); %endfor }); %endif %endfor })(DMP_CONTEXT.get()); ''') with open(filename, 'w') as fout: fout.write(template.render( enapps=enapps, script_map=script_map, filename=filename, ).strip()) def generate_script_map(self, config): ''' Maps templates in this app to their scripts. This function deep searches app/templates/* for the templates of this app. Returns the following dictionary with absolute paths: { ( 'appname', 'template1' ): [ '/abs/path/to/scripts/template1.js', '/abs/path/to/scripts/supertemplate1.js' ], ( 'appname', 'template2' ): [ '/abs/path/to/scripts/template2.js', '/abs/path/to/scripts/supertemplate2.js', '/abs/path/to/scripts/supersuper2.js' ], ... } Any files or subdirectories starting with double-underscores (e.g. __dmpcache__) are skipped. ''' script_map = OrderedDict() template_root = os.path.join(os.path.relpath(config.path, settings.BASE_DIR), 'templates') def recurse(folder): subdirs = [] if os.path.exists(folder): for filename in os.listdir(folder): if filename.startswith('__'): continue filerel = os.path.join(folder, filename) if os.path.isdir(filerel): subdirs.append(filerel) elif os.path.isfile(filerel): template_name = os.path.relpath(filerel, template_root) scripts = self.template_scripts(config, template_name) key = ( config.name, os.path.splitext(template_name)[0] ) self.message('Found template: {}; static files: {}'.format(key, scripts), 3) script_map[key] = scripts for subdir in subdirs: recurse(subdir) recurse(template_root) return script_map def template_scripts(self, config, template_name): ''' Returns a list of scripts used by the given template object AND its ancestors. This runs a ProviderRun on the given template (as if it were being displayed). This allows the WEBPACK_PROVIDERS to provide the JS files to us. For this algorithm to work, the providers must extend static_links.LinkProvider because that class creates the 'enabled' list of provider instances, and each provider instance has a url. ''' dmp = apps.get_app_config('django_mako_plus') template_obj = dmp.engine.get_template_loader(config, create=True).get_mako_template(template_name, force=True) mako_context = create_mako_context(template_obj) inner_run = WebpackProviderRun(mako_context['self']) inner_run.run() scripts = [] for data in inner_run.column_data: for provider in data.get('enabled', []): # if file doesn't exist, the provider won't be enabled if hasattr(provider, 'filepath'): # providers used to collect for webpack must have a .filepath property scripts.append(provider.filepath) # the absolute path to the file (see providers/static_links.py) return scripts ############################################################################### ### Specialized provider run for the above management command class WebpackProviderRun(ProviderRun): SETTINGS_KEY = 'WEBPACK_PROVIDERS' def get_template_inheritance(self, tself): ''' Normally, this returns a list of the template inheritance of tself, starting with the oldest ancestor. But for the webpack one, we just want the template itself, without any ancestors. ''' return [ tself.template ] <file_sep>/django_mako_plus/provider/context.py from django.utils.module_loading import import_string import json import logging from ..version import __version__ from ..util import log from .base import BaseProvider ################################### ### JS Context Provider class JsContextProvider(BaseProvider): ''' Adds all js_context() variables to DMP_CONTEXT. This should be listed before JsLinkProvider so the context variables are available during <script> runs. ''' DEFAULT_OPTIONS = { # the group this provider is part of. this only matters when # the html page limits the providers that will be called with # ${ django_mako_plus.links(group="...") } 'group': 'scripts', # the encoder to use for the JSON structure 'encoder': 'django.core.serializers.json.DjangoJSONEncoder', } def __init__(self, template, options): super().__init__(template, options) self.encoder = import_string(self.options['encoder']) self.template = "{}/{}".format(self.app_config.name, self.template_relpath) if log.isEnabledFor(logging.DEBUG): log.debug('%s created', repr(self)) def start(self, provider_run, data): data['templates'] = [] def provide(self, provider_run, data): data['templates'].append(self.template) def finish(self, provider_run, data): if len(data['templates']) == 0: return context_data = { jscontext('__router__'): { 'template': self.template, 'app': provider_run.request.dmp.app if provider_run.request is not None else None, 'page': provider_run.request.dmp.page if provider_run.request is not None else None, }, } for k in provider_run.context.keys(): if isinstance(k, jscontext): value = provider_run.context[k] context_data[k] = value.__jscontext__() if hasattr(value, '__jscontext__') else value # add to the JS DMP_CONTEXT provider_run.write('<script>') provider_run.write('DMP_CONTEXT.set("{version}", "{contextid}", {data}, {templates});'.format( version=__version__, contextid=provider_run.uid, data=json.dumps(context_data, cls=self.encoder, separators=(',', ':')) if context_data else '{}', templates=json.dumps(data['templates']), )) provider_run.write('</script>') class jscontext(str): ''' Marks a key in the context dictionary as a JS context item. JS context items are sent to the template like normal, but they are also added to the runtime JS namespace. See the tutorial for more information on this function. ''' # no code needed, just using the class for identity <file_sep>/django_mako_plus/provider/webpack.py from django.conf import settings from django.forms.utils import flatatt import os import os.path import posixpath from ..util import merge_dicts from .link import CssLinkProvider, JsLinkProvider class WebpackJsLinkProvider(JsLinkProvider): '''Generates a JS <script> tag for an app-level JS bundle file, if it exists.''' DEFAULT_OPTIONS = { 'skip_duplicates': True, 'async': False, } def build_default_filepath(self): return os.path.join( self.app_config.name, 'scripts', '__bundle__.js', ) def build_default_link(self, provider_run, data): attrs = {} attrs["data-context"] = provider_run.uid attrs["src"] ="{}?{:x}".format( posixpath.join( settings.STATIC_URL, self.app_config.name, 'scripts', '__bundle__.js', ), self.version_id, ) attrs['onload'] = "DMP_CONTEXT.checkBundleLoaded('{}')".format(provider_run.uid) if self.options['async']: attrs['async'] = 'async' return '<script{}></script>'.format(flatatt(attrs)) def finish(self, provider_run, data): # this trigger call must be separate because script links may not always # render (duplicates are skipped) super().finish(provider_run, data) if len(data['enabled']) > 0: provider_run.write('<script data-context="{uid}">DMP_CONTEXT.triggerBundleContext("{uid}")</script>'.format( uid=provider_run.uid, )) <file_sep>/docs/static.rst Static Files ========================== One of the primary tasks of DMP is to connect your static files to your templates. The following topics explain how this is done. .. toctree:: :maxdepth: 1 static_links static_context static_providers static_webpack static_webpack_faq static_custom <file_sep>/docs/basics_redirecting.rst Redirecting the Browser ------------------------- Redirecting the browser is common in today's sites. For example, during form submissions, web applications often redirect the browser to the *same* page after a form submission (and handling with a view)--effectively switching the browser from its current POST to a regular GET. If the user hits the refresh button within his or her browser, the page simply gets refreshed without the form being submitted again. It prevents users from being confused when the browser opens a popup asking if the post data should be submitted again. DMP provides a Javascript-based redirect response and four exception-based redirects. The first, ``HttpResponseJavascriptRedirect``, sends a regular HTTP 200 OK response that contains Javascript to redirect the browser: ``<script>window.location.href="...";</script>``. Normally, redirecting should be done via Django's built-in ``HttpResponseRedirect`` (HTTP 302), but there are times when a normal 302 doesn't do what you need. For example, suppose you need to redirect the top-level page from an Ajax response. Ajax redirects normally only redirects the Ajax itself (not the page that initiated the call), and this default behavior is usually what is needed. However, there are instances when the entire page must be redirected, even if the call is Ajax-based. Note that this class doesn't use the tag or Refresh header method because they aren't predictable within Ajax (for example, JQuery seems to ignore them). The four exception-based redirects allow you to raise a redirect from anywhere in your code. For example, the user might not be authenticated correctly, but the code that checks for this can't return a response object. Since these three are exceptions, they bubble all the way up the call stack to the DMP router -- where they generate a redirect to the browser. Exception-based redirects should be used sparingly, but they can help you create clean code. For example, without the ability to redirect with an exception, you might have to pass and return other variables (often the request/response objects) through many more function calls. As you might expect, ``RedirectException`` sends a normal 302 redirect and ``PermanentRedirectException`` sends a permanent 301 redirect. ``JavascriptRedirectException`` sends a redirect ``HttpResponseJavascriptRedirect`` as described above. The fourth exception, ``InternalRedirectException``, is simpler and faster: it restarts the routing process with a different view/template within the *current* request, without changing the browser url. Internal redirect exceptions are rare and shouldn't be abused. An example might be returning an "upgrade your browser" page to a client; since the user has an old browser, a regular 302 redirect might not work the way you expect. Redirecting internally is much safer because your server stays in control the entire time. The following code shows examples of different redirection methods: .. code-block:: python from django.http import HttpResponseRedirect from django_mako_plus import HttpResponseJavascriptRedirect from django_mako_plus import RedirectException, PermanentRedirectException, JavascriptRedirectException, InternalRedirectException # return a normal redirect with Django from a process_request method return HttpResponseRedirect('/some/new/url/') # return a Javascript-based redirect from a process_request method return HttpResponseJavascriptRedirect('/some/new/url/') # raise a normal redirect from anywhere in your code raise RedirectException('/some/new/url') # raise a permanent redirect from anywhere in your code raise PermanentRedirectException('/some/new/url') # raise a Javascript-based redirect from anywhere in your code raise JavascriptRedirectException('/some/new/url') # restart the routing process with a new view without returning to the browser. # the browser keeps the same url and doesn't know a redirect has happened. # the request.dmp.module and request.dmp.function variables are updated # to reflect the new values, but all other variables, such as request.dmp.urlparams, # request.GET, and request.POST remain the same as before. # the next line is as if the browser went to /homepage/upgrade/ raise InternalRedirectException('homepage.views.upgrade', 'process_request') DMP adds a custom header, "Redirect-Exception", to all exception-based redirects. Although you'll probably ignore this most of the time, the header allows you to further act on exception redirects in response middleware, your web server, or calling Javascript code. Is this an abuse of exceptions? Probably. But from one viewpoint, a redirect can be seen as an exception to normal processing. It is quite handy to be able to redirect the browser from anywhere in your codebase. If this feels dirty to you, feel free to skip it. <file_sep>/docs/basics_paths.rst Template Location/Import =========================================== .. contents:: :depth: 2 Template Inheritance Across Apps -------------------------------- You may have noticed that this tutorial has focused on a single app. Most projects consist of many apps. For example, a sales site might have an app for user management, an app for product management, and an app for the catalog and sales/shopping-cart experience. All of these apps probably want the same look and feel, and all of them likely want to extend from the **same** ``base.htm`` file. When you run ``python3 manage.py dmp_startapp <appname>``, you get **new** ``base.htm`` and ``base_ajax.htm`` files each time. This is done to get you started on your first app. On your second, third, and subsequent apps, you probably want to delete these starter files and instead extend your templates from the ``base.htm`` and ``base_ajax.htm`` files in your first app. In fact, in my projects, I usually create an app called ``base_app`` that contains the common ``base.htm`` html code, site-wide CSS, and site-wide Javascript. Subsequent apps simply extend from ``/base_app/templates/base.htm``. The common ``base_app`` doesn't really have end-user templates in it -- they are just supertemplates that support other, public apps. DMP supports cross-app inheritance by including your project root (e.g. ``settings.BASE_DIR``) in the template lookup path. All you need to do is use the full path (relative to the project root) to the template in the inherits statement. Suppose I have the following app structure: :: dmptest base_app/ __init__.py media/ scripts/ styles/ templates/ site_base_ajax.htm site_base.htm views/ __init__.py homepage/ __init__.py media/ scripts/ styles/ templates/ index.html views/ __init__.py I want ``homepage/templates/index.html`` to extend from ``base_app/templates/site_base.htm``. The following code in ``index.html`` sets up the inheritance: .. code-block:: html+mako <%inherit file="/base_app/templates/site_base.htm" /> Again, the front slash in the name above tells DMP to start the lookup at the project root. In fact, my pages are often three inheritance levels deep: ``base_app/templates/site_base.htm -> homepage/templates/base.htm -> homepage/templates/index.html`` to provide for site-wide page code, app-wide page code, and specific page code. Templates in Other Apps -------------------------- Need to render templates from a different app? There's two ways to do it. Note the imports in the code below: First Way: .. code-block:: python from django.conf import settings from django.http import HttpResponse from django_mako_plus import view_function, render_template from datetime import datetime @view_function def process_request(request): context = { 'now': datetime.now(), } # replace 'homepage' with the name of any DMP-enabled app: return HttpResponse(render_template(request, 'homepage', 'index.html', context)) Second Way (this way uses the standard Django API): .. code-block:: python from django.conf import settings from django.shortcuts import render from django_mako_plus import view_function from datetime import datetime @view_function def process_request(request): context = { 'now': datetime.now(), } # replace 'homepage' with the name of any DMP-enabled app: return render(request, 'homepage/index.html', context) Content Types and Status Codes -------------------------------- The ``request.dmp.render()`` function determines the mime type from the template extension and returns a *200* status code. What if you need to return JSON, CSV, or a 404 not found? The function takes these parameters too. A few examples: .. code-block:: python from django.http import HttpResponse # return CSV return request.dmp.render('my_csv.html', {}, content_type='text/csv') # return a custom error page return request.dmp.render('custom_error_page.html', {}, status=404) # specify a different template charset (or set globally in settings.py) return request.dmp.render('im_old.html', {}, content_type='cp1252') Changing the Template Location (globally) -------------------------------------------- Suppose your templates are located in a directory outside your normal project root. For whatever reason, you don't want to put your templates in the app/templates directory. Case 1: Templates Within Your Project Directory ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ If the templates you need to access are within your project directory, no extra setup is required. Simply reference those templates relative to the root project directory. For example, to access a template located at BASE\_DIR/homepage/mytemplates/sub1/page.html, use the following: .. code-block:: python return request.dmp.render('/homepage/mytemplates/sub1/page.html', context) Note the starting slash on the path. That tells DMP to start searching at your project root. Don't confuse the slashes in the above call with the slash used in Django's ``render`` function. When you call ``render``, the slash separates the app and filename. The above call uses ``request.dmp.render``, which is a different function. You should really standardize on one or the other throughout your project. Case 2: Templates Outside Your Project Directory ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Suppose your templates are located on a different disk or entirely different directory from your project. DMP allows you to add extra directories to the template search path through the ``TEMPLATES_DIRS`` setting. This setting contains a list of directories that are searched by DMP regardless of the app being referenced. To include the ``/var/templates/`` directory in the search path, set this variable as follows: .. code-block:: python 'TEMPLATES_DIRS': [ '/var/templates/', ], Suppose, after making the above change, you need to render the '/var/templates/page1.html' template: .. code-block:: python return request.dmp.render('page1.html', context) DMP will first search the current app's ``templates`` directory (i.e. the normal way), then it will search the ``TEMPLATES_DIRS`` list, which in this case contains ``/var/templates/``. Your ``page1.html`` template will be found and rendered. Importing Python Modules ------------------------------- It's easy to import Python modules in your Mako templates. Simply use a module-level block: .. code-block:: python <%! import datetime from decimal import Decimal %> or a Python-level block (see the Mako docs for the difference): .. code-block:: python <% import datetime from decimal import Decimal %> There may be some modules, such as ``re`` or ``decimal`` that are so useful you want them available in every template of your site. In settings.py, add these to the ``DEFAULT_TEMPLATE_IMPORTS`` variable: .. code-block:: python DEFAULT_TEMPLATE_IMPORTS = [ 'import os, os.path, re', 'from decimal import Decimal', ], Any entries in this list will be automatically included in templates throughout all apps of your site. With the above imports, you'll be able to use ``re`` and ``Decimal`` and ``os`` and ``os.path`` anywhere in any .html, .cssm, and .jsm file. Whenever you modify the DMP settings, be sure to clean out your cached templates with ``python3 manage.py dmp_cleanup``. This ensures your compiled templates are rebuilt with the new settings. Cleaning Up ----------- DMP caches its compiled templates in subdirectories of each app. The default locations for each app are ``app/templates/__dmpcache__``, ``app/scripts/__dmpcache__``, and ``app/styles/__dmpcache__``, although the exact name depends on your settings.py. Normally, these cache directories are hidden and warrant your utmost apathy. However, there are times when DMP fails to update a cached template as it should. Or you might just need a pristine project without these generated files. This can be done with a Unix find command or through DMP's ``dmp cleanup`` management command: :: # see what would be be done without actually deleting any cache folders python3 manage.py dmp_cleanup --trial-run # really delete the folders python3 manage.py dmp_cleanup With this management command, add ``--verbose`` to the command to include messages about skipped files, and add ``--quiet`` to silence all messages (except errors). <file_sep>/docs/basics_variables.rst Useful Variables ====================== At the beginning of each request (as part of its middleware), DMP adds a routing data object as ``request.dmp``. This object primarily supports the inner workings of the DMP router, but it may be useful to you as well. The following are available throughout the request: - ``request.dmp.app``: The Django application specified in the URL. In the URL ``http://www.server.com/calculator/index/1/2/3``, ``request.dmp.app`` is the string "calculator". | - ``request.dmp.page``: The name of the Python module specified in the URL. In the URL ``http://www.server.com/calculator/index/1/2/3``, the ``request.dmp.page`` is the string "index". In the URL ``http://www.server.com/calculator/index.somefunc/1/2/3``, ``request.dmp.page`` is still the string "index". | - ``request.dmp.function``: The name of the function within the module that will be called, even if it is not specified in the URL. In the URL ``http://www.server.com/calculator/index/1/2/3``, the ``request.dmp.function`` is the string "process\_request" (the default function). In the URL ``http://www.server.com/calculator/index.somefunc/1/2/3``, ``request.dmp.function`` is the string "somefunc". | - ``request.dmp.module``: The name of the real Python module specified in the URL, as it will be imported into the runtime module space. In the URL ``http://www.server.com/calculator/index/1/2/3``, ``request.dmp.module`` is the string "calculator.views.index". | - ``request.dmp.callable``: A reference to the view function. | - ``request.dmp.view_type``: The type of view: function (regular view function), class (class-based view), or template (direct template render). | - ``request.dmp.urlparams``: A list of parameters specified in the URL. See the the topic on `Parameter Conversion <topics_converters.html>`__ for more information. | A "default" routing object is added at the beginning of the request, but actual routing data isn't available **until the view middleware stage**. It isn't done earlier in the lifecycle because DMP should obey Django's urls.py routing rules (and urls.py comes after the middleware). <file_sep>/setup.py import os, os.path, sys, re from setuptools import setup MODULE_NAME = 'django_mako_plus' # I can't import the version file the normal way because it loads # __init__.py, which then imports the DMP engine. with open('django_mako_plus/version.py') as f: match = re.search("__version__\s=\s'(\d+\.\d+\.\d+)'", f.read()) if not match: print('Cannot determine the DMP version. Aborting setup.py.') sys.exit(1) VERSION = match.group(1) CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python :: 3 :: Only', 'Framework :: Django', 'Framework :: Django :: 1.11', 'Framework :: Django :: 1.10', 'Framework :: Django :: 1.9', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Topic :: Software Development', ] install_requires = [ 'django >= 1.9.0', 'mako >= 1.0.0', ] if len(sys.argv) >= 2 and sys.argv[1] == 'sdist': # remove the __pycache__ directories since the ones in project_template seems to stick around os.system('find . -name "__pycache__" -type d -exec rm -r "{}" \; > /dev/null') # Compile the list of packages available packages = [] def walk(root): for fname in os.listdir(root): fpath = os.path.join(root, fname) # skip hidden/cache files if fname.startswith('.') or fname.endswith('.pyc') or fname in ( '__pycache__', 'app_template', 'project_template' ): continue # if a directory, walk it elif os.path.isdir(fpath): walk(fpath) # if an __init__.py file, add the directory to the packages elif fname == '__init__.py': packages.append(os.path.dirname(fpath)) walk(MODULE_NAME) data_files = [] # add the readme/license data_files.extend([ ('', [ 'readme.md' ]), ('', [ 'readme.txt' ]), ('', [ 'license.txt' ]), ]) # add the extra directories # empty directories within app_template/ will cause problems with distutils, so be sure each directory has at least one file package_data_files = [] for template_dir in ( 'app_template', 'project_template', 'webroot' ): for root, dirs, files in os.walk(os.path.join(MODULE_NAME, template_dir)): dirs[:] = [ d for d in dirs if not d.startswith('.') and not d in ( '__pycache__', ) ] # skip hidden and __pycache__ directories for fname in files: if fname.startswith('.') or fname.endswith('.pyc'): # skip hidden/cache files continue package_data_files.append(os.path.join(root[len(MODULE_NAME)+1:], fname)) # read the long description if sdist description = 'Django+Mako: Routing by Convention, Python-Centric Template Language' long_description = description if len(sys.argv) > 1 and sys.argv[1] == 'sdist': long_description = open('readme.txt').read() # run the setup setup( name='django-mako-plus', description=description, long_description=long_description, version=VERSION, author='<NAME>', author_email='<EMAIL>', url="http://django-mako-plus.readthedocs.io/", download_url="https://github.com/doconix/django-mako-plus/archive/master.zip", packages=packages, package_data = { MODULE_NAME: package_data_files, }, entry_points={ 'console_scripts': [ 'django_mako_plus = django_mako_plus.__main__:main' ] }, install_requires=install_requires, classifiers=CLASSIFIERS, license='Apache 2.0', ) <file_sep>/django_mako_plus/templates/.cached_templates/stack_trace.html.py # -*- coding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED STOP_RENDERING = runtime.STOP_RENDERING __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1544556954.7268622 _enable_loop = True _template_filename = '/Users/conan/Documents/data/programming/django-mako-plus/django_mako_plus/templates/stack_trace.html' _template_uri = 'stack_trace.html' _source_encoding = 'utf-8' import django_mako_plus import django.utils.html import django_mako_plus _exports = [] from mako.exceptions import syntax_highlight, pygments_html_formatter def render_body(context,**pageargs): __M_caller = context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) bytes = context.get('bytes', UNDEFINED) len = context.get('len', UNDEFINED) self = context.get('self', UNDEFINED) isinstance = context.get('isinstance', UNDEFINED) tback = context.get('tback', UNDEFINED) min = context.get('min', UNDEFINED) range = context.get('range', UNDEFINED) max = context.get('max', UNDEFINED) __M_writer = context.writer() __M_writer('\n') __M_writer('\n<style>\n .stacktrace { margin:5px 5px 5px 5px; }\n .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }\n .nonhighlight { padding:0px; background-color:#DFDFDF; }\n .sample { padding:10px; margin:10px 10px 10px 10px;\n font-family:monospace; }\n .sampleline { padding:0px 10px 0px 10px; }\n .sourceline { margin:5px 5px 10px 5px; font-family:monospace;}\n .location { font-size:80%; }\n .highlight { white-space:pre; }\n .sampleline { white-space:pre; }\n\n') if pygments_html_formatter: __M_writer(' ') __M_writer(django_mako_plus.ExpressionPostProcessor(self, extra={'n_filter_on': True})(pygments_html_formatter.get_style_defs() )) __M_writer('\n .linenos { min-width: 2.5em; text-align: right; }\n pre { margin: 0; }\n .syntax-highlighted { padding: 0 10px; }\n .syntax-highlightedtable { border-spacing: 1px; }\n .nonhighlight { border-top: 1px solid #DFDFDF;\n border-bottom: 1px solid #DFDFDF; }\n .stacktrace .nonhighlight { margin: 5px 15px 10px; }\n .sourceline { margin: 0 0; font-family:monospace; }\n .code { background-color: #F8F8F8; width: 100%; }\n .error .code { background-color: #FFBDBD; }\n .error .syntax-highlighted { background-color: #FFBDBD; }\n') __M_writer('\n') __M_writer(' table.source {\n background-color: #fdfdfd;\n }\n table.source > tbody > tr > th {\n width: auto;\n }\n table.source > tbody > tr > td {\n font-family: inherit;\n white-space: normal;\n padding: 15px;\n }\n #template {\n background-color: #b3daff;\n }\n\n</style>\n') src = tback.source line = tback.lineno if isinstance(src, bytes): src = src.decode() if src: lines = src.split('\n') else: lines = None __M_locals_builtin_stored = __M_locals_builtin() __M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['src','lines','line'] if __M_key in __M_locals_builtin_stored])) __M_writer('\n<h3>') __M_writer(django_mako_plus.ExpressionPostProcessor(self)(tback.errorname)) __M_writer(': ') __M_writer(django_mako_plus.ExpressionPostProcessor(self)(tback.message)) __M_writer('</h3>\n\n') if lines: __M_writer(' <div class="sample">\n <div class="nonhighlight">\n') for index in range(max(0, line-4),min(len(lines), line+5)): __M_writer(' ') if pygments_html_formatter: pygments_html_formatter.linenostart = index + 1 __M_locals_builtin_stored = __M_locals_builtin() __M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in [] if __M_key in __M_locals_builtin_stored])) __M_writer('\n') if index + 1 == line: __M_writer(' ') if pygments_html_formatter: old_cssclass = pygments_html_formatter.cssclass pygments_html_formatter.cssclass = 'error ' + old_cssclass __M_locals_builtin_stored = __M_locals_builtin() __M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in ['old_cssclass'] if __M_key in __M_locals_builtin_stored])) __M_writer('\n ') __M_writer(django_mako_plus.ExpressionPostProcessor(self, extra={'n_filter_on': True})(syntax_highlight(language='mako')(lines[index] ))) __M_writer('\n ') if pygments_html_formatter: pygments_html_formatter.cssclass = old_cssclass __M_locals_builtin_stored = __M_locals_builtin() __M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in [] if __M_key in __M_locals_builtin_stored])) __M_writer('\n') else: __M_writer(' ') __M_writer(django_mako_plus.ExpressionPostProcessor(self, extra={'n_filter_on': True})(syntax_highlight(language='mako')(lines[index] ))) __M_writer('\n') __M_writer(' </div>\n </div>\n') __M_writer('\n<div class="stacktrace">\n') for (filename, lineno, function, line) in tback.reverse_traceback: __M_writer(' <div class="location">') __M_writer(django_mako_plus.ExpressionPostProcessor(self)(filename)) __M_writer(', line ') __M_writer(django_mako_plus.ExpressionPostProcessor(self)(lineno)) __M_writer(':</div>\n <div class="nonhighlight">\n ') if pygments_html_formatter: pygments_html_formatter.linenostart = lineno __M_locals_builtin_stored = __M_locals_builtin() __M_locals.update(__M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in [] if __M_key in __M_locals_builtin_stored])) __M_writer('\n <div class="sourceline">') __M_writer(django_mako_plus.ExpressionPostProcessor(self, extra={'n_filter_on': True})(syntax_highlight(filename)(line ))) __M_writer('</div>\n </div>\n') __M_writer('</div>\n') return '' finally: context.caller_stack._pop_frame() """ __M_BEGIN_METADATA {"filename": "/Users/conan/Documents/data/programming/django-mako-plus/django_mako_plus/templates/stack_trace.html", "uri": "stack_trace.html", "source_encoding": "utf-8", "line_map": {"19": 8, "21": 0, "34": 7, "35": 8, "36": 21, "37": 22, "38": 22, "39": 22, "40": 35, "41": 37, "42": 53, "56": 63, "57": 64, "58": 64, "59": 64, "60": 64, "61": 66, "62": 67, "63": 69, "64": 70, "65": 70, "72": 73, "73": 74, "74": 75, "75": 75, "83": 79, "84": 80, "85": 80, "86": 81, "93": 84, "94": 85, "95": 86, "96": 86, "97": 86, "98": 89, "99": 92, "100": 94, "101": 95, "102": 95, "103": 95, "104": 95, "105": 95, "106": 97, "113": 100, "114": 101, "115": 101, "116": 104, "122": 116}} __M_END_METADATA """ <file_sep>/django_mako_plus/templatetags/django_mako_plus.py from django import template from django.utils.safestring import mark_safe from ..convenience import render_template register = template.Library() ########################################### ### The tags in this file are DJANGO ### tags, not Mako ones. @register.simple_tag(takes_context=True) def dmp_include(context, app, template_name, def_name=None): ''' Includes a DMP (Mako) template into a normal django template. In other words, this is used whenyou have a Django-style template and need to include another template within it -- but that template is written in DMP (Mako) syntax rather than Django syntax. ''' return mark_safe(render_template( request=context.get('request'), app=app, template_name=template_name, context=context.flatten(), def_name=def_name ))
e6b9ca7b13a21fcc5a26e787191c845698a47f17
[ "JavaScript", "Python", "Text", "reStructuredText" ]
38
reStructuredText
BrightBridgeWeb/django-mako-plus
24690661b80562a510c1632853815df5111b606c
c42e6b3ff4a62b5110f6412958b8df585ae78881
refs/heads/master
<file_sep>import {statusEnum} from "../../enums/status.enum"; import {IsDateString, IsEnum, IsMongoId, IsNotEmpty, IsOptional, IsString, Validate} from "class-validator"; import {IsMinDateToday} from "../decorators/date-validate.decorator" import {ApiProperty} from "@nestjs/swagger"; export class CreateProjectDto { @ApiProperty({ description: 'The title of the project', }) @IsString() @IsNotEmpty() title: string; @ApiProperty({ description: 'Reference to responsible user' }) @IsMongoId() responsible: string; @ApiProperty({ description: 'Full description of the project' }) @IsString() @IsNotEmpty() description: string; @ApiProperty({ description: 'Status value', enum: statusEnum, default: statusEnum.new }) @IsString() @IsOptional() @IsEnum(statusEnum) status: statusEnum; @IsString() @IsNotEmpty() comment: string; @ApiProperty({ description: 'Date string', }) @IsDateString() @Validate(IsMinDateToday,{message: "dueDate should not be in the past"}) dueDate: Date } <file_sep>import { Controller, HttpStatus, Post, Res, Body, Get, NotFoundException, ValidationPipe, Param, Put, Delete, UseGuards, Req, UsePipes, Query } from '@nestjs/common'; import {ApiCreatedResponse, ApiNotFoundResponse, ApiOperation} from "@nestjs/swagger"; import {TaskService} from "./task.service"; import {CreateTaskDTO} from "./dto/create-task.dto"; import JwtAuthenticationGuard from "../auth/guards/jwt-authentification.guard"; import {RolesGuard} from "../auth/guards/roles.guard"; import {TaskFilterDto} from "./dto/task-filter.dto"; import {ApiImplicitQuery} from "@nestjs/swagger/dist/decorators/api-implicit-query.decorator"; @Controller('tasks') @UseGuards(JwtAuthenticationGuard, RolesGuard) @UsePipes(new ValidationPipe()) export class TaskController { constructor(private taskService: TaskService) { } @Post() @ApiCreatedResponse({ description: 'OK'}) @ApiOperation({ operationId: 'addTask', description: 'create new task' }) async addTask(@Req() req, @Body() createTaskDTO: CreateTaskDTO) { const newTask = await this.taskService.addTask(createTaskDTO, req.user); return newTask; } @Get('/:taskID') @ApiCreatedResponse({ description: 'OK'}) @ApiNotFoundResponse({ type: NotFoundException, description: 'Task does not exist!' }) @ApiOperation({ operationId: 'getTask', description: 'get task info' }) async getTask(@Res() res, @Param('taskID') taskID) { const task = await this.taskService.getTask(taskID); if (!task) { throw new NotFoundException('Task does not exist!'); } res.status(HttpStatus.OK).json({ task }) } @Get('/') @ApiCreatedResponse({ description: 'OK'}) @ApiOperation({ operationId: 'getTasksList', description: 'get task list' }) async getTasks(@Query() query: TaskFilterDto) { return await this.taskService.getTasks(query); } @Put('/:taskID') @ApiCreatedResponse({ description: 'OK'}) @ApiNotFoundResponse({ type: NotFoundException, description: 'Task does not exist!' }) @ApiOperation({ operationId: 'editTasks', description: 'edit task info' }) async updateTask(@Res() res, @Req() req, @Param('taskID') taskID, @Body() createTaskDTO: CreateTaskDTO) { const task = await this.taskService.updateTask(taskID, createTaskDTO, req.user); if (!task) { throw new NotFoundException('Task does not exist!'); } res.status(HttpStatus.OK).json( task ) } @Delete('/:taskID') @ApiCreatedResponse({ description: 'OK'}) @ApiNotFoundResponse({ type: NotFoundException, description: 'Task does not exist!' }) @ApiOperation({ operationId: 'deleteTask', description: 'delete task' }) async deleteTask(@Res() res, @Req() req, @Param('taskID') taskID) { const task = await this.taskService.deleteTask(taskID); res.status(HttpStatus.OK).json({ message: `Task ${taskID} was deleted` } ) } }<file_sep>import {Document} from 'mongoose'; import {roleEnum} from "../../enums/role.enum"; export interface User extends Document { readonly _id: string; readonly email: string; password?: string; roles: roleEnum[]; }<file_sep>import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { NestExpressApplication } from '@nestjs/platform-express'; import {SwaggerModule, DocumentBuilder} from '@nestjs/swagger'; import {join} from "path"; async function bootstrap() { const app = await NestFactory.create<NestExpressApplication>(AppModule); app.enableCors(); app.useStaticAssets(join(__dirname,"..", 'static')) const options = new DocumentBuilder() .setTitle('API') .setDescription('Test nest project api') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, options); SwaggerModule.setup('api', app, document); await app.listen(3000); } bootstrap(); <file_sep>import {roleEnum} from "../../enums/role.enum"; import {ObjectIdDTO} from "../../user/dto/object-id.dto"; export interface Payload { readonly id: ObjectIdDTO; readonly email: string; readonly roles: roleEnum[]; }<file_sep>export interface TaskChanges { readonly operationType: string; readonly ns: object; readonly fullDocument: object; }<file_sep>import * as mongoose from "mongoose" import {statusEnum} from "../../enums/status.enum"; export const ProjectSchema = new mongoose.Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, }, title: { type: String, required: true, }, description: { type: String, }, responsible: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: false, }, status: { type: String, enum: Object.values(statusEnum), required: true, }, dueDate: { type: Date, }, createdAt: { default: Date.now(), type: Date, }, updatedAt: { default: Date.now(), type: Date, }, comment: { type: String, } })<file_sep>import {IsString, IsEmail, Matches, MinLength, IsNotEmpty} from "class-validator"; export class CreateUserDto { @IsEmail() @IsString() @IsNotEmpty() readonly email: string; @IsString() @IsNotEmpty() @MinLength(6) @Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, { message: 'Password must contain: at least 1 upper case letter, at least 1 lower case letter, at least 1 number or special character' }) readonly password: string; }<file_sep>import {ValidatorConstraint, ValidatorConstraintInterface} from "class-validator"; @ValidatorConstraint() export class IsMinDateToday implements ValidatorConstraintInterface { validate(date: string): Promise<boolean> | boolean { return (new Date(date) >= new Date()) } }<file_sep>import { Controller, Post, Body, UsePipes, ValidationPipe, Res, HttpStatus } from '@nestjs/common'; import {Response} from 'express'; import {AuthService} from "./auth.service"; import {AuthCredentialsDto} from "./dto/auth-credentials.dto"; import {CreateUserDto} from "../user/dto/create-user.dto"; @Controller('auth') export class AuthController { constructor(private authService: AuthService) { } @Post('/login') async login(@Body() authCredentials: AuthCredentialsDto): Promise<{ accessToken: string }> { return this.authService.login(authCredentials); } @Post('/signUp') @UsePipes(ValidationPipe) async signUp(@Res() res: Response, @Body() createUserDto: CreateUserDto) { await this.authService.signUp(createUserDto); res.status(HttpStatus.OK).json({message: 'user was created'}); } } <file_sep>import { SubscribeMessage, WebSocketGateway, WebSocketServer, OnGatewayInit, OnGatewayDisconnect, OnGatewayConnection, WsException, } from "@nestjs/websockets"; import {Server, Socket} from "socket.io"; import {Logger} from "@nestjs/common"; import {AuthService} from "../auth/auth.service"; @WebSocketGateway() export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect { constructor(private authService: AuthService) { } @WebSocketServer() wss: Server; private logger: Logger = new Logger('EventGateway'); public afterInit(server: Server) { this.logger.log('Initialized'); } async handleConnection(client: Socket, ...args): Promise<any> { if (client.handshake.headers.authorization) { const token = client.handshake.headers.authorization.substring(7); const clientPayload = await this.authService.validate(token); if (!clientPayload) { client.disconnect(true); } } else { client.disconnect(true); } this.logger.log('Client connected: ' + client.id) } handleDisconnect(client: Socket): any { this.logger.log('Client disconnected: ' + client.id) } @SubscribeMessage("msgToServe") handleMessage(client: Socket, msg: string): void { this.wss.emit("message", {data: msg}); } sendEvent(event: string, msg: any): void { this.wss.emit(event, {data: msg}) } }<file_sep>import { Module } from '@nestjs/common'; import { ProjectService } from './project.service'; import { ProjectController } from './project.controller'; import {MongooseModule} from "@nestjs/mongoose"; import {ProjectSchema} from "./schemas/project.schema"; import {TaskSchema} from "../task/schemas/task.schema"; @Module({ imports:[MongooseModule.forFeature([{name: 'Project', schema: ProjectSchema}, {name: 'Task', schema:TaskSchema}])], controllers: [ProjectController], providers: [ProjectService] }) export class ProjectModule {} <file_sep>import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common'; import * as mongoose from "mongoose"; @Injectable() export class FiltersPipe implements PipeTransform { transform(query: any, metadata: ArgumentMetadata) { query.page = +query.page || 1; query.pageSize = +query.pageSize || 100; if (query.author){ query.author = mongoose.Types.ObjectId(query.author); } if (query.responsible){ query.responsible = mongoose.Types.ObjectId(query.responsible); } return query; } }<file_sep>import {Injectable} from '@nestjs/common'; import {InjectModel} from "@nestjs/mongoose"; import {Model} from "mongoose"; import {Task} from "./interfaces/task.interface"; import {CreateTaskDTO} from "./dto/create-task.dto"; import {User} from "../user/interfaces/user.interface"; import {EventsGateway} from "../events/events.gateway"; import {TaskChanges} from "./interfaces/task-change-object.interface"; import {Project} from "../project/interfaces/project.interface"; import {TaskFilterDto} from "./dto/task-filter.dto"; import * as _ from "lodash"; @Injectable() export class TaskService { constructor(@InjectModel('Task') private readonly taskModel: Model<Task>, @InjectModel('Project') private readonly projectModel: Model<Project>, private socket: EventsGateway) { this.checkTasksChanges(); } async addTask(createTaskDTO: CreateTaskDTO, user: User): Promise<Task> { const newTask = await this.taskModel(Object.assign(createTaskDTO, {author: user._id})); return newTask.save(); } async getTask(taskID): Promise<Task> { const task = await this.taskModel.findById(taskID).exec(); return task; } async getTasks(query: TaskFilterDto): Promise<Task[]> { const pageSize = query.pageSize || 100; const tasks = await this.taskModel.find(_.omit(query, ["pageSize", "page"])).skip(query.page * pageSize).limit(pageSize).exec(); return tasks; } async updateTask(taskID, createTaskDTO: CreateTaskDTO, user: User): Promise<Task> { const editedTask = await this.taskModel.findByIdAndUpdate(taskID, Object.assign(createTaskDTO, {executor: user._id}), {new: true}); return editedTask; } async deleteTask(taskID): Promise<Task> { return await this.taskModel.findByIdAndDelete(taskID); } async checkTasksChanges(): Promise<void> { this.taskModel.watch().on('change', (data: TaskChanges) => { this.socket.sendEvent(data.operationType, data) }) } } <file_sep>import * as mongoose from 'mongoose'; import {statusEnum} from "../../enums/status.enum"; export const TaskSchema = new mongoose.Schema({ author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true, }, title: { type: String, }, description: { type: String, }, executor: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: false, }, status: { type: String, enum: Object.values(statusEnum), required: true, }, createdAt: { default: Date.now(), type: Date, }, comment: { type: String, }, project:{ type: mongoose.Schema.Types.ObjectId, ref: 'Project', required: true, } });<file_sep>import { IsMongoId } from 'class-validator'; import { ObjectID } from 'mongodb'; export class ObjectIdDTO { @IsMongoId() public id: ObjectID; }<file_sep>import {Injectable} from '@nestjs/common'; import {CreateProjectDto} from './dto/create-project.dto'; import {UpdateProjectDto} from './dto/update-project.dto'; import {InjectModel} from "@nestjs/mongoose"; import {Model} from "mongodb"; import * as mongoose from "mongoose"; import * as _ from "lodash"; import {Project} from "./interfaces/project.interface"; import {ObjectIdDTO} from "../user/dto/object-id.dto"; import {User} from "../user/interfaces/user.interface"; import {Task} from "../task/interfaces/task.interface"; import {ProjectFilterDto} from "./dto/filter-project.dto"; @Injectable() export class ProjectService { constructor(@InjectModel('Project') private readonly projectModel: Model<Project>, @InjectModel('Task') private readonly taskModel: Model<Task>) { } create(createProjectDto: CreateProjectDto, user: User): Promise<Project> { return this.projectModel.create(Object.assign(createProjectDto, {author: user._id})); } async findAll(query: ProjectFilterDto): Promise<{ projects: Project[], pages: number }> { const skip = (query.page - 1) * query.pageSize; const [result] = await this.projectModel.aggregate([ { $facet: { count: [{$count: "value"}], projects: [{$match: _.omit(query, ["pageSize", "page"])}, {$skip: skip}, {$limit: query.pageSize}] } }, {$unwind: "$count"}, {$set: {count: "$count.value"}} ]); return {projects: result.projects, pages: Math.trunc(result.count / query.pageSize) || 1} } async findOne(id: ObjectIdDTO): Promise<Project> { return this.projectModel.findById(id); } async findTasksByProject(id: ObjectIdDTO): Promise<Project> { return this.projectModel.aggregate([ {"$match": {"_id": mongoose.Types.ObjectId(id)}}, { "$lookup": { from: "tasks", pipeline: [{ $match: { $and: [ { project: { $in: [mongoose.Types.ObjectId(id)] } }], }, }], as: "tasks" } } ]) } update(id: ObjectIdDTO, updateProjectDto: UpdateProjectDto): Promise<Project> { return this.projectModel.findByIdAndUpdate(id, Object.assign(updateProjectDto, {updatedAt: Date.now()})); } remove(id: ObjectIdDTO): Promise<Project> { this.taskModel.remove({project: id}); return this.projectModel.findByIdAndDelete(id); } } <file_sep>import { Controller, Get, Post, Body, Put, Param, Delete, UsePipes, ValidationPipe, UseGuards, Req, NotFoundException, HttpStatus, Query, Res } from '@nestjs/common'; import {ApiCreatedResponse, ApiNotFoundResponse, ApiOperation} from "@nestjs/swagger"; import {ProjectService} from './project.service'; import {CreateProjectDto} from './dto/create-project.dto'; import {UpdateProjectDto} from './dto/update-project.dto'; import JwtAuthenticationGuard from "../auth/guards/jwt-authentification.guard"; import {ProjectFilterDto} from "./dto/filter-project.dto"; import {FiltersPipe} from "./filters.pipe"; @Controller('projects') @UsePipes(new ValidationPipe()) @UseGuards(JwtAuthenticationGuard) export class ProjectController { constructor(private readonly projectService: ProjectService) { } @Post() create(@Body() createProjectDto: CreateProjectDto, @Req() req) { return this.projectService.create(createProjectDto, req.user); } @Get() @ApiCreatedResponse({ description: 'OK'}) @ApiOperation({ operationId: 'getProjectList', description: 'get project list' }) findAll(@Query(new FiltersPipe()) query: ProjectFilterDto) { return this.projectService.findAll(query); } @Get(':id') @ApiCreatedResponse({ description: 'OK'}) @ApiNotFoundResponse({ type: NotFoundException, description: 'Project does not exist!' }) @ApiOperation({ operationId: 'getProject', description: 'get project info by id' }) async findOne(@Param('id') id) { const project = await this.projectService.findOne(id); if (!project) { throw new NotFoundException('Project does not exist!'); } return project; } @Get(':id/tasks') @ApiCreatedResponse({ description: 'OK'}) @ApiOperation({ operationId: 'getTasksByProject', description: 'get tasks list by project id' }) async findTasks(@Param('id') id, @Res() res) { res.redirect(`/tasks?project=${id}`); } @Put(':id') @ApiCreatedResponse({ description: 'OK'}) @ApiNotFoundResponse({ type: NotFoundException, description: 'Project does not exist!' }) @ApiOperation({ operationId: 'editProject', description: 'edit project info' }) async update(@Param('id') id, @Body() updateProjectDto: UpdateProjectDto) { const project = await this.projectService.update(id, updateProjectDto); if (!project) { throw new NotFoundException('Project does not exist!'); } return project; } @Delete(':id') @ApiCreatedResponse({ description: 'OK'}) @ApiNotFoundResponse({ type: NotFoundException, description: 'Project does not exist!' }) @ApiOperation({ operationId: 'deleteProject', description: 'delete Project' }) async remove(@Param('id') id) { const project = await this.projectService.remove(id); if (!project) { throw new NotFoundException('Project does not exist!'); } return project; } } <file_sep>import {Module} from '@nestjs/common'; import {MongooseModule} from "@nestjs/mongoose"; import {TaskService} from './task.service'; import {TaskController} from './task.controller'; import {TaskSchema } from './schemas/task.schema'; import {AuthModule} from "../auth/auth.module"; import {EventsGateway} from "../events/events.gateway"; import {ProjectSchema} from "../project/schemas/project.schema"; @Module({ imports: [MongooseModule.forFeature([ {name: 'Project', schema: ProjectSchema}, {name: 'Task', schema:TaskSchema}]), AuthModule], providers: [TaskService, EventsGateway], controllers: [TaskController] }) export class TaskModule { } <file_sep>import {IsString, IsNotEmpty, IsEnum, IsOptional, IsMongoId} from "class-validator"; import {ApiProperty} from '@nestjs/swagger'; import {statusEnum} from "../../enums/status.enum"; export class CreateTaskDTO { @ApiProperty({ description: 'The title of the task', }) @IsString() @IsNotEmpty() readonly title: string; @ApiProperty({ description: 'Full description of the task' }) @IsString() @IsNotEmpty() readonly description: string; @ApiProperty({ description: 'Reference to parent project' }) @IsString() @IsNotEmpty() @IsMongoId() readonly project: string; @ApiProperty({ description: 'Status value', enum: statusEnum, default: statusEnum.new }) @IsString() @IsOptional() @IsEnum(statusEnum) readonly status: statusEnum; @ApiProperty({ description: 'Another task data', }) @IsString() readonly comment: string; }<file_sep>import {Injectable} from '@nestjs/common'; import {Model} from 'mongoose'; import {InjectModel} from "@nestjs/mongoose"; import {User} from "./interfaces/user.interface"; import {CreateUserDto} from "./dto/create-user.dto"; import * as bcrypt from 'bcrypt'; import {AuthCredentialsDto} from "../auth/dto/auth-credentials.dto"; import {UpdateUserDto} from "./dto/update-user.dto"; import {ObjectIdDTO} from "./dto/object-id.dto"; @Injectable() export class UserService { constructor(@InjectModel('User') private readonly userModel: Model<User>) { } async createUser(createUserDto: CreateUserDto): Promise<User> { const hash = await this.hashPassword(createUserDto.password); const createdUser = new this.userModel(Object.assign({}, createUserDto, { password: hash, roles: "user" })); return createdUser.save(); } async getUserByEmail(email: string): Promise<User> { return this.userModel.findOne({email}).exec(); } getUserById(id: ObjectIdDTO): Promise<User> { return this.userModel.findById(id).exec(); } updateUser(id: ObjectIdDTO, updateUserDto: UpdateUserDto): Promise<User>{ return this.userModel.findByIdAndUpdate(id, updateUserDto, {new: true}).exec(); } async validateUser(authCredentialDto: AuthCredentialsDto): Promise<User> { const {email, password} = authCredentialDto; const user = await this.getUserByEmail(email); if (user && (await bcrypt.compare(password, user.password))) { return user } else { return null } } getAllUsers(): Promise<User[]> { return this.userModel.find().exec(); } async hashPassword(password: string): Promise<string> { const saltRounds = 10; const salt = await bcrypt.genSalt(saltRounds); return await bcrypt.hash(password, salt); } } <file_sep>import { ExtractJwt, Strategy } from 'passport-jwt'; import * as _ from 'lodash'; import { PassportStrategy } from '@nestjs/passport'; import {Injectable, UnauthorizedException} from '@nestjs/common'; import {UserService} from "../user/user.service"; import {ConfigService} from "@nestjs/config"; import {User} from "../user/interfaces/user.interface"; import {ObjectIdDTO} from "../user/dto/object-id.dto"; import {Payload} from "./interfaces/payload.interface"; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private configService: ConfigService, private userService: UserService, ) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: configService.get<string>('JWT_SECRET') }); } async validate(payload: Payload): Promise<User>{ let user = await this.userService.getUserById(payload.id); if(!user){ throw new UnauthorizedException(); } return _.omit(user,['password']); } }<file_sep>export enum statusEnum { new = 'New', inWork = 'In Work', done = 'Done' }<file_sep>import { Module } from '@nestjs/common'; import { EventsGateway } from './events.gateway'; import {AuthModule} from "../auth/auth.module"; import {AuthService} from "../auth/auth.service"; @Module({ imports:[AuthModule], providers: [EventsGateway, AuthService], }) export class EventsModule {}<file_sep>import {ConfigModule} from "@nestjs/config"; export const configModule = ConfigModule.forRoot({ isGlobal: true });<file_sep>import { HttpException, HttpStatus, Injectable, InternalServerErrorException, } from '@nestjs/common'; import {JwtService} from "@nestjs/jwt"; import {UserService} from "../user/user.service"; import {CreateUserDto} from "../user/dto/create-user.dto"; import {AuthCredentialsDto} from "./dto/auth-credentials.dto"; @Injectable() export class AuthService { constructor( private userService: UserService, private jwtService: JwtService ) { } async login(authCredentialsDto: AuthCredentialsDto): Promise<{ accessToken: string }> { const user = await this.userService.validateUser(authCredentialsDto); if (user) { return { accessToken: this.jwtService.sign({ id: user._id, roles: user.roles, email: user.email }), }; } else { throw new HttpException('Wrong credentials provided', HttpStatus.BAD_REQUEST); } } async signUp(createUserDto: CreateUserDto) { try { await this.userService.createUser(createUserDto); } catch (e) { if (e.code === 11000) { throw new HttpException('User already exists.', HttpStatus.BAD_REQUEST) } else { throw new InternalServerErrorException(); } } } async validate(token: string): Promise<any> { try { const client = await this.jwtService.verifyAsync(token); return client; } catch (e) { return null; } } } <file_sep>import {Module} from '@nestjs/common'; import {MongooseModule} from '@nestjs/mongoose'; import {TaskModule} from './task/task.module'; import {AuthModule} from './auth/auth.module'; import {UserModule} from "./user/user.module"; import {configModule} from "./configure.root"; import { ProjectModule } from './project/project.module'; @Module({ imports: [ TaskModule,configModule, MongooseModule.forRoot(process.env.MONGODB_CONNECTION_STRING, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }), UserModule, AuthModule, ProjectModule ], controllers: [], providers: [], }) export class AppModule { } <file_sep>import {IsDateString, IsEnum, IsMongoId, IsNotEmpty, IsOptional, IsString} from "class-validator"; import {statusEnum} from "../../enums/status.enum"; export class UpdateProjectDto { @IsString() @IsNotEmpty() title?: string; @IsMongoId() responsible?: string; @IsString() @IsNotEmpty() description?: string; @IsString() @IsOptional() @IsEnum(statusEnum) status?: statusEnum; @IsString() @IsNotEmpty() comment?: string; @IsDateString() dueDate?: Date } <file_sep>import {Module} from '@nestjs/common'; import {JwtModule} from "@nestjs/jwt"; import {PassportModule} from "@nestjs/passport"; import {AuthService} from "./auth.service"; import {AuthController} from './auth.controller'; import {UserModule} from "../user/user.module"; import {JwtStrategy} from "./jwt.strategy"; import {configModule} from "../configure.root"; import {RolesGuard} from "./guards/roles.guard"; @Module({ imports: [ UserModule, configModule, JwtModule.register({ secret: process.env.JWT_SECRET, signOptions: { expiresIn: 3600, } } ), PassportModule.register({defaultStrategy: 'jwt'})], controllers: [AuthController], providers: [AuthService, JwtStrategy, RolesGuard], exports: [JwtStrategy, PassportModule, AuthService] }) export class AuthModule { } <file_sep>import {roleEnum} from "../../enums/role.enum"; import {IsNotEmpty} from "class-validator"; export class UpdateUserDto { @IsNotEmpty() roles: roleEnum[]; }<file_sep>import {statusEnum} from "../../enums/status.enum"; import {Task} from "../../task/interfaces/task.interface"; export interface Project extends Document { readonly _id: string; readonly author: string; title: string; responsible: string; description: string; status: statusEnum; comment: string; dueDate: Date; createdAt: Date; updatedAt: Date; }<file_sep>import { Document } from 'mongoose'; export interface Task extends Document { readonly author: string; readonly title: string; readonly description: string; readonly executor: string; readonly status: string; readonly time: string; readonly comment: string; readonly project: string; }<file_sep>import {statusEnum} from "../../enums/status.enum"; import {ApiModelProperty} from "@nestjs/swagger/dist/decorators/api-model-property.decorator"; import {Max} from "class-validator"; export class TaskFilterDto { @ApiModelProperty({ description: "Author Mongodb Id", required: false, }) author?: string; @ApiModelProperty({ description: "Executor Mongodb Id", required: false, }) executor?: string; @ApiModelProperty({ description: "Title for search", required: false, }) title?: string; description?: string; @ApiModelProperty({ description: "Project Mongodb Id", required: false, }) project?: string; @ApiModelProperty({ description: "Status value", required: false, enum: [statusEnum] }) status?: statusEnum; @ApiModelProperty({ description: "Current page value", required: false, default: 1 }) page?: number ; @ApiModelProperty({ description: "Amount of tasks per page", required: false, default: 100, maximum: 100 }) pageSize?: number; }<file_sep>import {roleEnum} from "../../enums/role.enum"; export interface AuthUser { readonly _id: string; readonly email: string; readonly roles: roleEnum[]; }<file_sep>import * as mongoose from 'mongoose'; import {roleEnum} from "../../enums/role.enum"; export const UserSchema = new mongoose.Schema({ email: { type: String, required: true }, password: { type: String, required: true }, roles: { type: [String], required: true, enum: Object.values(roleEnum) } }) UserSchema.index({email: 1}, {unique: true})<file_sep>import { Body, Controller, Get, NotFoundException, Param, Put, UseGuards, UsePipes, ValidationPipe } from '@nestjs/common'; import {UserService} from "./user.service"; import JwtAuthenticationGuard from "../auth/guards/jwt-authentification.guard"; import {RolesGuard} from "../auth/guards/roles.guard"; import {Roles} from "../auth/decorators/roles.decorator"; import {UpdateUserDto} from "./dto/update-user.dto"; import {ObjectIdDTO} from "./dto/object-id.dto"; import {roleEnum} from "../enums/role.enum"; @Controller('users') @UseGuards(JwtAuthenticationGuard, RolesGuard) @UsePipes(new ValidationPipe()) export class UserController { constructor(private userService: UserService) { } @Get('/') @Roles(roleEnum.admin) async getUsers() { return this.userService.getAllUsers(); } @Get('/:userId') @Roles(roleEnum.admin) async getUser(@Param('userId') userID) { const user = this.userService.getUserById(userID); if (!user) { throw new NotFoundException('User does not exist!'); } return user } @Put('/:userId') @Roles(roleEnum.admin) async updateUser(@Param('userId') userID, @Body() updateUserDto: UpdateUserDto) { const user = this.userService.updateUser(userID, updateUserDto); if (!user) { throw new NotFoundException('User does not exist!'); } return user } }
a4986c1dcc3c0c45e7ebae7a898ef1daad4be9bf
[ "TypeScript" ]
36
TypeScript
Nataly2315/testNest
929ce85fbf36410c847e30fb4b370b062ab925da
1bc58661ab1a1f7d162ea080a7fc8a4944f54d21
refs/heads/main
<file_sep>"use strict"; class ShowArray { constructor(array) { this.array = array; } [Symbol.iterator]() { let nextIndex = 0; let array = this.array; return { next() { return nextIndex < array.length ? { value: array[nextIndex++], done: false } : { done: true }; }, }; } } const array1 = []; for (let i = 0; i < 10; i++) { array1.push(+(Math.random() * 100).toFixed(0)); } const class1 = new ShowArray(array1); for (let num of class1) { console.log(num); // 1, затем 2, 3, 4, 5 } class User { static #counter = 0; constructor(name, surname) { this._name = name; this._surname = surname; User.#counter++; } set name(value) { if (typeof value !== "string") { throw new TypeError("Input string value"); } this._name = value; } set surname(value) { if (typeof value !== "string") { throw new TypeError("Input string value"); } this._surname = value; } get name() { return this._name; } get surname() { return this._surname; } getFullname() { console.log(this._name + " " + this._surname); } } class Stud extends User { static #counter = 0; constructor(name, surname, year) { super(name, surname); this._year = year; Stud.#counter++; } set year(value) { if (typeof value !== "number") { throw new TypeError("Input number value"); } this._year = value; } get year() { return this._year; } getFullname() { super.getFullname(); } getCourse() { console.log(`Course = ${new Date().getFullYear() - this.year}`); } getQuantity() { console.log(`Quantity of students = ${Stud.#counter}`); } } const stud1 = new Stud("Pete", "Tong", 2017); stud1.getFullname(); stud1.getCourse(); stud1.getQuantity(); const array2 = [0, 568, 56, 5, 8, 59]; function findAfter(array) { let indexOf0 = array.indexOf(0); let array2 = []; for (let i = indexOf0 + 1; i < array.length; i++) { array2.push(array[i]); } return array2; } console.log(findAfter(array2)); const array3 = [7, 7, 7, 1, 7, 7, 7, 7, 7, 7]; let [, , , num1] = array3; console.log(num1); const array4 = [1, 2, 3, [4, 5, [6, 7, 8, 9], 10, 11, 12], 13, 14, 15]; let [, , , [, num2, [, , num3]]] = array4; console.log(num2 + " " + num3); let [, , , [, , [...arr_]]] = array4; console.log(arr_); let [, , , [...res1], ...res2] = array4; console.log(res1+","+res2); <file_sep>"use strict"; const userCard = document.createElement("div"); userCard.classList.add("userCard"); const userImageElem = document.createElement("img"); userImageElem.setAttribute( "src", "https://i.pinimg.com/originals/3d/b7/7d/3db77df2a496f33b09c1861acc7a7b1c.jpg" ); userImageElem.setAttribute("alt", "user photo"); const userPhoto = document.createElement("div"); userPhoto.classList.add("userPhoto"); userPhoto.append(userImageElem); userCard.append(userPhoto); const userStat = document.createElement("div"); userStat.classList.add("userStat"); const userStatValue = document.createElement("div"); userStatValue.classList.add("userStatValue"); const p1 = document.createElement("p"); p1.innerText = "183"; const p2 = document.createElement("p"); p2.innerText = "92778"; const p3 = document.createElement("p"); p3.innerText = "30"; userStatValue.append(p1); userStatValue.append(p2); userStatValue.append(p3); userStat.append(userStatValue); const userStatName = document.createElement("div"); userStatName.classList.add("userStatName"); const p4 = document.createElement("p"); p4.innerText = "shots"; const p5 = document.createElement("p"); p5.innerText = "followers"; const p6 = document.createElement("p"); p6.innerText = "projects"; userStatName.append(p4); userStatName.append(p5); userStatName.append(p6); userStat.append(userStatName); userCard.append(userStat); const userButton = document.createElement("div"); userButton.classList.add("userButton"); const p7 = document.createElement("p"); p7.innerText = "Follow"; userButton.append(p7); userCard.append(userButton); document.body.append(userCard); /* <div class="userCard"> <div class="userPhoto"> <img src="https://i.pinimg.com/originals/3d/b7/7d/3db77df2a496f33b09c1861acc7a7b1c.jpg" alt="user photo"> </div> <div class="userStat"> <div class="userStatValue"> <p>183</p> <p>92778</p> <p>30</p> </div> <div class="userStatName"> <p>shots</p> <p>followers</p> <p>projects</p> </div> </div> <div class="userButton"> <p>Follow</p> </div> </div> */ <file_sep>"use strict"; let elemParag = document.getElementsByTagName("p"); for (let item of elemParag) { document.write("text paragraph's =" + item.innerHTML + "<br/>"); } let elemImage = document.getElementsByTagName("img"); elemImage[0].src = "https://ichef.bbci.co.uk/news/640/cpsprodpb/14236/production/_104368428_gettyimages-543560762.jpg"; <file_sep>"use strict"; let links = document.querySelectorAll("a"); for (let item of links) { let hrefL = item.getAttribute("href"); if (hrefL.includes("http://")) { item.style.color = "red"; } } let UL = document.createElement("ul"); let LI1 = document.createElement("li"); let LI2 = document.createElement("li"); let LI3 = document.createElement("li"); UL.append(LI1); UL.append(LI2); UL.append(LI3); document.body.appendChild(UL); let divElem = document.getElementById("id1"); divElem.setAttribute("newAttr", 100); divElem.removeAttribute("newAttr");
1a5217b3968a4014d5e457af88d965fd85b27325
[ "JavaScript" ]
4
JavaScript
buseloff/javascript_6
8a90b91d6f678d1fbe91278c2341ab0141d014be
45f2f30f09e5ada37719bf0ce1222d88cb9c5ff7
refs/heads/master
<repo_name>vinicius-matt/jubilant-guacamole<file_sep>/pc_list_ex8.php <?php function inciaisdias ($numero) { if ($numero==1 or $numero==8 or $numero==15 or $numero==22 or $numero==29) {echo "DOM";} if ($numero==2 or $numero==9 or $numero==16 or $numero==23 or $numero==30) {echo "SEG";} if ($numero==3 or $numero==10 or $numero==17 or $numero==24 or $numero==31) {echo "TER";} if ($numero==4 or $numero==11 or $numero==18 or $numero==25) {echo "QUA";} if ($numero==5 or $numero==12 or $numero==19 or $numero==26) {echo "QUI";} if ($numero==6 or $numero==13 or $numero==20 or $numero==27) { if ($numero==13) {echo "Sexta-feira e 13 mesmo, BIRL!\n";} echo "SEX";} if ($numero==7 or $numero==14 or $numero==21 or $numero==28) {echo "SAB";} if ($numero<1 or $numero>31) {echo "Esse não é um dia válido";} } echo "Digite o número do dia, Entendendo que o mês começa no domingo: "; $numero= (int) fgets(STDIN); inciaisdias ($numero);<file_sep>/pc_list_ex7.php <?php function meses ($numeromes) { if ($numeromes==1) {echo "O mês de número $numeromes é: Janeiro";} if ($numeromes==2) {echo "O mês de número $numeromes é: Fevereiro";} if ($numeromes==3) {echo "O mês de número $numeromes é: Março";} if ($numeromes==4) {echo "O mês de número $numeromes é: Abril";} if ($numeromes==5) {echo "O mês de número $numeromes é: Maio";} if ($numeromes==6) {echo "O mês de número $numeromes é: Junho";} if ($numeromes==7) {echo "O mês de número $numeromes é: Julho";} if ($numeromes==8) {echo "O mês de número $numeromes é: Agosto";} if ($numeromes==9) {echo "O mês de número $numeromes é: Setembro";} if ($numeromes==10) {echo "O mês de número $numeromes é: Outubro";} if ($numeromes==11) {echo "O mês de número $numeromes é: Novembro";} if ($numeromes==12) {echo "O mês de número $numeromes é: Dezembro";} if ($numeromes<1 or $numeromes>12) {echo "Então,\nsinto em lhe informar mas, um ano tem só 12(doze) meses, e não $numeromes meses";} } echo "Digite o número do mês: "; $numeromes= (int) fgets(STDIN); meses ($numeromes);<file_sep>/pc_list_ex3.php <?php function aprovadooureprovado ($nota1, $nota2) {$media= ($nota1+$nota2)/2; if ($media<6) {echo "Infelizmente não deu meu Consagrado, você foi Reprovado, com $media de média";} else {echo "PARABÉNS MEU CONSAGRADO! Você foi aprovado! Com $media de média";}} echo "Digite a nota 1: "; $nota1= (float) fgets(STDIN); echo "Digite a nota 2: "; $nota2= (float) fgets(STDIN); echo aprovadooureprovado($nota1,$nota2); <file_sep>/pc_list_ex5.php <?php function triangularporai ($lado1, $lado2, $lado3) {$perimetrotriang= $lado1+$lado2+$lado3; echo "TRIÂNGULO\n"; echo "Perímetro do triângulo: $perimetrotriang cm";} function quadrangularporai ($lado1, $lado2) {$areaquadrado= $lado1*$lado2; echo "QUADRADO\n"; echo "Área do quadrado: $areaquadrado cm";} function pentagonarporai () {echo "PENTÁGONO";} echo "Digite o número de lados da figura geométrica, de 3 até 5: "; $qtdlados= (int) fgets(STDIN); if ($qtdlados==3) {echo "Digite o lado 1: "; $lado1= (float) fgets(STDIN); echo "Digite o lado 2: "; $lado2= (float) fgets(STDIN); echo "Digite o lado 3: "; $lado3= (float) fgets(STDIN); triangularporai ($lado1, $lado2, $lado3); } if ($qtdlados==4) {echo "Digite o lado 1: "; $lado1= (float) fgets(STDIN); echo "Digite o lado 2: "; $lado2= (float) fgets(STDIN); quadrangularporai ($lado1, $lado2); } if ($qtdlados==5) {pentagonarporai ();}<file_sep>/README.md # Repositório para a lista de funções - [x] Exercício 1 - [x] Exercício 2 - [x] Exercício 3 - [x] Exercício 4 - [x] Exercício 5 - [x] Exercício 6 - [x] Exercício 7 - [x] Exercício 7 - deluxe edition - [x] Exercício 8 - [x] Exercício 9 - [x] Exercício 10 - [x] Exercício 10 - array version - [x] Exercício 11 <file_sep>/pc_list_ex4.php <?php function pesoideal ($sexo, $altura) {if ($sexo==1) {$pesoideal= (62.1*$altura)-44.7; echo "O seu peso na gravidade atual terrestre é de: $pesoideal"." Kgs";} elseif ($sexo==2) {$pesoideal= (72.7*$altura)-58; echo "O seu peso na gravidade atual terrestre é de: $pesoideal"." Kgs";}} echo "Digite 1-feminino e 2-masculino: "; $sexo= (int) fgets(STDIN); if ($sexo!=1 and $sexo!=2) {echo "Você sabe qual a diferencia entre Sexo e Gênero? \n\n"; echo "Enquanto sexo se refere às categorias inatas do ponto de vista biológico, ou seja, algo relacionado com feminino e masculino; o gênero diz respeito aos papeis sociais relacionados com a mulher e o homem (Moser, 1989).\nToda sociedade é marcada por diferenças de gênero, havendo, ainda, grande variação dos papeis associados em função da cultura e do tempo em que se vive. Ressalte-se, contudo, que a determinação social de gênero pode ser alterada por uma ação consciente tomada – inclusive por meio de políticas públicas.\nEm suma, enquanto sexo é uma categoria biológica, gênero é uma distinção sociológica.\nSexo é, em regra, fixo; já o papel de gênero muda no espaço e no tempo (principalmente com a tomada de consciência de distinções que são construídas socialmente, e que podem e devem ser em inúmeros casos ‘desconstruídas’, para que haja igualdade do ponto de vista social.\n"; exit;} echo "Digite a sua altura em cm: "; $altura= (int) fgets(STDIN); $altura= $altura/100; echo pesoideal($sexo,$altura); <file_sep>/pc_list_ex12.php <?php function polegaresparacentimetros ($pol) {$cm= $pol*2.54; return $cm;} echo "Digite as polegadas para a conversão: "; $pol= (float) fgets(STDIN); $cm= polegaresparacentimetros ($pol); if ($pol==0) {echo "Obviamente que, 0 polegadas são 0 centímetros";} if ($pol==1 or $pol==-1) {echo "$pol polegada equivale a $cm centímetros. "; if($pol==-1) {echo "Isso não faz sentido, como você ou qualquer um pode medir negativamente?\nExemplo: Aquela rua fica a -100 metros daqui";}} if ($pol>1 or $pol<-1) {echo "$pol polegadas equivalem a $cm centímetros. "; if($pol<-1) {echo "Isso não faz sentido, como você ou qualquer um pode medir negativamente?\nExemplo: Aquela rua fica a -100 metros daqui";}}<file_sep>/pc_list_ex6.php <?php function intervalo ($numeroinicial, $numerofinal) { if ($numeroinicial>$numerofinal) { for ($i=$numeroinicial; $i>=$numerofinal; $i--) {$intervalo+= $i;} echo "A soma dos números no intervalo de $numeroinicial, até o $numerofinal, foi de: $intervalo"; } elseif ($numeroinicial<$numerofinal) { for ($i=$numeroinicial; $i<=$numerofinal; $i++) {$intervalo+= $i;} echo "A soma dos números no intervalo de $numeroinicial, até o $numerofinal, foi de: $intervalo"; } elseif ($numeroinicial==$numerofinal) {echo "Os números são iguais";} } echo "Digite o número inicial: "; $numeroinicial= (int) fgets(STDIN); echo "Digite o número final: "; $numerofinal= (int) fgets(STDIN); intervalo ($numeroinicial, $numerofinal);<file_sep>/pc_list_ex11.php <?php function maior ($numero1, $numero2) { $maior[0]=$numero1; $maior[1]=$numero2; rsort($maior); echo "O maior número foi o: $maior[0]"; } echo "Digite o número 1: "; $numero1= (float) fgets(STDIN); echo "Digite o número 2: "; $numero2= (float) fgets(STDIN); maior ($numero1, $numero2);<file_sep>/pc_list_ex2.php <?php function hipotenusa ($catetoa,$catetob) {$hip = sqrt(($catetoa**2)+($catetob**2)); return $hip;} echo "Digite o cateto a: "; $catetoa = (float) fgets(STDIN); echo "Digite o cateto b: "; $catetob = (float) fgets(STDIN); $hipotenusa= hipotenusa($catetoa,$catetob); $hipotenusa= round($hipotenusa, 3); echo "A hipotenusa é: $hipotenusa "; <file_sep>/pc_List_Ex1.php <?php function Celsius ($fahrenheit) {$celsius = ($fahrenheit-32)*(5/9); return $celsius;} echo "Digite a temperatura em Fahrenheit para a conversão: "; $fahrenheit = (float) fgets(STDIN); $celsius= Celsius ($fahrenheit); $celsius= round ($celsius, 3); echo "Temperatura em Celsiu é: $celsius"."°C "; <file_sep>/pc_list_ex10.php <?php function maior ($numero1, $numero2) { if ($numero1>$numero2) {echo "O primeiro número($numero1) é maior que o segundo número($numero2)";} elseif ($numero1==$numero2) {echo "Os dois números tem o mesmo valor(são iguais)";} else {echo "O segundo número($numero2) é maior que o primeiro número($numero1)";} } echo "Digite o número 1: "; $numero1= (float) fgets(STDIN); echo "Digite o número 2: "; $numero2= (float) fgets(STDIN); maior ($numero1, $numero2);<file_sep>/pc_lis_ex9.php <?php function divisivel ($x, $y) { if ($x%$y==0) {echo "1 -\n$x é divisível por $y";} if ($x%$y!=0) {echo "0 -\n$x não é divisível por $y";} } echo "Digite o número 1(x): "; $x= (int) fgets(STDIN); echo "Digite o número 2(y): "; $y= (int) fgets(STDIN); divisivel ($x, $y);
73aa56805dbe1faf257d106d0e14b702acc2fc7b
[ "Markdown", "PHP" ]
13
PHP
vinicius-matt/jubilant-guacamole
cbd20cab8c6814f239c35b6bbebbecf27c16ff5e
7918d6c01dd2187170e48d506e02ace6ba8dab40
refs/heads/main
<file_sep># furry-sniffle A real estate scraper built for the website lamudi.com.mx on Python. <file_sep>import pandas as pd from bs4 import BeautifulSoup from time import sleep from random import randint from scraper_api import ScraperAPIClient import requests def attribute_cleaner(dirty_attribute): clean_attribute = " ".join(dirty_attribute.split()) return clean_attribute client = ScraperAPIClient('# Insert scraper api key here') total_df = pd.DataFrame() # Phase 1: Link extraction links = [] counter = 0 headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} for x in range(1, 54): if x % 3 != 0: main_web = client.get('https://www.lamudi.com.mx/mexico/huixquilucan/casa/for-sale/?page='+str(x)) soup = BeautifulSoup(main_web.text, 'lxml') for i in soup.find_all('a', class_='ListingCell-moreInfo-button-v2_redesign'): if i['href'] not in links: links.append(i['href']) else: continue else: sleep(randint(1, 3)) main_web = requests.get('https://www.lamudi.com.mx/mexico/huixquilucan/casa/for-sale/?page=' + str(x), headers=headers) soup = BeautifulSoup(main_web.text, 'lxml') for i in soup.find_all('a', class_='ListingCell-moreInfo-button-v2_redesign'): if i['href'] not in links: links.append(i['href']) else: continue print('Page ' + str(x) + ' links done.') print("\n\n Link extraction done! Moving to link info extraction...\n\n") # Phase 2: Info extraction for link in links: if counter % 3 == 0: web = requests.get(link, headers=headers) soup = BeautifulSoup(web.text, 'lxml') try: price = int(soup.find('span', class_='Overview-main FirstPrice').get_text().split()[1].replace(",", "")) except: price = 'N/A' try: address = soup.find('span', class_='Header-title-address-text').get_text() address = attribute_cleaner(address) except: address = 'N/A' try: latitude = float(soup.find('div', id='js-developmentMap')['data-lat']) except: latitude = 'N/A' try: longitude = float(soup.find('div', id='js-developmentMap')['data-lng']) except: longitude = 'N/A' try: parking_spaces = soup.find('div', {"data-attr-name": "car_spaces"}).next_sibling.next_sibling.get_text() parking_spaces = int(attribute_cleaner(parking_spaces)) except: parking_spaces = 'N/A' try: bedrooms = soup.find('div', {"data-attr-name": "bedrooms"}).next_sibling.next_sibling.get_text() bedrooms = int(attribute_cleaner(bedrooms)) except: bedrooms = 'N/A' try: bathrooms = soup.find('div', {"data-attr-name": "bathrooms"}).next_sibling.next_sibling.get_text() bathrooms = float(attribute_cleaner(bathrooms)) except: bathrooms = 'N/A' try: building_size = soup.find('div', {"data-attr-name": "building_size"}).next_sibling.next_sibling.get_text() building_size = int(attribute_cleaner(building_size)) except: building_size = 'N/A' try: land_size = soup.find('div', {"data-attr-name": "land_size"}).next_sibling.next_sibling.get_text() land_size = float(attribute_cleaner(land_size)) except: land_size = 'N/A' # Amenities amenities = [] try: for i in soup.find_all('div', class_='columns medium-12 small-12 ViewMore-text-description'): for h in i.find_all('div', class_='ellipsis'): amenities.append(attribute_cleaner(h.get_text())) except: continue counter += 1 else: web = client.get(link) soup = BeautifulSoup(web.text, 'lxml') try: price = int(soup.find('span', class_='Overview-main FirstPrice').get_text().split()[1].replace(",", "")) except: price = 'N/A' try: address = soup.find('span', class_='Header-title-address-text').get_text() address = attribute_cleaner(address) except: address = 'N/A' try: latitude = float(soup.find('div', id='js-developmentMap')['data-lat']) except: latitude = 'N/A' try: longitude = float(soup.find('div', id='js-developmentMap')['data-lng']) except: longitude = 'N/A' try: parking_spaces = soup.find('div', {"data-attr-name": "car_spaces"}).next_sibling.next_sibling.get_text() parking_spaces = int(attribute_cleaner(parking_spaces)) except: parking_spaces = 'N/A' try: bedrooms = soup.find('div', {"data-attr-name": "bedrooms"}).next_sibling.next_sibling.get_text() bedrooms = int(attribute_cleaner(bedrooms)) except: bedrooms = 'N/A' try: bathrooms = soup.find('div', {"data-attr-name": "bathrooms"}).next_sibling.next_sibling.get_text() bathrooms = float(attribute_cleaner(bathrooms)) except: bathrooms = 'N/A' try: building_size = soup.find('div', {"data-attr-name": "building_size"}).next_sibling.next_sibling.get_text() building_size = int(attribute_cleaner(building_size)) except: building_size = 'N/A' try: land_size = soup.find('div', {"data-attr-name": "land_size"}).next_sibling.next_sibling.get_text() land_size = float(attribute_cleaner(land_size)) except: land_size = 'N/A' # Amenities amenities = [] try: for i in soup.find_all('div', class_='columns medium-12 small-12 ViewMore-text-description'): for h in i.find_all('div', class_='ellipsis'): amenities.append(attribute_cleaner(h.get_text())) except: continue counter += 1 data = {"Address": address, "Latitude": latitude, "Longitude": longitude, "Price": price, "Parking_Spaces": parking_spaces, "Bedrooms": bedrooms, "Bathrooms": bathrooms, "Building_Size": building_size, "Land_Size": land_size} df = pd.DataFrame(data, index=[0]) for i in amenities: if i not in df.columns: df[str(i)] = 1 else: continue total_df = pd.concat([total_df, df], axis=0, ignore_index=True) print("Link #" + str(counter) + " done!") total_df.to_csv('real_estate_data.csv', index=False)
7eee79c32752b18416941df7d4b483723e977d09
[ "Markdown", "Python" ]
2
Markdown
ricardot66/furry-sniffle
8114a62c574063add82e80be38ee47c94a585b6f
e99310cedccdeceaba6fc9496187792e968bbfc3
refs/heads/master
<file_sep>apply plugin: 'java' apply plugin: 'kotlin' sourceSets { main.java.srcDirs += 'src/main/kotlin' test.java.srcDirs += 'src/test/kotlin' } dependencies { compile project(':app') compile kotlinStdLib testCompile assertJ testCompile jUnit testCompile mockito } <file_sep>package <%= packageName %>.app.usecase import <%= packageName %>.app.usecase.Interactor.Request import <%= packageName %>.app.usecase.Interactor.Response import rx.Observable interface Interactor<I : Request, O : Response> { fun execute(request: I): Observable<O> interface Request interface Response } <file_sep>apply plugin: 'java' apply plugin: 'kotlin' sourceSets { main.java.srcDirs += 'src/main/kotlin' test.java.srcDirs += 'src/test/kotlin' } dependencies { compile project(':core') compile kotlinStdLib testCompile assertJ testCompile jUnit testCompile mockito } <file_sep>package <%= packageName %>.presentation.navigation interface NavigationFactory { // Destination interfaces // interface MainScreen // Factory fuctions // fun main(): MainScreen } <file_sep>buildscript { ext.kotlinVersion = '1.0.3' repositories { jcenter() maven { url "https://oss.sonatype.org/content/repositories/snapshots" } } dependencies { classpath 'com.android.tools.build:gradle:1.5.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" } } allprojects { repositories { jcenter() maven { url "https://oss.sonatype.org/content/repositories/snapshots" } maven { url 'https://jitpack.io' } } } ext { ////////////////////////////////////////////////// // VERSIONS // Android androidBuildToolsVersion = '23.0.3' androidCompileSdkVersion = 23 androidMinSdkVersion = 19 androidTargetSdkVersion = 23 // Desktop // Libraries androidSupportVersion = '23.2.1' daggerVersion = '2.0.2' flowVersion = '1.0.0-alpha' javaxAnnotationVersion = '10.0-b28' javaxInjectVersion = '1' kotlinVersion = '1.0.1' kotterKnifeVersion = '0.1.0-SNAPSHOT' mortarVersion = '0.20' okHttpVersion = '3.2.0' paperParcelVersion = '1.0.0-beta8' phraseVersion = '1.1.0' retrofitVersion = '2.0.0' rxAndroidVersion = '1.1.0' rxBindingVersion = '0.4.0' rxJavaVersion = '1.1.1' // Testing assertJVersion = '1.7.1' jUnitVersion = '4.12' mockitoVersion = '1.10.5' ////////////////////////////////////////////////// // DEPENDENCIES // Android androidSupport = "com.android.support:support-v4:$androidSupportVersion" androidSupportAnnotations = "com.android.support:support-annotations:$androidSupportVersion" androidSupportAppCompat = "com.android.support:appcompat-v7:$androidSupportVersion" androidSupportDesign = "com.android.support:design:$androidSupportVersion" androidSupportRecyclerView = "com.android.support:recyclerview-v7:$androidSupportVersion" // Desktop // Third-party dagger = "com.google.dagger:dagger:$daggerVersion" daggerCompiler = "com.google.dagger:dagger-compiler:$daggerVersion" flow = "com.squareup.flow:flow:$flowVersion" javaxAnnotation = "org.glassfish:javax.annotation:$javaxAnnotationVersion" javaxInject = "javax.inject:javax.inject:$javaxInjectVersion" kotlinStdLib = "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" kotterKnife = "com.jakewharton:kotterknife:$kotterKnifeVersion" mortar = "com.squareup.mortar:mortar:$mortarVersion" okHttpLoggingInterceptor = "com.squareup.okhttp3:logging-interceptor:$okHttpVersion" paperParcel = "com.github.grandstaish.paperparcel:paperparcel-kotlin:$paperParcelVersion" paperParcelCompiler = "com.github.grandstaish.paperparcel:compiler:$paperParcelVersion" phrase = "com.squareup.phrase:phrase:$phraseVersion" retrofit = "com.squareup.retrofit2:retrofit:$retrofitVersion" retrofitAdapterRxJava = "com.squareup.retrofit2:adapter-rxjava:$retrofitVersion" retrofitConverterMoshi = "com.squareup.retrofit2:converter-moshi:$retrofitVersion" rxAndroid = "io.reactivex:rxandroid:$rxAndroidVersion" rxBinding = "com.jakewharton.rxbinding:rxbinding-kotlin:$rxBindingVersion" rxBindingDesign = "com.jakewharton.rxbinding:rxbinding-design-kotlin:$rxBindingVersion" rxBindingSupportV4 = "com.jakewharton.rxbinding:rxbinding-support-v4-kotlin:$rxBindingVersion" rxBindingAppCompatV7 = "com.jakewharton.rxbinding:rxbinding-appcompat-v7-kotlin:$rxBindingVersion" rxJava = "io.reactivex:rxjava:$rxJavaVersion" reduxKotlin = "com.github.pardom:redux-kotlin:-SNAPSHOT" reduxLoggerKotlin = "com.github.pardom:redux-logger-kotlin:-SNAPSHOT" reduxObservableKotlin = "com.github.pardom:redux-observable-kotlin:-SNAPSHOT" // Testing assertJ = "org.assertj:assertj-core:$assertJVersion" jUnit = "junit:junit:$jUnitVersion" mockito = "org.mockito:mockito-core:$mockitoVersion" } <file_sep># slush-clean-kotlin Kotlin Clean Architecture scaffolding <file_sep>package <%= packageName %>.presentation.navigation interface NavigationService { fun goBack(): Boolean fun goTo(newTop: Any) fun replaceTo(newTop: Any) fun resetTo(newTop: Any) }
d1199aa1ed08de731cc4775419381c899ed35b9e
[ "Markdown", "Kotlin", "Gradle" ]
7
Gradle
pardom-zz/slush-clean-kotlin
8082d0ddf6f5cf95d5a4c2549416bcc5c4c97d10
6d2be3471820000b4ba4cefc7be2350d864c8f26
refs/heads/master
<repo_name>chegez/MY-WORK<file_sep>/areacircle.php <?php //Area of a circle is pi*r*r //Area is a function area_circle($pi, $r, $r){ $a=" $pi*$r*$r "; return $a; } $pi="3.142"; $r="14cm"; echo "Area of the circle is=" . 3.142*$r*$r . " "; <file_sep>/additem.php <?php if(isset($_POST['submit'])){ $item=$_POST['item']; $cost=$_POST['cost']; } setcookie('item' , $item, time()+3600); echo $_COOKIE['item']; if($item=="shoe" || "hh" &&$cost=="6000" || "hh"){ echo"{$item}was successfully bought"; }else{ $message="errors."; } ?> <!DOCTYPEhtml PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title>Form</title> </head> <body> <?php echo $message ;?><br /> <form action="shopping.php"method="post"> Item: <input type="item"name="item"value="<?php echo htmlspecialchars($item); ?>"/><br /> Cost: <input type="cost"name="cost"value=""/><br /> <br/> <input type="submit"name="submit"value="Submit"/> </form> </body> </html> <file_sep>/hellow.php <?$php function sum_over($val1,$val2){ return $val1 + val2; } $val1=5; $val2=10; echo $va1+$val2; <file_sep>/inline.php <?php function chinese_zodiac($year){ switch ($year-4)%12) { case 0:return 'Rat'; case 1:return 'Ox'; case 2;return 'Tiger'; case 3;return 'Rabbit'; case 4;return 'Draggon'; case 5;return 'Snake'; case 6;return 'Horse'; case 7;return 'Goat'; case 8;return 'Monkey'; case 9;return 'Rooster'; case 10;return 'Dog'; case 11;return 'Pig'; echo "2015 is the year of " chinese_zodiac(2015); <file_sep>/areatriangle.php <?php //Calculating the area of a triangle as 1/2bh //Half is hl function area_triangle($hl, $b, $h){ return $hl * $b * $h; } $hl="0.5"; $b="12cm"; $h="10cm"; echo "Area of a triangle is =" . 0.5*$b*$h. " "; <file_sep>/connectit.php <?php // 1.Set the connection variables $dbhost = "localhost"; $dbuser = "test_app_name"; $dbpass = "<PASSWORD>"; $dbname = "test_app"; //connect to mysql server $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); //check if any connection error was encountered if(mysqli_connect_errno()) { echo "Error: Could not connect to database."; exit; } // 2. Perform database query $query = "SELECT * FROM subjects "; $result = mysqli_query($connection, $query); // Test if there was a query error if (!$result) { die("Database query failed."); } //var_dump($result);die(); // Use returned data (if any) while($row = mysqli_fetch_row($result)) { // output data from each row var_dump($row); } // Release returned data mysqli_free_result($result); // 3. Values in $_POST, subjects are id,name and age. $id = 1; $name = "Bobby"; $age = "25yrs"; // Perform database query $query = "INSERT INTO subjects ("; $query .= " id, name, age"; $query .= ") VALUES ("; $query .= " '{$id}', {$name}, {$age}"; $query .= ")"; $result = mysqli_query($connection, $query); //Find out the id,name and age of the record $id=mysqli_insert_id($connection); $name=mysqli_insert_name($connection); $age=mysqli_insert_age($connection); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <title>Databases</title> </head> <body> <ul> <?php // Use returned data (if any) while($subject = mysql_fetch_assoc($result)) { //output data from each column ?> <?php echo $subject["id", "name", "age"] . ")" .$subject["id", "name", "age"] ; <?php } ?> <?php // Release returned data mysqli_free_result($result); ?> </body> </html> <?php // 4. Delete connection id $id = 1; // Perform database query $query = "DELETE FROM subjects "; $query .= "WHERE id {$id} "; $query .= "LIMIT 1"; $result = mysqli_query($connection, $query); // Prepare the sql statement if ($result && mysqli_affected_columns($connection) == 1) { } else { die("Unable to delete."); } // 5. Close database connection mysqli_close($connection); ?> <file_sep>/areacircumferencecircle.php <?php //Form method is POST //Calculating area and cicumference of a circle function area_circle($pi, $rad){ return $pi* $rad* $rad; } $pi="3.142"; $rad="7cm"; echo "The circumference of the circle is=" . (3.142* $rad*2). "<br> "; echo "THe area of the circle is=" . (3.142*$rad*$rad). "<br> "; <file_sep>/dumpofitems.php <?php $shoppinglist=$items; //items and values be echoed plus total $items=$items("charger"=>"550", "shoes"=>"2500", "decorder"=>"4000", "socks"=>"1000", "bulb"=>"350"); $items=$items[$shoppinglist]; echo "Shoppinglist $shoppinglist will be $items";
800d01afe65f9824db7cc475786852ecfcddc488
[ "PHP" ]
8
PHP
chegez/MY-WORK
be099194be07cd31a460f07c89c3422460ef14f5
815cf8028734adddb7232cad22f24aa78dec9e0e
refs/heads/master
<file_sep>// // ViewController.swift // GeoCache // // Created by <NAME> on 10/31/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { var cacheCount = 0 var cacheArray = [GeoCache]() override func viewDidLoad() { super.viewDidLoad() cacheArray = loadCachesFromDefaults() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Properties @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailsLabel: UILabel! @IBOutlet weak var creatorLabel: UILabel! @IBOutlet weak var rewardLabel: UILabel! @IBOutlet weak var titleField: UITextField! @IBOutlet weak var detailsField: UITextField! @IBOutlet weak var creatorField: UITextField! @IBOutlet weak var rewardField: UITextField! @IBOutlet weak var addButton: UIButton! @IBOutlet weak var textField: UITextView! @IBOutlet weak var nextButton: UIButton! @IBAction func addGeoCache(_ sender: UIButton) { if ((titleField.text!).isEmpty || (detailsField.text!).isEmpty || (creatorField.text!).isEmpty || (rewardField.text!).isEmpty) { textField.text! = "Error: all of the above fields must be filled in" } else { var dict = [String: String]() dict["title"] = titleField.text! dict["details"] = detailsField.text! dict["creator"] = creatorField.text! dict["reward"] = rewardField.text! let newCache = GeoCache(fromDictionary: dict) cacheArray.append(newCache!) saveCachesToDefaults(cacheArray) } } @IBAction func nextCache(_ sender: UIButton) { // Set text fields to be what is in the next geocache if (cacheCount == cacheArray.count - 1) { cacheCount = 0 } else { cacheCount = cacheCount + 1 } let gc = cacheArray[cacheCount] let dict = gc.dictionary textField!.text = gc.description } } <file_sep>// // GeoCache.swift // // // Created by <NAME> on 10/29/17. // import Foundation struct GeoCache { let title: String let details: String let creator: String let reward: String let id: Int init?(fromDictionary dict: [String: Any]) { guard let title = dict["title"] else { return nil } self.title = title as! String guard let details = dict["details"] else { return nil } self.details = details as! String guard let creator = dict["creator"] else { return nil } self.creator = creator as! String guard let reward = dict["reward"] else { return nil } self.reward = reward as! String guard let id = dict["id"] else { return nil } self.id = id as! Int } var dictionary: [String: Any] { get { var dict = [String: Any]() dict["title"] = self.title dict["details"] = self.creator dict["creator"] = self.creator dict["reward"] = self.reward dict["id"] = self.id return dict } } var description: String { get { return "Title: " + self.title + "\r" + "Details: " + self.details + "\r" + "Creator: " + self.creator + "\r" + "Reward: " + self.reward + "\r" + "ID \(self.id)" } } } func randomCacheId() -> Int { return Int(arc4random()) } func loadCachesFromDefaults() -> [GeoCache] { let defaults = UserDefaults.standard let geocache_arr = defaults.array(forKey: "GeoCacheArray") ?? [Any]() var geocaches = [GeoCache]() for gc in geocache_arr { geocaches.append(GeoCache(fromDictionary: gc as! [String: Any])!) } return geocaches } func saveCachesToDefaults(_ caches: [GeoCache]) { let defaults = UserDefaults.standard var dict_array = [[String: Any]]() for gc in caches { dict_array.append(gc.dictionary) } defaults.set(dict_array, forKey: "GeoCacheArray") defaults.synchronize() } func sendCacheToServer(_ cache: GeoCache) { var request = URLRequest(url: URL(string: "http://localhost:5000/createCache")!) request.httpMethod = "POST" let data = try? JSONSerialization.data(withJSONObject: cache.dictionary) request.httpBody = data request.setValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in if let error = error { print(error.localizedDescription) return } print(response!) print(data!) }) task.resume() } func loadCachesFromServer(onComplete: @escaping ([GeoCache]) -> ()) { var gcArray = [GeoCache]() var request = URLRequest(url: URL(string: "http://localhost:5000/getCaches")!) request.httpMethod = "GET" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let task = URLSession.shared.dataTask(with: request, completionHandler: { data, response, error in if let error = error { print(error.localizedDescription) return } else { do { let cacheArray = try JSONSerialization.jsonObject(with: data!, options: []) as! [[String: Any]] for dict in cacheArray { gcArray.append(GeoCache(fromDictionary: dict)!) onComplete(gcArray) } } catch let error as NSError { print(error) } } }) task.resume() } <file_sep>// // GeoCache.swift // // // Created by <NAME> on 10/29/17. // import Foundation struct GeoCache { let title: String let details: String let creator: String let reward: String init?(fromDictionary dict: [String: String]) { guard let title = dict["title"] else { return nil } self.title = title guard let details = dict["details"] else { return nil } self.details = details guard let creator = dict["creator"] else { return nil } self.creator = creator guard let reward = dict["reward"] else { return nil } self.reward = reward } var dictionary: [String: String] { get { var dict = [String: String]() dict["title"] = self.title dict["details"] = self.creator dict["creator"] = self.creator dict["reward"] = self.reward return dict } } var description: String { get { return "Title: " + self.title + "\r" + "Details: " + self.details + "\r" + "Creator: " + self.creator + "\r" + "Reward: " + self.reward + "\r" } } } func loadCachesFromDefaults() -> [GeoCache] { let defaults = UserDefaults.standard let geocache_arr = defaults.array(forKey: "GeoCacheArray") ?? [Any]() var geocaches = [GeoCache]() for gc in geocache_arr { geocaches.append(GeoCache(fromDictionary: gc as! [String: String])!) } return geocaches } func saveCachesToDefaults(_ caches: [GeoCache]) { let defaults = UserDefaults.standard var dict_array = [[String: String]]() for gc in caches { dict_array.append(gc.dictionary) } defaults.set(dict_array, forKey: "GeoCacheArray") defaults.synchronize() } <file_sep>// // ViewController.swift // CS11 // // Created by <NAME> on 10/21/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Properties @IBOutlet weak var textFieldLeft: UITextField! @IBOutlet weak var label: UILabel! @IBOutlet weak var textFieldRight: UITextField! //MARK: Actions @IBAction func sendLeft(_ sender: UIButton) { let leftText = textFieldLeft.text! let newText = label.text! + leftText.lowercased() label.text = newText } @IBAction func sendRight(_ sender: UIButton) { let rightText = textFieldRight.text! let newText = label.text! + rightText.uppercased() label.text = newText } @IBAction func clearLabel(_ sender: UIButton) { label.text = "" } @IBAction func clearVowels(_ sender: UIButton) { let char_array = Array(label.text!) var output_text = "" for char in char_array { let lower_char = Character(String(char).lowercased()) if !(lower_char == "a" || lower_char == "e" || lower_char == "i" || lower_char == "o" || lower_char == "u") { output_text += String(char) } } label.text = output_text } } <file_sep>// // ViewController.swift // GeoCache // // Created by <NAME> on 10/31/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit class NewCacheViewController: UIViewController { var dict = [String: String]() var cache : GeoCache? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Properties @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var detailsLabel: UILabel! @IBOutlet weak var creatorLabel: UILabel! @IBOutlet weak var rewardLabel: UILabel! @IBOutlet weak var titleField: UITextField! @IBOutlet weak var detailsField: UITextField! @IBOutlet weak var creatorField: UITextField! @IBOutlet weak var rewardField: UITextField! @IBAction func cancel(sender: UIBarButtonItem) { if (cache != nil) { cache = nil } dismiss(animated: true, completion: nil) } @IBAction override func prepare(for segue: UIStoryboardSegue, sender: Any?) { print("prepare was reached") var dict = [String: Any]() if let value : String = titleField.text, !value.isEmpty { dict["title"] = titleField.text! } if let value : String = detailsField.text, !value.isEmpty { dict["details"] = detailsField.text! } if let value : String = creatorField.text, !value.isEmpty { dict["creator"] = creatorField.text! } if let value : String = rewardField.text, !value.isEmpty { dict["reward"] = rewardField.text! } dict["id"] = randomCacheId() if let tempcache : GeoCache = GeoCache(fromDictionary: dict) { cache = tempcache } else { print("could not create cache") } } }
42b8ffc3318328b0217c7c18e05cbd4d7c175404
[ "Swift" ]
5
Swift
preethiperi/cs11iostrack
8eda7c98bb686c98be6189a2794bec2cc81066a4
76e6e1eddce6a5c053b6c15c3ecd0fa12aa9dbd7
refs/heads/master
<file_sep>/* tslint:disable:no-unused-variable */ const PascalCase = { PascalCase: 1 }; <file_sep>interface Env { [key: string]: string; } let x: Env; x['foo']; <file_sep>console.log('log'); console.info('info'); console.warn('warn'); console.error('error'); console.trace('trace'); <file_sep>/* tslint:disable:no-unused-variable */ function foo() { } <file_sep>// Should not do `declare module`. Write `declare namespace` instead. declare module abc { } <file_sep>const gulp = require('gulp'); const gulpTslint = require('gulp-tslint'); const tslint = require('tslint'); const through = require('through'); const gutil = require('gulp-util'); const PluginError = gutil.PluginError; gulp.task('tslint-positive', function() { return gulp.src('spec/*.pass.ts') .pipe(gulpTslint({ configuration: './tslint.json', formatter: 'verbose' })) .pipe(gulpTslint.report()); }); gulp.task('tslint-negative', function() { return gulp.src('spec/*.fail.ts') .pipe(gulpTslint({ configuration: `./tslint.json`, formatter: 'verbose' })) .pipe((function() { var hasError = false; return through(function (file) { if (file.tslint.failureCount === 0) { gutil.log( `[${gutil.colors.cyan('gulp-tslint')}]`, gutil.colors.red(`error: ${file.tslint.failureCount}`), `(negative) ${file.relative}`); hasError = true; } }, function () { if (hasError) { this.emit('error', new PluginError('gulp-tslint', 'Failed negative test(s).')); } else { this.emit('end'); } }); })()); }); gulp.task('tslint', ['tslint-positive', 'tslint-negative']); gulp.task('default', ['tslint']); <file_sep> interface isMatch { } <file_sep>function someCbFn(fn) { fn({}); } someCbFn((err) => { someCbFn((err) => { return; }); });
ba2052045cea9e9efe6960deb2c8dfa741faf029
[ "JavaScript", "TypeScript" ]
8
TypeScript
types/_tslint-config-typings
a8d1f858d9e2a0fea869ca35e3d69a7a60ec436b
500e088f5c6578988945031cdada6b6d5e849fff
refs/heads/master
<repo_name>santiihoyos/vue-webpack-typescript<file_sep>/template/src/components/Main/MainComponent.ts import { Component, Vue } from 'vue-property-decorator' import './MainComponent.scss' @Component({ template: require('./MainComponent.html') }) export class MainComponent extends Vue { msg: string = 'This works!' onButtonClick () { alert(this.msg) } } export * from './MainComponent' <file_sep>/template/src/main.ts import Vue from 'vue' import VueRouter from 'vue-router' import { makeHot, reload } from './util/hot-reload' import { createRouter } from './router' import { MainComponent } from './components/Main/MainComponent' import './sass/main.scss' const mainComponent = () => import('./components/Main/MainComponent').then(({ MainComponent }) => MainComponent) if (process.env.ENV === 'development' && module.hot) { const mainModuleId = './components/Main/MainComponent' // first arguments for `module.hot.accept` and `require` methods have to be static strings // see https://github.com/webpack/webpack/issues/5668 makeHot(mainModuleId, mainComponent, module.hot.accept( './components/Main/MainComponent', () => reload(mainModuleId, (require('./components/Main/MainComponent') as any).NavbarComponent)) ) } // tslint:disable-next-line:no-unused-expression new Vue({ el: '#app-main', router: createRouter(), components: { 'main-component': mainComponent } })
045ad1a0e23d247c4207f847188bd52099332490
[ "TypeScript" ]
2
TypeScript
santiihoyos/vue-webpack-typescript
200c2b4bde35e838e4d5049b1bafbdf95fed82cc
c73efc0ef97bda399d5300b1c0f934cadfe73fc7
refs/heads/master
<file_sep>#!/usr/bin/env python3 import pyaudio #import wave import threading from array import array from time import sleep CHUNK = 512 FORMAT = pyaudio.paInt16 #paInt8 CHANNELS = 1 RATE = 44100 #sample rate RECORD_SECONDS = 30 #WAVE_OUTPUT_FILENAME = "pyaudio-output.wav" data = array('b', [0]) done = False lock = threading.Lock() def analyze(): global done global data while not done: #lock.acquire() dataAsInts = array('h', data) maxValue = max(dataAsInts) print(maxValue) sleep(0.1) #lock.release() p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) #buffer print("* recording") thrd = threading.Thread(target=analyze) thrd.start() try: while not done: #lock.acquire() data = stream.read(CHUNK) #lock.release() #frames.append(data) # 2 bytes(16 bits) per channel except KeyboardInterrupt: done = True thrd.join() print("* done recording") stream.stop_stream() stream.close() p.terminate() #wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb') #wf.setnchannels(CHANNELS) #wf.setsampwidth(p.get_sample_size(FORMAT)) #wf.setframerate(RATE) #wf.writeframes(b''.join(frames)) #wf.close() <file_sep>#!/usr/bin/python import serial import serial.tools.list_ports ports = list(serial.tools.list_ports.comports()) #List of serial ports (loaded automatically) def getCOM(): """ Function that returns the COM port of the XBee (if available) """ #Is list ports empty? if not ports: print("No Serial Ports found! Exiting now") exit() #If there is only one port available, automatically use that one if len(ports) == 1: return ports[0][0] #Display all available ports if there are more than one available print("Available Ports: ") for port in ports: print(port) return input("Enter Xbee Serialport: ") if __name__ == "__main__": #Set up serial #try: serialport = getCOM() print("Establishing connection to: %s" % serialport) ser = serial.Serial(serialport, 9600, timeout=1) #except: #print("Error establishing connection to serial port. Exiting now") #exit() try: while True: ser.write(bytes([int(input("Enter value to send: "))])) except (KeyboardInterrupt, SystemExit): ser.close() <file_sep>#!/usr/bin/python import pyaudio import sys import _thread from time import sleep from array import array #import RPi.GPIO as GPIO import serial import serial.tools.list_ports clap_count = 0 #pin = 24 exitFlag = False waitingForMoreClaps = False suspend = False ports = list(serial.tools.list_ports.comports()) #List of serial ports (loaded automatically) currentlyOn = False clapInProgress = False ON_POSITION = 54 OFF_POSITION = 80 TIME_TO_WAIT_AFTER_EACH_CLAP = 0 LOOP_DELAY = 1 TIME_TO_WAIT_FOR_ADDITIONAL_CLAPS = 2 def getCOM(): """ Function that returns the COM port of the XBee (if available) """ #Is list ports empty? if not ports: print("No Serial Ports found! Exiting now") exit() #If there is only one port available, automatically use that one if len(ports) == 1: return ports[0][0] #Display all available ports if there are more than one available print("Available Ports: ") for port in ports: print(port) return input("Enter Xbee Serialport: ") #def toggleLight(c): # GPIO.output(c, True) # sleep(1) # GPIO.output(c, False) # print("Light toggled") def waitForClaps(threadName): global clap_count global TIME_TO_WAIT_FOR_ADDITIONAL_CLAPS global exitFlag global waitingForMoreClaps global suspend global currentlyOn print("Waiting for more claps") sleep(TIME_TO_WAIT_FOR_ADDITIONAL_CLAPS) print("Claps detected: " + str(clap_count)) if clap_count == 1: if not suspend: toggleServo() elif clap_count == 2: #toggleLight(pin) #exitFlag = True pass elif clap_count == 3: suspend = not suspend print("Suspension: " + str(suspend)) if suspend: # If we just suspended, then turn lights off currentlyOn = True toggleServo() elif not suspend: # If we just restarted, then turn lights on currentlyOn = False toggleServo() elif clap_count == 4: exitFlag = True print("Waiting ended") clap_count = 0 waitingForMoreClaps = False def main(): global clap_count global pin global clapInProgress global waitingForMoreClaps CHUNK = 8192 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 THRESHOLD = 3000 MAX_VALUE = 0 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, #output=True, frames_per_buffer=CHUNK) #GPIO.setmode(GPIO.BCM) #GPIO.setup(pin, GPIO.OUT) try: print("Clap detection initialized") while True: #Get audio data try: data = stream.read(num_frames=CHUNK) except (OSError, IOError): data = array('b', [0]) print("E") as_ints = array('h', data) MAX_VALUE = max(as_ints) #Evaluate audio data if MAX_VALUE > THRESHOLD: #Clap detected if not clapInProgress: #Clap started now clapInProgress = True print("Clap started") else: # CLap is still ongoing print("Clap in progress") if not MAX_VALUE > THRESHOLD: #No clap detected if clapInProgress: #Clap ended now clapInProgress = False clap_count += 1 print("Clap ended") #sleep(TIME_TO_WAIT_AFTER_EACH_CLAP) if clap_count == 1 and not waitingForMoreClaps: #First clap in a series of claps _thread.start_new_thread( waitForClaps, ("waitThread",) ) waitingForMoreClaps = True if exitFlag: #Exit program sys.exit(0) #sleep(LOOP_DELAY) except (KeyboardInterrupt, SystemExit): print("Exiting") stream.stop_stream() stream.close() p.terminate() #GPIO.cleanup() def toggleServo(): global currentlyOn if currentlyOn: currentlyOn = False ser.write(bytes([OFF_POSITION])) print("Now switched off") else: currentlyOn = True ser.write(bytes([ON_POSITION])) print("Now switched on") if __name__ == "__main__": #Set up serial serialport = getCOM() print("Establishing connection to: %s" % serialport) ser = serial.Serial(serialport, 9600, timeout=1) toggleServo() # Main procedure main()
2210a15b31c74757708e81ca1f2126d486e90e50
[ "Python" ]
3
Python
joachimschmidt557/pi-clap
7af8e0dbcb2a8bc89bd0a207c76dccf482222b86
4a3d30f67500bf6f32873803c126bca05ef3f6af