/** * Authenticate user/password * * @access public * @param string $user User's name or email * @param string $password User's password * @return mixed Array of user's information otherwise Jaws_Error */ function Auth($user, $password) { if (!function_exists('imap_open')) { return Jaws_Error::raiseError('Undefined function imap_open()', __FUNCTION__); } $mbox = @imap_open('{' . $this->_Server . ':' . $this->_Port . ($this->_SSL ? '/imap/ssl' : '') . '}INBOX', $user, $password); if ($mbox) { @imap_close($mbox); $result = array(); $result['id'] = strtolower('imap:' . $user); $result['internal'] = false; $result['username'] = $user; $result['superadmin'] = false; $result['internal'] = false; $result['groups'] = array(); $result['nickname'] = $user; $result['concurrents'] = 0; $result['email'] = ''; $result['url'] = ''; $result['avatar'] = 'gadgets/Users/Resources/images/photo48px.png'; $result['language'] = ''; $result['theme'] = ''; $result['editor'] = ''; $result['timezone'] = null; return $result; } return Jaws_Error::raiseError(_t('GLOBAL_ERROR_LOGIN_WRONG'), __FUNCTION__); }
/** * Get files of the current root dir * * @access public * @param string $path Current directory * @return array A list of directories or files of a certain directory */ function GetCurrentRootDir($path) { $path = trim($path, '/'); $path = str_replace('..', '', $path); $fModel = $this->gadget->model->load('Files'); if (!is_dir($fModel->GetFileBrowserRootDir() . $path)) { return Jaws_Error::raiseError(_t('FILEBROWSER_ERROR_DIRECTORY_DOES_NOT_EXISTS'), 404, JAWS_ERROR_NOTICE); } $tree = array(); $tree['/'] = '/'; if (!empty($path)) { $parent_path = substr(strrev($path), 1); if (strpos($parent_path, '/')) { $parent_path = strrev(substr($parent_path, strpos($parent_path, '/'), strlen($parent_path))); } else { $parent_path = ''; } $vpath = ''; foreach (explode('/', $path) as $k) { if ($k != '') { $vpath .= '/' . $k; $tree[$vpath] = $k; } } } else { $tree[] = $path; } return $tree; }
/** * Updates the Tag gadget settings * * @access public * @param string $tagResultLimit Allow comments? * @return mixed True on success or Jaws_Error on failure */ function SaveSettings($tagResultLimit) { $res = $this->gadget->registry->update('tag_results_limit', $tagResultLimit); if ($res === false) { return Jaws_Error::raiseError(_t('TAGS_ERROR_CANT_UPDATE_PROPERTIES'), __FUNCTION__); } return true; }
/** * Updates the Comments gadget settings * * @access public * @param string $allowComments Allow comments? * @param int $defaultStatus Default comment status * @param int $orderType Order type * @return mixed True on success or Jaws_Error on failure */ function SaveSettings($allowComments, $defaultStatus, $orderType) { $res = $this->gadget->registry->update('allow_comments', $allowComments); $res = $res && $this->gadget->registry->update('default_comment_status', $defaultStatus); $res = $res && $this->gadget->registry->update('order_type', $orderType); if ($res === false) { return Jaws_Error::raiseError(_t('COMMENTS_ERROR_CANT_UPDATE_PROPERTIES'), __FUNCTION__); } return true; }
/** * Returns array of forum properties * * @access public * @param int $fid forum ID * @return mixed Array of forum properties or Jaws_Error on error */ function GetForum($fid) { $perm = $this->gadget->GetPermission('ForumPublic', $fid); if (is_null($perm)) { return Jaws_Error::raiseError(_t('GLOBAL_HTTP_ERROR_CONTENT_404'), 404, JAWS_ERROR_NOTICE); } if (!$perm) { return Jaws_Error::raiseError(_t('GLOBAL_ERROR_ACCESS_DENIED'), 403, JAWS_ERROR_NOTICE); } $table = Jaws_ORM::getInstance()->table('forums'); $table->select('id:integer', 'gid:integer', 'title', 'description', 'fast_url', 'topics:integer', 'posts:integer', 'order:integer', 'locked:boolean', 'published:boolean'); if (is_numeric($fid)) { $table->where('id', $fid); } else { $table->where('fast_url', $fid); } return $table->fetchRow(); }
/** * Listen network port over given address * * @access public * @param string $path path of web socket server * @param string $origin indicates the origin of the script establishing the connection * @param mixed $callback callback function loaded when data received * @return mixed True on success or Jaws_Error on failure */ public function open($path, $origin = '', $callback = null) { if (!($this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { return $this->close(); } // set send/receive timeouts socket_set_option($this->socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $this->receive_timeout, 'usec' => 0)); socket_set_option($this->socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => $this->send_timeout, 'usec' => 0)); // trying connect to WebSocket server if (false === @socket_connect($this->socket, $this->address, $this->port)) { return $this->close($this->socket); } $randomKey = base64_encode(Jaws_Utils::RandomText(16, true, true, true)); $header = "GET {$path} HTTP/1.1\r\n"; $header .= "Host: {$this->address}:{$this->port}\r\n"; $header .= "Upgrade: websocket\r\n"; $header .= "Connection: Upgrade\r\n"; $header .= "Sec-WebSocket-Key: {$randomKey}\r\n"; if (!empty($origin)) { $header .= "Sec-WebSocket-Origin: {$origin}\r\n"; } $header .= "Sec-WebSocket-Version: 13\r\n"; $header .= "\r\n"; // send hand-shake header if (false === @socket_write($this->socket, $header)) { return $this->close($this->socket); } // trying receive hand-shake response if (false === @socket_recv($this->socket, $response, 1024, 0)) { $last_error = error_get_last(); return $this->close($this->socket, $last_error['message']); } $expectedKey = $randomKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; $expectedKey = base64_encode(sha1($expectedKey, true)); if (preg_match('#Sec-WebSocket-Accept: (.*)\\r\\n\\r\\n$#imU', $response, $matches)) { $acceptKey = trim($matches[1]); if ($acceptKey === $expectedKey) { return true; } } $this->close($this->socket); return Jaws_Error::raiseError('Response header not valid'); }
/** * Loads the gadget hook file class in question, makes a instance and * stores it globally for later use so we do not have duplicates * of the same instance around in our code. * * @access public * @param string $hook Hook name * @return mixed Hook class object on successful, Jaws_Error otherwise */ public function &load($hook) { // filter non validate character $hook = preg_replace('/[^[:alnum:]_]/', '', $hook); if (!isset($this->objects[$hook])) { $classname = $this->gadget->name . '_Hooks_' . $hook; $file = JAWS_PATH . 'gadgets/' . $this->gadget->name . "/Hooks/{$hook}.php"; if (!file_exists($file)) { return Jaws_Error::raiseError("File [{$file}] not exists!", __FUNCTION__); } include_once $file; if (!Jaws::classExists($classname)) { return Jaws_Error::raiseError("Class [{$classname}] not exists!", __FUNCTION__); } $this->objects[$hook] = new $classname($this->gadget); $GLOBALS['log']->Log(JAWS_LOG_DEBUG, "Loaded gadget hook: [{$classname}]"); } return $this->objects[$hook]; }
/** * User authentication * * @access public * @param string $user username * @param string $password password * @return mixed True or Jaws_Error */ function userAuthentication($username, $password) { $authType = $GLOBALS['app']->Registry->fetch('authtype', 'Users'); $authType = preg_replace('/[^[:alnum:]_\\-]/', '', $authType); $authFile = JAWS_PATH . 'include/Jaws/Auth/' . $authType . '.php'; if (empty($authType) || !file_exists($authFile)) { $GLOBALS['log']->Log(JAWS_LOG_NOTICE, $authFile . ' file doesn\'t exists, using default authentication type'); $authType = 'Default'; } if ($username === '' && $password === '') { $result = Jaws_Error::raiseError(_t('GLOBAL_ERROR_LOGIN_WRONG'), __FUNCTION__, JAWS_ERROR_NOTICE); } require_once JAWS_PATH . 'include/Jaws/Auth/' . $authType . '.php'; $className = 'Jaws_Auth_' . $authType; $objAuth = new $className(); $result = $objAuth->Auth($username, $password); if (!Jaws_Error::IsError($result)) { $GLOBALS['app']->Session->SetAttribute('logged', true); $GLOBALS['app']->Session->SetAttribute('user', $result['id']); $GLOBALS['app']->Session->SetAttribute('groups', $result['groups']); $GLOBALS['app']->Session->SetAttribute('superadmin', $result['superadmin']); } return $result; }
/** * Get topics of forum * * @access public * @param int $fid Forum ID * @param int $published Is Published ? * @param int $uid User id * @param int $limit Count of topics to be returned * @param int $offset Offset of data array * @return mixed Array of topics or Jaws_Error on failure */ function GetTopics($fid, $published = null, $uid = null, $limit = 0, $offset = null) { $perm = $this->gadget->GetPermission('ForumPublic', $fid); if (is_null($perm)) { return Jaws_Error::raiseError(_t('GLOBAL_HTTP_ERROR_CONTENT_404'), 404, JAWS_ERROR_NOTICE); } if (!$perm) { return Jaws_Error::raiseError(_t('GLOBAL_ERROR_ACCESS_DENIED'), 403, JAWS_ERROR_NOTICE); } $table = Jaws_ORM::getInstance()->table('forums_topics'); $table->select('forums_topics.id:integer', 'fid:integer', 'subject', 'views:integer', 'replies:integer', 'first_post_id:integer', 'first_post_uid:integer', 'first_post_time:integer', 'last_post_id:integer', 'last_post_uid:integer', 'last_post_time:integer', 'fuser.username as first_username', 'fuser.nickname as first_nickname', 'luser.username as last_username', 'luser.nickname as last_nickname', 'locked:boolean', 'published:boolean'); $table->join('users as fuser', 'forums_topics.first_post_uid', 'fuser.id', 'left'); $table->join('users as luser', 'forums_topics.last_post_uid', 'luser.id', 'left'); $table->where('fid', $fid)->orderBy('last_post_time desc')->limit($limit, $offset); if (empty($uid)) { if (!is_null($published)) { $table->and()->where('published', (bool) $published); } } else { $published = is_null($published) ? true : (bool) $published; $table->and()->openWhere('first_post_uid', (int) $uid)->or()->closeWhere('published', $published); } return $table->fetchAll(); }
/** * Does any actions required to finish the stage, such as DB queries. * * @access public * @return bool|Jaws_Error Either true on success, or a Jaws_Error * containing the reason for failure. */ function Run() { if (version_compare($_SESSION['upgrade']['InstalledVersion'], '0.9.0', '<')) { return Jaws_Error::raiseError(_t('UPGRADE_REPORT_NOT_SUPPORTED'), 0, JAWS_ERROR_WARNING); } if (is_dir(JAWS_DATA . "languages")) { // transform customized translated files $rootfiles = array('Global.php', 'Date.php', 'Install.php', 'Upgrade.php'); $languages = scandir(JAWS_DATA . 'languages'); foreach ($languages as $lang) { if ($lang == '.' || $lang == '..') { continue; } $ostr = "define('_" . strtoupper($lang) . '_'; $nstr = "define('_" . strtoupper($lang) . '_DATA_'; // gadgets if (is_dir(JAWS_DATA . "languages/{$lang}/gadgets")) { $lGadgets = scandir(JAWS_DATA . "languages/{$lang}/gadgets"); foreach ($lGadgets as $lGadget) { if ($lGadget == '.' || $lGadget == '..') { continue; } $fstring = @file_get_contents(JAWS_DATA . "languages/{$lang}/gadgets/{$lGadget}"); $fstring = strtr($fstring, array($nstr => $nstr, $ostr => $nstr)); @file_put_contents(JAWS_DATA . "languages/{$lang}/gadgets/{$lGadget}", $fstring); } } // plugins if (is_dir(JAWS_DATA . "languages/{$lang}/plugins")) { $lPlugins = scandir(JAWS_DATA . "languages/{$lang}/plugins"); foreach ($lPlugins as $lPlugin) { if ($lPlugin == '.' || $lPlugin == '..') { continue; } $fstring = @file_get_contents(JAWS_DATA . "languages/{$lang}/plugins/{$lPlugin}"); $fstring = strtr($fstring, array($nstr => $nstr, $ostr => $nstr)); @file_put_contents(JAWS_DATA . "languages/{$lang}/plugins/{$lPlugin}", $fstring); } } } // others foreach ($rootfiles as $rfile) { if (file_exists(JAWS_DATA . "languages/{$lang}/{$rfile}")) { $fstring = @file_get_contents(JAWS_DATA . "languages/{$lang}/{$rfile}"); $fstring = strtr($fstring, array($nstr => $nstr, $ostr => $nstr)); @file_put_contents(JAWS_DATA . "languages/{$lang}/{$rfile}", $fstring); } } } foreach ($_SESSION['upgrade']['stagedVersions'] as $stagedVersion) { if (!$_SESSION['upgrade']['versions'][$stagedVersion]['status']) { if ($_SESSION['upgrade']['stage'] < $_SESSION['upgrade']['versions'][$stagedVersion]['stage']) { return true; } else { $_SESSION['upgrade']['stage']++; } } else { $_SESSION['upgrade']['stage']++; } } return true; }
/** * Displays image without saving and lose changes. * This method adds the Content-type HTTP header * * @access public * @param string $type Output format, default is the current used format * @param int $quality Image quality, default is 75 * @param int $expires Set Cache-Control and Expires of HTTP header * @return mixed True on success or a Jaws_Error object on error */ function display($type = '', $quality = null, $expires = 0) { if ($this->_readonly) { $result = parent::display($type, $quality, $expires); return $result; } $options = is_array($quality) ? $quality : array(); if (is_numeric($quality)) { $options['quality'] = $quality; } $quality = $this->_getOption('quality', $options, 75); $type = $type == 'jpg' ? 'jpeg' : $type; $type = strtolower($type == '' ? $this->_itype : $type); $type = empty($type) ? 'png' : $type; if (!$this->_typeSupported($type, 'w')) { return Jaws_Error::raiseError('Image type not supported for output.', __FUNCTION__); } if (!empty($expires)) { header("Cache-Control: max-age=" . $expires); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT'); } if (function_exists('imagealphablending')) { imagealphablending($this->_hImage, false); imagesavealpha($this->_hImage, true); } $funcName = 'image' . $type; header('Content-type: ' . image_type_to_mime_type($this->get_image_extension_to_type($type))); ob_start(); switch ($type) { case 'jpeg': $result = $funcName($this->_hImage, null, $quality); break; default: $result = $funcName($this->_hImage); } $content = ob_get_contents(); ob_end_clean(); $this->free(); if (!$result) { return Jaws_Error::raiseError('Couldn\'t display image', __FUNCTION__); } return $content; }
/** * Upload Files * * @access public * @param array $files $_FILES array * @param string $dest destination directory(include end directory separator) * @param string $allow_formats permitted file format * @param bool $overwrite overwrite file or generate random filename * null: random, true/false: overwrite? * @param bool $move_files moving or only copying files. this param avail for non-uploaded files * @param int $max_size max size of file * @return mixed Returns uploaded files array on success or Jaws_Error/FALSE on failure */ static function UploadFiles($files, $dest, $allow_formats = '', $overwrite = true, $move_files = true, $max_size = null) { if (empty($files) || !is_array($files)) { return false; } $result = array(); if (isset($files['tmp_name'])) { $files = array($files); } $finfo = false; if (extension_loaded('fileinfo')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type of file extension } $dest = rtrim($dest, "\\/") . DIRECTORY_SEPARATOR; $allow_formats = array_filter(explode(',', $allow_formats)); foreach ($files as $key => $listFiles) { if (!is_array($listFiles['tmp_name'])) { $listFiles = array_map(create_function('$item', 'return array($item);'), $listFiles); } for ($i = 0; $i < count($listFiles['name']); ++$i) { $file = array(); $file['name'] = $listFiles['name'][$i]; $file['tmp_name'] = $listFiles['tmp_name'][$i]; $file['size'] = $listFiles['size'][$i]; if (isset($listFiles['error'])) { $file['error'] = $listFiles['error'][$i]; } if (isset($file['error']) && !empty($file['error']) && $file['error'] != 4) { return Jaws_Error::raiseError(_t('GLOBAL_ERROR_UPLOAD_' . $file['error']), __FUNCTION__); } if (empty($file['tmp_name'])) { continue; } $file['type'] = $finfo ? finfo_file($finfo, $file['tmp_name']) : ''; $user_filename = isset($file['name']) ? $file['name'] : ''; $host_filename = strtolower(preg_replace('/[^[:alnum:]_\\.\\-]/', '', $user_filename)); // remove deny_formats extension, even double extension $host_filename = implode('.', array_diff(array_filter(explode('.', $host_filename)), self::$deny_formats)); $fileinfo = pathinfo($host_filename); if (isset($fileinfo['extension'])) { if (!empty($allow_formats) && !in_array($fileinfo['extension'], $allow_formats)) { return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD_INVALID_FORMAT', $host_filename), __FUNCTION__); } $fileinfo['extension'] = '.' . $fileinfo['extension']; } else { $fileinfo['extension'] = ''; } if (is_null($overwrite) || empty($fileinfo['filename'])) { $host_filename = time() . mt_rand() . $fileinfo['extension']; } elseif (!$overwrite && file_exists($dest . $host_filename)) { $host_filename .= $fileinfo['filename'] . '_' . time() . mt_rand() . $fileinfo['extension']; } $uploadfile = $dest . $host_filename; if (is_uploaded_file($file['tmp_name'])) { if (!move_uploaded_file($file['tmp_name'], $uploadfile)) { return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD', $host_filename), __FUNCTION__); } } else { // On windows-systems we can't rename a file to an existing destination, // So we first delete destination file if (file_exists($uploadfile)) { @unlink($uploadfile); } $res = $move_files ? @rename($file['tmp_name'], $uploadfile) : @copy($file['tmp_name'], $uploadfile); if (!$res) { return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD', $host_filename), __FUNCTION__); } } // Check if the file has been altered or is corrupted if (filesize($uploadfile) != $file['size']) { @unlink($uploadfile); return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD_CORRUPTED', $host_filename), __FUNCTION__); } Jaws_Utils::chmod($uploadfile); $result[$key][$i]['user_filename'] = $user_filename; $result[$key][$i]['host_filename'] = $host_filename; $result[$key][$i]['host_filetype'] = $file['type']; $result[$key][$i]['host_filesize'] = $file['size']; } } return $result; }
/** * drop an existing table via MDB2 management module * * @access public * @param string $table name of table * @return mixed MDB2_OK on success, a MDB2 error on failure */ function dropTable($table) { $this->dbc->loadModule('Manager'); $result = $this->dbc->manager->dropTable($this->getPrefix() . $table); if (MDB2::isError($result)) { if ($result->getCode() !== MDB2_ERROR_NOSUCHTABLE) { return Jaws_Error::raiseError($result->getMessage(), $result->getCode(), JAWS_ERROR_ERROR, 1); } } return true; }
/** * Displays image without saving and lose changes. * This method adds the Content-type HTTP header * * @access public * @param string $type Output format, default is the current used format * @param int $quality Image quality, default is 75 * @param int $expires Set Cache-Control and Expires of HTTP header * @return mixed True on success or a Jaws_Error object on error */ function display($type = '', $quality = null, $expires = 0) { if ($this->_readonly) { $result = parent::display($type, $quality, $expires); return $result; } $options = is_array($quality) ? $quality : array(); if (is_numeric($quality)) { $options['quality'] = $quality; } $quality = $this->_getOption('quality', $options, 75); try { $this->_hImage->setImageCompression($quality); } catch (ImagickException $error) { return Jaws_Error::raiseError('Could not set image compression.', __FUNCTION__); } $type = $type == 'jpg' ? 'jpeg' : $type; $type = strtolower($type == '' ? $this->_itype : $type); $type = empty($type) ? 'png' : $type; try { $this->_hImage->setImageFormat($type); } catch (ImagickException $error) { return Jaws_Error::raiseError('Could not save image to file (conversion failed).', __FUNCTION__); } try { $result = $this->_hImage->getImageBlob(); } catch (ImagickException $error) { return Jaws_Error::raiseError('Could not display image.', __FUNCTION__); } if (!empty($expires)) { header("Cache-Control: max-age=" . $expires); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT'); } header('Content-type: ' . image_type_to_mime_type($this->get_image_extension_to_type($type))); $this->free(); return $result; }
/** * Raw posts data to the URL * * @access public * @param string $url URL address * @param string $data Raw data * @param string $response Response body * @return mixed Response code on success, otherwise Jaws_Error */ function rawPostData($url, $data = '', &$response) { $this->httpRequest->reset($url, $this->options); $this->httpRequest->addHeader('User-Agent', $this->user_agent); $this->httpRequest->addHeader('Content-Type', $this->content_type); $this->httpRequest->setMethod(HTTP_REQUEST_METHOD_POST); // set post data $this->httpRequest->setBody($data); $result = $this->httpRequest->sendRequest(); if (PEAR::isError($result)) { return Jaws_Error::raiseError($result->getMessage(), $result->getCode(), $this->default_error_level, 1); } $response = $this->httpRequest->getResponseBody(); return $this->httpRequest->getResponseCode(); }
/** * Delete post * * @access public * @param int $pid Post ID * @param int $tid Topic ID * @param int $fid Forum ID * @return mixed True on successfully or Jaws_Error on failure */ function DeletePost($pid, $tid, $fid) { if (!$this->gadget->GetPermission('ForumPublic', $fid)) { return Jaws_Error::raiseError(_t('GLOBAL_ERROR_ACCESS_DENIED'), 403, JAWS_ERROR_NOTICE); } $table = Jaws_ORM::getInstance()->table('forums_posts'); $result = $table->delete()->where('id', $pid)->exec(); if (Jaws_Error::IsError($result)) { return $result; } // remove attachment file $aModel = $this->gadget->model->load('Attachments'); $aModel->DeletePostAttachments($pid); $tModel = $this->gadget->model->load('Topics'); $result = $tModel->UpdateTopicStatistics($tid); if (Jaws_Error::IsError($result)) { return $result; } $fModel = $this->gadget->model->load('Forums'); $result = $fModel->UpdateForumStatistics($fid); if (Jaws_Error::IsError($result)) { return $result; } return true; }
/** * Displays the captcha image * * @access public * @param int $key Captcha key * @return mixed Captcha raw image data or Jaws_Error if this method not supported */ function image($key) { return Jaws_Error::raiseError('image() method not supported by this captcha.', __FUNCTION__); }
/** * Sends data to the given client * * @access public * @param int $keySock Socket identifier * @param string $buffer Buffer data * @return mixed True or Jaws_Error */ public function send($keySock, &$buffer) { if (!socket_write(@$this->liveSocks[$keySock], $this->encode($buffer))) { return Jaws_Error::raiseError(socket_strerror(socket_last_error())); } return true; }
/** * Update the info of a group * * @access public * @param int $id Group ID * @param array $gData Group information data * @param int $owner The owner of group * @return bool Returns true if group was sucessfully updated, false if not */ function UpdateGroup($id, $gData, $owner = 0) { // unset invalid keys $invalids = array_diff(array_keys($gData), array('name', 'title', 'description', 'enabled')); foreach ($invalids as $invalid) { unset($gData[$invalid]); } // name if (isset($gData['name'])) { $gData['name'] = trim($gData['name'], '-_.@'); if (!preg_match('/^[[:alnum:]-_.@]{3,32}$/', $gData['name'])) { return Jaws_Error::raiseError(_t('GLOBAL_ERROR_INVALID_GROUPNAME'), __FUNCTION__, JAWS_ERROR_NOTICE); } $gData['name'] = strtolower($gData['name']); } $gData['owner'] = (int) $owner; // title if (isset($gData['title'])) { $gData['title'] = Jaws_UTF8::trim($gData['title']); if (empty($gData['title'])) { return Jaws_Error::raiseError(_t('GLOBAL_ERROR_INCOMPLETE_FIELDS'), __FUNCTION__, JAWS_ERROR_NOTICE); } } if (isset($gData['enabled'])) { $gData['enabled'] = (bool) $gData['enabled']; } $groupsTable = Jaws_ORM::getInstance()->table('groups'); $result = $groupsTable->update($gData)->where('id', $id)->exec(); if (Jaws_Error::IsError($result)) { if (MDB2_ERROR_CONSTRAINT == $result->getCode()) { $result->SetMessage(_t('USERS_GROUPS_ALREADY_EXISTS', $gData['name'])); } return $result; } // Let everyone know a group has been updated $res = $GLOBALS['app']->Listener->Shout('Users', 'UpdateGroup', $id); if (Jaws_Error::IsError($res)) { //do nothing } return true; }
/** * Send message * * @access public * @param integer $user User id * @param array $messageData Message data * @return mixed Message Id or Jaws_Error on failure */ function SendMessage($user, $messageData) { $table = Jaws_ORM::getInstance(); // merge recipient users & groups to an array $recipient_users = array(); if (trim($messageData['recipient_users']) == '0' || !empty($messageData['recipient_users'])) { if (trim($messageData['recipient_users']) == '0') { $table = $table->table('users'); $recipient_users = $table->select('id:integer')->fetchColumn(); } else { $recipient_users = explode(",", $messageData['recipient_users']); } } if (!empty($messageData['recipient_groups'])) { $recipient_groups = explode(",", $messageData['recipient_groups']); $table = $table->table('users_groups'); $table->select('user_id:integer'); $table->join('groups', 'groups.id', 'users_groups.group_id'); $table->where('group_id', $recipient_groups, 'in'); $group_users = $table->and()->where('groups.owner', $user)->fetchColumn(); if (!empty($group_users) && count($group_users) > 0) { $recipient_users = array_merge($recipient_users, $group_users); } } $recipient_users = array_unique($recipient_users); // validation input fields if (empty($messageData['subject']) || $messageData['folder'] != PrivateMessage_Info::PRIVATEMESSAGE_FOLDER_DRAFT && (empty($recipient_users) || count($recipient_users) <= 0)) { return Jaws_Error::raiseError(_t('PRIVATEMESSAGE_MESSAGE_INCOMPLETE_FIELDS'), __FUNCTION__, JAWS_ERROR_NOTICE); } $mTable = $table->table('pm_messages'); //Start Transaction $mTable->beginTransaction(); $messageIds = array(); $data = array(); $data['folder'] = $messageData['folder']; $data['subject'] = $messageData['subject']; $data['body'] = $messageData['body']; $data['attachments'] = isset($messageData['attachments']) ? count($messageData['attachments']) : 0; $data['recipient_users'] = $messageData['recipient_users']; $data['recipient_groups'] = isset($messageData['recipient_groups']) ? $messageData['recipient_groups'] : null; $data['update_time'] = time(); // Detect notification, draft or publish? $is_notification = $messageData['folder'] == PrivateMessage_Info::PRIVATEMESSAGE_FOLDER_NOTIFICATIONS; if ($messageData['folder'] == PrivateMessage_Info::PRIVATEMESSAGE_FOLDER_DRAFT) { if (empty($messageData['id'])) { // save new draft message $data['from'] = $user; $data['to'] = 0; $data['read'] = true; $data['insert_time'] = time(); $senderMessageId = $mTable->insert($data)->exec(); } else { // update old message info $senderMessageId = $messageData['id']; $mTable->update($data)->where('id', $senderMessageId)->exec(); } } else { // First insert a message in sender's outbox if (empty($messageData['id'])) { // new message if ($is_notification) { $senderMessageId = 0; } else { $data['folder'] = PrivateMessage_Info::PRIVATEMESSAGE_FOLDER_OUTBOX; $data['from'] = $user; $data['to'] = 0; $data['read'] = true; $data['insert_time'] = time(); $senderMessageId = $mTable->insert($data)->exec(); } } else { // update message $mTable->update($data)->where('id', $messageData['id'])->exec(); $senderMessageId = $messageData['id']; } // Insert message for every recipient if (!empty($recipient_users) && count($recipient_users) > 0) { $table = $table->table('pm_messages'); $from = $is_notification ? 0 : $user; $data['folder'] = $messageData['folder']; foreach ($recipient_users as $recipient_user) { $data['insert_time'] = time(); $data['from'] = $from; $data['to'] = $recipient_user; $data['read'] = false; $messageId = $table->insert($data)->exec(); if (Jaws_Error::IsError($messageId)) { //Rollback Transaction $table->rollback(); return false; } $messageIds[] = $messageId; // send notification on new private message if (!$is_notification) { $params = array(); $params['key'] = crc32('PrivateMessage' . $senderMessageId); $params['title'] = _t('PRIVATEMESSAGE_NEW_MESSAGE_NOTIFICATION_TITLE'); $params['summary'] = _t('PRIVATEMESSAGE_NEW_MESSAGE_NOTIFICATION'); $params['description'] = _t('PRIVATEMESSAGE_NEW_MESSAGE_NOTIFICATION_DESC', $data['subject']); $params['user'] = (int) $recipient_user; $this->gadget->event->shout('Notify', $params); } } } } // Insert attachments info if (!empty($messageData['attachments']) && count($messageData['attachments']) > 0) { $maData = array(); $pm_dir = JAWS_DATA . 'pm' . DIRECTORY_SEPARATOR . 'attachments' . DIRECTORY_SEPARATOR; foreach ($messageData['attachments'] as $attachment) { // check new attachments file -- we must copy tmp files to correct location if (is_array($attachment)) { $src_filepath = Jaws_Utils::upload_tmp_dir() . '/' . $attachment['filename']; $dest_filepath = $pm_dir . $attachment['filename']; if (!file_exists($src_filepath)) { continue; } if (!file_exists($pm_dir)) { if (!Jaws_Utils::mkdir($pm_dir)) { return new Jaws_Error(_t('GLOBAL_ERROR_FAILED_CREATING_DIR', JAWS_DATA)); } } $cres = Jaws_Utils::rename($src_filepath, $dest_filepath); Jaws_Utils::delete($src_filepath); if ($cres) { $aData = array('title' => $attachment['title'], 'filename' => $attachment['filename'], 'filesize' => $attachment['filesize'], 'filetype' => $attachment['filetype']); $table = $table->table('pm_attachments'); $attachmentId = $table->insert($aData)->exec(); if (Jaws_Error::IsError($attachmentId)) { //Rollback Transaction $table->rollback(); return false; } // Add sender message Id to pm_message_attachment table $maData[] = array('message' => $senderMessageId, 'attachment' => $attachmentId); // Add recipient message Id to pm_message_attachment table foreach ($messageIds as $messageId) { $maData[] = array('message' => $messageId, 'attachment' => $attachmentId); } } } else { // Add sender message Id to pm_message_attachment table $maData[] = array('message' => $senderMessageId, 'attachment' => $attachment); // Add recipient message Id to pm_message_attachment table foreach ($messageIds as $messageId) { $maData[] = array('message' => $messageId, 'attachment' => $attachment); } } } if (!empty($maData) && count($maData) > 0) { $table = $table->table('pm_message_attachment'); $res = $table->insertAll(array('message', 'attachment'), $maData)->exec(); if (Jaws_Error::IsError($res)) { //Rollback Transaction $table->rollback(); return false; } } else { //Rollback Transaction $table->rollback(); return false; } } //Commit Transaction $mTable->commit(); return $senderMessageId; }
/** * Overloading __get magic method * * @access private * @param string $property Property name * @return mixed Requested property otherwise Jaws_Error */ function __get($property) { switch ($property) { case 'title': case 'description': return _t(strtoupper($this->name . '_' . $property)); break; case 'acl': $classname = 'Jaws_Gadget_ACL'; break; case 'hook': case 'event': case 'model': case 'action': case 'request': case 'template': case 'registry': case 'installer': case 'translate': $classname = 'Jaws_Gadget_' . ucfirst($property); break; default: return Jaws_Error::raiseError("Property '{$property}' not exists!", __FUNCTION__); } $this->{$property} = new $classname($this); return $this->{$property}; }
/** * Load and get captcha * * @access public * @param string $field * @return bool True if captcha loaded successfully */ function checkCaptcha($field = 'default') { $status = $this->gadget->registry->fetch($field . '_captcha_status'); switch ($field) { case 'login': $bad_logins = (int) $GLOBALS['app']->Session->GetAttribute('bad_login_count'); if ($status == 'DISABLED' || $bad_logins < (int) $status) { return true; } break; default: if ($status == 'DISABLED' || $status == 'ANONYMOUS' && $GLOBALS['app']->Session->Logged()) { return true; } } $dCaptcha = $this->gadget->registry->fetch($field . '_captcha_driver'); $objCaptcha = Jaws_Captcha::getInstance($dCaptcha); if (!$objCaptcha->check()) { return Jaws_Error::raiseError(_t('GLOBAL_CAPTCHA_ERROR_DOES_NOT_MATCH'), 'Jaws_Captcha', JAWS_ERROR_NOTICE); } return true; }
/** * Loads the gadget model file in question, makes a instance and * stores it globally for later use so we do not have duplicates * of the same instance around in our code. * * @access public * @param string $filename Model class file name * @return mixed Model class object on successful, Jaws_Error otherwise */ public function &loadAdmin($filename = '') { // filter non validate character $filename = preg_replace('/[^[:alnum:]_]/', '', $filename); if (!isset($this->objects['AdminModel'][$filename])) { if (empty($filename)) { $classname = $this->gadget->name . '_AdminModel'; $file = JAWS_PATH . 'gadgets/' . $this->gadget->name . '/AdminModel.php'; if (!file_exists($file)) { return $this; } } else { $classname = $this->gadget->name . "_Model_Admin_{$filename}"; $file = JAWS_PATH . 'gadgets/' . $this->gadget->name . "/Model/Admin/{$filename}.php"; } if (!file_exists($file)) { return Jaws_Error::raiseError("File [{$file}] not exists!", __FUNCTION__); } include_once $file; if (!Jaws::classExists($classname)) { return Jaws_Error::raiseError("Class [{$classname}] not exists!", __FUNCTION__); } $this->objects['AdminModel'][$filename] = new $classname($this->gadget); $GLOBALS['log']->Log(JAWS_LOG_DEBUG, "Loaded gadget model: [{$classname}]"); } return $this->objects['AdminModel'][$filename]; }
/** * Close the socket * * @access public * @param resource $socket socket resource * @param string $errstr optional error message * @return mixed True on success or Jaws_Error for socket last error */ public function close($socket = null, $errstr = '') { if (!empty($socket)) { $errno = socket_last_error($socket); socket_close($socket); } else { $errno = socket_last_error(); } if (!empty($errno) || !empty($errstr)) { return Jaws_Error::raiseError(empty($errno) ? $errstr : socket_strerror($errno)); } return true; }
/** * Does any actions required to finish the stage, such as DB queries. * * @access public * @return bool|Jaws_Error Either true on success, or a Jaws_Error * containing the reason for failure. */ function Run() { //config string $configString = $this->BuildConfig(); $configMD5 = md5($configString); $existsConfig = @file_get_contents(JAWS_PATH . 'config/JawsConfig.php'); $existsMD5 = md5($existsConfig); if ($configMD5 !== $existsMD5) { if (!Jaws_Utils::is_writable(JAWS_PATH . 'config/')) { return Jaws_Error::raiseError(_t('UPGRADE_CONFIG_RESPONSE_MAKE_CONFIG', 'JawsConfig.php'), __FUNCTION__, JAWS_ERROR_WARNING); } // create/overwrite a new one if the dir is writeable $result = @file_put_contents(JAWS_PATH . 'config/JawsConfig.php', $configString); if ($result === false) { return Jaws_Error::raiseError(_t('UPGRADE_CONFIG_RESPONSE_WRITE_FAILED'), __FUNCTION__, JAWS_ERROR_WARNING); } } // Connect to database require_once JAWS_PATH . 'include/Jaws/DB.php'; $objDatabase = Jaws_DB::getInstance('default', $_SESSION['upgrade']['Database']); if (Jaws_Error::IsError($objDatabase)) { _log(JAWS_LOG_DEBUG, "There was a problem connecting to the database, please check the details and try again"); return new Jaws_Error(_t('UPGRADE_DB_RESPONSE_CONNECT_FAILED'), 0, JAWS_ERROR_WARNING); } // Create application include_once JAWS_PATH . 'include/Jaws.php'; $GLOBALS['app'] = jaws(); $GLOBALS['app']->Registry->Init(); _log(JAWS_LOG_DEBUG, "Setting " . JAWS_VERSION . " as the current installed version"); $GLOBALS['app']->Registry->update('version', JAWS_VERSION); //remove cache directory $path = JAWS_DATA . 'cache'; if (!Jaws_Utils::delete($path)) { _log(JAWS_LOG_DEBUG, "Can't delete {$path}"); } _log(JAWS_LOG_DEBUG, "Configuration file has been created/updated"); return true; }
/** * Add a new entry * * @access public * @param string $user User who is adding the photo * @param array $files info like original name, tmp name and size * @param string $title Title of the image * @param string $description Description of the image * @param bool $fromControlPanel Is it called from ControlPanel? * @param array $album Array containing the required info about the album * @return mixed Returns the ID of the new entry and Jaws_Error on error */ function NewEntry($user, $files, $title, $description, $fromControlPanel = true, $album) { // check if it's really a uploaded file. /*if (is_uploaded_file($files['tmp_name'])) { $GLOBALS['app']->Session->PushLastResponse(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO'), RESPONSE_ERROR); return new Jaws_Error(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO')); }*/ if (!preg_match("/\\.png\$|\\.jpg\$|\\.jpeg\$|\\.gif\$/i", $files['name'])) { $GLOBALS['app']->Session->PushLastResponse(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO_EXT'), RESPONSE_ERROR); return new Jaws_Error(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO_EXT')); } // Create directories $uploaddir = JAWS_DATA . 'phoo/' . date('Y_m_d') . '/'; if (!is_dir($uploaddir)) { if (!Jaws_Utils::is_writable(JAWS_DATA . 'phoo/')) { $GLOBALS['app']->Session->PushLastResponse(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO'), RESPONSE_ERROR); return new Jaws_Error(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO')); } $new_dirs = array(); $new_dirs[] = $uploaddir; $new_dirs[] = $uploaddir . 'thumb'; $new_dirs[] = $uploaddir . 'medium'; foreach ($new_dirs as $new_dir) { if (!Jaws_Utils::mkdir($new_dir)) { $GLOBALS['app']->Session->PushLastResponse(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO'), RESPONSE_ERROR); return new Jaws_Error(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO')); } } } $filename = $files['name']; if (file_exists($uploaddir . $files['name'])) { $filename = time() . '_' . $files['name']; } $res = Jaws_Utils::UploadFiles($files, $uploaddir, 'jpg,gif,png,jpeg', false, !$fromControlPanel); if (Jaws_Error::IsError($res)) { $GLOBALS['app']->Session->PushLastResponse($res->getMessage(), RESPONSE_ERROR); return new Jaws_Error($res->getMessage()); } elseif (empty($res)) { $GLOBALS['app']->Session->PushLastResponse(_t('GLOBAL_ERROR_UPLOAD_4'), RESPONSE_ERROR); return new Jaws_Error(_t('GLOBAL_ERROR_UPLOAD_4')); } $filename = $res[0][0]['host_filename']; $uploadfile = $uploaddir . $filename; // Resize Image include_once JAWS_PATH . 'include/Jaws/Image.php'; $objImage = Jaws_Image::factory(); if (Jaws_Error::IsError($objImage)) { return Jaws_Error::raiseError($objImage->getMessage()); } $thumbSize = explode('x', $this->gadget->registry->fetch('thumbsize')); $mediumSize = explode('x', $this->gadget->registry->fetch('mediumsize')); $objImage->load($uploadfile); $objImage->resize($thumbSize[0], $thumbSize[1]); $res = $objImage->save($this->GetThumbPath($uploadfile)); $objImage->free(); if (Jaws_Error::IsError($res)) { // Return an error if image can't be resized $GLOBALS['app']->Session->PushLastResponse(_t('PHOO_ERROR_CANT_RESIZE_TO_THUMB'), RESPONSE_ERROR); return new Jaws_Error($res->getMessage()); } $objImage->load($uploadfile); $objImage->resize($mediumSize[0], $mediumSize[1]); $res = $objImage->save($this->GetMediumPath($uploadfile)); $objImage->free(); if (Jaws_Error::IsError($res)) { // Return an error if image can't be resized $GLOBALS['app']->Session->PushLastResponse($res->getMessage(), RESPONSE_ERROR); return new Jaws_Error(_t('PHOO_ERROR_CANT_RESIZE_TO_MEDIUM')); } $data = array(); $data['user_id'] = $user; $data['filename'] = date('Y_m_d') . '/' . $filename; $data['title'] = $title; $data['description'] = $description; if ($this->gadget->registry->fetch('allow_comments') === 'true' && $album['allow_comments']) { $data['allow_comments'] = true; } else { $data['allow_comments'] = false; } if ($this->gadget->registry->fetch('published') === 'true' && $this->gadget->GetPermission('ManageAlbums')) { $data['published'] = true; } else { $data['published'] = false; } $jDate = Jaws_Date::getInstance(); $createtime = Jaws_DB::getInstance()->date(); if (function_exists('exif_read_data') && preg_match("/\\.jpg\$|\\.jpeg\$/i", $files['name']) && ($exifData = @exif_read_data($uploadfile, 1, true)) && !empty($exifData['IFD0']['DateTime']) && $jDate->ValidDBDate($exifData['IFD0']['DateTime'])) { $aux = explode(' ', $exifData['IFD0']['DateTime']); $auxdate = str_replace(':', '-', $aux[0]); $auxtime = $aux[1]; $createtime = $auxdate . ' ' . $auxtime; } $data['createtime'] = $createtime; $table = Jaws_ORM::getInstance()->table('phoo_image'); $result = $table->insert($data)->exec(); if (Jaws_Error::IsError($result)) { $GLOBALS['app']->Session->PushLastResponse(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO'), RESPONSE_ERROR); return new Jaws_Error(_t('PHOO_ERROR_CANT_UPLOAD_PHOTO')); } // Lets remove the original if keep_original = false if ($this->gadget->registry->fetch('keep_original') == 'false') { if (!empty($data['filename'])) { Jaws_Utils::delete(JAWS_DATA . 'phoo/' . $data['filename']); } } // shout SiteActivity event $saParams = array(); $saParams['action'] = 'Photo'; $this->gadget->event->shout('SiteActivity', $saParams); $GLOBALS['app']->Session->PushLastResponse(_t('PHOO_PHOTO_ADDED'), RESPONSE_NOTICE); return $result; }
/** * This function sends the email * * @access public * @return mixed */ function send() { $mail = null; switch ($this->mailer) { case 'phpmail': $mail = Mail::factory('mail'); break; case 'sendmail': $mail = Mail::factory('sendmail', $this->params); break; case 'smtp': $mail = Mail::factory('smtp', $this->params); break; default: return false; } $realbody = $this->mail_mime->get(array('html_encoding' => '8bit', 'text_encoding' => '8bit', 'head_encoding' => 'base64', 'html_charset' => 'utf-8', 'text_charset' => 'utf-8', 'head_charset' => 'utf-8')); if (empty($this->recipient)) { $this->AddRecipient(); } $headers = $this->mail_mime->headers($this->headers); $res = $mail->send($this->recipient, $headers, $realbody); if (PEAR::isError($res)) { return Jaws_Error::raiseError($res->getMessage(), __FUNCTION__, JAWS_ERROR_NOTICE); } return true; }
/** * Login * * @param string $username Username * @param string $password Password * @param bool $remember Remember me * @param string $authtype Authentication type * @return mixed An Array of user's attributes if success, otherwise Jaws_Error */ function Login($username, $password, $remember, $authtype = '') { $GLOBALS['log']->Log(JAWS_LOG_DEBUG, 'LOGGIN IN'); if ($username === '' && $password === '') { $result = Jaws_Error::raiseError(_t('GLOBAL_ERROR_LOGIN_WRONG'), __FUNCTION__, JAWS_ERROR_NOTICE); } else { if (!empty($authtype)) { $authtype = preg_replace('/[^[:alnum:]_\\-]/', '', $authtype); } else { $authtype = $this->_AuthType; } require_once JAWS_PATH . 'include/Jaws/Auth/' . $authtype . '.php'; $className = 'Jaws_Auth_' . $authtype; $this->_AuthModel = new $className(); $result = $this->_AuthModel->Auth($username, $password); if (!Jaws_Error::isError($result)) { $existSessions = 0; if (!empty($result['concurrents'])) { $existSessions = $this->GetUserSessions($result['id'], true); } if (empty($existSessions) || $result['concurrents'] > $existSessions) { // remove login trying count from session $this->DeleteAttribute('bad_login_count'); // create session & cookie $this->Create($result, $remember); // login event logging $GLOBALS['app']->Listener->Shout('Session', 'Log', array('Users', 'Login', JAWS_NOTICE)); // let everyone know a user has been logged $GLOBALS['app']->Listener->Shout('Session', 'LoginUser', $this->_Attributes); return $result; } else { // login conflict event logging $GLOBALS['app']->Listener->Shout('Session', 'Log', array('Users', 'Login', JAWS_WARNING, null, 403, $result['id'])); $result = Jaws_Error::raiseError(_t('GLOBAL_ERROR_LOGIN_CONCURRENT_REACHED'), __FUNCTION__, JAWS_ERROR_NOTICE); } } } // increment login trying count in session $this->SetAttribute('bad_login_count', (int) $this->GetAttribute('bad_login_count') + 1); return $result; }
/** * Sends notify to user * * @access public * @param array $users Users properties associated array * @param string $title Notification title * @param string $summary Notification summary * @param string $description Notification description * @return mixed Jaws_Error on failure */ function notify($users, $title, $summary, $description) { return Jaws_Error::raiseError('notify() method not supported by this driver.', __CLASS__); }
/** * Deletes a comment * * @access public * @param int $id Comment ID * @return bool True if success or Jaws_Error on any error */ function Delete($id) { $objORM = Jaws_ORM::getInstance(); // find comment reference id $gar = $objORM->table('comments_details')->select('cid:integer')->where('id', $id)->fetchOne(); if (Jaws_Error::IsError($gar)) { return $gar; } if (empty($gar)) { return Jaws_Error::raiseError(_t('COMMENTS_REFERENCE_NOTFOUND'), __FUNCTION__, JAWS_ERROR_NOTICE); } // begin transaction $objORM->beginTransaction(); $ret = $objORM->table('comments_details')->delete()->where('id', $id)->exec(); if (Jaws_Error::IsError($ret)) { return $ret; } // update comments count $res = $objORM->table('comments')->update(array('comments_count' => Jaws_ORM::getInstance()->table('comments_details')->select('count(id)')->where('cid', $gar), 'last_update' => time()))->where('id', $gar)->exec(); if (Jaws_Error::IsError($res)) { return $res; } //commit transaction $objORM->commit(); return $ret; }