function import_from_vcard() {
		if (logged_user()->isGuest()) {
			flash_error(lang('no access permissions'));
			ajx_current("empty");
			return;
		}
		@set_time_limit(0);
		ini_set('auto_detect_line_endings', '1');
		if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) unset($_SESSION['go_back']);
		if (isset($_SESSION['go_back'])) {
			unset($_SESSION['go_back']);
			ajx_current("start");
		} else {
                
                    if(!Contact::canAdd(logged_user(), active_context())) {
                            flash_error(lang('no access permissions'));
                            ajx_current("empty");
                            return;
                    } 

                    $this->setTemplate('vcard_import');
                    tpl_assign('import_type', 'contact');                

                    $filedata = array_var($_FILES, 'vcard_file');
                    if (is_array($filedata)) {
                            $filename = ROOT.'/tmp/'.logged_user()->getId().'temp.vcf';
                            copy($filedata['tmp_name'], $filename);
                            $result = $this->read_vcard_file($filename);
                            unlink($filename);
                            $import_result = array('import_ok' => array(), 'import_fail' => array());

                            foreach ($result as $contact_data) {
                                    try {
                                            DB::beginWork();
                                            if (isset($contact_data['photo_tmp_filename'])) {
                                                $file_id = FileRepository::addFile($contact_data['photo_tmp_filename'], array('public' => true));
                                                $contact_data['picture_file'] = $file_id;
                                                unlink($contact_data['photo_tmp_filename']);
                                                unset($contact_data['photo_tmp_filename']);
                                            }
                                            if (isset($contact_data['company_name'])) {
                                                $company = Contacts::findOne(array("conditions" => "`first_name` = '".mysql_real_escape_string($contact_data['company_name'])."'"));
                                                if ($company == null) {                                                        
                                                        $company = new Contact();
                                                        $company->setObjectName($contact_data['company_name']);
                                                        $company->setIsCompany(1);
                                                        $company->save();                                                        
                                                        ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_ADD);
                                                }
                                                $contact_data['company_id'] = $company->getObjectId();
                                                unset($contact_data['company_name']);
                                            }

                                            $contact_data['import_status'] = '('.lang('updated').')';
                                            $fname = DB::escape(array_var($contact_data, "first_name"));
                                            $lname = DB::escape(array_var($contact_data, "surname"));
                                            $email_cond = array_var($contact_data, "email") != '' ? " OR email_address = '".array_var($contact_data, "email")."'" : "";
                                            $contact = Contacts::findOne(array(
                                                "conditions" => "first_name = ".$fname." AND surname = ".$lname." $email_cond",
                                                'join' => array(
                                                        'table' => ContactEmails::instance()->getTableName(),
                                                        'jt_field' => 'contact_id',
                                                        'e_field' => 'object_id',
                                                )));                                                        
                                            $log_action = ApplicationLogs::ACTION_EDIT;
                                            if (!$contact) {
                                                    $contact = new Contact();
                                                    $contact_data['import_status'] = '('.lang('new').')';
                                                    $log_action = ApplicationLogs::ACTION_ADD;
                                                    $can_import = active_project() != null ? $contact->canAdd(logged_user(), active_project()) : can_manage_contacts(logged_user());
                                            } else {
                                                    $can_import = $contact->canEdit(logged_user());
                                            }

                                            if ($can_import) {
                                                    $comp_name = DB::escape(array_var($contact_data, "company_id"));
                                                    if ($comp_name != '') {
                                                            $company = Contacts::findOne(array("conditions" => "first_name = $comp_name AND is_company = 1"));
                                                            if ($company) {
                                                                    $contact_data['company_id'] = $company->getId();
                                                            } 
                                                            $contact_data['import_status'] .= " " . lang("company") . " $comp_name";
                                                    } else {
                                                            $contact_data['company_id'] = 0;
                                                    }
                                                    $contact_data['birthday'] = $contact_data["o_birthday"];
                                                    $contact_data['name'] = $contact_data['first_name']." ".$contact_data['surname'];
                                                    $contact->setFromAttributes($contact_data);
                                                    $contact->save();

                                                    //Home form
                                                    if($contact_data['h_address'] != "")
                                                        $contact->addAddress($contact_data['h_address'], $contact_data['h_city'], $contact_data['h_state'], $contact_data['h_country'], $contact_data['h_zipcode'], 'home');
                                                    if($contact_data['h_phone_number'] != "") $contact->addPhone($contact_data['h_phone_number'], 'home', true);
                                                    if($contact_data['h_phone_number2'] != "") $contact->addPhone($contact_data['h_phone_number2'], 'home');
                                                    if($contact_data['h_mobile_number'] != "") $contact->addPhone($contact_data['h_mobile_number'], 'mobile');
                                                    if($contact_data['h_fax_number'] != "") $contact->addPhone($contact_data['h_fax_number'], 'fax');
                                                    if($contact_data['h_pager_number'] != "") $contact->addPhone($contact_data['h_pager_number'], 'pager');
                                                    if($contact_data['h_web_page'] != "") $contact->addWebpage($contact_data['h_web_page'], 'personal');

                                                    //Work form
                                                    if($contact_data['w_address'] != "")
                                                        $contact->addAddress($contact_data['w_address'], $contact_data['w_city'], $contact_data['w_state'], $contact_data['w_country'], $contact_data['w_zipcode'], 'work');
                                                    if($contact_data['w_phone_number'] != "") $contact->addPhone($contact_data['w_phone_number'], 'work', true);
                                                    if($contact_data['w_phone_number2'] != "") $contact->addPhone($contact_data['w_phone_number2'], 'work');
                                                    if($contact_data['w_assistant_number'] != "") $contact->addPhone($contact_data['w_assistant_number'], 'assistant');
                                                    if($contact_data['w_callback_number'] != "") $contact->addPhone($contact_data['w_callback_number'], 'callback');
                                                    if($contact_data['w_fax_number'] != "") $contact->addPhone($contact_data['w_fax_number'], 'fax', true);
                                                    if($contact_data['w_web_page'] != "") $contact->addWebpage($contact_data['w_web_page'], 'work');

                                                    //Other form
                                                    if($contact_data['o_address'] != "")
                                                        $contact->addAddress($contact_data['o_address'], $contact_data['o_city'], $contact_data['o_state'], $contact_data['o_country'], $contact_data['o_zipcode'], 'other');
                                                    if($contact_data['o_phone_number'] != "") $contact->addPhone($contact_data['o_phone_number'], 'other', true);
                                                    if($contact_data['o_phone_number2'] != "") $contact->addPhone($contact_data['o_phone_number2'], 'other');
                                                    if($contact_data['o_web_page'] != "") $contact->addWebpage($contact_data['o_web_page'], 'other');

                                                    //Emails and instant messaging form
                                                    if($contact_data['email'] != "") $contact->addEmail($contact_data['email'], 'personal', true);
                                                    if($contact_data['email2'] != "") $contact->addEmail($contact_data['email2'], 'personal');
                                                    if($contact_data['email3'] != "") $contact->addEmail($contact_data['email3'], 'personal');

                                                    ApplicationLogs::createLog($contact, null, $log_action);
                                                    $import_result['import_ok'][] = $contact_data;
                                            } else {
                                                    throw new Exception(lang('no access permissions'));
                                            }
                                            DB::commit();					
                                    } catch (Exception $e) {
                                            DB::rollback();
                                            $fail_msg = substr_utf($e->getMessage(), strpos_utf($e->getMessage(), "\r\n"));
                                            $import_result['import_fail'][] = array('first_name' => $fname, 'surname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status'], 'fail_message' => $fail_msg);
                                    }
                            }
                            $_SESSION['go_back'] = true;
                            tpl_assign('import_result', $import_result);
                        }
                    }
                        
	}
Exemplo n.º 2
0
 /**
 * Return associated contact
 *
 * @param void
 * @return Contact
 */
 function getContact() {
   if (!isset($this->contact)) {
     $contact = Contacts::findOne(array('conditions' => array('`user_id` = ? ', $this->getId())));
     if ($contact instanceof Contact) {
       $this->contact = $contact;
     } else {
       $this->contact = new Contact;
       $this->contact->setDisplayName(lang('missing contact'));
       $this->contact->setCompanyId(owner_company()->getId());
     }
   }
   return $this->contact;
 } // getContact
Exemplo n.º 3
0
$argv or die("Are you using console ? \n");
$usage = "USAGE: plugin-console.php COMMAND [list, install, activate, deactivate, update, update_all] PLUGIN_NAME \n";
chdir(dirname(__FILE__) . '/../..');
define("CONSOLE_MODE", true);
define("PLUGIN_MANAGER_CONSOLE", true);
if (!defined('PUBLIC_FOLDER')) {
    define('PUBLIC_FOLDER', 'public');
}
require_once 'init.php';
if (!isset($argv) || !is_array($argv)) {
    die("There is no input arguments\n");
}
// if
$command = array_var($argv, 1);
$arg1 = array_var($argv, 2);
$usr = Contacts::findOne(array("conditions" => "user_type = (SELECT id FROM " . TABLE_PREFIX . "permission_groups WHERE name='Super Administrator')"));
$usr or die("Super Administrator user not found\n");
CompanyWebsite::instance()->logUserIn($usr);
$ctrl = new PluginController();
trim($command) or die("Command is required \n" . $usage);
if ($command == 'list') {
    foreach ($ctrl->index() as $plg) {
        /* @var $plg Plugin */
        echo "---------------------------------------------\n";
        echo "NAME: \t\t" . $plg->getSystemName() . "\n";
        echo "VERSION: \t" . $plg->getVersion() . "\n";
        echo "STATUS: \t" . ($plg->isInstalled() ? 'Installed ' : 'Uninstalled ') . ($plg->isActive() ? 'Activated ' : 'Inactive ') . "\n";
        if ($plg->updateAvailable()) {
            echo "*** There is a new version of this plugin *** \n";
        }
    }
Exemplo n.º 4
0
 /**
  * Execute a report and return results
  *
  * @param $id
  * @param $params
  *
  * @return array
  */
 static function executeReport($id, $params, $order_by_col = '', $order_by_asc = true, $offset = 0, $limit = 50, $to_print = false)
 {
     if (is_null(active_context())) {
         CompanyWebsite::instance()->setContext(build_context_array(array_var($_REQUEST, 'context')));
     }
     $results = array();
     $report = self::getReport($id);
     $show_archived = false;
     if ($report instanceof Report) {
         $conditionsFields = ReportConditions::getAllReportConditionsForFields($id);
         $conditionsCp = ReportConditions::getAllReportConditionsForCustomProperties($id);
         $ot = ObjectTypes::findById($report->getReportObjectTypeId());
         $table = $ot->getTableName();
         if ($ot->getType() == 'dimension_object' || $ot->getType() == 'dimension_group') {
             $hook_parameters = array('report' => $report, 'params' => $params, 'order_by_col' => $order_by_col, 'order_by_asc' => $order_by_asc, 'offset' => $offset, 'limit' => $limit, 'to_print' => $to_print);
             $report_result = null;
             Hook::fire('replace_execute_report_function', $hook_parameters, $report_result);
             if ($report_result) {
                 return $report_result;
             }
         }
         eval('$managerInstance = ' . $ot->getHandlerClass() . "::instance();");
         eval('$item_class = ' . $ot->getHandlerClass() . '::instance()->getItemClass(); $object = new $item_class();');
         $order_by = '';
         if (is_object($params)) {
             $params = get_object_vars($params);
         }
         $report_columns = ReportColumns::getAllReportColumns($id);
         $allConditions = "";
         $contact_extra_columns = self::get_extra_contact_columns();
         if (count($conditionsFields) > 0) {
             foreach ($conditionsFields as $condField) {
                 if ($condField->getFieldName() == "archived_on") {
                     $show_archived = true;
                 }
                 $skip_condition = false;
                 $model = $ot->getHandlerClass();
                 $model_instance = new $model();
                 $col_type = $model_instance->getColumnType($condField->getFieldName());
                 $allConditions .= ' AND ';
                 $dateFormat = 'm/d/Y';
                 if (isset($params[$condField->getId()])) {
                     $value = $params[$condField->getId()];
                     if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                         $dateFormat = user_config_option('date_format');
                     }
                 } else {
                     $value = $condField->getValue();
                 }
                 if ($ot->getHandlerClass() == 'Contacts' && in_array($condField->getFieldName(), $contact_extra_columns)) {
                     $allConditions .= self::get_extra_contact_column_condition($condField->getFieldName(), $condField->getCondition(), $value);
                 } else {
                     if ($value == '' && $condField->getIsParametrizable()) {
                         $skip_condition = true;
                     }
                     if (!$skip_condition) {
                         $field_name = $condField->getFieldName();
                         if (in_array($condField->getFieldName(), Objects::getColumns())) {
                             $field_name = 'o`.`' . $condField->getFieldName();
                         }
                         if ($condField->getCondition() == 'like' || $condField->getCondition() == 'not like') {
                             $value = '%' . $value . '%';
                         }
                         if ($col_type == DATA_TYPE_DATE || $col_type == DATA_TYPE_DATETIME) {
                             if ($value == date_format_tip($dateFormat)) {
                                 $value = EMPTY_DATE;
                             } else {
                                 $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                                 $value = $dtValue->format('Y-m-d');
                             }
                         }
                         if ($condField->getCondition() != '%') {
                             if ($col_type == DATA_TYPE_INTEGER || $col_type == DATA_TYPE_FLOAT) {
                                 $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                             } else {
                                 if ($condField->getCondition() == '=' || $condField->getCondition() == '<=' || $condField->getCondition() == '>=') {
                                     if ($col_type == DATA_TYPE_DATETIME || $col_type == DATA_TYPE_DATE) {
                                         $equal = 'datediff(' . DB::escape($value) . ', `' . $field_name . '`)=0';
                                     } else {
                                         $equal = '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                     }
                                     switch ($condField->getCondition()) {
                                         case '=':
                                             $allConditions .= $equal;
                                             break;
                                         case '<=':
                                         case '>=':
                                             $allConditions .= '(`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value) . ' OR ' . $equal . ') ';
                                             break;
                                     }
                                 } else {
                                     $allConditions .= '`' . $field_name . '` ' . $condField->getCondition() . ' ' . DB::escape($value);
                                 }
                             }
                         } else {
                             $allConditions .= '`' . $field_name . '` like ' . DB::escape("%{$value}");
                         }
                     } else {
                         $allConditions .= ' true';
                     }
                 }
             }
         }
         if (count($conditionsCp) > 0) {
             $dateFormat = user_config_option('date_format');
             $date_format_tip = date_format_tip($dateFormat);
             foreach ($conditionsCp as $condCp) {
                 $cp = CustomProperties::getCustomProperty($condCp->getCustomPropertyId());
                 $skip_condition = false;
                 if (isset($params[$condCp->getId() . "_" . $cp->getName()])) {
                     $value = $params[$condCp->getId() . "_" . $cp->getName()];
                 } else {
                     $value = $condCp->getValue();
                 }
                 if ($value == '' && $condCp->getIsParametrizable()) {
                     $skip_condition = true;
                 }
                 if (!$skip_condition) {
                     $current_condition = ' AND ';
                     $current_condition .= 'o.id IN ( SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv WHERE ';
                     $current_condition .= ' cpv.custom_property_id = ' . $condCp->getCustomPropertyId();
                     $fieldType = $object->getColumnType($condCp->getFieldName());
                     if ($condCp->getCondition() == 'like' || $condCp->getCondition() == 'not like') {
                         $value = '%' . $value . '%';
                     }
                     if ($cp->getType() == 'date') {
                         if ($value == $date_format_tip) {
                             continue;
                         }
                         $dtValue = DateTimeValueLib::dateFromFormatAndString($dateFormat, $value);
                         $value = $dtValue->format('Y-m-d H:i:s');
                     }
                     if ($condCp->getCondition() != '%') {
                         if ($cp->getType() == 'numeric') {
                             $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                         } else {
                             if ($cp->getType() == 'boolean') {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . ($value ? '1' : '0');
                                 if (!$value) {
                                     $current_condition .= ') OR o.id NOT IN (SELECT object_id as id FROM ' . TABLE_PREFIX . 'custom_property_values cpv2 WHERE cpv2.object_id=o.id AND cpv2.value=1 AND cpv2.custom_property_id = ' . $condCp->getCustomPropertyId();
                                 }
                             } else {
                                 $current_condition .= ' AND cpv.value ' . $condCp->getCondition() . ' ' . DB::escape($value);
                             }
                         }
                     } else {
                         $current_condition .= ' AND cpv.value like ' . DB::escape("%{$value}");
                     }
                     $current_condition .= ')';
                     $allConditions .= $current_condition;
                 }
             }
         }
         $select_columns = array('*');
         $join_params = null;
         if ($order_by_col == '') {
             $order_by_col = $report->getOrderBy();
         }
         if ($ot->getHandlerClass() == 'Contacts' && in_array($order_by_col, $contact_extra_columns)) {
             $join_params = self::get_extra_contact_column_order_by($order_by_col, $order_by_col, $select_columns);
         }
         $original_order_by_col = $order_by_col;
         if (in_array($order_by_col, self::$external_columns)) {
             $order_by_col = 'name_order';
             $join_params = array('table' => Objects::instance()->getTableName(), 'jt_field' => 'id', 'e_field' => $original_order_by_col, 'join_type' => 'left');
             $select_columns = array();
             $tmp_cols = $managerInstance->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "e.{$col}";
             }
             $tmp_cols = Objects::instance()->getColumns();
             foreach ($tmp_cols as $col) {
                 $select_columns[] = "o.{$col}";
             }
             $select_columns[] = 'jt.name as name_order';
         }
         if ($order_by_asc == null) {
             $order_by_asc = $report->getIsOrderByAsc();
         }
         if ($ot->getName() == 'task' && !SystemPermissions::userHasSystemPermission(logged_user(), 'can_see_assigned_to_other_tasks')) {
             $allConditions .= " AND assigned_to_contact_id = " . logged_user()->getId();
         }
         if ($managerInstance) {
             if ($order_by_col == "order") {
                 $order_by_col = "`{$order_by_col}`";
             }
             $listing_parameters = array("select_columns" => $select_columns, "order" => "{$order_by_col}", "order_dir" => $order_by_asc ? "ASC" : "DESC", "extra_conditions" => $allConditions, "count_results" => true, "join_params" => $join_params);
             if ($limit > 0) {
                 $listing_parameters["start"] = $offset;
                 $listing_parameters["limit"] = $limit;
             }
             if ($show_archived) {
                 $listing_parameters["archived"] = true;
             }
             $result = $managerInstance->listing($listing_parameters);
         } else {
             // TODO Performance Killer
             $result = ContentDataObjects::getContentObjects(active_context(), $ot, $order_by_col, $order_by_asc ? "ASC" : "DESC", $allConditions);
         }
         $objects = $result->objects;
         $totalResults = $result->total;
         $results['pagination'] = Reports::getReportPagination($id, $params, $original_order_by_col, $order_by_asc, $offset, $limit, $totalResults);
         $dimensions_cache = array();
         foreach ($report_columns as $column) {
             if ($column->getCustomPropertyId() == 0) {
                 $field = $column->getFieldName();
                 if (str_starts_with($field, 'dim_')) {
                     $dim_id = str_replace("dim_", "", $field);
                     $dimension = Dimensions::getDimensionById($dim_id);
                     $dimensions_cache[$dim_id] = $dimension;
                     $column_name = $dimension->getName();
                     $results['columns'][$field] = $column_name;
                     $results['db_columns'][$column_name] = $field;
                 } else {
                     if ($managerInstance->columnExists($field) || Objects::instance()->columnExists($field)) {
                         $column_name = Localization::instance()->lang('field ' . $ot->getHandlerClass() . ' ' . $field);
                         if (is_null($column_name)) {
                             $column_name = lang('field Objects ' . $field);
                         }
                         $results['columns'][$field] = $column_name;
                         $results['db_columns'][$column_name] = $field;
                     } else {
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if (in_array($field, $contact_extra_columns)) {
                                 $results['columns'][$field] = lang($field);
                                 $results['db_columns'][lang($field)] = $field;
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'Timeslots') {
                                 if (in_array($field, array('time', 'billing'))) {
                                     $results['columns'][$field] = lang('field Objects ' . $field);
                                     $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                 }
                             } else {
                                 if ($ot->getHandlerClass() == 'MailContents') {
                                     if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                         $results['columns'][$field] = lang('field Objects ' . $field);
                                         $results['db_columns'][lang('field Objects ' . $field)] = $field;
                                     }
                                 }
                             }
                         }
                     }
                 }
             } else {
                 $results['columns'][$column->getCustomPropertyId()] = $column->getCustomPropertyId();
             }
         }
         $report_rows = array();
         foreach ($objects as &$object) {
             /* @var $object Object */
             $obj_name = $object->getObjectName();
             $icon_class = $object->getIconClass();
             $row_values = array('object_type_id' => $object->getObjectTypeId());
             if (!$to_print) {
                 $row_values['link'] = '<a class="link-ico ' . $icon_class . '" title="' . clean($obj_name) . '" target="new" href="' . $object->getViewUrl() . '">&nbsp;</a>';
             }
             foreach ($report_columns as $column) {
                 if ($column->getCustomPropertyId() == 0) {
                     $field = $column->getFieldName();
                     if (str_starts_with($field, 'dim_')) {
                         $dim_id = str_replace("dim_", "", $field);
                         if (!array_var($dimensions_cache, $dim_id) instanceof Dimension) {
                             $dimension = Dimensions::getDimensionById($dim_id);
                             $dimensions_cache[$dim_id] = $dimension;
                         } else {
                             $dimension = array_var($dimensions_cache, $dim_id);
                         }
                         $om_object_id = $object instanceof Timeslot ? $object->getRelObjectId() : $object->getId();
                         $members = ObjectMembers::getMembersByObjectAndDimension($om_object_id, $dim_id, " AND om.is_optimization=0");
                         $value = "";
                         foreach ($members as $member) {
                             /* @var $member Member */
                             $val = $member->getPath();
                             $val .= ($val == "" ? "" : "/") . $member->getName();
                             if ($value != "") {
                                 $val = " - {$val}";
                             }
                             $value .= $val;
                         }
                         $row_values[$field] = $value;
                     } else {
                         if ($object instanceof Timeslot) {
                             if ($field == 'id') {
                                 $value = $object->getObjectId();
                             } else {
                                 $value = $object->getColumnValue($field);
                                 // if it is a task column
                                 if (in_array($field, ProjectTasks::instance()->getColumns())) {
                                     $task = ProjectTasks::findById($object->getRelObjectId());
                                     // if task exists
                                     if ($task instanceof ProjectTask) {
                                         $value = $task->getColumnValue($field);
                                         // if it is an external task column
                                         if (in_array($field, ProjectTasks::instance()->getExternalColumns())) {
                                             $value = self::instance()->getExternalColumnValue($field, $value, ProjectTasks::instance());
                                         } else {
                                             // if is a date then use format
                                             if (ProjectTasks::instance()->getColumnType($field) == DATA_TYPE_DATETIME && $value instanceof DateTimeValue) {
                                                 $value = format_value_to_print($field, $value->toMySQL(), DATA_TYPE_DATETIME, $report->getReportObjectTypeId());
                                             }
                                         }
                                     }
                                     $results['columns'][$field] = lang('field ProjectTasks ' . $field);
                                     $results['db_columns'][lang('field ProjectTasks ' . $field)] = $field;
                                 }
                             }
                         } else {
                             $value = $object->getColumnValue($field);
                         }
                         if ($value instanceof DateTimeValue) {
                             $dateFormat = user_config_option('date_format');
                             Hook::fire("custom_property_date_format", null, $dateFormat);
                             $tz = logged_user()->getTimezone();
                             if ($object instanceof ProjectTask) {
                                 if ($field == 'due_date' && !$object->getUseDueTime() || $field == 'start_date' && !$object->getUseStartTime()) {
                                     $dateFormat = user_config_option('date_format');
                                     $tz = 0;
                                 }
                             }
                             $value = format_date($value, $dateFormat, $tz * 3600);
                         }
                         if (in_array($field, $managerInstance->getExternalColumns())) {
                             if ($object instanceof Timeslot && $field == 'time') {
                                 $lastStop = $object->getEndTime() != null ? $object->getEndTime() : ($object->isPaused() ? $object->getPausedOn() : DateTimeValueLib::now());
                                 $seconds = $lastStop->getTimestamp() - $object->getStartTime()->getTimestamp();
                                 $hours = number_format($seconds / 3600, 2, ',', '.');
                                 $value = $hours;
                                 //$value = DateTimeValue::FormatTimeDiff($object->getStartTime(), $lastStop, "hm", 60, $object->getSubtract());
                             } else {
                                 if ($object instanceof Timeslot && $field == 'billing') {
                                     $value = config_option('currency_code', '$') . ' ' . $object->getFixedBilling();
                                 } else {
                                     $value = self::instance()->getExternalColumnValue($field, $value, $managerInstance);
                                 }
                             }
                         } else {
                             if ($field != 'link') {
                                 //$value = html_to_text(html_entity_decode($value));
                                 if ($object->getColumnType($field) == DATA_TYPE_STRING) {
                                     // change html block end tags and brs to \n, then remove all other html tags, then replace \n with <br>, to remove all styles and keep the enters
                                     $value = str_replace(array("</div>", "</p>", "<br>", "<br />", "<br/>"), "\n", $value);
                                     $value = nl2br(strip_tags($value));
                                 }
                             }
                         }
                         if (self::isReportColumnEmail($value)) {
                             if (logged_user()->hasMailAccounts()) {
                                 $value = '<a class="internalLink" href="' . get_url('mail', 'add_mail', array('to' => clean($value))) . '">' . clean($value) . '</a></div>';
                             } else {
                                 $value = '<a class="internalLink" target="_self" href="mailto:' . clean($value) . '">' . clean($value) . '</a></div>';
                             }
                         }
                         $row_values[$field] = $value;
                         if ($ot->getHandlerClass() == 'Contacts') {
                             if ($managerInstance instanceof Contacts) {
                                 $contact = Contacts::findOne(array("conditions" => "object_id = " . $object->getId()));
                                 if ($field == "email_address") {
                                     $row_values[$field] = $contact->getEmailAddress();
                                 }
                                 if ($field == "is_user") {
                                     $row_values[$field] = $contact->getUserType() > 0 && !$contact->getIsCompany();
                                 }
                                 if ($field == "im_values") {
                                     $str = "";
                                     foreach ($contact->getAllImValues() as $type => $value) {
                                         $str .= ($str == "" ? "" : " | ") . "{$type}: {$value}";
                                     }
                                     $row_values[$field] = $str;
                                 }
                                 if (in_array($field, array("mobile_phone", "work_phone", "home_phone"))) {
                                     if ($field == "mobile_phone") {
                                         $row_values[$field] = $contact->getPhoneNumber('mobile', null, false);
                                     } else {
                                         if ($field == "work_phone") {
                                             $row_values[$field] = $contact->getPhoneNumber('work', null, false);
                                         } else {
                                             if ($field == "home_phone") {
                                                 $row_values[$field] = $contact->getPhoneNumber('home', null, false);
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("personal_webpage", "work_webpage", "other_webpage"))) {
                                     if ($field == "personal_webpage") {
                                         $row_values[$field] = $contact->getWebpageUrl('personal');
                                     } else {
                                         if ($field == "work_webpage") {
                                             $row_values[$field] = $contact->getWebpageUrl('work');
                                         } else {
                                             if ($field == "other_webpage") {
                                                 $row_values[$field] = $contact->getWebpageUrl('other');
                                             }
                                         }
                                     }
                                 }
                                 if (in_array($field, array("home_address", "work_address", "other_address"))) {
                                     if ($field == "home_address") {
                                         $row_values[$field] = $contact->getStringAddress('home');
                                     } else {
                                         if ($field == "work_address") {
                                             $row_values[$field] = $contact->getStringAddress('work');
                                         } else {
                                             if ($field == "other_address") {
                                                 $row_values[$field] = $contact->getStringAddress('other');
                                             }
                                         }
                                     }
                                 }
                             }
                         } else {
                             if ($ot->getHandlerClass() == 'MailContents') {
                                 if (in_array($field, array('to', 'cc', 'bcc', 'body_plain', 'body_html'))) {
                                     $mail_data = MailDatas::findById($object->getId());
                                     $row_values[$field] = $mail_data->getColumnValue($field);
                                     if ($field == "body_html") {
                                         if (class_exists("DOMDocument")) {
                                             $d = new DOMDocument();
                                             $mock = new DOMDocument();
                                             $d->loadHTML(remove_css_and_scripts($row_values[$field]));
                                             $body = $d->getElementsByTagName('body')->item(0);
                                             foreach ($body->childNodes as $child) {
                                                 $mock->appendChild($mock->importNode($child, true));
                                             }
                                             // if css is inside an html comment => remove it
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css($row_values[$field]));
                                         } else {
                                             $row_values[$field] = preg_replace('/<!--(.*)-->/Uis', '', remove_css_and_scripts($row_values[$field]));
                                         }
                                     }
                                 }
                             }
                         }
                         if (!$to_print && $field == "name") {
                             $row_values[$field] = '<a target="new-' . $object->getId() . '" href="' . $object->getViewUrl() . '">' . $value . '</a>';
                         }
                     }
                 } else {
                     $colCp = $column->getCustomPropertyId();
                     $cp = CustomProperties::getCustomProperty($colCp);
                     if ($cp instanceof CustomProperty) {
                         /* @var $cp CustomProperty */
                         $row_values[$cp->getName()] = get_custom_property_value_for_listing($cp, $object);
                         $results['columns'][$colCp] = $cp->getName();
                         $results['db_columns'][$cp->getName()] = $colCp;
                     }
                 }
             }
             Hook::fire("report_row", $object, $row_values);
             $report_rows[] = $row_values;
         }
         if (!$to_print) {
             if (is_array($results['columns'])) {
                 array_unshift($results['columns'], '');
             } else {
                 $results['columns'] = array('');
             }
             Hook::fire("report_header", $ot, $results['columns']);
         }
         $results['rows'] = $report_rows;
     }
     return $results;
 }
Exemplo n.º 5
0
 /**
  * Returns the contact associated with the user, or null otherwise
  *
  */
 function getContact()
 {
     $cont = Contacts::findOne(array('include_trashed' => true, 'conditions' => array('user_id = ' . $this->getId())));
     if ($cont instanceof Contact) {
         return $cont;
     } else {
         return null;
     }
 }
Exemplo n.º 6
0
 /**
  * Return owner company
  *
  * @access public
  * @param void
  * @return Company
  */
 static function getOwnerCompany()
 {
     $owner_company = null;
     if (GlobalCache::isAvailable()) {
         $owner_company = GlobalCache::get('owner_company', $success);
         if ($success && $owner_company instanceof Contact) {
             return $owner_company;
         }
     }
     $owner_company = Contacts::findOne(array("conditions" => " is_company > 0", "limit" => 1, "order" => "object_id ASC"));
     if (GlobalCache::isAvailable()) {
         GlobalCache::update('owner_company', $owner_company);
     }
     return $owner_company;
 }
Exemplo n.º 7
0
chdir(dirname(__FILE__) . '/../..');
define("CONSOLE_MODE", true);
define("PLUGIN_MANAGER_CONSOLE", true);
if (!defined('PUBLIC_FOLDER')) {
    define('PUBLIC_FOLDER', 'public');
}
require_once 'init.php';
$success_message = "";
try {
    if (!isset($argv) || !is_array($argv)) {
        die("There is no input arguments\n");
    }
    // if
    $command = array_var($argv, 1);
    $arg1 = array_var($argv, 2);
    $usr = Contacts::findOne(array("conditions" => "user_type > 0", "order" => "user_type"));
    $usr or die("No users found\n");
    CompanyWebsite::instance()->logUserIn($usr);
    $ctrl = new PluginController();
    trim($command) or die("Command is required \n" . $usage);
    $plugins = $ctrl->index();
    if ($command == 'list') {
        foreach ($plugins as $plg) {
            /* @var $plg Plugin */
            echo "---------------------------------------------\n";
            echo "NAME: \t\t" . $plg->getSystemName() . "\n";
            echo "VERSION: \t" . $plg->getVersion() . "\n";
            echo "STATUS: \t" . ($plg->isInstalled() ? 'Installed ' : 'Uninstalled ') . ($plg->isActive() ? 'Activated ' : 'Inactive ') . "\n";
            if ($plg->updateAvailable()) {
                echo "*** There is a new version of this plugin *** \n";
            }
Exemplo n.º 8
0
function save_user_permissions_background($user, $pg_id, $is_guest = false, $users_ids_to_check = array(), $only_member_permissions = false)
{
    // system permissions
    $sys_permissions_data = array_var($_POST, 'sys_perm');
    // module permissions
    $mod_permissions_data = array_var($_POST, 'mod_perm');
    // root permissions
    $rp_permissions_data = array();
    $set_root_permissions = false;
    $tmp_contact = Contacts::findOne(array('conditions' => "permission_group_id={$pg_id}"));
    if ($tmp_contact instanceof Contact && $tmp_contact->getUserType() > 0) {
        if (in_array($tmp_contact->getUserTypeName(), array('Super Administrator', 'Administrator', 'Manager', 'Executive'))) {
            $set_root_permissions = true;
        }
    }
    $rp_genid = array_var($_POST, 'root_perm_genid', '0');
    if ($rp_genid && $set_root_permissions) {
        foreach ($_POST as $name => $value) {
            if (str_starts_with($name, $rp_genid . 'rg_root_')) {
                $rp_permissions_data[$name] = $value;
            }
        }
    }
    // member permissions
    $permissionsString = array_var($_POST, 'permissions');
    if (substr(php_uname(), 0, 7) == "Windows" || !can_save_permissions_in_background()) {
        //pclose(popen("start /B ". $command, "r"));
        save_permissions($pg_id, $is_guest, null, true, true, true, true, $users_ids_to_check, $only_member_permissions);
    } else {
        // save permissions in background
        $perm_filename = ROOT . "/tmp/uperm_" . gen_id();
        file_put_contents($perm_filename, $permissionsString);
        $sys_filename = ROOT . "/tmp/sys_" . gen_id();
        file_put_contents($sys_filename, json_encode($sys_permissions_data));
        $mod_filename = ROOT . "/tmp/mod_" . gen_id();
        file_put_contents($mod_filename, json_encode($mod_permissions_data));
        $rp_filename = ROOT . "/tmp/rp_" . gen_id();
        file_put_contents($rp_filename, json_encode($rp_permissions_data));
        $usrcheck_filename = ROOT . "/tmp/usrcheck_" . gen_id();
        file_put_contents($usrcheck_filename, json_encode($users_ids_to_check));
        $only_mem_perm_str = $only_member_permissions ? "1" : "0";
        $is_guest_str = $is_guest ? "1" : "0";
        $command = "nice -n19 " . PHP_PATH . " " . ROOT . "/application/helpers/save_user_permissions.php " . ROOT . " " . $user->getId() . " " . $user->getTwistedToken() . " {$pg_id} {$is_guest_str} {$perm_filename} {$sys_filename} {$mod_filename} {$rp_filename} {$usrcheck_filename} {$rp_genid} {$only_mem_perm_str}";
        exec("{$command} > /dev/null &");
        //Test php command
        exec(PHP_PATH . " -r 'echo function_exists(\"foo\") ? \"yes\" : \"no\";' 2>&1", $output, $return_var);
        if ($return_var != 0) {
            Logger::log(print_r("Error executing php command", true));
            Logger::log(print_r($output, true));
            Logger::log(print_r("Error code: " . $return_var, true));
        }
        //END Test php command
    }
}
Exemplo n.º 9
0
        }
    }
    DB::commit();
} catch (Exception $e) {
    DB::rollback();
    Logger::log("Error saving permissions (3): " . $e->getMessage() . "\n" . $e->getTraceAsString());
}
// fire hooks
try {
    DB::beginWork();
    Hook::fire('after_save_contact_permissions', $pg_id, $pg_id);
    DB::commit();
} catch (Exception $e) {
    DB::rollback();
    Logger::log("Error saving permissions (4): " . $e->getMessage() . "\n" . $e->getTraceAsString());
}
// remove contact object from members where permissions were deleted
$user = Contacts::findOne(array('conditions' => 'permission_group_id=' . $pg_id));
if ($user instanceof Contact) {
    $to_remove = array();
    foreach ($all_perm_deleted as $m_id => $must_remove) {
        if ($must_remove) {
            $to_remove[] = $m_id;
        }
    }
    ObjectMembers::removeObjectFromMembers($user, logged_user(), null, $to_remove);
}
@unlink($permissions_filename);
@unlink($sys_permissions_filename);
@unlink($mod_permissions_filename);
@unlink($root_permissions_filename);
Exemplo n.º 10
0
 function ical_export()
 {
     $this->setLayout('ical');
     require_once ROOT . '/environment/classes/event/CalFormatUtilities.php';
     if (!isset($_GET['t']) || !isset($_GET['cal'])) {
         header('HTTP/1.0 404 Not Found');
         die;
     }
     $token = $_GET['t'];
     $cal = $_GET['cal'];
     if (Contacts::tokenExists($token)) {
         $user = Contacts::findOne(array('conditions' => "token='{$token}'"));
         $conditions = " AND EXISTS (SELECT i.contact_id FROM " . TABLE_PREFIX . "event_invitations i WHERE i.event_id=e.object_id AND  i.contact_id=" . $user->getId() . ")";
         if (array_var($_GET, 'cal') != "") {
             $mem_cond = "e.object_id IN (SELECT object_id FROM " . TABLE_PREFIX . "object_members WHERE member_id IN (" . array_var($_GET, 'cal') . "))";
         } else {
             $mem_cond = "true";
         }
         $user_pgs = $user->getPermissionGroupIds();
         $perm_cond = " AND EXISTS (SELECT st.object_id FROM " . TABLE_PREFIX . "sharing_table st WHERE st.object_id=e.object_id AND st.group_id IN (" . implode(',', $user_pgs) . "))";
         $events = ProjectEvents::findAll(array('conditions' => "{$mem_cond} {$perm_cond} {$conditions}"));
         $calendar_name = isset($_GET['n']) ? $_GET['n'] : $user->getObjectName();
         $calendar_name = str_replace(' ', '_', $calendar_name);
         $content = CalFormatUtilities::generateICalInfo($events, $calendar_name, $user);
         tpl_assign('content', $content);
     } else {
         header('HTTP/1.0 404 Not Found');
         die;
     }
 }
 function import_from_vcard()
 {
     if (logged_user()->isGuest()) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     @set_time_limit(0);
     ini_set('auto_detect_line_endings', '1');
     if (isset($_GET['from_menu']) && $_GET['from_menu'] == 1) {
         unset($_SESSION['go_back']);
     }
     if (isset($_SESSION['go_back'])) {
         unset($_SESSION['go_back']);
         ajx_current("start");
     }
     tpl_assign('import_type', 'contact');
     if (!Contact::canAdd(logged_user(), active_or_personal_project())) {
         flash_error(lang('no access permissions'));
         ajx_current("empty");
         return;
     }
     // if
     $this->setTemplate('vcard_import');
     $filedata = array_var($_FILES, 'vcard_file');
     if (is_array($filedata) && !array_var($_GET, 'step2')) {
         $filename = ROOT . '/tmp/' . logged_user()->getId() . 'temp.vcf';
         copy($filedata['tmp_name'], $filename);
         //ajx_current("empty");
     } else {
         if (array_var($_GET, 'step2')) {
             $filename = ROOT . '/tmp/' . logged_user()->getId() . 'temp.vcf';
             $result = $this->read_vcard_file($filename);
             unlink($filename);
             $import_result = array('import_ok' => array(), 'import_fail' => array());
             foreach ($result as $contact_data) {
                 try {
                     DB::beginWork();
                     if (isset($contact_data['photo_tmp_filename'])) {
                         $file_id = FileRepository::addFile($contact_data['photo_tmp_filename'], array('public' => true));
                         $contact_data['picture_file'] = $file_id;
                         unlink($contact_data['photo_tmp_filename']);
                         unset($contact_data['photo_tmp_filename']);
                     }
                     if (isset($contact_data['company_name'])) {
                         $company = Companies::findOne(array("conditions" => "`name` = '" . mysql_real_escape_string($contact_data['company_name']) . "'"));
                         if ($company == null) {
                             $company = new Company();
                             $company->setName($contact_data['company_name']);
                             $company->setClientOfId(logged_user()->getCompanyId());
                             $company->save();
                             ApplicationLogs::createLog($company, null, ApplicationLogs::ACTION_ADD);
                         }
                         $contact_data['company_id'] = $company->getId();
                         unset($contact_data['company_name']);
                     }
                     $contact_data['import_status'] = '(' . lang('updated') . ')';
                     $fname = mysql_real_escape_string(array_var($contact_data, "firstname"));
                     $lname = mysql_real_escape_string(array_var($contact_data, "lastname"));
                     $contact = Contacts::findOne(array("conditions" => "firstname = '" . $fname . "' AND lastname = '" . $lname . "' OR email <> '' AND email = '" . array_var($contact_data, "email") . "'"));
                     $log_action = ApplicationLogs::ACTION_EDIT;
                     if (!$contact) {
                         $contact = new Contact();
                         $contact_data['import_status'] = '(' . lang('new') . ')';
                         $log_action = ApplicationLogs::ACTION_ADD;
                         $can_import = active_project() != null ? $contact->canAdd(logged_user(), active_project()) : can_manage_contacts(logged_user());
                     } else {
                         $can_import = $contact->canEdit(logged_user());
                     }
                     if ($can_import) {
                         $contact->setFromAttributes($contact_data);
                         $contact->save();
                         ApplicationLogs::createLog($contact, null, $log_action);
                         $contact->setTagsFromCSV(array_var($_GET, 'tags'));
                         if (active_project() instanceof Project) {
                             $pc = ProjectContacts::findOne(array("conditions" => "contact_id = " . $contact->getId() . " AND project_id = " . active_project()->getId()));
                             if (!$pc) {
                                 $pc = new ProjectContact();
                                 $pc->setContactId($contact->getId());
                                 $pc->setProjectId(active_project()->getId());
                                 $pc->setRole(array_var($contact_data, 'role'));
                                 $pc->save();
                             }
                             $contact->addToWorkspace(active_project());
                         }
                         $import_result['import_ok'][] = array('firstname' => $fname, 'lastname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status']);
                     } else {
                         throw new Exception(lang('no access permissions'));
                     }
                     DB::commit();
                 } catch (Exception $e) {
                     DB::rollback();
                     $fail_msg = substr_utf($e->getMessage(), strpos_utf($e->getMessage(), "\r\n"));
                     $import_result['import_fail'][] = array('firstname' => $fname, 'lastname' => $lname, 'email' => $contact_data['email'], 'import_status' => $contact_data['import_status'], 'fail_message' => $fail_msg);
                 }
             }
             $_SESSION['go_back'] = true;
             tpl_assign('import_result', $import_result);
         }
     }
 }