public function getUserData($token) { $url = self::API_URL . "users.get?uid={$token['user_id']}&fields=contacts,sex,bdate,timezone,photo_medium&access_token={$token['access_token']}"; $response = $this->get($url, $status); if ($response && ($response = json_decode($response, true))) { if (isset($response['error'])) { waLog::log($this->getId() . ':' . $status . ': Error ' . $response['error']['error_code'] . " (" . $response['error']['error_msg'] . ')', 'auth.log'); throw new waException($response['error']['error_msg'], $response['error']['error_code']); } $response = $response['response'][0]; if ($response) { $data = array('source' => 'vkontakte', 'source_id' => $response['uid'], 'url' => "http://vk.com/id" . $response['uid'], 'name' => $response['first_name'] . " " . $response['last_name'], 'firstname' => $response['first_name'], 'lastname' => $response['last_name'], 'photo_url' => $response['photo_medium']); if (!empty($token['email'])) { $data['email'] = $token['email']; } if ($response['home_phone']) { $data['phone.home'] = $response['home_phone']; } if ($response['sex']) { $data['sex'] = $response['sex'] == 2 ? 'm' : 'f'; } if ($response['bdate']) { $b = explode('.', $response['bdate']); if (count($b) == 3) { $data['birthday'] = $b[2] . '-' . $b[1] . '-' . $b[0]; } } return $data; } } waLog::log($this->getId() . ':' . $status . ': ' . "Can't get user info from VK API", 'auth.log'); throw new waException("Can't get user info from VK API", $status ? $status : 500); }
public function execute() { ob_start(); $app = $this->getApp(); $app_settings_model = new waAppSettingsModel(); $app_settings_model->set($app, 'cron_schedule', time()); waFiles::create($this->getConfig()->getPath('log') . '/' . $app . '/'); $log_file = "{$app}/cron.txt"; $post_model = new blogPostModel(); $params = array('datetime' => date("Y-m-d H:i:s"), 'status' => blogPostModel::STATUS_SCHEDULED); $posts_schedule = $post_model->select("id,blog_id,contact_id,status,datetime")->where('datetime <= s:datetime AND status=s:status', $params)->fetchAll(); if ($posts_schedule) { foreach ($posts_schedule as $post) { try { waLog::log("Attempt publishing post with id [{$post['id']}]", $log_file); $data = array("status" => blogPostModel::STATUS_PUBLISHED); waLog::log($post_model->updateItem($post['id'], $data, $post) ? "success" : "fail", $log_file); } catch (Exception $ex) { waLog::log($ex->getMessage(), $log_file); waLog::log($ex->getTraceAsString(), $log_file); } } } $action = __FUNCTION__; /** * @event cron_action * @param string $action * @return void */ wa()->event('cron_action', $action); if ($log = ob_get_clean()) { waLog::log($log, $log_file); } }
/** * @param $to * @param $text * @param string $from - sender * @return bool|mixed */ public function send($to, $text, $from = null) { try { $adapter = $this->getAdapter($from); $result = $adapter->send($to, $text, $from ? $from : $adapter->getOption('from')); return $result; } catch (waException $e) { waLog::log($e->getMessage(), 'sms.log'); return false; } }
protected function log($message, $level = self::LOG_WARNING) { static $path; if (!$path) { $path = wa()->getApp() . '-import-'; } if ($level <= $this->log_level) { waLog::log($message, $path . 'common.log'); } elseif (wa()->getConfig()->isDebug()) { waLog::log($message, $path . 'debug.log'); } }
public function __construct(waSystem $system, $routes = array()) { $this->system = $system; if (!$routes) { $routes = $this->system->getConfig()->getConfigFile('routing'); if (!is_array($routes)) { waLog::log("Invalid or missed routing config file"); $routes = array(); } } $this->setRoutes($routes); }
public function execute() { // counts to show in page header near app names $apps = $this->getUser()->getApps(false); $root_path = wa()->getConfig()->getRootPath(); $app_settings_model = new waAppSettingsModel(); foreach ($apps as $app_id => $app) { $class_name = $app_id . 'Config'; if ($app_settings_model->get($app_id, 'update_time') && file_exists($root_path . '/wa-apps/' . $app_id . '/lib/config/' . $class_name . '.class.php')) { try { $n = wa($app_id)->getConfig()->onCount(); if ($n !== null) { $this->response[$app_id] = $n; } } catch (Exception $ex) { waLog::log($ex->__toString()); } } } // cache counts in session wa()->getStorage()->write('apps-count', array_filter($this->response)); /* // announcements $user = wa()->getUser(); $am = new waAnnouncementModel(); $data = $am->getByApps($user->getId(), array_keys($apps), $user['create_datetime']); $announcements = array(); foreach ($data as $row) { // show no more than 1 message per application if (isset($announcements[$row['app_id']]) && count($announcements[$row['app_id']]) >= 1) { continue; } $announcements[$row['app_id']][] = waDateTime::format('datetime', $row['datetime']).': '.$row['text']; } if ($announcements) { $announcements_html = ''; foreach ($announcements as $app_id => $texts) { $announcements_html .= '<a href="#" rel="'.$app_id.'" class="wa-announcement-close">'._ws('[close]').'</a><p>'; $announcements_html .= implode('<br />', $texts); $announcements_html .= '</p>'; } if ($announcements_html) { $announcements_html = '<div id="wa-announcement">'.$announcements_html.'</div>'; } $this->response['__announce'] = $announcements_html; } */ }
public static function dump($var, $file = 'dump.log') { $result = ''; // Show where we've been called from if (function_exists('debug_backtrace')) { $result .= "dumped from "; foreach (debug_backtrace() as $row) { if (ifset($row['file']) == __FILE__ || empty($row['file']) && ifset($row['function']) == 'wa_dumpc') { continue; } $result .= ifset($row['file'], '???') . ' line #' . ifset($row['line'], '???') . ":\n"; break; } } $result .= wa_dump_helper($var) . "\n"; waLog::log($result, $file); }
protected function removeExtras($app_id, $extras_id) { try { $paths = array(); if (strpos($app_id, 'wa-plugins/') !== 0) { try { $plugin_instance = waSystem::getInstance($app_id)->getPlugin($extras_id); if (!$plugin_instance) { return false; } $plugin_instance->uninstall(); } catch (Exception $ex) { waLog::log($ex->getMessage(), 'installer.log'); } $this->installer->updateAppPluginsConfig($app_id, $extras_id, null); //wa-apps/$app_id/plugins/$slug $paths[] = wa()->getAppPath("{$this->extras_type}/{$extras_id}", $app_id); $paths[] = wa()->getTempPath(null, $app_id); //wa-cache/temp/$app_id/ $paths[] = wa()->getAppCachePath(null, $app_id); //wa-cache/apps/$app_id/ } else { $type = str_replace('wa-plugins/', '', $app_id); $paths[] = wa()->getConfig()->getPath('plugins') . '/' . $type . '/' . $extras_id; //wa-plugins/$type/$extras_id $paths[] = wa()->getAppCachePath(null, $type . '_' . $extras_id); //wa-cache/apps/$app_id/ } foreach ($paths as $path) { waFiles::delete($path, true); } return true; } catch (Exception $ex) { //TODO check config if (strpos($app_id, 'wa-plugins/') !== 0) { if (file_exists(reset($paths) . '/lib/plugin.php')) { $this->installer->updateAppPluginsConfig($app_id, $extras_id, true); } } throw $ex; } }
public function execute() { // close session wa()->getStorage()->close(); // counts to show in page header near app names $apps = $this->getUser()->getApps(false); $root_path = wa()->getConfig()->getRootPath(); $app_settings_model = new waAppSettingsModel(); foreach ($apps as $app_id => $app) { $class_name = $app_id . 'Config'; if ($app_settings_model->get($app_id, 'update_time') && file_exists($root_path . '/wa-apps/' . $app_id . '/lib/config/' . $class_name . '.class.php')) { try { $n = wa($app_id)->getConfig()->onCount(); if ($n !== null) { $this->response[$app_id] = $n; } } catch (Exception $ex) { waLog::log('Error ' . $ex->getCode() . ': ' . $ex->getMessage()); } } } // cache counts in session wa()->getStorage()->write('apps-count', array_filter($this->response)); }
public function run($params = NULL) { $app = $this->getApp(); $app_settings_model = new waAppSettingsModel(); $app_settings_model->set($app, 'last_schedule_cron_time', time()); waFiles::create($this->getConfig()->getPath('log') . '/' . $app . '/'); $log_file = "{$app}/schedule.txt"; $post_model = new blogPostModel(); $params = array('datetime' => date("Y-m-d H:i:s"), 'status' => blogPostModel::STATUS_SCHEDULED); $posts_schedule = $post_model->select("id, blog_id, contact_id, status, datetime")->where('datetime <= s:datetime AND status=s:status', $params)->fetchAll(); if ($posts_schedule) { foreach ($posts_schedule as $post) { try { waLog::log("Attempt publishing post with id [{$post['id']}]", $log_file); $data = array("status" => blogPostModel::STATUS_PUBLISHED, "datetime" => date("Y-m-d H:i:s")); $r = $post_model->updateItem($post['id'], $data, $post); waLog::log($r ? "success" : "fail", $log_file); } catch (Exception $ex) { waLog::log($ex->getMessage(), $log_file); waLog::log($ex->getTraceAsString(), $log_file); } } } }
private function error($message) { $path = wa()->getConfig()->getPath('log'); waFiles::create($path . '/shop/csvproducts.log'); waLog::log($message, 'shop/csvproducts.log'); }
/** * Validate data * * @param array &$data * @param array $options * * @return array messages or empty array */ public function validate(&$data, $options = array()) { $messages = array(); if ($data['blog_status'] != blogBlogModel::STATUS_PRIVATE) { if (!empty($data['id'])) { $url_validator = new blogSlugValidator(array('id' => $data['id'])); } else { if (!empty($options['transliterate']) && !$data['url']) { if ($data['title']) { $data['url'] = blogHelper::transliterate($data['title']); } else { $data['url'] = $this->genUniqueUrl(''); } } $url_validator = new blogSlugValidator(); } $url_validator->setSubject(blogSlugValidator::SUBJECT_POST); if (!$url_validator->isValid($data['url'])) { $messages['url'] = current($url_validator->getErrors()); if ($url_validator->isError(blogSlugValidator::ERROR_REQUIRED) && ($data['id'] || !$data['id'] && $data['status'] == blogPostModel::STATUS_DRAFT)) { $url = $this->select('url')->where('id = i:id', array('id' => $data['id']))->fetchField('url'); $data['url'] = $url ? $url : $this->genUniqueUrl($data['title']); unset($messages['url']); if (!$url_validator->isValid($data['url'])) { $messages['url'] = current($url_validator->getErrors()); } } elseif (!empty($options['make'])) { $data['url'] = $this->genUniqueUrl($data['url']); unset($messages['url']); if (!$url_validator->isValid($data['url'])) { $messages['url'] = current($url_validator->getErrors()); } } } } else { if (empty($data['id'])) { $data['url'] = $this->genUniqueUrl(empty($data['url']) ? $data['title'] : $data['url']); } else { $url = $this->select('url')->where('id = i:id', array('id' => $data['id']))->fetchField('url'); $data['url'] = $url ? $url : $this->genUniqueUrl($data['title']); } } if (isset($data['datetime']) && !is_null($data['datetime'])) { if (!empty($options['datetime'])) { $formats = (array) $options['datetime']; } elseif (isset($options['datetime'])) { $formats = array(); } elseif (strpos($data['datetime'], ':') !== false) { $formats = array('fulldatetime', 'datetime'); } else { $formats = array('date'); } if ($data['datetime'] != '') { $datetime = $data['datetime']; foreach ($formats as $format) { try { if ($datetime = waDateTime::parse($format, $data['datetime'])) { break; } } catch (Exception $ex) { $messages['datetime'] = _w('Incorrect format'); waLog::log($ex->getMessage()); } } if (preg_match('/^([\\d]{4})\\-([\\d]{1,2})\\-([\\d]{1,2})(\\s|$)/', $datetime, $matches)) { if (!checkdate($matches[2], $matches[3], $matches[1])) { $messages['datetime'] = _w('Incorrect format'); } } $data['datetime'] = $datetime; } else { if ($data['status'] != blogPostModel::STATUS_DRAFT) { $data['datetime'] = false; } } if ($data['datetime'] === false) { $messages['datetime'] = _w('Incorrect format'); } } /** * @event post_validate * @param array [string]mixed $data * @param array ['plugin']['%plugin_id%']mixed plugin data * @return array['%plugin_id%']['field']string error */ $messages['plugin'] = wa()->event('post_validate', $data); if (empty($messages['plugin'])) { unset($messages['plugin']); } return $messages; }
<?php $sqls = array(); $sqls[] = 'ALTER TABLE `blog_comment` CHANGE `email` `email` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL'; $sqls[] = 'ALTER TABLE `blog_comment` CHANGE `name` `name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL'; $sqls[] = 'ALTER TABLE `blog_comment` CHANGE `site` `site` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL'; $sqls[] = 'ALTER TABLE `blog_post` CHANGE `text` `text` MEDIUMTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL'; $model = new waModel(); foreach ($sqls as $sql) { try { $model->exec($sql); } catch (Exception $ex) { if (class_exists('waLog')) { waLog::log(basename(__FILE__) . ': ' . $ex->getMessage(), 'blog-update.log'); } } }
protected static function log($module_id, $data) { $module_id = strtolower($module_id); $filename = 'payment/' . $module_id . 'Payment.log'; $rec = "data:\n"; if (is_array($data)) { foreach ($data as $key => $val) { $rec .= "{$key}={$val}&\n"; } } else { $rec .= "{$data}\n"; } waLog::log($rec, $filename); }
public function execute() { $id = waRequest::post('id', null, waRequest::TYPE_INT); if (!$id) { throw new waException("Can't rotate photo"); } $direction = waRequest::post('direction', 'left', waRequest::TYPE_STRING_TRIM); if (isset($this->derection_angles[$direction])) { $photo_model = new photosPhotoModel(); $photo_rights_model = new photosPhotoRightsModel(); $photo = $photo_model->getById($id); if (!$photo_rights_model->checkRights($photo, true)) { throw new waException(_w("You don't have sufficient access rights")); } $photo_path = photosPhoto::getPhotoPath($photo); $paths = array(); try { $image = new photosImage($photo_path); $result_photo_path = preg_replace('/(\\.[^\\.]+)$/', '.result$1', $photo_path); $backup_photo_path = preg_replace('/(\\.[^\\.]+)$/', '.backup$1', $photo_path); $paths[] = $result_photo_path; $result = $image->rotate($this->derection_angles[$direction])->save($result_photo_path); if ($result) { $count = 0; while (!file_exists($result_photo_path) && ++$count < 5) { sleep(1); } if (!file_exists($result_photo_path)) { throw new waException("Error while rotate. I/O error"); } $paths[] = $backup_photo_path; if (waFiles::move($photo_path, $backup_photo_path)) { if (!waFiles::move($result_photo_path, $photo_path)) { if (!waFiles::move($backup_photo_path, $photo_path)) { throw new waException("Error while rotate. Original file corupted but backuped"); } throw new waException("Error while rotate. Operation canceled"); } else { $edit_datetime = date('Y-m-d H:i:s'); $data = array('edit_datetime' => $edit_datetime, 'width' => $photo['height'], 'height' => $photo['width']); $photo_model->updateById($id, $data); $photo = array_merge($photo, $data); $thumb_dir = photosPhoto::getPhotoThumbDir($photo); $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1); $paths[] = $back_thumb_dir; waFiles::delete($back_thumb_dir); if (!(waFiles::move($thumb_dir, $back_thumb_dir) || waFiles::delete($back_thumb_dir)) && !waFiles::delete($thumb_dir)) { throw new waException("Error while rebuild thumbnails"); } } $photo['thumb'] = photosPhoto::getThumbInfo($photo, photosPhoto::getThumbPhotoSize()); $photo['thumb_big'] = photosPhoto::getThumbInfo($photo, photosPhoto::getBigPhotoSize()); $photo['thumb_middle'] = photosPhoto::getThumbInfo($photo, photosPhoto::getMiddlePhotoSize()); $original_photo_path = photosPhoto::getOriginalPhotoPath($photo); if (wa('photos')->getConfig()->getOption('save_original') && file_exists($original_photo_path)) { $photo['original_exists'] = true; } else { $photo['original_exists'] = false; } $this->response['photo'] = $photo; $this->log('photo_edit', 1); $obligatory_sizes = $this->getConfig()->getSizes(); try { photosPhoto::generateThumbs($photo, $obligatory_sizes); } catch (Exception $e) { waLog::log($e->getMessage()); } } else { throw new waException("Error while rotate. Operation canceled"); } } foreach ($paths as $path) { waFiles::delete($path); } } catch (Exception $e) { foreach ($paths as $path) { waFiles::delete($path); } throw $e; } } }
protected function checkUpdates() { try { $app_settings_model = new waAppSettingsModel(); $time = $app_settings_model->get($this->application, 'update_time'); } catch (waDbException $e) { if ($e->getCode() == 2002 && !waSystemConfig::isDebug()) { return; } else { // table doesn't exist $time = null; } } catch (waException $e) { return; } if (!$time) { try { $this->install(); } catch (waException $e) { waLog::log($e->__toString()); throw $e; } $ignore_all = true; } else { $ignore_all = false; } if (!self::isDebug()) { $cache = new waVarExportCache('updates', 0, $this->application); if ($cache->isCached() && $cache->get() <= $time) { return; } } $path = $this->getAppPath() . '/lib/updates'; $cache_database_dir = $this->getPath('cache') . '/db'; if (file_exists($path)) { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); $files = array(); foreach ($iterator as $file) { /** * @var SplFileInfo $file */ if ($file->isFile() && preg_match('/^[0-9]+\\.php$/', $file->getFilename())) { $t = substr($file->getFilename(), 0, -4); if ($t > $time) { $files[$t] = $file->getPathname(); } } } ksort($files); if (!self::isDebug()) { // get last time if ($files) { $keys = array_keys($files); $cache->set(end($keys)); } else { $cache->set($time ? $time : 1); } } foreach ($files as $t => $file) { try { if (!$ignore_all) { include $file; waFiles::delete($cache_database_dir); $app_settings_model->set($this->application, 'update_time', $t); } } catch (Exception $e) { if (waSystemConfig::isDebug()) { echo $e; } // log errors waLog::log($e->__toString()); break; } } } else { $t = 1; } if ($ignore_all) { if (!isset($t) || !$t) { $t = 1; } if (!isset($app_settings_model)) { $app_settings_model = new waAppSettingsModel(); } $app_settings_model->set($this->application, 'update_time', $t); } if (isset($this->info['edition']) && $this->info['edition']) { if (!isset($app_settings_model)) { $app_settings_model = new waAppSettingsModel(); } if (!$app_settings_model->get($this->application, 'edition')) { $file_sql = $this->getAppPath('lib/config/app.' . $this->info['edition'] . '.sql'); if (file_exists($file_sql)) { self::executeSQL($file_sql, 1); } $app_settings_model->set($this->application, 'edition', $this->info['edition']); } } }
private function lj_query() { $params = array(); if ($this->get_challenge()) { $params = array('username' => $this->option('lj_user'), 'auth_method' => 'challenge', 'auth_challenge' => $this->challenge, 'auth_response' => $this->auth_response); $this->challenge = null; } else { waLog::log(_wp('LiveJournal does not appear to be responding right now. Please try again later.')); } $args = func_get_args(); $method = array_shift($args); if (isset($args[0])) { $params = array_merge($params, $args[0]); } return $this->xmlrpc("LJ.XMLRPC.{$method}", $params); }
/** * Execute SQL query * * @param string $sql * @param bool $unbuffer * @throws waDbException * @return resource */ private function run($sql, $unbuffer = false) { $sql = trim($sql); $result = $this->adapter->query($sql); if (!$result) { $error = "Query Error\nQuery: " . $sql . "\nError: " . $this->adapter->errorCode() . "\nMessage: " . $this->adapter->error(); $trace = debug_backtrace(); $stack = ""; $default = array('file' => 'n/a', 'line' => 'n/a'); foreach ($trace as $i => $row) { $row = array_merge($row, $default); $stack .= $i . ". " . $row['file'] . ":" . $row['line'] . "\n" . (isset($row['class']) ? $row['class'] : '') . (isset($row['type']) ? $row['type'] : '') . $row['function'] . "()\n"; } waLog::log($error . "\nStack:\n" . $stack, 'db.log'); throw new waDbException($error, $this->adapter->errorCode()); } return $result; }
// Create cli.php if not included in distr already $path = wa()->getConfig()->getRootPath() . '/cli.php'; if (!file_exists($path)) { if ($fp = fopen($path, 'w')) { $content = <<<CLI #!/usr/bin/php <?php require_once(dirname(__FILE__).'/wa-system/cli.php'); CLI; fwrite($fp, $content); fclose($fp); } } // Protect private dirs with .htaccess $paths = array('log', 'cache', 'config', 'installer'); foreach ($paths as $path) { $path = waSystem::getInstance()->getConfig()->getPath($path); waFiles::protect($path); } // Insert data into tables foreach (array('wa_country', 'wa_region') as $table) { if ($sql = @file_get_contents(dirname(__FILE__) . '/' . $table . '.sql')) { try { $m = new waModel(); $m->exec($sql); } catch (Exception $e) { waLog::log('Unable to populate ' . $table . ': ' . $e->getMessage() . "\n" . $e->getTraceAsString()); } } }
/** * @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; }
<?php //create first blog at install try { $name = wa()->accountName(); $blog = array('status' => blogBlogModel::STATUS_PUBLIC, 'name' => $name, 'icon' => 'blog', 'color' => 'b-white', 'url' => blogHelper::transliterate($name)); $app = wa()->getApp(); $blog_model = new blogBlogModel(); if ($blog_model->countAll() == 0) { $blog_id = $blog_model->insert($blog); $user = wa()->getUser(); if (!$user->isAdmin($app)) { $user->setRight($app, "blog.{$blog_id}", blogRightConfig::RIGHT_FULL); } } } catch (Exception $e) { waLog::log($e->getMessage()); }
/** * Store settings at storage * @param bool $force * @return void */ public function save($force = false) { $settingsChanged = $force ? $this->settingsChanged : array_fill_keys(array_keys($this->settings), true); $updated = false; if (is_array($settingsChanged)) { foreach ($settingsChanged as $name => &$changed) { if ($changed) { $updated = true; if (!isset($this->settingsParams[$name]) || !isset($this->settingsParams[$name]['settings_store']) || $this->settingsParams[$name]['settings_store'] == 'mysql') { $value = $this->settings[$name]; if (is_object($value) && isset($this->settingsParams[$name]['settings_object'])) { $class = get_class($value); if (class_exists($class) && in_array('waSettingWrapper', class_parents($class))) { $value = $value->store(); } else { waLog::log(sprintf('Invalid setting class %s for setting %s at %s', get_class($value), $name, $this->name)); } } if (is_array($value)) { //$value = serialize($value); $value = json_encode($value); } $this->saveSetting($name, $value); } $changed = false; } } } if ($updated) { $this->flush(); } }
/** * Download if neccassary local image copy for item (application or extras logo) * @param $item * @param $image_path * @return void */ private function fixItemImage(&$item, $image_path = null) { if ($image_path && !$item['current'] && isset($item['img']) && $item['img']) { $path = $image_path . '/' . $item['vendor']; if (!file_exists($path)) { mkdir($path, 0777, true); } if (strpos($item['slug'], '/') !== false) { if (!file_exists($path . '/' . dirname($item['slug']))) { mkdir($path . '/' . dirname($item['slug']), 0777, true); } } $path .= '/' . $item['slug'] . (isset($item['edition']) && $item['edition'] ? "_{$item['edition']}" : '') . '.png'; if (!file_exists($path) || time() - filectime($path) > 3600) { try { if ($img = $this->getFileContent($item['img'])) { file_put_contents($path, $img); } } catch (Exception $ex) { //ignore image downloading error if (class_exists('waLog')) { waLog::log($ex->__toString()); } } } if (file_exists($path)) { $item['img_cached'] = $item['vendor'] . '/' . $item['slug'] . (isset($item['edition']) && $item['edition'] ? "_{$item['edition']}" : '') . '.png'; } else { $item['img_cached'] = null; } } }
<?php $path = wa()->getDataPath('photo', true, 'contacts'); waFiles::create($path); $data = <<<DATA <ifModule mod_rewrite.c> RewriteEngine On #RewriteBase /wa-data/public/contacts/photo/ RewriteCond %{REQUEST_URI} \\.jpg\$ RewriteCond %{REQUEST_FILENAME} !-f \tRewriteRule ^(.*)\$ thumb.php [L,QSA] </ifModule> DATA; file_put_contents($path . '/.htaccess', $data); if (!copy($this->getAppPath('lib/config/data/thumb.php'), $path . '/thumb.php')) { $error = sprintf('Installation could not be completed due to the insufficient file write permissions for the %s folder.', $path); if (class_exists('waLog')) { waLog::log(basename(__FILE__) . ': ' . $error, 'contacts-install.log'); } throw new waException($error); }
public function checkUpdates() { try { $app_settings_model = new waAppSettingsModel(); $time = $app_settings_model->get($this->application, 'update_time'); } catch (waDbException $e) { // Can't connect to MySQL server if ($e->getCode() == 2002) { throw $e; } elseif (!empty($app_settings_model)) { $time = null; $row = $app_settings_model->getByField(array('app_id' => $this->application, 'name' => 'update_time')); if ($row) { $time = $row['value']; } } elseif ($this->application != 'webasyst' && $this->environment == 'frontend') { wa('webasyst'); } } catch (waException $e) { return; } if (empty($time)) { try { $this->install(); } catch (waException $e) { waLog::log($e->__toString()); throw $e; } $ignore_all = true; $time = null; } else { $ignore_all = false; } if (!self::isDebug()) { $cache = new waVarExportCache('updates', 0, $this->application); if ($cache->isCached() && $cache->get() <= $time) { return; } } $path = $this->getAppPath() . '/lib/updates'; $cache_database_dir = $this->getPath('cache') . '/db'; if (file_exists($path)) { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); $files = array(); foreach ($iterator as $file) { /** * @var SplFileInfo $file */ if ($file->isFile() && preg_match('/^[0-9]+\\.php$/', $file->getFilename())) { $t = substr($file->getFilename(), 0, -4); if ($t > $time) { $files[$t] = $file->getPathname(); } } } ksort($files); if (!self::isDebug()) { // get last time if ($files) { $keys = array_keys($files); $cache->set(end($keys)); } else { $cache->set($time ? $time : 1); } } foreach ($files as $t => $file) { try { if (!$ignore_all) { $this->includeUpdate($file); waFiles::delete($cache_database_dir); $app_settings_model->set($this->application, 'update_time', $t); } } catch (Exception $e) { if (waSystemConfig::isDebug()) { echo $e; } // log errors waLog::log($e->__toString()); break; } } } else { $t = 1; } if ($ignore_all) { if (!isset($t) || !$t) { $t = 1; } if (!isset($app_settings_model)) { $app_settings_model = new waAppSettingsModel(); } $app_settings_model->set($this->application, 'update_time', $t); } if (isset($this->info['edition']) && $this->info['edition']) { if (!isset($app_settings_model)) { $app_settings_model = new waAppSettingsModel(); } if (!$app_settings_model->get($this->application, 'edition')) { $app_settings_model->set($this->application, 'edition', $this->info['edition']); } } }
protected function log($to, $text, $response = '') { waLog::log('SMS to ' . $to . ' (' . mb_strlen($text) . ' chars).' . "\nResponse: " . $response, 'sms.log'); }
/** * Trigger event with given $name from current active application. * @param string $name * @param mixed $params passed to event handlers * @return array app_id or plugin_id => data returned from handler (unless null is returned) */ public function event($name, &$params = null) { $result = array(); if (is_array($name)) { $event_app_id = $name[0]; $system = self::getInstance($event_app_id); $name = $name[1]; } else { $event_app_id = $this->getConfig()->getApplication(); $system = $this; } $prefix = wa($event_app_id)->getConfig()->getPrefix(); // // Call handlers defined by applications // $apps = $this->getApps(); $path = $this->getConfig()->getPath('apps'); foreach ($apps as $app_id => $info) { $file_path = $path . "/" . $app_id . "/lib/handlers/" . $prefix . "." . $name . ".handler.php"; if (file_exists($file_path)) { waSystem::getInstance($app_id); include_once $file_path; $class_name = $name; if (strpos($name, '.') !== false) { $class_name = strtok($class_name, '.') . ucfirst(strtok('')); } $class_name = $app_id . ucfirst($prefix) . ucfirst($class_name) . "Handler"; /** * @var $handler waEventHandler */ $handler = new $class_name(); try { $r = $handler->execute($params); if ($r !== null) { $result[$app_id] = $r; } } catch (Exception $e) { waLog::log('Event handling error in ' . $file_path . ': ' . $e->getMessage()); } } } //self::setActive($event_app_id); // // Call handlers defined by current application's plugins // $plugins = $system->getConfig()->getPlugins(); foreach ($plugins as $plugin_id => $plugin) { foreach ($plugin['handlers'] as $handler_event => $handler_method) { if ($name == $handler_event) { // Remember active plugin locale name for _wp() to work self::pushActivePlugin($plugin_id, wa($event_app_id)->getConfig()->getPrefix()); $class_name = $event_app_id . ucfirst($plugin_id) . 'Plugin'; try { $class = new $class_name($plugin); // Load plugin locale if it exists $locale_path = $this->getAppPath('plugins/' . $plugin_id . '/locale', $event_app_id); if (is_dir($locale_path)) { waLocale::load($this->getLocale(), $locale_path, self::getActiveLocaleDomain(), false); } if (method_exists($class, $handler_method) && null !== ($r = $class->{$handler_method}($params))) { $result[$plugin_id . '-plugin'] = $r; } } catch (Exception $e) { waLog::log('Event handling error in ' . $class_name . '->' . $handler_method . '(): ' . $e->getMessage()); } self::popActivePlugin(); } } } return $result; }
public function execute() { $id = waRequest::get('id', null, waRequest::TYPE_INT); if (!$id) { throw new waException("Unknown image"); } $direction = waRequest::post('direction', 'left', waRequest::TYPE_STRING_TRIM); if (!isset($this->angles[$direction])) { throw new waException("Can't rotate image"); } $product_images_model = new shopProductImagesModel(); $image = $product_images_model->getById($id); if (!$image) { throw new waException("Unknown image"); } // check rights $product_model = new shopProductModel(); if (!$product_model->checkRights($image['product_id'])) { throw new waException(_w("Access denied")); } $image_path = shopImage::getPath($image); $paths = array(); try { $result_image_path = preg_replace('/(\\.[^\\.]+)$/', '.result$1', $image_path); $backup_image_path = preg_replace('/(\\.[^\\.]+)$/', '.backup$1', $image_path); $paths[] = $result_image_path; if ($this->rotate($image_path, $result_image_path, $this->angles[$direction])) { $count = 0; while (!file_exists($result_image_path) && ++$count < 5) { sleep(1); } if (!file_exists($result_image_path)) { throw new waException(_w("Error while rotate. I/O error")); } if (!waFiles::move($image_path, $backup_image_path)) { throw new waException(_w("Error while rotate. Operation canceled")); } $paths[] = $backup_image_path; if (!waFiles::move($result_image_path, $image_path)) { if (!waFiles::move($backup_image_path, $image_path)) { throw new waException(_w("Error while rotate. Original file corupted but backuped")); } throw new waException(_w("Error while rotate. Operation canceled")); } $datetime = date('Y-m-d H:i:s'); $data = array('edit_datetime' => $datetime, 'width' => $image['height'], 'height' => $image['width']); $product_images_model->updateById($id, $data); $image = array_merge($image, $data); $thumb_dir = shopImage::getThumbsPath($image); $back_thumb_dir = preg_replace('@(/$|$)@', '.back$1', $thumb_dir, 1); $paths[] = $back_thumb_dir; waFiles::delete($back_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")); } $config = $this->getConfig(); try { shopImage::generateThumbs($image, $config->getImageSizes()); } catch (Exception $e) { waLog::log($e->getMessage()); } $this->response = $image; $edit_datetime_ts = strtotime($image['edit_datetime']); $this->response['url_big'] = shopImage::getUrl($image, $config->getImageSize('big')) . '?' . $edit_datetime_ts; $this->response['url_crop'] = shopImage::getUrl($image, $config->getImageSize('crop')) . '?' . $edit_datetime_ts; } foreach ($paths as $path) { waFiles::delete($path); } } catch (Exception $e) { foreach ($paths as $path) { waFiles::delete($path); } throw $e; } }
/** * Trigger event with given $name from current active application. * * @param string $name Event name. * @param mixed $params Parameters passed to event handlers. * @param string[] $array_keys Array of expected template items for UI events. * @return array app_id or plugin_id => data returned from handler (unless null is returned) */ public function event($name, &$params = null, $array_keys = null) { $result = array(); if (is_array($name)) { $event_app_id = $name[0]; $event_system = self::getInstance($event_app_id); $name = $name[1]; } else { $event_app_id = $this->getConfig()->getApplication(); $event_system = $this; } $event_prefix = wa($event_app_id)->getConfig()->getPrefix(); if (!isset(self::$handlers['apps'])) { self::$handlers['apps'] = array(); $cache_file = $this->config->getPath('cache', 'config/handlers'); if (!waSystemConfig::isDebug() && file_exists($cache_file)) { self::$handlers['apps'] = (include $cache_file); } if (!self::$handlers['apps'] || !is_array(self::$handlers['apps'])) { $apps = $this->getApps(); $path = $this->getConfig()->getPath('apps'); foreach ($apps as $app_id => $app_info) { $files = waFiles::listdir($path . '/' . $app_id . '/lib/handlers/'); foreach ($files as $file) { if (substr($file, -12) == '.handler.php') { $file = explode('.', substr($file, 0, -12), 2); self::$handlers['apps'][$file[0]][$file[1]][] = $app_id; } } } if (!waSystemConfig::isDebug()) { waUtils::varExportToFile(self::$handlers['apps'], $cache_file); } } } if (!isset(self::$handlers['plugins'][$event_app_id])) { self::$handlers['plugins'][$event_app_id] = array(); $plugins = $event_system->getConfig()->getPlugins(); foreach ($plugins as $plugin_id => $plugin) { if (!empty($plugin['handlers'])) { foreach ($plugin['handlers'] as $handler_event => $handler_method) { self::$handlers['plugins'][$event_app_id][$handler_event][$plugin_id] = $handler_method; } } } } if (isset(self::$handlers['apps'][$event_app_id][$name])) { $path = $this->getConfig()->getPath('apps'); foreach (self::$handlers['apps'][$event_app_id][$name] as $app_id) { $file_path = $path . '/' . $app_id . '/lib/handlers/' . $event_prefix . "." . $name . ".handler.php"; if (!file_exists($file_path)) { continue; } wa($app_id); include_once $file_path; $class_name = $name; if (strpos($name, '.') !== false) { $class_name = strtok($class_name, '.') . ucfirst(strtok('')); } $class_name = $app_id . ucfirst($event_prefix) . ucfirst($class_name) . "Handler"; /** * @var $handler waEventHandler */ $handler = new $class_name(); try { $r = $handler->execute($params); if ($r !== null) { $result[$app_id] = $r; } } catch (Exception $e) { waLog::log('Event handling error in ' . $file_path . ': ' . $e->getMessage()); } } } if (isset(self::$handlers['plugins'][$event_app_id][$name])) { $plugins = $event_system->getConfig()->getPlugins(); foreach (self::$handlers['plugins'][$event_app_id][$name] as $plugin_id => $method) { if (!isset($plugins[$plugin_id])) { continue; } $plugin = $plugins[$plugin_id]; self::pushActivePlugin($plugin_id, $event_prefix); $class_name = $event_app_id . ucfirst($plugin_id) . 'Plugin'; try { $class = new $class_name($plugin); // Load plugin locale if it exists $locale_path = $this->getAppPath('plugins/' . $plugin_id . '/locale', $event_app_id); if (is_dir($locale_path)) { waLocale::load($this->getLocale(), $locale_path, self::getActiveLocaleDomain(), false); } if (method_exists($class, $method) && null !== ($r = $class->{$method}($params))) { if ($array_keys && is_array($r)) { foreach ($array_keys as $k) { if (!isset($r[$k])) { $r[$k] = ''; } } } $result[$plugin_id . '-plugin'] = $r; } } catch (Exception $e) { waLog::log('Event handling error in ' . $class_name . '->' . $name . '(): ' . $e->getMessage()); } self::popActivePlugin(); } } return $result; }
private function error($message) { $path = wa()->getConfig()->getPath('log'); waFiles::create($path . '/shop/images_regenerate.log'); waLog::log($message, 'shop/images_regenerate.log'); }