/** * Производим замену значений, отображаемых "как есть". */ private function replaceAsIsValues($html) { foreach ($this->ASIS_VALUES as $macros => $value) { $html = str_replace_first($macros, $value, $html); } return $html; }
/** * Shortcut function for retrieving single lang value * * @access public * @param string $name * @return string */ function lang($name) { // Get function arguments and remove first one. $args = func_get_args(); if (is_array($args)) { array_shift($args); } // if // Get value and if we have NULL done! if (plugin_active('i18n')) { $value = lang_from_db($name); } else { $value = Localization::instance()->lang($name); } if (is_null($value)) { return $value; } // if // We have args? Replace all %s with arguments if (is_array($args) && count($args)) { foreach ($args as $arg) { $value = str_replace_first('%s', $arg, $value); } // foreach } // if // Done here... return $value; }
/** * Render submit button * * @param array $params * @param string $content * @param Smarty $smarty * @param boolean $repeat * @return string */ function smarty_block_submit($params, $content, &$smarty, &$repeat) { $params['type'] = 'submit'; $accesskey = array_var($params, 'accesskey', 's'); if ($accesskey) { $params['accesskey'] = 's'; } // if $caption = clean(isset($params['not_lang']) ? $content : lang($content)); if ($accesskey) { $first = null; $first_pos = null; $to_highlight = array(strtolower($accesskey), strtoupper($accesskey)); foreach ($to_highlight as $accesskey_to_highlight) { if (($pos = strpos($caption, $accesskey_to_highlight)) === false) { continue; } // if if ($first_pos === null || $pos < $first_pos) { $first = $accesskey_to_highlight; $first_pos = $pos; } // if } // foreach if ($first !== null) { $caption = str_replace_first($first, "<u>{$first}</u>", $caption); } // if } // if // And done... return open_html_tag('button', $params) . '<span><span>' . $caption . '</span></span></button>'; }
/** * Add webpage * * @access public * @param void * @return null */ function add() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $this->setTemplate('add'); $notAllowedMember = ''; if(!ProjectWebpage::canAdd(logged_user(), active_context(), $notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); else flash_error(lang('no context permissions to add',lang("webpages"), $notAllowedMember)); ajx_current("empty"); return; } // if $webpage = new ProjectWebpage(); $webpage_data = array_var($_POST, 'webpage'); if(is_array(array_var($_POST, 'webpage'))) { try { if(substr_utf($webpage_data['url'],0,7) != 'http://' && substr_utf($webpage_data['url'],0,7) != 'file://' && substr_utf($webpage_data['url'],0,8) != 'https://' && substr_utf($webpage_data['url'],0,6) != 'about:' && substr_utf($webpage_data['url'],0,6) != 'ftp://') { $webpage_data['url'] = 'http://' . $webpage_data['url']; } $webpage->setFromAttributes($webpage_data); DB::beginWork(); $webpage->save(); $member_ids = json_decode(array_var($_POST, 'members')); //link it! $object_controller = new ObjectController(); $object_controller->add_subscribers($webpage); $object_controller->add_to_members($webpage, $member_ids); $object_controller->link_to_new_object($webpage); $object_controller->add_subscribers($webpage); $object_controller->add_custom_properties($webpage); ApplicationLogs::createLog($webpage, ApplicationLogs::ACTION_ADD); DB::commit(); flash_success(lang('success add webpage', $webpage->getObjectName())); ajx_current("back"); // Error... } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } } tpl_assign('webpage', $webpage); tpl_assign('webpage_data', $webpage_data); } // add
public function bind_param($a, $b = false, $c = false, $d = false, $e = false, $f = false, $g = false) { $sql = str_replace_first('?', $b, $this->sql); $sql = str_replace_first('?', $c, $sql); $sql = str_replace_first('?', $d, $sql); $sql = str_replace_first('?', $e, $sql); $sql = str_replace_first('?', $f, $sql); $sql = str_replace_first('?', $g, $sql); echo $sql . '<br />'; return true; }
public function parseItemsOnlyOnce($link, $type) { $content = $link->content; $obj = $link->{$type}; $link_text = $this->getContentLinks($link); foreach ($obj as $item) { if (!isContainedInElementsOfArray($item->text, $link_text[1]) && $item->pivot->relevance > 0.5) { $content = str_replace_first($item->text, '<a href="/' . $type . '/' . $item->slug . ' "class="' . $type . '">' . $item->text . '</a>', $content); } } $link->update(['content' => $content]); }
function lang($line, $id = '') { $CI =& get_instance(); $line = $CI->lang->line($line); $args = func_get_args(); if (is_array($args)) { array_shift($args); } if (is_array($args) && count($args)) { foreach ($args as $arg) { $line = str_replace_first('%s', $arg, $line); } } if ($id != '') { $line = '<label for="' . $id . '">' . $line . "</label>"; } return $line; }
function apiReadUrlXml($url, $data = []) { /* $url = $_REQUEST['url'];//'http://212.38.167.37/resultsproxy/getresultsxml3.aspx'; $data = array( 'loc' => 'ru-RU', 'action' => 'GETSPORTS' );*/ if (!extension_loaded('curl')) { throw new \ErrorException('cURL library is not loaded'); } $ch = curl_init(); $user_agent = 'PHP-STATSANDRESULTS-PROXY/1.0.0'; curl_setopt($ch, CURLOPT_USERAGENT, $user_agent); // curl_setopt($ch, CURLINFO_HEADER_OUT, true); // curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_URL, $url . (empty($data) ? '' : '?' . http_build_query($data))); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); curl_setopt($ch, CURLOPT_HTTPGET, true); $result = curl_exec($ch); curl_close($ch); return str_replace_first('<?xml version="1.0" encoding="utf-16"?>', '<?xml version="1.0" encoding="utf-8"?>', $result); }
/** * Prepare string. Replace every '?' with matching escaped value * * @param string $sql * @param array $arguments Array of arguments * @return string */ static function prepareString($sql, $arguments = null) { if (is_array($arguments) && count($arguments)) { foreach ($arguments as $argument) { $sql = str_replace_first('?', DB::escape($argument), $sql); } // foreach } // if return $sql; }
/** * This function exports all the data for a given module * Param $type - module name * Return type text */ function export($type) { global $log, $list_max_entries_per_page; $log->debug("Entering export(" . $type . ") method ..."); global $adb; $focus = 0; $content = ''; if ($type != "") { // vtlib customization: Hook to dynamically include required module file. // Refer to the logic in setting $currentModule in index.php $focus = CRMEntity::getInstance($type); } $log = LoggerManager::getLogger('export_' . $type); $db = PearDatabase::getInstance(); $oCustomView = new CustomView("{$type}"); $viewid = $oCustomView->getViewId("{$type}"); $sorder = $focus->getSortOrder(); $order_by = $focus->getOrderBy(); $search_type = $_REQUEST['search_type']; $export_data = $_REQUEST['export_data']; if (isset($_SESSION['export_where']) && $_SESSION['export_where'] != '' && $search_type == 'includesearch') { $where = $_SESSION['export_where']; } $query = $focus->create_export_query($where); if ($search_type != 'includesearch' && $type != 'Calendar') { $stdfiltersql = $oCustomView->getCVStdFilterSQL($viewid); $advfiltersql = $oCustomView->getCVAdvFilterSQL($viewid); if (isset($stdfiltersql) && $stdfiltersql != '') { $query .= ' and ' . $stdfiltersql; } if (isset($advfiltersql) && $advfiltersql != '') { $query .= ' and ' . $advfiltersql; } } $params = array(); if (($search_type == 'withoutsearch' || $search_type == 'includesearch') && $export_data == 'selecteddata') { $idstring = explode(";", $_REQUEST['idstring']); if ($type == 'Accounts' && count($idstring) > 0) { $query .= ' and vtiger_account.accountid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } elseif ($type == 'Contacts' && count($idstring) > 0) { $query .= ' and vtiger_contactdetails.contactid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } elseif ($type == 'Potentials' && count($idstring) > 0) { $query .= ' and vtiger_potential.potentialid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } elseif ($type == 'Leads' && count($idstring) > 0) { $query .= ' and vtiger_leaddetails.leadid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } elseif ($type == 'Products' && count($idstring) > 0) { $query .= ' and vtiger_products.productid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } elseif ($type == 'Documents' && count($idstring) > 0) { $query .= ' and vtiger_notes.notesid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } elseif ($type == 'HelpDesk' && count($idstring) > 0) { $query .= ' and vtiger_troubletickets.ticketid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } elseif ($type == 'Vendors' && count($idstring) > 0) { $query .= ' and vtiger_vendor.vendorid in (' . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); } else { if (count($idstring) > 0) { // vtlib customization: Hook to make the export feature available for custom modules. $query .= " and {$focus->table_name}.{$focus->table_index} in (" . generateQuestionMarks($idstring) . ')'; array_push($params, $idstring); // END } } } if (isset($order_by) && $order_by != '') { if ($order_by == 'smownerid') { $query .= ' ORDER BY user_name ' . $sorder; } elseif ($order_by == 'lastname' && $type == 'Documents') { $query .= ' ORDER BY vtiger_contactdetails.lastname ' . $sorder; } elseif ($order_by == 'crmid' && $type == 'HelpDesk') { $query .= ' ORDER BY vtiger_troubletickets.ticketid ' . $sorder; } else { $tablename = getTableNameForField($type, $order_by); $tablename = $tablename != '' ? $tablename . "." : ''; if ($adb->dbType == "pgsql") { $query .= ' GROUP BY ' . $tablename . $order_by; } $query .= ' ORDER BY ' . $tablename . $order_by . ' ' . $sorder; } } if ($export_data == 'currentpage') { $current_page = ListViewSession::getCurrentPage($type, $viewid); $limit_start_rec = ($current_page - 1) * $list_max_entries_per_page; if ($limit_start_rec < 0) { $limit_start_rec = 0; } $query .= ' LIMIT ' . $limit_start_rec . ',' . $list_max_entries_per_page; } $query = str_replace_first("INNER JOIN vtiger_accounting ON vtiger_crmentity.crmid=vtiger_accounting.accountingid", "INNER JOIN vtiger_accounting ON vtiger_accounting.accountingid = vtiger_crmentity.crmid INNER JOIN vtiger_accounting_payments ON vtiger_accounting_payments.idtransaction=vtiger_accounting.accountingid", $query); $query = str_replace("vtiger_accounting.accountingduedate", "vtiger_accounting_payments.paymentduedate", $query); $query = str_replace("vtiger_accounting.accountingpaymentdate", "vtiger_accounting_payments.paymentdate", $query); $query = str_replace("vtiger_accounting.accountingamountpartial", "vtiger_accounting_payments.amount", $query); $query = str_replace("vtiger_accounting.accountingpaymentmethod", "vtiger_accounting_payments.paymentmethod", $query); $query = str_replace("vtiger_accounting.paymentrefpartial", "vtiger_accounting_payments.ref", $query); $query = str_replace("vtiger_accounting.paymentpaidpartial", "vtiger_accounting_payments.paid", $query); $query = str_replace("vtiger_accounting.paymentvatpartial", "vtiger_accounting_payments.tax", $query); $query = str_replace("vtiger_accounting.paymentassocpartial", "vtiger_accounting_payments.associnv", $query); $query = str_replace("FROM vtiger_crmentity", ", vtiger_accounting_payments.ref AS paymentrefpartial,vtiger_accounting_payments.paymentduedate AS accountingduedate," . "vtiger_accounting_payments.paymentdate AS accountingpaymentdate,vtiger_accounting_payments.amount AS accountingamountpartial,vtiger_accounting_payments.tax AS paymentvatpartial," . "vtiger_accounting_payments.paymentmethod AS accountingpaymentmethod,vtiger_accounting_payments.associnv AS paymentassocpartial,vtiger_accounting_payments.paid AS paymentpaidpartial FROM vtiger_crmentity", $query); $result = $adb->pquery($query, $params, true, "Error exporting {$type}: " . "<BR>{$query}"); $fields_array = $adb->getFieldsArray($result); $fields_array = array_diff($fields_array, array("user_name")); $__processor = new ExportUtils($type, $fields_array); // Translated the field names based on the language used. $translated_fields_array = array(); $j = 0; $acc_config = Accounting::loadConfigParams(); foreach ($fields_array as $fld) { //for($i=0; $i<count($fields_array); $i++) { if ($fld == "paymentassocpartial") { if (!isset($acc_config['associnvoice']) || $acc_config['associnvoice'] == "false") { continue; } } if ($fld == "paymentvatpartial") { if (!isset($acc_config['showvat']) || $acc_config['showvat'] == "false") { continue; } } $translated_fields_array[$j++] = getTranslatedString($fld, $type); } $header = implode("\",\"", array_values($translated_fields_array)); $header = "\"" . $header; $header .= "\"\r\n"; /** Output header information */ echo $header; $column_list = implode(",", array_values($fields_array)); while ($val = $adb->fetchByAssoc($result, -1, false)) { $new_arr = array(); $val = $__processor->sanitizeValues($val); foreach ($val as $key => $value) { if ($key == "paymentid") { $id = $value; } } foreach ($val as $key => $value) { if ($key == "paymentassocpartial") { if (!isset($acc_config['associnvoice']) || $acc_config['associnvoice'] == "false") { continue; } } if ($key == "paymentvatpartial") { if (!isset($acc_config['showvat']) || $acc_config['showvat'] == "false") { continue; } } if ($type == 'Documents' && $key == 'description') { $value = strip_tags($value); $value = str_replace(' ', '', $value); array_push($new_arr, $value); } elseif ($key == "paymentassocpartial") { $value = trim($value); if (!empty($value)) { $parent_module = getSalesEntityType($value); $displayValueArray = getEntityName($parent_module, $value); if (!empty($displayValueArray)) { foreach ($displayValueArray as $k => $v) { $displayValue = $v; } } if (!empty($parent_module) && !empty($displayValue)) { $value = $parent_module . "::::" . $displayValue; } else { $value = ""; } } else { $value = ''; } array_push($new_arr, $value); } elseif ($key == "accountingduedate" || $key == "accountingpaymentdate") { if ($value == "0000-00-00") { $value = ""; } array_push($new_arr, $value); } elseif ($key != "user_name") { // Let us provide the module to transform the value before we save it to CSV file $value = $focus->transform_export_value($key, $value); array_push($new_arr, preg_replace("/\"/", "\"\"", $value)); } } $line = implode("\",\"", $new_arr); $line = "\"" . $line; $line .= "\"\r\n"; /** Output each row information */ echo $line; } $log->debug("Exiting export method ..."); return true; }
/** * Set something before file extension * * @access public * @param string $in Filename * @param string $insert Insert this * @return null */ function insert_before_file_extension($filename, $insert) { return str_replace_first('.', '.' . $insert, $filename); }
<?php function str_replace_first($from, $to, $subject) { $from = '/' . preg_quote($from, '/') . '/'; return preg_replace($from, $to, $subject, 1); } spl_autoload_register(function ($classname) { $classname = str_replace_first('Juborm\\', '', $classname); $classname = str_replace('\\', '/', $classname); if (!file_exists("phar://juborm.phar/{$classname}.php")) { die(print_r($classname, true)); } else { require_once "phar://juborm.phar/{$classname}.php"; } }, true, false);
/** * Create a new template * */ function new_template() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $notAllowedMember = ''; if (!ProjectTask::canAdd(logged_user(), active_context(), $notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) { flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); } else { flash_error(lang('no context permissions to add', lang("tasks"), $notAllowedMember)); } ajx_current("empty"); return; } // if $id = get_id(); $task = ProjectTasks::findById($id); if (!$task instanceof ProjectTask) { $task_data = array('is_template' => true); } else { $task_data = array('milestone_id' => $task->getMilestoneId(), 'title' => $task->getObjectName(), 'assigned_to' => $task->getAssignedToContactId(), 'parent_id' => $task->getParentId(), 'priority' => $task->getPriority(), 'time_estimate' => $task->getTimeEstimate(), 'text' => $task->getText(), 'is_template' => true, 'copyId' => $task->getId()); // array if ($task->getStartDate() instanceof DateTimeValue) { $task_data['start_date'] = $task->getStartDate()->getTimestamp(); } if ($task->getDueDate() instanceof DateTimeValue) { $task_data['due_date'] = $task->getDueDate()->getTimestamp(); } } $task = new ProjectTask(); tpl_assign('task_data', $task_data); tpl_assign('task', $task); $this->setTemplate("add_task"); }
function copy() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } ajx_set_no_toolbar(); $id = get_id(); $file = ProjectFiles::findById($id); if (!$file instanceof ProjectFile) { flash_error("file dnx"); ajx_current("empty"); return; } if (!$file->canView(logged_user())) { flash_error(lang("no access permissions")); ajx_current("empty"); return; } $original_members = $file->getMembers(); $members = $file->getAllowedMembersToAdd(logged_user(), $original_members); if (!$file->canAdd(logged_user(), $members, $notAllowedMember) ){ if (str_starts_with($notAllowedMember, '-- req dim --')) flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); else flash_error(lang('no context permissions to add',lang("files"), $notAllowedMember)); ajx_current("empty"); return; } try { DB::beginWork(); $copy = $file->copy(); $copy->setFilename(lang('copy of file', $file->getFilename())); $copy->save(); $copy->addToMembers($members); $copy->addToSharingTable(); $rev_data = array(); $rev_data['name'] = $copy->getFilename(); $rev_data['size'] = $file->getFileSize(); $rev_data['type'] = $file->getTypeString(); $rev_data['tmp_name'] = ROOT . '/tmp/' . rand () ; $handler = fopen($rev_data['tmp_name'], 'w'); $file_content = $file->getLastRevision()->getFileContent(); fputs($handler, $file_content); fclose($handler); $copy->handleUploadedFile($rev_data, false, lang("copied from file", $file->getFilename(), $file->getUniqueObjectId())); DB::commit(); $this->setTemplate('file_details'); tpl_assign('file', $copy); tpl_assign('last_revision', $copy->getLastRevision()); tpl_assign('revisions', $copy->getRevisions()); tpl_assign('order', null); tpl_assign('page', null); ajx_extra_data(array("title" => $copy->getFilename(), 'icon'=>'ico-file')); ajx_set_no_toolbar(true); //read object for this user $copy->setIsRead(logged_user()->getId(),true); ApplicationReadLogs::createLog($copy, ApplicationReadLogs::ACTION_READ); } catch (Exception $ex) { DB::rollback(); flash_error($ex->getMessage()); ajx_current("empty"); } }
/** * Add message * * @access public * @param void * @return null */ function add() { $this->setTemplate('add_message'); if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current('empty'); return; } $notAllowedMember = ''; if (!ProjectMessage::canAdd(logged_user(), active_context(), $notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) { flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); } else { trim($notAllowedMember) == "" ? flash_error(lang('you must select where to keep', lang('the message'))) : flash_error(lang('no context permissions to add', lang("messages"), $notAllowedMember)); } ajx_current("empty"); return; } // if $message = new ProjectMessage(); tpl_assign('message', $message); $message_data = array_var($_POST, 'message'); if (!is_array($message_data)) { // set layout for modal form if (array_var($_REQUEST, 'modal')) { $this->setLayout("json"); tpl_assign('modal', true); } $message_data = array(); } // if tpl_assign('message_data', $message_data); if (is_array(array_var($_POST, 'message'))) { foreach ($message_data as $k => &$v) { $v = remove_scripts($v); } try { if (config_option('untitled_notes')) { if (!array_var($message_data, "name")) { $message_data["name"] = lang("untitled note"); } } // Aliases if (config_option("wysiwyg_messages")) { $message_data['type_content'] = "html"; $message_data['text'] = preg_replace("/[\n|\r|\n\r]/", '', array_var($message_data, 'text')); } else { $message_data['type_content'] = "text"; } $message->setFromAttributes($message_data); DB::beginWork(); $message->save(); $object_controller = new ObjectController(); $member_ids = json_decode(array_var($_POST, 'members')); $object_controller->add_to_members($message, $member_ids); $object_controller->add_subscribers($message); $object_controller->link_to_new_object($message); $object_controller->add_custom_properties($message); DB::commit(); ApplicationLogs::createLog($message, ApplicationLogs::ACTION_ADD); flash_success(lang('success add message', $message->getObjectName())); if (array_var($_POST, 'popup', false)) { ajx_current("reload"); } else { ajx_current("back"); } if (array_var($_REQUEST, 'modal')) { evt_add("reload current panel"); } ajx_add("overview-panel", "reload"); // Error... } catch (Exception $e) { DB::rollback(); $message->setNew(true); flash_error($e->getMessage()); ajx_current("empty"); } // try } // if }
function add() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $notAllowedMember = ''; if(!(ProjectEvent::canAdd(logged_user(), active_context(),$notAllowedMember ))){ if (str_starts_with($notAllowedMember, '-- req dim --')) flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); else flash_error(lang('no context permissions to add',lang("events"), $notAllowedMember)); ajx_current("empty"); return ; } $this->setTemplate('event'); $event = new ProjectEvent(); $event_data = array_var($_POST, 'event'); $event_name = array_var($_GET, 'name'); //if sent from pupup //var_dump($event_data) ; $month = isset($_GET['month'])?$_GET['month']:date('n', DateTimeValueLib::now()->getTimestamp() + logged_user()->getTimezone() * 3600); $day = isset($_GET['day'])?$_GET['day']:date('j', DateTimeValueLib::now()->getTimestamp() + logged_user()->getTimezone() * 3600); $year = isset($_GET['year'])?$_GET['year']:date('Y', DateTimeValueLib::now()->getTimestamp() + logged_user()->getTimezone() * 3600); $user_filter = isset($_GET['user_filter']) ? $_GET['user_filter'] : logged_user()->getId(); if(!is_array($event_data)) { // if data sent from quickadd popup (via get) we se it, else default if (isset($_GET['start_time'])) $this->parseTime($_GET['start_time'], $hour, $minute); else { $hour = isset($_GET['hour']) ? $_GET['hour'] : date('G', DateTimeValueLib::now()->getTimestamp() + logged_user()->getTimezone() * 3600); $minute = isset($_GET['minute']) ? $_GET['minute'] : round((date('i') / 15), 0) * 15; //0,15,30 and 45 min } if(!user_config_option('time_format_use_24')) { if($hour >= 12){ $pm = 1; $hour = $hour - 12; } else $pm = 0; } $event_data = array( 'month' => isset($_GET['month']) ? $_GET['month'] : date('n', DateTimeValueLib::now()->getTimestamp() + logged_user()->getTimezone() * 3600), 'year' => isset($_GET['year']) ? $_GET['year'] : date('Y', DateTimeValueLib::now()->getTimestamp() + logged_user()->getTimezone() * 3600), 'day' => isset($_GET['day']) ? $_GET['day'] : date('j', DateTimeValueLib::now()->getTimestamp() + logged_user()->getTimezone() * 3600), 'hour' => $hour, 'minute' => $minute, 'pm' => (isset($pm) ? $pm : 0), 'typeofevent' => isset($_GET['type_id']) ? $_GET['type_id'] : 1, 'name' => $event_name, 'durationhour' => isset($_GET['durationhour']) ? $_GET['durationhour'] : 1, 'durationmin' => isset($_GET['durationmin']) ? $_GET['durationmin'] : 0, ); // array } // if tpl_assign('event', $event); tpl_assign('event_data', $event_data); tpl_assign('event_related', false); if (is_array(array_var($_POST, 'event'))) { try { $data = $this->getData($event_data); $event->setFromAttributes($data); DB::beginWork(); $event->save(); $this->registerInvitations($data, $event); if (isset($data['confirmAttendance'])) { $this->change_invitation_state($data['confirmAttendance'], $event->getId(), $user_filter); } if (array_var($_POST, 'members')) { $member_ids = json_decode(array_var($_POST, 'members')); } else { $member_ids = array(); $context = active_context(); foreach ($context as $selection) { if ($selection instanceof Member) $member_ids[] = $selection->getId(); } } ApplicationLogs::createLog($event, ApplicationLogs::ACTION_ADD, false, $is_silent); $object_controller = new ObjectController(); $object_controller->add_to_members($event, $member_ids); $object_controller->add_subscribers($event); $object_controller->link_to_new_object($event); $object_controller->add_custom_properties($event); $object_controller->add_reminders($event); if (array_var($_POST, 'popup', false)) { // create default reminder $def = explode(",", user_config_option("reminders_events")); $minutes = array_var($def, 2) * array_var($def, 1); $reminder = new ObjectReminder(); $reminder->setMinutesBefore($minutes); $reminder->setType(array_var($def, 0, 'reminder_email')); $reminder->setContext("start"); $reminder->setObject($event); $reminder->setUserId(0); $date = $event->getStart(); if ($date instanceof DateTimeValue) { $rdate = new DateTimeValue($date->getTimestamp() - $minutes * 60); $reminder->setDate($rdate); } $reminder->save(); // subscribe or not the invited users if (user_config_option('event_subscribe_invited')){ $data['subscribe_invited'] = "checked"; } // send or not the inivitations if (user_config_option('event_send_invitations')){ $data['send_notification'] = "checked"; } } $opt_rep_day = array(); if(array_var($event_data, 'repeat_saturdays')){ $opt_rep_day['saturday'] = true; }else{ $opt_rep_day['saturday'] = false; } if(array_var($event_data, 'repeat_sundays')){ $opt_rep_day['sunday'] = true; }else{ $opt_rep_day['sunday'] = false; } if (array_var($_POST, 'popup', false)) { $event->subscribeUser(logged_user()); ajx_current("reload"); } else { ajx_current("back"); } DB::commit(); $is_silent = false; if (isset($data['send_notification']) && $data['send_notification']) { $users_to_inv = array(); foreach ($data['users_to_invite'] as $us => $v) { if ($us != logged_user()->getId()) { $users_to_inv[] = Contacts::findById(array('id' => $us)); } } Notifier::notifEvent($event, $users_to_inv, 'new', logged_user()); $is_silent = true; } flash_success(lang('success add event', clean($event->getObjectName()))); ajx_add("overview-panel", "reload"); } catch(Exception $e) { DB::rollback(); flash_error($e->getMessage()); ajx_current("empty"); } // try } }
/** * Make the place-holder replacements on a JSON loaded line. * * @param string $line * @param array $replace * @return string */ protected function makeJsonReplacements($line, array $replace) { preg_match_all('#:(?:[a-zA-Z1-9]*)#s', $line, $placeholders); $placeholders = $placeholders[0]; foreach ($placeholders as $i => $key) { $line = str_replace_first($key, isset($replace[$i]) ? $replace[$i] : $key, $line); } return $line; }
/** * @param string $hex * * @return Colour */ public static function fromHex(string $hex) : Colour { $hex = str_replace_first('#', '', $hex); return new self(hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))); }
$conversation_block .= '</div>'; } else { $conversation_block = ''; } if($email->getBodyHtml() != ''){ if (defined('SANDBOX_URL')) { $html_content = $email->getBodyHtml(); // prevent some outlook malformed tags if(substr_count($html_content, "<style") != substr_count($html_content, "</style>") && substr_count($html_content, "/* Font Definitions */") >= 1) { $p1 = strpos($html_content, "/* Font Definitions */", 0); $html_content1 = substr($html_content, 0, $p1); $p0 = strrpos($html_content1, "</style>"); $html_content = ($p0 >= 0 ? substr($html_content1, 0, $p0) : $html_content1) . substr($html_content, $p1); $html_content = str_replace_first("/* Font Definitions */","<style>",$html_content); } } else { $html_content = purify_html($email->getBodyHtml()); } if (strpos($html_content, "<html") === false) { if (strpos($html_content, "<body") === false) { $html_content = "<body>" . $html_content . "</body>"; } if (strpos($html_content, "<head") === false) { $html_content = "<head></head>" . $html_content; } $html_content = "<html>" . $html_content . "</html>"; } //$html_content = convert_to_links($html_content); // commented because it can break HTML (e.g. if an URL or email is found on the title of an element) // links must open in a new tab or window
/** * Make a safely escaped where fragment of SQL out of a plain string or a rails-style * conditions statement like: array("username=? AND user_id IN ?", $username, array(1, 2, 75, 200)) * @param string $sql SQL to determine query type of * @return string|boolean one of 'INSERT', 'SELECT', 'UPDATE', 'DELETE', FALSE */ private function make_where_clause($where) { if (is_array($where)) { $token = '?'; // todo: move to define() $safe_token = '?SAFE_TOKEN?'; $where_text = array_shift($where); // replace ? tokens with a rarer token ?SAFE_TOKEN? to allow ?s in the actual content.. TODO: move to define() $where_text = str_replace($token, $safe_token, $where_text); $num_wheres = substr_count($where_text, $safe_token); if ($num_wheres != count($where)) { throw new InvalidSQLException("WHERE mismatch:expected {$num_wheres} got " . count($where)); } for ($i = 0; $i < $num_wheres; $i++) { $where_text = str_replace_first($safe_token, $this->make_where_val($where[$i]), $where_text); } $where = $where_text; } else { $where = $this->escape($where, $in_quotes = FALSE); //unescape single quotes so we can pass in strings like "blah != 'something'" $where = str_replace("\\'", "'", $where); } return $where; }
protected function doFinalize($html) { /* * ИНИЦИАЛИЗАЦИЯ */ $this->OBFUSCATABLE[] = DirManager::resources()->relDirPath('folded'); $this->OBFUSCATABLE[] = DirManager::resources()->relDirPath('scripts/ps'); //Расширим для предотвращения PREG_BACKTRACK_LIMIT_ERROR ini_set('pcre.backtrack_limit', 10 * 1000 * 1000); /* * НАЧАЛО РЫБОТЫ */ /* Удалим комментарии */ $pattern = "/<!--(.*?)-->/si"; $html = preg_replace($pattern, '', $html); $resources = ''; /* * JAVASCRIPT * <script ...>...</script> */ $linked = array(); $matches = array(); $pattern = "/<script ([^>]*)>(.*?)<\\/script>/si"; $cnt = preg_match_all($pattern, $html, $matches, PREG_PATTERN_ORDER); $attributes = $matches[1]; $contents = $matches[2]; for ($index = 0; $index < $cnt; $index++) { $attrs = $this->parseAttributesString($attributes[$index]); $content = trim($contents[$index]); if ($content) { //Есть содержимое, этот тег включаем сразу $tmp = PsHtml::linkJs(null, $content, $attrs); $resources .= $tmp . "\n"; $this->LOGGER->info($tmp); continue; } $src = array_get_value('src', $attrs); if (!$src || in_array($src, $linked)) { //Нет пути или путь уже включён - пропускаем continue; } $linked[] = $src; $newSrc = $this->tryReplaceResource($src); if (!$newSrc) { if ($this->LOGGER->isEnabled()) { $tmp = PsHtml::linkJs(null, null, $attrs); $this->LOGGER->info($tmp . ' [EXCLUDED]'); } continue; } $replaced = $src != $newSrc; if ($replaced) { $linked[] = $newSrc; $attrs['src'] = $newSrc; } $tmp = PsHtml::linkJs(null, null, $attrs); $resources .= $tmp . "\n"; if ($this->LOGGER->isEnabled()) { $attrs['src'] = $src; $this->LOGGER->info(($replaced ? PsHtml::linkJs(null, null, $attrs) . ' [REPLACED] ' : '') . $tmp); } } $html = preg_replace($pattern, '', $html); /* * FAVICON, CSS * <link .../> */ /* Вырежем css и другие "линки" */ $matches = array(); $pattern = "/<link ([^>]*)\\/>/si"; $cnt = preg_match_all($pattern, $html, $matches, PREG_PATTERN_ORDER); $attributes = $matches[1]; for ($index = 0; $index < $cnt; $index++) { $attrs = $this->parseAttributesString($attributes[$index]); $src = array_get_value('href', $attrs); if (!$src || in_array($src, $linked)) { //Нет пути или путь уже включён - пропускаем continue; } $linked[] = $src; $newSrc = $this->tryReplaceResource($src); if (!$newSrc) { if ($this->LOGGER->isEnabled()) { $tmp = PsHtml::linkLink($attrs); $this->LOGGER->info($tmp . ' [EXCLUDED]'); } continue; } $replaced = $src != $newSrc; if ($replaced) { $linked[] = $newSrc; $attrs['href'] = $newSrc; } $tmp = PsHtml::linkLink($attrs); $resources .= $tmp . "\n"; if ($this->LOGGER->isEnabled()) { $attrs['href'] = $src; $this->LOGGER->info(($replaced ? PsHtml::linkLink($attrs) . ' [REPLACED] ' : '') . $tmp); } } $html = preg_replace($pattern, '', $html); $resources = "\n" . trim($resources) . "\n"; /* * Удалим пробелы */ $matches = array(); $cnt = preg_match("/<head>(.*?)<\\/head>/si", $html, $matches); if ($cnt == 1) { /** * $headOld - ресурсы страницы, находящиеся в блоке <head ...>...</head> и * оставшиеся после вырезания .js и .css. Обычно там остаётся два блока: * <meta...>...</meta> и <title>...</title> */ $headOld = $matches[1]; $headNew = normalize_string($headOld); $headNew = "{$headNew} {$resources}"; $html = str_replace_first($headOld, $headNew, $html); } else { //Вставляем ресурсы в <head> $html = str_replace_first('</head>', $resources . '</head>', $html); } $this->LOGGER->infoBox('PAGE FINALISED', $html); return $html; }
function SaveMail(&$content, MailAccount $account, $uidl, $state = 0, $imap_folder_name = '', $read = null, &$received_count) { try { if (strpos($content, '+OK ') > 0) { $content = substr($content, strpos($content, '+OK ')); } self::parseMail($content, $decoded, $parsedMail, $warnings); $encoding = array_var($parsedMail, 'Encoding', 'UTF-8'); $enc_conv = EncodingConverter::instance(); $to_addresses = self::getAddresses(array_var($parsedMail, "To")); $from = self::getAddresses(array_var($parsedMail, "From")); $message_id = self::getHeaderValueFromContent($content, "Message-ID"); $in_reply_to_id = self::getHeaderValueFromContent($content, "In-Reply-To"); $uid = trim($uidl); if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) { $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding); } if ($uid == '') { $uid = trim($message_id); if ($uid == '') { $uid = array_var($parsedMail, 'Subject', 'MISSING UID'); } if (str_starts_with($uid, '<') && str_ends_with($uid, '>')) { $uid = utf8_substr($uid, 1, utf8_strlen($uid, $encoding) - 2, $encoding); } } // do not save duplicate emails if (MailContents::mailRecordExists($account->getId(), $uid, $imap_folder_name == '' ? null : $imap_folder_name)) { return; } if (!$from) { $parsedMail["From"] = self::getFromAddressFromContent($content); $from = array_var($parsedMail["From"][0], 'address', ''); } if (defined('EMAIL_MESSAGEID_CONTROL') && EMAIL_MESSAGEID_CONTROL) { if (trim($message_id) != "") { $id_condition = " AND `message_id`='" . trim($message_id) . "' AND `from`='{$from}'"; } else { $id_condition = " AND `name`= " . DB::escape(trim(array_var($parsedMail, 'Subject'))) . " AND `from`='{$from}'"; if (array_var($parsedMail, 'Date')) { $sent_date_dt = new DateTimeValue(strtotime(array_var($parsedMail, 'Date'))); $sent_date_str = $sent_date_dt->toMySQL(); $id_condition .= " AND `sent_date`='" . $sent_date_str . "'"; } } $same = MailContents::findOne(array('conditions' => "`account_id`=" . $account->getId() . $id_condition, 'include_trashed' => true)); if ($same instanceof MailContent) { return; } } $from_spam_junk_folder = strpos(strtolower($imap_folder_name), 'spam') !== FALSE || strpos(strtolower($imap_folder_name), 'junk') !== FALSE || strpos(strtolower($imap_folder_name), 'trash') !== FALSE; $user_id = logged_user() instanceof Contact ? logged_user()->getId() : $account->getContactId(); $max_spam_level = user_config_option('max_spam_level', null, $user_id); if ($max_spam_level < 0) { $max_spam_level = 0; } $spam_level_header = 'x-spam-level:'; foreach ($decoded[0]['Headers'] as $hdr_name => $hdrval) { if (strpos(strtolower($hdr_name), "spamscore") !== false || strpos(strtolower($hdr_name), "x-spam-level")) { $spam_level_header = $hdr_name; break; } } $mail_spam_level = strlen(trim(array_var($decoded[0]['Headers'], $spam_level_header, ''))); // if max_spam_level >= 10 then nothing goes to junk folder $spam_in_subject = false; if (config_option('check_spam_in_subject')) { $spam_in_subject = strpos_utf(strtoupper(array_var($parsedMail, 'Subject')), "**SPAM**") !== false; } if ($max_spam_level < 10 && ($mail_spam_level > $max_spam_level || $from_spam_junk_folder) || $spam_in_subject) { $state = 4; // send to Junk folder } //if you are in the table spam MailSpamFilters if ($state != 4) { $spam_email = MailSpamFilters::getFrom($account->getId(), $from); if ($spam_email) { $state = 0; if ($spam_email[0]->getSpamState() == "spam") { $state = 4; } } else { if ($state == 0) { if (strtolower($from) == strtolower($account->getEmailAddress())) { if (strpos($to_addresses, $from) !== FALSE) { $state = 5; } else { $state = 1; } //Show only in sent folder } } } } if (!isset($parsedMail['Subject'])) { $parsedMail['Subject'] = ''; } $mail = new MailContent(); $mail->setAccountId($account->getId()); $mail->setState($state); $mail->setImapFolderName($imap_folder_name); $mail->setFrom($from); $cc = trim(self::getAddresses(array_var($parsedMail, "Cc"))); if ($cc == '' && array_var($decoded, 0) && array_var($decoded[0], 'Headers')) { $cc = array_var($decoded[0]['Headers'], 'cc:', ''); } $mail->setCc($cc); $from_name = trim(array_var(array_var(array_var($parsedMail, 'From'), 0), 'name')); $from_encoding = detect_encoding($from_name); if ($from_name == '') { $from_name = $from; } else { if (strtoupper($encoding) == 'KOI8-R' || strtoupper($encoding) == 'CP866' || $from_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($from_name)) { //KOI8-R and CP866 are Russian encodings which PHP does not detect $utf8_from = $enc_conv->convert($encoding, 'UTF-8', $from_name); if ($enc_conv->hasError()) { $utf8_from = utf8_encode($from_name); } $utf8_from = utf8_safe($utf8_from); $mail->setFromName($utf8_from); } else { $mail->setFromName($from_name); } } $subject_aux = $parsedMail['Subject']; $subject_encoding = detect_encoding($subject_aux); $subject_multipart_encoding = array_var($parsedMail, 'SubjectEncoding', strtoupper($encoding)); if ($subject_multipart_encoding != 'UTF-8' && ($subject_multipart_encoding == 'KOI8-R' || $subject_multipart_encoding == 'CP866' || $subject_encoding != 'UTF-8' || !$enc_conv->isUtf8RegExp($subject_aux))) { //KOI8-R and CP866 are Russian encodings which PHP does not detect $utf8_subject = $enc_conv->convert($subject_multipart_encoding, 'UTF-8', $subject_aux); if ($enc_conv->hasError()) { $utf8_subject = utf8_encode($subject_aux); } $utf8_subject = utf8_safe($utf8_subject); $mail->setSubject($utf8_subject); } else { $utf8_subject = utf8_safe($subject_aux); $mail->setSubject($utf8_subject); } $mail->setTo($to_addresses); $sent_timestamp = false; if (array_key_exists("Date", $parsedMail)) { $sent_timestamp = strtotime($parsedMail["Date"]); } if ($sent_timestamp === false || $sent_timestamp === -1 || $sent_timestamp === 0) { $mail->setSentDate(DateTimeValueLib::now()); } else { $mail->setSentDate(new DateTimeValue($sent_timestamp)); } // if this constant is defined, mails older than this date will not be fetched if (defined('FIRST_MAIL_DATE')) { $first_mail_date = DateTimeValueLib::makeFromString(FIRST_MAIL_DATE); if ($mail->getSentDate()->getTimestamp() < $first_mail_date->getTimestamp()) { // return true to stop getting older mails from the server return true; } } $received_timestamp = false; if (array_key_exists("Received", $parsedMail) && $parsedMail["Received"]) { $received_timestamp = strtotime($parsedMail["Received"]); } if ($received_timestamp === false || $received_timestamp === -1 || $received_timestamp === 0) { $mail->setReceivedDate($mail->getSentDate()); } else { $mail->setReceivedDate(new DateTimeValue($received_timestamp)); if ($state == 5 && $mail->getSentDate()->getTimestamp() > $received_timestamp) { $mail->setReceivedDate($mail->getSentDate()); } } $mail->setSize(strlen($content)); $mail->setCreatedOn(new DateTimeValue(time())); $mail->setCreatedById($account->getContactId()); $mail->setAccountEmail($account->getEmail()); $mail->setMessageId($message_id); $mail->setInReplyToId($in_reply_to_id); // set hasAttachments=true onlu if there is any attachment with FileDisposition='attachment' $has_attachments = false; foreach (array_var($parsedMail, "Attachments", array()) as $attachment) { if (array_var($attachment, 'FileDisposition') == 'attachment') { $has_attachments = true; } } $mail->setHasAttachments($has_attachments); $mail->setUid($uid); $type = array_var($parsedMail, 'Type', 'text'); switch ($type) { case 'html': $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', '')); //Solve bad syntax styles outlook if it exists if (substr_count($utf8_body, "<style>") != substr_count($utf8_body, "</style>") && substr_count($utf8_body, "/* Font Definitions */") >= 1) { $p1 = strpos($utf8_body, "/* Font Definitions */", 0); $utf8_body1 = substr($utf8_body, 0, $p1); $p0 = strrpos($utf8_body1, "</style>"); $html_content = ($p0 >= 0 ? substr($utf8_body1, 0, $p0) : $utf8_body1) . substr($utf8_body, $p1); $utf8_body = str_replace_first("/* Font Definitions */", "<style>", $utf8_body); } if ($enc_conv->hasError()) { $utf8_body = utf8_encode(array_var($parsedMail, 'Data', '')); } $utf8_body = utf8_safe($utf8_body); $mail->setBodyHtml($utf8_body); break; case 'text': $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Data', '')); if ($enc_conv->hasError()) { $utf8_body = utf8_encode(array_var($parsedMail, 'Data', '')); } $utf8_body = utf8_safe($utf8_body); $mail->setBodyPlain($utf8_body); break; case 'delivery-status': $utf8_body = $enc_conv->convert($encoding, 'UTF-8', array_var($parsedMail, 'Response', '')); if ($enc_conv->hasError()) { $utf8_body = utf8_encode(array_var($parsedMail, 'Response', '')); } $utf8_body = utf8_safe($utf8_body); $mail->setBodyPlain($utf8_body); break; default: if (array_var($parsedMail, 'FileDisposition') == 'inline') { $attachs = array_var($parsedMail, 'Attachments', array()); $attached_body = ""; foreach ($attachs as $k => $attach) { if (array_var($attach, 'Type') == 'html' || array_var($attach, 'Type') == 'text') { $attached_body .= $enc_conv->convert(array_var($attach, 'Encoding'), 'UTF-8', array_var($attach, 'Data')); } } $mail->setBodyHtml($attached_body); } else { if (isset($parsedMail['FileName'])) { // content-type is a file type => set as it has attachments, they will be parsed when viewing email $mail->setHasAttachments(true); } } break; } if (isset($parsedMail['Alternative'])) { foreach ($parsedMail['Alternative'] as $alt) { if ($alt['Type'] == 'html' || $alt['Type'] == 'text') { $body = $enc_conv->convert(array_var($alt, 'Encoding', 'UTF-8'), 'UTF-8', array_var($alt, 'Data', '')); if ($enc_conv->hasError()) { $body = utf8_encode(array_var($alt, 'Data', '')); } // remove large white spaces //$exploded = preg_split("/[\s]+/", $body, -1, PREG_SPLIT_NO_EMPTY); //$body = implode(" ", $exploded); // remove html comments $body = preg_replace('/<!--.*-->/i', '', $body); } $body = utf8_safe($body); if ($alt['Type'] == 'html') { $mail->setBodyHtml($body); } else { if ($alt['Type'] == 'text') { $plain = html_to_text(html_entity_decode($body, null, "UTF-8")); $mail->setBodyPlain($plain); } } // other alternative parts (like images) are not saved in database. } } $repository_id = self::SaveContentToFilesystem($mail->getUid(), $content); $mail->setContentFileId($repository_id); // START TRANSACTION DB::beginWork(); // Conversation //check if exists a conversation for this mail $conv_mail = ""; if ($in_reply_to_id != "" && $message_id != "") { $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')")); //check if this mail is in two diferent conversations and fixit if ($conv_mail) { $other_conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` != " . $conv_mail->getConversationId() . " AND (`message_id` = '{$in_reply_to_id}' OR `in_reply_to_id` = '{$message_id}')")); if ($other_conv_mail) { $other_conv = MailContents::findAll(array("conditions" => "`account_id`=" . $account->getId() . " AND `conversation_id` = " . $other_conv_mail->getConversationId())); if ($other_conv) { foreach ($other_conv as $mail_con) { $mail_con->setConversationId($conv_mail->getConversationId()); $mail_con->save(); } } } } } elseif ($in_reply_to_id != "") { $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `message_id` = '{$in_reply_to_id}'")); } elseif ($message_id != "") { $conv_mail = MailContents::findOne(array("conditions" => "`account_id`=" . $account->getId() . " AND `in_reply_to_id` = '{$message_id}'")); } if ($conv_mail instanceof MailContent) { $conv_id = $conv_mail->getConversationId(); } else { $conv_id = MailContents::getNextConversationId($account->getId()); } $mail->setConversationId($conv_id); $mail->save(); // CLASSIFY RECEIVED MAIL WITH THE CONVERSATION $classified_with_conversation = false; $member_ids = array(); if (user_config_option('classify_mail_with_conversation', null, $account->getContactId()) && isset($conv_mail) && $conv_mail instanceof MailContent) { $member_ids = array_merge($member_ids, $conv_mail->getMemberIds()); $classified_with_conversation = true; } // CLASSIFY MAILS IF THE ACCOUNT HAS A DIMENSION MEMBER AND NOT CLASSIFIED WITH CONVERSATION $account_owner = Contacts::findById($account->getContactId()); if ($account->getMemberId() != '' && !$classified_with_conversation) { $acc_mem_ids = explode(',', $account->getMemberId()); foreach ($acc_mem_ids as $acc_mem_id) { $member_ids[] = $acc_mem_id; } } foreach ($member_ids as $k => &$mem_id) { if ($mem_id == "") { unset($member_ids[$k]); } } if (count($member_ids) > 0) { $members = Members::instance()->findAll(array('conditions' => 'id IN (' . implode(',', $member_ids) . ')')); $mail->addToMembers($members, true); /* $ctrl = new ObjectController(); $ctrl->add_to_members($mail, $member_ids, $account_owner);*/ $mail_controller = new MailController(); $mail_controller->do_classify_mail($mail, $member_ids, null, false, true); } $user = Contacts::findById($account->getContactId()); if ($user instanceof Contact) { $mail->subscribeUser($user); } $mail->addToSharingTable(); $mail->orderConversation(); //if email is from an imap account copy the state (read/unread) from the server if (!is_null($read)) { $mail->setIsRead($account->getContactId(), $read); } // increase received count $received_count++; // to apply email rules $null = null; Hook::fire('after_mail_download', $mail, $null); DB::commit(); } catch (Exception $e) { $ret = null; Hook::fire('on_save_mail_error', array('content' => $content, 'account' => $account, 'exception' => $e), $ret); Logger::log($e->__toString()); DB::rollback(); if (FileRepository::isInRepository($repository_id)) { FileRepository::deleteFile($repository_id); } if (strpos($e->getMessage(), "Query failed with message 'Got a packet bigger than 'max_allowed_packet' bytes'") === false) { throw $e; } } unset($parsedMail); return false; }
if ($partialpaymentview == 'false') { if (strpos($list_query, "ORDER BY") !== false) { $list_query = str_replace("ORDER BY", "GROUP BY vtiger_accounting.accounting_id ORDER BY", $list_query); } else { $list_query .= " GROUP BY vtiger_accounting.accounting_id ORDER BY vtiger_accounting.accountingid"; } } else { if (strpos($list_query, "ORDER BY") !== false) { //$list_query = str_replace("ORDER BY", "ORDER BY vtiger_accounting.accountingid", $list_query); } else { $list_query .= " ORDER BY vtiger_accounting.accountingid"; } } $list_query = str_replace("ORDER BY vtiger_accounting.accounting_id", "ORDER BY vtiger_accounting.accountingid", $list_query); // Fix to related to searchs $list_query = str_replace_first("concat(firstname,' ',lastname)", "concat(vtiger_contactdetails.firstname,' ',vtiger_contactdetails.lastname)", $list_query); $list_query = str_replace_second("concat(firstname,' ',lastname)", "concat(vtiger_leaddetails.firstname,' ',vtiger_leaddetails.lastname)", $list_query); //Postgres 8 fixes if ($adb->dbType == "pgsql") { $list_query = fixPostgresQuery($list_query, $log, 0); } if (PerformancePrefs::getBoolean('LISTVIEW_COMPUTE_PAGE_COUNT', false) === true) { $count_result = $adb->query(mkCountQuery($list_query)); $noofrows = $adb->query_result($count_result, 0, "count"); } else { $noofrows = null; } if ($partialpaymentview !== 'true') { $res = $adb->query($list_query); $noofrows = $adb->num_rows($res); }
function total_task_times($report_data = null, $task = null) { if (!$report_data) { $report_data = array_var($_POST, 'report'); // save selections into session $_SESSION['total_task_times_report_data'] = $report_data; } if (array_var($_GET, 'export') == 'csv') { $context = build_context_array(array_var($_REQUEST, 'context')); $report_data = json_decode(str_replace("'", '"', $_REQUEST['parameters']), true); tpl_assign('context', $context); } else { $context = active_context(); } $columns = array_var($report_data, 'columns'); if (!is_array($columns)) { $columns = array_var($_POST, 'columns', array()); } asort($columns); //sort the array by column order foreach ($columns as $column => $order) { if ($order > 0) { $newColumn = new ReportColumn(); //$newColumn->setReportId($newReport->getId()); if (is_numeric($column)) { $newColumn->setCustomPropertyId($column); } else { $newColumn->setFieldName($column); } } } $user = Contacts::findById(array_var($report_data, 'user')); $now = DateTimeValueLib::now(); $now->advance(logged_user()->getTimezone() * 3600, true); switch (array_var($report_data, 'date_type')) { case 1: //Today $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), $now->getDay(), $now->getYear()); $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), $now->getDay(), $now->getYear()); break; case 2: //This week $monday = $now->getMondayOfWeek(); $nextMonday = $now->getMondayOfWeek()->add('w', 1)->add('d', -1); $st = DateTimeValueLib::make(0, 0, 0, $monday->getMonth(), $monday->getDay(), $monday->getYear()); $et = DateTimeValueLib::make(23, 59, 59, $nextMonday->getMonth(), $nextMonday->getDay(), $nextMonday->getYear()); break; case 3: //Last week $monday = $now->getMondayOfWeek()->add('w', -1); $nextMonday = $now->getMondayOfWeek()->add('d', -1); $st = DateTimeValueLib::make(0, 0, 0, $monday->getMonth(), $monday->getDay(), $monday->getYear()); $et = DateTimeValueLib::make(23, 59, 59, $nextMonday->getMonth(), $nextMonday->getDay(), $nextMonday->getYear()); break; case 4: //This month $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), 1, $now->getYear()); $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), 1, $now->getYear())->add('M', 1)->add('d', -1); break; case 5: //Last month $now->add('M', -1); $st = DateTimeValueLib::make(0, 0, 0, $now->getMonth(), 1, $now->getYear()); $et = DateTimeValueLib::make(23, 59, 59, $now->getMonth(), 1, $now->getYear())->add('M', 1)->add('d', -1); break; case 6: //Date interval $st = getDateValue(array_var($report_data, 'start_value')); $st = $st->beginningOfDay(); $et = getDateValue(array_var($report_data, 'end_value')); $et = $et->endOfDay(); break; } $timeslotType = array_var($report_data, 'timeslot_type', 0); $group_by = array(); for ($i = 1; $i <= 3; $i++) { if ($timeslotType == 0) { $gb = array_var($report_data, 'group_by_' . $i); } else { $gb = array_var($report_data, 'alt_group_by_' . $i); } if ($gb != '0') { $group_by[] = $gb; } } $timeslots = Timeslots::getTaskTimeslots($context, null, $user, $st, $et, array_var($report_data, 'task_id', 0), $group_by, null, null, null, $timeslotType); $unworkedTasks = null; if (array_var($report_data, 'include_unworked') == 'checked') { $unworkedTasks = ProjectTasks::getPendingTasks(logged_user(), $workspace); tpl_assign('unworkedTasks', $unworkedTasks); } $gb_criterias = array(); foreach ($group_by as $text) { if (in_array($text, array('contact_id', 'rel_object_id'))) { $gb_criterias[] = array('type' => 'column', 'value' => $text); } else { if (in_array($text, array('milestone_id', 'priority'))) { $gb_criterias[] = array('type' => 'assoc_obj', 'fk' => 'rel_object_id', 'value' => $text); } else { if (str_starts_with($text, 'dim_')) { $gb_criterias[] = array('type' => 'dimension', 'value' => str_replace_first('dim_', '', $text)); } } } } $grouped_timeslots = groupObjects($gb_criterias, $timeslots); tpl_assign('columns', $columns); tpl_assign('timeslotsArray', array()); tpl_assign('grouped_timeslots', $grouped_timeslots); if (array_var($report_data, 'date_type') == 6) { $st->advance(logged_user()->getTimezone() * 3600, true); $et->advance(logged_user()->getTimezone() * 3600, true); } tpl_assign('start_time', $st); tpl_assign('end_time', $et); tpl_assign('user', $user); tpl_assign('post', $report_data); tpl_assign('template_name', 'total_task_times'); tpl_assign('title', lang('task time report')); tpl_assign('allow_export', false); if (array_var($_GET, 'export') == 'csv') { $this->setTemplate('total_task_times_csv'); ajx_current("empty"); } else { $this->setTemplate('report_wrapper'); } }
/** * Add company * * @param void * @return null */ function add_company() { if (logged_user()->isGuest()) { flash_error(lang('no access permissions')); ajx_current("empty"); return; } $notAllowedMember = ''; if(!Contact::canAdd(logged_user(),active_context(),$notAllowedMember)) { if (str_starts_with($notAllowedMember, '-- req dim --')) flash_error(lang('must choose at least one member of', str_replace_first('-- req dim --', '', $notAllowedMember, $in))); else flash_error(lang('no context permissions to add',lang("contacts"), $notAllowedMember)); ajx_current("empty"); return; } // if $company = new Contact(); $company->setIsCompany(1); $company_data = array_var($_POST, 'company'); if(!is_array($company_data)) { $company_data = array( 'timezone' => logged_user()->getTimezone(), ); // array } // if tpl_assign('company', $company); tpl_assign('company_data', $company_data); if (is_array(array_var($_POST, 'company'))) { $company->setFromAttributes($company_data); $company->setObjectName(); try { Contacts::validate($company_data); DB::beginWork(); $company->save(); if($company_data['address'] != "") $company->addAddress($company_data['address'], $company_data['city'], $company_data['state'], $company_data['country'], $company_data['zipcode'], 'work', true); if($company_data['phone_number'] != "") $company->addPhone($company_data['phone_number'], 'work', true); if($company_data['fax_number'] != "") $company->addPhone($company_data['fax_number'], 'fax', true); if($company_data['homepage'] != "") $company->addWebpage($company_data['homepage'], 'work'); if($company_data['email'] != "") $company->addEmail($company_data['email'], 'work' , true); $object_controller = new ObjectController(); $object_controller->add_subscribers($company); $member_ids = json_decode(array_var($_POST, 'members')); if (!is_null($member_ids)) { $object_controller->add_to_members($company, $member_ids); } $object_controller->link_to_new_object($company); $object_controller->add_custom_properties($company); ApplicationLogs::createLog($company, ApplicationLogs::ACTION_ADD); DB::commit(); flash_success(lang('success add client', $company->getObjectName())); evt_add("company added", array("id" => $company->getObjectId(), "name" => $company->getObjectName())); ajx_current("back"); } catch(Exception $e) { DB::rollback(); ajx_current("empty"); flash_error($e->getMessage()); } // try } // if } // add_company
/** * Render button * * @access public * @param string $this Button title * @param string $accesskey Accesskey. If NULL accesskey will be skipped * @param array $attributes Array of additinal attributes * @return string */ function button($title, $accesskey = 's', $attributes = null) { if (!is_array($attributes)) { $attributes = array(); } // if $attributes['class'] = 'submit'; $attributes['type'] = 'button'; $attributes['accesskey'] = $accesskey; if ($accesskey) { if (strpos($title, $accesskey) !== false) { $title = str_replace_first($accesskey, "<u>{$accesskey}</u>", $title); } // if } // if return open_html_tag('button', $attributes) . $title . close_html_tag('button'); }
/** * Helper function to insert some HTML after the last javascript include. * First in the head section, but if there is no script in the head, place * it anywhere. * * @param string $tag * @param string $html * @param bool $insidehead * @return string */ public function insertAfterJs($tag, $html, $insidehead = true) { // Set $context: only the part until </head>, or entire document. if ($insidehead) { $pos = strpos($html, "</head>"); $context = substr($html, 0, $pos); } else { $context = $html; } // then, attempt to insert it after the last <script> tag within context, matching indentation.. if (preg_match_all("~^([ \t]*)(.*)</script>~mi", $context, $matches)) { // matches[0] has some elements, the last index is -1, because zero indexed. $last = count($matches[0]) - 1; $replacement = sprintf("%s\n%s%s", $matches[0][$last], $matches[1][$last], $tag); $html = str_replace_first($matches[0][$last], $replacement, $html); } elseif ($insidehead) { // Second attempt: entire document $html = $this->insertAfterJs($tag, $html, false); } else { // Just insert it at the end of the head section. $html = $this->insertEndOfHead($tag, $html); } return $html; }
/** * @param string $colour */ public function setColourAttribute(string $colour) { $this->attributes['colour'] = substr(str_replace_first('#', '', $colour), 0, 6); }
static function findByContext($options = array()) { // Initialize method result $result = new stdClass(); $result->total = 0; $result->objects = array(); // Read arguments and Init Vars $limit = array_var($options, 'limit'); $offset = array_var($options, 'offset'); $trashed = array_var($options, 'trashed'); $archived = array_var($options, 'archived'); $members = active_context_members(false); $type_id = self::instance()->getObjectTypeId(); $uid = logged_user()->getId(); if ($limit > 0) { $limit_sql = "LIMIT " . ($offset ? "{$offset}, " : "") . "{$limit}"; } else { $limit_sql = ''; } $member_conditions = count($members) > 0 ? "id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members WHERE member_id IN (" . implode(',', $members) . "))" : "true"; $trashed_conditions = "AND o.trashed_on " . ($trashed ? ">" : "=") . " 0"; $archived_conditions = "AND o.archived_on " . ($archived ? ">" : "=") . " 0"; $extra_conditions = array_var($options, 'extra_conditions', ""); // Build Main SQL $template_sql = "\r\n\t \tSELECT <selection> FROM " . TABLE_PREFIX . "objects o\r\n\t \tINNER JOIN " . TABLE_PREFIX . "mail_contents m ON m.object_id = o.id\r\n\t \tWHERE \r\n\t \t\to.id IN ( \r\n\t \t\t\tSELECT object_id FROM " . TABLE_PREFIX . "sharing_table\r\n\t \t\t\tWHERE group_id IN (\r\n\t\t \t\t\tSELECT permission_group_id FROM " . TABLE_PREFIX . "contact_permission_groups WHERE contact_id = {$uid}\r\n\t\t\t\t\t)\r\n\t\t\t\t) \r\n\t\t\t\tAND {$member_conditions}\r\n\t\t\t\tAND o.object_type_id = {$type_id}\r\n\t\t\t\tAND m.is_deleted = 0 {$trashed_conditions} {$archived_conditions} {$extra_conditions}"; $count_sql = str_replace_first("<selection>", "COUNT(distinct(o.id)) as total", $template_sql); $sql = str_replace_first("<selection>", "distinct(o.id)", $template_sql) . " {$limit_sql}"; // count all emails $res = DB::execute($count_sql); $result->total = array_var($res->fetchRow(), 'total'); if ($result->total == 0) { return $result; } // Execute query and build the resultset $rows = DB::executeAll($sql); $mail_ids = array(); foreach ($rows as $row) { $mail_ids[] = $row['id']; } $result->objects = MailContents::findAll(array("conditions" => "object_id IN (" . implode(",", $mail_ids) . ")", "order" => array_var($options, 'order'))); return $result; }
/** * Set something before file extension * * @access public * @param string $in Filename * @param string $insert Insert this * @return null */ function insert_before_file_extension($filename, $insert) { if (strpos($filename,'.') > 0) return str_replace_first('.', $insert . '.', $filename); else return $filename . $insert; } // insert_before_file_extension