Beispiel #1
0
 /**
  * Registers the needed assets
  */
 public function registerAssets()
 {
     $view = $this->getView();
     $key = \Yii::$app->params['google']['api'];
     $zoom = 10;
     $width = 512;
     $height = 512;
     $center = '{lat: -34.397, lng: 150.644}';
     $maptype = 'roadmap';
     //'mobile';
     $params = ['maptype' => $maptype, 'zoom' => $zoom, 'key' => $key, 'language' => 'es', 'libraries' => 'places', 'sensor' => false];
     $params = http_build_query($params);
     $cssMapa = '
     #' . $this->idMapa . ' {
          height: 300px;
          width: 100% !important;
     }';
     $jsMapa = 'extcmsAB.MapaLocalizador._inicializarIconPosicion("' . $this->_iconPosicion . '");';
     $jsMapa .= 'extcmsAB.MapaLocalizador._inicializarLabelPosicion("' . $this->labelDireccion . '");';
     $jsMapa .= 'extcmsAB.MapaLocalizador._inicializarInputsPosicion("' . $this->_lat . '","' . $this->_lng . '","' . $this->_ubicacion . '");';
     $jsMapa .= 'extcmsAB.MapaLocalizador._inicializarPosicion(' . $this->_initlat . ',' . $this->_initlng . ');';
     $jsMapa .= 'extcmsAB.MapaLocalizador._inicializarInputCallback("' . $this->initElementCallback . '");';
     //$jsMapa .= 'extcmsAB.MapaLocalizador._initBuscarLocalizcion();';
     //        $jsMapa .= 'extcmsAB.MapaLocalizador._refrescarMapa();';
     $cssSimple = SimplificarHelper::simplificarCSS($cssMapa);
     $jsSimple = SimplificarHelper::simplificarJS($jsMapa);
     $view->registerCss($cssSimple);
     $view->registerJs($jsSimple);
     $view->registerJsFile('https://maps.googleapis.com/maps/api/js?' . $params);
     MapLocalizacionAsset::register($view);
 }
Beispiel #2
0
    /**
     * Registers the needed assets
     */
    public function registerAssets()
    {
        $view = $this->getView();
        /*$js = "Dropzone.autoDiscover = " . $this->autoDiscover . ";\n"
              . "var " . $this->id . " = new Dropzone('div#" . $this->dropzoneContainer . "', \n"
              . Json::encode($this->options) . ");";
          */
        /*if (!empty($this->clientEvents)) {
              foreach ($this->clientEvents as $event => $handler) {
                  $js .= "$this->id.on('$event', $handler);";
              }
          }*/
        $cssDropzone = '
        #' . $this->previewsContainer . ' {
            max-height: 212px;
            overflow: hidden;
            margin: 5px auto;
        }

        #' . $this->dropzoneContainer . ' {
            min-height: 62px;
            border: 2px dashed #ddd;
            overflow-y: auto;
            padding: 5px 0 8px 20px;
            width: 100%;
        }

        #' . $this->dropzoneContainer . ':hover {
            border: 2px dashed #35b8e0;
            background-color: rgba(235, 239, 242, 0.41);
        }

        #' . $this->dropzoneContainer . '.dz-drag-hover {
            border: 3px dashed #999;
        }

        #' . $this->dropzoneContainer . ' .imageholder{
            display:inline-block;
            background:#fff;
            margin:7px 12px 7px 0 !important;
            text-align:center;
            border:2px solid #313534;
            position:relative;
            cursor: pointer;
        }

        #' . $this->dropzoneContainer . ' figure{
            margin:0;
            padding:0;
            display:block;
            position: relative;
            overflow: hidden;
        }
        #' . $this->dropzoneContainer . ' figure .preview-image-wrapper .thumbnail {
            margin:0px !important;
            border-radius: 0px !important;
            padding: 0px !important;
            margin-bottom: 0px !important;
            line-height: 1.846153846;
            background-color: #ffffff;
            border: 2px !important;
            border-radius: 0px !important;
        }

        #' . $this->previewsContainer . ' {
            display: none;
        }';
        $jsDropzone = '// browser detect
        var instance = 0;
        var max_images = ' . $this->maxImagenes . ';
        var uploaderHtml5 = false;

        extcmsAB.CargadorImagenes.inicializarIconLoading("' . $this->_iconLoading . '");

        if (extcmsAB.CargadorImagenes._esSoportadoCanvas() && extcmsAB.CargadorImagenes._soportaDataUrl() && extcmsAB.CargadorImagenes._navegadorOptimo())
            uploaderHtml5 = true;

        Dropzone.isBrowserSupported = function() {
            var capableBrowser, regex, _i, _len, _ref;
            capableBrowser = true;
            if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) {
                if (document.querySelectorAll("html.mobile") != []) {
                    capableBrowser = extcmsAB.CargadorImagenes._navegadorOptimo();
                }
                if (!("classList" in document.createElement("a"))) {
                    capableBrowser = false;
                } else {
                    _ref = Dropzone.blacklistedBrowsers;
                    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                        regex = _ref[_i];
                        if (regex.test(navigator.userAgent)) {
                            capableBrowser = false;
                            continue;
                        }
                    }
                }
            } else {
                capableBrowser = false;
            }
            return capableBrowser;
        };

        var filesExceedError = false;

        var dropzoneObj = new Dropzone("div#' . $this->dropzoneContainer . '", {
            url: "' . $this->subirUrl . '",
            //url: "/admin/articulos/imagenes/"+instance,

             headers: {"' . \yii\web\Request::CSRF_HEADER . '":"' . \Yii::$app->getRequest()->getCsrfToken() . '"},
             params: {"' . \Yii::$app->getRequest()->csrfParam . '":"' . \Yii::$app->getRequest()->getCsrfToken() . '", "usuario":' . \Yii::$app->user->getId() . '},

            paramName: "file",
            parallelUploads: 1,
            uploadMultiple: false,
            addRemoveLinks: false,
            clickable: "#dropzone-clic-btn",
            maxThumbnailFilesize: 5,
            maxFilesize: 15,
            thumbnailWidth:100,
            maxFiles: 10,
            thumbnailHeight:100,
            imageWidth: 635,
            previewsContainer: "#' . $this->previewsContainer . '",
            imageHeight: 635,
            acceptedFiles: "image/jpeg, image/png, image/bmp ,image/gif",
            imageQuality: 0.8,
            previewTemplate: extcmsAB.CargadorImagenes._plantillaCargadorImagenes(),
            dictDefaultMessage: "Arrastra fotos aquí",
            dictFallbackMessage: "Tu navegador no soporta arrastrar fotos directamente",
            dictFallbackText: "Utilice el método antiguo para subir imágenes.",
            dictFileTooBig: "Archivo demasiado pesado",
            dictInvalidFileType: "Formato no permitido",
            dictResponseError: "Error al subir archivo",
            dictCancelUpload: "Cancelar subida",
            dictCancelUploadConfirmation: "Estas seguro que deseas cancelar la subida?",
            dictRemoveFile: "Eliminar foto",
            dictRemoveFileConfirmation: null,
            dictMaxFilesExceeded: "No puedes subir mas imágenes.",
            success: function(file,response) {
                var _element = file.previewElement;
                console.log(response);
                var photoId = getPhotoIdFromResponse(response);
                if (photoId == -1) {
                    this.emit("error", file, "Error al subir la imagen");
                    return _element.classList.add("dz-error-message");
                }
                _element.querySelector(".photoId").innerHTML = photoId;
                return _element.classList.add("dz-success");
            },
            init: function(obj) {
                $(function() {
                    hideOldDesk();
                });
                var myDropzone = this;
                var imgNames = [' . $this->_imagenes . '];

                //Populate any existing thumbnails
                for (var i = 0; i < imgNames.length; i++) {
                    if (imgNames[i].trim() != "") {
                        $("#' . $this->previewsContainer . '").show();

                        var mockFile = {
                            name: imgNames[i],
                            size: 0,
                            accepted: true,
                            type: "image/jpeg",
                            status: Dropzone.ADDED,
                            url: "http://ofertaski.com/libreria/imagenes/articulos/"+imgNames[i],
                            //url: "http://mimgs.sgmn.es:80/pta1_thumb/"+imgNames[i].substring(0,3)+"/"+imgNames[i],
                            numFoto: i,
                            photoId: imgNames[i].split(".")[0]
                        };

                        // Call the default addedfile event handler
                        myDropzone.emit("addedfile", mockFile);

                        // And optionally show the thumbnail of the file:
                        //myDropzone.emit("thumbnail", mockFile, "http://ofertaski.com/libreria/imagenes/defecto/categoria.jpg");
                        //myDropzone.emit("thumbnail", mockFile, "http://ofertaski.com/libreria/imagenes/defecto/"+imgNames[i].substring(0,3)+"/"+imgNames[i]);
                        myDropzone.emit("thumbnail", mockFile, "http://ofertaski.com/libreria/imagenes/articulos/"+imgNames[i]);

                        myDropzone.files.push(mockFile);
                    }
                }

                //init imagen principal si existen
                if(imgNames.length > 0){
                    extcmsAB.CargadorImagenes._initFotoPrincipal(' . $this->initImagenPrincipal . ');
                }
                

            },
            removedfile: function(file) {
                var _ref;
                if (file.previewElement) {
                    if ((_ref = file.previewElement) != null) {


                        console.log(file);
                        $.ajax({
                            url: "' . $this->eliminarUrl . '",
                            type: "POST",
                            data:{"imagen":file.name, "usuario":' . \Yii::$app->user->getId() . '},
                            dataType: "json",
                            //contentType: false,
                            //processData: false,
                            success:function(data){
                                console.log(data);
                            }

                        });

                        $( file.previewElement ).animate({
                            opacity: 0
                        }, 300, function() {
                            $(file.previewElement).remove();
                            if($(".main-img-thumbnail").length == 0) {
                                $(".main-img-thumbnail").remove();
                                extcmsAB.CargadorImagenes._cambiarFotoPrincipal(extcmsAB.CargadorImagenes._obtenerImagenPrincipal(0));
                            }

                        });
                    }
                }
                return this._updateMaxFilesReachedClass();
            },
            addedfile: function(file) {
                $("#' . $this->previewsContainer . '").show();
                var node, removeFileEvent, removeLink, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results, _numFoto, _lenNum, _photoId, _lenId;
                if (this.element === this.previewsContainer) {
                    this.element.classList.add("dz-started");
                }
                if (this.previewsContainer) {
                    file.previewElement = Dropzone.createElement(this.options.previewTemplate.trim());
                    file.previewTemplate = file.previewElement;
                    this.previewsContainer.appendChild(file.previewElement);
                    $(file.previewElement).click(function(e) {extcmsAB.CargadorImagenes._cambiarFotoPrincipal(this)});

                    _ref = file.previewElement.querySelectorAll("[data-dz-name]");
                    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                        node = _ref[_i];
                        node.textContent = file.name;
                    }
                    _ref1 = file.previewElement.querySelectorAll("[data-dz-size]");
                    for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
                        node = _ref1[_j];
                        node.innerHTML = this.filesize(file.size);
                    }
                    var numFoto = extcmsAB.CargadorImagenes._obtenerNumFoto(max_images);
                    _numFoto = file.previewElement.querySelectorAll(".numFoto");
                    for (_k = 0, _lenNum = _numFoto.length; _k < _lenNum; _k++) {
                        node = _numFoto[_k];
                        if (!isNaN(numFoto)) {
                            node.innerHTML = parseInt(numFoto,10);
                        }
                        if (file.numFoto != undefined) {
                            node.innerHTML = file.numFoto;
                        }
                    }
                    _photoId = file.previewElement.querySelectorAll(".photoId");
                    for (_l = 0, _lenId = _photoId.length; _l < _lenId; _l++) {
                        node = _photoId[_l];
                        node.innerHTML = file.photoId;
                    }
                    if (this.options.addRemoveLinks) {
                        file._removeLink = Dropzone.createElement("<a class=\\"dz-remove\\" href=\\"javascript:undefined;\\" data-dz-remove>" + this.options.dictRemoveFile + "</a>");
                        file.previewElement.appendChild(file._removeLink);
                    }
                    removeFileEvent = (function(_this) {
                        return function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            if (file.status === Dropzone.UPLOADING) {
                                return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
                                    return _this.removeFile(file);
                                });
                            } else {
                                if (_this.options.dictRemoveFileConfirmation) {
                                    return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
                                        return _this.removeFile(file);
                                    });
                                } else {
                                    return _this.removeFile(file);
                                }
                            }
                        };
                    })(this);
                    _ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
                    _results = [];
                    for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
                        removeLink = _ref2[_k];
                        _results.push(removeLink.addEventListener("click", removeFileEvent));
                    }
                    return _results;
                }
            },
            maxfilesexceeded: function(file) {

                if (!filesExceedError) {
                    filesExceedError = true;

                    this.removeFile(file);

                    $("#photo-uploader-msg").addClass("msg-alert-photo-uploader");
                    setTimeout(function(){
                        $("#photo-uploader-msg").removeClass("msg-alert-photo-uploader");
                    },4000);
                }
            },
            fallback: function() {
                var child, messageElement, span, _i, _len, _ref;
                this.element.className = "" + this.element.className + " dz-browser-not-supported";
                _ref = this.element.getElementsByTagName("div");
                for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                    child = _ref[_i];
                    if (/(^| )dz-message($| )/.test(child.className)) {
                        messageElement = child;
                        child.className = "dz-message";
                        continue;
                    }
                }
                if (!messageElement) {
                    messageElement = Dropzone.createElement("<div class=\\"dz-message\\"><span></span></div>");
                    this.element.appendChild(messageElement);
                }
                span = messageElement.getElementsByTagName("span")[0];
                if (span) {
                    span.textContent = this.options.dictFallbackMessage;
                }

                $(function() {
                    hideNewDesk();
                    hideNewMsite();
                });

                return this.element.appendChild(this.getFallbackForm());
            },
            totaluploadprogress: function() {

                filesExceedError = false;
                if ($("#main_image_new").val() == "") {
                    extcmsAB.CargadorImagenes._cambiarFotoPrincipal( $("div.dz-image-preview").first() );
                } else {
                    extcmsAB.CargadorImagenes._cambiarFotoPrincipal(extcmsAB.CargadorImagenes._obtenerImagenPrincipal($("#main_image_new").val()));
                }
            },
            error: function(file, message) {
                var node, _i, _len, _ref, _results;
                if (file.previewElement) {
                    file.previewElement.classList.add("dz-error");
                    if (typeof message !== "String" && message.error) {
                        message = message.error;
                    }
                    _ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
                    file.previewElement.querySelectorAll("[data-dz-thumbnail]")[0].className += " error-image-load";
                    _results = [];
                    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
                        node = _ref[_i];
                        _results.push(node.textContent = message);
                    }
                    return _results;
                }
            }
        });


        function getPhotoIdFromResponse(_response)	{
            try {
                return JSON.parse(_response).name.split(".")[0];
            } catch(e) {
                return -1;
            }
        }

        function hideNewMsite() {
            //$("#totalImgUpl").hide();
        }

        function hideNewDesk() {
            $("#old-photouploader").show();
            $("#new-photouploader").remove();
            $("#new-photouploader").find("input").attr("disabled", "disabled");
        }

        function hideOldDesk() {
            $("#old-photouploader").remove();
        }

        detectVerticalSquash = function(img) {
            var alpha, canvas, ctx, data, ey, ih, iw, py, ratio, sy;
            iw = img.naturalWidth;
            ih = img.naturalHeight;
            if (iw == ih)
                return 1;
            canvas = document.createElement("canvas");
            canvas.width = 1;
            canvas.height = ih;
            ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);
            data = ctx.getImageData(0, 0, 1, ih).data;
            sy = 0;
            ey = ih;
            py = ih;
            while (py > sy) {
                alpha = data[(py - 1) * 4 + 3];
                if (alpha === 0) {
                    ey = py;
                } else {
                    sy = py;
                }
                py = (ey + sy) >> 1;
            }
            ratio = py / ih;
            if (ratio === 0) {
                return 1;
            } else {
                return ratio;
            }
        };

        drawImageIOSFix = function(ctx, img, sx, sy, sw, sh, dx, dy, dw, dh) {
            var vertSquashRatio;
            vertSquashRatio = detectVerticalSquash(img);
            return ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh / vertSquashRatio);
        };



        $(document.body).on("dragover", function(e) {
            e.preventDefault();
            return false;
        });

        $(document.body).on("drop", function(e){
            e.preventDefault();
            return false;
        });';
        $cssSimple = SimplificarHelper::simplificarCSS($cssDropzone);
        $jsSimple = SimplificarHelper::simplificarJS($jsDropzone);
        $view->registerCss($cssSimple);
        $view->registerJs($jsSimple);
        DropZoneAsset::register($view);
    }