public static function log($message, $file = 'error.log') { $path = waConfig::get('wa_path_log'); if (!$path) { $path = dirname(dirname(dirname(__FILE__))); } $path .= '/' . $file; if (!file_exists($path)) { waFiles::create(dirname($path)); touch($path); chmod($path, 0666); } elseif (!is_writable($path)) { return false; } $fd = fopen($path, 'a'); if (!flock($fd, LOCK_EX)) { throw new waException('Unable to lock ' . $path); } fwrite($fd, "\n"); fwrite($fd, date('Y-m-d H:i:s: ')); fwrite($fd, $message); fflush($fd); flock($fd, LOCK_UN); fclose($fd); return true; }
protected function create($app_id, $module, $action_type, $action_names) { $files_created = array(); // Generate PHP controller contents $php_wrap = $this->getPhpWrap($app_id, $module, $action_type, $action_names); $php_inner = $this->getPhpInner($action_type, $action_names); $php = str_replace('%CLASS_CONTENT%', $php_inner, $php_wrap); // Save PHP controller into a file $action_path = wa()->getAppPath('lib/actions/' . $module . '/', $app_id); $action_filename = $this->getPhpFilename($app_id, $module, $action_type, $action_names); waFiles::create($action_path); file_put_contents($action_path . $action_filename, $php); $files_created[] = $action_path . $action_filename; // Save templates if ($action_type == 'action' || $action_type == 'actions') { $template_path = wa()->getAppPath('templates/actions/' . $module . '/', $app_id); waFiles::create($template_path); foreach ($action_names as $action_name) { $template_filename = $this->getTemplateFilename($module, $action_type, $action_name); file_put_contents($template_path . $template_filename, "<h1>Hello, World!</h1> <!-- !!! TODO FIXME -->\n\n<p>{$action_path}{$action_filename}</p>\n<p>{$template_path}{$template_filename}</p>"); $files_created[] = $template_path . $template_filename; } } print "Successfully created the following files:\n" . join("\n", $files_created); }
/** * Write message into log file. * * @return bool */ public static function log($message, $file = 'error.log') { if (!self::$path) { self::$path = waConfig::get('wa_path_log'); if (!self::$path) { self::$path = wa()->getConfig()->getRootPath() . DIRECTORY_SEPARATOR . 'wa-log'; } self::$path .= DIRECTORY_SEPARATOR; } $file = self::$path . $file; if (!file_exists($file)) { waFiles::create($file); touch($file); chmod($file, 0666); } elseif (!is_writable($file)) { return false; } $fd = fopen($file, 'a'); if (flock($fd, LOCK_EX)) { fwrite($fd, PHP_EOL . date('Y-m-d H:i:s:') . PHP_EOL . $message); fflush($fd); flock($fd, LOCK_UN); } fclose($fd); return true; }
public function execute() { $product_id = $this->get('product_id', true); $this->getProduct($product_id); $file = waRequest::file('file'); $image = $file->waImage(); if ($file->uploaded()) { $data = array('product_id' => $product_id, 'upload_datetime' => date('Y-m-d H:i:s'), 'width' => $image->width, 'height' => $image->height, 'size' => $file->size, 'original_filename' => basename($file->name), 'ext' => $file->extension, 'description' => waRequest::post('description')); $product_images_model = new shopProductImagesModel(); $image_id = $data['id'] = $product_images_model->add($data); if (!$image_id) { throw new waAPIException('server_error', 500); } /** * @var shopConfig $config */ $config = wa('shop')->getConfig(); $image_path = shopImage::getPath($data); if (file_exists($image_path) && !is_writable($image_path) || !file_exists($image_path) && !waFiles::create($image_path)) { $product_images_model->deleteById($image_id); throw new waAPIException(sprintf("The insufficient file write permissions for the %s folder.", substr($image_path, strlen($config->getRootPath())))); } $file->moveTo($image_path); unset($image); shopImage::generateThumbs($data, $config->getImageSizes()); $method = new shopProductImagesGetInfoMethod(); $_GET['id'] = $image_id; $this->response = $method->getResponse(true); } else { throw new waAPIException('server_error', $file->error); } }
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); } }
public function load($locale, $locale_path, $domain, $textdomain = true) { $file = $locale_path . '/' . $locale . '/LC_MESSAGES/' . $domain . '.po'; $cache_file = waSystem::getInstance()->getConfig()->getPath('cache') . '/apps/' . $domain . '/locale/' . $locale . '.php'; if (isset(self::$cache[$locale][$domain])) { } elseif (!file_exists($file)) { self::$cache[$locale][$domain] = array(); } elseif (file_exists($cache_file) && filemtime($cache_file) > filemtime($file)) { self::$cache[$locale][$domain] = (include $cache_file); } else { if (file_exists($file)) { $gettext = new waGettext($file); self::$cache[$locale][$domain] = $gettext->read(); } else { self::$cache[$locale][$domain] = array(); } waFiles::create($cache_file); waUtils::varExportToFile(self::$cache[$locale][$domain], $cache_file); } if (isset(self::$cache[$locale][$domain]['meta']['Plural-Forms']['plural']) && self::$cache[$locale][$domain]['meta']['Plural-Forms']['plural']) { self::$cache[$locale][$domain]['meta']['f'] = create_function('$n', self::$cache[$locale][$domain]['meta']['Plural-Forms']['plural']); } if ($textdomain) { self::$domain = $domain; self::$locale = $locale; } if (!self::$locale) { self::$locale = $locale; } }
protected function save(waRequestFile $file) { $product_id = waRequest::post('product_id', null, waRequest::TYPE_INT); $product_model = new shopProductModel(); if (!$product_model->checkRights($product_id)) { throw new waException(_w("Access denied")); } // check image if (!($image = $file->waImage())) { throw new waException('Incorrect image'); } $image_changed = false; /** * Extend upload proccess * Make extra workup * @event image_upload */ $event = wa()->event('image_upload', $image); if ($event) { foreach ($event as $plugin_id => $result) { if ($result) { $image_changed = true; } } } if (!$this->model) { $this->model = new shopProductImagesModel(); } $data = array('product_id' => $product_id, 'upload_datetime' => date('Y-m-d H:i:s'), 'width' => $image->width, 'height' => $image->height, 'size' => $file->size, 'original_filename' => basename($file->name), 'ext' => $file->extension); $image_id = $data['id'] = $this->model->add($data); if (!$image_id) { throw new waException("Database error"); } /** * @var shopConfig $config */ $config = $this->getConfig(); $image_path = shopImage::getPath($data); if (file_exists($image_path) && !is_writable($image_path) || !file_exists($image_path) && !waFiles::create($image_path)) { $this->model->deleteById($image_id); throw new waException(sprintf("The insufficient file write permissions for the %s folder.", substr($image_path, strlen($config->getRootPath())))); } if ($image_changed) { $image->save($image_path); // save original $original_file = shopImage::getOriginalPath($data); if ($config->getOption('image_save_original') && $original_file) { $file->moveTo($original_file); } } else { $file->moveTo($image_path); } unset($image); // free variable shopImage::generateThumbs($data, $config->getImageSizes()); return array('id' => $image_id, 'name' => $file->name, 'type' => $file->type, 'size' => $file->size, 'url_thumb' => shopImage::getUrl($data, $config->getImageSize('thumb')), 'url_crop' => shopImage::getUrl($data, $config->getImageSize('crop')), 'url_crop_small' => shopImage::getUrl($data, $config->getImageSize('crop_small')), 'description' => ''); }
public function set($key, $value, $expiration = null, $group = null) { $file = waFiles::create($this->options['path'] . '/' . $key . '.php'); $data = serialize(array('time' => time(), 'ttl' => $expiration, 'value' => $value)); if (!file_exists($file) || is_writable($file)) { $r = @file_put_contents($file, $data, LOCK_EX); if ($r) { @chmod($file, 0664); } return $r; } }
/** * @param string $file CSV file path * @param string $delimiter * @param string $encoding * @param string $method mb or iconv encoding method (default is iconv) */ public function __construct($file, $delimiter = ';', $encoding = 'utf-8', $method = 'iconv') { $this->file = ifempty($file); $this->delimiter = ifempty($delimiter, ';'); if ($this->delimiter == 'tab') { $this->delimiter = "\t"; } $this->encoding = ifempty($encoding, 'utf-8'); $this->method = in_array($method, array('mb', 'icon'), true) ? $method : 'iconv'; if ($this->file()) { waFiles::create($this->file); } $this->restore(); }
protected function create($app_id, $class_name, $table) { $files_created = array(); // Save PHP into a file $path = wa()->getAppPath('lib/model/', $app_id); if (!file_exists($path)) { // shop and helpdesk use `model` dir instead of `models` for some reason $path = wa()->getAppPath('lib/models/', $app_id); } $filename = preg_replace('~Model$~', '', $class_name) . '.model.php'; waFiles::create($path); file_put_contents($path . $filename, $this->getPhp($app_id, $class_name, $table)); $files_created[] = $path . $filename; print "Successfully created:\n" . join("\n", $files_created); }
protected function create($app_id, $layout) { $files_created = array(); // Save PHP into a file $layout_path = wa()->getAppPath('lib/layouts/', $app_id); $layout_filename = $app_id . ucfirst($layout) . '.layout.php'; waFiles::create($layout_path); file_put_contents($layout_path . $layout_filename, $this->getPhp($app_id, $layout)); $files_created[] = $layout_path . $layout_filename; // Save template into a file $template_path = wa()->getAppPath('templates/layouts/' . ucfirst($layout) . '.html', $app_id); waFiles::create($template_path); file_put_contents($template_path, $this->getHtml($app_id, $layout)); $files_created[] = $template_path; print "Successfully created the following files:\n" . join("\n", $files_created); }
protected function save(waRequestFile $file) { if (!$this->model) { $this->model = new shopProductSkusModel(); } $field = array('id' => waRequest::post('sku_id', null, waRequest::TYPE_INT), 'product_id' => waRequest::post('product_id', null, waRequest::TYPE_INT)); $data = array('file_size' => $file->size, 'file_name' => $file->name); $this->model->updateByField($field, $data); $file_path = shopProduct::getPath($field['product_id'], "sku_file/{$field['id']}." . pathinfo($file->name, PATHINFO_EXTENSION)); if (file_exists($file_path) && !is_writable($file_path) || !file_exists($file_path) && !waFiles::create($file_path)) { $data = array('file_size' => 0, 'file_name' => ''); $this->model->updateByField($field, $data); throw new waException(sprintf("The insufficient file write permissions for the %s folder.", substr($file_path, strlen($this->getConfig()->getRootPath())))); } $file->moveTo($file_path); return array('name' => $file->name, 'size' => waFiles::formatSize($file->size)); }
/** * Returns the list of available time zones with localized descriptions. * * @return array */ public static function getTimeZones() { $cache_file = wa()->getConfig()->getPath('cache', 'config/timezones' . wa()->getLocale()); if (file_exists($cache_file) && filemtime($cache_file) > filemtime(dirname(__FILE__) . "/data/timezones.php")) { return include $cache_file; } else { $data = self::getAllTimeZones(); $timezones = array(); foreach ($data as $timezone_id => $info) { foreach ($info[1] as &$c) { $c = _ws(str_replace('_', ' ', $c)); } $timezones[$timezone_id] = $info[0] . ' ' . implode(', ', $info[1]); } waFiles::create($cache_file); waUtils::varExportToFile($timezones, $cache_file); return $timezones; } }
/** * Write message into log file. * * @return bool */ public static function log($message, $file = 'error.log') { self::loadPath(); $file = self::$path . $file; if (!file_exists($file)) { waFiles::create($file); touch($file); chmod($file, 0666); } elseif (!is_writable($file)) { return false; } $fd = fopen($file, 'a'); if (flock($fd, LOCK_EX)) { fwrite($fd, PHP_EOL . date('Y-m-d H:i:s:') . PHP_EOL . $message); fflush($fd); flock($fd, LOCK_UN); } fclose($fd); return true; }
public static function log($message, $file = 'error.log') { $path = waSystem::getInstance()->getConfig()->getPath('log') . '/' . $file; if (!file_exists($path)) { waFiles::create($path); touch($path); chmod($path, 0666); } elseif (!is_writable($path)) { return false; } $fd = fopen($path, 'a'); if (!flock($fd, LOCK_EX)) { throw new waException('Unable to lock ' . $path); } fwrite($fd, "\n"); fwrite($fd, date('Y-m-d H:i:s: ')); fwrite($fd, $message); flock($fd, LOCK_UN); fclose($fd); return true; }
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); } } } }
protected function decodePart($part) { switch ($part['type']) { case self::TYPE_HEADER: $this->current_header = $part['value']; if (!isset($this->part['headers'][$part['value']])) { $this->part['headers'][$part['value']] = ''; } break; case self::TYPE_HEADER_VALUE: if ($this->current_header == 'content-type') { $info = $this->parseHeader($part['value']); $this->part['type'] = strtolower(strtok($info['value'], '/')); $this->part['subtype'] = strtolower(strtok('')); $this->part['params'] = $info['params']; unset($info); } if ($this->current_header === 'from ') { $this->current_header = 'from'; unset($this->part['headers']['from ']); $this->part['headers']['from'] = strtok($part['value'], ' '); $this->part['headers']['date'] = strtok(''); } elseif (strpos($part['value'], "\n") === false) { if ($part['value'] || !isset($this->part['headers'][$this->current_header])) { if ($this->current_header == 'content-transfer-encoding') { $part['value'] = strtolower($part['value']); } $this->part['headers'][$this->current_header] = $part['value']; } } else { $this->part['headers'][$this->current_header] = array(trim(strtok($part['value'], "\n"))); while (($value = strtok("\n")) !== false) { $this->part['headers'][$this->current_header][] = ltrim(rtrim($value), "\t"); } } break; case self::TYPE_ATTACH: $boundary = "\n--" . $part['boundary']; if (!file_exists($this->options['attach_path'])) { waFiles::create($this->options['attach_path']); } $path = $this->options['attach_path'] . (count($this->attachments) + 1); if (isset($this->part['params']['name'])) { if (($i = strrpos($this->part['params']['name'], '.')) !== false) { $path .= substr($this->part['params']['name'], $i); } } elseif ($this->part['type'] == 'image' && in_array($this->part['subtype'], array('gif', 'jpg', 'png'))) { $path .= '.' . $this->part['subtype']; } $attach = array('file' => basename($path)); if (isset($this->part['params']['name'])) { $attach['name'] = $this->part['params']['name']; } $attach['type'] = $this->part['type']; if (isset($this->part['subtype']) && $this->part['subtype']) { $attach['type'] .= '/' . $this->part['subtype']; } if (isset($this->part['headers']['content-id'])) { $attach['content-id'] = $this->part['headers']['content-id']; if (substr($attach['content-id'], 0, 1) == '<') { $attach['content-id'] = substr($attach['content-id'], 1); } if (substr($attach['content-id'], -1) == '>') { $attach['content-id'] = substr($attach['content-id'], 0, -1); } } $this->attachments[] = $attach; unset($attach); $fp = fopen($path, "w+"); if (isset($this->part['headers']['content-transfer-encoding'])) { if ($this->part['headers']['content-transfer-encoding'] == 'base64') { stream_filter_append($fp, "convert.base64-decode", STREAM_FILTER_WRITE); } elseif ($this->part['headers']['content-transfer-encoding'] == 'quoted-printable') { stream_filter_append($fp, "convert.quoted-printable-decode", STREAM_FILTER_WRITE); } } while (($i = strpos($this->buffer, $boundary, $this->buffer_offset)) === false && !$this->is_last) { fwrite($fp, $this->buffer_offset ? substr($this->buffer, $this->buffer_offset) : $this->buffer); $this->buffer = ''; $this->buffer_offset = 0; $this->read(); } // if last part if ($i === false) { // try find incorrect boundary end if (substr(rtrim($this->buffer, "\r\n"), -2) == '--') { $j = strrpos(rtrim($this->buffer, "\r\n"), "\n"); $this->buffer = rtrim(substr($this->buffer, 0, $j), "\r\n"); } // write part to attach file fwrite($fp, substr($this->buffer, $this->buffer_offset)); $this->buffer = ''; $this->buffer_offset = 0; $this->state = self::STATE_END; } else { fwrite($fp, substr($this->buffer, $this->buffer_offset, $i - $this->buffer_offset)); $this->buffer_offset = $i; $this->state = self::STATE_PART; } fclose($fp); if (!isset($this->part['headers']['content-disposition'])) { $this->body[$this->part['type'] . "/" . $this->part['subtype']] = file_get_contents($path); } if (isset($this->part['parent'])) { $this->part_index = $this->part['parent']; $this->part =& $this->parts[$this->part['parent']]; } break; case self::TYPE_PART: switch ($this->part['type']) { case 'text': $this->part['data'] = $part['value']; unset($part); if (isset($this->part['headers']['content-transfer-encoding'])) { switch ($this->part['headers']['content-transfer-encoding']) { case 'base64': $this->part['data'] = base64_decode($this->part['data']); break; case 'quoted-printable': $this->part['data'] = preg_replace("/=\r?\n/", '', $this->part['data']); $this->part['data'] = preg_replace_callback('/=([a-f0-9]{2})/i', array(__CLASS__, 'quotedPrintableReplace'), $this->part['data']); break; } } if (isset($this->part['params']['charset']) && $this->part['params']['charset']) { $this->part['params']['charset'] = preg_replace("/^[=\"]+/i", "", $this->part['params']['charset']); if (strtolower($this->part['params']['charset']) != 'utf-8') { $this->part['data'] = @iconv($this->part['params']['charset'], "utf-8//IGNORE", $this->part['data']); } } else { $charset = mb_detect_encoding($this->part['data']); if ($charset && strtolower($charset) != "utf-8" && ($temp = iconv($charset, 'UTF-8', $this->part['data']))) { $this->part['data'] = $temp; unset($temp); } elseif (!preg_match("//u", $this->part['data'])) { if (!$charset) { $temp = iconv("windows-1251", "utf-8", $this->part['data']); if (preg_match("/[а-я]/ui", $temp)) { $this->part['data'] = $temp; } } else { if ($temp = @iconv('utf-8', 'utf-8//IGNORE', $this->part['data'])) { $this->part['data'] = $temp; } } unset($temp); } } if (!isset($this->body[$this->part['type'] . '/' . $this->part['subtype']])) { $this->body[$this->part['type'] . '/' . $this->part['subtype']] = $this->part['data']; } break; default: $this->part['data'] = $part['value']; unset($part); } if (isset($this->part['parent'])) { $this->part_index = $this->part['parent']; $this->part =& $this->parts[$this->part['parent']]; } $this->clearBuffer(); } }
/** * Returns information about all app's installed plugins as an associative array. * * @return array */ public function getPlugins() { if ($this->plugins === null) { $locale = wa()->getLocale(); $file = waConfig::get('wa_path_cache') . "/apps/" . $this->application . '/config/plugins.' . $locale . '.php'; if (!file_exists($file) || SystemConfig::isDebug()) { waFiles::create(waConfig::get('wa_path_cache') . "/apps/" . $this->application . '/config'); // read plugins from file wa-config/[APP_ID]/plugins.php $path = $this->getConfigPath('plugins.php', true); if (!file_exists($path)) { $this->plugins = array(); return $this->plugins; } $all_plugins = (include $path); $this->plugins = array(); foreach ($all_plugins as $plugin_id => $enabled) { if ($enabled) { $plugin_config = $this->getPluginPath($plugin_id) . "/lib/config/plugin.php"; if (!file_exists($plugin_config)) { continue; } $plugin_info = (include $plugin_config); waSystem::pushActivePlugin($plugin_id, $this->application); // Load plugin locale if it exists $locale_path = wa()->getAppPath('plugins/' . $plugin_id . '/locale', $this->application); if (is_dir($locale_path)) { waLocale::load($locale, $locale_path, wa()->getActiveLocaleDomain(), false); } $plugin_info['name'] = _wp($plugin_info['name']); if (isset($plugin_info['title'])) { $plugin_info['title'] = _wp($plugin_info['title']); } if (isset($plugin_info['description'])) { $plugin_info['description'] = _wp($plugin_info['description']); } waSystem::popActivePlugin(); $plugin_info['id'] = $plugin_id; $plugin_info['app_id'] = $this->application; if (isset($plugin_info['img'])) { $plugin_info['img'] = 'wa-apps/' . $this->application . '/plugins/' . $plugin_id . '/' . $plugin_info['img']; } if (isset($plugin_info['rights']) && $plugin_info['rights']) { $plugin_info['handlers']['rights.config'] = 'rightsConfig'; } if (isset($plugin_info['frontend']) && $plugin_info['frontend']) { $plugin_info['handlers']['routing'] = 'routing'; } if (!empty($plugin_info[$this->application . '_settings'])) { $plugin_info['custom_settings'] = $plugin_info[$this->application . '_settings']; } $this->plugins[$plugin_id] = $plugin_info; } } if (!SystemConfig::isDebug()) { waUtils::varExportToFile($this->plugins, $file); } else { waFiles::delete($file); } } else { $this->plugins = (include $file); } } return $this->plugins; }
/** * * Returns path to config file * if $custom returns path in wa-config/apps/$app_id/$name * else wa-apps/$app_id/lib/config/$name * * @param string $name - filename * @param bool $custom - system or custom config */ public function configPath($name, $custom = false) { if ($custom) { $path = $this->getConfig()->getPath('config') . '/apps/' . $this->getApp() . '/' . $name; waFiles::create($path); return $path; } else { $path = $this->getConfig()->getAppPath('lib/config/' . $name); } return $path; }
public function execute() { $this->response = array(); // Initialize all needed post vars as $vars in current namespace foreach (array('x1', 'y1', 'x2', 'y2', 'w', 'h', 'ww', 'orig') as $var) { if (null === (${$var} = (int) waRequest::post($var))) { // $$ black magic... $this->response['error'] = 'wrong parameters'; return; } } $id = $this->getId(); $contact = new waContact($id); // Path to file we need to crop $rand = mt_rand(); $dir = waContact::getPhotoDir($id, true); $filename = wa()->getDataPath("{$dir}{$rand}.original.jpg", true, 'contacts'); $oldDir = wa()->getDataPath("{$dir}", true, 'contacts'); $no_old_photo = false; if (!$orig) { // Delete the old photos if they exist if (file_exists($oldDir)) { waFiles::delete($oldDir); $no_old_photo = true; } waFiles::create($oldDir); // Is there an uploaded file in session? $photoEditors = $this->getStorage()->read('photoEditors'); if (!isset($photoEditors[$id]) || !file_exists($photoEditors[$id])) { $this->response['error'] = 'Photo editor session is not found or already expired.'; return; } $newFile = $photoEditors[$id]; // Save the original image in jpeg for future use try { $img = waImage::factory($newFile)->save($filename); } catch (Exception $e) { $this->response['error'] = 'Unable to save new file ' . $filename . ' (' . pathinfo($filename, PATHINFO_EXTENSION) . ') as jpeg: ' . $e->getMessage(); return; } // Remove uploaded file unset($photoEditors[$id]); $this->getStorage()->write('photoEditors', $photoEditors); unlink($newFile); } else { // cropping an old file. Move it temporarily to temp dir to delete all cached thumbnails $oldFile = wa()->getDataPath("{$dir}{$contact['photo']}.original.jpg", TRUE, 'contacts'); $tempOldFile = wa()->getTempPath("{$id}/{$rand}.original.jpg", 'contacts'); waFiles::move($oldFile, $tempOldFile); // Delete thumbnails if (file_exists($oldDir)) { waFiles::delete($oldDir); } waFiles::create($oldDir); // return original image to its proper place waFiles::move($tempOldFile, $filename); } if (!file_exists($filename)) { $this->response['error'] = 'Image to crop not found (check directory access rights).'; return; } // Crop and save selected area $croppedFilename = wa()->getDataPath("{$dir}{$rand}.jpg", TRUE, 'contacts'); try { $img = waImage::factory($filename); $scale = $img->width / $ww; $img->crop(floor($w * $scale), floor($h * $scale), floor($x1 * $scale), floor($y1 * $scale))->save($croppedFilename); } catch (Exception $e) { $this->response['error'] = 'Unable to crop an image: ' . $e->getMessage(); return; } // Update record in DB for this user $contact['photo'] = $rand; $contact->save(); if ($no_old_photo) { $old_app = null; if (wa()->getApp() !== 'contacts') { $old_app = wa()->getApp(); waSystem::setActive('contacts'); } $this->logAction('photo_add', null, $contact->getId()); if ($old_app) { waSystem::setActive($old_app); } } // Update recent history to reload thumbnail correctly (if not called from personal account) if (wa()->getUser()->get('is_user')) { $history = new contactsHistoryModel(); $history->save('/contact/' . $id, null, null, '--'); } $this->response = array('url' => $contact->getPhoto()); }
/** * * Compress theme into archive file * @param string $path target archive path * @param string $name archive filename * @return string arcive path */ public function compress($path, $name = null) { if (!$name) { $name = "webasyst.{$this->app}.theme.{$this->id}.tar.gz"; } $target_file = "{$path}/{$this->app}/{$name}"; $autoload = waAutoload::getInstance(); $autoload->add('Archive_Tar', 'wa-installer/lib/vendors/PEAR/Tar.php'); $autoload->add('PEAR', 'wa-installer/lib/vendors/PEAR/PEAR.php'); if (file_exists($this->path) && class_exists('Archive_Tar', true)) { waFiles::create($target_file); $tar_object = new Archive_Tar($target_file, true); $tar_object->setIgnoreRegexp('@(\\.(php\\d?|svn|git|fw_|files\\.md5$))@'); $path = getcwd(); chdir(dirname($this->path)); if (!$tar_object->create('./' . basename($this->path))) { waFiles::delete($target_file); } chdir($path); } return $target_file; }
protected function checkAccess($path) { // create .htaccess to deny access to *.php and *.html files if (!file_exists($path . '/.htaccess')) { waFiles::create($path . '/'); $htaccess = <<<HTACCESS <FilesMatch "\\.(php\\d?|html)"> Deny from all </FilesMatch> HTACCESS; @file_put_contents($path . '/.htaccess', $htaccess); } }
/** * 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; }
public function getApps($system = false) { if (self::$apps === null) { $locale = $this->getUser()->getLocale(); $file = $this->config->getPath('cache', 'config/apps' . $locale); if (!file_exists($this->getConfig()->getPath('config', 'apps'))) { self::$apps = array(); throw new waException('File wa-config/apps.php not found.', 600); } if (!file_exists($file) || filemtime($file) < filemtime($this->getConfig()->getPath('config', 'apps')) || waSystemConfig::isDebug()) { waFiles::create($this->getConfig()->getPath('cache') . '/config'); $all_apps = (include $this->getConfig()->getPath('config', 'apps')); $all_apps['webasyst'] = true; self::$apps = array(); foreach ($all_apps as $app => $enabled) { if ($enabled) { waLocale::loadByDomain($app, $locale); $app_config = $this->getAppPath('lib/config/app.php', $app); if (!file_exists($app_config)) { if (false && SystemConfig::isDebug()) { throw new waException("Config not found. Create config by path " . $app_config); } continue; } $app_info = (include $app_config); $build_file = $app_config = $this->getAppPath('lib/config/build.php', $app); if (file_exists($build_file)) { $app_info['build'] = (include $build_file); } else { if (SystemConfig::isDebug()) { $app_info['build'] = time(); } else { $app_info['build'] = 0; } } $app_info['id'] = $app; $app_info['name'] = _wd($app, $app_info['name']); if (isset($app_info['icon'])) { if (is_array($app_info['icon'])) { foreach ($app_info['icon'] as $size => $url) { $app_info['icon'][$size] = 'wa-apps/' . $app . '/' . $url; } } else { $app_info['icon'] = array(48 => 'wa-apps/' . $app . '/' . $app_info['icon']); } } else { $app_info['icon'] = array(); } if (isset($app_info['img'])) { $app_info['img'] = 'wa-apps/' . $app . '/' . $app_info['img']; } else { $app_info['img'] = isset($app_info['icon'][48]) ? $app_info['icon'][48] : 'wa-apps/' . $app . '/img/' . $app . ".png"; } if (!isset($app_info['icon'][48])) { $app_info['icon'][48] = $app_info['img']; } if (!isset($app_info['icon'][24])) { $app_info['icon'][24] = $app_info['icon'][48]; } if (!isset($app_info['icon'][16])) { $app_info['icon'][16] = $app_info['icon'][24]; } self::$apps[$app] = $app_info; } } if (!file_exists($file) || filemtime($file) < filemtime($this->getConfig()->getPath('config', 'apps'))) { waUtils::varExportToFile(self::$apps, $file); } } else { self::$apps = (include $file); waLocale::loadByDomain('webasyst', $locale); } } if ($system) { return self::$apps; } else { $apps = self::$apps; unset($apps['webasyst']); return $apps; } }
public function execute() { $path = $this->getConfig()->getPath('config', 'routing'); if (file_exists($path)) { $routes = (include $path); } else { $routes = array(); } $domain = siteHelper::getDomain(); $url = mb_strtolower(rtrim(waRequest::post('url'), '/')); if ($url != $domain) { $domain_model = new siteDomainModel(); // domain already exists if ($domain_model->getByName($url)) { $this->errors = sprintf(_w("Website with a domain name %s is already registered in this Webasyst installation. Delete %s website (Site app > %s > Settings) to be able to use it's domain name for another website."), $url, $url, $url); return; } $domain_model->updateById(siteHelper::getDomainId(), array('name' => $url)); $routes[$url] = $routes[$domain]; unset($routes[$domain]); // move configs $old = $this->getConfig()->getConfigPath('domains/' . $domain . '.php'); if (file_exists($old)) { waFiles::move($old, $this->getConfig()->getConfigPath('domains/' . $url . '.php')); } $old = wa()->getDataPath('data/' . $domain . '/', true, 'site', false); if (file_exists($old)) { waFiles::move($old, wa()->getDataPath('data/' . $url . '/', true)); clearstatcache(); try { waFiles::delete($old, true); } catch (waException $e) { } } $domain = $url; siteHelper::setDomain(siteHelper::getDomainId(), $domain); } // save wa_apps $domain_config_path = $this->getConfig()->getConfigPath('domains/' . $domain . '.php'); if (file_exists($domain_config_path)) { $domain_config = (include $domain_config_path); } else { $domain_config = array(); } $title = waRequest::post('title'); $style = waRequest::post('background'); if (!$style || substr($style, 0, 1) == '.') { if ($s = $this->saveBackground()) { $style = '.' . $s; } } $domain_model = new siteDomainModel(); $domain_model->updateById(siteHelper::getDomainId(), array('title' => $title, 'style' => $style)); $save_config = false; if ($title) { $domain_config['name'] = $title; $save_config = true; } else { if (isset($domain_config['name'])) { unset($domain_config['name']); $save_config = true; } } waUtils::varExportToFile($routes, $path); if (waRequest::post('wa_apps_type')) { $apps = waRequest::post('apps'); if (!$domain_config) { // create directory waFiles::create($domain_config_path); } $domain_config['apps'] = array(); foreach ($apps['url'] as $i => $u) { $domain_config['apps'][] = array('url' => $u, 'name' => $apps['name'][$i]); } $save_config = true; } else { if (isset($domain_config['apps'])) { unset($domain_config['apps']); $save_config = true; } } if (waRequest::post('cdn')) { $domain_config['cdn'] = waRequest::post('cdn'); $save_config = true; } elseif (!empty($domain_config['cdn'])) { unset($domain_config['cdn']); $save_config = true; } // save other settings foreach (array('head_js', 'google_analytics') as $key) { if (!empty($domain_config[$key]) || waRequest::post($key)) { $domain_config[$key] = waRequest::post($key); $save_config = true; } } if ($save_config && !waUtils::varExportToFile($domain_config, $domain_config_path)) { $this->errors = sprintf(_w('Settings could not be saved due to the insufficient file write permissions for the "%s" folder.'), 'wa-config/apps/site/domains'); } $this->saveFavicon(); $this->saveTouchicon(); $this->saveRobots(); $this->logAction('site_edit'); }
if ($matches[4] && $app_config->getOption('enable_2x')) { $enable_2x = true; $size = explode('x', $size); foreach ($size as &$s) { $s *= 2; } unset($s); $size = implode('x', $size); } } wa()->getStorage()->close(); if ($file && file_exists($protected_path . $file) && !file_exists($public_path . $request_file)) { $main_thumb_file_path = $public_path . $main_thumb_file; $target_dir_path = dirname($public_path . $request_file); if (!file_exists($target_dir_path)) { waFiles::create($target_dir_path . '/'); } $max_size = $app_config->getOption('max_size'); $image = photosPhoto::generateThumb(array('path' => $main_thumb_file_path, 'size' => $main_thumbnail_size), $protected_path . $file, $size, $app_config->getOption('sharpen'), $max_size ? $enable_2x ? 2 * $max_size : $max_size : false); if ($image) { $quality = $app_config->getSaveQuality($enable_2x); $image->save($public_path . $request_file, $quality); clearstatcache(); } } if ($file && file_exists($public_path . $request_file)) { waFiles::readFile($public_path . $request_file); } else { /* $url = wa()->getRootUrl(); $url = substr($url, 0, -strlen('/wa-data/public/photo/'));
private function error($message) { $path = wa()->getConfig()->getPath('log'); waFiles::create($path . '/shop/images_regenerate.log'); waLog::log($message, 'shop/images_regenerate.log'); }
private function error($message) { $path = wa()->getConfig()->getPath('log'); waFiles::create($path . '/shop/csvproducts.log'); waLog::log($message, 'shop/csvproducts.log'); }
/** * @return bool */ protected function saveFromPost($form, $contact) { $data = $form->post(); if (!$data || !is_array($data)) { return false; } // save photo before all $photo_file = waRequest::file('photo_file'); if (array_key_exists('photo', $data)) { if ($photo_file->uploaded() && ($avatar = $photo_file->waImage())) { // add/update photo $square = min($avatar->height, $avatar->width); // setPhoto with crop $rand = mt_rand(); $path = wa()->getDataPath(waContact::getPhotoDir($contact->getId()), 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($photo_file)->save($filename, 90); $filename = $path . $rand . ".jpg"; waFiles::create($filename); waImage::factory($photo_file)->crop($square, $square)->save($filename, 90); waContactFields::getStorage('waContactInfoStorage')->set($contact, array('photo' => $rand)); } elseif (empty($data['photo'])) { // remove photo $contact->set('photo', ""); } $this->form->values['photo'] = $data['photo'] = $contact->get('photo'); } // Validation if (!$form->isValid($contact)) { return false; } // Password validation if (!empty($data['password']) && $data['password'] !== $data['password_confirm']) { $form->errors('password', _ws('Passwords do not match')); return false; } elseif (empty($data['password']) || empty($data['password_confirm'])) { unset($data['password']); } unset($data['password_confirm']); // get old data for logging if ($this->contact) { $old_data = array(); foreach ($data as $field_id => $field_value) { $old_data[$field_id] = $this->contact->get($field_id); } } foreach ($data as $field => $value) { $contact->set($field, $value); } $errors = $contact->save(); // If something went wrong during save for any reason, // show it to user. In theory it shouldn't but better be safe. if ($errors) { foreach ($errors as $field => $errs) { foreach ($errs as $e) { $form->errors($field, $e); } } return false; } // get new data for logging $new_data = array(); foreach ($data as $field_id => $field_value) { if (!isset($errors[$field_id])) { $new_data[$field_id] = $this->contact->get($field_id); } } $this->logProfileEdit($old_data, $new_data); return true; }
<?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); }