/** * Upload documents * @param $uploadType * @param bool $withoutMessage * @return int */ public static function uploadDocuments($uploadType, $withoutMessage = false) { if(isset($_SESSION[$uploadType]) && count($_SESSION[$uploadType]) > 0) { $settings = UsersSettings::model()->findByAttributes(array( 'User_ID' => Yii::app()->user->userID, )); //get default bank account $condition = new CDbCriteria(); $condition->condition = "users_project_list.User_ID = '" . Yii::app()->user->userID . "'"; $condition->addCondition("users_project_list.Client_ID = '" . Yii::app()->user->clientID . "'"); $condition->addCondition("t.Account_Num_ID = '" . $settings->Default_Bank_Acct . "'"); $condition->join = "LEFT JOIN projects ON projects.Project_ID = t.Project_ID LEFT JOIN users_project_list ON users_project_list.Project_ID = t.Project_ID"; $bankAcct = BankAcctNums::model()->with('client.company', 'project')->find($condition); $defaultBankAcct = 0; if ($bankAcct) { $defaultBankAcct = $settings->Default_Bank_Acct; } //get user to send email $person_to_email = false; if (Yii::app()->user->id != 'user' && Yii::app()->user->id != 'single_user') { $person_to_email = Users::model()->with('person')->findByPk(Yii::app()->user->userID); } else { $condition = new CDbCriteria(); $condition->join = "LEFT JOIN users_client_list ON users_client_list.User_ID = t.User_ID"; $condition->addInCondition('users_client_list.User_Type', array(UsersClientList::APPROVER, UsersClientList::PROCESSOR, UsersClientList::CLIENT_ADMIN)); $condition->addInCondition('t.User_Type', array(Users::ADMIN, Users::DB_ADMIN, Users::DATA_ENTRY_CLERK), "OR"); $condition->addCondition("users_client_list.Client_ID = '" . Yii::app()->user->clientID . "'"); $person_to_email = Users::model()->with('person')->find($condition); } foreach ($_SESSION[$uploadType] as $key => $current_upload_file) { // check fed id if ($current_upload_file['doctype'] == self::W9) { if (!preg_match('/^(\d{2}\-\d{7})|(\d{3}\-\d{2}\-\d{4})|(IN[-]\d{6})|(T0[-]\d{7})$/', $current_upload_file['fed_id'])) { return 2; } } } // insert documents into DB foreach ($_SESSION[$uploadType] as $key => $current_upload_file) { if (file_exists($current_upload_file['filepath'])) { // create document $document = new Documents(); $document->Document_Type = $current_upload_file['doctype']; $document->User_ID = Yii::app()->user->userID; $document->Client_ID = Yii::app()->user->clientID; $document->Project_ID = Yii::app()->user->projectID; $document->Created = date("Y-m-d H:i:s"); $document->save(); $new_doc_id=$document->Document_ID; Audits::LogAction($document->Document_ID ,Audits::ACTION_UPLOAD); // insert image $image = new Images(); $imageData = addslashes(fread(fopen($current_upload_file['filepath'],"rb"),filesize($current_upload_file['filepath']))); //$imageData = FileModification::ImageToPdfByFilePath($current_upload_file['filepath']); $image->Document_ID = $document->Document_ID; $image->Img = $imageData; $image->File_Name = $current_upload_file['name']; $image->Mime_Type = $current_upload_file['mimetype']; $image->File_Hash = sha1_file($current_upload_file['filepath']); $image->File_Size = intval(filesize($current_upload_file['filepath'])); $image->Pages_Count = FileModification::calculatePagesByPath($current_upload_file['filepath']); $image->save(); $infile = @file_get_contents($current_upload_file['filepath'], FILE_BINARY); if (($current_upload_file['mimetype'] == 'application/pdf' && $image->findPdfText($infile) == '') || $current_upload_file['mimetype'] != 'application/pdf') { Documents::crateDocumentThumbnail($current_upload_file['filepath'], 'thumbs', $current_upload_file['mimetype'], $document->Document_ID, 80); } // delete file from temporary catalog and from cache table //unlink($current_upload_file['filepath']); FileCache::deleteBothFromCacheById($current_upload_file['file_id']); if ($current_upload_file['doctype'] == self::W9) { // if document is W9 // get additional fields $fedId = trim($current_upload_file['fed_id']); $newCompanyName = trim($current_upload_file['company_name']); // get company info $company = Companies::model()->with('client')->findByAttributes(array( 'Company_Fed_ID' => $fedId, )); // create w9 $W9 = new W9(); $W9->Document_ID = $document->Document_ID; $W9->W9_Owner_ID = Yii::app()->user->clientID; $W9->Creator_ID = Yii::app()->user->userID; $W9->Business_Name = trim($current_upload_file['bus_name']); $W9->Tax_Class = trim($current_upload_file['tax_name']); // get user info $user = Users::model()->with('person')->findByPk(Yii::app()->user->userID); if ($company) { // if company exisits $client = $company->client; //fill created company with dataentry values from session Companies::fillWithSessionDataEntry($company,$current_upload_file); $existingW9 = W9::model()->findByAttributes(array( 'Client_ID' => $client->Client_ID, 'W9_Owner_ID' => Yii::app()->user->clientID, )); if ($existingW9) { $W9->Revision_ID = -1; } else { $W9->Revision_ID = 0; } $vendor = Vendors::model()->findByAttributes(array( 'Client_Client_ID' => Yii::app()->user->clientID, 'Vendor_Client_ID' => $client->Client_ID, )); if (isset($vendor->Active_Relationship) && $vendor->Active_Relationship == Vendors::NOT_ACTIVE_RELATIONSHIP) { $vendor->Active_Relationship = Vendors::ACTIVE_RELATIONSHIP; $vendor->save(); } else if (!$vendor && Yii::app()->user->clientID != 0 && Yii::app()->user->clientID != $client->Client_ID) { $vendor = new Vendors(); $vendor->Vendor_ID_Shortcut = ''; $vendor->Vendor_Client_ID = $client->Client_ID; $vendor->Client_Client_ID = Yii::app()->user->clientID; $vendor->Vendor_Name_Checkprint = ''; $vendor->Vendor_1099 = ''; $vendor->Vendor_Default_GL = ''; $vendor->Vendor_Default_GL_Note = ''; $vendor->Vendor_Note_General = ''; $vendor->Vendor_Contact = trim($current_upload_file['contact']); $vendor->Vendor_Phone = trim($current_upload_file['phone']); $vendor->save(); } } else { //if company does not exists, create new company $client = Companies::createEmptyCompany($fedId, $newCompanyName); $company_model = Companies::model()->findByPk($client->Company_ID); //fill created company with dataentry values from session Companies::fillWithSessionDataEntry($company_model,$current_upload_file); if (Yii::app()->user->clientID != 0) { $vendor = new Vendors(); $vendor->Vendor_ID_Shortcut = ''; $vendor->Vendor_Client_ID = $client->Client_ID; $vendor->Client_Client_ID = Yii::app()->user->clientID; $vendor->Vendor_Name_Checkprint = ''; $vendor->Vendor_1099 = ''; $vendor->Vendor_Default_GL = ''; $vendor->Vendor_Default_GL_Note = ''; $vendor->Vendor_Note_General = ''; $vendor->Vendor_Contact = trim($current_upload_file['contact']); $vendor->Vendor_Phone = trim($current_upload_file['phone']); $vendor->save(); } $W9->Revision_ID = 0; } // save w9 $W9->Client_ID = $client->Client_ID; $W9->save(); if ($person_to_email) { Mail::sendNewW9ForDataEntry($person_to_email->person->Email, $person_to_email->person->First_Name, $person_to_email->person->Last_Name); } } else if ($current_upload_file['doctype'] == self::AP) { //create aps $aps = new Aps(); $aps->Document_ID = $document->Document_ID; $aps->Vendor_ID = 0; $aps->PO_ID = 0; $aps->AP_Approval_Value = Aps::NOT_READY_FOR_APPROVAL; $aps->Invoice_Number = 0; $aps->save(); } else if ($current_upload_file['doctype'] == self::PM) { //create payment $payment = new Payments(); $payment->Document_ID = $document->Document_ID; $payment->Vendor_ID = 0; $payment->Payment_Check_Number = 0; $payment->Payment_Amount = 0; if ($defaultBankAcct != 0) { $payment->Account_Num_ID = $defaultBankAcct; } else { $payment->Account_Num_ID = 0; } $payment->save(); } else if ($current_upload_file['doctype'] == self::PO) { //create pos $po = new Pos(); $po->Document_ID = $document->Document_ID; $po->Vendor_ID = 0; $po->PO_Number = Pos::getNewPoNumber(); $po->PO_Date = date('Y-m-d'); $po->PO_Backup_Document_ID = 0; $po->save(); } else if ($current_upload_file['doctype'] == self::PR) { $payroll = new Payrolls(); $payroll->Document_ID = $document->Document_ID; $payroll->save(); } else if ($current_upload_file['doctype'] == self::JE) { $je = new Journals(); $je->Document_ID = $document->Document_ID; $je->save(); } else if ($current_upload_file['doctype'] == self::PC) { $pc = new Pcs(); $pc->Document_ID = $document->Document_ID; $pc->save(); } else if ($current_upload_file['doctype'] == self::AR) { $ar = new Ars(); $ar->Document_ID = $document->Document_ID; $ar->save(); } } $arr[$current_upload_file['name']]['string']= Images::getAjaxStringForLastUploadSection($new_doc_id); $arr[$current_upload_file['name']]['key']=$key; } $_SESSION[$uploadType] = array(); if (!$withoutMessage) { Yii::app()->user->setFlash('success', "Documents have been uploaded!"); } return json_encode($arr); } else { $answer['empty']=1; return json_encode($answer); } }
/** * Create thumbnail for image in specified size * @param $objImage * @param $intNewWidth * @param $intNewHeight * @param $intType */ protected function createThumb($objImage, $intNewWidth, $intNewHeight, $intType) { // Verify that the size doesn't already exist in the db (usually the original which // we don't want to overwrite) $objImageThumbnail = Images::LoadByRowidSize($objImage->id, $intType); if (!is_null($objImageThumbnail)) { return; } //Get our original file from Lightspeed $strOriginalFile = $objImage->image_path; $strTempThumbnail = Images::GetImageName($strOriginalFile, $intNewWidth, $intNewHeight, 'temp'); $strNewThumbnail = Images::GetImageName($strOriginalFile, $intNewWidth, $intNewHeight); $strOriginalFileWithPath = Images::GetImagePath($strOriginalFile); $strTempThumbnailWithPath = Images::GetImagePath($strTempThumbnail); $strNewThumbnailWithPath = Images::GetImagePath($strNewThumbnail); $image = Yii::app()->image->load($strOriginalFileWithPath); $quality = _xls_get_conf('IMAGE_QUALITY', '75'); $sharpness = _xls_get_conf('IMAGE_SHARPEN', '20'); if ($sharpness != 0) { $image->resize($intNewWidth, $intNewHeight)->quality($quality)->sharpen($sharpness); } else { $image->resize($intNewWidth, $intNewHeight)->quality($quality); } if (Images::IsWritablePath($strNewThumbnail)) { if (_xls_get_conf('IMAGE_FORMAT', 'jpg') == 'jpg') { $strSaveFunc = 'imagejpeg'; $strLoadFunc = "imagecreatefromjpeg"; } else { $strSaveFunc = 'imagepng'; $strLoadFunc = "imagecreatefrompng"; } $image->save($strNewThumbnailWithPath); //just save normally with no special effects //See if we have a thumbnail record in our Images table, create or update $objThumbImage = Images::model()->findByAttributes(array('width' => $intNewWidth, 'height' => $intNewHeight, 'index' => $objImage->index, 'parent' => $objImage->id, 'product_id' => $objImage->product_id)); if (!$objThumbImage instanceof Images) { $objThumbImage = new Images(); Images::model()->deleteAllByAttributes(array('width' => $intNewWidth, 'height' => $intNewHeight, 'parent' => $objImage->id)); //sanity check to prevent SQL UNIQUE errors } $objThumbImage->image_path = $strNewThumbnail; $objThumbImage->width = $intNewWidth; $objThumbImage->height = $intNewHeight; $objThumbImage->parent = $objImage->id; $objThumbImage->index = $objImage->index; $objThumbImage->product_id = $objImage->product_id; $objThumbImage->save(); } else { Yii::log("Directory permissions error writing " . $strNewThumbnail, 'error', 'application.' . __CLASS__ . "." . __FUNCTION__); } }
/** * Store a newly created resource in storage. * * @return Response */ public function store() { $file = array('image' => Input::file('image')); // setting up rules $rules = array('image' => 'required|mimes:jpeg,gif'); // doing the validation, passing post data, rules and the messages $validator = Validator::make($file, $rules); // process the login if ($validator->fails()) { return Redirect::to('images/create')->withErrors($validator)->withInput(Input::except('password')); } else { // store // $userId = Auth::user()->id; // $file = Input::file('image'); // $data = Img::make($file)->encode('data-url'); // // $this->image->user_id = $userId; // $this->image->img_name = $data->encoded; // $this->image->save(); $file = Input::file('image'); $picture = $file->getClientOriginalName(); $generatepic = rand(32321323, 8687868678) . $picture; $fullpath = $file->move('../public/img', $generatepic); $images = new Images(); $images->image = $fullpath; // $images->image = Input::file('image')->getClientOriginalName(); $images->save(); // redirect Session::flash('message', 'Successfully uploaded!'); return Redirect::to('images'); } }
public function actionIndex() { if (!empty($_POST)) { $images = CUploadedFile::getInstancesByName('images'); if (isset($images) && count($images) > 0) { // go through each uploaded image foreach ($images as $image => $pic) { $model = new Images(); $imageType = explode('.', $pic->name); $imageType = $imageType[count($imageType) - 1]; $imageName = md5(uniqid()) . '.' . $imageType; if ($pic->saveAs(Yii::getPathOfAlias('webroot') . '/upload/images/' . $imageName)) { $model->image = $imageName; $model->name = $pic->name; $model->created = time(); $model->save(); Yii::app()->user->setFlash('success', translate('Thêm thành công.')); } // handle the errors here, if you want } } $this->redirect(PIUrl::createUrl('/admin/images/index/')); } $criteria = new CDbCriteria(); $criteria->order = 'id DESC'; $count = Images::model()->count($criteria); $pages = new CPagination($count); // results per page $pages->pageSize = 18; $pages->applyLimit($criteria); $model = Images::model()->findAll($criteria); $this->render('index', compact('model', 'pages')); }
public function addPost($user_id, $post_content, $location, $url_arr, $album, $cats) { $model = new Posts(); $model->post_content = $post_content; $model->post_comment_count = 0; $model->post_like_count = 0; $model->post_view_count = 0; $model->location = $location; $model->created_at = time(); $model->status = 1; $model->updated_at = time(); $model->user_id = $user_id; if (!$model->save(FALSE)) { return FALSE; } $cats = json_decode($cats, TRUE); foreach ($cats as $cat) { $cat_model = new CatPost(); $cat_model->cat_id = $cat; $cat_model->post_id = $model->post_id; $cat_model->status = 1; $cat_model->created_at = time(); $cat_model->updated_at = time(); if (!$cat_model->save(FALSE)) { return FALSE; } } if (is_array($url_arr)) { foreach ($url_arr as $url) { $image = new Images(); $image->post_id = $model->post_id; $image->created_at = time(); $image->created_by = $user_id; $image->updated_at = time(); $image->status = 1; $image->album_id = $album; $image->image_like_count = 0; $image->img_url = $url; if (!$image->save(FALSE)) { return FALSE; } } } else { $image = new Images(); $image->post_id = $model->post_id; $image->created_at = time(); $image->created_by = $user_id; $image->updated_at = time(); $image->status = 1; $image->album_id = $album; $image->image_like_count = 0; $image->img_url = $url_arr; if (!$image->save(FALSE)) { return FALSE; } } return $model->post_id; }
/** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate() { $model = new Images(); // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['Images'])) { $model->attributes = $_POST['Images']; if ($model->save()) { $this->redirect(array('view', 'id' => $model->id)); } } $this->render('create', array('model' => $model)); }
public function save() { $transaction = Yii::$app->db->beginTransaction(); try { $characteristics = new Characteristics(); $characteristics->display_type = $this->displayType; $characteristics->mechanism_type = $this->mechanismType; $characteristics->starp_type = $this->starpType; $characteristics->sex = $this->sex; if (!$characteristics->save(false)) { throw new \Exception('Charasteristic not save, transaction rollback'); } $products = new Products(); $products->clk_name = $this->name; $products->clk_description = $this->description; $products->characteristics_id = $characteristics->id; $products->price = $this->price; if (!$products->save(false)) { throw new \Exception('Product not save, transaction rollback'); } $hashName = Yii::$app->security->generateRandomString(); $fullImagePath = self::FULL_IMAGES_PATH . $hashName . '.' . $this->images->extension; if (!$this->images->saveAs($fullImagePath)) { throw new \Exception('Image not save in full image path'); } $imgSizeReduct = function ($side = 'width') use($fullImagePath) { $size = getimagesize($fullImagePath); if ($side === 'width') { return $size[0] / self::THUMB_REDUCTION; } if ($side === 'height') { return $size[1] / self::THUMB_REDUCTION; } }; $images = new Images(); $transformation = new Transformation(); $imagine = new Imagine(); $transformation->thumbnail(new Box($imgSizeReduct('width'), $imgSizeReduct('height')))->save(Yii::getAlias('@webroot/' . self::THUMBS_IMAGES_PATH . $hashName . '.' . $this->images->extension)); $transformation->apply($imagine->open(Yii::getAlias('@webroot/' . self::FULL_IMAGES_PATH . $hashName . '.' . $this->images->extension))); $images->product_id = $products->id; $images->img_name = $hashName . '.' . $this->images->extension; if (!$images->save(false)) { throw new \Exception('Images not save, transaction rollback'); } $transaction->commit(); Yii::$app->session->addFlash('success', 'Product successfully added'); } catch (\Exception $e) { $transaction->rollBack(); throw $e; } }
public static function addImage($imageOfId, $entityId, $image) { $destinationFileName = ImageUtils::generateFileName(basename($image)); $destinationFile = self::getImagesDirectory($entityId, $imageOfId) . $destinationFileName; $success = Yii::app()->s3->upload($image, $destinationFile, Yii::app()->params['s3BucketName']); if ($success) { $images = new Images(); $images->image_of_id = $imageOfId; $images->entity_id = $entityId; $images->filename = $destinationFileName; return $images->save(); } else { return Yii::app()->s3->lastError; } }
function add($request, $response, $args) { $body = $request->getParsedBody(); if (!isset($_FILES['image'])) { echo "No files uploaded!!"; return; } $name = $_FILES['image']['name']; if (move_uploaded_file($_FILES['image']['tmp_name'], 'uploads/' . $name) === true) { $url = 'uploads/' . $name; } $image = new Images(); $image->title = $body['title']; $image->url = $url; $image->save(); }
/** * Performs the work of inserting or updating the row in the database. * * If the object is new, it inserts it; otherwise an update is performed. * All related objects are also updated in this method. * * @param PropelPDO $con * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. * @throws PropelException * @see save() */ protected function doSave(PropelPDO $con) { $affectedRows = 0; // initialize var to track total num of affected rows if (!$this->alreadyInSave) { $this->alreadyInSave = true; // We call the save method on the following object(s) if they // were passed to this object by their coresponding set // method. This object relates to these object(s) by a // foreign key reference. if ($this->aImages !== null) { if ($this->aImages->isModified() || $this->aImages->isNew()) { $affectedRows += $this->aImages->save($con); } $this->setImages($this->aImages); } if ($this->isNew()) { $this->modifiedColumns[] = ColorPeer::ID; } // If this object has been modified, then save it to the database. if ($this->isModified()) { if ($this->isNew()) { $pk = ColorPeer::doInsert($this, $con); $affectedRows += 1; // we are assuming that there is only 1 row per doInsert() which // should always be true here (even though technically // BasePeer::doInsert() can insert multiple rows). $this->setId($pk); //[IMV] update autoincrement primary key $this->setNew(false); } else { $affectedRows += ColorPeer::doUpdate($this, $con); } $this->resetModified(); // [HL] After being saved an object is no longer 'modified' } if ($this->collProductHasColors !== null) { foreach ($this->collProductHasColors as $referrerFK) { if (!$referrerFK->isDeleted()) { $affectedRows += $referrerFK->save($con); } } } $this->alreadyInSave = false; } return $affectedRows; }
public function actionUpload($id) { $model = $this->checkOwner($id); Yii::import("ext.EAjaxUpload.qqFileUploader"); $allowedExtensions = param('allowedImgExtensions', array('jpg', 'jpeg', 'gif', 'png')); //$sizeLimit = param('maxImgFileSize', 8 * 1024 * 1024); $sizeLimit = Images::getMaxSizeLimit(); $uploader = new qqFileUploader($allowedExtensions, $sizeLimit); $path = Yii::getPathOfAlias('webroot.uploads.objects.' . $model->id . '.' . Images::ORIGINAL_IMG_DIR); $pathMod = Yii::getPathOfAlias('webroot.uploads.objects.' . $model->id . '.' . Images::MODIFIED_IMG_DIR); $oldUMask = umask(0); if (!is_dir($path)) { @mkdir($path, 0777, true); } if (!is_dir($pathMod)) { @mkdir($pathMod, 0777, true); } umask($oldUMask); if (is_writable($path) && is_writable($pathMod)) { touch($path . DIRECTORY_SEPARATOR . 'index.htm'); touch($pathMod . DIRECTORY_SEPARATOR . 'index.htm'); $result = $uploader->handleUpload($path . DIRECTORY_SEPARATOR, false, uniqid()); if (isset($result['success']) && $result['success']) { $resize = new CImageHandler(); if ($resize->load($path . DIRECTORY_SEPARATOR . $result['filename'])) { $resize->thumb(param('maxImageWidth', 1024), param('maxImageHeight', 768), Images::KEEP_PHOTO_PROPORTIONAL)->save(); $image = new Images(); $image->id_object = $model->id; $image->id_owner = $model->owner_id; $image->file_name = $result['filename']; $image->save(); } else { $result['error'] = 'Wrong image type.'; @unlink($path . DIRECTORY_SEPARATOR . $result['filename']); } } } else { $result['error'] = 'Access denied.'; } // to pass data through iframe you will need to encode all html tags $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES); echo $result; }
public function actionIndex() { if (!empty($_POST)) { $images = CUploadedFile::getInstancesByName('images'); if (isset($images) && count($images) > 0) { // go through each uploaded image foreach ($images as $image => $pic) { $model = new Images(); $model->scenario = 'image'; $imageName = $this->getFileName($pic); $model->image = $imageName; if ($pic->saveAs(Yii::getPathOfAlias('webroot') . '/upload/images/' . $imageName)) { $model->link = $imageName; $model->name = $pic->name; $model->created = time(); $model->album_id = Images::$IMAGE_PHOTO; //dump($model); if ($model->save()) { Yii::app()->user->setFlash('success', translate('Thêm thành công.')); } else { dump($model->errors); } } // handle the errors here, if you want } } $this->redirect(PIUrl::createUrl('admin/images/index')); } $criteria = new CDbCriteria(); $criteria->condition = 'album_id=:album_id'; $criteria->order = 'id DESC'; $criteria->params = array(':album_id' => Images::$IMAGE_PHOTO); $count = Images::model()->count($criteria); $pages = new CPagination($count); // results per page $pages->pageSize = 18; $pages->applyLimit($criteria); $listImage = Images::model()->findAll($criteria); //dump($model); $dataAlbums = Albums::model()->getAlbums(); $this->render('index', compact('pages', 'dataAlbums', 'listImage')); }
public function actionCreate() { $model = new DatasetAttributes(); $att = Attribute::model()->findByAttributes(array('attribute_name' => Attribute::FUP)); if (!$att) { $att = new Attribute(); $att->attribute_name = Attribute::FUP; $att->definition = ''; $att->save(); } $model->attribute_id = $att->id; $image = new Images(); if (isset($_POST['DatasetAttributes'])) { $args = $_POST['DatasetAttributes']; $exist = DatasetAttributes::model()->findByAttributes(array('dataset_id' => $args['dataset_id'], 'attribute_id' => $att->id)); if ($exist) { $model = $exist; } $model->attributes = $args; $model->value = ''; //$image->attributes = $_POST['Images']; $image->license = "no license"; $image->photographer = "no author"; $image->source = "gigadb"; if ($image->validate()) { $image->save(); } else { Yii::log(print_r($image->getErrors(), true), 'debug'); } if ($image) { $model->image_id = $image->id; } if ($model->validate()) { $model->save(); $this->redirect('/dataset/' . $model->dataset->identifier); } else { Yii::log(print_r($model->getErrors(), true), 'debug'); } } $this->render('create', array('model' => $model, 'image' => $image)); }
public function actionInsert() { if (isset($_POST['choose'])) { $post = new Posts(); $post->status = 0; $post->updated_at = time(); $post->created_at = time(); $post->user_id = 1; $post->post_content = $_POST['caption']; $post->save(FALSE); $image = new Images(); $image->created_at = time(); $image->updated_at = time(); $image->post_id = $post->post_id; $image->created_by = 1; $image->img_url = $_POST['image_standard_url']; $image->status = 0; $image->save(FALSE); } echo CJSON::encode(array('message' => 'success')); }
public function uploadImages() { if ($this->validate()) { $transformation = new Transformation(); $imagine = new Imagine(); //$randHeight = function() { //return rand(250, 330); //}; foreach ($this->imageFiles as $file) { /* @var $file \yii\web\UploadedFile */ $imageRandName = Yii::$app->security->generateRandomString(12); $fullImagePath = self::FULL_IMAGES_PATH . $imageRandName . '.' . $file->extension; $file->saveAs($fullImagePath); $imgSizeReduct = function ($side = 'width') use($fullImagePath) { $size = getimagesize($fullImagePath); if ($side === 'width') { return $size[0] / self::THUMB_REDUCTION; } if ($side === 'height') { return $size[1] / self::THUMB_REDUCTION; } }; $transformation->thumbnail(new Box($imgSizeReduct(), $imgSizeReduct('height')))->save(Yii::getAlias('@webroot/' . self::THUMBS_IMAGES_PATH . $imageRandName . '.' . $file->extension)); $transformation->apply($imagine->open(Yii::getAlias('@webroot/' . self::FULL_IMAGES_PATH . $imageRandName . '.' . $file->extension))); $images = new Images(); $images->name = $imageRandName . '.' . $file->extension; $images->alt = $this->alt; if (!$images->save()) { Yii::$app->session->addFlash('danger', 'Image not saved into data base!'); return false; } } Yii::$app->session->addFlash('success', 'Image uploaded successfully'); return true; } Yii::$app->session->addFlash('danger', 'Incorrect data'); return false; }
public function guardar() { $nombrearchivo = $_FILES["imagen"]['name']; if ($nombrearchivo != "") { if ($ext = explode('.', $nombrearchivo)) { $nombresinext = reset($ext); $ext = '.' . end($ext); } else { $ext = NULL; } if (!is_dir(APP_IMGS)) { mkdir(APP_IMGS . '/', 0777, true); } $path = APP_IMGS . '/'; $archivo = Upload::factory("imagen", 'file'); $archivo->setPath($path); $archivo->setExtensions(array('jpg', 'jpeg', 'png')); //le asignamos las extensiones a permitir $archivo->setMaxSize('10485760'); //le asignamos el tamaño maximo del archivo $archivo->overwrite($nombresinext, true); //fijamos que pueda sobreescribir el requisito si lo actualiza*/ if ($archivo->isUploaded()) { $archivo->save($nombresinext); $images = new Images(); $images->direc_fisica = APP_IMGSPUBLIC . $nombresinext . $ext; $images->direc_acortada = ''; $images->time = date('Y-m-d h:m'); $images->save(); Flash::valid('Guardado exitosamente'); } else { Flash::warning('No se ha Podido Subir la imagen'); } } Redirect::to('/'); }
public function post_upload() { $input = Input::all(); $rules = array('file' => 'image|max:3000'); $messages = array('image' => 'Todos los archivos deben ser imagenes', 'max' => 'Las imagenes deben ser de menos de 3Mb'); $validation = Validator::make($input, $rules, $messages); if ($validation->fails()) { return Response::make($validation)->withErrors($validation); } $id = Input::get('art_id'); $misc_id = Input::get('misc_id'); $file = Input::file('file'); $images = new Images(); $images->misc_id = $misc_id; if (file_exists('images/items/' . $id . '/' . $file->getClientOriginalName())) { //guardamos la imagen en public/imgs con el nombre original $i = 0; //indice para el while //separamos el nombre de la img y la extensión $info = explode(".", $file->getClientOriginalName()); //asignamos de nuevo el nombre de la imagen completo $miImg = $file->getClientOriginalName(); //mientras el archivo exista iteramos y aumentamos i while (file_exists('images/items/' . $id . '/' . $miImg)) { $i++; $miImg = $info[0] . "(" . $i . ")" . "." . $info[1]; } //guardamos la imagen con otro nombre ej foto(1).jpg || foto(2).jpg etc $file->move("images/items/" . $id, $miImg); $blank = Image::make('images/blank.jpg'); $img = Image::make('images/items/' . $id . '/' . $miImg); if ($img->width() > $img->height()) { $img->widen(900); } else { $img->heighten(1200); } $blank->insert($img, 'center')->interlace()->save('images/items/' . $id . '/' . $miImg); if ($miImg != $file->getClientOriginalName()) { $images->image = $id . '/' . $miImg; } } else { $file->move("images/items/" . $id, $file->getClientOriginalName()); $blank = Image::make('images/blank.jpg'); $img = Image::make('images/items/' . $id . '/' . $file->getClientOriginalName()); if ($img->width() > $img->height()) { $img->widen(900); } else { $img->heighten(1200); } $blank->insert($img, 'center')->interlace()->save('images/items/' . $id . '/' . $file->getClientOriginalName()); $images->image = $id . '/' . $file->getClientOriginalName(); } $images->save(); return Response::json(array('image' => $images->id)); if ($upload_success) { return Response::json('success', 200); } else { return Response::json('error', 400); } }
/** * Generate or regenerate PDF for PO * @param $poId * @param bool $approved */ public static function generatePdf($poId, $approved = false) { // get PO $po = Pos::model()->with('dists', 'decr_details', 'document')->findByPk($poId); // get PO dists $poDists = $po->dists; // get PO details $poDecrDetails = $po->decr_details; // get PO formatting $poFormatting = PoFormatting::model()->findByAttributes(array( 'Project_ID' => $po->document->Project_ID, )); // get Sign_Requested_By user info $signRequestedByUser = Users::model()->with('person')->findByPk($po->Sign_Requested_By); $aproval_detail_list = Audits::getApprovalDetailList($po->Document_ID); // get current vendor info $currentVendor = Vendors::model()->with('client.company.adreses')->findByPk($po->Vendor_ID); $condition = UsersClientList::getClientAdminCondition($currentVendor->client->Client_ID); $vendorAdmin = UsersClientList::model()->with('user.person')->find($condition); // get content for pdf $content = Yii::app()->controller->renderPartial('application.views.po.po_template', array( 'po' => $po, 'poFormatting' => $poFormatting, 'poDecrDetails' => $poDecrDetails, 'poDists' => $poDists, 'currentVendor' => $currentVendor, 'vendorAdmin' => $vendorAdmin, 'signRequestedByUser' => $signRequestedByUser, 'aproval_detail_list' => $aproval_detail_list, 'approved' => $approved, 'paymentTypes' => array( 'OA' => 'On Account', 'CC' => 'Credit Card', 'DP' => 'Deposit', 'CK' => 'Payment Check', 'PC' => 'Petty Cash', ), ), true); $fileName = 'protected/data/generated_po/' . Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf'; Yii::import('ext.html2pdf.HTML2PDF'); $html2pdf = new HTML2PDF('P', 'A4', 'en'); $html2pdf->writeHTML($content);//TO LONG TIME!!!!!! NEEDS OPTIMISATION $html2pdf->Output($fileName, 'F'); // insert or update image image $image = Images::model()->findByAttributes(array( 'Document_ID' => $po->Document_ID, )); if (!$image) { $image = new Images(); } $imageData = addslashes(fread(fopen($fileName,"rb"), filesize($fileName))); $image->Document_ID = $po->Document_ID; $image->Img = $imageData; $image->File_Name = Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf'; $image->Mime_Type = 'application/pdf'; $image->File_Hash = sha1_file($fileName); $image->File_Size = intval(filesize($fileName)); $image->Pages_Count = FileModification::calculatePagesByPath($fileName); $image->save(); if (file_exists($fileName)) { @unlink($fileName); } }
public function testGridFS() { $image = new Images(); $image->name = 'Phalcon'; $success = $image->save('unit-tests/assets/logo.png'); $this->assertTrue($success); $this->assertInstanceOf('MongoId', $image->_id); $firstImageId = $image->_id; $images = Images::find(); $this->assertTrue(is_object($images)); $this->assertEquals(count($images), 1); $this->assertEquals($images[0]->name, 'Phalcon'); $this->assertInstanceOf('MongoGridFSFile', $images[0]->getFile()); }
public static function fileToDatabase($doc_id,$filepath,$pages_count) { // insert or update image image $image = Images::model()->findByAttributes(array( 'Document_ID' => $doc_id, )); if (!$image) { $image = new Images(); } $imageData = addslashes(fread(fopen($filepath,"rb"),filesize($filepath))); $image->Document_ID = $doc_id; $image->Img = $imageData; $image->File_Name = Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf'; $image->Mime_Type = 'application/pdf'; $image->File_Hash = sha1_file($filepath); $image->File_Size = intval(filesize($filepath)); $image->Pages_Count = $pages_count; $image->save(); }
/** * Webhook create product action. * * @return void * * @Route("/add", methods={"POST"}, name="import-product-add") */ public function addAction() { if (isset($_SERVER['HTTP_X_HARAVAN_HMAC_SHA256'])) { $myApp = AppModel::findFirstById(1); $hmac_header = $_SERVER['HTTP_X_HARAVAN_HMAC_SHA256']; $data = file_get_contents('php://input'); $verified = Utils::verify_webhook($data, $hmac_header, $myApp->sharedSecret); if ($verified) { $product = json_decode($data); $cleanData = strip_tags($product->body_html); $myStore = StoreModel::findFirst(['name = :storeName:', 'bind' => ['storeName' => $_SERVER['HTTP_HARAVAN_SHOP_DOMAIN']]]); // Create session information $this->session->get('oauth_token') != "" ? $this->session->get('oauth_token') : $this->session->set('oauth_token', $myStore->accessToken); $this->session->get('shop') != "" ? $this->session->get('shop') : $this->session->set('shop', $myStore->name); $this->session->get('sid') != "" ? $this->session->get('sid') : $this->session->set('sid', $myStore->id); // Get collection id from collect API $haravanCollection = EnHelper::getInstance('haravan', 'import')->getCollectsByProductId($product->id); // if category already mapped to five -> continue, else -> exit $myCategoryMap = CategoryMap::findFirst(['hid = :hid:', 'bind' => ['hid' => $haravanCollection[0]->collection_id]]); if (!$myCategoryMap) { exit; } $myProductQueue = ProductQueue::findFirst(['pid = :pid:', 'bind' => ['pid' => (int) $product->id]]); if ($myProductQueue == false) { $myProductQueue = new ProductQueue(); $myProductQueue->pid = (int) $product->id; $myProductQueue->pdata = json_encode($product, JSON_UNESCAPED_UNICODE); $myProductQueue->status = ProductQueue::STATUS_QUEUE; $myProductQueue->retryCount = 0; $myProductQueue->priority = 1; $myProductQueue->fcid = $myCategoryMap->fid; $myProductQueue->sid = $myStore->id; if ($myProductQueue->create()) { //Push to Beanstalk Queue $queue = $this->getDI()->get('queue'); $queue->choose('haraapp.import'); $addedToQueue = $queue->put([['storeId' => $myStore->id, 'haravanId' => $myCategoryMap->hid, 'haravanProductId' => $product->id], ['priority' => $myProductQueue->priority, 'delay' => 10, 'ttr' => 3600]]); if ($addedToQueue) { error_log($item->hid . ' - added to queue.'); $itemInQueue = $itemInQueue + 1; $itemList[] = $item->hid; } } else { foreach ($myProductQueue->getMessages() as $msg) { error_log($msg); } } } // insert table ADS $myAds = new AdsModel(); $myAds->assign(['uid' => $myStore->uid, 'udid' => "", 'rid' => $product->id, 'cid' => $myCategoryMap->fid, 'title' => $product->title, 'slug' => Utils::slug($product->title), 'description' => $cleanData, 'price' => $product->variants[0]->price, 'instock' => 1, 'cityid' => 0, 'districtid' => 0, 'status' => 1, 'isdeleted' => 0, 'seokeyword' => $product->tags, 'lastpostdate' => time()]); if ($myAds->create()) { $pass = true; // Insert table IMAGES if (isset($product->images)) { foreach ($product->images as $img) { $this->debug($img->src); $response = \Requests::get($img->src); if ($response->status_code == 200) { // Download image to local $filePart = explode('.', $img->filename); $namePart = $filePart[0]; $extPart = $filePart[1]; $path = rtrim($config->global->product->directory, '/\\') . '/' . date('Y') . '/' . date('m') . DIRECTORY_SEPARATOR; $fullPath = $config->global->staticFive . $path; $uploadOK = $filefive->put($path . $namePart . '.' . $extPart, (string) $response->body); // Resise image $myResize = new PhImage($fullPath . $namePart . '.' . $extPart); $orig_width = $myResize->getWidth(); $orig_height = $myResize->getHeight(); $height = $orig_height * 1200 / $orig_width; $mediumHeight = $orig_height * 600 / $orig_width; $smallHeight = $orig_height * 200 / $orig_width; $myResize->resize(1200, $height)->crop(1200, $height)->save($fullPath . $namePart . '.' . $extPart); $myResize->resize(600, $mediumHeight)->crop(600, $mediumHeight)->save($fullPath . $namePart . '-medium' . '.' . $extPart); $myResize->resize(200, $smallHeight)->crop(200, $smallHeight)->save($fullPath . $namePart . '-small' . '.' . $extPart); if ($uploadOK) { error_log("image upload ok"); // Save to db $myImage = new Images(); $myImage->assign(['aid' => $myAds->id, 'name' => $myAds->title, 'path' => $path . $namePart . '.' . $extPart, 'status' => Images::STATUS_ENABLE, 'orderNo' => $img->position]); if ($myImage->save()) { // Update first image to ads table if ($img->position == 1) { $myAds->image = $path . $namePart . '.' . $extPart; if ($myAds->update()) { error_log('Update first image to ads success'); } } } else { error_log("cannot save image!"); } } else { error_log("cannot download image!"); } } else { error_log("cannot get image url!"); } } } $imageName = strlen($myAds->image) > 0 ? $myAds->image : ""; // Save to product_map table $myProduct = new ProductMap(); $myProduct->assign(['sid' => $myStore->id, 'uid' => $myStore->uid, 'hid' => $data['haravanProductId'], 'aid' => $myAds->id, 'cid' => $myAds->cid, 'title' => $myAds->title, 'price' => $myAds->price, 'image' => $imageName, 'slug' => $myAds->slug, 'status' => $myAds->status]); if ($myProduct->create()) { error_log($myProduct->title . ' created success!'); } // Delete queued data. (Production) // $myProductQueue->delete(); } } } else { error_log('Request not from haravan'); } }
public static function createNewFromSessionData($current_upload_file,$client){ if (file_exists($current_upload_file['filepath'])) { // create document $document = new Documents(); $document->Document_Type = $current_upload_file['doctype']; $document->User_ID = Yii::app()->user->userID; $document->Client_ID = Yii::app()->user->clientID; $document->Project_ID = Yii::app()->user->projectID; $document->Created = date("Y-m-d H:i:s"); $document->save(); $new_doc_id=$document->Document_ID; Audits::LogAction($document->Document_ID ,Audits::ACTION_UPLOAD); // insert image $image = new Images(); $imageData = addslashes(fread(fopen($current_upload_file['filepath'],"rb"),filesize($current_upload_file['filepath']))); //$imageData = FileModification::ImageToPdfByFilePath($current_upload_file['filepath']); $image->Document_ID = $document->Document_ID; $image->Img = $imageData; $image->File_Name = $current_upload_file['name']; $image->Mime_Type = $current_upload_file['mimetype']; $image->File_Hash = sha1_file($current_upload_file['filepath']); $image->File_Size = intval(filesize($current_upload_file['filepath'])); $image->Pages_Count = FileModification::calculatePagesByPath($current_upload_file['filepath']); $image->save(); $infile = @file_get_contents($current_upload_file['filepath'], FILE_BINARY); if (($current_upload_file['mimetype'] == 'application/pdf' && $image->findPdfText($infile) == '') || $current_upload_file['mimetype'] != 'application/pdf') { Documents::crateDocumentThumbnail($current_upload_file['filepath'], 'thumbs', $current_upload_file['mimetype'], $document->Document_ID, 80); } // delete file from temporary catalog unlink($current_upload_file['filepath']); } $fedId = trim($current_upload_file['fed_id']); $newCompanyName = trim($current_upload_file['company_name']); // get company info $company = Companies::model()->with('client')->findByAttributes(array( 'Company_Fed_ID' => $fedId, )); // create w9 $W9 = new W9(); $W9->Document_ID = $document->Document_ID; $W9->W9_Owner_ID = Yii::app()->user->clientID; $W9->Creator_ID = Yii::app()->user->userID; $W9->Business_Name = trim($current_upload_file['bus_name']); $W9->Tax_Class = trim($current_upload_file['tax_name']); // get user info $user = Users::model()->with('person')->findByPk(Yii::app()->user->userID); if ($company) { // if company exisits $client = $company->client; //fill created company with dataentry values from session Companies::fillWithSessionDataEntry($company,$current_upload_file); $existingW9 = W9::model()->findByAttributes(array( 'Client_ID' => $client->Client_ID, 'W9_Owner_ID' => Yii::app()->user->clientID, )); if ($existingW9) { $W9->Revision_ID = -1; } else { $W9->Revision_ID = 0; } $vendor = Vendors::model()->findByAttributes(array( 'Client_Client_ID' => Yii::app()->user->clientID, 'Vendor_Client_ID' => $client->Client_ID, )); if (isset($vendor->Active_Relationship) && $vendor->Active_Relationship == Vendors::NOT_ACTIVE_RELATIONSHIP) { $vendor->Active_Relationship = Vendors::ACTIVE_RELATIONSHIP; $vendor->save(); } else if (!$vendor && Yii::app()->user->clientID != 0 && Yii::app()->user->clientID != $client->Client_ID) { $vendor = new Vendors(); $vendor->Vendor_ID_Shortcut = ''; $vendor->Vendor_Client_ID = $client->Client_ID; $vendor->Client_Client_ID = Yii::app()->user->clientID; $vendor->Vendor_Name_Checkprint = ''; $vendor->Vendor_1099 = ''; $vendor->Vendor_Default_GL = ''; $vendor->Vendor_Default_GL_Note = ''; $vendor->Vendor_Note_General = ''; $vendor->save(); } } else { //if company does not exists, create new company $company_model = Companies::model()->findByPk($client->Company_ID); //fill created company with dataentry values from session Companies::fillWithSessionDataEntry($company_model,$current_upload_file); if (Yii::app()->user->clientID != 0) { $vendor = new Vendors(); $vendor->Vendor_ID_Shortcut = ''; $vendor->Vendor_Client_ID = $company_model->Company_ID; $vendor->Client_Client_ID = Yii::app()->user->clientID; $vendor->Vendor_Name_Checkprint = ''; $vendor->Vendor_1099 = ''; $vendor->Vendor_Default_GL = ''; $vendor->Vendor_Default_GL_Note = ''; $vendor->Vendor_Note_General = ''; $vendor->save(); } $W9->Revision_ID = 0; } // save w9 $W9->Client_ID = $client->Client_ID; $W9->save(); return $W9; }
/** * ToDo: need to update and make photo processors use a more condensed version of this * Create Thumbnail from Lightspeed original file. Technically to Web Store, any resized copy of the original * whether larger or smaller is considered a "thumbnail". * @param $intNewWidth * @param $intNewHeight * @return bool|Images */ public function CreateThumb($intNewWidth, $intNewHeight) { // Delete previous thumbbnail if ($this->id) { $objImage = Images::LoadByWidthParent($intNewWidth, $this->id); if ($objImage) { $objImage->Delete(); } } //Get our original file from Lightspeed $strOriginalFile = $this->image_path; $strTempThumbnail = Images::GetImageName($strOriginalFile, $intNewWidth, $intNewHeight, 'temp'); $strNewThumbnail = Images::GetImageName($strOriginalFile, $intNewWidth, $intNewHeight); $strOriginalFileWithPath = Images::GetImagePath($strOriginalFile); $strTempThumbnailWithPath = Images::GetImagePath($strTempThumbnail); $strNewThumbnailWithPath = Images::GetImagePath($strNewThumbnail); $image = Yii::app()->image->load($strOriginalFileWithPath); $image->resize($intNewWidth, $intNewHeight)->quality(_xls_get_conf('IMAGE_QUALITY', '75'))->sharpen(_xls_get_conf('IMAGE_SHARPEN', '20')); if (Images::IsWritablePath($strNewThumbnail)) { if (_xls_get_conf('IMAGE_FORMAT', 'jpg') == 'jpg') { $strSaveFunc = 'imagejpeg'; $strLoadFunc = "imagecreatefromjpeg"; } else { $strSaveFunc = 'imagepng'; $strLoadFunc = "imagecreatefrompng"; } $image->save($strTempThumbnailWithPath, false); $src = $strLoadFunc($strTempThumbnailWithPath); //We've saved the resize, so let's load it and resave it centered $dst_file = $strNewThumbnailWithPath; $dst = imagecreatetruecolor($intNewWidth, $intNewHeight); $colorFill = imagecolorallocate($dst, 255, 255, 255); imagefill($dst, 0, 0, $colorFill); if (_xls_get_conf('IMAGE_FORMAT', 'jpg') == 'png') { imagecolortransparent($dst, $colorFill); } $arrOrigSize = getimagesize($strOriginalFileWithPath); $arrSize = Images::CalculateNewSize($arrOrigSize[0], $arrOrigSize[1], $intNewWidth, $intNewHeight); $intStartX = $intNewWidth / 2 - $arrSize[0] / 2; imagecopymerge($dst, $src, $intStartX, 0, 0, 0, $arrSize[0], $arrSize[1], 100); $strSaveFunc($dst, $dst_file); @unlink($strTempThumbnailWithPath); //We save it, then pass back to do a redir immediately //Make sure we don't have an existing record for whatever reason $objNew = Images::LoadByWidthHeightParent($intNewWidth, $intNewHeight, $this->id); if (!$objNew instanceof Images) { $objNew = new Images(); } $objNew->image_path = $strNewThumbnail; $objNew->parent = $this->id; $objNew->width = $intNewWidth; $objNew->height = $intNewHeight; $objNew->index = $this->index; $objNew->product_id = $this->product_id; try { if (!$objNew->save()) { Yii::log("Thumbnail creation error " . print_r($objNew->getErrors()), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__); } } catch (Exception $objExc) { Yii::log("Thumbnail creation exception " . $objExc, 'error', 'application.' . __CLASS__ . "." . __FUNCTION__); } return $objNew; } else { Yii::log("Directory permissions error attempting to save " . $strNewThumbnail, 'error', 'application.' . __CLASS__ . "." . __FUNCTION__); return false; } }
public function actionUpload($id) { $model = $this->checkOwner($id); $maxImgs = 0; # unlimited $currImgCount = 0; if (issetModule('tariffPlans') && issetModule('paidservices')) { $sql = 'SELECT COUNT(id) FROM {{images}} WHERE id_object = ' . $model->id; $currImgCount = Yii::app()->db->createCommand($sql)->queryScalar(); $userTariffInfo = TariffPlans::getTariffInfoByUserId($model->owner_id); $maxImgs = $userTariffInfo['limitPhotos']; if (Yii::app()->user->checkAccess("backend_access")) { # admin or moderator $maxImgs = 0; } } if ($maxImgs > 0 && $currImgCount >= $maxImgs) { $result['error'] = Yii::t("module_tariffPlans", "You are trying to download more than {num} pictures ( your tariff limit )", array("{num}" => $maxImgs)); $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES); echo $result; Yii::app()->end(); } Yii::import("ext.EAjaxUpload.qqFileUploader"); $allowedExtensions = param('allowedImgExtensions', array('jpg', 'jpeg', 'gif', 'png')); //$sizeLimit = param('maxImgFileSize', 8 * 1024 * 1024); $sizeLimit = Images::getMaxSizeLimit(); $uploader = new qqFileUploader($allowedExtensions, $sizeLimit); $path = Yii::getPathOfAlias('webroot.uploads.objects.' . $model->id . '.' . Images::ORIGINAL_IMG_DIR); $pathMod = Yii::getPathOfAlias('webroot.uploads.objects.' . $model->id . '.' . Images::MODIFIED_IMG_DIR); $oldUMask = umask(0); if (!is_dir($path)) { @mkdir($path, 0777, true); } if (!is_dir($pathMod)) { @mkdir($pathMod, 0777, true); } umask($oldUMask); if (is_writable($path) && is_writable($pathMod)) { touch($path . DIRECTORY_SEPARATOR . 'index.htm'); touch($pathMod . DIRECTORY_SEPARATOR . 'index.htm'); $result = $uploader->handleUpload($path . DIRECTORY_SEPARATOR, false, uniqid()); if (isset($result['success']) && $result['success']) { $resize = new CImageHandler(); if ($resize->load($path . DIRECTORY_SEPARATOR . $result['filename'])) { $resize->thumb(param('maxImageWidth', 1024), param('maxImageHeight', 768), Images::KEEP_PHOTO_PROPORTIONAL)->save(); $image = new Images(); $image->id_object = $model->id; $image->id_owner = $model->owner_id; $image->file_name = $result['filename']; if ($image->save() && $model->hasAttribute('count_img')) { $model->count_img++; $model->update('count_img'); } } else { $result['error'] = 'Wrong image type.'; @unlink($path . DIRECTORY_SEPARATOR . $result['filename']); } } } else { $result['error'] = 'Access denied.'; } // to pass data through iframe you will need to encode all html tags $result = htmlspecialchars(json_encode($result), ENT_NOQUOTES); echo $result; }
private function addListingFromCSV($value, $isZip, $maxSorter, $selectedImportUser) { if (is_array($value)) { $model = new $this->modelName(); $type = !empty($value['type']) ? $value['type'] : Apartment::TYPE_DEFAULT; $priceType = !empty($value['priceType']) ? $value['priceType'] : ''; $objType = !empty($value['objType']) ? $value['objType'] : min(Apartment::getObjTypesArray()); $countryName = !empty($value['countryName']) ? trim($value['countryName']) : null; $regionName = !empty($value['regionName']) ? trim($value['regionName']) : null; $cityName = !empty($value['cityName']) ? trim($value['cityName']) : null; $countryId = $countryInfo = $regionId = $regionInfo = $cityId = $cityInfo = 0; if (issetModule('location')) { if ($countryName) { if (isFree()) { $countryInfo = Country::model()->findByAttributes(array('name_' . Yii::app()->language => $countryName)); } else { Yii::app()->setLanguage($this->defLang); $countryInfo = Country::model()->findByAttributes(array('name_' . Yii::app()->language => $countryName)); Yii::app()->setLanguage($this->currLang); } if ($countryInfo && isset($countryInfo->id)) { $countryId = $countryInfo->id; } } if ($regionName) { if (isFree()) { $regionInfo = Region::model()->findByAttributes(array('name_' . Yii::app()->language => $regionName)); } else { Yii::app()->setLanguage($this->defLang); $regionInfo = Region::model()->findByAttributes(array('name_' . Yii::app()->language => $regionName)); Yii::app()->setLanguage($this->currLang); } if ($regionInfo && isset($regionInfo->id)) { $regionId = $regionInfo->id; } } if ($cityName) { if (isFree()) { $cityInfo = City::model()->findByAttributes(array('name_' . Yii::app()->language => $cityName)); } else { Yii::app()->setLanguage($this->defLang); $cityInfo = City::model()->findByAttributes(array('name_' . Yii::app()->language => $cityName)); Yii::app()->setLanguage($this->currLang); } if ($cityInfo && isset($cityInfo->id)) { $cityId = $cityInfo->id; } } } else { if ($cityName) { Yii::import('application.modules.apartmentCity.models.ApartmentCity'); if (isFree()) { $cityInfo = ApartmentCity::model()->findByAttributes(array('name_' . Yii::app()->language => $cityName)); } else { Yii::app()->setLanguage($this->defLang); $cityInfo = ApartmentCity::model()->findByAttributes(array('name_' . Yii::app()->language => $cityName)); Yii::app()->setLanguage($this->currLang); } if ($cityInfo && isset($cityInfo->id)) { $cityId = $cityInfo->id; } } } // if type for sale - set price type only for sale if ($type == Apartment::TYPE_SALE) { $priceType = Apartment::PRICE_SALE; } $isPricePoa = isset($value['isPricePoa']) ? $value['isPricePoa'] : 0; $price = !empty($value['price']) ? $value['price'] : ''; $priceTo = !empty($value['priceTo']) ? $value['priceTo'] : ''; $numberRooms = !empty($value['numberRooms']) ? $value['numberRooms'] : ''; $floor = !empty($value['floor']) ? $value['floor'] : ''; $floor_total = !empty($value['floorTotal']) ? $value['floorTotal'] : ''; $square = !empty($value['square']) ? $value['square'] : ''; $landSquare = !empty($value['landSquare']) ? $value['landSquare'] : ''; $sleeps = !empty($value['sleeps']) ? $this->deleteChars($value['sleeps']) : ''; if (isFree()) { $title = !empty($value['title']) ? $this->deleteChars($value['title']) : ''; $description = !empty($value['description']) ? $this->deleteChars($value['description']) : ''; $near = !empty($value['near']) ? $this->deleteChars($value['near']) : ''; $address = !empty($value['location']) ? $this->deleteChars($value['location']) : ''; $exchange = !empty($value['exchange']) ? $this->deleteChars($value['exchange']) : ''; } else { if ($this->allLangs) { foreach ($this->i18nMaskFields as $i18nMaskField) { foreach ($this->allLangs as $lang) { $title[$lang->name_iso] = $this->deleteChars($value['title_' . $lang->name_iso]); $description[$lang->name_iso] = $this->deleteChars($value['description_' . $lang->name_iso]); $near[$lang->name_iso] = $this->deleteChars($value['near_' . $lang->name_iso]); $address[$lang->name_iso] = $this->deleteChars($value['location_' . $lang->name_iso]); $exchange[$lang->name_iso] = $this->deleteChars($value['exchange_' . $lang->name_iso]); } } } } $lat = !empty($value['lat']) ? $value['lat'] : ''; $lng = !empty($value['lng']) ? $value['lng'] : ''; // references $adRef = array(); $adRef['bathroom'] = !empty($value['bathroom']) ? explode($this->separatorElem, $value['bathroom']) : null; $adRef['safety'] = !empty($value['safety']) ? explode($this->separatorElem, $value['safety']) : null; $adRef['comfort'] = !empty($value['comfort']) ? explode($this->separatorElem, $value['comfort']) : null; $adRef['kitchen'] = !empty($value['kitchen']) ? explode($this->separatorElem, $value['kitchen']) : null; $adRef['employment'] = !empty($value['employment']) ? explode($this->separatorElem, $value['employment']) : null; $adRef['entertainment'] = !empty($value['entertainment']) ? explode($this->separatorElem, $value['entertainment']) : null; $adRef['services'] = !empty($value['services']) ? explode($this->separatorElem, $value['services']) : null; $adRef['terms'] = !empty($value['terms']) ? explode($this->separatorElem, $value['terms']) : null; $photos = !empty($value['photos']) ? explode($this->separatorElem, $value['photos']) : null; // insert into apartments table if (isFree()) { $sql = 'INSERT INTO {{apartment}} (type, obj_type_id, loc_country, loc_region, loc_city, city_id, date_updated, date_created, activity_always, is_price_poa, price, price_to, num_of_rooms, floor, floor_total, square, land_square, window_to, title_' . Yii::app()->language . ', description_' . Yii::app()->language . ', description_near_' . Yii::app()->language . ', exchange_to_' . Yii::app()->language . ', living_conditions, services, address_' . Yii::app()->language . ', berths, active, lat, lng, rating, is_special_offer, is_free_to, price_type, sorter, owner_active, owner_id) VALUES (:type, :objType, :locCountryId, :locRegionId, :locCityId, :cityId, NOW(), NOW(), :activityAlways, :isPricePoa, :price, :priceTo,:numberRooms, :floor, :floorTotal, :square, :landSquare, :windowTo, :title, :description, :descriptionNear, :exchangeTo, :livingConditions, :services, :address, :berths, :active, :lat, :lng, :rating, "", "", :priceType, :maxSorter, :ownerActive, :ownerId) '; $command = Yii::app()->db->createCommand($sql); $command->bindValue(":type", $type, PDO::PARAM_INT); $command->bindValue(":objType", $objType, PDO::PARAM_INT); $command->bindValue(":locCountryId", $countryId, PDO::PARAM_INT); $command->bindValue(":locRegionId", $regionId, PDO::PARAM_INT); $command->bindValue(":locCityId", $cityId, PDO::PARAM_INT); $command->bindValue(":cityId", $cityId, PDO::PARAM_INT); $command->bindValue(":activityAlways", 1, PDO::PARAM_INT); $command->bindValue(":isPricePoa", $isPricePoa, PDO::PARAM_INT); $command->bindValue(":price", $price, PDO::PARAM_STR); $command->bindValue(":priceTo", $priceTo, PDO::PARAM_STR); $command->bindValue(":numberRooms", $numberRooms, PDO::PARAM_INT); $command->bindValue(":floor", $floor, PDO::PARAM_INT); $command->bindValue(":floorTotal", $floor_total, PDO::PARAM_INT); $command->bindValue(":square", $square, PDO::PARAM_INT); $command->bindValue(":landSquare", $landSquare, PDO::PARAM_INT); $command->bindValue(":windowTo", 0, PDO::PARAM_INT); $command->bindValue(":title", $title, PDO::PARAM_STR); $command->bindValue(":description", $description, PDO::PARAM_STR); $command->bindValue(":descriptionNear", $near, PDO::PARAM_STR); $command->bindValue(":exchangeTo", $exchange, PDO::PARAM_STR); $command->bindValue(":livingConditions", 0, PDO::PARAM_INT); $command->bindValue(":services", 0, PDO::PARAM_INT); $command->bindValue(":address", $address, PDO::PARAM_STR); $command->bindValue(":berths", $sleeps, PDO::PARAM_STR); $command->bindValue(":active", 0, PDO::PARAM_INT); $command->bindValue(":lat", $lat, PDO::PARAM_STR); $command->bindValue(":lng", $lng, PDO::PARAM_STR); $command->bindValue(":rating", 0, PDO::PARAM_INT); $command->bindValue(":priceType", $priceType, PDO::PARAM_INT); $command->bindValue(":maxSorter", $maxSorter, PDO::PARAM_INT); $command->bindValue(":ownerActive", 1, PDO::PARAM_INT); $command->bindValue(":ownerId", $selectedImportUser, PDO::PARAM_INT); $command->execute(); $lastId = Yii::app()->db->getLastInsertID(); } else { $fieldsSQL = $placeholdersSQL = $valuesSQL = array(); if ($this->allLangs) { foreach ($this->allLangs as $lang) { $fieldsSQL[] = 'title_' . $lang->name_iso; $fieldsSQL[] = 'description_' . $lang->name_iso; $fieldsSQL[] = 'description_near_' . $lang->name_iso; $fieldsSQL[] = 'address_' . $lang->name_iso; $fieldsSQL[] = 'exchange_to_' . $lang->name_iso; $placeholdersSQL[] = ':title_' . $lang->name_iso; $placeholdersSQL[] = ':description_' . $lang->name_iso; $placeholdersSQL[] = ':description_near_' . $lang->name_iso; $placeholdersSQL[] = ':address_' . $lang->name_iso; $placeholdersSQL[] = ':exchange_to_' . $lang->name_iso; $valuesSQL[':title_' . $lang->name_iso] = $this->deleteChars($title[$lang->name_iso]); $valuesSQL[':description_' . $lang->name_iso] = $this->deleteChars($description[$lang->name_iso]); $valuesSQL[':description_near_' . $lang->name_iso] = $this->deleteChars($near[$lang->name_iso]); $valuesSQL[':address_' . $lang->name_iso] = $this->deleteChars($address[$lang->name_iso]); $valuesSQL[':exchange_to_' . $lang->name_iso] = $this->deleteChars($exchange[$lang->name_iso]); } } $sql = 'INSERT INTO {{apartment}} ( type, obj_type_id, loc_country, loc_region, loc_city, city_id, date_updated, date_created, activity_always, is_price_poa, price, price_to, num_of_rooms, floor, floor_total, square, land_square, window_to, living_conditions, services, berths, active, lat, lng, rating, is_special_offer, is_free_to, price_type, sorter, owner_active, owner_id, ' . implode(", ", $fieldsSQL) . ' ) VALUES ( :type, :objType, :locCountryId, :locRegionId, :locCityId, :cityId, NOW(), NOW(), :activityAlways, :isPricePoa, :price, :priceTo,:numberRooms, :floor, :floorTotal, :square, :landSquare, :windowTo, :livingConditions, :services, :berths, :active, :lat, :lng, :rating, "", "", :priceType, :maxSorter, :ownerActive, :ownerId, ' . implode(", ", $placeholdersSQL) . ' ) '; $command = Yii::app()->db->createCommand($sql); $command->bindValue(":type", $type, PDO::PARAM_INT); $command->bindValue(":objType", $objType, PDO::PARAM_INT); $command->bindValue(":locCountryId", $countryId, PDO::PARAM_INT); $command->bindValue(":locRegionId", $regionId, PDO::PARAM_INT); $command->bindValue(":locCityId", $cityId, PDO::PARAM_INT); $command->bindValue(":cityId", $cityId, PDO::PARAM_INT); $command->bindValue(":activityAlways", 1, PDO::PARAM_INT); $command->bindValue(":isPricePoa", $isPricePoa, PDO::PARAM_INT); $command->bindValue(":price", $price, PDO::PARAM_STR); $command->bindValue(":priceTo", $priceTo, PDO::PARAM_STR); $command->bindValue(":numberRooms", $numberRooms, PDO::PARAM_INT); $command->bindValue(":floor", $floor, PDO::PARAM_INT); $command->bindValue(":floorTotal", $floor_total, PDO::PARAM_INT); $command->bindValue(":square", $square, PDO::PARAM_INT); $command->bindValue(":landSquare", $landSquare, PDO::PARAM_INT); $command->bindValue(":windowTo", 0, PDO::PARAM_INT); $command->bindValue(":livingConditions", 0, PDO::PARAM_INT); $command->bindValue(":services", 0, PDO::PARAM_INT); $command->bindValue(":berths", $sleeps, PDO::PARAM_STR); $command->bindValue(":active", 0, PDO::PARAM_INT); $command->bindValue(":lat", $lat, PDO::PARAM_STR); $command->bindValue(":lng", $lng, PDO::PARAM_STR); $command->bindValue(":rating", 0, PDO::PARAM_INT); $command->bindValue(":priceType", $priceType, PDO::PARAM_INT); $command->bindValue(":maxSorter", $maxSorter, PDO::PARAM_INT); $command->bindValue(":ownerActive", 1, PDO::PARAM_INT); $command->bindValue(":ownerId", $selectedImportUser, PDO::PARAM_INT); foreach ($valuesSQL as $name => $value) { $command->bindValue($name, $value, PDO::PARAM_STR); } $command->execute(); $lastId = Yii::app()->db->getLastInsertID(); } // insert references foreach ($adRef as $key => $value) { switch ($key) { case 'comfort': $refId = 1; break; case 'bathroom': $refId = 2; break; case 'kitchen': $refId = 3; break; case 'employment': $refId = 4; break; case 'safety': $refId = 5; break; case 'entertainment': $refId = 7; break; case 'terms': $refId = 9; break; case 'services': $refId = 10; break; } if (is_array($value) && count($value) > 0) { foreach ($value as $item) { // get reference id by name if (isFree()) { //$sql = "SELECT id FROM {{apartment_reference_values}} WHERE title_" . Yii::app()->language . " = '" . $item . "' AND reference_category_id = '" . $refId . "'"; //$valId = Yii::app()->db->createCommand($sql)->queryRow(); $valId = Yii::app()->db->createCommand()->select('id')->from('{{apartment_reference_values}}')->where('title_' . Yii::app()->language . ' = :title AND reference_category_id = :catId', array(':title' => $item, ':catId' => $refId))->queryRow(); } else { Yii::app()->setLanguage($this->defLang); //$sql = "SELECT id FROM {{apartment_reference_values}} WHERE title_" . Yii::app()->language . " = '" . $item . "' AND reference_category_id = '" . $refId . "'"; //$valId = Yii::app()->db->createCommand($sql)->queryRow(); $valId = Yii::app()->db->createCommand()->select('id')->from('{{apartment_reference_values}}')->where('title_' . Yii::app()->language . ' = :title AND reference_category_id = :catId', array(':title' => $item, ':catId' => $refId))->queryRow(); Yii::app()->setLanguage($this->currLang); } if (isset($valId['id']) && !empty($valId['id'])) { $sql = 'INSERT INTO {{apartment_reference}} (reference_id, reference_value_id, apartment_id) VALUES (:refId, :refValId, :apId) '; $command = Yii::app()->db->createCommand($sql); $command->bindValue(":refId", $refId, PDO::PARAM_INT); $command->bindValue(":refValId", $valId['id'], PDO::PARAM_INT); $command->bindValue(":apId", $lastId, PDO::PARAM_INT); $command->execute(); } } } } // get and upload photos if (is_array($photos) && count($photos) > 0) { $arrFiles = $arrImgs = array(); $IecsvFiles = array(); foreach ($photos as $key => $item) { if (!$isZip) { if (stristr($item, "http")) { $pathParts = pathinfo($item); $file = $pathParts['basename']; $fileExt = $pathParts['extension']; $photoPath = $model->csvPath . DIRECTORY_SEPARATOR . $file; // get file by cUrl if (function_exists('curl_version')) { $ch = curl_init(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $item); $fp = fopen($photoPath, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); } else { // no CUrl, try differently file_put_contents($photoPath, file_get_contents($item)); } // reset file name - remove host. only filename and extension. $item = $file; } } else { // image from zip arhive $photoPath = $model->csvPath . DIRECTORY_SEPARATOR . $item; } if (file_exists($photoPath)) { $IecsvFiles[$key]['name'] = $item; $IecsvFiles[$key]['tmp_name'] = $photoPath; } } if (count($IecsvFiles) > 0) { $apartment = Apartment::model()->findByPk($lastId); $path = Yii::getPathOfAlias('webroot.uploads.objects.' . $apartment->id . '.' . Images::ORIGINAL_IMG_DIR); $pathMod = Yii::getPathOfAlias('webroot.uploads.objects.' . $apartment->id . '.' . Images::MODIFIED_IMG_DIR); $oldUMask = umask(0); if (!is_dir($path)) { @mkdir($path, 0777, true); } if (!is_dir($pathMod)) { @mkdir($pathMod, 0777, true); } umask($oldUMask); $result['error'] = ''; if (is_writable($path) && is_writable($pathMod)) { touch($path . DIRECTORY_SEPARATOR . 'index.htm'); touch($pathMod . DIRECTORY_SEPARATOR . 'index.htm'); foreach ($IecsvFiles as $IecsvFile) { if (copy($model->csvPath . DIRECTORY_SEPARATOR . $IecsvFile['name'], $path . DIRECTORY_SEPARATOR . $IecsvFile['name'])) { $resize = new CImageHandler(); if ($resize->load($path . DIRECTORY_SEPARATOR . $IecsvFile['name'])) { $resize->thumb(param('maxImageWidth', 1024), param('maxImageHeight', 768), Images::KEEP_PHOTO_PROPORTIONAL)->save(); $image = new Images(); $image->id_object = $apartment->id; $image->id_owner = $apartment->owner_id; $image->file_name = $IecsvFile['name']; $image->save(); } } else { $result['error'] = 'No copy'; } } } else { $result['error'] = 'Access denied.'; } } } } }
public static function addImage($filePath, $objectId, $isMain, $ownerId) { $path = Yii::getPathOfAlias('webroot.uploads.objects.' . $objectId . '.' . Images::ORIGINAL_IMG_DIR); $pathMod = Yii::getPathOfAlias('webroot.uploads.objects.' . $objectId . '.' . Images::MODIFIED_IMG_DIR); $oldUMask = umask(0); if (!is_dir($path)) { @mkdir($path, 0777, true); } if (!is_dir($pathMod)) { @mkdir($pathMod, 0777, true); } umask($oldUMask); if (is_writable($path) && is_writable($pathMod)) { touch($path . DIRECTORY_SEPARATOR . 'index.htm'); touch($pathMod . DIRECTORY_SEPARATOR . 'index.htm'); $ext = $ext = pathinfo($filePath, PATHINFO_EXTENSION); $mewFName = md5($filePath) . '.' . $ext; $newFilePath = $path . DIRECTORY_SEPARATOR . $mewFName; $resize = new CImageHandler(); echo $filePath . '<br/>'; if ($resize->load($filePath)) { $resize->thumb(param('maxImageWidth', 1024), param('maxImageHeight', 768), Images::KEEP_PHOTO_PROPORTIONAL)->save($newFilePath); $image = new Images(); $image->id_object = $objectId; $image->id_owner = $ownerId; $image->is_main = $isMain; $image->file_name = $mewFName; $image->save(); } else { echo $newFilePath . ': Wrong image type.<br/>'; @unlink($newFilePath); } } }
/** * Attached event for anytime a product photo is uploaded * @param $event * @return bool */ public function onUploadPhoto($event) { if (!isset($_SERVER['amazon_key'])) { Yii::log("Attempted Cloud transaction but amazon_key not set", 'error', 'application.' . __CLASS__ . "." . __FUNCTION__); return true; } $this->init(); //We were passed these by the CEventPhoto class $objProduct = $event->objProduct; $intSequence = $event->intSequence; //Check to see if we have an Image record already $criteria = new CDbCriteria(); $criteria->AddCondition("`product_id`=:product_id"); $criteria->AddCondition("`index`=:index"); $criteria->AddCondition("`parent`=`id`"); $criteria->params = array(':index' => $intSequence, ':product_id' => $objProduct->id); $objImage = Images::model()->find($criteria); if (!$objImage instanceof Images) { $objImage = new Images(); } $objImage->product_id = $objProduct->id; $objImage->index = $intSequence; //Save image record Yii::trace("saving " . $objImage->strImageName, 'application.' . __CLASS__ . "." . __FUNCTION__); if (!$objImage->save()) { Yii::log("Error saving image " . print_r($objImage->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__); return false; } $objImage->parent = $objImage->id; //Assign parent to self $objImage->save(); //Update product record with imageid if this is a primary if ($intSequence == 0) { $objProduct->image_id = $objImage->id; if (!$objProduct->save()) { Yii::log("Error updating product " . print_r($objProduct->getErrors(), true), 'error', 'application.' . __CLASS__ . "." . __FUNCTION__); return false; } } $this->updateCloudId($event, $objImage->id); return true; }
/** * Generate or regenerate PDF for AP * @param $apId * @param bool $approved * @deprecated since 26.05.2015 * */ public static function generatePdf($apId, $approved = false) { // get AP $ap = Aps::model()->with('dists', 'document', 'ck_req_detail')->findByPk($apId); $ckReqDet = $ap->ck_req_detail; // get PO dists $apDists = $ap->dists; // get PO formatting $poFormatting = PoFormatting::model()->findByAttributes(array( 'Project_ID' => $ap->document->Project_ID, )); // get Sign_Requested_By user info $signRequestedByUser = Users::model()->with('person')->findByPk($ckReqDet->Sign_Requested_By); $aproval_detail_list = Audits::getApprovalDetailList($ap->Document_ID); // get current vendor info $currentVendor = Vendors::model()->with('client.company.adreses')->findByPk($ap->Vendor_ID); $condition = UsersClientList::getClientAdminCondition($currentVendor->client->Client_ID); $vendorAdmin = UsersClientList::model()->with('user.person')->find($condition); // get content for pdf $content = Yii::app()->controller->renderPartial('application.views.ap.ap_template', array( 'ap' => $ap, 'ckReqDet' => $ckReqDet, 'poFormatting' => $poFormatting, 'apDists' => $apDists, 'currentVendor' => $currentVendor, 'vendorAdmin' => $vendorAdmin, 'signRequestedByUser' => $signRequestedByUser, 'aproval_detail_list' => $aproval_detail_list, 'approved' => $approved, ), true); $fileName = Helper::createDirectory('generated_po'); $fileName = $fileName.'/' . Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf'; Yii::import('ext.html2pdf.HTML2PDF'); $html2pdf = new HTML2PDF('P', 'A4', 'en'); $html2pdf->writeHTML($content); $html2pdf->Output($fileName, 'F'); // insert or update image image $image = Images::model()->findByAttributes(array( 'Document_ID' => $ap->Document_ID, )); if (!$image) { $image = new Images(); } $imageData = addslashes(fread(fopen($fileName,"rb"),filesize($fileName))); $image->Document_ID = $ap->Document_ID; $image->Img = $imageData; $image->File_Name = Yii::app()->user->userID . '-' . date("Y_m_d_H_i_s") . '.pdf'; $image->Mime_Type = 'application/pdf'; $image->File_Hash = sha1_file($fileName); $image->File_Size = intval(filesize($fileName)); $image->Pages_Count = FileModification::calculatePagesByPath($fileName); $image->save(); if (file_exists($fileName)) { @unlink($fileName); } }
/** * This is the default 'index' action that is invoked * when an action is not explicitly requested by users. */ public function actionIndex() { $allsite = file_get_html('http://dnepropetrovsk.dnp.olx.ua/nedvizhimost/arenda-kvartir/dolgosrochnaya-arenda-kvartir/'); $allads = $allsite->find('table[id="offers_table"]/table'); $all_tr = array_reverse($allads); foreach ($all_tr as $index => $article) { $title = $article->find('strong', 0)->plaintext; $link = $article->find('a', 0)->href; if (!empty($link) && $link !== "#") { $add = file_get_html($link); /*price*/ $price = $add->find('div[id=offeractions]/div[1]/div[1]/strong', 0)->plaintext; /*phone*/ $isclasses = $add->find('ul[id=contact_methods]/li', 0)->class; $isclasses_explode = explode(' ', $isclasses); $phone_id = ''; foreach ($isclasses_explode as $index => $lasses) { if (strpos($lasses, "'id':") !== false) { $lasses_explode = explode(':', $lasses); $phone_id = str_replace("'", '', $lasses_explode[count($lasses_explode) - 1]); $phone_id = str_replace(",", '', $phone_id); } } /*get contact - get to http://dnepropetrovsk.dnp.olx.ua/ajax/misc/contact/phone/{ID}/*/ $ch = curl_init(); // //GET запрос указывается в строке URL curl_setopt($ch, CURLOPT_URL, 'http://dnepropetrovsk.dnp.olx.ua/ajax/misc/contact/phone/' . $phone_id . '/'); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_USERAGENT, 'Olx getter'); $data = curl_exec($ch); curl_close($ch); $phone = json_decode($data)->value; /*description*/ $description = $add->find('div[id=textContent]/p[class=pding10 lheight20 large]', 0)->plaintext; /*author name */ $author = $add->find('div[id=offeractions]/span[class=block color-5 brkword xx-large]', 0)->plaintext; $search_by_link = Ads::model()->findByAttributes(array('link' => $link)); if (!$search_by_link) { $ads = new Ads(); $ads->title = $title; $ads->description = $description; $ads->link = $link; $ads->author = $author; $ads->phone = $phone; $ads->price = $price; $ads->time_create = time(); $ads->read_status = 0; if ($ads->save()) { foreach ($add->find('div[id=offerdescription]/img') as $index => $im) { $images = new Images(); $images->ads_id = $ads->id; $images->link = $im->src; $images->save(); } } } // else break; } } }
public static function writeToBase($path_to_dir,$filename,$mime,$docId){ $image = Images::model()->findByAttributes(array( 'Document_ID' => $docId, )); if(!$image) { $image= new Images(); $image->Document_ID=$docId; } $path= $path_to_dir.'/'.$filename; $imageData = addslashes(fread(fopen($path,"rb"),filesize($path))); $image->Img = $imageData; $image->File_Name = $filename; $image->Mime_Type = $mime; $image->File_Hash = sha1_file($path); $image->File_Size = intval(filesize($path)); $image->Pages_Count = FileModification::calculatePagesByPath($path); $image->save(); unlink($path); $result['path_to_dir']=$path_to_dir; $result['file_name']=$filename; $result['mime']=$mime; }