public function revertFile($file) { if ($f = $this->getFile($file)) { if ($f['parent'] && $this->parent_theme_id) { $this->getParentTheme()->revertFile($file); return; } else { waFiles::copy($this->path_original . '/' . $file, $this->path . '/' . $file); } $this->setFiles(array($file => array('modified' => 0))); $this->save(); } }
/** * @param array $options * @return shopProduct * @throws waException */ public function duplicate($options = array()) { if (!$this->checkRights()) { throw new waRightsException('Access denied'); } $data = $this->data; $skip = array('id', 'create_datetime', 'id_1c', 'rating', 'rating_count', 'total_sales', 'image_id', 'contact_id', 'ext', 'count', 'sku_count'); foreach ($skip as $field) { if (isset($data[$field])) { unset($data[$field]); } } $duplicate = new shopProduct(); $this->getStorage(null); $sku_files = array(); $sku_images = array(); $ignore_select = true; foreach (self::$data_storages as $key => $i) { $raw = $this->getStorage($key)->getData($this); switch ($key) { case 'features_selectable': $storage_data = array(); if (!$ignore_select) { if ($this->sku_type == shopProductModel::SKU_TYPE_SELECTABLE) { if (!is_array($raw)) { $raw = array(); } foreach ($raw as $id => $f) { if (!empty($f['selected'])) { foreach ($f['values'] as $value_id => &$value) { if (!empty($value['selected'])) { $value = array('id' => $value_id); } else { unset($f['values'][$value_id]); } } $storage_data[$id] = $f; } } } } break; case 'skus': $storage_data = array(); $i = 0; foreach ($raw as $sku_id => $sku) { if (!empty($sku['virtual']) || $ignore_select) { if ($file_path = shopProductSkusModel::getPath($sku)) { $sku_files[$sku['id']] = array('file_name' => $sku['file_name'], 'file_description' => $sku['file_description'], 'file_size' => $sku['file_size'], 'file_path' => $file_path); } if (!empty($sku['image_id'])) { $sku_images[$sku['id']] = $sku['image_id']; } foreach (array('id', 'id_1c', 'product_id', 'image_id', 'file_name', 'file_size', 'file_description') as $field) { if (isset($sku[$field])) { unset($sku[$field]); } } $storage_data[--$i] = $sku; } } break; case 'tags': $storage_data = array_values($raw); break; case 'categories': $storage_data = array_keys($raw); break; default: $storage_data = $raw; break; } $duplicate->{$key} = $storage_data; } $counter = 0; $data['url'] = shopHelper::genUniqueUrl($this->url, $this->model, $counter); $data['name'] = $this->name . sprintf('(%d)', $counter ? $counter : 1); $duplicate->save($data); $product_id = $duplicate->getId(); $sku_map = array_combine(array_keys($this->skus), array_keys($duplicate->skus)); $config = wa('shop')->getConfig(); $image_thumbs_on_demand = $config->getOption('image_thumbs_on_demand'); /** * @var shopConfig $config */ if ($this->pages) { $product_pages_model = new shopProductPagesModel(); foreach ($this->pages as $page) { unset($page['id']); unset($page['create_time']); unset($page['update_datetime']); unset($page['create_contact_id']); $page['product_id'] = $duplicate->getId(); $product_pages_model->add($page); } } #duplicate images $product_skus_model = new shopProductSkusModel(); $images_model = new shopProductImagesModel(); $images = $images_model->getByField('product_id', $this->getId(), $images_model->getTableId()); $callback = create_function('$a, $b', 'return (max(-1, min(1, $a["sort"] - $b["sort"])));'); usort($images, $callback); foreach ($images as $id => $image) { $source_path = shopImage::getPath($image); $original_file = shopImage::getOriginalPath($image); $image['product_id'] = $duplicate->getId(); if ($sku_id = array_search($image['id'], $sku_images)) { $sku_id = $sku_map[$sku_id]; } unset($image['id']); try { if ($image['id'] = $images_model->add($image, $id == $this->image_id)) { waFiles::copy($source_path, shopImage::getPath($image)); if (file_exists($original_file)) { waFiles::copy($original_file, shopImage::getOriginalPath($image)); } if ($sku_id) { $product_skus_model->updateById($sku_id, array('image_id' => $image['id'])); } if (!$image_thumbs_on_demand) { shopImage::generateThumbs($image, $config->getImageSizes()); //TODO use dummy copy with rename files } } } catch (waDbException $ex) { //just ignore it waLog::log('Error during copy product: ' . $ex->getMessage(), 'shop.log'); } catch (waException $ex) { if (!empty($image['id'])) { $images_model->deleteById($image['id']); } waLog::log('Error during copy product: ' . $ex->getMessage(), 'shop.log'); } } foreach ($sku_files as $sku_id => $data) { $source_path = $data['file_path']; unset($data['file_path']); $sku_id = $sku_map[$sku_id]; $sku = array_merge($duplicate->skus[$sku_id], $data); $product_skus_model->updateById($sku_id, $data); $target_path = shopProductSkusModel::getPath($sku); try { waFiles::copy($source_path, $target_path); } catch (waException $ex) { $data = array('file_name' => '', 'file_description' => '', 'file_size' => 0); $product_skus_model->updateById($sku_id, $data); print $ex->getMessage(); } } $product_features_model = new shopProductFeaturesModel(); $skus_features = $product_features_model->getSkuFeatures($this->id); $skus_features_data = array(); foreach ($skus_features as $sku_id => $features) { $sku_id = $sku_map[$sku_id]; foreach ($features as $feature_id => $feature_value_id) { $skus_features_data[] = compact('product_id', 'sku_id', 'feature_id', 'feature_value_id'); } } if ($skus_features_data) { $product_features_model->multipleInsert($skus_features_data); } if ($this->sku_type == shopProductModel::SKU_TYPE_SELECTABLE) { $product_features_selectable_model = new shopProductFeaturesSelectableModel(); if ($features_selectable = $product_features_selectable_model->getByField('product_id', $this->id, true)) { foreach ($features_selectable as &$feature_selectable) { $feature_selectable['product_id'] = $product_id; } unset($feature_selectable); $product_features_selectable_model->multipleInsert($features_selectable); } } $product_services_model = new shopProductServicesModel(); if ($services = $product_services_model->getByField('product_id', $this->id, true)) { foreach ($services as &$service) { unset($service['id']); $service['product_id'] = $product_id; $service['sku_id'] = ifset($sku_map[$service['sku_id']]); unset($service); } $product_services_model->multipleInsert($services); } $product_related_model = new shopProductRelatedModel(); if ($related = $product_related_model->getByField('product_id', $this->id, true)) { foreach ($related as &$row) { $row['product_id'] = $product_id; } unset($row); $product_related_model->multipleInsert($related); } $params = array('product' => &$this, 'duplicate' => &$duplicate); /** * @wa-event product_duplicate */ wa()->event('product_duplicate', $params); return $duplicate; }
/** * Merge given contacts into master contact, save, send merge event, then delete slaves. * * !!! Probably should move it into something like contactsHelper * * @param array $merge_ids list of contact ids * @param int $master_id contact id to merge others into * @return array */ public static function merge($merge_ids, $master_id) { $merge_ids[] = $master_id; // List of contacts to merge $collection = new contactsCollection('id/' . implode(',', $merge_ids)); $contacts_data = $collection->getContacts('*'); // Master contact data if (!$master_id || !isset($contacts_data[$master_id])) { throw new waException('No contact to merge into.'); } $master_data = $contacts_data[$master_id]; unset($contacts_data[$master_id]); $master = new waContact($master_id); $result = array('total_requested' => count($contacts_data) + 1, 'total_merged' => 0, 'error' => '', 'users' => 0); if ($master_data['photo']) { $filename = wa()->getDataPath(waContact::getPhotoDir($master_data['id']) . "{$master_data['photo']}.original.jpg", true, 'contacts'); if (!file_exists($filename)) { $master_data['photo'] = null; } } $data_fields = waContactFields::getAll('enabled'); $check_duplicates = array(); // field_id => true $update_photo = null; // if need to update photo here it is file paths // merge loop foreach ($contacts_data as $id => $info) { if ($info['is_user'] > 0) { $result['users']++; unset($contacts_data[$id]); continue; } foreach ($data_fields as $f => $field) { if (!empty($info[$f])) { if ($field->isMulti()) { $master->add($f, $info[$f]); $check_duplicates[$f] = true; } else { // Field does not allow multiple values. // Set value if no value yet. if (empty($master_data[$f])) { $master[$f] = $master_data[$f] = $info[$f]; } } } } // photo if (!$master_data['photo'] && $info['photo'] && !$update_photo) { $filename_original = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.original.jpg", true, 'contacts'); if (file_exists($filename_original)) { $update_photo = array('original' => $filename_original); $filename_crop = wa()->getDataPath(waContact::getPhotoDir($info['id']) . "{$info['photo']}.jpg", true, 'contacts'); if (file_exists($filename_crop)) { $update_photo['crop'] = $filename_crop; } } } // birthday parts if (!empty($data_fields['birthday'])) { foreach (array('birth_day', 'birth_month', 'birth_year') as $f) { if (empty($master_data[$f]) && !empty($info[$f])) { $master[$f] = $master_data[$f] = $info[$f]; } } } } // Remove duplicates foreach (array_keys($check_duplicates) as $f) { $values = $master[$f]; if (!is_array($values) || count($values) <= 1) { continue; } $unique_values = array(); // md5 => true foreach ($values as $k => $v) { if (is_array($v)) { if (isset($v['value']) && is_string($v['value'])) { $v = $v['value']; } else { unset($v['ext'], $v['status']); ksort($v); $v = serialize($v); } } $hash = md5(mb_strtolower($v)); if (!empty($unique_values[$hash])) { unset($values[$k]); continue; } $unique_values[$hash] = true; } $master[$f] = array_values($values); } // Save master contact $errors = $master->save(array(), 42); // 42 == do not validate anything at all if ($errors) { $errormsg = array(); foreach ($errors as $field => $err) { if (!is_array($err)) { $err = array($err); } foreach ($err as $str) { $errormsg[] = $field . ': ' . $str; } } $result['error'] = implode("\n<br>", $errormsg); return $result; } // Merge categories $category_ids = array(); $ccm = new waContactCategoriesModel(); foreach ($ccm->getContactsCategories($merge_ids) as $cid => $cats) { $category_ids += array_flip($cats); } $category_ids = array_keys($category_ids); $ccm->add($master_id, $category_ids); // update photo if ($update_photo) { $rand = mt_rand(); $path = wa()->getDataPath(waContact::getPhotoDir($master['id']), true, 'contacts', false); // delete old image if (file_exists($path)) { waFiles::delete($path); } waFiles::create($path); $filename = $path . "/" . $rand . ".original.jpg"; waFiles::create($filename); waImage::factory($update_photo['original'])->save($filename, 90); if (!empty($update_photo['crop'])) { $filename = $path . "/" . $rand . ".jpg"; waFiles::create($filename); waImage::factory($update_photo['crop'])->save($filename, 90); } else { waFiles::copy($filename, $path . "/" . $rand . ".jpg"); } $master->save(array('photo' => $rand)); } $result['total_merged'] = count($contacts_data) + 1; $contact_ids = array_keys($contacts_data); // wa_log $log_model = new waLogModel(); $log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id)); // wa_login_log $login_log_model = new waLoginLogModel(); $login_log_model->updateByField('contact_id', $contact_ids, array('contact_id' => $master_id)); // Merge event $params = array('contacts' => $contact_ids, 'id' => $master_data['id']); wa()->event(array('contacts', 'merge'), $params); // Delete all merged contacts $contact_model = new waContactModel(); $contact_model->delete($contact_ids, false); // false == do not trigger event $history_model = new contactsHistoryModel(); foreach ($contact_ids as $contact_id) { $history_model->deleteByField(array('type' => 'add', 'hash' => '/contact/' . $contact_id)); } return $result; }
private function stepImportImage() { /** * @var shopProductImagesModel $model */ static $model; if (!is_array($this->data['map'][self::STAGE_IMAGE]) && $this->data['map'][self::STAGE_IMAGE]) { $this->data['map'][self::STAGE_IMAGE] = array($this->data['map'][self::STAGE_IMAGE]); } if ($file = reset($this->data['map'][self::STAGE_IMAGE])) { if (!$model) { $model = new shopProductImagesModel(); } //TODO store image id & if repeated - skip it $target = 'new'; $u = @parse_url($file); $_is_url = false; if (!$u || !(isset($u['scheme']) && isset($u['host']) && isset($u['path']))) { } elseif (in_array($u['scheme'], array('http', 'https', 'ftp', 'ftps'))) { $_is_url = true; } else { $target = 'skip'; $file = null; $this->error(sprintf('Unsupported file source protocol', $u['scheme'])); } $search = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'ext' => pathinfo($file, PATHINFO_EXTENSION)); try { $name = preg_replace('@[^a-zA-Zа-яА-Я0-9\\._\\-]+@', '', basename(urldecode($file))); if ($_is_url) { $pattern = sprintf('@/(%d)/images/(\\d+)/\\2\\.(\\d+(x\\d+)?)\\.([^\\.]+)$@', $search['product_id']); if (preg_match($pattern, $file, $matches)) { $image = array('product_id' => $matches[1], 'id' => $matches[2], 'ext' => $matches[5]); if (strpos($file, shopImage::getUrl($image, $matches[3])) !== false && $model->getByField($image)) { #skip local file $target = 'skip'; $file = null; } } if ($file) { waFiles::upload($file, $file = wa()->getTempPath('csv/upload/images/' . waLocale::transliterate($name, 'en_US'))); } } elseif ($file) { $file = $this->data['upload_path'] . $file; } if ($file && file_exists($file)) { if ($image = waImage::factory($file)) { $search['original_filename'] = $name; $data = array('product_id' => $this->data['map'][self::STAGE_PRODUCT], 'upload_datetime' => date('Y-m-d H:i:s'), 'width' => $image->width, 'height' => $image->height, 'size' => filesize($file), 'original_filename' => $name, 'ext' => pathinfo($file, PATHINFO_EXTENSION)); if ($exists = $model->getByField($search)) { $data = array_merge($exists, $data); $thumb_dir = shopImage::getThumbsPath($data); $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1); $paths[] = $back_thumb_dir; waFiles::delete($back_thumb_dir); // old backups if (file_exists($thumb_dir)) { if (!(waFiles::move($thumb_dir, $back_thumb_dir) || waFiles::delete($back_thumb_dir)) && !waFiles::delete($thumb_dir)) { throw new waException(_w("Error while rebuild thumbnails")); } } } $image_changed = false; /** * TODO move it code into product core method */ /** * Extend add/update product images * Make extra workup * @event image_upload */ $event = wa()->event('image_upload', $image); if ($event) { foreach ($event as $result) { if ($result) { $image_changed = true; break; } } } if (empty($data['id'])) { $image_id = $data['id'] = $model->add($data); } else { $image_id = $data['id']; $target = 'update'; $model->updateById($image_id, $data); } if (!$image_id) { throw new waException("Database error"); } $image_path = shopImage::getPath($data); if (file_exists($image_path) && !is_writable($image_path) || !file_exists($image_path) && !waFiles::create($image_path)) { $model->deleteById($image_id); throw new waException(sprintf("The insufficient file write permissions for the %s folder.", substr($image_path, strlen($this->getConfig()->getRootPath())))); } if ($image_changed) { $image->save($image_path); /** * @var shopConfig $config */ $config = $this->getConfig(); if ($config->getOption('image_save_original') && ($original_file = shopImage::getOriginalPath($data))) { waFiles::copy($file, $original_file); } } else { waFiles::copy($file, $image_path); } $this->data['processed_count'][self::STAGE_IMAGE][$target]++; } else { $this->error(sprintf('Invalid image file', $file)); } } elseif ($file) { $this->error(sprintf('File %s not found', $file)); $target = 'skip'; $this->data['processed_count'][self::STAGE_IMAGE][$target]++; } else { $this->data['processed_count'][self::STAGE_IMAGE][$target]++; } } catch (Exception $e) { $this->error($e->getMessage()); //TODO skip on repeated error } array_shift($this->data['map'][self::STAGE_IMAGE]); ++$this->data['current'][self::STAGE_IMAGE]; if ($_is_url) { waFiles::delete($file); } } return true; }
<?php $path = wa()->getDataPath('photos', true, 'contacts', false); if (!file_exists($path . './htaccess')) { $path = wa()->getDataPath('photos', true, 'contacts'); waFiles::write($path . '/thumb.php', '<?php $file = realpath(dirname(__FILE__)."/../../../../")."/wa-apps/contacts/lib/config/data/thumb.php"; if (file_exists($file)) { include($file); } else { header("HTTP/1.0 404 Not Found"); } '); waFiles::copy(wa()->getAppPath('lib/config/data/.htaccess', 'contacts'), $path . '/.htaccess'); }
protected function init() { try { $backend = wa()->getEnv() == 'backend'; $profiles = new shopImportexportHelper('yandexmarket'); switch ($this->encoding) { case 'windows-1251': setlocale(LC_CTYPE, 'ru_RU.CP-1251', 'ru_RU.CP1251', 'ru_RU.win'); break; } $this->data['offset'] = array('offers' => 0); $this->data['timestamp'] = time(); $default_export_config = array('zero_stock' => 0, 'compare_price' => 0, 'sku' => 0, 'sku_group' => '', 'hidden_categories' => 0); if ($backend) { $hash = shopImportexportHelper::getCollectionHash(); $profile_config = array('hash' => $hash['hash'], 'domain' => waRequest::post('domain'), 'map' => array(), 'types' => array_filter((array) waRequest::post('types')), 'export' => (array) waRequest::post('export', array()) + $default_export_config, 'company' => waRequest::post('company'), 'company_name' => waRequest::post('company_name'), 'shop' => waRequest::post('shop'), 'lifetime' => waRequest::post('lifetime', 0, waRequest::TYPE_INT), 'utm_source' => waRequest::post('utm_source'), 'utm_medium' => waRequest::post('utm_medium'), 'utm_campaign' => waRequest::post('utm_campaign')); $this->data['map'] = $this->plugin()->map(waRequest::post('map', array()), $profile_config['types']); foreach ($this->data['map'] as $type => $offer_map) { foreach ($offer_map['fields'] as $field => $info) { if (!empty($info['source']) && preg_match('@^\\w+:(.+)$@', $info['source'], $matches) && $matches[1] != '%s') { $profile_config['map'][$type][$field] = $info['source']; } } if (empty($profile_config['map'][$type])) { unset($profile_config['map'][$type]); } } $profile_id = $profiles->setConfig($profile_config); $this->plugin()->getHash($profile_id); } else { $profile_id = waRequest::param('profile_id'); if (!$profile_id || !($profile = $profiles->getConfig($profile_id))) { throw new waException('Profile not found', 404); } $profile_config = $profile['config']; $profile_config['export'] += $default_export_config; $this->data['map'] = $this->plugin()->map($profile_config['map'], $profile_config['types']); foreach ($this->data['map'] as $type => &$offer_map) { foreach ($offer_map['fields'] as $field => &$info) { $info['source'] = ifempty($profile_config['map'][$type][$field], 'skip:'); } unset($offer_map); } } foreach ($this->data['map'] as $type => &$offer_map) { if ($type != 'simple') { $offer_map['fields']['type'] = array('source' => 'value:' . $type, 'attribute' => true); } unset($offer_map); } $feature_model = new shopFeatureModel(); foreach ($this->data['map'] as $type => &$offer_map) { foreach ($offer_map['fields'] as $field => &$info) { if (strpos($field, 'param.') === 0 && isset($info['source'])) { switch (preg_replace('@:.+$@', '', $info['source'])) { case 'feature': if ($feature = $feature_model->getByCode(preg_replace('@^[^:]+:@', '', $info['source']))) { $info['source_name'] = $feature['name']; } break; } } } unset($info); unset($offer_map); } $this->data['hash'] = $profile_config['hash']; if (!isset($this->data['categories'])) { $this->data['categories'] = array(); } $this->data['export'] = $profile_config['export']; $this->data['domain'] = $profile_config['domain']; $this->data['utm'] = array(); foreach (array('utm_source', 'utm_medium', 'utm_campaign') as $field) { if (!empty($profile_config[$field])) { $this->data['utm'][$field] = $profile_config[$field]; } } if ($this->data['utm']) { $this->data['utm'] = http_build_query(array_map('rawurlencode', $this->data['utm'])); } $this->data['types'] = array(); foreach ($profile_config['types'] as $type => $type_map) { $this->data['types'] += array_fill_keys(array_filter(array_map('intval', $type_map)), $type); } $this->initRouting(); $model = new shopCategoryModel(); if (empty($this->data['export']['hidden_categories'])) { $sql = <<<SQL SELECT COUNT(1) as `cnt` FROM shop_category c LEFT JOIN shop_category_routes cr ON (c.id = cr.category_id) WHERE ((cr.route IS NULL) OR (cr.route = s:route)) AND (`c`.`type`=i:type) AND (`c`.`status`=1) SQL; } else { $sql = <<<SQL SELECT COUNT(1) as `cnt` FROM shop_category c LEFT JOIN shop_category_routes cr ON (c.id = cr.category_id) WHERE ((cr.route IS NULL) OR (cr.route = s:route)) AND (`c`.`type`=i:type) SQL; } $params = array('route' => $this->data['domain'], 'type' => shopCategoryModel::TYPE_STATIC); $this->data['count'] = array('category' => (int) $model->query($sql, $params)->fetchField('cnt'), 'product' => $this->getCollection()->count()); $stages = array_keys($this->data['count']); $this->data['current'] = array_fill_keys($stages, 0); $this->data['processed_count'] = array_fill_keys($stages, 0); $this->data['stage'] = reset($stages); $this->data['stage_name'] = $this->getStageName($this->data['stage']); $this->data['memory'] = memory_get_peak_usage(); $this->data['memory_avg'] = memory_get_usage(); if (!class_exists('DOMDocument')) { throw new waException('PHP extension DOM required'); } $this->dom = new DOMDocument("1.0", $this->encoding); $this->dom->encoding = $this->encoding; $this->dom->preserveWhiteSpace = false; $this->dom->formatOutput = true; /** * @var shopConfig $config */ $config = wa('shop')->getConfig(); $xml = <<<XML <?xml version="1.0" encoding="{$this->encoding}"?> <!DOCTYPE yml_catalog SYSTEM "shops.dtd"> <yml_catalog date="%s"> </yml_catalog> XML; $original = shopYandexmarketPlugin::path('shops.dtd'); $target = $this->getTempPath('shops.dtd'); $ft = filesize($target); $fo = filesize($original); if (!file_exists($target) || filesize($target) != filesize($original) && waFiles::delete($target)) { waFiles::copy($original, $target); } $this->dom->loadXML(sprintf($xml, date("Y-m-d H:i"))); $this->dom->lastChild->appendChild($shop = $this->dom->createElement("shop")); $name = ifempty($profile_config['company_name'], $config->getGeneralSettings('name')); $name = str_replace('&', '&', $name); $name = str_replace("'", ''', $name); $this->addDomValue($shop, 'name', $name); $company = str_replace('&', '&', $profile_config['company']); $company = str_replace("'", ''', $company); $this->addDomValue($shop, 'company', $company); $this->addDomValue($shop, 'url', preg_replace('@^https@', 'http', wa()->getRouteUrl('shop/frontend', array(), true))); if ($phone = $config->getGeneralSettings('phone')) { $shop->appendChild($this->dom->createElement('phone', $phone)); } $this->addDomValue($shop, 'platform', 'Shop-Script'); $this->addDomValue($shop, 'version', wa()->getVersion('shop')); $currencies = $this->dom->createElement('currencies'); $model = new shopCurrencyModel(); $this->data['currency'] = array(); $available_currencies = shopYandexmarketPlugin::settingsPrimaryCurrencies(); if (empty($available_currencies)) { throw new waException('Экспорт не может быть выполнен: не задано ни одной валюты, которая могла бы использоваться в качестве основной.'); } unset($available_currencies['auto']); $primary_currency = $this->plugin()->getSettings('primary_currency'); $this->data['default_currency'] = $config->getCurrency(); if (!isset($available_currencies[$primary_currency])) { $primary_currency = $this->data['default_currency']; if (!isset($available_currencies[$primary_currency])) { reset($available_currencies); $primary_currency = key($available_currencies); } } $this->data['primary_currency'] = $primary_currency; $rate = $available_currencies[$primary_currency]['rate']; $available_currencies = $model->getCurrencies(shopYandexmarketPlugin::getConfigParam('currency')); foreach ($available_currencies as $info) { if ($info['rate'] > 0) { $info['rate'] = $info['rate'] / $rate; $this->data['currency'][] = $info['code']; if (abs(round($info['rate'], 4) - $info['rate']) / $info['rate'] > 0.01) { $info['rate'] = 'CB'; } $value = array('id' => $info['code'], 'rate' => $this->format('rate', $info['rate'])); $this->addDomValue($currencies, 'currency', $value); } } $shop->appendChild($currencies); $shop->appendChild($this->dom->createElement('categories')); $fields = array('store' => true, 'pickup' => true, 'delivery' => true, 'deliveryIncluded' => false, 'local_delivery_cost' => '%0.2f', 'adult' => true); foreach ($fields as $field => $include_value) { $value = ifset($profile_config['shop'][$field], ''); if ($value || $value !== '') { if ($include_value) { $value = $include_value === true ? $value : $this->format($field, $value, array('format', $include_value)); $this->addDomValue($shop, $field, $value); } else { $shop->appendChild($this->dom->createElement($field)); } } } $shop->appendChild($this->dom->createElement('offers')); if (!$this->data['currency']) { throw new waException('Не задано ни одной поддерживаемой валюты'); } if (!in_array($this->data['primary_currency'], $this->data['currency'])) { $this->data['primary_currency'] = reset($this->data['currency']); } $this->data['path'] = array('offers' => shopYandexmarketPlugin::path($profile_id . '.xml')); $this->save(); $this->dom = null; $this->loadDom(); } catch (waException $ex) { $this->error($ex->getMessage()); echo json_encode(array('error' => $ex->getMessage())); exit; } }
/** * Copy existing theme * @param string $id * @param array $params * @throws waException * @return waTheme */ public function copy($id = null, $params = array()) { if ($id) { self::verify($id); } else { $id = $this->id; } $target = wa()->getDataPath("themes/{$id}", true, $this->app, false); if (file_exists($target . '/' . self::PATH)) { throw new waException(sprintf(_ws("Theme %s already exists"), $id)); } self::protect($this->app); waFiles::copy($this->path, $target, '/\\.(files\\.md5|cvs|svn|git|php\\d*)$/'); @touch($target . '/' . self::PATH); if ($this->id != $id) { //hack for extended classes $class = get_class($this); /** * @var $instance waTheme */ $instance = new $class($id, $this->app); $instance->init(); $instance->info['id'] = $id; $instance->changed['id'] = true; foreach ($params as $param => $value) { $instance[$param] = $value; } $instance['system'] = false; $instance->save(); return $instance; } else { $this->initPath(); foreach ($params as $param => $value) { $this[$param] = $value; } if ($params) { $this->save(); } return $this; } }
private function reset() { /** * @event reset * * Notify plugins about reset all settings * * @param void * @return void */ wa()->event('reset'); //XXX hardcode $tables = array('shop_page', 'shop_page_params', 'shop_category', 'shop_category_params', 'shop_category_products', 'shop_category_routes', 'shop_product', 'shop_product_params', 'shop_product_features', 'shop_product_features_selectable', 'shop_product_images', 'shop_product_pages', 'shop_product_related', 'shop_product_reviews', 'shop_product_services', 'shop_product_skus', 'shop_product_stocks', 'shop_product_stocks_log', 'shop_search_index', 'shop_search_word', 'shop_tag', 'shop_product_tags', 'shop_set', 'shop_set_products', 'shop_stock', 'shop_feature', 'shop_feature_values_dimension', 'shop_feature_values_double', 'shop_feature_values_text', 'shop_feature_values_varchar', 'shop_feature_values_color', 'shop_feature_values_range', 'shop_type', 'shop_type_features', 'shop_type_services', 'shop_type_upselling', 'shop_service', 'shop_service_variants', 'shop_currency', 'shop_customer', 'shop_cart_items', 'shop_order', 'shop_order_items', 'shop_order_log', 'shop_order_log_params', 'shop_order_params', 'shop_affiliate_transaction', 'shop_checkout_flow', 'shop_notification', 'shop_notification_params', 'shop_coupon', 'shop_discount_by_sum', 'shop_tax', 'shop_tax_regions', 'shop_tax_zip_codes', 'shop_affiliate_transaction', 'shop_importexport'); $model = new waModel(); foreach ($tables as $table) { $exist = false; try { $model->query(sprintf("SELECT * FROM `%s` WHERE 0", $table)); $exist = true; $model->query(sprintf("TRUNCATE `%s`", $table)); } catch (waDbException $ex) { if ($exist) { throw $ex; } } } $sqls = array(); $sqls[] = 'UPDATE`shop_type` SET`count` = 0'; $sqls[] = 'UPDATE`shop_set` SET`count` = 0'; foreach ($sqls as $sql) { $model->query($sql); } $ccm = new waContactCategoryModel(); $ccm->deleteByField('app_id', 'shop'); $app_settings_model = new waAppSettingsModel(); $currency_model = new shopCurrencyModel(); $currency_model->insert(array('code' => 'USD', 'rate' => 1.0, 'sort' => 1), 2); $app_settings_model->set('shop', 'currency', 'USD'); $app_settings_model->set('shop', 'use_product_currency', true); $paths = array(); $paths[] = wa()->getDataPath('products', false, 'shop'); $paths[] = wa()->getDataPath('products', true, 'shop'); $paths[] = wa()->getTempPath(); $config_path = wa()->getConfigPath('shop'); foreach (waFiles::listdir($config_path, true) as $path) { if (!in_array($path, array('plugins.php', '..', '.'))) { $paths[] = $config_path . '/' . $path; } } $paths[] = wa()->getCachePath(null, 'shop'); foreach ($paths as $path) { waFiles::delete($path, true); } $path = wa()->getDataPath('products', true, 'shop'); waFiles::write($path . '/thumb.php', '<?php $file = realpath(dirname(__FILE__)."/../../../../")."/wa-apps/shop/lib/config/data/thumb.php"; if (file_exists($file)) { include($file); } else { header("HTTP/1.0 404 Not Found"); } '); waFiles::copy($this->getConfig()->getAppPath('lib/config/data/.htaccess'), $path . '/.htaccess'); echo json_encode(array('result' => 'ok', 'redirect' => '?action=welcome')); exit; }
<?php $path = wa()->getDataPath(null, true, 'photos'); waFiles::copy($this->getAppPath('lib/config/data/.htaccess'), $path . '/.htaccess'); waFiles::write($path . '/thumb.php', '<?php $file = realpath(dirname(__FILE__)."/../../../")."/wa-apps/photos/lib/config/data/thumb.php"; if (file_exists($file)) { include($file); } else { header("HTTP/1.0 404 Not Found"); } ');
/** * Adds an image to contact. * * @param string $file Path to image file * @throws waException * @return string */ public function setPhoto($file) { if (!file_exists($file)) { throw new waException('file not exists'); } if (!$this->getId()) { throw new waException('Contact not saved!'); } $rand = mt_rand(); $path = wa()->getDataPath(self::getPhotoDir($this->getId()), true, 'contacts'); // delete old image if (file_exists($path)) { waFiles::delete($path); } waFiles::create($path); $filename = $path . "/" . $rand . ".original.jpg"; waFiles::create($filename); waImage::factory($file)->save($filename, 90); waFiles::copy($filename, $path . "/" . $rand . ".jpg"); waContactFields::getStorage('waContactInfoStorage')->set($this, array('photo' => $rand)); return $this->getPhoto(); }
public static function path($file = 'market.xml') { $path = wa()->getDataPath('plugins/yandexmarket/' . $file, false, 'shop', true); if ($file == 'shops.dtd') { $original = dirname(__FILE__) . '/config/' . $file; if (!file_exists($path) || filesize($path) != filesize($original) && waFiles::delete($path)) { waFiles::copy($original, $path); } } return $path; }
protected function createStructure($paths) { foreach ($paths as $path => $content) { if (is_integer($path)) { $path = $content; $content = false; } if (preg_match('@\\.[\\w]+$@', $path)) { $file = $this->path . $path; waFiles::create(dirname($file), true); if (is_array($content)) { waUtils::varExportToFile($content, $file); } elseif ($content && file_exists($content)) { waFiles::copy($content, $file); } else { waFiles::write($file, $content); } } else { waFiles::create($this->path . $path, true); } } }
protected function create($type, $id, $path, $params = array()) { $template_id = 'wapattern'; $template_path = wa()->getConfig()->getPath('plugins') . '/' . $type . '/' . $template_id . '/'; if (!file_exists($path)) { try { $path .= '/'; mkdir($path); // lib mkdir($path . 'lib'); waFiles::protect($path . 'lib'); $plugin_class = null; mkdir($path . 'lib/classes'); // config mkdir($path . 'lib/config'); // app description $plugin = array('name' => empty($params['name']) ? ucfirst($id) : $params['name'], 'description' => '', 'icon' => 'img/' . $id . '.png', 'version' => empty($params['version']) ? '1.0.0' : $params['version'], 'vendor' => empty($params['vendor']) ? '' : $params['vendor']); waUtils::varExportToFile($plugin, $path . 'lib/config/plugin.php'); switch ($type) { case 'payment': #settings if (isset($params['settings'])) { waUtils::varExportToFile(array(), $path . 'lib/config/settings.php'); } #plugin class $template_class_path = $template_path . 'lib/' . $template_id . ucfirst($type) . '.class.php'; $class_path = $path . 'lib/' . $id . ucfirst($type) . '.class.php'; $template = file_get_contents($template_class_path); waFiles::write($class_path, str_replace($template_id, $id, $template)); #plugin template mkdir($path . 'templates'); waFiles::protect($path . 'templates'); waFiles::copy($template_path . 'templates/payment.html', $path . 'templates/payment.html'); break; case 'shipping': #settings if (isset($params['settings'])) { waUtils::varExportToFile(array(), $path . 'lib/config/settings.php'); } #plugin class $template_class_path = $template_path . 'lib/' . $template_id . ucfirst($type) . '.class.php'; $class_path = $path . 'lib/' . $id . ucfirst($type) . '.class.php'; $template = file_get_contents($template_class_path); waFiles::write($class_path, str_replace($template_id, $id, $template)); break; default: throw new waException(sprintf("Plugin type \"%s\" not supported yet.\n", $type)); break; } print "Plugin with id \"{$id}\" created!\n"; } catch (waException $ex) { print "Plugin with id \"{$id}\" was NOT created.\n"; if (waSystemConfig::isDebug()) { echo $ex; } else { print "Error:" . $ex->getMessage() . "\n"; } waFiles::delete($path); } } else { print "Plugin with id \"{$id}\" already exists.\n"; } }